Skip to content

Commit

Permalink
Refactor runtime print.
Browse files Browse the repository at this point in the history
  • Loading branch information
fubark committed Mar 8, 2024
1 parent bb721cb commit 8299b5f
Show file tree
Hide file tree
Showing 14 changed files with 122 additions and 105 deletions.
2 changes: 1 addition & 1 deletion src/arc.zig
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn release(vm: *cy.VM, val: cy.Value) void {
if (cy.TrackGlobalRC) {
if (cy.Trace) {
if (vm.refCounts == 0) {
rt.errFmt(vm, "Double free. {}", &.{cy.fmt.v(obj.getTypeId())});
rt.printErrorFmt(vm, "Double free. {}\n", &.{cy.fmt.v(obj.getTypeId())});
cy.fatal();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/bc_gen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ fn genExpr(c: *Chunk, idx: usize, cstr: Cstr) anyerror!GenValue {
.varSym => genVarSym(c, idx, cstr, nodeId),
.blockExpr => genBlockExpr(c, idx, cstr, nodeId),
else => {
rt.errZFmt(c.vm, "{}", .{code});
rt.printErrorZFmt(c.vm, "{}\n", .{code});
return error.TODO;
}
};
Expand Down
3 changes: 3 additions & 0 deletions src/builtins/builtins.zig
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ pub fn dump(vm: *cy.VM, args: [*]const Value, _: u8) anyerror!Value {
const res = try allocToCyon(vm, vm.alloc, args[0]);
defer vm.alloc.free(res);
rt.print(vm, res);
rt.print(vm, "\n");
return Value.Void;
}

Expand Down Expand Up @@ -976,9 +977,11 @@ pub fn print_c(ctx: cy.Context, arg: rt.Any) callconv(.C) rt.Error {
return cy.builtins.prepThrowZError2(ctx, err, @errorReturnTrace());
};
rt.print(ctx, str);
rt.print(ctx, "\n");
} else {
const str = arg.type.toPrintString(ctx, arg);
rt.print(ctx, str.slice());
rt.print(ctx, "\n");
ctx.release(str.buf);
}
return rt.Error.initNull();
Expand Down
1 change: 1 addition & 0 deletions src/bytecode.zig
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,7 @@ pub fn dumpInst(vm: *cy.VM, pcOffset: u32, code: OpCode, pc: [*]const Inst, opts
fmt.print(w, "{}| {}", &.{fmt.repeat(' ', @intCast(ExtraStartCol-len)), v(extra)});
}
}
try w.writeByte('\n');
rt.print(vm, vm.getTempString());
}

Expand Down
5 changes: 2 additions & 3 deletions src/capi.zig
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ pub const expandTypeTemplate = c.csExpandTypeTemplate;
pub const setResolver = c.csSetResolver;
pub const setModuleLoader = c.csSetModuleLoader;
pub const setPrinter = c.csSetPrinter;
pub const setErrorFn = c.csSetErrorFn;
pub const setLogger = c.csSetLogger;
pub const setErrorPrinter = c.csSetErrorPrinter;
pub const setUserData = c.csSetUserData;
pub const getUserData = c.csGetUserData;
pub const getGlobalRC = c.csGetGlobalRC;
Expand Down Expand Up @@ -71,7 +70,7 @@ pub fn initValueSlice(slice: []const cy.Value) ValueSlice {

pub const FuncFn = c.CsFuncFn;
pub const PrintFn = c.CsPrintFn;
pub const ErrorFn = c.CsErrorFn;
pub const PrintErrorFn = c.CsPrintErrorFn;
pub const LogFn = c.CsLogFn;
pub const FuncInfo = c.CsFuncInfo;
pub const FuncResult = c.CsFuncResult;
Expand Down
6 changes: 3 additions & 3 deletions src/cgen.zig
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ const Chunk = struct {
return TypeName.init(name);
}
} else {
rt.errZFmt(c.sema.compiler.vm, "Unsupported sym type: {}", .{id});
rt.printErrorZFmt(c.sema.compiler.vm, "Unsupported sym type: {}\n", .{id});
return error.TODO;
}
}
Expand Down Expand Up @@ -638,7 +638,7 @@ pub fn gen(self: *cy.Compiler) !cy.compiler.AotCompileResult {
defer self.alloc.free(res.stdout);

if (res.term != .Exited or res.term.Exited != 0) {
rt.errMsg(self.vm, res.stderr);
rt.printError(self.vm, res.stderr);
return error.CCError;
}
}
Expand Down Expand Up @@ -917,7 +917,7 @@ fn genExpr(c: *Chunk, loc: usize, cstr: Cstr) anyerror!Value {
// .typeSym => genTypeSym(c, idx, cstr, nodeId),
// .varSym => genVarSym(c, idx, cstr, nodeId),
else => {
rt.errZFmt(c.vm, "{}", .{code});
rt.printErrorZFmt(c.vm, "{}\n", .{code});
return error.TODO;
},
};
Expand Down
34 changes: 16 additions & 18 deletions src/chunk.zig
Original file line number Diff line number Diff line change
Expand Up @@ -637,24 +637,22 @@ pub const Chunk = struct {

pub fn dumpLocals(self: *const Chunk, sproc: *sema.Proc) !void {
if (cy.Trace) {
if (!cy.silentInternal) {
rt.print(self.vm, "Locals:");
const params = self.getProcParams(sproc);
for (params) |svar| {
const typeId: types.TypeId = svar.vtype.id;
rt.printFmt(self.vm, "{} (param), local: {}, dyn: {}, rtype: {}, lifted: {}", &.{
v(svar.name()), v(svar.local), v(svar.vtype.dynamic), v(typeId),
v(svar.inner.local.lifted),
});
}
const vars = self.getProcVars(sproc);
for (vars) |svar| {
const typeId: types.TypeId = svar.vtype.id;
rt.printFmt(self.vm, "{}, local: {}, dyn: {}, rtype: {}, lifted: {}", &.{
v(svar.name()), v(svar.local), v(svar.vtype.dynamic), v(typeId),
v(svar.inner.local.lifted),
});
}
rt.print(self.vm, "Locals:\n");
const params = self.getProcParams(sproc);
for (params) |svar| {
const typeId: types.TypeId = svar.vtype.id;
rt.printFmt(self.vm, "{} (param), local: {}, dyn: {}, rtype: {}, lifted: {}\n", &.{
v(svar.name()), v(svar.local), v(svar.vtype.dynamic), v(typeId),
v(svar.inner.local.lifted),
});
}
const vars = self.getProcVars(sproc);
for (vars) |svar| {
const typeId: types.TypeId = svar.vtype.id;
rt.printFmt(self.vm, "{}, local: {}, dyn: {}, rtype: {}, lifted: {}\n", &.{
v(svar.name()), v(svar.local), v(svar.vtype.dynamic), v(typeId),
v(svar.inner.local.lifted),
});
}
}
}
Expand Down
11 changes: 3 additions & 8 deletions src/cli.zig
Original file line number Diff line number Diff line change
Expand Up @@ -60,38 +60,33 @@ fn logFn(str: c.Str) callconv(.C) void {
}
}

fn errorFn(_: ?*c.VM, str: c.Str) callconv(.C) void {
if (cy.silentError) {
fn printError(_: ?*c.VM, str: c.Str) callconv(.C) void {
if (c.silent()) {
return;
}
if (cy.isWasmFreestanding) {
os_mod.hostFileWrite(2, str.buf, str.len);
os_mod.hostFileWrite(2, "\n", 1);
} else {
const w = std.io.getStdErr().writer();
w.writeAll(c.strSlice(str)) catch cy.fatal();
w.writeByte('\n') catch cy.fatal();
w.writeAll(c.fromStr(str)) catch cy.fatal();
}
}

fn print(_: ?*c.VM, str: c.Str) callconv(.C) void {
if (cy.isWasmFreestanding) {
os_mod.hostFileWrite(1, str.buf, str.len);
os_mod.hostFileWrite(1, "\n", 1);
} else {
// Temporarily redirect to error for tests to avoid hanging the Zig runner.
if (builtin.is_test) {
const w = std.io.getStdErr().writer();
const slice = c.strSlice(str);
w.writeAll(slice) catch cy.fatal();
w.writeByte('\n') catch cy.fatal();
return;
}

const w = std.io.getStdOut().writer();
const slice = c.strSlice(str);
w.writeAll(slice) catch cy.fatal();
w.writeByte('\n') catch cy.fatal();
}
}

Expand Down
32 changes: 15 additions & 17 deletions src/debug.zig
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ pub fn printTraceAtNode(c: *cy.Chunk, nodeId: cy.NodeId) !void {

pub fn printTraceAtPc(vm: *cy.VM, pc: u32, title: []const u8, msg: []const u8) !void {
if (pc == cy.NullId) {
rt.errFmt(vm, "{}: {} (external)", &.{v(title), v(msg)});
rt.printErrorFmt(vm, "{}: {} (external)\n", &.{v(title), v(msg)});
return;
}
if (getIndexOfDebugSym(vm, pc)) |idx| {
Expand All @@ -121,7 +121,7 @@ pub fn printTraceAtPc(vm: *cy.VM, pc: u32, title: []const u8, msg: []const u8) !
const node = chunk.ast.node(sym.loc);
try printUserError(vm, title, msg, sym.file, node.srcPos);
} else {
rt.errFmt(vm, "{}: {}\nMissing debug sym for {}, pc: {}.", &.{
rt.printErrorFmt(vm, "{}: {}\nMissing debug sym for {}, pc: {}.\n", &.{
v(title), v(msg), v(vm.ops[pc].opcode()), v(pc)});
}
}
Expand All @@ -137,9 +137,8 @@ pub fn printLastUserPanicError(vm: *cy.VM) !void {
if (cy.silentError) {
return;
}
const w = vm.clearTempString();
var w = rt.ErrorWriter{ .c = vm };
try writeLastUserPanicError(vm, w);
rt.errMsg(vm, vm.getTempString());
}

fn writeLastUserPanicError(vm: *const cy.VM, w: anytype) !void {
Expand Down Expand Up @@ -186,15 +185,14 @@ pub fn printUserError(vm: *cy.VM, title: []const u8, msg: []const u8, chunkId: u
if (cy.silentError) {
return;
}
const w = vm.clearTempString();
try writeUserError(vm, w, title, msg, chunkId, pos);
rt.errMsg(vm, vm.getTempString());
var w = rt.ErrorWriter{ .c = vm };
try writeUserError(vm.compiler, w, title, msg, chunkId, pos);
}

/// Reduced to using writer so printed errors can be tested.
pub fn writeUserError(vm: *const cy.VM, w: anytype, title: []const u8, msg: []const u8, chunkId: u32, pos: u32) !void {
pub fn writeUserError(c: *const cy.Compiler, w: anytype, title: []const u8, msg: []const u8, chunkId: u32, pos: u32) !void {
if (chunkId != cy.NullId) {
const chunk = vm.compiler.chunks.items[chunkId];
const chunk = c.chunks.items[chunkId];
if (pos != NullId) {
var line: u32 = undefined;
var col: u32 = undefined;
Expand Down Expand Up @@ -510,14 +508,14 @@ pub fn dumpBytecode(vm: *cy.VM, opts: DumpBytecodeOptions) !void {
// const sblock = &chunk.semaBlocks.items[funcDecl.semaBlockId];
// try chunk.dumpLocals(sblock);
}
rt.print(vm, "");
rt.print(vm, "\n");

const node = chunk.ast.node(sym.loc);
const msg = try std.fmt.allocPrint(vm.alloc, "pc={} op={s} node={s}", .{ pcContext, @tagName(pc[pcContext].opcode()), @tagName(node.type()) });
defer vm.alloc.free(msg);
try printUserError(vm, "Trace", msg, sym.file, node.srcPos);

rt.print(vm, "Bytecode:");
rt.print(vm, "Bytecode:\n");
const ContextSize = 40;
const startSymIdx = if (idx >= ContextSize) idx - ContextSize else 0;
pcOffset = debugTable[startSymIdx].pc;
Expand Down Expand Up @@ -570,7 +568,7 @@ pub fn dumpBytecode(vm: *cy.VM, opts: DumpBytecodeOptions) !void {
}
}
} else {
rt.print(vm, "Bytecode:");
rt.print(vm, "Bytecode:\n");

var curMarkerIdx: u32 = if (vm.compiler.buf.debugMarkers.items.len > 0) 0 else cy.NullId;
var nextMarkerPc: u32 = if (curMarkerIdx == 0) vm.compiler.buf.debugMarkers.items[curMarkerIdx].pc else cy.NullId;
Expand All @@ -588,11 +586,11 @@ pub fn dumpBytecode(vm: *cy.VM, opts: DumpBytecodeOptions) !void {
instIdx += 1;
}

rt.printFmt(vm, "\nConstants ({}):", &.{v(vm.compiler.buf.mconsts.len)});
rt.printFmt(vm, "\nConstants ({}):\n", &.{v(vm.compiler.buf.mconsts.len)});
for (vm.compiler.buf.mconsts) |extra| {
const val = cy.Value{ .val = extra.val };
const str = try vm.bufPrintValueShortStr(&vm.tempBuf, val);
rt.printFmt(vm, "{}", &.{v(str)});
rt.printFmt(vm, "{}\n", &.{v(str)});
}
}
}
Expand All @@ -601,13 +599,13 @@ fn dumpMarkerAdvance(vm: *cy.VM, curMarkerIdx: *u32, nextMarkerPc: *u32) void {
const marker = vm.compiler.buf.debugMarkers.items[curMarkerIdx.*];
switch (marker.etype()) {
.label => {
rt.printFmt(vm, "{}:", &.{v(marker.getLabelName())});
rt.printFmt(vm, "{}:\n", &.{v(marker.getLabelName())});
},
.funcStart => {
rt.printFmt(vm, "---- func begin: {}", &.{v(marker.data.funcStart.func.name())});
rt.printFmt(vm, "---- func begin: {}\n", &.{v(marker.data.funcStart.func.name())});
},
.funcEnd => {
rt.printFmt(vm, "---- func end: {}", &.{v(marker.data.funcEnd.func.name())});
rt.printFmt(vm, "---- func end: {}\n", &.{v(marker.data.funcEnd.func.name())});
},
}
curMarkerIdx.* += 1;
Expand Down
6 changes: 3 additions & 3 deletions src/include/cyber.h
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,13 @@ typedef struct CsModuleLoaderResult {
// set symbol loaders, and return true. Otherwise, return false.
typedef bool (*CsModuleLoaderFn)(CsVM* vm, CsStr resolvedSpec, CsModuleLoaderResult* out);

// Handler for the builtin `print`.
// Handler for printing. The builtin `print` would invoke this.
// The default behavior is a no-op.
typedef void (*CsPrintFn)(CsVM* vm, CsStr str);

// Handler for VM errors.
// Handler for printing errors.
// The default behavior is a no-op.
typedef void (*CsErrorFn)(CsVM* vm, CsStr str);
typedef void (*CsPrintErrorFn)(CsVM* vm, CsStr str);

// Handler for compiler and runtime logs.
// The default behavior is a no-op.
Expand Down
Loading

0 comments on commit 8299b5f

Please sign in to comment.