Open-Source Wikis

/

Zig

/

Systems

/

Compiler

ziglang/zig

Compiler

Active contributors: andrewrk, mlugg, jacobly, vexu, jakub-konka

Purpose

The "compiler" here is the core of src/: the pipeline that takes a Zig module, runs semantic analysis with comptime evaluation, and produces analyzed IR ready for a backend. This page covers the orchestrator (Compilation), the module graph (Zcu), the analyzer (Sema), the IRs (ZIR/AIR), and the interned tables (InternPool).

Directory layout

src/
├── main.zig                       # CLI dispatch (~350 KB)
├── Compilation.zig                # pipeline orchestrator (~344 KB)
├── Compilation/                   # internal helpers
├── Zcu.zig                        # module graph, error rendering (~212 KB)
├── Zcu/                           # support files
├── Sema.zig                       # comptime + type checking (~1.6 MB)
├── Sema/
│   ├── arith.zig                  # arithmetic
│   ├── bitcast.zig                # bitcast lowering
│   ├── comptime_ptr_access.zig    # comptime pointer reads/writes
│   └── LowerZon.zig               # ZON value lowering
├── Air.zig                        # Analyzed IR (~104 KB)
├── Air/                           # AIR helpers
├── InternPool.zig                 # interned types/values/strings (~513 KB)
├── Type.zig                       # type model (~165 KB)
├── Value.zig                      # value model (~135 KB)
├── mutable_value.zig              # comptime mutable values
├── Package.zig                    # package model (~7.5 KB)
├── Package/                       # package fetch/manifest
├── codegen.zig                    # backend dispatch
├── codegen/                       # per-target backends
├── link.zig                       # linker dispatch
├── link/                          # per-format linkers
├── target.zig                     # target tables (~28 KB)
├── crash_report.zig               # custom panic handler
├── tracy.zig                      # Tracy integration
├── dev.zig                        # build-mode "subset of features" knobs
├── IncrementalDebugServer.zig     # incremental compile debug server
├── fmt.zig                        # zig fmt
├── introspect.zig                 # path discovery
├── print_zir.zig                  # ZIR pretty-printer
├── print_value.zig                # Value pretty-printer
├── print_targets.zig              # zig targets
├── print_env.zig                  # zig env
├── register_manager.zig           # shared register allocator (~28 KB)
└── ...

Key abstractions

Type / module File Description
Compilation src/Compilation.zig Owns the thread pool, queues, cache, and lifetime of one compilation.
Zcu src/Zcu.zig Zig Compilation Unit: the analyzed-decl graph for the whole compilation.
Sema src/Sema.zig Walks ZIR, evaluates comptime, emits AIR.
Air src/Air.zig Analyzed IR — linear list of typed instructions.
Zir lib/std/zig/Zir.zig Zig IR — flat untyped IR per file.
InternPool src/InternPool.zig Interned types, values, strings; canonical identity for equality.
Type src/Type.zig Type model used by Sema and codegen.
Value src/Value.zig Compile-time value model.
Package src/Package.zig Source-package descriptor; consumed by Compilation.
crash_report src/crash_report.zig Replaces the default panic handler with one that prints a Zig stack trace plus the active analysis context.

How it works

graph TD
  CLI["main.zig parseArgs"] --> Cfg["Compilation.Config"]
  Cfg --> Comp["Compilation.create"]
  Comp --> Pool["ThreadPool"]
  Comp --> Cache["Build/Cache"]
  Comp --> Pkgs["Package.zig (root + deps)"]
  Pkgs --> Zcu["Zcu (decls + dep graph)"]
  Zcu --> AstGen["AstGen (per file → ZIR)"]
  AstGen --> SemaQ["Sema work queue"]
  SemaQ --> Sema["Sema.zig analyzeBody"]
  Sema --> InternPool
  Sema --> AIR["Air per analyzed function"]
  AIR --> CG["codegen dispatch"]
  CG -->|LLVM| LLVM["codegen/llvm.zig"]
  CG -->|self-hosted| HW["codegen/<arch>/CodeGen.zig"]
  CG -->|C| Cb["codegen/c.zig"]
  LLVM --> Link["link.zig"]
  HW --> Link
  Cb --> Link

