Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
% Text-extraction gate for accents with unambiguous reference Unicode metadata.
\defaulthyphenchar=45 \defaultskewchar=127
\input math-fonts
\hsize=300pt
\def\hat{\mathaccent"705E }
\noindent Native accents: $\hat a+\hat x_i^2=\hat{a+b}$.\par
\noindent Nested accents: $\hat{\hat x}$ and $x^{\hat y}_{\hat z}$.\par
\noindent Actual script masters: $\hat x+\scriptstyle\hat x+\scriptscriptstyle\hat x$.\par
\noindent Fractions: ${\hat x\over\hat y_i}$ and $\hat{{a\over b}}$.\par
\skewchar\teni=-1
\noindent Disabled skew: $\hat x$.\par
{\skewchar\teni=127}
\noindent Persistent font state: $\hat x$.\par
\tracinglostchars=2
\noindent Missing accent: $\mathaccent"00C8 x_i^2$ retains its base and scripts.\par
\end
+19
View File
@@ -0,0 +1,19 @@
% Actual font integer defaults, scoped selectors and native mathaccent geometry.
\defaulthyphenchar=45 \defaultskewchar=127
\input math-fonts
\hsize=300pt
\def\hat{\mathaccent"705E }
\def\widehat{\mathaccent"0362 }
\def\vec{\mathaccent"017E }
\noindent Native accents: $\hat a+\hat x_i^2=\hat{a+b}$ and $\widehat{a+b+c}$.\par
\noindent Nested accents: $\hat{\hat x}$ and $x^{\hat y}_{\hat z}$.\par
\noindent Actual script masters: $\hat x+\scriptstyle\hat x+\scriptscriptstyle\hat x$.\par
\noindent Fractions: ${\hat x\over\hat y_i}$ and $\hat{{a\over b}}$.\par
\noindent Vector: $\vec x$ uses the actual OML slot.\par
\skewchar\teni=-1
\noindent Disabled skew: $\hat x$.
{\skewchar\teni=127}\noindent Restored resource state: $\hat x$.\par
\tracinglostchars=2
\noindent Missing accent: $\mathaccent"00C8 x_i^2$ retains its base and scripts.\par
\message{Actual font integers: \the\skewchar\teni/\the\hyphenchar\tenrm.}
\end
+5
View File
@@ -0,0 +1,5 @@
% This file is executed by the Route-D token/state core, not rewritten.
\countdef\counter=0
\counter=4
\def\greet#1{Hello, #1.}
\endinput
+19
View File
@@ -0,0 +1,19 @@
% Owned native hbox/vbox/vtop, box registers, glue setting and depth.
\catcode123=1 \catcode125=2 \catcode35=6
\font\body=cmr10 \body
\hsize=240pt \baselineskip=12pt \parfillskip=0pt plus1fil
\boxmaxdepth=100pt \hbadness=10000 \vbadness=10000
\setbox0=\vbox to45pt{\hbox{Vertical top}\vskip2pt plus1fil\hbox{Vertical bottom}}
\copy0
\kern8pt
\hbox{Left \vtop{\hbox{First row}\hbox{Second row}} Right}
\kern8pt
\vbox to40pt{\hbox{Finite stretch}\vskip4pt plus8pt\hbox{Finite end}}
\kern8pt
\vbox to20pt{\hbox{Finite shrink}\vskip10pt minus8pt\hbox{Tight end}}
\kern8pt
\vbox{\hbox{Nested native box}\hrule height.4pt\hbox to150pt{Left\hskip0pt plus1fil Right}}
\kern8pt
\noindent Inline \copy0 beside native text.\par
\message{Native box packing completed. Width=\the\wd0, height=\the\ht0, depth=\the\dp0.}
\end
@@ -0,0 +1,10 @@
% Real delimiter fields, as configured by a format over native primitives.
\delimiterfactor=901 \delimitershortfall=5pt
\delcode`\(="028300 \delcode`\)="029301
\delcode`\[="05B302 \delcode`\]="05D303
\delcode`\<="26830A \delcode`\>="26930B
\delcode`\/="02F30E \delcode`\|="26A30C
\def\lbrace{\delimiter"4266308 } \def\rbrace{\delimiter"5267309 }
\def\lceil{\delimiter"4264306 } \def\rfloor{\delimiter"5263305 }
\def\uparrow{\delimiter"3222378 } \def\downarrow{\delimiter"3223379 }
\def\updownarrow{\delimiter"326C33F }
@@ -0,0 +1,13 @@
% Matching-Unicode word-box gate for real normal-size paired delimiters.
\defaulthyphenchar=45
\input math-fonts
\input delimiter-codes
\hsize=300pt
\noindent Native pairs: $a+\left(b=c\right)d$ and $\left[a+b\right]=c$.\par
\noindent Nested pairs: $\left(\left[a+b\right]=c\right)$ retain their own lists.\par
\noindent Script pairs: $x^{\left(a+b\right)}$ use real optical masters.\par
\noindent Null pairs: $\left.a+b\right)$ and $\left(a+b\right.$.\par
\noindent Display pairs preserve baseline and depth.\par
$$\left(a+b=c\right)$$
Continuation after the display uses measured depth.\par
\end
+17
View File
@@ -0,0 +1,17 @@
% Full native delimiter outline/position gate, including extensible pieces.
\defaulthyphenchar=45 \defaultskewchar=127
\input math-fonts
\input delimiter-codes
\hsize=300pt
\noindent Native pairs: $a+\left(b=c\right)d$ and $\left[a+b\right]$.\par
\noindent Nested fractions: $\left( {a\over{b\over c}}\right)$.\par
\noindent Original style: $\left(\scriptscriptstyle a+b\right)$; script pairs: $x^{\left(a+b\right)}$.\par
{\delimiterfactor=5000
\noindent Actual brace pieces: $\left\lbrace a\over b\right\rbrace$.\par
\noindent Arrow pieces: $\left\uparrow a\over b\right\downarrow$ and $\left\updownarrow a\over b\right|$.\par
}
\noindent Mixed fields: $\left\lceil a\over b\right\rfloor$ and $\left<a\over b\right>$.\par
\noindent Null pairs: $\left.a\over b\right)$ and $\left(\right.$.\par
$$\left\lbrace {a\over{b\over c}}\right\rbrace$$
Continuation after display keeps the actual delimiter depth.\par
\end
+27
View File
@@ -0,0 +1,27 @@
% Actual mag/true and per-shipout device changes, including automatic paper.
\input math-fonts
\mag=1200
\pdfpagewidth=320truebp \pdfpageheight=240truebp
\pdfhorigin=12truebp \pdfvorigin=18truebp
\hoffset=2pt \voffset=3pt
\immediate\openout1=device.aux
\count0=1
\setbox0=\vbox{\hsize=200pt \baselineskip=14pt
\noindent Native device state follows this actual box and its original fonts.
Both text and mathematics $x_i^j+y$ share the same physical magnification.\par
\kern3truept \hrule height1pt
\hbox{Origin and offsets move together.}
\write1{SHIP=\number\count0;MAG=\number\mag}}
\shipout\copy0
{\pdfpagewidth=280truebp \pdfpageheight=210truebp
\pdfhorigin=20truebp \pdfvorigin=24truebp
\hoffset=-2pt \voffset=1pt
\count0=2 \shipout\copy0}
\pdfpagewidth=0pt \pdfpageheight=0pt
\pdfhorigin=8truebp \pdfvorigin=10truebp
\hoffset=0pt \voffset=0pt
\count0=3 \shipout\box0
\pdfpagewidth=999pt \pdfpageheight=888pt
\pdfhorigin=100pt \pdfvorigin=100pt
\immediate\closeout1
\end
+17
View File
@@ -0,0 +1,17 @@
% Actual showbox diagnostics, with continued execution and TeX diagnostic status.
\defaulthyphenchar=45
\input math-fonts
\hsize=240pt \showboxbreadth=3 \showboxdepth=2
\setbox0=\hbox{Actual native box.}
\message{BEFORE_SHOWS}
\tracingonline=0 \showbox0
\tracingonline=1 \showbox0
\setbox1=\vbox{\hbox{Nested material.}\vskip2pt plus1fil\hbox{Real depth.}}
\showboxbreadth=20 \showboxdepth=4 \showbox1
\setbox2=\vbox{\noindent Raw paragraph glue survives diagnostic inspection.\par}
\showbox2
\showbox3
\message{AFTER_SHOWS}
\copy0 \copy1 \copy2
\noindent Continued after diagnostics with measured material.\par
\end
@@ -0,0 +1,21 @@
% Real primitive lists and actual pattern/exception reconstitution.
\input math-fonts.tex
\hsize=110pt \parindent=0pt \baselineskip=17pt \parskip=7pt
\pretolerance=-1 \tolerance=10000 \hbadness=10000
\lefthyphenmin=1 \righthyphenmin=1
\hyphenation{of-fi-ce dif-fi-cult af-fine af-fix fluf-fy ef-fi-cient}
X office difficult affine affix fluffy efficient office.\par
X ``office'' (difficult) office affine.\par
\hyphenpenalty=-10000 \exhyphenpenalty=-10000
AA\discretionary{f-}{fi}{ffi}VV words after the branch.\par
\hyphenpenalty=50 \exhyphenpenalty=50
\font\small=cmr7 at9pt
\hyphenpenalty=-10000
AA\discretionary{\small PRE}{\small POST}{replacement}VV more words.\par
\hyphenpenalty=-10000
AA $a\discretionary{f-}{fi}{}b$ VV\par
\hyphenpenalty=50
\font\body=cmr10 at12pt \body
X office difficult affine office.\par
\message{DISCRETIONARIES-DONE}
\end
+22
View File
@@ -0,0 +1,22 @@
% Native display mode, real pre/post penalties, skips and continuation state.
\input math-fonts
\hsize=240pt \parskip=4pt
\displaywidowpenalty=50 \widowpenalty=150
\predisplaypenalty=10000 \postdisplaypenalty=0
\abovedisplayskip=12pt plus3pt minus9pt
\belowdisplayskip=12pt plus3pt minus9pt
\abovedisplayshortskip=0pt plus3pt
\belowdisplayshortskip=7pt plus3pt minus4pt
\noindent Native display formulas keep actual mathematical font masters.\par
\noindent Short prefix.$$x_i^2+y_j$$Continuation shares the paragraph state.\par
\noindent This longer prefix selects the ordinary display skips by its measured extent.
$${a+b\over c+d}=x$$The fraction keeps its measured baseline and depth.\par
\noindent Inline $y$ precedes a display.$$x+y=z$$Its italic kern stays separate from the visible edge.\par
\predisplaypenalty=-10000 \postdisplaypenalty=0
\noindent Before forced page.$$a+b=c$$After forced page.\par
\predisplaypenalty=10000 \postdisplaypenalty=-10000
\noindent Final formula prefix.$$x_2^3$$After formula starts another page.\par
\postdisplaypenalty=0
\vbox{\hsize=180pt\noindent Boxed display.$$a+b$$Resumed boxed text.\par}
\message{Native display execution completed.}
\end
@@ -0,0 +1,28 @@
% Explicit font requests, actual resources and arbitrary sizes; no format macros.
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45
\font\body=cmr10 at12pt
\font\small=cmr7 at9pt
\font\bold=cmbx10 at13pt
\font\italic=cmti10 scaled1201
\font\mono=cmtt10 at11pt
\font\sans=cmss10 scaled1150
\hsize=330pt \parindent=0pt \baselineskip=20pt \parskip=7pt
\parfillskip=0pt plus1fil \pretolerance=10000 \tolerance=10000
\body Real native fonts retain the requested resource and size. Roman text,
{\bold bold text}, {\italic italic text}, {\mono mono text}, {\sans sans text},
and {\small a smaller optical master scaled to nine points} share this paragraph.\par
\body office affine ff fi fl ffi ffl -- --- ``quotes'' !` ?`\par
\bold office affine ff fi fl ffi ffl -- --- ``quotes''\par
\italic office affine ff fi fl ffi ffl -- --- ``quotes''\par
\mono office affine ff fi fl ffi ffl -- --- ``quotes''\par
\small CMR7 is used at nine points without replacement.\par
\body
\setbox0=\hbox{A V}
{\fontdimen2\body=5pt}
\copy0\par
A V\par
\fontdimen6\body=18pt \fontdimen5\body=7pt
\setbox1=\hbox{A\hskip1em V\hskip1ex Z}\copy1\par
\message{DYNAMIC-FONTS-DONE}
\end
+16
View File
@@ -0,0 +1,16 @@
% No format, class or package is preloaded. Run native --initex --etex.
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45 \font\nativefont=cmr10 \nativefont \hsize=468pt \baselineskip=12pt \parfillskip=0pt plus1fil
\protected\def\nativeword{Native e-TeX expansion is active.}
\edef\saved{\nativeword}
\saved\par
\toksdef\stored=300
\stored={\saved}
\the\stored\par
\count32767=\numexpr(1+2)*5/2\relax
\unless\ifnum\count32767=8
\errmessage{Expression evaluation failed}
\fi
Expression result: \the\count32767.\par
\message{Native e-TeX bootstrap: semantic checks passed}
\end
+18
View File
@@ -0,0 +1,18 @@
% Fixed glue enters real horizontal, vertical, mathematical and output lists.
\input math-fonts.tex
\pdfpagewidth=360bp \pdfpageheight=300bp
\pdfhorigin=24bp \pdfvorigin=24bp
\hsize=300bp \vsize=220bp \parindent=0pt
\immediate\openout0=pages.aux
\output={\shipout\vbox{\unvbox255\hbox to\hsize{Left\hfil Footer\hfill Right}}}
\hbox to\hsize{A\hfil B\hfil C}
\hbox to\hsize{A\hss B\hfilneg C\hfill D}
\hbox to10pt{A\hss B}
\hbox spread1sp{A\hskip0pt plus-1fil B\hskip0pt plus3fil C}
\hbox spread6pt{A\hfilneg B\hfilneg C}
\vbox to40pt{\hbox{Top}\vfil\vfilneg\vfill\hbox{Bottom}}
\noindent Native math uses actual normal-unit glue: $x_i\hskip4pt+x^2$.
\hbox to\hsize{$a\hfil b\hfill c$}
\write0{fixed-glue-page=\the\count0}
\par
\end
+16
View File
@@ -0,0 +1,16 @@
% Actual CMR10 OT1 slots. The acceptance grid is 16 cells x 8 rows.
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=-1 \font\p=cmr10 \p
\hsize=320pt \baselineskip=18pt \boxmaxdepth=100pt
\hbadness=10000 \vbadness=10000 \tracinglostchars=2
\def\cell#1{\hbox to20pt{\char#1\hskip0pt plus1fil}}
\vbox{
\hbox{\cell{0}\cell{1}\cell{2}\cell{3}\cell{4}\cell{5}\cell{6}\cell{7}\cell{8}\cell{9}\cell{10}\cell{11}\cell{12}\cell{13}\cell{14}\cell{15}}
\hbox{\cell{16}\cell{17}\cell{18}\cell{19}\cell{20}\cell{21}\cell{22}\cell{23}\cell{24}\cell{25}\cell{26}\cell{27}\cell{28}\cell{29}\cell{30}\cell{31}}
\hbox{\cell{32}\cell{33}\cell{34}\cell{35}\cell{36}\cell{37}\cell{38}\cell{39}\cell{40}\cell{41}\cell{42}\cell{43}\cell{44}\cell{45}\cell{46}\cell{47}}
\hbox{\cell{48}\cell{49}\cell{50}\cell{51}\cell{52}\cell{53}\cell{54}\cell{55}\cell{56}\cell{57}\cell{58}\cell{59}\cell{60}\cell{61}\cell{62}\cell{63}}
\hbox{\cell{64}\cell{65}\cell{66}\cell{67}\cell{68}\cell{69}\cell{70}\cell{71}\cell{72}\cell{73}\cell{74}\cell{75}\cell{76}\cell{77}\cell{78}\cell{79}}
\hbox{\cell{80}\cell{81}\cell{82}\cell{83}\cell{84}\cell{85}\cell{86}\cell{87}\cell{88}\cell{89}\cell{90}\cell{91}\cell{92}\cell{93}\cell{94}\cell{95}}
\hbox{\cell{96}\cell{97}\cell{98}\cell{99}\cell{100}\cell{101}\cell{102}\cell{103}\cell{104}\cell{105}\cell{106}\cell{107}\cell{108}\cell{109}\cell{110}\cell{111}}
\hbox{\cell{112}\cell{113}\cell{114}\cell{115}\cell{116}\cell{117}\cell{118}\cell{119}\cell{120}\cell{121}\cell{122}\cell{123}\cell{124}\cell{125}\cell{126}\cell{127}}
}\message{Native OT1 slot grid completed.}\end
+14
View File
@@ -0,0 +1,14 @@
% Actual font slots and missing characters, with genuine diagnostic channels.
\defaulthyphenchar=45
\input math-fonts
\hsize=240pt
\tracingonline=0 \tracinglostchars=1
\noindent Before a missing slot \char200 after it.\par
\tracinglostchars=2
\nullfont\char65\tenrm
\noindent Real OT1 slots: \char0{} \char11{} \char92{} \char123{} \char127{}.\par
\noindent Missing math nucleus $a+\mathchar"01C8^2+b$ retains the script.\par
\iffontchar\font65 \message{Actual current font contains slot 65.}\fi
\iffontchar\textfont1 200 \errmessage{Bad TFM presence}\fi
\message{Native font diagnostics completed.}
\end
+22
View File
@@ -0,0 +1,22 @@
% Actual font-tail italic corrections and glue quantities reach the same PDF.
\input math-fonts.tex
\font\italic=cmti10
\font\roman=cmr10
\pdfpagewidth=360bp \pdfpageheight=240bp
\pdfhorigin=24bp \pdfvorigin=24bp
\hsize=300bp \vsize=180bp \parindent=0pt
\output={\shipout\box255}
\immediate\openout0=pages.aux
\skip0=7pt plus2.5fill minus3.25fil
\noindent Native italic correction: {\italic f\/A fi\/A A\/A}.
Tail-font lookup: {\italic f}\roman\/A.
\par
\hbox{A\kern\gluestretch\skip0 B\kern\glueshrink\skip0 C}
\noindent Stretch: \the\gluestretch\skip0;
shrink: \the\glueshrink\skip0;
orders: \the\gluestretchorder\skip0, \the\glueshrinkorder\skip0.
Math zero correction: $a\/b+a\/^2+x_i$.
\write0{components=\the\gluestretch\skip0,\the\glueshrink\skip0;
orders=\the\gluestretchorder\skip0,\the\glueshrinkorder\skip0}
\par
\end
+17
View File
@@ -0,0 +1,17 @@
% Real paragraph-to-vlist penalties, consumed by the native page builder.
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45 \font\p=cmr10 \p
\hsize=200pt \baselineskip=12pt \parfillskip=0pt plus1fil
\hbadness=10000 \vbadness=10000 \boxmaxdepth=100pt
\interlinepenalty=0 \clubpenalty=-10000 \widowpenalty=0 \brokenpenalty=0
\noindent First\penalty-10000 Second\penalty-10000 Third\par
\clubpenalty=0 \widowpenalty=-10000
\noindent Fourth\penalty-10000 Fifth\penalty-10000 Sixth\par
\widowpenalty=0 \interlinepenalty=-10000
\noindent Seventh\penalty-10000 Eighth\penalty-10000 Ninth\par
\interlinepenalty=0 \brokenpenalty=-10000 \hyphenpenalty=-10000 \hsize=40pt
\noindent con\-struction\par
\hsize=200pt \interlinepenalty=10000 \clubpenalty=150 \widowpenalty=150
\noindent Kept\penalty-10000 Together\penalty-10000 Here\par
\message{Native interline page execution completed.}
\end
+14
View File
@@ -0,0 +1,14 @@
% Run in a scratch working directory: native --initex --etex /path/to/job.tex job.pdf
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45 \font\nativefont=cmr10 \nativefont \hsize=468pt \baselineskip=12pt \parfillskip=0pt plus1fil
\immediate\openout0=job-time.aux
\immediate\write0{\the\year/\the\month/\the\day, minutes=\the\time}
\immediate\closeout0
\openin1=job-time.aux
\ifeof1\errmessage{The written job file was not found}\fi
\endlinechar=-1
\read1 to\captured
\closein1
Captured job time: \captured.\par
\message{Native job file was written and read back successfully.}
\end
+30
View File
@@ -0,0 +1,30 @@
\catcode123=1 \catcode125=2 \catcode35=6 \catcode94=7
\defaulthyphenchar=45 \font\rm=cmr10 \rm
\hsize=108pt \parindent=0pt \baselineskip=12pt
\parfillskip=0pt plus1fil \parskip=5pt
\pretolerance=-1 \tolerance=10000 \hbadness=10000 \vbadness=10000
\linepenalty=10 \hyphenpenalty=50 \exhyphenpenalty=50
\adjdemerits=10000 \doublehyphendemerits=10000 \finalhyphendemerits=5000
\lefthyphenmin=2 \righthyphenmin=3 \uchyph=1
\language=1
\patterns{hy1phen phen1a a1tion para1graph con1struc struc1tion de1mon mon1stra stra1tion}
\language=2
\patterns{hyphen1ation para1graph construc1tion demon1stration}
\language=0
\uppercase{\def\heading{native language tables}}
\heading\par
\language=1
Language one: hyphenation paragraph construction demonstration
hyphenation paragraph construction demonstration.\par
\language=2
Language two: hyphenation paragraph construction demonstration
hyphenation paragraph construction demonstration.\par
\language=1
Within one paragraph: hyphenation paragraph
\language=2 construction demonstration
\language=1 hyphenation paragraph construction demonstration.\par
\lccode64=97 \hyphenation{p@r@-graph}
Mapped exceptions: paragraph paragraph paragraph paragraph.\par
\lowercase{\def\converted{CASE TOKENS RETAIN THEIR CATEGORIES.}}
\converted\par
\end
+16
View File
@@ -0,0 +1,16 @@
% Exercise deletion in the same lists consumed by page construction and PDF.
\input math-fonts.tex
\pdfpagewidth=320bp \pdfpageheight=240bp
\pdfhorigin=24bp \pdfvorigin=24bp
\hsize=270bp \vsize=180bp \parindent=0pt
\output={\shipout\box255}
\immediate\openout0=pages.aux
\noindent Native list tails: \hskip30pt\unskip text remains adjacent.
\hbox{A\kern20pt\unkern B\penalty99\unpenalty C}
and math $x_a\mskip18mu\unskip+ y_a\mkern12mu\unkern$.
\write0{list-tail-page=\the\count0}
\par
\setbox0=\vbox{\hbox{Internal vertical tail.}\vskip30pt\unskip
\kern12pt\unkern\penalty23\unpenalty}
\box0
\end
+24
View File
@@ -0,0 +1,24 @@
% Actual rules, moved boxes, original list transfer and paragraph line boxes.
\input math-fonts
\hsize=270pt \baselineskip=15pt \parskip=4pt
\pretolerance=10000 \tolerance=10000
\overfullrule=3pt \hfuzz=0pt
\noindent Native rules inherit their actual containing box dimensions.\par
\hbox{A\vrule width1pt B\raise3pt\hbox{Raised}\lower2pt\hbox{lowered}C}
\vbox{\hbox{A running horizontal rule follows this measured text.}
\hrule height.5pt
\hbox{Its width comes from this box rather than the paragraph.}}
\setbox1=\hbox to8pt{gj}
\noindent A real overfull box has a marker: \copy1.\par
\noindent Its original list can be transferred: \unhcopy1.\par
\setbox2=\hbox to160pt{A\hskip0pt plus1fil B}
\noindent Packed material: \copy2.\par
\noindent Original unpacked material: \unhcopy2.\par
\vbox{\moveright10pt\hbox{Horizontal movement lives on the vertical list.}
\moveleft3pt\hbox{The next box retains its own baseline.}}
\setbox3=\vbox{\hsize=120pt\noindent Paragraph line boxes retain their actual original glue and glyph nodes.\par
\global\setbox4=\lastbox}
\noindent Extracted line material: \unhcopy4.\par
\noindent Mathematics can contain actual text boxes:
$x+\raise2pt\hbox{Text}_i^j+\hbox{A\vrule B}$.\par
\end
+12
View File
@@ -0,0 +1,12 @@
\input bootstrap
\message{Native bootstrap ready: counter=\the\counter}
\greet{Route-D}
\par
{\counter=9 \greet{local state}}
\par
\ifnum\counter=4
The outer register value was restored.
\else
Incorrect register state.
\fi
\end
+21
View File
@@ -0,0 +1,21 @@
% Explicit native CM family setup. No plain/LaTeX format or macro replacements.
\catcode123=1 \catcode125=2 \catcode35=6
\catcode36=3 \catcode94=7 \catcode95=8
\font\tenrm=cmr10 \font\sevenrm=cmr7 \font\fiverm=cmr5
\font\teni=cmmi10 \font\seveni=cmmi7 \font\fivei=cmmi5
\font\tensy=cmsy10 \font\sevensy=cmsy7 \font\fivesy=cmsy5
\font\tenex=cmex10
\textfont0=\tenrm \scriptfont0=\sevenrm \scriptscriptfont0=\fiverm
\textfont1=\teni \scriptfont1=\seveni \scriptscriptfont1=\fivei
\textfont2=\tensy \scriptfont2=\sevensy \scriptscriptfont2=\fivesy
\textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex
\tenrm
\mathcode`\+="202B \mathcode`\-="2200 \mathcode`\*="2203
\mathcode`\=="303D \mathcode`\<="313C \mathcode`\>="313E
\mathcode`\(="4028 \mathcode`\)="5029
\mathcode`\,="613B \mathcode`\;="603B
\thinmuskip=3mu \medmuskip=4mu plus2mu minus4mu \thickmuskip=5mu plus5mu
\scriptspace=.5pt \nulldelimiterspace=1.2pt
\binoppenalty=700 \relpenalty=500
\hsize=100pt \baselineskip=12pt \parfillskip=0pt plus1fil
\hbadness=10000 \vbadness=10000 \boxmaxdepth=100pt
@@ -0,0 +1,20 @@
% Native noad ligatures, actual operator variants and limits through PDF output.
\input math-fonts
\hsize=270pt \baselineskip=15pt \parskip=4pt
\abovedisplayskip=12pt \belowdisplayskip=12pt
\abovedisplayshortskip=3pt \belowdisplayshortskip=7pt
\mathchardef\Sum="1350 \mathchardef\Product="1351 \mathchardef\Integral="1352
Native text families retain their ligatures inside math: $\fam0 ffi+AV$.
Scripts keep the right nucleus: $\fam0 ff_i^j+fi^2$.\par
Inline operators use side scripts $\Sum_i^n+\Integral\nolimits_0^1$.
Forced limits also work inline $\Product\limits_i^n$.\par
\noindent Display operators use their actual font list successors.
$$\Sum_{i=1}^n x_i+\Product_{j=1}^m y_j$$
Continuation keeps the same baseline state.\par
\noindent Explicit side limits retain the display variant.
$$\Integral\nolimits_0^1 x^2+\mathop{fi}\limits_i^n$$
The native paragraph continues after the formula.\par
\noindent A limit can contain real stretchable material.
$$\Sum\limits^{a\mskip0mu plus1fil b}_j$$
Final text uses the same font resources.\par
\end
+16
View File
@@ -0,0 +1,16 @@
% Native math modes/noads/families and actual paragraph penalties.
\input math-fonts
\hsize=240pt \parskip=5pt
Inline $a+b=c$ uses real binary and relation classes. Scripts $x_i^2+y^{jk}$
retain their measured optical font masters.\par
Grouped ${a+b}=c$ suppresses inner automatic penalties. Fractions
${a+b\over c+d}=x$ use the same measured geometry for layout and painting.\par
\mathchardef\alpha="010B \mathchardef\beta="010C
Math character definitions $\alpha+\beta=1$ use real family slots.\par
\hbox{Restricted $a+b=c$ inserts no automatic penalties.}
\hsize=85pt \binoppenalty=-10000 \relpenalty=-10000
\noindent$a+b+c=d+e+f=g+h+i$\par
\hsize=240pt \binoppenalty=10000 \relpenalty=10000
Prohibited internal breaks keep $a+b=c+d$ together.\par
\message{Native math noad execution completed.}
\end
+31
View File
@@ -0,0 +1,31 @@
% Real online page/output/shipout execution; no format or document emulation.
\input math-fonts
\pdfpagewidth=612bp \pdfpageheight=792bp
\hsize=270pt \vsize=100pt \topskip=10pt \maxdepth=4pt
\baselineskip=15pt \parskip=4pt
\pretolerance=10000 \tolerance=10000
\count0=0
\immediate\openout1=pages.aux
\output={\global\advance\count0 by1
\shipout\vbox{\hbox{Native page \number\count0}
\unvbox255\hbox{Footer \number\count0}}}
\noindent Original paragraph lines feed the online native page builder.
The output routine executes while the job is running and can inspect its actual page box.
Its header and footer are constructed from the same native box primitives.\par
\noindent Marks\mark{FIRST} and deferred writes\write1{FIRST-PAGE=\number\count0}
remain attached to their original material.
Copying a box preserves its contents and dropping one does not execute its writes.\par
\hbox{A\vrule width1pt B\raise2pt\hbox{Raised}\lower1pt\hbox{lowered}}
\hrule height.5pt
\noindent Mathematics $x_i^j+y$ keeps actual font slots and sizes inside the page.
A displayed formula also participates in real vertical breaking.
$$x+y$$
The following paragraph resumes after the display with its correct baseline and depth.\par
\penalty-10000
\noindent An explicit penalty can finish a page without simulating a document command.
The remaining text continues through the same contribution list and output group.\par
\noindent The final\mark{LAST} page carries a late write\write1{LAST-PAGE=\number\count0}
whose page number is expanded at actual shipout.
All original glyphs and rule positions can be compared with an independent TeX job.\par
\closeout1
\end
+22
View File
@@ -0,0 +1,22 @@
% Run: native --initex --etex paragraphs.tex paragraphs.pdf
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45 \font\body=cmr10 \body
\hsize=210pt \parindent=12pt \baselineskip=12pt
\parfillskip=0pt plus1fil \parskip=6pt
\pretolerance=100 \tolerance=200 \emergencystretch=2pt
\linepenalty=10 \hyphenpenalty=50 \adjdemerits=10000
\lefthyphenmin=2 \righthyphenmin=3
Native paragraphs are built from tokens and measured font glyphs. The line
breaks and spaces in this paragraph are retained when the document is exported.\par
{\hsize=140pt \hangindent=12pt \hangafter=1
A local measure and hanging indent apply to this paragraph. Leaving the group
restores the previous measure without changing these measured lines.\par}
\noindent The restored measure is \the\hsize. Each paragraph uses its own state,
and line spacing carries the previous line depth across paragraph boundaries.\par
\pretolerance=-1 \tolerance=10000
\hyphenation{para-graph hy-phen-a-tion con-struc-tion}
\hsize=100pt
Paragraph construction uses real hyphenation exceptions when a later pass
requires them. No language patterns are silently injected.\par
\message{Native paragraph construction completed.}
\end
+17
View File
@@ -0,0 +1,17 @@
% Real PDF configuration and late per-stream changes over the same native box.
\input math-fonts
\pdfoutput=1 \pdfmajorversion=1 \pdfminorversion=7
\pdfobjcompresslevel=3 \pdfcompresslevel=9 \pdfdecimaldigits=4
\pdfpagewidth=260bp \pdfpageheight=180bp
\pdfhorigin=12pt \pdfvorigin=16pt
\count0=1 \immediate\openout1=config.aux
\setbox0=\vbox{\hsize=200pt \baselineskip=14pt
\noindent Native compressed pages retain actual text, fonts and mathematics $x_i^j+y$.\par
\kern.37pt \hrule height.4pt
\hbox{Actual fine rules and \raise.3pt\hbox{raised} text.}
\write1{PAGE=\number\count0;ZIP=\number\pdfcompresslevel}}
\shipout\copy0
\pdfcompresslevel=0 \pdfdecimaldigits=0 \pdfobjcompresslevel=0
\count0=2 \shipout\box0
\immediate\closeout1
\end
+13
View File
@@ -0,0 +1,13 @@
\catcode123=1\catcode125=2
\pdfminorversion=7\pdfobjcompresslevel=3\pdfcompresslevel=0
\pdfdecimaldigits=3\pdfpkresolution=300
\pdfpagewidth=420bp\pdfpageheight=160bp
\pdfhorigin=20pt\pdfvorigin=20pt
\font\R=cmr10 at20pt\font\I=cmmi10 at20pt\font\E=cmex10 at20pt
\immediate\openout1=bitmap.aux\count0=1
\setbox0=\vbox{\hbox{\R Native bitmap AV office -- ffi}
\kern3pt\hbox{\I ABC\kern2pt\E\char80}
\write1{PAGE=\number\count0;DPI=\number\pdfpkresolution}}
\shipout\copy0
\pdfpkresolution=1200\pdfcompresslevel=9\count0=2
\shipout\box0\immediate\closeout1\end
+22
View File
@@ -0,0 +1,22 @@
% Strict native demo, with INITEX categories and no preloaded format.
\catcode123=1 \catcode125=2 \catcode35=6
\defaulthyphenchar=45 \font\nativefont=cmr10 \nativefont \hsize=468pt \baselineskip=12pt \parfillskip=0pt plus1fil
\dimendef\width=300
\skipdef\flex=301
\muskipdef\mathspace=302
\width=2.5pt
\advance\width by1.25pt
\flex=1pt plus2fil minus.5pt
\mathspace=3mu plus1fil
\mathchardef\symbol=4660
Native width: \the\width.\par
Glue value: \the\flex.\par
Math glue value: \the\mathspace.\par
Math character code: \number\symbol.\par
Current input line: \the\inputlineno.\par
\ifdim\width>3pt
\message{Native quantity checks passed.}
\else
\errmessage{Native quantity comparison failed}
\fi
\end
+21
View File
@@ -0,0 +1,21 @@
% Native sfcode is consumed by real character and inter-word glue construction.
\catcode123=1 \catcode125=2 \catcode35=6
\font\body=cmr10 \body
\hsize=240pt \parindent=0pt \baselineskip=12pt
\parfillskip=0pt plus1fil \parskip=6pt
\hbadness=10000 \vbadness=10000
\sfcode`\.=3000 \sfcode`\!=3000 \sfcode`\?=3000
\sfcode`\)=0 \sfcode`\]=0
Sentence spacing follows native character codes. Next sentence uses extra
space. An abbreviation A. keeps ordinary spacing. An end.) Next sentence
retains the previous factor through its closing parenthesis.\par
{\sfcode`\.=1000
Local codes use ordinary spacing. Next sentence stays in this local group.
The measured paragraph keeps these spaces after the group closes.\par}
Restored codes produce sentence spacing. Next sentence uses the restored
table without changing the preceding paragraph.\par
\xspaceskip=9pt plus1pt minus1pt
Explicit sentence glue is consumed here. Next sentence uses xspaceskip.
An abbreviation A. still uses the normal font space.\par
\message{Native sfcode construction completed.}
\end
+25
View File
@@ -0,0 +1,25 @@
% Actual vertical breaking, remaining-list pruning and migrating marks.
\input math-fonts
\hsize=270pt \baselineskip=15pt \parskip=4pt
\pretolerance=10000 \tolerance=10000
\splitmaxdepth=2pt \splittopskip=10pt plus1fil
\noindent Native splitting consumes original paragraph lines and rules.\par
\setbox1=\vbox{\hsize=135pt\baselineskip=14pt\parskip=0pt
\marks7{SEVEN}
\noindent Alpha\mark{FIRST} beta gamma delta epsilon zeta eta theta iota kappa.
Original glyph nodes keep their fonts and positions.\mark{MIDDLE}\par
\noindent Symbols $x_i^j$ remain in their actual line boxes.\par
\hbox{A\vrule width1pt B\raise2pt\hbox{Raised}\mark{BOXMARK}}
\hrule height.5pt
\hbox{The final material has depth: gj.}\mark{LAST}}
\setbox0=\vsplit1 to38pt\relax
\message{SPLIT-FIRST=\splitfirstmark/\splitbotmark/\splitfirstmarks7}
\hbox{First fragment:\hskip8pt\box0}
\noindent First mark: \splitfirstmark. Class seven: \splitfirstmarks7.\par
\setbox0=\vsplit1 to38pt\relax
\message{SPLIT-REST=\splitfirstmark/\splitbotmark/\splitfirstmarks7}
\hbox{Second fragment:\hskip8pt\box0}
\noindent The remaining box is repacked from its original nodes.\par
\box1
\noindent Split marks are scoped by splitting rather than ordinary groups.\par
\end
+12
View File
@@ -0,0 +1,12 @@
\catcode123=1\catcode125=2
\pdfminorversion=7\pdfobjcompresslevel=3\pdfcompresslevel=0\pdfpkresolution=600
\pdfpagewidth=300bp\pdfpageheight=160bp\pdfhorigin=20pt\pdfvorigin=20pt
\tracingstats=2\tracingonline=0
\font\F=cmr10\F
\immediate\openout1=statistics.aux\count0=1
\def\payload{Native resource statistics AV office}
\setbox0=\vbox{\hbox{\payload}\kern2pt\hbox{Second actual line}
\write1{PAGE=\number\count0}}
\shipout\copy0
\pdfcompresslevel=9\count0=2\shipout\box0
\immediate\closeout1\end
@@ -0,0 +1,4 @@
\documentclass{article}
\begin{document}
Hello native LaTeX.
\end{document}
@@ -0,0 +1,12 @@
\documentclass[10pt,letterpaper]{article}
\begin{document}
\section{Font resources and sizes}
Roman text keeps the actual class-selected font and size.
\textbf{Bold text uses its own font resource.}
\textit{Italic text retains its metrics and correction.}
\texttt{Monospace text uses the requested typewriter face.}
Ordinary punctuation includes -- and --- with ``quoted words''.
A sentence ends here. An abbreviation A. keeps its ordinary space.
{\large A local size is selected through the real format.}\par
The original size is restored for this paragraph.
\end{document}
@@ -0,0 +1,12 @@
\documentclass[11pt,a4paper]{article}
\begin{document}
\section{Font resources and sizes}
Roman text keeps the actual class-selected font and size.
\textbf{Bold text uses its own font resource.}
\textit{Italic text retains its metrics and correction.}
\texttt{Monospace text uses the requested typewriter face.}
Ordinary punctuation includes -- and --- with ``quoted words''.
A sentence ends here. An abbreviation A. keeps its ordinary space.
{\large A local size is selected through the real format.}\par
The original size is restored for this paragraph.
\end{document}
@@ -0,0 +1,12 @@
\documentclass[12pt,letterpaper]{article}
\begin{document}
\section{Font resources and sizes}
Roman text keeps the actual class-selected font and size.
\textbf{Bold text uses its own font resource.}
\textit{Italic text retains its metrics and correction.}
\texttt{Monospace text uses the requested typewriter face.}
Ordinary punctuation includes -- and --- with ``quoted words''.
A sentence ends here. An abbreviation A. keeps its ordinary space.
{\large A local size is selected through the real format.}\par
The original size is restored for this paragraph.
\end{document}
@@ -0,0 +1,10 @@
\documentclass{article}
\begin{document}
\section{Math and native measurements}
Inline math uses actual family fonts: \(x^2+y=z\).
The following display retains its measured baseline and depth.
\[
\left(\frac{a+b}{c}\right)=z
\]
This paragraph continues after the display with ordinary spacing.
\end{document}
@@ -0,0 +1,17 @@
\documentclass{article}
\begin{document}
\section{Natural page flow}
\newcount\paragraphnumber
\paragraphnumber=0
\loop
\advance\paragraphnumber by1
Paragraph \the\paragraphnumber. Native page flow retains actual measured
lines, spacing, penalties and page ownership. These ordinary paragraphs
exercise the real output routine without a manual page break.\par
\ifnum\paragraphnumber<80
\repeat
\newpage
This explicit page follows the naturally paginated material.
\clearpage
The final paragraph is shipped by the real end of document routine.
\end{document}
@@ -0,0 +1,3 @@
\section{Child source}\label{sec:child}
\ProjectName{} is expanded from the main source definition.
The shared definition and section number are retained across input files.
@@ -0,0 +1,9 @@
\documentclass{article}
\newcommand{\ProjectName}{Native project}
\begin{document}
\section{Project entry}\label{sec:entry}
\ProjectName{} loads an ordinary child source and preserves custom macros.
\input{chapter}
The entry is section \ref{sec:entry}; the child is section \ref{sec:child}
on page \pageref{sec:child}. Real auxiliary files resolve these references.
\end{document}
+456
View File
@@ -0,0 +1,456 @@
//! Real LaTeX acceptance for editor-owned logical input batches. Package bytes
//! are supplied explicitly; no installed namespace is claimed to be snapshotted.
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::{Path, PathBuf},
sync::Arc,
};
use texrra_engine::native::{
AttemptPhase, CompileRequest, CompiledDocument, Entry, GeneratedInitialState,
HostPreparationPhase, NativeCompiler, ProjectDefinition, ProjectSnapshot, StreamJournal,
};
use texrra_tex_core::{
artifacts::file_version,
execution::JobTime,
resources::{ResourceVersion, WorldConfig},
};
fn request(cwd: &Path, image: &Path, roots: &[PathBuf]) -> Result<CompileRequest, String> {
let mut r = CompileRequest::new(
WorldConfig::from_environment(cwd, roots.to_vec())?,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 16, 123)
.unwrap()
.with_pdf_clock(0, 480)
.unwrap(),
);
r.entry = Entry::Format(image.into());
r.etex = true;
r.limits.steps = 600_000_000;
r.resource_manifest = Some("resources.json".into());
r.layout_manifest = Some("layout.json".into());
r = r.observe_generated_initial();
Ok(r)
}
fn initial(cwd: &Path) -> Result<GeneratedInitialState, String> {
let path = cwd.join("main.aux");
GeneratedInitialState::new(
cwd.into(),
BTreeMap::from([(path.clone(), file_version(&path)?)]),
)
}
// Physical IDs may differ when independently creating an initially absent file.
// Preserve their equality relations within each job, plus all other evidence.
// Original journals remain untouched in the saved report.
fn stream_behavior(journal: &StreamJournal) -> Result<serde_json::Value, String> {
let mut value = serde_json::to_value(journal).map_err(|e| e.to_string())?;
let mut identities = BTreeMap::new();
for event in value["events"].as_array_mut().unwrap() {
for pointer in [
"/effect/OpenInput/result/Ok/storage/File/Ok/unix_identity",
"/effect/OutputOpened/descriptor/Ok/unix_identity",
] {
if let Some(identity) = event.pointer_mut(pointer).filter(|v| !v.is_null()) {
let key = serde_json::to_string(identity).map_err(|e| e.to_string())?;
let next = identities.len() + 1;
let id = identities.entry(key).or_insert(next);
*identity = serde_json::json!({"within_job_identity":id});
}
}
}
Ok(value)
}
fn compile(c: &NativeCompiler, r: CompileRequest) -> Result<Arc<CompiledDocument>, String> {
c.compile_detailed(r).map_err(|e| e.to_string())
}
fn save(path: &Path, value: &impl serde::Serialize) -> Result<(), String> {
fs::write(
path,
serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())
}
fn put(path: &Path, data: &[u8]) -> Result<(), String> {
fs::write(path, data).map_err(|e| e.to_string())
}
fn restore(path: &Path, bytes: Option<&[u8]>) -> Result<(), String> {
if let Some(data) = bytes {
put(path, data)
} else {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
}
}
}
fn run() -> Result<(), String> {
let mut args = std::env::args_os().skip(1);
let image = PathBuf::from(
args.next()
.ok_or("native_atomic_session IMAGE NEW_OUTPUT_DIR TEXMF_ROOT...")?,
)
.canonicalize()
.map_err(|e| e.to_string())?;
let out = PathBuf::from(args.next().ok_or("missing output directory")?);
let roots: Vec<PathBuf> = args.map(PathBuf::from).collect();
if roots.is_empty() {
return Err("explicit TEXMF roots required".into());
}
fs::create_dir(&out).map_err(|e| e.to_string())?;
let out = out.canonicalize().map_err(|e| e.to_string())?;
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/native-format-stage/a4-project");
let original_main = fs::read_to_string(fixture.join("main.tex")).map_err(|e| e.to_string())?;
let original_child =
fs::read_to_string(fixture.join("chapter.tex")).map_err(|e| e.to_string())?;
let original_versions = [
file_version(&fixture.join("main.tex"))?,
file_version(&fixture.join("chapter.tex"))?,
];
let seed = out.join("physical-seed");
let shared = out.join("shared");
fs::create_dir(&seed).map_err(|e| e.to_string())?;
fs::create_dir(&shared).map_err(|e| e.to_string())?;
put(&seed.join("main.tex"), original_main.as_bytes())?;
put(&seed.join("chapter.tex"), original_child.as_bytes())?;
let seed_compiler = NativeCompiler::default();
let mut seed_result = None;
let mut assets: BTreeMap<PathBuf, Arc<[u8]>> = BTreeMap::new();
for pass in 1..=3 {
let document = compile(&seed_compiler, request(&seed, &image, &roots)?)?;
let mut captured = Vec::new();
for (path, value) in document.inputs.files() {
if path.starts_with(&seed) {
continue;
}
let value = value.map_err(str::to_owned)?;
captured.push(value.version.clone());
if let Some(previous) = assets.insert(path.into(), value.data.clone()) {
if previous != value.data {
return Err(format!(
"seed resource changed between passes: {}",
path.display()
));
}
}
}
save(&seed.join(format!("pass-{pass}-captured.json")), &captured)?;
save(
&seed.join(format!("pass-{pass}-resources.json")),
&document.resources,
)?;
// Existence-only positive probes are namespace entries too. In
// particular, first-pass unresolved references can request fonts which
// the converged third pass no longer reads. Do not infer the complete
// logical bundle from the last pass's byte reads alone.
for path in document
.resources
.trace
.lookups
.iter()
.filter_map(|v| v.resolved.as_ref())
{
if !path.starts_with(&seed) && !assets.contains_key(path) {
assets.insert(
path.clone(),
Arc::from(fs::read(path).map_err(|e| e.to_string())?),
);
}
}
seed_result = Some(document);
}
let seed_result = seed_result.unwrap();
// This explicitly defines a new finite logical package bundle. Other
// installed files are not inferred present; callers can supply any bundle.
let mut coverage: BTreeSet<PathBuf> = roots.iter().cloned().collect();
coverage.insert(shared.clone());
for path in assets.keys() {
if !coverage.iter().any(|r| path.starts_with(r)) {
coverage.insert(path.parent().ok_or("asset requires parent")?.into());
}
}
let asset_versions: Vec<_> = assets
.iter()
.map(|(path, data)| ResourceVersion {
path: path.clone(),
bytes: data.len() as u64,
sha256: format!("{:x}", Sha256::digest(data)),
})
.collect();
save(&out.join("package-assets.json"), &asset_versions)?;
let poison = br"\texrraPhysicalPoisonMustNotExecute";
for name in ["main.tex", "chapter.tex", "optional.tex"] {
put(&shared.join(name), poison)?;
}
let cases=vec![
("unmodified",original_main.clone(),original_child.clone(),"chapter.tex",None),
("body",original_main.clone(),format!("{original_child}\\par A body buffer edit.\n"),"chapter.tex",None),
("macro",original_main.replace("{Native project}","{Atomic macro edit}"),original_child.clone(),"chapter.tex",None),
("new-input",original_main.replace(r"\input{chapter}",r"\input{buffer-note}"),format!("{original_child}\\par A new input buffer.\n"),"buffer-note.tex",None),
("absent",original_main.replace(r"\end{document}","\\par\\InputIfFileExists{optional.tex}{}{Missing optional branch.}\n\\end{document}"),original_child.clone(),"chapter.tex",None),
("present",original_main.replace(r"\end{document}","\\par\\InputIfFileExists{optional.tex}{}{Missing optional branch.}\n\\end{document}"),original_child.clone(),"chapter.tex",Some("Present optional buffer.\\par\n")),
];
let compiler = NativeCompiler::default();
let mut rows = Vec::new();
let mut last: Option<Arc<CompiledDocument>> = None;
let mut previous_project: Option<Arc<ProjectSnapshot>> = None;
let first_initial = initial(&shared)?;
for (index, (name, main, child, child_name, optional)) in cases.into_iter().enumerate() {
let case = out.join(name);
fs::create_dir(&case).map_err(|e| e.to_string())?;
put(&case.join("main.tex"), main.as_bytes())?;
put(&case.join(child_name), child.as_bytes())?;
if let Some(text) = optional {
put(&case.join("optional.tex"), text.as_bytes())?;
}
let mut configuration = request(&shared, &image, &roots)?.world;
configuration.cwd = shared.clone();
let mut files = assets.clone();
files.insert(shared.join("main.tex"), Arc::from(main.as_bytes()));
files.insert(shared.join(child_name), Arc::from(child.as_bytes()));
if let Some(text) = optional {
files.insert(shared.join("optional.tex"), Arc::from(text.as_bytes()));
}
let definition = ProjectDefinition {
configuration,
revision: index as u64 + 1,
roots: coverage.clone(),
files,
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([shared.clone()]),
generated: BTreeSet::from([shared.join("main.aux")]),
};
let rebuilt = ProjectSnapshot::new(definition.clone())?;
let mut edited_files = None;
let mut unchanged_buffer_bytes = 0;
let project = if let Some(previous) = &previous_project
&& previous
.files()
.map(|(path, _)| path)
.eq(definition.files.keys().map(PathBuf::as_path))
{
let edits: BTreeMap<_, _> = definition
.files
.iter()
.filter(|(path, data)| {
let old = &previous.file(path).unwrap().data;
!Arc::ptr_eq(old, data) && old.as_ref() != data.as_ref()
})
.map(|(path, data)| (path.clone(), data.clone()))
.collect();
edited_files = Some(edits.len());
let next = previous.with_file_edits(definition.revision, edits)?;
assert_eq!(next.version(), rebuilt.version());
assert_eq!(next.content_descriptor()?, rebuilt.content_descriptor()?);
for (path, before) in previous.files() {
let after = next.file(path).unwrap();
if before.version == after.version {
assert!(Arc::ptr_eq(&before.data, &after.data));
unchanged_buffer_bytes += before.version.bytes;
}
}
next
} else {
rebuilt.clone()
};
previous_project = Some(project.clone());
put(
&case.join("content-descriptor.json"),
&project.content_descriptor()?,
)?;
if index == 1 {
let previous = last.as_ref().unwrap();
let pdf = fs::read(shared.join("main.pdf")).map_err(|e| e.to_string())?;
let log = fs::read(shared.join("main.log")).map_err(|e| e.to_string())?;
let aux = fs::read(shared.join("main.aux")).map_err(|e| e.to_string())?;
let failure = compiler
.compile_detailed(
request(&shared, &image, &roots)?
.with_project(project.clone())
.with_generated_initial(first_initial.clone()),
)
.err()
.ok_or("expected stale generated initial precondition failure")?;
assert_eq!(failure.phase, AttemptPhase::Preparing);
assert_eq!(
failure.host_preparation.phase,
HostPreparationPhase::GeneratedInitial
);
assert!(failure.failed_execution.is_none() && failure.completed_execution.is_none());
assert_eq!(
failure.host_preparation.generated_initial.as_ref(),
Some(&initial(&shared)?)
);
assert!(Arc::ptr_eq(previous, &compiler.latest().unwrap()));
assert_eq!(fs::read(shared.join("main.pdf")).unwrap(), pdf);
assert_eq!(fs::read(shared.join("main.log")).unwrap(), log);
assert_eq!(fs::read(shared.join("main.aux")).unwrap(), aux);
save(
&out.join("generated-stale-failure.json"),
&serde_json::json!({"revision":failure.revision,"phase":failure.phase,"error":failure.error,"request":failure.request,"host_preparation":failure.host_preparation,"project":project.version(),"execution_absent":true,"old_publication_pdf_log_aux_preserved":true}),
)?;
}
if index == 3 {
let mut bad = definition;
bad.revision = 100;
let text = main.replace(
r"\end{document}",
"\\texrraUndefinedAtomicProof\n\\end{document}",
);
bad.files
.insert(shared.join("main.tex"), Arc::from(text.as_bytes()));
let bad = ProjectSnapshot::new(bad)?;
let previous = last.as_ref().unwrap();
let previous_pdf = fs::read(shared.join("main.pdf")).map_err(|e| e.to_string())?;
let failure = compiler
.compile_detailed(
request(&shared, &image, &roots)?
.with_project(bad.clone())
.with_generated_initial(initial(&shared)?),
)
.err()
.ok_or("expected actual atomic execution failure")?;
assert!(failure.to_string().contains("texrraUndefinedAtomicProof"));
assert_eq!(
failure
.inputs
.as_ref()
.unwrap()
.project()
.unwrap()
.version(),
bad.version()
);
assert!(Arc::ptr_eq(previous, &compiler.latest().unwrap()));
assert_eq!(fs::read(shared.join("main.pdf")).unwrap(), previous_pdf);
save(
&out.join("atomic-failure.json"),
&serde_json::json!({"phase":failure.phase,"error":failure.error,"project":failure.inputs.as_ref().unwrap().project().unwrap().version(),"source_versions":failure.failed_execution.as_ref().unwrap().evidence.source_versions,"host_preparation":failure.host_preparation,"host_runtime":failure.host_runtime,"stream_io":failure.resources.as_ref().unwrap().stream_io,"old_publication_preserved":true}),
)?;
// Genuine failed aux side effects remain; restore a known starting
// state for the next shared/clean comparison, not inside the engine.
put(
&shared.join("main.aux"),
&fs::read(out.join("macro/pass-3.aux")).map_err(|e| e.to_string())?,
)?;
}
for pass in 1..=3 {
let aux = shared.join("main.aux");
let before = fs::read(&aux).ok();
let expected_initial = initial(&shared)?;
let actual = compile(
&compiler,
request(&shared, &image, &roots)?
.with_project(project.clone())
.with_generated_initial(expected_initial.clone()),
)?;
let actual_layout = fs::read(shared.join("layout.json")).map_err(|e| e.to_string())?;
let after = fs::read(&aux).map_err(|e| e.to_string())?;
restore(&aux, before.as_deref())?;
let fresh = compile(
&NativeCompiler::default(),
request(&shared, &image, &roots)?
.with_project(rebuilt.clone())
.with_generated_initial(expected_initial.clone()),
)?;
assert_eq!(
actual.resources.generated_initial.as_ref(),
Some(&expected_initial)
);
assert_eq!(
actual.resources.generated_initial,
fresh.resources.generated_initial
);
assert_eq!(
stream_behavior(&actual.resources.stream_io)?,
stream_behavior(&fresh.resources.stream_io)?
);
assert_eq!(actual.pages, fresh.pages);
assert_eq!(actual.pdf, fresh.pdf);
assert_eq!(actual.source_map.pages, fresh.source_map.pages);
assert_eq!(
actual.execution.source_versions,
fresh.execution.source_versions
);
assert_eq!(fs::read(&aux).unwrap(), after);
assert_eq!(
actual.resources.trace.project_version.as_ref(),
Some(project.version())
);
assert!(actual.inputs.replay_gaps().is_empty());
for filename in ["main.tex", "chapter.tex", "optional.tex"] {
assert_eq!(fs::read(shared.join(filename)).unwrap(), poison);
}
assert!(!shared.join("buffer-note.tex").exists());
let pdf = case.join(format!("pass-{pass}.pdf"));
let map = case.join(format!("pass-{pass}-source-map.json"));
let layout = case.join(format!("pass-{pass}-layout.json"));
let saved_aux = case.join(format!("pass-{pass}.aux"));
put(&pdf, actual.pdf.as_ref().ok_or("expected a real page")?)?;
save(&map, &actual.source_map)?;
put(&layout, &actual_layout)?;
put(&saved_aux, &after)?;
if name == "unmodified" && pass == 3 {
assert_eq!(actual.pdf, seed_result.pdf);
assert_eq!(actual.source_map.pages, seed_result.source_map.pages);
assert_eq!(after, fs::read(seed.join("main.aux")).unwrap());
}
let work = actual.line_break_work;
let independent = fresh.line_break_work;
assert_eq!(
work.examined_edges + work.reused_edges,
independent.examined_edges + independent.reused_edges
);
assert_eq!(
work.solved_passes + work.reused_passes,
independent.solved_passes + independent.reused_passes
);
rows.push(serde_json::json!({
"case":name,"pass":pass,"revision":actual.revision(),"project":project.version(),
"editor_delta_files":edited_files,
"editor_delta_unchanged_bytes":unchanged_buffer_bytes,
"pdf":file_version(&pdf)?,"source_map":file_version(&map)?,"layout":file_version(&layout)?,
"aux":file_version(&saved_aux)?,"aux_before":before,"resources":actual.resources,
"independent_stream_io":fresh.resources.stream_io,"host_preparation":actual.host_preparation,
"host_runtime":actual.host_runtime,"source_versions":actual.execution.source_versions,
"full_clean_equal":true,"physical_poison_untouched":true,
"line_break_work": {
"solved_passes":work.solved_passes,"reused_passes":work.reused_passes,
"examined_edges":work.examined_edges,"reused_edges":work.reused_edges
},
"independent_line_break_work": {
"solved_passes":independent.solved_passes,"reused_passes":independent.reused_passes,
"examined_edges":independent.examined_edges,"reused_edges":independent.reused_edges
}
}));
save(
&out.join("progress.json"),
&serde_json::json!({"passed":false,"rows":rows}),
)?;
last = Some(actual);
}
}
assert_eq!(
original_versions,
[
file_version(&fixture.join("main.tex"))?,
file_version(&fixture.join("chapter.tex"))?
]
);
save(
&out.join("report.json"),
&serde_json::json!({"passed":true,"scope":"atomic external logical project versions, exact complete known generated initial preconditions and real live I/O; no effect replay, execution/layout reuse or realtime claim","format":file_version(&image)?,"original_sources":original_versions,"logical_bundle":file_version(&out.join("package-assets.json"))?,"atomic_cases":6,"atomic_revisions":18,"independent_full_jobs":18,"physical_seed_jobs":3,"failure_jobs":2,"executed_failure_jobs":1,"preparation_failure_jobs":1,"compile_attempts":41,"executed_jobs":40,"physical_poison_untouched":true,"generated_initial_state_explicitly_restored":true,"generated_initial_expectations_checked":true,"rows":rows}),
)?;
println!("atomic real LaTeX project batches, failure and full-clean equality passed");
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("{e}");
std::process::exit(1);
}
}
+252
View File
@@ -0,0 +1,252 @@
//! Acceptance driver: real LaTeX failures/recovery and strict observed inputs.
//! All project mutations occur in newly created copies of the frozen A4 case.
use std::{
fs,
path::{Path, PathBuf},
sync::Arc,
};
use texrra_engine::native::{
AttemptPhase, CompileError, CompileRequest, CompiledDocument, Entry, HostObservation,
HostPreparationPhase, NativeCompiler,
};
use texrra_tex_core::{artifacts::file_version, execution::JobTime, resources::WorldConfig};
fn request(cwd: &Path, image: &Path, roots: &[PathBuf]) -> Result<CompileRequest, String> {
let mut r = CompileRequest::new(
WorldConfig::from_environment(cwd, roots.to_vec())?,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 16, 123)
.unwrap()
.with_pdf_clock(0, 480)
.unwrap(),
);
r.entry = Entry::Format(image.to_owned());
r.etex = true;
r.limits.steps = 600_000_000;
r.resource_manifest = Some("resources.json".into());
r.layout_manifest = Some("layout.json".into());
Ok(r)
}
fn compile(c: &NativeCompiler, r: CompileRequest) -> Result<Arc<CompiledDocument>, String> {
c.compile_detailed(r).map_err(|e| e.to_string())
}
fn same(a: &CompiledDocument, b: &CompiledDocument) {
assert_eq!(a.pdf, b.pdf);
assert_eq!(a.pages, b.pages);
assert_eq!(a.source_map.pages, b.source_map.pages);
assert_eq!(a.execution.source_versions, b.execution.source_versions);
}
fn save(path: &Path, value: &impl serde::Serialize) -> Result<(), String> {
fs::write(
path,
serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())
}
fn run() -> Result<(), String> {
let mut args = std::env::args_os().skip(1);
let image = PathBuf::from(
args.next()
.ok_or("native_attempt_replay IMAGE NEW_OUTPUT_DIR TEXMF_ROOT...")?,
)
.canonicalize()
.map_err(|e| e.to_string())?;
let out = PathBuf::from(args.next().ok_or("missing output directory")?);
let roots: Vec<PathBuf> = args.map(PathBuf::from).collect();
if roots.is_empty() {
return Err("explicit TEXMF roots required".into());
}
fs::create_dir(&out).map_err(|e| e.to_string())?;
let out = out.canonicalize().map_err(|e| e.to_string())?;
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/native-format-stage/a4-project");
let main = fs::read(fixture.join("main.tex")).map_err(|e| e.to_string())?;
let child = fs::read(fixture.join("chapter.tex")).map_err(|e| e.to_string())?;
let original = [
file_version(&fixture.join("main.tex"))?,
file_version(&fixture.join("chapter.tex"))?,
];
let shared = out.join("shared");
let clean = out.join("clean");
for p in [&shared, &clean] {
fs::create_dir(p).map_err(|e| e.to_string())?;
fs::write(p.join("main.tex"), &main).map_err(|e| e.to_string())?;
fs::write(p.join("chapter.tex"), &child).map_err(|e| e.to_string())?;
}
let compiler = NativeCompiler::default();
let reference = NativeCompiler::default();
let mut baseline = None;
let mut expected = None;
for _ in 0..3 {
baseline = Some(compile(&compiler, request(&shared, &image, &roots)?)?);
expected = Some(compile(&reference, request(&clean, &image, &roots)?)?);
}
let baseline = baseline.unwrap();
let expected = expected.unwrap();
same(&baseline, &expected);
let stable_aux = fs::read(shared.join("main.aux")).map_err(|e| e.to_string())?;
assert!(baseline.inputs.file(&image).is_some());
assert_eq!(
&*baseline.inputs.file(&shared.join("main.tex")).unwrap().data,
&main
);
let bad_main = String::from_utf8(main.clone())
.unwrap()
.replace(r"\end{document}", "\\input failure.tex\n\\end{document}");
assert_ne!(bad_main.as_bytes(), main);
fs::write(shared.join("main.tex"), bad_main).map_err(|e| e.to_string())?;
fs::write(
shared.join("failure.tex"),
br"\immediate\openout15=partial.dat\immediate\write15{PARTIAL}\texrraUndefinedAttemptProof",
)
.map_err(|e| e.to_string())?;
let mut failed_request = request(&shared, &image, &roots)?;
failed_request.failure_manifest = Some(out.join("failed-attempt-full.json"));
let failure = compiler
.compile_detailed(failed_request)
.err()
.ok_or("expected execution failure")?;
assert_eq!(failure.phase, AttemptPhase::Executing);
assert!(matches!(failure.error, CompileError::Execution(_)));
assert!(
failure.evidence_gaps.is_empty(),
"{:?}",
failure.evidence_gaps
);
assert_eq!(failure.host_preparation.phase, HostPreparationPhase::Ready);
let policy = failure.host_preparation.ledger.as_ref().unwrap();
assert!(policy.eof && policy.error.is_none());
assert_eq!(
policy.version,
failure
.resources
.as_ref()
.unwrap()
.generated_artifacts
.ledger_input
);
assert!(failure.host_runtime.iter().any(
|o| matches!(o,HostObservation::Operation {name,result:Ok(()),..} if name=="open output")
));
save(
&out.join("failed-host.json"),
&serde_json::json!({"preparation":failure.host_preparation,"runtime":failure.host_runtime,"world_failure":failure.world_failure}),
)?;
let failed = failure.failed_execution.as_ref().unwrap();
assert!(
failed
.evidence
.sources
.iter()
.any(|s| s.name.ends_with("failure.tex"))
);
assert_eq!(fs::read(shared.join("partial.dat")).unwrap(), b"PARTIAL\n");
assert!(Arc::ptr_eq(&baseline, &compiler.latest().unwrap()));
save(&out.join("failed-execution.json"), failed)?;
save(&out.join("failed-resources.json"), &failure.resources)?;
let mut failed_generated = Vec::new();
for (index, write) in failure
.resources
.as_ref()
.unwrap()
.generated_artifacts
.writes
.iter()
.enumerate()
{
if let Some(version) = &write.after {
let saved = out.join(format!("failed-generated-{index}.bin"));
fs::write(&saved, fs::read(&version.path).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())?;
let receipt = file_version(&saved)?.unwrap();
assert_eq!(receipt.sha256, version.sha256);
assert_eq!(receipt.bytes, version.bytes);
failed_generated.push(serde_json::json!({"path":write.path,"before":write.before,"after":version,"saved":receipt}));
}
}
let failed_inputs = failure.inputs.as_ref().unwrap();
for name in ["main.tex", "chapter.tex", "failure.tex"] {
fs::remove_file(shared.join(name)).map_err(|e| e.to_string())?;
}
// Failed LaTeX really truncated/wrote aux. Replay keeps real I/O; reset the
// known starting generated version explicitly, rather than pinning it.
fs::write(shared.join("main.aux"), &stable_aux).map_err(|e| e.to_string())?;
let replay_failure = compiler
.compile_detailed(request(&shared, &image, &roots)?.with_inputs(failed_inputs.clone()))
.err()
.ok_or("expected replay failure")?;
assert_eq!(
replay_failure.failed_execution.as_ref().unwrap().error,
failed.error
);
assert_eq!(
replay_failure
.failed_execution
.as_ref()
.unwrap()
.evidence
.source_versions,
failed.evidence.source_versions
);
save(
&out.join("replayed-failure-resources.json"),
&replay_failure.resources,
)?;
fs::write(shared.join("main.aux"), &stable_aux).map_err(|e| e.to_string())?;
let replay = compile(
&compiler,
request(&shared, &image, &roots)?.with_inputs(baseline.inputs.clone()),
)?;
same(&baseline, &replay);
assert_eq!(fs::read(shared.join("main.aux")).unwrap(), stable_aux);
fs::write(out.join("replayed.pdf"), replay.pdf.as_ref().unwrap()).map_err(|e| e.to_string())?;
save(&out.join("replayed-source-map.json"), &replay.source_map)?;
let mut unknown = request(&shared, &image, &roots)?.with_inputs(baseline.inputs.clone());
unknown.input = "uncaptured.tex".into();
fs::write(shared.join("uncaptured.tex"), &main).map_err(|e| e.to_string())?;
let denied = compiler
.compile_detailed(unknown)
.err()
.ok_or("unobserved external input must fail")?;
assert_eq!(denied.phase, AttemptPhase::Preparing);
assert!(
denied
.to_string()
.contains("snapshot has no lookup observation")
);
fs::write(shared.join("main.tex"), &main).map_err(|e| e.to_string())?;
fs::write(shared.join("chapter.tex"), &child).map_err(|e| e.to_string())?;
let recovered = compile(&compiler, request(&shared, &image, &roots)?)?;
same(&recovered, &expected);
assert_eq!(
original,
[
file_version(&fixture.join("main.tex"))?,
file_version(&fixture.join("chapter.tex"))?
]
);
let captured: Vec<_> = baseline
.inputs
.files()
.map(|(p, f)| serde_json::json!({"path":p,"version":f.ok().map(|f| &f.version)}))
.collect();
save(
&out.join("report.json"),
&serde_json::json!({"passed":true,"scope":"full native LaTeX attempts and strict captured external inputs; generated state explicitly restored for equivalent starting worlds; no incremental/performance claim",
"format":file_version(&image)?,"original_sources":original,"compile_attempts":11,"executed_jobs":10,"baseline_revision":baseline.revision(),"replayed_revision":replay.revision(),"recovered_revision":recovered.revision(),
"captured":captured,"failed_phase":format!("{:?}",failure.phase),"failed_sources":failed.evidence.source_versions,"failed_generated":failure.resources.as_ref().unwrap().generated_artifacts,
"failure_report":file_version(&out.join("failed-attempt-full.json"))?,"failed_host":file_version(&out.join("failed-host.json"))?,"host_evidence_verified":true,
"failed_generated_saved":failed_generated,
"failure_primary_preserved":true,"old_publication_preserved":true,"partial_io_preserved":true,"removed_project_sources_replayed":true,"unknown_physical_file_denied":true,"replay_equals_baseline_and_clean":true,"recovery_equals_clean":true,
"replayed_pdf":file_version(&out.join("replayed.pdf"))?,"replayed_source_map":file_version(&out.join("replayed-source-map.json"))?}),
)?;
println!("real LaTeX failed attempt, strict replay and clean recovery passed");
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("{e}");
std::process::exit(1);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Compare page updates with independent full previews of the original A3 article.
use sha2::{Digest, Sha256};
use std::{fs, path::PathBuf, sync::Arc};
use texrra_engine::native::{CompileRequest, Entry, NativeCompiler};
use texrra_tex_core::{
execution::JobTime,
resources::{InputPolicy, WorldConfig},
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut arguments = std::env::args_os().skip(1).map(PathBuf::from);
let source = arguments.next().ok_or("missing original A3 source")?;
let image = arguments.next().ok_or("missing native LaTeX format")?;
let dst = arguments.next().ok_or("missing new evidence directory")?;
let roots: Vec<_> = arguments.collect();
assert!(!roots.is_empty());
fs::create_dir(&dst)?;
let directory = dst.canonicalize()?;
let original = fs::read_to_string(&source)?;
let marker = "This explicit page follows the naturally paginated material.";
assert_eq!(original.matches(marker).count(), 1);
let edited = original.replace(
marker,
"This edited page follows the naturally paginated and independently measured material.",
);
let compiler = NativeCompiler::default();
let mut world = WorldConfig::from_environment(&directory, roots)?;
world.input_policy = InputPolicy::Tex;
let mut request = CompileRequest::new(
world,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 18, 1000)?.with_pdf_clock(0, 0)?,
);
request.entry = Entry::Format(image);
request.etex = true;
request.limits.steps = 600_000_000;
fs::write(directory.join("main.tex"), &original)?;
let first = compiler.compile(request.clone())?;
let first_preview = first.preview_since(None)?;
assert!(first_preview.page_count > 2);
fs::write(directory.join("main.tex"), &edited)?;
let second = compiler.compile(request.clone())?;
let update = second.preview_since(Some(first.revision()))?;
assert_eq!(update.base_revision, Some(first.revision()));
assert_eq!(update.page_count, first_preview.page_count);
assert_eq!(update.pages.len(), 1);
let changed = update.page_count - 2;
assert_eq!(update.pages[0].index, changed);
let full = second.preview_since(None)?;
for index in 0..update.page_count {
if index != changed {
assert!(Arc::ptr_eq(
&first_preview.pages[index].svg,
&full.pages[index].svg
));
}
}
assert_ne!(
first.source_map.pages.last(),
second.source_map.pages.last()
);
let independent = NativeCompiler::default().compile(request)?;
assert_eq!(full.pages, independent.preview_since(None)?.pages);
assert_eq!(second.source_map.pages, independent.source_map.pages);
assert_eq!(second.pdf, independent.pdf);
let report = serde_json::json!({
"original_source_sha256": format!("{:x}", Sha256::digest(original.as_bytes())),
"edited_source_sha256": format!("{:x}", Sha256::digest(edited.as_bytes())),
"pages": update.page_count,
"changed_page": changed + 1,
"same_svg_allocations": update.page_count - 1,
"pdf_sha256": format!("{:x}", Sha256::digest(second.pdf.as_deref().unwrap())),
"independent_pdf_svg_and_source_map_equal": true,
"unchanged_last_page_uses_current_sources": true,
});
let report = serde_json::to_vec_pretty(&report)?;
fs::write(directory.join("report.json"), &report)?;
println!("{}", String::from_utf8(report)?);
Ok(())
}
+272
View File
@@ -0,0 +1,272 @@
//! External acceptance driver for the public full-job API, not a runtime frontend.
//! Uses a real native LaTeX image and isolated copies of the frozen A4 project.
use std::{
fs,
path::{Path, PathBuf},
sync::Arc,
};
use texrra_engine::native::{CompileRequest, CompiledDocument, Entry, NativeCompiler};
use texrra_tex_core::{
artifacts::file_version, execution::JobTime, render::DisplayItem, resources::WorldConfig,
};
fn request(cwd: &Path, image: &Path, roots: &[PathBuf]) -> Result<CompileRequest, String> {
let world = WorldConfig::from_environment(cwd, roots.to_vec())?;
let mut r = CompileRequest::new(
world,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 16, 123)
.unwrap()
.with_pdf_clock(0, 480)
.unwrap(),
);
r.entry = Entry::Format(image.to_owned());
r.etex = true;
r.limits.steps = 600_000_000;
r.resource_manifest = Some("resources.json".into());
r.layout_manifest = Some("layout.json".into());
Ok(r)
}
fn compile(
compiler: &NativeCompiler,
cwd: &Path,
image: &Path,
roots: &[PathBuf],
) -> Result<Arc<CompiledDocument>, String> {
compiler
.compile(request(cwd, image, roots)?)
.map_err(|e| e.to_string())
}
fn snapshot(path: &Path) -> Result<Option<texrra_tex_core::resources::ResourceVersion>, String> {
file_version(path)
}
fn main() {
if let Err(e) = run() {
eprintln!("{e}");
std::process::exit(1);
}
}
fn run() -> Result<(), String> {
let mut args = std::env::args_os().skip(1);
let image = PathBuf::from(
args.next()
.ok_or("native_project_session IMAGE NEW_OUTPUT_DIR TEXMF_ROOT...")?,
)
.canonicalize()
.map_err(|e| e.to_string())?;
let out = PathBuf::from(args.next().ok_or("missing new output directory")?);
let roots: Vec<PathBuf> = args.map(PathBuf::from).collect();
if roots.is_empty() {
return Err("explicit TEXMF roots required".into());
}
fs::create_dir(&out).map_err(|e| format!("new session directory: {e}"))?;
let out = out.canonicalize().map_err(|e| e.to_string())?;
let fixture =
Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/native-format-stage/a4-project");
let original_main = fs::read_to_string(fixture.join("main.tex")).map_err(|e| e.to_string())?;
let original_child =
fs::read_to_string(fixture.join("chapter.tex")).map_err(|e| e.to_string())?;
let original_versions = [
snapshot(&fixture.join("main.tex"))?,
snapshot(&fixture.join("chapter.tex"))?,
];
let shared = out.join("shared");
fs::create_dir(&shared).map_err(|e| e.to_string())?;
let compiler = NativeCompiler::default();
let cases = [
(
"unmodified",
original_main.clone(),
"chapter.tex",
original_child.clone(),
),
(
"body",
original_main.clone(),
"chapter.tex",
format!("{original_child}\\par A session body edit.\n"),
),
(
"input",
original_main.replace(r"\input{chapter}", r"\input{chapter-edit}"),
"chapter-edit.tex",
format!("{original_child}\\par A changed input file.\n"),
),
(
"macro",
original_main.replace("Native project", "A changed project macro"),
"chapter.tex",
original_child.clone(),
),
(
"font",
original_main.clone(),
"chapter.tex",
format!(
"{original_child}\\par {{\\fontsize{{12}}{{14}}\\selectfont Explicit font edit.}}\n"
),
),
(
"aux",
original_main.clone(),
"chapter.tex",
format!(
"{original_child}\\par \\ifdefined\\SessionAux\\SessionAux\\else No aux override.\\fi\n"
),
),
(
"math",
original_main.clone(),
"chapter.tex",
format!("{original_child}\\par Math baseline. $x_i^2+\\frac{{a}}{{b}}+\\sqrt{{y}}$.\n"),
),
(
"math-macro",
original_main.replace(
r"\begin{document}",
r"\newcommand{\ProjectFormula}[1]{#1_j^3+\frac{c}{d}+\sqrt{z}}\begin{document}",
),
"chapter.tex",
format!("{original_child}\\par Math macro edit. $\\ProjectFormula{{u}}$.\n"),
),
(
"math-font",
original_main.clone(),
"chapter.tex",
format!(
"{original_child}\\par {{\\fontsize{{12}}{{14}}\\selectfont Math font edit. $v_k^4+\\frac{{e}}{{f}}+\\sqrt{{w}}$}}.\n"
),
),
];
let mut rows = Vec::new();
for (name, main, child_name, child) in cases {
let case = out.join(name);
fs::create_dir(&case).map_err(|e| e.to_string())?;
let clean = case.join("clean");
fs::create_dir(&clean).map_err(|e| e.to_string())?;
for dir in [&shared, &clean, &case] {
fs::write(dir.join("main.tex"), &main).map_err(|e| e.to_string())?;
fs::write(dir.join(child_name), &child).map_err(|e| e.to_string())?;
}
if name == "aux" {
use std::io::Write;
let mut file = fs::OpenOptions::new()
.append(true)
.open(shared.join("main.aux"))
.map_err(|e| e.to_string())?;
writeln!(file, "\\gdef\\SessionAux{{Auxiliary edit visible}}")
.map_err(|e| e.to_string())?;
}
if let Ok(before) = fs::read(shared.join("main.aux")) {
// Give the independent job genuine ownership, then supply exactly
// the same observed aux bytes. Never adopt an unknown user input.
compile(&NativeCompiler::default(), &clean, &image, &roots)?;
fs::write(clean.join("main.aux"), before).map_err(|e| e.to_string())?;
}
for pass in 1..=3 {
let before = snapshot(&shared.join("main.aux"))?;
let a = compile(&compiler, &shared, &image, &roots)?;
let b = compile(&NativeCompiler::default(), &clean, &image, &roots)?;
if a.pages != b.pages
|| a.pdf != b.pdf
|| a.source_map.pages != b.source_map.pages
|| a.source_map
.sources
.iter()
.map(|s| (&s.version, s.kind))
.collect::<Vec<_>>()
!= b.source_map
.sources
.iter()
.map(|s| (&s.version, s.kind))
.collect::<Vec<_>>()
|| fs::read(shared.join("main.aux")).map_err(|e| e.to_string())?
!= fs::read(clean.join("main.aux")).map_err(|e| e.to_string())?
{
return Err(format!("session/clean output differs: {name} pass {pass}"));
}
for file in ["main.tex", child_name] {
let path = shared.join(file);
if !a.resources.trace.reads.iter().any(|v| v.path == path) {
return Err(format!("actual source not read: {}", path.display()));
}
}
if name == "font"
&& !a.pages.iter().flat_map(|p| p.items.iter()).any(
|item| matches!(item,DisplayItem::NativeGlyph {font,..} if font.name=="cmr12"),
)
{
return Err("font edit did not use actual cmr12 glyphs".into());
}
if name.starts_with("math") {
use texrra_tex_core::provenance::Derivation;
if !a.source_map.is_complete()
|| ![Derivation::Fraction, Derivation::Radical].iter().all(|d| {
a.source_map
.pages
.iter()
.flat_map(|p| &p.entries)
.any(|e| e.source.derivations.contains(d))
})
{
return Err(format!(
"real mathematical paint or sources missing: {name} pass {pass}"
));
}
}
if name == "math-font"
&& !a
.pages
.iter()
.flat_map(|p| &p.items)
.any(|i| matches!(i,DisplayItem::NativeGlyph{font,..} if font.name=="cmmi12"))
{
return Err("real NFSS math size did not use cmmi12".into());
}
let pdf = case.join(format!("pass-{pass}.pdf"));
fs::write(&pdf, a.pdf.as_deref().ok_or("no actual PDF")?).map_err(|e| e.to_string())?;
let aux = case.join(format!("pass-{pass}.aux"));
fs::copy(shared.join("main.aux"), &aux).map_err(|e| e.to_string())?;
let receipt = &a.resources.generated_artifacts;
let layout = case.join(format!("pass-{pass}-layout.json"));
fs::copy(shared.join("layout.json"), &layout).map_err(|e| e.to_string())?;
let map = case.join(format!("pass-{pass}-source-map.json"));
fs::write(
&map,
serde_json::to_vec_pretty(&a.source_map).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())?;
let mapped: usize = a.source_map.pages.iter().map(|p| p.entries.len()).sum();
let unmapped: usize = a.source_map.pages.iter().map(|p| p.unmapped.len()).sum();
rows.push(serde_json::json!({"case":name,"pass":pass,"revision":a.revision(),"pages":a.pages.len(),
"pdf":snapshot(&pdf)?,"aux_before":before,"aux_after":snapshot(&aux)?,
"source_map":snapshot(&map)?,"mapped_paint":mapped,"unmapped_paint":unmapped,"shared_clean_source_map_equal":true,
"layout":snapshot(&layout)?,
"source_versions":a.execution.source_versions,"resource_reads":a.resources.trace.reads,
"generated_artifacts":receipt,"shared_clean_pages_pdf_aux_equal":true}));
fs::write(
out.join("progress.json"),
serde_json::to_vec_pretty(&serde_json::json!({"passed":false,"rows":rows}))
.map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())?;
}
}
if [
snapshot(&fixture.join("main.tex"))?,
snapshot(&fixture.join("chapter.tex"))?,
] != original_versions
{
return Err("original frozen project changed".into());
}
let report = serde_json::json!({"schema":1,"passed":true,"scope":"full native API session and retained paint source maps vs independent clean jobs; uncollected paths explicitly unmapped, no incremental/performance claim", "format":snapshot(&image)?,"original_sources":original_versions,"rows":rows});
fs::write(
out.join("report.json"),
serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())?;
println!("27 shared revisions match independent clean jobs; original sources unchanged");
Ok(())
}