Skip to content
Getting Started & Language · Compiler Architecture

IRs and Crate Layout

What weylc's four intermediate representations (HIR, SIR, KIR, TIR) hold and when each lowers to the next, how the 18 workspace crates are layered, the main cross-crate traits, and how Weyl talks to external software.

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 ​

LayerContentsMain typesLowers when
HIRThe source program after name resolution and type checkingHirModule, Item, Expr, TypeTableAlways; deterministic translation to SIR
SIRTranslation-invariant Hamiltonian templates plus a DAG of derivation stepsSirModel, TermTemplate, DeriveGraph, PassNodeA pass has fixed clusters, sectors and order; templates are instantiated into KIR
KIRFlat term streams: fixed header + prime-field coefficients + monomial bytesTermHeader, Stream<F>, KirOpRational coefficients have been recovered by CRT; TIR is generated
TIRNumerical kernels with no symbolic content: mat-vec, series coefficient tablesTirKernelInterpreted, 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:

rust
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:

rust
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.

rust
#[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 KK 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. KK 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:

rust
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).

LayerCratePurposePhase
0weyl-numRationals, big integers, 63-bit prime fields, CRT, Wang rational reconstructionP1
0weyl-syntaxLexer, recursive-descent parser, lossless rowan syntax treeP1
1weyl-canonicalGraded-algebra normal forms: symplectic Pauli strings (P1), fermions/bosons (P2)P1
1weyl-topoFinite groups, anyon data of quantum doubles D(G)D(G), Lagrangian subgroups, condensationP1
2weyl-typesType checking, operator types, error tagsP1
3weyl-hirHIR / SIR definitions and HIR → SIR translationP1
4weyl-casKIR term streams, sort-merge, disk spill, finite-field reconstructionP1
4weyl-seriesKnetter–Uhrig pCUT, cluster expansion, truncated series, dlog-PadéP1
4weyl-egraphEquality saturation on SIR with egg / egglogP1
5weyl-tirTIR definitions and reference interpreterP1
5weyl-oracleIndependent oracles: stabilizer-reduced ED, exact free fermions, residual fitsP1
5weyl-jit-clifTIR → Cranelift JITP1
5weyl-mlirTIR → MLIR, plus AOT compilationP3
5weyl-neural-rtNeural-potential runtime with confidence fallbacksP3
5weyl-ffiOutward interfaces: cxx, C ABI, PyO3 (all optional features)P2
6weyl-mcpMCP protocol, JSON Schema validation of actions, telemetry, replay logsP1
6weyl-leanTranslation of Weyl claims to Lean 4 goals, counterexample pre-checksP2
6weylcCompiler driver, Pass Manager, default scheduler, CLIP1

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:

rust
// 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.

Weyl v0.1 · MIT License