Compare commits

..
9 Commits
Author SHA1 Message Date
Minus 77ea433215 native x86-64 backend (pluggable, per-opcode lowering)
A second backend that lowers each bytecode instruction to a machine-code
call into a runtime helper, with control flow as real branches.

- cat/backend/x86_64_glue.c: one helper per opcode, mirroring cat/vm.c
  exactly (frame lifecycle, arith, cmp, attr/idx, call/callmethod, is,
  next/fornext, try/raise).  Helpers use the SysV convention (f in rdi,
  a/b/c in rsi/rdx/rcx) and return 0/1/-1.
- cat/backend/x86_64.c: emits AT&T assembly (one labelled block per
  instruction, one call per helper, real jumps for JUMP/JUMPIF/JUMPIFNOT/
  FORNEXT/RETURN, an .Lonerror block that resumes try handlers), plus a
  small generated _main.c that rebuilds the bytecode and boots the VM.
  Builds with as + cc linked against libcatscript.a.
- generators are not lowered: their prototype carries no nat_entry, so
  the VM runs them (their bytecode is rebuilt by the generated main), and
  the emitted code simply falls back to the interpreter.
- cat_vm_exec_closure dispatches to a prototype's nat_entry when present.
- tests: native-vs-interpreter equivalence check.  Suite 155 -> 156.

Verified: hello, control, classes, generators, arith, errors, text, oop,
slots, reflect, toml, files, ffi all match the interpreter natively.
2026-11-18 20:19:54 +00:00
Minus 1832326a3d pluggable backend registry + generalized CLI
- cat/backend/backend.h: the CAT_BACKEND_Backend contract (name,
  description, native flag, emit(), compile()).
- cat/backend/registry.c: the single table of targets; cat_backend_find/
  default/count/at.  Adding a backend = one file + one line here.
- cat/backend/c.c: exposes cat_backend_c_backend(); body unchanged.
- cat/backend/x86_64.c: the native x86-64 backend descriptor (lowering
  stubbed for now).
- main.c: --backend <name> --emit/--build, --list-backends; --emit-c and
  --build stay as shortcuts for the default (c) backend.
- Makefile: build the new files.  Suite 151 -> 155.
2026-11-18 19:42:04 +00:00
Minus 841c445a05 generics: <T, ...> type parameters on classes and interfaces
- parse_type_params(): accepts an optional `<T, U, ...>` list after a
  class/interface/trait name and records the names.
- The declaration is tagged `__generic` with the comma-joined parameter
  list (e.g. "T" or "K,V").  Parameters are an erasure model: they are
  compile-time only, so a generic class is an ordinary class at runtime.
- tests/generics.cat + suite: generic class, generic interface, a class
  implementing a generic interface, and a two-parameter class.
  Suite 152 -> 155.
2026-11-18 17:39:29 +00:00
Minus 33a1152958 C backend: ahead-of-time compilation to a native binary
- new cat/backend/c.{h,c}: lower a compiled CAT_BYTECODE_Function to a
  self-contained C translation unit that rebuilds the bytecode and runs
  it on the catscript runtime.  The tree is emitted in pre-order with
  forward declarations; constants (int/float/text/bool) are recreated by
  the matching constructors; jumps keep their absolute targets.
- Makefile: also build libcatscript.a (all objects but main.o) so an AOT
  program links the runtime without clashing on `main`.
- main.c: `--emit-c <file>` prints the generated C; `--build <file> <out>`
  emits it, invokes the system `cc`, and produces the executable.
- tests/aot.cat + suite: the native binary's stdout must equal the
  interpreter's (arithmetic, recursion, objects, interfaces, `is`,
  concat, comparisons).  Suite 151 -> 152.

