Architecture
Leonardo is structured as a layered set of packages. Dependencies point inward: every domain package imports core (and usually scalar); nothing imports cli or parser; the graph is a strict DAG.
cli
┌──┴──┐
parser latex
┌────────┬─────────┬──────┼──────┬─────────┬─────────┬────────┐
matrix equation transform ode logic probability domain vector … control
└────────┴─────────┴──────┴──────┴─────────┴─────────┴────────┘
scalar
│
core
The picture is a simplification — some domains also import each other in one direction (equation imports logic; statistics imports probability and matrix; transform imports matrix; control imports transform, matrix, vector and statistics; optimize imports matrix, equation, vector and logic) — but the invariants hold everywhere: core imports no domain, every arrow is one-way, and parser and cli sit above all of them.
latex sits in that top band too, and for a reason worth stating: a renderer that must match on scalar.Sin and matrix._Matrix cannot live in core, which imports no domain. So a domain-aware renderer sits above everything, as parser does, or is distributed across the nodes, as toString is — there is no third place, which is why a toLatex extension beside toExpression sounds obvious and is impossible.
Modules
That layering is also the artifact boundary. Because nothing imports cli, it can be published separately — and it is, so that a library consumer never resolves JLine. The MCP server sits one layer further out, over the REPL, for the same reason: its protocol stack must reach no one who only wants the library.
| Artifact | Contains | Extra dependencies |
|---|---|---|
it.grypho:leonardo | Every package except cli | scala-parser-combinators, spire |
it.grypho:leonardo-repl | cli only; depends on leonardo | jline |
it.grypho:leonardo-mcp | The MCP server; depends on leonardo-repl; JVM only | the MCP Java SDK (with Jackson and Reactor), slf4j-simple |
Every module is compiled for Java 25. The build checks the generated POMs on every run (sbt checks), so neither leonardo nor leonardo-repl can come to name the MCP server’s dependencies by accident.
The split cost no code change, which is the practical dividend of the layering rule: cli being a leaf that nothing imports is exactly what made it detachable. It also left the library free of any terminal dependency — the one thing that would have blocked a Scala.js cross-build.
Running off the JVM
The library and the REPL cross-build for Scala.js (the MCP server is a JVM process and does not), and their whole suites run on Node as well as the JVM: every library case except the one that needs real threads, and every REPL case except those that drive JLine or files. The port needed two platform-specific pieces in the library and four in the REPL; everything else is the same source.
| Platform-specific | Why |
|---|---|
| Parallel block dispatch | java.util.stream has no Scala.js counterpart, and a browser is single-threaded anyway |
Double rendering | Scala.js renders a Double the JavaScript way — 1 for 1.0, 0.00003 for 3.0E-5 |
| JLine read loop, highlighter | a terminal line editor has no meaning in a browser |
:save / :load storage | files on the JVM, localStorage in a browser — the same commands either way |
The interesting part is what did not need changing. Session — the entire REPL behaviour, including command parsing, display and session scripts — is untouched, because Session.execute, Session.script and Session.load were already pure string in / string out. The file system was the only JVM-bound part of :save, and it never lived inside Session.
Nothing Scala.js is published yet: the cross-build exists to prove the library runs in a browser and to keep that true, since CI runs the JavaScript suite on every push.
The browser front end
A third project, web, is the page itself. It is JS-only, publishes nothing, and is kept out of the root aggregate so that linking a bundle is never in the path of an ordinary library change; CI names it explicitly instead.
It is almost entirely not there, which is the point. Session.step already dispatches every command on both platforms, so the page is a text box, a transcript and a history ring. Only two things are genuinely browser-only: the drawing commands (plot, points, bode, nyquist, rlocus, hist, curve, arrows, polygon), which a terminal cannot honour, and the shareable link. A figure is data before it is a picture, so the same lines also render as an SVG image ahead of time (Session.figure), which is how the lessons show their figures.
The settings panel is the same argument again. It is generated from Session.settings — the (command, argument) pairs :save already writes — and a changed control issues the command a user would have typed, so the panel holds no state and there is nothing for it to disagree with. Typing latex on at the prompt moves the checkbox, because the fields are refreshed from the session after every line rather than tracked alongside it.
| Weight over the wire | |
|---|---|
| Leonardo, the whole CAS | 7.27 MB raw, 957 KB gzipped (measured 2026-11-01) |
Plotly (cartesian distribution, vendored) | 1.3 MB raw, 436 KB gzipped |
| MathLive (full build, with the math editor, vendored) | 845 KB raw, 228 KB gzipped |
| The KaTeX maths fonts | 254 KB, fetched only when a formula or the editor needs them |
About 1.6 MB on a first visit for a computer algebra system with interactive plotting and typeset output, then nothing: the files are cached, and a session never fetches another script. The CAS has doubled since the first measurement (3.46 MB raw, 475 KB gzipped) as the library grew; one download of that size is still no reason for module splitting or lazy loading, which would add a second request at the moment a user first types a command.
MathLive’s full build is vendored, because the page has a math editor: the <math-field> element and the conversion functions the typesetting uses come in one file (it replaced the render-only build, 111 KB gzipped, when the editor arrived). Its 232 KB of keyboard sounds are not shipped, by decision. It bundles no second CAS: @cortex-js/compute-engine is looked up on globalThis and its conversions simply decline when it is absent.
Plotting adopts no Scala dependency. Plotly’s input is plain JSON, so the facade is a string builder — pure, and therefore unit-tested without a browser. The one line of it that chose Plotly over Vega-Lite is scaleanchor: a Nyquist diagram, a pole-zero map or a two-element vector drawn as a point is geometry, and on unequal axes the unit circle becomes an ellipse. Vega-Lite has no aspect lock, and deriving one from the data range stops holding the moment the reader zooms — a confidently wrong picture rather than a refusal.
Nothing the user types leaves the tab: the CAS is in the bundle, sessions live in localStorage, and a shared link carries its session in the URL fragment, which browsers never transmit.
The diagram below is generated automatically from docs/structure.puml by running sbt puml (or sbt site which runs the full pipeline); sbt graphml writes the same diagram as GraphML for Gephi and for yEd, and a repository guard keeps both copies current.
Class and package diagram
Drag to pan · scroll, double-click, or use the corner controls to zoom · open the diagram in its own tab
Package guide
| Package | Role | Documentation |
|---|---|---|
core | _Expression trait, _Value marker, _Number, _Bool, _Complex, _Rational, _Surd, _Interval, _Truth, _Based, _Variable, _MatrixValue, Environment and its configurable work budgets — the foundation shared by every domain | Expressions & Evaluation |
scalar | AST nodes (Sum, Product, Power, functions, functionals) and all algorithms: derive, integrate, simplify, expand, normalize, compile, sample, series expansions, domain analysis, plus a data-driven rewrite-rule engine (Rewrite) backing the parameterised table of integrals (IntegralRules) | Expressions & Evaluation · Calculus |
matrix | _Matrix symbolic node + _MatrixOperation nodes, constructors, block matrices, the decompositions, expm, chol, the SVD and what reads off it (pinv, rank, cond, nullspace, orth), norm, dot, cross, trace, size, rationalize; dense _MatrixValue kernels live in core | Matrices |
equation | _Equation, _Comparison, _EqualityCheck relation nodes; solve (equations, inequalities, matrix unknowns) and solveSystem | Equations & Complex Numbers |
transform | Laplace, the two-sided and causal Fourier transforms, inverse Laplace, the one-sided z-transform and its inverse, and dft/idft/conv | Features |
ode | _ODE node; closed-form linear and separable tiers, linear systems by the matrix exponential, Runge–Kutta for the rest — vector systems certified by step doubling — and the public odeStep/odeSolve | Features |
logic | The five connectives over one Kleene/fuzzy rule table; simplification, CNF/DNF, truth tables, membership curves, defuzzification | Logic |
probability | Distributions as first-class values (the geometric, hypergeometric and F families included); pdf/cdf/prob/quantile; expect/variance by a linearity rule table; Bayes’ theorem over hypotheses and conjugate posteriors (bayes, posterior); seeded draws by inversion and PRBS (draw, prbs) | Features |
statistics | Descriptive and order statistics, regression by QR (ordinary, ridge, weighted), recursive least squares, inference (ttest, proptest, chisqtest, vartest, anova, confint), bincounts | Features |
domain | Renders the neutral domain analysis (domain, differentiable, singularities) into relation nodes | Features |
vector | grad/div/curl/laplacian/jacobian/hessian over an ordered coordinate tuple, in three coordinate systems | Calculus |
optimize | Stationary points by elimination with case splits and Gröbner bases, their classification, convexity from principal minors, Lagrange multipliers, the KKT conditions, and the certified numeric solvers: minimize, qp, lsqfit, nlp, and the exact lp | Optimization |
control | Transfer-function algebra, stability, the Routh table, time and frequency response, the root locus, state space, controllability and pole placement, discretisation, linearisation, ARX identification, discrete simulation, MPC prediction matrices, LQR and the Kalman filter | Control Systems |
latex | ToLatex(e) — an expression as math-mode LaTeX source, display only; nothing reads it back | Interactive REPL |
parser | Recursive-descent Parser (extends JavaTokenParsers); produces all AST node types; ReservedWords guard | Getting Started |
cli | Interactive Session (pure, IO-free core) + repl read loop; session scripts (:save/:load). Ships as the separate leonardo-repl artifact | Interactive REPL |
Key design decisions
Dual eval model — eval(env): Either[_Expression, _Value] is the single reduction point. Right means fully concrete; Left means one or more variables remain free. Every node type implements it; no special dispatch needed.
_ElementWise marker — nodes that are plain containers (matrix literals, matrix sums, transposes, equations) implement this trait. Algorithms such as derive, simplify, and expand use children/rebuild to distribute over them without domain-specific cases in the algorithm code.
Memoization — derive and simplify cache results in a bounded ConcurrentHashMap (see Memo.scala). This is the biggest win for simplifyFully’s fixpoint loop and for _DefIntegral’s numeric integration, which re-derives the same subexpressions hundreds of times per evaluation.
compile fast path — compile(e, v, env): Option[Double ⇒ Double] translates an expression into a JVM closure when all nodes are compilable. Used by _DefIntegral (adaptive Simpson) and sample; eliminates per-step AST allocation and environment lookup. compile(e, vars, env) and compileMatrix(m, vars, env) are the multi-variable forms over a positional Array[Double] (F_0058), built from the same table rather than a second one, so a function added to it reaches all three.
A new carrier type must earn its place — a domain gets a _Value or a wrapper of its own only when something must read a value as one. A vector field is an n×1 _Matrix; a transfer function is an ordinary Ratio; a state-space model is the same 1×4 row of matrices lu and qr already return; an inequality’s solution set is a _Comparison. The reason is that a carrier is a wall: simplify, derive, substitute, the exact tier and the parser all operate on expressions, so a type outside that set would have to be taught to each of them or be cut off from all of them. The price is paid in ergonomics — with no type to dispatch on, control must take its frequency variable as an explicit argument everywhere — and in documentation, which is why Control Systems opens by saying so.