Three forms
Recoil can run host Rebol code at compile time, and can embed the Rebol interpreter at runtime.
| Form | Evaluation | C code emitted | Links Rebol |
|---|---|---|---|
comptime [body] | parse time, evaluated immediately | literal value baked into the C | no |
compfunc [spec] [body] | parse time, registered as a Rebol function | not emitted | no |
rebol [body] | runtime | a call to __recoil_rebol_eval_* | yes |
comptime
Evaluates a Rebol block during parsing; the normalized result is substituted into the source as a literal. It can appear anywhere an expression is expected.
x: make i32! comptime [1 + 2 + 3] ; 6, decided at parse time
print x ; prints 6
hostname: comptime [
call/output "hostname" out: ""
trim/tail out
]
The block has full access to the host Rebol environment (file system, environment variables, …).
Result types
Passed through: integer! (→ i32!/i64! by size), decimal! (→ f64!), string!, char!, file!, none!, words, get-words and paths (as identifier references), and a block! holding exactly one expression, which is parsed and normalized. Anything else raises P1301; a multi-expression block raises P1300.
x: comptime [make object! []] ; P1301: unsupported result type
The evaluated body may contain several statements; only its final result is substituted:
x: make i32! comptime [ ; evaluates to 2
a: 1
a + 1
]
A returned block must describe a single Recoil expression. Returning multiple bindings is rejected:
x: make i32! comptime [copy [a: 1 b: 2]] ; P1300
An error raised inside the body surfaces as P1305 (COMPTIME ERROR: boom).
compfunc
Defines a Rebol function that exists only at compile time. It is callable from comptime blocks and from Recoil source; no runtime code is emitted for it — only its result survives into the generated C.
double: compfunc [x] [x * 2] ; define at compile time
y: make i32! double 21 ; called at compile time → 42
print y ; the C contains "= 42;", no call
quad: compfunc [x] [double (double x)] ; compfuncs can call compfuncs
z: make i32! quad 10 ; 40
specis a Rebol function spec (words only, no type constraints);bodyis arbitrary Rebol.- A call consumes exactly the number of argument expressions declared by its spec; extra expressions become subsequent statements. Surplus expressions are never counted as arguments, so
P1303does not fire for them; a surplus bare literal that is not the last statement isT4108. An unknown compfunc isP1302. - An error inside the body surfaces as
P1304(COMPTIME ERROR: in 'failer': boom). - Compfuncs are registered per compilation and cleared between compilations.
- Words you set in the body are local to the call, so carry state in the Recoil program, not in the body.
- A compfunc is visible to the module that declares it, and to a module that lists it in an import from a module that exports it (
Exports: [two],Imports: [lib [two]]). Another module’s private compfunc is not visible and does not replace a function of the same name; using it gives warningP1308and then the usual undeclared-name error. - A compfunc body or
comptimeblock calls the compfuncs its module can see by bare name. If one has the name of a Rebol function (find), it is called instead of the Rebol one inside that module’s bodies, with warningP1309. - A compfunc call is audited and policed (
--fail-on-comptime-in-untrusted) against the module and file that declare it, not the call site. - Do not name a compfunc like a compiler-provided helper (
macro-expr,macro-error,reflect-*): that isP1307.
Macros
A compfunc can return more than a value. It can return Recoil AST (macro-expr) or a block of Recoil source, and the result replaces the call. Whatever it produces then goes through type checking, the borrow checker, IR lowering and code generation like code you wrote by hand, so no call to the macro survives into the generated C.
| Body returns | Meaning |
|---|---|
| a scalar | the literal value is spliced in |
a block! from a comptime | parsed as one expression (P1300 otherwise) |
a block! from a compfunc | source, parsed where the call stands as a sequence of ordinary forms; it may declare (see below) |
macro-expr ast | ast is already AST and is spliced in without re-parsing |
Raw arguments: #raw
By default a compfunc receives its arguments already parsed, and a compile-time argument must be a value the compiler can compute. A leading #raw in the spec passes each argument as the source tokens it consumed, unevaluated. The call still consumes exactly as many expressions as the spec has parameters.
tok-count: compfunc [#raw expr] [
reduce [length? expr]
]
y: make i32! tok-count 1 + 2 ; expr is the 3-token span [1 + 2]
print y ; 3
- A lit-word parameter (
'name) takes exactly one token (a word, block, paren or literal) instead of an expression. Use it for a name that may also be a function: withcompfunc [#raw 'what body],describe show [x: i64!]handswhatthe wordshowandbodythe block. - A compfunc call or
comptimeblock inside a#rawargument does not run while the argument is captured; its tokens are handed over as written and run when your macro parses them.
Resolved types: #typed
Next to #raw, #typed declares one extra trailing parameter that receives a block of resolved types, one per raw argument. Only a module-top-level binding or a function-local binding with an inferrable type resolves; any other argument gets none. The call site does not consume the synthetic parameter.
x: make [#flexible vector! [i32!]] none
is-flex: compfunc [#raw #typed w types] [
either all [block? types/1 not empty? types/1 types/1/1 = #flexible] [
[1]
] [
[0]
]
]
y: make i32! is-flex x
print y ; 1
Returning AST: macro-expr
macro-expr wraps already-built AST. Because a plain argument has to be computable at compile time, a macro that wraps runtime variables takes its arguments #raw and builds the AST around the tokens it captured:
double-it: compfunc [#raw e] [macro-expr reduce ['* e/1 2]]
n: 21
y: make i32! double-it n ; expands to n * 2
print y ; 42
Without #raw, double-it n would try to evaluate n at compile time and fail with P1304. With a literal argument the plain form works: mk-double: compfunc [x] [macro-expr reduce ['* x 2]], then mk-double 21.
- A
macro-exprmacro is expression-only. Statement AST (a declaration, for example) isP1301, as is a wrapper that carries noast. To declare, return a block instead. - The AST shape is the compiler’s internal one, not a stable interface, and it can change between releases.
- The built-ins
rejoin,map,filterandfoldare macros of this kind. The combinators expand to an inlineforeachand take a get-word naming a plain declared function (filter nums :even?), not a lambda.
Expanding to declarations: a block result is source
A compfunc that returns a block returns source. The block is parsed where the call stands, in the parser’s current state, as a sequence of ordinary forms; what a hand-written form could do, an expansion can do. This one declares a struct and a getter per field:
record: compfunc [#raw 'name fields] [
out: compose/only [(to-set-word first name) make struct! (first fields)]
foreach [fname ftype] first fields [
append out reduce [
to-set-word append copy "get-" form to-word fname 'func
reduce [to-word 'p reduce [first name] to-set-word 'return reduce [to-word 'i64!]]
reduce ['return to-path reduce [quote p to-word fname]]
]
]
out
]
record point! [x: i64! y: i64!] ; declares point!, get-x and get-y
print get-x make point! [x: 3 y: 4] ; 3
- Declarations in the expansion (
func,make struct!,generic, …) are registered like source and usable after the call. They are spliced in before the form that holds the call. - The value of the call is the last expression of the expansion. An expansion with no expression has the value
0, which is harmless as a top-level form.[x: 5]or[print 1]as the last form gives0, unlike a paren(x: 5), which yields 5. - Functions and generic structs of one expansion are found before it is parsed, so generated functions may call each other in any order. Using a generated name before the macro call is not supported and is not diagnosed yet: it compiles to a reference to an unknown name.
- Expansions are parsed in order, so reflection sees what earlier expansions declared.
- Names the module keeps private are renamed in the returned tokens the same way as in the module’s source, so a macro may name its own module’s private type. A type an expansion declares keeps a plain name; two modules whose macros declare the same name are
M2000. - A diagnostic raised while an expansion is parsed ends with
(in expansion of 'name'). - Expansions nest (a macro may return a call of another, or of itself) up to 32 levels (
P1784) and may return at most 20000 tokens (P1785). A result that does not parse as forms isP1786. - Where only a value can be kept (a
whilecondition, a struct field value, aparserule paren, the right operand ofand/or), an expansion may add nothing but its value: more isP1787. - Inside a function body an expansion is executable code only: its statements run before the statement that holds the call. It may not declare a type or callback wrapper (
P1788), and a nestedfuncisP1783as for handwritten source.
Hygiene: gensym
There is no automatic hygiene: a name the macro introduces is an ordinary name of the surrounding code. gensym 'stem returns a fresh word (__gensym_stem_N) for a local the macro introduces, so it cannot collide with the caller’s names (a candidate already bound in scope is skipped). The stem may hold letters, digits, - and _ only. Call it once per local and reuse the word.
swap-vars: compfunc [#raw 'a 'b] [
t: gensym 'tmp
compose [
(to-set-word t) (first a)
(to-set-word first a) (first b)
(to-set-word first b) (t)
]
]
f: func [return: [i64!]] [
tmp: 5 ; the caller’s own tmp is untouched
x: mutable 1
y: mutable 2
swap-vars x y
print tmp ; 5
print x ; 2
print y ; 1
return 0
]
f
Reflection: reading declared types and functions
A compfunc can look up what the program has declared so far and generate code from it. The helpers return plain data, or none for a name that is not declared.
| Helper | Returns |
|---|---|
reflect-kind 'name | 'struct, 'enum, 'sum, 'alias, or none |
reflect-struct 'name | the fields in declaration order: objects with name and type |
reflect-enum 'name | the variants: objects with name and value |
reflect-sum 'name | the variants: objects with name and fields (name/type objects) |
reflect-alias 'name | a constrain alias: an object with name, base and predicate |
reflect-function 'name | a func: an object with name, params (name, type, borrowed?) and return-type |
A type is a word (i64!) or, for a parameterised type, a block ([vector! [i64!]]), in the parser’s resolved form rather than the exact source. This macro sums every i64! field of a struct:
point!: make struct! [px: i64! py: i64! label: string! pz: i64!]
; sum-fields p point! expands to p/px + p/py + p/pz
sum-fields: compfunc [#raw v t] [
terms: copy []
foreach field reflect-struct t/1 [
if field/type = 'i64! [append/only terms reduce ['path-get v/1 field/name]]
]
acc: first terms
foreach term next terms [acc: reduce ['+ acc term]]
macro-expr acc
]
p: make point! [px: 4 py: 5 label: "z" pz: 30]
print sum-fields p point! ; 39
Take the type name #raw so the compfunc receives the word instead of evaluating it. To name a function (whose call would otherwise consume the tokens after it), pass a lit-word and convert: reflect-function to-word t/1 for describe 'inc.
- Reflection sees only what the parser has read before the call. A name declared later is
none. A generic struct template isnone(it is not a type), but a used instance such astwin__gs__i64_t__f64_t!is a struct. - Reflection does not enforce import visibility: private types and functions, and types a selective import leaves out, can be reflected (private types under their qualified name,
mod__name__priv!). - The data is a deep copy in a shape of its own; changing it affects nothing outside your compfunc.
- A field typed with a
constrainalias reports the expansion, so the alias name is lost; attributes stay inside the type ([#unique string!]), sofield/type = 'string!does not match a#uniquestring field. noneis silent: looping over it does nothing, and a macro that getsnonefor a forward reference or misspelled name usually fails with a genericP1304. Test for it:unless fields [macro-error 'M1001 "unknown type"].- Reflect a
constrainalias right after declaring it; the parser forgets it once it has parsed a struct literal or a compile-time result. - Compfuncs are skipped under
--lsp-parse-only, so reflection does not run there.
Your own diagnostics: macro-error
A macro that rejects its input should say so with a code of its own, not a generic P1304. macro-error raises a diagnostic with a code you choose in M1000 to M1999 and a message you write.
check-pos: compfunc [x y] [
if x < 0 [macro-error/arg 'M1001 "x must be positive" 1]
if y < 0 [macro-error/arg 'M1002 "y must be positive" 2]
x + y
]
check-pos 1 -5 ; COMPTIME ERROR M1002: y must be positive
macro-error code messageanchors the diagnostic at the compfunc call.macro-error/arg code message nrecords the first token of thenth argument of that call as the location; the command line prints only the message today, so the location is for tools that read the diagnostic object.- The code must be a plain capitalised word,
M1followed by three digits. Any other code (a string, a lower-case word,M2000, a built-inPcode), a message that is not a string, or an argument number the call does not have isP1306instead. - Inside a
comptime [...]block there is no call to count in, so the diagnostic is anchored at the block and/argis ignored. - The range
M1000toM1999belongs to macro authors; the compiler never assigns a code in it. Pick codes per macro library and document them there. - An ordinary Rebol error (
do make error! "...") is stillP1304orP1305.
Macro limits
Still deferred to 0.13: automatic hygiene (gensym is the manual tool), AST re-entry, declaring a type or callback wrapper from an expansion inside a function body (P1788), and inline lambda arguments to map, filter and fold. Under --lsp-parse-only a macro call is not expanded (P1311), so code that uses names the macro would have declared can fail with an unrelated error. The security audit also scans a block a macro returns: if it contains #include, #link, #extern, #export, foreign, callback, c-fn!, rebol, comptime, compfunc or an unsafe/ path, a macro-expansion event is emitted, attributed to the module and file that declared the macro. Such expansions are allowed; the event makes them reviewable.
rebol (runtime)
Embeds a Rebol block that runs at runtime through the host interpreter. Unlike comptime it emits a C call and requires linking the Rebol runtime. It needs an explicit target type — a typed binding, make or as:
x: make i32! rebol [1 + 1]
y: as f64! rebol [3.14]
z: make string! rebol [{hello}]
if true [rebol ["abc"]] ; T4001: requires explicit target type
p: make c-pointer! rebol [1 + 1] ; T4002: cannot target this type
| Target type | C function called |
|---|---|
logic! | __recoil_rebol_eval_logic |
i8! i16! i32! i64! | __recoil_rebol_eval_i64 (cast) |
u8! u16! u32! u64! | __recoil_rebol_eval_u64 (cast) |
f32! f64! | __recoil_rebol_eval_f64 |
char! | __recoil_rebol_eval_char |
string! | __recoil_rebol_eval_string |
c-string! | __recoil_rebol_eval_c_string |
none! | __recoil_rebol_eval_none (default) |
When rebol is used the compiler adds the embed header, finds a Rebol static or shared library and appends the link flag. If none is found, P1705 (static) or P1706 (shared) is raised. Choose with --rebol-static (default) or --rebol-shared.
Security & tooling
comptime and compfunc run arbitrary Rebol inside the compiler process during parsing — the same privilege model as Rust proc macros or a C build.rs.
--fail-on-comptime-in-untrustederrors if comptime/compfunc runs in an untrusted dependency tier.--security-audit FILEemits structured events for everycomptime,compfuncandrebolsite.--lsp-parse-only(with--transpile) skips execution:0is substituted and warningP1310(comptime) orP1311(compfunc) is emitted, so downstream analysis may be incomplete. It exists for editors and linters that should not run untrusted code.
See CLI & Targets and Packages.
Diagnostic codes
| Code | Severity | Description |
|---|---|---|
P1300 | error | comptime result block must contain a single expression |
P1301 | error | unsupported compile-time result type, or a macro-expr that is malformed or returns statement AST |
P1302 | error | unknown compfunc |
P1303 | error | wrong compfunc arity |
P1304 | error | compfunc body raised an error |
P1305 | error | comptime block body raised an error |
P1306 | error | macro-error misused: invalid code, message not a string, or /arg names an argument the call does not have |
P1307 | error | a compfunc named like a compiler-provided macro helper |
P1308 | warning | a name is a compfunc of another module that is not exported to and imported by this one |
P1309 | warning | a compfunc has the name of a Rebol function and replaces it inside its module’s bodies |
P1783 | error | a func, generic func or c-fn! declared inside a function body (including in a macro expansion there) |
P1784 | error | macro expansions nest more than 32 levels |
P1785 | error | a macro returned more than 20000 tokens |
P1786 | error | a macro’s result is not valid source |
P1787 | error | a macro expansion adds statements or declarations where only a value is kept |
P1788 | error | a macro expansion declares a type or callback wrapper inside a function body |
M1000–M1999 | error | reserved for diagnostics a macro raises with macro-error |
P1310 | warning | comptime skipped under --lsp-parse-only |
P1311 | warning | compfunc skipped under --lsp-parse-only |
T4001 | error | rebol [...] requires an explicit target type |
T4002 | error | rebol [...] cannot target the given type |
P1705 | error | missing Rebol static library |
P1706 | error | missing Rebol shared library |