Compare commits

..
14 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
Minus 7cdf388bf4 object, not table: fix user-facing terminology
The language is OOP with a single compound value, the object (an
anonymous `{...}` or a class instance); it is not Lua and has no
"tables".  The visible type name was already `object`; this fixes the
remaining user-facing wording:

- error messages: "object has no member 'x'", "object is not callable".
- README: drop the "Lua-like" phrasing; describe member objects, not
  tables.
- self-hosted front-end AST node `t="object"` (was "table"), updated
  across parser/compiler/checker.
- test comments/expected output aligned ("object:").

The internal C symbols keep the cat_types_table_* naming convention.
Suite stays 130 green.
2026-11-17 23:14:17 +00:00
Minus a73600e221 refcount: globals, modules and stdlib own their values
Extend the ownership discipline to the VM's global table and the
non-container value producers:

- cat_vm_set_global_owned: takes ownership of a freshly-created value
  (used for the native-registered globals and the `module` table).
- cat_vm_free releases the saved `module` stack entries and the globals
  table (which cascades: each stored value drops its reference).
- module enter/leave retains the saved `module` while it is off-global.
- stdlib/ffi/file build their tables with owned values and drop the
  transient reference after a store.

Suite stays 130 green.
2026-11-17 22:43:29 +00:00
Minus ee5861a25c refcount: own constants, closure attrs and generators
- bytecode constant pool: cat_bytecode_add_const retains, and
  cat_bytecode_function_free releases each constant, so a chunk owns its
  constants even when built from borrowed values (bc_run).  The compiler
  drops its own reference via add_const_owned.
- closures: function_destroy releases upvalues (if any) and the attrs
  table.
- generators: add a destroy that frees the operand stack and releases
  the captured closure and arguments; generator_new retains them.

Verified with AddressSanitizer (detect_leaks=0): suite 130 green, no
ASan reports.
2026-11-17 22:15:10 +00:00
Minus fddfa5dea2 refcount: containers own their values (table, list)
Wiring the reference count into the two value containers:

- cat_types_table_set retains the new value and releases the old one;
  table_destroy releases every stored value before freeing its own keys.
- cat_types_list_push / list_set_attribute retain; list_destroy releases.
- ffi library/function constructors set refcnt = 1 (they are heap-owned);
  selector singletons are immortal like empty/true/false.
- file / in-memory stream constructors set refcnt = 1.
- the stack-allocated closure in cat_vm_run is marked immortal so a
  stray release can never free stack storage.

Globals are a table, so they inherit the ownership rule for free.
Suite still 130 green.
2026-11-17 22:14:03 +00:00
Minus 22b8de3040 value: thread-safe reference counting foundation
Add an atomic reference count to the common value header and the
retain/release API, without changing any existing ownership behaviour
(containers still do not free their children, so nothing new is freed
and the suite stays green).

- CAT_VALUE_Value gains `_Atomic long refcnt`.
- cat_value_retain / cat_value_release use atomic RMW with acq_rel
  ordering; the last release calls vtable->destroy after an acquire
  fence.  cat_value_refcount and cat_value_make_immortal complete the
  API.
