diff --git a/src/cgen.zig b/src/cgen.zig index dc1093baa..2ca075721 100644 --- a/src/cgen.zig +++ b/src/cgen.zig @@ -61,7 +61,7 @@ const Compiler = struct { var new_name: []const u8 = undefined; const res = try c.c_names.getOrPut(c.alloc, sym_name); if (res.found_existing) { - new_name = try std.fmt.allocPrint(c.alloc, "{s}_{}", .{name_n, res.value_ptr.*}); + new_name = try std.fmt.allocPrint(c.alloc, "{s}_{}", .{ name_n, res.value_ptr.* }); res.value_ptr.* += 1; } else { new_name = try std.fmt.allocPrint(c.alloc, "{s}_0", .{name_n}); @@ -82,12 +82,12 @@ fn normalizeSymName(buf: []u8, name: []const u8) ![]const u8 { // Normalize to C name. var fbuf = std.io.fixedBufferStream(buf); const w = fbuf.writer(); - try w.print("{s}{s}", .{name[0..idx], normalizeChar(name[idx])}); + try w.print("{s}{s}", .{ name[0..idx], normalizeChar(name[idx]) }); - var rest = name[idx+1..]; + var rest = name[idx + 1 ..]; while (std.mem.indexOfAny(u8, rest, ReplaceChars)) |idx2| { - try w.print("{s}{s}", .{rest[0..idx2], normalizeChar(rest[idx2])}); - rest = rest[idx2+1..]; + try w.print("{s}{s}", .{ rest[0..idx2], normalizeChar(rest[idx2]) }); + rest = rest[idx2 + 1 ..]; } try w.writeAll(rest); return fbuf.getWritten(); @@ -191,7 +191,7 @@ const Chunk = struct { } fn proc(c: *Chunk) *Proc { - return &c.procs.items[c.procs.items.len-1]; + return &c.procs.items[c.procs.items.len - 1]; } fn pushProc(c: *Chunk, b: Proc) !void { @@ -222,7 +222,7 @@ const Chunk = struct { var col: u32 = undefined; var lineStart: u32 = undefined; c.ast.computeLinePos(node.pos(), &line, &col, &lineStart); - try c.pushSpanFmtEnd("#line {} \"{s}\"", .{line, c.srcUri}); + try c.pushSpanFmtEnd("#line {} \"{s}\"", .{ line, c.srcUri }); } try c.pushIndent(); } @@ -330,7 +330,7 @@ const Chunk = struct { rt.errZFmt(c.sema.compiler.vm, "Unsupported sym type: {}\n", .{id}); return error.TODO; } - } + }, }; } @@ -341,7 +341,7 @@ const Chunk = struct { const type_e = c.sema.types.items[id]; if (type_e.kind == .object) { const c_name = c.cSymName(type_e.sym); - try c.bufPushFmt("BOX_OBJ({s}, ", .{ c_name }); + try c.bufPushFmt("BOX_OBJ({s}, ", .{c_name}); } else { const name = c.sema.getTypeBaseName(id); return c.base.reportErrorFmt("Unsupported box macro: {}", &.{v(name)}, null); @@ -441,8 +441,7 @@ const Cstr = struct { } }; -const Value = struct { -}; +const Value = struct {}; pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { var compiler = Compiler{ @@ -477,8 +476,7 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { else => {}, } }, - .hostobj_t, - .object_t => { + .hostobj_t, .object_t => { try compiler.genSymName(sym, sym.name()); }, else => {}, @@ -544,7 +542,7 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { } for (self.chunks.items, 0..) |chunk, i| { - log.tracev("Perform codegen for chunk{}: {s}", .{chunk.id, chunk.srcUri}); + log.tracev("Perform codegen for chunk{}: {s}", .{ chunk.id, chunk.srcUri }); try genChunk(&chunks[i]); log.tracev("Done. performChunkCodegen {s}", .{chunk.srcUri}); } @@ -585,7 +583,7 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { } else { exePath = try std.fmt.allocPrintZ(self.alloc, "out/{s}", .{stemName}); } - errdefer self.alloc.free(exePath); + errdefer self.alloc.free(exePath); if (self.config.backend == cc.BackendTCC) { // const src = try std.fs.cwd().readFileAllocOptions(self.alloc, outPath, 1e9, null, @alignOf(u8), 0); @@ -621,7 +619,7 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { // } if (tcc.tcc_add_file(state, outPath.ptr) == -1) { - // if (tcc.tcc_compile_string(state, src.ptr) == -1) { + // if (tcc.tcc_compile_string(state, src.ptr) == -1) { return error.TCCError; } @@ -640,9 +638,9 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult { return error.TCCError; } } else { - const res = try std.ChildProcess.run(.{ + const res = try std.process.Child.run(.{ .allocator = self.alloc, - .argv = &.{"clang", "-o", exePath, outPath, "zig-out/lib/librt.a"}, + .argv = &.{ "clang", "-o", exePath, outPath, "zig-out/lib/librt.a" }, }); defer self.alloc.free(res.stderr); defer self.alloc.free(res.stdout); @@ -723,7 +721,7 @@ fn genHead(c: *Compiler, w: std.ArrayListUnmanaged(u8).Writer, chunks: []Chunk) const params = base.sema.getFuncSig(func.funcSigId).params(); if (params.len > 0) { for (params) |param| { - try w.print(", {}", .{ try chunk.cTypeName(param.type) }); + try w.print(", {}", .{try chunk.cTypeName(param.type)}); } } try w.writeAll(");\n"); @@ -735,7 +733,7 @@ fn genHead(c: *Compiler, w: std.ArrayListUnmanaged(u8).Writer, chunks: []Chunk) const params = funcSig.params(); if (params.len > 0) { for (params) |param| { - try w.print(", {}", .{ try chunk.cTypeName(param.type) }); + try w.print(", {}", .{try chunk.cTypeName(param.type)}); } } try w.writeAll(");\n"); @@ -754,20 +752,19 @@ fn genObjectDecl(c: *Chunk, sym: *cy.Sym, w: std.ArrayListUnmanaged(u8).Writer) const object_t = sym.cast(.object_t); for (object_t.getFields()) |field| { - if (field.sym.head.type == .struct_t) { - } else if (field.sym.head.type == .object_t) { + if (field.sym.head.type == .struct_t) {} else if (field.sym.head.type == .object_t) { try genObjectDecl(c, @ptrCast(field.sym), w); } } const c_name = c.cSymName(sym); - try w.print("typedef struct {s} {{\n", .{ c_name }); + try w.print("typedef struct {s} {{\n", .{c_name}); for (object_t.getFields()) |field| { try w.print(" {} {s};\n", .{ try c.cTypeName(field.type), field.sym.head.name(), }); } - try w.print("}} {s};\n", .{ c_name }); + try w.print("}} {s};\n", .{c_name}); const name = try cStringLit(c, sym.name()); try w.print( @@ -778,7 +775,8 @@ fn genObjectDecl(c: *Chunk, sym: *cy.Sym, w: std.ArrayListUnmanaged(u8).Writer) \\ .kind = CbTypeObject, \\}}; \\ - , .{ c_name, name }, + , + .{ c_name, name }, ); try w.print( \\{s}* new{s}(CbRT* rt, {s} init) {{ @@ -793,7 +791,8 @@ fn genObjectDecl(c: *Chunk, sym: *cy.Sym, w: std.ArrayListUnmanaged(u8).Writer) \\}} \\ \\ - , .{ c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name }, + , + .{ c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name, c_name }, ); } @@ -823,40 +822,42 @@ fn genStmts(c: *Chunk, idx: u32) !void { fn genStmt(c: *Chunk, loc: u32) anyerror!void { const code = c.ir.getStmtCode(loc); const node = c.ir.getNode(loc); - errdefer if (c.errNode == null) { c.errNode = node; }; + errdefer if (c.errNode == null) { + c.errNode = node; + }; if (cy.Trace) { const contextStr = try c.encoder.format(node, &cy.tempBuf); - log.tracev("----{s}: {{{s}}}", .{@tagName(code), contextStr}); + log.tracev("----{s}: {{{s}}}", .{ @tagName(code), contextStr }); } switch (code) { - .breakStmt => try breakStmt(c, node), + .breakStmt => try breakStmt(c, node), // .contStmt => try contStmt(c, node), - .declareLocal => try declareLocal(c, loc, node), - .declareLocalInit => try declareLocalInit(c, loc, node), + .declareLocal => try declareLocal(c, loc, node), + .declareLocalInit => try declareLocalInit(c, loc, node), // .destrElemsStmt => try destrElemsStmt(c, idx, node), - .exprStmt => try exprStmt(c, loc, node), + .exprStmt => try exprStmt(c, loc, node), // .forIterStmt => try forIterStmt(c, idx, node), - .forRangeStmt => try forRangeStmt(c, loc, node), - .funcBlock => try funcBlock(c, loc, node), - .ifStmt => try ifStmt(c, loc, node), - .loopStmt => try loopStmt(c, loc, node), - .mainBlock => try mainBlock(c, loc, node), - .opSet => try opSet(c, loc, node), + .forRangeStmt => try forRangeStmt(c, loc, node), + .funcBlock => try funcBlock(c, loc, node), + .ifStmt => try ifStmt(c, loc, node), + .loopStmt => try loopStmt(c, loc, node), + .mainBlock => try mainBlock(c, loc, node), + .opSet => try opSet(c, loc, node), // .pushDebugLabel => try pushDebugLabel(c, idx), - .retExprStmt => try retExprStmt(c, loc, node), + .retExprStmt => try retExprStmt(c, loc, node), // .retStmt => try retStmt(c), // .setCaptured => try setCaptured(c, idx, node), - .set_field => try setField(c, loc, node), + .set_field => try setField(c, loc, node), // .setFuncSym => try setFuncSym(c, idx, node), - .setIndex => try setIndex(c, loc, node), - .setLocal => try setLocal(c, loc, node), + .setIndex => try setIndex(c, loc, node), + .setLocal => try setLocal(c, loc, node), // .setObjectField => try setObjectField(c, idx, .{}, node), // .setVarSym => try setVarSym(c, idx, node), // .setLocalType => try setLocalType(c, idx), // .switchStmt => try switchStmt(c, idx, node), // .tryStmt => try tryStmt(c, idx, node), - .verbose => { + .verbose => { if (cy.Trace and !cc.verbose()) { cc.setVerbose(true); c.proc().resetVerboseOnEnd = true; @@ -864,7 +865,7 @@ fn genStmt(c: *Chunk, loc: u32) anyerror!void { }, else => { return error.TODO; - } + }, } log.tracev("----{s}: end", .{@tagName(code)}); @@ -889,11 +890,11 @@ fn genExpr(c: *Chunk, loc: usize, cstr: Cstr) anyerror!Value { if (cy.Trace) { const contextStr = try c.encoder.format(node, &cy.tempBuf); - log.tracev("{s}: {{{s}}}", .{@tagName(code), contextStr}); + log.tracev("{s}: {{{s}}}", .{ @tagName(code), contextStr }); } const res = try switch (code) { - .box => genBox(c, loc, cstr, node), + .box => genBox(c, loc, cstr, node), // .captured => genCaptured(c, idx, cstr, node), // .cast => genCast(c, idx, cstr, node), // .coinitCall => genCoinitCall(c, idx, cstr, node), @@ -903,26 +904,26 @@ fn genExpr(c: *Chunk, loc: usize, cstr: Cstr) anyerror!Value { // .errorv => genError(c, idx, cstr, node), // .falsev => genFalse(c, cstr, node), // .fieldDynamic => genFieldDynamic(c, idx, cstr, .{}, node), - .field => genField(c, loc, cstr, node), + .field => genField(c, loc, cstr, node), // .float => genFloat(c, idx, cstr, node), // .funcSym => genFuncSym(c, idx, cstr, node), // .ifExpr => genIfExpr(c, idx, cstr, node), - .int => genInt(c, loc, cstr, node), + .int => genInt(c, loc, cstr, node), // .lambda => genLambda(c, idx, cstr, node), // .list => genList(c, idx, cstr, node), - .local => genLocal(c, loc, cstr, node), + .local => genLocal(c, loc, cstr, node), // .map => genMap(c, idx, cstr, node), - .object_init => genObjectInit(c, loc, cstr, node), + .object_init => genObjectInit(c, loc, cstr, node), // .pre => return error.Unexpected, - .preBinOp => genBinOp(c, loc, cstr, .{}, node), - .call_dyn => genCallDyn(c, loc, cstr, node), - .call_sym => genCallFuncSym(c, loc, cstr, node), + .preBinOp => genBinOp(c, loc, cstr, .{}, node), + .call_dyn => genCallDyn(c, loc, cstr, node), + .call_sym => genCallFuncSym(c, loc, cstr, node), // .preCallObjSym => genCallObjSym(c, idx, cstr, node), // .preUnOp => genUnOp(c, idx, cstr, node), - .string => genString(c, loc, cstr, node), + .string => genString(c, loc, cstr, node), // .stringTemplate => genStringTemplate(c, idx, cstr, node), // .switchBlock => genSwitchBlock(c, idx, cstr, node), - .symbol => genSymbol(c, loc, cstr, node), + .symbol => genSymbol(c, loc, cstr, node), // .throw => genThrow(c, idx, node), // .truev => genTrue(c, cstr, node), // .tryExpr => genTryExpr(c, idx, cstr, node), @@ -963,7 +964,7 @@ fn mainBlock(c: *Chunk, loc: usize, node: *ast.Node) !void { } // if (bcgen.shouldGenMainScopeReleaseOps(c.compiler)) { - // try genBlockReleaseLocals(c); + // try genBlockReleaseLocals(c); // } try c.pushLineNoMapping("return 0;"); @@ -985,7 +986,7 @@ fn declareLocalInit(c: *Chunk, idx: u32, node: *ast.Node) !void { reserveLocal(c, data.id, data.name(), data.declType, data.lifted); const start = c.bufStart(); - try c.bufPushFmt("{} {s} = ", .{try c.cTypeName(data.declType), data.name()}); + try c.bufPushFmt("{} {s} = ", .{ try c.cTypeName(data.declType), data.name() }); const val = try genExpr(c, data.init, Cstr.init()); _ = val; @@ -1137,7 +1138,7 @@ fn genSymbol(c: *Chunk, loc: usize, cstr: Cstr, node: *ast.Node) !Value { _ = cstr; _ = node; const data = c.ir.getExprData(loc, .symbol); - try c.bufPushFmt("CB_SYM(\"{s}\", {})", .{data.name, data.name.len}); + try c.bufPushFmt("CB_SYM(\"{s}\", {})", .{ data.name, data.name.len }); return Value{}; } @@ -1166,12 +1167,12 @@ fn reserveLocal(c: *Chunk, ir_id: u8, name: []const u8, declType: cy.TypeId, lif .rcCandidate = c.sema.isRcCandidateType(declType), .lifted = lifted, .type = declType, - }}; + } }; } fn setLocal(c: *Chunk, loc: usize, node: *ast.Node) !void { const data = c.ir.getStmtData(loc, .setLocal).generic; - const local_loc = c.ir.advanceStmt(loc, .setLocal); + const local_loc = c.ir.advanceStmt(loc, .setLocal); const local_data = c.ir.getExprData(local_loc, .local); const start = c.bufStart(); @@ -1466,7 +1467,7 @@ fn funcBlock(c: *Chunk, loc: usize, node: *ast.Node) !void { try c.pushSpanFmt("{} {s}(CbRT* rt", .{ try c.cTypeName(func.retType), c.cSymName(func) }); if (params.len > 0) { for (params) |param| { - try c.pushSpanFmt(", {} {s}", .{ try c.cTypeName(param.declType), param.name()}); + try c.pushSpanFmt(", {} {s}", .{ try c.cTypeName(param.declType), param.name() }); } } try c.pushSpanEnd(") {"); @@ -1651,7 +1652,7 @@ const BinOpOptions = struct { fn genBinOp(c: *Chunk, loc: usize, cstr: Cstr, opts: BinOpOptions, node: *ast.Node) !Value { _ = cstr; const data = c.ir.getExprData(loc, .preBinOp).binOp; - log.tracev("binop {} {}", .{data.op, data.leftT}); + log.tracev("binop {} {}", .{ data.op, data.leftT }); if (data.op == .and_op) { return error.TODO; @@ -1696,33 +1697,20 @@ fn genBinOp(c: *Chunk, loc: usize, cstr: Cstr, opts: BinOpOptions, node: *ast.No .index => { if (data.leftT == bt.ListDyn) { try c.bufPush(", "); - // } else if (data.leftT == bt.Tuple) { - // try pushInlineBinExpr(c, .indexTuple, leftv.local, rightv.local, inst.dst, node); - // } else if (data.leftT == bt.Map) { - // try pushInlineBinExpr(c, .indexMap, leftv.local, rightv.local, inst.dst, node); + // } else if (data.leftT == bt.Tuple) { + // try pushInlineBinExpr(c, .indexTuple, leftv.local, rightv.local, inst.dst, node); + // } else if (data.leftT == bt.Map) { + // try pushInlineBinExpr(c, .indexMap, leftv.local, rightv.local, inst.dst, node); } else return error.TODO; retained = true; }, - .bitwiseAnd, - .bitwiseOr, - .bitwiseXor, - .bitwiseLeftShift, - .bitwiseRightShift => { + .bitwiseAnd, .bitwiseOr, .bitwiseXor, .bitwiseLeftShift, .bitwiseRightShift => { // if (data.leftT == bt.Integer) { // try pushInlineBinExpr(c, getIntOpCode(data.op), leftv.local, rightv.local, inst.dst, node); // } else return error.Unexpected; return error.TODO; }, - .greater, - .greater_equal, - .less, - .less_equal, - .star, - .slash, - .percent, - .caret, - .plus, - .minus => { + .greater, .greater_equal, .less, .less_equal, .star, .slash, .percent, .caret, .plus, .minus => { if (data.leftT == bt.Float) { if (data.rightT == bt.Float) { try c.bufPush(cBinOpLit(data.op)); @@ -1840,16 +1828,16 @@ pub fn cStringLit(self: *Chunk, raw: []const u8) ![]const u8 { if (std.mem.indexOfAny(u8, raw, ReplaceChars)) |idx| { var fbuf = std.io.fixedBufferStream(self.base.tempBufU8.items[0..]); const w = fbuf.writer(); - try w.print("{s}{s}", .{raw[0..idx], S.replacement(raw[idx])}); + try w.print("{s}{s}", .{ raw[0..idx], S.replacement(raw[idx]) }); - var rest = raw[idx+1..]; + var rest = raw[idx + 1 ..]; while (std.mem.indexOfAny(u8, rest, ReplaceChars)) |idx2| { - try w.print("{s}{s}", .{rest[0..idx2], S.replacement(rest[idx2])}); - rest = rest[idx2+1..]; + try w.print("{s}{s}", .{ rest[0..idx2], S.replacement(rest[idx2]) }); + rest = rest[idx2 + 1 ..]; } try w.writeAll(rest); return fbuf.getWritten(); } else { return raw; } -} \ No newline at end of file +} diff --git a/src/cli.zig b/src/cli.zig index b77d95931..e168913f0 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -11,7 +11,7 @@ const v = cy.fmt.v; const log = cy.log.scoped(.cli); const rt = cy.rt; -const builtins = std.ComptimeStringMap(void, .{ +const builtins = std.StaticStringMap(void).initComptime(.{ .{"core"}, .{"math"}, .{"cy"}, @@ -21,7 +21,7 @@ const Src = @embedFile("std/cli.cy"); const func = cy.hostFuncEntry; const funcs = [_]C.HostFuncEntry{ - func("replReadLine", zErrFunc(replReadLine)), + func("replReadLine", zErrFunc(replReadLine)), }; pub fn create(vm: *cy.VM, r_uri: []const u8) C.Module { @@ -33,10 +33,10 @@ pub fn create(vm: *cy.VM, r_uri: []const u8) C.Module { return mod; } -const stdMods = std.ComptimeStringMap(*const fn(*cy.VM, r_uri: []const u8) C.Module, .{ - .{"cli", create}, - .{"os", os_mod.create}, - .{"test", test_mod.create}, +const stdMods = std.StaticStringMap(*const fn (*cy.VM, r_uri: []const u8) C.Module).initComptime(.{ + .{ "cli", create }, + .{ "os", os_mod.create }, + .{ "test", test_mod.create }, }); pub const CliData = struct { @@ -136,7 +136,7 @@ pub fn loader(vm_: ?*C.VM, spec_: C.Str, res: ?*C.Module) callconv(.C) bool { if (e == error.HandledError) { return false; } else { - const msg = cy.fmt.allocFormat(alloc, "Can not load `{}`. {}", &.{v(spec), v(e)}) catch return false; + const msg = cy.fmt.allocFormat(alloc, "Can not load `{}`. {}", &.{ v(spec), v(e) }) catch return false; defer alloc.free(msg); C.reportApiError(@ptrCast(vm), C.toStr(msg)); return false; @@ -144,7 +144,7 @@ pub fn loader(vm_: ?*C.VM, spec_: C.Str, res: ?*C.Module) callconv(.C) bool { }; } else { src = std.fs.cwd().readFileAlloc(alloc, spec, 1e10) catch |e| { - const msg = cy.fmt.allocFormat(alloc, "Can not load `{}`. {}", &.{v(spec), v(e)}) catch return false; + const msg = cy.fmt.allocFormat(alloc, "Can not load `{}`. {}", &.{ v(spec), v(e) }) catch return false; defer alloc.free(msg); C.reportApiError(@ptrCast(vm), C.toStr(msg)); return false; @@ -185,7 +185,7 @@ fn resolve(vm_: ?*C.VM, params: C.ResolverParams) callconv(.C) bool { if (e == error.HandledError) { return false; } else { - const msg = cy.fmt.allocFormat(alloc, "Resolve module `{}`, error: `{}`", &.{v(uri), v(e)}) catch return false; + const msg = cy.fmt.allocFormat(alloc, "Resolve module `{}`, error: `{}`", &.{ v(uri), v(e) }) catch return false; defer alloc.free(msg); C.reportApiError(@ptrCast(vm), C.toStr(msg)); return false; @@ -202,7 +202,7 @@ fn zResolve(vm: *cy.VM, alloc: std.mem.Allocator, chunkId: cy.ChunkId, buf: []u8 if (std.mem.startsWith(u8, spec, "http://") or std.mem.startsWith(u8, spec, "https://")) { const uri = try std.Uri.parse(spec); if (std.mem.endsWith(u8, uri.host.?.percent_encoded, "github.com")) { - if (std.mem.count(u8, uri.path.percent_encoded, "/") == 2 and uri.path.percent_encoded[uri.path.percent_encoded.len-1] != '/') { + if (std.mem.count(u8, uri.path.percent_encoded, "/") == 2 and uri.path.percent_encoded[uri.path.percent_encoded.len - 1] != '/') { var fbuf = std.io.fixedBufferStream(buf); const w = fbuf.writer(); @@ -227,7 +227,7 @@ fn zResolve(vm: *cy.VM, alloc: std.mem.Allocator, chunkId: cy.ChunkId, buf: []u8 _ = try fbuf.write(spec); break :b; }; - try fbuf.writer().print("{s}/{s}", .{dir, spec}); + try fbuf.writer().print("{s}/{s}", .{ dir, spec }); } else { _ = try fbuf.write(spec); } @@ -274,7 +274,7 @@ fn loadUrl(vm: *cy.VM, alloc: std.mem.Allocator, url: []const u8) ![]const u8 { if (C.verbose()) { const cachePath = try cache.allocSpecFilePath(alloc, entry); defer alloc.free(cachePath); - rt.logZFmt("Using cached `{s}` at `{s}`", .{url, cachePath}); + rt.logZFmt("Using cached `{s}` at `{s}`", .{ url, cachePath }); } return src; } @@ -302,7 +302,7 @@ fn loadUrl(vm: *cy.VM, alloc: std.mem.Allocator, url: []const u8) ![]const u8 { if (res.status != .ok) { // Stop immediately. - const e = try cy.fmt.allocFormat(alloc, "Can not load `{}`. Response code: {}", &.{v(url), v(res.status)}); + const e = try cy.fmt.allocFormat(alloc, "Can not load `{}`. Response code: {}", &.{ v(url), v(res.status) }); defer alloc.free(e); C.reportApiError(@ptrCast(vm), C.toStr(e)); return error.HandledError; @@ -365,4 +365,4 @@ pub const FallbackReadLine = struct { const self: *@This() = @ptrCast(@alignCast(ptr)); self.alloc.free(line); } -}; \ No newline at end of file +}; diff --git a/src/parser.zig b/src/parser.zig index 29dfe9d3a..2cebce7dd 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -16,7 +16,7 @@ const IndexSlice = cy.IndexSlice(u32); const dumpParseErrorStackTrace = !cy.isFreestanding and builtin.mode == .Debug and !cy.isWasm and true; -const attributes = std.ComptimeStringMap(cy.ast.AttributeType, .{ +const attributes = std.StaticStringMap(cy.ast.AttributeType).initComptime(.{ .{ "host", .host }, }); @@ -56,8 +56,8 @@ pub const Parser = struct { /// Variable dependencies. deps: std.StringHashMapUnmanaged(*ast.Node), - reportFn: *const fn(*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror, - tokenizerReportFn: *const fn(*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror!void, + reportFn: *const fn (*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror, + tokenizerReportFn: *const fn (*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror!void, ctx: *anyopaque, has_error: bool, @@ -192,7 +192,7 @@ pub const Parser = struct { const stmts = try self.parseBodyStatements(0, .{ .allow_decls = true }); // Mark last expression stmt. - const last = stmts[stmts.len-1]; + const last = stmts[stmts.len - 1]; if (last.type() == .exprStmt) { last.cast(.exprStmt).isLastRootStmt = true; } @@ -387,7 +387,7 @@ pub const Parser = struct { const start = self.next_pos; // Assumes first token is `=>`. self.advance(); - + // Parse body expr. try self.pushBlock(); const expr = (try self.parseExpr(.{})) orelse { @@ -408,7 +408,7 @@ pub const Parser = struct { const start = self.next_pos; // Assumes first token is `:`. self.advance(); - + try self.pushBlock(); const stmts = try self.parseSingleOrIndentedBodyStmts(); _ = self.popBlock(); @@ -613,16 +613,7 @@ pub const Parser = struct { const start = self.next_pos; var token = self.peek(); switch (token.tag()) { - .dyn_k, - .void_k, - .struct_k, - .enum_k, - .type_k, - .error_k, - .symbol_k, - .none_k, - .Func_k, - .ident => { + .dyn_k, .void_k, .struct_k, .enum_k, .type_k, .error_k, .symbol_k, .none_k, .Func_k, .ident => { self.advance(); return @ptrCast(try self.newSpanNode(.ident, start)); }, @@ -650,7 +641,7 @@ pub const Parser = struct { const name_start = self.node_stack.items.len; defer self.node_stack.items.len = name_start; try self.pushNode(name); - + while (self.peek().tag() == .dot) { self.advance(); name = (try self.parseOptName()) orelse { @@ -767,10 +758,7 @@ pub const Parser = struct { decl = @ptrCast(try self.parseTraitDecl(start, name, config)); }, // `object` is optional. - .left_paren, - .object_k, - .new_line, - .colon => { + .left_paren, .object_k, .new_line, .colon => { decl = @ptrCast(try self.parseObjectDecl(start, name, config)); }, .minus_right_angle => { @@ -781,7 +769,7 @@ pub const Parser = struct { }, else => { decl = @ptrCast(try self.parseDistinctTypeDecl(start, name, config)); - } + }, } if (opt_template) |template| { @@ -809,20 +797,7 @@ pub const Parser = struct { return self.reportError("Unnamed type is not allowed in this context.", &.{}); } }, - .left_paren, - .left_bracket, - .star, - .question, - .ampersand, - .pound, - .dyn_k, - .void_k, - .type_k, - .symbol_k, - .func_k, - .Func_k, - .error_k, - .ident => { + .left_paren, .left_bracket, .star, .question, .ampersand, .pound, .dyn_k, .void_k, .type_k, .symbol_k, .func_k, .Func_k, .error_k, .ident => { return try self.parseTermExpr(.{}); }, else => { @@ -938,10 +913,7 @@ pub const Parser = struct { }); } - fn newObjectDecl(self: *Parser, start: TokenId, node_t: ast.NodeType, opt_name: ?*ast.Node, - config: TypeDeclConfig, impl_withs: []*ast.ImplWith, fields: []*ast.Field, funcs: []*ast.FuncDecl, - is_tuple: bool) !*ast.ObjectDecl { - + fn newObjectDecl(self: *Parser, start: TokenId, node_t: ast.NodeType, opt_name: ?*ast.Node, config: TypeDeclConfig, impl_withs: []*ast.ImplWith, fields: []*ast.Field, funcs: []*ast.FuncDecl, is_tuple: bool) !*ast.ObjectDecl { const n = try self.ast.newNodeErase(.objectDecl, .{ .name = opt_name, .pos = self.tokenSrcPos(start), @@ -1566,8 +1538,7 @@ pub const Parser = struct { spec = @ptrCast(try self.newSpanNode(.raw_string_lit, self.next_pos)); self.advance(); }, - .new_line => { - }, + .new_line => {}, .null => {}, .minus_right_angle => { self.advance(); @@ -1793,7 +1764,7 @@ pub const Parser = struct { // try self.pushBlock(); // const res = try self.parseIndentedBodyStatements(); // _ = self.popBlock(); - + // const id = try self.pushNode(.label_decl, start); // self.nodes.items[id].head = .{ // .left_right = .{ @@ -1916,7 +1887,7 @@ pub const Parser = struct { return self.parseAtDecl(config.allow_decls); }, .def_k => { - return self.parseDefDecl(.{ .attrs = &.{}, .hidden = false, .allow_decl = config.allow_decls}); + return self.parseDefDecl(.{ .attrs = &.{}, .hidden = false, .allow_decl = config.allow_decls }); }, .pound => { self.advance(); @@ -1978,7 +1949,7 @@ pub const Parser = struct { }); }, .func_k => { - return self.parseFuncDecl(.{ .attrs = &.{}, .hidden = false, .allow_decl = config.allow_decls}); + return self.parseFuncDecl(.{ .attrs = &.{}, .hidden = false, .allow_decl = config.allow_decls }); }, .if_k => { return try self.parseIfStatement(); @@ -2077,8 +2048,7 @@ pub const Parser = struct { var token = self.peek(); while (token.tag() != .null) { switch (token.tag()) { - .new_line, - .indent => { + .new_line, .indent => { self.advance(); token = self.peek(); continue; @@ -2131,7 +2101,7 @@ pub const Parser = struct { if (self.peek().tag() == .func_k) { return self.parseFuncDecl(.{ .hidden = hidden, .attrs = attrs, .allow_decl = allow_decls }); } else if (self.peek().tag() == .def_k) { - return self.parseDefDecl(.{ .attrs = attrs, .hidden = hidden, .allow_decl = allow_decls}); + return self.parseDefDecl(.{ .attrs = attrs, .hidden = hidden, .allow_decl = allow_decls }); } else if (self.peek().tag() == .var_k) { return try self.parseVarDecl(.{ .hidden = hidden, .attrs = attrs, .typed = true, .allow_static = allow_decls }); } else if (self.peek().tag() == .dyn_k) { @@ -2377,7 +2347,7 @@ pub const Parser = struct { .name_len = token.data.end_pos - token.pos(), .arg = arg, }); - } + } } return self.parseExpr(.{}); } @@ -2455,10 +2425,7 @@ pub const Parser = struct { while (true) { const token = self.peek(); switch (token.tag()) { - .right_bracket, - .right_paren, - .new_line, - .null => break, + .right_bracket, .right_paren, .new_line, .null => break, .comma => { self.advance(); arg = (try self.parseExpr(.{})) orelse { @@ -2763,49 +2730,7 @@ pub const Parser = struct { call.ct = true; left = @ptrCast(call); }, - .minus_double_dot, - .dot_dot, - .right_bracket, - .right_paren, - .right_brace, - .else_k, - .catch_k, - .comma, - .colon, - .equal, - .plus, - .minus, - .star, - .slash, - .ampersand, - .vert_bar, - .double_vert_bar, - .double_left_angle, - .double_right_angle, - .caret, - .left_angle, - .left_angle_equal, - .right_angle, - .right_angle_equal, - .percent, - .equal_equal, - .bang_equal, - .and_k, - .or_k, - .as_k, - .minus_right_angle, - .raw_string, - .string, - .bin, - .oct, - .hex, - .dec, - .float, - .if_k, - .templateString, - .equal_right_angle, - .new_line, - .null => break, + .minus_double_dot, .dot_dot, .right_bracket, .right_paren, .right_brace, .else_k, .catch_k, .comma, .colon, .equal, .plus, .minus, .star, .slash, .ampersand, .vert_bar, .double_vert_bar, .double_left_angle, .double_right_angle, .caret, .left_angle, .left_angle_equal, .right_angle, .right_angle_equal, .percent, .equal_equal, .bang_equal, .and_k, .or_k, .as_k, .minus_right_angle, .raw_string, .string, .bin, .oct, .hex, .dec, .float, .if_k, .templateString, .equal_right_angle, .new_line, .null => break, else => break, } } @@ -3104,7 +3029,7 @@ pub const Parser = struct { }, else => { return null; - } + }, } } @@ -3285,7 +3210,7 @@ pub const Parser = struct { } else if (self.peek().tag() == .comma) { self.advance(); const param = try self.genDynFuncParam(expr); - const params = try self.parseFuncParams(&.{ param }); + const params = try self.parseFuncParams(&.{param}); if (self.peek().tag() == .equal_right_angle) { return @ptrCast(try self.parseInferLambda(params)); } else if (self.peek().tag() == .colon) { @@ -3300,7 +3225,7 @@ pub const Parser = struct { .switch_k => { return @ptrCast(try self.parseSwitch(false)); }, - else => {} + else => {}, } return try self.parseTermExpr2(config); } @@ -3322,10 +3247,7 @@ pub const Parser = struct { .equal => { break; }, - .plus, - .minus, - .star, - .slash => { + .plus, .minus, .star, .slash => { if (self.peekAhead(1).tag() == .equal) { break; } @@ -3340,21 +3262,7 @@ pub const Parser = struct { .op_pos = self.tokenSrcPos(op_start), }); }, - .ampersand, - .vert_bar, - .double_vert_bar, - .double_left_angle, - .double_right_angle, - .caret, - .left_angle, - .left_angle_equal, - .right_angle, - .percent, - .equal_equal, - .bang_equal, - .and_k, - .or_k, - .right_angle_equal => { + .ampersand, .vert_bar, .double_vert_bar, .double_left_angle, .double_right_angle, .caret, .left_angle, .left_angle_equal, .right_angle, .percent, .equal_equal, .bang_equal, .and_k, .or_k, .right_angle_equal => { const bin_op = toBinExprOp(next.tag()).?; const op_start = self.next_pos; self.advance(); @@ -3417,30 +3325,21 @@ pub const Parser = struct { .default = default, }); }, - .right_bracket, - .right_paren, - .right_brace, - .else_k, - .comma, - .colon, - .minus_right_angle, - .new_line, - .null => break, + .right_bracket, .right_paren, .right_brace, .else_k, .comma, .colon, .minus_right_angle, .new_line, .null => break, else => { if (!config.parseShorthandCallExpr) { return left; } // Attempt to parse as no paren call expr. switch (left.type()) { - .accessExpr, - .ident => { + .accessExpr, .ident => { return @ptrCast(try self.parseNoParenCallExpression(left)); }, else => { return left; - } + }, } - } + }, } } return left; @@ -3597,8 +3496,7 @@ pub const Parser = struct { self.advance(); const token = self.peek(); switch (token.tag()) { - .new_line, - .null => { + .new_line, .null => { return self.ast.newNodeErase(.returnStmt, .{ .pos = self.tokenSrcPos(start) }); }, else => { @@ -3626,10 +3524,7 @@ pub const Parser = struct { self.advance(); is_assign_stmt = true; }, - .plus, - .minus, - .star, - .slash => { + .plus, .minus, .star, .slash => { // +=, -=, etc. self.advance(); self.advance(); @@ -3645,10 +3540,7 @@ pub const Parser = struct { } switch (expr.type()) { - .accessExpr, - .deref, - .array_expr, - .ident => {}, + .accessExpr, .deref, .array_expr, .ident => {}, else => { return self.reportError("Unsupported assignment left expression: {}", &.{v(expr.type())}); }, @@ -3733,7 +3625,7 @@ pub const Parser = struct { pub const Result = struct { inner: ResultView, - + pub fn init(alloc: std.mem.Allocator, view: ResultView) !Result { const arr = try view.nodes.clone(alloc); const nodes = try alloc.create(std.ArrayListUnmanaged(ast.Node)); @@ -3747,7 +3639,7 @@ pub const Result = struct { while (iter.next()) |entry| { const dep = entry.key_ptr.*; const offset = @intFromPtr(dep.ptr) - @intFromPtr(view.src.ptr); - try deps.put(alloc, new_src[offset..offset+dep.len], entry.value_ptr.*); + try deps.put(alloc, new_src[offset .. offset + dep.len], entry.value_ptr.*); } return Result{ @@ -3813,53 +3705,31 @@ fn toBinExprOp(op: cy.tokenizer.TokenType) ?cy.ast.BinaryExprOp { .equal_equal => .equal_equal, .and_k => .and_op, .or_k => .or_op, - .null, - .as_k, .at, .await_k, - .bang, .bin, .break_k, - .minus_right_angle, .case_k, .catch_k, .coinit_k, .colon, .comma, .context_k, .continue_k, .coresume_k, .coyield_k, .cstruct_k, - .dec, .def_k, .dot, .dot_bang, .dot_question, .dot_dot, .dot_star, - .else_k, .enum_k, .err, .error_k, .equal, .equal_right_angle, - .false_k, .float, .for_k, .func_k, .Func_k, - .hex, .ident, .if_k, .mod_k, .indent, - .left_brace, .left_bracket, .left_paren, .dyn_k, - .minus_double_dot, .new_line, .none_k, .not_k, .object_k, .oct, .pass_k, .underscore, .pound, .question, - .return_k, .right_brace, .right_bracket, .right_paren, .rune, .raw_string, - .string, .struct_k, .switch_k, .symbol_k, .templateExprStart, .templateString, - .throw_k, .tilde, .trait_k, .true_k, .try_k, .type_k, .use_k, .var_k, .void_k, .while_k, .with_k => null, + .null, .as_k, .at, .await_k, .bang, .bin, .break_k, .minus_right_angle, .case_k, .catch_k, .coinit_k, .colon, .comma, .context_k, .continue_k, .coresume_k, .coyield_k, .cstruct_k, .dec, .def_k, .dot, .dot_bang, .dot_question, .dot_dot, .dot_star, .else_k, .enum_k, .err, .error_k, .equal, .equal_right_angle, .false_k, .float, .for_k, .func_k, .Func_k, .hex, .ident, .if_k, .mod_k, .indent, .left_brace, .left_bracket, .left_paren, .dyn_k, .minus_double_dot, .new_line, .none_k, .not_k, .object_k, .oct, .pass_k, .underscore, .pound, .question, .return_k, .right_brace, .right_bracket, .right_paren, .rune, .raw_string, .string, .struct_k, .switch_k, .symbol_k, .templateExprStart, .templateString, .throw_k, .tilde, .trait_k, .true_k, .try_k, .type_k, .use_k, .var_k, .void_k, .while_k, .with_k => null, }; } pub fn getBinOpPrecedence(op: cy.ast.BinaryExprOp) u8 { switch (op) { - .bitwiseLeftShift, - .bitwiseRightShift => return 10, + .bitwiseLeftShift, .bitwiseRightShift => return 10, .bitwiseAnd => return 9, - .bitwiseXor, - .bitwiseOr => return 8, + .bitwiseXor, .bitwiseOr => return 8, .caret => return 7, - .slash, - .percent, - .star => { + .slash, .percent, .star => { return 6; }, - .minus, - .plus => { + .minus, .plus => { return 5; }, .cast => return 4, - .greater, - .greater_equal, - .less, - .less_equal, - .bang_equal, - .equal_equal => { + .greater, .greater_equal, .less, .less_equal, .bang_equal, .equal_equal => { return 3; }, @@ -3867,8 +3737,7 @@ pub fn getBinOpPrecedence(op: cy.ast.BinaryExprOp) u8 { .or_op => return 1, - .range, - .reverse_range => return 0, + .range, .reverse_range => return 0, else => return 0, } @@ -3910,9 +3779,9 @@ test "Parse dependency variables" { pub fn logSrcPos(src: []const u8, start: u32, len: u32) void { if (start + len > src.len) { - log.tracev("{s}", .{ src[start..] }); + log.tracev("{s}", .{src[start..]}); } else { - log.tracev("{s}", .{ src[start..start+len] }); + log.tracev("{s}", .{src[start .. start + len]}); } } @@ -3928,17 +3797,12 @@ const ParseTermConfig = struct { fn isRecordKeyNodeType(node_t: ast.NodeType) bool { switch (node_t) { - .ident, - .raw_string_lit, - .decLit, - .binLit, - .octLit, - .hexLit => { + .ident, .raw_string_lit, .decLit, .binLit, .octLit, .hexLit => { return true; }, else => { return false; - } + }, } } @@ -3948,4 +3812,4 @@ fn defaultReportFn(ctx: *anyopaque, format: []const u8, args: []const cy.fmt.Fmt _ = args; _ = pos; return error.ParseError; -} \ No newline at end of file +} diff --git a/src/std/os.zig b/src/std/os.zig index d3ecb0e8c..3ddd33932 100644 --- a/src/std/os.zig +++ b/src/std/os.zig @@ -30,72 +30,72 @@ const Src = @embedFile("os.cy"); const func = cy.hostFuncEntry; const funcs = [_]C.HostFuncEntry{ // Top level - func("access", zErrFunc(access)), - func("args", zErrFunc(osArgs)), - func("cacheUrl", zErrFunc(cacheUrl)), - func("copyFile", zErrFunc(copyFile)), - func("createDir", zErrFunc(createDir)), - func("createFile", zErrFunc(createFile)), - func("cstr", zErrFunc(cstr)), - func("cwd", zErrFunc(cwd)), - func("dirName", zErrFunc(dirName)), - func("execCmd", zErrFunc(execCmd)), - func("exePath", zErrFunc(exePath)), - func("exit", exit), - func("fetchUrl", zErrFunc(fetchUrl)), - func("free", free), - func("getEnv", zErrFunc(getEnv)), - func("getEnvAll", zErrFunc(getEnvAll)), - func("malloc", zErrFunc(malloc)), - func("milliTime", milliTime), - func("newFFI", newFFI), - func("now", zErrFunc(now)), - func("openDir", zErrFunc(openDir)), - func("openDir", zErrFunc(openDir2)), - func("openFile", zErrFunc(openFile)), - func("parseArgs", zErrFunc(parseArgs)), - func("readAll", zErrFunc(readAll)), - func("readFile", zErrFunc(readFile)), - func("readLine", zErrFunc(readLine)), - func("realPath", zErrFunc(realPath)), - func("removeDir", zErrFunc(removeDir)), - func("removeFile", zErrFunc(removeFile)), - func("setEnv", zErrFunc(setEnv)), - func("sleep", sleep), - func("unsetEnv", unsetEnv), - func("writeFile", zErrFunc(writeFile)), + func("access", zErrFunc(access)), + func("args", zErrFunc(osArgs)), + func("cacheUrl", zErrFunc(cacheUrl)), + func("copyFile", zErrFunc(copyFile)), + func("createDir", zErrFunc(createDir)), + func("createFile", zErrFunc(createFile)), + func("cstr", zErrFunc(cstr)), + func("cwd", zErrFunc(cwd)), + func("dirName", zErrFunc(dirName)), + func("execCmd", zErrFunc(execCmd)), + func("exePath", zErrFunc(exePath)), + func("exit", exit), + func("fetchUrl", zErrFunc(fetchUrl)), + func("free", free), + func("getEnv", zErrFunc(getEnv)), + func("getEnvAll", zErrFunc(getEnvAll)), + func("malloc", zErrFunc(malloc)), + func("milliTime", milliTime), + func("newFFI", newFFI), + func("now", zErrFunc(now)), + func("openDir", zErrFunc(openDir)), + func("openDir", zErrFunc(openDir2)), + func("openFile", zErrFunc(openFile)), + func("parseArgs", zErrFunc(parseArgs)), + func("readAll", zErrFunc(readAll)), + func("readFile", zErrFunc(readFile)), + func("readLine", zErrFunc(readLine)), + func("realPath", zErrFunc(realPath)), + func("removeDir", zErrFunc(removeDir)), + func("removeFile", zErrFunc(removeFile)), + func("setEnv", zErrFunc(setEnv)), + func("sleep", sleep), + func("unsetEnv", unsetEnv), + func("writeFile", zErrFunc(writeFile)), // File - func("File.close", fs.fileClose), - func("File.iterator", zErrFunc(fs.fileIterator)), - func("File.next", zErrFunc(fs.fileNext)), - func("File.read", zErrFunc(fs.fileRead)), - func("File.readAll", zErrFunc(fs.fileReadAll)), - func("File.seek", zErrFunc(fs.fileSeek)), - func("File.seekFromCur", zErrFunc(fs.fileSeekFromCur)), - func("File.seekFromEnd", zErrFunc(fs.fileSeekFromEnd)), - func("File.stat", zErrFunc(fs.fileOrDirStat)), - func("File.streamLines", zErrFunc(fs.fileStreamLines)), - func("File.streamLines2", zErrFunc(fs.fileStreamLines1)), - func("File.write", zErrFunc(fs.fileWrite)), + func("File.close", fs.fileClose), + func("File.iterator", zErrFunc(fs.fileIterator)), + func("File.next", zErrFunc(fs.fileNext)), + func("File.read", zErrFunc(fs.fileRead)), + func("File.readAll", zErrFunc(fs.fileReadAll)), + func("File.seek", zErrFunc(fs.fileSeek)), + func("File.seekFromCur", zErrFunc(fs.fileSeekFromCur)), + func("File.seekFromEnd", zErrFunc(fs.fileSeekFromEnd)), + func("File.stat", zErrFunc(fs.fileOrDirStat)), + func("File.streamLines", zErrFunc(fs.fileStreamLines)), + func("File.streamLines2", zErrFunc(fs.fileStreamLines1)), + func("File.write", zErrFunc(fs.fileWrite)), // Dir - func("Dir.iterator", fs.dirIterator), - func("Dir.stat", zErrFunc(fs.fileOrDirStat)), - func("Dir.walk", fs.dirWalk), + func("Dir.iterator", fs.dirIterator), + func("Dir.stat", zErrFunc(fs.fileOrDirStat)), + func("Dir.walk", fs.dirWalk), // DirIterator func("DirIterator.next", zErrFunc(fs.dirIteratorNext)), // FFI - func("FFI.bindCallback", zErrFunc(ffi.ffiBindCallback)), - func("FFI.bindLib", zErrFunc(bindLib)), - func("FFI.bindLib2", zErrFunc(bindLibExt)), - func("FFI.bindObjPtr", zErrFunc(ffi.ffiBindObjPtr)), - func("FFI.cbind", zErrFunc(ffi.ffiCbind)), - func("FFI.cfunc", zErrFunc(ffi.ffiCfunc)), - func("FFI.new", zErrFunc(ffi.ffiNew)), - func("FFI.unbindObjPtr", zErrFunc(ffi.ffiUnbindObjPtr)), + func("FFI.bindCallback", zErrFunc(ffi.ffiBindCallback)), + func("FFI.bindLib", zErrFunc(bindLib)), + func("FFI.bindLib2", zErrFunc(bindLibExt)), + func("FFI.bindObjPtr", zErrFunc(ffi.ffiBindObjPtr)), + func("FFI.cbind", zErrFunc(ffi.ffiCbind)), + func("FFI.cfunc", zErrFunc(ffi.ffiCfunc)), + func("FFI.new", zErrFunc(ffi.ffiNew)), + func("FFI.unbindObjPtr", zErrFunc(ffi.ffiUnbindObjPtr)), }; pub fn create(vm: *cy.VM, r_uri: []const u8) C.Module { @@ -105,12 +105,12 @@ pub fn create(vm: *cy.VM, r_uri: []const u8) C.Module { const htype = C.hostTypeEntry; const types = [_]C.HostTypeEntry{ - htype("File", C.HOST_OBJECT(&cli_data.FileT, null, fs.fileFinalizer)), - htype("Dir", C.HOST_OBJECT(&cli_data.DirT, null, fs.dirFinalizer)), - htype("DirIterator", C.HOST_OBJECT(&cli_data.DirIterT, fs.dirIterGetChildren, fs.dirIterFinalizer)), - htype("FFI", C.HOST_OBJECT(&cli_data.FFIT, ffi.ffiGetChildren, ffi.ffiFinalizer)), - htype("CArray", C.DECL_TYPE_GET(&cli_data.CArrayT)), - htype("CDimArray", C.DECL_TYPE_GET(&cli_data.CDimArrayT)), + htype("File", C.HOST_OBJECT(&cli_data.FileT, null, fs.fileFinalizer)), + htype("Dir", C.HOST_OBJECT(&cli_data.DirT, null, fs.dirFinalizer)), + htype("DirIterator", C.HOST_OBJECT(&cli_data.DirIterT, fs.dirIterGetChildren, fs.dirIterFinalizer)), + htype("FFI", C.HOST_OBJECT(&cli_data.FFIT, ffi.ffiGetChildren, ffi.ffiFinalizer)), + htype("CArray", C.DECL_TYPE_GET(&cli_data.CArrayT)), + htype("CDimArray", C.DECL_TYPE_GET(&cli_data.CDimArrayT)), }; var config = C.ModuleConfig{ @@ -176,7 +176,7 @@ fn zPostTypeLoad(c: *cy.Compiler, mod: C.Sym) !void { vars[4] = .{ "stdout", stdout }; } vars[5] = .{ "system", try cy.heap.allocString(c.vm, @tagName(builtin.os.tag)) }; - + if (comptime std.simd.suggestVectorLength(u8)) |VecSize| { vars[6] = .{ "vecBitSize", cy.Value.initI32(VecSize * 8) }; } else { @@ -272,7 +272,7 @@ pub fn access(vm: *cy.VM) anyerror!Value { .readWrite => .read_write, else => { return error.InvalidArgument; - } + }, }; try std.fs.cwd().access(path, .{ .mode = zmode }); return Value.Void; @@ -288,7 +288,7 @@ fn openFile(vm: *cy.VM) anyerror!Value { .readWrite => .read_write, else => { return error.InvalidArgument; - } + }, }; const file = try std.fs.cwd().openFile(path, .{ .mode = zmode }); return fs.allocFile(vm, file.handle); @@ -396,7 +396,7 @@ fn parseArgs(vm: *cy.VM) anyerror!Value { vm.retain(opt.name); try map.put(vm.alloc, opt.name, Value.True); opt.found = true; - } + }, } continue; } @@ -605,7 +605,7 @@ fn newFFI(vm: *cy.VM) Value { pub fn bindLib(vm: *cy.VM) anyerror!Value { if (!cy.hasFFI) return vm.prepPanic("Unsupported."); - return @call(.never_inline, ffi.ffiBindLib, .{vm, .{}}); + return @call(.never_inline, ffi.ffiBindLib, .{ vm, .{} }); } pub fn bindLibExt(vm: *cy.VM) anyerror!Value { @@ -619,7 +619,7 @@ pub fn bindLibExt(vm: *cy.VM) anyerror!Value { if (val.isTrue()) { config.gen_table = true; } - return @call(.never_inline, ffi.ffiBindLib, .{vm, config}); + return @call(.never_inline, ffi.ffiBindLib, .{ vm, config }); } pub extern fn hostFileWrite(fid: u32, str: [*]const u8, strLen: usize) void; @@ -672,7 +672,7 @@ pub fn execCmd(vm: *cy.VM) anyerror!Value { try buf.append(vm.alloc, str); } - const res = try std.ChildProcess.run(.{ + const res = try std.process.Child.run(.{ .allocator = vm.alloc, .argv = buf.items, .max_output_bytes = 1024 * 1024 * 10, @@ -755,6 +755,6 @@ pub fn writeFile(vm: *cy.VM) anyerror!Value { if (!cy.hasStdFiles) return vm.prepPanic("Unsupported."); const path = vm.getString(0); const content = vm.getString(1); - try std.fs.cwd().writeFile(path, content); + try std.fs.cwd().writeFile(.{ .sub_path = path, .data = content }); return Value.Void; -} \ No newline at end of file +} diff --git a/src/tokenizer.zig b/src/tokenizer.zig index 2fbf21414..aeb36295f 100644 --- a/src/tokenizer.zig +++ b/src/tokenizer.zig @@ -4,7 +4,7 @@ const tt = stdx.testing; const cy = @import("cyber.zig"); const v = cy.fmt.v; -const keywords = std.ComptimeStringMap(TokenType, .{ +const keywords = std.StaticStringMap(TokenType).initComptime(.{ .{ "and", .and_k }, .{ "as", .as_k }, .{ "await", .await_k }, @@ -215,7 +215,7 @@ pub const Tokenizer = struct { ignoreErrors: bool, has_error: bool, - reportFn: *const fn(*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror!void, + reportFn: *const fn (*anyopaque, format: []const u8, args: []const cy.fmt.FmtValue, pos: u32) anyerror!void, ctx: *anyopaque, pub fn init(alloc: std.mem.Allocator, src: []const u8) Tokenizer { @@ -429,7 +429,7 @@ pub const Tokenizer = struct { }, else => { try t.pushToken(.equal, start); - } + }, } } else { try t.pushToken(.equal, start); @@ -459,16 +459,12 @@ pub const Tokenizer = struct { try t.pushToken(.right_angle, start); } }, - ' ', - '\r', - '\t' => { + ' ', '\r', '\t' => { // Consume whitespace. while (!isAtEnd(t)) { const ch2 = peek(t); switch (ch2) { - ' ', - '\r', - '\t' => advance(t), + ' ', '\r', '\t' => advance(t), else => return tokenizeOne(t, state), } } @@ -501,7 +497,7 @@ pub const Tokenizer = struct { } } } - try t.pushSpanToken(.rune, start+1, t.nextPos-1); + try t.pushSpanToken(.rune, start + 1, t.nextPos - 1); }, '"' => { if (state.stateT == .templateExprToken) { @@ -562,13 +558,11 @@ pub const Tokenizer = struct { try t.pushToken(.err, start); return .{ .stateT = .token }; } else { - try t.reportErrorAt("unknown character: {} ({}) at {}", &.{ - cy.fmt.char(ch), v(ch), v(start) - }, start); + try t.reportErrorAt("unknown character: {} ({}) at {}", &.{ cy.fmt.char(ch), v(ch), v(start) }, start); } }, } - } + }, } return .{ .stateT = .token }; } @@ -635,7 +629,7 @@ pub const Tokenizer = struct { } if (t.src.len >= t.nextPos + 2) { - if (t.src[t.nextPos] == '#' and t.src[t.nextPos+1] == '!') { + if (t.src[t.nextPos] == '#' and t.src[t.nextPos + 1] == '!') { // Ignore shebang line. while (!isAtEnd(t)) { if (peek(t) == '\n') { @@ -898,7 +892,7 @@ pub const Tokenizer = struct { if (next < '0' or next > '9') { try t.pushSpanToken(.dec, start, t.nextPos); return; - } + } advance(t); advance(t); consumeDigits(t); @@ -939,7 +933,7 @@ pub const Tokenizer = struct { return; } - if (t.src[t.nextPos-1] == '0') { + if (t.src[t.nextPos - 1] == '0') { // Less common integer notation. if (ch == 'x') { // Hex integer. @@ -988,7 +982,7 @@ pub const Tokenizer = struct { return; } else { if (std.ascii.isAlphabetic(ch)) { - const char: []const u8 = &[_]u8{ ch }; + const char: []const u8 = &[_]u8{ch}; return t.reportError("Unsupported integer notation: {}", &.{v(char)}); } } @@ -1038,4 +1032,4 @@ test "tokenizer internals." { try tt.eq(std.enums.values(TokenType).len, 97); try tt.eq(keywords.kvs.len, 42); -} \ No newline at end of file +} diff --git a/src/vm.zig b/src/vm.zig index b0db4783b..03ca399a4 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -57,7 +57,7 @@ const VMC = extern struct { fields_cap: usize, fields_len: usize, - /// Static vars. + /// Static vars. varSyms: [*]rt.VarSym, varSyms_cap: usize, varSyms_len: usize, @@ -215,7 +215,7 @@ pub const VM = struct { /// Whether this VM is already deinited. Used to skip the next deinit to avoid using undefined memory. deinited: bool, - deinitedRtObjects: bool, + deinitedRtObjects: bool, tempBuf: [128]u8 align(4), @@ -359,7 +359,7 @@ pub const VM = struct { const data = try self.alloc.create(cy.builtins.BuiltinsData); try self.data.put(self.alloc, "builtins", data); - + try @call(.never_inline, cy.bindings.bindCore, .{self}); } @@ -669,20 +669,20 @@ pub const VM = struct { const PROT_WRITE = 2; const PROT_EXEC = 4; try std.posix.mprotect(jitRes.buf.items.ptr[0..jitRes.buf.capacity], PROT_READ | PROT_EXEC); - + // Memory must be reset to original setting in order to be freed. defer std.posix.mprotect(jitRes.buf.items.ptr[0..jitRes.buf.capacity], PROT_WRITE) catch cy.fatal(); - if (jitRes.buf.items.len > 500*4) { - logger.tracev("jit code (size: {}) {}...", .{jitRes.buf.items.len, std.fmt.fmtSliceHexLower(jitRes.buf.items[0..100*4])}); + if (jitRes.buf.items.len > 500 * 4) { + logger.tracev("jit code (size: {}) {}...", .{ jitRes.buf.items.len, std.fmt.fmtSliceHexLower(jitRes.buf.items[0 .. 100 * 4]) }); } else { - logger.tracev("jit code (size: {}) {}", .{jitRes.buf.items.len, std.fmt.fmtSliceHexLower(jitRes.buf.items)}); + logger.tracev("jit code (size: {}) {}", .{ jitRes.buf.items.len, std.fmt.fmtSliceHexLower(jitRes.buf.items) }); } - const bytes = jitRes.buf.items[jitRes.mainPc..jitRes.mainPc+12*4]; - logger.tracev("main start {}: {}", .{jitRes.mainPc, std.fmt.fmtSliceHexLower(bytes)}); + const bytes = jitRes.buf.items[jitRes.mainPc .. jitRes.mainPc + 12 * 4]; + logger.tracev("main start {}: {}", .{ jitRes.mainPc, std.fmt.fmtSliceHexLower(bytes) }); - const main: *const fn(*VM, [*]Value) callconv(.C) void = @ptrCast(@alignCast(jitRes.buf.items.ptr + jitRes.mainPc)); + const main: *const fn (*VM, [*]Value) callconv(.C) void = @ptrCast(@alignCast(jitRes.buf.items.ptr + jitRes.mainPc)); // @breakpoint(); main(self, self.c.framePtr); return Value.initInt(0); @@ -728,7 +728,7 @@ pub const VM = struct { return error.Panic; } } else { - const exeRes = try std.ChildProcess.run(.{ + const exeRes = try std.process.Child.run(.{ .allocator = self.alloc, .argv = &.{res.aot.exePath}, }); @@ -756,7 +756,7 @@ pub const VM = struct { while (i < vmc.NumCodes) : (i += 1) { if (self.c.trace.opCounts[i].count > 0) { const op = std.meta.intToEnum(cy.OpCode, self.c.trace.opCounts[i].code) catch continue; - std.debug.print("\t{s} {}\n", .{@tagName(op), self.c.trace.opCounts[i].count}); + std.debug.print("\t{s} {}\n", .{ @tagName(op), self.c.trace.opCounts[i].count }); } } } @@ -776,7 +776,7 @@ pub const VM = struct { const details = self.funcSymDetails.buf[i]; const name = details.namePtr[0..details.nameLen]; const sigStr = try self.sema.formatFuncSig(details.funcSigId, &cy.tempBuf, null); - fmt.printStderr("\t{}{}: {}\n", &.{v(name), v(sigStr), v(i)}); + fmt.printStderr("\t{}{}: {}\n", &.{ v(name), v(sigStr), v(i) }); } } @@ -786,7 +786,7 @@ pub const VM = struct { var iter = self.field_map.iterator(); while (iter.next()) |it| { const name = rt.getName(self, it.key_ptr.*); - fmt.printStderr("\t{}: {}\n", &.{v(name), v(it.value_ptr.*)}); + fmt.printStderr("\t{}: {}\n", &.{ v(name), v(it.value_ptr.*) }); } } } @@ -829,7 +829,7 @@ pub const VM = struct { _ = self; _ = pc; - // If there are fewer return values than required from the function call, + // If there are fewer return values than required from the function call, // fill the missing slots with the none value. switch (numRetVals) { 0 => @compileError("Not supported."), @@ -855,7 +855,7 @@ pub const VM = struct { self.unwind_slots = buf.unwind_slots.items; self.unwind_slot_prevs = buf.unwind_slot_prevs.items; self.unwind_trys = buf.unwind_trys.items; - + self.c.pc = @ptrCast(&buf.ops.items[buf.main_pc]); try cy.fiber.stackEnsureTotalCapacity(self, buf.mainStackSize); @@ -881,7 +881,7 @@ pub const VM = struct { self.num_evals += 1; self.last_bc_len = @intCast(self.c.ops_len); } - try @call(.never_inline, evalLoopGrowStack, .{self, true}); + try @call(.never_inline, evalLoopGrowStack, .{ self, true }); logger.tracev("main stack size: {}", .{buf.mainStackSize}); if (self.endLocal == 255) { @@ -926,7 +926,7 @@ pub const VM = struct { // Copy callee + args to a new blank frame. vm.c.framePtr[ret + CalleeStart] = func; - @memcpy(vm.c.framePtr[ret+CallArgStart..ret+CallArgStart+args.len], args); + @memcpy(vm.c.framePtr[ret + CallArgStart .. ret + CallArgStart + args.len], args); if (cy.Trace) { vm.c.trace_indent += 1; @@ -940,7 +940,7 @@ pub const VM = struct { // Only user funcs start eval loop. if (!cy.value.isHostFunc(vm, func)) { if (config.from_external) { - @call(.never_inline, evalLoopGrowStack, .{vm, true}) catch |err| { + @call(.never_inline, evalLoopGrowStack, .{ vm, true }) catch |err| { if (err == error.Panic) { // Dump for now. const frames = try cy.debug.allocStackTrace(vm, vm.c.getStack(), vm.compactTrace.items()); @@ -958,7 +958,7 @@ pub const VM = struct { // return builtins.prepThrowZError(@ptrCast(vm), err, @errorReturnTrace()); }; } else { - @call(.never_inline, evalLoopGrowStack, .{vm, false}) catch |err| { + @call(.never_inline, evalLoopGrowStack, .{ vm, false }) catch |err| { if (err == error.Panic) { return err; } else { @@ -996,7 +996,7 @@ pub const VM = struct { const mod = parent.getMod().?; const c = mod.chunk; - const name = try std.fmt.allocPrint(self.alloc, "{s}{}", .{baseName, uniqId}); + const name = try std.fmt.allocPrint(self.alloc, "{s}{}", .{ baseName, uniqId }); errdefer self.alloc.free(name); if (mod.getSym(name)) |_| { @@ -1089,7 +1089,7 @@ pub const VM = struct { pub fn ensureMethod(self: *VM, name: []const u8) !rt.MethodId { const nameId = try rt.ensureNameSym(self, name); - const res = try @call(.never_inline, @TypeOf(self.method_map).getOrPut, .{&self.method_map, self.alloc, nameId}); + const res = try @call(.never_inline, @TypeOf(self.method_map).getOrPut, .{ &self.method_map, self.alloc, nameId }); if (!res.found_existing) { const id: u32 = @intCast(self.methods.len); try self.methods.append(self.alloc, .{ .name = nameId }); @@ -1121,7 +1121,7 @@ pub const VM = struct { return cur_id; } - pub fn setMethodGroup(self: *VM, type_id: cy.TypeId, name: []const u8, group: rt.FuncGroupId) !void { + pub fn setMethodGroup(self: *VM, type_id: cy.TypeId, name: []const u8, group: rt.FuncGroupId) !void { const method = try self.ensureMethod(name); const key = rt.TypeMethodKey.initTypeMethodKey(type_id, method); try self.type_method_map.put(self.alloc, key, group); @@ -1132,7 +1132,9 @@ pub const VM = struct { try self.funcSyms.append(self.alloc, func); try self.funcSymDetails.append(self.alloc, .{ - .namePtr = name.ptr, .nameLen = @intCast(name.len), .funcSigId = sig, + .namePtr = name.ptr, + .nameLen = @intCast(name.len), + .funcSigId = sig, }); return @intCast(id); } @@ -1184,7 +1186,7 @@ pub const VM = struct { return error.Panic; } - fn panic(self: *VM, msg: []const u8) error{Panic, OutOfMemory} { + fn panic(self: *VM, msg: []const u8) error{ Panic, OutOfMemory } { @setCold(true); const dupe = try self.alloc.dupe(u8, msg); self.c.curFiber.panicPayload = @as(u64, @intFromPtr(dupe.ptr)) | (@as(u64, dupe.len) << 48); @@ -1209,7 +1211,7 @@ pub const VM = struct { return error.Panic; } - fn getFieldMissingSymbolError(self: *VM) error{Panic, OutOfMemory} { + fn getFieldMissingSymbolError(self: *VM) error{ Panic, OutOfMemory } { @setCold(true); return self.panic("Field not found in value."); } @@ -1284,7 +1286,7 @@ pub const VM = struct { const name_arg = try self.allocString(name); defer self.release(name_arg); - var args: [3]Value = .{rec_arg, name_arg, val}; + var args: [3]Value = .{ rec_arg, name_arg, val }; const func = self.getCompatMethodFunc(rec_t, self.compiler.setMID, args[1..]) orelse { return error.Unexpected; }; @@ -1325,7 +1327,7 @@ pub const VM = struct { const name_arg = try self.allocString(name); defer self.release(name_arg); - var args: [2]Value = .{rec_arg, name_arg}; + var args: [2]Value = .{ rec_arg, name_arg }; const func = self.getCompatMethodFunc(rec_t, self.compiler.getMID, args[1..]) orelse { return error.Unexpected; }; @@ -1339,9 +1341,14 @@ pub const VM = struct { /// Assumes overloaded function. Finds first matching function at runtime. fn callSymDyn( - self: *VM, pc: [*]cy.Inst, fp: [*]Value, entry: u32, ret: u8, nargs: u8, + self: *VM, + pc: [*]cy.Inst, + fp: [*]Value, + entry: u32, + ret: u8, + nargs: u8, ) !cy.fiber.PcFp { - const vals = fp[ret+CallArgStart..ret+CallArgStart+nargs]; + const vals = fp[ret + CallArgStart .. ret + CallArgStart + nargs]; var cur = entry; while (cur != cy.NullId) { @@ -1396,7 +1403,11 @@ pub const VM = struct { } fn callSym( - self: *VM, pc: [*]cy.Inst, framePtr: [*]Value, func: rt.FuncSymbol, ret: u8, + self: *VM, + pc: [*]cy.Inst, + framePtr: [*]Value, + func: rt.FuncSymbol, + ret: u8, ) !cy.fiber.PcFp { switch (func.type) { .host_func => { @@ -1461,7 +1472,7 @@ pub const VM = struct { const target_t = target_params[i]; const arg_t = arg.getTypeId(); if (!types.isTypeSymCompat(self.compiler, arg_t, target_t.type)) { - if (!@call(.never_inline, canInferArg, .{self, arg, target_t.type})) { + if (!@call(.never_inline, canInferArg, .{ self, arg, target_t.type })) { return false; } } @@ -1494,7 +1505,7 @@ pub const VM = struct { /// Assumes args does not include rec. fn getCompatMethodFunc(self: *VM, rec_t: cy.TypeId, method_id: rt.MethodId, args: []cy.Value) ?rt.FuncSymbol { - const group_id = @call(.never_inline, getTypeMethod, .{self, rec_t, method_id}) orelse { + const group_id = @call(.never_inline, getTypeMethod, .{ self, rec_t, method_id }) orelse { return null; }; @@ -1545,9 +1556,9 @@ pub const VM = struct { if (val.isString()) { const str = val.asString(); if (str.len > 20) { - try w.print("String({}) {s}...", .{str.len, str[0..20]}); + try w.print("String({}) {s}...", .{ str.len, str[0..20] }); } else { - try w.print("String({}) {s}", .{str.len, str}); + try w.print("String({}) {s}", .{ str.len, str }); } } else { _ = try self.writeValue(w, val); @@ -1585,7 +1596,7 @@ pub const VM = struct { pub fn writeValue(self: *const VM, w: anytype, val: Value) !void { const typeId = val.getTypeId(); - + switch (typeId) { bt.Float => { const f = val.asF64(); @@ -1630,7 +1641,7 @@ pub const VM = struct { const sym = self.c.types[typeId].sym; const enumv = val.getEnumValue(); const name = sym.cast(.enum_t).getValueSym(enumv).head.name(); - try std.fmt.format(w, "{s}.{s}", .{sym.name(), name}); + try std.fmt.format(w, "{s}.{s}", .{ sym.name(), name }); } else { try w.writeAll("Unknown"); } @@ -1660,7 +1671,7 @@ pub const VM = struct { } const name = self.compiler.sema.getTypeBaseName(typeId); try w.writeAll(name); - } + }, } } @@ -1780,26 +1791,26 @@ fn toF64OrPanic(vm: *cy.VM, val: Value) !f64 { } else if (val.isInteger()) { return @floatFromInt(val.asInteger()); } else { - return @call(.never_inline, panicConvertFloatError, .{vm, val}); + return @call(.never_inline, panicConvertFloatError, .{ vm, val }); } } -pub fn panicDivisionByZero(vm: *cy.VM) error{Panic, OutOfMemory} { +pub fn panicDivisionByZero(vm: *cy.VM) error{ Panic, OutOfMemory } { @setCold(true); return vm.panic("Division by zero."); } -pub fn panicExpectedInteger(vm: *cy.VM) error{Panic, OutOfMemory} { +pub fn panicExpectedInteger(vm: *cy.VM) error{ Panic, OutOfMemory } { @setCold(true); return vm.panic("Expected integer operand."); } -pub fn panicExpectedFloat(vm: *cy.VM) error{Panic, OutOfMemory} { +pub fn panicExpectedFloat(vm: *cy.VM) error{ Panic, OutOfMemory } { @setCold(true); return vm.panic("Expected float operand."); } -fn panicConvertFloatError(vm: *cy.VM, val: Value) error{Panic, OutOfMemory} { +fn panicConvertFloatError(vm: *cy.VM, val: Value) error{ Panic, OutOfMemory } { @setCold(true); const typeId = val.getTypeId(); return vm.panicFmt("Cannot convert `{}` to float.", &.{v(vm.c.types[typeId].name)}); @@ -1858,12 +1869,11 @@ const Root = @This(); /// If successful, execution should continue. pub fn handleInterrupt(vm: *VM, rootFp: u32) !void { if (vm.c.curFiber.panicType == vmc.PANIC_NATIVE_THROW) { - const res = try @call(.never_inline, cy.fiber.throw, .{ - vm, rootFp, vm.getFiberContext(), Value.initRaw(vm.c.curFiber.panicPayload) }); + const res = try @call(.never_inline, cy.fiber.throw, .{ vm, rootFp, vm.getFiberContext(), Value.initRaw(vm.c.curFiber.panicPayload) }); vm.c.pc = vm.c.ops + res.pc; vm.c.framePtr = vm.c.stack + res.fp; } else { - const res = try @call(.never_inline, panicCurFiber, .{ vm }); + const res = try @call(.never_inline, panicCurFiber, .{vm}); vm.c.pc = vm.c.ops + res.pc; vm.c.framePtr = vm.c.stack + res.fp; } @@ -1871,7 +1881,7 @@ pub fn handleInterrupt(vm: *VM, rootFp: u32) !void { /// To reduce the amount of code inlined in the hot loop, handle StackOverflow at the top and resume execution. /// This is also the entry way for native code to call into the VM, assuming pc, framePtr, and virtual registers are already set. -pub fn evalLoopGrowStack(vm: *VM, handle_panic: bool) error{StackOverflow, OutOfMemory, Panic, NoDebugSym, Unexpected, Await, End}!void { +pub fn evalLoopGrowStack(vm: *VM, handle_panic: bool) error{ StackOverflow, OutOfMemory, Panic, NoDebugSym, Unexpected, Await, End }!void { logger.tracev("begin eval loop", .{}); // Record the start fp offset, so that stack unwinding knows when to stop. @@ -1894,12 +1904,12 @@ pub fn evalLoopGrowStack(vm: *VM, handle_panic: bool) error{StackOverflow, OutOf } if (handle_panic) { - try @call(.never_inline, handleExecResult, .{vm, res, startFp}); + try @call(.never_inline, handleExecResult, .{ vm, res, startFp }); } else { if (res == vmc.RES_CODE_PANIC or res == vmc.RES_CODE_UNKNOWN) { return error.Panic; } else { - try @call(.never_inline, handleExecResult, .{vm, res, startFp}); + try @call(.never_inline, handleExecResult, .{ vm, res, startFp }); } } } @@ -1916,7 +1926,7 @@ fn handleExecResult(vm: *VM, res: vmc.ResultCode, fpStart: u32) !void { try @call(.never_inline, cy.fiber.growStackAuto, .{vm}); } else if (res == vmc.RES_CODE_UNKNOWN) { logger.tracev("Unknown error code.", .{}); - const cont = try @call(.never_inline, panicCurFiber, .{ vm }); + const cont = try @call(.never_inline, panicCurFiber, .{vm}); vm.c.pc = vm.c.ops + cont.pc; vm.c.framePtr = vm.c.stack + cont.fp; } @@ -2012,7 +2022,7 @@ fn dumpEvalOp(vm: *VM, pc: [*]const cy.Inst, fp: [*]const cy.Value) !void { extra = try std.fmt.bufPrint(&S.buf, "rt: sym={s}", .{name}); }, .constOp => { - const idx = @as(*const align (1) u16, @ptrCast(pc + 1)).*; + const idx = @as(*align(1) const u16, @ptrCast(pc + 1)).*; _ = idx; const dst = pc[3].val; _ = dst; @@ -2030,10 +2040,10 @@ fn dumpEvalOp(vm: *VM, pc: [*]const cy.Inst, fp: [*]const cy.Value) !void { }, .callSym => { const ret = pc[1].val; - const symId = @as(*const align(1) u16, @ptrCast(pc + 4)).*; + const symId = @as(*align(1) const u16, @ptrCast(pc + 4)).*; const details = vm.funcSymDetails.buf[symId]; const name = details.namePtr[0..details.nameLen]; - extra = try std.fmt.bufPrint(&S.buf, "rt: sym={s}, fp={}", .{name, cy.fiber.getStackOffset(vm.c.stack, fp) + ret}); + extra = try std.fmt.bufPrint(&S.buf, "rt: sym={s}, fp={}", .{ name, cy.fiber.getStackOffset(vm.c.stack, fp) + ret }); }, .call => { const ret = pc[1].val; @@ -2083,7 +2093,7 @@ fn canInferArg(vm: *VM, arg: Value, target_t: cy.TypeId) bool { const name = vm.syms.buf[arg.asSymbolId()].name; if (type_e.sym.cast(.enum_t).getMemberTag(name)) |value| { _ = value; - + return true; } } else if (target_t == bt.Symbol) { @@ -2125,18 +2135,18 @@ fn preCallDyn(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, final_r // Setup the final call frame with args copied. // This allows arg unboxing so that post call release still operates on boxed args. fp[final_ret + 1] = buildCallInfo2(cont, cy.bytecode.CallInstLen, @intCast(func_stack_size)); - fp[final_ret + 2] = Value{ .retPcPtr = pc + cy.bytecode.CallInstLen}; + fp[final_ret + 2] = Value{ .retPcPtr = pc + cy.bytecode.CallInstLen }; fp[final_ret + 3] = Value{ .retFramePtr = fp + ret }; - const args = fp[ret+CallArgStart..ret+CallArgStart+nargs]; - const final_args = fp[final_ret+CallArgStart..final_ret+CallArgStart+nargs]; + const args = fp[ret + CallArgStart .. ret + CallArgStart + nargs]; + const final_args = fp[final_ret + CallArgStart .. final_ret + CallArgStart + nargs]; if (req_type_check) { // Perform type check on args. for (args, 0..) |arg, i| { const cstrType = sig.params_ptr[i]; const argType = arg.getTypeId(); if (!types.isTypeSymCompat(vm.compiler, argType, cstrType.type)) { - const final_arg = @call(.never_inline, inferArg, .{vm, arg, cstrType.type}) orelse { + const final_arg = @call(.never_inline, inferArg, .{ vm, arg, cstrType.type }) orelse { return panicIncompatibleLambdaSig(vm, args, sig_id); }; args[i] = final_arg; @@ -2144,7 +2154,7 @@ fn preCallDyn(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, final_r continue; } if (vm.sema.isUnboxedType(cstrType.type)) { - const final_arg = @call(.never_inline, unbox, .{vm, arg, argType}); + const final_arg = @call(.never_inline, unbox, .{ vm, arg, argType }); final_args[i] = final_arg; continue; } @@ -2174,7 +2184,7 @@ pub fn call(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, callee: Value, ret: u8, switch (obj.func_ptr.kind) { .bc => { if (numArgs != obj.func_ptr.numParams) { - logger.tracev("lambda params/args mismatch {} {}", .{numArgs, obj.func_ptr.numParams}); + logger.tracev("lambda params/args mismatch {} {}", .{ numArgs, obj.func_ptr.numParams }); return vm.interruptThrowSymbol(.InvalidSignature); } @@ -2192,7 +2202,7 @@ pub fn call(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, callee: Value, ret: u8, }, .host => { if (numArgs != obj.func_ptr.numParams) { - logger.tracev("hostfunc params/args mismatch {} {}", .{numArgs, obj.func_ptr.numParams}); + logger.tracev("hostfunc params/args mismatch {} {}", .{ numArgs, obj.func_ptr.numParams }); return vm.interruptThrowSymbol(.InvalidSignature); } @@ -2230,7 +2240,7 @@ fn callFuncUnion(vm: *VM, pc: [*]cy.Inst, framePtr: [*]cy.Value, callee: cy.Valu switch (func.kind) { .closure => { if (numArgs != func.numParams) { - logger.tracev("closure params/args mismatch {} {}", .{numArgs, func.numParams}); + logger.tracev("closure params/args mismatch {} {}", .{ numArgs, func.numParams }); return vm.interruptThrowSymbol(.InvalidSignature); } @@ -2252,7 +2262,7 @@ fn callFuncUnion(vm: *VM, pc: [*]cy.Inst, framePtr: [*]cy.Value, callee: cy.Valu }, .bc => { if (numArgs != func.numParams) { - logger.tracev("lambda params/args mismatch {} {}", .{numArgs, func.numParams}); + logger.tracev("lambda params/args mismatch {} {}", .{ numArgs, func.numParams }); return vm.interruptThrowSymbol(.InvalidSignature); } @@ -2270,7 +2280,7 @@ fn callFuncUnion(vm: *VM, pc: [*]cy.Inst, framePtr: [*]cy.Value, callee: cy.Valu }, .host => { if (numArgs != func.numParams) { - logger.tracev("hostfunc params/args mismatch {} {}", .{numArgs, func.numParams}); + logger.tracev("hostfunc params/args mismatch {} {}", .{ numArgs, func.numParams }); return vm.interruptThrowSymbol(.InvalidSignature); } @@ -2303,13 +2313,13 @@ fn panicCastAbstractError(vm: *cy.VM, val: Value, expTypeSymId: cy.sema.SymbolId const sym = vm.compiler.sema.getSymbol(expTypeSymId); const name = cy.sema.getName(&vm.compiler, sym.key.resolvedSymKey.nameId); return vm.panicFmt("Can not cast `{}` to `{}`.", &.{ - v(vm.c.types.buf[val.getTypeId()].name), v(name), + v(vm.c.types.buf[val.getTypeId()].name), v(name), }); } fn panicCastError(vm: *cy.VM, val: Value, expTypeId: cy.TypeId) !void { return vm.panicFmt("Can not cast `{}` to `{}`.", &.{ - v(vm.c.types.buf[val.getTypeId()].name), v(vm.c.types.buf[expTypeId].name), + v(vm.c.types.buf[val.getTypeId()].name), v(vm.c.types.buf[expTypeId].name), }); } @@ -2330,7 +2340,7 @@ fn allocMethodCallTypeIds(vm: *cy.VM, rec_t: cy.TypeId, vals: []const Value) ![] return typeIds; } -fn panicIncompatibleFieldType(vm: *cy.VM, fieldSemaTypeId: types.TypeId, rightv: Value) error{Panic, OutOfMemory} { +fn panicIncompatibleFieldType(vm: *cy.VM, fieldSemaTypeId: types.TypeId, rightv: Value) error{ Panic, OutOfMemory } { defer release(vm, rightv); const fieldTypeName = sema.getSymName(&vm.compiler, fieldSemaTypeId); @@ -2339,13 +2349,14 @@ fn panicIncompatibleFieldType(vm: *cy.VM, fieldSemaTypeId: types.TypeId, rightv: const rightTypeName = sema.getSymName(&vm.compiler, rightSemaTypeId); return vm.panicFmt( \\Assigning to `{}` field with incompatible type `{}`. - , &.{ + , + &.{ v(fieldTypeName), v(rightTypeName), }, ); } -fn panicIncompatibleLambdaSig(vm: *cy.VM, args: []const Value, cstrFuncSigId: sema.FuncSigId) error{Panic, OutOfMemory} { +fn panicIncompatibleLambdaSig(vm: *cy.VM, args: []const Value, cstrFuncSigId: sema.FuncSigId) error{ Panic, OutOfMemory } { const cstrFuncSigStr = vm.compiler.sema.allocFuncSigStr(cstrFuncSigId, true, null) catch return error.OutOfMemory; defer vm.alloc.free(cstrFuncSigStr); const argTypes = try allocValueTypeIds(vm, args); @@ -2356,21 +2367,22 @@ fn panicIncompatibleLambdaSig(vm: *cy.VM, args: []const Value, cstrFuncSigId: se return vm.panicFmt( \\Incompatible call arguments `({})` \\to the lambda `func {}`. - , &.{ + , + &.{ v(argsSigStr), v(cstrFuncSigStr), }, ); } /// Runtime version of `sema.reportIncompatibleCallSig`. -fn panicIncompatibleCallSymSig(vm: *cy.VM, overload_entry: u32, args: []const Value) error{Panic, OutOfMemory} { +fn panicIncompatibleCallSymSig(vm: *cy.VM, overload_entry: u32, args: []const Value) error{ Panic, OutOfMemory } { // Use first func to determine name. const first_ofunc = vm.overloaded_funcs.buf[overload_entry]; const first_func_details = vm.funcSymDetails.buf[first_ofunc.id]; const name = first_func_details.namePtr[0..first_func_details.nameLen]; - // vm.curFiber.panicType = vmc.PANIC_INFLIGHT_OOM; - // return error.Panic; + // vm.curFiber.panicType = vmc.PANIC_INFLIGHT_OOM; + // return error.Panic; const arg_types = try allocValueTypeIds(vm, args); defer vm.alloc.free(arg_types); @@ -2378,10 +2390,10 @@ fn panicIncompatibleCallSymSig(vm: *cy.VM, overload_entry: u32, args: []const Va const call_args_str = vm.compiler.sema.allocTypesStr(arg_types, null) catch return error.OutOfMemory; defer vm.alloc.free(call_args_str); - var msg: std.ArrayListUnmanaged(u8) = .{}; + var msg: std.ArrayListUnmanaged(u8) = .{}; defer msg.deinit(vm.alloc); const w = msg.writer(vm.alloc); - try w.print("Can not find compatible function for call: `{s}({s})`.", .{name, call_args_str}); + try w.print("Can not find compatible function for call: `{s}({s})`.", .{ name, call_args_str }); // if (num_ret == 1) { // try w.writeAll(" Expects non-void return."); // } @@ -2391,7 +2403,7 @@ fn panicIncompatibleCallSymSig(vm: *cy.VM, overload_entry: u32, args: []const Va var funcStr = vm.compiler.sema.formatFuncSig(first_func_details.funcSigId, &cy.tempBuf, null) catch { return error.OutOfMemory; }; - try w.print(" func {s}{s}", .{name, funcStr}); + try w.print(" func {s}{s}", .{ name, funcStr }); var cur = first_ofunc.next; while (cur != cy.NullId) { @@ -2399,15 +2411,13 @@ fn panicIncompatibleCallSymSig(vm: *cy.VM, overload_entry: u32, args: []const Va try w.writeByte('\n'); const func_details = vm.funcSymDetails.buf[ofunc.id]; funcStr = vm.sema.formatFuncSig(func_details.funcSigId, &cy.tempBuf, null) catch return error.OutOfMemory; - try w.print(" func {s}{s}", .{name, funcStr}); + try w.print(" func {s}{s}", .{ name, funcStr }); cur = ofunc.next; } return vm.panic(msg.items); } -fn panicIncompatibleMethodSig( - vm: *cy.VM, method_id: rt.MethodId, recv: Value, args: []const Value -) error{Panic, OutOfMemory} { +fn panicIncompatibleMethodSig(vm: *cy.VM, method_id: rt.MethodId, recv: Value, args: []const Value) error{ Panic, OutOfMemory } { const typeId = recv.getTypeId(); const typeIds = try allocMethodCallTypeIds(vm, typeId, args); @@ -2423,13 +2433,13 @@ fn panicIncompatibleMethodSig( }); }; - var msg: std.ArrayListUnmanaged(u8) = .{}; + var msg: std.ArrayListUnmanaged(u8) = .{}; defer msg.deinit(vm.alloc); const w = msg.writer(vm.alloc); const call_args_str = vm.compiler.sema.allocTypesStr(typeIds[1..], null) catch return error.OutOfMemory; defer vm.alloc.free(call_args_str); - try w.print("Can not find compatible method for call: `({s}) {s}({s})`.", .{typeName, name, call_args_str}); + try w.print("Can not find compatible method for call: `({s}) {s}({s})`.", .{ typeName, name, call_args_str }); try w.writeAll("\n"); try w.print("Methods named `{s}`:\n", .{name}); @@ -2440,7 +2450,7 @@ fn panicIncompatibleMethodSig( const funcStr = vm.sema.formatFuncSig(func.sig, &cy.tempBuf, null) catch { return error.OutOfMemory; }; - try w.print(" func {s}{s}", .{name, funcStr}); + try w.print(" func {s}{s}", .{ name, funcStr }); } } else { var cur: u32 = group.id; @@ -2455,7 +2465,7 @@ fn panicIncompatibleMethodSig( const funcStr = vm.sema.formatFuncSig(func.sig, &cy.tempBuf, null) catch { return error.OutOfMemory; }; - try w.print(" func {s}{s}", .{name, funcStr}); + try w.print(" func {s}{s}", .{ name, funcStr }); if (ofunc.next != cy.NullId) { try w.writeByte('\n'); } @@ -2466,7 +2476,12 @@ fn panicIncompatibleMethodSig( } fn getObjectFunctionFallback( - vm: *VM, pc: [*]cy.Inst, recv: Value, typeId: u32, method: rt.MethodId, vals: []const Value, + vm: *VM, + pc: [*]cy.Inst, + recv: Value, + typeId: u32, + method: rt.MethodId, + vals: []const Value, ) !Value { @setCold(true); _ = typeId; @@ -2488,32 +2503,29 @@ fn getObjectFunctionFallback( // - multiple methods exist with the name but the call signature doesn't match up // const relPc = getInstOffset(vm, pc); // if (debug.getDebugSym(vm, relPc)) |sym| { - // const chunk = vm.compiler.chunks.items[sym.file]; - // const node = chunk.nodes[sym.loc]; - // if (node.node_t == .callExpr) { - return panicIncompatibleMethodSig(vm, method, recv, vals); - // } else { - // release(vm, recv); - // // Debug node is from: - // // `for [iterable]:` - // const name = vm.methodGroupExts.buf[rtSymId].getName(); - // return vm.panicFmt("`{}` is either missing in `{}` or the call signature: {}(self, 0 args) is unsupported.", &.{ - // v(name), v(vm.types.buf[typeId].name), v(name), - // }); - // } + // const chunk = vm.compiler.chunks.items[sym.file]; + // const node = chunk.nodes[sym.loc]; + // if (node.node_t == .callExpr) { + return panicIncompatibleMethodSig(vm, method, recv, vals); + // } else { + // release(vm, recv); + // // Debug node is from: + // // `for [iterable]:` + // const name = vm.methodGroupExts.buf[rtSymId].getName(); + // return vm.panicFmt("`{}` is either missing in `{}` or the call signature: {}(self, 0 args) is unsupported.", &.{ + // v(name), v(vm.types.buf[typeId].name), v(name), + // }); + // } // } else { // return vm.panicFmt("Missing debug sym at {}", &.{v(getInstOffset(vm, pc))}); // } } /// Use new pc local to avoid deoptimization. -fn callObjSymFallback( - vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, recv: Value, typeId: u32, method: rt.MethodId, - ret: u8, numArgs: u8 -) !cy.fiber.PcFp { +fn callObjSymFallback(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, recv: Value, typeId: u32, method: rt.MethodId, ret: u8, numArgs: u8) !cy.fiber.PcFp { @setCold(true); // const func = try @call(.never_inline, getObjectFunctionFallback, .{obj, symId}); - const vals = framePtr[ret+CallArgStart+1..ret+CallArgStart+1+numArgs-1]; + const vals = framePtr[ret + CallArgStart + 1 .. ret + CallArgStart + 1 + numArgs - 1]; const func = try getObjectFunctionFallback(vm, pc, recv, typeId, method, vals); _ = func; return vm.panic("Missing method."); @@ -2525,7 +2537,7 @@ pub inline fn buildDynFrameInfo(cont: bool, comptime call_inst_off: u8, stack_si .call_inst_off = call_inst_off, .stack_size = stack_size, .type = .dyn, - }}; + } }; } pub inline fn buildCallInfo2(cont: bool, comptime callInstOffset: u8, stack_size: u8) Value { @@ -2534,7 +2546,7 @@ pub inline fn buildCallInfo2(cont: bool, comptime callInstOffset: u8, stack_size .call_inst_off = callInstOffset, .stack_size = stack_size, .type = .vm, - }}; + } }; } pub inline fn buildCallInfo(comptime cont: bool, comptime callInstOffset: u8, stack_size: u8) Value { @@ -2543,7 +2555,7 @@ pub inline fn buildCallInfo(comptime cont: bool, comptime callInstOffset: u8, st .call_inst_off = callInstOffset, .stack_size = stack_size, .type = .vm, - }}; + } }; } pub inline fn buildRootCallInfo(comptime cont: bool) Value { @@ -2552,7 +2564,7 @@ pub inline fn buildRootCallInfo(comptime cont: bool) Value { .call_inst_off = 0, .stack_size = 4, .type = .host, - }}; + } }; } pub inline fn getInstOffset(vm: *const VM, to: [*]const cy.Inst) u32 { @@ -2566,19 +2578,19 @@ pub inline fn getStackOffset(vm: *const VM, to: [*]const Value) u32 { /// Like Value.dump but shows heap values. pub fn dumpValue(vm: *const VM, val: Value) void { if (val.isFloat()) { - fmt.printStdout("Float {}\n", &.{ v(val.asF64()) }); + fmt.printStdout("Float {}\n", &.{v(val.asF64())}); } else { if (val.isPointer()) { const obj = val.asHeapObject(); switch (obj.getTypeId()) { - bt.ListDyn => fmt.printStdout("List {} len={}\n", &.{v(obj), v(obj.list.list.len)}), - bt.Map => fmt.printStdout("Map {} size={}\n", &.{v(obj), v(obj.map.inner.size)}), + bt.ListDyn => fmt.printStdout("List {} len={}\n", &.{ v(obj), v(obj.list.list.len) }), + bt.Map => fmt.printStdout("Map {} size={}\n", &.{ v(obj), v(obj.map.inner.size) }), bt.String => { const str = obj.string.getSlice(); if (str.len > 20) { - fmt.printStdout("String {} len={} str=\"{}\"...\n", &.{v(obj), v(str.len), v(str[0..20])}); + fmt.printStdout("String {} len={} str=\"{}\"...\n", &.{ v(obj), v(str.len), v(str[0..20]) }); } else { - fmt.printStdout("String {} len={} str=\"{}\"\n", &.{v(obj), v(str.len), v(str)}); + fmt.printStdout("String {} len={} str=\"{}\"\n", &.{ v(obj), v(str.len), v(str) }); } }, bt.Lambda => fmt.printStdout("Lambda {}\n", &.{v(obj)}), @@ -2587,7 +2599,7 @@ pub fn dumpValue(vm: *const VM, val: Value) void { bt.HostFunc => fmt.printStdout("NativeFunc {}\n", &.{v(obj)}), else => { const name = vm.compiler.sema.types.items[obj.getTypeId()].sym.name(); - fmt.printStdout("HeapObject {} {} {}\n", &.{v(obj), v(obj.getTypeId()), v(name)}); + fmt.printStdout("HeapObject {} {} {}\n", &.{ v(obj), v(obj.getTypeId()), v(name) }); }, } } else { @@ -2603,15 +2615,14 @@ fn opMatch(pc: [*]const cy.Inst, framePtr: [*]const Value) u16 { while (i < numCases) : (i += 1) { const right = framePtr[pc[3 + i * 3].val]; // Can immediately match numbers, objects, primitives. - const cond = if (expr.val == right.val) true else - @call(.never_inline, evalCompareBool, .{expr, right}); + const cond = if (expr.val == right.val) true else @call(.never_inline, evalCompareBool, .{ expr, right }); if (cond) { // Jump. - return @as(*const align (1) u16, @ptrCast(pc + 4 + i * 3)).*; + return @as(*align(1) const u16, @ptrCast(pc + 4 + i * 3)).*; } } // else case - return @as(*const align (1) u16, @ptrCast(pc + 4 + i * 3 - 1)).*; + return @as(*align(1) const u16, @ptrCast(pc + 4 + i * 3 - 1)).*; } fn releaseFuncSymDep(vm: *VM, symId: SymbolId) void { @@ -2630,16 +2641,14 @@ fn releaseFuncSymDep(vm: *VM, symId: SymbolId) void { } } -fn reportAssignFuncSigMismatch(vm: *VM, srcFuncSigId: u32, dstFuncSigId: u32) error{OutOfMemory, Panic} { +fn reportAssignFuncSigMismatch(vm: *VM, srcFuncSigId: u32, dstFuncSigId: u32) error{ OutOfMemory, Panic } { const dstSig = vm.compiler.sema.allocFuncSigStr(dstFuncSigId, true) catch fatal(); const srcSig = vm.compiler.sema.allocFuncSigStr(srcFuncSigId, true) catch fatal(); defer { vm.alloc.free(dstSig); vm.alloc.free(srcSig); } - return vm.panicFmt("Assigning to static function `func {}` with a different function signature `func {}`.", - &.{v(dstSig), v(srcSig)} - ); + return vm.panicFmt("Assigning to static function `func {}` with a different function signature `func {}`.", &.{ v(dstSig), v(srcSig) }); } fn isAssignFuncSigCompat(vm: *VM, srcFuncSigId: sema.FuncSigId, dstFuncSigId: sema.FuncSigId) bool { @@ -2707,11 +2716,11 @@ fn preCallObjSym(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, fina // Setup the final call frame with args copied. // This allows arg unboxing so that post call release still operates on boxed args. fp[final_ret + 1] = buildCallInfo2(true, cy.bytecode.CallObjSymInstLen, func_stack_size); - fp[final_ret + 2] = Value{ .retPcPtr = pc + cy.bytecode.CallObjSymInstLen}; + fp[final_ret + 2] = Value{ .retPcPtr = pc + cy.bytecode.CallObjSymInstLen }; fp[final_ret + 3] = Value{ .retFramePtr = fp + ret }; - const args = fp[ret+CallArgStart..ret+CallArgStart+nargs]; - const final_args = fp[final_ret+CallArgStart..final_ret+CallArgStart+nargs]; + const args = fp[ret + CallArgStart .. ret + CallArgStart + nargs]; + const final_args = fp[final_ret + CallArgStart .. final_ret + CallArgStart + nargs]; if (req_type_check) { // Perform type check on args. for (args, 0..) |arg, i| { @@ -2720,7 +2729,7 @@ fn preCallObjSym(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, fina // Arguments are already type checked when matching methods. if (arg.getTypeId() == bt.TagLit) { - const final_arg = @call(.never_inline, inferArg, .{vm, arg, cstrType.type}) orelse { + const final_arg = @call(.never_inline, inferArg, .{ vm, arg, cstrType.type }) orelse { return panicIncompatibleLambdaSig(vm, args, sig_id); }; args[i] = final_arg; @@ -2728,7 +2737,7 @@ fn preCallObjSym(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, fina continue; } if (vm.sema.isUnboxedType(cstrType.type)) { - const final_arg = @call(.never_inline, unbox, .{vm, arg, argType}); + const final_arg = @call(.never_inline, unbox, .{ vm, arg, argType }); final_args[i] = final_arg; continue; } @@ -2744,8 +2753,13 @@ fn preCallObjSym(vm: *VM, pc: [*]cy.Inst, fp: [*]Value, nargs: u8, ret: u8, fina /// Assumes args are compatible. /// Like `callSym` except inlines different op codes. fn callMethod( - vm: *VM, pc: [*]cy.Inst, fp: [*]cy.Value, func: rt.FuncSymbol, - typeId: cy.TypeId, nargs: u8, ret: u8, + vm: *VM, + pc: [*]cy.Inst, + fp: [*]cy.Value, + func: rt.FuncSymbol, + typeId: cy.TypeId, + nargs: u8, + ret: u8, ) !?cy.fiber.PcFp { switch (func.type) { .func => { @@ -2876,15 +2890,15 @@ fn zUnbox(vm: *VM, val: cy.Value, type_id: cy.TypeId) callconv(.C) cy.Value { fn zCallTrait(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, vtable_idx: u16, ret: u8) callconv(.C) vmc.PcFpResult { // Get func from vtable. - const trait = framePtr[ret+4].asHeapObject(); + const trait = framePtr[ret + 4].asHeapObject(); const vtable = vm.vtables.buf[trait.trait.vtable]; const func_id = vtable[vtable_idx]; const func = vm.funcSyms.buf[func_id]; // Unwrap impl to first arg slot. - framePtr[ret+5] = trait.trait.impl; + framePtr[ret + 5] = trait.trait.impl; - const res = @call(.always_inline, VM.callSym, .{vm, pc, framePtr, func, ret}) catch |err| { + const res = @call(.always_inline, VM.callSym, .{ vm, pc, framePtr, func, ret }) catch |err| { if (err == error.Panic) { return .{ .pc = undefined, @@ -2914,7 +2928,7 @@ fn zCallTrait(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, vtable_idx: u16, ret: fn zCallSym(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, symId: u16, ret: u8) callconv(.C) vmc.PcFpResult { const func = vm.funcSyms.buf[symId]; - const res = @call(.always_inline, VM.callSym, .{vm, pc, framePtr, func, ret}) catch |err| { + const res = @call(.always_inline, VM.callSym, .{ vm, pc, framePtr, func, ret }) catch |err| { if (err == error.Panic) { return .{ .pc = undefined, @@ -2943,7 +2957,7 @@ fn zCallSym(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, symId: u16, ret: u8) ca } fn zCallSymDyn(vm: *VM, pc: [*]cy.Inst, framePtr: [*]Value, symId: u16, ret: u8, numArgs: u8) callconv(.C) vmc.PcFpResult { - const res = @call(.always_inline, VM.callSymDyn, .{vm, pc, framePtr, @as(u32, @intCast(symId)), ret, numArgs}) catch |err| { + const res = @call(.always_inline, VM.callSymDyn, .{ vm, pc, framePtr, @as(u32, @intCast(symId)), ret, numArgs }) catch |err| { if (err == error.Panic) { return .{ .pc = undefined, @@ -2977,7 +2991,7 @@ fn zDumpEvalOp(vm: *VM, pc: [*]const cy.Inst, fp: [*]const cy.Value) callconv(.C pub fn zFreeObject(vm: *cy.VM, obj: *HeapObject) callconv(.C) void { cy.heap.freeObject(vm, obj, false); -} +} fn zEnd(vm: *cy.VM, pc: [*]const cy.Inst) callconv(.C) void { vm.endLocal = pc[1].val; @@ -2986,12 +3000,7 @@ fn zEnd(vm: *cy.VM, pc: [*]const cy.Inst) callconv(.C) void { fn zAllocLambda(vm: *cy.VM, rt_id: u32, ptr_t: cy.TypeId) callconv(.C) vmc.ValueResult { const func = vm.funcSyms.buf[rt_id]; - const func_ptr = cy.heap.allocBcFuncPtr(vm, ptr_t, func.data.func.pc, - @intCast(func.nparams), - @intCast(func.data.func.stackSize), - @intCast(func.sig), - func.req_type_check - ) catch { + const func_ptr = cy.heap.allocBcFuncPtr(vm, ptr_t, func.data.func.pc, @intCast(func.nparams), @intCast(func.data.func.stackSize), @intCast(func.sig), func.req_type_check) catch { return .{ .val = undefined, .code = vmc.RES_CODE_UNKNOWN, @@ -3073,10 +3082,16 @@ fn zOtherToF64(val: Value) callconv(.C) f64 { } fn zCallObjSym( - vm: *cy.VM, pc: [*]cy.Inst, stack: [*]Value, recv: Value, - typeId: cy.TypeId, method: u16, ret: u8, numArgs: u8, + vm: *cy.VM, + pc: [*]cy.Inst, + stack: [*]Value, + recv: Value, + typeId: cy.TypeId, + method: u16, + ret: u8, + numArgs: u8, ) callconv(.C) vmc.CallObjSymResult { - const args = stack[ret+CallArgStart+1..ret+CallArgStart+1+numArgs-1]; + const args = stack[ret + CallArgStart + 1 .. ret + CallArgStart + 1 + numArgs - 1]; if (vm.getCompatMethodFunc(typeId, method, args)) |func| { const mb_res = callMethod(vm, pc, stack, func, typeId, numArgs, ret) catch |err| { if (err == error.Panic) { @@ -3101,7 +3116,7 @@ fn zCallObjSym( }; } } - const res = @call(.never_inline, callObjSymFallback, .{vm, pc, stack, recv, typeId, method, ret, numArgs}) catch |err| { + const res = @call(.never_inline, callObjSymFallback, .{ vm, pc, stack, recv, typeId, method, ret, numArgs }) catch |err| { if (err == error.Panic) { return .{ .pc = undefined, @@ -3510,7 +3525,7 @@ fn zGetTypeName(vm: *VM, id: cy.TypeId) callconv(.C) vmc.Str { return vmc.Str{ .ptr = "DanglingObject", .len = "DanglingObject".len }; } if (vm.c.types[id].kind == .null) { - cy.panicFmt("Type `{}` is uninited.", .{ id }); + cy.panicFmt("Type `{}` is uninited.", .{id}); } } const name = vm.c.types[id].sym.name(); @@ -3538,8 +3553,8 @@ fn spawn(args: struct { env_map: ?*const std.process.EnvMap = null, max_output_bytes: usize = 50 * 1024, expand_arg0: std.posix.Arg0Expand = .no_expand, -}) !std.ChildProcess.Term { - var child = std.ChildProcess.init(args.argv, args.allocator); +}) !std.process.Child.Term { + var child = std.process.Child.init(args.argv, args.allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; @@ -3553,7 +3568,6 @@ fn spawn(args: struct { } pub const VMGetArgExt = struct { - pub fn getByte(vm: *VM, idx: u32) u8 { return vm.c.framePtr[CallArgStart + idx].asByte(); } @@ -3564,7 +3578,7 @@ pub const VMGetArgExt = struct { pub fn setInt(vm: *VM, idx: u32, i: i64) void { vm.c.framePtr[CallArgStart + idx] = Value.initInt(i); - } + } pub fn getPointer(vm: *VM, idx: u32) ?*anyopaque { return vm.c.framePtr[CallArgStart + idx].asPointer(); @@ -3584,7 +3598,7 @@ pub const VMGetArgExt = struct { pub fn setBool(vm: *VM, idx: u32, b: bool) void { vm.c.framePtr[CallArgStart + idx] = Value.initBool(b); - } + } pub fn getEnumValue(vm: *VM, idx: u32) u32 { return vm.c.framePtr[CallArgStart + idx].getEnumValue(); @@ -3596,7 +3610,7 @@ pub const VMGetArgExt = struct { pub fn setSymbol(vm: *VM, idx: u32, id: u32) void { vm.c.framePtr[CallArgStart + idx] = Value.initSymbol(id); - } + } pub fn getObject(vm: *VM, comptime Ptr: type, idx: u32) Ptr { return vm.c.framePtr[CallArgStart + idx].castHeapObject(Ptr); @@ -3614,4 +3628,4 @@ pub const VMGetArgExt = struct { pub fn getFuncPtrType(vm: *cy.VM, sig: cy.sema.FuncSigId) !cy.TypeId { const chunk = vm.sema.func_ptr_tmpl.chunk(); return cy.sema.getFuncPtrType(chunk, sig); -} \ No newline at end of file +}