Kex is a small functional programming language with Ruby-like syntax, immutable data by default, UFCS method chains, type-directed make blocks, pattern matching, and explicit side-effect boundaries.
It is designed for code that reads like a scripting language without giving up typed records, sum types, pure functions, and predictable dispatch.
record Vector2D do
x : Float
y : Float
end
make Vector2D do
let +(other: This) -> This do
return Vector2D { x: @x + other.x, y: @y + other.y }
end
let *(factor: Float) -> This do
return Vector2D { x: @x * factor, y: @y * factor }
end
let near?(other: This) -> Bool do
(@x - other.x).abs < 0.01 && (@y - other.y).abs < 0.01
end
let to(String) -> String do
"(${@x}, ${@y})"
end
end
main do
let position = Vector2D { x: 3.0, y: 4.0 }
let velocity = Vector2D { x: 1.0, y: -0.5 }
let arrived = position + velocity * 2.0
IO.printLine("next position: ${arrived.to(String)}")
IO.printLine("arrived? ${arrived.near?(Vector2D { x: 5.0, y: 3.0 })}")
endKex tries to make the common path feel light:
- Functions compose through method syntax with UFCS:
items.filter(...).map(...).take(10). - Domain behavior lives near the type through
make, without classes or inheritance-heavy hierarchies.@fieldis shorthand forthis.fieldinside those blocks, and operators (+,==, ...) can be overloaded the same way. - Pattern matching works in function clauses,
matchexpressions, and receiver patterns. - Effects are visible: functions are pure unless marked
foul, andmainis the effect boundary. - Records, sum types, optional values, result values, ranges, streams, maps, and lists are built into the language model.
Uniform Function Call Syntax means value.f(arg) is equivalent to f(value, arg). You get fluent pipelines while keeping functions as plain functions.
let suspicious = requests
.filter { |req| req.path.startsWith?("/admin") }
.reject(&.authenticated?)
.map { |req| SecurityEvent.from(req) }
.take(20)
# Equivalent forms; pick whichever reads better locally.
requests.map(&normalize)
map(requests, &normalize)make blocks attach behavior to a type. The same method name — even an operator — can exist for different receiver types; dispatch is based on the receiver. Inside a make block, @field is shorthand for this.field.
record Vector2D do
x : Float
y : Float
static do
let Zero = Vector2D { x: 0.0, y: 0.0 }
let UnitX = Vector2D { x: 1.0, y: 0.0 }
end
end
record Vector3D do
x : Float
y : Float
z : Float
end
make Vector2D do
let +(other: This) -> This do
return Vector2D { x: @x + other.x, y: @y + other.y }
end
let *(factor: Float) -> This do
return Vector2D { x: @x * factor, y: @y * factor }
end
let dot(other: This) -> Float do
return @x * other.x + @y * other.y
end
let to(String) -> String do
return "(${@x}, ${@y})"
end
end
make Vector3D do
let +(other: This) -> This do
return Vector3D { x: @x + other.x, y: @y + other.y, z: @z + other.z }
end
let to(String) -> String do
return "(${@x}, ${@y}, ${@z})"
end
end
let unitX = Vector2D { x: 1.0, y: 0.0 }
let shot = (unitX * 2.0 + Vector2D { x: 0.0, y: 5.0 }).to(String)
# "(2.0, 5.0)" — `*` resolves through Vector2D::*, `+` through Vector2D::+Kex supports multi-clause functions, match expressions, destructuring, and @pattern to match on the receiver itself (separate from the @field shorthand shown above).
let fizzBuzz(n: Int) -> String do
match (n.modulo(3), n.modulo(5)) do
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
(_, _) -> n.to(String)
end
end
main do
(1..100)
.map(&fizzBuzz)
.each { |s| IO.printLine(s) }
endData modeling is direct: records for product types, type for unions, ? for optional values, and Result for fallible flows.
type ParseError = InvalidFormat(String) | Overflow | EmptyInput
let parseInt(s: String) -> Result<Int, ParseError> do
return Error(EmptyInput) if s.empty?
match Integer.parse(s) do
Ok(n) -> Ok(n)
Error(_) -> Error(InvalidFormat(s))
end
end
let parsePort(s: String) -> Result<Int, ParseError> do
let n = parseInt(s)?
return Error(Overflow) if n > 65535
return Ok(n)
end
foul loadConfig(path: String) -> Result<Config, AppError> do
let content = IO.readFile(path)?
let parsed = Config.parse(content)?
let port = parsePort(parsed.get("port"))?
return Ok(Config { port: port, host: parsed.get("host") })
endFunctions are pure unless marked foul. Pure code cannot call foul code, so side effects stay visible in the type of the program.
let compute(x: Int) = x * 2 + 1
foul readConfig(path: String) do
return File.read(path)
end
# Compile error: pure code cannot call foul code.
let bad(path: String) = readConfig(path)main is implicitly foul, so programs still have a natural place for IO.
Bindings are immutable by default. var opts into local mutation, and ! is reassignment sugar for methods that return an updated value — it rebinds the variable rather than mutating the underlying value in place, so aliases never see the change.
let frozen = [1, 2, 3]
# frozen.push!(4)
# runtime error: Cannot use '!' on immutable binding: frozen
var list = [1, 2, 3, 4, 5]
list.push!(6)
list.filter!(&.even?)
list.map! { |x| x * 10 }
# list is now [20, 40, 60]Ranges and streams share collection-style operations. Infinite streams stay lazy until consumed.
let naturals = Stream.Sequence(from: 0) { |n| n + 1 }
let primes = Stream.Sequence(from: 2) { |n| n + 1 }
.filter do |n|
(2..n - 1).all? { |d| n.modulo(d) != 0 }
end
let firstTenPrimes = primes.take(10)
let squaresOfMultiplesOfThree = (1..100)
.filter { |x| x.modulo(3) == 0 }
.map { |x| x * x }
.take(5)~ creates a partially applied function. Bound arguments fill left-to-right; _ marks an explicit open slot for a specific position. Chained (args) groups that fully saturate the function call it immediately — no extra wrapping.
let add(a, b) = a + b
let multiply(a, b) = a * b
let inc = ~add(1)
let double = ~multiply(2)
main do
let multipled = [1, 2, 3].map(~multiply(10))
IO.printLine(multipled)
let summed = (1..100).reduce(0, ~(+))
IO.printLine(summed)
endTraits declare required methods and can provide default implementations. Implementing types get the defaults for free.
trait Shape do
area : () -> Float
perimeter : () -> Float
let describe = "area=${this.area}, perimeter=${this.perimeter}"
end
record Circle do
radius : Float
end
record Rectangle do
width : Float
height : Float
end
make Circle, implement: Shape do
let area = Math.PI * @radius * @radius
let perimeter = 2.0 * Math.PI * @radius
end
make Rectangle, implement: Shape do
let area = @width * @height
let perimeter = 2.0 * (@width + @height)
let describe = "Rectangle ${@width}x${@height} (area=${this.area})" # override default
end
let shapes = [
Circle { radius: 5.0 },
Rectangle { width: 4.0, height: 6.0 },
]
shapes.each { |s| IO.printLine(s.describe) }
# area=78.53981633974483, perimeter=31.41592653589793
# Rectangle 4.0x6.0 (area=24.0)Kex is intended to make embedded DSLs feel native. Block arguments and do |x| ... end syntax let library code read like built-in language constructs.
let app = Http.routes do
get "/" do |req|
Response.ok("Welcome")
end
get "/users/:id" do |req|
match UserService.find(req.params.id) do
Just(user) -> Response.json(user)
None -> Response.notFound("user not found")
end
end
post "/users" do |req|
let user = UserService.create(req.body)
return Response.created(user) if user.ok?
return Response.error("error while creating user")
end
endRecords can define type-level constructors and constants in static do blocks. Constructors are capitalized lets that build an instance; constants are capitalized lets that just hold a value.
record Temperature do
celsius : Float
static do
let Celsius(value: Float) -> Temperature do
return Temperature { celsius: value }
end
let Fahrenheit(value: Float) -> Temperature do
return Temperature { celsius: (value - 32.0) * 5.0 / 9.0 }
end
let Freezing = Temperature { celsius: 0.0 }
end
end
make Temperature do
let to(String) -> String do
return "${@celsius}C"
end
end
let boiling = Temperature.Fahrenheit(212.0).to(String) # "100.0C"
let zero = Temperature.Freezing.to(String) # "0.0C"Build the compiler:
make buildRun a file:
make run F=examples/fizzbuzz.kex
build/kex examples/vectors_advanced.kexStart the REPL:
make replInstall the binary somewhere on your PATH:
make build
sudo make installBy default, make install copies the existing build/kex to /usr/local/bin/kex. It intentionally does not build as root. To install elsewhere:
make install PREFIX=$HOME/.localmake build # Build the compiler
make test # Run C++ unit tests
make spec # Run executable language specs
make parse # Parse all examples
make repl # Start the interactive REPL
make run F=file # Run a .kex file (type-checks first; use --no-check to skip)
make check F=file # Run semantic analysis only
make check-prelude # Type-check all src/prelude/*.kex files
make install # Install build/kex to /usr/local/bin/kex
make uninstall # Remove the installed binary
make clean # Remove build artifactsRequires CMake 3.20+ and a C++20 compiler. Readline is optional.
Good starting points:
examples/basics.kex- core syntaxexamples/traits.kex- Shape trait, required/default/overridden methods, multiple traitsexamples/vectors_advanced.kex- records, static constructors, UFCS methodsexamples/streams.kex- lazy ranges and streamsexamples/html_dsl.kex- DSL-oriented blocksexamples/error_handling.kex-Result, optional values, and?spec/type_dispatch.kex- dispatch throughmakeand receiver patternsspec/operator_overloading.kex- overloading+,*,==per receiver typespec/at_field_shorthand.kex-@field/@method(...)insidemakeblocksspec/mutating_calls.kex-var/letand!mutation semanticsspec/static_namespacing.kex- static constructors/constants stay namespaced under their typespec/math.kex- theMathmodule (Math.PI,Math.sqrt, trig, logs, ...)spec/testing_dsl.kex- thedescribe/it/asserttesting DSL itselfspec/json_parser.spec.kex- a spec forexamples/json_parser.kexusingdescribe/it/assert(see "Specs for example files" indocs/testing.md)
src/
lexer/ Tokenizer
parser/ Recursive descent parser
ast/ AST node types
semantic/ Scope resolution, purity checking, type checking
interpreter/ Tree-walk interpreter
prelude/ Kex-language specs for the built-in prelude (documented with RDoc-style comments)
main.cxx CLI entry point
examples/ Language showcase files
spec/ Runnable programs with expected output
tests/ C++ unit tests
docs/ Language reference documentation
grammar.ebnf Formal grammar specification
The compiler is written in C++20 with no external dependencies beyond the standard library and optional readline.
Source flows through:
Lexer -> Parser -> AST -> Analyzer -> Evaluator
The current evaluator is a tree-walk interpreter. There is no bytecode or IR yet.
Key implementation choices:
- AST nodes and runtime values use
std::variant. make Vec2 do let add(...) endregisters behavior asVec2::add.- UFCS resolves by checking the receiver type and looking up the mangled method name.
- Purity is enforced in a semantic pass before evaluation.
Working today:
- Lexer, parser, AST, semantic analysis, and tree-walk evaluation
- Records, sum types, functions, lambdas, pattern matching, destructuring
- Lists, maps, ranges, streams, strings, chars, numbers, optional values, result values
- UFCS,
makedispatch,toconversion convention, operator overloading @field/@method(...)shorthand forthisinsidemakeblocksfoulpurity boundaries, and localvarmutation enforced at runtime- Traits:
trait ... do end,make X implement: Trait do end,Comparable,Equatable - Currying and partial application with
~func(args),~(op), and_placeholders - Type checker active by default (
kex rungates on type checking;--no-checkto skip) - Stdlib type signatures, trait-constrained overload resolution, lambda type inference
- Arbitrary-precision
Integer(GMP-backed), numeric tower, match exhaustiveness checking - Rich stdlib:
uniq,partition,indexOf,flatMap,contains?,min/maxreturningOptional, char predicates (digit?,alpha?,space?), and more - REPL with optional readline support
Planned or incomplete:
- Bytecode VM or WASM codegen
- Full process/actor runtime
is?/astype introspection and explicit conversion- Namespace/import resolution beyond
usingblocks - Compiled metaprogramming beyond the parser/design sketch
MIT