pub fn generateApi(self: *Module, w: *std.Io.Writer) !void { try w.print("// hello world \n", .{}); for (0..self.enums.items.len) |i| { try generateEnum(self, w, i); } for (0..self.structs.items.len) |i| { try generateStruct(self, w, i); } } // writes into the buffer, allocates fn pointerTypeLookup(typedef: []tad.TypeRef, module: *const Module, gpa: mem.Allocator) ![]const u8 { _ = module; for (typedef) |tok| { switch (tok.tokenKind) { .label => {}, else => return error.InvalidTokenType, } } var writer: std.Io.Writer.Allocating = .init(gpa); const w = &writer.writer; _ = w; return try writer.toOwnedSlice(); } fn generateStruct(self: *Module, w: *std.Io.Writer, structIndex: usize) !void { const st = self.structs.items[structIndex]; try w.print("pub const {s} = extern struct {{\n", .{st.name}); for (st.fields.items) |field| { try w.print(" {s}: {s}\n", .{ field.name, "void, // unimplemented" }); } } fn generateEnum(self: *Module, w: *std.Io.Writer, index: usize) !void { const en = &self.enums.items[index]; const gpa = self.gpa; try w.print("pub const {s} = enum", .{en.name}); // todo... this is kind of perfect for a checkpoint allocator var seenValues: std.AutoHashMapUnmanaged(i64, usize) = .empty; defer seenValues.deinit(gpa); // todo... need to swap i64 with a struct IntegerValue { backingType: union(BackingType){...}}; var dupes: std.ArrayList(usize) = .empty; defer dupes.deinit(gpa); switch (en.backingType) { else => { return error.InvalidBackingType; }, .int, .uint => { try w.print("(c_{s}) ", .{@tagName(en.backingType)}); }, .i32, .i64, .u32, .u64, .u8, .i8 => { const tag = @tagName(en.backingType); try w.print("({s})", .{tag}); }, } try w.writeAll("{\n"); var value: i64 = 0; for (en.values.items, 0..) |v, i| { const isDefine = (v.value != value); value = v.value; if (!seenValues.contains(v.value)) { try w.print(" {s}", .{v.name}); if (isDefine) { try w.print(" = {s}{d}", .{ if (v.presentation == .hex) "0x" else "", v.value }); } try seenValues.put(gpa, value, i); try w.print(",\n", .{}); } else { try dupes.append(gpa, i); } value += 1; } const anyint = en.allowAnyInt or dupes.items.len > 0; if (anyint) { try w.print(" _,\n", .{}); } try w.print("\n", .{}); // duplicates aliases as const in zig. var fbuf: [64]u8 = undefined; for (dupes.items) |d| { const dupe = en.values.items[d]; const radix: u8 = if (dupe.presentation == .hex) 16 else 10; try w.print(" pub const {s}: @This() = {s};\n", .{ dupe.name, fbuf[0..std.fmt.printInt(&fbuf, dupe.value, radix, .lower, .{})], }); } try w.print("}};", .{}); } const std = @import("std"); const tad = @import("tad.zig"); const Token = tad.Token; const mem = std.mem; const Module = tad.Module; pub const logScopeLevels: []const std.log.ScopeLevel = &.{ .{ .scope = .tad_zig_generator, .level = .debug }, }; pub const log = std.log.scoped(.tad_zig_generator);