Compare commits

..

No commits in common. "1ea115b277bb833bf3d7df48a38b8351e27a7366" and "1828eb3b453e62414767915c02c2c16dc90eb96f" have entirely different histories.

11 changed files with 368 additions and 496 deletions

View File

@ -1,8 +1,8 @@
@log_info("game is loading")
title = "Afterglow"
return {
title = "Afterglow",
title = title,
width = 1280,
height = 800,
tick_rate = 60,

View File

@ -116,32 +116,18 @@ pub fn Functor(comptime Output: type, comptime Input: type) type {
pub fn bind(comptime State: type, state: *const State, comptime invoker: fn (capture: *const State, input: Input) Output) Self {
const is_zero_aligned = @alignOf(State) == 0;
const Invoker = struct {
fn invoke(context: *const anyopaque, input: Input) Output {
if (is_zero_aligned) {
return invoker(@ptrCast(context), input);
}
return invoker(@ptrCast(@alignCast(context)), input);
}
};
return .{
.context = if (is_zero_aligned) state else @ptrCast(state),
.invoker = Invoker.invoke,
};
}
pub fn from(comptime invoker: fn (input: Input) Output) Self {
const Invoker = struct {
fn invoke(_: *const anyopaque, input: Input) Output {
return invoker(input);
}
};
.invoker = struct {
fn invoke(context: *const anyopaque, input: Input) Output {
if (is_zero_aligned) {
return invoker(@ptrCast(context), input);
}
return .{
.context = &.{},
.invoker = Invoker.invoke,
return invoker(@ptrCast(@alignCast(context)), input);
}
}.invoke,
};
}
@ -176,19 +162,6 @@ pub fn Generator(comptime Output: type, comptime Input: type) type {
};
}
pub fn from(comptime invoker: fn (input: Input) Output) Self {
const Invoker = struct {
fn invoke(_: *const anyopaque, input: Input) Output {
return invoker(input);
}
};
return .{
.context = &.{},
.invoker = Invoker.invoke,
};
}
pub fn invoke(self: Self, input: Input) Output {
return self.invoker(self.context, input);
}

View File

@ -73,12 +73,12 @@ pub fn Stack(comptime Value: type) type {
self.capacity = packed_size;
}
pub fn peek(self: Self) ?Value {
pub fn peek(self: *Self) ?Value {
if (self.values.len == 0) {
return null;
}
return self.values[self.values.len - 1];
return &self.values[self.values.len - 1];
}
pub fn pop(self: *Self) ?Value {
@ -93,22 +93,6 @@ pub fn Stack(comptime Value: type) type {
return self.values[last_index];
}
pub fn push_all(self: *Self, values: []const Value) io.AllocationError!void {
const new_length = self.values.len + values.len;
if (new_length > self.capacity) {
try self.grow(values.len + values.len);
}
const offset_index = self.values.len;
self.values = self.values.ptr[0 .. new_length];
for (0 .. values.len) |index| {
self.values[offset_index + index] = values[index];
}
}
pub fn push_one(self: *Self, value: Value) io.AllocationError!void {
if (self.values.len == self.capacity) {
try self.grow(math.max(1, self.capacity));
@ -122,13 +106,3 @@ pub fn Stack(comptime Value: type) type {
}
};
}
pub fn stack_as_writer(self: *ByteStack) io.Writer {
return io.Writer.bind(ByteStack, self, write_stack);
}
fn write_stack(stack: *ByteStack, bytes: []const io.Byte) ?usize {
stack.push_all(bytes) catch return null;
return bytes.len;
}

View File

@ -103,13 +103,6 @@ pub fn Slab(comptime Value: type) type {
};
}
pub fn StringTable(comptime Value: type) type {
return Table([]const io.Byte, Value, .{
.hash = hash_string,
.match = io.equals,
});
}
pub fn Table(comptime Key: type, comptime Value: type, comptime traits: TableTraits(Key)) type {
const load_max = 0.75;
@ -150,7 +143,7 @@ pub fn Table(comptime Key: type, comptime Value: type, comptime traits: TableTra
pub const Iterable = struct {
table: *Self,
iterations: usize,
iterations: usize = 0,
pub fn next(self: *Iterable) ?Entry {
while (self.iterations < self.table.entries.len) {
@ -167,13 +160,6 @@ pub fn Table(comptime Key: type, comptime Value: type, comptime traits: TableTra
const Self = @This();
pub fn as_iterable(self: *Self) Iterable {
return .{
.table = self,
.iterations = 0,
};
}
pub fn remove(self: *Self, key: Key) ?Entry {
const hash_max = math.min(math.max_int(@typeInfo(usize).Int), self.entries.len);
var hashed_key = math.wrap(traits.hash(key), math.min_int(@typeInfo(usize).Int), hash_max);
@ -346,3 +332,8 @@ fn hash_string(key: []const io.Byte) usize {
return hash_code;
}
pub const string_table_traits = TableTraits([]const io.Byte){
.hash = hash_string,
.match = io.equals,
};

View File

@ -12,14 +12,14 @@ pub const Manifest = struct {
height: u16 = 480,
tick_rate: f32 = 60.0,
pub fn load(self: *Manifest, env: *kym.RuntimeEnv, file_access: file.Access) kym.RuntimeError!void {
const manifest_ref = try env.execute_file(file_access, file.Path.from(&.{"app.ona"}));
pub fn load(self: *Manifest, env: *kym.RuntimeEnv, global_ref: ?*const kym.RuntimeRef, file_access: file.Access) kym.RuntimeError!void {
var manifest_ref = try env.execute_file(global_ref, file_access, file.Path.from(&.{"app.ona"}));
defer env.discard(manifest_ref);
defer env.discard(&manifest_ref);
const title_ref = try kym.get_field(env, manifest_ref, "title");
var title_ref = try kym.get_dynamic_field(env, manifest_ref, "title");
defer env.discard(title_ref);
defer env.discard(&title_ref);
const title_string = switch (env.unbox(title_ref)) {
.string => |string| string,
@ -27,9 +27,9 @@ pub const Manifest = struct {
};
const width = @as(u16, get: {
const ref = try kym.get_field(env, manifest_ref, "width");
var ref = try kym.get_dynamic_field(env, manifest_ref, "width");
defer env.discard(ref);
defer env.discard(&ref);
// TODO: Add safety-checks to int cast.
break: get switch (env.unbox(ref)) {
@ -39,9 +39,9 @@ pub const Manifest = struct {
});
const height = @as(u16, get: {
const ref = try kym.get_field(env, manifest_ref, "height");
var ref = try kym.get_dynamic_field(env, manifest_ref, "height");
defer env.discard(ref);
defer env.discard(&ref);
// TODO: Add safety-checks to int cast.
break: get switch (env.unbox(ref)) {
@ -51,9 +51,9 @@ pub const Manifest = struct {
});
const tick_rate = @as(f32, get: {
const ref = try kym.get_field(env, manifest_ref, "tick_rate");
var ref = try kym.get_dynamic_field(env, manifest_ref, "tick_rate");
defer env.discard(ref);
defer env.discard(&ref);
break: get switch (env.unbox(ref)) {
.number => |number| @floatCast(number),
@ -74,14 +74,69 @@ pub const Manifest = struct {
}
};
pub fn log_info(message: []const coral.io.Byte) void {
ext.SDL_LogInfo(ext.SDL_LOG_CATEGORY_APPLICATION, "%.*s", @as(c_int, @intCast(message.len)), message.ptr);
}
pub const LogSeverity = enum {
info,
warn,
fail,
};
pub fn log_warn(message: []const coral.io.Byte) void {
ext.SDL_LogWarn(ext.SDL_LOG_CATEGORY_APPLICATION, "%.*s", @as(c_int, @intCast(message.len)), message.ptr);
}
pub const WritableLog = struct {
severity: LogSeverity,
write_buffer: coral.list.ByteStack,
pub fn log_fail(message: []const coral.io.Byte) void {
ext.SDL_LogError(ext.SDL_LOG_CATEGORY_APPLICATION, "%.*s", @as(c_int, @intCast(message.len)), message.ptr);
}
pub fn as_writer(self: *WritableLog) coral.io.Writer {
return coral.io.Writer.bind(WritableLog, self, struct {
fn write(writable_log: *WritableLog, bytes: []const coral.io.Byte) ?usize {
writable_log.write(bytes) catch return null;
return bytes.len;
}
}.write);
}
pub fn free(self: *WritableLog) void {
self.write_buffer.free();
}
pub fn make(log_severity: LogSeverity, allocator: coral.io.Allocator) WritableLog {
return .{
.severity = log_severity,
.write_buffer = coral.list.ByteStack.make(allocator),
};
}
pub fn write(self: *WritableLog, bytes: []const coral.io.Byte) coral.io.AllocationError!void {
const format_string = "%.*s";
var line_written = @as(usize, 0);
for (bytes) |byte| {
if (byte == '\n') {
ext.SDL_LogError(
ext.SDL_LOG_CATEGORY_APPLICATION,
format_string,
self.write_buffer.values.len,
self.write_buffer.values.ptr);
self.write_buffer.clear();
line_written = 0;
continue;
}
try self.write_buffer.push_one(byte);
line_written += 1;
}
if (self.write_buffer.values.len == 0) {
ext.SDL_LogError(
ext.SDL_LOG_CATEGORY_APPLICATION,
format_string,
self.write_buffer.values.len,
self.write_buffer.values.ptr);
self.write_buffer.clear();
}
}
};

View File

@ -10,12 +10,19 @@ const file = @import("./file.zig");
const tokens = @import("./kym/tokens.zig");
pub const Args = []const ?*const RuntimeRef;
pub const CallContext = struct {
env: *RuntimeEnv,
caller: ?*const RuntimeRef,
userdata: []coral.io.Byte,
userdata: []u8,
args: []const ?*const RuntimeRef = &.{},
pub fn arg_at(self: CallContext, index: u8) RuntimeError!*const RuntimeRef {
if (!coral.math.is_clamped(index, 0, self.args.len - 1)) {
return self.env.check_fail("argument out of bounds");
}
return self.args[@as(usize, index)];
}
};
pub const DynamicObject = struct {
@ -23,21 +30,8 @@ pub const DynamicObject = struct {
typeinfo: *const Typeinfo,
};
pub const ErrorHandler = coral.io.Generator(void, ErrorInfo);
pub const ErrorInfo = struct {
message: []const coral.io.Byte,
frames: []const Frame,
};
pub const Float = f64;
pub const Frame = struct {
name: []const coral.io.Byte,
arg_count: u8,
locals_top: usize,
};
pub const IndexContext = struct {
env: *RuntimeEnv,
userdata: []coral.io.Byte,
@ -46,18 +40,22 @@ pub const IndexContext = struct {
pub const RuntimeEnv = struct {
allocator: coral.io.Allocator,
error_handler: ErrorHandler,
syscallers: SyscallerTable,
err_writer: coral.io.Writer,
local_refs: RefStack,
frames: FrameStack,
ref_values: RefSlab,
const FrameStack = coral.list.Stack(Frame);
const SyscallerTable = coral.map.StringTable(Syscaller);
const FrameStack = coral.list.Stack(struct {
locals_top: usize,
});
const RefStack = coral.list.Stack(?*RuntimeRef);
pub const Options = struct {
out_writer: coral.io.Writer = coral.io.null_writer,
err_writer: coral.io.Writer = coral.io.null_writer,
};
const RefSlab = coral.map.Slab(struct {
ref_count: usize,
@ -70,13 +68,13 @@ pub const RuntimeEnv = struct {
},
});
pub const Syscall = struct {
pub const ScriptSource = struct {
name: []const coral.io.Byte,
caller: Syscaller,
data: []const coral.io.Byte,
};
pub fn acquire(self: *RuntimeEnv, ref: ?*const RuntimeRef) ?*RuntimeRef {
const key = @intFromPtr(ref orelse return null);
const key = @intFromPtr(ref);
var ref_data = self.ref_values.remove(key);
coral.debug.assert(ref_data != null);
@ -88,14 +86,25 @@ pub const RuntimeEnv = struct {
return @ptrFromInt(key);
}
pub fn bind_syscalls(self: *RuntimeEnv, syscalls: []const Syscall) RuntimeError!void {
for (syscalls) |syscall| {
_ = try self.syscallers.replace(syscall.name, syscall.caller);
}
pub fn call(
self: *RuntimeEnv,
caller_ref: *const RuntimeRef,
callable_ref: *const RuntimeRef,
arg_refs: []const *const RuntimeRef,
) RuntimeError!*RuntimeRef {
const callable = (try callable_ref.fetch(self)).to_object();
return callable.userinfo.call(.{
.env = self,
.caller = caller_ref,
.callable = callable_ref,
.userdata = callable.userdata,
.args = arg_refs,
});
}
pub fn discard(self: *RuntimeEnv, ref: ?*RuntimeRef) void {
const key = @intFromPtr(ref orelse return);
pub fn discard(self: *RuntimeEnv, ref: *?*RuntimeRef) void {
const key = @intFromPtr(ref.* orelse return);
var ref_data = self.ref_values.remove(key) orelse unreachable;
coral.debug.assert(ref_data.ref_count != 0);
@ -111,31 +120,32 @@ pub const RuntimeEnv = struct {
} else {
coral.debug.assert(self.ref_values.insert_at(key, ref_data));
}
ref.* = null;
}
pub fn execute_file(self: *RuntimeEnv, file_access: file.Access, file_path: file.Path) RuntimeError!?*RuntimeRef {
if ((try file.allocate_and_load(self.allocator, file_access, file_path))) |file_data| {
defer self.allocator.deallocate(file_data);
pub fn execute_file(self: *RuntimeEnv, global_ref: ?*const RuntimeRef, file_access: file.Access, file_path: file.Path) RuntimeError!?*RuntimeRef {
const error_message = "failed to load file";
if (file_path.to_string()) |string| {
return self.execute_script(string, file_data);
}
}
const file_data = (try file.allocate_and_load(self.allocator, file_access, file_path)) orelse {
return self.raise(error.SystemFailure, error_message);
};
return self.raise(error.BadOperation, "failed to load file");
defer self.allocator.deallocate(file_data);
return self.execute_script(global_ref, .{
.name = file_path.to_string() orelse return self.raise(error.SystemFailure, error_message),
.data = file_data,
});
}
pub fn execute_script(
self: *RuntimeEnv,
name: []const coral.io.Byte,
data: []const coral.io.Byte,
) RuntimeError!?*RuntimeRef {
pub fn execute_script(self: *RuntimeEnv, global_ref: ?*const RuntimeRef, source: ScriptSource) RuntimeError!?*RuntimeRef {
var ast = Ast.make(self.allocator);
defer ast.free();
{
var tokenizer = tokens.Tokenizer{.source = data};
var tokenizer = tokens.Tokenizer{.source = source.data};
ast.parse(&tokenizer) catch |parse_error| switch (parse_error) {
error.BadSyntax => return self.raise(error.BadSyntax, ast.error_message),
@ -149,20 +159,17 @@ pub const RuntimeEnv = struct {
try exe.compile_ast(ast);
return try exe.execute(name);
return exe.execute(global_ref, source.name);
}
pub fn frame_pop(self: *RuntimeEnv) void {
const frame = self.frames.pop();
pub fn frame_pop(self: *RuntimeEnv) RuntimeError!void {
const frame = self.frames.pop() orelse return self.raise(error.IllegalState, "stack underflow");
coral.debug.assert(frame != null);
coral.debug.assert(self.local_refs.drop((self.local_refs.values.len - frame.?.locals_top) + frame.?.arg_count));
coral.debug.assert(self.local_refs.drop(self.local_refs.values.len - frame.locals_top));
}
pub fn frame_push(self: *RuntimeEnv, frame_name: []const coral.io.Byte, arg_count: u8) RuntimeError!void {
try self.frames.push_one(.{
.name = frame_name,
.arg_count = arg_count,
pub fn frame_push(self: *RuntimeEnv) RuntimeError!void {
return self.frames.push_one(.{
.locals_top = self.local_refs.values.len,
});
}
@ -172,26 +179,27 @@ pub const RuntimeEnv = struct {
self.ref_values.free();
}
pub fn get_arg(self: *RuntimeEnv, index: usize) RuntimeError!?*const RuntimeRef {
const frame = self.frames.peek() orelse return self.raise(error.IllegalState, "stack underflow");
pub fn get_dynamic(self: *RuntimeEnv, indexable_ref: ?*const RuntimeRef, index_ref: ?*const RuntimeRef) RuntimeError!?*RuntimeRef {
return switch (self.unbox(indexable_ref)) {
.nil => self.raise(error.BadOperation, "nil is immutable"),
.boolean => self.raise(error.BadOperation, "boolean has no such index"),
.number => self.raise(error.BadOperation, "number has no such index"),
.string => self.raise(error.BadOperation, "string has no such index"),
if (index >= frame.arg_count) {
return null;
}
return self.local_refs.values[frame.locals_top - (1 + index)];
.dynamic => |dynamic| dynamic.typeinfo.get(.{
.userdata = dynamic.userdata,
.env = self,
.index_ref = index_ref,
}),
};
}
pub fn local_get(self: *RuntimeEnv, local: u8) ?*RuntimeRef {
pub fn local_get(self: *RuntimeEnv, local: u8) RuntimeError!?*RuntimeRef {
return self.local_refs.values[local];
}
pub fn local_pop(self: *RuntimeEnv) ?*RuntimeRef {
const ref = self.local_refs.pop();
coral.debug.assert(ref != null);
return ref.?;
pub fn local_pop(self: *RuntimeEnv) RuntimeError!?*RuntimeRef {
return self.local_refs.pop() orelse self.raise(error.IllegalState, "stack underflow");
}
pub fn local_push_ref(self: *RuntimeEnv, ref: ?*RuntimeRef) RuntimeError!void {
@ -206,17 +214,16 @@ pub const RuntimeEnv = struct {
return self.local_refs.push_one(try self.new_number(number));
}
pub fn local_set(self: *RuntimeEnv, local: u8, value: ?*RuntimeRef) void {
pub fn local_set(self: *RuntimeEnv, local: u8, value: ?*RuntimeRef) RuntimeError!void {
self.local_refs.values[local] = self.acquire(value);
}
pub fn make(allocator: coral.io.Allocator, error_handler: ErrorHandler) coral.io.AllocationError!RuntimeEnv {
return RuntimeEnv{
pub fn make(allocator: coral.io.Allocator, options: Options) RuntimeError!RuntimeEnv {
return .{
.local_refs = RefStack.make(allocator),
.ref_values = RefSlab.make(allocator),
.frames = FrameStack.make(allocator),
.syscallers = SyscallerTable.make(allocator),
.error_handler = error_handler,
.err_writer = options.err_writer,
.allocator = allocator,
};
}
@ -228,11 +235,7 @@ pub const RuntimeEnv = struct {
}));
}
pub fn new_dynamic(
self: *RuntimeEnv,
userdata: []const coral.io.Byte,
typeinfo: *const Typeinfo,
) RuntimeError!*RuntimeRef {
pub fn new_dynamic(self: *RuntimeEnv, userdata: []const coral.io.Byte, typeinfo: *const Typeinfo) RuntimeError!*RuntimeRef {
const userdata_copy = try coral.io.allocate_copy(self.allocator, userdata);
errdefer self.allocator.deallocate(userdata_copy);
@ -268,17 +271,30 @@ pub const RuntimeEnv = struct {
}));
}
pub fn raise(self: *RuntimeEnv, error_value: RuntimeError, message: []const coral.io.Byte) RuntimeError {
self.error_handler.invoke(.{
.message = message,
.frames = self.frames.values,
});
pub fn raise(self: *RuntimeEnv, error_value: RuntimeError, error_message: []const u8) RuntimeError {
// TODO: Print stack trace from state.
coral.utf8.print_formatted(self.err_writer, "{name}@{line}: {message}", .{
.name = "???",
.line = @as(u64, 0),
.message = error_message,
}) catch {};
return error_value;
}
pub fn syscaller(self: *RuntimeEnv, name: []const coral.io.Byte) RuntimeError!Syscaller {
return self.syscallers.lookup(name) orelse self.raise(error.BadOperation, "attempt to call undefined syscall");
pub fn set_dynamic(self: *RuntimeEnv, indexable_ref: ?*const RuntimeRef, index_ref: ?*const RuntimeRef, value_ref: ?*const RuntimeRef) RuntimeError!void {
return switch (self.unbox(indexable_ref)) {
.nil => self.raise(error.BadOperation, "nil is immutable"),
.boolean => self.raise(error.BadOperation, "boolean is immutable"),
.number => self.raise(error.BadOperation, "number is immutable"),
.string => self.raise(error.BadOperation, "string is immutable"),
.dynamic => |dynamic| dynamic.typeinfo.set(.{
.userdata = dynamic.userdata,
.env = self,
.index_ref = index_ref,
}, value_ref),
};
}
pub fn unbox(self: *RuntimeEnv, ref: ?*const RuntimeRef) Unboxed {
@ -294,48 +310,18 @@ pub const RuntimeEnv = struct {
.dynamic => |dynamic| .{.dynamic = dynamic},
};
}
pub fn unbox_dynamic(self: *RuntimeEnv, ref: ?*const RuntimeRef) RuntimeError![]const coral.io.Byte {
if (ref) |live_ref| {
const ref_data = self.ref_values.lookup(@intFromPtr(live_ref));
coral.debug.assert(ref_data != null);
if (ref_data.?.object == .dynamic) {
return ref_data.?.object.dynamic;
}
}
return self.raise(error.TypeMismatch, "expected dynamic");
}
pub fn unbox_string(self: *RuntimeEnv, ref: ?*const RuntimeRef) RuntimeError![]const coral.io.Byte {
if (ref) |live_ref| {
const ref_data = self.ref_values.lookup(@intFromPtr(live_ref));
coral.debug.assert(ref_data != null);
if (ref_data.?.object == .string) {
return ref_data.?.object.string;
}
}
return self.raise(error.TypeMismatch, "expected string");
}
};
pub const RuntimeError = coral.io.AllocationError || error {
IllegalState,
SystemFailure,
TypeMismatch,
BadOperation,
BadSyntax,
Assertion,
};
pub const RuntimeRef = opaque {};
pub const Syscaller = coral.io.Generator(RuntimeError!?*RuntimeRef, *RuntimeEnv);
pub const TestContext = struct {
env: *RuntimeEnv,
userdata: []const coral.io.Byte,
@ -343,30 +329,13 @@ pub const TestContext = struct {
};
pub const Typeinfo = struct {
name: []const coral.io.Byte,
call: *const fn (context: CallContext) RuntimeError!?*RuntimeRef = default_call,
clean: *const fn (userdata: []coral.io.Byte) void = default_clean,
get: *const fn (context: IndexContext) RuntimeError!?*RuntimeRef = default_get,
set: *const fn (context: IndexContext, value: ?*const RuntimeRef) RuntimeError!void = default_set,
call: *const fn (context: CallContext) RuntimeError!?*RuntimeRef,
clean: *const fn (userdata: []u8) void,
get: *const fn (context: IndexContext) RuntimeError!?*RuntimeRef,
set: *const fn (context: IndexContext, value: ?*const RuntimeRef) RuntimeError!void,
test_difference: *const fn (context: TestContext) RuntimeError!Float = default_test_difference,
test_equality: *const fn (context: TestContext) RuntimeError!bool = default_test_equality,
fn default_call(context: CallContext) RuntimeError!?*RuntimeRef {
return context.env.raise(error.TypeMismatch, "object is not callable");
}
fn default_clean(_: []coral.io.Byte) void {
// Nothing to clean by default.
}
fn default_get(context: IndexContext) RuntimeError!?*RuntimeRef {
return context.env.raise(error.TypeMismatch, "object is not indexable");
}
fn default_set(context: IndexContext, _: ?*const RuntimeRef) RuntimeError!void {
return context.env.raise(error.TypeMismatch, "object is not indexable");
}
fn default_test_difference(context: TestContext) RuntimeError!Float {
return context.env.raise(error.TypeMismatch, "object is not comparable");
}
@ -383,89 +352,16 @@ pub const Unboxed = union (enum) {
nil,
boolean: bool,
number: Float,
string: []const coral.io.Byte,
string: []const u8,
dynamic: *const DynamicObject,
pub fn expect_dynamic(self: Unboxed, env: *RuntimeEnv) RuntimeError!*const DynamicObject {
return switch (self) {
.dynamic => |dynamic| dynamic,
else => env.raise(error.TypeMismatch, "expected dynamic"),
};
}
};
pub fn assert(env: *RuntimeEnv, condition: bool, message: []const coral.io.Byte) RuntimeError!void {
if (!condition) {
return env.raise(error.Assertion, message);
}
}
pub fn get_dynamic_field(env: *RuntimeEnv, indexable: ?*const RuntimeRef, field: []const u8) RuntimeError!?*RuntimeRef {
var interned_field = try env.new_string(field);
pub fn call(
env: *RuntimeEnv,
caller_ref: ?*const RuntimeRef,
callable_ref: ?*const RuntimeRef,
arg_refs: Args,
) RuntimeError!?*RuntimeRef {
for (arg_refs) |arg_ref| {
try env.local_push_ref(arg_ref);
}
defer env.discard(&interned_field);
env.frame_push("", arg_refs.len);
defer env.frame_pop();
const dynamic = try env.unbox(callable_ref).expect_dynamic();
return dynamic.type_info.call(.{
.env = env,
.caller = caller_ref,
.userdata = dynamic.userdata,
});
}
pub fn get(
env: *RuntimeEnv,
indexable_ref: ?*const RuntimeRef,
index_ref: ?*const RuntimeRef,
) RuntimeError!?*RuntimeRef {
const dynamic = try env.unbox(indexable_ref).expect_dynamic(env);
return dynamic.typeinfo.get(.{
.userdata = dynamic.userdata,
.env = env,
.index_ref = index_ref,
});
}
pub fn get_field(env: *RuntimeEnv, indexable_ref: ?*const RuntimeRef, field_name: []const coral.io.Byte) RuntimeError!?*RuntimeRef {
const field_name_ref = try env.new_string(field_name);
defer env.discard(field_name_ref);
return get(env, indexable_ref, field_name_ref);
}
pub fn set(
env: *RuntimeEnv,
indexable_ref: ?*const RuntimeRef,
index_ref: ?*const RuntimeRef,
value_ref: ?*const RuntimeRef,
) RuntimeError!void {
const dynamic = try env.unbox(indexable_ref).expect_dynamic(env);
return dynamic.typeinfo.set(.{
.userdata = dynamic.userdata,
.env = env,
.index_ref = index_ref,
}, value_ref);
}
pub fn set_field(env: *RuntimeEnv, indexable_ref: ?*const RuntimeRef, field_name: []const coral.io.Byte, value_ref: ?*const RuntimeRef) RuntimeError!void {
const field_name_ref = try env.new_string(field_name);
defer env.discard(field_name_ref);
return set(env, indexable_ref, field_name_ref, value_ref);
return env.get_dynamic(indexable, interned_field);
}
pub fn new_table(env: *RuntimeEnv) RuntimeError!?*RuntimeRef {

View File

@ -17,7 +17,7 @@ pub const Expression = union (enum) {
grouped_expression: *Expression,
get_local: []const coral.io.Byte,
call_system: struct {
call_global: struct {
identifier: []const coral.io.Byte,
argument_expressions: List,
},
@ -85,7 +85,7 @@ pub const Statement = union (enum) {
expression: Expression,
},
call_system: struct {
call_global: struct {
identifier: []const coral.io.Byte,
argument_expressions: Expression.List,
},
@ -249,7 +249,7 @@ pub fn parse(self: *Self, tokenizer: *tokens.Tokenizer) ParseError!void {
tokenizer.step();
try self.statements.push_one(.{
.call_system = .{
.call_global = .{
.argument_expressions = expressions_list,
.identifier = identifier,
},
@ -344,7 +344,7 @@ fn parse_factor(self: *Self, tokenizer: *tokens.Tokenizer) ParseError!Expression
tokenizer.step();
return Expression{
.call_system = .{
.call_global = .{
.identifier = identifier,
.argument_expressions = expression_list,
},
@ -361,7 +361,7 @@ fn parse_factor(self: *Self, tokenizer: *tokens.Tokenizer) ParseError!Expression
tokenizer.step();
return Expression{
.call_system = .{
.call_global = .{
.identifier = identifier,
.argument_expressions = expression_list,
},

View File

@ -51,7 +51,8 @@ const AstCompiler = struct {
});
}
try self.chunk.append_opcode(.{.push_table = @intCast(fields.values.len)});
try self.chunk.append_opcode(.{
.push_table = .{.field_count = @intCast(fields.values.len)}});
},
.binary_operation => |operation| {
@ -86,11 +87,11 @@ const AstCompiler = struct {
.get_local => |local| {
try self.chunk.append_opcode(.{
.push_local = self.resolve_local(local) orelse return self.chunk.env.raise(error.OutOfMemory, "undefined local"),
.local_push_ref = self.resolve_local(local) orelse return self.chunk.env.raise(error.OutOfMemory, "undefined local"),
});
},
.call_system => |call| {
.call_global => |call| {
if (call.argument_expressions.values.len > coral.math.max_int(@typeInfo(u8).Int)) {
return self.chunk.env.raise(error.OutOfMemory, "functions may receive a maximum of 255 locals");
}
@ -100,8 +101,12 @@ const AstCompiler = struct {
}
try self.chunk.append_opcode(.{.push_const = try self.chunk.declare_constant_string(call.identifier)});
try self.chunk.append_opcode(.{.syscall = @intCast(call.argument_expressions.values.len)});
try self.chunk.append_opcode(.pop);
try self.chunk.append_opcode(.{
.global_call = .{
.arg_count = @intCast(call.argument_expressions.values.len),
},
});
},
}
}
@ -121,7 +126,7 @@ const AstCompiler = struct {
}
},
.call_system => |call| {
.call_global => |call| {
if (call.argument_expressions.values.len > coral.math.max_int(@typeInfo(u8).Int)) {
return self.chunk.env.raise(error.OutOfMemory, "functions may receive a maximum of 255 locals");
}
@ -131,8 +136,12 @@ const AstCompiler = struct {
}
try self.chunk.append_opcode(.{.push_const = try self.chunk.declare_constant_string(call.identifier)});
try self.chunk.append_opcode(.{.syscall = @intCast(call.argument_expressions.values.len)});
try self.chunk.append_opcode(.pop);
try self.chunk.append_opcode(.{
.global_call = .{
.arg_count = @intCast(call.argument_expressions.values.len),
},
});
}
}
}
@ -172,16 +181,21 @@ const RefList = coral.list.Stack(?*kym.RuntimeRef);
const LocalsList = coral.list.Stack([]const u8);
pub const Opcode = union (enum) {
pop,
push_nil,
push_true,
push_false,
push_const: Constant,
push_local: u8,
push_table: u32,
local_push_ref: u8,
set_local: u8,
call: u8,
syscall: u8,
get_global,
push_table: struct {
field_count: u32,
},
global_call: struct {
arg_count: u8,
},
not,
neg,
@ -228,9 +242,9 @@ pub fn declare_constant_number(self: *Self, constant: kym.Float) kym.RuntimeErro
return self.env.raise(error.BadSyntax, "functions may contain a maximum of 65,535 constants");
}
const constant_ref = try self.env.new_number(constant);
var constant_ref = try self.env.new_number(constant);
errdefer self.env.discard(constant_ref);
errdefer self.env.discard(&constant_ref);
try self.constant_refs.push_one(constant_ref);
@ -244,128 +258,93 @@ pub fn declare_constant_string(self: *Self, constant: []const coral.io.Byte) kym
return self.env.raise(error.BadSyntax, "functions may contain a maximum of 65,535 constants");
}
const constant_ref = try self.env.new_string(constant);
var constant_ref = try self.env.new_string(constant);
errdefer self.env.discard(constant_ref);
errdefer self.env.discard(&constant_ref);
try self.constant_refs.push_one(constant_ref);
return @intCast(tail);
}
pub fn execute(self: *Self, name: []const coral.io.Byte) kym.RuntimeError!?*kym.RuntimeRef {
try self.env.frame_push(name, 0);
pub fn execute(self: *Self, global_ref: ?*const kym.RuntimeRef, name: []const coral.io.Byte) kym.RuntimeError!?*kym.RuntimeRef {
_ = name;
defer self.env.frame_pop();
try self.env.frame_push();
for (self.opcodes.values) |opcode| {
switch (opcode) {
.pop => self.env.discard(self.env.local_pop()),
.push_nil => try self.env.local_push_ref(null),
.push_true => try self.env.local_push_boolean(true),
.push_false => try self.env.local_push_boolean(false),
.push_const => |constant| try self.env.local_push_ref(self.constant_refs.values[constant]),
.push_table => |field_count| {
const table_ref = try kym.new_table(self.env);
.push_table => |push_table| {
var table_ref = try kym.new_table(self.env);
defer self.env.discard(table_ref);
defer self.env.discard(&table_ref);
{
const dynamic = try self.env.unbox(table_ref).expect_dynamic(self.env);
var popped = @as(usize, 0);
while (popped < field_count) : (popped += 1) {
const index_ref = self.env.local_pop();
const value_ref = self.env.local_pop();
try dynamic.typeinfo.set(.{
.userdata = dynamic.userdata,
.env = self.env,
.index_ref = index_ref,
}, value_ref);
while (popped < push_table.field_count) : (popped += 1) {
try self.env.set_dynamic(table_ref, try self.env.local_pop(), try self.env.local_pop());
}
}
try self.env.local_push_ref(table_ref);
},
.push_local => |local| {
const ref = self.env.local_get(local);
.local_push_ref => |local| {
var ref = try self.env.local_get(local);
defer self.env.discard(ref);
defer self.env.discard(&ref);
try self.env.local_push_ref(ref);
},
.get_global => {
var identifier_ref = try self.env.local_pop();
defer self.env.discard(&identifier_ref);
var ref = try self.env.get_dynamic(global_ref, identifier_ref);
defer self.env.discard(&ref);
try self.env.local_push_ref(ref);
},
.set_local => |local| {
const ref = self.env.local_pop();
var ref = try self.env.local_pop();
defer self.env.discard(ref);
defer self.env.discard(&ref);
self.env.local_set(local, ref);
try self.env.local_set(local, ref);
},
.call => |arg_count| {
const callable_ref = self.env.local_pop();
.global_call => |_| {
defer self.env.discard(callable_ref);
try self.env.frame_push("", arg_count);
defer self.env.frame_pop();
const dynamic = try self.env.unbox(callable_ref).expect_dynamic(self.env);
const result_ref = try dynamic.typeinfo.call(.{
.env = self.env,
.caller = null,
.userdata = dynamic.userdata,
});
defer self.env.discard(result_ref);
try self.env.local_push_ref(result_ref);
},
.syscall => |arg_count| {
const identifier_ref = self.env.local_pop();
defer self.env.discard(identifier_ref);
const identifier = try self.env.unbox_string(identifier_ref);
try self.env.frame_push(identifier, arg_count);
errdefer self.env.frame_pop();
const result_ref = try (try self.env.syscaller(identifier)).invoke(self.env);
defer self.env.discard(result_ref);
self.env.frame_pop();
try self.env.local_push_ref(result_ref);
},
.neg => try self.env.local_push_number(switch (self.env.unbox(self.env.local_pop())) {
.neg => try self.env.local_push_number(switch (self.env.unbox(try self.env.local_pop())) {
.number => |number| -number,
else => return self.env.raise(error.TypeMismatch, "object is not scalar negatable"),
}),
.not => try self.env.local_push_boolean(switch (self.env.unbox(self.env.local_pop())) {
.not => try self.env.local_push_boolean(switch (self.env.unbox(try self.env.local_pop())) {
.boolean => |boolean| !boolean,
else => return self.env.raise(error.TypeMismatch, "object is not boolean negatable"),
}),
.add => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_ref(switch (self.env.unbox(lhs_ref)) {
.number => |lhs_number| switch (self.env.unbox(rhs_ref)) {
@ -378,13 +357,13 @@ pub fn execute(self: *Self, name: []const coral.io.Byte) kym.RuntimeError!?*kym.
},
.sub => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_ref(switch (self.env.unbox(lhs_ref)) {
.number => |lhs_number| switch (self.env.unbox(rhs_ref)) {
@ -397,13 +376,13 @@ pub fn execute(self: *Self, name: []const coral.io.Byte) kym.RuntimeError!?*kym.
},
.mul => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_ref(switch (self.env.unbox(lhs_ref)) {
.number => |lhs_number| switch (self.env.unbox(rhs_ref)) {
@ -416,13 +395,13 @@ pub fn execute(self: *Self, name: []const coral.io.Byte) kym.RuntimeError!?*kym.
},
.div => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_ref(switch (self.env.unbox(lhs_ref)) {
.number => |lhs_number| switch (self.env.unbox(rhs_ref)) {
@ -435,72 +414,76 @@ pub fn execute(self: *Self, name: []const coral.io.Byte) kym.RuntimeError!?*kym.
},
.eql => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_boolean(try kym.test_equality(self.env, lhs_ref, rhs_ref));
},
.cgt => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_boolean(try kym.test_difference(self.env, lhs_ref, rhs_ref) > 0);
},
.clt => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_boolean(try kym.test_difference(self.env, lhs_ref, rhs_ref) < 0);
},
.cge => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_boolean(try kym.test_difference(self.env, lhs_ref, rhs_ref) >= 0);
},
.cle => {
const rhs_ref = self.env.local_pop();
var rhs_ref = try self.env.local_pop();
defer self.env.discard(rhs_ref);
defer self.env.discard(&rhs_ref);
const lhs_ref = self.env.local_pop();
var lhs_ref = try self.env.local_pop();
defer self.env.discard(lhs_ref);
defer self.env.discard(&lhs_ref);
try self.env.local_push_boolean(try kym.test_difference(self.env, lhs_ref, rhs_ref) <= 0);
},
}
}
return self.env.local_pop();
const result = try self.env.local_pop();
try self.env.frame_pop();
return result;
}
pub fn free(self: *Self) void {
for (self.constant_refs.values) |constant| {
for (self.constant_refs.values) |*constant| {
self.env.discard(constant);
}

View File

@ -4,10 +4,10 @@ const kym = @import("../kym.zig");
fields: FieldTable,
const FieldTable = coral.map.StringTable(struct {
const FieldTable = coral.map.Table([]const coral.io.Byte, struct {
key_ref: ?*kym.RuntimeRef,
value_ref: ?*kym.RuntimeRef,
});
}, coral.map.string_table_traits);
const Self = @This();
@ -22,12 +22,16 @@ pub fn make(env: *kym.RuntimeEnv) Self {
}
pub const typeinfo = kym.Typeinfo{
.name = "table",
.call = typeinfo_call,
.clean = typeinfo_clean,
.get = typeinfo_get,
.set = typeinfo_set,
};
fn typeinfo_call(context: kym.CallContext) kym.RuntimeError!?*kym.RuntimeRef {
return context.env.raise(error.TypeMismatch, "cannot call a table");
}
fn typeinfo_clean(userdata: []u8) void {
@as(*Self, @ptrCast(@alignCast(userdata.ptr))).free();
}
@ -45,15 +49,15 @@ fn typeinfo_get(context: kym.IndexContext) kym.RuntimeError!?*kym.RuntimeRef {
fn typeinfo_set(context: kym.IndexContext, value_ref: ?*const kym.RuntimeRef) kym.RuntimeError!void {
const table = @as(*Self, @ptrCast(@alignCast(context.userdata.ptr)));
const acquired_value_ref = context.env.acquire(value_ref);
var acquired_value_ref = context.env.acquire(value_ref);
errdefer context.env.discard(acquired_value_ref);
errdefer context.env.discard(&acquired_value_ref);
switch (context.env.unbox(context.index_ref)) {
.string => |string| {
const acquired_index_ref = context.env.acquire(context.index_ref);
var acquired_index_ref = context.env.acquire(context.index_ref);
errdefer context.env.discard(acquired_index_ref);
errdefer context.env.discard(&acquired_index_ref);
var displaced_table_entry = if (acquired_value_ref) |ref| try table.fields.replace(string, .{
.key_ref = acquired_index_ref,
@ -61,8 +65,8 @@ fn typeinfo_set(context: kym.IndexContext, value_ref: ?*const kym.RuntimeRef) ky
}) else table.fields.remove(string);
if (displaced_table_entry) |*entry| {
context.env.discard(entry.value.key_ref);
context.env.discard(entry.value.value_ref);
context.env.discard(&entry.value.key_ref);
context.env.discard(&entry.value.value_ref);
}
},

View File

@ -10,85 +10,81 @@ const heap = @import("./heap.zig");
const kym = @import("./kym.zig");
fn kym_handle_errors(info: kym.ErrorInfo) void {
var remaining_frames = info.frames.len;
while (remaining_frames != 0) {
remaining_frames -= 1;
app.log_fail(info.frames[remaining_frames].name);
}
}
fn kym_log_info(env: *kym.RuntimeEnv) kym.RuntimeError!?*kym.RuntimeRef {
app.log_info(try env.unbox_string(try env.get_arg(0)));
return null;
}
fn kym_log_warn(env: *kym.RuntimeEnv) kym.RuntimeError!?*kym.RuntimeRef {
app.log_warn(try env.unbox_string(try env.get_arg(0)));
return null;
}
fn kym_log_fail(env: *kym.RuntimeEnv) kym.RuntimeError!?*kym.RuntimeRef {
app.log_fail(try env.unbox_string(try env.get_arg(0)));
return null;
}
pub const RuntimeError = error {
OutOfMemory,
InitFailure,
BadManifest,
};
fn last_sdl_error() [:0]const u8 {
return coral.io.slice_sentineled(@as(u8, 0), @as([*:0]const u8, @ptrCast(ext.SDL_GetError())));
}
pub fn run_app(file_access: file.Access) void {
pub fn run_app(file_access: file.Access) RuntimeError!void {
var info_log = app.WritableLog.make(.info, heap.allocator);
defer info_log.free();
var fail_log = app.WritableLog.make(.fail, heap.allocator);
defer fail_log.free();
if (ext.SDL_Init(ext.SDL_INIT_EVERYTHING) != 0) {
return app.log_fail(last_sdl_error());
try fail_log.write(last_sdl_error());
return error.InitFailure;
}
defer ext.SDL_Quit();
var script_env = kym.RuntimeEnv.make(heap.allocator, kym.ErrorHandler.from(kym_handle_errors)) catch {
return app.log_fail("failed to initialize script runtime");
var script_env = kym.RuntimeEnv.make(heap.allocator, .{
.out_writer = info_log.as_writer(),
.err_writer = fail_log.as_writer(),
}) catch {
try fail_log.write("failed to initialize script runtime");
return error.InitFailure;
};
defer script_env.free();
script_env.bind_syscalls(&.{
.{
.name = "log_info",
.caller = kym.Syscaller.from(kym_log_info),
},
.{
.name = "log_fail",
.caller = kym.Syscaller.from(kym_log_fail),
},
}) catch {
return app.log_fail("failed to initialize script runtime");
var globals_ref = kym.new_table(&script_env) catch {
try fail_log.write("failed to initialize script runtime");
return error.InitFailure;
};
defer script_env.discard(&globals_ref);
var manifest = app.Manifest{};
manifest.load(&script_env, file_access) catch return;
manifest.load(&script_env, globals_ref, file_access) catch {
fail_log.write("failed to load / execute app.ona manifest") catch {};
return error.BadManifest;
};
const window = create: {
const pos = ext.SDL_WINDOWPOS_CENTERED;
const flags = 0;
break: create ext.SDL_CreateWindow(&manifest.title, pos, pos, manifest.width, manifest.height, flags) orelse {
return app.log_fail(last_sdl_error());
fail_log.write(last_sdl_error()) catch {};
return error.InitFailure;
};
};
defer ext.SDL_DestroyWindow(window);
const renderer = create: {
const default_driver_index = -1;
const defaultDriverIndex = -1;
const flags = ext.SDL_RENDERER_ACCELERATED;
break: create ext.SDL_CreateRenderer(window, default_driver_index, flags) orelse {
return app.log_fail(last_sdl_error());
break: create ext.SDL_CreateRenderer(window, defaultDriverIndex, flags) orelse {
fail_log.write(last_sdl_error()) catch {};
return error.InitFailure;
};
};

View File

@ -1,5 +1,5 @@
const ona = @import("ona");
pub fn main() anyerror!void {
ona.run_app(.{.sandboxed_path = &ona.file.Path.cwd});
pub fn main() ona.RuntimeError!void {
try ona.run_app(.{.sandboxed_path = &ona.file.Path.cwd});
}