The Elo Language
Elo is a small expression language that compiles to JavaScript,Ruby, Python, and SQL. Write once, run anywhere.
Types
Elo has a simple type system with the following types. Use typeOf() to inspect types at runtime.
| Type | Description | Examples |
|---|---|---|
Int | Integer numbers | 42, -7, 0 |
Float | Floating-point numbers | 3.14, -0.5 |
Bool | Boolean values | true, false |
String | Text strings | 'hello', 'world' |
DateTime | Dates and timestamps | D2024-01-15, NOW, TODAY |
Duration | Time periods | P1D, PT2H30M, P1Y2M |
Interval | Time ranges | Interval({start: NOW, end: EOD}) |
Tuple | Key-value tuples | {name: 'Alice', age: 30} |
List | Ordered collections | [1, 2, 3], ['a', 'b'] |
Function | Lambda functions | fn( x ~> x * 2 ) |
Null | Null values | null |
Note: Use null for absent values. Use isNull() and isNotNull() to check for null, and the | operator to provide defaults: x | 'default'.
typeOf(42) == 'Int' and typeOf(P1D) == 'Duration'
Use typeOf() to get the type name as a string.
Note: typeOf inspects the value at run time, not the type the compiler worked out, and JavaScript has a single number type — so typeOf(2.0) is'Int' there and 'Float' on Ruby, Python and PostgreSQL. A Float that happens to be whole is the one case wheretypeOf is target-dependent; everything else agrees.
Literals
Elo supports numbers, booleans, strings, dates, and durations as first-class values.
Numbers
42 + 3.14
Numbers include integers and floating-point values.
Booleans
true and not false
true and false are boolean literals.
Strings
'hello world'
Strings use single quotes. Escape with backslash: 'it\'s working'.
Dates & Times
A date or a datetime is a zone-free wall clock: it means the time it spells, and the timezone of the machine running the compiled code never moves it. So the same expression answers the same thing on a server in Brussels, in a browser in Los Angeles and in PostgreSQL. NOW and TODAY are the exception, and read the host's local clock — that is what they are for.
D2025-12-25
ISO date format with D prefix.
TODAY < NOW
NOW is the current timestamp, TODAY is midnight today.
SOY <= TODAY and TODAY <= EOY
Start/End of Year (SOY/EOY), Quarter (SOQ/EOQ), Month (SOM/EOM), Week (SOW/EOW).
TODAY in BOT ... EOT
Beginning of Time (BOT) and End of Time (EOT) for open-ended ranges.
Durations
P1Y2M3D
1 year, 2 months, 3 days. Use P prefix (ISO 8601).
PT2H30M
2 hours and 30 minutes. Use PT for time-only durations.
D2026-01-31 + P1M
Years and months are calendar units, not fixed lengths: + P1M keeps the day-of-month and moves to the next month, clamping to its last day when that day does not exist — here D2026-02-28.
Data Paths
Type Selectors
Literal syntax (like 42 or 'hello') is shorthand for type selectors. Type selectors validate and convert values to specific types. They throw an error if parsing fails.
Int('123')Parses the string to the integer 123.
String(42) + ' items'
Converts a value to its string representation.
Date('2024-12-25')Parses ISO 8601 date string to a date value.
Data('{"name": "Alice"}').nameParses a JSON string and accesses a property.
Available: Int(), Float(), Bool(), String(), Null(), Date(), Datetime(), Duration(), Interval(), Data().
Note: Type selectors can be combined into Data Schemas for validating complex data structures.
Operators
Elo provides arithmetic, comparison, and logical operators.
Arithmetic
(10 + 5) * 2 - 8 / 4
Addition +, subtraction -, multiplication *, division /.
2 ^ 10 + 17 % 5
Power ^ and modulo % operators.
^ yields a Float, even on two whole numbers: 2 ^ -1 is 0.5 and nothing tells the compiler the exponent's sign, soround, floor, ceil and/ all treat a power as a Float. Ruby's **answers a Rational for a negative exponent, which Elo converts.
/ is real division and% is floored, on every target.7 / 2 is 3.5, never 3, so Ruby compiles it tofdiv and PostgreSQL casts to double precision— both truncate integer division natively. % takes the sign of the divisor, so -7 % 3 is 2 and7 % -3 is -2: x % n stays inside[0, n) for a positive n, which is what a cycle like day % 7 is written for. JavaScript and PostgreSQL take the sign of the dividend natively, so Elo corrects them.
TODAY + P7D
Add durations to dates. Subtract with -.
D2026-01-31 + (P1M - P10D)
A duration has a calendar part (years, months) and an exact part. * by a whole number and -between durations keep the calendar part, so this shifts to 28 February and then back ten days: D2026-02-18.
A month in a duration is a calendar month.D2026-03-01 + P1M is D2026-04-01 andD2026-03-01 + P1M * 2 is D2026-05-01, clamping to the last day of the target month where the day does not exist there. Multiplying by a fraction or dividing cannot keep it — half a calendar month is not a thing — so those collapse the duration to its nominal length, where a month is 30 days. The in… conversions read that nominal length too.
Comparison
10 > 5 and 3 <= 3
Use >, <, >=, <=, ==, !=.
Logical
(5 > 3 and 2 < 4) or not (1 == 2)
Combine conditions with and, or, and not.
Pipe Operator
' hello world ' |> trim |> upper
The pipe operator |> passes the left value as the first argument to the right function.
'42' |> padStart(5, '0')
Additional arguments follow the piped value.
Alternative Operator
indexOf('hello', 'x') | indexOf('hello', 'l') | -1The | operator returns the first non-null value.
Tuples
Elo tuples are collections of named values. They use JSON-like syntax with key-value pairs and compile to native structures in each target language.
{name: 'Alice', age: 30}Create a tuple with named attributes.
{budget: 1500}.budgetAccess attributes with dot notation.
let t = {x: 10, y: 20} in t.x + t.yBind a tuple to a variable and access its attributes.
Note: Tuples look like JavaScript objects but Elo uses relational terminology. In SQL, they compile to PostgreSQL JSONB using jsonb_build_object().
Lists
Elo lists are ordered sequences using JSON-like array syntax. Lists are heterogeneous and compile to native arrays.
[1, 2, 3]
Create a list with integer elements.
[1, 'two', true, null]
Lists can mix different types including null.
[[1, 2], [3, 4]]
Lists can contain other lists.
Note: Lists look like JavaScript arrays but Elo uses relational terminology. In SQL, they compile to PostgreSQL ARRAY[...] syntax.
SQL: a PostgreSQL array carries one element type and nests only rectangularly, so the two lists above —[1, 'two', true, null] and a nesting of uneven lengths like [[1], [2, 3]] — have no array to compile to. They run on JavaScript, Ruby and Python; the SQL compiler refuses them with a message naming what it found, rather than emitting something PostgreSQL rejects. [1, 1.5] and[D2024-01-01, NOW] are fine, because PostgreSQL unifies numbers and temporals exactly, and so isflat([[1], [2, 3]]), which concatenates the parts instead of building the nested list. For data that genuinely mixes types,Data carries it as jsonb, which has no such restriction.
Lambdas
Elo provides anonymous functions using lambdas:
- Lambdas:
fn( params ~> body )orx ~> body(sugar)
Lambda Expressions
fn( x ~> x * 2 )
A function that doubles its input.
fn( x, y ~> x + y )
Lambdas can take multiple parameters. Each one needs its own name — fn( x, x ~> x ) is refused, as a repeated let binding is.
[1, 2, 3] |> map(x ~> x * 2)
Single-param lambdas can omit fn(). Returns [2, 4, 6].
Invoking Lambdas
let double = fn( x ~> x * 2 ) in double(5)
Bind a lambda to a name, then call it. Returns 10.
Note: Lambdas compile to JavaScript, Ruby, and Python only. SQL does not support function expressions.
Local Variables
Use let ... in expressions to bind local variables.
let x = 10 in x * 2
Bind a value to a name, then use it in an expression.
let width = 5, height = 3 in width * height
Bind multiple variables separated by commas. Each one is in scope for the ones after it: let w = 5, area = w * 2 in area.
One binding per name. The same name twice in one let is refused, as it is for type definitions. A nested let may still shadow a name for its own body — let x = 1 in let x = 2 in x is 2.
A binding that shadows another may build on it: the value of a binding is read in the scope around it, solet x = 1 in let x = x + 1 in x is 2. What it shadows is untouched once the inner scope closes —let x = 1 in (let x = x + 1 in x) + x is 3.
Conditionals
Use if ... then ... else expressions to branch based on conditions.
if 5 > 3 then 'yes' else 'no'
Returns 'yes' if the condition is true, 'no' otherwise.
let x = 10 in if x > 5 then 'big' else 'small'
Combine conditionals with local variables.
Range Membership
Check if a value falls within a range using the in operator.
5 in 1..10
True if 5 >= 1 AND 5 <= 10. Both ends are included.
5 in 1...10
True if 5 >= 1 AND 5 < 10. End is excluded.
TODAY in SOY..EOY
Check if today is within the current year.
Data Selector
The Data() selector parses JSON strings into Elo values. This is useful when receiving data as text from external sources.
Data('{"name": "Alice", "age": 30}')Parses a JSON string into a tuple with name and age attributes.
Data('[1, 2, 3]')Parses a JSON string into a list.
Data('{"user": {"name": "Bob"}}').user.nameParse and immediately access nested properties.
Note: See Type Selectors for all available selectors. For validating and transforming complex JSON structures, see Data Schemas.
Input Data
Every Elo program has access to external input via the special _ variable. When an expression uses _, the compiled output becomes a function that takes input data as a parameter.
_ * 2
Doubles the input value.
_.price * _.quantity
Access attributes of an input tuple.
_.budget * 1.21
Apply VAT to a budget value from input.
Note: When using the CLI, use elo with JSON input: elo -e "_.x + _.y" -d '{"x": 1, "y": 2}'
Data Paths
Data paths are syntactic sugar for lists of strings and integers. They provide a concise way to describe locations within nested data structures.
.name
Equivalent to ['name'].
.user.address.city
Equivalent to ['user', 'address', 'city'].
.items.0.name
Equivalent to ['items', 0, 'name']. Integers access list elements.
Navigating Data
Use fetch() to retrieve values and patch() to update them immutably.
fetch({user: {name: 'Alice'}}, .user.name)Returns 'Alice'. Returns null if path doesn't exist.
fetch({a: 1, b: 2}, {x: .a, y: .b})Fetch multiple paths into a tuple. Returns {x: 1, y: 2}.
fetch({a: 1, b: 2}, [.a, .b])Fetch multiple paths into a list. Returns [1, 2].
patch({user: {name: 'Alice'}}, .user.name, 'Bob')Returns a new tuple with the value updated at the path.
Note: Since data paths are lists, typeOf(.name) returns 'List'. The stdlib uses "DataPath" as a conceptual name in function signatures.
Data Schemas
Data schemas let you validate and transform complex data structures like JSON. Define schemas using uppercase let bindings with type selectors, then apply them with the pipe operator.
Note: Data schemas compile to JavaScript, Ruby, and Python only. SQL is not supported.
Basic Types
These type selectors can be used as schema types: Int, Float, Bool, String, Null, Date, Datetime, Duration, Data. Use . (dot) for any value. Interval is a selector but not a schema type — build one with Interval({start: …, end: …}) instead.
let Job = { span: Duration, payload: Data }, job = _ |> Job in inDays(job.span)Duration parses an ISO 8601 string into a real duration; Data accepts any plain data and parses a JSON string.
let T = Int in '42' |> T
Coerces the string '42' to integer 42.
let T = . in 'anything' |> T
The dot . accepts any value unchanged.
Tuple Types
let Person = { name: String, age: Int } in
{ name: 'Alice', age: '30' } |> PersonValidates shape and coerces age from string to integer.
let T = { name: String, age :? Int } in
{ name: 'Bob' } |> TOptional attributes (with :?) can be missing. Missing fields are omitted from result.
let T = { name: String, ... } in
{ name: 'Eve', extra: 42 } |> TOpen tuples (...) allow extra attributes. They're ignored in output.
Array Types
let Numbers = [Int] in ['1', '2', '3'] |> Numbers
Coerces each element. Returns [1, 2, 3].
let People = [{ name: String }] in
[{ name: 'A' }, { name: 'B' }] |> PeopleValidates each element against the tuple type.
Union Types
let T = Int|String in 'hello' |> T
Tries alternatives left-to-right. Returns first successful match.
let T = [Int|String] in ['42', 'hello'] |> T
Returns [42, 'hello'] - numeric strings become integers.
Subtype Constraints
let Positive = Int(i | i > 0) in '42' |> Positive
Adds a predicate constraint. Throws if value is not positive.
let Adult = { age: Int(a | a >= 18) } in
{ age: '25' } |> AdultConstraints compose with tuple types.
let PosEven = Int(i | positive: i > 0, even: i % 2 == 0) in '42' |> PosEven
Multiple labeled constraints (Finitio-style). Label becomes error message.
let Adult = Int(a | 'must be 18 or older': a >= 18) in '25' |> Adult
Use string labels for human-readable error messages.
Named Type Aliases
let
Age = Int(a | a >= 0),
Person = { name: String, age: Age }
in { name: 'Alice', age: '30' } |> PersonDefine multiple types and reference them by name. Each refers to the ones before it, and there is no limit on how many a file defines.
One definition per name. The same name twice in one let — or twice in a prelude — is refused. A nested let may still redefine a name for its own body.
Type Prelude
A .elo file may open with type definitions, before any expression. They scope every expression below them, so a schema is declared once for the file instead of once per expression. A file that defines types and nothing else is a valid file — it simply compiles to nothing.
Age = Int(a | a >= 0)
Person = { name: String, age: Age }
{ name: 'Alice', age: '30' } |> PersonSugar for the let Age = …, Person = … in above. The comma between two definitions is optional, as is the in.
Data Formats
The CLI and playground support multiple input and output formats. Input data is parsed and made available as the _ variable. Results can be formatted for different use cases.
JSON Format
JSON is the default format. Values map directly to Elo types:
| JSON | Elo Type | Example |
|---|---|---|
number | Int or Float | 42, 3.14 |
string | String | "hello" |
boolean | Bool | true, false |
null | Null | null |
object | Tuple | {"name": "Alice"} |
array | List | [1, 2, 3] |
upper(_.name) + ' is ' + String(_.age)
Access fields from a JSON object.
CSV Format
CSV input is parsed as a list of tuples. The first row provides field names (headers), and subsequent rows become tuple values. All values are strings.
name,age Alice,30 Bob,25
_):[
{name: 'Alice', age: '30'},
{name: 'Bob', age: '25'}
]Since CSV values are strings, you can convert them manually:
_ |> map(r ~> {name: r.name, age: Int(r.age)})Convert age strings to integers field by field.
Better approach: Use data schemas to declare a schema. This validates structure and converts types in one step:
let Person = {name: String, age: Int}
in _ |> map(p ~> p |> Person)Define a schema once, apply it to each row.
Output Formats
Results can be formatted as:
- JSON — Standard JSON serialization (default)
- Elo — Elo code syntax (readable, can be copy-pasted)
- CSV — For lists of tuples (spreadsheet-compatible)
CLI Usage
# JSON input (default)
elo -e "_.x + _.y" -d '{"x": 1, "y": 2}'
# CSV input from file (format auto-detected from .csv extension)
elo -e "map(_, r ~> r.name)" -d @data.csv
# Explicit CSV format
elo -e "map(_, r ~> r.name)" -d @data.txt -f csv
# Output as CSV
elo -e "[{a: 1}, {a: 2}]" -o csv
# Output as Elo code
elo -e "{name: 'test'}" -o eloCustom Format Adapters
The format system is pluggable. You can provide custom adapters for formats like XLSX using libraries such as PapaParse or SheetJS. See the FormatAdapter interface in src/formats.ts.
Imports
An import brings in the types and the value another .elofile declares. It is written at the top of a program, before itstype prelude.
Note: there is nothing special about an imported file. A module is an ordinary program: its type prelude is what it exports as types, and its expression is what it exports as a value. A module that declares types and no expression exports no value.
A module
Age = Int(a | a >= 0)
Person = { name: String, age: Age }Exports the types Age and Person, and no value.
let double_fn = fn( x ~> x * 2 )
in { double: double_fn, one: 1 }Exports the names double and one: its value is an object, and each property is a name an importer may bring in.
Importing them
import { Person, Age } from './types'
import { double } from './reusable'
import './reusable' as r
People = [Person]
{ name: 'Alice', age: double(15) } |> PersonThe type prelude comes after the imports and may build on them. double is called by its own name; r.double(15) is the same function through the alias.
| Form | Brings in |
|---|---|
import { Name } from 'path' | An uppercase name is a type of the module's prelude; a lowercase one is a property of its value, called by its own name |
import 'path' as name | The module's value, reached by member access. Not its types — those come through the named form |
import, from and as are keywords only in an import, so a program using one as a name still means what it meant. An import written after the type prelude is refused: it declares what the whole source may use, so it comes first.
A path is relative to the file that wrote it — ./types,../shared/types — with .elo added. A bare'types' is refused, to keep that spelling free for a future package. Cycles are refused, naming the chain.
A name the module does not export is refused, naming the module and the line the import is written on — for a value as well as for a type, so a typo is not something you meet as anull later. A module whose expression is an object literal has its exports written down, which is how a module is normally written. One whose expression is anything else (_ |> T, an if, a member read) has keys that only exist at run time, so any name is accepted from it.
An imported type is expanded: the module's own type names are substituted into it, so you get that one type and nothing else of the module's becomes visible. A module's value is boundonce per program — however many names come from it, and however many other modules import it — and its _ is the importing program's input.
Imports are resolved at compile time, by inlining: the emitted code is one self-contained expression, so there is nothing to deploy beside it and nothing is read at runtime. The modules of a program are bound at its root, in dependency order, so a shared helper is emitted once and evaluated once however many paths reach it. An import inherits the portability of what it brings in: an imported type is a type definition and an imported function is a lambda, so the SQL target refuses either exactly as it refuses the construct written inline.
Assertions
Use assert() to validate conditions at runtime.
assert(2 + 2 == 4)
Throws an error if the condition is false.
indexOf('hello', 'x') | fail('character not found')Use fail(message) to throw an error with a custom message.
Guards
Guards validate conditions before returning a value. Use guard for preconditions and check for postconditions.
guard 5 > 0 in 5 * 2
Throws if condition is false, returns the body otherwise.
guard positive: 10 > 0 in 10
Labels become part of the error message on failure.
guard 10 > 0, 10 < 100 in 10
Separate multiple constraints with commas.
Let with Guard
let x = 5 guard x > 0 in x * 2
Sugar syntax: bind a value, then guard on it.
let x = 10 check x > 0 in x + 5
check is a synonym for guard, used for postconditions.
Pipe-Style Guards
5 |> guard(x | x > 0)
Creates a lambda that validates its input. Returns the value if valid.
Note: Guards compile to JavaScript, Ruby, and Python only. Use --strip-guards to remove guards in production builds.
Type Checking
Elo is dynamically typed: a type mismatch normally surfaces when the compiled code runs. Some of them do not get that far.
Refused by every compile
A call whose argument types are known and that matches no signature is wrong whatever the target, so it never compiles — on any target, with or without a flag. Same for an unknown name and a wrong argument count.
| Refused | Because |
|---|---|
foo(1) | no function by that name |
upper('a', 'b') | no signature takes two arguments |
startOfMonth('2026-03-15') | it takes a Date or a DateTime, not a String — write startOfMonth(Date('2026-03-15')) if that is what you meant |
'hello' - 5 | the same, for a name written as an operator |
Reported by --typecheck
eloc --typecheck is an optional pass that looks for the rest. It reports every problem it finds in one run and does not change the generated code — the same code is emitted with or without the flag.
| Reports | Example |
|---|---|
| Condition that is not a Bool | if 42 then 1 else 2 |
| A field a declared schema does not have | order.totl |
| A value that may be null, used as if it were not | k.a + 1 where a :? Int |
What it stays silent about
The checker only reports what it can justify. The input _is Any until it is coerced, so a call whose argument type is unknown is accepted without complaint: upper(_) is never reported, because _ may well be a String.
_ may be a Stringupper(_)
Declare your input
Declared types are what give the checker something to work with — and Elo already has them. A data schema is validated and coerced at runtime, so past the coercion the value provably has the declared shape, and the checker reads it. This is the idiomatic way to write Elo, and the way to get the most out of--typecheck:
let Order = { total: Int, customer: { name: String } }, order = _ |> Order in order.total * 2Inside the in body, the checker then reports:
| Reports | Because |
|---|---|
order.totl | the schema declares no such field — and this is the mistake that fails silently at runtime, giving null rather than an error |
upper(order.total) | total is declared Int |
order.customer.nam | a wrong path through a nested schema |
order.total.toFixed | an Int has no fields; use a stdlib function |
Lists carry their element type, so a lambda parameter is typed from the list it iterates — in let Order = { lines: [{ price: Int }] }, writing map(order.lines, fn(l ~> upper(l.price))) is reported. Unions are accepted for an operation every member supports and reported for one only some support, so { x: Int|Float }allows k.x + 1 while { x: Int|String }does not. Predicates inside asubtype constraint are checked too.
Optional fields are strict about null
:? is a statement that a field may be absent, so{ a :? Int } makes k.a anInt|Null and k.a + 1 is reported. Null is a bug factory, and this is the one place the checker insists. Any of the usual ways of handling it clears the report:
| Form | Reads as |
|---|---|
k.a | 0 | a fallback — the result of | is never null |
if isNull(k.a) then 0 else k.a + 1 | tested; the else branch knows |
if isNotNull(k.a) then k.a + 1 else 0 | tested; the then branch knows |
guard isNotNull(k.a) in k.a + 1 | guarded for everything it guards |
That knowledge is deliberately narrow: isNull andisNotNull applied to a path, &&-chained, plus the | operator. The checker does no boolean algebra, so isNotNull(a) || isNotNull(b) establishes nothing about either — you should not have to work out what the checker knows.
Requiring a declaration
--strict turns the silence about unknown types into a diagnostic, so upper(_) is reported until the input is declared. That makes it a contract rather than a lint: a host can require the idiomatic form and then promise that a saved formula will not fail at evaluation for type reasons. Functions that genuinely accept anything — isNull, typeOf,assert, fetch — stay quiet under it.
--input-type supplies the declaration from outside, for a host that already knows the shape of its data. It takes an Elo type expression, so there is one spelling of a schema:
eloc --input-type '{ total: Int }' -e "upper(_.total)"
# 1:1: error: No signature of upper accepts upper(Int). ...Compiling with the checker's types
--optimize hands what the checker found back to the code generator.
A declared type needs no flag: the compiler reads the declaration itself, so a field of a declared schema is emitted as the type it was declared to be.
eloc -t ruby -e "let T = { a: Int, b: Int }, k = _ |> T in k.a - k.b"
# ... k[:a] - k[:b]What the flag adds is what the checker works out and the compiler does not — chiefly a lambda parameter typed from the element type of a declared list, which is inference about a call rather than the shape of a declaration.
eloc -t js -e "let S = { xs: [Int] }, s = _ |> S in map(s.xs, fn( x ~> x * 2 ))"
# ... s.xs.map((x) => kMul(x, 2))
eloc -t js --optimize -e "let S = { xs: [Int] }, s = _ |> S in map(s.xs, fn( x ~> x * 2 ))"
# ... s.xs.map((x) => x * 2)The gain is a real operation instead of a function call per operation, and a smaller output, wherever a type is known. The benefit is proportional to how much the program declares: for an undeclared _ the checker knows no more than the compiler, so the flag changes nothing.
It refuses to compile from the types of a program it reported on. On a node carrying a diagnostic the recorded type is a guess rather than a conclusion, and emitting from it would turn a visible error into silently wrong code — so the output is the unannotated one and the run fails. The two emissions must otherwise agree, which is the property worth checking rather than the size: every line of the fixture corpus is executed both ways, on all four targets, on every test run.
What it does not see
The checker is a single pass over the expression, and these are its blind spots. None of them produce a wrong answer — the checker stays silent rather than guessing — but it is worth knowing where its silence means "fine" and where it means "cannot tell".
| Not seen | Why |
|---|---|
let f = fn(x ~> upper(x)) in f(1) | a function bound with let is checked once, not once per call site, so its parameters stay Any. Written inline, upper(1) is reported. |
upper(fetch(k, .a)) | data paths and fetch reach into data by a key computed at runtime, so the result is Any even when k is declared. |
| a union of more than a handful of members | the checker tries each member combination, and gives up past a small cap rather than doing exponential work. It widens to Any, so it never reports something wrong — it just stops reporting. |
anything about an undeclared _ | the headline limitation, and the one you can do something about: declare the input and most of the rest follows. |
Nor does it say anything about runtime cost or failure. A well-typed expression can still divide by zero, exhaust memory, or take a long time — see Running Elo safely.
Note: an unknown field is reported for adeclared schema, not for an object literal. A schema is a contract the runtime enforces — extras are rejected outright, or with ... allowed in but stripped from the coerced value, so the field cannot be read either way. An object literal is just a value, and reading a key it does not have is how Elo expresses absence (isNull({}.budget)).
Type checking is a correctness and portability tool, not a security feature: the guarantees on the security pagehold whether or not you run it.
Get Started
Ready to use Elo on your computer? Here's how to get started.
Try Online First
The easiest way to explore Elo is the online playground — no installation needed.
Install the CLI
To run Elo locally, install the command-line tools via npm:
npm install -g @enspirit/elo
This gives you two commands:
elo— Evaluate Elo expressions and see results immediatelyeloc— Compile Elo to JavaScript, Ruby, Python, or SQL
Quick Examples
# Evaluate an expression
elo -e "2 + 3 * 4" # => 14
# Evaluate from a file
echo "upper('hello')" > hello.elo
elo hello.elo # => HELLO
# Compile to JavaScript
eloc -e "2 + 3" # => (function(_) { return 2 + 3; })What's Next?
- Learning Elo? Start with the Learn tutorial
- Building an app? See the JavaScript API below
- Need a function? Browse the Standard Library
JavaScript API
For Node.js or browser projects, install the library:
npm install @enspirit/elo
compile()
Every Elo expression compiles to a function that takes _ (the implicit input) as parameter.
import { compile } from '@enspirit/elo';
import { DateTime, Duration } from 'luxon';
const double = compile('_ * 2', { runtime: { DateTime, Duration } });
double(21); // => 42When a call fails
A value Elo refuses raises an EloFailure — an ordinaryError that also says what kind of thing failed, so you do not have to read that back out of the message.
import type { EloFailure } from '@enspirit/elo';
try {
compile("Pos = Int(i | positive: i > 0)\nRec = { a: Pos }\n_ |> Rec")(input);
} catch (error) {
const failure = error as EloFailure;
failure.kind; // 'schema' | 'missing' | 'constraint' | 'guard' | 'check'
failure.path; // '.a' — where in the input, for the schema kinds
failure.label; // 'positive' — the constraint, guard or check that named it
}| Input | kind | message |
|---|---|---|
{"a":"x"} | schema | .a: expected Int, got "x" |
{} | missing | .a: expected Int, got undefined |
{"a":0} | constraint | .a: constraint 'positive' failed |
{"a":1,"b":2} | schema | .b: unexpected attribute |
kind and label come from the construct that refused the value, so they are stable. message is for a human and its wording is not: reading a category out of it is how rewording a diagnostic silently breaks a host.
Ruby and Python report the same three, from their own preludes: Ruby raises a StandardError answering kind,path and label, and Python anEloFailure with those attributes. SQL has none of this — it refuses type definitions and guards outright, so it has no such failure to report.
A source that imports
An import makes the compiler read a file, so it is a capability the host grants: pass a loader, and the filethe source came from, which a path is resolved against. Without a loader, an import is refused.
import { compile } from '@enspirit/elo';
import { nodeLoader } from '@enspirit/elo/node'; // reads the filesystem
const run = compile(source, {
runtime: { DateTime, Duration, Interval },
loader: nodeLoader(),
file: 'main.elo',
});nodeLoader is behind a second entry point on purpose:@enspirit/elo itself must stay importable in a browser, where there are no files to read — this playground is such a host, and refuses an import. A host may pass its own ModuleLoaderinstead, over a map of sources, a database, or a bundler's virtual filesystem.
A file of one-line expressions
readProgram is the --lines reading: the header is lifted off once with loadProgram and scopes every line, which is what the scope option is for.
const program = loadProgram(source, { loader: nodeLoader(), file });
for (const line of readProgram(program.body, true)) {
if (hasNoExpression(line)) continue; // a blank or a comment
console.log(compile(line, { runtime, scope: program, file })(input));
}Lower-Level API
import { parse, compileToJavaScript, compileToRuby, compileToPython, compileToSQL } from '@enspirit/elo';
const ast = parse('2 + 3 * 4');
compileToJavaScript(ast); // => "2 + 3 * 4"
compileToRuby(ast); // => "2 + 3 * 4"
compileToPython(ast); // => "2 + 3 * 4"
compileToSQL(ast); // => "2 + 3 * 4"Command Line
Elo provides two CLI tools: eloc (compiler) and elo (evaluator).
Evaluator (elo)
Quickly evaluate Elo expressions:
# Evaluate an expression
elo -e "2 + 3 * 4" # => 14
# Evaluate with input data
elo -e "_.x + _.y" -d '{"x": 1, "y": 2}' # => 3
# Evaluate a file: one program
elo program.elo
# Evaluate a file of one-line expressions, one result per line
elo expressions.elo --lines| Option | Description |
|---|---|
-e, --expression | Expression to evaluate |
-d, --data | JSON input data for _ |
--stdin | Read JSON input from stdin |
--lines | One expression per line, instead of one program |
Compiler (eloc)
Compile Elo to other languages:
# Compile to JavaScript (default) eloc -e "2 + 3 * 4" # Compile to Ruby eloc -e "2 + 3 * 4" -t ruby # Compile to SQL eloc -e "2 + 3 * 4" -t sql # Compile to Python eloc -e "2 + 3 * 4" -t python # Include runtime prelude eloc -e "NOW + PT2H" -t ruby -p # Emit a target's prelude on its own eloc --prelude-only -t ruby # Compile a file: one program eloc program.elo -t ruby # Report the type errors a compile does not refuse on its own eloc --typecheck -e "if 1 then 2 else 3"
Every compile-time refusal names where it is — the line, the column, and the file when the source came from one. With--lines the line counts from the top of the file, and a refusal inside an imported module names the module:
eloc main.elo # Compilation error: Error: Unknown function rond(Any, Int) at line 1, column 18 of helper.elo
| Option | Description |
|---|---|
-e, --expression | Expression to compile |
-t, --target | Target: js, ruby, python, sql |
-p, --prelude | Include runtime imports (not for sql) |
--prelude-only | Emit only the prelude |
--strip-guards | Remove guard/check assertions |
--lines | One expression per line, instead of one program |
--typecheck | Report the advisory type errors, exit non-zero if any |
--strict | Also report what the checker cannot type |
--input-type | Declare the type of _ |
--optimize | Compile with the checker's types |
-f, --file | Output to file |
A file is one program
A .elo file holds one program: optionalimports, an optionaltype prelude, then one expression. Newlines inside that expression mean nothing, so a schema or alet may be laid out over as many lines as it needs. A file that declares types and no expression is valid too, and compiles to nothing.
--lines asks for the other reading: every line is its own expression, and every line of source gives one line of emitted code. A source holding two expressions without it is a parse error that says so.
The prelude
Compiled Elo needs a small runtime in its target, and--prelude-only emits it. For js,ruby and python it is prepended to the expression — that is what -p does.
SQL is the exception. The emitted SQL is a pure expression, and an expression has nowhere to define a function, so SQL's prelude — the elo_* helpers the compiler calls for type selectors and Data operations — is a set ofCREATE OR REPLACE FUNCTION statements that must be installed in the database once, before any compiled Elo runs there:
eloc --prelude-only -t sql | psql "$DATABASE_URL"
Every definition is CREATE OR REPLACE, so re-running it is idempotent — on each deploy is a fine place for it.eloc -p -t sql refuses rather than emit statements no host can run as an expression.
Versioning
Elo follows semantic versioning, which is a promise about a surface — so here is the surface. Three tiers, and the tier a thing sits in decides what changing it costs.
Public — changes only in a major release
- The language and the standard library, and their intended semantics
- The
eloandelocbinaries: their options, and their exit codes —0when code was produced, non-zero when the compiler refused - The TypeScript entry points for parsing, compiling, evaluating and type-checking:
compile,parse, the fourcompileTo…functions,typecheck,getPrelude, and the module loader.@enspirit/elostays importable in a browser;@enspirit/elo/nodeis where anything touching the filesystem lives - Two things that live inside the generated code, because a host has to hold onto them: a failure's
kind,pathandlabel— themessageprose is not promised, which is why the kinds exist — and the elevenelo_*PostgreSQL prelude function names you install in your database
Protected — may change in a minor release, always announced in the changelog
- The AST: its node shapes and its factory functions
- The type checker's diagnostic codes. The checker keeps working and keeps reporting; which code it uses for a given mistake may be renamed
Private — no promise at all
- The shape of the generated code. Do not depend on how an expression translates, nor on the target language's own dynamic behaviour around it. Elo promises what an expression means, not what it compiles to
- Everything else reachable from the package. Being importable is not a promise
Which version to depend on. Use 1.x if Elo is a black box to you — the language, the CLIs,compile(). Pin 1.2.x if you build or read an AST, or branch on diagnostic codes.
What counts as a breaking change
A program Elo never meant to accept is a bug fix, not a break. The compiler used to accept round('x'), and[1, 'two'] on PostgreSQL, and emitted code that raised or that the database rejected; refusing them breaks nothing that worked. Where the four targets disagreed, at most one of them was right.
What makes "never meant to" checkable rather than a matter of opinion:the acceptance corpus is the specification. A behaviour asserted by a fixture, on a target, is promised. A behaviour no fixture asserts is unspecified, and making the four targets agree on it is a fix.
Pin the behaviour you depend on
Which means: if your code relies on something, send us an assertion for it. A fixture is the only thing that turns a behaviour you observed into a behaviour Elo owes you — and it is the cheapest contribution there is, one line:
assert(startOfMonth(D2026-03-15) == D2026-03-01)
Add it under test/fixtures/, regenerate, open a pull request. It then runs on Ruby, JavaScript, Python and PostgreSQL on every commit.
This is the most useful thing an Elo user can contribute, for two reasons. An assertion that passes on all four targets costs us nothing and locks the behaviour down for good. One thatfails on one has found a portability bug — most of the defects fixed in 1.2.0 were exactly that, four targets asked the same question and one answering differently. Either way you end up better off, and you do not need to know how the compiler works.
Unsure whether something is specified? Search the corpus. If it is not there, it is not promised yet — and that is the gap worth a pull request.