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:
Minus committed 2026-11-18 17:17:20 +00:00
1 parent 96e8f516cc
commit 95f3823acf
5 files changed
+100 -1

No files matched your search

+1
View File
@@ -30,6 +30,7 @@ enum CAT_LEXER_Kind {
CAT_LEXER_TOK_RAISE, CAT_LEXER_TOK_USE, CAT_LEXER_TOK_CLASS, CAT_LEXER_TOK_RAISE, CAT_LEXER_TOK_USE, CAT_LEXER_TOK_CLASS,
CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS, CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS,
CAT_LEXER_TOK_IS, CAT_LEXER_TOK_IS,
CAT_LEXER_TOK_COMPTIME,
/* symbols */ /* symbols */
CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR, CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR,
CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET, CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET,
+75
View File
@@ -25,6 +25,9 @@
#include "cat/compiler.h" #include "cat/compiler.h"
#include "cat/lexer.h" #include "cat/lexer.h"
#include "cat/error.h" #include "cat/error.h"
#include "cat/vm.h"
#include "cat/stdlib/stdlib.h"
#include "cat/stdlib/build.h"
#include "cat/types/int.h" #include "cat/types/int.h"
#include "cat/types/float.h" #include "cat/types/float.h"
#include "cat/types/ascii_text.h" #include "cat/types/ascii_text.h"
@@ -59,6 +62,7 @@ typedef struct {
int brk_n[16]; int brk_n[16];
int nloops; int nloops;
int repl; /* REPL mode: a lone expression is echoed */ int repl; /* REPL mode: a lone expression is echoed */
CAT_VM_State *ct_vm; /* embedded VM for `comptime` (lazy) */
} Compiler; } Compiler;
static void err_at(Compiler *c, int line, const char *fmt, ...) static void err_at(Compiler *c, int line, const char *fmt, ...)
@@ -274,6 +278,42 @@ static CAT_TYPES_TYPE_Type *literal_type(Compiler *c)
} }
} }
/* `comptime "<source>"` -- evaluate catscript at COMPILE time, in an
* embedded VM created lazily and shared for the whole compilation. The
* result value is used directly (as a constant in an expression, or
* discarded as a statement). Compile-time errors are reported as normal
* compile errors. */
static CAT_VALUE_Value *comptime_run(Compiler *c, const char *src, int line)
{
CAT_ERROR_Error e;
CAT_BYTECODE_Function *fn;
CAT_VALUE_Value *out = NULL;
int rc;
if (c->ct_vm == NULL) {
c->ct_vm = cat_vm_new();
if (c->ct_vm == NULL) {
err_at(c, line, "comptime: cannot start VM");
return NULL;
}
cat_stdlib_stdlib_install(c->ct_vm);
cat_stdlib_build_install(c->ct_vm);
}
cat_error_clear(&e);
fn = cat_compiler_compile(src, &e);
if (fn == NULL) {
err_at(c, line, "comptime: %s", e.message);
return NULL;
}
rc = cat_vm_run(c->ct_vm, fn, &out);
cat_bytecode_function_free(fn);
if (rc != 0) {
err_at(c, line, "comptime: %s", c->ct_vm->err.message);
return NULL;
}
return out;
}
/* Compile `function (params) body end` starting at `function`. */ /* Compile `function (params) body end` starting at `function`. */
static int compile_function_literal(Compiler *c, const char *name) static int compile_function_literal(Compiler *c, const char *name)
{ {
@@ -426,6 +466,26 @@ static void primary(Compiler *c)
expect(c, CAT_LEXER_TOK_RBRACE, "'}'"); expect(c, CAT_LEXER_TOK_RBRACE, "'}'");
break; break;
} }
case CAT_LEXER_TOK_COMPTIME: {
/* `comptime "<source>"` in an expression position: run the source
* now and use its result value as a constant. Only string literals
* are accepted as the source (simple and predictable). */
CAT_VALUE_Value *v;
next(c);
if (!check(c, CAT_LEXER_TOK_STRING)) {
err_at(c, t.line, "comptime expects a string literal");
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, t.line);
break;
}
v = comptime_run(c, c->tok.text, t.line);
next(c);
if (v == NULL) {
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, t.line);
break;
}
emit(c, CAT_BYTECODE_OP_CONST, add_const_owned(c, v), 0, t.line);
break;
}
case CAT_LEXER_TOK_NAME: { case CAT_LEXER_TOK_NAME: {
char name[256]; char name[256];
int slot; int slot;
@@ -1214,6 +1274,18 @@ static void block(Compiler *c)
next(c); next(c);
continue; continue;
} }
/* `comptime "src"` as a STATEMENT: run for side effects and discard. */
if (check(c, CAT_LEXER_TOK_COMPTIME)) {
int line = c->tok.line;
next(c);
if (check(c, CAT_LEXER_TOK_STRING)) {
comptime_run(c, c->tok.text, line);
next(c);
accept(c, CAT_LEXER_TOK_SEMI);
continue;
}
/* otherwise fall through: `stat` reports a clear error */
}
stat(c); stat(c);
if (c->failed) if (c->failed)
break; break;
@@ -1252,6 +1324,9 @@ CAT_BYTECODE_Function *cat_compiler_compile_mode(const char *source,
block(&c); block(&c);
emit(&c, CAT_BYTECODE_OP_RETURN0, 0, 0, c.tok.line); emit(&c, CAT_BYTECODE_OP_RETURN0, 0, 0, c.tok.line);
if (c.ct_vm != NULL)
cat_vm_free(c.ct_vm);
if (c.failed) { if (c.failed) {
cat_bytecode_function_free(fn); cat_bytecode_function_free(fn);
return NULL; return NULL;
+2 -1
View File
@@ -27,6 +27,7 @@ static const struct kw g_keywords[] = {
{ "extends", CAT_LEXER_TOK_EXTENDS }, { "extends", CAT_LEXER_TOK_EXTENDS },
{ "interface", CAT_LEXER_TOK_INTERFACE }, { "interface", CAT_LEXER_TOK_INTERFACE },
{ "is", CAT_LEXER_TOK_IS }, { "is", CAT_LEXER_TOK_IS },
{ "comptime", CAT_LEXER_TOK_COMPTIME },
{ "false", CAT_LEXER_TOK_FALSE }, { "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR }, { "for", CAT_LEXER_TOK_FOR },
{ "function", CAT_LEXER_TOK_FUNCTION }, { "function", CAT_LEXER_TOK_FUNCTION },
@@ -290,7 +291,7 @@ const char *cat_lexer_kind_name(int kind)
"for", "function", "if", "in", "local", "nil", "not", "for", "function", "if", "in", "local", "nil", "not",
"or", "repeat", "return", "then", "true", "until", "while", "or", "repeat", "return", "then", "true", "until", "while",
"yield", "try", "except", "raise", "use", "class", "extends", "yield", "try", "except", "raise", "use", "class", "extends",
"interface", "implements", "is", "interface", "implements", "is", "comptime",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=",
"<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",", "<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",",
".", ":", "::", "..", "->" ".", ":", "::", "..", "->"
+17
View File
@@ -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")
+5
View File
@@ -254,6 +254,11 @@ esac
# ---- self-hosted front-end (written in catscript) ------------------- # ---- 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` out=`$BIN tests/types.cat`
check "types-ok" "ok: 42 3.5 hi true" "`echo "$out" | sed -n 1p`" check "types-ok" "ok: 42 3.5 hi true" "`echo "$out" | sed -n 1p`"
check "types-widen" "widen: 7" "`echo "$out" | sed -n 2p`" check "types-widen" "widen: 7" "`echo "$out" | sed -n 2p`"