Syntax basics
Recoil borrows Rebol's surface syntax. If you've never seen Rebol, here is everything you need — there are only a handful of lexical rules.
Words, values, and blocks
Code is made of words (names like print or
add), values (like 42 or
"hi"), and blocks — anything inside square
brackets [ ]. A block is just a grouped sequence of items; Recoil
uses blocks for function bodies, type specifications, and literal data alike.
; a comment starts with a semicolon and runs to end of line
print 42 ; a call: the word `print` applied to the value 42
Calls have no parentheses or commas
A function call is a word followed by its arguments, separated by spaces. Arguments are consumed left to right.
add 2 3 ; add(2, 3) in C terms
print add 2 3 ; print(add(2, 3))
Use parentheses only to group sub-expressions:
x: (10 + 5) * 2 ; 30
Set-words and get-words
A word ending in a colon is a set-word — it binds a value. A word starting with a colon is a get-word — it refers to something without moving it (used for borrowing and for passing functions).
count: 0 ; set-word: bind `count` to 0
greet :name ; get-word: borrow `name` for the call
Refinements and paths
A leading / marks a refinement — a named
variant or sub-call. A / between words or indices forms a
path.
file/open %data.txt ; `open` action in the `file` namespace
p/x ; field access
nums/0 ; index access (0-based)
nums/:idx ; index by a variable
Types end in !
By convention every type name ends with an exclamation mark:
i32!, logic!, string!,
struct!. The make word constructs typed values from a
type and an initializer.
point!: make struct! [x: i32! y: i32!]
Attributes
An attribute is a word that starts with #. It
is not a value: it tags a type or a function with a capability the compiler
then checks. Attributes go in one of two places:
- a type attribute is the first word inside a type spec
block, so it is part of the type:
[#mutable string!],[#flexible [string! 16]] - a function attribute sits in a function's spec block,
next to the parameters:
func [#export return: [none!]]
buf: make [#mutable string!] "hello" ; type attribute: buf may change in place
init: func [
"Announce that the library is ready."
#export
return: [none!] "Nothing."
] [ ; function attribute: visible in a library
print "ready"
]
This guide uses five. Each is explained where it first matters:
| Attribute | On | Meaning | Explained in |
|---|---|---|---|
#mutable | type | contents may be modified in place | Bindings |
#flexible | type | may also grow and shrink | Bindings |
#unique | type | a series that moves on assignment instead of being shared | Ownership & borrowing |
#export | function | expose the function from a generated library | Functions |
#capture | function | the outer bindings a closure keeps | Closures |
The reference lists the rest,
such as #atomic and #stack.
Bindings & implicit typing
The idiomatic way to introduce a value is a set-word with a right-hand side. The type is inferred from that right-hand side — you rarely write it out.
count: 0 ; i32!
ratio: 3.14159 ; f64!
ch: #"A" ; char!
flag: true ; logic!
total: add 10 20 ; inferred from the call result → i32!
doubled: count * 2 ; inferred from the operands
When you need make
Use the explicit make Type! value form when inference has nothing
concrete to latch onto, or when you want a non-default type:
- a non-default width or type:
big: make i64! 1 - a heap-allocated, reference-counted
string!(a bare"..."literal is already astring!, a static one that is never freed):msg: make string! "hello" - typed or empty containers and structs:
nums: make [#mutable vector! [i32! 3]] [] - callables and ports:
cb: make fn-ptr! add,fp: make port! file/open %data.txt
Mutability
Bindings are immutable by default. There is no mut
keyword — mutability is part of the value's type spec, written inside
make [ ... ]:
buf: make [#mutable string!] "hello"
buf/0: #"H"
grow: make [#flexible [string! 16]] none
append grow "world"
#mutable— contents may be modified in place (fixed size).#flexible— may also grow/shrink (append,insert,remove).
A binding that must be reassigned is declared with
mutable as its direct initializer:
count: mutable 0
count: count + 1
Prefer computing a value once from an either or a helper function over
reassigning a binding.
Datatypes
Recoil has a concrete, statically-known type for every value.
Scalars
- Integers:
i8!i16!i32!i64!and unsignedu8!u16!u32!u64! - Floats:
f32!f64! logic!,char!,size!none!— a safe "absence of value";void!— "no value at all" (function return only, cannot be assigned)
Owned & resource types
string!— the user-facing string; shared and reference-countedurl!,file!,port!,error!,c-pointer!,binary!(a byte buffer)
Structured & container types
vector!(fixed-size, homogeneous),array!,block!(heterogeneous),dict!,map!,slice!(zero-copy view),value!(a tagged cell),channel!(a typed queue between tasks)struct!,enum!,sum!(tagged union),fsm!,rule!,bitset!,fn-ptr!
ABI-facing types
Boundary types for FFI and the C ABI: c-string!,
c-struct!, c-array!, c-fn!. In ordinary
code prefer string!; use c-string! only at the C
boundary. See FFI & Systems.
Copy, move, and borrow
How a value behaves on assignment depends on its type. Scalars copy;
the managed series (string!, block!,
vector!, array!) are shared and
reference-counted; every other owned type moves:
| Category | Types | On assignment |
|---|---|---|
| Copy | integers, floats, logic!, char!, enum!, size!, file!, bitset! | duplicated; original stays valid |
| Share | string!, block!, vector!, array!, typed dict! | a reference is added; both bindings stay valid |
| Move | url!, port!, error!, map!, c-pointer!, binary!, and any series marked #unique | ownership transfers; original becomes inaccessible |
| Borrow | slice! and get-word references | a view; does not take ownership |
Native series are shared by default: assigning or passing one
just adds a reference. Add #unique to opt back into move-only
ownership (see Memory & sharing).
Sum types inherit move sensitivity from their variant fields.
See Ownership & borrowing below for the rules the borrow checker enforces.
Indexed paths
voice!: make struct! [phase: f64! active: logic!]
voices: make [#mutable vector! [voice! 2]] []
idx: 1
voices/:idx/phase: 0.5 ; field through a variable index
print voices/:idx/phase
Control flow & expressions
Recoil is expression-oriented: most control forms produce a value.
if and either
Both are expressions. The chosen branch's last value becomes the result. An
expression if usually appears in a typed context such as
make.
if x > 10 [print "big"]
if [x > 10] [print "big"] ; block condition also works
label: either x > 10 [
1
] [
2
]
; a one-armed if yields none when false: for a scalar value (make i32! if ...) it is P1627, so use either
match over sums
Branch on a sum! value and bind its payload
(see Sum types & pattern matching):
status: match value [
some [payload] [1]
none [0]
]
all and any
Short-circuiting boolean expressions:
ok: make logic! all [1 = 1 2 = 2]
some: make logic! any [0 = 1 2 = 2]
Loops
while, repeat, and foreach are also
expressions: each yields its body's last value from the final iteration
(boxed as value!), or a boxed none! if the body never
ran.
i: make [#mutable i32!] 0
while [i < 5] [
print i
i: i + 1
]
repeat n 10 [print n] ; 0..9
foreach [key val] counts [ ; two-variable iteration over a dict
print val
]
Inside loops, break and continue behave as usual.
return expr exits the enclosing function.
go
go [body] spawns a cooperative task. It is a statement only and produces
no value. Ready tasks run in FIFO spawn order; a task yields when it calls
sleep, blocks on a channel, or waits in yielding I/O. go/after ms [body]
delays the start. Tasks talk through typed channels:
make channel! [i32! 4], send ch value and
receive ch (see Tasks & channels).
demo: func [
"Spawn a task, then yield so the task gets to run."
] [
print "main"
go [print "task"]
sleep 10 ; yield, so the task gets to run
]
demo
go is only allowed inside a function body.
Sum types & pattern matching
A sum! is a tagged union: a value is exactly one of its named
variants, and each variant may carry fields. match is how you take
one apart.
Declaring and constructing
Variants are listed in a block. A variant with a field block carries a
payload; a bare word is a payload-free variant. Construct a value with
Type!/variant, giving the fields in a block:
Shape!: make sum! [
circle [radius: i32!]
square [side: i32!]
]
c: make Shape! Shape!/circle [radius: 3]
s: make Shape! Shape!/square [side: 4]
A sum copies or moves according to its variant field types, so a variant
holding a string! or dict! behaves like that field
does.
Matching and binding
Each arm is variant [bindings] [body]. The bindings name the
payload fields in declaration order, and are visible only inside that arm. A
payload-free variant takes an empty binding block. match is an
expression, so it can be the last value of a function:
describe: func [sh [Shape!] return: [string!]] [
match sh [
circle [r] [rejoin ["circle-" r]]
square [s] [rejoin ["square-" s]]
]
]
print describe make Shape! Shape!/circle [radius: 3]
In value position every arm must produce the same type. In statement position the result is discarded, so arms may disagree, which is how the common drain-a-scanner loop is written:
Step!: make sum! [
ok [n: i32!]
need-more
done
]
step: Step!/ok [n: 7]
match step [
ok [n] [append out #"K"]
need-more [] [active: false]
done [] [active: false]
]
Exhaustiveness and default
A match must cover every variant, or end in a
default arm. default takes no bindings and must come
last. Leaving a variant out is a compile-time error, not a runtime surprise:
out: make i32! match value [
ok [payload] [payload] ; P1622: missing branch(es) for [error]
]
match blk/0 [
rv-i32 [v] [print v]
default [print "other"]
]
| Code | Raised when |
|---|---|
| P1614 | the subject is not a sum! value |
| P1616 / P1617 | a variant is matched twice / is not a variant of the subject |
| P1618 | an arm binds the wrong number of payload fields |
| P1620 | an arm binds the same name twice |
| P1621 | the match has no arms |
| P1622 | a variant is missing and there is no default |
| P1623 / P1624 / P1625 | more than one default / it is not last / it has bindings |
| P1626 | value-position arms produce different types |
Matching on plain values
match only takes a sum! subject. To branch on a
literal scalar, use switch; it is an expression and requires a
default branch (P1737):
n: make i32! 2
result: make i32! switch n [
1 [10]
2 [20]
default [30]
]
Functions
Functions are defined with func: a spec block (a doc string,
the parameters, and a return: type) followed by a body
block. The last expression is the result unless an earlier
return exits first.
add: func [
"Add two signed 32-bit integers."
a [i32!] "Left operand."
b [i32!] "Right operand."
return: [i32!] "The sum."
] [
a + b
]
print add 7 8 ; 15
A function with no return: returns void! and cannot be
assigned.
Documenting functions
Every function is documented in its spec: one sentence about the function as
the first element, then a description after each parameter's type and after the
return: type, as in add above. Describe what the caller
supplies and receives, including who owns a value. Attributes such as
#export go after the doc string. The compiler keeps these strings on
the parsed function spec. Nothing turns them into documents yet, so writing them
now gives a future generator complete input. See
Functions
for the exact placement rules.
Borrowed parameters
Mark a parameter with a get-word to borrow it instead of taking ownership.
Pass the argument as a get-word too. Shared series stay valid either way; borrowing
matters for #unique and other move-only values:
greet: func [
"Print a borrowed string."
:name [string!] "The borrowed string to print; the caller keeps it."
return: [none!] "Nothing."
] [
print name
]
msg: make [#unique string!] "hello"
greet :msg
print msg ; still valid — msg was borrowed, not moved
Method chaining
A refinement call passes the value on its left as the first argument, so calls chain left to right:
result: 10 /add 5 /mul 2 ; mul(add(10, 5), 2) = 30
Functions used in a chain must not return void!.
Exporting
Mark a function #export to expose it from a generated library
(see Packages & Libraries):
init: func [
"Announce that the library is ready."
#export
return: [none!] "Nothing."
] [
print "ready"
]
Closures & function pointers
Callable values have type fn-ptr! and are introduced with
make fn-ptr!. A closure captures variables from its enclosing
scope via an explicit #capture list in its spec.
A plain function pointer
add: func [
"Add two signed 32-bit integers."
x [i32!] "Left operand."
y [i32!] "Right operand."
return: [i32!] "The sum."
] [
return x + y
]
callback: make fn-ptr! add
print callback 3 4 ; 7
Capture by value
base: 100
bump: make fn-ptr! func [
"Add the captured base to a value."
#capture [base]
a [i32!] "The value to offset."
return: [i32!] "The value plus the captured base."
] [
a + base
]
print bump 7 ; 107
Capture by reference
Capture a mutable binding by get-word to mutate it through the closure:
counter: make [#mutable i32!] 0
inc: make fn-ptr! func [
"Increment the captured counter and return it."
#capture [:counter]
return: [i32!] "The counter after the increment."
] [
counter: counter + 1
return counter
]
print inc ; 1
print inc ; 2
func: the spec (which holds both
#capture and the typed parameters) and the body. A third block
leaves the body empty.
Generics
A function becomes generic when generic [T] precedes its
func. The names in the block are type parameters, usable anywhere a
type is: parameters, the return type, and size-of T.
min-value: generic [T] func [
"Return the smaller of two comparable values."
left [T] "The first candidate value."
right [T] "The second candidate value."
return: [T] "The smaller input value."
] [
if left < right [return left]
return right
]
Calling a generic
Pass the concrete types in a block straight after the function name, one per type parameter. A call that omits them is rejected with requires explicit type arguments, and an argument that does not match the substituted parameter type is a type error.
print min-value [i64!] 9 4
print clamp-value [i32!] 20 0 9
quicksort [i64!] all-i64 scratch-i64-view
The standard library uses this form throughout: std/math/core
(min-value, max-value, clamp-value) and
std/sort (quicksort, mergesort).
How instantiation works
Generics are resolved at compile time, before borrow checking. The
monomorphization pass finds each call with concrete type arguments, clones the
generic function with the parameters substituted, and rewrites the call to the
clone. Each distinct argument tuple produces one ordinary function with a
mangled name, so clamp-value [i64!] and
clamp-value [i32!] become two separate C functions
(clamp_value__g__i64_t, clamp_value__g__i32_t). There
is no boxing and no runtime dispatch. Because the body is checked per
instantiation, size-of T emits a concrete
sizeof(...):
type-size: generic [T] func [
"Return the concrete type size."
return: [size!] "Concrete type size in bytes."
] [
return size-of T
]
primitive-bytes: make size! type-size [i32!]
Limits
- Type arguments are always explicit; they are not inferred from the value arguments.
- The number of type arguments must equal the number of parameters in
generic [...]. - A qualified call such as
dep/a/fcannot instantiate a generic (P1749); import the name and call it unqualified. - A generic is a template: it produces no code until some call instantiates it.
Generic structs
A struct! can take type parameters too. Declare it once with
placeholders for the types, and name it with concrete types wherever you use it.
pair-of! [i64! string!] is an ordinary struct: the compiler generates
it the first time it sees that combination, and from then on it has the same
fields, actions, ownership rules and C layout as a struct you wrote by hand. There
is no run-time cost and no boxing.
pair-of!: generic [A B] make struct! [first: A second: B]
p: make [pair-of! [i64! string!]] [first: 3 second: "hello"]
print p/first ; 3
print p/second ; hello
Declaring
- The name is a type word ending in
!. The parameters are one or more distinct plain words; one spelled like a type (generic [i64!]), an empty or repeated list isP1770.hasbounds, which generic functions accept, are not accepted here. - Declare it at module top level; inside a function it is
P1773. The name cannot be another struct, enum, sum, fsm or alias of the module, nor a language type such asvector!(P1771). - The declaration defines no type by itself. Its fields are checked once per instance, not when it is declared.
- The declaration may come after the code that uses it.
Instantiating
Write the name followed by a block of type arguments, one per parameter, in
order, anywhere a type may appear: a make, a parameter, a return type,
a struct, sum-variant or c-struct! field, a vector!
element, or size-of. An argument is a type word, or a block for a
parameterised type, so they nest.
swap-sum: func [x [pair-of! [i64! i64!]] return: [i64!]] [
return x/first + x/second
]
make-pair: func [a [i64!] b [i64!] return: [pair-of! [i64! i64!]]] [
return make [pair-of! [i64! i64!]] [first: a second: b]
]
print swap-sum make-pair 2 5 ; 7
n: make [pair-of! [i64! [pair-of! [i64! i64!]]]] [
first: 1
second: make [pair-of! [i64! i64!]] [first: 2 second: 3]
]
print n/second/second ; 3
maketakes exactly one type. Writemake [pair-of! [i64! f64!]] [...], with the type and its arguments inside one block.make pair-of! [i64! f64!] [...]reads the arguments as the value; a baremake pair-of! [...]is rejected withP1777.- The wrong number of arguments is
P1774; an argument that is not a type (a number, a string) isP1775; a struct that contains itself with the same arguments isP1776. - Attributes wrap the whole type:
make [#mutable pair-of! [i64! i64!]] [...].
make [pair-of! [i64!]] [first: 1]
; TYPE ERROR P1774: Generic struct pair-of! takes 2 type argument(s), got 1: ...
What an instance is
Two uses with the same arguments are the same type: one C struct shared by the
whole program. Different arguments are different types, even when they look alike
once flattened: pair-of! [i64! i64!] and pair-of! [i64! i32!]
are unrelated and cannot be passed for each other. Fields are read and written with
paths, and the instance is copied or moved exactly as a hand-written struct with the
same fields would be (see Ownership & borrowing).
The template’s fields are checked per instance, with the real types in place, so one template can be fine for one instance and invalid for another. The error names the instance and points at the line that used it, with the code the equivalent hand-written struct would raise:
box!: generic [T] make struct! [v: T]
p: make [box! [c-string!]] [v: "x"]
; STRUCT ERROR P1511: In box! [c-string!]: c-string! is FFI-only; use string!, ...
Modules
A template belongs to the module that declares it and obeys Exports:
and Imports: like any other name. Export it to let other modules apply
it, and list it in a named import (Imports: [mod [twin! total]]).
; tests/generic-struct-export-a.rcl
Recoil [Type: module Module: tests/generic-struct-export-a Exports: [twin! total]]
twin!: generic [T U] make struct! [a: T b: U]
total: func [p [twin! [i64! i64!]] return: [i64!]] [return p/a + p/b]
; an importer
Recoil [Imports: [tests/generic-struct-export-a]]
p: make [twin! [i64! string!]] [a: 1 b: "x"]
print total make [twin! [i64! i64!]] [a: 4 b: 5] ; 9
- Two modules that apply the same exported template to the same arguments share one instance, and their values are interchangeable.
- A template that is not exported is private. Another module that tries gets
P1778, naming the module that declares it. Two modules may each declare a private template of the same name; they are unrelated. - Private types as arguments keep their module’s identity:
box! [foo!]in two modules that each have a privatefoo!are two different instances. - An instance may appear in an exported signature even when the template is private; the importer can call the function and read the result’s fields without naming the template.
- A template’s own words mean what they mean in its module, even if the importer declares a name of its own.
- Exported type names are global: two exported types (or two types of
programs with no
Module:header) with the same name areM2000, which names the other module.
Real uses: std/rational and std/complex
Two standard-library modules are each built on one generic struct, and both
export the template so an importer can write the type itself. std/rational
declares ratio!: generic [T] make struct! [num: T den: T] and
std/complex declares complex!: generic [T] make struct! [re: T im: T].
Their arithmetic is generic [T] over these structs, with the type
argument at the call (ratio-add [i32!] a b, complex-mul [f32!] a b);
only the libm-backed complex functions stay f64!.
Recoil [Imports: [std/rational std/complex]]
half: ratio 1 2 ; a ratio! [i64!] in lowest terms
sum: ratio-add half ratio 1 3
print ratio-form sum ; 5/6
q: make [ratio! [i64!]] [num: 7 den: 2] ; the type is nameable here
print ratio-floor [i64!] q ; 3
z: complex 3.0 4.0 ; a complex! [f64!]
print complex-abs z ; 5.000000
w: make [complex! [f32!]] [re: 1.0 im: 2.0] ; another width
print w/im ; 2.000000
See Standard Library for the module listings.
Generic functions over generic structs
A generic function may apply a generic struct to its own type parameters, in its
signature and body. Inside the function box! [T] is a placeholder; when
it is instantiated for i32! it becomes the same box! [i32!]
a hand-written use makes. A parameterised argument needs its own brackets:
box! [[twin! [T T]]], not box! [twin! [T T]].
box!: generic [T] make struct! [v: T]
wrap: generic [T] func [x [T] return: [box! [T]]] [
return make [box! [T]] [v: x]
]
add-box: generic [T] func [x [box! [T]] y [box! [T]] return: [box! [T]]] [
return make [box! [T]] [v: x/v + y/v]
]
c: add-box [i32!] wrap [i32!] 4 wrap [i32!] 5 ; box! [i32!]
print c/v ; 9
Per-instance field checks happen when the function is instantiated, so a call that makes an invalid instance reports it for that call.
Not supported yet
- A closure inside a generic function that mentions its type parameter
(
P1781; a closure that does not mention it is fine). sum!,map!,c-struct!andfsm!declarations cannot be generic.extendon an instance:extend twin! [...]isT4200, because there is no way to name an instance inextendyet.- A generic struct as a typed
dict!value or adict!field (P1703/P1764, as for any struct).
Diagnostics
| Code | Meaning |
|---|---|
P1770 | Parameter list empty, repeated, not plain words, or spelled like a type; also has bounds |
P1771 | Template name is already a type in this module, in either declaration order |
P1773 | Template declared inside a function |
P1774 | Wrong number of type arguments |
P1775 | A type argument is not a type |
P1776 | A struct refers to itself with the same arguments |
P1777 | Template named without type arguments |
P1778 | Template not visible here: not exported by its module, or not imported |
P1781 | A closure in a generic function uses the function’s type parameter |
Ownership & borrowing
Recoil's defining feature is a static borrow checker that enforces memory safety at compile time, with no tracing garbage collector. Every binding is in one of three states: owned (holds valid data), moved (ownership transferred away — using it is an error), or borrowed (referenced without transfer).
Shared by default
Assigning or passing a string!, block!,
vector! or array! adds a reference. The original
binding stays valid, and the value is freed when the last reference goes away:
s1: "Hello"
s2: s1 ; a reference is added
print s1 ; ok: both bindings are live
print s2
Move semantics with #unique
Add #unique to a series type to opt back into move-only
ownership. Ports, maps, errors, binary! and pointers are always move-only.
s1: make [#unique string!] "Hello"
s2: s1 ; ownership moves to s2
print s1 ; compile error: 's1' used after move
's1' used after move
The same holds for ports, errors, dicts, maps, binary! and
pointer-like values, which are always move-sensitive.
Recovering ownership
Assigning a fresh value makes a moved binding owned again (the binding
must be declared mutable to be reassigned):
s1: mutable make [#unique string!] "Hello"
s2: s1 ; s1 moved away
s1: make [#unique string!] "Fresh" ; s1 owned again
print s1 ; ok
Borrowing avoids the move
A borrowed parameter takes a view, so even a #unique value
keeps its owner:
greet: func [
"Print a borrowed string."
:name [string!] "The borrowed string to print; the caller keeps it."
] [print name]
msg: make [#unique string!] "hi"
greet :msg ; borrowed
print msg ; still owned
print is itself a borrowing operation, so printing a binding
never consumes it.
Branches
If a binding is moved in any branch, it is considered moved afterward. The checker does not know which branch ran:
consume: func [
"Print a message, taking ownership of it."
msg [#unique string!] "The message to print; ownership moves into the function."
] [print msg]
s1: make [#unique string!] "Hello"
either ready [
consume s1 ; moves s1
] [
print s1 ; ok in this branch
]
print s1 ; error: 's1' used after move
Mutability is enforced too
s: make string! "hi"
s/0: #"H" ; error: 's' is not mutable (B3003)
s: make [#mutable string!] "hi"
s/0: #"H" ; ok
Continue with Memory & sharing for
#unique, stack vectors, series capabilities and views.
Error handling
Recoil reports problems at three layers: parse/type errors
and borrow-checker errors at compile time, and
runtime errors through a structured error!
value.
The error! value
e: make error! "something went wrong"
Automatic runtime checks
Division by zero, integer overflow, and out-of-bounds indexing set a
thread-local error state instead of crashing. Check the global state with
the zero-arity errored?, or test a specific value with
error?:
divide: func [
"Divide one signed 32-bit integer by another."
a [i32!] "The dividend."
b [i32!] "The divisor; zero sets a runtime error."
return: [i32!] "The quotient of a and b."
] [
a / b
]
result: divide 10 0 ; a constant 10 / 0 is rejected at compile time
if errored? [print "a math error occurred"]
if error? e [print "this specific value is an error"]
Cleanup with defer
defer runs a block when the function exits (LIFO).
defer/error runs only when an error is set.
fp: make port! file/open %data.txt
defer [file/close fp] ; always runs on exit
defer/error [print "cleaning up after failure"]
Live and sticky error slots
Errors travel through two thread-local slots rather than result types.
- The live slot holds the most recent error. It is
cleared on function entry, by
errored?, and on entry to a runtime function. An error you ignore therefore stays live until one of those, instead of being erased by the next successful read. - The sticky slot is set only by arithmetic faults (overflow, divide by zero) and is not cleared by ordinary operations. It exists so that an unhandled math error survives until the program ends.
If two fallible fragments in one expression both fail, such as
a / 0 + b / 0, one of the two errors is left in the slot but
which one is unspecified. Split the expression across statements when you
need to know.
errored? consumes the error
errored? takes no operand and clears both slots:
checking an error counts as handling it. A second check returns false.
error? takes exactly one operand and only tests that value.
a: make i32! 2147483647
b: make i32! a + 1
if errored? [print "caught"]
either errored? [print "again"] [print "consumed"]
This prints caught, then consumed.
Returning an error!
A function that can fail may return an error! where its
return type allows; the caller tests the result with error?:
try-divide: func [a [i32!] b [i32!] return: [i32!]] [
if b = 0 [
return make error! "zero"
]
return a / b
]
result: make i32! try-divide 10 0
if error? result [print 1]
defer/error as a failure guard
defer/error fires on return only when the live slot holds an
error at that moment, which makes it the place for rollback. Plain
defer blocks run last-registered first.
with-error: func [return: [i32!]] [
defer/error [print 1]
return make error! "oops"
]
without-error: func [return: [i32!]] [
defer/error [print 9]
return 0
]
The unhandled math-error trap
An overflow that returns 0 would be indistinguishable from a
real result, so the generated main ends by reading the sticky slot.
An unhandled overflow or divide by zero prints
error: ... (code N) to stderr and exits with status 1; one cleared
with errored? exits 0. Only math errors trap: port, parse, user and
FFI errors are ordinary conditions programs handle themselves. Exported
library entry points are not trapped either, because the embedding caller owns
error inspection.
Error categories
| Range | Category | Examples |
|---|---|---|
| 300–399 | Math | division by zero, integer overflow |
| 700–701 | Series | index out of bounds, past end |
| 500 | FFI | null pointer |
| 800–841 | Port | TCP, TLS, HTTP and DNS failures |
| 850–853 | Parse / FST | no match, unexpected end, port read failure |
| 860 | Channel | send on a closed channel, receive on a closed and drained one |
| 900+ | User | custom application errors (make error!) |
The full taxonomy and the diagnostics format live in the Reference.