⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠐⠢⠒⣲⢄⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⢠⢒⢰⠄⠀⠀⠀⢀⠌⠀⠀⠀⡌⠄⣀⠂⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⡜⢸⠈⠠⡀⠀⢀⠃⠀⠀⠀⠀⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⢣⠀⢀⠀⠦⡀⢧⡄⠀⣷⠁⢀⡨⠐⠒⠀⠤⢄⡀⠀⠀⠀ ⠀⠀⠀⠀⢀⡀⠀⠣⡉⠢⡀⠑⡄⠃⠐⠠⠰⢁⠤⠤⠤⠀⠀⠀⠈⠢⡀⠀ ⠀⠀⢀⠎⠁⠀⠀⠀⠀⠱⠎⠱⠈⢸⡀⢀⠎⠁⠀⠀⠀⠀⠀⠀⠀⠀⠈⡆ ⠀⣀⢎⠾⠑⠃⠈⠁⠀⠰⠖⢉⠉⢐⣠⠖⠐⠢⣀⣀⣀⣀⠤⠒⠒⢄⠀⡇ ⠸⠁⠀⣀⣀⠀⠀⢀⠤⠒⠋⢁⠔⡌⢘⢄⠀⠀⠙⡄⠀⠀⠀⠀⢗⠃⢃⠇ ⠠⣤⣮⠀⠀⠀⡠⠁⠀⡴⠊⠁⠀⡇⠈⠀⠀⠀⠀⢠⠀⠀⠀⠀⠀⠈⠁⠀ ⠀⠀⠀⠀⠀⢠⠁⠀⠀⠀⠀⠀⢠⠴⡄⠀⠀⠠⡀⠀⠣⡀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠸⡀⡎⣴⢒⠊⠉⠀⠀⠀⠑⠢⡀⠑⠄⠀⢱⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠑⠬⠮⠟⠀⠀⠀⠀⠀⠀⠀⠘⠦⠐⠐⠊⠀⠀⠀⠀⠀⠀
revo in 1 minute
more
to get help on any function, just go over to ./std
you can also point :h in the repl at any documented declaration
rεvo > #* just returns 5 *#
> global hi = fn() 5
hi()/0
rεvo > :h hi
fn hi() -> int
just returns 5
rεvo > :h print
print(args: any...) -> :ok
prints values to stdout with space separatorthe fundamental types are:
-
numbers -
1, 1.0, -0.14 -
tables -
{1, 7}, {k = "v", [1 + 4] = "8"}
they have an array part and a hashmap part, and are used to represent any other data structure
that is not already a fundamental type (like strings). there are some builtin methods
anything that contains more than one item and has to be mutable should be a table.they are always passed by reference, never copied unless you manually
{1,2,3}:copy() -
atoms (a.k.a. symbols, sigils)
only to be used to compare against other atomsare the way to express nil, true, and false
they are not to be created at runtime. very useful to express tagged unions with tables
only
:false,0,:undef,:missing,:no,:none,:no_result, and:nilare falsey - everything else (including""and{{}}) is truthypub inline fn isFalse(val: Value) bool { return ( // (val.bits >= Value.new.atom(0).bits // and val.bits <= Value.new.atom(CoreAtoms.lastFalse).bits) // or val.bits == Value.new.num(0).bits // ); }for this reason, the language does not have exceptions/errors and uses
{:err, :ErrorName}and{:ok, value}together with pattern matching,?,orelseand:unwrap()
to handle errors. toplevel?panics instead of returning silently: -
functions
a function is very simple. it (technically) is just one expression, to which you can give parametersthe syntax only requires for one expression. so how do you make it a real procedure?
do 1 2 3 endallows for grouping multiple expressions together. it normally evaluates
to just what the last expression was, and fordo 1 2 3 end, it’s 3. you can, however,
do 1 return 2 3 end, which returns early with 2!parameters can be marked optional with
?. when omitted, they default to:none:it is always first-class, no matter how it may appear
it also captures values from the outer scope, like most modern languages
closures capture outer values by reference, so mutations are visible
to all closures sharing that variable:also, every function really is a function and never just a procedure.
all expressions return something, it’s just that sometimes the result is not going to be of
much use to youa call normally uses parens. when its only argument is a string or table
literal, you can drop them and keep one space:postfix operators apply to the result:
f "x":upper()is(f "x"):upper(). usef("a", "b")for multiple args -
strings -
"string"
they’re just like any other strings. double-quoted strings process escape sequences, while
single-quoted strings are completely literal (no escape processing):you can also use the
"string":method()methods:found in the std docs
-
tables (array part/tuple)
sequences with 0-based indexing, useful for error handling and
storing data you know the shape of.
types
the compiler infers types, tracks them, and uses them to pick fast paths.
they fall back to any when inference fails.
type annotations
bindings and function parameters can carry type annotations:
return types come after ->:
function-typed bindings also validate arguments:
tables can be annotated by shape, extra fields are fine:
array entries are positional, just the type:
type aliases
type creates a local name for a type expression:
type expression syntax:
| syntax | meaning |
|---|---|
int |
built-in name or alias |
int? |
int | :nil (optional sugar) |
int | string |
union type |
{int, string} |
table with two array entries |
fn(int) -> bool |
function signature |
fn(?a: int) -> bool |
function signature with optional param |
table<int> |
table with value type int |
table<string, int> |
table with key string, value int |
{ name: string } |
table with field name: string (extra fields ok) |
{ ?name: string } |
table where name: string may be absent (name: string? instead means the key is required but may hold :nil) |
{ number, number } |
table with two array entries (extra fields ok) |
{ number, name: string } |
mixed array and named fields |
!int |
:ok(int) | :err(any) (error union sugar) |
type names cannot be used as values at runtime:
ambient declarations
declare names something the host provides
you’re gonna need this for calling functions that come from outside of revo
it works like a typed const, the compiler trusts the type and compiles references
to a plain global load, and the value must exist at runtime or you get undefined variable
function ambients declare a signature with no body. calls typecheck against it
and the return type flows into inference:
#* ... *# attaches text for the lsp hover:
declare is top-level only, once per name, order-sensitive like const, and
rejects value rebinding of the name.
union types
unions model tagged values. each variant is either an atom alone or an atom with a payload:
coercion
assigning a value to a typed binding coerces automatically when safe:
- same type coerces
anycoerces from/to everythingint->float:true/:false->bool- atom matching a union’s atom-only variant
- function types: contravariant in params, covariant in return
type narrowing
type predicates in if conditions narrow the type within the branch:
supported predicates: number?, string?, table?, atom?, function?, opaque?, resource?
runtime type predicates
built-in checks that narrow types at runtime:
typeof(x) returns the runtime type as an atom:
structural types
tables carry fields and closures; structural types describe their shape:
field writes just work:
table methods
methods are closures stored in the table and receive self as the first
argument. method fields go in the type too, so colon calls resolve to
them instead of baselib methods with the same name:
? suffix convention
functions whose name ends with ? must return bool:
opaque
opaque wraps a raw pointer as a value:
opaque values compare by pointer identity and have no destructor; the caller manages the pointer’s lifetime
resource
owned handles from c! same hiding as opaque, plus a per-handle
metatable & a __gc hook. light never finalizes; resource does, once
operators
standard arithmetic and comparison work as you’d expect:
integer division with // floors toward negative infinity, like python. it works on floats too
(x // y is floor(x / y)), returning an int when both operands are integral and a float otherwise
bitwise operators are spelled as words and, like python, reject non-integral operands at runtime:
since numbers are all the same runtime type, “integral” is judged by value: 2 band 3.0 works (3.0 is integral),
but 2 band 3.5 is an error. // 0 is a runtime error
bitwise operators bind tighter than +/- but looser than *//, so 1 + 2 band 3 is 1 + (2 band 3)
rather than (1 + 2) band 3. shl/shr wrap on overflow; shift amounts outside 0..63 are a runtime error
^ is exponentiation, like python’s **. it’s right-associative and binds tighter than multiplication and
unary minus (-2 ^ 2 is -(2 ^ 2) == -4). integral base with non-negative integral exponent stays an
integer (wrapping); anything else gives a float (2 ^ -1 == 0.5):
numbers are plain doubles, so literals may use the full float range (1.5e300 is fine). arithmetic
overflow gives inf (1e308 * 10), which compares and propagates like math says; dividing by zero
is a runtime error, not nan
and/or preserve value semantics rather than collapsing to booleans, which makes them useful
for default values and short-circuit guards:
assignment operators exist and work as you’d expect. since assignment is an expression, it
returns the rhs:
~ concatenates values into strings!!! polymorphic with fast paths for strings and numbers:
custom types can opt in via __tostring:
control flow
if/else
if is an expression and returns the value of whichever branch was taken:
loops
loop creates a loop block. a loop always evaluates to :nil; break exits it, continue skips to the next iteration
BUT you CAN carry a value out of a loop!!!
break out of a labeled loop or do-block with a value:
labeled loops
loops and do-blocks can carry a label (like loop/a, for/a, while/a, do/a). break/a exits the named block with the value you give it; continue/a restarts the named loop. a labeled block only produces a value when it is exited with a labeled break; otherwise it evaluates to :nil:
while and for
match
match arms are expressions. wildcards and guards let you cover complex cases cleanly:
comma arms try each pattern in order, first hit wins:
a miss falls through to :nil, and the type knows it
cover every variant and the :nil is gone:
the checker warns when an arm can’t fire
covered tags first:
same for patterns the subject can’t meet:
pipe operator
pipe passes a value as the first argument to the next expression:
they apply to most of the language, since everything will likely return something useful
pipes pair well with ?, orelse, and match for error handling:
iteration
all collection functions live under the iter module. transforms (iter.map, iter.filter,
iter.take, …) return lazy iterators; call iter.collect (or iter.collect_string,
iter.collect_string) to materialize them into a value. terminal ops (iter.reduce,
iter.each, iter.find, iter.all?, iter.any?, iter.count, iter.sum) run eagerly:
slicing
[start..end] extracts a contiguous portion of a string or table.
[start..step..end] adds a step to skip elements. any bound can be omitted.
errors
revo does not have exceptions and tries to crash only in extreme scenarios
this means, errors are treated as values
if a function may error, it’s likely to return either
{:ok, value}
… or {:err, :ErrorName}
see examples/errors.rv for full examples
propagation: ? and orelse
revo has two operators for error handling: ? for early return and orelse for defaults
the ? operator
? propagates errors up the call stack. if an expression is an error ({:err, ...}), the function returns immediately with that error. otherwise, the value is unwrapped. at toplevel, the error panics instead of returning silently.
the toplevel is implicitly a function, so returning an error from it panics too
test blocks
test "name" do ... end defines a small test body that only runs when you pass --test
it uses the same module scope as the rest of the file, so it can call local helpers directly
if a test body hits ? on an error, it behaves like the rest of the language and panics at top-level
orelse
orelse assigns a default value when an expression is nil, undef, or an error
fibers and channels
fibers are cooperative (not preemptive). the main fiber runs first and the run queue is FIFO.
spawn takes a function call expression and runs it in a new fiber
, returning a {:fiber, id} handle
join is a builtin that blocks until it’s done and returns the result
channels coordinate fibers. unbuffered channels (chan()) block the sender until a receiver
is ready. buffered channels block only when full:
yield suspends the current fiber and pushes it back to the run queue. sleep(ms) parks it
without blocking other fibers:
modules
import("x") gives you a module. it’s resolved at compile time, from the file that wrote it
## ./helper.rv ##
pub fn help() do
print("helped")
end## ./main.rv ##
const helper = import("./helper") # next to this file
const json = import("std:json") # inside the std collection
helper.help() # helpedthe path is a literal. import isn’t a value, and it can’t be shadowed
import("helper") # error: bare paths are reserved, write `./helper`
import("/opt/x") # error: absolute paths aren't portable
import(path) # error: use `revo.load` for computed paths
let imp = import # error: not a value./x means x.rv or x/init.rv. both existing is an error. ./x.rv means just that file
a module is a body that runs once. with pub, its value is a read-only record of the pub names. without, it’s the last value
## ./geo.rv ##
pub const pi = 3
pub fn area(r) pi * r * r
print("loaded geo") # runs, the module is still {pi, area}
## ./double.rv ##
fn(x) x * 2
## ./main.rv ##
const geo = import("./geo")
geo.area(2) # 12
geo.pi = 4 # error: pub records are read-only
import("./double")(3) # 6an explicit return wins over pub, with a warning. pub is const-only, so expose state through a fn
let n = 0
pub fn count() n
pub fn bump() do n = n + 1 end
pub const {lo, hi} = {0, 9} # exports bothpub type exports a type, through the module’s binding
## ./shapes.rv ##
pub type Point = {x: number, y: number}
## ./main.rv ##
const shapes = import("./shapes")
let p: shapes.Point = {x = 1, y = 2}use binds a module by its path stem
use("std:json") # const json = import("std:json")
use("./helper") # const helper = import("./helper")
helper.help() # helpedit’s a statement with a literal path, and the stem has to be a name. otherwise bind it yourself
const my_lib = import("./my-lib")a module loads the first time its import runs, once per vm. fibers that import it while it loads wait for it
fn lazy() import("./big").run() # loads on the first calla cycle of top-level imports is a compile error. a lazy one is fine, unless it runs while its target is still loading
revo.load is the dynamic one. the path is data, so it resolves from the cwd. it shares the module table
const plugin = revo.load(path)? # {:ok, m} | {:err, e}
const again = revo.load(path, {fresh = :true})? # reruns itdlls go through revo.dload. type them with a binding
## ./lib.rv ##
const lib: {
add: fn(a: number, b: number) -> number,
} = revo.dload("./lib.so")
return libcollections are name:x prefixes. std: is built in, add more with revo --collection name=dir
doc comments
names and types carry most of the documentation. for the rest there’s
#* ... *#:
multi-line works too:
any declaration can take one - functions, type aliases, plain values:
extract docs with revo doc script.rv:
# docs for script.rv
- add/2
adds two numbersthe baselib runs on the same comments: src/baselib/base.rv is the single
source of truth behind runtime registration, compile-time typing, and the
ref:std
">generated reference
advanced
comptime
comp evaluates an expression at compile time and replaces it with the constant result in the
bytecode. compile time happens both when executing a script directly and when running
revo compile in.rv out.rvo:
metatables
metatables let you customize table behavior via metamethods. set one with set_meta:
plain table fields always resolve before __index is called. metatable fields (like methods)
resolve before __index too, which is how obj:method() works without any extra magic:
forloops can also iterate over any object that has an __iter metamethod set