The symbolic part of weylc does not use LLVM IR or MLIR. The reason is concrete: those IRs are built from SSA values and instructions, while symbolic derivation deals in normal forms of non-commuting operators, series carrying truncation ideals, and tens of millions of intermediate terms at high orders. None of that maps naturally or efficiently onto a general-purpose IR. So the compiler defines four representations of its own, HIR → SIR → KIR → TIR, and only the last one (pure numerical kernels) is handed to Cranelift or MLIR.
Overview
| Layer | Contents | Main types | Lowers when |
|---|---|---|---|
| HIR | The source program after name resolution and type checking | HirModule, Item, Expr, TypeTable | Always; deterministic translation to SIR |
| SIR | Translation-invariant Hamiltonian templates plus a DAG of derivation steps | SirModel, TermTemplate, DeriveGraph, PassNode | A pass has fixed clusters, sectors and order; templates are instantiated into KIR |
| KIR | Flat term streams: fixed header + prime-field coefficients + monomial bytes | TermHeader, Stream<F>, KirOp | Rational coefficients have been recovered by CRT; TIR is generated |
| TIR | Numerical kernels with no symbolic content: mat-vec, series coefficient tables | TirKernel | Interpreted, or compiled by Cranelift JIT / MLIR AOT |
The oracle (weyl-oracle) does not go through SIR → KIR. It reads the original Hamiltonian from HIR, builds its own TirKernel::MatVec for exact diagonalization, and reports the result (Verdict, OracleDiag) to the Pass Manager. A bug in the expansion code therefore cannot appear on both the checked and the checking side.
HIR and SIR
HIR
HIR is the syntax tree after type checking and corresponds closely to the .weyl source. Indexed expressions such as l ∋ v or d_{i+1} stay symbolic and are not unrolled to concrete sites. Simplified definitions:
pub struct HirModule {
pub items: Arena<Item>,
pub exprs: Arena<Expr>,
pub types: TypeTable,
pub spans: SpanMap,
// plus an interner, symbol table, etc.
}
pub enum Item {
Units(UnitsDecl), Given(GivenDecl), Define(DefineDecl), Claim(ClaimDecl),
Check(CheckDecl), Require(RequireDecl), Expand(ExpandDecl), Solve(SolveDecl),
Estimate(EstimateDecl), Compare(CompareDecl), Theorem(TheoremDecl),
}
pub enum Expr {
Sum { binder: SmolStr, domain: DomainExpr, body: ExprId },
Prod { binder: SmolStr, domain: DomainExpr, body: ExprId },
Mul(ExprId, ExprId), Add(ExprId, ExprId), Scale(ScalarExpr, ExprId),
// plus commutators [A, B], adjoints A†, group actions g ▷ A, generators σˣ_l,
// references to defined quantities A_v, bra-kets, etc.
}TypeTable records, for every ExprId, the operator type (space, charge, hermiticity, grade, support), physical dimension, and error tag Err.
SIR
SIR writes the Hamiltonian as templates of the form "local operator in a unit cell + translation orbit" (TermTemplate) and compiles expand, estimate, compare and similar statements into a dataflow DAG (DeriveGraph). The Pass Manager, equality saturation with egg / egglog, and LLM scheduling all operate on this layer only:
pub struct TermTemplate {
pub name: SmolStr,
pub coeff: ParamPoly, // rational polynomial in J, x, κ₁, κ₂
pub local: LocalOp, // operator within a unit cell: (offset, sublattice, generator)
pub orbit: OrbitSpec, // translation group and region (bulk / Bot / Top)
pub tags: TermTags, // charge, hermiticity, part of H₀?, T_n selection
}
pub struct PassNode { pub pass: PassId, pub params: PassParams, pub out_err: Err, pub state: NodeState }KIR and TIR
KIR
The intermediate terms of high-order perturbation theory are handled in KIR. It follows FORM: terms are stored as contiguous flat records rather than pointer trees, sorting and collecting like terms work on bytes, and data spills to disk when memory runs out.
#[repr(C, align(8))]
pub struct TermHeader {
pub len: u32, // record length in bytes, including padding
pub mono_len: u16, // length of the monomial bytes
pub flags: u16, // one bit says whether the coefficient carries a factor i
}
// Record layout: [TermHeader 8B][coeff: [u64; K]][mono: mono_len B][pad to 8B]
pub enum KirOp {
Load(SourceRef), // instantiate a SIR template on a concrete cluster
Multiply(StreamId, StreamId), // multiply and normalize
Normalize(StreamId), // sort, collect like terms, drop zeros
Project(StreamId, Sector), // project to a quasiparticle-number / symmetry sector
Truncate(StreamId, Trunc), // drop terms in the truncation ideal
Apply(StreamId, StreamId), // act with operators on cluster states
Reconstruct(StreamId), // CRT + rational reconstruction to exact rationals
}Coefficients are computed in parallel over 63-bit prime fields (in Montgomery form) and recovered as rationals at the end by the Chinese remainder theorem and rational reconstruction, so numerators and denominators never blow up along the way. is at least 4 by default; the actual value comes from a bound on coefficient size estimated before the expansion runs.
TIR
TIR holds only numerical kernels, with no reference to symbolic structure:
pub enum TirKernel {
// matrix-free H·v for Lanczos
MatVec { basis: SectorBasis, terms: Vec<PauliTerm>, precision: Precision },
// univariate rational series coefficients with their error tag
SeriesTable { var: String, coeffs: Vec<Rational>, err: Err },
// multivariate version
MultiSeriesTable { vars: Vec<String>, terms: Vec<(Vec<u32>, Rational)>, err: Err },
}
// Precision is F64 or DoubleDouble (about 106 mantissa bits)weyl-tir includes a reference interpreter. weyl-jit-clif compiles MatVec to native code with Cranelift; weyl-mlir lowers kernels to MLIR and, for ahead-of-time builds, runs the external mlir-opt, mlir-translate and clang.
The 18 workspace crates
The workspace has 18 crates; weylc provides both a library and the executable, the rest are libraries. Dependencies may only point from a higher layer to a lower one. cargo xtask check-layers checks this from cargo metadata, and allows only a few explicitly listed edges within a layer (e.g. weyl-series → weyl-cas).
| Layer | Crate | Purpose | Phase |
|---|---|---|---|
| 0 | weyl-num | Rationals, big integers, 63-bit prime fields, CRT, Wang rational reconstruction | P1 |
| 0 | weyl-syntax | Lexer, recursive-descent parser, lossless rowan syntax tree | P1 |
| 1 | weyl-canonical | Graded-algebra normal forms: symplectic Pauli strings (P1), fermions/bosons (P2) | P1 |
| 1 | weyl-topo | Finite groups, anyon data of quantum doubles , Lagrangian subgroups, condensation | P1 |
| 2 | weyl-types | Type checking, operator types, error tags | P1 |
| 3 | weyl-hir | HIR / SIR definitions and HIR → SIR translation | P1 |
| 4 | weyl-cas | KIR term streams, sort-merge, disk spill, finite-field reconstruction | P1 |
| 4 | weyl-series | Knetter–Uhrig pCUT, cluster expansion, truncated series, dlog-Padé | P1 |
| 4 | weyl-egraph | Equality saturation on SIR with egg / egglog | P1 |
| 5 | weyl-tir | TIR definitions and reference interpreter | P1 |
| 5 | weyl-oracle | Independent oracles: stabilizer-reduced ED, exact free fermions, residual fits | P1 |
| 5 | weyl-jit-clif | TIR → Cranelift JIT | P1 |
| 5 | weyl-mlir | TIR → MLIR, plus AOT compilation | P3 |
| 5 | weyl-neural-rt | Neural-potential runtime with confidence fallbacks | P3 |
| 5 | weyl-ffi | Outward interfaces: cxx, C ABI, PyO3 (all optional features) | P2 |
| 6 | weyl-mcp | MCP protocol, JSON Schema validation of actions, telemetry, replay logs | P1 |
| 6 | weyl-lean | Translation of Weyl claims to Lean 4 goals, counterexample pre-checks | P2 |
| 6 | weylc | Compiler driver, Pass Manager, default scheduler, CLI | P1 |
The driver and Pass Manager of weylc live in its library; main.rs only dispatches subcommands (check, fmt, dump-ir, explain, run, mcp, replay, export-ed, theorem, diagram, sched-eval). The MCP server is started with weylc mcp, and integration tests call the driver library directly.
Main cross-crate traits
These traits define the boundaries between modules, so implementations can be swapped and property-tested:
// weyl-num: coefficient fields
pub trait Field: Copy + Eq + Hash + Add<Output = Self> + Sub<Output = Self>
+ Mul<Output = Self> + Neg<Output = Self> {
fn zero() -> Self; fn one() -> Self; fn inv(self) -> Option<Self>;
}
// weyl-canonical: non-commutative graded algebras
pub trait GradedAlgebra {
type Word: AsRef<[u8]> + Ord + Hash; // byte order is the monomial order
type Phase: Copy; // Z₄ phase for Pauli, ±1 for fermions
fn grade(w: &Self::Word) -> Grade;
fn mul(a: &Self::Word, b: &Self::Word, out: &mut WordBuf) -> Self::Phase;
fn commutes(a: &Self::Word, b: &Self::Word) -> bool;
fn adjoint(w: &Self::Word, out: &mut WordBuf) -> Self::Phase;
}
// weyl-cas: the write side of a term stream
pub trait TermSink<F: Field> {
fn push(&mut self, coeff: &[F], mono: &[u8]);
fn push_flagged(&mut self, coeff: &[F], mono: &[u8], imaginary: bool);
fn finish(self) -> Stream<F> where Self: Sized;
}
// weyl-series: perturbative expansions
pub trait Expansion {
fn prepare(&mut self, model: &SirModel, opts: &ExpandOpts) -> Result<ExpansionPlan, Diagnostic>;
fn coefficients(&self, order: u32) -> &CoeffTable;
fn evaluate_on_cluster<F: Field>(&self, c: &Cluster, obs: Observable, sink: &mut dyn TermSink<F>);
}
// weyl-oracle: oracles
pub trait Oracle {
fn name(&self) -> &'static str;
fn applicable(&self, claim: &Claim) -> bool;
fn check(&self, claim: &Claim, budget: &Budget) -> Verdict;
}
// weylc: passes. Params is the only thing a scheduler (including an LLM) can set
pub trait Pass {
const NAME: &'static str;
type Params: Serialize + DeserializeOwned + JsonSchema;
fn run(&self, node: &mut PassNode, cx: &mut PassCx, p: &Self::Params) -> PassOutcome;
}Working with external software
The compiler itself is written entirely in Rust, and external physics software is integrated in a strict order of preference. The default route is to generate code or data files—exporting ITensor or TeNPy scripts, HDF5 or JSON coefficient tables, or SDP inputs from TIR—and execute them in a separate process, which also avoids linking GPL or commercially licensed libraries such as FORM, GAP, or Symbolica. When direct linking is warranted, C and Fortran libraries such as LAPACK and ARPACK are wrapped through -sys bindings generated by bindgen, while Python interoperability is handled by building weyl-ffi as a cdylib that exposes a weyl Python package through PyO3. Only when no C ABI exists (as with ITensor C++, Eigen, or a custom MLIR dialect) does Weyl resort to in-process C++ bindings via cxx, exposing narrow handles and converting C++ exceptions into Result values at the boundary; values returned by external libraries are never tagged Exact.