- 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.
## 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
// 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
}Transitions live in constrained extensions, one per source state. Each consumes the machine, runs your closure on the context, and returns the machine in its next phase.
extension CheckoutMachine where Phase == CheckoutPhase.Cart {
/// Transitions from `Cart` to `Paying`.
public consuming func pay(amount: Int) async throws -> CheckoutMachine<CheckoutPhase.Paying> {
let next = try await _payInt(_context, amount)
return CheckoutMachine<CheckoutPhase.Paying>(
_context: next,
_payInt: _payInt,
_succeed: _succeed,
_fail: _fail
)
}
}
extension CheckoutMachine where Phase == CheckoutPhase.Paying {
public consuming func succeed() async throws -> CheckoutMachine<CheckoutPhase.Receipt> { … }
public consuming func fail() async throws -> CheckoutMachine<CheckoutPhase.Cart> { … }
}A keypad door lock from the showcase: guards with an [else] branch, entry and exit hooks, auto-lock timers, an in-place output event and a wildcard source.
machine DoorLock
@states
init Locked
state Unlocked
state Alarmed
final Disabled
@entry Unlocked / disengageBolt
@exit Unlocked / engageBolt
@entry Alarmed / soundAlarm
@transitions
Locked -> enterPin(pin: String) [pinCorrect] -> Unlocked
Locked -> enterPin(pin: String) [else] -> Alarmed
Unlocked -> lock -> Locked
Unlocked -> after(30s) -> Locked # auto-lock
Unlocked -*> lockState(isOpen: Bool) # output event
Alarmed -> reset(adminCode: String) -> Locked
* -> disable -> DisabledThe parser, validator and emitters are separate products, for tools and editors that want the pipeline without the plugin. Each takes text or values and returns values: no file system, no global state.
import UrkelParser
import UrkelValidation
import UrkelEmitterSwift
let file = try UrkelParser.parse(source) // String → UrkelFile (throws UrkelParseError)
for diagnostic in UrkelValidator.validate(file) { // [Diagnostic]
print(diagnostic.severity, diagnostic.message) // warning Unreachable state: Refunded
}
let swift = try SwiftSyntaxEmitter().emit(file: file) // checked with SwiftParser
print(swift.stateMachine, swift.client, swift.dependency)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.
p50 wall clock, release build, Apple silicon. Method and full table: docs/performance.md.
Install
Add the package, attach the plugin.
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")]
),
]
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
.urkelfiles into the target; the build plugin generates the machine, a runtime builder and a swift-dependencies client next to your code. The generated files importDependencies, so the target depends on swift-dependencies. - Prefer checked-in output? Run the
urkel-generatecommand 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,UrkelValidationorUrkelEmitterSwiftalone.