Stages inside Compilation

  1. Config and package resolution. Compilation.create builds a Config from CLI flags, then resolves the root Package and its dependencies (src/Package/).
  2. AstGen. Each Zig file is parsed (std.zig.Parse) and lowered to ZIR (std.zig.AstGen). ZIR is cached on disk.
  3. Decl analysis. Zcu enumerates top-level decls; Sema analyzes them on demand. Each decl carries a dependency set used to invalidate it on edits.
  4. Codegen. Once a function's AIR is ready, Compilation enqueues codegen for it; the chosen backend (src/codegen/* or LLVM) writes per-decl artifacts.
  5. Link. The selected linker (src/link/*) merges artifacts into the final output.

Sema in one paragraph

Sema.zig is the only place comptime runs. It owns a working Sema value per analyzed function/decl with the current ZIR slice, the type/value stack, and access to InternPool. AIR is emitted as it goes. The largest blocks of code in the file handle: function bodies (calls, control flow), type construction (@Type, @typeInfo), arithmetic (Sema/arith.zig), bitcast (Sema/bitcast.zig), and pointer arithmetic with comptime memory (Sema/comptime_ptr_access.zig). ZON values are lowered in Sema/LowerZon.zig.

InternPool

InternPool is the canonical identity table for types, values, and strings. Anything that needs equality goes through it. The pool is split into typed sub-pools (Index.Tag); the encoding is dense to keep peak memory low for large compilations.

Incremental compilation

Compilation is incremental by construction:

  • ZIR is cached per file.
  • Sema-results are cached per decl, with explicit dependency sets.
  • Edits flow in via lib/std/Build/Watch.zig or the IncrementalDebugServer (src/IncrementalDebugServer.zig).
  • Only invalidated decls are re-analyzed and re-codegen'd.

tools/incr-check.zig is the fixture-driven test harness for this path.

Integration points

  • Frontend. Calls std.zig.Parse and std.zig.AstGen from lib/std/zig/. See Frontend.
  • Backends. src/codegen.zig dispatches to src/codegen/* or src/codegen/llvm.zig. See Code generation backends.
  • Linkers. src/link.zig owns a link.File; per-format details in src/link/*. See Linkers.
  • Build system. lib/std/Build constructs Compilation.Config indirectly via the build runner. See Build system.
  • Standard library. Compilation uses std.Thread.Pool, std.Build.Cache, std.fs, etc.

Entry points for modification

  • New compile error. Add the diagnostic in the relevant Sema site and a test under test/cases/compile_errors/.
  • New AIR instruction. Add it to src/Air.zig, lower from Sema, and handle it in every backend (src/codegen/*).
  • New comptime builtin. Edit lib/std/zig/BuiltinFn.zig (the table), lib/std/zig/AstGen.zig (lowering to ZIR), and src/Sema.zig (analysis).
  • Watch-mode change. Look at lib/std/Build/Watch.zig and src/IncrementalDebugServer.zig. Use tools/incr-check.zig to add a regression test.

Key source files

File Purpose
src/main.zig Top-level CLI; constructs Compilation.
src/Compilation.zig The pipeline driver.
src/Zcu.zig Module graph.
src/Sema.zig Semantic analysis + comptime.
src/Sema/arith.zig Arithmetic.
src/Sema/bitcast.zig Bitcast.
src/Sema/comptime_ptr_access.zig Comptime pointer reads/writes.
src/Sema/LowerZon.zig ZON → Value.
src/Air.zig AIR encoding.
src/Type.zig Type model.
src/Value.zig Value model.
src/InternPool.zig Interned types/values/strings.
src/codegen.zig Backend dispatch.
src/link.zig Linker dispatch.
src/crash_report.zig Panic handler.
src/IncrementalDebugServer.zig Incremental debug server.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Compiler – Zig wiki | Factory