Dependently-typed programming language for the BEAM virtual machine with one kernel-checked compiler pipeline and first-class OTP concurrency.
Cure compiles .cure source files to BEAM bytecode, enabling programs to run
natively on the Erlang VM alongside Erlang and Elixir code.
flowchart TD
A[.cure source] -->|Cure.Compiler.Lexer| B[Token stream]
B -->|Cure.Compiler.Parser| C[MetaAST — Metastatic 3-tuples]
C -->|Cure.Elab.Program| D[Checked dependent Core]
D -->|Cure.Core.Kernel| E[Validated and erased Core]
E -->|Cure.Elab.Emit| F[Erlang Abstract Forms]
F -->|Cure.Compiler.BeamWriter| G[BEAM bytecode]
Every pipeline stage emits structured events via Cure.Pipeline.Events,
backed by an Elixir Registry in PubSub mode. External tools (LSP, profilers,
IDE plugins) can subscribe to observe and react to compilation in real time.
Cure uses Metastatic's MetaAST 3-tuple format as its internal AST:
{type_atom, keyword_meta, children_or_value}This provides a well-defined, layered AST structure and interoperability with Metastatic's cross-language analysis tools.
- Dependent types -- types that depend on values, verified at compile time
- Indexed and dependent types -- GADT-style indexed families, dependent function results, implicit arguments, Sigma pairs, and kernel-checked propositional equality
- Records -- named product types with construction (
Point{x: 1, y: 2}), field access (p.x), and functional update (Point{p | x: new_x}); compile to BEAM maps; type-checked with per-field schemas - Typed FSM macros -- finite state machines as transparent standard-library
syntax with
compile-time verification (reachability, deadlock freedom, hard event validation),
dual-mode compilation (simple
gen_statemor callbackGenServer), Finitomata-inspired!/?event suffixes, inlineon_transitionhandlers, and lifecycle callbacks (on_enter,on_exit,on_failure,on_timer) - Typed actors and supervisors (v0.25.0, dependent macro surface in
v0.34) --
actor Nameandsup Nameexpand to checked lifted modules overStd.Otp, with compile-time checks on strategy / intensity / period / child-id uniqueness / restart / shutdown.Std.Actor,Std.Process, andStd.Supervisorexpose the runtime from Cure source - Applications and releases (v0.26.0) -- an
app Namecontainer declares the project's OTPApplicationcallback in Cure source withvsn,description,root,applications,env,on_start,on_stop, andon_phase :nameclauses. The compiler rejects projects with more than oneappcontainer and cross-checks its name and start phases against[application]inCure.toml. Thecure releasesubcommand (alsomix cure.release) packages the compiler output as a bootable BEAM release under_build/cure/rel/<name>/.Std.Appexposesensure_all_started,stop,env,env_int,env_atom,env_bool, andenv_stringfrom Cure source - Melquiades Operator (v0.25.0) --
pid <-| message(Unicode aliaspid ✉ message) is library-defined sugar forStd.Otp.tell; it checks the message against the indexed process handle and returnsEffect(Unit) - Indentation-structured -- no closing delimiters, visual layout determines scope
- Expression-oriented -- everything is an expression, the last expression in a block is its value
- BEAM-native -- compiles to standard BEAM bytecode, full OTP interoperability
- Interfaces and implementations -- ad-hoc polymorphism via
interface/implementation, explicitrequiresconstraints, canonical cross-module instance lookup, and structural derivation - Quantitative types -- erased, linear, affine, and unrestricted binders are checked by the dependent kernel before erasure
- Effects --
Effect(T)marks direct-style computations while keeping the effect former visible to dependent checking
mod MyApp.Math
use Std.Result
use Std.Option
type Sign = Positive | Negative | Zero
fn double(n: Int) -> Int = n + n
fn classify(x: Int) -> Sign =
match x
x when x > 0 -> Positive
x when x < 0 -> Negative
_ -> Zero
fn safe_divide(a: Int, b: Int) -> Result(Int, Atom) =
pickup
b == 0 -> Error(:division_by_zero)
else -> Ok(a / b)
# Compile a Cure source file to BEAM bytecode
mix cure.compile path/to/file.cure
# Compile all .cure files in a directory
mix cure.compile path/to/dir/ --output-dir _build/cure/project/ebincure repl drops you into a readline-grade loop backed by a raw-mode
line editor with live Cure syntax highlighting (via makeup_cure +
marcli), persistent history, incremental reverse search, Tab
completion, and a minimal vi mode:
cure(1)> fn add_ints(a: Int, b: Int) -> Int = a + b
defined add/2
cure(2)> :t add_ints(1, 2)
add_ints(1, 2) : Int
cure(3)> :bench Std.List.map([1, 2], fn (x) -> x + 1) 10000
n=10000 min=1 us avg=2 us p95=3 us max=42 us
Key bindings (emacs mode): Left/Right cursor, Up/Down for
history, Ctrl+A/Ctrl+E begin/end of line, Ctrl+W kill word,
Ctrl+K/Ctrl+U kill to end/start, Ctrl+R incremental history
search, Tab completion for meta-commands, file paths, loaded
modules and Cure keywords, Ctrl+L clear screen, Ctrl+C abort
line, Ctrl+D EOF. A minimal vi mode is available via :mode vi.
Meta-commands include :t, :effects, :load, :reload, :use,
:fmt, :holes, :env, :reset, :history, :search, :save,
:edit, :time, :bench, :ast, :theme, :mode, :color,
:clear, :help, :quit. See docs/REPL.md.
From Elixir code:
# Compile and load into the running VM
{:ok, module} = Cure.Compiler.compile_and_load(source)
module.my_function(args)
# Compile to disk
{:ok, module, warnings} = Cure.Compiler.compile_file("hello.cure")Cure-- root module, versionCure.Pipeline.Events-- PubSub event system (Registry-backed); every pipeline stage emits structured events that external tools can subscribe toCure.Compiler-- orchestrator: source -> lex -> parse -> elaborate -> validate/erase -> emit -> .beamCure.Compiler.Token-- token struct (type,value,line,col)Cure.Compiler.Lexer-- tokenizer for the full Cure syntax (keywords, operators, literals, indentation, string interpolation, FSM transitions)Cure.Compiler.Parser-- Pratt (precedence-climbing) parser producing MetaAST 3-tuples; indentation-aware, handles all expression and structural forms (functions, modules, records, types, protocols, implementations, imports, FSMs)Cure.Compiler.Parser.Precedence-- operator binding power tableCure.Compiler.ModuleIndexandCure.Compiler.ModuleInterface-- canonical module identities, dependency ownership, and immutable checked exports used by both authored and macro-generated referencesCure.Elab.Program-- module-level dependent elaboration, declaration grouping, import/interface loading, totality checks, and canonical definition identityCure.Elab.Elaborator-- bidirectional elaboration from surface MetaAST into dependentCure.CoretermsCure.Core.Kernel-- trusted validation boundary for the dependent CoreCure.Elab.EraseandCure.Elab.Emit-- erase proof/index arguments and lower the remaining Core program to Erlang abstract formsCure.Compiler.BeamWriter-- compiles Erlang abstract forms to BEAM bytecode via:compile.forms/2and writes.beamfilesCure.App.Resource-- emits the OTP<name>.appresource file into the output directory; threads metadata from the container and[application](vsn,applications,included_applications,registered,env,start_phases)Cure.Release-- builds a bootable BEAM release under_build/cure/rel/<name>/:.rel/start.boot/start.scriptassembly via:systools,sys.config/vm.argscopying, and the POSIXbin/<name>runner script (emits:releaseevents, surfacesE052/E055)Cure.Diagnostic.Registry,Cure.Diagnostic.Adapter, andCure.Diagnostic.Sink-- stable diagnostic ownership, conversion, and shared terminal/JSON/editor presentationCure.SMT.Process-- optional Z3 solver process management via Erlang port (used strictly for guard linting inCure.Elab.GuardLint, never in the trusted type-checking or proof-admission boundary)Mix.Tasks.Cure.Compile--mix cure.compiletask with formatted error outputMix.Tasks.Cure.CompileStdlib--mix cure.compile_stdlibcompiles the standard libraryMix.Tasks.Cure.Release--mix cure.releasebuilds a bootable BEAM release for the project'sappcontainer (v0.26.0)
The standard library is self-hosted -- written in Cure itself under lib/std/.
Compile it with mix cure.compile_stdlib.
Std.Core-- identity, composition, application, and other foundational combinators.OptionandResultnow live in their canonicalStd.OptionandStd.ResultmodulesStd.List(29 functions) -- length, is_empty, head, tail, last, cons, append, concat, reverse, map, filter, foldl, foldr, flat_map, zip_with, nth, at, set_at, take, drop, contains, find, any, all, uncons, split_first, sum, product, countStd.Math(18 functions) -- abs, sqrt, pow, log, log2, log10, ceil, floor, round, pi, max, min, clamp, sign, negate, is_even, is_odd, safe_divStd.String(34 functions) -- characters, from_characters, length, is_empty, concat, downcase, upcase, lowercased, uppercased, lowercased_character, uppercased_character, has_prefix, has_suffix, contains, first, last, prefix, suffix, drop_first, drop_last, trim, trim_leading, trim_trailing, split, split_on, from_int, from_float, from_atom, to_int, to_float, to_existing_atom, unsafe_to_atom, repeat, reverse (to_atomwas split intoto_existing_atomandunsafe_to_atom)Std.Tuple-- canonical flat tuple types and projections:first,second,swap, and n-ary accessors such asthirdStd.Optic-- statically typed lenses, affine traversals, and composable record-field optics; replaces the retiredStd.AccessStd.Show--Showinterface withshow/1dispatch for Int, Float, String, Bool, Atom;show_line/1convenienceStd.Equatable/Std.Comparable-- comparison interfaces backing==,!=,<,<=,>,>=, andcompareStd.Equivalent-- the inductive identity type and its kernel-checkedreflexive,sym,trans, andcongproofsStd.Io(8 functions) -- put_chars, println, print, int_to_string, float_to_string, atom_to_string, print_int, print_floatStd.System(8 functions) -- monotonic_time, system_time, timestamp_ms, timestamp_us, node, otp_version, cpu_count, exitStd.Actor(v0.25.0; rebuilt as a source macro in 0.34) -- defines theactorandbehaviormacros, which expand a declarative state/message/query spec into a checkedGenServerlifted module. The generated actor module itself, notStd.Actor, exposesstart,start_link,send,request, andstopStd.Process(6 functions) -- self, monitor, demonitor, link, unlink, is_alive. A compatibility facade overStd.Otp's indexed process handles and effects; new code should callStd.OtpdirectlyStd.Supervisor(v0.25.0; rebuilt as a source macro in 0.34) -- defines thesupmacro plus the restart/shutdown/strategy vocabulary (permanent,transient,temporary,brutal_shutdown,shutdown_after,one_for_one,one_for_all,rest_for_one, ...) and child-spec builders it expands intoStd.App(7 functions) -- ensure_all_started, stop, env, env_int, env_atom, env_bool, env_string. Effect-typed wrappers over:application, alongside theappmacro described on the Applications page
See the examples/ directory for sample Cure programs:
cure_calc/-- the getting-started project: a pure-Cure four-function calculator (recursiveExprADT, totalResult-returning evaluator,Std.Testsuite) built, run, and tested with thecureCLI alone. Walked through step by step indocs/GETTING_STARTED.mdhello.cure-- minimal module with a greeting functionmath.cure-- arithmetic, multi-clause factorial, conditionalstraffic_light.cure-- FSM definition with wildcard transitionslist_basics.cure-- list operations (map, filter, fold)result_handling.cure-- Result type error handling with and_thenpattern_guards.cure-- pattern matching, guards, match expressionsrecursion.cure-- recursive functions (factorial, fibonacci, reverse)protocols.cure-- interface definition, implementation, constraints, and dispatchffi.cure-- calling Erlang functions via @externadt.cure-- algebraic data types (Option, Result, Color)records.cure-- record definition, construction, field access, and functional update withTypeName{base | field: val}syntaxcure_turnstile/-- full example project: callback-mode FSM withon_transitionhandler, GenServer wrapper, and testscure_spline/-- full example project: natural cubic spline interpolation library in Cure (Thomas algorithm, per-segment cubic coefficients, evaluation/derivative/sampling), with an Elixir wrapper, a demo that renders an ASCII plot of a fitted sine, and a 25-case test suitecure_moneta/-- full example project: money and ledger library; multi-line ADT (Currency), domain aliases (PositiveAmount,Rate),Money{amount, currency, fractional_units}record (EUR/JPY/OMR-aware display),ShowandEquatableinterfaces, FX conversion via@externFFI, ledger mutations withResult-chaining, and a payment transaction FSM with hard (dispatch!), soft (retry?,cancel?), wildcard,on_timer,on_enter, andon_failurecallbackscure_colony/-- v0.25.0 supervision-tree demo: a worker actor, an echo actor, and asup Colonysupervisor wiring them under a:one_for_onestrategy with per-childrestartandshutdownoverrides. Exercisesactor,sup, and the Melquiades Operator end to endcure_forge/-- v0.26.0 fully-fledged application demo: a metrics actor, a logger actor, a queue actor, and a pool actor, wired under asup Forge.Roottree that is itself therootof anapp CureForgecontainer. Exercisesapp(withvsn,description,env,applications,on_start,on_stop, andon_phase :warm_cache), end-to-end message passing between actors through the Melquiades Operator<-|,Std.Appenvironment reads, andcure releasepackagingcure_motif/-- length-indexed step sequencer showcase: refinement types for every MIDI-domain primitive,Std.Vector-backedPattern(n)helpers with observable length claims, an@record-annotated callback-modeEnvelopeFSM,Cure.Temporalliveness proofs over the FSM graph, a three-actor supervision tree (Clock,Sequencer,Voice), a Melquiades-relay sequencer, anapp CureMotifcontainer, and an Elixir-side ASCII piano-roll renderer driven byCureMotif.Demo.run/0cure_exchange/-- a multi-currency exchange and escrow engine, as two sibling projects over the same seven-stateCreated -> FundsReserved -> (Cancelled | ExecutingSwap) -> (Completed | Refunding -> Refunded)graph:cure_exchange/cure/is pure Cure (Std.Fsm's transition-graph DSL, a hand-written total mirror usingFsmAction/Keep/Next,Result-typed ledger reserve/capture/release effects, and aStd.Otpprocess-identity demo), with its README documenting several toolchain edge cases found while building it;cure_exchange/elixir/puts only the FSM in Cure and drives it from an ElixirGenServer/DynamicSupervisorstack that owns the rate-lock timer, a simulated bank webhook, a settlement safety net, and the multi-step refund rollback
Compile and run:
cure compile examples/hello.cure
cure run examples/recursion.cure
cure check examples/protocols.cure- Getting Started -- from an empty directory to a
compiled, running, tested project: toolchain install, stdlib resolution,
Cure.toml, and thecheck/compile/run/testloop, usingexamples/cure_calcas the worked example - Tutorial -- fourteen short chapters across the language
- Language Specification -- syntax, keywords, operators, all constructs
- Macros --
macrocontainers, syntax rules and holes,becomes/computed by/syntax family,Std.Syntax, and self-provingexample/explain(v0.34.0) - Type System -- dependent bidirectional checking, indexed families, quantitative binders, conversion, and erasure
- Dependent Types -- indexed-family and proof programming guide
- Patterns -- structural patterns, guards, pins, and
pattern-valued
let - FFI --
@externforeign-function interface: module forms, effects, and lowering - FSM Guide -- FSM definition, compilation, runtime, verification
- Supervision -- typed actors,
supcontainers, the Melquiades Operator, links and monitors (v0.25.0) - Applications --
appcontainers,Cure.toml[application]/[release]sections, thecure releasesubcommand, andStd.App(v0.26.0) - Documentation Tooling --
cure docpipeline,[doc]config, placeholder interpolation, Makeup highlighting, REPL Markdown renderer (v0.29.0) - John --
mix cure.john,cure john, and the:johnREPL meta-command; collector / renderer / Marcli fallback reference (v0.30.0) - Standard Library -- API reference for the stdlib modules (every module now ships a
## Examplesblock)
mix deps.get
mix compile
mix testmix format
mix credo --strict
mix dialyzer
mix coverallsAll four run in CI (Dialyzer on Linux, where the PLT is built and cached).
mix coveralls enforces a minimum line-coverage floor configured in mix.exs.
The classic checker/code-generator has been removed. Every source file now
passes through the dependent elaborator, trusted Core validator, erasure, and
BEAM emitter. v0.36.0 delivers full Agda-style universe polymorphism
(removing the fixed three-level ceiling), interactive proof tooling and
extensible tactics (goal-state introspection across CLI/REPL/LSP/VS Code,
template and typed computed tactic macros, checked solvers including bounded
omega, explicit @simp admission, and automatic proof-admission totality),
a 238-module Agda soundness and executable certificate-replay development in
proof/, and broad editor/LSP/formatter upgrades across Neovim,
VS Code, Zed, and the web playground. See CHANGELOG.md for the
full inventory and blog/2026-11-26-cure-v0.36.0.md
for the release narrative. The 0.34 dependent-pipeline work (indexed families,
quantitative binders, interfaces and implementations, structural derivation,
canonical module interfaces, macro expansion, structured diagnostics) is
described in ROADMAP-0.34.md.
- v0.36.0 -- Universe Polymorphism, Interactive Tactics & Mechanised Verification:
end-to-end Agda-style universe polymorphism (
Cure.Core.UniverseLevel, unbounded cumulativity withUniverse.ceiling/0removed, surface universe syntax and use-site inference, universe-polymorphicEquivalent/List/Option/Sigmaacross 82 stdlib modules, grade-0 erasure enforcement, and Antigen polymorphic antibodies); Lean 4 parity Phases 1–4 (goal-state introspection inE110, REPL:goals, LSPcure/proofStateand hole-goal inlay hints, native VS Codecure.goalstree,Cure.Elab.Tacticmonad, templatetactic ... becomes ...and typed goal-inspecting computed tactics, checkedsearch/assumption/positivity/decide/omegasolvers,@simp/@lemma(:simp)admission, deterministicrewrite using h all, and automatic proof-admission totality); a 238-module Agda soundness and executable wire-format certificate-replay development; the linear resource pool example (examples/cure_pool); and unified editor/LSP/formatter tooling (mix cure.editors.sync, Neovim tree-sitter, LSP hover docs & byte framing). - v0.35.0 -- Mechanised Soundness, Tree-Sitter & Kernel Hardening: an
18-module Agda formalisation of the Core calculus proving Progress,
Preservation (zero postulates), and the fuel-indexed, coinductive, and
classical soundness theorems, plus confluence of
_⇝_; the written soundness argumentdocs/SOUNDNESS.md; thetree-sitter-curegrammar and the rebuiltzed-cureextension; the hole firewall (Emit.reject_holes/2,E014); enforced@total true(E013);E123for a missing module identity; and normalisedunwrap/unwrap_oracrossStd.Option/Std.Result. - v0.34.0 / v0.34.3 -- One Dependent Pipeline: the classic checker and code
generator were removed; every program elaborates to dependent Core, is
checked by the kernel, quantitatively erased, and emitted as BEAM through one
path. Added indexed families, quantitative binders, interfaces and
implementations, structural derivation, canonical module interfaces, macro
expansion, and structured diagnostics; the
fsm/actor/sup/appcontainers became transparent lifted modules. - v0.33.0: the dependent-core convergence line leading into 0.34 (kernel convergence, proof-ergonomics vocabulary, and the migration to the single pipeline).
- v0.32.0 -- Trust, Export, Recall, Narrate: proof-carrying packages
(
mix cure.verify), cross-language ADT export to proto3 (mix cure.export_types), REPL session snapshots (cure snap), and a narrative architecture generator (cure story). Error codesE065-E070. - v0.30.2 / v0.30.1:
johnpolish -- UTF-8 fixes formix cure.john, structurederl_crash.dumpsummaries, ASCII-only banners, dialyzer cleanups. - v0.30.0 -- John: a single panoramic diagnostic exposed via
mix cure.john,cure john, and the:johnREPL meta-command; reports Cure / BEAM / system / project / runtime state as Markdown-to-ANSI. - v0.29.0 -- Make Documentation Great:
cure docproduces an ExDoc-like two-pane site driven by[doc]inCure.toml; stdlib gains## Examplesblocks; website ships/stdlib; REPL gets a block-aware Markdown renderer; Vim and VS Code plugins re-aligned with the current grammar. - v0.28.0 -- Talk Back: parser error recovery (
E063), "did you mean?" suggestions,cure fmt --dry-run,cure blessSocratic type-error assistant,@record+cure replayFSM time-travel, Playground with live type-checking and sandboxed evaluator. Patches v0.28.1 / v0.28.2 promoted REPL top-level declarations (Cure.REPL.Session) into the checker env. - v0.27.0 -- See Your System Breathe: observability and verification:
Cure.OTel,cure top,cure trace,Cure.Temporal(LTL bounded model checker),Cure.Protocol(session-typed binary protocols), typed-hole suggestions; new stdlib modulesStd.Time,Std.Regex,Std.CRDT; OSC 8 clickable error paths; LiveView Playground. - v0.26.0 -- Applications and Releases:
appcontainer,[application]/[release]sections inCure.toml,cure releasepackaging,Std.App. Error codesE051-E055. - v0.25.0 -- Typed Supervision Trees: Melquiades Operator
<-|(alias✉), typedactorandsupcontainers compiling toGenServer/Supervisormodules,Std.Actor/Std.Process/Std.Supervisor. - v0.24.0 -- The REPL You Deserve: raw-mode line editor with live
Makeup-powered syntax highlighting, persistent history,
Ctrl+Rincremental search, Tab completion, minimal vi mode, Marcli-rendered:help. - v0.23.0 -- Packaging, Proof, and Polish: remote package registry
(
Cure.Project.Registry), Ed25519 signing, transparency log,cure publish,cure doctor,cure fix,cure test --cover,Std.Json,Std.Http, property shrinking. Error codesE038-E042. - v0.22.0 -- Loose Ends: multi-statement lambda bodies (brace and
endforms), binary comprehension generators,byte_sizerefinements on trailing binary segments, first-class FSM state struct. - v0.21.0 -- Through the Segments: Erlang-style binary destructuring
with exhaustiveness (
E031), multi-linetypeADTs, ADT function-arrow payloads, deepletdestructuring,@derive(Functor, Monoid, JSON), algebra formatter as default,Std.Access. - v0.20.0 -- The Shape of Things: plain
#comments as AST nodes, full bitstring segment grammar (<<x::utf8, rest::binary>>),Inspect.Algebra-style pretty printer, structural pattern refinement narrowing. - v0.19.0 -- Bring the Furniture:
proofcontainers,assert_type, record field defaults,@derive(Show, Eq, Ord), property-based testing, lazy iterator protocol, package-version resolver, mutual-recursion totality, multi-head cons patterns. - v0.18.0 -- Deep Destructuring: nested patterns across tuples, lists,
maps, records, and ADT constructors; pin operator
^x; repeated-variable equality guards; record field punning; nested-exhaustiveness analyser. - v0.17.0 -- Proofs & Polish: Toward Idris: dependent pairs / Pi types /
propositional equality, type-level normaliser, unification with implicit
args, typed holes, totality checker, path-sensitive refinement, REPL,
cure watch, LSP inlay hints / rename / semantic tokens,cure new,Cure.lock,cure bench, doctests, MIT license, VS Code extension scaffold. - v0.16.0 -- Finitomata-Inspired FSM Rewrite: dual-mode FSM compilation,
hard (
event!) / soft (event?) suffixes, lifecycle callbacks (on_enter,on_exit,on_failure,on_timer), introspection API. - v0.15.0 -- Developer Experience: public
Cure.quote/ printer API, effect system, HTML doc generator, formatter, first REPL,Std.Test. - v0.14.0 -- Real-World Readiness:
Cure.tomlpackage management (path deps), cross-module protocol registry,cure testwithStd.Test. - v0.13.0 -- Depth Over Breadth: dependent-type verification at call
sites, type-level arithmetic in return types, LSP code actions /
definition / incremental compile, experimental AST optimizer,
Std.Map/Std.Set/Std.Option/Std.Functor. - v0.12.0 -- The Complete Rewrite: rewrite from Erlang to Elixir, import resolution, dependent-type representation, typeclass derive, LSP symbols, Z3 model parser, FSM type-safety analysis, Levenshtein-based suggestions.
- v0.11.0 -- First Roadmap Complete: nine self-hosted stdlib modules, protocol/typeclass system, Z3 SMT integration with refinement types, guard refinement, type-directed optimizer, pattern-exhaustiveness checker, FSM runtime, LSP, CLI escript, MCP server.
- v0.10.0 -- Project Bootstrap: initial Elixir project, lexer with
indentation tracking, Pratt parser, BEAM codegen, type-system foundation,
FSM
gen_statemcompiler, CLI, CI, examples.
MIT. See the repository's LICENSE.