• Swift 6
  • macOS 13+
  • SwiftPM build plugin
  • Typestate · ~Copyable

State machines
the compiler enforces.

Describe a state machine in a few lines of .urkel. Urkel generates typestate Swift where every state is a type, every transition consuming, and calling one from the wrong state is a build error, not a runtime guard.

Checkout.urkelYou write
## A checkout flow.
machine Checkout: CheckoutContext

@states
  init  Cart
  state Paying
  final Receipt

@transitions
  Cart   -> pay(amount: Int) -> Paying
  Paying -> succeed          -> Receipt
  Paying -> fail             -> Cart
Checkout.swiftYou get
// The phase is part of the type, so each step only offers its own transitions.
func checkout(_ cart: consuming CheckoutMachine<CheckoutPhase.Cart>) async throws -> Int {
    let paying = try await cart.pay(amount: 4_200)   // Cart → Paying
    let receipt = try await paying.succeed()         // Paying → Receipt
    return receipt.withContext { $0.charged }        // read without consuming
}

try await cart.succeed()
// error: referencing instance method 'succeed()' on 'CheckoutMachine'
//   requires the types 'CheckoutPhase.Cart' and 'CheckoutPhase.Paying' be equivalent

let again = try await cart.pay(amount: 4_200)
// error: 'cart' consumed more than once

The errors are the Swift compiler's own, on the code Urkel generated for Checkout.urkel.

Why

An enum knows the state.
Only a type can forbid the transition.

With an enum and a few booleans, the compiler has no idea which calls are legal now. Every method guards at run time, and a forgotten guard is a bug you find in production. Urkel moves that check into the type system, inspired by Alex Ozun's typestate in Swift.

Runtime guards

Legal or not, every call compiles. The state can change between the check and the work.

var state: State = .cart
func succeed() async throws {
    guard state == .paying else { throw CheckoutError.invalidState }
    state = .receipt
}

Typestate with Urkel

succeed() exists only on CheckoutMachine<CheckoutPhase.Paying>, and consuming means the old state is gone once you leave it.

// Generated for Checkout.urkel (bodies omitted)
extension CheckoutMachine where Phase == CheckoutPhase.Paying {
    public consuming func succeed() async throws
        -> CheckoutMachine<CheckoutPhase.Receipt>
    public consuming func fail() async throws
        -> CheckoutMachine<CheckoutPhase.Cart>
}

How it works

Write the machine. Build. Implement the effects.

Urkel generates the interface and the rules; you keep the behaviour in plain closures over your own types.

Describe it in .urkel

States, typed events, guards, actions, timers and sub-machines, in a format that reads like the diagram on the whiteboard. Bring your own types: pay(amount: Int), state(userId: String) Authenticated.

Build

The UrkelPlugin build-tool plugin compiles every .urkel file in the target on each build. The generated Swift is parsed back with SwiftParser before it is written, so syntax errors never reach your build.

Inject the side effects

Each transition is a @Sendable closure on a generated runtime, wrapped in a swift-dependencies client with testValue and previewValue ready for tests and previews.

Features

A small language for real machines.

The 24 machines in Examples/Showcase cover every construct: Bluetooth peripherals, media players, game AI, checkouts and login flows.

Typestate, move-only

Machines are generic over a phantom Phase, ~Copyable and Sendable. Transitions are consuming, so a state can be neither duplicated nor reused.

Guards, actions, hooks

[isValid] / [else] branches return a combined state enum to match on; / track actions and @entry / @exit hooks run around each transition.

Timers and eventless moves

after(30s) becomes a cancellable startTimer(onFire:); always becomes an autoTransition(). Internal -*> handlers run in place without leaving the state.

Hierarchy and composition

Compound states with @history, state-carried data, @import sub-machines forked with => Sub.init, and @on Sub::State reactions to them.

Plugins and a CLI

A build-tool plugin, an urkel-generate command plugin for checked-in output, and urkel generate | watch | validate | paths | test-stubs | visualize.

Diagnostics, diagrams, templates

Validation reports unknown states, duplicate or missing initial states and unreachable states. Export Mermaid or an interactive HTML visualiser, or emit Kotlin and anything else through Mustache templates.

Code tour

From text to types.

What the compiler generates for Checkout.urkel, and the same pipeline as a library.

Every state becomes an empty enum: a phantom type with no runtime cost. The machine is generic over it, move-only, and carries your context.

// Generated for Checkout.urkel (initializer and method bodies omitted)
public enum CheckoutPhase {
    /// The initial phase.
    public enum Cart {}
    public enum Paying {}
    /// A terminal phase — no further transitions.
    public enum Receipt {}
}

public struct CheckoutMachine<Phase>: ~Copyable, Sendable {
    fileprivate let _context: CheckoutContext
    fileprivate let _payInt: @Sendable (CheckoutContext, Int) async throws -> CheckoutContext
    fileprivate let _succeed: @Sendable (CheckoutContext) async throws -> CheckoutContext
    fileprivate let _fail: @Sendable (CheckoutContext) async throws -> CheckoutContext

    /// Read-only access to the context without consuming the machine.
    public borrowing func withContext<R>(_ body: (borrowing CheckoutContext) throws -> R) rethrows -> R
}

Fast enough to forget

Compiling a machine costs about a millisecond.

The build plugin runs on every build, so the compiler is benchmarked with package-benchmark on the showcase machines and on a synthetic 200-state machine.

1.2 msper showcase machine: parse, validate and emit (28 ms for all 24)
0.76 sto emit a 200-state, 1,000-transition machine, down from 260 s
3.5×faster end to end on the showcase than 0.3.0
70%of emission is SwiftParser proving the output is valid Swift

p50 wall clock, release build, Apple silicon. Method and full table: docs/performance.md.

Install

Add the package, attach the plugin.

Package.swift
dependencies: [
    .package(url: "https://github.com/mackoj/urkel.git", from: "0.3.0"),
],
targets: [
    .target(
        name: "Checkout",
        dependencies: [.product(name: "Dependencies", package: "swift-dependencies")],
        plugins: [.plugin(name: "UrkelPlugin", package: "urkel")]
    ),
]
Terminal
swift package plugin --allow-writing-to-package-directory urkel-generate
swift run UrkelCLI validate Sources/Checkout/Checkout.urkel
  • Swift 6.1 tools (Xcode 16.3 or later), macOS 13 or later.
  • Drop .urkel files into the target; the build plugin generates the machine, a runtime builder and a swift-dependencies client next to your code. The generated files import Dependencies, so the target depends on swift-dependencies.
  • Prefer checked-in output? Run the urkel-generate command plugin instead of the build plugin.
  • Configure output paths, imports or a Mustache template per directory with urkel-config.json.
  • Only need the compiler? Depend on UrkelParser, UrkelValidation or UrkelEmitterSwift alone.