comptime: compile-time evaluation (Zig-style)
`comptime "<source>"` runs catscript inside the compiler, in an embedded
VM created lazily and shared for the whole compilation:
- expression position: the result value is baked into the program as a
constant (`local x = comptime "return 6 * 7"` -> x is 42).
- statement position: runs for side effects (compile-time globals) and
the value is discarded.
- errors raised at compile time surface as normal compile errors
("line N: comptime: boom").
- the embedded VM is freed at the end of compilation.
This reuses the existing interpreter, which is why it is cheap: the
language already has a VM to embed. tests/comptime.cat + suite block.
Suite 141 -> 144.
This commit is contained in:
1 parent
96e8f516cc
commit
95f3823acf
5 files changed
+100
-1
No files matched your search
@@ -0,0 +1,17 @@
|
||||
-- tests/comptime.cat -- compile-time evaluation (Zig-style).
|
||||
--
|
||||
-- `comptime "<source>"` runs catscript IN the compiler, in an embedded
|
||||
-- VM, and uses the result. In an expression it becomes a constant; as a
|
||||
-- statement it runs for side effects (compile-time globals).
|
||||
|
||||
-- expression position: the value is baked into the program as a constant
|
||||
local x = comptime "return 6 * 7"
|
||||
print("ct-expr:", x)
|
||||
|
||||
-- compile-time string building
|
||||
local s = comptime "return \"hi \" .. \"there\""
|
||||
print("ct-text:", s)
|
||||
|
||||
-- statement position: side effects, discard the value
|
||||
comptime "done = true"
|
||||
print("after-ct")
|
||||
@@ -254,6 +254,11 @@ esac
|
||||
|
||||
# ---- self-hosted front-end (written in catscript) -------------------
|
||||
|
||||
out=`$BIN tests/comptime.cat`
|
||||
check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`"
|
||||
check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`"
|
||||
check "comptime-stmt" "after-ct" "`echo "$out" | sed -n 3p`"
|
||||
|
||||
out=`$BIN tests/types.cat`
|
||||
check "types-ok" "ok: 42 3.5 hi true" "`echo "$out" | sed -n 1p`"
|
||||
check "types-widen" "widen: 7" "`echo "$out" | sed -n 2p`"
|
||||
|
||||
Reference in new issue
Block a user