- every heap constructor sets refcnt = 1 (its creator's reference).
- singletons are immortal (refcnt = -1): the empty object and
  true/false, so they are never freed and need no locking.

This makes the COUNT safe to share across threads.  It does not make a
mutable object safe under concurrent writes.
2026-11-17 22:12:31 +00:00
54 changed files with 3129 additions and 97 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 $@ $<
+4 -4
View File
@@ -1,7 +1,7 @@
# catscript
Uma linguagem de scripting pequena, escrita em C, **100% orientada a
objetos**, com sintaxe parecida com Lua e **tipagem estrutural**.
objetos**, com sintaxe enxuta e **tipagem estrutural**.
Este repositório contém:
@@ -64,7 +64,7 @@ parser, o checker e o compiler são programas catscript**:
- `src/catscript/compiler.cat` — gera bytecode a partir da AST.
O runtime C expõe primitivas (`bc_run`, `bc_dump`) que transformam uma
"chunk" (uma tabela catscript: `{name, nparams, nlocals, consts, protos,
"chunk" (um objeto catscript: `{name, nparams, nlocals, consts, protos,
code}`) em bytecode executável. Assim, código catscript compila e executa
código catscript.
@@ -339,8 +339,8 @@ Vulkan roda **headless** (lavapipe/llvmpipe); GLFW precisa de um display
## Funções também são objetos
Uma closure tem sua própria tabela de membros, então carrega `_doc_` (e
qualquer outro atributo) como uma tabela:
Uma closure tem seu próprio objeto de membros, então carrega `_doc_` (e
qualquer outro atributo) como um objeto:
```lua
function add(a, b) return a + b end
+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 */
+39 -1
View File
@@ -18,6 +18,7 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdatomic.h>
struct CAT_ERROR_Error;
struct CAT_VALUE_Value;
@@ -151,11 +152,40 @@ struct CAT_VALUE_Vtable {
void (*destroy)(CAT_VALUE_Value *self);
};
/* The common header shared by every concrete value. */
/* The common header shared by every concrete value.
*
* `refcnt` is a thread-safe reference count:
* - a live, heap-owned value starts at 1 (its creator's reference);
* - `cat_value_retain`/`cat_value_release` add/drop references with
* atomic operations, and the last release calls vtable->destroy;
* - a value with a negative count is IMMORTAL (singletons such as the
* empty object and true/false, or stack-allocated wrappers): retain
* and release are no-ops for it, so it is never freed.
*
* Note: atomic refcounts make the COUNT safe across threads; they do NOT
* make a mutable object (a table being written from two threads) safe. */
struct CAT_VALUE_Value {
CAT_VALUE_Vtable *vtable;
_Atomic long refcnt;
};
/* ---- reference counting (thread-safe) ---- */
/* Add a reference. No-op for NULL and immortal values. */
void cat_value_retain(CAT_VALUE_Value *v);
/* Drop a reference. When the last reference goes, calls vtable->destroy.
* No-op for NULL and immortal values. */
void cat_value_release(CAT_VALUE_Value *v);
/* The current reference count (for tests/diagnostics); negative means
* immortal, 0 means unowned/NULL. */
long cat_value_refcount(CAT_VALUE_Value *v);
/* Mark a value immortal (never freed). Used for singletons and for
* wrappers whose storage lives on the C stack. */
void cat_value_make_immortal(CAT_VALUE_Value *v);
/* ---- dispatch helpers used by compiler/VM and embedders ---- */
int cat_value_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
@@ -178,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
+22
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
@@ -88,6 +104,12 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out);
CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name);
int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v);
/* Like cat_vm_set_global, but the caller hands over its reference: the
* globals table takes ownership and the caller's ref is dropped. Use
* with an inline-created value. */
int cat_vm_set_global_owned(CAT_VM_State *vm, const char *name,
CAT_VALUE_Value *v);
void cat_vm_free(CAT_VM_State *vm);
#endif /* CAT_VM_H */
+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;
}
+9 -7
View File
@@ -55,6 +55,10 @@ int cat_bytecode_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v)
fn->consts = ncp;
fn->capconsts = nc;
}
/* The pool owns a reference: this keeps constants alive as long as
* the chunk does, even when the caller built it from borrowed
* values (e.g. `bc_run` reading a table). */
cat_value_retain(v);
fn->consts[fn->nconsts].value = v;
return fn->nconsts++;
}
@@ -84,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];
@@ -115,12 +119,10 @@ void cat_bytecode_function_free(CAT_BYTECODE_Function *fn)
if (fn == NULL)
return;
/* Constant VALUES are intentionally not destroyed here. A chunk's
* constants may be shared (e.g. a chunk built from a catscript table
* via bc_run borrows the table's values), and destroying them would
* double-free. The pool itself is freed; leaked values are bounded
* by the number of compilations in a single run. */
(void)i;
/* Release the constant values this chunk owned (it took a reference
* in cat_bytecode_add_const). The last holder frees them. */
for (i = 0; i < fn->nconsts; i++)
cat_value_release(fn->consts[i].value);
for (i = 0; i < fn->nprotos; i++)
cat_bytecode_function_free(fn->protos[i]);
free(fn->code);
+329 -25
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, ...)
@@ -112,7 +119,19 @@ static FuncCtx *ctx(Compiler *c)
static int add_string(Compiler *c, const char *s)
{
return cat_bytecode_add_const(cur_fn(c), cat_types_ascii_text_new(s));
CAT_VALUE_Value *v = cat_types_ascii_text_new(s);
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v); /* pool owns it now */
return k;
}
/* Add a freshly-created constant: the pool takes a reference, we drop
* ours, so the constant lives exactly as long as the chunk. */
static int add_const_owned(Compiler *c, CAT_VALUE_Value *v)
{
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v);
return k;
}
static CAT_BYTECODE_Function *cur_fn(Compiler *c)
@@ -140,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;
@@ -179,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:
@@ -187,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 ||
@@ -214,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`. */
@@ -242,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++;
@@ -258,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;
@@ -284,13 +406,13 @@ static void primary(Compiler *c)
switch (t.kind) {
case CAT_LEXER_TOK_INT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_int_new(t.ival));
int k = add_const_owned(c, cat_types_int_new(t.ival));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
}
case CAT_LEXER_TOK_FLOAT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_float_new(t.fval));
int k = add_const_owned(c, cat_types_float_new(t.fval));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
@@ -353,7 +475,7 @@ static void primary(Compiler *c)
c->lx.line = sl;
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
add_const_owned(c,
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
@@ -363,7 +485,7 @@ static void primary(Compiler *c)
} else {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
add_const_owned(c,
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
@@ -376,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;
@@ -548,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);
}
}
@@ -602,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: {
@@ -695,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. */
@@ -735,7 +891,7 @@ static void stat(Compiler *c)
expr(c); /* step */
else
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c), cat_types_int_new(1)),
add_const_owned(c, cat_types_int_new(1)),
0, line);
expect(c, CAT_LEXER_TOK_DO, "'do'");
slot = add_local(c, var);
@@ -814,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);
@@ -863,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;
}
@@ -872,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 {
@@ -1056,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;
@@ -1094,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",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=",
"<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",",
".", ":", "::", "..", "->"
+20 -11
View File
@@ -86,22 +86,25 @@ static void module_dir(const char *path, char *buf, size_t cap)
CAT_VALUE_Value *cat_module_table(const char *name, const char *path)
{
CAT_VALUE_Value *t = cat_types_table_new();
CAT_VALUE_Value *nv;
CAT_ERROR_Error e;
char dir[512];
cat_error_clear(&e);
cat_types_table_set(t, "name",
cat_types_ascii_text_new(name ? name : "main"),
&e);
nv = cat_types_ascii_text_new(name ? name : "main");
cat_types_table_set(t, "name", nv, &e);
cat_value_release(nv);
/* `path`/`dir` reflect where this unit came from, when known. */
if (path != NULL && path[0] != '\0') {
cat_error_clear(&e);
cat_types_table_set(t, "path",
cat_types_ascii_text_new(path), &e);
nv = cat_types_ascii_text_new(path);
cat_types_table_set(t, "path", nv, &e);
cat_value_release(nv);
module_dir(path, dir, sizeof(dir));
cat_error_clear(&e);
cat_types_table_set(t, "dir",
cat_types_ascii_text_new(dir), &e);
nv = cat_types_ascii_text_new(dir);
cat_types_table_set(t, "dir", nv, &e);
cat_value_release(nv);
}
return t;
}
@@ -114,15 +117,21 @@ void cat_module_enter(CAT_VM_State *vm, const char *name, const char *path)
return;
prev = cat_vm_get_global(vm, "module");
if (vm->nmodule < (int)(sizeof(vm->module_stack) /
sizeof(vm->module_stack[0])))
sizeof(vm->module_stack[0]))) {
/* Keep the saved module alive while it is off the global. */
cat_value_retain(prev);
vm->module_stack[vm->nmodule++] = prev;
cat_vm_set_global(vm, "module", cat_module_table(name, path));
}
cat_vm_set_global_owned(vm, "module", cat_module_table(name, path));
}
void cat_module_leave(CAT_VM_State *vm)
{
CAT_VALUE_Value *prev;
if (vm == NULL || vm->nmodule <= 0)
return;
cat_vm_set_global(vm, "module",
vm->module_stack[--vm->nmodule]);
prev = vm->module_stack[--vm->nmodule];
cat_vm_set_global(vm, "module", prev);
cat_value_release(prev); /* drop the stack's reference */
}
+122 -8
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)
{
@@ -665,27 +760,46 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
int i;
for (i = 0; std[i].name != NULL; i++)
cat_vm_set_global(vm, std[i].name,
cat_vm_set_global_owned(vm, std[i].name,
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(vm, "AbstractFile",
cat_vm_set_global_owned(vm, "AbstractFile",
cat_types_native_new("AbstractFile", lf_abstractfile));
cat_vm_set_global(vm, "File", cat_types_file_class_table());
cat_vm_set_global(vm, "StringIO",
cat_vm_set_global_owned(vm, "File", cat_types_file_class_table());
cat_vm_set_global_owned(vm, "StringIO",
cat_types_native_new("StringIO", lf_stringio));
cat_vm_set_global(vm, "BytesIO",
cat_vm_set_global_owned(vm, "BytesIO",
cat_types_native_new("BytesIO", lf_bytesio));
/* the `ffi` library: call native code (ctypes/CDLL-like) */
cat_vm_set_global(vm, "ffi", cat_types_ffi_module());
cat_vm_set_global_owned(vm, "ffi", cat_types_ffi_module());
/* the empty object: the value for "no value" (catscript has no nil) */
cat_vm_set_global(vm, "empty", cat_types_empty());
/* `memory(n)` -- an owned, bounds-checked byte buffer */
cat_vm_set_global(vm, "memory",
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(vm, "module", cat_module_table("main", NULL));
cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL));
return 0;
}
+1
View File
@@ -46,6 +46,7 @@ CAT_VALUE_Value *cat_types_ascii_text_new(const char *s)
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_ascii_vtable;
t->text.base.refcnt = 1;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
+2 -2
View File
@@ -24,12 +24,12 @@ CAT_VALUE_Vtable *cat_types_bool_vtable(void)
CAT_VALUE_Value *cat_types_bool_true(void)
{
static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable }, 1 };
static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable, -1 }, 1 };
return &t.base;
}
CAT_VALUE_Value *cat_types_bool_false(void)
{
static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable }, 0 };
static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable, -1 }, 0 };
return &f.base;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_byte_new(unsigned int v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_byte_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 0;
n->number.i = (long long)(v & 0xFFu);
n->number.f = (double)(v & 0xFFu);
+1
View File
@@ -59,6 +59,7 @@ CAT_VALUE_Value *cat_types_char_new(int width, const char *s)
}
c->buf[width] = '\0';
c->text.base.vtable = cat_types_char_vtable(width);
c->text.base.refcnt = 1;
c->text.bytes = c->buf;
c->text.len = width;
return &c->text.base;
+7
View File
@@ -44,7 +44,14 @@ CAT_VALUE_Vtable *cat_types_empty_vtable(void)
CAT_VALUE_Value *cat_types_empty(void)
{
static CAT_VALUE_Value g_empty;
static int inited = 0;
if (!inited) {
g_empty.vtable = &g_empty_vtable;
/* immortal: the empty object is shared and never freed */
atomic_store_explicit(&g_empty.refcnt, -1, memory_order_relaxed);
inited = 1;
}
return &g_empty;
}
+10 -5
View File
@@ -331,6 +331,7 @@ CAT_VALUE_Value *cat_types_ffi_load(const char *path)
return cat_types_empty();
}
l->base.vtable = &g_library_vtable;
l->base.refcnt = 1;
l->handle = h;
l->path = strdup(path);
return &l->base;
@@ -353,6 +354,7 @@ CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name,
if (f == NULL)
return cat_types_empty();
f->base.vtable = &g_function_vtable;
f->base.refcnt = 1;
f->sym = sym;
f->name = strdup(name);
f->sig = sig ? strdup(sig) : NULL;
@@ -374,6 +376,7 @@ CAT_VALUE_Value *cat_types_ffi_bind_addr(unsigned long long addr,
if (f == NULL)
return cat_types_empty();
f->base.vtable = &g_function_vtable;
f->base.refcnt = 1;
f->sym = (void *)(size_t)addr;
f->name = strdup(name ? name : "?");
f->sig = sig ? strdup(sig) : NULL;
@@ -441,13 +444,15 @@ static int ffi_pointer_native(CAT_VM_State *vm, CAT_VALUE_Value **args,
CAT_VALUE_Value *cat_types_ffi_module(void)
{
CAT_VALUE_Value *m = cat_types_table_new();
CAT_VALUE_Value *nv;
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(m, "load",
cat_types_native_new("load", ffi_load_native), &e);
cat_types_table_set(m, "pointer",
cat_types_native_new("pointer", ffi_pointer_native),
&e);
nv = cat_types_native_new("load", ffi_load_native);
cat_types_table_set(m, "load", nv, &e);
cat_value_release(nv);
nv = cat_types_native_new("pointer", ffi_pointer_native);
cat_types_table_set(m, "pointer", nv, &e);
cat_value_release(nv);
return m;
}
+6 -1
View File
@@ -297,6 +297,7 @@ CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode)
return cat_types_empty();
}
f->af.base.vtable = &g_file_vtable;
f->af.base.refcnt = 1;
f->af.mode = m;
f->af.closed = 0;
f->af.is_bytes = 0;
@@ -312,6 +313,7 @@ CAT_VALUE_Value *cat_types_file_stringio(const char *initial)
if (m == NULL)
return cat_types_empty();
m->af.base.vtable = &g_memfile_vtable;
m->af.base.refcnt = 1;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->af.is_bytes = 1; /* in-memory */
m->cap = 128;
@@ -342,6 +344,7 @@ CAT_VALUE_Value *cat_types_file_bytesio(void)
if (m == NULL)
return cat_types_empty();
m->af.base.vtable = &g_memfile_vtable;
m->af.base.refcnt = 1;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->cap = 128;
m->buf = malloc((size_t)m->cap);
@@ -380,9 +383,11 @@ static int cm_open(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value *cat_types_file_class_table(void)
{
CAT_VALUE_Value *t = cat_types_table_new();
CAT_VALUE_Value *nv = cat_types_native_new("open", cm_open);
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(t, "open", cat_types_native_new("open", cm_open), &e);
cat_types_table_set(t, "open", nv, &e);
cat_value_release(nv);
return t;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_float_new(double v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_float_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 1;
n->number.f = v;
n->number.i = (long long)v;
+7
View File
@@ -67,7 +67,13 @@ static int function_set_attribute(CAT_VALUE_Value *self, const char *name,
static void function_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self;
int i;
for (i = 0; i < cl->nupvals; i++)
cat_value_release(cl->upvals[i]);
free(cl->upvals);
if (cl->attrs != NULL)
cat_value_release(cl->attrs);
/* proto is owned by its enclosing module/bytecode tree, unless this
* closure built it at runtime (injected bytecode) */
if (cl->owns_proto && cl->proto != NULL)
@@ -105,6 +111,7 @@ CAT_VALUE_Value *cat_types_function_new(CAT_BYTECODE_Function *proto)
if (cl == NULL)
return NULL;
cl->base.vtable = &g_function_vtable;
cl->base.refcnt = 1;
cl->proto = proto;
cl->nupvals = 0;
cl->upvals = NULL;
+21
View File
@@ -31,11 +31,25 @@ static int generator_get_attribute(CAT_VALUE_Value *self, const char *name,
return (cat_error_raise(err, "generator has no method '%s'", name), -1);
}
static void generator_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_GENERATOR_Generator *g = (CAT_TYPES_GENERATOR_Generator *)self;
int i;
free(g->stack);
for (i = 0; i < g->nargs; i++)
cat_value_release(g->args[i]);
if (g->cl != NULL)
cat_value_release(&g->cl->base);
free(g);
}
static CAT_VALUE_Vtable g_generator_vtable = {
.type_name = "generator",
.kind = CAT_VALUE_KIND_GENERATOR,
.next = { generator_next },
.get_attribute = { generator_get_attribute },
.destroy = generator_destroy,
};
CAT_VALUE_Vtable *cat_types_generator_vtable(void)
@@ -58,6 +72,7 @@ CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
if (g == NULL)
return cat_types_empty();
g->base.vtable = &g_generator_vtable;
g->base.refcnt = 1;
g->vm = vm;
g->cl = cl;
g->frame.fn = cl->proto;
@@ -76,6 +91,12 @@ CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
for (i = 0; i < nargs && i < 256; i++)
g->args[i] = args[i];
g->nargs = nargs;
/* Own references to the closure and the captured arguments: the
* generator keeps them alive across suspensions. */
if (cl != NULL)
cat_value_retain(&cl->base);
for (i = 0; i < nargs && i < 256; i++)
cat_value_retain(g->args[i]);
return &g->base;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_int_new(long long v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_int_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 0;
n->number.i = v;
n->number.f = (double)v;
+7
View File
@@ -57,6 +57,8 @@ static int list_set_attribute(CAT_VALUE_Value *self, const char *name,
if (idx < 0 || idx >= l->n)
return (cat_error_raise(err,
"list index %ld out of range", idx), -1);
cat_value_retain(value);
cat_value_release(l->items[idx]);
l->items[idx] = value;
return 0;
}
@@ -66,7 +68,10 @@ static int list_set_attribute(CAT_VALUE_Value *self, const char *name,
static void list_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
int i;
for (i = 0; i < l->n; i++)
cat_value_release(l->items[i]);
free(l->items);
free(l);
}
@@ -97,6 +102,7 @@ CAT_VALUE_Value *cat_types_list_new(void)
if (l == NULL)
return NULL;
l->base.vtable = &g_list_vtable;
l->base.refcnt = 1;
return &l->base;
}
@@ -114,6 +120,7 @@ int cat_types_list_push(CAT_VALUE_Value *list, CAT_VALUE_Value *v)
l->cap = nc;
}
l->items[l->n++] = v;
cat_value_retain(v);
return 0;
}
+1
View File
@@ -275,6 +275,7 @@ CAT_VALUE_Value *cat_types_memory_new(size_t size)
if (m == NULL)
return NULL;
m->base.vtable = &g_memory_vtable;
m->base.refcnt = 1;
m->size = size;
m->data = calloc(1, size ? size : 1);
if (m->data == NULL) {
+1
View File
@@ -74,6 +74,7 @@ CAT_VALUE_Value *cat_types_native_new_doc(const char *name,
if (nf == NULL)
return NULL;
nf->base.vtable = &g_native_vtable;
nf->base.refcnt = 1;
nf->name = strdup(name ? name : "native");
nf->doc = doc ? strdup(doc) : NULL;
nf->cb = cb;
+4 -1
View File
@@ -102,8 +102,11 @@ CAT_VALUE_Value *cat_types_selector_lookup(const char *name)
return NULL;
/* accept both `_dot_` and `.` spellings of a selector */
for (i = 0; i < (int)(sizeof(g_sel) / sizeof(g_sel[0])); i++) {
if (g_sel[i].base.vtable == NULL)
if (g_sel[i].base.vtable == NULL) {
g_sel[i].base.vtable = &g_selector_vtable;
/* static singleton: immortal, never freed */
g_sel[i].base.refcnt = -1;
}
}
strncpy(key, name, sizeof(key) - 1);
key[sizeof(key) - 1] = '\0';
+13 -8
View File
@@ -39,7 +39,7 @@ static int table_get_attribute(CAT_VALUE_Value *self, const char *name,
return 0;
}
}
return (cat_error_raise(err, "table has no key '%s'", name), -1);
return (cat_error_raise(err, "object has no member '%s'", name), -1);
}
static int table_set_attribute(CAT_VALUE_Value *self, const char *name,
@@ -62,7 +62,7 @@ static int table_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs,
cat_error_clear(&e);
if (cat_value_get_attribute(self, "new", &ctor, &e) != 0 || ctor == NULL)
return (cat_error_raise(err,
"table is not callable (no 'new')"), -1);
"object is not callable (no 'new')"), -1);
callargs[0] = self;
for (i = 0; i < nargs && i < 257; i++)
callargs[i + 1] = args[i];
@@ -73,12 +73,13 @@ static void table_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)self;
int i;
/* Values are NOT destroyed: the same value object may be referenced
* from several tables (globals, constants, locals), so a recursive
* destroy would double-free. We only release the table's own keys
* and storage. */
for (i = 0; i < t->npairs; i++)
/* Release the values we own, then our own keys and storage. Values
* are shared, so we drop exactly one reference each; the last holder
* frees them. */
for (i = 0; i < t->npairs; i++) {
cat_value_release(t->pairs[i].value);
free(t->pairs[i].key);
}
free(t->pairs);
free(t);
}
@@ -104,6 +105,7 @@ CAT_VALUE_Value *cat_types_table_new(void)
if (t == NULL)
return NULL;
t->base.vtable = &g_table_vtable;
t->base.refcnt = 1;
return &t->base;
}
@@ -124,6 +126,8 @@ int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key,
(void)err;
if (idx >= 0) {
cat_value_retain(value);
cat_value_release(t->pairs[idx].value);
t->pairs[idx].value = value;
return 0;
}
@@ -137,6 +141,7 @@ int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key,
}
t->pairs[t->npairs].key = strdup(key);
t->pairs[t->npairs].value = value;
cat_value_retain(value);
t->npairs++;
return 0;
}
@@ -151,7 +156,7 @@ int cat_types_table_get(CAT_VALUE_Value *tbl, const char *key,
*out = t->pairs[idx].value;
return 0;
}
return (cat_error_raise(err, "table has no key '%s'", key), -1);
return (cat_error_raise(err, "object has no member '%s'", key), -1);
}
int cat_types_table_count(CAT_VALUE_Value *tbl)
+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;
}
+1
View File
@@ -69,6 +69,7 @@ CAT_VALUE_Value *cat_types_utf8_text_new(const char *s)
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_utf8_vtable;
t->text.base.refcnt = 1;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
+123
View File
@@ -25,6 +25,56 @@
#include <stdlib.h>
#include <string.h>
/* ---- reference counting (thread-safe) -------------------------------
*
* The count lives in the common value header. retain/release use atomic
* read-modify-write with acquire/release ordering, so the object graph
* can be shared across threads safely. Destroying the object runs on
* whichever thread drops the last reference.
*
* A negative count marks an immortal value (a singleton, or a wrapper
* whose storage lives on the C stack); retain/release ignore it. */
void cat_value_retain(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
if (atomic_load_explicit(&v->refcnt, memory_order_relaxed) < 0)
return;
atomic_fetch_add_explicit(&v->refcnt, 1, memory_order_relaxed);
}
void cat_value_release(CAT_VALUE_Value *v)
{
long prev;
if (v == NULL)
return;
prev = atomic_load_explicit(&v->refcnt, memory_order_relaxed);
if (prev < 0)
return;
if (atomic_fetch_sub_explicit(&v->refcnt, 1,
memory_order_acq_rel) == 1) {
/* Last reference: publish our writes, then destroy. */
atomic_thread_fence(memory_order_acquire);
if (v->vtable != NULL && v->vtable->destroy != NULL)
v->vtable->destroy(v);
}
}
long cat_value_refcount(CAT_VALUE_Value *v)
{
if (v == NULL)
return 0;
return atomic_load_explicit(&v->refcnt, memory_order_relaxed);
}
void cat_value_make_immortal(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
atomic_store_explicit(&v->refcnt, -1, memory_order_relaxed);
}
const char *cat_value_type_name(CAT_VALUE_Value *v)
{
if (v == NULL || v->vtable == NULL || v->vtable->type_name == NULL)
@@ -256,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)
{
+61 -10
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));
@@ -70,6 +76,19 @@ int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v)
return cat_types_table_set(vm->globals, name, v, &e);
}
/* Set a global from a freshly-created value, transferring ownership to
* the globals table (the caller's reference is dropped). Use this when
* the value is created inline: `cat_vm_set_global_owned(vm, "x",
* cat_types_native_new(...))`. */
int cat_vm_set_global_owned(CAT_VM_State *vm, const char *name,
CAT_VALUE_Value *v)
{
int rc = cat_vm_set_global(vm, name, v);
cat_value_release(v);
return rc;
}
int cat_vm_register_native(CAT_VM_State *vm, const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int,
CAT_VALUE_Value **))
@@ -77,7 +96,7 @@ int cat_vm_register_native(CAT_VM_State *vm, const char *name,
/* A native function is a first-class value. Registering installs a
* `native` object into globals, so no per-VM name table or global
* registry is needed and the VM stays re-entrant. */
cat_vm_set_global(vm, name, cat_types_native_new(name, cb));
cat_vm_set_global_owned(vm, name, cat_types_native_new(name, cb));
return 0;
}
@@ -94,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");
@@ -338,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();
@@ -360,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();
@@ -465,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: {
@@ -480,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;
}
@@ -535,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;
@@ -557,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)
{
@@ -587,15 +623,30 @@ int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **ou
memset(&cl, 0, sizeof(cl));
cl.base.vtable = cat_types_function_vtable();
cl.proto = fn;
/* This closure lives on the C stack: mark it immortal so a stray
* release can never try to free it. */
cat_value_make_immortal(&cl.base);
return cat_vm_exec_closure(vm, &cl, NULL, 0, out);
}
void cat_vm_free(CAT_VM_State *vm)
{
int i;
if (vm == NULL)
return;
if (vm->globals != NULL && vm->globals->vtable &&
vm->globals->vtable->destroy)
vm->globals->vtable->destroy(vm->globals);
/* Release any module still saved on the stack (e.g. the initial
* `module` if the run never balanced enter/leave). */
while (vm->nmodule > 0) {
CAT_VALUE_Value *m = vm->module_stack[--vm->nmodule];
cat_value_release(m);
}
/* The globals table owns one reference per value it holds; releasing
* it cascades: each stored value's reference drops and the last
* holder frees it. */
if (vm->globals != NULL)
cat_value_release(vm->globals);
for (i = 0; i < vm->nnatives; i++)
(void)vm->natives[i];
free(vm);
}
+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;
+1 -1
View File
@@ -60,7 +60,7 @@ function chk_expr(e)
chk_expr(e.idx)
elseif t == "attr" then
chk_expr(e.obj)
elseif t == "table" then
elseif t == "object" then
local i = 1
while i <= len(e.fields) do
chk_expr(e.fields[i].v)
+1 -1
View File
@@ -145,7 +145,7 @@ function cmp_expr(e)
elseif t == "attr" then
cmp_expr(e.obj)
cmp_emit(22, cmp_addstr(e.name), 0, 0)
elseif t == "table" then
elseif t == "object" then
cmp_emit(24, 0, 0, 0)
local pos = 1
local i = 1
+2 -2
View File
@@ -11,7 +11,7 @@
-- { t="method", obj=O, name="m", args={...} }
-- { t="index", obj=O, idx=I }
-- { t="attr", obj=O, name="a" }
-- { t="table", fields={ {k=..., v=...}, ... } } -- positional k is empty
-- { t="object", fields={ {k=..., v=...}, ... } } -- positional k is empty
-- { t="func", name=..., params={...}, body={stats} }
--
-- Statements:
@@ -125,7 +125,7 @@ function par_table()
par_advance()
end
par_expect("}", "'}'")
return { t = "table", fields = fields }
return { t = "object", fields = fields }
end
function par_args()
+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")
+2 -2
View File
@@ -1,7 +1,7 @@
-- tests/functions_as_objects.cat -- functions are objects too.
--
-- A closure carries a member table, so it can hold `_doc_` (and any
-- other attribute) exactly like a table. `help()` reads it; a dotted
-- A closure carries a member object, so it can hold `_doc_` (and any
-- other attribute) exactly like an object. `help()` reads it; a dotted
-- assignment can reach an attribute of a nested object (a method).
local t = {x = 1, y = 2}
+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))
+2 -2
View File
@@ -1,6 +1,6 @@
-- tests/module.cat -- the `module` global reflects the current unit.
--
-- `module` is a global table: `name` is the basename of the running
-- `module` is a global object: `name` is the basename of the running
-- file, `path` its path and `dir` its directory. Importing another
-- file (use/dofile) swaps `module` for the duration of that file and
-- restores the caller's afterwards.
@@ -8,7 +8,7 @@
print("name:", module.name)
print("dir:", module.dir)
-- a user may mutate it like any table
-- a user may mutate it like any object
module.extra = "tagged"
print("extra:", module.extra)
+1 -1
View File
@@ -19,7 +19,7 @@ class Point
end
local p = Point(3, 4)
print("table:", tostring(t))
print("object:", tostring(t))
print("point:", tostring(p))
print("int:", tostring(42))
print("str:", tostring("hi"))
+88 -1
View File
@@ -162,7 +162,7 @@ check "fn-help" "add(a, b) -- soma dois numeros." "`echo "$out" | sed -n
# ---- _repr_ protocol -------------------------------------------------
out=`$BIN tests/repr.cat`
check "repr-value" "table: a custom point" "`echo "$out" | sed -n 1p`"
check "repr-value" "object: a custom point" "`echo "$out" | sed -n 1p`"
check "repr-method" "point: Point(3, 4)" "`echo "$out" | sed -n 2p`"
check "repr-int" "int: 42" "`echo "$out" | sed -n 3p`"
check "repr-str" "str: hi" "`echo "$out" | sed -n 4p`"
@@ -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 ]
+1 -1
View File
@@ -17,7 +17,7 @@ counter.bump(3)
counter.bump(4)
print("with self:", counter.n)
-- a plain table field
-- a plain object field
local point = { x = 10, y = 20 }
print("field x:", point.x)
+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())