Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
weird zig segfault
const std = @import("std");
const warn = std.debug.warn;
const fmt = std.fmt;
const mem = std.mem;
var alloc = &std.heap.DirectAllocator.init().allocator;
pub const ExprType = enum {
Binary,
Literal,
};
pub const Expr = union(ExprType) {
Binary: Binary,
Literal: Literal,
};
pub const Binary = struct {
left: *Expr,
right: *Expr,
token: []const u8,
};
pub const LiteralType = enum {
String,
Number,
};
pub const Literal = union(LiteralType) {
String: []const u8,
Number: f64,
};
pub fn expr_print(a: *mem.Allocator, e: Expr) ![]const u8 {
const s = switch (e) {
ExprType.Binary => try parenthesize(a, e.Binary.token, e),
ExprType.Literal => blk: {
switch(e.Literal) {
Literal.String => {
break :blk try fmt.allocPrint(a, "{}", e.Literal.String);
},
Literal.Number => {
break :blk try fmt.allocPrint(a, "{.}", e.Literal.Number);
}
}
},
};
return s;
}
pub fn parenthesize(a: *mem.Allocator, name: []const u8, e: Expr) fmt.AllocPrintError![]const u8 {
const buf = switch (e) {
ExprType.Binary => blk: {
var left = try expr_print(a, e.Binary.left.*);
var right = try expr_print(a, e.Binary.right.*);
defer a.free(left);
defer a.free(right);
break :blk try fmt.allocPrint(a, "({} {} {})", name, left, right);
},
ExprType.Literal => unreachable,
};
return buf;
}
pub fn parse1() !Expr {
var l = Expr{
.Literal = Literal {
.String = "left-value",
}
};
var r = Expr{
.Literal = Literal {
.Number = 20.0,
}
};
var e = Expr {
.Binary = Binary{
.left = &l,
.right = &r,
.token = "PLUS",
}
};
var s = try expr_print(alloc, e);
defer alloc.free(s);
return e;
}
pub fn parse_infinite() Expr {
var l = Expr{
.Literal = Literal {
.String = "left-value",
}
};
var r = Expr{
.Literal = Literal {
.Number = 20.0,
}
};
var e = Expr {
.Binary = Binary{
.left = &l,
.right = &r,
.token = "PLUS",
}
};
return e;
}
pub fn main() void {
// var e = try parse();
var e1 = parse1();
warn("e1: {}\n", e1);
var e2 = parse_infinite();
warn("e: {}", e2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment