spl 编写编译器基础框架 ai修复出现的stage2和stage3问题并提供新语法

This commit is contained in:
zzy committed 2026-11-07 21:52:02 +08:00
1 parent 126b979f72
commit 50ee126d44
87 files changed
+3168 -394

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
type .{ .Vec } = @import("core/vec.spl");
type .{ .Allocator } = @import("core/alloc.spl");
type .{ .String } = @import("core/str.spl");
type .{ .Result } = @import("core/error.spl");
type ptr = @import("core/ptr.spl");
type .{ .File } = @import("compiler/shape.spl");
type SourceId = u32;
pub comptime fn SourceFile(A: Allocator): type {
ret struct {
id: SourceId,
name: @Vec(u8, A),
content: @Vec(u8, A),
line_offsets: @Vec(usize, A),
}
}
type SourceError = enum {
UnknownError,
FileOpenError,
FileAttributeError,
FileReadError,
OutOfMemory,
}
pub comptime fn Source(A: Allocator, F: File): type {
ret struct {
// TODO HashSet 进行去重
files: @Vec(@SourceFile(A), A),
fshape: F,
alloc: A,
pub fn new(alloc: A, fshape: F): @self {
ret .{ .files = @Vec(@SourceFile(A), A).empty(alloc), .alloc = alloc, .fshape = fshape };
}
pub fn add_file(@Self self: *@self, name: []const u8): @Result(SourceId, SourceError) {
var fp = self.fshape.open(name, .Read) catch .Err(_) {
ret .(.Err(.FileOpenError));
};
errdefer { fp.close(); }
var size = fp.size() catch .Err(_) {
ret .(.Err(.FileAttributeError));
};
var content = @Vec(u8, A).with_capacity(self.alloc, size) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
content._set_len(size);
var read_size = fp.read(content.as_slice()) catch .Err(_) {
ret .(.Err(.FileReadError));
};
if read_size != size {
ret .(.Err(.FileReadError));
}
var owned_name = @Vec(u8, A).with_capacity(self.alloc, name.len()) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
owned_name._set_len(name.len());
ptr.copy(owned_name.as_slice().as_ptr(), name.as_ptr(), name.len());
ret self.add_virtual(owned_name, content);
}
pub fn add_virtual(@Self self: *@self, name: @Vec(u8, A), content: @Vec(u8, A)): @Result(SourceId, SourceError) {
var id = self.files.len();
var file: @SourceFile(A) = .{
.id = id as u32,
.name = name,
.content = content,
.line_offsets = @Vec(usize, A).empty(self.alloc),
};
self.files.push(file) catch .Err(e) {
ret .(.Err(.OutOfMemory));
};
ret .(.Ok(id as SourceId));
}
}
}
+30
View File
@@ -0,0 +1,30 @@
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result, .Option } = @import("core/error.spl");
pub type FileMode = enum {
Read,
Write,
Append,
}
pub type File = shape: Writer + Reader {
fn open(path: []const u8, mode: FileMode): @Result(@self, IOError);
fn close(@Self self: *@self): @Result((), IOError);
fn size(@Self self: *@self): @Result(usize, IOError);
}
pub type Time = shape {
}
pub type Memory = shape {
}
pub type Process = shape {
}
pub type VM = shape {
}
+197
View File
@@ -0,0 +1,197 @@
#extern(vm) fn vm_fopen(path: *any, mode: *any): *any;
#extern(vm) fn vm_fclose(f: *any): i32;
#extern(vm) fn vm_fread(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fwrite(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fsize(f: *any): usize;
#extern(vm) fn vm_fflush(f: *any): i32;
#extern(vm) fn vm_stdin(): *any;
#extern(vm) fn vm_stdout(): *any;
#extern(vm) fn vm_stderr(): *any;
#extern(vm) fn vm_putchar(c: i32): i32;
#extern(vm) fn vm_getchar(): i32;
#extern(vm) fn vm_exit(code: i32);
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
#extern(vm) fn vm_realloc(p: *any, sz: usize): *any;
#extern(vm) fn vm_memcpy(dst: *any, src: *any, n: usize): *any;
#extern(vm) fn vm_memcmp(a: *any, b: *any, n: usize): isize;
// 时间/参考量接口(原生 vm_timestamp,case 探测风格,不假设一定可用)。
// available() -> 1 = 时间可用;0 = 不可用(其余 time 相关返回值恒为 0)
// sec() -> 当前秒
// ns() -> 当前纳秒部分
// steps() -> VM 已执行指令数(参考量)
// now_ns() -> 完整纳秒时间戳(单次调用;纪元纳秒 < 2^64,无需 i128)
#extern(vm) fn vm_timestamp(kind: usize): usize;
#extern(vm) fn vm_new(): *any;
#extern(vm) fn vm_drop(vm: *any): void;
#extern(vm) fn vm_load(vm: *any, fpath: *u8): void;
#extern(vm) fn vm_load_from_buffer(vm: *any, buf: *any, len: usize): i32;
#extern(vm) fn vm_push(vm: *any, val: spl_vm_val_t): void;
#extern(vm) fn vm_call(vm: *any, name: *u8, nargs: u64): i32;
#extern(vm) fn vm_run(vm: *any): i32;
#extern(vm) fn vm_ret_val(vm: *any): spl_vm_val_t;
#extern(vm) fn vm_mem_alloc(vm: *any, size: usize): spl_vm_val_t;
#extern(vm) fn vm_mem_read(vm: *any, off: spl_vm_val_t, dst: *any, n: usize): i32;
#extern(vm) fn vm_mem_write(vm: *any, off: spl_vm_val_t, src: *any, n: usize): i32;
#extern(vm) fn vm_stack_get(vm: *any, index: usize): spl_vm_val_t;
#extern(vm) fn vm_set_foreign(vm: *any, entry: []u8, ctx: *any): void;
// 把外部处理器名绑定到宿主函数。SIR 后端按名调用宿主 VM 函数,无需登记;
// 原生后端没有名字到地址的运行时表,需要这里先登记函数指针。
#extern(vm) fn vm_bind_foreign(entry: []u8,
handler: fn(*any, u64, u64, *any, u64, u64): u64): void;
type .{ .Allocator, .AllocError, .Layout } = @import("core/alloc.spl");
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result } = @import("core/error.spl");
pub fn strlen(str: *const u8): usize {
var len: usize = 0;
while (str[len] != 0) {
len = len + 1;
}
ret len;
}
pub type VMAllocator = struct: Allocator {
pub fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError) {
var res = vm_alloc(layout.size);
if res == null {
ret .(.Err(AllocError.OutOfMemory));
}
ret .(.Ok(res));
}
pub fn dealloc(@Self self: *@self, ptr: *any, layout: Layout) {
vm_free(ptr);
}
}
// pub type VMReader = struct: Reader {
// }
pub type VMWriter = struct: Writer {
file: *any;
pub fn with_file(f: *any): VMWriter {
ret VMWriter { .file = f };
}
pub fn with_stdout(): VMWriter {
ret VMWriter { .file = vm_stdout() };
}
pub fn with_stderr(): VMWriter {
ret VMWriter { .file = vm_stderr() };
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
}
type .{ .File, .FileMode, .Time, .Memory, .Process, .VM } = @import("./shape.spl");
type ptr = @import("core/ptr.spl");
type VMFile = struct: File {
file: *any;
pub fn with_stdout(): @self {
ret .{ .file = vm_stdout() };
}
pub fn with_stderr(): @self {
ret .{ .file = vm_stderr() };
}
pub fn open(path: []const u8, mode: FileMode): @Result(@self, IOError) {
var mode_str: []const u8 = match (mode) {
.Read => {"rb\0"},
.Write => {"wb\0"},
.Append => {"ab\0"},
};
// TODO hack it;
var path_cstr: [1024]u8 = .[];
ptr.copy(path_cstr.as_ptr(), path.as_ptr(), path.len());
path_cstr[path.len()] = 0;
var f = vm_fopen(path_cstr.as_ptr() as *any, mode_str.as_ptr() as *any);
if f == null {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(VMFile { .file = f }));
}
pub fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fread(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn size(@Self self: *@self): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
ret .(.Ok(vm_fsize(f)));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
pub fn close(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fclose(f);
if result != 0 {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(()));
}
}
+16
View File
@@ -0,0 +1,16 @@
type .{ .Result } = @import("./error.spl");
pub type Layout = struct {
size: usize;
align: usize;
}
pub type AllocError = enum {
OutOfMemory,
InvalidLayout,
}
pub type Allocator = shape {
fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError);
fn dealloc(@Self self: *@self, ptr: *any, layout: Layout);
}
+59
View File
@@ -0,0 +1,59 @@
pub comptime fn Option(T: type): type {
ret enum {
pub Some: T,
pub None: void,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic("called unwrap on None"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { ret f(); }
// }
// }
};
}
pub comptime fn Result(T: type, E: type): type {
ret enum {
#ok
pub Ok: T,
#error
pub Err: E,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic("called unwrap on Err"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { ret f(); }
// }
// }
};
}
+23
View File
@@ -0,0 +1,23 @@
pub type Display = shape {
fn fmt(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Debug = shape {
fn debug(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Sink = shape {
fn write_byte(@Self self: *@self, byte: u8): bool;
// TODO shape default value for `fn write_bytes(@Self self: *@self, bytes: []const u8): bool;`
};
pub comptime fn Formatter(S: Sink): type {
ret struct {
out: S,
pub fn with_sink(out: S): @self {
ret .{ .out = out };
}
};
}
View File
Whitespace-only changes.
+19
View File
@@ -0,0 +1,19 @@
type .{ .Allocator } = @import("./alloc.spl");
type .{ .Result } = @import("./error.spl");
type .{ .static } = @import("./macro.spl");
type IOError = enum {
UnknownError,
OutOfMemory,
BufferTooSmall,
}
pub type Reader = shape {
fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError);
}
pub type Writer = shape {
fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError);
fn flush(@Self self: *@self): @Result((), IOError);
}
+22
View File
@@ -0,0 +1,22 @@
type meta = @import("meta");
type .{ .Ref } = meta;
#hook(param)
macro fn default(callee: Ref, value: Ref, fallback: Ref): Ref {
if value != 0 { ret value; }
if fallback != 0 { @meta.error(704); ret 0; }
// TODO check the same type
ret Ref;
}
#hook(param)
macro fn Self(callee: Ref, value: Ref): Ref {
// TODO value direct not supported
// @meta.
ret @meta.construct(.{ .kind = .Addr(value) });
}
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
pub fn bytes_eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
fn copy(dst: *any, src: *const any, count: usize) {
var _dst = dst as *u8;
var _src = src as *const u8;
var i: usize = 0;
while (i < count) {
_dst[i] = _src[i];
i = i + 1;
}
}
+120
View File
@@ -0,0 +1,120 @@
type .{ .Vec } = @import("./vec.spl");
type .{ .Allocator, .AllocError } = @import("./alloc.spl");
type .{ .Result, .Option } = @import("./error.spl");
type .{ .Format } = @import("./fmt.spl");
type .{ .static } = @import("./macro.spl");
type FromStr = shape {
type Err;
fn from_str(s: []const u8): @Result(@self, Err);
}
pub fn eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
pub fn starts_with(s: []const u8, prefix: []const u8): bool {
if prefix.len() > s.len() { ret false; }
ret eq(s[0..prefix.len()], prefix);
}
pub fn index_byte(s: []const u8, b: u8, from: usize): @Option(usize) {
var i = from;
while i < s.len() {
if s[i] == b { ret .Some(i); }
i = i + 1;
}
ret .None;
}
pub fn is_space(b: u8): bool {
ret b == ' ' || b == '\t' || b == '\r' || b == '\n';
}
pub fn is_digit(b: u8): bool {
ret b >= '0' && b <= '9';
}
pub fn is_hex_digit(b: u8): bool {
ret is_digit(b) || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F');
}
pub fn is_alpha(b: u8): bool {
ret (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z');
}
pub fn is_ident_start(b: u8): bool {
ret is_alpha(b) || b == '_';
}
pub fn is_ident_continue(b: u8): bool {
ret is_ident_start(b) || is_digit(b);
}
pub fn trim_ascii(s: []const u8): []const u8 {
var a: usize = 0;
var b: usize = s.len();
while a < b && is_space(s[a]) { a = a + 1; }
while b > a && is_space(s[b - 1]) { b = b - 1; }
ret s[a..b];
}
pub comptime fn String(A: Allocator): type {
ret struct {
data: @Vec(u8, A),
pub fn new(alloc: A): @self {
ret .{ .data = @Vec(u8, A).empty(alloc) };
}
pub fn from_slice(alloc: A, s: []const u8): @Result(@self, AllocError) {
var out: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try out.push_str(s);
ret .(.Ok(out));
}
pub fn push_str(@Self self: *@self, s: []const u8): @Result((), AllocError) {
var i: usize = 0;
while i < s.len() {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn from_cstr(alloc: A, s: *const u8): @Result(@self, AllocError) {
var res: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try res.push_cstr(s);
ret .(.Ok(res));
}
pub fn push_cstr(@Self self: *@self, s: *const u8): @Result((), AllocError) {
var i: usize = 0;
while s[i] != 0 {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn as_slice(@Self self: *@self): []const u8 {
ret self.data.as_slice();
}
pub fn len(@Self self: *@self): usize {
ret self.data.len();
}
pub fn clear(@Self self: *@self) {
self.data.clear();
}
pub fn drop(@Self self: *@self) {
self.data.drop();
}
};
}
+279
View File
@@ -0,0 +1,279 @@
type .{ .Option, .Result } = @import("./error.spl");
type .{ .Layout, .AllocError, .Allocator } = @import("./alloc.spl");
type ptr = @import("ptr.spl");
comptime fn RawVec(t: type): type {
ret struct {
data: *t,
length: usize,
cap: usize,
pub fn empty(): @self {
ret .{ .data = null, .length = 0, .cap = 0 };
}
pub fn len(@Self self: *@self): usize {
ret self.length;
}
pub fn capacity(@Self self: *@self): usize {
ret self.cap;
}
pub fn as_raw_ptr(@Self self: *@self): *t {
ret self.data;
}
pub fn as_slice(@Self self: *@self): []t {
ret @Slice(t).from_raw_parts(self.data, self.length);
}
pub fn get(@Self self: *@self, i: usize): @Option(t) {
if i >= self.length { ret .None }
ret .Some(self.data[i]);
}
pub fn at(@Self self: *@self, i: usize): @Option(*t) {
if i >= self.length { ret .None }
ret .Some(self.data + i);
}
pub fn set(@Self self: *@self, i: usize, v: t): bool {
if (i >= self.length) { ret false }
self.data[i] = v;
ret true;
}
pub fn clear(@Self self: *@self): () {
self.length = 0;
}
pub fn truncate(@Self self: *@self, n: usize): () {
if n < self.length {
self.length = n;
}
}
pub fn reset(@Self self: *@self): () {
self.data = null;
self.length = 0;
self.cap = 0;
}
pub fn set_unchecked(@Self self: *@self, i: usize, v: t) {
self.data[i] = v;
}
pub fn push_unchecked(@Self self: *@self, v: t): () {
self.data[self.length] = v;
self.length = self.length + 1;
}
pub fn pop_unchecked(@Self self: *@self): t {
self.length = self.length - 1;
ret self.data[self.length];
}
pub fn insert_unchecked(@Self self: *@self, i: usize, v: t): () {
var j = self.length;
while j > i {
self.data[j] = self.data[j - 1];
j = j - 1;
}
self.data[i] = v;
self.length += 1;
}
pub fn remove_unchecked(@Self self: *@self, i: usize): t {
var v = self.data[i];
var j = i;
while j + 1 < self.length {
self.data[j] = self.data[j + 1];
j = j + 1;
}
self.length -= 1;
ret v;
}
};
}
fn layout_of(size: usize, align: usize, n: usize): Layout {
var limit: usize = ~(0 as usize);
@assert(n == 0 || size <= limit / n, "layout overflow");
ret .{ .size = size * n, .align = align };
}
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap {
cap = min_cap;
}
while cap < need {
cap = cap * 2;
}
ret cap;
}
comptime fn Grow(T: type, A: Allocator): type {
ret struct {
fn reserve(base: *@RawVec(T), alloc: A, additional: usize): @Result((), AllocError) {
var need = base.len() + additional;
if need <= base.capacity() {
ret;
}
var new_cap = grow_capacity(base.capacity(), 8, need);
var old_layout = layout_of(@sizeof(T), @alignof(T), base.capacity());
var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap);
var p: *u8 = try alloc.alloc(new_layout) as *u8;
if base.capacity() != 0 {
// TODO : Use copy_nonoverlapping to copy the data from the old allocation to the new one
// This is a placeholder for the actual memory copy operation
ptr.copy(p, base.data as *u8, base.len() * @sizeof(T));
alloc.dealloc(base.data as *any, old_layout);
}
base.data = p as *T;
base.cap = new_cap;
}
};
}
pub comptime fn Vec(T: type, A: Allocator): type {
ret struct {
base: @RawVec(T),
alloc: A,
pub fn empty(alloc: A): @self {
ret .{ .base = @RawVec(T).empty(), .alloc = alloc };
}
pub fn with_capacity(alloc: A, n: usize): @Result(@self, AllocError) {
@assert(@sizeof(T) > 0, "zero-size element unsupported");
var v: @self = .{ .base = @RawVec(T).empty(), .alloc = alloc };
if n == 0 {
ret .Ok(v);
}
try @Grow(T, A).reserve(&v.base, v.alloc, n);
ret .Ok(v);
}
pub fn len(@Self self: *@self): usize {
ret self.base.len();
}
pub fn capacity(@Self self: *@self): usize {
ret self.base.capacity();
}
pub fn as_slice(@Self self: *@self): []T {
ret self.base.as_slice();
}
pub fn get(@Self self: *@self, i: usize): @Option(T) {
ret self.base.get(i);
}
pub fn at(@Self self: *@self, i: usize): @Option(*T) {
ret self.base.at(i);
}
pub fn set(@Self self: *@self, i: usize, v: T): bool {
ret @RawVec(T).set(&self.base, i, v);
}
pub fn reserve(@Self self: *@self, additional: usize): @Result((), AllocError){
try @Grow(T, A).reserve(&self.base, self.alloc, additional);
}
pub fn push(@Self self: *@self, v: T): @Result((), AllocError) {
if self.base.len() + 1 > self.base.cap {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).push_unchecked(&self.base, v);
ret .Ok(());
}
pub fn pop(@Self self: *@self): @Option(T) {
if self.base.len() == 0 {
ret .None;
}
ret .Some(@RawVec(T).pop_unchecked(&self.base));
}
pub fn append(@Self self: *@self, items: []T): @Result((), AllocError) {
var count = items.len();
if count == 0 {
ret .Ok(());
}
var offset: usize = 0;
var inside = false;
if self.base.len() != 0 {
var base_addr = self.base.data as usize;
var src_addr = items.as_ptr() as usize;
if src_addr >= base_addr && src_addr - base_addr < self.base.len() * @sizeof(T) {
offset = src_addr - base_addr;
inside = true;
}
}
if self.base.len() + count > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, count);
}
var src = items.as_ptr();
if inside {
src = ((self.base.data as *u8) + offset) as *T;
}
var i: usize = 0;
while i < count {
@RawVec(T).push_unchecked(&self.base, src[i]);
i = i + 1;
}
ret .Ok(());
}
pub fn insert(@Self self: *@self, i: usize, v: T): @Result((), AllocError) {
@assert(i <= self.base.len(), "insert out of range");
if self.base.len() + 1 > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).insert_unchecked(&self.base, i, v);
ret .Ok(());
}
pub fn remove(@Self self: *@self, i: usize): @Option(T) {
if (i < self.base.len()) {
ret .None;
}
var res = @RawVec(T).remove_unchecked(&self.base, i);
ret .Some(res);
}
pub fn clear(@Self self: *@self): void {
@RawVec(T).clear(&self.base);
}
pub fn truncate(@Self self: *@self, n: usize): bool {
if (n >= self.base.len()) { ret false }
@RawVec(T).truncate(&self.base, n);
ret true;
}
pub fn _set_len(@Self self: *@self, n: usize): bool {
if (n >= self.base.capacity()) { ret false; }
self.base.length = n;
ret true;
}
pub fn drop(@Self self: *@self) {
if self.base.capacity() != 0 {
self.alloc.dealloc(self.base.data as *u8,
layout_of(@sizeof(T), @alignof(T), self.base.capacity()));
}
@RawVec(T).reset(&self.base);
}
pub fn take(@Self self: *@self): @self {
var r = self.*;
@RawVec(T).reset(&self.base);
ret r;
}
};
}
+69
View File
@@ -0,0 +1,69 @@
type .{ .VMWriter, .VMFile, .strlen, .VMAllocator } = @import("compiler/vm.spl");
type .{ .Vec } = @import("core/vec.spl");
type .{ .Source, .SourceError } = @import("lexer/source.spl");
fn spl_main(args: const[] const[] u8): i32 {
var alloc = VMAllocator{};
var writer = VMFile.with_stdout();
// var writer = VMFile.open("output.txt", .Write) catch .Err(_) {
// @assert(false, "Failed to open output.txt for writing");
// };
for arg in args {
writer.write(arg);
writer.write("\n");
}
var vmfile = VMFile{};
var source = @Source(VMAllocator, VMFile).new(alloc, vmfile);
var ft = source.add_file("./src/test.spl") catch .Err(e) {
match e {
.UnknownError => { @assert(false, "unknow error"); },
.FileOpenError => { @assert(false, "fopen error"); },
.FileAttributeError => { @assert(false, "fattr error"); },
.FileReadError => { @assert(false, "fread error"); },
.OutOfMemory => { @assert(false, "oom error"); } ,
_ => { @assert(false, "error"); },
}
ret 1;
};
}
fn main(argc: i32, _argv: const **u8, envp: const **u8): i32 {
// for i in 0..argc {
// var arg = _argv[i];
// var j: usize = 0;
// while (arg[j] != 0) {
// vm_putchar(arg[j] as i32);
// j = j + 1;
// }
// vm_putchar('\n' as i32);
// }
// var writer = VMWriter.with_stdout();
// // var res = writer.write("Hello, World!\n");
// var argv: []const *u8 = @Slice(const *u8).from_raw_parts(_argv as **u8, argc as usize) as []const *u8;
// for arg in argv {
// // var j: usize = 0;
// // while (arg[j] != 0) {
// // vm_putchar(arg[j] as i32);
// // j = j + 1;
// // }
// // vm_putchar('\n' as i32);
// writer.write(@Slice(const u8).from_raw_parts(arg, strlen(arg)));
// writer.write("\n");
// }
var alloc = VMAllocator{};
var argv: @Vec([]u8, VMAllocator) = @Vec([]u8, VMAllocator)
.with_capacity(alloc, argc as usize)
catch .Err(_) { ret 1; };
for arg in @Slice(*u8).from_raw_parts(_argv as **u8, argc as usize) {
var len = strlen(arg);
var arg_slice = @Slice(u8).from_raw_parts(arg, len);
argv.push(arg_slice) catch .Err(_) { ret 1; };
}
ret spl_main(argv.as_slice());
}