The backend is faithful by construction: it lowers the very bytecode the
interpreter runs, so native output matches the interpreter exactly
(including current language quirks, e.g. upvalues and `try`/`catch`).
2026-11-18 17:37:25 +00:00
Minus 70728093ef traits + Sized(): default methods and the sized marker
- `trait` keyword: like `interface`, but tagged `__trait`; its methods
  carry default bodies.  A class that `implements` a trait has those
  bodies mixed in (a class's own method wins), then is checked
  structurally -- so the mix-in runs BEFORE `__implements_check`.
- runtime `__trait_mixin(cls, trait)`: copies a trait's default methods
  into the class (skipping `__*` meta keys and existing members).
- `Sized` -- the marker object for "layout known at compile time"; every
  concrete value satisfies it, so `x is Sized` / `implements(x, Sized)`
  hold and signatures can name it (`buf : Sized()`).
- tests/traits.cat + suite: default method, override, `is`, and Sized.
  Suite 144 -> 151.
2026-11-18 17:18:58 +00:00
Minus 95f3823acf 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.
2026-11-18 17:17:20 +00:00
Minus 96e8f516cc type checker, phase 2: return hints checked
- parse the `-> T` return hint into the function context (was consumed
  and dropped).
- `return <literal>` is checked against the declared return type: a
  concrete mismatch raises at compile time.  Opaque/unknown returns and
  non-literal expressions stay permissive.
- tests/types.cat + suite: a valid `-> int` function.  Suite 140 -> 141.
2026-11-18 17:15:42 +00:00
Minus 48b1b84ea6 type checker, phase 1: hints are checked where concrete
First slice of the static-typing foundation (traits/generics/Sized()
will build on it).  Typing stays structural and permissive: an unknown
or opaque name is never a rejection, so existing programs keep working.

- new module cat/types/type.{h,c}: compile-time-only descriptors
  (int/float/bool/text/empty/object/function/list/memory/any + interned
  named/opaque types), with equal/assignable/join and int->float widening.
- compiler: skip_type_hint -> parse_type_hint, which returns the type of
  the first identifier in a hint (the rest of a balanced hint is still
  consumed and ignored, so `cbyte[sentinel_sized<0>]` parses).
- `local NAME : T = <literal>` is checked: assigning a known concrete
  literal of the wrong kind to a known concrete type raises at compile
  time ("line N: cannot assign text to int").  Unknown/opaque names and
  non-literal expressions stay permissive.
- FuncCtx tracks a declared/inferred type per local slot.
- tests/types.cat + suite block: ok hints, int->float widening, opaque
  names accepted, and a wrong assignment rejected.  Suite 136 -> 140.
2026-11-18 16:56:40 +00:00
Minus b945182739 interface + structural is: runtime-checked interfaces
Add nominal interface declarations with structural, runtime checking
(the owner asked for the operator AND the runtime check).

- lexer: `interface` and `is` are keywords; `implements` is a soft
  keyword (matched by text in the class clause) so the `implements()`
  stdlib function is not shadowed.
- `interface NAME [extends BASE] <function m() end> end` builds a table
  tagged `__interface`; members name the required methods (with an
  optional default body, shared via `__index`). Interface inheritance
  follows `__index`.
- class: `class C [extends B] [implements I, ...]` -- after the class
  global is set, `__implements_check` runs and raises if the class does
  not satisfy each declared interface.
- new opcode `IS` (`obj is iface`): structural membership test, and it
  degrades to an exact type (vtable) match when the right side is not an
  interface, so `x is SomeClass` reads naturally. Backed by
  `cat_value_is()`.
- stdlib: `implements(obj, iface)` (the same test as a function).
- tests/interface.cat + suite block: interface satisfaction, interface
  inheritance, duck typing (no `implements` needed), and a missing
  method failing. Suite 130 -> 136, all green.
2026-11-18 15:56:10 +00:00
28 changed files with 2856 additions and 29 deletions

No files matched your search

+16 -1
View File
@@ -21,6 +21,7 @@ LDLIBS ?= -lm -lffi -ldl
BUILD := build/catscript
BIN := $(BUILD)/catscript
LIB := $(BUILD)/libcatscript.a
SRCS := \
src/main.c \
@@ -31,7 +32,12 @@ SRCS := \
src/cat/compiler.c \
src/cat/vm.c \
src/cat/module.c \
src/cat/backend/c.c \
src/cat/backend/x86_64.c \
src/cat/backend/x86_64_glue.c \
src/cat/backend/registry.c \
src/cat/types/empty.c \
src/cat/types/type.c \
src/cat/types/bool.c \
src/cat/types/number.c \
src/cat/types/int.c \
@@ -56,6 +62,11 @@ SRCS := \
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
# The runtime archive is every object EXCEPT the CLI entry point, so an
# ahead-of-time compiled program can link the runtime without clashing
# on `main`.
LIBOBJS := $(filter-out $(BUILD)/main.o,$(OBJS))
.PHONY: help all test clean examples
# Default goal: print the help.
@@ -66,12 +77,16 @@ help:
@echo " make clean - remove build artifacts"
@echo " make help - show this help (default goal)"
all: $(BIN)
all: $(BIN) $(LIB)
$(BIN): $(OBJS)
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)
$(LIB): $(LIBOBJS)
@mkdir -p $(dir $@)
$(AR) rcs $@ $(LIBOBJS)
$(BUILD)/%.o: src/%.c
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
+47
View File
@@ -0,0 +1,47 @@
/*
* cat/backend/backend.h -- the pluggable backend contract.
*
* Naming rule: symbols here are cat_backend_* / CAT_BACKEND_*.
*
* A "backend" turns a compiled CAT_BYTECODE_Function into an artifact:
* either printed text (its translation unit / assembly) or a built
* binary. Every backend is described by a CAT_BACKEND_Backend record and
* registered once in the registry (registry.c). Adding a new backend is
* then: write a file that exposes one `cat_backend_<name>_backend()`
* returning a static descriptor, and add a line to the registry table.
* The CLI never changes.
*/
#ifndef CAT_BACKEND_BACKEND_H
#define CAT_BACKEND_BACKEND_H
#include "cat/bytecode.h"
#include <stddef.h>
#include <stdio.h>
/* CAT_BACKEND_Backend -- one target, described declaratively. */
typedef struct CAT_BACKEND_Backend {
const char *name; /* selector, e.g. "c" or "x86_64" */
const char *description; /* one line for `--list-backends` */
int native; /* 1 if it builds a real native binary */
/* Dump the artifact (translation unit / assembly) to `out`. */
int (*emit)(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out);
/* Build a native executable at `outpath`. On failure returns
* non-zero and fills `errbuf`. */
int (*compile)(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz);
} CAT_BACKEND_Backend;
/* Look up a backend by name, or NULL when unknown. */
const CAT_BACKEND_Backend *cat_backend_find(const char *name);
/* The backend used when none is named (the C backend). */
const CAT_BACKEND_Backend *cat_backend_default(void);
/* Enumerate the registry. */
int cat_backend_count(void);
const CAT_BACKEND_Backend *cat_backend_at(int i);
#endif /* CAT_BACKEND_BACKEND_H */
+36
View File
@@ -0,0 +1,36 @@
/*
* cat/backend/c.h -- the C backend (ahead-of-time compilation).
*
* Naming rule: symbols here are cat_backend_c_* / CAT_BACKEND_C_*.
*
* The bytecode produced by the compiler is lowered to a standalone C
* translation unit. The generated program embeds its bytecode and runs
* it on the catscript runtime, but contains no compiler: a native `cc`
* build of the output is the executable, so nothing is parsed or
* compiled at run time.
*
* Two entry points:
* - cat_backend_c_emit() write the C for a compiled program
* - cat_backend_c_compile() emit + invoke cc to produce a binary
*/
#ifndef CAT_BACKEND_C_H
#define CAT_BACKEND_C_H
#include "cat/bytecode.h"
#include <stddef.h>
#include <stdio.h>
/* Write a self-contained C translation unit for `fn` to `out`.
* `module_name`/`module_path` seed the runtime `module` table. */
int cat_backend_c_emit(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out);
/* Emit the C for `fn` to a temporary file, compile it with the system C
* compiler, and write the executable to `outpath`. On failure returns
* non-zero and fills `errbuf`. */
int cat_backend_c_compile(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz);
#endif /* CAT_BACKEND_C_H */
+112
View File
@@ -0,0 +1,112 @@
/*
* cat/backend/x86_64.h -- runtime glue for the native x86-64 backend.
*
* Naming rule: cat_backend_x86_64_* / CAT_BACKEND_X86_64_*.
*
* Each bytecode instruction lowers to a call into one helper here (one
* per opcode); control flow becomes real jumps in the generated code.
* The assembly never needs struct offsets: it just sets arguments and
* calls a symbol.
*
* Helper convention (SysV): f in rdi, operands a/b/c in rsi/rdx/rcx.
* Return in eax: 0 ok; 1 ok-take-branch (popcond/fornext); -1 error
* (vm->err set), and the generated code runs its .Lonerror block.
*/
#ifndef CAT_BACKEND_X86_64_H
#define CAT_BACKEND_X86_64_H
#include "cat/value.h"
#include "cat/vm.h"
#include "cat/bytecode.h"
#include "cat/types/function.h"
typedef struct CAT_BACKEND_X86_64_Handler {
void *target; /* code address of the catch block */
int sp;
} CAT_BACKEND_X86_64_Handler;
typedef struct CAT_BACKEND_X86_64_Frame {
CAT_VM_State *vm;
CAT_BYTECODE_Function *fn;
CAT_VALUE_Value **stack;
CAT_VALUE_Value *locals[256];
int sp;
int nhandlers;
CAT_BACKEND_X86_64_Handler handlers[CAT_VM_MAXHANDLER];
CAT_VALUE_Value *ret;
} CAT_BACKEND_X86_64_Frame;
/* A generated entry point. Returns 0 (f->ret set) or -1 (vm->err set). */
typedef int (*CAT_BACKEND_X86_64_Entry)(CAT_BACKEND_X86_64_Frame *f);
/* Bridge used by cat_vm_exec_closure for a prototype with a native entry. */
int cat_backend_x86_64_top_call(CAT_VM_State *vm,
CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out);
/* Frame lifecycle (prologue/epilogue helpers). */
void cat_backend_x86_64_frame_init(CAT_BACKEND_X86_64_Frame *f,
CAT_VM_State *vm,
CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, long nargs);
void cat_backend_x86_64_frame_done(CAT_BACKEND_X86_64_Frame *f);
/* On error: resume the innermost handler (its code address), else NULL. */
void *cat_backend_x86_64_handle_error(CAT_BACKEND_X86_64_Frame *f);
/* Constant constructors (rebuild the pool in generated `main`). */
CAT_VALUE_Value *cat_backend_x86_64_const_int(long long v);
CAT_VALUE_Value *cat_backend_x86_64_const_float(double v);
CAT_VALUE_Value *cat_backend_x86_64_const_text(const char *s);
CAT_VALUE_Value *cat_backend_x86_64_const_bool(long t);
CAT_VALUE_Value *cat_backend_x86_64_const_empty(void);
/* One helper per opcode. */
int cat_backend_x86_64_const(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_empty(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_true(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_false(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_getlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_setlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_getglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_setglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_pop(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_dup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_arith(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_neg(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_not(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_cmp(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_concat(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_getattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_setattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_getidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_setidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_newtable(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_closure(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_call(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_callmethod(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_print(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_printexpr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_is(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_next(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_popcond(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_fornext(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_return(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_trysetup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_tryend(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
int cat_backend_x86_64_raise(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c);
/* Rebuild bytecode (used by generated `main`). */
CAT_BYTECODE_Function *cat_backend_x86_64_fn_new(const char *name);
void cat_backend_x86_64_fn_setup(CAT_BYTECODE_Function *fn, long nparams,
long nlocals, long is_generator);
void cat_backend_x86_64_fn_add_const(CAT_BYTECODE_Function *fn,
CAT_VALUE_Value *v);
void cat_backend_x86_64_fn_emit(CAT_BYTECODE_Function *fn, long op, long a,
long b, long c, long line);
void cat_backend_x86_64_fn_add_proto(CAT_BYTECODE_Function *fn,
CAT_BYTECODE_Function *p);
void cat_backend_x86_64_fn_set_entry(CAT_BYTECODE_Function *fn, void *entry);
#endif /* CAT_BACKEND_X86_64_H */
+2
View File
@@ -65,6 +65,7 @@ enum CAT_BYTECODE_Op {
CAT_BYTECODE_OP_RAISE, /* pop value -> raise it */
CAT_BYTECODE_OP_FORNEXT, /* A: exit target; pop it -> push next or jump */
CAT_BYTECODE_OP_PRINTEXPR, /* pop, print its repr (REPL echo) */
CAT_BYTECODE_OP_IS, /* pop iface, obj -> push obj is iface (structural) */
};
/* One instruction: opcode + three integer operands. */
@@ -96,6 +97,7 @@ typedef struct CAT_BYTECODE_Function {
int nlocals; /* number of local slots */
int nparams; /* number of parameters */
int is_generator; /* contains yield: calls produce a generator */
void *nat_entry; /* native code entry (x86_64 backend), or NULL */
} CAT_BYTECODE_Function;
CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name);
+4 -1
View File
@@ -28,7 +28,10 @@ enum CAT_LEXER_Kind {
CAT_LEXER_TOK_TRUE, CAT_LEXER_TOK_UNTIL, CAT_LEXER_TOK_WHILE,
CAT_LEXER_TOK_YIELD, CAT_LEXER_TOK_TRY, CAT_LEXER_TOK_EXCEPT,
CAT_LEXER_TOK_RAISE, CAT_LEXER_TOK_USE, CAT_LEXER_TOK_CLASS,
CAT_LEXER_TOK_EXTENDS,
CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS,
CAT_LEXER_TOK_IS,
CAT_LEXER_TOK_COMPTIME,
CAT_LEXER_TOK_TRAIT,
/* symbols */
CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR,
CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET,
+70
View File
@@ -0,0 +1,70 @@
/*
* cat/types/type.h -- compile-time type descriptors.
*
* Naming rule: symbols here are cat_types_type_* / CAT_TYPES_TYPE_*.
*
* These are COMPILE-TIME only: they never reach the runtime value graph
* (no refcounting, no vtable). A type is either a primitive singleton or
* a named/opaque type interned by the compiler. Typing stays structural:
* an unknown or opaque type is `any`-compatible, so checking never turns
* a working program into a rejected one by guessing.
*/
#ifndef CAT_TYPES_TYPE_H
#define CAT_TYPES_TYPE_H
/* Type categories. NAMED is any user/interface/opaque name. */
typedef enum CAT_TYPES_TYPE_Kind {
CAT_TYPES_TYPE_ANY = 0,
CAT_TYPES_TYPE_EMPTY,
CAT_TYPES_TYPE_BOOL,
CAT_TYPES_TYPE_INT,
CAT_TYPES_TYPE_FLOAT,
CAT_TYPES_TYPE_TEXT,
CAT_TYPES_TYPE_OBJECT,
CAT_TYPES_TYPE_FUNCTION,
CAT_TYPES_TYPE_LIST,
CAT_TYPES_TYPE_MEMORY,
CAT_TYPES_TYPE_NAMED
} CAT_TYPES_TYPE_Kind;
typedef struct CAT_TYPES_TYPE_Type {
const char *name; /* lowercase name, or the interned user name */
int kind; /* a CAT_TYPES_TYPE_Kind */
} CAT_TYPES_TYPE_Type;
/* Primitive singletons (immortal, shared). */
CAT_TYPES_TYPE_Type *cat_types_type_any(void);
CAT_TYPES_TYPE_Type *cat_types_type_empty(void);
CAT_TYPES_TYPE_Type *cat_types_type_bool(void);
CAT_TYPES_TYPE_Type *cat_types_type_int(void);
CAT_TYPES_TYPE_Type *cat_types_type_float(void);
CAT_TYPES_TYPE_Type *cat_types_type_text(void);
CAT_TYPES_TYPE_Type *cat_types_type_object(void);
CAT_TYPES_TYPE_Type *cat_types_type_function(void);
CAT_TYPES_TYPE_Type *cat_types_type_list(void);
CAT_TYPES_TYPE_Type *cat_types_type_memory(void);
/* Intern a named/opaque type (`cint`, `Drawable`, `List<int>`, ...).
* Returns a shared descriptor; the name is copied. Never freed (a
* compiler process interns a bounded set of names). */
CAT_TYPES_TYPE_Type *cat_types_type_named(const char *name);
const char *cat_types_type_name(const CAT_TYPES_TYPE_Type *t);
/* Structural equality (same name). `any` equals only `any`. */
int cat_types_type_equal(const CAT_TYPES_TYPE_Type *a,
const CAT_TYPES_TYPE_Type *b);
/* Is a value of type `src` acceptable where `dst` is expected?
* Permissive by design: `any` is assignable both ways, and an unknown
* named type is assignable to/from a concrete one (structural, no
* guessing). Only two known, concrete, incompatible types fail.
* `int` is assignable to `float`. */
int cat_types_type_assignable(const CAT_TYPES_TYPE_Type *dst,
const CAT_TYPES_TYPE_Type *src);
/* Result type of combining two operand types (e.g. `int + float`). */
CAT_TYPES_TYPE_Type *cat_types_type_join(const CAT_TYPES_TYPE_Type *a,
const CAT_TYPES_TYPE_Type *b);
#endif /* CAT_TYPES_TYPE_H */
+8
View File
@@ -208,6 +208,14 @@ int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err);
int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
CAT_ERROR_Error *err);
/* Structural `is`: is `obj` a member-wise implementation of the interface
* `iface`? An interface is a table carrying a `__interface` member whose
* other members name the required methods; inheritance (`__index`) is
* followed. When `iface` is not an interface, the test degrades to an
* exact type (vtable) match. Sets *out to 0/1. */
int cat_value_is(CAT_VALUE_Value *obj, CAT_VALUE_Value *iface, int *out,
CAT_ERROR_Error *err);
/* Advance an iterator/generator. Returns 0 and sets *out to the next
* value, 1 when the iterator is exhausted (*out untouched), or -1 on
* error. A separate exhaustion status (rather than an empty/sentinel
+16
View File
@@ -69,6 +69,17 @@ CAT_VM_State *cat_vm_new(void);
int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn,
CAT_VALUE_Value **out);
/* Call any callable value by the VM's own rules: a closure runs its
* prototype (or yields a generator), a native runs its C callback, a
* table with a `call` member is invoked. Exposed for out-of-line code
* generators (e.g. the native backend's CALL helper). */
int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
/* Print a value the way `print` does (used by code generators). */
void cat_vm_print_value(CAT_VALUE_Value *v);
/* Register a native function (name, C callback) into globals. */
int cat_vm_register_native(CAT_VM_State *vm, const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int,
@@ -78,6 +89,11 @@ int cat_vm_register_native(CAT_VM_State *vm, const char *name,
* closures/natives invoked through the object system. */
CAT_VM_State *cat_vm_current(void);
/* Install/restore the thread-local current VM. Out-of-line code
* generators (the native backend) call this around native execution so
* natives invoked from generated code see the active VM. */
void cat_vm_set_current(CAT_VM_State *vm);
/* Run (or resume) a frame. Returns 0 when the frame returns (*out set),
* 1 when it yields (*out set, frame left resumable), or -1 on error
* (vm->err set). The frame owns neither its operand stack nor its
+332
View File
@@ -0,0 +1,332 @@
/*
* cat/backend/c.c -- the C backend (see cat/backend/c.h).
*
* Naming rule: symbols here are cat_backend_c_* / CAT_BACKEND_C_*.
*
* A compiled CAT_BYTECODE_Function is written out as a C translation
* unit that rebuilds the bytecode at startup and runs it on the
* catscript runtime. The result is a native binary produced by `cc`
* with no compiler inside it: parsing/compilation happen ahead of time.
*/
#include "cat/backend/c.h"
#include "cat/backend/backend.h"
#include "cat/bytecode.h"
#include "cat/error.h"
#include "cat/types/number.h"
#include "cat/types/ascii_text.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* opcode mnemonics, for readable comments in the generated C. */
static const char *c_op_name(unsigned char op)
{
static const char *names[] = {
"NOP", "CONST", "EMPTY", "TRUE", "FALSE", "GETLOCAL", "SETLOCAL",
"GETGLOBAL", "SETGLOBAL", "ADD", "SUB", "MUL", "DIV", "REM",
"NEG", "NOT", "EQ", "NE", "LT", "LE", "GT", "GE", "GETATTR",
"SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF",
"JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE",
"GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT",
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR", "IS"
};
if (op < sizeof(names) / sizeof(names[0]))
return names[op];
return "?";
}
/* Write `s` as the body of a C string literal, octal-escaping anything
* that is not safe to emit verbatim. Three-digit octal escapes never
* bleed into following characters. */
static void c_escape(FILE *out, const char *s)
{
const unsigned char *p = (const unsigned char *)s;
for (; p != NULL && *p != '\0'; p++) {
unsigned char ch = *p;
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x7f)
fprintf(out, "\\%03o", ch);
else
fputc(ch, out);
}
}
/* Number of functions in a prototype subtree (including itself). */
static int c_count_fns(CAT_BYTECODE_Function *fn)
{
int n = 1, i;
for (i = 0; i < fn->nprotos; i++)
n += c_count_fns(fn->protos[i]);
return n;
}
/* Emit the C expression that recreates a constant value. */
static void c_emit_const(FILE *out, CAT_VALUE_Value *v)
{
if (v == NULL) {
fprintf(out, "cat_types_empty()");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v;
if (n->is_float)
fprintf(out, "cat_types_float_new(%.17g)", n->f);
else
fprintf(out, "cat_types_int_new(%lldLL)", n->i);
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) {
fprintf(out, "cat_types_ascii_text_new(\"");
c_escape(out, cat_types_text_bytes(v));
fprintf(out, "\")");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) {
int t = 1;
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_value_truthy(v, &t, &e);
fprintf(out, "%s", t ? "cat_types_bool_true()"
: "cat_types_bool_false()");
return;
}
/* anything else cannot appear as a literal constant in practice */
fprintf(out, "cat_types_empty()");
}
/* Emit the definition body for the function numbered `idx`. Child
* functions are numbered in pre-order, so child i's index is
* idx + 1 + (size of the subtrees before it). */
static void c_emit_fn(FILE *out, CAT_BYTECODE_Function *fn, int idx)
{
int i;
int child;
fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void)\n{\n",
idx);
fprintf(out, "\tCAT_BYTECODE_Function *fn = "
"cat_bytecode_function_new(\"");
c_escape(out, fn->name ? fn->name : "<anon>");
fprintf(out, "\");\n\n");
fprintf(out, "\tfn->nparams = %d;\n\tfn->nlocals = %d;\n",
fn->nparams, fn->nlocals);
fprintf(out, "\tfn->is_generator = %d;\n\n", fn->is_generator);
for (i = 0; i < fn->nconsts; i++) {
fprintf(out, "\tcat_bytecode_add_const(fn, ");
c_emit_const(out, fn->consts[i].value);
fprintf(out, ");\n");
}
if (fn->nconsts > 0)
fprintf(out, "\n");
child = idx + 1;
for (i = 0; i < fn->nprotos; i++) {
fprintf(out, "\tcat_bytecode_add_proto(fn, cat_prog_fn_%d());\n",
child);
child += c_count_fns(fn->protos[i]);
}
if (fn->nprotos > 0)
fprintf(out, "\n");
for (i = 0; i < fn->ncode; i++) {
CAT_BYTECODE_Instr *in = &fn->code[i];
fprintf(out, "\tcat_bytecode_emit(fn, %d, %d, %d, %d, %d);"
" /* %s */\n",
in->op, in->a, in->b, in->c, in->line,
c_op_name(in->op));
}
fprintf(out, "\treturn fn;\n}\n\n");
}
/* Pre-order forward declarations. */
static void c_emit_decls(FILE *out, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void);\n",
self);
for (i = 0; i < fn->nprotos; i++)
c_emit_decls(out, fn->protos[i], next);
}
/* Pre-order definitions (mirrors c_emit_decls). */
static void c_emit_defs(FILE *out, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
c_emit_fn(out, fn, self);
for (i = 0; i < fn->nprotos; i++)
c_emit_defs(out, fn->protos[i], next);
}
/* Directory holding the running executable, or NULL. */
static char *c_exe_dir(void)
{
char buf[4096];
ssize_t n;
char *slash;
n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n <= 0)
return NULL;
buf[n] = '\0';
slash = strrchr(buf, '/');
if (slash == NULL)
return NULL;
*slash = '\0';
return strdup(buf);
}
int cat_backend_c_emit(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out)
{
int next;
if (fn == NULL || out == NULL)
return -1;
fprintf(out, "/* generated by catscript -- C backend (AOT). */\n");
fprintf(out, "#include \"cat/vm.h\"\n");
fprintf(out, "#include \"cat/bytecode.h\"\n");
fprintf(out, "#include \"cat/module.h\"\n");
fprintf(out, "#include \"cat/error.h\"\n");
fprintf(out, "#include \"cat/stdlib/stdlib.h\"\n");
fprintf(out, "#include \"cat/stdlib/build.h\"\n");
fprintf(out, "#include \"cat/types/number.h\"\n");
fprintf(out, "#include \"cat/types/int.h\"\n");
fprintf(out, "#include \"cat/types/float.h\"\n");
fprintf(out, "#include \"cat/types/ascii_text.h\"\n");
fprintf(out, "#include \"cat/types/bool.h\"\n");
fprintf(out, "#include \"cat/types/empty.h\"\n\n");
fprintf(out, "#include <stdio.h>\n\n");
next = 0;
fprintf(out, "/* function prototypes */\n");
c_emit_decls(out, fn, &next);
fprintf(out, "\n");
next = 0;
c_emit_defs(out, fn, &next);
fprintf(out, "int main(void)\n{\n");
fprintf(out, "\tCAT_VM_State *vm;\n");
fprintf(out, "\tCAT_BYTECODE_Function *top;\n");
fprintf(out, "\tCAT_VALUE_Value *out = NULL;\n");
fprintf(out, "\tint rc;\n\n");
fprintf(out, "\tvm = cat_vm_new();\n");
fprintf(out, "\tif (vm == NULL)\n\t\treturn 1;\n");
fprintf(out, "\tcat_stdlib_stdlib_install(vm);\n");
fprintf(out, "\tcat_stdlib_build_install(vm);\n");
fprintf(out, "\tcat_module_enter(vm, \"");
c_escape(out, module_name ? module_name : "<aot>");
fprintf(out, "\", ");
if (module_path != NULL) {
fprintf(out, "\"");
c_escape(out, module_path);
fprintf(out, "\"");
} else {
fprintf(out, "NULL");
}
fprintf(out, ");\n\n");
fprintf(out, "\ttop = cat_prog_fn_0();\n");
fprintf(out, "\trc = cat_vm_run(vm, top, &out);\n");
fprintf(out, "\tif (rc != 0)\n");
fprintf(out, "\t\tfprintf(stderr, \"catscript: %%s\\n\", "
"vm->err.message);\n");
fprintf(out, "\tcat_bytecode_function_free(top);\n");
fprintf(out, "\tcat_vm_free(vm);\n");
fprintf(out, "\treturn rc != 0;\n}\n");
return 0;
}
/* Descriptor for the registry (see cat/backend/backend.h). */
const CAT_BACKEND_Backend *cat_backend_c_backend(void)
{
static const CAT_BACKEND_Backend b = {
.name = "c",
.description = "portable C translation unit built by cc",
.native = 1,
.emit = cat_backend_c_emit,
.compile = cat_backend_c_compile,
};
return &b;
}
int cat_backend_c_compile(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz)
{
char tmpl[] = "/tmp/catscript-aot-XXXXXX.c";
char cmd[9216];
char inc[4096];
char lib[4096];
char *dir;
FILE *f;
int fd;
int st;
if (errbuf != NULL && errsz > 0)
errbuf[0] = '\0';
fd = mkstemps(tmpl, 2);
if (fd < 0)
return -1;
f = fdopen(fd, "w");
if (f == NULL) {
close(fd);
return -1;
}
if (cat_backend_c_emit(fn, module_name, module_path, f) != 0) {
fclose(f);
unlink(tmpl);
return -1;
}
fclose(f);
dir = c_exe_dir();
if (dir == NULL) {
unlink(tmpl);
if (errbuf != NULL)
snprintf(errbuf, errsz,
"cannot locate the catscript runtime");
return -1;
}
snprintf(inc, sizeof(inc), "%s/../../include", dir);
snprintf(lib, sizeof(lib), "%s/libcatscript.a", dir);
if (access(lib, R_OK) != 0) {
unlink(tmpl);
free(dir);
if (errbuf != NULL)
snprintf(errbuf, errsz,
"runtime archive missing at %s", lib);
return -1;
}
snprintf(cmd, sizeof(cmd),
"cc -std=c11 -O2 -D_DEFAULT_SOURCE -I'%s' -o '%s' '%s' '%s' "
"-lm -lffi -ldl 2>&1",
inc, outpath, tmpl, lib);
st = system(cmd);
unlink(tmpl);
free(dir);
if (st != 0) {
if (errbuf != NULL)
snprintf(errbuf, errsz,
"C compiler failed (status %d)", st);
return -1;
}
return 0;
}
+64
View File
@@ -0,0 +1,64 @@
/*
* cat/backend/registry.c -- the backend registry (see backend.h).
*
* Naming rule: symbols here are cat_backend_* / CAT_BACKEND_*.
*
* Every available backend appears exactly once in g_backends. This is
* the ONLY place that enumerates targets: the CLI and the library ask the
* registry, so adding a backend means writing its file and adding one
* line below.
*/
#include "cat/backend/backend.h"
#include <string.h>
/* Each backend exposes a descriptor accessor (defined in its own file). */
const CAT_BACKEND_Backend *cat_backend_c_backend(void);
const CAT_BACKEND_Backend *cat_backend_x86_64_backend(void);
static const CAT_BACKEND_Backend *backend_get(int i)
{
/* Kept as a switch so the table stays a single, obvious place. */
switch (i) {
case 0: return cat_backend_c_backend();
case 1: return cat_backend_x86_64_backend();
default: return NULL;
}
}
static int backend_total(void)
{
return 2;
}
int cat_backend_count(void)
{
return backend_total();
}
const CAT_BACKEND_Backend *cat_backend_at(int i)
{
if (i < 0 || i >= backend_total())
return NULL;
return backend_get(i);
}
const CAT_BACKEND_Backend *cat_backend_find(const char *name)
{
int i;
if (name == NULL)
return NULL;
for (i = 0; i < backend_total(); i++) {
const CAT_BACKEND_Backend *b = backend_get(i);
if (b != NULL && b->name != NULL && strcmp(b->name, name) == 0)
return b;
}
return NULL;
}
const CAT_BACKEND_Backend *cat_backend_default(void)
{
return cat_backend_find("c");
}
+509
View File
@@ -0,0 +1,509 @@
/*
* cat/backend/x86_64.c -- the native x86-64 backend (see backend.h).
*
* Naming rule: symbols here are cat_backend_x86_64_* / CAT_BACKEND_X86_64_*.
*
* Lowers a compiled CAT_BYTECODE_Function to x86-64 assembly (AT&T, SysV)
* and assembles/links it with `as` + `cc` against the catscript runtime.
* The emitted code is machine code: no C translation unit carries the
* program logic. Each bytecode instruction becomes a call into a runtime
* helper (cat/backend/x86_64_glue.c), and control flow becomes real
* branches inside the generated code.
*
* A program is emitted as two temp files -- `<x>.s` (the function bodies)
* and `<x>_main.c` (which rebuilds the bytecode and boots the VM) -- then
* assembled and linked together.
*
* Only "lowerable" functions become native: generator functions (whose
* `yield` needs coroutine resumption) are left to the interpreter, so the
* prototype simply carries no nat_entry and the VM runs it as usual.
*/
#include "cat/backend/backend.h"
#include "cat/backend/x86_64.h"
#include "cat/bytecode.h"
#include "cat/types/number.h"
#include "cat/types/ascii_text.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* ---- small emission helpers ---- */
/* Escape a C string literal body. */
static void x_escape(FILE *o, const char *s)
{
const unsigned char *p = (const unsigned char *)s;
for (; p != NULL && *p != '\0'; p++) {
if (*p == '"' || *p == '\\' || *p < 0x20 || *p >= 0x7f)
fprintf(o, "\\%03o", *p);
else
fputc(*p, o);
}
}
/* Count functions in a prototype subtree (pre-order numbering). */
static int x_count(CAT_BYTECODE_Function *fn)
{
int n = 1, i;
for (i = 0; i < fn->nprotos; i++)
n += x_count(fn->protos[i]);
return n;
}
/* A native entry can carry this function only if it never yields. */
static int x_lowerable(CAT_BYTECODE_Function *fn)
{
return fn->is_generator == 0;
}
/* Emit `call sym` with f=rdi, a/b/c in rsi/rdx/rcx. */
static void x_call(FILE *o, const char *sym, int a, int b, int c)
{
fprintf(o, "\tmovq %%rbx, %%rdi\n");
fprintf(o, "\tmovl $%d, %%esi\n", a);
fprintf(o, "\tmovl $%d, %%edx\n", b);
fprintf(o, "\tmovl $%d, %%ecx\n", c);
fprintf(o, "\tcall %s\n", sym);
}
/* Emit a call followed by the error check. */
static void x_call_chk(FILE *o, int idx, const char *sym, int a, int b, int c)
{
x_call(o, sym, a, b, c);
fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx);
}
/* Map an opcode to its helper symbol, or NULL when it is control flow. */
static const char *x_sym(unsigned char op)
{
switch (op) {
case CAT_BYTECODE_OP_CONST: return "cat_backend_x86_64_const";
case CAT_BYTECODE_OP_EMPTY: return "cat_backend_x86_64_empty";
case CAT_BYTECODE_OP_TRUE: return "cat_backend_x86_64_true";
case CAT_BYTECODE_OP_FALSE: return "cat_backend_x86_64_false";
case CAT_BYTECODE_OP_GETLOCAL: return "cat_backend_x86_64_getlocal";
case CAT_BYTECODE_OP_SETLOCAL: return "cat_backend_x86_64_setlocal";
case CAT_BYTECODE_OP_GETGLOBAL: return "cat_backend_x86_64_getglobal";
case CAT_BYTECODE_OP_SETGLOBAL: return "cat_backend_x86_64_setglobal";
case CAT_BYTECODE_OP_POP: return "cat_backend_x86_64_pop";
case CAT_BYTECODE_OP_DUP: return "cat_backend_x86_64_dup";
case CAT_BYTECODE_OP_ADD: case CAT_BYTECODE_OP_SUB:
case CAT_BYTECODE_OP_MUL: case CAT_BYTECODE_OP_DIV:
case CAT_BYTECODE_OP_REM: return "cat_backend_x86_64_arith";
case CAT_BYTECODE_OP_NEG: return "cat_backend_x86_64_neg";
case CAT_BYTECODE_OP_NOT: return "cat_backend_x86_64_not";
case CAT_BYTECODE_OP_EQ: case CAT_BYTECODE_OP_NE:
case CAT_BYTECODE_OP_LT: case CAT_BYTECODE_OP_LE:
case CAT_BYTECODE_OP_GT: case CAT_BYTECODE_OP_GE:
return "cat_backend_x86_64_cmp";
case CAT_BYTECODE_OP_CONCAT: return "cat_backend_x86_64_concat";
case CAT_BYTECODE_OP_GETATTR: return "cat_backend_x86_64_getattr";
case CAT_BYTECODE_OP_SETATTR: return "cat_backend_x86_64_setattr";
case CAT_BYTECODE_OP_GETIDX: return "cat_backend_x86_64_getidx";
case CAT_BYTECODE_OP_SETIDX: return "cat_backend_x86_64_setidx";
case CAT_BYTECODE_OP_NEWTABLE: return "cat_backend_x86_64_newtable";
case CAT_BYTECODE_OP_CLOSURE: return "cat_backend_x86_64_closure";
case CAT_BYTECODE_OP_CALL: return "cat_backend_x86_64_call";
case CAT_BYTECODE_OP_CALLMETHOD: return "cat_backend_x86_64_callmethod";
case CAT_BYTECODE_OP_PRINT: return "cat_backend_x86_64_print";
case CAT_BYTECODE_OP_PRINTEXPR: return "cat_backend_x86_64_printexpr";
case CAT_BYTECODE_OP_IS: return "cat_backend_x86_64_is";
case CAT_BYTECODE_OP_NEXT: return "cat_backend_x86_64_next";
case CAT_BYTECODE_OP_TRYEND: return "cat_backend_x86_64_tryend";
default: return NULL;
}
}
/* Emit the body of one lowerable function. */
static void x_emit_fn(FILE *o, CAT_BYTECODE_Function *fn, int idx)
{
int i;
fprintf(o, "\t.text\n\t.globl cat_nat_fn_%d\n\t.type cat_nat_fn_%d, @function\n",
idx, idx);
fprintf(o, "cat_nat_fn_%d:\n", idx);
fprintf(o, "\tpushq %%rbx\n\tpushq %%rbp\n\tsubq $8, %%rsp\n");
fprintf(o, "\tmovq %%rdi, %%rbx\n");
for (i = 0; i < fn->ncode; i++) {
CAT_BYTECODE_Instr *in = &fn->code[i];
const char *sym;
fprintf(o, ".Lfn%d_ip_%d:\n", idx, i);
switch (in->op) {
case CAT_BYTECODE_OP_NOP:
break;
case CAT_BYTECODE_OP_JUMP:
fprintf(o, "\tjmp .Lfn%d_ip_%d\n", idx, in->a);
break;
case CAT_BYTECODE_OP_JUMPIF:
x_call(o, "cat_backend_x86_64_popcond", 0, 0, 0);
fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx);
fprintf(o, "\tjne .Lfn%d_ip_%d\n", idx, in->a);
break;
case CAT_BYTECODE_OP_JUMPIFNOT:
x_call(o, "cat_backend_x86_64_popcond", 0, 0, 0);
fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx);
fprintf(o, "\tje .Lfn%d_ip_%d\n", idx, in->a);
break;
case CAT_BYTECODE_OP_FORNEXT:
x_call(o, "cat_backend_x86_64_fornext", 0, 0, 0);
fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx);
fprintf(o, "\tjne .Lfn%d_ip_%d\n", idx, in->a);
break;
case CAT_BYTECODE_OP_RETURN:
x_call(o, "cat_backend_x86_64_return", 0, 0, 0);
fprintf(o, "\tjmp .Lret_%d\n", idx);
break;
case CAT_BYTECODE_OP_RETURN0:
x_call(o, "cat_backend_x86_64_empty", 0, 0, 0);
x_call(o, "cat_backend_x86_64_return", 0, 0, 0);
fprintf(o, "\tjmp .Lret_%d\n", idx);
break;
case CAT_BYTECODE_OP_TRYSETUP:
fprintf(o, "\tmovq %%rbx, %%rdi\n");
fprintf(o, "\tleaq .Lfn%d_ip_%d(%%rip), %%rsi\n", idx, in->a);
fprintf(o, "\txorl %%edx, %%edx\n\txorl %%ecx, %%ecx\n");
fprintf(o, "\tcall cat_backend_x86_64_trysetup\n");
break;
case CAT_BYTECODE_OP_RAISE:
x_call(o, "cat_backend_x86_64_raise", 0, 0, 0);
fprintf(o, "\tjmp .Lonerror_%d\n", idx);
break;
case CAT_BYTECODE_OP_ADD: case CAT_BYTECODE_OP_SUB:
case CAT_BYTECODE_OP_MUL: case CAT_BYTECODE_OP_DIV:
case CAT_BYTECODE_OP_REM:
/* pass the opcode itself as operand a */
x_call_chk(o, idx, "cat_backend_x86_64_arith",
in->op, 0, 0);
break;
case CAT_BYTECODE_OP_EQ: case CAT_BYTECODE_OP_NE:
case CAT_BYTECODE_OP_LT: case CAT_BYTECODE_OP_LE:
case CAT_BYTECODE_OP_GT: case CAT_BYTECODE_OP_GE:
x_call_chk(o, idx, "cat_backend_x86_64_cmp", in->op, 0, 0);
break;
default:
sym = x_sym(in->op);
if (sym != NULL)
x_call_chk(o, idx, sym, in->a, in->b, in->c);
break;
}
}
/* fell off the end: return the empty object */
x_call(o, "cat_backend_x86_64_empty", 0, 0, 0);
x_call(o, "cat_backend_x86_64_return", 0, 0, 0);
fprintf(o, "\tjmp .Lret_%d\n", idx);
fprintf(o, ".Lonerror_%d:\n", idx);
fprintf(o, "\tmovq %%rbx, %%rdi\n\tcall cat_backend_x86_64_handle_error\n");
fprintf(o, "\ttestq %%rax, %%rax\n\tje .Lfail_%d\n\tjmp *%%rax\n", idx);
fprintf(o, ".Lfail_%d:\n\tmovl $-1, %%eax\n", idx);
fprintf(o, ".Lret_%d:\n", idx);
fprintf(o, "\taddq $8, %%rsp\n\tpopq %%rbp\n\tpopq %%rbx\n\tret\n\n");
}
/* Emit only the lowerable functions of a tree, in pre-order, so indices
* match the generated `_main.c` (which numbers ALL functions). */
static void x_emit_tree(FILE *o, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
if (x_lowerable(fn))
x_emit_fn(o, fn, self);
for (i = 0; i < fn->nprotos; i++)
x_emit_tree(o, fn->protos[i], next);
}
/* Emit the whole assembly translation unit for a program. */
static void x_emit_prog(FILE *o, CAT_BYTECODE_Function *fn)
{
int next = 0;
fprintf(o, "/* generated by catscript -- native x86-64 backend. */\n");
fprintf(o, "\t.text\n");
x_emit_tree(o, fn, &next);
fprintf(o, "\t.section .note.GNU-stack,\"\",@progbits\n");
}
/* ---- the generated `_main.c`: rebuild bytecode and boot the VM ---- */
static void x_const_expr(FILE *o, CAT_VALUE_Value *v)
{
if (v == NULL) {
fprintf(o, "cat_backend_x86_64_const_empty()");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v;
if (n->is_float)
fprintf(o, "cat_backend_x86_64_const_float(%.17g)", n->f);
else
fprintf(o, "cat_backend_x86_64_const_int(%lldLL)", n->i);
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) {
fprintf(o, "cat_backend_x86_64_const_text(\"");
x_escape(o, cat_types_text_bytes(v));
fprintf(o, "\")");
return;
}
if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) {
int t = 1;
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_value_truthy(v, &t, &e);
fprintf(o, "cat_backend_x86_64_const_bool(%d)", t);
return;
}
fprintf(o, "cat_backend_x86_64_const_empty()");
}
static void x_main_decls(FILE *o, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int i;
fprintf(o, "static CAT_BYTECODE_Function *cat_nat_proto_%d(void);\n", self);
fprintf(o, "extern int cat_nat_fn_%d(void);\n", self);
for (i = 0; i < fn->nprotos; i++)
x_main_decls(o, fn->protos[i], next);
}
static void x_main_defs(FILE *o, CAT_BYTECODE_Function *fn, int *next)
{
int self = (*next)++;
int child, i;
fprintf(o, "static CAT_BYTECODE_Function *cat_nat_proto_%d(void)\n{\n",
self);
fprintf(o, "\tCAT_BYTECODE_Function *fn = cat_backend_x86_64_fn_new(\"");
x_escape(o, fn->name ? fn->name : "<anon>");
fprintf(o, "\");\n");
fprintf(o, "\tcat_backend_x86_64_fn_setup(fn, %d, %d, %d);\n",
fn->nparams, fn->nlocals, fn->is_generator);
for (i = 0; i < fn->nconsts; i++) {
fprintf(o, "\tcat_backend_x86_64_fn_add_const(fn, ");
x_const_expr(o, fn->consts[i].value);
fprintf(o, ");\n");
}
child = self + 1;
for (i = 0; i < fn->nprotos; i++) {
fprintf(o, "\tcat_backend_x86_64_fn_add_proto(fn, cat_nat_proto_%d());\n",
child);
child += x_count(fn->protos[i]);
}
/* Rebuild the instruction array: functions the native code does not
* run (generators) are executed by the interpreter and need it. */
for (i = 0; i < fn->ncode; i++) {
CAT_BYTECODE_Instr *in = &fn->code[i];
fprintf(o, "\tcat_backend_x86_64_fn_emit(fn, %d, %d, %d, %d, %d);\n",
in->op, in->a, in->b, in->c, in->line);
}
if (x_lowerable(fn))
fprintf(o, "\tcat_backend_x86_64_fn_set_entry(fn, (void *)cat_nat_fn_%d);\n",
self);
fprintf(o, "\treturn fn;\n}\n\n");
for (i = 0; i < fn->nprotos; i++)
x_main_defs(o, fn->protos[i], next);
}
static void x_emit_main_c(FILE *o, CAT_BYTECODE_Function *fn,
const char *module_name, const char *module_path)
{
int next = 0;
fprintf(o, "/* generated by catscript -- native x86-64 backend (boot). */\n");
fprintf(o, "#include \"cat/vm.h\"\n#include \"cat/bytecode.h\"\n");
fprintf(o, "#include \"cat/module.h\"\n#include \"cat/error.h\"\n");
fprintf(o, "#include \"cat/stdlib/stdlib.h\"\n");
fprintf(o, "#include \"cat/stdlib/build.h\"\n");
fprintf(o, "#include \"cat/backend/x86_64.h\"\n#include <stdio.h>\n\n");
next = 0;
x_main_decls(o, fn, &next);
fprintf(o, "\n");
next = 0;
x_main_defs(o, fn, &next);
fprintf(o, "int main(void)\n{\n");
fprintf(o, "\tCAT_VM_State *vm;\n\tCAT_BYTECODE_Function *top;\n");
fprintf(o, "\tCAT_VALUE_Value *out = NULL;\n\tint rc;\n\n");
fprintf(o, "\tvm = cat_vm_new();\n\tif (vm == NULL)\n\t\treturn 1;\n");
fprintf(o, "\tcat_stdlib_stdlib_install(vm);\n\tcat_stdlib_build_install(vm);\n");
fprintf(o, "\tcat_module_enter(vm, \"");
x_escape(o, module_name ? module_name : "<aot>");
fprintf(o, "\", ");
if (module_path != NULL) {
fprintf(o, "\"");
x_escape(o, module_path);
fprintf(o, "\"");
} else {
fprintf(o, "NULL");
}
fprintf(o, ");\n\n");
fprintf(o, "\ttop = cat_nat_proto_0();\n");
fprintf(o, "\trc = cat_vm_run(vm, top, &out);\n");
fprintf(o, "\tif (rc != 0)\n\t\tfprintf(stderr, \"catscript: %%s\\n\", vm->err.message);\n");
fprintf(o, "\tcat_bytecode_function_free(top);\n\tcat_vm_free(vm);\n");
fprintf(o, "\treturn rc != 0;\n}\n");
}
/* Directory of the running executable, or NULL. */
static char *x_exe_dir(void)
{
char buf[4096];
ssize_t n;
char *slash;
n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n <= 0)
return NULL;
buf[n] = '\0';
slash = strrchr(buf, '/');
if (slash == NULL)
return NULL;
*slash = '\0';
return strdup(buf);
}
int x86_64_emit_public(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out)
{
(void)module_name;
(void)module_path;
x_emit_prog(out, fn);
return 0;
}
static int x86_64_emit(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, FILE *out)
{
(void)module_name;
(void)module_path;
x_emit_prog(out, fn);
return 0;
}
int x86_64_compile(CAT_BYTECODE_Function *fn, const char *module_name,
const char *module_path, const char *outpath,
char *errbuf, size_t errsz)
{
char stmpl[] = "/tmp/cat-nat-XXXXXX.s";
char ctmpl[] = "/tmp/cat-nat-XXXXXX.c";
char otmpl[] = "/tmp/cat-nat-XXXXXX.o";
char cmd[16384], inc[4096], lib[4096];
char *dir;
FILE *f;
int sfd, cfd, ofd, st;
if (errbuf != NULL && errsz > 0)
errbuf[0] = '\0';
if (fn == NULL) {
if (errbuf != NULL)
snprintf(errbuf, errsz, "no program to compile");
return -1;
}
sfd = mkstemps(stmpl, 2);
if (sfd < 0)
return -1;
f = fdopen(sfd, "w");
if (f == NULL) {
close(sfd);
return -1;
}
x_emit_prog(f, fn);
fclose(f);
cfd = mkstemps(ctmpl, 2);
if (cfd < 0) {
unlink(stmpl);
return -1;
}
f = fdopen(cfd, "w");
if (f == NULL) {
close(cfd);
unlink(stmpl);
return -1;
}
x_emit_main_c(f, fn, module_name, module_path);
fclose(f);
ofd = mkstemps(otmpl, 2);
if (ofd >= 0)
close(ofd);
dir = x_exe_dir();
if (dir == NULL) {
unlink(stmpl);
unlink(ctmpl);
unlink(otmpl);
if (errbuf != NULL)
snprintf(errbuf, errsz, "cannot locate the catscript runtime");
return -1;
}
snprintf(inc, sizeof(inc), "%s/../../include", dir);
snprintf(lib, sizeof(lib), "%s/libcatscript.a", dir);
if (access(lib, R_OK) != 0) {
unlink(stmpl);
unlink(ctmpl);
unlink(otmpl);
free(dir);
if (errbuf != NULL)
snprintf(errbuf, errsz, "runtime archive missing at %s", lib);
return -1;
}
/* assemble the generated .s */
snprintf(cmd, sizeof(cmd),
"cc -std=c11 -D_DEFAULT_SOURCE -I'%s' -c '%s' -o '%s' 2>&1",
inc, stmpl, otmpl);
st = system(cmd);
if (st != 0) {
unlink(stmpl);
unlink(ctmpl);
unlink(otmpl);
free(dir);
if (errbuf != NULL)
snprintf(errbuf, errsz,
"assembler failed (status %d)", st);
return -1;
}
/* link: object + boot C + runtime archive */
snprintf(cmd, sizeof(cmd),
"cc -std=c11 -O2 -D_DEFAULT_SOURCE -I'%s' -o '%s' '%s' '%s' "
"'%s' -lm -lffi -ldl 2>&1",
inc, outpath, otmpl, ctmpl, lib);
st = system(cmd);
unlink(stmpl);
unlink(ctmpl);
unlink(otmpl);
free(dir);
if (st != 0) {
if (errbuf != NULL)
snprintf(errbuf, errsz,
"C linker failed (status %d)", st);
return -1;
}
return 0;
}
const CAT_BACKEND_Backend *cat_backend_x86_64_backend(void)
{
static const CAT_BACKEND_Backend b = {
.name = "x86_64",
.description = "native x86-64 assembly (SysV), linked by cc",
.native = 1,
.emit = x86_64_emit,
.compile = x86_64_compile,
};
return &b;
}
+569
View File
@@ -0,0 +1,569 @@
/*
* cat/backend/x86_64_glue.c -- runtime glue for the native backend.
*
* Naming rule: cat_backend_x86_64_* / CAT_BACKEND_X86_64_*.
*
* The generated assembly calls one helper here per opcode. The helpers
* mirror cat/vm.c's interpreter exactly, so both engines agree on
* observable behaviour. Part 1: frame lifecycle, constants, operands.
*/
#include "cat/backend/x86_64.h"
#include "cat/vm.h"
#include "cat/error.h"
#include "cat/types/empty.h"
#include "cat/types/bool.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/table.h"
#include "cat/types/function.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int xdeliver(CAT_VM_State *vm, const CAT_ERROR_Error *from)
{
if (from->raised) {
cat_error_clear(&vm->err);
cat_error_raise(&vm->err, "%s", from->message);
vm->err.value = from->value;
return -1;
}
return 0;
}
void cat_backend_x86_64_frame_init(CAT_BACKEND_X86_64_Frame *f,
CAT_VM_State *vm,
CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, long nargs)
{
CAT_BYTECODE_Function *fn = cl ? cl->proto : NULL;
int i;
memset(f, 0, sizeof(*f));
f->vm = vm;
f->fn = fn;
f->stack = calloc((size_t)((fn ? fn->ncode : 0) + 64),
sizeof(*f->stack));
for (i = 0; i < 256; i++)
f->locals[i] = NULL;
if (fn != NULL)
for (i = 0; i < nargs && i < fn->nparams && i < 256; i++)
f->locals[i] = args ? args[i] : NULL;
}
void cat_backend_x86_64_frame_done(CAT_BACKEND_X86_64_Frame *f)
{
free(f->stack);
f->stack = NULL;
}
void *cat_backend_x86_64_handle_error(CAT_BACKEND_X86_64_Frame *f)
{
if (f->nhandlers > 0) {
CAT_BACKEND_X86_64_Handler *h = &f->handlers[--f->nhandlers];
f->sp = h->sp;
if (f->vm->err.value != NULL)
f->stack[f->sp++] = f->vm->err.value;
else
f->stack[f->sp++] =
cat_types_ascii_text_new(f->vm->err.message);
cat_error_clear(&f->vm->err);
return h->target;
}
return NULL;
}
CAT_VALUE_Value *cat_backend_x86_64_const_int(long long v)
{
return cat_types_int_new(v);
}
CAT_VALUE_Value *cat_backend_x86_64_const_float(double v)
{
return cat_types_float_new(v);
}
CAT_VALUE_Value *cat_backend_x86_64_const_text(const char *s)
{
return cat_types_ascii_text_new(s);
}
CAT_VALUE_Value *cat_backend_x86_64_const_bool(long t)
{
return t ? cat_types_bool_true() : cat_types_bool_false();
}
CAT_VALUE_Value *cat_backend_x86_64_const_empty(void)
{
return cat_types_empty();
}
int cat_backend_x86_64_const(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *v = f->fn->consts[a].value;
(void)b; (void)c;
f->stack[f->sp++] = v;
return 0;
}
int cat_backend_x86_64_empty(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->stack[f->sp++] = cat_types_empty();
return 0;
}
int cat_backend_x86_64_true(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->stack[f->sp++] = cat_types_bool_true();
return 0;
}
int cat_backend_x86_64_false(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->stack[f->sp++] = cat_types_bool_false();
return 0;
}
int cat_backend_x86_64_getlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)b; (void)c;
f->stack[f->sp++] = f->locals[a] ? f->locals[a] : cat_types_empty();
return 0;
}
int cat_backend_x86_64_setlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)b; (void)c;
f->locals[a] = f->stack[--f->sp];
return 0;
}
int cat_backend_x86_64_getglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *g;
(void)b; (void)c;
g = cat_vm_get_global(f->vm,
cat_types_text_bytes(f->fn->consts[a].value));
if (g == NULL) {
cat_error_clear(&f->vm->err);
cat_error_raise(&f->vm->err, "global '%s' is not defined",
cat_types_text_bytes(f->fn->consts[a].value));
return -1;
}
f->stack[f->sp++] = g;
return 0;
}
int cat_backend_x86_64_setglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)b; (void)c;
cat_vm_set_global(f->vm, cat_types_text_bytes(f->fn->consts[a].value),
f->stack[--f->sp]);
return 0;
}
int cat_backend_x86_64_pop(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->sp--;
return 0;
}
int cat_backend_x86_64_dup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->stack[f->sp] = f->stack[f->sp - 1];
f->sp++;
return 0;
}
int cat_backend_x86_64_newtable(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->stack[f->sp++] = cat_types_table_new();
return 0;
}
int cat_backend_x86_64_closure(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)b; (void)c;
f->stack[f->sp++] = cat_types_function_new(f->fn->protos[a]);
return 0;
}
int cat_backend_x86_64_arith(CAT_BACKEND_X86_64_Frame *f, long op, long b, long c)
{
CAT_VALUE_Value *y = f->stack[--f->sp];
CAT_VALUE_Value *x = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
int st;
(void)b; (void)c;
cat_error_clear(&e);
switch (op) {
case CAT_BYTECODE_OP_ADD: st = cat_value_add(x, y, &r, &e); break;
case CAT_BYTECODE_OP_SUB: st = cat_value_sub(x, y, &r, &e); break;
case CAT_BYTECODE_OP_MUL: st = cat_value_mul(x, y, &r, &e); break;
case CAT_BYTECODE_OP_DIV: st = cat_value_div(x, y, &r, &e); break;
default: st = cat_value_rem(x, y, &r, &e); break;
}
if (st != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_neg(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *x = f->stack[--f->sp];
CAT_VALUE_Value *zero = cat_types_int_new(0);
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
if (cat_value_sub(zero, x, &r, &e) != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_not(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *x = f->stack[--f->sp];
CAT_ERROR_Error e;
int t = 1;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
cat_value_truthy(x, &t, &e);
f->stack[f->sp++] = t ? cat_types_bool_false() : cat_types_bool_true();
return 0;
}
int cat_backend_x86_64_cmp(CAT_BACKEND_X86_64_Frame *f, long op, long b, long c)
{
CAT_VALUE_Value *y = f->stack[--f->sp];
CAT_VALUE_Value *x = f->stack[--f->sp];
int c2 = 0, eq = 0, has = 0;
int res;
(void)b; (void)c;
if (x == NULL) x = cat_types_empty();
if (y == NULL) y = cat_types_empty();
if (x == y) {
eq = 1; has = 1; c2 = 0;
} else if (x->vtable && y->vtable &&
x->vtable->kind == CAT_VALUE_KIND_TEXT &&
y->vtable->kind == CAT_VALUE_KIND_TEXT) {
c2 = strcmp(cat_types_text_bytes(x), cat_types_text_bytes(y));
eq = (c2 == 0); has = 1;
} else if (x->vtable && y->vtable &&
x->vtable->kind == CAT_VALUE_KIND_NUMBER &&
y->vtable->kind == CAT_VALUE_KIND_NUMBER) {
double xv = cat_types_number_as_double(x);
double yv = cat_types_number_as_double(y);
c2 = (xv < yv) ? -1 : (xv > yv) ? 1 : 0;
eq = (c2 == 0); has = 1;
}
res = 0;
switch (op) {
case CAT_BYTECODE_OP_EQ: res = eq; break;
case CAT_BYTECODE_OP_NE: res = !eq; break;
case CAT_BYTECODE_OP_LT: res = has && (c2 < 0); break;
case CAT_BYTECODE_OP_LE: res = has && (c2 <= 0); break;
case CAT_BYTECODE_OP_GT: res = has && (c2 > 0); break;
default: res = has && (c2 >= 0); break;
}
f->stack[f->sp++] = res ? cat_types_bool_true() : cat_types_bool_false();
return 0;
}
int cat_backend_x86_64_concat(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *y = f->stack[--f->sp];
CAT_VALUE_Value *x = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
if (cat_types_text_concat(x, y, &r, &e) != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_getattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *obj = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
(void)b; (void)c;
cat_error_clear(&e);
if (cat_value_get_attribute(obj, cat_types_text_bytes(f->fn->consts[a].value),
&r, &e) != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_setattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *val = f->stack[--f->sp];
CAT_VALUE_Value *obj = f->stack[--f->sp];
CAT_ERROR_Error e;
(void)b; (void)c;
cat_error_clear(&e);
if (cat_value_set_attribute(obj, cat_types_text_bytes(f->fn->consts[a].value),
val, &e) != 0)
return xdeliver(f->vm, &e);
return 0;
}
static void xkey(CAT_VALUE_Value *idx, char *buf, size_t n)
{
if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER)
snprintf(buf, n, "%lld", cat_types_number_as_int(idx));
else
snprintf(buf, n, "%s", cat_types_text_bytes(idx));
}
int cat_backend_x86_64_getidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *idx = f->stack[--f->sp];
CAT_VALUE_Value *obj = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
char key[64];
(void)a; (void)b; (void)c;
cat_error_clear(&e);
xkey(idx, key, sizeof(key));
if (cat_value_get_attribute(obj, key, &r, &e) != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_setidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *val = f->stack[--f->sp];
CAT_VALUE_Value *idx = f->stack[--f->sp];
CAT_VALUE_Value *obj = f->stack[--f->sp];
CAT_ERROR_Error e;
char key[64];
(void)a; (void)b; (void)c;
cat_error_clear(&e);
xkey(idx, key, sizeof(key));
if (cat_value_set_attribute(obj, key, val, &e) != 0)
return xdeliver(f->vm, &e);
return 0;
}
int cat_backend_x86_64_call(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
int n = (int)a;
CAT_VALUE_Value *fnv = f->stack[f->sp - n - 1];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
(void)b; (void)c;
cat_error_clear(&e);
if (cat_vm_call_value(f->vm, fnv, &f->stack[f->sp - n], n, &r, &e) != 0)
return xdeliver(f->vm, &e);
f->sp -= n + 1;
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_callmethod(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
int n = (int)a;
CAT_VALUE_Value *obj = f->stack[f->sp - n - 1];
CAT_VALUE_Value *method = NULL;
CAT_VALUE_Value *callargs[257];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
int j, st;
(void)c;
cat_error_clear(&e);
if (cat_value_get_attribute(obj, cat_types_text_bytes(f->fn->consts[b].value),
&method, &e) != 0)
return xdeliver(f->vm, &e);
callargs[0] = obj;
for (j = 0; j < n && j < 256; j++)
callargs[j + 1] = f->stack[f->sp - n + j];
st = cat_vm_call_value(f->vm, method, callargs, n + 1, &r, &e);
if (st != 0)
return xdeliver(f->vm, &e);
f->sp -= n + 1;
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_print(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
cat_vm_print_value(f->stack[--f->sp]);
return 0;
}
int cat_backend_x86_64_printexpr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *v = f->stack[--f->sp];
(void)a; (void)b; (void)c;
if (v == NULL || cat_types_empty_is(v))
return 0;
printf("%s\n", cat_types_text_bytes(cat_value_repr(v)));
return 0;
}
int cat_backend_x86_64_is(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *iface = f->stack[--f->sp];
CAT_VALUE_Value *obj = f->stack[--f->sp];
int r = 0;
CAT_ERROR_Error e;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
if (cat_value_is(obj, iface, &r, &e) != 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = r ? cat_types_bool_true() : cat_types_bool_false();
return 0;
}
int cat_backend_x86_64_next(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *it = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
int nr;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
nr = cat_value_next(it, &r, &e);
if (nr < 0)
return xdeliver(f->vm, &e);
f->stack[f->sp++] = (nr == 0 && r) ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_popcond(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *cond = f->stack[--f->sp];
CAT_ERROR_Error e;
int t = 1;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
cat_value_truthy(cond, &t, &e);
return t ? 1 : 0;
}
int cat_backend_x86_64_fornext(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *it = f->stack[--f->sp];
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error e;
int nr;
(void)a; (void)b; (void)c;
cat_error_clear(&e);
nr = cat_value_next(it, &r, &e);
if (nr < 0)
return xdeliver(f->vm, &e);
if (nr == 1)
return 1;
f->stack[f->sp++] = r ? r : cat_types_empty();
return 0;
}
int cat_backend_x86_64_return(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
f->ret = f->stack[--f->sp];
return 0;
}
int cat_backend_x86_64_trysetup(CAT_BACKEND_X86_64_Frame *f, long target, long b, long c)
{
(void)b; (void)c;
if (f->nhandlers < CAT_VM_MAXHANDLER) {
f->handlers[f->nhandlers].target = (void *)target;
f->handlers[f->nhandlers].sp = f->sp;
f->nhandlers++;
}
return 0;
}
int cat_backend_x86_64_tryend(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
(void)a; (void)b; (void)c;
if (f->nhandlers > 0)
f->nhandlers--;
return 0;
}
int cat_backend_x86_64_raise(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c)
{
CAT_VALUE_Value *v = f->stack[--f->sp];
const char *msg = (v && v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT)
? cat_types_text_bytes(v) : "raised";
(void)a; (void)b; (void)c;
cat_error_raise_value(&f->vm->err, v, "%s", msg);
return -1;
}
int cat_backend_x86_64_top_call(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out)
{
CAT_BACKEND_X86_64_Frame f;
CAT_BACKEND_X86_64_Entry entry = (CAT_BACKEND_X86_64_Entry)cl->proto->nat_entry;
CAT_VM_State *prev = cat_vm_current();
int rc;
cat_backend_x86_64_frame_init(&f, vm, cl, args, nargs);
cat_vm_set_current(vm);
rc = entry(&f);
cat_vm_set_current(prev);
*out = rc == 0 ? (f.ret ? f.ret : cat_types_empty())
: cat_types_empty();
cat_backend_x86_64_frame_done(&f);
return rc;
}
/* ---- bytecode rebuild helpers for generated `main` ---- */
CAT_BYTECODE_Function *cat_backend_x86_64_fn_new(const char *name)
{
return cat_bytecode_function_new(name);
}
void cat_backend_x86_64_fn_setup(CAT_BYTECODE_Function *fn, long nparams,
long nlocals, long is_generator)
{
fn->nparams = (int)nparams;
fn->nlocals = (int)nlocals;
fn->is_generator = (int)is_generator;
}
void cat_backend_x86_64_fn_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v)
{
cat_bytecode_add_const(fn, v);
}
void cat_backend_x86_64_fn_emit(CAT_BYTECODE_Function *fn, long op, long a,
long b, long c, long line)
{
cat_bytecode_emit(fn, (unsigned char)op, (int)a, (int)b, (int)c,
(int)line);
}
void cat_backend_x86_64_fn_add_proto(CAT_BYTECODE_Function *fn, CAT_BYTECODE_Function *p)
{
cat_bytecode_add_proto(fn, p);
}
void cat_backend_x86_64_fn_set_entry(CAT_BYTECODE_Function *fn, void *entry)
{
fn->nat_entry = entry;
}
+1 -1
View File
@@ -88,7 +88,7 @@ static const char *op_name(unsigned char op)
"SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF",
"JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE",
"GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT",
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR"
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR", "IS"
};
if (op < sizeof(names) / sizeof(names[0]))
return names[op];
+311 -19
View File
@@ -25,9 +25,13 @@
#include "cat/compiler.h"
#include "cat/lexer.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/float.h"
#include "cat/types/ascii_text.h"
#include "cat/types/type.h"
#include <stdarg.h>
#include <stdio.h>
@@ -40,6 +44,8 @@
typedef struct {
CAT_BYTECODE_Function *fn;
char locals[MAXLOCALS][64];
CAT_TYPES_TYPE_Type *local_types[MAXLOCALS]; /* declared/inferred */
CAT_TYPES_TYPE_Type *ret_type; /* declared `-> T` (or any) */
int nlocals;
int is_generator; /* body used `yield` */
} FuncCtx;
@@ -56,6 +62,7 @@ typedef struct {
int brk_n[16];
int nloops;
int repl; /* REPL mode: a lone expression is echoed */
CAT_VM_State *ct_vm; /* embedded VM for `comptime` (lazy) */
} Compiler;
static void err_at(Compiler *c, int line, const char *fmt, ...)
@@ -152,6 +159,7 @@ static int add_local(Compiler *c, const char *name)
return -1;
slot = f->nlocals++;
snprintf(f->locals[slot], sizeof(f->locals[slot]), "%s", name);
f->local_types[slot] = NULL;
if (f->nlocals > f->fn->nlocals)
f->fn->nlocals = f->nlocals;
return slot;
@@ -191,6 +199,7 @@ static int bp_of(int kind)
case CAT_LEXER_TOK_EQ: case CAT_LEXER_TOK_NE:
case CAT_LEXER_TOK_LT: case CAT_LEXER_TOK_LE:
case CAT_LEXER_TOK_GT: case CAT_LEXER_TOK_GE: return 3;
case CAT_LEXER_TOK_IS: return 3;
case CAT_LEXER_TOK_CONCAT: return 4;
case CAT_LEXER_TOK_PLUS: case CAT_LEXER_TOK_MINUS: return 5;
case CAT_LEXER_TOK_STAR: case CAT_LEXER_TOK_SLASH:
@@ -199,17 +208,21 @@ static int bp_of(int kind)
}
}
/* Skip an advisory type expression: e.g. `: int`, `: cbyte[]`,
* `: DynSized()`, `: sentinel_sized<'\0'>`. Types are advisory only
* (catscript is structurally typed), so we parse and discard a full
* balanced type expression, ignoring `()`, `<>`, `[]` nesting. */
static void skip_type_hint(Compiler *c)
/* Parse an optional type hint: e.g. `: int`, `: cbyte[]`,
* `: DynSized()`, `: sentinel_sized<0>`. We consume a full balanced
* expression (ignoring `()`, `<>`, `[]` nesting) and return the
* descriptor of the FIRST identifier -- structural typing: the first
* name IS the type. With no `:` it returns `any`. */
static CAT_TYPES_TYPE_Type *parse_type_core(Compiler *c, int colon)
{
CAT_TYPES_TYPE_Type *t = NULL;
int depth = 0;
if (colon) {
if (!check(c, CAT_LEXER_TOK_COLON))
return;
return cat_types_type_any();
next(c);
}
for (;;) {
int k = c->tok.kind;
if (k == CAT_LEXER_TOK_LPAREN || k == CAT_LEXER_TOK_LT ||
@@ -226,14 +239,111 @@ static void skip_type_hint(Compiler *c)
next(c);
continue;
}
if ((k == CAT_LEXER_TOK_NAME || k == CAT_LEXER_TOK_INT ||
k == CAT_LEXER_TOK_STRING) ||
(k == CAT_LEXER_TOK_COMMA && depth > 0)) {
if (k == CAT_LEXER_TOK_NAME) {
if (t == NULL)
t = cat_types_type_named(c->tok.text);
next(c);
continue;
}
if (k == CAT_LEXER_TOK_INT || k == CAT_LEXER_TOK_STRING) {
next(c);
continue;
}
if (k == CAT_LEXER_TOK_COMMA && depth > 0) {
next(c);
continue;
}
break;
}
return (t != NULL) ? t : cat_types_type_any();
}
static CAT_TYPES_TYPE_Type *parse_type_hint(Compiler *c)
{
return parse_type_core(c, 1);
}
/* Parse an optional `<T, U, ...>` type-parameter list at the cursor.
* Returns the number of parameters (0 when there is none). When `out`
* is given, the parameter names are written there joined by commas
* (e.g. "T,U"), so a declaration can tag itself with its parameters. */
static int parse_type_params(Compiler *c, char *out, size_t outsz)
{
int n = 0;
size_t used = 0;
if (!check(c, CAT_LEXER_TOK_LT))
return 0;
next(c);
if (out != NULL && outsz > 0)
out[0] = '\0';
while (!check(c, CAT_LEXER_TOK_GT) && !check(c, CAT_LEXER_TOK_EOF)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
if (out != NULL && used + strlen(c->tok.text) + 2 < outsz) {
if (used > 0)
out[used++] = ',';
strcpy(out + used, c->tok.text);
used += strlen(c->tok.text);
}
n++;
next(c);
}
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
expect(c, CAT_LEXER_TOK_GT, "'>'");
return n;
}
/* The type of the value the cursor is on, when it is a literal; NULL when
* the expression is not a simple literal (then we say nothing). */
static CAT_TYPES_TYPE_Type *literal_type(Compiler *c)
{
switch (c->tok.kind) {
case CAT_LEXER_TOK_INT: return cat_types_type_int();
case CAT_LEXER_TOK_FLOAT: return cat_types_type_float();
case CAT_LEXER_TOK_STRING: return cat_types_type_text();
case CAT_LEXER_TOK_TRUE:
case CAT_LEXER_TOK_FALSE: return cat_types_type_bool();
case CAT_LEXER_TOK_NIL: return cat_types_type_empty();
default: return NULL;
}
}
/* `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`. */
@@ -254,7 +364,7 @@ static int compile_function_literal(Compiler *c, const char *name)
char pn[64];
snprintf(pn, sizeof(pn), "%s", c->tok.text);
next(c);
skip_type_hint(c);
nc.local_types[nc.nlocals] = parse_type_hint(c);
/* add_local into nc directly */
snprintf(nc.locals[nc.nlocals], sizeof(nc.locals[0]), "%s", pn);
nc.nlocals++;
@@ -270,10 +380,10 @@ static int compile_function_literal(Compiler *c, const char *name)
sub->nlocals = nc.nlocals;
/* optional return type hint */
if (accept(c, CAT_LEXER_TOK_ARROW)) {
if (check(c, CAT_LEXER_TOK_NAME))
next(c);
}
if (accept(c, CAT_LEXER_TOK_ARROW))
nc.ret_type = parse_type_core(c, 0);
else
nc.ret_type = cat_types_type_any();
/* push context and compile body */
c->stack[c->nstack++] = nc;
@@ -388,6 +498,26 @@ static void primary(Compiler *c)
expect(c, CAT_LEXER_TOK_RBRACE, "'}'");
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: {
char name[256];
int slot;
@@ -560,6 +690,9 @@ static void expr_bp(Compiler *c, int minbp)
}
next(c);
expr_bp(c, bp + 1);
if (kind == CAT_LEXER_TOK_IS)
emit(c, CAT_BYTECODE_OP_IS, 0, 0, c->tok.line);
else
emit(c, binop_for(kind), 0, 0, c->tok.line);
}
}
@@ -614,17 +747,28 @@ static void stat(Compiler *c)
if (check(c, CAT_LEXER_TOK_NAME)) {
char name[256];
int slot;
CAT_TYPES_TYPE_Type *decl;
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
skip_type_hint(c);
if (accept(c, CAT_LEXER_TOK_ASSIGN))
decl = parse_type_hint(c);
if (accept(c, CAT_LEXER_TOK_ASSIGN)) {
CAT_TYPES_TYPE_Type *lit = literal_type(c);
if (lit != NULL &&
!cat_types_type_assignable(decl, lit))
err_at(c, line,
"cannot assign %s to %s",
cat_types_type_name(lit),
cat_types_type_name(decl));
expr(c);
else
} else {
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, line);
}
slot = add_local(c, name);
if (slot >= 0)
if (slot >= 0) {
ctx(c)->local_types[slot] = decl;
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
}
}
break;
case CAT_LEXER_TOK_IF: {
@@ -707,7 +851,7 @@ static void stat(Compiler *c)
snprintf(var, sizeof(var), "%s", c->tok.text);
next(c);
}
skip_type_hint(c);
(void)parse_type_hint(c);
if (check(c, CAT_LEXER_TOK_IN)) {
/* for NAME in expr do <body> end -- iterate any iterator
* (generator). Each round calls NEXT; empty ends the loop. */
@@ -826,19 +970,41 @@ static void stat(Compiler *c)
* class's `init` if present. The table is bound to a global NAME. */
char name[256];
char base[256];
char impl[8][256];
char tparams[256];
int nparams_t;
int nimpl = 0;
int i;
next(c);
name[0] = '\0';
base[0] = '\0';
tparams[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
nparams_t = parse_type_params(c, tparams, sizeof(tparams));
if (accept(c, CAT_LEXER_TOK_EXTENDS)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(base, sizeof(base), "%s", c->tok.text);
next(c);
}
}
if (check(c, CAT_LEXER_TOK_NAME) &&
strcmp(c->tok.text, "implements") == 0) {
next(c);
for (;;) {
if (check(c, CAT_LEXER_TOK_NAME)) {
if (nimpl < 8)
snprintf(impl[nimpl], sizeof(impl[0]),
"%s", c->tok.text);
nimpl++;
next(c);
}
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* __index: base (inheritance) or the class itself */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
@@ -875,6 +1041,110 @@ static void stat(Compiler *c)
}
expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
if (nparams_t > 0) {
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
emit(c, CAT_BYTECODE_OP_CONST,
add_string(c, tparams), 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR,
add_string(c, "__generic"), 0, line);
}
/* runtime assertion: the class must satisfy each declared interface
* (structural check, performed by __implements_check), and gets any
* trait's default methods mixed in (a no-op for plain interfaces). */
for (i = 0; i < nimpl && i < 8; i++) {
/* mix a trait's defaults in FIRST, then assert the class
* satisfies the contract (a plain interface adds nothing). */
emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, "__trait_mixin"), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, impl[i]), 0, line);
emit(c, CAT_BYTECODE_OP_CALL, 2, 0, line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, "__implements_check"), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, impl[i]), 0, line);
emit(c, CAT_BYTECODE_OP_CALL, 2, 0, line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
}
break;
}
case CAT_LEXER_TOK_TRAIT:
case CAT_LEXER_TOK_INTERFACE: {
/* interface|trait NAME [extends BASE] <function m(...) end> end
*
* Both build a table tagged `__interface` so the `is` operator and
* the runtime check work the same way. A `trait` is additionally
* tagged `__trait`: its methods carry default bodies, and a class
* that `implements` it has those methods mixed in. */
char name[256];
char base[256];
char tparams[256];
int nparams_t;
int is_trait = (c->tok.kind == CAT_LEXER_TOK_TRAIT);
next(c);
name[0] = '\0';
base[0] = '\0';
tparams[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
nparams_t = parse_type_params(c, tparams, sizeof(tparams));
if (accept(c, CAT_LEXER_TOK_EXTENDS)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(base, sizeof(base), "%s", c->tok.text);
next(c);
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* the interface marker, so `is` knows to check structurally */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__interface"), 0, line);
if (is_trait) {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__trait"), 0, line);
}
/* interface/trait inheritance */
if (base[0] != '\0') {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, base), 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__index"), 0, line);
}
while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF)) {
if (!check(c, CAT_LEXER_TOK_FUNCTION)) {
err_at(c, c->tok.line,
"expected 'function' or 'end' in %s",
is_trait ? "trait" : "interface");
break;
}
next(c);
{
char mname[256];
int proto;
mname[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
}
proto = compile_function_literal(c, mname);
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, mname), 0, line);
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
if (nparams_t > 0) {
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
emit(c, CAT_BYTECODE_OP_CONST,
add_string(c, tparams), 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR,
add_string(c, "__generic"), 0, line);
}
break;
}
@@ -884,6 +1154,13 @@ static void stat(Compiler *c)
!check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) &&
!check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) &&
!check(c, CAT_LEXER_TOK_EXCEPT)) {
CAT_TYPES_TYPE_Type *lit = literal_type(c);
CAT_TYPES_TYPE_Type *want = ctx(c)->ret_type;
if (lit != NULL && want != NULL &&
!cat_types_type_assignable(want, lit))
err_at(c, line, "cannot return %s from function returning %s",
cat_types_type_name(lit),
cat_types_type_name(want));
expr(c);
emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line);
} else {
@@ -1068,6 +1345,18 @@ static void block(Compiler *c)
next(c);
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);
if (c->failed)
break;
@@ -1106,6 +1395,9 @@ CAT_BYTECODE_Function *cat_compiler_compile_mode(const char *source,
block(&c);
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) {
cat_bytecode_function_free(fn);
return NULL;
+5
View File
@@ -25,6 +25,10 @@ static const struct kw g_keywords[] = {
{ "except", CAT_LEXER_TOK_EXCEPT },
{ "end", CAT_LEXER_TOK_END },
{ "extends", CAT_LEXER_TOK_EXTENDS },
{ "interface", CAT_LEXER_TOK_INTERFACE },
{ "is", CAT_LEXER_TOK_IS },
{ "comptime", CAT_LEXER_TOK_COMPTIME },
{ "trait", CAT_LEXER_TOK_TRAIT },
{ "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR },
{ "function", CAT_LEXER_TOK_FUNCTION },
@@ -288,6 +292,7 @@ const char *cat_lexer_kind_name(int kind)
"for", "function", "if", "in", "local", "nil", "not",
"or", "repeat", "return", "then", "true", "until", "while",
"yield", "try", "except", "raise", "use", "class", "extends",
"interface", "implements", "is", "comptime", "trait",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=",
"<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",",
".", ":", "::", "..", "->"
+114
View File
@@ -606,6 +606,101 @@ static int lf_class_new(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
return 0;
}
/* `implements(obj, iface)` -- structural runtime test: does `obj` answer
* every method the interface `iface` requires? Mirrors the `is`
* operator. */
static int lf_implements(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
int r = 0;
if (nargs < 2 || args[0] == NULL || args[1] == NULL) {
*out = cat_types_bool_false();
return 0;
}
if (cat_value_is(args[0], args[1], &r, &vm->err) != 0)
return -1;
*out = r ? cat_types_bool_true() : cat_types_bool_false();
return 0;
}
/* `__implements_check(cls, iface)` -- emitted after a class that declares
* `implements I`: raises unless the class satisfies the interface. */
static int lf_implements_check(CAT_VM_State *vm, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out)
{
int r = 0;
if (nargs < 2 || args[0] == NULL || args[1] == NULL) {
*out = cat_types_empty();
return 0;
}
if (cat_value_is(args[0], args[1], &r, &vm->err) != 0)
return -1;
if (!r) {
CAT_VALUE_Value *nm = NULL;
CAT_ERROR_Error e;
const char *iname = "interface";
cat_error_clear(&e);
if (cat_value_get_attribute(args[1], "name", &nm, &e) == 0 &&
nm != NULL && nm->vtable &&
nm->vtable->kind == CAT_VALUE_KIND_TEXT)
iname = cat_types_text_bytes(nm);
return (cat_error_raise(&vm->err,
"class %s does not implement %s",
cat_value_type_name(args[0]), iname), -1);
}
*out = cat_types_empty();
return 0;
}
/* `__trait_mixin(cls, trait)` -- copy a trait's default methods into a
* class that implements it (a mix-in). Existing class members win. */
static int lf_trait_mixin(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_VALUE_Value *cls;
CAT_VALUE_Value *tr;
CAT_VALUE_Value *marker = NULL;
CAT_ERROR_Error e;
int i;
if (nargs < 2 || args[0] == NULL || args[1] == NULL) {
*out = cat_types_empty();
return 0;
}
cls = args[0];
tr = args[1];
cat_error_clear(&e);
if (cat_value_get_attribute(tr, "__trait", &marker, &e) != 0 ||
marker == NULL) {
*out = cat_types_empty();
return 0; /* not a trait: nothing to mix in */
}
if (tr->vtable != cat_types_table_vtable() ||
cls->vtable != cat_types_table_vtable()) {
*out = cat_types_empty();
return 0;
}
for (i = 0; i < cat_types_table_count(tr); i++) {
const char *k = cat_types_table_key_at(tr, i);
CAT_VALUE_Value *v;
CAT_VALUE_Value *existing = NULL;
if (strncmp(k, "__", 2) == 0)
continue;
cat_error_clear(&e);
if (cat_types_table_get(cls, k, &existing, &e) == 0)
continue; /* the class already provides it */
v = cat_types_table_value_at(tr, i);
cat_error_clear(&e);
cat_types_table_set(cls, k, v, &e);
}
*out = cat_types_empty();
return 0;
}
static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
@@ -669,6 +764,11 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
cat_types_native_new_doc(std[i].name, std[i].cb,
std[i].doc));
cat_vm_register_native(vm, "__class_new", lf_class_new);
cat_vm_register_native(vm, "__implements_check", lf_implements_check);
cat_vm_register_native(vm, "__trait_mixin", lf_trait_mixin);
cat_vm_set_global_owned(vm, "implements",
cat_types_native_new_doc("implements", lf_implements,
"implements(obj, iface) -- teste estrutural: obj atende a interface?"));
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
cat_vm_set_global_owned(vm, "AbstractFile",
cat_types_native_new("AbstractFile", lf_abstractfile));
@@ -685,6 +785,20 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
cat_vm_set_global_owned(vm, "memory",
cat_types_native_new_doc("memory", lf_memory,
"memory(n) -- buffer de n bytes com limites verificados."));
/* `Sized` -- the marker interface for "layout known at compile time".
* Every concrete catscript value has a known layout, so every value
* satisfies it; it exists so signatures can express the bound
* (`buf : Sized()`) and the checker can reason about it. */
{
CAT_VALUE_Value *sized = cat_types_table_new();
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(sized, "__interface", cat_types_bool_true(), &e);
cat_error_clear(&e);
cat_types_table_set(sized, "__sized", cat_types_bool_true(), &e);
cat_vm_set_global_owned(vm, "Sized", sized);
}
/* `module` reflects the unit currently executing (name/path/dir) */
cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL));
return 0;
+139
View File
@@ -0,0 +1,139 @@
/*
* cat/types/type.c -- compile-time type descriptors.
*
* Naming rule: symbols here are cat_types_type_* / CAT_TYPES_TYPE_*.
*
* All descriptors are immortal singletons (no teardown): a compiler
* process interns a bounded, small set of names.
*/
#include "cat/types/type.h"
#include <stdlib.h>
#include <string.h>
/* One descriptor per primitive. Names are lowercase per the language
* rule. */
static CAT_TYPES_TYPE_Type g_any = { "any", CAT_TYPES_TYPE_ANY };
static CAT_TYPES_TYPE_Type g_empty = { "empty", CAT_TYPES_TYPE_EMPTY };
static CAT_TYPES_TYPE_Type g_bool = { "bool", CAT_TYPES_TYPE_BOOL };
static CAT_TYPES_TYPE_Type g_int = { "int", CAT_TYPES_TYPE_INT };
static CAT_TYPES_TYPE_Type g_float = { "float", CAT_TYPES_TYPE_FLOAT };
static CAT_TYPES_TYPE_Type g_text = { "text", CAT_TYPES_TYPE_TEXT };
static CAT_TYPES_TYPE_Type g_object = { "object", CAT_TYPES_TYPE_OBJECT };
static CAT_TYPES_TYPE_Type g_function = { "function", CAT_TYPES_TYPE_FUNCTION };
static CAT_TYPES_TYPE_Type g_list = { "list", CAT_TYPES_TYPE_LIST };
static CAT_TYPES_TYPE_Type g_memory = { "memory", CAT_TYPES_TYPE_MEMORY };
/* Interned named types. A small open-addressed table of string -> Type. */
#define NAMED_CAP 512
static CAT_TYPES_TYPE_Type *g_named[NAMED_CAP];
CAT_TYPES_TYPE_Type *cat_types_type_any(void) { return &g_any; }
CAT_TYPES_TYPE_Type *cat_types_type_empty(void) { return &g_empty; }
CAT_TYPES_TYPE_Type *cat_types_type_bool(void) { return &g_bool; }
CAT_TYPES_TYPE_Type *cat_types_type_int(void) { return &g_int; }
CAT_TYPES_TYPE_Type *cat_types_type_float(void) { return &g_float; }
CAT_TYPES_TYPE_Type *cat_types_type_text(void) { return &g_text; }
CAT_TYPES_TYPE_Type *cat_types_type_object(void) { return &g_object; }
CAT_TYPES_TYPE_Type *cat_types_type_function(void) { return &g_function; }
CAT_TYPES_TYPE_Type *cat_types_type_list(void) { return &g_list; }
CAT_TYPES_TYPE_Type *cat_types_type_memory(void) { return &g_memory; }
CAT_TYPES_TYPE_Type *cat_types_type_named(const char *name)
{
unsigned long h = 5381;
const char *p;
size_t slot;
if (name == NULL || name[0] == '\0')
return &g_any;
/* Known primitives are their singletons, not new named types. */
if (strcmp(name, "any") == 0) return &g_any;
if (strcmp(name, "empty") == 0) return &g_empty;
if (strcmp(name, "bool") == 0) return &g_bool;
if (strcmp(name, "int") == 0) return &g_int;
if (strcmp(name, "float") == 0) return &g_float;
if (strcmp(name, "text") == 0) return &g_text;
if (strcmp(name, "object") == 0) return &g_object;
if (strcmp(name, "function") == 0 ||
strcmp(name, "closure") == 0) return &g_function;
if (strcmp(name, "list") == 0) return &g_list;
if (strcmp(name, "memory") == 0) return &g_memory;
for (p = name; *p != '\0'; p++)
h = ((h << 5) + h) + (unsigned char)*p;
slot = h % NAMED_CAP;
for (;;) {
if (g_named[slot] == NULL) {
CAT_TYPES_TYPE_Type *t = calloc(1, sizeof(*t));
if (t == NULL)
return &g_any;
t->name = strdup(name);
t->kind = CAT_TYPES_TYPE_NAMED;
g_named[slot] = t;
return t;
}
if (g_named[slot]->kind == CAT_TYPES_TYPE_NAMED &&
strcmp(g_named[slot]->name, name) == 0)
return g_named[slot];
slot = (slot + 1) % NAMED_CAP;
}
}
const char *cat_types_type_name(const CAT_TYPES_TYPE_Type *t)
{
return (t != NULL) ? t->name : "any";
}
int cat_types_type_equal(const CAT_TYPES_TYPE_Type *a,
const CAT_TYPES_TYPE_Type *b)
{
if (a == b)
return 1;
if (a == NULL || b == NULL)
return 0;
if (a->kind != b->kind)
return 0;
if (a->kind == CAT_TYPES_TYPE_NAMED)
return strcmp(a->name, b->name) == 0;
return 1;
}
int cat_types_type_assignable(const CAT_TYPES_TYPE_Type *dst,
const CAT_TYPES_TYPE_Type *src)
{
if (dst == NULL || src == NULL)
return 1;
if (dst->kind == CAT_TYPES_TYPE_ANY || src->kind == CAT_TYPES_TYPE_ANY)
return 1;
if (cat_types_type_equal(dst, src))
return 1;
/* int widens to float */
if (dst->kind == CAT_TYPES_TYPE_FLOAT && src->kind == CAT_TYPES_TYPE_INT)
return 1;
/* A named/opaque type is structural: we do not know its members, so
* we never reject a concrete value against it (or vice versa). Only
* two KNOWN, CONCRETE, distinct primitives fail. */
if (dst->kind == CAT_TYPES_TYPE_NAMED || src->kind == CAT_TYPES_TYPE_NAMED)
return 1;
return 0;
}
CAT_TYPES_TYPE_Type *cat_types_type_join(const CAT_TYPES_TYPE_Type *a,
const CAT_TYPES_TYPE_Type *b)
{
if (a == NULL || b == NULL)
return &g_any;
if (a->kind == CAT_TYPES_TYPE_ANY || b->kind == CAT_TYPES_TYPE_ANY)
return &g_any;
if (a->kind == CAT_TYPES_TYPE_FLOAT || b->kind == CAT_TYPES_TYPE_FLOAT) {
/* float dominates numeric combinations */
if (a->kind == CAT_TYPES_TYPE_FLOAT ||
a->kind == CAT_TYPES_TYPE_INT)
return &g_float;
}
if (cat_types_type_equal(a, b))
return (CAT_TYPES_TYPE_Type *)a;
return &g_any;
}
+73
View File
@@ -306,6 +306,79 @@ int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name,
"type %s has no attribute '%s'", cat_value_type_name(self), name), -1);
}
/* Does `obj` answer member `name`? Used by the structural `is` test. */
static int obj_has_member(CAT_VALUE_Value *obj, const char *name)
{
CAT_VALUE_Value *tmp = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
return cat_value_get_attribute(obj, name, &tmp, &e) == 0;
}
int cat_value_is(CAT_VALUE_Value *obj, CAT_VALUE_Value *iface, int *out,
CAT_ERROR_Error *err)
{
CAT_ERROR_Error e;
CAT_VALUE_Value *marker = NULL;
int is_iface = 0;
if (out != NULL)
*out = 0;
if (obj == NULL || iface == NULL)
return 0;
/* An interface is a table tagged with `__interface`; follow interface
* inheritance (`__index`) too. Anything else degrades to an exact
* type (vtable) match, so `x is SomeClass` still reads naturally. */
cat_error_clear(&e);
if (cat_value_get_attribute(iface, "__interface", &marker, &e) == 0 &&
marker != NULL)
is_iface = 1;
if (!is_iface) {
if (out != NULL)
*out = (obj->vtable == iface->vtable);
return 0;
}
if (iface->vtable != cat_types_table_vtable()) {
if (out != NULL)
*out = 0;
return 0;
}
{
int i, ok = 1;
/* every required method (a key not starting with `__`) must be
* answered by the object: this is structural typing at runtime. */
for (i = 0; i < cat_types_table_count(iface) && ok; i++) {
const char *k = cat_types_table_key_at(iface, i);
if (strncmp(k, "__", 2) == 0)
continue;
if (!obj_has_member(obj, k))
ok = 0;
}
if (ok) {
CAT_VALUE_Value *base = NULL;
cat_error_clear(&e);
if (cat_value_get_attribute(iface, "__index", &base, &e) == 0 &&
base != NULL && base != iface) {
int sub = 0;
if (cat_value_is(obj, base, &sub, err) != 0 || !sub)
ok = 0;
}
}
if (out != NULL)
*out = ok;
}
return 0;
}
int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
+29 -6
View File
@@ -24,6 +24,7 @@
#include "cat/types/function.h"
#include "cat/types/native.h"
#include "cat/types/generator.h"
#include "cat/backend/x86_64.h"
#include <stdio.h>
#include <stdlib.h>
@@ -39,6 +40,11 @@ CAT_VM_State *cat_vm_current(void)
return g_current_vm;
}
void cat_vm_set_current(CAT_VM_State *vm)
{
g_current_vm = vm;
}
CAT_VM_State *cat_vm_new(void)
{
CAT_VM_State *vm = calloc(1, sizeof(*vm));
@@ -107,11 +113,11 @@ static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from)
/* Call any callable value: native, closure, or generator factory. A
* closure whose prototype contains `yield` is not executed here; it
* produces a generator (lazy). */
static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
static void print_value(CAT_VALUE_Value *v)
void cat_vm_print_value(CAT_VALUE_Value *v)
{
if (v == NULL)
printf("empty\n");
@@ -351,7 +357,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
CAT_VALUE_Value *fnv = stack[sp - n - 1];
CAT_VALUE_Value *r = NULL;
int st;
st = call_value(vm, fnv, &stack[sp - n], n, &r, &e);
st = cat_vm_call_value(vm, fnv, &stack[sp - n], n, &r, &e);
if (st != 0) { deliver_error(vm, &e); goto on_error; }
sp -= n + 1;
stack[sp++] = r ? r : cat_types_empty();
@@ -373,7 +379,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
callargs[j + 1] = stack[sp - n + j];
{
CAT_VALUE_Value *r = NULL;
int st = call_value(vm, method, callargs, n + 1, &r, &e);
int st = cat_vm_call_value(vm, method, callargs, n + 1, &r, &e);
if (st != 0) { deliver_error(vm, &e); goto on_error; }
sp -= n + 1;
stack[sp++] = r ? r : cat_types_empty();
@@ -478,7 +484,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
}
case CAT_BYTECODE_OP_PRINT: {
CAT_VALUE_Value *v = stack[--sp];
print_value(v);
cat_vm_print_value(v);
break;
}
case CAT_BYTECODE_OP_PRINTEXPR: {
@@ -493,6 +499,18 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
printf("%s\n", cat_types_text_bytes(s));
break;
}
case CAT_BYTECODE_OP_IS: {
/* pop iface, pop obj -> push (obj is iface), structural */
CAT_VALUE_Value *iface = stack[--sp];
CAT_VALUE_Value *obj = stack[--sp];
int r = 0;
if (cat_value_is(obj, iface, &r, &e) != 0) {
deliver_error(vm, &e); goto on_error;
}
stack[sp++] = r ? cat_types_bool_true()
: cat_types_bool_false();
break;
}
default:
break;
}
@@ -548,6 +566,11 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
*out = cat_types_generator_new(vm, cl, args, nargs);
return 0;
}
#ifdef __x86_64__
/* A prototype lowered by the native backend runs as machine code. */
if (cl->proto != NULL && cl->proto->nat_entry != NULL)
return cat_backend_x86_64_top_call(vm, cl, args, nargs, out);
#endif
memset(&f, 0, sizeof(f));
f.fn = cl->proto;
f.cl = cl;
@@ -570,7 +593,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
return 0;
}
static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
+123 -1
View File
@@ -17,6 +17,8 @@
#include "cat/module.h"
#include "cat/stdlib/stdlib.h"
#include "cat/stdlib/build.h"
#include "cat/backend/c.h"
#include "cat/backend/backend.h"
#include "cat/error.h"
#include <stdio.h>
@@ -141,20 +143,136 @@ static void main_repl(void)
static void main_usage(void)
{
printf("catscript -- a small Lua-like scripting language\n\n");
printf("catscript -- a small scripting language\n\n");
printf("usage:\n");
printf(" catscript <file.cat> run a script\n");
printf(" catscript --dump <file> print compiled bytecode\n");
printf(" catscript --emit-c <file> print the compiled C (AOT)\n");
printf(" catscript --build <file> <out> compile to a native binary\n");
printf(" catscript --backend <name> --emit <file> emit a backend's artifact\n");
printf(" catscript --backend <name> --build <file> <out> build with a backend\n");
printf(" catscript --list-backends list available backends\n");
printf(" catscript --help show this help\n");
printf(" catscript start a REPL\n");
}
/* `--list-backends`: one line per registered target. */
static int main_list_backends(void)
{
int i, n = cat_backend_count();
for (i = 0; i < n; i++) {
const CAT_BACKEND_Backend *b = cat_backend_at(i);
if (b == NULL)
continue;
printf("%-10s %-8s %s\n", b->name,
b->native ? "native" : "text", b->description);
}
return 0;
}
/* Emit a backend's artifact for a file to `out` (stdout when NULL). */
static int main_emit_backend(const CAT_BACKEND_Backend *b, const char *path,
FILE *out)
{
CAT_ERROR_Error err;
CAT_BYTECODE_Function *fn;
char *src = main_read_file(path);
int rc;
if (b == NULL || b->emit == NULL) {
fprintf(stderr, "catscript: backend cannot emit text\n");
return 1;
}
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", path);
return 1;
}
cat_error_clear(&err);
fn = cat_compiler_compile(src, &err);
free(src);
if (fn == NULL) {
fprintf(stderr, "catscript: %s\n", err.message);
return 1;
}
rc = b->emit(fn, main_basename(path), path, out);
cat_bytecode_function_free(fn);
return rc != 0;
}
/* `--emit-c`: compile a file and print the C translation unit. */
static int main_emit_c(const char *path)
{
return main_emit_backend(cat_backend_default(), path, stdout);
}
/* Build a native executable with a specific backend. */
static int main_build_backend(const CAT_BACKEND_Backend *b, const char *path,
const char *outpath)
{
CAT_ERROR_Error err;
CAT_BYTECODE_Function *fn;
char *src = main_read_file(path);
char errbuf[256];
int rc;
if (b == NULL || b->compile == NULL) {
fprintf(stderr, "catscript: backend cannot build a binary\n");
return 1;
}
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", path);
return 1;
}
cat_error_clear(&err);
fn = cat_compiler_compile(src, &err);
free(src);
if (fn == NULL) {
fprintf(stderr, "catscript: %s\n", err.message);
return 1;
}
rc = b->compile(fn, main_basename(path), path, outpath,
errbuf, sizeof(errbuf));
cat_bytecode_function_free(fn);
if (rc != 0) {
fprintf(stderr, "catscript: %s\n",
errbuf[0] ? errbuf : "cannot build native binary");
return 1;
}
return 0;
}
/* `--build <file> <out>`: compile a file to a native executable. */
static int main_build(const char *path, const char *outpath)
{
return main_build_backend(cat_backend_default(), path, outpath);
}
int main(int argc, char **argv)
{
if (argc >= 2 && strcmp(argv[1], "--help") == 0) {
main_usage();
return 0;
}
if (argc >= 2 && strcmp(argv[1], "--list-backends") == 0)
return main_list_backends();
/* --backend <name> {--emit <file> | --build <file> <out>} */
if (argc >= 3 && strcmp(argv[1], "--backend") == 0) {
const CAT_BACKEND_Backend *b = cat_backend_find(argv[2]);
if (b == NULL) {
fprintf(stderr, "catscript: unknown backend '%s'\n",
argv[2]);
return 1;
}
if (argc >= 5 && strcmp(argv[3], "--emit") == 0)
return main_emit_backend(b, argv[4], stdout);
if (argc >= 6 && strcmp(argv[3], "--build") == 0)
return main_build_backend(b, argv[4], argv[5]);
fprintf(stderr, "catscript: --backend needs --emit or --build\n");
return 1;
}
if (argc >= 3 && strcmp(argv[1], "--dump") == 0) {
char *src = main_read_file(argv[2]);
int rc;
@@ -166,6 +284,10 @@ int main(int argc, char **argv)
free(src);
return rc;
}
if (argc >= 3 && strcmp(argv[1], "--emit-c") == 0)
return main_emit_c(argv[2]);
if (argc >= 4 && strcmp(argv[1], "--build") == 0)
return main_build(argv[2], argv[3]);
if (argc >= 2) {
char *src = main_read_file(argv[1]);
int rc;
+32
View File
@@ -0,0 +1,32 @@
-- tests/aot.cat -- the C backend (ahead-of-time compilation).
--
-- Built with `catscript --build tests/aot.cat /tmp/aot_native`, this must
-- produce byte-for-byte the same stdout as the interpreter. It exercises
-- arithmetic, calls, recursion, objects, interfaces and structural `is`.
function add(a, b) return a + b end
print("add:", add(2, 3))
function fact(n)
if n <= 1 then return 1 end
return n * fact(n - 1)
end
print("fact:", fact(5))
local p = { x = 1, y = 2 }
p.x = p.x + 10
print("point:", p.x, p.y)
interface Shape
function area(self) end
end
class Square implements Shape
function init(self, side) self.side = side end
function area(self) return self.side * self.side end
end
local s = Square(4)
print("area:", s.area(), s is Shape)
print("text:", "ca" .. "tscript", 3 < 4, 5 == 5, not (2 == 3))
+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")
+32
View File
@@ -0,0 +1,32 @@
-- tests/generics.cat -- generic type parameters (erasure model).
--
-- `class Box<T>` / `interface Container<T>` accept a `<T, ...>` parameter
-- list. Parameter names are compile-time only (erased at runtime), so a
-- generic declaration is an ordinary class/interface tagged with its
-- parameters in `__generic` -- structural, like the rest of the typing.
class Box<T>
function init(self, v) self.v = v end
function get(self) return self.v end
end
interface Container<T>
function size(self) end
end
class Vec implements Container
function size(self) return 3 end
end
local b = Box("hi")
print("box:", b.get(), b::__generic)
local v = Vec()
print("vec:", v.size(), v is Container)
-- two parameters
class Pair<K, V>
function init(self, k, val) self.k = k self.val = val end
end
local p = Pair("x", 9)
print("pair:", p.k, p.val, p::__generic)
+47
View File
@@ -0,0 +1,47 @@
-- tests/interface.cat -- interfaces: structural typing at runtime.
--
-- `interface` declares a named contract; a class may declare
-- `implements I` (checked at class definition) and any object answers
-- the structural `is` operator, so a duck-typed object satisfies an
-- interface too.
interface Drawable
function draw() print("default draw") end
end
interface Shape extends Drawable
function area() return 0 end
end
class Circle implements Shape
function draw() print("draw circle") end
function area() return 3 end
end
local c = Circle()
print("circle is Drawable:", c is Drawable)
print("circle is Shape:", c is Shape)
c.draw()
print("circle area:", c.area())
-- a duck-typed object (no `implements`) still satisfies structurally
class Blob
function draw() print("blob draw") end
function area() return 1 end
end
local b = Blob()
print("blob is Drawable:", b is Drawable)
print("blob is Shape:", b is Shape)
-- an object missing a required method does not satisfy
class Line
function draw() print("line draw") end
end
local l = Line()
print("line is Drawable:", l is Drawable)
print("line is Shape:", l is Shape)
print("implements(c, Shape):", implements(c, Shape))
print("implements(l, Shape):", implements(l, Shape))
+87
View File
@@ -254,6 +254,63 @@ esac
# ---- self-hosted front-end (written in catscript) -------------------
out=`$BIN tests/traits.cat`
check "trait-default" "hello, Marcel" "`echo "$out" | sed -n 1p`"
check "trait-second" "HELLO, Marcel" "`echo "$out" | sed -n 2p`"
check "trait-is" "person is Greeter: true" "`echo "$out" | sed -n 3p`"
check "trait-override" "beep R2" "`echo "$out" | sed -n 4p`"
check "trait-robot" "robot is Greeter: true" "`echo "$out" | sed -n 6p`"
check "trait-sized" "sized: true" "`echo "$out" | sed -n 7p`"
check "trait-sized-fn" "implements Sized: true" "`echo "$out" | sed -n 8p`"
out=`$BIN tests/generics.cat`
check "generic-box" "box: hi T" "`echo "$out" | sed -n 1p`"
check "generic-iface" "vec: 3 true" "`echo "$out" | sed -n 2p`"
check "generic-pair" "pair: x 9 K,V" "`echo "$out" | sed -n 3p`"
out=`$BIN tests/aot.cat`
exp=`$BIN tests/aot.cat`
$BIN --build tests/aot.cat build/tests/aot_native >/dev/null 2>&1
if [ -x build/tests/aot_native ]; then
got=`build/tests/aot_native`
if [ "$exp" = "$got" ]; then
check "aot-native" "interpreter == native" "interpreter == native"
else
check "aot-native" "interpreter == native" "diverged: $got"
fi
else
check "aot-native" "native binary built" "missing"
fi
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`"
check "types-opaque" "opaque: 42 empty" "`echo "$out" | sed -n 3p`"
check "types-ret" "ret: 5" "`echo "$out" | sed -n 4p`"
# type hints are CHECKED where both sides are concrete
printf 'local x : int = "bad"\n' > /tmp/catscript_badtype.cat
if $BIN /tmp/catscript_badtype.cat >/dev/null 2>&1
then
check "types-reject" "reject" "accepted"
else
check "types-reject" "reject" "reject"
fi
rm -f /tmp/catscript_badtype.cat
out=`$BIN tests/interface.cat`
check "iface-is-sub" "circle is Drawable: true" "`echo "$out" | sed -n 1p`"
check "iface-is-inherited" "circle is Shape: true" "`echo "$out" | sed -n 2p`"
check "iface-method" "draw circle" "`echo "$out" | sed -n 3p`"
check "iface-duck" "blob is Shape: true" "`echo "$out" | sed -n 6p`"
check "iface-missing" "line is Shape: false" "`echo "$out" | sed -n 8p`"
check "iface-fn" "implements(c, Shape): true" "`echo "$out" | sed -n 9p`"
out=`$BIN tests/selfhost_lexer.cat`
case "$out" in
*"NAME [x]"*) check "selfhost-lexer" "yes" "yes" ;;
@@ -270,6 +327,36 @@ case "$out" in
*) check "selfhost-compile-2" "sum = 42" "missing" ;;
esac
# the native x86_64 backend must AGREE with the interpreter
cat > /tmp/cat_nat_eq.cat <<'EOCAT'
local i = 0
local acc = 0
while i < 5 do
acc = acc + i * 2
i = i + 1
end
print("acc", acc)
print("cmp", 3 < 4, "a" == "a")
local t = {}
t.x = 7
t["y"] = 8
print("t", t.x + t.y)
print("hi " .. "there")
EOCAT
want=`$BIN /tmp/cat_nat_eq.cat 2>&1`
if $BIN --backend x86_64 --build /tmp/cat_nat_eq.cat /tmp/cat_nat_eq_bin >/dev/null 2>&1 && [ -x /tmp/cat_nat_eq_bin ]
then
got=`/tmp/cat_nat_eq_bin 2>&1`
if [ "$got" = "$want" ]; then
check "nat-x86_64-eq" "match" "match"
else
check "nat-x86_64-eq" "match" "differs"
fi
else
check "nat-x86_64-eq" "skip" "skip"
fi
rm -f /tmp/cat_nat_eq.cat /tmp/cat_nat_eq_bin
echo ""
echo "$pass passed, $fail failed"
[ "$fail" -eq 0 ]
+35
View File
@@ -0,0 +1,35 @@
-- tests/traits.cat -- traits: interfaces with default methods (mix-in).
--
-- A `trait` is an interface whose methods carry default bodies. A class
-- that `implements` it gets those bodies mixed in (unless it defines its
-- own), and satisfies the trait structurally. Methods take explicit
-- `self`, like every method in catscript.
trait Greeter
function greet(self) return "hello, " .. self.name end
function loud(self) return "HELLO, " .. self.name end
end
class Person implements Greeter
function init(self, n) self.name = n end
end
-- a class may override a trait's default method
class Robot implements Greeter
function init(self, n) self.name = n end
function greet(self) return "beep " .. self.name end
end
local p = Person("Marcel")
print(p.greet())
print(p.loud())
print("person is Greeter:", p is Greeter)
local r = Robot("R2")
print(r.greet())
print(r.loud())
print("robot is Greeter:", r is Greeter)
-- Sized(): every concrete value has a known layout, so it is satisfied
print("sized:", p is Sized)
print("implements Sized:", implements(p, Sized))
+26
View File
@@ -0,0 +1,26 @@
-- tests/types.cat -- compile-time type checking of hints.
--
-- Hints are now CHECKED where both sides are concrete and known; opaque
-- or unknown names remain permissive (structural typing never rejects a
-- program by guessing).
local x : int = 42
local y : float = 3.5
local z : text = "hi"
local b : bool = true
print("ok:", x, y, z, b)
-- int widens to float
local f : float = 7
print("widen:", f)
-- opaque type names stay permissive (no false rejection)
local n : cint = 42
local buf : cbyte[] = empty
print("opaque:", n, buf)
-- return type hints are checked where concrete
function good() -> int
return 5
end
print("ret:", good())