AI-Assisted TeX Rendering in Rust: Lessons from a Ten-Minute Prototype
An AI-generated Rust prototype illustrates how large language models can accelerate the development of a math rendering engine without replacing the engineering behind TeX. This article examines the limits of formula support across content platforms, the architecture of a focused renderer, Rust’s advantages, and the testing, caching, and safety measures needed to turn a prototype into a service.
1. Why Math Rendering Remains a Gap on the Web
For researchers and technical writers, sharing a document containing mathematical formulas on a social platform, messaging app, or blog can be frustrating. Carefully written LaTeX expressions—with nested fractions, superscripts, subscripts, and Greek letters—may appear as raw markup rather than readable mathematics.
Three technical factors explain this problem:
- Rendering overhead: A complete TeX engine includes complex subsystems for macro expansion, line and page breaking, and font metrics. Many content platforms are reluctant to integrate an entire typesetting pipeline.
- Fragmented support: Markdown does not require math rendering. Some platforms integrate lightweight JavaScript libraries, while others provide no support at all.
- Format compatibility: Sharing formula source requires the recipient’s platform to render it. Converting formulas to images introduces concerns about resolution, font consistency, and accessibility, particularly for screen reader users.
Common workarounds have their own drawbacks. Screenshots from PDFs produce inconsistent styles and variable image quality. Online conversion services add third-party dependencies, network latency, and privacy concerns.
2. Understanding TeX: Powerful Design, Substantial Complexity
To assess what it means to “rewrite a typesetting engine,” it helps to understand TeX’s design.
Donald Knuth began developing TeX in the late 1970s after becoming dissatisfied with the quality of published typesetting. What he initially expected to finish in about six months became a project refined over nearly a decade. TeX is known for its mathematical precision: its version numbers progressively approach π, and Knuth established an increasing monetary reward for reported bugs. Recipients have often preferred to frame the checks rather than cash them.
Several technical characteristics are easy to underestimate:
- Turing completeness: TeX is more than a markup language. It supports conditional logic, iteration, recursion, and macro expansion. Community projects have used it to implement fractal renderers, maze solvers, and cellular automata.
- Global line-breaking optimization: TeX uses a dynamic programming algorithm with penalties to select line breaks across a paragraph. Rather than making a greedy decision for each line, it treats paragraph layout as an optimization problem.
- A box model grounded in font metrics: Characters and formula components are represented as boxes with dimensions. Layout emerges from nesting and positioning these boxes.
These capabilities also create complexity. TeX’s macro language can be difficult to understand, and its error messages are often challenging to interpret. For many graduate students, learning to troubleshoot it becomes a significant nonacademic burden.
This helps explain why complete TeX implementations are uncommon. Most systems that advertise “LaTeX math support” implement only a subset of mathematical typesetting, not the full language and document layout system.
3. Define the Scope: Render Formulas, Not Entire Documents
The central engineering decision is practical: do not attempt to reproduce all of TeX when the immediate problem is mathematical formula rendering.
A focused renderer can be divided into four layers:
- Lexical analysis: Split the source into tokens, identifying commands, brace-delimited groups, superscript and subscript markers, and other syntax.
- Parsing: Use a recursive descent parser to turn the token stream into an abstract syntax tree, or AST. The parser must handle recursively nested structures such as fractions, radicals, and matrices.
- Layout: Traverse the AST and use font metrics—including character widths, heights, and baseline relationships—to build a positioned box tree.
- Drawing and output: Render the box tree as a PNG image or SVG vector graphic, or generate HTML/CSS for browser rendering.
The layout layer is usually the most error-prone. Mathematical typography imposes strict requirements on spacing, sizing, and baseline alignment.
For example, nested fractions require coordinated adjustments to numerator and denominator sizes, spacing, and the fraction rule. The placement of limits around a summation symbol also differs between inline and display math. Such details account for much of the implementation effort.
A working prototype therefore demonstrates progress on a bounded problem—not equivalence to a complete TeX engine.
4. Why Rust Fits a Math Rendering Engine
Rust offers several useful properties for this kind of renderer:
- Memory safety with systems-level performance: Parsers and layout engines perform extensive tree manipulation. Rust’s ownership model helps prevent dangling references and data races at compile time while supporting performance comparable to C and C++.
- Enums and pattern matching for ASTs: Formula nodes map naturally to enum variants, and pattern matching makes parsing and layout logic easier to express clearly.
- WebAssembly deployment: Compiling the engine to WebAssembly allows the rendering core to be reused in browsers and compatible server-side environments, alongside native command-line deployments.
An illustrative AST might look like this:
enum Expr {Symbol(String),Group(Vec<Expr>),Fraction(Box<Expr>, Box<Expr>),Superscript(Box<Expr>, Box<Expr>),Subscript(Box<Expr>, Box<Expr>),Radical(Box<Expr>),// ...}
The layout stage then produces boxes containing width, height, depth below the baseline, and relative offsets for child elements. The drawing layer consumes those boxes to generate the final output.
This separation keeps formula structure distinct from its visual representation.
5. What the LLM Contributes—and What It Does Not
The striking claim in the source account is that a large language model generated a working Rust prototype in roughly ten minutes. The useful lesson is not that a model reproduced decades of TeX engineering in that time. It is that well-scoped tasks with clear specifications and established domain knowledge can move from idea to prototype much faster with LLM assistance.
That distinction matters:
- A prototype cannot establish full coverage. TeX has been tested through decades of use. Its many edge cases—including line breaking for very large expressions and recursive script-size adjustments—are unlikely to be covered by an initial implementation.
- Generated code is a starting point. Production readiness still requires human review and broader test coverage, especially in precision-sensitive areas such as font metrics.
- Architecture and acceptance remain human responsibilities. A productive workflow assigns architectural decisions and validation to engineers, while the model helps generate boilerplate and reference implementations.
The result is an accelerated development loop, not a replacement for understanding mathematical typesetting.
6. Engineering Recommendations for a Formula Rendering Service
For a service that converts LaTeX formulas into shareable images, the following architecture provides a practical path:
- Expose rendering as a stateless service. Deploy the engine through serverless functions that accept LaTeX source and return PNG or SVG output. Stateless processing supports horizontal scaling.
- Cache repeated formulas. Use a formula hash as a cache key, backed by object storage and a CDN, so identical formulas do not need to be rendered repeatedly.
- Support multiple output formats. SVG suits vector graphics and printing, PNG suits social sharing, and HTML/CSS suits embedded web content.
- Enforce resource limits. A full TeX implementation’s macro expansion capabilities can create resource-exhaustion risks. Limit parsing depth, expansion counts, and rendering time.
- Improve fidelity incrementally. Start with common structures: fractions, radicals, superscripts, subscripts, Greek letters, and matrices. Then extend support to alignment environments and automatically sized delimiters.
The goal is to deliver a useful, controlled subset before pursuing more advanced compatibility.
7. Conclusion
The difficulty of sharing mathematical formulas across content platforms points to a clear engineering approach: define the boundary around math typesetting, build a safe and efficient rendering core in a modern language such as Rust, and deliver it through stateless services and caching infrastructure.
Large language models can accelerate the initial implementation, but they do not remove the need for careful layout rules, testing, and human validation. A ten-minute prototype should be understood as a starting point for a focused renderer, not a complete rewrite of TeX.
TeX established a demanding standard for mathematical typography over years of development. Today’s developers can build on that foundation at a much lower initial cost. The broader lesson is to understand the design of established systems, isolate the capability that users actually need, and use modern tools to implement that capability responsibly.
