code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const chrono = @import("chrono"); const TransactionTree = @import("./transaction_tree.zig").Tree; const ArrayDeque = @import("./array_deque.zig").ArrayDeque; pub const Context = struct { allocator: *std.mem.Allocator, payers: std.StringHashMap(Payer), pub fn init(allocator: *std.mem.Allocator) @This() { return @This(){ .allocator = allocator, .payers = std.StringHashMap(Payer).init(allocator), }; } pub fn deinit(this: *@This()) void { var iter = this.payers.valueIterator(); while (iter.next()) |payer| { payer.transactions.deinit(); this.allocator.free(payer.name); } this.payers.deinit(); } pub fn addPoints(this: *@This(), datetime: chrono.datetime.DateTime, payer: []const u8, points: i128) !void { const gop = try this.payers.getOrPut(payer); if (!gop.found_existing) { gop.value_ptr.name = try this.allocator.dupe(u8, payer); gop.key_ptr.* = gop.value_ptr.name; gop.value_ptr.transactions = TransactionTree.init(this.allocator); } const timestamp = datetime.toTimestamp(); // Check if this would make the points negative at the time of the transaction const balance_at_time = gop.value_ptr.transactions.getBalanceAtTime(timestamp); if (points < 0 and balance_at_time + points < 0) return error.PointsWouldBeNegative; // Check if this would make the points negative in total const balance = gop.value_ptr.transactions.getBalance(); if (points < 0 and balance + points < 0) return error.PointsWouldBeNegative; try gop.value_ptr.transactions.putNoClobber(datetime.toTimestamp(), points); } pub fn spendPoints(this: *@This(), allocator: *std.mem.Allocator, points: i128) !std.StringHashMap(i128) { if (points < 0) return error.CantSpendNegativePoints; var spent_points = std.StringHashMap(i128).init(allocator); errdefer spent_points.deinit(); var payers_oldest = std.StringHashMap(ArrayDeque(Payer.OldestPointsResult)).init(allocator); defer { var iter = payers_oldest.valueIterator(); while (iter.next()) |old_points_array| { old_points_array.deinit(); } payers_oldest.deinit(); } { var iter = this.payers.valueIterator(); while (iter.next()) |payer| { var old_points = try payer.oldestPoints(allocator); if (old_points.len() > 0) { try payers_oldest.putNoClobber(payer.name, old_points); } else { old_points.deinit(); } } } var points_left = points; while (points_left > 0) { var oldest_points_or_null: ?Payer.OldestPointsResult = null; var oldest_points_payer_name_or_null: ?[]const u8 = null; var iter = payers_oldest.iterator(); while (iter.next()) |old_points_array_entry| { const old_points = old_points_array_entry.value_ptr.idx(0).?; if (oldest_points_or_null == null or old_points.timestamp < oldest_points_or_null.?.timestamp) { oldest_points_or_null = old_points; oldest_points_payer_name_or_null = old_points_array_entry.key_ptr.*; } } if (oldest_points_or_null) |oldest_points| { const points_used = std.math.min(oldest_points.amount, points_left); const gop = try spent_points.getOrPut(oldest_points_payer_name_or_null.?); if (!gop.found_existing) { gop.value_ptr.* = 0; } gop.value_ptr.* -= points_used; const old_payer = payers_oldest.getPtr(oldest_points_payer_name_or_null.?).?; if (oldest_points.amount > points_used) { const old_points = old_payer.idxMut(0).?; old_points.amount -= points_used; } else { _ = old_payer.pop_front(); if (old_payer.len() <= 0) { old_payer.deinit(); std.debug.assert(payers_oldest.remove(oldest_points_payer_name_or_null.?)); } } points_left -= oldest_points.amount; } else { return error.PointsWouldBeNegative; } } // TODO: Make this atomic const now = std.time.timestamp(); var iter = spent_points.iterator(); while (iter.next()) |spent_points_entry| { const payer = this.payers.getPtr(spent_points_entry.key_ptr.*).?; try payer.transactions.putNoClobber(now, spent_points_entry.value_ptr.*); } return spent_points; } pub fn getBalance(this: *@This(), allocator: *std.mem.Allocator) !std.StringHashMap(i128) { var payers = std.StringHashMap(i128).init(allocator); errdefer payers.deinit(); var iter = this.payers.valueIterator(); while (iter.next()) |payer| { try payers.putNoClobber(payer.name, payer.transactions.getBalance()); } return payers; } }; pub const Payer = struct { name: []const u8, transactions: TransactionTree, pub const OldestPointsResult = struct { timestamp: i64, amount: i128, }; fn oldestPoints(this: @This(), allocator: *std.mem.Allocator) !ArrayDeque(OldestPointsResult) { var points_queue = ArrayDeque(OldestPointsResult).init(allocator); errdefer points_queue.deinit(); var current_balance: i128 = 0; var iter = this.transactions.iterator(.first); while (try iter.next()) |entry| { current_balance += entry.change; if (entry.change > 0) { try points_queue.push_back(.{ .timestamp = entry.timestamp, .amount = entry.change }); } else if (entry.change < 0) { var points_to_remove = -entry.change; while (points_to_remove > 0) { const oldest_points = points_queue.idxMut(0) orelse unreachable; // Balance should never dip below zero if (oldest_points.amount <= points_to_remove) { points_to_remove -= oldest_points.amount; _ = points_queue.pop_front(); } else { oldest_points.amount -= points_to_remove; points_to_remove = 0; } } } } return points_queue; } }; pub fn parseDateTime(dtString: []const u8) !chrono.datetime.DateTime { const naive_datetime = try chrono.format.parseNaiveDateTime("%Y-%m-%dT%H:%M:%SZ", dtString); return naive_datetime.with_timezone(chrono.timezone.UTC); } test "Use the oldest points" { var ctx = Context.init(std.testing.allocator); defer ctx.deinit(); // Add points to balance try ctx.addPoints(try parseDateTime("2020-11-02T14:00:00Z"), "DANNON", 1_000); try ctx.addPoints(try parseDateTime("2020-10-31T11:00:00Z"), "UNILEVER", 200); try ctx.addPoints(try parseDateTime("2020-10-31T10:00:00Z"), "DANNON", 300); try ctx.addPoints(try parseDateTime("2020-10-31T15:00:00Z"), "DANNON", -200); try ctx.addPoints(try parseDateTime("2020-11-01T14:00:00Z"), "<NAME>", 10_000); // Spend 5,000 points, make sure the points are from the payers expected var spentPoints = try ctx.spendPoints(std.testing.allocator, 5_000); defer spentPoints.deinit(); try std.testing.expectEqual(@as(i128, -100), spentPoints.get("DANNON").?); try std.testing.expectEqual(@as(i128, -200), spentPoints.get("UNILEVER").?); try std.testing.expectEqual(@as(i128, -4_700), spentPoints.get("<NAME>").?); // get balance var balance = try ctx.getBalance(std.testing.allocator); defer balance.deinit(); try std.testing.expectEqual(@as(i128, 1_000), balance.get("DANNON").?); try std.testing.expectEqual(@as(i128, 0), balance.get("UNILEVER").?); try std.testing.expectEqual(@as(i128, 5_300), balance.get("<NAME>").?); try std.testing.expectEqual(@as(i128, 3), balance.count()); } test "get payer's oldest points" { var payer = Payer{ .name = "hello", .transactions = TransactionTree.init(std.testing.allocator), }; defer payer.transactions.deinit(); try payer.transactions.putNoClobber(100, 1_000); try payer.transactions.putNoClobber(200, -500); try payer.transactions.putNoClobber(250, -500); try payer.transactions.putNoClobber(300, 1_000); try payer.transactions.putNoClobber(666, 666); try payer.transactions.putNoClobber(777, -666); try payer.transactions.putNoClobber(1000, 1_337); try payer.transactions.putNoClobber(1001, -500); { var oldest_points = try payer.oldestPoints(std.testing.allocator); defer oldest_points.deinit(); try std.testing.expectEqual(Payer.OldestPointsResult{ .timestamp = 666, .amount = 500 }, oldest_points.idx(0).?); } try payer.transactions.putNoClobber(1002, -501); { var oldest_points = try payer.oldestPoints(std.testing.allocator); defer oldest_points.deinit(); try std.testing.expectEqual(Payer.OldestPointsResult{ .timestamp = 1000, .amount = 1336 }, oldest_points.idx(0).?); } }
src/context.zig
const builtin = @import("builtin"); const clap = @import("../clap.zig"); const std = @import("std"); const args = clap.args; const debug = std.debug; const heap = std.heap; const io = std.io; const mem = std.mem; const os = std.os; const testing = std.testing; /// The result returned from StreamingClap.next pub fn Arg(comptime Id: type) type { return struct { const Self = @This(); param: *const clap.Param(Id), value: ?[]const u8 = null, }; } /// A command line argument parser which, given an ArgIterator, will parse arguments according /// to the params. StreamingClap parses in an iterating manner, so you have to use a loop /// together with StreamingClap.next to parse all the arguments of your program. pub fn StreamingClap(comptime Id: type, comptime ArgIterator: type) type { return struct { const State = union(enum) { normal, chaining: Chaining, rest_are_positional, const Chaining = struct { arg: []const u8, index: usize, }; }; params: []const clap.Param(Id), iter: *ArgIterator, state: State = .normal, positional: ?*const clap.Param(Id) = null, diagnostic: ?*clap.Diagnostic = null, /// Get the next Arg that matches a Param. pub fn next(parser: *@This()) !?Arg(Id) { switch (parser.state) { .normal => return try parser.normal(), .chaining => |state| return try parser.chaining(state), .rest_are_positional => { const param = parser.positionalParam() orelse unreachable; const value = parser.iter.next() orelse return null; return Arg(Id){ .param = param, .value = value }; }, } } fn normal(parser: *@This()) !?Arg(Id) { const arg_info = (try parser.parseNextArg()) orelse return null; const arg = arg_info.arg; switch (arg_info.kind) { .long => { const eql_index = mem.indexOfScalar(u8, arg, '='); const name = if (eql_index) |i| arg[0..i] else arg; const maybe_value = if (eql_index) |i| arg[i + 1 ..] else null; for (parser.params) |*param| { const match = param.names.long orelse continue; if (!mem.eql(u8, name, match)) continue; if (param.takes_value == .none) { if (maybe_value != null) return parser.err(arg, .{ .long = name }, error.DoesntTakeValue); return Arg(Id){ .param = param }; } const value = blk: { if (maybe_value) |v| break :blk v; break :blk parser.iter.next() orelse return parser.err(arg, .{ .long = name }, error.MissingValue); }; return Arg(Id){ .param = param, .value = value }; } return parser.err(arg, .{ .long = name }, error.InvalidArgument); }, .short => return try parser.chaining(.{ .arg = arg, .index = 0, }), .positional => if (parser.positionalParam()) |param| { // If we find a positional with the value `--` then we // interpret the rest of the arguments as positional // arguments. if (mem.eql(u8, arg, "--")) { parser.state = .rest_are_positional; const value = parser.iter.next() orelse return null; return Arg(Id){ .param = param, .value = value }; } return Arg(Id){ .param = param, .value = arg }; } else { return parser.err(arg, .{}, error.InvalidArgument); }, } } fn chaining(parser: *@This(), state: State.Chaining) !?Arg(Id) { const arg = state.arg; const index = state.index; const next_index = index + 1; for (parser.params) |*param| { const short = param.names.short orelse continue; if (short != arg[index]) continue; // Before we return, we have to set the new state of the clap defer { if (arg.len <= next_index or param.takes_value != .none) { parser.state = .normal; } else { parser.state = .{ .chaining = .{ .arg = arg, .index = next_index, }, }; } } const next_is_eql = if (next_index < arg.len) arg[next_index] == '=' else false; if (param.takes_value == .none) { if (next_is_eql) return parser.err(arg, .{ .short = short }, error.DoesntTakeValue); return Arg(Id){ .param = param }; } if (arg.len <= next_index) { const value = parser.iter.next() orelse return parser.err(arg, .{ .short = short }, error.MissingValue); return Arg(Id){ .param = param, .value = value }; } if (next_is_eql) return Arg(Id){ .param = param, .value = arg[next_index + 1 ..] }; return Arg(Id){ .param = param, .value = arg[next_index..] }; } return parser.err(arg, .{ .short = arg[index] }, error.InvalidArgument); } fn positionalParam(parser: *@This()) ?*const clap.Param(Id) { if (parser.positional) |p| return p; for (parser.params) |*param| { if (param.names.long) |_| continue; if (param.names.short) |_| continue; parser.positional = param; return param; } return null; } const ArgInfo = struct { arg: []const u8, kind: enum { long, short, positional, }, }; fn parseNextArg(parser: *@This()) !?ArgInfo { const full_arg = parser.iter.next() orelse return null; if (mem.eql(u8, full_arg, "--") or mem.eql(u8, full_arg, "-")) return ArgInfo{ .arg = full_arg, .kind = .positional }; if (mem.startsWith(u8, full_arg, "--")) return ArgInfo{ .arg = full_arg[2..], .kind = .long }; if (mem.startsWith(u8, full_arg, "-")) return ArgInfo{ .arg = full_arg[1..], .kind = .short }; return ArgInfo{ .arg = full_arg, .kind = .positional }; } fn err(parser: @This(), arg: []const u8, names: clap.Names, _err: anytype) @TypeOf(_err) { if (parser.diagnostic) |d| d.* = .{ .arg = arg, .name = names }; return _err; } }; } fn testNoErr( params: []const clap.Param(u8), args_strings: []const []const u8, results: []const Arg(u8), ) !void { var iter = args.SliceIterator{ .args = args_strings }; var c = StreamingClap(u8, args.SliceIterator){ .params = params, .iter = &iter, }; for (results) |res| { const arg = (try c.next()) orelse return error.TestFailed; try testing.expectEqual(res.param, arg.param); const expected_value = res.value orelse { try testing.expectEqual(@as(@TypeOf(arg.value), null), arg.value); continue; }; const actual_value = arg.value orelse return error.TestFailed; try testing.expectEqualSlices(u8, expected_value, actual_value); } if (try c.next()) |_| return error.TestFailed; } fn testErr( params: []const clap.Param(u8), args_strings: []const []const u8, expected: []const u8, ) !void { var diag: clap.Diagnostic = undefined; var iter = args.SliceIterator{ .args = args_strings }; var c = StreamingClap(u8, args.SliceIterator){ .params = params, .iter = &iter, .diagnostic = &diag, }; while (c.next() catch |err| { var buf: [1024]u8 = undefined; var fbs = io.fixedBufferStream(&buf); diag.report(fbs.writer(), err) catch return error.TestFailed; try testing.expectEqualStrings(expected, fbs.getWritten()); return; }) |_| {} try testing.expect(false); } test "short params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a' } }, .{ .id = 1, .names = .{ .short = 'b' } }, .{ .id = 2, .names = .{ .short = 'c' }, .takes_value = .one, }, .{ .id = 3, .names = .{ .short = 'd' }, .takes_value = .many, }, }; const a = &params[0]; const b = &params[1]; const c = &params[2]; const d = &params[3]; try testNoErr( &params, &.{ "-a", "-b", "-ab", "-ba", "-c", "0", "-c=0", "-ac", "0", "-ac=0", "-d=0", }, &.{ .{ .param = a }, .{ .param = b }, .{ .param = a }, .{ .param = b }, .{ .param = b }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = c, .value = "0" }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = d, .value = "0" }, }, ); } test "long params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .long = "aa" } }, .{ .id = 1, .names = .{ .long = "bb" } }, .{ .id = 2, .names = .{ .long = "cc" }, .takes_value = .one, }, .{ .id = 3, .names = .{ .long = "dd" }, .takes_value = .many, }, }; const aa = &params[0]; const bb = &params[1]; const cc = &params[2]; const dd = &params[3]; try testNoErr( &params, &.{ "--aa", "--bb", "--cc", "0", "--cc=0", "--dd=0", }, &.{ .{ .param = aa }, .{ .param = bb }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = dd, .value = "0" }, }, ); } test "positional params" { const params = [_]clap.Param(u8){.{ .id = 0, .takes_value = .one, }}; try testNoErr( &params, &.{ "aa", "bb" }, &.{ .{ .param = &params[0], .value = "aa" }, .{ .param = &params[0], .value = "bb" }, }, ); } test "all params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a', .long = "aa" }, }, .{ .id = 1, .names = .{ .short = 'b', .long = "bb" }, }, .{ .id = 2, .names = .{ .short = 'c', .long = "cc" }, .takes_value = .one, }, .{ .id = 3, .takes_value = .one }, }; const aa = &params[0]; const bb = &params[1]; const cc = &params[2]; const positional = &params[3]; try testNoErr( &params, &.{ "-a", "-b", "-ab", "-ba", "-c", "0", "-c=0", "-ac", "0", "-ac=0", "--aa", "--bb", "--cc", "0", "--cc=0", "something", "-", "--", "--cc=0", "-a", }, &.{ .{ .param = aa }, .{ .param = bb }, .{ .param = aa }, .{ .param = bb }, .{ .param = bb }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = bb }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = positional, .value = "something" }, .{ .param = positional, .value = "-" }, .{ .param = positional, .value = "--cc=0" }, .{ .param = positional, .value = "-a" }, }, ); } test "errors" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a', .long = "aa" }, }, .{ .id = 1, .names = .{ .short = 'c', .long = "cc" }, .takes_value = .one, }, }; try testErr(&params, &.{"q"}, "Invalid argument 'q'\n"); try testErr(&params, &.{"-q"}, "Invalid argument '-q'\n"); try testErr(&params, &.{"--q"}, "Invalid argument '--q'\n"); try testErr(&params, &.{"--q=1"}, "Invalid argument '--q'\n"); try testErr(&params, &.{"-a=1"}, "The argument '-a' does not take a value\n"); try testErr(&params, &.{"--aa=1"}, "The argument '--aa' does not take a value\n"); try testErr(&params, &.{"-c"}, "The argument '-c' requires a value but none was supplied\n"); try testErr( &params, &.{"--cc"}, "The argument '--cc' requires a value but none was supplied\n", ); }
clap/streaming.zig
const root = @import("@root"); const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; var argc_ptr: [*]usize = undefined; comptime { const strong_linkage = builtin.GlobalLinkage.Strong; if (builtin.link_libc) { @export("main", main, strong_linkage); } else if (builtin.os == builtin.Os.windows) { @export("WinMainCRTStartup", WinMainCRTStartup, strong_linkage); } else { @export("_start", _start, strong_linkage); } } nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> [*]usize) ); }, builtin.Arch.i386 => { argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> [*]usize) ); }, builtin.Arch.aarch64v8 => { argc_ptr = asm ("mov %[argc], sp" : [argc] "=r" (-> [*]usize) ); }, else => @compileError("unsupported arch"), } // If LLVM inlines stack variables into _start, they will overwrite // the command line argument data. @noInlineCall(posixCallMainAndExit); } extern fn WinMainCRTStartup() noreturn { @setAlignStack(16); if (!builtin.single_threaded) { _ = @import("../os/windows/tls.zig"); } std.os.windows.ExitProcess(callMain()); } // TODO https://github.com/ziglang/zig/issues/265 fn posixCallMainAndExit() noreturn { if (builtin.os == builtin.Os.freebsd) { @setAlignStack(16); } const argc = argc_ptr[0]; const argv = @ptrCast([*][*]u8, argc_ptr + 1); const envp_optional = @ptrCast([*]?[*]u8, argv + argc + 1); var envp_count: usize = 0; while (envp_optional[envp_count]) |_| : (envp_count += 1) {} const envp = @ptrCast([*][*]u8, envp_optional)[0..envp_count]; if (builtin.os == builtin.Os.linux) { // Scan auxiliary vector. const auxv = @ptrCast([*]std.elf.Auxv, envp.ptr + envp_count + 1); std.os.linux_elf_aux_maybe = auxv; var i: usize = 0; var at_phdr: usize = 0; var at_phnum: usize = 0; var at_phent: usize = 0; while (auxv[i].a_un.a_val != 0) : (i += 1) { switch (auxv[i].a_type) { std.elf.AT_PAGESZ => assert(auxv[i].a_un.a_val == std.os.page_size), std.elf.AT_PHDR => at_phdr = auxv[i].a_un.a_val, std.elf.AT_PHNUM => at_phnum = auxv[i].a_un.a_val, std.elf.AT_PHENT => at_phent = auxv[i].a_un.a_val, else => {}, } } if (!builtin.single_threaded) linuxInitializeThreadLocalStorage(at_phdr, at_phnum, at_phent); } std.os.posix.exit(callMainWithArgs(argc, argv, envp)); } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. inline fn callMainWithArgs(argc: usize, argv: [*][*]u8, envp: [][*]u8) u8 { std.os.ArgIteratorPosix.raw = argv[0..argc]; std.os.posix_environ_raw = envp; return callMain(); } extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @ptrCast([*][*]u8, c_envp)[0..env_count]; return callMainWithArgs(@intCast(usize, c_argc), c_argv, envp); } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. inline fn callMain() u8 { switch (@typeId(@typeOf(root.main).ReturnType)) { builtin.TypeId.NoReturn => { root.main(); }, builtin.TypeId.Void => { root.main(); return 0; }, builtin.TypeId.Int => { if (@typeOf(root.main).ReturnType.bit_count != 8) { @compileError("expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"); } return root.main(); }, builtin.TypeId.ErrorUnion => { root.main() catch |err| { std.debug.warn("error: {}\n", @errorName(err)); if (builtin.os != builtin.Os.zen) { if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace); } } return 1; }; return 0; }, else => @compileError("expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"), } } var tls_end_addr: usize = undefined; const main_thread_tls_align = 32; var main_thread_tls_bytes: [64]u8 align(main_thread_tls_align) = [1]u8{0} ** 64; fn linuxInitializeThreadLocalStorage(at_phdr: usize, at_phnum: usize, at_phent: usize) void { var phdr_addr = at_phdr; var n = at_phnum; var base: usize = 0; while (n != 0) : ({n -= 1; phdr_addr += at_phent;}) { const phdr = @intToPtr(*std.elf.Phdr, phdr_addr); // TODO look for PT_DYNAMIC when we have https://github.com/ziglang/zig/issues/1917 switch (phdr.p_type) { std.elf.PT_PHDR => base = at_phdr - phdr.p_vaddr, std.elf.PT_TLS => std.os.linux_tls_phdr = phdr, else => continue, } } const tls_phdr = std.os.linux_tls_phdr orelse return; std.os.linux_tls_img_src = @intToPtr([*]const u8, base + tls_phdr.p_vaddr); assert(main_thread_tls_bytes.len >= tls_phdr.p_memsz); // not enough preallocated Thread Local Storage assert(main_thread_tls_align >= tls_phdr.p_align); // preallocated Thread Local Storage not aligned enough @memcpy(&main_thread_tls_bytes, std.os.linux_tls_img_src, tls_phdr.p_filesz); tls_end_addr = @ptrToInt(&main_thread_tls_bytes) + tls_phdr.p_memsz; linuxSetThreadArea(@ptrToInt(&tls_end_addr)); } fn linuxSetThreadArea(addr: usize) void { switch (builtin.arch) { builtin.Arch.x86_64 => { const ARCH_SET_FS = 0x1002; const rc = std.os.linux.syscall2(std.os.linux.SYS_arch_prctl, ARCH_SET_FS, addr); // acrh_prctl is documented to never fail assert(rc == 0); }, else => @compileError("Unsupported architecture"), } }
std/special/bootstrap.zig
const std = @import("std"); const warn = std.debug.warn; const wgi = @import("WindowGraphicsInput/WindowGraphicsInput.zig"); const window = wgi.window; const input = wgi.input; const image = wgi.image; const c = wgi.c; const Constants = wgi.Constants; const vertexarray = wgi.vertexarray; const buffer = wgi.buffer; const render = @import("RTRenderEngine/RTRenderEngine.zig"); const ModelData = @import("ModelFiles/ModelFiles.zig").ModelData; const c_allocator = std.heap.c_allocator; const maths = @import("Mathematics/Mathematics.zig"); const Matrix = maths.Matrix; const Vector = maths.Vector; const Files = @import("Files.zig"); const loadFile = Files.loadFile; const compress = @import("Compress/Compress.zig"); const assets = @import("Assets/Assets.zig"); const Asset = assets.Asset; const HSV2RGB = @import("Colour.zig").HSV2RGB; const scenes = @import("Scene/Scene.zig"); var camera_position: [3]f32 = [3]f32{ 0.0, 1.75, 10.0 }; var camera_rotation_euler: [3]f32 = [3]f32{ 0.0, 0.0, 0.0 }; var cursor_enabled: bool = true; fn mouseCallback(button: i32, action: i32, mods: i32) void { if (button == 1 and action == Constants.RELEASE) { cursor_enabled = !cursor_enabled; input.setCursorEnabled(cursor_enabled); } } fn moveNoUp(x: f32, y: f32, z: f32) void { if (z != 0.0) { camera_position[0] += (z * std.math.sin(camera_rotation_euler[1])); camera_position[2] += (z * std.math.cos(camera_rotation_euler[1])); } if (x != 0.0) { camera_position[0] += (x * std.math.sin(camera_rotation_euler[1] + 1.57079632679)); camera_position[2] += (x * std.math.cos(camera_rotation_euler[1] + 1.57079632679)); } if (y != 0.0) { camera_position[0] += y * std.math.sin(camera_rotation_euler[2]); camera_position[2] += -std.math.sin(camera_rotation_euler[0]) * y; } } var fullscreen: bool = false; fn keyCallback(key: i32, scancode: i32, action: i32, mods: i32) void { if (action == Constants.RELEASE and key == Constants.KEY_F11) { if (fullscreen) { window.exitFullScreen(1024, 768); } else { window.goFullScreen(); } fullscreen = !fullscreen; } } fn assetFileLoaded(a: *Asset) void { std.debug.warn("Asset file loaded: {}\n", .{a.*.file_path[0..a.*.file_path_len]}); } fn assetLoaded(a: *Asset) void { std.debug.warn("Asset loaded: {}\n", .{a.*.file_path[0..a.*.file_path_len]}); } pub fn main() !void { errdefer @import("ErrorDialog.zig").showErrorMessageDialog("Fatal Error", "An error has occurred."); // Specify root folder for assets assets.setAssetsDirectory("DemoAssets" ++ Files.path_seperator); // Loads the scene file // This is a text file which containts a list of assets and game objects const scene_file = try loadFile("DemoAssets" ++ Files.path_seperator ++ "Farm.scene", c_allocator); defer c_allocator.free(scene_file); var assets_list = std.ArrayList(Asset).init(c_allocator); defer assets_list.deinit(); // Gets the assets list from the scene file and creates asset objects try scenes.getAssets(scene_file, &assets_list); const num_scene_assets = assets_list.items.len; defer { // Free all assets (even if they are being used) for (assets_list.items) |*a| { a.*.free(true); } } for (assets_list.items) |*a| { a.*.whenFileLoaded = assetFileLoaded; a.*.whenAssetDecoded = assetLoaded; } try assets.startAssetLoader1(assets_list.items, c_allocator); try window.createWindow(false, 1024, 768, "Demo 1", true, 0); defer window.closeWindow(); window.setResizeable(true); window.loadIcon("DemoAssets" ++ Files.path_seperator ++ "icon.jpg", c_allocator) catch |e| { warn("Error loading icon: {}\n", .{e}); }; input.setKeyCallback(keyCallback); input.setMouseButtonCallback(mouseCallback); try render.init(wgi.getMicroTime(), c_allocator); defer render.deinit(c_allocator); const settings = render.getSettings(); scenes.getAmbient(scene_file, &settings.*.ambient); scenes.getClearColour(scene_file, &settings.*.clear_colour); std.mem.copy(f32, settings.*.fog_colour[0..3], &settings.*.clear_colour); settings.*.fog_colour[3] = 1; settings.enable_point_lights = false; settings.enable_spot_lights = true; settings.max_fragment_lights = 2; settings.max_vertex_lights = 0; settings.enable_specular_light = false; var root_object: render.Object = render.Object.init("root"); defer root_object.delete(true); var camera: render.Object = render.Object.init("camera"); try root_object.addChild(&camera); render.setActiveCamera(&camera); var spotlight: render.Object = render.Object.init("light"); spotlight.light = render.Light{ .light_type = render.Light.LightType.Spotlight, .colour = [3]f32{ 100, 100, 100 }, .attenuation = 1, .cast_realtime_shadows = true, .shadow_near = 0.5, .shadow_far = 20.0, .shadow_resolution_width = 1024, }; //try root_object.addChild(&spotlight); // Wait for game assets to finish loading // Keep calling pollEvents() to stop the window freezing // This would be where a loading bar is shown while (!assets.assetsLoaded()) { window.pollEvents(); if (window.windowShouldClose()) { return; } // 0.1s std.time.sleep(100000000); } assets.assetLoaderCleanup(); // Check all assets were loaded successfully for (assets_list.items) |*a| { if (a.state != Asset.AssetState.Ready) { return error.AssetLoadError; } } // Load the farm const scene = try scenes.loadSceneFromFile(scene_file, assets_list.items[0..num_scene_assets], c_allocator); try root_object.addChild(scene); // Free assets (data has been uploaded the GPU) // This frees the cpu-side copy of model data and textures which is now stored on the GPU for (assets_list.items) |*a| { a.freeData(); } const windmill_blades = scene.findChild("Windmill_Blades"); if (windmill_blades == null) { return error.NoWindmillBlades; } // Copy of the windmill blades default position/rotation/scale const windmill_blades_default_transform = windmill_blades.?.*.transform; // Artistic choice windmill_blades.?.mesh_renderer.?.recieve_shadows = false; const static_geometry = scene.findChild("FarmStatic"); if (static_geometry == null) { return error.NoStaticGeometry; } static_geometry.?.mesh_renderer.?.enable_per_object_light = false; const light = scene.findChild("Light"); if (light != null) { // These values have been tweaked to provide a near-optimal depth texture // TODO This information should be moved into the scene file light.?.light.?.shadow_width = 54.0; light.?.light.?.shadow_height = 30.0; light.?.light.?.shadow_resolution_width = 1024; } var mouse_pos_prev: [2]i32 = input.getMousePosition(); var brightness: f32 = 1.0; var contrast: f32 = 1.0; var last_frame_time = wgi.getMicroTime(); var last_fps_print_time = last_frame_time; var fps_count: u32 = 0; // Game loop var rotation: f32 = 0; while (!window.windowShouldClose()) { if (input.isKeyDown(Constants.KEY_ESCAPE)) { break; } const micro_time = wgi.getMicroTime(); const this_frame_time = micro_time; const deltaTime = @intToFloat(f32, this_frame_time - last_frame_time) * 0.000001; last_frame_time = this_frame_time; if (this_frame_time - last_fps_print_time >= 990000) { warn("{}\n", .{fps_count + 1}); fps_count = 0; last_fps_print_time = this_frame_time; } else { fps_count += 1; } if (input.isKeyDown(Constants.KEY_LEFT_BRACKET)) { brightness -= 0.08; if (brightness < 0.0) { brightness = 0.0; } } else if (input.isKeyDown(Constants.KEY_RIGHT_BRACKET)) { brightness += 0.08; } if (input.isKeyDown(Constants.KEY_COMMA)) { contrast -= 0.01; if (contrast < 0.0) { contrast = 0.0; } } else if (input.isKeyDown(Constants.KEY_PERIOD)) { contrast += 0.01; } render.setImageCorrection(brightness, contrast); // FPS-style camera rotation const mouse_pos = input.getMousePosition(); if (!cursor_enabled) { camera_rotation_euler[1] += -0.1 * deltaTime * @intToFloat(f32, mouse_pos[0] - mouse_pos_prev[0]); camera_rotation_euler[0] += 0.1 * deltaTime * @intToFloat(f32, mouse_pos[1] - mouse_pos_prev[1]); const max_angle = 1.4; if (camera_rotation_euler[0] > max_angle) { camera_rotation_euler[0] = max_angle; } else if (camera_rotation_euler[0] < -max_angle) { camera_rotation_euler[0] = -max_angle; } } mouse_pos_prev = mouse_pos; // FPS-style movement var speed: f32 = 1.0; if (input.isKeyDown(Constants.KEY_LEFT_CONTROL)) { speed = 10.0; } if (input.isKeyDown(Constants.KEY_W)) { moveNoUp(0.0, 0.0, -1.875 * deltaTime * speed); } else if (input.isKeyDown(Constants.KEY_S)) { moveNoUp(0.0, 0.0, 1.875 * deltaTime * speed); } if (input.isKeyDown(Constants.KEY_D)) { moveNoUp(1.875 * deltaTime * speed, 0.0, 0.0); } else if (input.isKeyDown(Constants.KEY_A)) { moveNoUp(-1.875 * deltaTime * speed, 0.0, 0.0); } var m = Matrix(f32, 4).rotateY(camera_rotation_euler[1]); m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ camera_position[0], camera_position[1] - 0.4, camera_position[2] }))); spotlight.setTransform(m); // Levitation (does not take camera rotation into account) if (input.isKeyDown(Constants.KEY_SPACE)) { camera_position[1] += 1.875 * deltaTime * speed; } else if (input.isKeyDown(Constants.KEY_LEFT_SHIFT)) { camera_position[1] -= 1.875 * deltaTime * speed; } // Transforms must be done in this order: // Scale // Rotate x // Rotate y // Rotate z // Translation m = Matrix(f32, 4).rotateX(camera_rotation_euler[0]); m = m.mul(Matrix(f32, 4).rotateY(camera_rotation_euler[1])); m = m.mul(Matrix(f32, 4).rotateZ(camera_rotation_euler[2])); m = m.mul(Matrix(f32, 4).translate(Vector(f32, 3).init(camera_position))); camera.setTransform(m); // Use deltaTime to make rotation speed consistent, regardless of frame rate. rotation += deltaTime * 0.1; windmill_blades.?.setTransform(Matrix(f32, 4).rotateZ(rotation).mul(windmill_blades_default_transform)); try render.render(&root_object, micro_time, c_allocator); window.swapBuffers(); window.pollEvents(); } }
src/Demo1.zig
const std = @import("std"); const os = std.os; const Flag = @import("Flag.zig"); uring: os.linux.IO_Uring, // For IO-bound tasks // TODO: thread waiting: bool = false, // Whether the last resumed wait task is still waiting wait_q: TaskQueue = .{}, // For task-bound tasks cpu_q: TaskQueue = .{}, // For CPU-bound tasks debug: if (std.debug.runtime_safety) struct { io_count: usize = 0, fn submitIo(db: *@This()) void { db.io_count += 1; } fn completeIo(db: *@This()) void { db.io_count -= 1; } fn assertThereAreTasks(db: *const @This()) void { const self = @fieldParentPtr(EventLoop, "debug", db); std.debug.assert(self.debug.io_count > 0 or self.wait_q.len > 0 or self.cpu_q.len > 0); } } else struct { fn submitIo(_: @This()) void {} fn completeIo(_: @This()) void {} fn assertThereAreTasks(_: @This()) void {} } = .{}, const EventLoop = @This(); const TaskQueue = std.TailQueue(anyframe); pub fn init() !EventLoop { const uring = try os.linux.IO_Uring.init(4096, 0); return EventLoop{ .uring = uring }; } pub fn deinit(self: *EventLoop) void { std.debug.assert(self.wait_q.len == 0); std.debug.assert(self.cpu_q.len == 0); self.uring.deinit(); } pub fn run(self: *EventLoop, comptime func: anytype, args: anytype) !void { var done = false; // TODO: thread var frame = async struct { fn wrapper(wargs: anytype, wdone: *bool) !void { try @call(.{}, func, wargs); wdone.* = true; } }.wrapper(args, &done); // TODO: thread - this will probably need a lot of work while (!done) { // This could trigger if a function suspends without informing the event loop self.debug.assertThereAreTasks(); // Prioritize whichever queue is longest switch (longest(.{ .io = self.uring.cq_ready(), .wait = if (!self.waiting) self.wait_q.len else 0, .cpu = self.cpu_q.len, })) { .io => { const cqe = try self.uring.copy_cqe(); const data = @intToPtr(*SubmissionData, cqe.user_data); data.res = cqe.res; resume data.frame; }, .wait => { var node_opt = self.wait_q.first; while (node_opt) |node| { resume node.data; if (self.waiting) { node_opt = node.next; } else { break; } } continue; // We've not run any tasks so skip to the next loop iteration }, .cpu => resume self.cpu_q.pop().?.data, } self.waiting = false; // We've run a task, so we can retry waiting tasks now } nosuspend { try await frame; } } fn longest(queues: anytype) std.meta.FieldEnum(@TypeOf(queues)) { const T = @TypeOf(queues); const E = std.meta.FieldEnum(T); const fields = comptime std.meta.fieldNames(T); var n: usize = @field(queues, fields[0]); var q = @field(E, fields[0]); inline for (fields[1..]) |field| { if (n < @field(queues, field)) { n = @field(queues, field); q = @field(E, field); } } return q; } /// Yield to the event loop, allowing other tasks to run. /// Can be used by CPU-bound tasks to run concurrently with other tasks. pub fn yield(self: *EventLoop) void { var node = TaskQueue.Node{ .data = @frame() }; self.cpu_q.prepend(&node); suspend {} } /// Create a waiter, which can be used to wait for other tasks to progress. pub fn wait(self: *EventLoop) Waiter { return .{ .loop = self }; } // TODO: thread pub const Waiter = struct { loop: *EventLoop, node: TaskQueue.Node = .{ .data = undefined }, /// Yield to the event loop, waiting for at least one other task to progress. /// Can be used by task-bound tasks to wait on one or more other tasks. /// After this returns, either retry or finish must be called before any suspending functions. pub fn start(self: *Waiter) void { self.node.data = @frame(); self.loop.wait_q.prepend(&self.node); suspend {} } /// Yield back to the event loop after start returns. Call this if the waited-upon tasks have not progressed sufficiently. /// After this returns, either retry or finish must be called before any suspending functions. pub fn retry(self: *Waiter) void { self.loop.waiting = true; self.node.data = @frame(); suspend {} } /// Finish the wait. Call this if the waited-upon tasks have progressed sufficiently to allow work to be done on this task. /// After this is called, start must be called again if the waiter is to be reused. pub fn finish(self: *Waiter) void { self.loop.waiting = false; self.loop.wait_q.remove(&self.node); } }; pub fn runDetached(self: *EventLoop, allocator: *std.mem.Allocator, comptime func: anytype, args: anytype) !void { _ = self; const Args = @TypeOf(args); const wrapper = struct { fn wrapper(loop: *EventLoop, walloc: *std.mem.Allocator, wargs: Args) void { loop.yield(); @call(.{}, func, wargs); suspend { walloc.destroy(@frame()); } } }.wrapper; const frame = try allocator.create(@Frame(wrapper)); frame.* = async wrapper(self, allocator, args); } /// Wait for completion of any of the provided futures or flags // TODO: add support for WaitGroup? // TODO: use anyframe instead of Future. See ziglang/zig#3164 // TODO: thread pub fn any(self: *EventLoop, alternatives: anytype) AnyRet(@TypeOf(alternatives)) { const Alts = @TypeOf(alternatives); const Ret = AnyRet(Alts); const fields = comptime std.meta.fields(Alts); // Launch waiters inline for (fields) |field| { const f = @field(alternatives, field.name); if (field.field_type == *Flag) { if (f.value) { return @unionInit(Ret, field.name, {}); } } else { if (f.value) |value| { return @unionInit(Ret, field.name, value); } if (!f.waiting) { _ = async @field(alternatives, field.name).wait(); } } } // Wait for completion var w = self.wait(); w.start(); defer w.finish(); while (true) { // Slow for large numbers of alternatives, might be worth using a flag inline for (fields) |field| { const f = @field(alternatives, field.name); if (field.field_type == *Flag) { if (f.value) { return @unionInit(Ret, field.name, {}); } } else { if (f.value) |value| { return @unionInit(Ret, field.name, value); } } } w.retry(); } } // TODO: support pointer to struct as well as struct of pointers pub fn AnyRet(comptime Alts: type) type { var fields: [std.meta.fields(Alts).len]std.builtin.TypeInfo.UnionField = undefined; for (std.meta.fields(Alts)) |field, i| { const ptr = @typeInfo(field.field_type).Pointer; if (ptr.is_const or ptr.size != .One or !(ptr.child == Flag or @hasDecl(ptr.child, "Value"))) { @compileError(std.fmt.comptimePrint("Expected pointer to flag or future, got {s} (field '{}')", .{ @typeName(field.field_type), std.fmt.fmtSliceEscapeLower(field.name), })); } const T = if (ptr.child == Flag) void else ptr.child.Value; fields[i] = .{ .name = field.name, .field_type = T, .alignment = if (@sizeOf(T) > 0) @alignOf(T) else 0, }; } // Workaround for ziglang/zig#8114. Why does it work? No clue! var ti = @typeInfo(union { _: void }); ti.Union.tag_type = std.meta.FieldEnum(Alts); ti.Union.fields = &fields; return @Type(ti); } // IO resources pub const connect = @import("Socket.zig").open; pub const listen = @import("Listener.zig").open; pub const signalOpen = @import("SignalFile.zig").open; // Sync primitives pub const flag = Flag.init; pub const waitGroup = @import("WaitGroup.zig").init; //// For internal use //// pub fn close(self: *EventLoop, fd: os.fd_t) void { const res = self.submit(.close, .{fd}) catch { os.close(fd); // We want to close even if it means blocking return; }; switch (errno(res)) { os.EBADF => unreachable, // Always a race condition. os.EINTR => {}, // This is still a success. See https://github.com/ziglang/zig/issues/2425 else => {}, } } pub fn read(self: *EventLoop, fd: os.fd_t, buf: []u8) ReadError!u31 { const res = try self.submit(.read, .{ fd, buf, 0 }); switch (errno(res)) { 0 => return @intCast(u31, res), os.EINVAL => unreachable, os.EFAULT => unreachable, os.EAGAIN => return error.WouldBlock, os.EBADF => return error.NotOpenForReading, // Can be a race condition. os.EIO => return error.InputOutput, os.EISDIR => return error.IsDir, os.ENOBUFS => return error.SystemResources, os.ENOMEM => return error.SystemResources, else => |err| return os.unexpectedErrno(err), } } pub const ReadError = error{ WouldBlock, NotOpenForReading, InputOutput, IsDir, SystemResources, } || SubmitError; pub fn recv(self: *EventLoop, fd: os.socket_t, buf: []u8) RecvError!u31 { const res = try self.submit(.recv, .{ fd, buf, 0 }); switch (errno(res)) { 0 => return @intCast(u31, res), os.EBADF => unreachable, // always a race condition os.EFAULT => unreachable, os.EINVAL => unreachable, os.ENOTCONN => unreachable, os.ENOTSOCK => unreachable, os.EAGAIN => return error.WouldBlock, os.ENOMEM => return error.SystemResources, os.ECONNREFUSED => return error.ConnectionRefused, os.ECONNRESET => return error.ConnectionResetByPeer, else => |err| return os.unexpectedErrno(err), } } pub const RecvError = error{ WouldBlock, SystemResources, ConnectionRefused, ConnectionResetByPeer, } || SubmitError; pub fn send(self: *EventLoop, fd: os.socket_t, buf: []const u8) SendError!u31 { const res = try self.submit(.send, .{ fd, buf, 0 }); return switch (errno(res)) { 0 => @intCast(u31, res), os.EACCES => error.AccessDenied, os.EAGAIN => error.WouldBlock, os.EALREADY => error.FastOpenAlreadyInProgress, os.EBADF => unreachable, // always a race condition os.ECONNRESET => error.ConnectionResetByPeer, os.EDESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set. os.EFAULT => unreachable, // An invalid user space address was specified for an argument. os.EINVAL => unreachable, // Invalid argument passed. os.EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified os.EMSGSIZE => error.MessageTooBig, os.ENOBUFS => error.SystemResources, os.ENOMEM => error.SystemResources, os.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket. os.EOPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type. os.EPIPE => error.BrokenPipe, os.EHOSTUNREACH => error.NetworkUnreachable, os.ENETUNREACH => error.NetworkUnreachable, os.ENETDOWN => error.NetworkSubsystemFailed, else => |err| os.unexpectedErrno(err), }; } pub const SendError = os.SendError || SubmitError; pub fn accept(self: *EventLoop, fd: os.socket_t, addr: *os.sockaddr, addrlen: *os.socklen_t) !os.socket_t { return self.submit(.accept, .{ fd, addr, addrlen, 0 }); } pub fn connectRaw(self: *EventLoop, fd: os.socket_t, addr: *const os.sockaddr, addrlen: os.socklen_t) !void { const ret = try self.submit(.connect, .{ fd, addr, addrlen }); _ = ret; // TODO } const SubmitError = @typeInfo(@typeInfo(@TypeOf(os.linux.IO_Uring.submit)).Fn.return_type.?).ErrorUnion.error_set; fn submit(self: *EventLoop, comptime op: DeclEnum(os.linux.IO_Uring), args: anytype) SubmitError!i32 { var data = SubmissionData{ .frame = @frame() }; const func = @field(os.linux.IO_Uring, @tagName(op)); const fargs = .{ &self.uring, @ptrToInt(&data) } ++ args; var waiter = self.wait(); _ = @call(.{}, func, fargs) catch |err| switch (err) { error.SubmissionQueueFull => { waiter.start(); while (true) { if (@call(.{}, func, fargs)) |_| { break; } else |_| { waiter.retry(); } } waiter.finish(); }, }; self.debug.submitIo(); defer self.debug.completeIo(); suspend _ = try self.uring.submit(); // TODO: batch submissions? return data.res; } const SubmissionData = struct { frame: anyframe->SubmitError!i32, res: i32 = undefined, }; fn DeclEnum(comptime T: type) type { const decls = std.meta.declarations(T); var fields: [decls.len]std.builtin.TypeInfo.EnumField = undefined; for (decls) |decl, i| { fields[i] = .{ .name = decl.name, .value = i }; } return @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = std.math.IntFittingRange(0, fields.len - 1), .fields = &fields, .decls = &.{}, .is_exhaustive = true, } }); } fn errno(res: i32) u12 { return if (-4096 < res and res < 0) @intCast(u12, -res) else 0; }
src/io/EventLoop.zig
const std = @import("std"); const zpm = @import(".zpm/pkgs.zig"); const packages = zpm.pkgs; const examples = [_][]const u8{ // "apps/hello-world/main", // "apps/ascii-printer/main", }; pub fn addTest(b: *std.build.Builder, global_step: *std.build.Step, comptime tool_name: []const u8, src: []const u8) *std.build.LibExeObjStep { const test_runner = b.addTest(src); const test_step = b.step("test-" ++ tool_name, "Runs the test suite for " ++ tool_name); test_step.dependOn(&test_runner.step); global_step.dependOn(&test_runner.step); return test_runner; } pub fn build(b: *std.build.Builder) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const hex2bin = b.addExecutable("hex2bin", "tools/hex2bin/main.zig"); hex2bin.addPackage(packages.args); hex2bin.addPackage(packages.ihex); hex2bin.setTarget(target); hex2bin.setBuildMode(mode); hex2bin.install(); const emulator = b.addExecutable("emulator", "tools/emulator/pc-main.zig"); emulator.addPackage(packages.args); emulator.addPackage(packages.ihex); emulator.addPackage(packages.@"spu-mk2"); emulator.setTarget(target); emulator.setBuildMode(mode); emulator.install(); const disassembler = b.addExecutable("disassembler", "tools/disassembler/main.zig"); disassembler.addPackage(packages.args); disassembler.addPackage(packages.ihex); disassembler.addPackage(packages.@"spu-mk2"); disassembler.setTarget(target); disassembler.setBuildMode(mode); disassembler.install(); const assembler = b.addExecutable("assembler", "tools/assembler/main.zig"); assembler.addPackage(packages.args); assembler.addPackage(packages.ihex); assembler.addPackage(packages.@"spu-mk2"); assembler.setTarget(target); assembler.setBuildMode(mode); assembler.install(); const test_step = b.step("test", "Runs the full test suite"); { const asm_test = addTest(b, test_step, "assembler", "tools/assembler/main.zig"); asm_test.addPackage(zpm.pkgs.@"spu-mk2"); asm_test.addPackage(zpm.pkgs.args); _ = addTest(b, test_step, "debugger", "tools/debugger/main.zig"); _ = addTest(b, test_step, "emulator", "tools/emulator/pc-main.zig"); } inline for (examples) |src_file| { const step = assembler.run(); step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/" ++ std.fs.path.basename(std.fs.path.dirname(src_file).?) ++ ".hex", src_file ++ ".asm", }); b.getInstallStep().dependOn(&step.step); } const assemble_step = assembler.run(); assemble_step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/ashet-bios.hex", "./apps/ashet-bios/main.asm", }); // const refresh_cmd = make_vhd.run(); // refresh_cmd.step.dependOn(&gen_firmware_blob.step); // refresh_cmd.addArgs(&[_][]const u8{ // "--output", // "./soc/vhdl/src/builtin-rom.vhd", // "./zig-out/firmware/firmware.bin", // }); // const gen_mem_file = hex2mem.run(); // gen_mem_file.step.dependOn(&assemble_step.step); // gen_mem_file.addArgs(&[_][]const u8{ // "--output", // "./soc/vhdl/firmware.mem", // "./zig-out/firmware/firmware.hex", // }); // b.getInstallStep().dependOn(&gen_mem_file.step); // b.getInstallStep().dependOn(&refresh_cmd.step); const emulate_cmd = emulator.run(); emulate_cmd.step.dependOn(&assemble_step.step); emulate_cmd.addArgs(&[_][]const u8{ "./zig-out/firmware/firmware.hex", }); { const assemble_wasm_step = assembler.run(); assemble_wasm_step.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/wasm.hex", "./apps/web-firmware/main.asm", }); const gen_wasm_firmware_blob = hex2bin.run(); gen_wasm_firmware_blob.step.dependOn(&assemble_wasm_step.step); gen_wasm_firmware_blob.addArgs(&[_][]const u8{ "-o", "./zig-out/firmware/wasm.bin", "./zig-out/firmware/wasm.hex", }); const wasm_emulator = b.addSharedLibrary("emulator", "tools/emulator/web-main.zig", .unversioned); wasm_emulator.addPackage(packages.ihex); wasm_emulator.addPackage(packages.@"spu-mk2"); wasm_emulator.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }); wasm_emulator.setBuildMode(mode); wasm_emulator.step.dependOn(&gen_wasm_firmware_blob.step); wasm_emulator.install(); const wasm_step = b.step("wasm", "Builds the WASM emulator"); wasm_step.dependOn(&wasm_emulator.install_step.?.step); } // Cross-target // { // const cross_step = b.step("cross-build", "Builds all the toolchain for all cross targets."); // const MyTarget = struct { // target: std.zig.CrossTarget, // folder: []const u8, // }; // const targets = [_]MyTarget{ // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-windows" }), .folder = "build/x86_64-windows" }, // // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-macosx" }), .folder = "build/x86_64-macosx" }, // not supported by zig-serial atm // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-linux" }), .folder = "build/x86_64-linux" }, // .{ .target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-windows" }), .folder = "build/i386-windows" }, // linker error _GetCommState // }; // for (targets) |cross_target| { // const crossToolchain = try buildToolchain(b, sdl_sdk, cross_target.folder, cross_target.target, mode); // cross_step.dependOn(&crossToolchain.debugger.step); // cross_step.dependOn(&crossToolchain.emulator.step); // cross_step.dependOn(&crossToolchain.disassembler.step); // cross_step.dependOn(&crossToolchain.assembler.step); // cross_step.dependOn(&crossToolchain.hex2bin.step); // cross_step.dependOn(&crossToolchain.ashet_emulator.step); // } // } }
build.zig
const std = @import("std"); const getElapsedTime = @import("kira/glfw.zig").getElapsedTime; const glfw = @import("kira/glfw.zig"); const renderer = @import("kira/renderer.zig"); const gl = @import("kira/gl.zig"); const input = @import("kira/input.zig"); const window = @import("kira/window.zig"); usingnamespace @import("kira/log.zig"); const check = @import("kira/utils.zig").check; usingnamespace @import("sharedtypes.zig"); usingnamespace @import("renderer.zig"); fn pcloseCallback(handle: ?*c_void) void { pwinrun = false; if (procs.close) |fun| { fun(); } } fn presizeCallback(handle: ?*c_void, w: i32, h: i32) void { gl.viewport(0, 0, w, h); if (procs.resize) |fun| { fun(w, h); } } fn keyboardCallback(handle: ?*c_void, key: i32, sc: i32, ac: i32, mods: i32) void { pinput.handleKeyboard(key, ac) catch unreachable; } fn mousebuttonCallback(handle: ?*c_void, key: i32, ac: i32, mods: i32) void { pinput.handleMButton(key, ac) catch unreachable; } fn mousePosCallback(handle: ?*c_void, x: f64, y: f64) void { pmouseX = @floatCast(f32, x); pmouseY = @floatCast(f32, y); } pub const Callbacks = struct { update: ?fn (deltatime: f32) anyerror!void = null, fixed: ?fn (fixedtime: f32) anyerror!void = null, draw: ?fn () anyerror!void = null, resize: ?fn (w: i32, h: i32) void = null, close: ?fn () void = null, }; var pwin: *Window = undefined; var pwinrun = false; var pframetime = window.FrameTime{}; var pfps = window.FpsDirect{}; var pinput: *Input = undefined; var pmouseX: f32 = 0; var pmouseY: f32 = 0; var pengineready = false; var ptargetfps: f64 = 0.0; // error: inferring error set of return type valid only for function definitions // var pupdateproc: ?fn (deltatime: f32) !void = null; // ^ var procs = Callbacks{}; var allocator: *std.mem.Allocator = undefined; /// Initializes the engine pub fn init(callbacks: Callbacks, width: i32, height: i32, title: []const u8, fpslimit: u32, alloc: *std.mem.Allocator) !void { if (pengineready) return Error.EngineIsInitialized; allocator = alloc; pwin = try allocator.create(Window); pinput = try allocator.create(Input); try glfw.init(); glfw.resizable(false); glfw.initGLProfile(); pwin.* = window.Info{}; pwin.size.width = width; pwin.size.height = height; pwin.minsize = pwin.size; pwin.maxsize = pwin.size; pwin.title = title; pwin.callbacks.close = pcloseCallback; pwin.callbacks.resize = presizeCallback; pwin.callbacks.keyinp = keyboardCallback; pwin.callbacks.mouseinp = mousebuttonCallback; pwin.callbacks.mousepos = mousePosCallback; const sw = glfw.getScreenWidth(); const sh = glfw.getScreenHeight(); pwin.position.x = @divTrunc((sw - pwin.size.width), 2); pwin.position.y = @divTrunc((sh - pwin.size.height), 2); pinput.* = Input{}; pinput.clearAllBindings(); try pwin.create(false); glfw.makeContext(pwin.handle); gl.init(); gl.setBlending(true); if (fpslimit == 0) { glfw.vsync(true); } else { glfw.vsync(false); } try initRenderer(allocator, pwin); setCallbacks(callbacks); if (fpslimit != 0) ptargetfps = 1.0 / @intToFloat(f32, fpslimit); pengineready = true; std.log.info("kiragine -> initialized! Size -> width:{} & height:{} ; Title:{}", .{ pwin.size.width, pwin.size.height, pwin.title }); } /// Deinitializes the engine pub fn deinit() Error!void { if (!pengineready) return Error.EngineIsNotInitialized; deinitRenderer(); try pwin.destroy(); gl.deinit(); glfw.deinit(); std.log.info("kiragine -> deinitialized!", .{}); allocator.destroy(pwin); allocator.destroy(pinput); } /// Opens the window pub fn open() Error!void { if (!pengineready) return Error.EngineIsNotInitialized; pwinrun = true; } /// Closes the window pub fn close() Error!void { if (!pengineready) return Error.EngineIsNotInitialized; pwinrun = false; } /// Updates the engine pub fn update() !void { if (!pengineready) return Error.EngineIsNotInitialized; // Source: https://gafferongames.com/post/fix_your_timestep/ var last: f64 = getElapsedTime(); var accumulator: f64 = 0; var dt: f64 = 0.01; while (pwinrun) { pframetime.start(); var ftime: f64 = pframetime.current - last; if (ftime > 0.25) { ftime = 0.25; } last = pframetime.current; accumulator += ftime; if (procs.update) |fun| { try fun(@floatCast(f32, pframetime.delta)); } if (procs.fixed) |fun| { while (accumulator >= dt) : (accumulator -= dt) { try fun(@floatCast(f32, dt)); } } pinput.handle(); if (procs.draw) |fun| { try fun(); } glfw.sync(pwin.handle); glfw.processEvents(); pframetime.stop(); pframetime.sleep(ptargetfps); pfps = pfps.calculate(pframetime); } } /// Returns the fps pub fn getFps() u32 { return pfps.fps; } /// Returns the window pub fn getWindow() *Window { return pwin; } /// Returns the input pub fn getInput() *Input { return pinput; } /// Returns the mouse pos x pub fn getMouseX() f32 { return pmouseX; } /// Returns the mouse pos y pub fn getMouseY() f32 { return pmouseY; } /// Sets the callbacks pub fn setCallbacks(calls: Callbacks) void { procs = calls; }
src/kiragine/core.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const camera = @import("camera.zig"); const Camera = camera.Camera; const Ray = camera.Ray; const HitRecord = camera.HitRecord; const vm = @import("vecmath_j.zig"); const math = std.math; const Vec3 = vm.Vec3; const material = @import("material.zig"); const Material = material.Material; const Random = std.rand.DefaultPrng; const util = @import("utils.zig"); pub const Sphere = struct { center : Vec3, radius : f32, material : *const Material, }; pub const Scene = struct { const Self = @This(); sphereList : ArrayList(Sphere), pub fn init( alloc : *Allocator ) Scene { return .{ .sphereList = ArrayList(Sphere).init(alloc) }; } pub fn deinit(self: Self) void { self.sphereList.deinit(); } }; pub fn writePixel( file : std.fs.File, pixel : Vec3 ) anyerror!void { var ir : u8 = @floatToInt( u8, 255.999 * pixel.v[0] ); var ig : u8 = @floatToInt( u8, 255.999 * pixel.v[1] ); var ib : u8 = @floatToInt( u8, 255.999 * pixel.v[2] ); _ = try file.writer().print("{d} {d} {d}\n", .{ ir, ig, ib } ); } pub fn sphereIsectRay( ray : Ray, sphere : Sphere, t_min : f32, t_max : f32 ) ?HitRecord { const oc = Vec3.sub( ray.orig, sphere.center ); const a = Vec3.lengthSq( ray.dir ); const half_b = Vec3.dot( oc, ray.dir ); const c = Vec3.lengthSq( oc ) - sphere.radius*sphere.radius; const discriminant = half_b*half_b - a*c; if (discriminant < 0) { return null; } const sqrt_d = math.sqrt( discriminant ); // Find the closest root in the accepted range var root = ( -half_b - sqrt_d ) / a; if ( (root < t_min) or (t_max < root) ) { root = (-half_b + sqrt_d) / a; if (root < t_min) { return null; } } const p = ray.at( root ); const n = Vec3.mul_s( (Vec3.sub(p, sphere.center) ), 1.0/sphere.radius); const front = Vec3.dot( ray.dir, n ) < 0.0; return HitRecord { .t = root, .point = p, .normal = if (front) n else Vec3.mul_s( n, -1.0 ), .front_face = front, .mtl = sphere.material }; } pub fn sceneIsectRay( ray : Ray, scene : Scene, t_min : f32, t_max : f32 ) ?HitRecord { var best_hit : ?HitRecord = null; // Check any spheres in the scene for ( scene.sphereList.items) |sph| { var maybe_hit : ?HitRecord = sphereIsectRay( ray, sph, t_min, t_max ); if ( maybe_hit != null) { const hit = maybe_hit.?; if (best_hit == null) { best_hit = hit; } else { const curr_best_hit = best_hit.?; if (hit.t < curr_best_hit.t) { best_hit = hit; } } } } return best_hit; } pub fn traceRay( ray : Ray, scene : Scene, rng : *Random, depth: i32 ) Vec3 { if (depth <= 0) { return Vec3.initZero(); } const hit : ?HitRecord = sceneIsectRay( ray, scene, 0.0001, 1000.0 ); if (hit != null) { const hitSph = hit.?; // const targetDir = util.randomInHemisphere( rng, hitSph.normal ); // const bounceRay : Ray = .{ .orig = hitSph.point, // .dir = targetDir }; // var bounce = traceRay( bounceRay, scene, rng, depth-1 ); // return Vec3.mul( bounce, hitSph.mtl.albedo ); const result = hitSph.mtl.scatter( rng, ray, hitSph ); if (result != null) { const resultScatter = result.?; var bounce = traceRay( resultScatter.scatterRay, scene, rng, depth-1 ); return Vec3.mul( resultScatter.attenuation, bounce ); } else { return Vec3.initZero(); } } // Background, sky color var dir_n : Vec3 = Vec3.normalize( ray.dir ); var sky_t : f32 = 0.5 * (dir_n.v[1] + 1.0); const static = struct { const sky = Vec3.init( 0.5, 0.7, 1.0 ); const ground = Vec3.init( 1.0, 1.0, 1.0 ); //const sky = Vec3.init( 1.0, 0.0, 0.0 ); //const ground = Vec3.init( 0.0, 0.0, 1.0 ); }; return Vec3.add( Vec3.mul_s( static.ground, 1.0 - sky_t ), Vec3.mul_s( static.sky, sky_t ) ); } pub fn traceScene( alloc : *Allocator ) anyerror!void { var rng = Random.init( 0 ); // Image //const aspect_ratio : f32 = 16.0 / 9.0; const aspect_ratio : f32 = 3.0 / 2.0; const image_width: usize = 800; //const image_width: usize = 200; // small for testing const image_height: usize = @floatToInt( usize, @intToFloat( f32, image_width) / aspect_ratio ); const samples_per_pixel : usize = 200; //const samples_per_pixel : usize = 32; const max_depth : i32 = 50; const maxcol : f32 = @intToFloat( f32, image_width-1 ); const maxrow : f32 = @intToFloat( f32, image_height-1 ); // Camera const lookfrom = Vec3.init( 13, 2, 3); const lookat = Vec3.init( 0, 0, 0 ); //const focus_dist = Vec3.length( Vec3.sub( lookfrom, lookat ) ); const focus_dist = 10.0; const aperture :f32 = 0.2; const cam : Camera = Camera.init( lookfrom, lookat, Vec3.init( 0, 1, 0 ), // up vector 40.0, aspect_ratio, aperture, focus_dist ); // Scene var scene = Scene.init( alloc ); defer scene.deinit(); // ground const mtlGround = Material.makeLambertian( Vec3.init( 0.5, 0.8, 0.5 ) ); try scene.sphereList.append( Sphere { .center = Vec3.init( 0, -1000, 0 ), .radius = 1000.0, .material = &mtlGround, } ); // Big Spheres const mtlBigSphere1 = Material.makeGlass( Vec3.init( 1,1,1), 1.5 ); try scene.sphereList.append( Sphere { .center = Vec3.init( 0, 1, 0 ), .radius = 1.0, .material = &mtlBigSphere1, } ); const mtlBigSphere2 = Material.makeLambertian( Vec3.init( 0.4, 0.2, 0.1) ); try scene.sphereList.append( Sphere { .center = Vec3.init( -4, 1, 0 ), .radius = 1.0, .material = &mtlBigSphere2, } ); const mtlBigSphere3 = Material.makeMetallic( Vec3.init( 0.7, 0.6, 0.5), 0.0 ); try scene.sphereList.append( Sphere { .center = Vec3.init( 4, 1, 0 ), .radius = 1.0, .material = &mtlBigSphere3, } ); // Allocate all the materials to an arena var mtl_alloc = std.heap.ArenaAllocator.init( alloc ); defer mtl_alloc.deinit(); var a : i32 = -11; while ( a < 11) : ( a += 1) { var b : i32 = -11; while ( b < 11) : ( b += 1) { const center = Vec3.init( @intToFloat( f32, a) + rng.random().float( f32 ) * 0.9, 0.2, @intToFloat( f32, b) + rng.random().float( f32 ) * 0.9 ); var choose_mat = rng.random().float( f32 ); var mtlSphere = try mtl_alloc.allocator.create( Material ); if (choose_mat < 0.6) { // Diffuse const color1 = util.randomVec3( &rng ); const albedo= Vec3.init( color1.v[0]*color1.v[0], color1.v[1]*color1.v[1], color1.v[2]*color1.v[2] ); mtlSphere.* = Material.makeLambertian( albedo ); } else if (choose_mat < 0.8 ) { // Metal const roughness = util.randomRange( &rng, 0.0, 0.5 ); const grey = util.randomRange( &rng, 0.5, 1.0 ); const albedo= Vec3.init( grey, grey, grey ); mtlSphere.* = Material.makeMetallic( albedo, roughness ); } else { // Glass mtlSphere.* = Material.makeGlass( Vec3.init(1,1,1), util.randomRange( &rng, 0.5, 1.5 ) ); } try scene.sphereList.append( Sphere { .center = center, .radius = 0.2, .material = mtlSphere, } ); } } // Scene output const file = try std.fs.cwd().createFile( "image.ppm", .{ .read = true }, ); defer file.close(); _ = try file.writer().print("P3\n", .{} ); _ = try file.writer().print("{d} {d}\n255\n", .{ image_width, image_height }); std.debug.print("Sizeof Sphere is {d}\n", .{ @sizeOf(Sphere) } ); var j : usize = image_height-1; while ( true ) : ( j = j - 1) { var i : usize = 0; if (j % 10 == 0) { //std.log.info("Scanlines remaining: {d}", .{j} ); std.debug.print("Scanlines remaining: {d}\n", .{j} ); } while ( i < image_width ) : (i += 1 ) { var color_accum = Vec3.initZero(); var s : usize = 0; while ( s < samples_per_pixel) : ( s += 1) { // jitter sample const uu = rng.random().float( f32 ); const vv = rng.random().float( f32 ); var u : f32 = (@intToFloat( f32, i ) + uu) / maxcol; var v : f32 = (@intToFloat( f32, j ) + vv) / maxrow; const r : Ray = cam.genRay( &rng, u, v ); var sample_color : Vec3 = traceRay( r, scene, &rng, max_depth ); color_accum = Vec3.add( color_accum, sample_color ); } var color = Vec3.mul_s( color_accum, 1.0 / @intToFloat( f32, samples_per_pixel) ); var colorGamma = Vec3.init( math.sqrt( color.v[0] ), math.sqrt( color.v[1] ), math.sqrt( color.v[2] ) ); _ = try writePixel( file, colorGamma ); } if (j==0) break; } } pub fn main() anyerror!void { var gpalloc = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(!gpalloc.deinit()); //std.log.info("All your codebase are belong to us.", .{}); traceScene( &gpalloc.allocator ) catch |err| { std.log.err("traceScene failed with error {s}.", .{ err } ); return; }; std.log.info( "Wrote file.", .{} ); } test "basic test" { try std.testing.expectEqual(10, 3 + 7); }
src/main.zig
const clap = @import("zig-clap"); const std = @import("std"); const base64 = std.base64; const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const fs = std.fs; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const Clap = clap.ComptimeClap(clap.Help, &params); const Names = clap.Names; const Param = clap.Param(clap.Help); const params = [_]Param{ clap.parseParam("-h, --help display this help text and exit ") catch unreachable, clap.parseParam("-t, --tmp <DIR> override the folder used to stored temporary files") catch unreachable, clap.parseParam("-v, --verbose print commands before executing them ") catch unreachable, clap.parseParam(" --zig <EXE> override the path to the Zig executable ") catch unreachable, Param{ .takes_value = true, }, }; fn usage(stream: var) !void { try stream.writeAll( \\Usage: hacky-zig-repl [OPTION]... \\Allows repl like functionality for Zig. \\ \\Options: \\ ); try clap.help(stream, &params); } const repl_template = \\usingnamespace @import("std"); \\pub fn main() !void {{ \\{} \\{} \\ try __repl_print_stdout(_{}); \\}} \\ \\fn __repl_print_stdout(v: var) !void {{ \\ const stdout = io.getStdOut().outStream(); \\ try stdout.writeAll("_{} = "); \\ try fmt.formatType( \\ v, \\ "", \\ fmt.FormatOptions{{}}, \\ stdout, \\ 3, \\ ); \\ try stdout.writeAll("\n"); \\}} \\ ; pub fn main() anyerror!void { @setEvalBranchQuota(10000); const stdin = io.getStdIn().inStream(); const stdout = io.getStdOut().outStream(); const stderr = io.getStdErr().outStream(); const pa = std.heap.page_allocator; var arg_iter = try clap.args.OsIterator.init(pa); var args = Clap.parse(pa, clap.args.OsIterator, &arg_iter) catch |err| { usage(stderr) catch {}; return err; }; if (args.flag("--help")) return try usage(stdout); const zig_path = args.option("--zig") orelse "zig"; const tmp_dir = args.option("--tmp") orelse "/tmp"; const verbose = args.flag("--verbose"); var last_run_buf = std.ArrayList(u8).init(pa); var line_buf = std.ArrayList(u8).init(pa); var i: usize = 0; while (true) : (line_buf.shrink(0)) { const last_run = last_run_buf.items; var arena = heap.ArenaAllocator.init(pa); defer arena.deinit(); const allocator = &arena.allocator; // TODO: proper readline prompt try stdout.writeAll(">> "); stdin.readUntilDelimiterArrayList(&line_buf, '\n', math.maxInt(usize)) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; const line = mem.trim(u8, line_buf.items, " \t"); if (line.len == 0) continue; const assignment = try fmt.allocPrint(allocator, "const _{} = {};\n", .{ i, line }); var crypt_src: [224 / 8]u8 = undefined; crypto.Blake2s224.hash(last_run, &crypt_src); var encoded_src: [base64.Base64Encoder.calcSize(crypt_src.len)]u8 = undefined; fs.base64_encoder.encode(&encoded_src, &crypt_src); const file_name = try fmt.allocPrint(allocator, "{}/{}.zig", .{ tmp_dir, &encoded_src }); if (verbose) debug.warn("writing source to '{}'\n", .{file_name}); const file = try std.fs.cwd().createFile(file_name, .{}); defer file.close(); try file.outStream().print(repl_template, .{ last_run, assignment, i, i }); if (verbose) debug.warn("running command '{} run {}'\n", .{ zig_path, file_name }); run(allocator, &[_][]const u8{ zig_path, "run", file_name }) catch |err| { debug.warn("error: {}\n", .{err}); continue; }; try last_run_buf.appendSlice(assignment); i += 1; } } fn run(allocator: *mem.Allocator, argv: []const []const u8) !void { const process = try std.ChildProcess.init(argv, allocator); defer process.deinit(); try process.spawn(); switch (try process.wait()) { std.ChildProcess.Term.Exited => |code| { if (code != 0) return error.ProcessFailed; }, else => return error.ProcessFailed, } }
src/main.zig
const std = @import("std"); const A = std.heap.c_allocator; const c = @import("../headers/c.zig"); const call = @import("./safe.zig").call; pub const Env = struct { inner: c.napi_env, pub fn init(env: c.napi_env) Env { return Env { .inner = env }; } pub fn throw_error(self: Env, name: [:0]const u8) !void { try call(c.napi_throw_error, .{self.inner, null, name}); } pub fn throw(self: Env, err: anytype) !void { try call(c.napi_throw, .{self.inner, Value.from(err).inner}); } pub fn seal(self: Env, value: anytype) !void { try call(c.napi_object_seal, .{self.inner, Value.from(value).inner}); } pub fn freeze(self: Env, value: anytype) !void { try call(c.napi_object_freeze, .{self.inner, Value.from(value).inner}); } }; const Ref = struct {}; const Wrapped = struct {}; const External = struct {}; const AsyncWork = struct {}; pub const CallbackInfo = struct { inner: c.napi_callback_info, }; pub const Value = struct { inner: c.napi_value, pub fn from(value: anytype) Value { const T = @TypeOf(value); return switch (T) { c.napi_value => Value { .inner = value }, else => @compileError("expected napi type, got: " ++ @typeName(T)), Null, Date, Value, Array, Error, Object, String, Number, Buffer, BigInt, Promise, Boolean, Function, Undefined, TypedArray, ArrayBuffer => Value { .inner = value.inner }, }; } }; pub const Null = struct { inner: c.napi_value, pub fn init(env: Env) !Null { var raw: c.napi_value = undefined; try call(c.napi_get_null, .{env.inner, &raw}); return Null { .inner = raw }; } }; pub const Undefined = struct { inner: c.napi_value, pub fn init(env: Env) !Undefined { var raw: c.napi_value = undefined; try call(c.napi_get_undefined, .{env.inner, &raw}); return Undefined { .inner = raw }; } }; pub const Error = struct { inner: c.napi_value, pub fn init(env: Env, code: ?String, value: String) !Error { var raw: c.napi_value = undefined; try call(c.napi_create_error, .{env.inner, if (code) |x| x.inner else null, value.inner, &raw}); return Error { .inner = raw }; } }; pub const Boolean = struct { inner: c.napi_value, pub fn init(env: Env, value: bool) !Boolean { var raw: c.napi_value = undefined; try call(c.napi_get_boolean, .{env.inner, value, &raw}); return Boolean { .inner = raw }; } pub fn get(self: Boolean, env: Env) !bool { var value: bool = undefined; try call(c.napi_get_value_bool, .{env.inner, self.inner, &value}); return value; } }; pub const Date = struct { inner: c.napi_value, pub fn init(env: Env, value: i64) !Date { var raw: c.napi_value = undefined; try call(c.napi_create_date, .{env.inner, @intToFloat(f64, value), &raw}); return Date { .inner = raw }; } pub fn get(self: Date, env: Env) !i64 { var value: f64 = undefined; try call(c.napi_get_date_value, .{env.inner, self.inner, &value}); return @floatToInt(i64, value); } }; pub const Promise = struct { inner: c.napi_value, deferred: c.napi_deferred, pub fn init(env: Env) !Promise { var raw: c.napi_value = undefined; var deferred: c.napi_deferred = undefined; try call(c.napi_create_promise, .{env.inner, &deferred, &raw}); return Promise { .inner = raw, .deferred = deferred }; } // TODO: add serde support? pub fn reject(self: Promise, env: Env, value: anytype) !void { try call(c.napi_reject_deferred, .{env.inner, self.deferred, Value.from(value).inner}); } // TODO: add serde support? pub fn resolve(self: Promise, env: Env, value: anytype) !void { try call(c.napi_resolve_deferred, .{env.inner, self.deferred, Value.from(value).inner}); } }; pub const Array = struct { inner: c.napi_value, pub fn len(self: Array, env: Env) !u32 { var length: u32 = undefined; try call(c.napi_get_array_length, .{env.inner, self.inner, &length}); return length; } pub fn set(self: Array, env: Env, index: u32, value: anytype) !void { try call(c.napi_set_element, .{env.inner, self.inner, index, Value.from(value).inner}); } pub fn has(self: Array, env: Env, index: u32) !bool { var b: bool = undefined; try call(c.napi_has_element, .{env.inner, self.inner, index, &b}); return b; } pub fn delete(self: Array, env: Env, index: u32) !bool { var b: bool = undefined; try call(c.napi_delete_element, .{env.inner, self.inner, index, &b}); return b; } pub fn init(env: Env, size: usize) !Array { var raw: c.napi_value = undefined; try call(c.napi_create_array_with_length, .{env.inner, size, &raw}); return Array { .inner = raw }; } pub fn get(self: Array, env: Env, index: u32) !Value { var raw: c.napi_value = undefined; try call(c.napi_get_element, .{env.inner, self.inner, index, &raw}); return Value { .inner = raw }; } }; pub const String = struct { inner: c.napi_value, const encoding = enum { utf8, utf16, latin1, pub fn size(comptime self: encoding) type { return switch (self) { .utf16 => u16, .utf8, .latin1 => u8, }; } }; pub fn len(self: String, env: Env, comptime enc: encoding) !usize { var length: usize = undefined; try call(switch (enc) { .utf8 => c.napi_get_value_string_utf8, .utf16 => c.napi_get_value_string_utf16, .latin1 => c.napi_get_value_string_latin1, }, .{env.inner, self.inner, null, 0, &length}); return length; } pub fn init(env: Env, comptime enc: encoding, value: []const enc.size()) !String { var raw: c.napi_value = undefined; try call(switch (enc) { .utf8 => c.napi_create_string_utf8, .utf16 => c.napi_create_string_utf16, .latin1 => c.napi_create_string_latin1, }, .{env.inner, value.ptr, value.len, &raw}); return String { .inner = raw }; } pub fn get(self: String, env: Env, comptime enc: encoding, allocator: std.mem.Allocator) ![]enc.size() { var length: usize = try self.len(env, enc); const slice = try allocator.alloc(enc.size(), length); errdefer allocator.free(slice); try call(switch (enc) { .utf8 => c.napi_get_value_string_utf8, .utf16 => c.napi_get_value_string_utf16, .latin1 => c.napi_get_value_string_latin1, }, .{env.inner, self.inner, slice.ptr, 1 + length, &length}); return slice; } }; pub const Object = struct { inner: c.napi_value, pub fn init(env: Env) !Object { var raw: c.napi_value = undefined; try call(c.napi_create_object, .{env.inner, &raw}); return Object { .inner = raw }; } pub fn set(self: Object, env: Env, key: anytype, value: anytype) !void { try call(c.napi_set_property, .{env.inner, self.inner, Value.from(key).inner, Value.from(value).inner}); } pub fn keys(self: Object, env: Env) !Array { var raw: c.napi_value = undefined; try call(c.napi_get_property_names, .{env.inner, self.inner, &raw}); return Array { .inner = raw }; } pub fn set_named(self: Object, env: Env, comptime name: [:0]const u8, value: anytype) !void { try call(c.napi_set_named_property, .{env.inner, self.inner, name, Value.from(value).inner}); } pub fn has(self: Object, env: Env, key: anytype) !bool { var result: bool = undefined; try call(c.napi_has_property, .{env.inner, self.inner, Value.from(key).inner, &result}); return result; } pub fn delete(self: Object, env: Env, key: anytype) !bool { var result: bool = undefined; try call(c.napi_delete_property, .{env.inner, self.inner, Value.from(key).inner, &result}); return result; } pub fn has_own(self: Object, env: Env, key: anytype) !bool { var result: bool = undefined; try call(c.napi_has_own_property, .{env.inner, self.inner, Value.from(key).inner, &result}); return result; } pub fn has_named(self: Object, env: Env, comptime name: [:0]const u8) !bool { var result: bool = undefined; try call(c.napi_has_named_property, .{env.inner, self.inner, name, &result}); return result; } pub fn get(self: Object, env: Env, key: anytype) !Value { var raw: c.napi_value = undefined; try call(c.napi_get_property, .{env.inner, self.inner, Value.from(key).inner, &raw}); return Value { .inner = raw }; } pub fn get_named(self: Object, env: Env, comptime name: [:0]const u8) !Value { var raw: c.napi_value = undefined; try call(c.napi_get_named_property, .{env.inner, self.inner, name, &raw}); return Value { .inner = raw }; } }; pub const BigInt = struct { inner: c.napi_value, pub fn init(env: Env, value: anytype) !BigInt { const T = @TypeOf(value); var raw: c.napi_value = undefined; switch (@typeInfo(T)) { else => @compileError("expected int type, got: " ++ @typeName(T)), .ComptimeInt => try call(if (0 > value) c.napi_create_bigint_int64 else c.napi_create_bigint_uint64, .{env.inner, @as(if (0 > value) i64 else u64, value), &raw}), .Int => |info| switch (T) { i64 => try call(c.napi_create_bigint_int64, .{env.inner, @as(i64, value), &raw}), u64 => try call(c.napi_create_bigint_uint64, .{env.inner, @as(u64, value), &raw}), else => switch (info.bits) { 0...63 => switch (info.signedness) { .signed => try call(c.napi_create_bigint_int64, .{env.inner, @as(i64, value), &raw}), .unsigned => try call(c.napi_create_bigint_uint64, .{env.inner, @as(u64, value), &raw}), }, else => |bits| { const size = @ceil(bits / 64.0); const TT = std.meta.Int(.unsigned, @minimum(65535, 64 * size)); const abs: TT align(8) = @intCast(TT, if (.unsigned == info.signedness) value else std.math.absCast(value)); try call(c.napi_create_bigint_words, .{env.inner, @boolToInt(value <= 0), size, @ptrCast([*]const u64, &abs), &raw}); }, }, } } return BigInt { .inner = raw }; } pub fn get(self: BigInt, env: Env, comptime T: type) !T { switch (@typeInfo(T)) { else => @compileError("expected runtime int type, got: " ++ @typeName(T)), .Int => |info| switch (info.bits) { 64 => { var value: T = undefined; var lossless: bool = undefined; try call(switch (info.signedness) { .signed => c.napi_get_value_bigint_int64, .unsigned => c.napi_get_value_bigint_uint64, }, .{env.inner, self.inner, &value, &lossless}); return value; }, 0...63 => { var lossless: bool = undefined; var value: if (.unsigned == info.signedness) u64 else i64 = undefined; try call(switch (info.signedness) { .signed => c.napi_get_value_bigint_int64, .unsigned => c.napi_get_value_bigint_uint64, }, .{env.inner, self.inner, &value, &lossless}); return std.math.cast(T, value); }, else => |bits| { const size = @ceil(bits / 64.0); const TT = std.meta.Int(.unsigned, @minimum(65535, 64 * size)); var sign: i32 = undefined; var len: usize = undefined; var value: TT align(8) = 0; try call(c.napi_get_value_bigint_words, .{env.inner, self.inner, null, &len, null}); if (64 * len > @typeInfo(TT).Int.bits) return error.Overflow; try call(c.napi_get_value_bigint_words, .{env.inner, self.inner, &sign, &len, @ptrCast([*]u64, &value)}); const v = try std.math.cast(T, value); return switch (info.signedness) { .signed => if (0 == sign) v else std.math.negateCast(v), .unsigned => if (0 == sign) v else (std.math.maxInt(T) - v + 1), }; }, } } } }; pub const Number = struct { inner: c.napi_value, pub fn init(env: Env, value: anytype) !Number { const T = @TypeOf(value); var raw: c.napi_value = undefined; switch (@typeInfo(T)) { else => @compileError("expected number, got: " ++ @typeName(T)), .Float, .ComptimeFloat => try call(c.napi_create_double, .{env.inner, @floatCast(f64, value), &raw}), .ComptimeInt => { if (value >= std.math.minInt(i32) and value <= std.math.maxInt(i32)) try call(c.napi_create_int32, .{env.inner, @as(i32, value), &raw}) else if (value >= std.math.minInt(i52) and value <= std.math.maxInt(i52)) try call(c.napi_create_int64, .{env.inner, @as(i64, value), &raw}) else @compileError("comptime_int can't be represented as number (i52), use bigint instead"); }, // TODO: checked usize, isize lowering in serde .Int => |info| switch (info.bits) { 33...51 => try call(c.napi_create_int64, .{env.inner, @as(i64, value), &raw}), 52 => try call(c.napi_create_int64, .{env.inner, @as(i64, @as(i52, value)), &raw}), else => @compileError(@typeName(T) ++ " can't be represented as number (i52), use bigint instead"), 0...32 => switch (info.signedness) { .signed => try call(c.napi_create_int32, .{env.inner, @as(i32, value), &raw}), .unsigned => try call(c.napi_create_uint32, .{env.inner, @as(u32, value), &raw}), }, }, } return Number { .inner = raw }; } pub fn get(self: Number, env: Env, comptime T: type) !T { switch (@typeInfo(T)) { else => @compileError("expected runtime number type, got: " ++ @typeName(T)), .Float => { var value: f64 = undefined; try call(c.napi_get_value_double, .{env.inner, self.inner, &value}); return @floatCast(T, value); }, .Int => |info| switch (info.bits) { 33...63 => { var value: i64 = undefined; try call(c.napi_get_value_int64, .{env.inner, self.inner, &value}); return std.math.cast(T, value); }, 32 => { var value: T = undefined; try call(switch (info.signedness) { .signed => c.napi_get_value_int32, .unsigned => c.napi_get_value_uint32, }, .{env.inner, self.inner, &value}); return value; }, else => { var value: i64 = undefined; try call(c.napi_get_value_int64, .{env.inner, self.inner, &value}); switch (info.signedness) { .signed => return @as(T, value), .unsigned => return if (0 <= value) @intCast(T, value) else error.Overflow, } }, 0...31 => switch (info.signedness) { .signed => { var value: i32 = undefined; try call(c.napi_get_value_int32, .{env.inner, self.inner, &value}); return std.math.cast(T, value); }, .unsigned => { var value: u32 = undefined; try call(c.napi_get_value_uint32, .{env.inner, self.inner, &value}); return std.math.cast(T, value); }, }, }, } } }; pub const Buffer = struct { inner: c.napi_value, pub fn init(env: Env, size: usize) !Buffer { var raw: c.napi_value = undefined; try call(c.napi_create_buffer, .{env.inner, size, null, &raw}); return Buffer { .inner = raw }; } pub fn len(self: Buffer, env: Env) !usize { var length: usize = undefined; var ptr: ?*anyopaque = undefined; try call(c.napi_get_buffer_info, .{env.inner, self.inner, &ptr, &length}); return length; } pub fn get(self: Buffer, env: Env) ![]u8 { var ptr: [*]u8 = undefined; var length: usize = undefined; try call(c.napi_get_buffer_info, .{env.inner, self.inner, @ptrCast([*]?*anyopaque, &ptr), &length}); return ptr[0..length]; } pub fn dupe(env: Env, slice: []const u8) !Buffer { var ptr: [*]u8 = undefined; var raw: c.napi_value = undefined; try call(c.napi_create_buffer, .{env.inner, slice.len, @ptrCast([*]?*anyopaque, &ptr), &raw}); @memcpy(ptr, slice.ptr, slice.len); return Buffer { .inner = raw }; } pub fn external(env: Env, slice: []u8, data: anytype, finalizer: ?fn ([]u8, @TypeOf(data)) void) !Buffer { var raw: c.napi_value = undefined; if (null == finalizer) { const is_void = if (type == @TypeOf(data)) .Void == @typeInfo(data) else .Void == @typeInfo(@TypeOf(data)); if (is_void) try call(c.napi_create_external_buffer, .{env.inner, slice.len, slice.ptr, null, null, &raw}) else { if (@TypeOf(data) != std.mem.Allocator) @compileError("expected allocator, got: " ++ @typeName(@TypeOf(data))); const Info = struct { len: usize, ptr: [*]u8, a: std.mem.Allocator, }; const wrapper = opaque { pub fn finalizer(_: c.napi_env, _: ?*anyopaque, ri: ?*anyopaque) callconv(.C) void { const info = @ptrCast(*Info, @alignCast(@alignOf(*Info), ri)); defer A.destroy(info); info.a.free(info.ptr[0..info.len]); } }; const info = try A.create(Info); info.a = data; info.len = slice.len; info.ptr = slice.ptr; errdefer A.destroy(info); try call(c.napi_create_external_buffer, .{env.inner, slice.len, slice.ptr, wrapper.finalizer, @ptrCast(* align(@alignOf(*Info)) anyopaque, info), &raw}); } } else { const Info = struct { len: usize, ptr: [*]u8, data: @TypeOf(data), f: @typeInfo(@TypeOf(finalizer)).Optional.child, }; const wrapper = opaque { pub fn finalizer(_: c.napi_env, _: ?*anyopaque, ri: ?*anyopaque) callconv(.C) void { const info = @ptrCast(*Info, @alignCast(@alignOf(*Info), ri)); defer A.destroy(info); info.f(info.ptr[0..info.len], info.data); } }; const info = try A.create(Info); info.data = data; info.f = finalizer.?; info.len = slice.len; info.ptr = slice.ptr; errdefer A.destroy(info); try call(c.napi_create_external_buffer, .{env.inner, slice.len, slice.ptr, wrapper.finalizer, @ptrCast(* align(@alignOf(*Info)) anyopaque, info), &raw}); } return Buffer { .inner = raw }; } }; pub const TypedArray = struct { inner: c.napi_value, pub const types = enum { u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, u8clamped, pub fn size(comptime self: types) comptime_int { return switch (self) { .u16, .i16 => 2, .u32, .i32, .f32 => 4, .u64, .i64, .f64 => 8, .u8, .i8, .u8clamped => 1, }; } }; pub fn len(self: TypedArray, env: Env) !usize { var length: usize = undefined; try call(c.napi_get_typedarray_info, .{env.inner, self.inner, null, &length, null, null, null}); return length; } pub fn buffer(self: TypedArray, env: Env) !ArrayBuffer { var raw: c.napi_value = undefined; try call(c.napi_get_typedarray_info, .{env.inner, self.inner, null, null, null, &raw, null}); return ArrayBuffer { .inner = raw }; } pub fn get(self: TypedArray, env: Env, comptime T: type) ![]T { const wt = switch (T) { else => @compileError("unsupported type: " ++ @typeName(T)), u8, i8 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_1 }, u24, i24 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_3 }, u40, i40 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_5 }, u48, i48 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_6 }, u56, i56 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_7 }, u72, i72 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_9 }, u88, i88 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_11 }, u96, i96 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_12 }, u104, i104 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_13 }, u112, i112 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_14 }, u120, i120 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_15 }, u16, i16, f16 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_2 }, u32, i32, f32 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_4 }, u64, i64, f64 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_8 }, u80, i80, f80 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_10 }, u128, i128, f128 => .{ .s = @sizeOf(T), .e = error.bytelength_not_multiple_of_16 }, }; var l: usize = undefined; var ptr: [*]T = undefined; var t: c.napi_typedarray_type = undefined; try call(c.napi_get_typedarray_info, .{env.inner, self.inner, &t, &l, @ptrCast([*]?*anyopaque, &ptr), null, null}); const ts: u8 = switch (t) { else => unreachable, c.napi_int16_array, c.napi_uint16_array => 2, c.napi_int32_array, c.napi_uint32_array, c.napi_float32_array => 4, c.napi_int8_array, c.napi_uint8_array, c.napi_uint8_clamped_array => 1, c.napi_bigint64_array, c.napi_biguint64_array, c.napi_float64_array => 8, }; if (ts != wt.s and (0 != ((l * ts) % wt.s))) return wt.e; return ptr[0..(l * ts / wt.s)]; } pub fn init(env: Env, comptime t: types, ab: ArrayBuffer, offset: usize, length: usize) !TypedArray { const l = try ab.len(env); var raw: c.napi_value = undefined; if (l <= offset) return error.offset_out_of_bounds; const ll = l - offset; if (ll < length * t.size()) return error.length_out_of_bounds; switch (t) { .i8, .u8, .u8clamped => try call(c.napi_create_typedarray, .{env.inner, switch (t) { else => unreachable, .i8 => c.napi_int8_array, .u8 => c.napi_uint8_array, .u8clamped => c.napi_uint8_clamped_array, }, length, ab.inner, 0, &raw}), .f32 => { if (0 != (ll % 4)) return error.arraybuffer_length_not_multiple_of_4; try call(c.napi_create_typedarray, .{env.inner, c.napi_float32_array, length, ab.inner, 0, &raw}); }, .f64 => { if (0 != (ll % 8)) return error.arraybuffer_length_not_multiple_of_8; try call(c.napi_create_typedarray, .{env.inner, c.napi_float64_array, length, ab.inner, 0, &raw}); }, .i16, .u16 => { if (0 != (ll % 2)) return error.arraybuffer_length_not_multiple_of_2; try call(c.napi_create_typedarray, .{env.inner, if (t == .i16) c.napi_int16_array else c.napi_uint16_array, length, ab.inner, 0, &raw}); }, .i32, .u32 => { if (0 != (ll % 4)) return error.arraybuffer_length_not_multiple_of_4; try call(c.napi_create_typedarray, .{env.inner, if (t == .i32) c.napi_int32_array else c.napi_uint32_array, length, ab.inner, 0, &raw}); }, .i64, .u64 => { if (0 != (ll % 8)) return error.arraybuffer_length_not_multiple_of_8; try call(c.napi_create_typedarray, .{env.inner, if (t == .i64) c.napi_bigint64_array else c.napi_biguint64_array, length, ab.inner, 0, &raw}); }, } return TypedArray { .inner = raw }; } }; pub const ArrayBuffer = struct { inner: c.napi_value, pub fn init(env: Env, size: usize) !ArrayBuffer { var raw: c.napi_value = undefined; try call(c.napi_create_arraybuffer, .{env.inner, size, null, &raw}); return ArrayBuffer { .inner = raw }; } pub fn len(self: ArrayBuffer, env: Env) !usize { var length: usize = undefined; var ptr: ?*anyopaque = undefined; try call(c.napi_get_arraybuffer_info, .{env.inner, self.inner, &ptr, &length}); return length; } pub fn get(self: ArrayBuffer, env: Env) ![]u8 { var ptr: [*]u8 = undefined; var length: usize = undefined; try call(c.napi_get_arraybuffer_info, .{env.inner, self.inner, @ptrCast([*]?*anyopaque, &ptr), &length}); return ptr[0..length]; } pub fn dupe(env: Env, slice: []const u8) !ArrayBuffer { var ptr: [*]u8 = undefined; var raw: c.napi_value = undefined; try call(c.napi_create_arraybuffer, .{env.inner, slice.len, @ptrCast([*]?*anyopaque, &ptr), &raw}); @memcpy(ptr, slice.ptr, slice.len); return ArrayBuffer { .inner = raw }; } pub fn cast(self: ArrayBuffer, env: Env, comptime t: TypedArray.types) !TypedArray { const length = try self.len(env); var raw: c.napi_value = undefined; switch (t) { .i8, .u8, .u8clamped => try call(c.napi_create_typedarray, .{env.inner, switch (t) { else => unreachable, .i8 => c.napi_int8_array, .u8 => c.napi_uint8_array, .u8clamped => c.napi_uint8_clamped_array, }, length, self.inner, 0, &raw}), .f32 => { if (0 != (length % 4)) return error.length_not_multiple_of_4; try call(c.napi_create_typedarray, .{env.inner, c.napi_float32_array, length / 4, self.inner, 0, &raw}); }, .f64 => { if (0 != (length % 8)) return error.length_not_multiple_of_8; try call(c.napi_create_typedarray, .{env.inner, c.napi_float64_array, length / 8, self.inner, 0, &raw}); }, .i16, .u16 => { if (0 != (length % 2)) return error.length_not_multiple_of_2; try call(c.napi_create_typedarray, .{env.inner, if (t == .i16) c.napi_int16_array else c.napi_uint16_array, length / 2, self.inner, 0, &raw}); }, .i32, .u32 => { if (0 != (length % 4)) return error.length_not_multiple_of_4; try call(c.napi_create_typedarray, .{env.inner, if (t == .i32) c.napi_int32_array else c.napi_uint32_array, length / 4, self.inner, 0, &raw}); }, .i64, .u64 => { if (0 != (length % 8)) return error.length_not_multiple_of_8; try call(c.napi_create_typedarray, .{env.inner, if (t == .i64) c.napi_bigint64_array else c.napi_biguint64_array, length / 8, self.inner, 0, &raw}); }, } return TypedArray { .inner = raw }; } pub fn external(env: Env, slice: []u8, data: anytype, finalizer: ?fn ([]u8, @TypeOf(data)) void) !ArrayBuffer { var raw: c.napi_value = undefined; if (null == finalizer) { const is_void = if (type == @TypeOf(data)) .Void == @typeInfo(data) else .Void == @typeInfo(@TypeOf(data)); if (is_void) try call(c.napi_create_external_arraybuffer, .{env.inner, slice.ptr, slice.len, null, null, &raw}) else { if (@TypeOf(data) != std.mem.Allocator) @compileError("expected allocator, got: " ++ @typeName(@TypeOf(data))); const Info = struct { len: usize, ptr: [*]u8, a: std.mem.Allocator, }; const wrapper = opaque { pub fn finalizer(_: c.napi_env, _: ?*anyopaque, ri: ?*anyopaque) callconv(.C) void { const info = @ptrCast(*Info, @alignCast(@alignOf(*Info), ri)); defer A.destroy(info); info.a.free(info.ptr[0..info.len]); } }; const info = try A.create(Info); info.a = data; info.len = slice.len; info.ptr = slice.ptr; errdefer A.destroy(info); try call(c.napi_create_external_arraybuffer, .{env.inner, slice.ptr, slice.len, wrapper.finalizer, @ptrCast(* align(@alignOf(*Info)) anyopaque, info), &raw}); } } else { const Info = struct { len: usize, ptr: [*]u8, data: @TypeOf(data), f: @typeInfo(@TypeOf(finalizer)).Optional.child, }; const wrapper = opaque { pub fn finalizer(_: c.napi_env, _: ?*anyopaque, ri: ?*anyopaque) callconv(.C) void { const info = @ptrCast(*Info, @alignCast(@alignOf(*Info), ri)); defer A.destroy(info); info.f(info.ptr[0..info.len], info.data); } }; const info = try A.create(Info); info.data = data; info.f = finalizer.?; info.len = slice.len; info.ptr = slice.ptr; errdefer A.destroy(info); try call(c.napi_create_external_arraybuffer, .{env.inner, slice.ptr, slice.len, wrapper.finalizer, @ptrCast(* align(@alignOf(*Info)) anyopaque, info), &raw}); } return ArrayBuffer { .inner = raw }; } }; pub const Function = struct { inner: c.napi_value, pub fn init(env: Env, comptime name: [:0]const u8, comptime f: fn (env: Env, info: CallbackInfo) anyerror!Value) !Function { const wrapper = opaque { pub fn zig(e: Env, ri: c.napi_callback_info) !Value { return try f(e, CallbackInfo { .inner = ri }); } pub fn callback(re: c.napi_env, ri: c.napi_callback_info) callconv(.C) c.napi_value { if (zig(Env.init(re), ri)) |x| { return x.inner; } else |err| Env.init(re).throw_error(@errorName(err)) catch {}; return null; } }; var raw: c.napi_value = undefined; try call(c.napi_create_function, .{env.inner, name, name.len, wrapper.callback, null, &raw}); return Function { .inner = raw }; } }; const Class = struct {};
src/napi/c-napi/types.zig
const std = @import("std"); const stdx = @import("stdx"); const fatal = stdx.fatal; const vk = @import("vk"); const platform = @import("platform"); const graphics = @import("../../graphics.zig"); const gpu = graphics.gpu; pub const SwapChain = @import("swapchain.zig").SwapChain; pub usingnamespace @import("command.zig"); const log = stdx.log.scoped(.vk); pub const shader = @import("shader.zig"); pub const framebuffer = @import("framebuffer.zig"); pub const renderpass = @import("renderpass.zig"); pub const image = @import("image.zig"); pub const buffer = @import("buffer.zig"); pub const command = @import("command.zig"); pub const memory = @import("memory.zig"); pub const pipeline = @import("pipeline.zig"); pub const Pipeline = pipeline.Pipeline; pub const descriptor = @import("descriptor.zig"); const shaders = @import("shaders/shaders.zig"); pub const VkContext = struct { alloc: std.mem.Allocator, physical: vk.VkPhysicalDevice, device: vk.VkDevice, graphics_queue: vk.VkQueue, present_queue: vk.VkQueue, cmd_pool: vk.VkCommandPool, cmd_bufs: []vk.VkCommandBuffer, pass: vk.VkRenderPass, framebuffer_size: vk.VkExtent2D, framebuffers: []vk.VkFramebuffer, // TODO: Move this into gpu.inner. default_linear_sampler: vk.VkSampler, default_nearest_sampler: vk.VkSampler, const Self = @This(); pub fn init(alloc: std.mem.Allocator, win: *platform.Window, swapchain: graphics.SwapChain) Self { var ret = graphics.vk.VkContext{ .alloc = alloc, .physical = win.impl.inner.physical_device, .device = win.impl.inner.device, .cmd_pool = undefined, .cmd_bufs = undefined, .graphics_queue = undefined, .present_queue = undefined, .framebuffer_size = swapchain.impl.buf_dim, .framebuffers = undefined, .pass = undefined, .default_linear_sampler = undefined, .default_nearest_sampler = undefined, }; const queue_family = win.impl.inner.queue_family; vk.getDeviceQueue(ret.device, queue_family.graphics_family.?, 0, &ret.graphics_queue); vk.getDeviceQueue(ret.device, queue_family.present_family.?, 0, &ret.present_queue); ret.cmd_pool = command.createCommandPool(ret.device, queue_family); const num_framebuffers = @intCast(u32, swapchain.impl.images.len); ret.cmd_bufs = command.createCommandBuffers(alloc, ret.device, ret.cmd_pool, num_framebuffers); ret.pass = renderpass.createRenderPass(ret.device, swapchain.impl.buf_format); ret.framebuffers = framebuffer.createFramebuffers(alloc, ret.device, ret.pass, ret.framebuffer_size, swapchain.impl.image_views, swapchain.impl.depth_image_views); ret.default_linear_sampler = ret.createDefaultTextureSampler(true); ret.default_nearest_sampler = ret.createDefaultTextureSampler(false); return ret; } pub fn deinit(self: Self, alloc: std.mem.Allocator) void { for (self.framebuffers) |fb| { vk.destroyFramebuffer(self.device, fb, null); } alloc.free(self.framebuffers); vk.destroyCommandPool(self.device, self.cmd_pool, null); alloc.free(self.cmd_bufs); vk.destroySampler(self.device, self.default_linear_sampler, null); vk.destroySampler(self.device, self.default_nearest_sampler, null); vk.destroyRenderPass(self.device, self.pass, null); } pub fn initImage(self: Self, img: *gpu.Image, width: usize, height: usize, mb_data: ?[]const u8, linear_filter: bool) void { img.* = .{ .tex_id = undefined, .width = width, .height = height, .inner = undefined, .remove = false, }; var staging_buf: vk.VkBuffer = undefined; var staging_buf_mem: vk.VkDeviceMemory = undefined; const size = width * height * 4; buffer.createBuffer(self.physical, self.device, size, vk.VK_BUFFER_USAGE_TRANSFER_SRC_BIT, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &staging_buf, &staging_buf_mem); // Copy to gpu. if (mb_data) |data| { var gpu_data: ?*anyopaque = null; var res = vk.mapMemory(self.device, staging_buf_mem, 0, size, 0, &gpu_data); vk.assertSuccess(res); std.mem.copy(u8, @ptrCast([*]u8, gpu_data)[0..size], data); vk.unmapMemory(self.device, staging_buf_mem); } var tex_image: vk.VkImage = undefined; var tex_image_mem: vk.VkDeviceMemory = undefined; image.createDefaultImage(self.physical, self.device, width, height, vk.VK_FORMAT_R8G8B8A8_SRGB, vk.VK_IMAGE_TILING_OPTIMAL, vk.VK_IMAGE_USAGE_TRANSFER_DST_BIT | vk.VK_IMAGE_USAGE_SAMPLED_BIT, vk.VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &tex_image, &tex_image_mem); // Transition to transfer dst layout. self.transitionImageLayout(tex_image, vk.VK_FORMAT_R8G8B8A8_SRGB, vk.VK_IMAGE_LAYOUT_UNDEFINED, vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); self.copyBufferToImage(staging_buf, tex_image, width, height); // Transition to shader access layout. self.transitionImageLayout(tex_image, vk.VK_FORMAT_R8G8B8A8_SRGB, vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, vk.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // Cleanup. vk.destroyBuffer(self.device, staging_buf, null); vk.freeMemory(self.device, staging_buf_mem, null); const tex_image_view = image.createDefaultTextureImageView(self.device, tex_image); img.inner.image = tex_image; img.inner.image_mem = tex_image_mem; img.inner.image_view = tex_image_view; if (linear_filter) { img.inner.sampler = self.default_linear_sampler; } else { img.inner.sampler = self.default_nearest_sampler; } } pub fn createDefaultTextureSampler(self: Self, linear_filter: bool) vk.VkSampler { const create_info = vk.VkSamplerCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = if (linear_filter) vk.VK_FILTER_LINEAR else vk.VK_FILTER_NEAREST, .minFilter = if (linear_filter) vk.VK_FILTER_LINEAR else vk.VK_FILTER_NEAREST, .addressModeU = vk.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .addressModeV = vk.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .addressModeW = vk.VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .anisotropyEnable = vk.VK_FALSE, .maxAnisotropy = 0, .borderColor = vk.VK_BORDER_COLOR_INT_OPAQUE_BLACK, .unnormalizedCoordinates = vk.VK_FALSE, .compareEnable = vk.VK_FALSE, .compareOp = vk.VK_COMPARE_OP_ALWAYS, .mipmapMode = vk.VK_SAMPLER_MIPMAP_MODE_LINEAR, .mipLodBias = 0, .minLod = 0, .maxLod = 0, .pNext = null, .flags = 0, }; var ret: vk.VkSampler = undefined; const res = vk.createSampler(self.device, &create_info, null, &ret); vk.assertSuccess(res); return ret; } fn beginSingleTimeCommands(self: Self) vk.VkCommandBuffer { const alloc_info = vk.VkCommandBufferAllocateInfo{ .sType = vk.VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .level = vk.VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandPool = self.cmd_pool, .commandBufferCount = 1, .pNext = null, }; var ret: vk.VkCommandBuffer = undefined; var res = vk.allocateCommandBuffers(self.device, &alloc_info, &ret); vk.assertSuccess(res); const begin_info = vk.VkCommandBufferBeginInfo{ .sType = vk.VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = vk.VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, .pNext = null, .pInheritanceInfo = null, }; res = vk.beginCommandBuffer(ret, &begin_info); vk.assertSuccess(res); return ret; } fn endSingleTimeCommands(self: Self, cmd_buf: vk.VkCommandBuffer) void { var res = vk.endCommandBuffer(cmd_buf); vk.assertSuccess(res); const submit_info = vk.VkSubmitInfo{ .sType = vk.VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd_buf, .pNext = null, .waitSemaphoreCount = 0, .pWaitSemaphores = null, .signalSemaphoreCount = 0, .pSignalSemaphores = null, .pWaitDstStageMask = 0, }; res = vk.queueSubmit(self.graphics_queue, 1, &submit_info, null); vk.assertSuccess(res); res = vk.queueWaitIdle(self.graphics_queue); vk.assertSuccess(res); vk.freeCommandBuffers(self.device, self.cmd_pool, 1, &cmd_buf); } fn copyBuffer(self: Self, src: vk.VkBuffer, dst: vk.VkBuffer, size: vk.VkDeviceSize) void { const cmd_buf = self.beginSingleTimeCommands(); const copy = vk.VkBufferCopy{ .size = size, }; vk.cmdCopyBuffer(cmd_buf, src, dst, 1, &copy); self.endSingleTimeCommands(cmd_buf); } pub fn transitionImageLayout(self: Self, img: vk.VkImage, format: vk.VkFormat, old_layout: vk.VkImageLayout, new_layout: vk.VkImageLayout) void { const cmd_buf = self.beginSingleTimeCommands(); _ = format; var barrier = vk.VkImageMemoryBarrier{ .sType = vk.VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = old_layout, .newLayout = new_layout, .srcQueueFamilyIndex = vk.VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = vk.VK_QUEUE_FAMILY_IGNORED, .image = img, .subresourceRange = .{ .aspectMask = vk.VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }, .srcAccessMask = 0, .dstAccessMask = 0, .pNext = null, }; var src_stage: vk.VkPipelineStageFlags = undefined; var dst_stage: vk.VkPipelineStageFlags = undefined; if (old_layout == vk.VK_IMAGE_LAYOUT_UNDEFINED and new_layout == vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = vk.VK_ACCESS_TRANSFER_WRITE_BIT; src_stage = vk.VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = vk.VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (old_layout == vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL and new_layout == vk.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = vk.VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = vk.VK_ACCESS_SHADER_READ_BIT; src_stage = vk.VK_PIPELINE_STAGE_TRANSFER_BIT; dst_stage = vk.VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if (old_layout == vk.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL and new_layout == vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = vk.VK_ACCESS_SHADER_READ_BIT; barrier.dstAccessMask = vk.VK_ACCESS_TRANSFER_WRITE_BIT; src_stage = vk.VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; dst_stage = vk.VK_PIPELINE_STAGE_TRANSFER_BIT; } else { stdx.fatal(); } vk.cmdPipelineBarrier(cmd_buf, src_stage, dst_stage, 0, 0, null, 0, null, 1, &barrier ); self.endSingleTimeCommands(cmd_buf); } pub fn copyBufferToImage(self: Self, buf: vk.VkBuffer, img: vk.VkImage, width: usize, height: usize) void { const cmd_buf = self.beginSingleTimeCommands(); const copy = vk.VkBufferImageCopy{ .bufferOffset = 0, .bufferRowLength = 0, .bufferImageHeight = 0, .imageSubresource = .{ .aspectMask = vk.VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = 0, .baseArrayLayer = 0, .layerCount = 1, }, .imageOffset = .{ .x = 0, .y = 0, .z = 0, }, .imageExtent = .{ .width = @intCast(u32, width), .height = @intCast(u32, height), .depth = 1, }, }; vk.cmdCopyBufferToImage(cmd_buf, buf, img, vk.VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy); self.endSingleTimeCommands(cmd_buf); } }; pub fn createPlanePipeline(device: vk.VkDevice, pass: vk.VkRenderPass, view_dim: vk.VkExtent2D) Pipeline { // const bind_descriptors = [_]vk.VkVertexInputBindingDescription{ // vk.VkVertexInputBindingDescription{ // .binding = 0, // .stride = 0, // .inputRate = vk.VK_VERTEX_INPUT_RATE_VERTEX, // }, // }; // const attr_descriptors = [_]vk.VkVertexInputAttributeDescription{ // vk.VkVertexInputAttributeDescription{ // .binding = 0, // .location = 0, // .format = vk.VK_FORMAT_R32G32B32A32_SFLOAT, // .offset = 0, // }, // }; const pvis_info = vk.VkPipelineVertexInputStateCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .vertexBindingDescriptionCount = 0, .vertexAttributeDescriptionCount = 0, // .pVertexBindingDescriptions = &bind_descriptors, .pVertexBindingDescriptions = null, // .pVertexAttributeDescriptions = &attr_descriptors, .pVertexAttributeDescriptions = null, .pNext = null, .flags = 0, }; const push_const_range = [_]vk.VkPushConstantRange{ vk.VkPushConstantRange{ .offset = 0, .size = 16 * 4, .stageFlags = vk.VK_SHADER_STAGE_VERTEX_BIT, }, }; const pl_info = vk.VkPipelineLayoutCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 0, .pSetLayouts = null, .pushConstantRangeCount = 1, .pPushConstantRanges = &push_const_range[0], .pNext = null, .flags = 0, }; const vert_src align(4) = shaders.plane_vert_spv; const frag_src align(4) = shaders.plane_frag_spv; return pipeline.createDefaultPipeline(device, pass, view_dim, &vert_src, &frag_src, pvis_info, pl_info, .{ .depth_test = true }); } pub fn createGradientPipeline(device: vk.VkDevice, pass: vk.VkRenderPass, view_dim: vk.VkExtent2D) Pipeline { const bind_descriptors = [_]vk.VkVertexInputBindingDescription{ vk.VkVertexInputBindingDescription{ .binding = 0, .stride = 40, .inputRate = vk.VK_VERTEX_INPUT_RATE_VERTEX, }, }; const attr_descriptors = [_]vk.VkVertexInputAttributeDescription{ vk.VkVertexInputAttributeDescription{ .binding = 0, .location = 0, .format = vk.VK_FORMAT_R32G32B32A32_SFLOAT, .offset = 0, }, }; const pvis_info = vk.VkPipelineVertexInputStateCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .vertexBindingDescriptionCount = 1, .vertexAttributeDescriptionCount = 1, .pVertexBindingDescriptions = &bind_descriptors, .pVertexAttributeDescriptions = &attr_descriptors, .pNext = null, .flags = 0, }; const push_const_range = [_]vk.VkPushConstantRange{ vk.VkPushConstantRange{ .offset = 0, .size = 16 * 4, .stageFlags = vk.VK_SHADER_STAGE_VERTEX_BIT, }, vk.VkPushConstantRange{ .offset = 16 * 4, .size = 4 * 12, .stageFlags = vk.VK_SHADER_STAGE_FRAGMENT_BIT, }, }; const pl_info = vk.VkPipelineLayoutCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 0, .pSetLayouts = null, .pushConstantRangeCount = 2, .pPushConstantRanges = &push_const_range[0], .pNext = null, .flags = 0, }; const vert_src align(4) = shaders.gradient_vert_spv; const frag_src align(4) = shaders.gradient_frag_spv; return pipeline.createDefaultPipeline(device, pass, view_dim, &vert_src, &frag_src, pvis_info, pl_info, .{ .depth_test = false, }); } pub fn createTexPipeline(device: vk.VkDevice, pass: vk.VkRenderPass, view_dim: vk.VkExtent2D, desc_set: vk.VkDescriptorSetLayout, depth_test: bool, wireframe: bool) Pipeline { const bind_descriptors = [_]vk.VkVertexInputBindingDescription{ vk.VkVertexInputBindingDescription{ .binding = 0, .stride = 40, .inputRate = vk.VK_VERTEX_INPUT_RATE_VERTEX, }, }; const attr_descriptors = [_]vk.VkVertexInputAttributeDescription{ vk.VkVertexInputAttributeDescription{ .binding = 0, .location = 0, .format = vk.VK_FORMAT_R32G32B32A32_SFLOAT, .offset = 0, }, vk.VkVertexInputAttributeDescription{ .binding = 0, .location = 1, .format = vk.VK_FORMAT_R32G32_SFLOAT, .offset = 16, }, vk.VkVertexInputAttributeDescription{ .binding = 0, .location = 2, .format = vk.VK_FORMAT_R32G32B32A32_SFLOAT, .offset = 24, }, }; const pvis_info = vk.VkPipelineVertexInputStateCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .vertexBindingDescriptionCount = 1, .vertexAttributeDescriptionCount = 3, .pVertexBindingDescriptions = &bind_descriptors, .pVertexAttributeDescriptions = &attr_descriptors, .pNext = null, .flags = 0, }; const push_const_range = [_]vk.VkPushConstantRange{ vk.VkPushConstantRange{ .offset = 0, .size = 16 * 4, .stageFlags = vk.VK_SHADER_STAGE_VERTEX_BIT, }, }; const pl_info = vk.VkPipelineLayoutCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &desc_set, .pushConstantRangeCount = 1, .pPushConstantRanges = &push_const_range, .pNext = null, .flags = 0, }; const vert_src align(4) = shaders.tex_vert_spv; const frag_src align(4) = shaders.tex_frag_spv; return pipeline.createDefaultPipeline(device, pass, view_dim, &vert_src, &frag_src, pvis_info, pl_info, .{ .depth_test = depth_test, .line_mode = wireframe, }); } // TODO: Implement a list of pools. Once a pool runs out of space a new one is created. /// Currently a fixed max of 100 textures. pub fn createTexDescriptorPool(device: vk.VkDevice) vk.VkDescriptorPool { const pool_sizes = [_]vk.VkDescriptorPoolSize{ vk.VkDescriptorPoolSize{ .@"type" = vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 100, }, }; const create_info = vk.VkDescriptorPoolCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .poolSizeCount = pool_sizes.len, .pPoolSizes = &pool_sizes, .maxSets = 100, .pNext = null, .flags = 0, }; var ret: vk.VkDescriptorPool = undefined; const res = vk.createDescriptorPool(device, &create_info, null, &ret); vk.assertSuccess(res); return ret; } pub fn createTexDescriptorSetLayout(device: vk.VkDevice) vk.VkDescriptorSetLayout { // mvp uniform. // const mvp_layout_binding = vk.VkDescriptorSetLayoutBinding{ // .binding = 0, // .descriptorType = vk.VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // .descriptorCount = 1, // .stageFlags = vk.VK_SHADER_STAGE_VERTEX_BIT, // .pImmutableSamplers = null, // }; const sampler_layout_binding = vk.VkDescriptorSetLayoutBinding{ .binding = 0, .descriptorCount = 1, .descriptorType = vk.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImmutableSamplers = null, .stageFlags = vk.VK_SHADER_STAGE_FRAGMENT_BIT, }; const bindings = [_]vk.VkDescriptorSetLayoutBinding{ //mvp_layout_binding, sampler_layout_binding, }; const create_info = vk.VkDescriptorSetLayoutCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = bindings.len, .pBindings = &bindings, .pNext = null, .flags = 0, }; var set_layout: vk.VkDescriptorSetLayout = undefined; const res = vk.createDescriptorSetLayout(device, &create_info, null, &set_layout); vk.assertSuccess(res); return set_layout; } pub const Pipelines = struct { wireframe_pipeline: Pipeline, tex_pipeline: Pipeline, tex_pipeline_2d: Pipeline, gradient_pipeline_2d: Pipeline, plane_pipeline: Pipeline, pub fn deinit(self: Pipelines, device: vk.VkDevice) void { self.wireframe_pipeline.deinit(device); self.tex_pipeline.deinit(device); self.tex_pipeline_2d.deinit(device); self.gradient_pipeline_2d.deinit(device); self.plane_pipeline.deinit(device); } };
graphics/src/backend/vk/graphics.zig
const std = @import("std"); const builtin = @import("builtin"); const fs = std.fs; const mem = std.mem; const ascii = std.ascii; const Allocator = mem.Allocator; const testing = std.testing; // zig fmt: off pub const known_files = &[_][]const u8{ "/etc/mime.types", "/etc/httpd/mime.types", // Mac OS X "/etc/httpd/conf/mime.types", // Apache "/etc/apache/mime.types", // Apache 1 "/etc/apache2/mime.types", // Apache 2 "/usr/local/etc/httpd/conf/mime.types", "/usr/local/lib/netscape/mime.types", "/usr/local/etc/httpd/conf/mime.types", // Apache 1.2 "/usr/local/etc/mime.types", // Apache 1.3 }; pub const suffix_map = &[_][2][]const u8 { .{".svgz", ".svg.gz"}, .{".tgz" , ".tar.gz"}, .{".taz" , ".tar.gz"}, .{".tz" , ".tar.gz"}, .{".tbz2", ".tar.bz2"}, .{".txz" , ".tar.xz"}, }; pub const encodings_map = &[_][2][]const u8 { .{".gz" , "gzip"}, .{".Z" , "compress"}, .{".bz2", "bzip2"}, .{".xz" , "xz"}, }; // Before adding new types, make sure they are either registered with IANA, // at http://www.isi.edu/in-notes/iana/assignments/media-types // or extensions, i.e. using the x- prefix // If you add to these, please keep them sorted! pub const extension_map = &[_][2][]const u8 { .{".a" , "application/octet-stream"}, .{".ai" , "application/postscript"}, .{".aif" , "audio/x-aiff"}, .{".aifc" , "audio/x-aiff"}, .{".aiff" , "audio/x-aiff"}, .{".au" , "audio/basic"}, .{".avi" , "video/x-msvideo"}, .{".bat" , "text/plain"}, .{".bcpio" , "application/x-bcpio"}, .{".bin" , "application/octet-stream"}, .{".bmp" , "image/x-ms-bmp"}, .{".c" , "text/plain"}, .{".cdf" , "application/x-cdf"}, // Dup .{".cdf" , "application/x-netcdf"}, .{".cpio" , "application/x-cpio"}, .{".csh" , "application/x-csh"}, .{".css" , "text/css"}, .{".csv" , "text/csv"}, .{".dll" , "application/octet-stream"}, .{".doc" , "application/msword"}, .{".dot" , "application/msword"}, .{".dvi" , "application/x-dvi"}, .{".eml" , "message/rfc822"}, .{".eps" , "application/postscript"}, .{".etx" , "text/x-setext"}, .{".exe" , "application/octet-stream"}, .{".gif" , "image/gif"}, .{".gtar" , "application/x-gtar"}, .{".h" , "text/plain"}, .{".hdf" , "application/x-hdf"}, .{".htm" , "text/html"}, .{".html" , "text/html"}, .{".ico" , "image/vnd.microsoft.icon"}, .{".ief" , "image/ief"}, .{".jpe" , "image/jpeg"}, .{".jpeg" , "image/jpeg"}, .{".jpg" , "image/jpeg"}, .{".js" , "application/javascript"}, .{".json" , "application/json"}, .{".ksh" , "text/plain"}, .{".latex" , "application/x-latex"}, .{".m1v" , "video/mpeg"}, .{".man" , "application/x-troff-man"}, .{".me" , "application/x-troff-me"}, .{".mht" , "message/rfc822"}, .{".mhtml" , "message/rfc822"}, .{".mid" , "audio/midi"}, .{".midi" , "audio/midi"}, .{".mif" , "application/x-mif"}, .{".mjs" , "application/javascript"}, .{".mov" , "video/quicktime"}, .{".movie" , "video/x-sgi-movie"}, .{".mp2" , "audio/mpeg"}, .{".mp3" , "audio/mpeg"}, .{".mp4" , "video/mp4"}, .{".mpa" , "video/mpeg"}, .{".mpe" , "video/mpeg"}, .{".mpeg" , "video/mpeg"}, .{".mpg" , "video/mpeg"}, .{".ms" , "application/x-troff-ms"}, .{".nc" , "application/x-netcdf"}, .{".nws" , "message/rfc822"}, .{".o" , "application/octet-stream"}, .{".obj" , "application/octet-stream"}, .{".oda" , "application/oda"}, .{".p12" , "application/x-pkcs12"}, .{".p7c" , "application/pkcs7-mime"}, .{".pbm" , "image/x-portable-bitmap"}, .{".pdf" , "application/pdf"}, .{".pfx" , "application/x-pkcs12"}, .{".pgm" , "image/x-portable-graymap"}, .{".pct" , "image/pict"}, .{".pic" , "image/pict"}, .{".pict" , "image/pict"}, .{".pl" , "text/plain"}, .{".png" , "image/png"}, .{".pnm" , "image/x-portable-anymap"}, .{".pot" , "application/vnd.ms-powerpoint"}, .{".ppa" , "application/vnd.ms-powerpoint"}, .{".ppm" , "image/x-portable-pixmap"}, .{".pps" , "application/vnd.ms-powerpoint"}, .{".ppt" , "application/vnd.ms-powerpoint"}, .{".ps" , "application/postscript"}, .{".pwz" , "application/vnd.ms-powerpoint"}, .{".py" , "text/x-python"}, .{".pyc" , "application/x-python-code"}, .{".pyo" , "application/x-python-code"}, .{".qt" , "video/quicktime"}, .{".ra" , "audio/x-pn-realaudio"}, .{".ram" , "application/x-pn-realaudio"}, .{".ras" , "image/x-cmu-raster"}, .{".rdf" , "application/xml"}, .{".rgb" , "image/x-rgb"}, .{".roff" , "application/x-troff"}, .{".rtf" , "application/rtf"}, .{".rtx" , "text/richtext"}, .{".sgm" , "text/x-sgml"}, .{".sgml" , "text/x-sgml"}, .{".sh" , "application/x-sh"}, .{".shar" , "application/x-shar"}, .{".snd" , "audio/basic"}, .{".so" , "application/octet-stream"}, .{".src" , "application/x-wais-source"}, .{".sv4cpio", "application/x-sv4cpio"}, .{".sv4crc" , "application/x-sv4crc"}, .{".svg" , "image/svg+xml"}, .{".swf" , "application/x-shockwave-flash"}, .{".t" , "application/x-troff"}, .{".tar" , "application/x-tar"}, .{".tcl" , "application/x-tcl"}, .{".tex" , "application/x-tex"}, .{".texi" , "application/x-texinfo"}, .{".texinfo", "application/x-texinfo"}, .{".tif" , "image/tiff"}, .{".tiff" , "image/tiff"}, .{".tr" , "application/x-troff"}, .{".tsv" , "text/tab-separated-values"}, .{".txt" , "text/plain"}, .{".ustar" , "application/x-ustar"}, .{".vcf" , "text/x-vcard"}, .{".wav" , "audio/x-wav"}, .{".webm" , "video/webm"}, .{".wiz" , "application/msword"}, .{".wsdl" , "application/xml"}, .{".xbm" , "image/x-xbitmap"}, .{".xlb" , "application/vnd.ms-excel"}, .{".xls" , "application/excel"}, .{".xls" , "application/vnd.ms-excel"}, // Dup .{".xml" , "text/xml"}, .{".xpdl" , "application/xml"}, .{".xpm" , "image/x-xpixmap"}, .{".xsl" , "application/xml"}, .{".xwd" , "image/x-xwindowdump"}, .{".xul" , "text/xul"}, .{".zip" , "application/zip"}, }; // zig fmt: on // Whitespace characters const WS = " \t\r\n"; // Replace inplace fn replace(line: []u8, find: u8, replacement: u8) void { var i: usize = 0; while (i < line.len) : (i += 1) { if (line[i] == find) line[i] = replacement; } } // Trim that doesn't require a const slice fn trim(slice: []u8, values: []const u8) []u8 { var begin: usize = 0; var end: usize = slice.len; while (begin < end and mem.indexOfScalar(u8, values, slice[begin]) != null) : (begin += 1) {} while (end > begin and mem.indexOfScalar(u8, values, slice[end - 1]) != null) : (end -= 1) {} return slice[begin..end]; } pub const Registry = struct { const StringMap = std.StringHashMap([]const u8); const StringArray = std.ArrayList([]const u8); const StringArrayMap = std.StringHashMap(*StringArray); loaded: bool = false, arena: std.heap.ArenaAllocator, // Maps extension type to mime type type_map: StringMap, // Maps mime type to list of extensions type_map_inv: StringArrayMap, pub fn init(allocator: *Allocator) Registry { // Must call load separately to avoid https://github.com/ziglang/zig/issues/2765 return Registry{ .arena = std.heap.ArenaAllocator.init(allocator), .type_map = StringMap.init(allocator), .type_map_inv = StringArrayMap.init(allocator), }; } // Add a mapping between a type and an extension. // this copies both and will overwrite any existing entries pub fn addType(self: *Registry, ext: []const u8, mime_type: []const u8) !void { // Add '.' if necessary const allocator = &self.arena.allocator; const extension = if (mem.startsWith(u8, ext, ".")) try mem.dupe(allocator, u8, mem.trim(u8, ext, WS)) else try mem.concat(allocator, u8, &[_][]const u8{ ".", mem.trim(u8, ext, WS) }); return self.addTypeInternal(extension, try mem.dupe(allocator, u8, mem.trim(u8, mime_type, WS))); } // Add a mapping between a type and an extension. // this assumes the entries added are already owend fn addTypeInternal(self: *Registry, ext: []const u8, mime_type: []const u8) !void { // std.debug.warn(" adding {}: {} to registry...\n", .{ext, mime_type}); const allocator = &self.arena.allocator; _ = try self.type_map.put(ext, mime_type); if (self.type_map_inv.getEntry(mime_type)) |entry| { // Check if it's already there const type_map = entry.value_ptr.*; for (type_map.items) |e| { if (mem.eql(u8, e, ext)) return; // Already there } try type_map.append(ext); } else { // Create a new list of extensions const extensions = try allocator.create(StringArray); extensions.* = StringArray.init(allocator); _ = try self.type_map_inv.put(mime_type, extensions); try extensions.append(ext); } } pub fn load(self: *Registry) !void { if (self.loaded) return; self.loaded = true; // Load defaults for (extension_map) |entry| { try self.addType(entry[0], entry[1]); } // Load from system if (builtin.os.tag == .windows) { // TODO: Windows } else { try self.loadRegistryLinux(); } } pub fn loadRegistryLinux(self: *Registry) !void { for (known_files) |path| { var file = fs.openFileAbsolute(path, .{ .read = true }) catch continue; // std.debug.warn("Loading {}...\n", .{path}); try self.loadRegistryFile(file); } } // Read a single mime.types-format file. pub fn loadRegistryFile(self: *Registry, file: fs.File) !void { var stream = &std.io.bufferedReader(file.reader()).reader(); var buf: [1024]u8 = undefined; while (true) { const result = try stream.readUntilDelimiterOrEof(&buf, '\n'); if (result == null) break; // EOF var line = trim(result.?, WS); // Strip comments const end = mem.indexOf(u8, line, "#") orelse line.len; line = line[0..end]; // Replace tabs with spaces to normalize so tokenize works replace(line, '\t', ' '); // Empty or no spaces if (line.len == 0 or mem.indexOf(u8, line, " ") == null) continue; var it = mem.tokenize(line, " "); const mime_type = it.next() orelse continue; while (it.next()) |ext| { try self.addType(ext, mime_type); } } } // Guess the mime type from the filename pub fn getTypeFromFilename(self: *Registry, filename: []const u8) ?[]const u8 { const last_dot = mem.lastIndexOf(u8, filename, "."); if (last_dot) |i| return self.getTypeFromExtension(filename[i..]); return null; } // Guess the type of a file based on its URL. pub fn getTypeFromExtension(self: *Registry, ext: []const u8) ?[]const u8 { if (self.type_map.getEntry(ext)) |entry| { return entry.value_ptr.*; } return null; } pub fn getExtensionsByType(self: *Registry, mime_type: []const u8) ?*StringArray { if (self.type_map_inv.getEntry(mime_type)) |entry| { return entry.value_ptr.*; } return null; } pub fn deinit(self: *Registry) void { // Free type self.type_map.deinit(); // Free the type map self.type_map_inv.deinit(); // And free anything else self.arena.deinit(); } }; pub var instance: ?Registry = null; test "guess-ext" { var registry = Registry.init(std.testing.allocator); defer registry.deinit(); try registry.load(); try testing.expectEqualSlices(u8, "image/png", registry.getTypeFromFilename("an-image.png").?); try testing.expectEqualSlices(u8, "application/javascript", registry.getTypeFromFilename("wavascript.js").?); } test "guess-ext-from-file" { var registry = Registry.init(std.testing.allocator); defer registry.deinit(); try registry.load(); // This ext is not in the list above try testing.expectEqualSlices(u8, "application/x-7z-compressed", registry.getTypeFromFilename("archive.7z").?); } test "guess-ext-unknown" { var registry = Registry.init(std.testing.allocator); defer registry.deinit(); try registry.load(); // This ext is not in the list above try testing.expect(registry.getTypeFromFilename("notanext") == null); }
src/mimetypes.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const ArrayList = std.ArrayList; const assert = std.debug.assert; const utils = @import("utils.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const Step = enum { e, se, sw, w, nw, ne }; const AllSteps = [_]Step{ .e, .w, .se, .sw, .ne, .nw }; const Coordinate = struct { x: isize, y: isize, }; fn parse_steps(allo: *std.mem.Allocator, line: []const u8) ArrayList(Step) { // foo var output = ArrayList(Step).init(allo); var ptr: usize = 0; while (ptr < line.len) { if (std.mem.startsWith(u8, line[ptr..], "se")) { output.append(Step.se) catch unreachable; ptr += 2; } else if (std.mem.startsWith(u8, line[ptr..], "sw")) { output.append(Step.sw) catch unreachable; ptr += 2; } else if (std.mem.startsWith(u8, line[ptr..], "ne")) { output.append(Step.ne) catch unreachable; ptr += 2; } else if (std.mem.startsWith(u8, line[ptr..], "nw")) { output.append(Step.nw) catch unreachable; ptr += 2; } else if (std.mem.startsWith(u8, line[ptr..], "e")) { output.append(Step.e) catch unreachable; ptr += 1; } else if (std.mem.startsWith(u8, line[ptr..], "w")) { output.append(Step.w) catch unreachable; ptr += 1; } } return output; } fn follow_steps(steps: []Step, output: *Coordinate) void { for (steps) |step| { switch (step) { .e => output.x += 2, .w => output.x -= 2, .se => { output.x += 1; output.y += 1; }, .sw => { output.x -= 1; output.y += 1; }, .ne => { output.x += 1; output.y -= 1; }, .nw => { output.x -= 1; output.y -= 1; }, } } } fn process_tile(coord: Coordinate, tiles: std.AutoHashMap(Coordinate, bool)) bool { const am_flipped = tiles.get(coord) orelse false; var flipped: usize = 0; for (AllSteps) |step| { var neighbor_coord = Coordinate{ .x = coord.x, .y = coord.y }; follow_steps(&[_]Step{step}, &neighbor_coord); const maybe_neighbor = tiles.get(neighbor_coord); if (maybe_neighbor) |neighbor| { if (neighbor) flipped += 1; } } if (am_flipped) { return !(flipped == 0 or flipped > 2); } else { return (flipped == 2); } } fn count_flipped(tiles: std.AutoHashMap(Coordinate, bool)) usize { var iter = tiles.iterator(); var output: usize = 0; while (iter.next()) |key_val| { if (key_val.value) output += 1; } return output; } pub fn main() !void { const begin = @divTrunc(std.time.nanoTimestamp(), 1000); // setup // defer _ = gpa.deinit(); var allo = &gpa.allocator; var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1"); defer allo.free(lines.buffer); // setup // var seen_tiles = std.AutoHashMap(Coordinate, bool).init(allo); defer seen_tiles.deinit(); while (lines.next()) |line| { const parsed_steps = parse_steps(allo, line); defer parsed_steps.deinit(); var coordinate = Coordinate{ .x = 0, .y = 0 }; follow_steps(parsed_steps.items, &coordinate); var maybe_seen_tile = seen_tiles.get(coordinate); // flip tile if it exists if (maybe_seen_tile) |*seen_tile| { seen_tiles.put(coordinate, !seen_tile.*) catch unreachable; } else { seen_tiles.put(coordinate, true) catch unreachable; } } // p1 // print("p1: {}\n", .{count_flipped(seen_tiles)}); // p2 // var day: usize = 0; while (day < 100) : (day += 1) { var new_seen_tiles = std.AutoHashMap(Coordinate, bool).init(allo); var tile_iter = seen_tiles.iterator(); while (tile_iter.next()) |key_val| { // process all existing tiles const coordinate = key_val.key; const tile_new_state = process_tile(coordinate, seen_tiles); // only put flipped tiles - saves memory and processing if (tile_new_state) { new_seen_tiles.put(coordinate, true) catch unreachable; } for (AllSteps) |step| { var neighbor_coord = Coordinate{ .x = coordinate.x, .y = coordinate.y }; follow_steps(&[_]Step{step}, &neighbor_coord); const neighbor_new_state = process_tile(neighbor_coord, seen_tiles); if (neighbor_new_state) { new_seen_tiles.put(neighbor_coord, neighbor_new_state) catch unreachable; } } } seen_tiles.clearAndFree(); seen_tiles = new_seen_tiles; } // p2 final print("p2: {}\n", .{count_flipped(seen_tiles)}); // end // const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin; print("all done in {} microseconds\n", .{delta}); }
day_24/src/main.zig
const clap = @import("clap"); const std = @import("std"); const ArgIterator = @import("arg_iterator.zig"); const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); const Allocator = std.mem.Allocator; pub fn arch(allocator: *Allocator, it: *ArgIterator) !void { // TODO: remove Arch. from beginning of print try stdout.print("{}\n", .{std.builtin.arch}); return error.Todo; } pub fn ascii(allocator: *Allocator, it: *ArgIterator) !void { try stdout.writeAll( \\Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex Dec Hex \\ 0 00 NUL 16 10 DLE 32 20 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p \\ 1 01 SOH 17 11 DC1 33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q \\ 2 02 STX 18 12 DC2 34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r \\ 3 03 ETX 19 13 DC3 35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s \\ 4 04 EOT 20 14 DC4 36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t \\ 5 05 ENQ 21 15 NAK 37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u \\ 6 06 ACK 22 16 SYN 38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v \\ 7 07 BEL 23 17 ETB 39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w \\ 8 08 BS 24 18 CAN 40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x \\ 9 09 HT 25 19 EM 41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y \\ 10 0A LF 26 1A SUB 42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z \\ 11 0B VT 27 1B ESC 43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B { \\ 12 0C FF 28 1C FS 44 2C , 60 3C < 76 4C L 92 5C \ 108 6C l 124 7C | \\ 13 0D CR 29 1D GS 45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D } \\ 14 0E SO 30 1E RS 46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~ \\ 15 0F SI 31 1F US 47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL \\ ); } pub fn base64(allocator: *Allocator, it: *ArgIterator) !void { const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h Display this help and exit") catch unreachable, clap.parseParam("-d Decode") catch unreachable, clap.parseParam("-i Ignore non-alphanumeric characters") catch unreachable, clap.parseParam("-w <COLUMNS> Wrap output at COLUMS (default 76, or 0 for nowrap)") catch unreachable, }; var args = try clap.ComptimeClap(clap.Help, &params).parse(allocator, ArgIterator, it); defer args.deinit(); var buf_plain: [3 * std.mem.page_size]u8 = undefined; var buf_encoded: [4 * std.mem.page_size]u8 = undefined; const encoding = !args.flag("-d"); if (encoding) { const encoder = std.base64.standard_encoder; const n = try stdin.read(&buf_plain); const enc_n = std.base64.Base64Encoder.calcSize(n); encoder.encode(buf_encoded[0..enc_n], buf_plain[0..n]); _ = try stdout.write(buf_encoded[0..enc_n]); _ = try stdout.write("\n"); return error.Todo; } else { return error.Todo; } }
src/commands.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const customsDeclarations = @embedFile("input06.txt"); fn isSpace(line: []const u8) bool { for (line) |c| { if (!std.ascii.isSpace(c)) return false; } return true; } const Declaration = struct { total: u32, fields: [27]u32 }; fn getAllDeclarations(allocator: *Allocator) !std.ArrayList(Declaration) { var declarations = std.ArrayList(Declaration).init(allocator); var lines = std.mem.split(customsDeclarations, "\n"); var total: u32 = 0; var fields: [27]u32 = undefined; std.mem.set(u32, &fields, 0); while (lines.next()) |line| { if (isSpace(line)) { try declarations.append(Declaration{ .total = total, .fields = fields, }); std.mem.set(u32, &fields, 0); total = 0; } else { total += 1; for (line) |c| { if (std.ascii.isAlpha(c)) { fields[c - 'a'] += 1; } } } } try declarations.append(Declaration{ .total = total, .fields = fields, }); return declarations; } fn printDeclaration(declaration: [27]u32) void { var index: u8 = 0; while (index < 27) : (index += 1) { if (declaration[index] > 0) print("{c}, ", .{index + 'a'}); } print("\n", .{}); } fn part1() !void { print("Part1:\n", .{}); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var declarations = try getAllDeclarations(&gpa.allocator); defer declarations.deinit(); var total: u32 = 0; for (declarations.items) |declaration| { for (declaration.fields) |c| { if (c > 0) total += 1; } } print("Total: {}\n", .{total}); } fn part2() !void { print("\nPart2:\n", .{}); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var declarations = try getAllDeclarations(&gpa.allocator); defer declarations.deinit(); var total: u32 = 0; for (declarations.items) |declaration| { for (declaration.fields) |c| { if (c == declaration.total) { total += 1; } } } print("Total: {}\n", .{total}); } pub fn main() !void { try part1(); try part2(); }
src/day06.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w = zwin32.base; const d3d = zwin32.d3d; const d3d12 = zwin32.d3d12; const wasapi = zwin32.wasapi; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const zd3d12 = @import("zd3d12"); const common = @import("common"); const c = common.c; const vm = common.vectormath; const GuiRenderer = common.GuiRenderer; const Vec2 = vm.Vec2; const Vec3 = vm.Vec3; const Vec4 = vm.Vec4; const Mat4 = vm.Mat4; pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const window_name = "zig-gamedev: bindless"; const window_width = 1920; const window_height = 1080; const env_texture_resolution = 512; const irradiance_texture_resolution = 64; const prefiltered_env_texture_resolution = 256; const prefiltered_env_texture_num_mip_levels = 6; const brdf_integration_texture_resolution = 512; const mesh_cube = 0; const mesh_helmet = 1; const Vertex = struct { position: [3]f32, normal: [3]f32, texcoords0: [2]f32, tangent: [4]f32, }; comptime { assert(@sizeOf([2]Vertex) == 2 * 48); assert(@alignOf([2]Vertex) == 4); } // In this demo program, Mesh is just a range of vertices/indices in a single global vertex/index buffer. const Mesh = struct { index_offset: u32, vertex_offset: u32, num_indices: u32, }; const Scene_Const = extern struct { world_to_clip: Mat4, camera_position: Vec3, draw_mode: i32, }; const Draw_Const = extern struct { object_to_world: Mat4, base_color_index: u32, ao_index: u32, metallic_roughness_index: u32, normal_index: u32, }; const ResourceView = struct { resource: zd3d12.ResourceHandle, view: d3d12.CPU_DESCRIPTOR_HANDLE, }; const Texture = struct { resource: zd3d12.ResourceHandle, persistent_descriptor: zd3d12.PersistentDescriptor, }; const texture_ao: u32 = 0; const texture_base_color: u32 = 1; const texture_metallic_roughness: u32 = 2; const texture_normal: u32 = 3; const DemoState = struct { grfx: zd3d12.GraphicsContext, gui: GuiRenderer, frame_stats: common.FrameStats, depth_texture: ResourceView, mesh_pbr_pso: zd3d12.PipelineHandle, sample_env_texture_pso: zd3d12.PipelineHandle, meshes: std.ArrayList(Mesh), vertex_buffer: zd3d12.ResourceHandle, index_buffer: zd3d12.ResourceHandle, mesh_textures: [4]Texture, env_texture: ResourceView, irradiance_texture: ResourceView, prefiltered_env_texture: ResourceView, brdf_integration_texture: ResourceView, draw_mode: i32, camera: struct { position: Vec3, forward: Vec3, pitch: f32, yaw: f32, }, mouse: struct { cursor_prev_x: i32, cursor_prev_y: i32, }, }; fn loadMesh( arena: std.mem.Allocator, file_path: []const u8, all_meshes: *std.ArrayList(Mesh), all_vertices: *std.ArrayList(Vertex), all_indices: *std.ArrayList(u32), ) void { var indices = std.ArrayList(u32).init(arena); var positions = std.ArrayList([3]f32).init(arena); var normals = std.ArrayList([3]f32).init(arena); var texcoords0 = std.ArrayList([2]f32).init(arena); var tangents = std.ArrayList([4]f32).init(arena); const pre_indices_len = all_indices.items.len; const pre_positions_len = all_vertices.items.len; const data = common.parseAndLoadGltfFile(file_path); defer c.cgltf_free(data); common.appendMeshPrimitive(data, 0, 0, &indices, &positions, &normals, &texcoords0, &tangents); all_meshes.append(.{ .index_offset = @intCast(u32, pre_indices_len), .vertex_offset = @intCast(u32, pre_positions_len), .num_indices = @intCast(u32, indices.items.len - pre_indices_len), }) catch unreachable; all_indices.ensureTotalCapacity(indices.items.len) catch unreachable; for (indices.items) |mesh_index| { all_indices.appendAssumeCapacity(mesh_index); } all_vertices.ensureTotalCapacity(positions.items.len) catch unreachable; for (positions.items) |_, index| { all_vertices.appendAssumeCapacity(.{ .position = positions.items[index], .normal = normals.items[index], .texcoords0 = texcoords0.items[index], .tangent = tangents.items[index], }); } } fn drawToCubeTexture( grfx: *zd3d12.GraphicsContext, dest_texture: zd3d12.ResourceHandle, dest_mip_level: u32, ) void { const desc = grfx.getResourceDesc(dest_texture); assert(dest_mip_level < desc.MipLevels); const texture_width = @intCast(u32, desc.Width) >> @intCast(u5, dest_mip_level); const texture_height = desc.Height >> @intCast(u5, dest_mip_level); assert(texture_width == texture_height); grfx.cmdlist.RSSetViewports(1, &[_]d3d12.VIEWPORT{.{ .TopLeftX = 0.0, .TopLeftY = 0.0, .Width = @intToFloat(f32, texture_width), .Height = @intToFloat(f32, texture_height), .MinDepth = 0.0, .MaxDepth = 1.0, }}); grfx.cmdlist.RSSetScissorRects(1, &[_]d3d12.RECT{.{ .left = 0, .top = 0, .right = @intCast(c_long, texture_width), .bottom = @intCast(c_long, texture_height), }}); grfx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); const zero = Vec3.initZero(); const object_to_view = [_]Mat4{ Mat4.initLookToLh(zero, Vec3.init(1.0, 0.0, 0.0), Vec3.init(0.0, 1.0, 0.0)), Mat4.initLookToLh(zero, Vec3.init(-1.0, 0.0, 0.0), Vec3.init(0.0, 1.0, 0.0)), Mat4.initLookToLh(zero, Vec3.init(0.0, 1.0, 0.0), Vec3.init(0.0, 0.0, -1.0)), Mat4.initLookToLh(zero, Vec3.init(0.0, -1.0, 0.0), Vec3.init(0.0, 0.0, 1.0)), Mat4.initLookToLh(zero, Vec3.init(0.0, 0.0, 1.0), Vec3.init(0.0, 1.0, 0.0)), Mat4.initLookToLh(zero, Vec3.init(0.0, 0.0, -1.0), Vec3.init(0.0, 1.0, 0.0)), }; const view_to_clip = Mat4.initPerspectiveFovLh(math.pi * 0.5, 1.0, 0.1, 10.0); var cube_face_idx: u32 = 0; while (cube_face_idx < 6) : (cube_face_idx += 1) { const cube_face_rtv = grfx.allocateTempCpuDescriptors(.RTV, 1); grfx.device.CreateRenderTargetView( grfx.lookupResource(dest_texture).?, &d3d12.RENDER_TARGET_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURE2DARRAY, .u = .{ .Texture2DArray = .{ .MipSlice = dest_mip_level, .FirstArraySlice = cube_face_idx, .ArraySize = 1, .PlaneSlice = 0, }, }, }, cube_face_rtv, ); grfx.addTransitionBarrier(dest_texture, d3d12.RESOURCE_STATE_RENDER_TARGET); grfx.flushResourceBarriers(); grfx.cmdlist.OMSetRenderTargets(1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{cube_face_rtv}, w.TRUE, null); grfx.deallocateAllTempCpuDescriptors(.RTV); const mem = grfx.allocateUploadMemory(Mat4, 1); mem.cpu_slice[0] = object_to_view[cube_face_idx].mul(view_to_clip).transpose(); grfx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base); // NOTE(mziulek): We assume that the first mesh in vertex/index buffer is a 'cube'. grfx.cmdlist.DrawIndexedInstanced(36, 1, 0, 0, 0); } grfx.addTransitionBarrier(dest_texture, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); } fn init(gpa_allocator: std.mem.Allocator) DemoState { const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable; var grfx = zd3d12.GraphicsContext.init(gpa_allocator, window); // V-Sync grfx.present_flags = 0; grfx.present_interval = 1; var arena_allocator_state = std.heap.ArenaAllocator.init(gpa_allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); const mesh_pbr_pso = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Texcoords", 0, .R32G32_FLOAT, 0, 24, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Tangent", 0, .R32G32B32A32_FLOAT, 0, 32, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.DSVFormat = .D32_FLOAT; pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; break :blk grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/mesh_pbr.vs.cso", content_dir ++ "shaders/mesh_pbr.ps.cso", ); }; const sample_env_texture_pso = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Texcoords", 0, .R32G32_FLOAT, 0, 24, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Tangent", 0, .R32G32B32A32_FLOAT, 0, 32, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.DSVFormat = .D32_FLOAT; pso_desc.RasterizerState.CullMode = .FRONT; pso_desc.DepthStencilState.DepthFunc = .LESS_EQUAL; pso_desc.DepthStencilState.DepthWriteMask = .ZERO; pso_desc.PrimitiveTopologyType = .TRIANGLE; break :blk grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/sample_env_texture.vs.cso", content_dir ++ "shaders/sample_env_texture.ps.cso", ); }; const temp_pipelines = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Texcoords", 0, .R32G32_FLOAT, 0, 24, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Tangent", 0, .R32G32B32A32_FLOAT, 0, 32, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R16G16B16A16_FLOAT; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.DepthStencilState.DepthEnable = w.FALSE; pso_desc.RasterizerState.CullMode = .FRONT; pso_desc.PrimitiveTopologyType = .TRIANGLE; const generate_env_texture_pso = grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/generate_env_texture.vs.cso", content_dir ++ "shaders/generate_env_texture.ps.cso", ); const generate_irradiance_texture_pso = grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/generate_irradiance_texture.vs.cso", content_dir ++ "shaders/generate_irradiance_texture.ps.cso", ); const generate_prefiltered_env_texture_pso = grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/generate_prefiltered_env_texture.vs.cso", content_dir ++ "shaders/generate_prefiltered_env_texture.ps.cso", ); const generate_brdf_integration_texture_pso = grfx.createComputeShaderPipeline( arena_allocator, &d3d12.COMPUTE_PIPELINE_STATE_DESC.initDefault(), content_dir ++ "shaders/generate_brdf_integration_texture.cs.cso", ); break :blk .{ .generate_env_texture_pso = generate_env_texture_pso, .generate_irradiance_texture_pso = generate_irradiance_texture_pso, .generate_prefiltered_env_texture_pso = generate_prefiltered_env_texture_pso, .generate_brdf_integration_texture_pso = generate_brdf_integration_texture_pso, }; }; var all_meshes = std.ArrayList(Mesh).init(gpa_allocator); var all_vertices = std.ArrayList(Vertex).init(arena_allocator); var all_indices = std.ArrayList(u32).init(arena_allocator); loadMesh(arena_allocator, content_dir ++ "cube.gltf", &all_meshes, &all_vertices, &all_indices); loadMesh( arena_allocator, content_dir ++ "SciFiHelmet/SciFiHelmet.gltf", &all_meshes, &all_vertices, &all_indices, ); const depth_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, grfx.viewport_width, grfx.viewport_height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE; break :blk desc; }, d3d12.RESOURCE_STATE_DEPTH_WRITE, &d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0), ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.DSV, 1), }; grfx.device.CreateDepthStencilView( grfx.lookupResource(depth_texture.resource).?, null, depth_texture.view, ); var mipgen_rgba8 = zd3d12.MipmapGenerator.init(arena_allocator, &grfx, .R8G8B8A8_UNORM, content_dir); var mipgen_rgba16f = zd3d12.MipmapGenerator.init(arena_allocator, &grfx, .R16G16B16A16_FLOAT, content_dir); grfx.beginFrame(); var gui = GuiRenderer.init(arena_allocator, &grfx, 1, content_dir); const vertex_buffer = blk: { var vertex_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_vertices.items.len * @sizeOf(Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const upload = grfx.allocateUploadBufferRegion(Vertex, @intCast(u32, all_vertices.items.len)); for (all_vertices.items) |vertex, i| { upload.cpu_slice[i] = vertex; } grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(vertex_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(vertex_buffer, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); break :blk vertex_buffer; }; const index_buffer = blk: { var index_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_indices.items.len * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const upload = grfx.allocateUploadBufferRegion(u32, @intCast(u32, all_indices.items.len)); for (all_indices.items) |index, i| { upload.cpu_slice[i] = index; } grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(index_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(index_buffer, d3d12.RESOURCE_STATE_INDEX_BUFFER); break :blk index_buffer; }; // // BEGIN: Upload texture data to the GPU. // const equirect_texture = blk: { var width: u32 = 0; var height: u32 = 0; c.stbi_set_flip_vertically_on_load(1); const image_data = c.stbi_loadf( content_dir ++ "Newport_Loft.hdr", @ptrCast(*i32, &width), @ptrCast(*i32, &height), null, 3, ); assert(image_data != null and width > 0 and height > 0); const equirect_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initTex2d(.R32G32B32_FLOAT, width, height, 1), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1), }; grfx.device.CreateShaderResourceView( grfx.lookupResource(equirect_texture.resource).?, null, equirect_texture.view, ); grfx.updateTex2dSubresource( equirect_texture.resource, 0, std.mem.sliceAsBytes(image_data[0 .. width * height * 3]), width * @sizeOf(f32) * 3, ); c.stbi_image_free(image_data); grfx.addTransitionBarrier(equirect_texture.resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); break :blk equirect_texture; }; var mesh_textures: [4]Texture = undefined; { const resource = grfx.createAndUploadTex2dFromFile( content_dir ++ "SciFiHelmet/SciFiHelmet_AmbientOcclusion.png", .{}, ) catch |err| hrPanic(err); _ = grfx.lookupResource(resource).?.SetName(L("SciFiHelmet/SciFiHelmet_AmbientOcclusion.png")); mesh_textures[texture_ao] = blk: { const srv_allocation = grfx.allocatePersistentGpuDescriptors(1); grfx.device.CreateShaderResourceView( grfx.lookupResource(resource).?, null, srv_allocation.cpu_handle, ); mipgen_rgba8.generateMipmaps(&grfx, resource); grfx.addTransitionBarrier(resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); const t = Texture{ .resource = resource, .persistent_descriptor = srv_allocation, }; break :blk t; }; } { const resource = grfx.createAndUploadTex2dFromFile( content_dir ++ "SciFiHelmet/SciFiHelmet_BaseColor.png", .{}, ) catch |err| hrPanic(err); _ = grfx.lookupResource(resource).?.SetName(L("SciFiHelmet/SciFiHelmet_BaseColor.png")); mesh_textures[texture_base_color] = blk: { const srv_allocation = grfx.allocatePersistentGpuDescriptors(1); grfx.device.CreateShaderResourceView( grfx.lookupResource(resource).?, null, srv_allocation.cpu_handle, ); mipgen_rgba8.generateMipmaps(&grfx, resource); grfx.addTransitionBarrier(resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); const t = Texture{ .resource = resource, .persistent_descriptor = srv_allocation, }; break :blk t; }; } { const resource = grfx.createAndUploadTex2dFromFile( content_dir ++ "SciFiHelmet/SciFiHelmet_MetallicRoughness.png", .{}, ) catch |err| hrPanic(err); _ = grfx.lookupResource(resource).?.SetName(L("SciFiHelmet/SciFiHelmet_MetallicRoughness.png")); mesh_textures[texture_metallic_roughness] = blk: { const srv_allocation = grfx.allocatePersistentGpuDescriptors(1); grfx.device.CreateShaderResourceView( grfx.lookupResource(resource).?, null, srv_allocation.cpu_handle, ); mipgen_rgba8.generateMipmaps(&grfx, resource); grfx.addTransitionBarrier(resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); const t = Texture{ .resource = resource, .persistent_descriptor = srv_allocation, }; break :blk t; }; } { const resource = grfx.createAndUploadTex2dFromFile( content_dir ++ "SciFiHelmet/SciFiHelmet_Normal.png", .{}, ) catch |err| hrPanic(err); _ = grfx.lookupResource(resource).?.SetName(L("SciFiHelmet/SciFiHelmet_Normal.png")); mesh_textures[texture_normal] = blk: { const srv_allocation = grfx.allocatePersistentGpuDescriptors(1); grfx.device.CreateShaderResourceView( grfx.lookupResource(resource).?, null, srv_allocation.cpu_handle, ); mipgen_rgba8.generateMipmaps(&grfx, resource); grfx.addTransitionBarrier(resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); const t = Texture{ .resource = resource, .persistent_descriptor = srv_allocation, }; break :blk t; }; } const env_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC{ .Dimension = .TEXTURE2D, .Alignment = 0, .Width = env_texture_resolution, .Height = env_texture_resolution, .DepthOrArraySize = 6, .MipLevels = 0, .Format = .R16G16B16A16_FLOAT, .SampleDesc = .{ .Count = 1, .Quality = 0 }, .Layout = .UNKNOWN, .Flags = d3d12.RESOURCE_FLAG_ALLOW_RENDER_TARGET, }, d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1), }; grfx.device.CreateShaderResourceView( grfx.lookupResource(env_texture.resource).?, &d3d12.SHADER_RESOURCE_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURECUBE, .Shader4ComponentMapping = d3d12.DEFAULT_SHADER_4_COMPONENT_MAPPING, .u = .{ .TextureCube = .{ .MipLevels = 0xffff_ffff, .MostDetailedMip = 0, .ResourceMinLODClamp = 0.0, }, }, }, env_texture.view, ); const irradiance_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC{ .Dimension = .TEXTURE2D, .Alignment = 0, .Width = irradiance_texture_resolution, .Height = irradiance_texture_resolution, .DepthOrArraySize = 6, .MipLevels = 0, .Format = .R16G16B16A16_FLOAT, .SampleDesc = .{ .Count = 1, .Quality = 0 }, .Layout = .UNKNOWN, .Flags = d3d12.RESOURCE_FLAG_ALLOW_RENDER_TARGET, }, d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1), }; grfx.device.CreateShaderResourceView( grfx.lookupResource(irradiance_texture.resource).?, &d3d12.SHADER_RESOURCE_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURECUBE, .Shader4ComponentMapping = d3d12.DEFAULT_SHADER_4_COMPONENT_MAPPING, .u = .{ .TextureCube = .{ .MipLevels = 0xffff_ffff, .MostDetailedMip = 0, .ResourceMinLODClamp = 0.0, }, }, }, irradiance_texture.view, ); const prefiltered_env_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC{ .Dimension = .TEXTURE2D, .Alignment = 0, .Width = prefiltered_env_texture_resolution, .Height = prefiltered_env_texture_resolution, .DepthOrArraySize = 6, .MipLevels = prefiltered_env_texture_num_mip_levels, .Format = .R16G16B16A16_FLOAT, .SampleDesc = .{ .Count = 1, .Quality = 0 }, .Layout = .UNKNOWN, .Flags = d3d12.RESOURCE_FLAG_ALLOW_RENDER_TARGET, }, d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1), }; grfx.device.CreateShaderResourceView( grfx.lookupResource(prefiltered_env_texture.resource).?, &d3d12.SHADER_RESOURCE_VIEW_DESC{ .Format = .UNKNOWN, .ViewDimension = .TEXTURECUBE, .Shader4ComponentMapping = d3d12.DEFAULT_SHADER_4_COMPONENT_MAPPING, .u = .{ .TextureCube = .{ .MipLevels = prefiltered_env_texture_num_mip_levels, .MostDetailedMip = 0, .ResourceMinLODClamp = 0.0, }, }, }, prefiltered_env_texture.view, ); const brdf_integration_texture = .{ .resource = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d( .R16G16_FLOAT, brdf_integration_texture_resolution, brdf_integration_texture_resolution, 1, // mip levels ); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; break :blk desc; }, d3d12.RESOURCE_STATE_UNORDERED_ACCESS, null, ) catch |err| hrPanic(err), .view = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1), }; grfx.device.CreateShaderResourceView( grfx.lookupResource(brdf_integration_texture.resource).?, null, brdf_integration_texture.view, ); grfx.flushResourceBarriers(); grfx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = grfx.lookupResource(vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(vertex_buffer)), .StrideInBytes = @sizeOf(Vertex), }}); grfx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = grfx.lookupResource(index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(index_buffer)), .Format = .R32_UINT, }); // // Generate env. (cube) texture content. // grfx.setCurrentPipeline(temp_pipelines.generate_env_texture_pso); grfx.cmdlist.SetGraphicsRootDescriptorTable(1, grfx.copyDescriptorsToGpuHeap(1, equirect_texture.view)); drawToCubeTexture(&grfx, env_texture.resource, 0); mipgen_rgba16f.generateMipmaps(&grfx, env_texture.resource); grfx.addTransitionBarrier(env_texture.resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); // // Generate irradiance (cube) texture content. // grfx.setCurrentPipeline(temp_pipelines.generate_irradiance_texture_pso); grfx.cmdlist.SetGraphicsRootDescriptorTable(1, grfx.copyDescriptorsToGpuHeap(1, env_texture.view)); drawToCubeTexture(&grfx, irradiance_texture.resource, 0); mipgen_rgba16f.generateMipmaps(&grfx, irradiance_texture.resource); grfx.addTransitionBarrier(irradiance_texture.resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); // // Generate prefiltered env. (cube) texture content. // grfx.setCurrentPipeline(temp_pipelines.generate_prefiltered_env_texture_pso); grfx.cmdlist.SetGraphicsRootDescriptorTable(2, grfx.copyDescriptorsToGpuHeap(1, env_texture.view)); { var mip_level: u32 = 0; while (mip_level < prefiltered_env_texture_num_mip_levels) : (mip_level += 1) { const roughness = @intToFloat(f32, mip_level) / @intToFloat(f32, prefiltered_env_texture_num_mip_levels - 1); grfx.cmdlist.SetGraphicsRoot32BitConstant(1, @bitCast(u32, roughness), 0); drawToCubeTexture(&grfx, prefiltered_env_texture.resource, mip_level); } } grfx.addTransitionBarrier(prefiltered_env_texture.resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); // // Generate BRDF integration texture. // { const uav = grfx.allocateTempCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateUnorderedAccessView( grfx.lookupResource(brdf_integration_texture.resource).?, null, null, uav, ); grfx.setCurrentPipeline(temp_pipelines.generate_brdf_integration_texture_pso); grfx.cmdlist.SetComputeRootDescriptorTable(0, grfx.copyDescriptorsToGpuHeap(1, uav)); const num_groups = @divExact(brdf_integration_texture_resolution, 8); grfx.cmdlist.Dispatch(num_groups, num_groups, 1); grfx.addTransitionBarrier(brdf_integration_texture.resource, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); grfx.deallocateAllTempCpuDescriptors(.CBV_SRV_UAV); } grfx.endFrame(); grfx.finishGpuCommands(); // Release temporary resources. mipgen_rgba8.deinit(&grfx); mipgen_rgba16f.deinit(&grfx); grfx.destroyResource(equirect_texture.resource); grfx.destroyPipeline(temp_pipelines.generate_env_texture_pso); grfx.destroyPipeline(temp_pipelines.generate_irradiance_texture_pso); grfx.destroyPipeline(temp_pipelines.generate_prefiltered_env_texture_pso); grfx.destroyPipeline(temp_pipelines.generate_brdf_integration_texture_pso); return .{ .grfx = grfx, .gui = gui, .frame_stats = common.FrameStats.init(), .depth_texture = depth_texture, .mesh_pbr_pso = mesh_pbr_pso, .sample_env_texture_pso = sample_env_texture_pso, .meshes = all_meshes, .mesh_textures = mesh_textures, .env_texture = env_texture, .irradiance_texture = irradiance_texture, .prefiltered_env_texture = prefiltered_env_texture, .brdf_integration_texture = brdf_integration_texture, .vertex_buffer = vertex_buffer, .index_buffer = index_buffer, .draw_mode = 0, .camera = .{ .position = Vec3.init(2.2, 0.0, 2.2), .forward = Vec3.initZero(), .pitch = 0.0, .yaw = math.pi + 0.25 * math.pi, }, .mouse = .{ .cursor_prev_x = 0, .cursor_prev_y = 0, }, }; } fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void { demo.grfx.finishGpuCommands(); demo.meshes.deinit(); demo.gui.deinit(&demo.grfx); demo.grfx.deinit(gpa_allocator); common.deinitWindow(gpa_allocator); demo.* = undefined; } fn update(demo: *DemoState) void { demo.frame_stats.update(demo.grfx.window, window_name); common.newImGuiFrame(demo.frame_stats.delta_time); c.igSetNextWindowPos( c.ImVec2{ .x = @intToFloat(f32, demo.grfx.viewport_width) - 600.0 - 20, .y = 20.0 }, c.ImGuiCond_FirstUseEver, c.ImVec2{ .x = 0.0, .y = 0.0 }, ); c.igSetNextWindowSize(c.ImVec2{ .x = 600.0, .y = 0.0 }, c.ImGuiCond_FirstUseEver); _ = c.igBegin( "Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoSavedSettings, ); _ = c.igRadioButton_IntPtr("Draw PBR effect", &demo.draw_mode, 0); _ = c.igRadioButton_IntPtr("Draw Ambient Occlusion texture", &demo.draw_mode, 1); _ = c.igRadioButton_IntPtr("Draw Base Color texture", &demo.draw_mode, 2); _ = c.igRadioButton_IntPtr("Draw Metallic texture", &demo.draw_mode, 3); _ = c.igRadioButton_IntPtr("Draw Roughness texture", &demo.draw_mode, 4); _ = c.igRadioButton_IntPtr("Draw Normal texture", &demo.draw_mode, 5); c.igEnd(); // Handle camera rotation with mouse. { var pos: w.POINT = undefined; _ = w.GetCursorPos(&pos); const delta_x = @intToFloat(f32, pos.x) - @intToFloat(f32, demo.mouse.cursor_prev_x); const delta_y = @intToFloat(f32, pos.y) - @intToFloat(f32, demo.mouse.cursor_prev_y); demo.mouse.cursor_prev_x = pos.x; demo.mouse.cursor_prev_y = pos.y; if (w.GetAsyncKeyState(w.VK_RBUTTON) < 0) { demo.camera.pitch += 0.0025 * delta_y; demo.camera.yaw += 0.0025 * delta_x; demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi); demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi); demo.camera.yaw = vm.modAngle(demo.camera.yaw); } } // Handle camera movement with 'WASD' keys. { const speed: f32 = 5.0; const delta_time = demo.frame_stats.delta_time; const transform = Mat4.initRotationX(demo.camera.pitch).mul(Mat4.initRotationY(demo.camera.yaw)); var forward = Vec3.init(0.0, 0.0, 1.0).transform(transform).normalize(); demo.camera.forward = forward; const right = Vec3.init(0.0, 1.0, 0.0).cross(forward).normalize().scale(speed * delta_time); forward = forward.scale(speed * delta_time); if (w.GetAsyncKeyState('W') < 0) { demo.camera.position = demo.camera.position.add(forward); } else if (w.GetAsyncKeyState('S') < 0) { demo.camera.position = demo.camera.position.sub(forward); } if (w.GetAsyncKeyState('D') < 0) { demo.camera.position = demo.camera.position.add(right); } else if (w.GetAsyncKeyState('A') < 0) { demo.camera.position = demo.camera.position.sub(right); } } } fn draw(demo: *DemoState) void { var grfx = &demo.grfx; grfx.beginFrame(); const cam_world_to_view = vm.Mat4.initLookToLh( demo.camera.position, demo.camera.forward, vm.Vec3.init(0.0, 1.0, 0.0), ); const cam_view_to_clip = vm.Mat4.initPerspectiveFovLh( math.pi / 3.0, @intToFloat(f32, grfx.viewport_width) / @intToFloat(f32, grfx.viewport_height), 0.1, 100.0, ); const cam_world_to_clip = cam_world_to_view.mul(cam_view_to_clip); const back_buffer = grfx.getBackBuffer(); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); grfx.flushResourceBarriers(); grfx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w.TRUE, &demo.depth_texture.view, ); grfx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.0, 0.0, 0.0, 0.0 }, 0, null, ); grfx.cmdlist.ClearDepthStencilView(demo.depth_texture.view, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null); grfx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); grfx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = grfx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(demo.vertex_buffer)), .StrideInBytes = @sizeOf(Vertex), }}); grfx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = grfx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(demo.index_buffer)), .Format = .R32_UINT, }); grfx.setCurrentPipeline(demo.mesh_pbr_pso); // Set scene constants { const mem = grfx.allocateUploadMemory(Scene_Const, 1); mem.cpu_slice[0] = .{ .world_to_clip = cam_world_to_clip.transpose(), .camera_position = demo.camera.position, .draw_mode = demo.draw_mode, }; grfx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base); } // Draw SciFiHelmet. { const object_to_world = vm.Mat4.initRotationY(@floatCast(f32, 0.25 * demo.frame_stats.time)); const mem = grfx.allocateUploadMemory(Draw_Const, 1); mem.cpu_slice[0] = .{ .object_to_world = object_to_world.transpose(), .base_color_index = demo.mesh_textures[texture_base_color].persistent_descriptor.index, .ao_index = demo.mesh_textures[texture_ao].persistent_descriptor.index, .metallic_roughness_index = demo.mesh_textures[texture_metallic_roughness].persistent_descriptor.index, .normal_index = demo.mesh_textures[texture_normal].persistent_descriptor.index, }; grfx.cmdlist.SetGraphicsRootConstantBufferView(1, mem.gpu_base); grfx.cmdlist.SetGraphicsRootDescriptorTable(2, blk: { const table = grfx.copyDescriptorsToGpuHeap(1, demo.irradiance_texture.view); _ = grfx.copyDescriptorsToGpuHeap(1, demo.prefiltered_env_texture.view); _ = grfx.copyDescriptorsToGpuHeap(1, demo.brdf_integration_texture.view); break :blk table; }); grfx.cmdlist.DrawIndexedInstanced( demo.meshes.items[mesh_helmet].num_indices, 1, demo.meshes.items[mesh_helmet].index_offset, @intCast(i32, demo.meshes.items[mesh_helmet].vertex_offset), 0, ); } // Draw env. cube texture. { var world_to_view_origin = cam_world_to_view; world_to_view_origin.r[3] = Vec4.init(0.0, 0.0, 0.0, 1.0); const mem = grfx.allocateUploadMemory(Mat4, 1); mem.cpu_slice[0] = world_to_view_origin.mul(cam_view_to_clip).transpose(); grfx.setCurrentPipeline(demo.sample_env_texture_pso); grfx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base); grfx.cmdlist.SetGraphicsRootDescriptorTable(1, grfx.copyDescriptorsToGpuHeap(1, demo.env_texture.view)); grfx.cmdlist.DrawIndexedInstanced( demo.meshes.items[mesh_cube].num_indices, 1, demo.meshes.items[mesh_cube].index_offset, @intCast(i32, demo.meshes.items[mesh_cube].vertex_offset), 0, ); } demo.gui.draw(grfx); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); grfx.flushResourceBarriers(); grfx.endFrame(); } pub fn main() !void { common.init(); defer common.deinit(); var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa_allocator_state.deinit(); std.debug.assert(leaked == false); } const gpa_allocator = gpa_allocator_state.allocator(); var demo = init(gpa_allocator); defer deinit(&demo, gpa_allocator); while (true) { var message = std.mem.zeroes(w.user32.MSG); const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch unreachable; if (has_message) { _ = w.user32.translateMessage(&message); _ = w.user32.dispatchMessageA(&message); if (message.message == w.user32.WM_QUIT) { break; } } else { update(&demo); draw(&demo); } } }
samples/bindless/src/bindless.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { _ = input_text; // part1 (buggué car fait tout les karts en un coup et donc ils pourraient se croiser sans crasher "effet tunnel" -> mais ça passe) const ans1 = ans: { const desired_nb_scores = 260321; var scores: [256 * 1024]u4 = undefined; scores[0] = 3; scores[1] = 7; var nb_scores: usize = 2; var elf1: usize = 0; var elf2: usize = 1; while (nb_scores < desired_nb_scores + 10) { const new: u5 = @intCast(u5, scores[elf1]) + scores[elf2]; if (new >= 10) { scores[nb_scores] = @intCast(u4, new / 10); nb_scores += 1; } scores[nb_scores] = @intCast(u4, new % 10); nb_scores += 1; elf1 = (elf1 + scores[elf1] + 1) % nb_scores; elf2 = (elf2 + scores[elf2] + 1) % nb_scores; } var ans: u64 = 0; for (scores[desired_nb_scores .. desired_nb_scores + 10]) |s| { ans = ans * 10 + s; } break :ans ans; }; // part2 const ans2 = ans: { const desired_final_digits = [_]u4{ 2, 6, 0, 3, 2, 1 }; const scores = try allocator.alloc(u4, 128 * 1024 * 1024); defer allocator.free(scores); scores[0] = 3; scores[1] = 7; var nb_scores: usize = 2; var elf1: usize = 0; var elf2: usize = 1; while (!std.mem.endsWith(u4, scores[0..nb_scores], &desired_final_digits) and !std.mem.endsWith(u4, scores[0 .. nb_scores - 1], &desired_final_digits)) { const new: u5 = @intCast(u5, scores[elf1]) + scores[elf2]; if (new >= 10) { scores[nb_scores] = @intCast(u4, new / 10); nb_scores += 1; // /!\ le piège est ici! la sequence peut être un cran avant la fin... } scores[nb_scores] = @intCast(u4, new % 10); nb_scores += 1; elf1 = (elf1 + scores[elf1] + 1) % nb_scores; elf2 = (elf2 + scores[elf2] + 1) % nb_scores; } if (std.mem.endsWith(u4, scores[0 .. nb_scores - 1], &desired_final_digits)) { break :ans (nb_scores - 1) - desired_final_digits.len; } else { break :ans nb_scores - desired_final_digits.len; } }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day13.txt", run);
2018/day14.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const lib = @import("lib.zig"); usingnamespace lib; //; // typecheck after you get all the args u want // display is human readable // write is machine readable // slices generated can be interned from vectors // like the relationship between sumbols and strings //; // just use a number type instead of ints and floats? // gets around type checking for math fns // makes bitwise operators weird // TODO need // move eqv fn for records into orth // functions // text // string manipulation // substring // string format // thread exit // math stuff // handle integer overflow // check where it can happen and make it a Thread.Error or change + to +% // short circuiting and and or // subslice, first rest // TODO want // def vs def_clobber, def doesnt clobber // try using the return stack for eval,restore // more ways to print vm info // word table // ports // string, vector port // write an iterator to a port // all returns of error.TypeError report what was expected // dont use zig stack for recursion // zig value iterator that can iterate over slices // if iterating over a non slice value, just return that value once then return null // for display and write // rename record to array ? // could give them a resize fn // could write vecs in orth // functions // text // printing functions // write // need to translate '\n' in strings to a "\n" // math // fract // dont type check, have separte functions for ints and floats ? // general versions of fns like + can be written in orth that typecheck // homogeneous vector thing // []i64, []f64 etc //; pub fn f_def(t: *Thread) Thread.Error!void { const eval_on_lookup = try t.stack.pop(); const name = try t.stack.pop(); const value = try t.stack.pop(); if (name != .Symbol) return error.TypeError; if (eval_on_lookup != .Boolean) return error.TypeError; if (t.vm.word_table.items[name.Symbol]) |prev| { // TODO print that youre overriding? t.vm.dropValue(prev.value); } t.vm.word_table.items[name.Symbol] = .{ .value = value, .eval_on_lookup = eval_on_lookup.Boolean, }; } pub fn f_ref(t: *Thread) Thread.Error!void { const name = try t.stack.pop(); if (name != .Symbol) return error.TypeError; if (t.vm.word_table.items[name.Symbol]) |dword| { try t.stack.push(t.vm.dupValue(dword.value)); try t.stack.push(.{ .Boolean = true }); } else { try t.stack.push(.{ .Boolean = false }); try t.stack.push(.{ .Boolean = false }); } } pub fn f_eval(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); try t.evaluateValue(null, val, 0); } pub fn f_eval_restore(t: *Thread) Thread.Error!void { const restore_num = try t.stack.pop(); const val = try t.stack.pop(); if (restore_num != .Int) return error.TypeError; const restore_u = @intCast(usize, restore_num.Int); var i: usize = 0; while (i < restore_u) : (i += 1) { try t.restore_stack.push(try t.stack.pop()); } try t.evaluateValue(null, val, restore_u); } pub fn f_nop(t: *Thread) Thread.Error!void {} pub fn f_panic(t: *Thread) Thread.Error!void { return error.Panic; } pub fn f_type_error(t: *Thread) Thread.Error!void { return error.TypeError; } pub fn f_stack_len(t: *Thread) Thread.Error!void { try t.stack.push(.{ .Int = @intCast(i64, t.stack.data.items.len) }); } pub fn f_stack_index(t: *Thread) Thread.Error!void { const idx = try t.stack.pop(); if (idx != .Int) return error.TypeError; try t.stack.push(t.vm.dupValue((try t.stack.index(@intCast(usize, idx.Int))).*)); } pub fn f_stack_clear(t: *Thread) Thread.Error!void { for (t.stack.data.items) |v| { t.vm.dropValue(v); } t.stack.data.items.len = 0; } // pub fn f_print_rstack(t: *Thread) Thread.Error!void { // const len = t.return_stack.data.items.len; // std.debug.print("RSTACK| len: {}\n", .{len}); // for (t.return_stack.data.items) |it, i| { // std.debug.print(" {}| ", .{len - i - 1}); // t.nicePrintValue(it.value); // if (it.restore_ct == std.math.maxInt(usize)) { // std.debug.print(" :: max\n", .{}); // } else { // std.debug.print(" :: {}\n", .{it.restore_ct}); // } // } // } // // pub fn f_print_current(t: *Thread) Thread.Error!void { // std.debug.print("CURRENT EXEC: {}| {{", .{t.restore_ct}); // for (t.current_execution) |val| { // t.nicePrintValue(val); // } // std.debug.print("}}\n", .{}); // } // display/write === fn writerDisplayValue(writer: anytype, t: *Thread, value: Value) !void { switch (value) { .Int => |val| try std.fmt.format(writer, "{}", .{val}), .Float => |val| try std.fmt.format(writer, "{d}f", .{val}), .Char => |val| try std.fmt.format(writer, "{c}", .{val}), .Boolean => |val| { const str = if (val) "#t" else "#f"; try std.fmt.format(writer, "{s}", .{str}); }, .Sentinel => try std.fmt.format(writer, "#sentinel", .{}), .Symbol => |val| try std.fmt.format(writer, ":{}", .{t.vm.symbol_table.items[val]}), .Word => |val| try std.fmt.format(writer, "{}", .{t.vm.symbol_table.items[val]}), .String => |val| try std.fmt.format(writer, "{}", .{val}), .Slice => |slc| { try std.fmt.format(writer, "{{ ", .{}); for (slc) |val| { // TODO writerDisplayValue(writer, t, val) catch unreachable; try std.fmt.format(writer, " ", .{}); } try std.fmt.format(writer, "}}", .{}); }, .FFI_Fn => |val| try std.fmt.format(writer, "fn({})", .{t.vm.symbol_table.items[val.name_id]}), .RcPtr => |ptr| { const name_id = t.vm.type_table.items[ptr.rc.type_id].name_id; if (ptr.is_weak) { try std.fmt.format(writer, "rc@({} {})W", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.rc.ptr), }); } else { try std.fmt.format(writer, "rc@({} {})", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.rc.ptr), }); } }, .UnmanagedPtr => |ptr| { const name_id = t.vm.type_table.items[ptr.type_id].name_id; try std.fmt.format(writer, "ffi@({} {})", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.ptr), }); }, } } fn writerWriteValue(writer: anytype, t: *Thread, value: Value) !void { switch (value) { .Int => |val| try std.fmt.format(writer, "{}", .{val}), .Float => |val| try std.fmt.format(writer, "{d}", .{val}), .Char => |val| switch (val) { ' ' => try std.fmt.format(writer, "#\\space", .{}), '\n' => try std.fmt.format(writer, "#\\newline", .{}), '\t' => try std.fmt.format(writer, "#\\tab", .{}), else => try std.fmt.format(writer, "#\\{c}", .{val}), }, .Boolean => |val| { const str = if (val) "#t" else "#f"; try std.fmt.format(writer, "{s}", .{str}); }, .Sentinel => try std.fmt.format(writer, "#sentinel", .{}), .Symbol => |val| try std.fmt.format(writer, ":{}", .{t.vm.symbol_table.items[val]}), .Word => |val| try std.fmt.format(writer, "{}", .{t.vm.symbol_table.items[val]}), // TODO have to convert escapes in strings .String => |val| try std.fmt.format(writer, "\"{}\"", .{val}), .Slice => |slc| { try std.fmt.format(writer, "{{ ", .{}); for (slc) |val| { // TODO writerWriteValue(writer, t, val) catch unreachable; try std.fmt.format(writer, " ", .{}); } try std.fmt.format(writer, "}}", .{}); }, .FFI_Fn => |val| try std.fmt.format(writer, "{}", .{t.vm.symbol_table.items[val.name_id]}), .RcPtr => |ptr| { // TODO what to do here const name_id = t.vm.type_table.items[ptr.rc.type_id].name_id; if (ptr.is_weak) { try std.fmt.format(writer, "rc@({} {})W", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.rc.ptr), }); } else { try std.fmt.format(writer, "rc@({} {})", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.rc.ptr), }); } }, .UnmanagedPtr => |ptr| { // TODO what to do here const name_id = t.vm.type_table.items[ptr.type_id].name_id; try std.fmt.format(writer, "ffi@({} {})", .{ t.vm.symbol_table.items[name_id], @ptrToInt(ptr.ptr), }); }, } } // repl == pub fn f_read(t: *Thread) Thread.Error!void { const stdin = std.io.getStdIn(); // TODO report errors better const str: ?[]u8 = stdin.reader().readUntilDelimiterAlloc(t.vm.allocator, '\n', 2048) catch null; if (str) |s| { try t.vm.string_literals.append(s); try t.stack.push(.{ .String = s }); } } // TODO this should return a result pub fn f_parse(t: *Thread) Thread.Error!void { const str = try t.stack.pop(); if (str != .String) return error.TypeError; var tk = Tokenizer.init(str.String); var tokens = ArrayList(Token).init(t.vm.allocator); defer tokens.deinit(); // TODO report errors better // errors like this should make it into orth while (tk.next() catch unreachable) |token| { try tokens.append(token); } const vals = t.vm.parse(tokens.items) catch unreachable; defer t.vm.allocator.free(vals); // TODO // var rc = try ft_quotation.makeRc(t.vm.allocator); // try rc.obj.appendSlice(vals); // try t.evaluateValue(.{ .UnmanagedPtr = ft_quotation.ffi_type.makePtr(rc.ref()) }, 0); } // built in types === pub fn f_value_type_of(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); try t.stack.push(.{ .Symbol = @enumToInt(@as(ValueType, val)) }); t.vm.dropValue(val); } pub fn f_rc_type_of(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); if (val != .RcPtr) return error.TypeError; try t.stack.push(.{ .Symbol = t.vm.type_table.items[val.RcPtr.rc.type_id].name_id }); t.vm.dropValue(val); } pub fn f_unmanaged_type_of(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); if (val != .UnmanagedPtr) return error.TypeError; try t.stack.push(.{ .Symbol = t.vm.type_table.items[val.UnmanagedPtr.type_id].name_id }); t.vm.dropValue(val); } pub fn f_word_to_symbol(t: *Thread) Thread.Error!void { const word = try t.stack.pop(); if (word != .Word) return error.TypeError; try t.stack.push(.{ .Symbol = word.Word }); } pub fn f_symbol_to_word(t: *Thread) Thread.Error!void { const sym = try t.stack.pop(); if (sym != .Symbol) return error.TypeError; try t.stack.push(.{ .Word = sym.Symbol }); } pub fn f_symbol_to_string(t: *Thread) Thread.Error!void { const sym = try t.stack.pop(); if (sym != .Symbol) return error.TypeError; try t.stack.push(.{ .String = t.vm.symbol_table.items[sym.Symbol] }); } // chars === // TODO // pub fn f_char_to_integer() // math === pub fn f_negative(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); switch (val) { .Int => |i| try t.stack.push(.{ .Int = -i }), .Float => |f| try t.stack.push(.{ .Float = -f }), else => return error.TypeError, } } pub fn f_plus(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| try t.stack.push(.{ .Int = a.Int + i }), .Float => |f| try t.stack.push(.{ .Float = a.Float + f }), else => return error.TypeError, } } pub fn f_minus(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| try t.stack.push(.{ .Int = a.Int - i }), .Float => |f| try t.stack.push(.{ .Float = a.Float - f }), else => return error.TypeError, } } pub fn f_times(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| try t.stack.push(.{ .Int = a.Int * i }), .Float => |f| try t.stack.push(.{ .Float = a.Float * f }), else => return error.TypeError, } } pub fn f_divide(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| { if (i == 0) return error.DivideByZero; try t.stack.push(.{ .Int = @divTrunc(a.Int, i) }); }, .Float => |f| { if (f == 0) return error.DivideByZero; try t.stack.push(.{ .Float = a.Float / f }); }, else => return error.TypeError, } } pub fn f_mod(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| { if (i == 0) return error.DivideByZero; if (i < 0) return error.NegativeDenominator; try t.stack.push(.{ .Int = @mod(a.Int, i) }); }, .Float => |f| { if (f == 0) return error.DivideByZero; if (f < 0) return error.NegativeDenominator; try t.stack.push(.{ .Float = @mod(a.Float, f) }); }, else => return error.TypeError, } } pub fn f_rem(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| { if (i == 0) return error.DivideByZero; if (i < 0) return error.NegativeDenominator; try t.stack.push(.{ .Int = @rem(a.Int, i) }); }, .Float => |f| { if (f == 0) return error.DivideByZero; if (f < 0) return error.NegativeDenominator; try t.stack.push(.{ .Float = @rem(a.Float, f) }); }, else => return error.TypeError, } } pub fn f_lt(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| try t.stack.push(.{ .Boolean = a.Int < i }), .Float => |f| try t.stack.push(.{ .Boolean = a.Float < f }), else => return error.TypeError, } } pub fn f_number_equal(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); const a = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (b) { .Int => |i| try t.stack.push(.{ .Boolean = a.Int == i }), .Float => |f| try t.stack.push(.{ .Boolean = a.Float == f }), else => return error.TypeError, } } pub fn f_float_to_int(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); if (a != .Float) return error.TypeError; try t.stack.push(.{ .Int = @floatToInt(i32, a.Float) }); } pub fn f_int_to_float(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); if (a != .Int) return error.TypeError; try t.stack.push(.{ .Float = @intToFloat(f32, a.Int) }); } // bitwise === pub fn f_bnot(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); switch (val) { .Int => |i| try t.stack.push(.{ .Int = ~i }), else => return error.TypeError, } } pub fn f_band(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (a) { .Int => |i| try t.stack.push(.{ .Int = i & b.Int }), else => return error.TypeError, } } pub fn f_bior(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (a) { .Int => |i| try t.stack.push(.{ .Int = i | b.Int }), else => return error.TypeError, } } pub fn f_bxor(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); if (@as(@TagType(Value), a) != b) return error.TypeError; switch (a) { .Int => |i| try t.stack.push(.{ .Int = i ^ b.Int }), else => return error.TypeError, } } pub fn f_bshl(t: *Thread) Thread.Error!void { const amt = try t.stack.pop(); const num = try t.stack.pop(); if (@as(@TagType(Value), amt) != num) return error.TypeError; switch (num) { // TODO do something abt these casts .Int => |i| try t.stack.push(.{ .Int = num.Int << @intCast(u6, amt.Int) }), else => return error.TypeError, } } pub fn f_bshr(t: *Thread) Thread.Error!void { const amt = try t.stack.pop(); const num = try t.stack.pop(); if (@as(@TagType(Value), amt) != num) return error.TypeError; switch (num) { // TODO do something abt these casts .Int => |i| try t.stack.push(.{ .Int = num.Int >> @intCast(u6, amt.Int) }), else => return error.TypeError, } } pub fn f_integer_length(t: *Thread) Thread.Error!void { const num = try t.stack.pop(); switch (num) { .Int => |i| { var ct: i64 = 0; var val = i; while (val > 0) : (val >>= 1) { ct += 1; } try t.stack.push(.{ .Int = ct }); }, else => return error.TypeError, } } // chars === pub fn f_char_to_int(t: *Thread) Thread.Error!void { const ch = try t.stack.pop(); if (ch != .Char) return error.TypeError; try t.stack.push(.{ .Int = ch.Char }); } pub fn f_int_to_char(t: *Thread) Thread.Error!void { const i = try t.stack.pop(); if (i != .Int) return error.TypeError; try t.stack.push(.{ .Char = @intCast(u8, i.Int) }); } // conditionals === pub fn f_choose(t: *Thread) Thread.Error!void { const if_false = try t.stack.pop(); const if_true = try t.stack.pop(); const condition = try t.stack.pop(); if (condition != .Boolean) return error.TypeError; switch (condition) { .Boolean => |b| { if (b) { try t.stack.push(if_true); t.vm.dropValue(if_false); } else { try t.stack.push(if_false); t.vm.dropValue(if_true); } }, else => return error.TypeError, } } fn areValuesEqual(a: Value, b: Value) bool { return if (@as(@TagType(Value), a) == b) switch (a) { .Int => |val| val == b.Int, .Float => |val| val == b.Float, .Char => |val| val == b.Char, .Boolean => |val| val == b.Boolean, .Sentinel => true, .String => |val| val.ptr == b.String.ptr and val.len == b.String.len, .Word => |val| val == b.Word, .Symbol => |val| val == b.Symbol, .Slice => |val| val.ptr == b.Slice.ptr and val.len == b.Slice.len, .FFI_Fn => |ptr| ptr.name_id == b.FFI_Fn.name_id and ptr.func == b.FFI_Fn.func, .RcPtr => |ptr| ptr.rc == b.RcPtr.rc and ptr.is_weak == b.RcPtr.is_weak, .UnmanagedPtr => |ptr| ptr.type_id == b.UnmanagedPtr.type_id and ptr.ptr == b.UnmanagedPtr.ptr, } else false; } pub fn f_equal(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); try t.stack.push(.{ .Boolean = areValuesEqual(a, b) }); t.vm.dropValue(a); t.vm.dropValue(b); } fn areValuesEquivalent(t: *Thread, a: Value, b: Value) bool { return if (@as(@TagType(Value), a) == b) switch (a) { .Int, .Float, .Boolean, .Char, .Sentinel, .Symbol, .Word, .FFI_Fn, => areValuesEqual(a, b), .String => |val| std.mem.eql(u8, val, b.String), // TODO dont use the zig stack .Slice => |val| blk: { for (val) |v, i| { if (!areValuesEquivalent(t, v, b.Slice[i])) break :blk false; } break :blk true; }, .RcPtr => |ptr| t.vm.type_table.items[ptr.rc.type_id].ty.Rc.equivalent_fn(t, ptr, b), .UnmanagedPtr => |ptr| t.vm.type_table.items[ptr.type_id].ty.Unmanaged.equivalent_fn(t, ptr, b), } else blk: { // TODO break :blk false; }; } pub fn f_equivalent(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); try t.stack.push(.{ .Boolean = areValuesEquivalent(t, a, b) }); t.vm.dropValue(a); t.vm.dropValue(b); } pub fn f_not(t: *Thread) Thread.Error!void { const b = try t.stack.pop(); if (b != .Boolean) return error.TypeError; try t.stack.push(.{ .Boolean = !b.Boolean }); } pub fn f_and(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); if (a != .Boolean) return error.TypeError; if (b != .Boolean) return error.TypeError; try t.stack.push(.{ .Boolean = a.Boolean and b.Boolean }); } pub fn f_or(t: *Thread) Thread.Error!void { const a = try t.stack.pop(); const b = try t.stack.pop(); if (a != .Boolean) return error.TypeError; if (b != .Boolean) return error.TypeError; try t.stack.push(.{ .Boolean = a.Boolean or b.Boolean }); } // return stack === pub fn f_to_r(t: *Thread) Thread.Error!void { try t.return_stack.push(.{ .value = try t.stack.pop(), .restore_ct = std.math.maxInt(usize), }); } pub fn f_from_r(t: *Thread) Thread.Error!void { try t.stack.push((try t.return_stack.pop()).value); } pub fn f_peek_r(t: *Thread) Thread.Error!void { try t.stack.push(t.vm.dupValue((try t.return_stack.peek()).value)); } // shuffle === pub fn f_drop(t: *Thread) Thread.Error!void { const val = try t.stack.pop(); t.vm.dropValue(val); } pub fn f_dup(t: *Thread) Thread.Error!void { const val = try t.stack.peek(); try t.stack.push(t.vm.dupValue(val)); } pub fn f_over(t: *Thread) Thread.Error!void { const val = (try t.stack.index(1)).*; try t.stack.push(t.vm.dupValue(val)); } pub fn f_pick(t: *Thread) Thread.Error!void { const val = (try t.stack.index(2)).*; try t.stack.push(t.vm.dupValue(val)); } pub fn f_swap(t: *Thread) Thread.Error!void { var slice = t.stack.data.items; if (slice.len < 2) return error.StackUnderflow; std.mem.swap(Value, &slice[slice.len - 1], &slice[slice.len - 2]); } // slices === pub fn f_slice_len(t: *Thread) Thread.Error!void { const slc = try t.stack.pop(); if (slc != .Slice) return error.TypeError; try t.stack.push(.{ .Int = @intCast(i64, slc.Slice.len) }); } pub fn f_slice_get(t: *Thread) Thread.Error!void { const slc = try t.stack.pop(); const idx = try t.stack.pop(); if (slc != .Slice) return error.TypeError; if (idx != .Int) return error.TypeError; try t.stack.push(t.vm.dupValue(slc.Slice[@intCast(usize, idx.Int)])); } pub fn f_slice_to_vec(t: *Thread) Thread.Error!void { const slc = try t.stack.pop(); if (slc != .Slice) return error.TypeError; var clone = try t.vm.allocator.dupe(Value, slc.Slice); var vec = try t.vm.allocator.create(ft_vec.Vec); vec.* = ft_vec.Vec.fromOwnedSlice(t.vm.allocator, clone); var rc = try Rc.makeOne(t.vm.allocator, ft_vec.type_id, vec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } // rc === pub fn f_is_weak(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; try t.stack.push(.{ .Boolean = this.RcPtr.is_weak }); t.vm.dropValue(this); } pub fn f_downgrade(t: *Thread) Thread.Error!void { const this = try t.stack.index(0); if (this.* != .RcPtr) return error.TypeError; var ptr = &this.*.RcPtr; const ref_ct = ptr.rc.ref_ct; t.vm.dropValue(this.*); if (ref_ct == 1) { _ = t.stack.pop() catch unreachable; try t.stack.push(.{ .Boolean = false }); try t.stack.push(.{ .Boolean = false }); } else { ptr.is_weak = true; try t.stack.push(.{ .Boolean = true }); } } pub fn f_upgrade(t: *Thread) Thread.Error!void { const this = try t.stack.index(0); if (this.* != .RcPtr) return error.TypeError; var ptr = &this.*.RcPtr; ptr.is_weak = false; ptr.rc.inc(); } // record === pub const ft_record = struct { const Self = @This(); pub const Record = []Value; var type_id: usize = undefined; pub fn install(vm: *VM) Allocator.Error!void { type_id = try vm.installType("record", .{ .ty = .{ .Rc = .{ .finalize_fn = finalize, }, }, }); } pub fn finalize(vm: *VM, ptr: RcPtr) void { var rec = ptr.rc.cast(Record); for (rec.*) |val| { vm.dropValue(val); } vm.allocator.free(rec.*); vm.allocator.destroy(rec); } //; pub fn _make(t: *Thread) Thread.Error!void { const slot_ct = try t.stack.pop(); if (slot_ct != .Int) return error.TypeError; var rec = try t.vm.allocator.create(Record); var data = try t.vm.allocator.alloc(Value, @intCast(usize, slot_ct.Int)); for (data) |*v| { v.* = .{ .Sentinel = {} }; } rec.* = data; var rc = try Rc.makeOne(t.vm.allocator, type_id, rec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _clone(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var this_data = this.RcPtr.rc.cast(Record); var rec = try t.vm.allocator.create(Record); var data = try t.vm.allocator.alloc(Value, @intCast(usize, this_data.len)); for (data) |*v, i| { v.* = t.vm.dupValue(this_data.*[i]); } rec.* = data; var rc = try Rc.makeOne(t.vm.allocator, type_id, rec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _set(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const idx = try t.stack.pop(); const val = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (idx != .Int) return error.TypeError; var rec = this.RcPtr.rc.cast(Record); rec.*[@intCast(usize, idx.Int)] = val; t.vm.dropValue(this); } pub fn _get(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const idx = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (idx != .Int) return error.TypeError; var rec = this.RcPtr.rc.cast(Record); try t.stack.push(t.vm.dupValue(rec.*[@intCast(usize, idx.Int)])); t.vm.dropValue(this); } }; // vec === // TODO vec insert, vec append // non mutating versions of fns pub const ft_vec = struct { const Self = @This(); pub const Vec = ArrayList(Value); var type_id: usize = undefined; pub fn install(vm: *VM) Allocator.Error!void { type_id = try vm.installType("vec", .{ .ty = .{ .Rc = .{ .finalize_fn = finalize, }, }, }); } pub fn finalize(vm: *VM, ptr: RcPtr) void { var vec = ptr.rc.cast(Vec); for (vec.items) |val| { vm.dropValue(val); } vec.deinit(); vm.allocator.destroy(vec); } //; pub fn _make(t: *Thread) Thread.Error!void { var vec = try t.vm.allocator.create(Vec); vec.* = Vec.init(t.vm.allocator); var rc = try Rc.makeOne(t.vm.allocator, type_id, vec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _make_capacity(t: *Thread) Thread.Error!void { const capacity = try t.stack.pop(); if (capacity != .Int) return error.TypeError; var vec = try t.vm.allocator.create(Vec); vec.* = try Vec.initCapacity( t.vm.allocator, @intCast(usize, capacity.Int), ); var rc = try Rc.makeOne(t.vm.allocator, type_id, vec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _to_slice(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); const slc = try t.vm.allocator.dupe(Value, vec.items); try t.vm.slice_literals.append(.{ .Slice = slc }); try t.stack.push(.{ .Slice = slc }); t.vm.dropValue(this); } pub fn _push(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const val = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); try vec.append(val); t.vm.dropValue(this); } pub fn _pop(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); // TODO error if vec.items.len == 0 const popped = vec.items[vec.items.len - 1]; vec.items.len -= 1; try t.stack.push(popped); t.vm.dropValue(this); } pub fn _set(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const idx = try t.stack.pop(); const val = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (idx != .Int) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); t.vm.dropValue(vec.items[@intCast(usize, idx.Int)]); vec.items[@intCast(usize, idx.Int)] = val; t.vm.dropValue(this); } pub fn _get(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const idx = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (idx != .Int) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); try t.stack.push(t.vm.dupValue(vec.items[@intCast(usize, idx.Int)])); t.vm.dropValue(this); } pub fn _len(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); try t.stack.push(.{ .Int = @intCast(i32, vec.items.len) }); t.vm.dropValue(this); } pub fn _reverse_in_place(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var vec = this.RcPtr.rc.cast(Vec); std.mem.reverse(Value, vec.items); t.vm.dropValue(this); } }; // string === // TODO separate out code that takes a literal string pub const ft_string = struct { const Self = @This(); pub const String = ArrayList(u8); var type_id: usize = undefined; pub fn install(vm: *VM) Allocator.Error!void { type_id = try vm.installType("string", .{ .ty = .{ .Rc = .{ .finalize_fn = finalize, }, }, }); } pub fn finalize(vm: *VM, ptr: RcPtr) void { var string = ptr.rc.cast(String); string.deinit(); vm.allocator.destroy(string); } //; fn makeRcFromSlice(allocator: *Allocator, slice: []const u8) Allocator.Error!*Rc { var string = try allocator.create(String); string.* = String.init(allocator); try string.appendSlice(slice); var rc = try Rc.makeOne(allocator, type_id, string); return rc; } fn makeRcMoveSlice(allocator: *Allocator, slice: []u8) Allocator.Error!*Rc { var string = try allocator.create(String); string.* = String.fromOwnedSlice(allocator, slice); var rc = try Rc.makeOne(allocator, type_id, string); return rc; } pub fn _make(t: *Thread) Thread.Error!void { var string = try t.vm.allocator.create(String); string.* = String.init(t.vm.allocator); var rc = try Rc.makeOne(t.vm.allocator, type_id, string); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _clone(t: *Thread) Thread.Error!void { const other = try t.stack.pop(); switch (other) { .String => |str| { var rc = try makeRcFromSlice(t.vm.allocator, str); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); }, .RcPtr => |ptr| { if (ptr.rc.type_id != type_id) return error.TypeError; var other_str = ptr.rc.cast(String); var rc = try makeRcFromSlice(t.vm.allocator, other_str.items); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); t.vm.dropValue(other); }, else => return error.TypeError, } } pub fn _append_in_place(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const other = try t.stack.pop(); switch (this) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } switch (other) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } const rc = switch (this) { .String => |str| try makeRcFromSlice(t.vm.allocator, str), .RcPtr => |ptr| ptr.rc, else => unreachable, }; const o_str = switch (other) { .String => |str| str, .RcPtr => |ptr| ptr.rc.cast(String).items, else => unreachable, }; try rc.cast(String).appendSlice(o_str); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); t.vm.dropValue(other); } pub fn _to_symbol(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); switch (this) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } const str = switch (this) { .String => |str| str, .RcPtr => |ptr| ptr.rc.cast(String).items, else => unreachable, }; try t.stack.push(.{ .Symbol = try t.vm.internSymbol(str) }); t.vm.dropValue(this); } pub fn _to_vec(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); switch (this) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } const str = switch (this) { .String => |str| str, .RcPtr => |ptr| ptr.rc.cast(String).items, else => unreachable, }; var vec = try t.vm.allocator.create(ft_vec.Vec); vec.* = try ft_vec.Vec.initCapacity(t.vm.allocator, str.len); for (str) |ch| { vec.append(.{ .Char = ch }) catch unreachable; } var rc = try Rc.makeOne(t.vm.allocator, ft_vec.type_id, vec); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); t.vm.dropValue(this); } pub fn _get(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const idx = try t.stack.pop(); switch (this) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } if (idx != .Int) return error.TypeError; const str = switch (this) { .String => |str| str, .RcPtr => |ptr| ptr.rc.cast(String).items, else => unreachable, }; try t.stack.push(.{ .Char = str[@intCast(usize, idx.Int)] }); t.vm.dropValue(this); } pub fn _len(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); switch (this) { .String => {}, .RcPtr => |ptr| if (ptr.rc.type_id != type_id) return error.TypeError, else => return error.TypeError, } const str = switch (this) { .String => |str| str, .RcPtr => |ptr| ptr.rc.cast(String).items, else => unreachable, }; try t.stack.push(.{ .Int = @intCast(i32, str.len) }); t.vm.dropValue(this); } }; // map === pub const ft_map = struct { const Self = @This(); pub const Map = std.AutoHashMap(usize, Value); pub var type_id: usize = undefined; pub fn install(vm: *VM) Allocator.Error!void { type_id = try vm.installType("map", .{ .ty = .{ .Rc = .{ .finalize_fn = finalize, }, }, }); } pub fn finalize(vm: *VM, ptr: RcPtr) void { var map = ptr.rc.cast(Map); var iter = map.iterator(); while (iter.next()) |entry| { vm.dropValue(entry.value); } map.deinit(); vm.allocator.destroy(map); } //; pub fn _make(t: *Thread) Thread.Error!void { var map = try t.vm.allocator.create(Map); map.* = Map.init(t.vm.allocator); var rc = try Rc.makeOne(t.vm.allocator, type_id, map); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); } pub fn _set(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const sym = try t.stack.pop(); const value = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (sym != .Symbol) return error.TypeError; var map = this.RcPtr.rc.cast(Map); // TODO handle overwrite try map.put(sym.Symbol, value); t.vm.dropValue(this); } pub fn _get(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const sym = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (sym != .Symbol) return error.TypeError; var map = this.RcPtr.rc.cast(Map); if (map.get(sym.Symbol)) |val| { try t.stack.push(t.vm.dupValue(val)); try t.stack.push(.{ .Boolean = true }); } else { try t.stack.push(.{ .String = "not found" }); try t.stack.push(.{ .Boolean = false }); } t.vm.dropValue(this); } }; // file == pub const ft_file = struct { const Self = @This(); pub const File = struct { filepath: []u8, file: std.fs.File, }; pub var type_id: usize = undefined; pub fn install(vm: *VM) Allocator.Error!void { type_id = try vm.installType("file", .{ .ty = .{ .Rc = .{ .finalize_fn = finalize, }, }, }); } pub fn finalize(vm: *VM, ptr: RcPtr) void { var file = ptr.rc.cast(File); vm.allocator.free(file.filepath); file.file.close(); vm.allocator.destroy(file); } //; // TODO // file close // read until delimiter // write until delimiter pub fn _open(t: *Thread) Thread.Error!void { // TODO allow ffi string // want to use a symbol or array or something for open_flags const path = try t.stack.pop(); const open_flags = try t.stack.pop(); if (path != .String) return error.TypeError; if (open_flags != .String) return error.TypeError; var flags = std.fs.File.OpenFlags{ .read = false, }; for (open_flags.String) |ch| { if (ch == 'r' or ch == 'R') flags.read = true; if (ch == 'w' or ch == 'W') flags.write = true; } var f = std.fs.cwd().openFile(path.String, flags) catch |err| { try t.stack.push(.{ .String = "couldn't load file" }); try t.stack.push(.{ .Boolean = false }); return; }; errdefer f.close(); var file = try t.vm.allocator.create(File); file.* = .{ .filepath = try t.vm.allocator.dupe(u8, path.String), .file = f, }; var rc = try Rc.makeOne(t.vm.allocator, type_id, file); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); try t.stack.push(.{ .Boolean = true }); } // TODO there could be an error if <file>,std is called more than once // and orth tries to close one of the files twice pub fn _std(t: *Thread) Thread.Error!void { const which = try t.stack.pop(); if (which != .Symbol) return error.TypeError; var fp: []const u8 = undefined; var f: std.fs.File = undefined; if (which.Symbol == try t.vm.internSymbol("in")) { fp = "stdin"; f = std.io.getStdIn(); } else if (which.Symbol == try t.vm.internSymbol("out")) { fp = "stdout"; f = std.io.getStdOut(); } else if (which.Symbol == try t.vm.internSymbol("err")) { fp = "stderr"; f = std.io.getStdErr(); } else { // TODO try t.stack.push(.{ .Boolean = false }); try t.stack.push(.{ .Boolean = false }); return; } var file = try t.vm.allocator.create(File); file.* = .{ .filepath = try t.vm.allocator.dupe(u8, fp), .file = f, }; var rc = try Rc.makeOne(t.vm.allocator, type_id, file); try t.stack.push(.{ .RcPtr = .{ .rc = rc, .is_weak = false, }, }); try t.stack.push(.{ .Boolean = true }); } pub fn _filepath(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; const file = this.RcPtr.rc.cast(File); var rc_str = try ft_string.makeRcFromSlice(t.vm.allocator, file.filepath); try t.stack.push(.{ .RcPtr = .{ .rc = rc_str, .is_weak = false, }, }); t.vm.dropValue(this); } // TODO could use eof object instead of result type pub fn _read_char(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var file = this.RcPtr.rc.cast(File); var buf = [1]u8{undefined}; // TODO handle read errors const ct = file.file.read(&buf) catch unreachable; if (ct == 0) { try t.stack.push(.{ .Boolean = false }); try t.stack.push(.{ .Boolean = false }); } else { try t.stack.push(.{ .Char = buf[0] }); try t.stack.push(.{ .Boolean = true }); } t.vm.dropValue(this); } pub fn _peek_char(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var file = this.RcPtr.rc.cast(File); var buf = [1]u8{undefined}; // TODO handle read errors const ct = file.file.read(&buf) catch unreachable; if (ct == 0) { try t.stack.push(.{ .Boolean = false }); try t.stack.push(.{ .Boolean = false }); } else { file.file.seekBy(-@intCast(i64, ct)) catch unreachable; try t.stack.push(.{ .Char = buf[0] }); try t.stack.push(.{ .Boolean = true }); } t.vm.dropValue(this); } pub fn _read_delimiter(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const delim = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (delim != .Char) return error.TypeError; var file = this.RcPtr.rc.cast(File); var reader = file.file.reader(); const buf = reader.readUntilDelimiterAlloc( t.vm.allocator, delim.Char, std.math.maxInt(usize), ) catch |err| { switch (err) { error.OutOfMemory => return error.OutOfMemory, else => unreachable, } }; var rc_str = try ft_string.makeRcMoveSlice(t.vm.allocator, buf); try t.stack.push(.{ .RcPtr = .{ .rc = rc_str, .is_weak = false, }, }); try t.stack.push(.{ .Boolean = true }); t.vm.dropValue(this); } pub fn _read_all(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var file = this.RcPtr.rc.cast(File); // TODO file.file.seekTo(0) catch unreachable; const buf = file.file.readToEndAlloc( t.vm.allocator, std.math.maxInt(usize), ) catch |err| { switch (err) { error.OutOfMemory => return error.OutOfMemory, else => unreachable, } }; var rc_str = try ft_string.makeRcMoveSlice(t.vm.allocator, buf); try t.stack.push(.{ .RcPtr = .{ .rc = rc_str, .is_weak = false, }, }); try t.stack.push(.{ .Boolean = true }); t.vm.dropValue(this); } pub fn _display(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const val = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var file = this.RcPtr.rc.cast(File); writerDisplayValue(file.file.writer(), t, val) catch unreachable; t.vm.dropValue(this); t.vm.dropValue(val); } pub fn _write(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const val = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; var file = this.RcPtr.rc.cast(File); writerWriteValue(file.file.writer(), t, val) catch unreachable; t.vm.dropValue(this); t.vm.dropValue(val); } pub fn _write_char(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const ch = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; if (ch != .Char) return error.TypeError; const buf = [1]u8{ch.Char}; var file = this.RcPtr.rc.cast(File); // TODO file.file.writeAll(&buf) catch unreachable; t.vm.dropValue(this); } pub fn _write_all(t: *Thread) Thread.Error!void { const this = try t.stack.pop(); const str = try t.stack.pop(); if (this != .RcPtr) return error.TypeError; if (this.RcPtr.rc.type_id != type_id) return error.TypeError; // TODO take ffi string if (str != .String) return error.TypeError; var file = this.RcPtr.rc.cast(File); // TODO file.file.writeAll(str.String) catch unreachable; t.vm.dropValue(this); } }; // ===== const BuiltinDefinition = struct { name: []const u8, func: FFI_Fn.Function, }; pub const builtins = [_]BuiltinDefinition{ .{ .name = "def", .func = f_def }, .{ .name = "ref", .func = f_ref }, .{ .name = "eval'", .func = f_eval }, .{ .name = "eval,restore'", .func = f_eval_restore }, .{ .name = "nop", .func = f_nop }, .{ .name = "panic", .func = f_panic }, .{ .name = "type-error", .func = f_type_error }, .{ .name = "stack.len", .func = f_stack_len }, .{ .name = "stack.index", .func = f_stack_index }, .{ .name = "stack.clear!", .func = f_stack_clear }, // .{ .name = ".rstack'", .func = f_print_rstack }, // .{ .name = ".current'", .func = f_print_current }, .{ .name = "read", .func = f_read }, .{ .name = "parse", .func = f_parse }, .{ .name = "value-type-of", .func = f_value_type_of }, .{ .name = "rc-type-of", .func = f_rc_type_of }, .{ .name = "unmanaged-type-of", .func = f_unmanaged_type_of }, .{ .name = "word>symbol", .func = f_word_to_symbol }, .{ .name = "symbol>word", .func = f_symbol_to_word }, .{ .name = "symbol>string", .func = f_symbol_to_string }, .{ .name = "neg", .func = f_negative }, .{ .name = "+", .func = f_plus }, .{ .name = "-", .func = f_minus }, .{ .name = "*", .func = f_times }, .{ .name = "/", .func = f_divide }, .{ .name = "mod", .func = f_mod }, .{ .name = "rem", .func = f_rem }, .{ .name = "<", .func = f_lt }, .{ .name = "=", .func = f_number_equal }, .{ .name = "float>int", .func = f_float_to_int }, .{ .name = "int>float", .func = f_int_to_float }, .{ .name = "~", .func = f_bnot }, .{ .name = "&", .func = f_band }, .{ .name = "|", .func = f_bior }, .{ .name = "^", .func = f_bxor }, .{ .name = "<<", .func = f_bshl }, .{ .name = ">>", .func = f_bshr }, .{ .name = "integer-length", .func = f_integer_length }, .{ .name = "char>int", .func = f_char_to_int }, .{ .name = "int>char", .func = f_int_to_char }, .{ .name = "?", .func = f_choose }, .{ .name = "eq?", .func = f_equal }, .{ .name = "eqv?", .func = f_equivalent }, .{ .name = "not", .func = f_not }, .{ .name = "and", .func = f_and }, .{ .name = "or", .func = f_or }, .{ .name = ">R", .func = f_to_r }, .{ .name = "<R", .func = f_from_r }, .{ .name = ".R", .func = f_peek_r }, .{ .name = "drop", .func = f_drop }, .{ .name = "dup", .func = f_dup }, .{ .name = "over", .func = f_over }, .{ .name = "pick", .func = f_pick }, .{ .name = "swap", .func = f_swap }, .{ .name = "slen", .func = f_slice_len }, .{ .name = "sget", .func = f_slice_get }, .{ .name = "slice>vec", .func = f_slice_to_vec }, .{ .name = "rc-ptr.weak?", .func = f_is_weak }, .{ .name = "downgrade", .func = f_downgrade }, .{ .name = "upgrade", .func = f_upgrade }, .{ .name = "<record>", .func = ft_record._make }, .{ .name = "<record>,clone", .func = ft_record._clone }, .{ .name = "rset!", .func = ft_record._set }, .{ .name = "rget", .func = ft_record._get }, .{ .name = "<vec>", .func = ft_vec._make }, .{ .name = "<vec>,capacity", .func = ft_vec._make_capacity }, .{ .name = "vec>slice", .func = ft_vec._to_slice }, // TODO // .{ .name = "vec>string", .func = ft_vec._to_string }, .{ .name = "vpush!", .func = ft_vec._push }, .{ .name = "vpop!", .func = ft_vec._pop }, .{ .name = "vset!", .func = ft_vec._set }, .{ .name = "vget", .func = ft_vec._get }, .{ .name = "vlen", .func = ft_vec._len }, .{ .name = "vreverse!", .func = ft_vec._reverse_in_place }, .{ .name = "<string>", .func = ft_string._make }, .{ .name = "<string>,clone", .func = ft_string._clone }, .{ .name = "string-append!", .func = ft_string._append_in_place }, .{ .name = "string>symbol", .func = ft_string._to_symbol }, .{ .name = "string>vec", .func = ft_string._to_vec }, .{ .name = "strget", .func = ft_string._get }, .{ .name = "strlen", .func = ft_string._len }, .{ .name = "<map>", .func = ft_map._make }, .{ .name = "mset!", .func = ft_map._set }, .{ .name = "mget", .func = ft_map._get }, .{ .name = "<file>,open", .func = ft_file._open }, .{ .name = "<file>,std", .func = ft_file._std }, .{ .name = "file.filepath", .func = ft_file._filepath }, .{ .name = "file.read-char", .func = ft_file._read_char }, .{ .name = "file.peek-char", .func = ft_file._peek_char }, .{ .name = "file.read-delimiter", .func = ft_file._read_delimiter }, .{ .name = "file.read-all", .func = ft_file._read_all }, .{ .name = "file.display", .func = ft_file._display }, .{ .name = "file.write", .func = ft_file._write }, .{ .name = "file.write-char", .func = ft_file._write_char }, .{ .name = "file.write-all", .func = ft_file._write_all }, };
src/builtins.zig
const std = @import("std"); const io = std.io; const kernel = @import("root"); const mm = kernel.mm; const x86 = @import("../x86.zig"); var vga_console: ?VGAConsole = null; pub fn getConsole() *VGAConsole { if (vga_console == null) { vga_console = VGAConsole.init(); } return &vga_console.?; } pub const VGADevice = struct { const VGA_WIDTH = 80; const VGA_HEIGHT = 25; const Buffer = [VGA_HEIGHT][VGA_WIDTH]u16; const Color = enum(u4) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Purple = 5, Brown = 6, Gray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightPurple = 13, Yellow = 14, White = 15, }; const default_color = make_color(Color.Gray, Color.Black); pub fn get_buffer() *Buffer { const phys = mm.PhysicalAddress.new(0xb8000); return mm.directMapping().to_virt(phys).into_pointer(*Buffer); } pub fn make_color(back: Color, front: Color) u8 { const b = @enumToInt(front); const f = @enumToInt(back); return (@as(u8, b) << 4) | @as(u8, f); } pub fn make_entry(c: u8, color: u8) u16 { return (@as(u16, c) & 0xff) + (@as(u16, color) << 8); } pub fn put_at(c: u8, x: u16, y: u16) void { get_buffer()[y][x] = make_entry(c, default_color); } pub fn clear() void { var i: u16 = 0; while (i < VGA_HEIGHT) : (i += 1) { clear_row(i); } } fn clear_row(idx: u16) void { std.debug.assert(idx < VGA_HEIGHT); const entry = make_entry(' ', default_color); std.mem.set(u16, get_buffer()[idx][0..], entry); } pub fn scroll_row() void { // Copy one row up var i: u16 = 1; while (i < VGADevice.VGA_HEIGHT) : (i += 1) { // Copy ith row into i-1th row var dest = get_buffer()[i - 1][0..]; var src = get_buffer()[i][0..]; std.mem.copy(u16, dest, src); } clear_row(VGADevice.VGA_HEIGHT - 1); } pub fn disable_cursor() void { x86.out(u8, 0x3d4, 0x0a); x86.out(u8, 0x3d5, 0x20); } pub fn set_cursor(x: u16, y: u16) void { const pos = VGA_WIDTH * y + x; x86.out(u8, 0x3d4, 0x0f); x86.out(u8, 0x3d5, @intCast(u8, pos & 0xff)); x86.out(u8, 0x3d4, 0x0e); x86.out(u8, 0x3d5, @intCast(u8, (pos >> 8) & 0xff)); } }; pub const VGAConsole = struct { cursor_x: u16, cursor_y: u16, pub fn init() VGAConsole { VGADevice.clear(); return VGAConsole{ .cursor_x = 0, .cursor_y = 0, }; } const Self = @This(); const VGAError = error{VGAError}; pub const Writer = io.Writer(*VGAConsole, VGAError, write); pub fn writer(self: *Self) Writer { return .{ .context = self }; } fn ensure_scrolled(self: *Self) void { if (self.cursor_x >= VGADevice.VGA_WIDTH) { self.cursor_y += 1; self.cursor_x = 0; } if (self.cursor_y == VGADevice.VGA_HEIGHT) { self.cursor_y = VGADevice.VGA_HEIGHT - 1; VGADevice.scroll_row(); } } fn write_char(self: *Self, c: u8) void { switch (c) { '\n' => { self.cursor_y += 1; self.cursor_x = 0; }, '\r' => { self.cursor_x = 0; }, else => { std.debug.assert(self.cursor_x < VGADevice.VGA_WIDTH); std.debug.assert(self.cursor_y < VGADevice.VGA_HEIGHT); VGADevice.put_at(c, self.cursor_x, self.cursor_y); self.cursor_x += 1; }, } self.ensure_scrolled(); } pub fn write(self: *Self, str: []const u8) VGAError!usize { for (str) |c| { self.write_char(c); } VGADevice.set_cursor(self.cursor_x, self.cursor_y); return str.len; } };
kernel/arch/x86/vga.zig
usingnamespace @import("../c.zig"); usingnamespace @import("../math/Math.zig"); const std = @import("std"); const ArrayList = std.ArrayList; const debug = @import("std").debug; const Mesh = @import("Mesh.zig").Mesh; const allocator = std.heap.page_allocator; const ImportError = error{ AIImportError, //assimp failed to import the scene ZeroMeshes, //scene contains 0 meshes MultipleMeshes, //scene contains more than 1 mesh AssetPath, //issue with path to asset BadDataCounts, //issue with data not having matching quantities }; pub fn ImportMesh(filePath: []const u8) !Mesh { _ = try std.fs.openFileAbsolute(filePath, .{}); //sanity check accessing the file before trying to import const importedScene: *const aiScene = aiImportFile(filePath.ptr, aiProcess_Triangulate) orelse { const errStr = aiGetErrorString(); debug.warn("{s}\n", .{errStr[0..std.mem.len(errStr)]}); return ImportError.AIImportError; }; defer aiReleaseImport(importedScene); if (importedScene.mNumMeshes > 1) { return ImportError.MultipleMeshes; } else if (importedScene.mNumMeshes == 0) { return ImportError.ZeroMeshes; } const importMesh: *const aiMesh = importedScene.mMeshes[0]; const fileName = std.fs.path.basename(filePath); var returnMesh = Mesh{ .m_name = fileName, .m_vertices = try ArrayList(Vec3).initCapacity(allocator, importMesh.mNumVertices), .m_normals = try ArrayList(Vec3).initCapacity(allocator, importMesh.mNumVertices), .m_texCoords = try ArrayList(Vec2).initCapacity(allocator, importMesh.mNumVertices), //TODO channels .m_indices = ArrayList(u32).init(allocator), //TODO can we make the capacity/resize handling better? .m_vertexBO = 0, .m_normalBO = 0, .m_texCoordBO = 0, .m_indexBO = 0, }; // Copy data from the imported mesh structure to ours for (importMesh.mVertices[0..importMesh.mNumVertices]) |vert| { returnMesh.m_vertices.appendAssumeCapacity(.{ .x = vert.x, .y = vert.y, .z = vert.z, }); } for (importMesh.mNormals[0..importMesh.mNumVertices]) |normal| { returnMesh.m_normals.appendAssumeCapacity(.{ .x = normal.x, .y = normal.y, .z = normal.z, }); } for (importMesh.mTextureCoords[0][0..importMesh.mNumVertices]) |uvCoord| { returnMesh.m_texCoords.appendAssumeCapacity(.{ .x = uvCoord.x, .y = uvCoord.y, }); } for (importMesh.mFaces[0..importMesh.mNumFaces]) |face, i| { if (face.mNumIndices != 3) { debug.warn("Bad face count at face {} with count {}\n", .{ i, face.mNumIndices }); return ImportError.BadDataCounts; } for (face.mIndices[0..face.mNumIndices]) |index| { try returnMesh.m_indices.append(index); } } debug.warn("Imported {s} successfully:\n{} vertices, {} normals, {} texCoords, and {} indices\n", .{ fileName, returnMesh.m_vertices.items.len, returnMesh.m_normals.items.len, returnMesh.m_texCoords.items.len, returnMesh.m_indices.items.len, }); return returnMesh; }
src/presentation/AssImpInterface.zig
const std = @import("std"); const vk = @import("../include/vk.zig"); const Context = @import("../backend/context.zig").Context; const Framebuffer = @import("../backend/framebuffer.zig").Framebuffer; pub const Step = @import("step.zig").Step; pub const renderpass = @import("renderpass.zig"); pub const pipeline = @import("pipeline.zig"); pub const descriptor = @import("descriptor.zig"); pub const command = @import("command.zig"); pub const Program = struct { context: *const Context, steps: []const Step, pub fn build(context: *const Context, steps: []const Step) Program { if (steps[0] != .RenderPass) std.debug.panic("steps does not start with a renderpass!", .{}); return Program{ .context = context, .steps = steps, }; } pub fn execute(self: *const Program, cb: vk.CommandBuffer, fb: Framebuffer) !void { // begin try self.context.vkd.beginCommandBuffer(cb, .{ .flags = .{}, .p_inheritance_info = null, }); // dynamic states const viewport = vk.Viewport{ .x = 0.0, .y = 0.0, .width = @intToFloat(f32, fb.size.width), .height = @intToFloat(f32, fb.size.height), .min_depth = 0.0, .max_depth = 1.0, }; const scissor = vk.Rect2D{ .offset = vk.Offset2D{ .x = 0, .y = 0 }, .extent = fb.size, }; self.context.vkd.cmdSetViewport(cb, 0, 1, @ptrCast([*]const vk.Viewport, &viewport)); self.context.vkd.cmdSetScissor(cb, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor)); // execute for (self.steps) |step| { try switch (step) { .RenderPass => |r| r.execute(cb, fb), .Pipeline => |p| p.execute(cb, fb), .Command => |c| c.execute(self.context, cb, fb), }; } // executePost var spets = try self.context.allocator.dupe(Step, self.steps); defer self.context.allocator.free(spets); std.mem.reverse(Step, spets); for (spets) |step| { try switch (step) { .RenderPass => |r| r.executePost(cb, fb), else => {}, }; } // end try self.context.vkd.endCommandBuffer(cb); } };
render/src/program/program.zig
const std = @import("std"); comptime { @setFloatMode(.Optimized); } pub const Vec2 = std.meta.Vector(2, f64); /// Turn a scalar into a vector pub inline fn v(s: f64) Vec2 { return @splat(2, s); } /// Find the dot product of two vectors pub inline fn dot(a: Vec2, b: Vec2) f64 { return @reduce(.Add, a * b); } /// Find |a|^2 pub inline fn mag2(a: Vec2) f64 { return dot(a, a); } /// Find |a| pub inline fn mag(a: Vec2) f64 { return @sqrt(mag2(a)); } /// Normalize a vector pub inline fn normalize(a: Vec2) Vec2 { return a * v(1 / mag(a)); } /// (x, y) -> (-y, x) pub inline fn conj(a: Vec2) Vec2 { return .{ -a[1], a[0] }; } /// Compute (a x b) x c /// /// Useful for computing perpendicular vectors: /// - ((a x b) x a) is perpendicular to a, pointing towards b /// - ((b x a) x a) is perpendicular to a, pointing away from b pub inline fn tripleCross(a: Vec2, b: Vec2, c: Vec2) Vec2 { const k = a[0] * b[1] - a[1] * b[0]; return .{ c[1] * -k, c[0] * k }; } /// Rotate vector a by rotating the vector (1, 0) to vector b pub inline fn rotate(a: Vec2, b: Vec2) Vec2 { // This is just a complex number multiply const p = a * Vec2{ b[0], b[0] }; const q = Vec2{ a[1], a[0] } * Vec2{ b[1], b[1] } * Vec2{ -1, 1 }; return p + q; } /// Compute approximate equality between vectors or floats /// See here for more info: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ pub inline fn close(a: anytype, b: anytype, ulp_threshold: u63) bool { switch (@TypeOf(a, b)) { f64 => { if (a == b) return true; if (std.math.signbit(a) != std.math.signbit(b)) return false; const ulps = @bitCast(i64, a) - @bitCast(i64, b); return ulps <= ulp_threshold and -ulps <= ulp_threshold; }, Vec2 => { if (@reduce(.And, a == b)) return true; const signs = @bitCast(std.meta.Vector(2, u64), a) ^ @bitCast(std.meta.Vector(2, u64), b); if (@reduce(.Or, signs) >> 63 != 0) { return false; } const ulps = @bitCast(std.meta.Vector(2, i64), a) - @bitCast(std.meta.Vector(2, i64), b); const thres_v = @splat(2, @as(i64, ulp_threshold)); return @reduce(.And, ulps <= thres_v) and @reduce(.And, -ulps <= thres_v); }, else => @compileError("Unsupported type " ++ @typeName(@TypeOf(a, b)) ++ " for v.close"), } } test "close float" { const values = [_]f64{ 0.49999999999999988897769753748434595763683319091796875, 0.499999999999999944488848768742172978818416595458984375, 0.5, 0.50000000000000011102230246251565404236316680908203125, 0.5000000000000002220446049250313080847263336181640625, }; try std.testing.expect(close(values[2], values[1], 1)); try std.testing.expect(close(values[2], values[3], 1)); try std.testing.expect(!close(values[2], values[0], 1)); try std.testing.expect(!close(values[2], values[4], 1)); try std.testing.expect(close(values[2], values[1], 2)); try std.testing.expect(close(values[2], values[3], 2)); try std.testing.expect(close(values[2], values[0], 2)); try std.testing.expect(close(values[2], values[4], 2)); } test "close vec" { const values = [_]f64{ 0.49999999999999988897769753748434595763683319091796875, 0.499999999999999944488848768742172978818416595458984375, 0.5, 0.50000000000000011102230246251565404236316680908203125, 0.5000000000000002220446049250313080847263336181640625, }; const vecs = [_]Vec2{ .{ values[0], values[0] }, .{ values[0], values[1] }, .{ values[1], values[1] }, .{ values[1], values[2] }, .{ values[2], values[2] }, .{ values[2], values[3] }, .{ values[3], values[3] }, .{ values[3], values[4] }, .{ values[4], values[4] }, }; try std.testing.expect(close(vecs[4], vecs[2], 1)); try std.testing.expect(close(vecs[4], vecs[3], 1)); try std.testing.expect(close(vecs[4], vecs[5], 1)); try std.testing.expect(close(vecs[4], vecs[6], 1)); try std.testing.expect(!close(vecs[4], vecs[0], 1)); try std.testing.expect(!close(vecs[4], vecs[1], 1)); try std.testing.expect(!close(vecs[4], vecs[7], 1)); try std.testing.expect(!close(vecs[4], vecs[8], 1)); try std.testing.expect(close(vecs[4], vecs[2], 2)); try std.testing.expect(close(vecs[4], vecs[3], 2)); try std.testing.expect(close(vecs[4], vecs[5], 2)); try std.testing.expect(close(vecs[4], vecs[6], 2)); try std.testing.expect(close(vecs[4], vecs[0], 2)); try std.testing.expect(close(vecs[4], vecs[1], 2)); try std.testing.expect(close(vecs[4], vecs[7], 2)); try std.testing.expect(close(vecs[4], vecs[8], 2)); }
v.zig
const std = @import("std"); const json = std.json; const mem = std.mem; const testing = std.testing; pub const jsonrpc_version = "2.0"; const default_parse_options = json.ParseOptions{ .allocator = null, .duplicate_field_behavior = .Error, .ignore_unknown_fields = false, .allow_trailing_data = false, }; pub const SimpleRequest = Request([]const Value); pub const SimpleResponse = Response(Value, Value); /// Primitive json value which can be represented as Zig value. /// Includes all json values but "object". For objects one should construct a Zig struct. pub const Value = union(enum) { Bool: bool, Integer: i64, Float: f64, String: []const u8, // Recursive definition of structs for JSON does not work yet, waiting for new release. // See https://github.com/ziglang/zig/pull/9307 // After fixing it, please also enable and fix the commented test case. // Array: []const Value, }; /// Id can be a number, a string or null. pub const IdValue = union(enum) { Integer: i64, Float: f64, String: []const u8, }; /// Parses a `method` of a Request object from `string`. Caller owns the memory. /// Only works for `Request`, throws error otherwise. pub fn parseMethodAlloc(ally: *mem.Allocator, string: []const u8) ![]u8 { const RequestMethod = struct { method: []u8 }; const parse_options = json.ParseOptions{ .allocator = ally, .duplicate_field_behavior = .Error, .ignore_unknown_fields = true, .allow_trailing_data = false, }; var token_stream = json.TokenStream.init(string); const parsed = try json.parse(RequestMethod, &token_stream, parse_options); return parsed.method; } /// Parses a `method` of a Request object from `string`. /// Only works for `Request`, throws error otherwise. pub fn parseMethod(buf: []u8, string: []const u8) ![]u8 { var fba = std.heap.FixedBufferAllocator.init(buf); var ally = &fba.allocator; return try parseMethodAlloc(ally, string); } /// Parses an `id` of a Request object from `string`. Caller owns the memory. /// Does not work for `Notification`, throws error. pub fn parseIdAlloc(ally: ?*mem.Allocator, string: []const u8) !?IdValue { const RequestId = struct { id: ?IdValue }; const parse_options = json.ParseOptions{ .allocator = ally, .duplicate_field_behavior = .Error, .ignore_unknown_fields = true, .allow_trailing_data = false, }; var token_stream = json.TokenStream.init(string); const parsed = try json.parse(RequestId, &token_stream, parse_options); return parsed.id; } /// Parses an `id` of a Request object from `string`. /// Does not work for `Notification`, throws error. pub fn parseId(buf: ?[]u8, string: []const u8) !?IdValue { if (buf) |b| { var fba = std.heap.FixedBufferAllocator.init(b); var ally = &fba.allocator; return try parseIdAlloc(ally, string); } else { return try parseIdAlloc(null, string); } } pub const RequestKind = enum { Request, RequestNoParams, Notification, NotificationNoParams }; /// The resulting structure which represents a "Request" object as specified in JSON-RPC 2.0. /// Request object has `null` in `id` field for Notification type. pub fn Request(comptime ParamsShape: type) type { const error_message = "Only Struct or Slice is allowed, found '" ++ @typeName(ParamsShape) ++ "'"; switch (@typeInfo(ParamsShape)) { .Struct => {}, .Pointer => |info| { if (info.size != .Slice) @compileError(error_message); }, else => @compileError(error_message), } return union(RequestKind) { /// Request object with all the fields present. Request: struct { jsonrpc: []const u8, method: []const u8, id: ?IdValue, params: ParamsShape, }, /// Request object with `params` field omitted. RequestNoParams: struct { jsonrpc: []const u8, method: []const u8, id: ?IdValue, }, /// Notification object with all the fields present. Notification: struct { jsonrpc: []const u8, method: []const u8, params: ParamsShape, }, /// Notification object with `params` field omitted. NotificationNoParams: struct { jsonrpc: []const u8, method: []const u8, }, const Self = @This(); /// Initializes a Request object. Pass `null` to `params` in order to omit it. pub fn init(_id: ?IdValue, _method: []const u8, _params: ?ParamsShape) Self { if (_params) |p| { return Self{ .Request = .{ .jsonrpc = jsonrpc_version, .id = _id, .method = _method, .params = p, } }; } else { return Self{ .RequestNoParams = .{ .jsonrpc = jsonrpc_version, .id = _id, .method = _method, } }; } } /// Initializes a Notification object. Pass `null` to `params` in order to omit it. pub fn initNotification(_method: []const u8, _params: ?ParamsShape) Self { if (_params) |p| { return Self{ .Notification = .{ .jsonrpc = jsonrpc_version, .method = _method, .params = p, } }; } else { return Self{ .NotificationNoParams = .{ .jsonrpc = jsonrpc_version, .method = _method, } }; } } /// Getter function for `jsonrpc`. pub fn jsonrpc(self: Self) []const u8 { return switch (self) { .Request => |s| s.jsonrpc, .RequestNoParams => |s| s.jsonrpc, .Notification => |s| s.jsonrpc, .NotificationNoParams => |s| s.jsonrpc, }; } /// Getter function for `method`. pub fn method(self: Self) []const u8 { return switch (self) { .Request => |s| s.method, .RequestNoParams => |s| s.method, .Notification => |s| s.method, .NotificationNoParams => |s| s.method, }; } /// Getter function for `id`. pub fn id(self: Self) ?IdValue { return switch (self) { .Request => |s| s.id, .RequestNoParams => |s| s.id, .Notification, .NotificationNoParams => unreachable, }; } /// Getter function for `params`. pub fn params(self: Self) ParamsShape { return switch (self) { .Request => |s| s.params, .Notification => |s| s.params, .RequestNoParams, .NotificationNoParams => unreachable, }; } /// Parses a string into a Request object. Requires `allocator` if /// any of the `Request` values are pointers/slices; pass `null` otherwise. /// Caller owns the memory, free it with `parseFree`. pub fn parseAlloc(allocator: *mem.Allocator, string: []const u8) !Self { var parse_options = default_parse_options; parse_options.allocator = allocator; var token_stream = json.TokenStream.init(string); const result = try json.parse(Self, &token_stream, parse_options); if (!mem.eql(u8, jsonrpc_version, result.jsonrpc())) return error.IncorrectJsonrpcVersion; return result; } /// Frees memory from call to `parseAlloc`. pub fn parseFree(self: Self, allocator: *mem.Allocator) void { var parse_options = default_parse_options; parse_options.allocator = allocator; json.parseFree(Self, self, parse_options); } /// Parses a string into a Request object. pub fn parse(buf: []u8, string: []const u8) !Self { var fba = std.heap.FixedBufferAllocator.init(buf); return try parseAlloc(&fba.allocator, string); } /// Generates a string representation of a Request object. Caller owns the memory. pub fn generateAlloc(self: Self, allocator: *mem.Allocator) ![]u8 { var result = std.ArrayList(u8).init(allocator); try self.writeTo(result.writer()); return result.toOwnedSlice(); } /// Generates a string representation of a Request object. pub fn generate(self: Self, buf: []u8) ![]u8 { var fba = std.heap.FixedBufferAllocator.init(buf); return try self.generateAlloc(&fba.allocator); } /// Writes a string representation of a Request object to a specified `stream`. pub fn writeTo(self: Self, stream: anytype) !void { try json.stringify(self, .{}, stream); } }; } pub const ResponseKind = enum { Result, Error }; /// The resulting structure which represents a "Response" object as specified in JSON-RPC 2.0. /// Response object has either `null` value in `result` or in `error` field depending on the type. pub fn Response(comptime ResultShape: type, comptime ErrorDataShape: type) type { return union(ResponseKind) { /// Successful Response object. Result: struct { jsonrpc: []const u8, id: ?IdValue, result: ResultShape, }, /// Error Response object. Error: struct { jsonrpc: []const u8, id: ?IdValue, @"error": ErrorObject, }, const Self = @This(); const ErrorObjectWithoutData = struct { code: i64, message: []const u8 }; const ErrorObjectWithData = struct { code: i64, message: []const u8, data: ErrorDataShape }; const ErrorObject = union(enum) { WithoutData: ErrorObjectWithoutData, WithData: ErrorObjectWithData, }; /// Initializes a successful Response object. pub fn initResult(_id: ?IdValue, _result: ResultShape) Self { return Self{ .Result = .{ .jsonrpc = jsonrpc_version, .id = _id, .result = _result, } }; } /// Initializes an error Response object. Pass `null` to `data` to omit this field. pub fn initError(_id: ?IdValue, _code: i64, _message: []const u8, _data: ?ErrorDataShape) Self { if (_data) |data| { return Self{ .Error = .{ .jsonrpc = jsonrpc_version, .id = _id, .@"error" = .{ .WithData = .{ .code = _code, .message = _message, .data = data } }, } }; } else { return Self{ .Error = .{ .jsonrpc = jsonrpc_version, .id = _id, .@"error" = .{ .WithoutData = .{ .code = _code, .message = _message } }, } }; } } /// Getter function for `jsonrpc`. pub fn jsonrpc(self: Self) []const u8 { return switch (self) { .Result => |s| s.jsonrpc, .Error => |s| s.jsonrpc, }; } /// Getter function for `id`. pub fn id(self: Self) ?IdValue { return switch (self) { .Result => |s| s.id, .Error => |s| s.id, }; } /// Getter function for `result`. pub fn result(self: Self) ResultShape { return switch (self) { .Result => |s| s.result, .Error => unreachable, }; } /// Getter function for `error`. pub fn @"error"(self: Self) ErrorObject { return switch (self) { .Result => unreachable, .Error => |s| s.@"error", }; } /// Getter function for `error.code`. pub fn errorCode(self: Self) i64 { return switch (self) { .Result => unreachable, .Error => |s| switch (s.@"error") { .WithoutData => |e| e.code, .WithData => |e| e.code, }, }; } /// Getter function for `error.message`. pub fn errorMessage(self: Self) []const u8 { return switch (self) { .Result => unreachable, .Error => |s| switch (s.@"error") { .WithoutData => |e| e.message, .WithData => |e| e.message, }, }; } /// Getter function for `error.data`. pub fn errorData(self: Self) ErrorDataShape { return switch (self) { .Result => unreachable, .Error => |s| switch (s.@"error") { .WithoutData => unreachable, .WithData => |e| e.data, }, }; } /// Parses a string into a `Response` object. Requires `allocator` if /// any of the `Response` values are pointers/slices; pass `null` otherwise. /// Caller owns the memory, free it with `parseFree`. pub fn parseAlloc(allocator: ?*mem.Allocator, string: []const u8) !Self { var parse_options = default_parse_options; parse_options.allocator = allocator; var token_stream = json.TokenStream.init(string); const rs = try json.parse(Self, &token_stream, parse_options); if (!mem.eql(u8, jsonrpc_version, rs.jsonrpc())) return error.IncorrectJsonrpcVersion; return rs; } /// Frees memory from `parseAlloc` call. pub fn parseFree(self: Self, allocator: *mem.Allocator) void { var parse_options = default_parse_options; parse_options.allocator = allocator; json.parseFree(Self, self, parse_options); } /// Parses a string into a `Response` object. pub fn parse(buf: []u8, string: []const u8) !Self { var fba = std.heap.FixedBufferAllocator.init(buf); return try parseAlloc(&fba.allocator, string); } /// Generates a string representation of a Response object. Caller owns the memory. pub fn generateAlloc(self: Self, allocator: *mem.Allocator) ![]u8 { var rs = std.ArrayList(u8).init(allocator); try self.writeTo(rs.writer()); return rs.toOwnedSlice(); } /// Generates a string representation of a Response object. pub fn generate(self: Self, buf: []u8) ![]u8 { var fba = std.heap.FixedBufferAllocator.init(buf); return try self.generateAlloc(&fba.allocator); } /// Writes a string representation of a Response object to a specified `stream`. pub fn writeTo(self: Self, stream: anytype) !void { try json.stringify(self, .{}, stream); } }; } // =========================================================================== // Testing // =========================================================================== // // Note that "generate" tests depend on how Zig orders keys in the object type. In spec they have // no order and for the actual use it also doesn't matter. test "jsonrpc: parse alloc request" { const params = [_]Value{ .{ .String = "Bob" }, .{ .String = "Alice" }, .{ .Integer = 10 } }; const request = SimpleRequest.init(IdValue{ .Integer = 63 }, "startParty", &params); const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":63} ; const parsed = try SimpleRequest.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqual(RequestKind.Request, std.meta.activeTag(parsed)); try testing.expectEqualStrings(request.jsonrpc(), parsed.jsonrpc()); try testing.expectEqualStrings(request.method(), parsed.method()); try testing.expectEqualStrings(request.params()[0].String, parsed.params()[0].String); try testing.expectEqualStrings(request.params()[1].String, parsed.params()[1].String); try testing.expectEqual(request.params()[2].Integer, parsed.params()[2].Integer); try testing.expectEqual(request.id(), parsed.id()); parsed.parseFree(testing.allocator); } test "jsonrpc: parse request" { const params = [_]Value{ .{ .String = "Bob" }, .{ .String = "Alice" }, .{ .Integer = 10 } }; const request = SimpleRequest.init(IdValue{ .Integer = 63 }, "startParty", &params); const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":63} ; var buf: [4096]u8 = undefined; const parsed = try SimpleRequest.parse(&buf, jsonrpc_string); try testing.expectEqualStrings(request.jsonrpc(), parsed.jsonrpc()); try testing.expectEqualStrings(request.method(), parsed.method()); try testing.expectEqualStrings(request.params()[0].String, parsed.params()[0].String); try testing.expectEqualStrings(request.params()[1].String, parsed.params()[1].String); try testing.expectEqual(request.params()[2].Integer, parsed.params()[2].Integer); try testing.expectEqual(request.id(), parsed.id()); } const Face = struct { fg: []const u8, bg: []const u8, attributes: []const []const u8 = mem.span(&empty_attr), const empty_attr = [_][]const u8{}; }; const Span = struct { face: Face, contents: []const u8, }; fn expectEqualFaces(expected: Face, actual: Face) !void { try testing.expectEqualStrings(expected.fg, actual.fg); try testing.expectEqualStrings(expected.bg, actual.bg); var i: usize = 0; while (i < expected.attributes.len) : (i += 1) { try testing.expectEqualStrings(expected.attributes[i], actual.attributes[i]); } } fn expectEqualSpans(expected: Span, actual: Span) !void { try expectEqualFaces(expected.face, actual.face); try testing.expectEqualStrings(expected.contents, actual.contents); } fn removeSpaces(allocator: *mem.Allocator, str: []const u8) ![]u8 { var result = std.ArrayList(u8).init(allocator); var inside_string = false; for (str) |ch| { switch (ch) { '"' => { if (inside_string) { inside_string = false; } else { inside_string = true; } try result.append(ch); }, ' ', '\n' => { if (inside_string) try result.append(ch); }, else => try result.append(ch), } } return result.items; } test "jsonrpc: parse complex request" { const reverse_attr = [_][]const u8{"reverse"}; const final_attr = [_][]const u8{ "final_fg", "final_bg" }; const Parameter = union(enum) { lines: []const []const Span, face: Face, }; const ParamsShape = []const Parameter; const MyRequest = Request(ParamsShape); const first_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default", .attributes = mem.span(&reverse_attr) }, .contents = " 1", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " ", }, Span{ .face = Face{ .fg = "black", .bg = "white", .attributes = mem.span(&final_attr) }, .contents = "*", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "** this is a *scratch* buffer", }, }; const second_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " 1 ", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "*** use it for notes", }, }; const lines_array = [_][]const Span{ mem.span(&first_line_array), mem.span(&second_line_array), }; const params = [_]Parameter{ .{ .lines = mem.span(&lines_array) }, .{ .face = Face{ .fg = "default", .bg = "default" } }, .{ .face = Face{ .fg = "blue", .bg = "default" } }, }; const request = MyRequest.initNotification("draw", &params); // Taken from Kakoune editor and modified. const jsonrpc_string = \\{ \\ "jsonrpc": "2.0", \\ "method": "draw", \\ "params": [ \\ [ \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [ \\ "reverse" \\ ] \\ }, \\ "contents": " 1" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " " \\ }, \\ { \\ "face": { \\ "fg": "black", \\ "bg": "white", \\ "attributes": [ \\ "final_fg", \\ "final_bg" \\ ] \\ }, \\ "contents": "*" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "** this is a *scratch* buffer" \\ } \\ ], \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " 1 " \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "*** use it for notes" \\ } \\ ] \\ ], \\ { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ { \\ "fg": "blue", \\ "bg": "default", \\ "attributes": [] \\ } \\ ] \\} ; const parsed = try MyRequest.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(request.jsonrpc(), parsed.jsonrpc()); try testing.expectEqualStrings(request.method(), parsed.method()); try testing.expectEqual(RequestKind.Notification, std.meta.activeTag(request)); var line_idx: usize = 0; const lines = request.params()[0].lines; while (line_idx < lines.len) : (line_idx += 1) { var span_idx: usize = 0; const spans = lines[line_idx]; while (span_idx < spans.len) : (span_idx += 1) { try expectEqualSpans(spans[span_idx], parsed.params()[0].lines[line_idx][span_idx]); } } try expectEqualFaces(request.params()[1].face, parsed.params()[1].face); try expectEqualFaces(request.params()[2].face, parsed.params()[2].face); parsed.parseFree(testing.allocator); } test "jsonrpc: generate alloc request" { const params = [_]Value{ .{ .String = "Bob" }, .{ .String = "Alice" }, .{ .Integer = 10 } }; const request = SimpleRequest.init(IdValue{ .Integer = 63 }, "startParty", &params); const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","id":63,"params":["Bob","Alice",10]} ; const generated = try request.generateAlloc(testing.allocator); try testing.expectEqualStrings(jsonrpc_string, generated); testing.allocator.free(generated); } test "jsonrpc: generate request" { const params = [_]Value{ .{ .String = "Bob" }, .{ .String = "Alice" }, .{ .Integer = 10 } }; const request = SimpleRequest.init(IdValue{ .Integer = 63 }, "startParty", &params); const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","id":63,"params":["Bob","Alice",10]} ; var buf: [256]u8 = undefined; const generated = try request.generate(&buf); try testing.expectEqualStrings(jsonrpc_string, generated); } test "jsonrpc: generate notification without ID" { const params = [_]Value{ .{ .String = "Bob" }, .{ .String = "Alice" }, .{ .Integer = 10 } }; const request = SimpleRequest.initNotification("startParty", &params); const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10]} ; const generated = try request.generateAlloc(testing.allocator); try testing.expectEqualStrings(jsonrpc_string, generated); testing.allocator.free(generated); } test "jsonrpc: generate complex request" { const reverse_attr = [_][]const u8{"reverse"}; const final_attr = [_][]const u8{ "final_fg", "final_bg" }; const Parameter = union(enum) { lines: []const []const Span, face: Face, }; const ParamsShape = []const Parameter; const MyRequest = Request(ParamsShape); const first_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default", .attributes = mem.span(&reverse_attr) }, .contents = " 1", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " ", }, Span{ .face = Face{ .fg = "black", .bg = "white", .attributes = mem.span(&final_attr) }, .contents = "*", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "** this is a *scratch* buffer", }, }; const second_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " 1 ", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "*** use it for notes", }, }; const lines_array = [_][]const Span{ mem.span(&first_line_array), mem.span(&second_line_array), }; const params = [_]Parameter{ .{ .lines = mem.span(&lines_array) }, .{ .face = Face{ .fg = "default", .bg = "default" } }, .{ .face = Face{ .fg = "blue", .bg = "default" } }, }; const request = MyRequest.init(IdValue{ .Integer = 87 }, "draw", &params); // Taken from Kakoune editor and modified. const jsonrpc_string = \\{ \\ "jsonrpc": "2.0", \\ "method": "draw", \\ "id": 87, \\ "params": [ \\ [ \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [ \\ "reverse" \\ ] \\ }, \\ "contents": " 1" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " " \\ }, \\ { \\ "face": { \\ "fg": "black", \\ "bg": "white", \\ "attributes": [ \\ "final_fg", \\ "final_bg" \\ ] \\ }, \\ "contents": "*" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "** this is a *scratch* buffer" \\ } \\ ], \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " 1 " \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "*** use it for notes" \\ } \\ ] \\ ], \\ { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ { \\ "fg": "blue", \\ "bg": "default", \\ "attributes": [] \\ } \\ ] \\} ; const generated = try request.generateAlloc(testing.allocator); const stripped_jsonrpc_string = try removeSpaces(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(stripped_jsonrpc_string, generated); testing.allocator.free(generated); testing.allocator.free(stripped_jsonrpc_string); } test "jsonrpc: parse alloc success response" { const data = Value{ .Integer = 42 }; const response = SimpleResponse.initResult(IdValue{ .Integer = 63 }, data); const jsonrpc_string = \\{"jsonrpc":"2.0","result":42,"id":63} ; const parsed = try SimpleResponse.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqual(ResponseKind.Result, std.meta.activeTag(parsed)); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.result().Integer, parsed.result().Integer); try testing.expectEqual(response.id(), parsed.id()); parsed.parseFree(testing.allocator); } test "jsonrpc: parse buf success response" { const data = Value{ .Integer = 42 }; const response = SimpleResponse.initResult(IdValue{ .Integer = 63 }, data); const jsonrpc_string = \\{"jsonrpc":"2.0","result":42,"id":63} ; var buf: [4096]u8 = undefined; const parsed = try SimpleResponse.parse(&buf, jsonrpc_string); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.result().Integer, parsed.result().Integer); try testing.expectEqual(response.id(), parsed.id()); } test "jsonrpc: parse error response" { const response = SimpleResponse.initError(IdValue{ .Integer = 63 }, 13, "error message", null); const jsonrpc_string = \\{"jsonrpc":"2.0","error":{"code":13,"message":"error message"},"id":63} ; const parsed = try SimpleResponse.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqual(ResponseKind.Error, std.meta.activeTag(parsed)); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.errorCode(), parsed.errorCode()); try testing.expectEqualStrings(response.errorMessage(), parsed.errorMessage()); try testing.expectEqual(response.id(), parsed.id()); parsed.parseFree(testing.allocator); } test "jsonrpc: parse error response with data" { const response = SimpleResponse.initError( IdValue{ .Integer = 63 }, 13, "error message", Value{ .String = "additional info" }, ); const jsonrpc_string = \\{"jsonrpc":"2.0","id":63,"error":{"code":13,"message":"error message","data":"additional info"}} ; const parsed = try SimpleResponse.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.errorCode(), parsed.errorCode()); try testing.expectEqualStrings(response.errorMessage(), parsed.errorMessage()); try testing.expectEqual(response.id(), parsed.id()); try testing.expectEqualStrings(response.errorData().String, parsed.errorData().String); parsed.parseFree(testing.allocator); } // TODO: enable after the issue with Array type is fixed. // test "jsonrpc: parse array response" { // const data = [_]Value{ .{ .Integer = 42 }, .{ .String = "The Answer" } }; // const array_data = .{ .Array = mem.span(&data) }; // const response = SimpleResponse.initResult(IdValue{ .Integer = 63 }, array_data); // const jsonrpc_string = // \\{"jsonrpc":"2.0","result":[42,"The Answer"],"id":63} // ; // const parsed = try SimpleResponse.parseAlloc(testing.allocator, jsonrpc_string); // try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); // try testing.expectEqual(response.result().Array[0].Integer, parsed.result().Array[0].Integer); // try testing.expectEqualStrings(response.result().Array[1].String, parsed.result().Array[1].String); // try testing.expectEqual(response.id(), parsed.id()); // parsed.parseFree(testing.allocator); // } test "jsonrpc: parse custom array response" { const CustomArrayResponse = Response([2]u32, Value); const array_data = [_]u32{ 58, 67 }; const response = CustomArrayResponse.initResult(IdValue{ .Integer = 63 }, array_data); const jsonrpc_string = \\{"jsonrpc":"2.0","result":[58,67],"id":63} ; const parsed = try CustomArrayResponse.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.result()[0], parsed.result()[0]); try testing.expectEqual(response.result()[1], parsed.result()[1]); try testing.expectEqual(response.id(), parsed.id()); parsed.parseFree(testing.allocator); } test "jsonrpc: parse complex response" { const reverse_attr = [_][]const u8{"reverse"}; const final_attr = [_][]const u8{ "final_fg", "final_bg" }; const Parameter = union(enum) { lines: []const []const Span, face: Face, }; const ResultShape = []const Parameter; const MyResponse = Response(ResultShape, Value); const first_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default", .attributes = mem.span(&reverse_attr) }, .contents = " 1", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " ", }, Span{ .face = Face{ .fg = "black", .bg = "white", .attributes = mem.span(&final_attr) }, .contents = "*", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "** this is a *scratch* buffer", }, }; const second_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " 1 ", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "*** use it for notes", }, }; const lines_array = [_][]const Span{ mem.span(&first_line_array), mem.span(&second_line_array), }; const params = [_]Parameter{ .{ .lines = mem.span(&lines_array) }, .{ .face = Face{ .fg = "default", .bg = "default" } }, .{ .face = Face{ .fg = "blue", .bg = "default" } }, }; const params_array = mem.span(&params); const response = MyResponse.initResult(IdValue{ .Integer = 98 }, params_array); // Taken from Kakoune editor and modified. const jsonrpc_string = \\{ \\ "jsonrpc": "2.0", \\ "id": 98, \\ "result": [ \\ [ \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [ \\ "reverse" \\ ] \\ }, \\ "contents": " 1" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " " \\ }, \\ { \\ "face": { \\ "fg": "black", \\ "bg": "white", \\ "attributes": [ \\ "final_fg", \\ "final_bg" \\ ] \\ }, \\ "contents": "*" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "** this is a *scratch* buffer" \\ } \\ ], \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " 1 " \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "*** use it for notes" \\ } \\ ] \\ ], \\ { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ { \\ "fg": "blue", \\ "bg": "default", \\ "attributes": [] \\ } \\ ] \\} ; const parsed = try MyResponse.parseAlloc(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(response.jsonrpc(), parsed.jsonrpc()); try testing.expectEqual(response.id(), parsed.id()); var line_idx: usize = 0; const lines = response.result()[0].lines; while (line_idx < lines.len) : (line_idx += 1) { var span_idx: usize = 0; const spans = lines[line_idx]; while (span_idx < spans.len) : (span_idx += 1) { try expectEqualSpans(spans[span_idx], parsed.result()[0].lines[line_idx][span_idx]); } } try expectEqualFaces(response.result()[1].face, parsed.result()[1].face); try expectEqualFaces(response.result()[2].face, parsed.result()[2].face); parsed.parseFree(testing.allocator); } test "jsonrpc: generate alloc success response" { const data = Value{ .Integer = 42 }; const response = SimpleResponse.initResult(IdValue{ .Integer = 63 }, data); const jsonrpc_string = \\{"jsonrpc":"2.0","id":63,"result":42} ; const generated = try response.generateAlloc(testing.allocator); try testing.expectEqualStrings(jsonrpc_string, generated); testing.allocator.free(generated); } test "jsonrpc: generate success response" { const data = Value{ .Integer = 42 }; const response = SimpleResponse.initResult(IdValue{ .Integer = 63 }, data); const jsonrpc_string = \\{"jsonrpc":"2.0","id":63,"result":42} ; var buf: [256]u8 = undefined; const generated = try response.generate(&buf); try testing.expectEqualStrings(jsonrpc_string, generated); } test "jsonrpc: generate error response" { const response = SimpleResponse.initError(IdValue{ .Integer = 63 }, 13, "error message", null); const jsonrpc_string = \\{"jsonrpc":"2.0","id":63,"error":{"code":13,"message":"error message"}} ; const generated = try response.generateAlloc(testing.allocator); defer testing.allocator.free(generated); try testing.expectEqualStrings(jsonrpc_string, generated); } test "jsonrpc: generate error response with data" { const response = SimpleResponse.initError( IdValue{ .Integer = 63 }, 13, "error message", Value{ .String = "additional data" }, ); const jsonrpc_string = \\{"jsonrpc":"2.0","id":63,"error":{"code":13,"message":"error message","data":"additional data"}} ; const generated = try response.generateAlloc(testing.allocator); defer testing.allocator.free(generated); try testing.expectEqualStrings(jsonrpc_string, generated); } test "jsonrpc: generate complex response" { const reverse_attr = [_][]const u8{"reverse"}; const final_attr = [_][]const u8{ "final_fg", "final_bg" }; const Parameter = union(enum) { lines: []const []const Span, face: Face, }; const ResultShape = []const Parameter; const MyResponse = Response(ResultShape, Value); const first_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default", .attributes = mem.span(&reverse_attr) }, .contents = " 1", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " ", }, Span{ .face = Face{ .fg = "black", .bg = "white", .attributes = mem.span(&final_attr) }, .contents = "*", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "** this is a *scratch* buffer", }, }; const second_line_array = [_]Span{ Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = " 1 ", }, Span{ .face = Face{ .fg = "default", .bg = "default" }, .contents = "*** use it for notes", }, }; const lines_array = [_][]const Span{ mem.span(&first_line_array), mem.span(&second_line_array), }; const params = [_]Parameter{ .{ .lines = mem.span(&lines_array) }, .{ .face = Face{ .fg = "default", .bg = "default" } }, .{ .face = Face{ .fg = "blue", .bg = "default" } }, }; const params_array = mem.span(&params); const response = MyResponse.initResult(IdValue{ .Integer = 98 }, params_array); // Taken from Kakoune editor and modified. const jsonrpc_string = \\{ \\ "jsonrpc": "2.0", \\ "id": 98, \\ "result": [ \\ [ \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [ \\ "reverse" \\ ] \\ }, \\ "contents": " 1" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " " \\ }, \\ { \\ "face": { \\ "fg": "black", \\ "bg": "white", \\ "attributes": [ \\ "final_fg", \\ "final_bg" \\ ] \\ }, \\ "contents": "*" \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "** this is a *scratch* buffer" \\ } \\ ], \\ [ \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": " 1 " \\ }, \\ { \\ "face": { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ "contents": "*** use it for notes" \\ } \\ ] \\ ], \\ { \\ "fg": "default", \\ "bg": "default", \\ "attributes": [] \\ }, \\ { \\ "fg": "blue", \\ "bg": "default", \\ "attributes": [] \\ } \\ ] \\} ; const generated = try response.generateAlloc(testing.allocator); const stripped_jsonrpc_string = try removeSpaces(testing.allocator, jsonrpc_string); try testing.expectEqualStrings(stripped_jsonrpc_string, generated); testing.allocator.free(generated); testing.allocator.free(stripped_jsonrpc_string); } test "jsonrpc: parse request and only return a method" { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":63} ; const method = try parseMethodAlloc(testing.allocator, jsonrpc_string); try testing.expectEqualStrings("startParty", method); testing.allocator.free(method); } test "jsonrpc: parse request and only return a method" { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":63} ; var buf: [32]u8 = undefined; const method = try parseMethod(&buf, jsonrpc_string); try testing.expectEqualStrings("startParty", method); } test "jsonrpc: parse request and only return a string ID" { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":"uuid-85"} ; var buf: [32]u8 = undefined; const id = try parseId(&buf, jsonrpc_string); try testing.expectEqualStrings("uuid-85", id.?.String); } test "jsonrpc: parse request and only return an integer ID" { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":63} ; const id = try parseId(null, jsonrpc_string); try testing.expectEqual(@as(?IdValue, IdValue{ .Integer = 63 }), id); } test "jsonrpc: must return an error if jsonrpc has missing field" { var buf: [512]u8 = undefined; { const jsonrpc_string = \\{"method":"startParty","params":["Bob","Alice",10],"id":63} ; try testing.expectError(error.NoUnionMembersMatched, SimpleRequest.parse(&buf, jsonrpc_string)); } { const jsonrpc_string = \\{"id":63,"result":42} ; try testing.expectError(error.NoUnionMembersMatched, SimpleResponse.parse(&buf, jsonrpc_string)); } } test "jsonrpc: must return an error if jsonrpc has incorrect version" { var buf: [512]u8 = undefined; { const jsonrpc_string = \\{"jsonrpc":"2.1","method":"startParty","params":["Bob","Alice",10],"id":63} ; try testing.expectError(error.IncorrectJsonrpcVersion, SimpleRequest.parse(&buf, jsonrpc_string)); } { const jsonrpc_string = \\{"jsonrpc":"2.1","id":63,"result":42} ; try testing.expectError(error.IncorrectJsonrpcVersion, SimpleResponse.parse(&buf, jsonrpc_string)); } } test "jsonrpc: parse null id values" { var buf: [256]u8 = undefined; { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","params":["Bob","Alice",10],"id":null} ; const request = try SimpleRequest.parse(&buf, jsonrpc_string); try testing.expectEqual(@as(?IdValue, null), request.id()); } { const jsonrpc_string = \\{"jsonrpc":"2.0","id":null,"result":42} ; const response = try SimpleResponse.parse(&buf, jsonrpc_string); try testing.expectEqual(@as(?IdValue, null), response.id()); } } test "jsonrpc: parse requests without params" { var buf: [256]u8 = undefined; { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty","id":"uid250"} ; const request = try SimpleRequest.parse(&buf, jsonrpc_string); try testing.expectEqual(RequestKind.RequestNoParams, std.meta.activeTag(request)); } { const jsonrpc_string = \\{"jsonrpc":"2.0","method":"startParty"} ; const request = try SimpleRequest.parse(&buf, jsonrpc_string); try testing.expectEqual(RequestKind.NotificationNoParams, std.meta.activeTag(request)); } }
src/jsonrpc.zig
const std = @import("std"); const Compilation = @import("Compilation.zig"); const Type = @import("Type.zig"); const Builtins = @This(); const Builtin = struct { spec: Type.Specifier, func_ty: Type.Func, attrs: Attributes, const Attributes = packed struct { printf_like: u8 = 0, vprintf_like: u8 = 0, noreturn: bool = false, libm: bool = false, libc: bool = false, returns_twice: bool = false, eval_args: bool = true, }; }; const BuiltinMap = std.StringHashMapUnmanaged(Builtin); _builtins: BuiltinMap = .{}, _params: []Type.Func.Param = &.{}, pub fn deinit(b: *Builtins, gpa: std.mem.Allocator) void { b._builtins.deinit(gpa); gpa.free(b._params); } fn add( a: std.mem.Allocator, b: *BuiltinMap, name: []const u8, ret_ty: Type, param_types: []const Type, spec: Type.Specifier, attrs: Builtin.Attributes, ) void { var params = a.alloc(Type.Func.Param, param_types.len) catch unreachable; // fib for (param_types) |param_ty, i| { params[i] = .{ .name_tok = 0, .ty = param_ty, .name = "" }; } b.putAssumeCapacity(name, .{ .spec = spec, .func_ty = .{ .return_type = ret_ty, .params = params, }, .attrs = attrs, }); } pub fn create(comp: *Compilation) !Builtins { const builtin_count = 3; const param_count = 5; var b = BuiltinMap{}; try b.ensureTotalCapacity(comp.gpa, builtin_count); errdefer b.deinit(comp.gpa); var _params = try comp.gpa.alloc(Type.Func.Param, param_count); errdefer comp.gpa.free(_params); var fib_state = std.heap.FixedBufferAllocator.init(std.mem.sliceAsBytes(_params)); const a = fib_state.allocator(); const void_ty = Type{ .specifier = .void }; var va_list = comp.types.va_list; if (va_list.isArray()) va_list.decayArray(); add(a, &b, "__builtin_va_start", void_ty, &.{ va_list, .{ .specifier = .special_va_start } }, .func, .{}); add(a, &b, "__builtin_va_end", void_ty, &.{va_list}, .func, .{}); add(a, &b, "__builtin_va_copy", void_ty, &.{ va_list, va_list }, .func, .{}); return Builtins{ ._builtins = b, ._params = _params }; } pub fn hasBuiltin(b: Builtins, name: []const u8) bool { if (std.mem.eql(u8, name, "__builtin_va_arg") or std.mem.eql(u8, name, "__builtin_choose_expr")) return true; return b._builtins.getPtr(name) != null; } pub fn get(b: Builtins, name: []const u8) ?Type { const builtin = b._builtins.getPtr(name) orelse return null; return Type{ .specifier = builtin.spec, .data = .{ .func = &builtin.func_ty }, }; }
src/Builtins.zig
const c = @cImport({ @cInclude("epoxy/gl.h"); }); const gl = @import("zgl.zig"); pub const VertexArray = enum(c.GLuint) { invalid = 0, _, pub const create = gl.createVertexArray; pub const delete = gl.deleteVertexArray; pub const gen = gl.genVertexArray; pub const bind = gl.bindVertexArray; pub const enableVertexAttribute = gl.enableVertexArrayAttrib; pub const disableVertexAttribute = gl.disableVertexArrayAttrib; pub const attribFormat = gl.vertexArrayAttribFormat; pub const attribIFormat = gl.vertexArrayAttribIFormat; pub const attribLFormat = gl.vertexArrayAttribLFormat; pub const attribBinding = gl.vertexArrayAttribBinding; pub const vertexBuffer = gl.vertexArrayVertexBuffer; pub const elementBuffer = gl.vertexArrayElementBuffer; }; pub const Buffer = enum(c.GLuint) { invalid = 0, _, pub const create = gl.createBuffer; pub const gen = gl.genBuffer; pub const bind = gl.bindBuffer; pub const delete = gl.deleteBuffer; pub const data = gl.namedBufferData; }; pub const Shader = enum(c.GLuint) { invalid = 0, _, pub const create = gl.createShader; pub const delete = gl.deleteShader; pub const compile = gl.compileShader; pub const source = gl.shaderSource; pub const get = gl.getShader; pub const getCompileLog = gl.getShaderInfoLog; }; pub const Program = enum(c.GLuint) { invalid = 0, _, pub const create = gl.createProgram; pub const delete = gl.deleteProgram; pub const attach = gl.attachShader; pub const detach = gl.detachShader; pub const link = gl.linkProgram; pub const use = gl.useProgram; pub const uniform1ui = gl.programUniform1ui; pub const uniform1i = gl.programUniform1i; pub const uniform1f = gl.programUniform1f; pub const uniform3f = gl.programUniform3f; pub const uniform4f = gl.programUniform4f; pub const uniformMatrix4 = gl.programUniformMatrix4; pub const get = gl.getProgram; pub const getCompileLog = gl.getProgramInfoLog; pub const uniformLocation = gl.getUniformLocation; }; pub const Texture = enum(c.GLuint) { invalid = 0, _, pub const create = gl.createTexture; pub const delete = gl.deleteTexture; pub const bindTo = gl.bindTextureUnit; pub const parameter = gl.textureParameter; pub const storage2D = gl.textureStorage2D; pub const storage3D = gl.textureStorage3D; pub const subImage2D = gl.textureSubImage2D; pub const subImage3D = gl.textureSubImage3D; };
types.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Allocator = std.mem.Allocator; const ShuntingYard = struct { const OperatorStack = std.ArrayList(u8); const OutputStack = std.ArrayList(usize); operator_stack: OperatorStack, output_stack: OutputStack, fn init(allocator: Allocator) ShuntingYard { return ShuntingYard { .operator_stack = OperatorStack.init(allocator), .output_stack = OutputStack.init(allocator), }; } fn deinit(self: *ShuntingYard) void { self.operator_stack.deinit(); self.output_stack.deinit(); } fn eval(self: *ShuntingYard, line: []const u8, precedence: bool) !usize { for (line) |token| { if (token == ' ') { continue; } if (token >= '0' and token <= '9') { try self.output_stack.append(token - '0'); } else if (token == '(') { try self.operator_stack.append(token); } else if (token == ')') { while (self.operator_stack.popOrNull()) |op| { if (op == '(') { break; } try self.processOp(op); } } else { while (self.operator_stack.popOrNull()) |op| { if (op == '('or (precedence and token == '+' and op == '*')) { try self.operator_stack.append(op); break; } try self.processOp(op); } try self.operator_stack.append(token); } } while (self.operator_stack.popOrNull()) |op| { try self.processOp(op); } return self.output_stack.pop(); } fn processOp(self: *ShuntingYard, op: u8) !void { const rhs = self.output_stack.pop(); const lhs = self.output_stack.pop(); try self.output_stack.append(switch (op) { '+' => lhs + rhs, '*' => lhs * rhs, else => unreachable }); } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var shunting_yard = ShuntingYard.init(problem.allocator); defer shunting_yard.deinit(); var res1: usize = 0; var res2: usize = 0; while (problem.line()) |line| { res1 += try shunting_yard.eval(line, false); res2 += try shunting_yard.eval(line, true); } return problem.solution(res1, res2); }
src/main/zig/2020/day18.zig
const std = @import("std"); const builtin = @import("builtin"); const Terminal = @import("tty.zig"); const SerialPort = @import("serial-port.zig"); const PIC = @import("pic.zig").PIC; const gdt = @import("gdt.zig"); const idt = @import("idt.zig"); const Keyboard = @import("./keyboard.zig"); // Exports comptime { @export(multiboot, .{ .name = "multiboot", .section = ".multiboot" }); @export(start, .{ .name = "_start" }); } // Declare constants for the multiboot header. const ALIGN = 1 << 0; // align loaded modules on page boundaries const MEMINFO = 1 << 1; // provide memory map const VIDEO_MODE = 1 << 2; // set the video mode const FLAGS = ALIGN | MEMINFO | VIDEO_MODE; // this is the Multiboot 'flag' field const MAGIC = 0x1BADB002; // 'magic number' lets bootloader find the header const CHECKSUM = -(MAGIC + FLAGS); // checksum of above, to prove we are multiboot const MultiBoot = extern struct { magic: c_long, flags: c_long, checksum: c_long, // For memory info header_addr: c_long = 0x00000000, load_addr: c_long = 0x00000000, load_end_addr: c_long = 0x00000000, bss_end_addr: c_long = 0x00000000, entry_addr: c_long = 0x00000000, // For video mode mode_type: c_long = 0x00000001, // 0 for linear graphics, 1 for ega width: c_long, height: c_long, depth: c_long, }; // Declare a multiboot header that marks the program as a kernel. var multiboot align(4) = MultiBoot{ .magic = MAGIC, .flags = FLAGS, .checksum = CHECKSUM, .width = 720, .height = 480, .depth = 32, }; // This allocates room for a small stack by creating a symbol at the bottom of it, // then allocating 16384 bytes for it, and finally creating a symbol at the top. var stack_bytes: [16 * 1024]u8 align(16) linksection(".bss") = undefined; // The linker script specifies _start as the entry point to the kernel and the // bootloader will jump to this position once the kernel has been loaded. It // doesn't make sense to return from this function as the bootloader is gone. fn start() callconv(.Naked) void { @call(.{ .stack = stack_bytes[0..] }, kmain, .{}); } // Create a new panic function so that we can see what has gone wrong. This // defers to kernel.panic. // pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { // @setCold(true); // tty.reset(); // tty.write("KERNEL PANIC: "); // tty.write(msg); // while (true) {} // } pub fn main() anyerror!void { SerialPort.init(SerialPort.COM1, 9600, .none, .eight); Terminal.clear(); PIC.init(); idt.init(); // gdt.init(); // Keyboard.init(); Terminal.print("All your {} are belong to {}!\r\n", .{ "base", "us" }); idt.fireInterrupt(0x40); unreachable; } pub fn kmain() callconv(.C) noreturn { main() catch |err| { Terminal.print("Error: {}", .{err}); }; while (true) { asm volatile ("hlt"); } }
src/kernel/arch/x86/boot/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day14.txt"); const edata = \\NNCB \\ \\CH -> B \\HH -> N \\CB -> H \\NH -> C \\HB -> C \\HC -> B \\HN -> C \\NN -> C \\BH -> H \\NC -> B \\NB -> B \\BN -> B \\BB -> N \\BC -> B \\CC -> N \\CN -> C ; const Rule = [3]u8; const Input = struct { list: []u8, rules: []Rule, }; pub fn main() !void { const input: Input = blk: { var list = List(u8).init(gpa); var lines = tokenize(u8, data, "\r\n"); const fst = lines.next().?; for (fst) |c| { try list.append(c); } var rules = List(Rule).init(gpa); while (lines.next()) |line| { var cols = tokenize(u8, line, " ->"); const pair = cols.next().?; const insert = cols.next().?; try rules.append(.{ pair[0], pair[1], insert[0] }); } break :blk .{.list = list.toOwnedSlice(), .rules = rules.toOwnedSlice()}; }; //print("{s}:\n{s}\n\n", .{ input.list, input.rules }); { // part 1 // copy input into mutable array var list = List(u8).init(gpa); for (input.list) |c| { try list.append(c); } const rules = input.rules; var step: usize = 1; while (step <= 10) : (step += 1) { const Insertion = struct { index: usize, // character will be inserted before this index char: u8, }; // This list must be kept in decending order by index number var insertions = List(Insertion).init(gpa); defer insertions.deinit(); { var index: usize = list.items.len - 1; while (index > 0) : (index -= 1) { for (rules) |rule| { if (std.mem.eql(u8, rule[0..2], list.items[index - 1 .. index + 1])) { try insertions.append(.{ .index = index, .char = rule[2] }); } } } } var outlist = List(u8).init(gpa); defer outlist.deinit(); for (list.items) |c, index| { // if index is in insertion list, pop insertion off list and append it to outlist if (insertions.items.len != 0) { const insertion = insertions.items[insertions.items.len - 1]; if (insertion.index == index) { try outlist.append(insertion.char); _ = insertions.pop(); } } try outlist.append(c); } // copy outlist into list try list.resize(outlist.items.len); for (outlist.items) |c, index| { list.items[index] = c; } } // get counts of each letter var counts = std.AutoArrayHashMap(u8, usize).init(gpa); defer counts.deinit(); for (list.items) |c| { if (counts.get(c)) |count| { try counts.put(c, count + 1); } else { try counts.put(c, 1); } } var max_count: usize = 0; var min_count: usize = std.math.maxInt(usize); while (counts.popOrNull()) |entry| { max_count = max(max_count, entry.value); min_count = min(min_count, entry.value); } const answer = max_count - min_count; assert(answer == 2745); print("{}\n", .{answer}); } { // part 2 // This time, track the number of each pair // Each insertion simply removes one pair and creates two pairs // The count for each of these pairs needs to be tracked // To get the answer, the number of each character needs to be tracked const Pair = struct { a: u8, b: u8, }; var pair_counts = std.AutoArrayHashMap(Pair, usize).init(gpa); defer pair_counts.deinit(); var char_counts = std.AutoArrayHashMap(u8, usize).init(gpa); defer char_counts.deinit(); // get initial counts for (input.list) |c, i| { // pair count if (i+1 < input.list.len) { const pair: Pair = .{.a=input.list[i], .b=input.list[i+1]}; try pair_counts.put(pair, if (pair_counts.get(pair)) |count| count+1 else 1); } // char count try char_counts.put(c, if (char_counts.get(c)) |count| count+1 else 1); } { var step: usize = 1; while (step <= 40) : (step += 1) { var pair_deletions = List(Pair).init(gpa); defer pair_deletions.deinit(); var pair_additions = std.AutoArrayHashMap(Pair, usize).init(gpa); defer pair_additions.deinit(); for (input.rules) |rule| { const pair0: Pair = .{.a=rule[0], .b=rule[1]}; const pair1: Pair = .{.a=rule[0], .b=rule[2]}; const pair2: Pair = .{.a=rule[2], .b=rule[1]}; const count0 = if (pair_counts.get(pair0)) |n| n else 0; const count1 = if (pair_additions.get(pair1)) |n| n else 0; const count2 = if (pair_additions.get(pair2)) |n| n else 0; try pair_deletions.append(pair0); try pair_additions.put(pair1, count1+count0); try pair_additions.put(pair2, count2+count0); const char_count = if (char_counts.get(rule[2])) |n| n else 0; try char_counts.put(rule[2], char_count + count0); if (count0 != 0) { //print("{c}{c} -> {c}{c}, {c}{c} {d} times\n", .{pair0.a,pair0.b,pair1.a,pair1.b,pair2.a,pair2.b,count0}); } } for (pair_deletions.items) |pair_to_delete| { try pair_counts.put(pair_to_delete, 0); } { var iter = pair_additions.iterator(); while (iter.next()) |entry| { const pair = entry.key_ptr.*; const delta = entry.value_ptr.*; const count = if (pair_counts.get(pair)) |n| n else 0; try pair_counts.put(pair, count+delta); //print("add {d} to {c}{c}\n", .{delta,pair.a,pair.b}); } } if (false) { {var iter = pair_counts.iterator(); while (iter.next()) |entry| { const pair = entry.key_ptr.*; const count = entry.value_ptr.*; if (count != 0) print("{c}{c}: {d}\n", .{pair.a, pair.b, count}); }} {var iter = char_counts.iterator(); while (iter.next()) |entry| { const char = entry.key_ptr.*; const count = entry.value_ptr.*; if (count != 0) print("{c}: {d}\n", .{char, count}); }} print("\n",.{}); } }} var max_count: usize = 0; var min_count: usize = std.math.maxInt(usize); while (char_counts.popOrNull()) |entry| { max_count = max(max_count, entry.value); min_count = min(min_count, entry.value); } const answer = max_count - min_count; assert(answer == 3420801168962); print("{}\n", .{answer}); } } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day14.zig
//-------------------------------------------------------------------------------- // Section: Types (4) //-------------------------------------------------------------------------------- const IID_IHolographicCameraInterop_Value = Guid.initString("7cc1f9c5-6d02-41fa-9500-e1809eb48eec"); pub const IID_IHolographicCameraInterop = &IID_IHolographicCameraInterop_Value; pub const IHolographicCameraInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, CreateDirect3D12BackBufferResource: fn( self: *const IHolographicCameraInterop, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, ppCreatedTexture2DResource: ?*?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDirect3D12HardwareProtectedBackBufferResource: fn( self: *const IHolographicCameraInterop, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, pProtectedResourceSession: ?*ID3D12ProtectedResourceSession, ppCreatedTexture2DResource: ?*?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireDirect3D12BufferResource: fn( self: *const IHolographicCameraInterop, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireDirect3D12BufferResourceWithTimeout: fn( self: *const IHolographicCameraInterop, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, duration: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnacquireDirect3D12BufferResource: fn( self: *const IHolographicCameraInterop, pResourceToUnacquire: ?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraInterop_CreateDirect3D12BackBufferResource(self: *const T, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, ppCreatedTexture2DResource: ?*?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraInterop.VTable, self.vtable).CreateDirect3D12BackBufferResource(@ptrCast(*const IHolographicCameraInterop, self), pDevice, pTexture2DDesc, ppCreatedTexture2DResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraInterop_CreateDirect3D12HardwareProtectedBackBufferResource(self: *const T, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, pProtectedResourceSession: ?*ID3D12ProtectedResourceSession, ppCreatedTexture2DResource: ?*?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraInterop.VTable, self.vtable).CreateDirect3D12HardwareProtectedBackBufferResource(@ptrCast(*const IHolographicCameraInterop, self), pDevice, pTexture2DDesc, pProtectedResourceSession, ppCreatedTexture2DResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraInterop_AcquireDirect3D12BufferResource(self: *const T, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraInterop.VTable, self.vtable).AcquireDirect3D12BufferResource(@ptrCast(*const IHolographicCameraInterop, self), pResourceToAcquire, pCommandQueue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraInterop_AcquireDirect3D12BufferResourceWithTimeout(self: *const T, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, duration: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraInterop.VTable, self.vtable).AcquireDirect3D12BufferResourceWithTimeout(@ptrCast(*const IHolographicCameraInterop, self), pResourceToAcquire, pCommandQueue, duration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraInterop_UnacquireDirect3D12BufferResource(self: *const T, pResourceToUnacquire: ?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraInterop.VTable, self.vtable).UnacquireDirect3D12BufferResource(@ptrCast(*const IHolographicCameraInterop, self), pResourceToUnacquire); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IHolographicCameraRenderingParametersInterop_Value = Guid.initString("f75b68d6-d1fd-4707-aafd-fa6f4c0e3bf4"); pub const IID_IHolographicCameraRenderingParametersInterop = &IID_IHolographicCameraRenderingParametersInterop_Value; pub const IHolographicCameraRenderingParametersInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, CommitDirect3D12Resource: fn( self: *const IHolographicCameraRenderingParametersInterop, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitDirect3D12ResourceWithDepthData: fn( self: *const IHolographicCameraRenderingParametersInterop, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64, pDepthResourceToCommit: ?*ID3D12Resource, pDepthResourceFence: ?*ID3D12Fence, depthResourceFenceSignalValue: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraRenderingParametersInterop_CommitDirect3D12Resource(self: *const T, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraRenderingParametersInterop.VTable, self.vtable).CommitDirect3D12Resource(@ptrCast(*const IHolographicCameraRenderingParametersInterop, self), pColorResourceToCommit, pColorResourceFence, colorResourceFenceSignalValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicCameraRenderingParametersInterop_CommitDirect3D12ResourceWithDepthData(self: *const T, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64, pDepthResourceToCommit: ?*ID3D12Resource, pDepthResourceFence: ?*ID3D12Fence, depthResourceFenceSignalValue: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicCameraRenderingParametersInterop.VTable, self.vtable).CommitDirect3D12ResourceWithDepthData(@ptrCast(*const IHolographicCameraRenderingParametersInterop, self), pColorResourceToCommit, pColorResourceFence, colorResourceFenceSignalValue, pDepthResourceToCommit, pDepthResourceFence, depthResourceFenceSignalValue); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IHolographicQuadLayerInterop_Value = Guid.initString("cfa688f0-639e-4a47-83d7-6b7f5ebf7fed"); pub const IID_IHolographicQuadLayerInterop = &IID_IHolographicQuadLayerInterop_Value; pub const IHolographicQuadLayerInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, CreateDirect3D12ContentBufferResource: fn( self: *const IHolographicQuadLayerInterop, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, ppTexture2DResource: ?*?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDirect3D12HardwareProtectedContentBufferResource: fn( self: *const IHolographicQuadLayerInterop, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, pProtectedResourceSession: ?*ID3D12ProtectedResourceSession, ppCreatedTexture2DResource: ?*?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireDirect3D12BufferResource: fn( self: *const IHolographicQuadLayerInterop, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireDirect3D12BufferResourceWithTimeout: fn( self: *const IHolographicQuadLayerInterop, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, duration: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnacquireDirect3D12BufferResource: fn( self: *const IHolographicQuadLayerInterop, pResourceToUnacquire: ?*ID3D12Resource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerInterop_CreateDirect3D12ContentBufferResource(self: *const T, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, ppTexture2DResource: ?*?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerInterop.VTable, self.vtable).CreateDirect3D12ContentBufferResource(@ptrCast(*const IHolographicQuadLayerInterop, self), pDevice, pTexture2DDesc, ppTexture2DResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerInterop_CreateDirect3D12HardwareProtectedContentBufferResource(self: *const T, pDevice: ?*ID3D12Device, pTexture2DDesc: ?*D3D12_RESOURCE_DESC, pProtectedResourceSession: ?*ID3D12ProtectedResourceSession, ppCreatedTexture2DResource: ?*?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerInterop.VTable, self.vtable).CreateDirect3D12HardwareProtectedContentBufferResource(@ptrCast(*const IHolographicQuadLayerInterop, self), pDevice, pTexture2DDesc, pProtectedResourceSession, ppCreatedTexture2DResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerInterop_AcquireDirect3D12BufferResource(self: *const T, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerInterop.VTable, self.vtable).AcquireDirect3D12BufferResource(@ptrCast(*const IHolographicQuadLayerInterop, self), pResourceToAcquire, pCommandQueue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerInterop_AcquireDirect3D12BufferResourceWithTimeout(self: *const T, pResourceToAcquire: ?*ID3D12Resource, pCommandQueue: ?*ID3D12CommandQueue, duration: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerInterop.VTable, self.vtable).AcquireDirect3D12BufferResourceWithTimeout(@ptrCast(*const IHolographicQuadLayerInterop, self), pResourceToAcquire, pCommandQueue, duration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerInterop_UnacquireDirect3D12BufferResource(self: *const T, pResourceToUnacquire: ?*ID3D12Resource) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerInterop.VTable, self.vtable).UnacquireDirect3D12BufferResource(@ptrCast(*const IHolographicQuadLayerInterop, self), pResourceToUnacquire); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IHolographicQuadLayerUpdateParametersInterop_Value = Guid.initString("e5f549cd-c909-444f-8809-7cc18a9c8920"); pub const IID_IHolographicQuadLayerUpdateParametersInterop = &IID_IHolographicQuadLayerUpdateParametersInterop_Value; pub const IHolographicQuadLayerUpdateParametersInterop = extern struct { pub const VTable = extern struct { base: IInspectable.VTable, CommitDirect3D12Resource: fn( self: *const IHolographicQuadLayerUpdateParametersInterop, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IInspectable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHolographicQuadLayerUpdateParametersInterop_CommitDirect3D12Resource(self: *const T, pColorResourceToCommit: ?*ID3D12Resource, pColorResourceFence: ?*ID3D12Fence, colorResourceFenceSignalValue: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IHolographicQuadLayerUpdateParametersInterop.VTable, self.vtable).CommitDirect3D12Resource(@ptrCast(*const IHolographicQuadLayerUpdateParametersInterop, self), pColorResourceToCommit, pColorResourceFence, colorResourceFenceSignalValue); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (9) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const D3D12_RESOURCE_DESC = @import("../../graphics/direct3d12.zig").D3D12_RESOURCE_DESC; const HRESULT = @import("../../foundation.zig").HRESULT; const ID3D12CommandQueue = @import("../../graphics/direct3d12.zig").ID3D12CommandQueue; const ID3D12Device = @import("../../graphics/direct3d12.zig").ID3D12Device; const ID3D12Fence = @import("../../graphics/direct3d12.zig").ID3D12Fence; const ID3D12ProtectedResourceSession = @import("../../graphics/direct3d12.zig").ID3D12ProtectedResourceSession; const ID3D12Resource = @import("../../graphics/direct3d12.zig").ID3D12Resource; const IInspectable = @import("../../system/win_rt.zig").IInspectable; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/win_rt/holographic.zig
const std = @import("std"); const COMMON_MAGIC = .{ 0xc7b1dd30df4c8b88, 0x0a82e883a194f07b }; pub const Uuid = struct { a: u32, b: u16, c: u16, d: [8]u8, }; pub const File = struct { revision: u64, base: u64, length: u64, path: []const u8, cmdline: []const u8, partiton_index: u64, _unused: u32, tftp_ip: u32, tftp_port: u32, mbr_disk_id: u32, gpt_disk_uuid: Uuid, gpt_part_uuid: Uuid, part_uuid: Uuid, }; pub const Identifiers = enum([4]u64) { BootloaderInfo = .{ COMMON_MAGIC, 0xf55038d8e2a1202f, 0x279426fcf5f59740 }, Hhdm = .{ COMMON_MAGIC, 0x48dcf1cb8ad2b852, 0x63984e959a98244b }, Framebuffer = .{ COMMON_MAGIC, 0xcbfe81d7dd2d1977, 0x063150319ebc9b71 }, Terminal = .{ COMMON_MAGIC, 0x0785a0aea5d0750f, 0x1c1936fee0d6cf6e }, FiveLevelPaging = .{ COMMON_MAGIC, 0x94469551da9b3192, 0xebe5e86db7382888 }, Smp = .{ COMMON_MAGIC, 0x95a67b819a1b857e, 0xa0b61b723b6a73e0 }, MemoryMap = .{ COMMON_MAGIC, 0x67cf3d9d378a806f, 0xe304acdfc50c3c62 }, EntryPoint = .{ COMMON_MAGIC, 0x13d86c035a1cd3e1, 0x2b0caa89d8f3026a }, KernelFile = .{ COMMON_MAGIC, 0xad97e90e83f1ed67, 0x31eb5d1c5ff23b69 }, Module = .{ COMMON_MAGIC, 0x3e7e279702be32af, 0xca1c4f3bd1280cee }, Rdsp = .{ COMMON_MAGIC, 0xc5e77b6b397e7b43, 0x27637845accdcf3c }, Smbios = .{ COMMON_MAGIC, 0x9e9046f11e095391, 0xaa4a520fefbde5ee }, EfiSystemTable = .{ COMMON_MAGIC, 0x5ceba5163eaaf6d6, 0x0a6981610cf65fcc }, BootTime = .{ COMMON_MAGIC, 0x502746e184c088aa, 0xfbc5ec83e6327893 }, KernelAddress = .{ COMMON_MAGIC, 0x71ba76863cc55f63, 0xb2644a48c516a487 }, }; pub const BootloaderInfo = struct { pub const Request = struct { id: [4]u64 = Identifiers.BootloaderInfo, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, name: []const u8, version: []const u8, }; }; pub const Hhdm = struct { pub const Request = struct { id: [4]u64 = Identifiers.Hhdm, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, offset: u64, }; }; pub const Framebuffer = struct { pub const Request = struct { id: [4]u64 = Identifiers.Framebuffer, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, display_count: u64, displays: [*]Display, }; pub const Display = struct { address: u64, width: u16, height: u16, pitch: u16, bpp: u16, memory_model: u8, red_mask_size: u8, red_mask_shift: u8, green_mask_size: u8, green_mask_shift: u8, blue_mask_size: u8, blue_mask_shift: u8, _unused: u8, edid_size: u64, edid: u64, }; }; pub const Terminal = struct { pub const Request = struct { id: [4]u64 = Identifiers.Terminal, revision: u64, response: Response = null, callback: fn (u64, u64, u64, u64) void = null, }; pub const Response = struct { revision: u64, columns: u32, rows: u32, write: fn (ptr: [:0]const u8, length: u64) callconv(.C) void, }; }; pub const FiveLevelPaging = struct { pub const Request = struct { id: [4]u64 = Identifiers.FiveLevelPaging, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, }; }; pub const Smp = struct { pub const Request = struct { id: [4]u64 = Identifiers.Smp, revision: u64, response: Response = null, flags: u64 = 0, }; pub const Response = struct { revision: u64, flags: u32, bsp_lapic_id: u32, cpu_count: u64, cpus: [*]Info, }; pub const Info = struct { processor_id: u32, lapic_id: u32, reserved_id: u64, goto_address: fn (*Info) void, extra_argument: u64, }; }; pub const MemoryMap = struct { pub const Request = struct { id: [4]u64 = Identifiers.MemoryMap, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, entry_count: u64, entries: [*]Entry, }; pub const Entry = struct { base: u64, length: u64, type: Types, }; pub const Types = enum { Usable, Reserved, AcpiReclaimable, AcpiNvs, BadMemory, BootloaderReclaimable, KernelAndModules, Framebuffer, }; }; pub const EntryPoint = struct { pub const Request = struct { id: [4]u64 = Identifiers.EntryPoint, revision: u64, response: Response = null, entry_point: fn () void = null, }; pub const Response = struct { revision: u64, }; }; pub const KernelFile = struct { pub const Request = struct { id: [4]u64 = Identifiers.KernelFile, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, kernel_file: *File, }; }; pub const Module = struct { pub const Request = struct { id: [4]u64 = Identifiers.Module, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, module_count: u64, modules: [*]File, }; }; pub const Rdsp = struct { pub const Request = struct { id: [4]u64 = Identifiers.Rdsp, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, address: u64, }; }; pub const Smbios = struct { pub const Request = struct { id: [4]u64 = Identifiers.Smbios, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, entry_32: u64, entry_64: u64, }; }; pub const EfiSystemTable = struct { pub const Request = struct { id: [4]u64 = Identifiers.EfiSystemTable, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, system_table: std.os.uefi.SystemTable, }; }; pub const BootTime = struct { pub const Request = struct { id: [4]u64 = Identifiers.BootTime, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, boot_time: i64, }; }; pub const KernelAddress = struct { pub const Request = struct { id: [4]u64 = Identifiers.KernelAddress, revision: u64, response: Response = null, }; pub const Response = struct { revision: u64, physical_base: u64, virtual_base: u64, }; };
src/main.zig
const c = @import("../c_global.zig").c_imp; const std = @import("std"); // dross-zig const Texture = @import("texture.zig").Texture; const Vector2 = @import("../core/vector2.zig").Vector2; // ----------------------------------------- // - TextureRegion - // ----------------------------------------- /// A sub-portion of a texture to allow for the use of /// texture atlass/spritesheets. pub const TextureRegion = struct { internal_texture: ?*Texture = undefined, texture_coordinates: [4]Vector2 = undefined, current_coordinates: Vector2 = undefined, region_size: Vector2 = undefined, number_of_regions: Vector2 = undefined, const Self = @This(); /// Allocates and builds a new TextureRegion instance. /// Comments: The caller will own the TextureRegion, but /// the texture passed is owned by the ResourceHandler. pub fn new( allocator: *std.mem.Allocator, atlas: *Texture, // The Texture Atlas to put a region from. coordinates: Vector2, // The region coordinates Ex: (1, 2) would be equal to (8, 16) if the region_size was 8x8. region_size: Vector2, // The size of the cell/region being sampled from. Ex: 16x16 region size on an atlas for a 16x16 sprite. number_of_regions: Vector2, // How many regions does the sprite occupy? Ex: 16x16 region size would need a number of regions(1, 2) for a 16x32 sprite. ) !*Self { var self = try allocator.create(TextureRegion); self.internal_texture = atlas; self.current_coordinates = coordinates; self.region_size = region_size; self.number_of_regions = number_of_regions; self.calculateTextureCoordinates(); return self; } /// Cleans up and de-allocates the TextureRegion /// NOTE(devon): The referenced texture is owned by the /// ResourceHandler, so it will be freed by that system. pub fn free(allocator: *std.mem.Allocator, self: *Self) void { allocator.destroy(self); } /// Calculate the texture coordinates of the TextureRegion pub fn calculateTextureCoordinates(self: *Self) void { const region_w = self.region_size.x(); const region_h = self.region_size.y(); const coordinate_x = self.current_coordinates.x(); const coordinate_y = self.current_coordinates.y(); const texture_size = self.internal_texture.?.size(); const texture_w = texture_size.?.x(); const texture_h = texture_size.?.y(); const min_coords = Vector2.new( (coordinate_x * region_w) / texture_w, (coordinate_y * region_h) / texture_h, ); const max_coords = Vector2.new( ((coordinate_x + self.number_of_regions.x()) * region_w) / texture_w, ((coordinate_y + self.number_of_regions.y()) * region_h) / texture_h, ); const min_x = min_coords.x(); const min_y = min_coords.y(); const max_x = max_coords.x(); const max_y = max_coords.y(); self.texture_coordinates = [4]Vector2{ Vector2.new(min_x, min_y), Vector2.new(max_x, min_y), Vector2.new(max_x, max_y), Vector2.new(min_x, max_y), }; } /// Sets the TextureRegion's atlas coordinates. /// If `recalculate` is true, then it'll automatically /// recalculate the texture coordinates based on /// the atlas coordinates. pub fn setAtlasCoordinates(self: *Self, new_coordinates: Vector2, recalculate: bool) void { // Check the bounds if (new_coordinates.x() < 0.0 or new_coordinates.y() < 0.0) return; const texture_size = self.internal_texture.?.size(); if (new_coordinates.x() * self.region_size.x() >= texture_size.?.x() or new_coordinates.y() * self.region_size.y() >= texture_size.?.y()) return; self.current_coordinates = new_coordinates; if (recalculate) self.calculateTextureCoordinates(); } /// Returns the assigned Texture Atlas pub fn texture(self: *Self) ?*Texture { return self.internal_texture; } /// Returns the assigned Texture Coordinates pub fn textureCoordinates(self: *Self) *[4]Vector2 { return &self.texture_coordinates; } /// Returns the current Atlas Coordinates pub fn atlasCoordinates(self: *Self) Vector2 { return self.current_coordinates; } };
src/renderer/texture_region.zig
const std = @import("std"); const assert = std.debug.assert; const expect = std.testing.expect; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const fixedBufferStream = std.io.fixedBufferStream; const Pixel = u8; const Layer = struct { pixels: []Pixel, const Self = @This(); pub fn fromStream(alloc: *Allocator, stream: anytype, w: usize, h: usize) !Self { var pixels = try alloc.alloc(Pixel, w * h); for (pixels) |*p| { var buf: [1]u8 = undefined; if ((try stream.readAll(&buf)) == 0) return error.EndOfStream; p.* = try std.fmt.parseInt(u8, &buf, 10); } return Self{ .pixels = pixels, }; } pub fn countDigit(self: Self, digit: u8) usize { var result: usize = 0; for (self.pixels) |p| { if (p == digit) result += 1; } return result; } }; test "read layer" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var reader = fixedBufferStream("001123").reader(); const lay = try Layer.fromStream(allocator, reader, 3, 2); expect(lay.countDigit(1) == 2); expect(lay.countDigit(0) == 2); } const Image = struct { layers: []Layer, const Self = @This(); pub fn fromStream(alloc: *Allocator, stream: anytype, w: usize, h: usize) !Self { var layers = ArrayList(Layer).init(alloc); while (Layer.fromStream(alloc, stream, w, h)) |l| { try layers.append(l); } else |e| switch (e) { error.EndOfStream => {}, error.InvalidCharacter => {}, else => return e, } return Self{ .layers = layers.items, }; } }; test "read image" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var reader = fixedBufferStream("123456789012").reader(); const img = try Image.fromStream(allocator, reader, 3, 2); expect(img.layers.len == 2); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); const input_file = try std.fs.cwd().openFile("input08.txt", .{}); var input_stream = input_file.reader(); // read image const img = try Image.fromStream(allocator, input_stream, 25, 6); // find layer with fewest 0 digits var res: ?Layer = null; for (img.layers) |l| { if (res) |min_layer| { if (l.countDigit(0) < min_layer.countDigit(0)) { res = l; } } else { res = l; } } // calculate result const result = res.?.countDigit(1) * res.?.countDigit(2); std.debug.warn("result: {}\n", .{result}); }
zig/08.zig
const std = @import("std"); const expect = std.testing.expect; const expectError = std.testing.expectError; const expectEqual = std.testing.expectEqual; test "switch all prongs unreachable" { try testAllProngsUnreachable(); comptime try testAllProngsUnreachable(); } fn testAllProngsUnreachable() !void { try expect(switchWithUnreachable(1) == 2); try expect(switchWithUnreachable(2) == 10); } fn switchWithUnreachable(x: i32) i32 { while (true) { switch (x) { 1 => return 2, 2 => break, else => continue, } } return 10; } fn return_a_number() anyerror!i32 { return 1; } test "capture value of switch with all unreachable prongs" { const x = return_a_number() catch |err| switch (err) { else => unreachable, }; try expect(x == 1); } test "anon enum literal used in switch on union enum" { const Foo = union(enum) { a: i32, }; var foo = Foo{ .a = 1234 }; switch (foo) { .a => |x| { try expect(x == 1234); }, } } test "else prong of switch on error set excludes other cases" { const S = struct { fn doTheTest() !void { try expectError(error.C, bar()); } const E = error{ A, B, } || E2; const E2 = error{ C, D, }; fn foo() E!void { return error.C; } fn bar() E2!void { foo() catch |err| switch (err) { error.A, error.B => {}, else => |e| return e, }; } }; try S.doTheTest(); comptime try S.doTheTest(); } test "switch prongs with error set cases make a new error set type for capture value" { const S = struct { fn doTheTest() !void { try expectError(error.B, bar()); } const E = E1 || E2; const E1 = error{ A, B, }; const E2 = error{ C, D, }; fn foo() E!void { return error.B; } fn bar() E1!void { foo() catch |err| switch (err) { error.A, error.B => |e| return e, else => {}, }; } }; try S.doTheTest(); comptime try S.doTheTest(); } test "return result loc and then switch with range implicit casted to error union" { const S = struct { fn doTheTest() !void { try expect((func(0xb) catch unreachable) == 0xb); } fn func(d: u8) anyerror!u8 { return switch (d) { 0xa...0xf => d, else => unreachable, }; } }; try S.doTheTest(); comptime try S.doTheTest(); } test "switch with null and T peer types and inferred result location type" { const S = struct { fn doTheTest(c: u8) !void { if (switch (c) { 0 => true, else => null, }) |v| { _ = v; @panic("fail"); } } }; try S.doTheTest(1); comptime try S.doTheTest(1); } test "switch prongs with cases with identical payload types" { const Union = union(enum) { A: usize, B: isize, C: usize, }; const S = struct { fn doTheTest() !void { try doTheSwitch1(Union{ .A = 8 }); try doTheSwitch2(Union{ .B = -8 }); } fn doTheSwitch1(u: Union) !void { switch (u) { .A, .C => |e| { try expect(@TypeOf(e) == usize); try expect(e == 8); }, .B => |e| { _ = e; @panic("fail"); }, } } fn doTheSwitch2(u: Union) !void { switch (u) { .A, .C => |e| { _ = e; @panic("fail"); }, .B => |e| { try expect(@TypeOf(e) == isize); try expect(e == -8); }, } } }; try S.doTheTest(); comptime try S.doTheTest(); } test "switch on pointer type" { const S = struct { const X = struct { field: u32, }; const P1 = @intToPtr(*X, 0x400); const P2 = @intToPtr(*X, 0x800); const P3 = @intToPtr(*X, 0xC00); fn doTheTest(arg: *X) i32 { switch (arg) { P1 => return 1, P2 => return 2, else => return 3, } } }; try expect(1 == S.doTheTest(S.P1)); try expect(2 == S.doTheTest(S.P2)); try expect(3 == S.doTheTest(S.P3)); comptime try expect(1 == S.doTheTest(S.P1)); comptime try expect(2 == S.doTheTest(S.P2)); comptime try expect(3 == S.doTheTest(S.P3)); } test "switch on error set with single else" { const S = struct { fn doTheTest() !void { var some: error{Foo} = error.Foo; try expect(switch (some) { else => |a| blk: { a catch {}; break :blk true; }, }); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "switch capture copies its payload" { const S = struct { fn doTheTest() !void { var tmp: union(enum) { A: u8, B: u32, } = .{ .A = 42 }; switch (tmp) { .A => |value| { // Modify the original union tmp = .{ .B = 0x10101010 }; try expectEqual(@as(u8, 42), value); }, else => unreachable, } } }; try S.doTheTest(); comptime try S.doTheTest(); }
test/behavior/switch_stage1.zig
const std = @import("std"); pub const max_write_bytes: u16 = 1024 * 16; const CommandIntType = u8; pub const Command = enum(CommandIntType) { stat = 0, opendir, releasedir, readdir, access, open, close, read, write, create, unlink, truncate, mkdir, rmdir, rename, _, }; pub fn send(writer: std.fs.File.Writer, value: anytype) !void { var offset: usize = 0; const size = @sizeOf(@TypeOf(value)); while (offset < size) { const val = @bitCast(i64, std.os.linux.write(writer.context.handle, @ptrCast([*]const u8, &value) + offset, size - offset)); if (val <= 0) { std.log.err("Write fail on fd {d}: {d}", .{ writer.context.handle, -val }); return error.WriteFail; } offset += @intCast(usize, val); } } pub fn sendfrom(writer: std.fs.File.Writer, buf: []const u8) !void { var offset: usize = 0; while (offset < buf.len) { const val = @bitCast(i64, std.os.linux.write(writer.context.handle, buf.ptr + offset, buf.len - offset)); if (val <= 0) { std.log.err("Write fail on fd {d}: {d}", .{ writer.context.handle, -val }); return error.WriteFail; } offset += @intCast(usize, val); } } pub fn recv(reader: std.fs.File.Reader, comptime T: type) !T { var value: T = undefined; //TODO: Figure out why this doesn't work?? //try recvinto(reader, std.mem.toBytes(&value)[0..@sizeOf(T)]); // We'll just use this for now... var offset: usize = 0; const size = @sizeOf(T); while (offset < size) { const val = @bitCast(i64, std.os.linux.read(reader.context.handle, @ptrCast([*]u8, &value) + offset, size - offset)); if (val <= 0) { std.log.err("Read fail on fd {d}: {d}", .{ reader.context.handle, -val }); return error.ReadFail; } offset += @intCast(usize, val); } return value; } pub fn recvinto(reader: std.fs.File.Reader, buf: []u8) !void { var offset: usize = 0; while (offset < buf.len) { const val = @bitCast(i64, std.os.linux.read(reader.context.handle, buf.ptr + offset, buf.len - offset)); if (val <= 0) { std.log.err("Read fail on fd {d}: {d}", .{ reader.context.handle, -val }); return error.ReadFail; } offset += @intCast(usize, val); } } pub const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; pub const ReadPath = struct { buffer: [MAX_PATH_BYTES]u8 = undefined, len: usize = 0, pub fn ptr(self: *const @This()) [*:0]const u8 { return @ptrCast([*:0]const u8, &self.buffer[0]); } pub fn slice(self: *@This()) []u8 { return self.buffer[0..self.len]; } }; pub fn recvpath(reader: std.fs.File.Reader) callconv(.Inline) !ReadPath { var result: ReadPath = .{}; result.len = try recv(reader, u16); if (result.len > MAX_PATH_BYTES) { return error.PathTooLong; } try recvinto(reader, result.slice()); return result; } pub fn sendpath(writer: std.fs.File.Writer, path: [*:0]const u8) !void { const span = std.mem.span(path); if (span.len > MAX_PATH_BYTES) { return error.PathTooLong; } try send(writer, @intCast(u16, span.len)); try sendfrom(writer, span); }
src/comms.zig
const uefi = @import("std").os.uefi; const fmt = @import("std").fmt; // https://github.com/ziglang/zig/blob/master/lib/std/os/uefi/protocols/simple_text_output_protocol.zig pub var out: *uefi.protocols.SimpleTextOutputProtocol = undefined; // EFI uses UCS-2 encoded null-terminated strings. UCS-2 encodes // code points in exactly 16 bit. Unlike UTF-16, it does not support all // Unicode code points. // We need to print each character in an [_]u8 individually because EFI // encodes strings as UCS-2. pub fn puts(msg: []const u8) void { for (msg) |c| { const c_ = [2]u16{ c, 0 }; // work around https://github.com/ziglang/zig/issues/4372 _ = out.outputString(@ptrCast(*const [1:0]u16, &c_)); } } // For use with formatting strings var printf_buf: [100]u8 = undefined; pub fn printf(comptime format: []const u8, args: anytype) void { buf_printf(printf_buf[0..], format, args); } pub fn buf_printf(buf: []u8, comptime format: []const u8, args: anytype) void { puts(fmt.bufPrint(buf, format, args) catch unreachable); } // implement memcpy as we're not including stdlib export fn memcpy(dest: [*:0]u8, source: [*:0]const u8, length: u64) [*:0]u8 { var index: u64 = 0; while (index < length) { dest[index] = source[index]; index += 1; } return dest; } export fn memset (dest: [*:0]u8, value: u8, length: u64) [*:0]u8 { var index: u64 = 0; while (index < length) { dest[index] = value; index += 1; } return dest; } // This is here for testing video buffer memory after calling exitBootServices // https://forum.osdev.org/viewtopic.php?f=1&t=26796 pub fn draw_triangle(arg_lfb_base_addr: u64, arg_center_x: u64, arg_center_y: u64, arg_width: u64, arg_color: u32) void { var lfb_base_addr = arg_lfb_base_addr; var center_x = arg_center_x; var center_y = arg_center_y; var width = arg_width; var color = arg_color; var at: [*c]u32 = @intToPtr([*c]u32, lfb_base_addr); var row: u64 = undefined; var col: u64 = undefined; at += (1024 *% (center_y -% width / 2) +% center_x -% width / 2); { row = 0; while (row < (width / 2)) : (row +%= 1) { { col = 0; while (col < (width -% (row *% 2))) : (col +%= 1) { (blk: { const ref = &at; const tmp = ref.*; ref.* += 1; break :blk tmp; }).?.* = color; } } at += 1024 -% col; { col = 0; while (col < (width -% (row *% 2))) : (col +%= 1) { (blk: { const ref = &at; const tmp = ref.*; ref.* += 1; break :blk tmp; }).?.* = color; } } at += (1024 -% col) +% 1; } } }
bootstrap/console.zig
const std = @import("std"); const Builder = std.build.Builder; const allocator = std.testing.allocator; const process = std.process; const path = std.fs.path; pub fn build(b: *Builder) !void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const notcurses_source_path = "deps/notcurses"; const notcurses = b.addStaticLibrary("notcurses", null); notcurses.setTarget(target); notcurses.setBuildMode(mode); notcurses.linkLibC(); notcurses.linkSystemLibrary("ncurses"); notcurses.linkSystemLibrary("readline"); notcurses.linkSystemLibrary("unistring"); notcurses.linkSystemLibrary("z"); notcurses.addIncludeDir(notcurses_source_path ++ "/include"); notcurses.addIncludeDir(notcurses_source_path ++ "/build/include"); notcurses.addIncludeDir(notcurses_source_path ++ "/src"); notcurses.addCSourceFiles(&[_][]const u8{ notcurses_source_path ++ "/src/lib/blit.c", notcurses_source_path ++ "/src/lib/debug.c", notcurses_source_path ++ "/src/lib/direct.c", notcurses_source_path ++ "/src/lib/fade.c", notcurses_source_path ++ "/src/lib/fd.c", notcurses_source_path ++ "/src/lib/fill.c", notcurses_source_path ++ "/src/lib/input.c", notcurses_source_path ++ "/src/lib/kitty.c", notcurses_source_path ++ "/src/lib/layout.c", notcurses_source_path ++ "/src/lib/linux.c", notcurses_source_path ++ "/src/lib/menu.c", notcurses_source_path ++ "/src/lib/metric.c", notcurses_source_path ++ "/src/lib/notcurses.c", notcurses_source_path ++ "/src/lib/plot.c", // notcurses_source_path ++ "/src/lib/png.c", notcurses_source_path ++ "/src/lib/progbar.c", notcurses_source_path ++ "/src/lib/reader.c", notcurses_source_path ++ "/src/lib/reel.c", notcurses_source_path ++ "/src/lib/render.c", notcurses_source_path ++ "/src/lib/selector.c", notcurses_source_path ++ "/src/lib/signal.c", notcurses_source_path ++ "/src/lib/sixel.c", notcurses_source_path ++ "/src/lib/sprite.c", notcurses_source_path ++ "/src/lib/stats.c", notcurses_source_path ++ "/src/lib/tabbed.c", notcurses_source_path ++ "/src/lib/termdesc.c", notcurses_source_path ++ "/src/lib/tree.c", notcurses_source_path ++ "/src/lib/visual.c", notcurses_source_path ++ "/src/compat/compat.c", }, &[_][]const u8{ "-DUSE_MULTIMEDIA=none", "-DUSE_QRCODEGEN=OFF", "-DPOLLRDHUP=0x2000", }); const jni = b.addSharedLibrary("notcurses-jni", null, b.version(0, 1, 0)); jni.setTarget(target); jni.setBuildMode(mode); jni.install(); jni.linkLibC(); jni.setOutputDir("target/native"); jni.addCSourceFiles(&[_][]const u8{ "src/swig/notcurses_wrap.c" }, &[_][]const u8{ "-Wno-deprecated", }); const JAVA_HOME = try process.getEnvVarOwned(allocator, "JAVA_HOME"); defer allocator.free(JAVA_HOME); const java_include = try path.join(allocator, &.{JAVA_HOME, "include"}); defer allocator.free(java_include); jni.addIncludeDir(java_include); const java_include_linux = try path.join(allocator, &.{JAVA_HOME, "include", "linux"}); defer allocator.free(java_include_linux); jni.addIncludeDir(java_include_linux); jni.addIncludeDir(notcurses_source_path ++ "/include"); jni.linkLibrary(notcurses); const jni_step = b.step("notcurses-jni", "Build the notcurses JNI lib"); jni_step.dependOn(&jni.step); }
build.zig
const std = @import("std"); const gameWorld = @import("GameWorld.zig"); const ent = @import("Entity.zig"); const componentData = @import("ComponentData.zig"); const GameWorld = gameWorld.GameWorld; const Entity = ent.Entity; const ArrayList = std.ArrayList; const mem = std.mem; const allocator = std.heap.page_allocator; const k_entityAllocChunk = 100; //scales with Entity sizeof const EntityError = error{ MaxEntities, Unknown, }; const EntityFastLookup = struct { m_idx: ?u32, m_eid: u32, }; // wrap entity optional because ArrayList hates optionals for some reason... const EntityEntry = struct { m_e: ?Entity, }; pub const EntityManager = struct { m_entityFastTable: ArrayList(EntityFastLookup) = ArrayList(EntityFastLookup).init(allocator), m_entities: ArrayList(EntityEntry) = ArrayList(EntityEntry).init(allocator), m_endOfEids: u32 = ent.GetEidStart(), m_firstFreeEntitySlot: u32 = 0, // potentially speed up KillEntity a bit on average... //TODO should eids be re-used? pub fn Initialize() EntityManager { return EntityManager{}; // will probably do additional initialization later on... } pub fn CreateEntity(self: *EntityManager) !*Entity { if (!ent.CheckEid(self.m_endOfEids)) return EntityError.MaxEntities; var newEntityIdx: u32 = 0; if (self.m_firstFreeEntitySlot == self.m_entities.len) { // append new const newEntry = Entity{ .m_eid = self.m_endOfEids }; try self.m_entities.append(EntityEntry{ .m_e = newEntry }); newEntityIdx = @intCast(u32, self.m_entities.len) - 1; self.m_firstFreeEntitySlot += 1; } else { // use existing freed slot self.m_entities.items[self.m_firstFreeEntitySlot].m_e = Entity{ .m_eid = self.m_endOfEids }; newEntityIdx = self.m_firstFreeEntitySlot; while (self.m_firstFreeEntitySlot < self.m_entities.len and self.m_entities.items[self.m_firstFreeEntitySlot].m_e != null) { self.m_firstFreeEntitySlot += 1; } } try self.m_entityFastTable.append(EntityFastLookup{ .m_eid = self.m_endOfEids, .m_idx = newEntityIdx, }); //TODO should go back and delete entity if the lookup table has an issue self.m_endOfEids += 1; return &(self.m_entities.items[newEntityIdx].m_e orelse return EntityError.Unknown); } // returns null if entity has been destoryed or doesn't exist pub fn GetEntity(self: *EntityManager, eid: u32) ?Entity { const lookup = self.FastLookup(eid) orelse return null; const entityIdx: u32 = lookup.m_idx orelse return null; return self.m_entities.items[entityIdx].m_e orelse return null; } pub fn KillEntity(self: *EntityManager, eid: u32) bool { const lookup = self.FastLookup(eid) orelse return false; const entityIdx: u32 = lookup.m_idx orelse return false; // free the entity data self.m_entities.items[entityIdx].m_e = null; if (entityIdx < self.m_firstFreeEntitySlot) { self.m_firstFreeEntitySlot = entityIdx; } // the eid is now forever null in the lookup table lookup.m_idx = null; return true; } fn FastLookup(self: *EntityManager, eid: u32) ?*EntityFastLookup { if (!ent.CheckEid(eid) or eid >= self.m_endOfEids) { return null; } return &self.m_entityFastTable.items[eid - ent.GetEidStart()]; } };
src/game/EntityManager.zig
pub const FADF_AUTO = @as(u32, 1); pub const FADF_STATIC = @as(u32, 2); pub const FADF_EMBEDDED = @as(u32, 4); pub const FADF_FIXEDSIZE = @as(u32, 16); pub const FADF_RECORD = @as(u32, 32); pub const FADF_HAVEIID = @as(u32, 64); pub const FADF_HAVEVARTYPE = @as(u32, 128); pub const FADF_BSTR = @as(u32, 256); pub const FADF_UNKNOWN = @as(u32, 512); pub const FADF_DISPATCH = @as(u32, 1024); pub const FADF_VARIANT = @as(u32, 2048); pub const FADF_RESERVED = @as(u32, 61448); pub const PARAMFLAG_NONE = @as(u32, 0); pub const PARAMFLAG_FIN = @as(u32, 1); pub const PARAMFLAG_FOUT = @as(u32, 2); pub const PARAMFLAG_FLCID = @as(u32, 4); pub const PARAMFLAG_FRETVAL = @as(u32, 8); pub const PARAMFLAG_FOPT = @as(u32, 16); pub const PARAMFLAG_FHASDEFAULT = @as(u32, 32); pub const PARAMFLAG_FHASCUSTDATA = @as(u32, 64); pub const IMPLTYPEFLAG_FDEFAULT = @as(u32, 1); pub const IMPLTYPEFLAG_FSOURCE = @as(u32, 2); pub const IMPLTYPEFLAG_FRESTRICTED = @as(u32, 4); pub const IMPLTYPEFLAG_FDEFAULTVTABLE = @as(u32, 8); pub const DISPID_UNKNOWN = @as(i32, -1); pub const DISPID_VALUE = @as(u32, 0); pub const DISPID_PROPERTYPUT = @as(i32, -3); pub const DISPID_NEWENUM = @as(i32, -4); pub const DISPID_EVALUATE = @as(i32, -5); pub const DISPID_CONSTRUCTOR = @as(i32, -6); pub const DISPID_DESTRUCTOR = @as(i32, -7); pub const DISPID_COLLECT = @as(i32, -8); pub const STDOLE_MAJORVERNUM = @as(u32, 1); pub const STDOLE_MINORVERNUM = @as(u32, 0); pub const STDOLE_LCID = @as(u32, 0); pub const STDOLE2_MAJORVERNUM = @as(u32, 2); pub const STDOLE2_MINORVERNUM = @as(u32, 0); pub const STDOLE2_LCID = @as(u32, 0); pub const VARIANT_NOVALUEPROP = @as(u32, 1); pub const VARIANT_ALPHABOOL = @as(u32, 2); pub const VARIANT_NOUSEROVERRIDE = @as(u32, 4); pub const VARIANT_CALENDAR_HIJRI = @as(u32, 8); pub const VARIANT_LOCALBOOL = @as(u32, 16); pub const VARIANT_CALENDAR_THAI = @as(u32, 32); pub const VARIANT_CALENDAR_GREGORIAN = @as(u32, 64); pub const VARIANT_USE_NLS = @as(u32, 128); pub const LOCALE_USE_NLS = @as(u32, 268435456); pub const VTDATEGRE_MAX = @as(u32, 2958465); pub const VTDATEGRE_MIN = @as(i32, -657434); pub const NUMPRS_LEADING_WHITE = @as(u32, 1); pub const NUMPRS_TRAILING_WHITE = @as(u32, 2); pub const NUMPRS_LEADING_PLUS = @as(u32, 4); pub const NUMPRS_TRAILING_PLUS = @as(u32, 8); pub const NUMPRS_LEADING_MINUS = @as(u32, 16); pub const NUMPRS_TRAILING_MINUS = @as(u32, 32); pub const NUMPRS_HEX_OCT = @as(u32, 64); pub const NUMPRS_PARENS = @as(u32, 128); pub const NUMPRS_DECIMAL = @as(u32, 256); pub const NUMPRS_THOUSANDS = @as(u32, 512); pub const NUMPRS_CURRENCY = @as(u32, 1024); pub const NUMPRS_EXPONENT = @as(u32, 2048); pub const NUMPRS_USE_ALL = @as(u32, 4096); pub const NUMPRS_STD = @as(u32, 8191); pub const NUMPRS_NEG = @as(u32, 65536); pub const NUMPRS_INEXACT = @as(u32, 131072); pub const VARCMP_LT = @as(u32, 0); pub const VARCMP_EQ = @as(u32, 1); pub const VARCMP_GT = @as(u32, 2); pub const VARCMP_NULL = @as(u32, 3); pub const ID_DEFAULTINST = @as(i32, -2); pub const DISPATCH_METHOD = @as(u32, 1); pub const DISPATCH_PROPERTYGET = @as(u32, 2); pub const DISPATCH_PROPERTYPUT = @as(u32, 4); pub const DISPATCH_PROPERTYPUTREF = @as(u32, 8); pub const LOAD_TLB_AS_32BIT = @as(u32, 32); pub const LOAD_TLB_AS_64BIT = @as(u32, 64); pub const ACTIVEOBJECT_STRONG = @as(u32, 0); pub const ACTIVEOBJECT_WEAK = @as(u32, 1); pub const SID_VariantConversion = Guid.initString("1f101481-bccd-11d0-9336-00a0c90dcaa9"); pub const SID_GetCaller = Guid.initString("4717cc40-bcb9-11d0-9336-00a0c90dcaa9"); pub const SID_ProvideRuntimeContext = Guid.initString("74a5040c-dd0c-48f0-ac85-194c3259180a"); pub const DISPATCH_CONSTRUCT = @as(u32, 16384); pub const DISPID_THIS = @as(i32, -613); //-------------------------------------------------------------------------------- // Section: Types (78) //-------------------------------------------------------------------------------- pub const LPEXCEPFINO_DEFERRED_FILLIN = fn( pExcepInfo: ?*EXCEPINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const SAFEARRAYBOUND = extern struct { cElements: u32, lLbound: i32, }; pub const _wireSAFEARR_BSTR = extern struct { Size: u32, aBstr: ?*?*FLAGGED_WORD_BLOB, }; pub const _wireSAFEARR_UNKNOWN = extern struct { Size: u32, apUnknown: ?*?*IUnknown, }; pub const _wireSAFEARR_DISPATCH = extern struct { Size: u32, apDispatch: ?*?*IDispatch, }; pub const _wireSAFEARR_VARIANT = extern struct { Size: u32, aVariant: ?*?*_wireVARIANT, }; pub const _wireSAFEARR_BRECORD = extern struct { Size: u32, aRecord: ?*?*_wireBRECORD, }; pub const _wireSAFEARR_HAVEIID = extern struct { Size: u32, apUnknown: ?*?*IUnknown, iid: Guid, }; pub const SF_TYPE = enum(i32) { ERROR = 10, I1 = 16, I2 = 2, I4 = 3, I8 = 20, BSTR = 8, UNKNOWN = 13, DISPATCH = 9, VARIANT = 12, RECORD = 36, HAVEIID = 32781, }; pub const SF_ERROR = SF_TYPE.ERROR; pub const SF_I1 = SF_TYPE.I1; pub const SF_I2 = SF_TYPE.I2; pub const SF_I4 = SF_TYPE.I4; pub const SF_I8 = SF_TYPE.I8; pub const SF_BSTR = SF_TYPE.BSTR; pub const SF_UNKNOWN = SF_TYPE.UNKNOWN; pub const SF_DISPATCH = SF_TYPE.DISPATCH; pub const SF_VARIANT = SF_TYPE.VARIANT; pub const SF_RECORD = SF_TYPE.RECORD; pub const SF_HAVEIID = SF_TYPE.HAVEIID; pub const _wireSAFEARRAY_UNION = extern struct { sfType: u32, u: extern struct { BstrStr: _wireSAFEARR_BSTR, UnknownStr: _wireSAFEARR_UNKNOWN, DispatchStr: _wireSAFEARR_DISPATCH, VariantStr: _wireSAFEARR_VARIANT, RecordStr: _wireSAFEARR_BRECORD, HaveIidStr: _wireSAFEARR_HAVEIID, ByteStr: BYTE_SIZEDARR, WordStr: SHORT_SIZEDARR, LongStr: LONG_SIZEDARR, HyperStr: HYPER_SIZEDARR, }, }; pub const _wireSAFEARRAY = extern struct { cDims: u16, fFeatures: u16, cbElements: u32, cLocks: u32, uArrayStructs: _wireSAFEARRAY_UNION, rgsabound: [1]SAFEARRAYBOUND, }; pub const SAFEARRAY = extern struct { cDims: u16, fFeatures: u16, cbElements: u32, cLocks: u32, pvData: ?*c_void, rgsabound: [1]SAFEARRAYBOUND, }; pub const VARIANT = extern struct { Anonymous: extern union { Anonymous: extern struct { vt: u16, wReserved1: u16, wReserved2: u16, wReserved3: u16, Anonymous: extern union { llVal: i64, lVal: i32, bVal: u8, iVal: i16, fltVal: f32, dblVal: f64, boolVal: i16, __OBSOLETE__VARIANT_BOOL: i16, scode: i32, cyVal: CY, date: f64, bstrVal: ?BSTR, punkVal: ?*IUnknown, pdispVal: ?*IDispatch, parray: ?*SAFEARRAY, pbVal: ?*u8, piVal: ?*i16, plVal: ?*i32, pllVal: ?*i64, pfltVal: ?*f32, pdblVal: ?*f64, pboolVal: ?*i16, __OBSOLETE__VARIANT_PBOOL: ?*i16, pscode: ?*i32, pcyVal: ?*CY, pdate: ?*f64, pbstrVal: ?*?BSTR, ppunkVal: ?*?*IUnknown, ppdispVal: ?*?*IDispatch, pparray: ?*?*SAFEARRAY, pvarVal: ?*VARIANT, byref: ?*c_void, cVal: CHAR, uiVal: u16, ulVal: u32, ullVal: u64, intVal: i32, uintVal: u32, pdecVal: ?*DECIMAL, pcVal: ?PSTR, puiVal: ?*u16, pulVal: ?*u32, pullVal: ?*u64, pintVal: ?*i32, puintVal: ?*u32, Anonymous: extern struct { pvRecord: ?*c_void, pRecInfo: ?*IRecordInfo, }, }, }, decVal: DECIMAL, }, }; pub const _wireBRECORD = extern struct { fFlags: u32, clSize: u32, pRecInfo: ?*IRecordInfo, pRecord: ?*u8, }; pub const _wireVARIANT = extern struct { clSize: u32, rpcReserved: u32, vt: u16, wReserved1: u16, wReserved2: u16, wReserved3: u16, Anonymous: extern union { llVal: i64, lVal: i32, bVal: u8, iVal: i16, fltVal: f32, dblVal: f64, boolVal: i16, scode: i32, cyVal: CY, date: f64, bstrVal: ?*FLAGGED_WORD_BLOB, punkVal: ?*IUnknown, pdispVal: ?*IDispatch, parray: ?*?*_wireSAFEARRAY, brecVal: ?*_wireBRECORD, pbVal: ?*u8, piVal: ?*i16, plVal: ?*i32, pllVal: ?*i64, pfltVal: ?*f32, pdblVal: ?*f64, pboolVal: ?*i16, pscode: ?*i32, pcyVal: ?*CY, pdate: ?*f64, pbstrVal: ?*?*FLAGGED_WORD_BLOB, ppunkVal: ?*?*IUnknown, ppdispVal: ?*?*IDispatch, pparray: ?*?*?*_wireSAFEARRAY, pvarVal: ?*?*_wireVARIANT, cVal: CHAR, uiVal: u16, ulVal: u32, ullVal: u64, intVal: i32, uintVal: u32, decVal: DECIMAL, pdecVal: ?*DECIMAL, pcVal: ?PSTR, puiVal: ?*u16, pulVal: ?*u32, pullVal: ?*u64, pintVal: ?*i32, puintVal: ?*u32, }, }; pub const TYPEKIND = enum(i32) { ENUM = 0, RECORD = 1, MODULE = 2, INTERFACE = 3, DISPATCH = 4, COCLASS = 5, ALIAS = 6, UNION = 7, MAX = 8, }; pub const TKIND_ENUM = TYPEKIND.ENUM; pub const TKIND_RECORD = TYPEKIND.RECORD; pub const TKIND_MODULE = TYPEKIND.MODULE; pub const TKIND_INTERFACE = TYPEKIND.INTERFACE; pub const TKIND_DISPATCH = TYPEKIND.DISPATCH; pub const TKIND_COCLASS = TYPEKIND.COCLASS; pub const TKIND_ALIAS = TYPEKIND.ALIAS; pub const TKIND_UNION = TYPEKIND.UNION; pub const TKIND_MAX = TYPEKIND.MAX; pub const TYPEDESC = extern struct { Anonymous: extern union { lptdesc: ?*TYPEDESC, lpadesc: ?*ARRAYDESC, hreftype: u32, }, vt: u16, }; pub const ARRAYDESC = extern struct { tdescElem: TYPEDESC, cDims: u16, rgbounds: [1]SAFEARRAYBOUND, }; pub const PARAMDESCEX = extern struct { cBytes: u32, varDefaultValue: VARIANT, }; pub const PARAMDESC = extern struct { pparamdescex: ?*PARAMDESCEX, wParamFlags: u16, }; pub const IDLDESC = extern struct { dwReserved: usize, wIDLFlags: u16, }; pub const ELEMDESC = extern struct { tdesc: TYPEDESC, Anonymous: extern union { idldesc: IDLDESC, paramdesc: PARAMDESC, }, }; pub const TYPEATTR = extern struct { guid: Guid, lcid: u32, dwReserved: u32, memidConstructor: i32, memidDestructor: i32, lpstrSchema: ?PWSTR, cbSizeInstance: u32, typekind: TYPEKIND, cFuncs: u16, cVars: u16, cImplTypes: u16, cbSizeVft: u16, cbAlignment: u16, wTypeFlags: u16, wMajorVerNum: u16, wMinorVerNum: u16, tdescAlias: TYPEDESC, idldescType: IDLDESC, }; pub const DISPPARAMS = extern struct { rgvarg: ?*VARIANT, rgdispidNamedArgs: ?*i32, cArgs: u32, cNamedArgs: u32, }; pub const EXCEPINFO = extern struct { wCode: u16, wReserved: u16, bstrSource: ?BSTR, bstrDescription: ?BSTR, bstrHelpFile: ?BSTR, dwHelpContext: u32, pvReserved: ?*c_void, pfnDeferredFillIn: ?LPEXCEPFINO_DEFERRED_FILLIN, scode: i32, }; pub const CALLCONV = enum(i32) { FASTCALL = 0, CDECL = 1, MSCPASCAL = 2, // PASCAL = 2, this enum value conflicts with MSCPASCAL MACPASCAL = 3, STDCALL = 4, FPFASTCALL = 5, SYSCALL = 6, MPWCDECL = 7, MPWPASCAL = 8, MAX = 9, }; pub const CC_FASTCALL = CALLCONV.FASTCALL; pub const CC_CDECL = CALLCONV.CDECL; pub const CC_MSCPASCAL = CALLCONV.MSCPASCAL; pub const CC_PASCAL = CALLCONV.MSCPASCAL; pub const CC_MACPASCAL = CALLCONV.MACPASCAL; pub const CC_STDCALL = CALLCONV.STDCALL; pub const CC_FPFASTCALL = CALLCONV.FPFASTCALL; pub const CC_SYSCALL = CALLCONV.SYSCALL; pub const CC_MPWCDECL = CALLCONV.MPWCDECL; pub const CC_MPWPASCAL = CALLCONV.MPWPASCAL; pub const CC_MAX = CALLCONV.MAX; pub const FUNCKIND = enum(i32) { VIRTUAL = 0, PUREVIRTUAL = 1, NONVIRTUAL = 2, STATIC = 3, DISPATCH = 4, }; pub const FUNC_VIRTUAL = FUNCKIND.VIRTUAL; pub const FUNC_PUREVIRTUAL = FUNCKIND.PUREVIRTUAL; pub const FUNC_NONVIRTUAL = FUNCKIND.NONVIRTUAL; pub const FUNC_STATIC = FUNCKIND.STATIC; pub const FUNC_DISPATCH = FUNCKIND.DISPATCH; pub const INVOKEKIND = enum(i32) { FUNC = 1, PROPERTYGET = 2, PROPERTYPUT = 4, PROPERTYPUTREF = 8, }; pub const INVOKE_FUNC = INVOKEKIND.FUNC; pub const INVOKE_PROPERTYGET = INVOKEKIND.PROPERTYGET; pub const INVOKE_PROPERTYPUT = INVOKEKIND.PROPERTYPUT; pub const INVOKE_PROPERTYPUTREF = INVOKEKIND.PROPERTYPUTREF; pub const FUNCDESC = extern struct { memid: i32, lprgscode: ?*i32, lprgelemdescParam: ?*ELEMDESC, funckind: FUNCKIND, invkind: INVOKEKIND, @"callconv": CALLCONV, cParams: i16, cParamsOpt: i16, oVft: i16, cScodes: i16, elemdescFunc: ELEMDESC, wFuncFlags: u16, }; pub const VARKIND = enum(i32) { PERINSTANCE = 0, STATIC = 1, CONST = 2, DISPATCH = 3, }; pub const VAR_PERINSTANCE = VARKIND.PERINSTANCE; pub const VAR_STATIC = VARKIND.STATIC; pub const VAR_CONST = VARKIND.CONST; pub const VAR_DISPATCH = VARKIND.DISPATCH; pub const VARDESC = extern struct { memid: i32, lpstrSchema: ?PWSTR, Anonymous: extern union { oInst: u32, lpvarValue: ?*VARIANT, }, elemdescVar: ELEMDESC, wVarFlags: u16, varkind: VARKIND, }; pub const TYPEFLAGS = enum(i32) { APPOBJECT = 1, CANCREATE = 2, LICENSED = 4, PREDECLID = 8, HIDDEN = 16, CONTROL = 32, DUAL = 64, NONEXTENSIBLE = 128, OLEAUTOMATION = 256, RESTRICTED = 512, AGGREGATABLE = 1024, REPLACEABLE = 2048, DISPATCHABLE = 4096, REVERSEBIND = 8192, PROXY = 16384, }; pub const TYPEFLAG_FAPPOBJECT = TYPEFLAGS.APPOBJECT; pub const TYPEFLAG_FCANCREATE = TYPEFLAGS.CANCREATE; pub const TYPEFLAG_FLICENSED = TYPEFLAGS.LICENSED; pub const TYPEFLAG_FPREDECLID = TYPEFLAGS.PREDECLID; pub const TYPEFLAG_FHIDDEN = TYPEFLAGS.HIDDEN; pub const TYPEFLAG_FCONTROL = TYPEFLAGS.CONTROL; pub const TYPEFLAG_FDUAL = TYPEFLAGS.DUAL; pub const TYPEFLAG_FNONEXTENSIBLE = TYPEFLAGS.NONEXTENSIBLE; pub const TYPEFLAG_FOLEAUTOMATION = TYPEFLAGS.OLEAUTOMATION; pub const TYPEFLAG_FRESTRICTED = TYPEFLAGS.RESTRICTED; pub const TYPEFLAG_FAGGREGATABLE = TYPEFLAGS.AGGREGATABLE; pub const TYPEFLAG_FREPLACEABLE = TYPEFLAGS.REPLACEABLE; pub const TYPEFLAG_FDISPATCHABLE = TYPEFLAGS.DISPATCHABLE; pub const TYPEFLAG_FREVERSEBIND = TYPEFLAGS.REVERSEBIND; pub const TYPEFLAG_FPROXY = TYPEFLAGS.PROXY; pub const FUNCFLAGS = enum(i32) { RESTRICTED = 1, SOURCE = 2, BINDABLE = 4, REQUESTEDIT = 8, DISPLAYBIND = 16, DEFAULTBIND = 32, HIDDEN = 64, USESGETLASTERROR = 128, DEFAULTCOLLELEM = 256, UIDEFAULT = 512, NONBROWSABLE = 1024, REPLACEABLE = 2048, IMMEDIATEBIND = 4096, }; pub const FUNCFLAG_FRESTRICTED = FUNCFLAGS.RESTRICTED; pub const FUNCFLAG_FSOURCE = FUNCFLAGS.SOURCE; pub const FUNCFLAG_FBINDABLE = FUNCFLAGS.BINDABLE; pub const FUNCFLAG_FREQUESTEDIT = FUNCFLAGS.REQUESTEDIT; pub const FUNCFLAG_FDISPLAYBIND = FUNCFLAGS.DISPLAYBIND; pub const FUNCFLAG_FDEFAULTBIND = FUNCFLAGS.DEFAULTBIND; pub const FUNCFLAG_FHIDDEN = FUNCFLAGS.HIDDEN; pub const FUNCFLAG_FUSESGETLASTERROR = FUNCFLAGS.USESGETLASTERROR; pub const FUNCFLAG_FDEFAULTCOLLELEM = FUNCFLAGS.DEFAULTCOLLELEM; pub const FUNCFLAG_FUIDEFAULT = FUNCFLAGS.UIDEFAULT; pub const FUNCFLAG_FNONBROWSABLE = FUNCFLAGS.NONBROWSABLE; pub const FUNCFLAG_FREPLACEABLE = FUNCFLAGS.REPLACEABLE; pub const FUNCFLAG_FIMMEDIATEBIND = FUNCFLAGS.IMMEDIATEBIND; pub const VARFLAGS = enum(i32) { READONLY = 1, SOURCE = 2, BINDABLE = 4, REQUESTEDIT = 8, DISPLAYBIND = 16, DEFAULTBIND = 32, HIDDEN = 64, RESTRICTED = 128, DEFAULTCOLLELEM = 256, UIDEFAULT = 512, NONBROWSABLE = 1024, REPLACEABLE = 2048, IMMEDIATEBIND = 4096, }; pub const VARFLAG_FREADONLY = VARFLAGS.READONLY; pub const VARFLAG_FSOURCE = VARFLAGS.SOURCE; pub const VARFLAG_FBINDABLE = VARFLAGS.BINDABLE; pub const VARFLAG_FREQUESTEDIT = VARFLAGS.REQUESTEDIT; pub const VARFLAG_FDISPLAYBIND = VARFLAGS.DISPLAYBIND; pub const VARFLAG_FDEFAULTBIND = VARFLAGS.DEFAULTBIND; pub const VARFLAG_FHIDDEN = VARFLAGS.HIDDEN; pub const VARFLAG_FRESTRICTED = VARFLAGS.RESTRICTED; pub const VARFLAG_FDEFAULTCOLLELEM = VARFLAGS.DEFAULTCOLLELEM; pub const VARFLAG_FUIDEFAULT = VARFLAGS.UIDEFAULT; pub const VARFLAG_FNONBROWSABLE = VARFLAGS.NONBROWSABLE; pub const VARFLAG_FREPLACEABLE = VARFLAGS.REPLACEABLE; pub const VARFLAG_FIMMEDIATEBIND = VARFLAGS.IMMEDIATEBIND; pub const CLEANLOCALSTORAGE = extern struct { pInterface: ?*IUnknown, pStorage: ?*c_void, flags: u32, }; pub const CUSTDATAITEM = extern struct { guid: Guid, varValue: VARIANT, }; pub const CUSTDATA = extern struct { cCustData: u32, prgCustData: ?*CUSTDATAITEM, }; const IID_ICreateTypeInfo_Value = @import("../zig.zig").Guid.initString("00020405-0000-0000-c000-000000000046"); pub const IID_ICreateTypeInfo = &IID_ICreateTypeInfo_Value; pub const ICreateTypeInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetGuid: fn( self: *const ICreateTypeInfo, guid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTypeFlags: fn( self: *const ICreateTypeInfo, uTypeFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDocString: fn( self: *const ICreateTypeInfo, pStrDoc: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpContext: fn( self: *const ICreateTypeInfo, dwHelpContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVersion: fn( self: *const ICreateTypeInfo, wMajorVerNum: u16, wMinorVerNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRefTypeInfo: fn( self: *const ICreateTypeInfo, pTInfo: ?*ITypeInfo, phRefType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddFuncDesc: fn( self: *const ICreateTypeInfo, index: u32, pFuncDesc: ?*FUNCDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddImplType: fn( self: *const ICreateTypeInfo, index: u32, hRefType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetImplTypeFlags: fn( self: *const ICreateTypeInfo, index: u32, implTypeFlags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAlignment: fn( self: *const ICreateTypeInfo, cbAlignment: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSchema: fn( self: *const ICreateTypeInfo, pStrSchema: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddVarDesc: fn( self: *const ICreateTypeInfo, index: u32, pVarDesc: ?*VARDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFuncAndParamNames: fn( self: *const ICreateTypeInfo, index: u32, rgszNames: [*]?PWSTR, cNames: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVarName: fn( self: *const ICreateTypeInfo, index: u32, szName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTypeDescAlias: fn( self: *const ICreateTypeInfo, pTDescAlias: ?*TYPEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DefineFuncAsDllEntry: fn( self: *const ICreateTypeInfo, index: u32, szDllName: ?PWSTR, szProcName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFuncDocString: fn( self: *const ICreateTypeInfo, index: u32, szDocString: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVarDocString: fn( self: *const ICreateTypeInfo, index: u32, szDocString: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFuncHelpContext: fn( self: *const ICreateTypeInfo, index: u32, dwHelpContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVarHelpContext: fn( self: *const ICreateTypeInfo, index: u32, dwHelpContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMops: fn( self: *const ICreateTypeInfo, index: u32, bstrMops: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTypeIdldesc: fn( self: *const ICreateTypeInfo, pIdlDesc: ?*IDLDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LayOut: fn( self: *const ICreateTypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetGuid(self: *const T, guid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetGuid(@ptrCast(*const ICreateTypeInfo, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetTypeFlags(self: *const T, uTypeFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetTypeFlags(@ptrCast(*const ICreateTypeInfo, self), uTypeFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetDocString(self: *const T, pStrDoc: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetDocString(@ptrCast(*const ICreateTypeInfo, self), pStrDoc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetHelpContext(self: *const T, dwHelpContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetHelpContext(@ptrCast(*const ICreateTypeInfo, self), dwHelpContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetVersion(self: *const T, wMajorVerNum: u16, wMinorVerNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetVersion(@ptrCast(*const ICreateTypeInfo, self), wMajorVerNum, wMinorVerNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_AddRefTypeInfo(self: *const T, pTInfo: ?*ITypeInfo, phRefType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).AddRefTypeInfo(@ptrCast(*const ICreateTypeInfo, self), pTInfo, phRefType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_AddFuncDesc(self: *const T, index: u32, pFuncDesc: ?*FUNCDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).AddFuncDesc(@ptrCast(*const ICreateTypeInfo, self), index, pFuncDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_AddImplType(self: *const T, index: u32, hRefType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).AddImplType(@ptrCast(*const ICreateTypeInfo, self), index, hRefType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetImplTypeFlags(self: *const T, index: u32, implTypeFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetImplTypeFlags(@ptrCast(*const ICreateTypeInfo, self), index, implTypeFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetAlignment(self: *const T, cbAlignment: u16) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetAlignment(@ptrCast(*const ICreateTypeInfo, self), cbAlignment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetSchema(self: *const T, pStrSchema: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetSchema(@ptrCast(*const ICreateTypeInfo, self), pStrSchema); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_AddVarDesc(self: *const T, index: u32, pVarDesc: ?*VARDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).AddVarDesc(@ptrCast(*const ICreateTypeInfo, self), index, pVarDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetFuncAndParamNames(self: *const T, index: u32, rgszNames: [*]?PWSTR, cNames: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetFuncAndParamNames(@ptrCast(*const ICreateTypeInfo, self), index, rgszNames, cNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetVarName(self: *const T, index: u32, szName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetVarName(@ptrCast(*const ICreateTypeInfo, self), index, szName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetTypeDescAlias(self: *const T, pTDescAlias: ?*TYPEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetTypeDescAlias(@ptrCast(*const ICreateTypeInfo, self), pTDescAlias); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_DefineFuncAsDllEntry(self: *const T, index: u32, szDllName: ?PWSTR, szProcName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).DefineFuncAsDllEntry(@ptrCast(*const ICreateTypeInfo, self), index, szDllName, szProcName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetFuncDocString(self: *const T, index: u32, szDocString: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetFuncDocString(@ptrCast(*const ICreateTypeInfo, self), index, szDocString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetVarDocString(self: *const T, index: u32, szDocString: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetVarDocString(@ptrCast(*const ICreateTypeInfo, self), index, szDocString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetFuncHelpContext(self: *const T, index: u32, dwHelpContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetFuncHelpContext(@ptrCast(*const ICreateTypeInfo, self), index, dwHelpContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetVarHelpContext(self: *const T, index: u32, dwHelpContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetVarHelpContext(@ptrCast(*const ICreateTypeInfo, self), index, dwHelpContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetMops(self: *const T, index: u32, bstrMops: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetMops(@ptrCast(*const ICreateTypeInfo, self), index, bstrMops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_SetTypeIdldesc(self: *const T, pIdlDesc: ?*IDLDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).SetTypeIdldesc(@ptrCast(*const ICreateTypeInfo, self), pIdlDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo_LayOut(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo.VTable, self.vtable).LayOut(@ptrCast(*const ICreateTypeInfo, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICreateTypeInfo2_Value = @import("../zig.zig").Guid.initString("0002040e-0000-0000-c000-000000000046"); pub const IID_ICreateTypeInfo2 = &IID_ICreateTypeInfo2_Value; pub const ICreateTypeInfo2 = extern struct { pub const VTable = extern struct { base: ICreateTypeInfo.VTable, DeleteFuncDesc: fn( self: *const ICreateTypeInfo2, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteFuncDescByMemId: fn( self: *const ICreateTypeInfo2, memid: i32, invKind: INVOKEKIND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteVarDesc: fn( self: *const ICreateTypeInfo2, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteVarDescByMemId: fn( self: *const ICreateTypeInfo2, memid: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteImplType: fn( self: *const ICreateTypeInfo2, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCustData: fn( self: *const ICreateTypeInfo2, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFuncCustData: fn( self: *const ICreateTypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetParamCustData: fn( self: *const ICreateTypeInfo2, indexFunc: u32, indexParam: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVarCustData: fn( self: *const ICreateTypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetImplTypeCustData: fn( self: *const ICreateTypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpStringContext: fn( self: *const ICreateTypeInfo2, dwHelpStringContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFuncHelpStringContext: fn( self: *const ICreateTypeInfo2, index: u32, dwHelpStringContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVarHelpStringContext: fn( self: *const ICreateTypeInfo2, index: u32, dwHelpStringContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Invalidate: fn( self: *const ICreateTypeInfo2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const ICreateTypeInfo2, szName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ICreateTypeInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_DeleteFuncDesc(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).DeleteFuncDesc(@ptrCast(*const ICreateTypeInfo2, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_DeleteFuncDescByMemId(self: *const T, memid: i32, invKind: INVOKEKIND) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).DeleteFuncDescByMemId(@ptrCast(*const ICreateTypeInfo2, self), memid, invKind); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_DeleteVarDesc(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).DeleteVarDesc(@ptrCast(*const ICreateTypeInfo2, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_DeleteVarDescByMemId(self: *const T, memid: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).DeleteVarDescByMemId(@ptrCast(*const ICreateTypeInfo2, self), memid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_DeleteImplType(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).DeleteImplType(@ptrCast(*const ICreateTypeInfo2, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetCustData(self: *const T, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetCustData(@ptrCast(*const ICreateTypeInfo2, self), guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetFuncCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetFuncCustData(@ptrCast(*const ICreateTypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetParamCustData(self: *const T, indexFunc: u32, indexParam: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetParamCustData(@ptrCast(*const ICreateTypeInfo2, self), indexFunc, indexParam, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetVarCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetVarCustData(@ptrCast(*const ICreateTypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetImplTypeCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetImplTypeCustData(@ptrCast(*const ICreateTypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetHelpStringContext(self: *const T, dwHelpStringContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetHelpStringContext(@ptrCast(*const ICreateTypeInfo2, self), dwHelpStringContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetFuncHelpStringContext(self: *const T, index: u32, dwHelpStringContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetFuncHelpStringContext(@ptrCast(*const ICreateTypeInfo2, self), index, dwHelpStringContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetVarHelpStringContext(self: *const T, index: u32, dwHelpStringContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetVarHelpStringContext(@ptrCast(*const ICreateTypeInfo2, self), index, dwHelpStringContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_Invalidate(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).Invalidate(@ptrCast(*const ICreateTypeInfo2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeInfo2_SetName(self: *const T, szName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeInfo2.VTable, self.vtable).SetName(@ptrCast(*const ICreateTypeInfo2, self), szName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICreateTypeLib_Value = @import("../zig.zig").Guid.initString("00020406-0000-0000-c000-000000000046"); pub const IID_ICreateTypeLib = &IID_ICreateTypeLib_Value; pub const ICreateTypeLib = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateTypeInfo: fn( self: *const ICreateTypeLib, szName: ?PWSTR, tkind: TYPEKIND, ppCTInfo: ?*?*ICreateTypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const ICreateTypeLib, szName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVersion: fn( self: *const ICreateTypeLib, wMajorVerNum: u16, wMinorVerNum: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGuid: fn( self: *const ICreateTypeLib, guid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDocString: fn( self: *const ICreateTypeLib, szDoc: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpFileName: fn( self: *const ICreateTypeLib, szHelpFileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpContext: fn( self: *const ICreateTypeLib, dwHelpContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLcid: fn( self: *const ICreateTypeLib, lcid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLibFlags: fn( self: *const ICreateTypeLib, uLibFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveAllChanges: fn( self: *const ICreateTypeLib, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_CreateTypeInfo(self: *const T, szName: ?PWSTR, tkind: TYPEKIND, ppCTInfo: ?*?*ICreateTypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).CreateTypeInfo(@ptrCast(*const ICreateTypeLib, self), szName, tkind, ppCTInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetName(self: *const T, szName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetName(@ptrCast(*const ICreateTypeLib, self), szName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetVersion(self: *const T, wMajorVerNum: u16, wMinorVerNum: u16) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetVersion(@ptrCast(*const ICreateTypeLib, self), wMajorVerNum, wMinorVerNum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetGuid(self: *const T, guid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetGuid(@ptrCast(*const ICreateTypeLib, self), guid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetDocString(self: *const T, szDoc: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetDocString(@ptrCast(*const ICreateTypeLib, self), szDoc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetHelpFileName(self: *const T, szHelpFileName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetHelpFileName(@ptrCast(*const ICreateTypeLib, self), szHelpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetHelpContext(self: *const T, dwHelpContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetHelpContext(@ptrCast(*const ICreateTypeLib, self), dwHelpContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetLcid(self: *const T, lcid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetLcid(@ptrCast(*const ICreateTypeLib, self), lcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SetLibFlags(self: *const T, uLibFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SetLibFlags(@ptrCast(*const ICreateTypeLib, self), uLibFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib_SaveAllChanges(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib.VTable, self.vtable).SaveAllChanges(@ptrCast(*const ICreateTypeLib, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICreateTypeLib2_Value = @import("../zig.zig").Guid.initString("0002040f-0000-0000-c000-000000000046"); pub const IID_ICreateTypeLib2 = &IID_ICreateTypeLib2_Value; pub const ICreateTypeLib2 = extern struct { pub const VTable = extern struct { base: ICreateTypeLib.VTable, DeleteTypeInfo: fn( self: *const ICreateTypeLib2, szName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCustData: fn( self: *const ICreateTypeLib2, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpStringContext: fn( self: *const ICreateTypeLib2, dwHelpStringContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpStringDll: fn( self: *const ICreateTypeLib2, szFileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ICreateTypeLib.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib2_DeleteTypeInfo(self: *const T, szName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib2.VTable, self.vtable).DeleteTypeInfo(@ptrCast(*const ICreateTypeLib2, self), szName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib2_SetCustData(self: *const T, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib2.VTable, self.vtable).SetCustData(@ptrCast(*const ICreateTypeLib2, self), guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib2_SetHelpStringContext(self: *const T, dwHelpStringContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib2.VTable, self.vtable).SetHelpStringContext(@ptrCast(*const ICreateTypeLib2, self), dwHelpStringContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateTypeLib2_SetHelpStringDll(self: *const T, szFileName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateTypeLib2.VTable, self.vtable).SetHelpStringDll(@ptrCast(*const ICreateTypeLib2, self), szFileName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispatch_Value = @import("../zig.zig").Guid.initString("00020400-0000-0000-c000-000000000046"); pub const IID_IDispatch = &IID_IDispatch_Value; pub const IDispatch = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetTypeInfoCount: fn( self: *const IDispatch, pctinfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeInfo: fn( self: *const IDispatch, iTInfo: u32, lcid: u32, ppTInfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIDsOfNames: fn( self: *const IDispatch, riid: ?*const Guid, rgszNames: [*]?PWSTR, cNames: u32, lcid: u32, rgDispId: [*]i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Invoke: fn( self: *const IDispatch, dispIdMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pDispParams: ?*DISPPARAMS, pVarResult: ?*VARIANT, pExcepInfo: ?*EXCEPINFO, puArgErr: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatch_GetTypeInfoCount(self: *const T, pctinfo: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatch.VTable, self.vtable).GetTypeInfoCount(@ptrCast(*const IDispatch, self), pctinfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatch_GetTypeInfo(self: *const T, iTInfo: u32, lcid: u32, ppTInfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatch.VTable, self.vtable).GetTypeInfo(@ptrCast(*const IDispatch, self), iTInfo, lcid, ppTInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatch_GetIDsOfNames(self: *const T, riid: ?*const Guid, rgszNames: [*]?PWSTR, cNames: u32, lcid: u32, rgDispId: [*]i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatch.VTable, self.vtable).GetIDsOfNames(@ptrCast(*const IDispatch, self), riid, rgszNames, cNames, lcid, rgDispId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatch_Invoke(self: *const T, dispIdMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pDispParams: ?*DISPPARAMS, pVarResult: ?*VARIANT, pExcepInfo: ?*EXCEPINFO, puArgErr: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatch.VTable, self.vtable).Invoke(@ptrCast(*const IDispatch, self), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IEnumVARIANT_Value = @import("../zig.zig").Guid.initString("00020404-0000-0000-c000-000000000046"); pub const IID_IEnumVARIANT = &IID_IEnumVARIANT_Value; pub const IEnumVARIANT = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumVARIANT, celt: u32, rgVar: [*]VARIANT, pCeltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumVARIANT, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumVARIANT, ppEnum: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumVARIANT_Next(self: *const T, celt: u32, rgVar: [*]VARIANT, pCeltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumVARIANT.VTable, self.vtable).Next(@ptrCast(*const IEnumVARIANT, self), celt, rgVar, pCeltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumVARIANT_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumVARIANT.VTable, self.vtable).Skip(@ptrCast(*const IEnumVARIANT, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumVARIANT_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumVARIANT.VTable, self.vtable).Reset(@ptrCast(*const IEnumVARIANT, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumVARIANT_Clone(self: *const T, ppEnum: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumVARIANT.VTable, self.vtable).Clone(@ptrCast(*const IEnumVARIANT, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; pub const DESCKIND = enum(i32) { NONE = 0, FUNCDESC = 1, VARDESC = 2, TYPECOMP = 3, IMPLICITAPPOBJ = 4, MAX = 5, }; pub const DESCKIND_NONE = DESCKIND.NONE; pub const DESCKIND_FUNCDESC = DESCKIND.FUNCDESC; pub const DESCKIND_VARDESC = DESCKIND.VARDESC; pub const DESCKIND_TYPECOMP = DESCKIND.TYPECOMP; pub const DESCKIND_IMPLICITAPPOBJ = DESCKIND.IMPLICITAPPOBJ; pub const DESCKIND_MAX = DESCKIND.MAX; pub const BINDPTR = extern union { lpfuncdesc: ?*FUNCDESC, lpvardesc: ?*VARDESC, lptcomp: ?*ITypeComp, }; const IID_ITypeComp_Value = @import("../zig.zig").Guid.initString("00020403-0000-0000-c000-000000000046"); pub const IID_ITypeComp = &IID_ITypeComp_Value; pub const ITypeComp = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Bind: fn( self: *const ITypeComp, szName: ?PWSTR, lHashVal: u32, wFlags: u16, ppTInfo: ?*?*ITypeInfo, pDescKind: ?*DESCKIND, pBindPtr: ?*BINDPTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BindType: fn( self: *const ITypeComp, szName: ?PWSTR, lHashVal: u32, ppTInfo: ?*?*ITypeInfo, ppTComp: ?*?*ITypeComp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeComp_Bind(self: *const T, szName: ?PWSTR, lHashVal: u32, wFlags: u16, ppTInfo: ?*?*ITypeInfo, pDescKind: ?*DESCKIND, pBindPtr: ?*BINDPTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeComp.VTable, self.vtable).Bind(@ptrCast(*const ITypeComp, self), szName, lHashVal, wFlags, ppTInfo, pDescKind, pBindPtr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeComp_BindType(self: *const T, szName: ?PWSTR, lHashVal: u32, ppTInfo: ?*?*ITypeInfo, ppTComp: ?*?*ITypeComp) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeComp.VTable, self.vtable).BindType(@ptrCast(*const ITypeComp, self), szName, lHashVal, ppTInfo, ppTComp); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeInfo_Value = @import("../zig.zig").Guid.initString("00020401-0000-0000-c000-000000000046"); pub const IID_ITypeInfo = &IID_ITypeInfo_Value; pub const ITypeInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetTypeAttr: fn( self: *const ITypeInfo, ppTypeAttr: ?*?*TYPEATTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeComp: fn( self: *const ITypeInfo, ppTComp: ?*?*ITypeComp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFuncDesc: fn( self: *const ITypeInfo, index: u32, ppFuncDesc: ?*?*FUNCDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVarDesc: fn( self: *const ITypeInfo, index: u32, ppVarDesc: ?*?*VARDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNames: fn( self: *const ITypeInfo, memid: i32, rgBstrNames: [*]?BSTR, cMaxNames: u32, pcNames: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRefTypeOfImplType: fn( self: *const ITypeInfo, index: u32, pRefType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImplTypeFlags: fn( self: *const ITypeInfo, index: u32, pImplTypeFlags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIDsOfNames: fn( self: *const ITypeInfo, rgszNames: [*]?PWSTR, cNames: u32, pMemId: [*]i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Invoke: fn( self: *const ITypeInfo, pvInstance: ?*c_void, memid: i32, wFlags: u16, pDispParams: ?*DISPPARAMS, pVarResult: ?*VARIANT, pExcepInfo: ?*EXCEPINFO, puArgErr: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentation: fn( self: *const ITypeInfo, memid: i32, pBstrName: ?*?BSTR, pBstrDocString: ?*?BSTR, pdwHelpContext: ?*u32, pBstrHelpFile: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDllEntry: fn( self: *const ITypeInfo, memid: i32, invKind: INVOKEKIND, pBstrDllName: ?*?BSTR, pBstrName: ?*?BSTR, pwOrdinal: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRefTypeInfo: fn( self: *const ITypeInfo, hRefType: u32, ppTInfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddressOfMember: fn( self: *const ITypeInfo, memid: i32, invKind: INVOKEKIND, ppv: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstance: fn( self: *const ITypeInfo, pUnkOuter: ?*IUnknown, riid: ?*const Guid, ppvObj: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMops: fn( self: *const ITypeInfo, memid: i32, pBstrMops: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContainingTypeLib: fn( self: *const ITypeInfo, ppTLib: ?*?*ITypeLib, pIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseTypeAttr: fn( self: *const ITypeInfo, pTypeAttr: ?*TYPEATTR, ) callconv(@import("std").os.windows.WINAPI) void, ReleaseFuncDesc: fn( self: *const ITypeInfo, pFuncDesc: ?*FUNCDESC, ) callconv(@import("std").os.windows.WINAPI) void, ReleaseVarDesc: fn( self: *const ITypeInfo, pVarDesc: ?*VARDESC, ) callconv(@import("std").os.windows.WINAPI) void, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetTypeAttr(self: *const T, ppTypeAttr: ?*?*TYPEATTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetTypeAttr(@ptrCast(*const ITypeInfo, self), ppTypeAttr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetTypeComp(self: *const T, ppTComp: ?*?*ITypeComp) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetTypeComp(@ptrCast(*const ITypeInfo, self), ppTComp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetFuncDesc(self: *const T, index: u32, ppFuncDesc: ?*?*FUNCDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetFuncDesc(@ptrCast(*const ITypeInfo, self), index, ppFuncDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetVarDesc(self: *const T, index: u32, ppVarDesc: ?*?*VARDESC) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetVarDesc(@ptrCast(*const ITypeInfo, self), index, ppVarDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetNames(self: *const T, memid: i32, rgBstrNames: [*]?BSTR, cMaxNames: u32, pcNames: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetNames(@ptrCast(*const ITypeInfo, self), memid, rgBstrNames, cMaxNames, pcNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetRefTypeOfImplType(self: *const T, index: u32, pRefType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetRefTypeOfImplType(@ptrCast(*const ITypeInfo, self), index, pRefType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetImplTypeFlags(self: *const T, index: u32, pImplTypeFlags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetImplTypeFlags(@ptrCast(*const ITypeInfo, self), index, pImplTypeFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetIDsOfNames(self: *const T, rgszNames: [*]?PWSTR, cNames: u32, pMemId: [*]i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetIDsOfNames(@ptrCast(*const ITypeInfo, self), rgszNames, cNames, pMemId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_Invoke(self: *const T, pvInstance: ?*c_void, memid: i32, wFlags: u16, pDispParams: ?*DISPPARAMS, pVarResult: ?*VARIANT, pExcepInfo: ?*EXCEPINFO, puArgErr: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).Invoke(@ptrCast(*const ITypeInfo, self), pvInstance, memid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetDocumentation(self: *const T, memid: i32, pBstrName: ?*?BSTR, pBstrDocString: ?*?BSTR, pdwHelpContext: ?*u32, pBstrHelpFile: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetDocumentation(@ptrCast(*const ITypeInfo, self), memid, pBstrName, pBstrDocString, pdwHelpContext, pBstrHelpFile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetDllEntry(self: *const T, memid: i32, invKind: INVOKEKIND, pBstrDllName: ?*?BSTR, pBstrName: ?*?BSTR, pwOrdinal: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetDllEntry(@ptrCast(*const ITypeInfo, self), memid, invKind, pBstrDllName, pBstrName, pwOrdinal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetRefTypeInfo(self: *const T, hRefType: u32, ppTInfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetRefTypeInfo(@ptrCast(*const ITypeInfo, self), hRefType, ppTInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_AddressOfMember(self: *const T, memid: i32, invKind: INVOKEKIND, ppv: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).AddressOfMember(@ptrCast(*const ITypeInfo, self), memid, invKind, ppv); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_CreateInstance(self: *const T, pUnkOuter: ?*IUnknown, riid: ?*const Guid, ppvObj: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).CreateInstance(@ptrCast(*const ITypeInfo, self), pUnkOuter, riid, ppvObj); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetMops(self: *const T, memid: i32, pBstrMops: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetMops(@ptrCast(*const ITypeInfo, self), memid, pBstrMops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_GetContainingTypeLib(self: *const T, ppTLib: ?*?*ITypeLib, pIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo.VTable, self.vtable).GetContainingTypeLib(@ptrCast(*const ITypeInfo, self), ppTLib, pIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_ReleaseTypeAttr(self: *const T, pTypeAttr: ?*TYPEATTR) callconv(.Inline) void { return @ptrCast(*const ITypeInfo.VTable, self.vtable).ReleaseTypeAttr(@ptrCast(*const ITypeInfo, self), pTypeAttr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_ReleaseFuncDesc(self: *const T, pFuncDesc: ?*FUNCDESC) callconv(.Inline) void { return @ptrCast(*const ITypeInfo.VTable, self.vtable).ReleaseFuncDesc(@ptrCast(*const ITypeInfo, self), pFuncDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo_ReleaseVarDesc(self: *const T, pVarDesc: ?*VARDESC) callconv(.Inline) void { return @ptrCast(*const ITypeInfo.VTable, self.vtable).ReleaseVarDesc(@ptrCast(*const ITypeInfo, self), pVarDesc); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeInfo2_Value = @import("../zig.zig").Guid.initString("00020412-0000-0000-c000-000000000046"); pub const IID_ITypeInfo2 = &IID_ITypeInfo2_Value; pub const ITypeInfo2 = extern struct { pub const VTable = extern struct { base: ITypeInfo.VTable, GetTypeKind: fn( self: *const ITypeInfo2, pTypeKind: ?*TYPEKIND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeFlags: fn( self: *const ITypeInfo2, pTypeFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFuncIndexOfMemId: fn( self: *const ITypeInfo2, memid: i32, invKind: INVOKEKIND, pFuncIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVarIndexOfMemId: fn( self: *const ITypeInfo2, memid: i32, pVarIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCustData: fn( self: *const ITypeInfo2, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFuncCustData: fn( self: *const ITypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParamCustData: fn( self: *const ITypeInfo2, indexFunc: u32, indexParam: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVarCustData: fn( self: *const ITypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImplTypeCustData: fn( self: *const ITypeInfo2, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentation2: fn( self: *const ITypeInfo2, memid: i32, lcid: u32, pbstrHelpString: ?*?BSTR, pdwHelpStringContext: ?*u32, pbstrHelpStringDll: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllCustData: fn( self: *const ITypeInfo2, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllFuncCustData: fn( self: *const ITypeInfo2, index: u32, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParamCustData: fn( self: *const ITypeInfo2, indexFunc: u32, indexParam: u32, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllVarCustData: fn( self: *const ITypeInfo2, index: u32, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllImplTypeCustData: fn( self: *const ITypeInfo2, index: u32, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITypeInfo.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetTypeKind(self: *const T, pTypeKind: ?*TYPEKIND) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetTypeKind(@ptrCast(*const ITypeInfo2, self), pTypeKind); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetTypeFlags(self: *const T, pTypeFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetTypeFlags(@ptrCast(*const ITypeInfo2, self), pTypeFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetFuncIndexOfMemId(self: *const T, memid: i32, invKind: INVOKEKIND, pFuncIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetFuncIndexOfMemId(@ptrCast(*const ITypeInfo2, self), memid, invKind, pFuncIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetVarIndexOfMemId(self: *const T, memid: i32, pVarIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetVarIndexOfMemId(@ptrCast(*const ITypeInfo2, self), memid, pVarIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetCustData(self: *const T, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetCustData(@ptrCast(*const ITypeInfo2, self), guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetFuncCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetFuncCustData(@ptrCast(*const ITypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetParamCustData(self: *const T, indexFunc: u32, indexParam: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetParamCustData(@ptrCast(*const ITypeInfo2, self), indexFunc, indexParam, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetVarCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetVarCustData(@ptrCast(*const ITypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetImplTypeCustData(self: *const T, index: u32, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetImplTypeCustData(@ptrCast(*const ITypeInfo2, self), index, guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetDocumentation2(self: *const T, memid: i32, lcid: u32, pbstrHelpString: ?*?BSTR, pdwHelpStringContext: ?*u32, pbstrHelpStringDll: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetDocumentation2(@ptrCast(*const ITypeInfo2, self), memid, lcid, pbstrHelpString, pdwHelpStringContext, pbstrHelpStringDll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetAllCustData(self: *const T, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetAllCustData(@ptrCast(*const ITypeInfo2, self), pCustData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetAllFuncCustData(self: *const T, index: u32, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetAllFuncCustData(@ptrCast(*const ITypeInfo2, self), index, pCustData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetAllParamCustData(self: *const T, indexFunc: u32, indexParam: u32, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetAllParamCustData(@ptrCast(*const ITypeInfo2, self), indexFunc, indexParam, pCustData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetAllVarCustData(self: *const T, index: u32, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetAllVarCustData(@ptrCast(*const ITypeInfo2, self), index, pCustData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeInfo2_GetAllImplTypeCustData(self: *const T, index: u32, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeInfo2.VTable, self.vtable).GetAllImplTypeCustData(@ptrCast(*const ITypeInfo2, self), index, pCustData); } };} pub usingnamespace MethodMixin(@This()); }; pub const SYSKIND = enum(i32) { WIN16 = 0, WIN32 = 1, MAC = 2, WIN64 = 3, }; pub const SYS_WIN16 = SYSKIND.WIN16; pub const SYS_WIN32 = SYSKIND.WIN32; pub const SYS_MAC = SYSKIND.MAC; pub const SYS_WIN64 = SYSKIND.WIN64; pub const LIBFLAGS = enum(i32) { RESTRICTED = 1, CONTROL = 2, HIDDEN = 4, HASDISKIMAGE = 8, }; pub const LIBFLAG_FRESTRICTED = LIBFLAGS.RESTRICTED; pub const LIBFLAG_FCONTROL = LIBFLAGS.CONTROL; pub const LIBFLAG_FHIDDEN = LIBFLAGS.HIDDEN; pub const LIBFLAG_FHASDISKIMAGE = LIBFLAGS.HASDISKIMAGE; pub const TLIBATTR = extern struct { guid: Guid, lcid: u32, syskind: SYSKIND, wMajorVerNum: u16, wMinorVerNum: u16, wLibFlags: u16, }; const IID_ITypeLib_Value = @import("../zig.zig").Guid.initString("00020402-0000-0000-c000-000000000046"); pub const IID_ITypeLib = &IID_ITypeLib_Value; pub const ITypeLib = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetTypeInfoCount: fn( self: *const ITypeLib, ) callconv(@import("std").os.windows.WINAPI) u32, GetTypeInfo: fn( self: *const ITypeLib, index: u32, ppTInfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeInfoType: fn( self: *const ITypeLib, index: u32, pTKind: ?*TYPEKIND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeInfoOfGuid: fn( self: *const ITypeLib, guid: ?*const Guid, ppTinfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLibAttr: fn( self: *const ITypeLib, ppTLibAttr: ?*?*TLIBATTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeComp: fn( self: *const ITypeLib, ppTComp: ?*?*ITypeComp, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentation: fn( self: *const ITypeLib, index: i32, pBstrName: ?*?BSTR, pBstrDocString: ?*?BSTR, pdwHelpContext: ?*u32, pBstrHelpFile: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsName: fn( self: *const ITypeLib, szNameBuf: ?PWSTR, lHashVal: u32, pfName: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindName: fn( self: *const ITypeLib, szNameBuf: ?PWSTR, lHashVal: u32, ppTInfo: [*]?*ITypeInfo, rgMemId: [*]i32, pcFound: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseTLibAttr: fn( self: *const ITypeLib, pTLibAttr: ?*TLIBATTR, ) callconv(@import("std").os.windows.WINAPI) void, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetTypeInfoCount(self: *const T) callconv(.Inline) u32 { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetTypeInfoCount(@ptrCast(*const ITypeLib, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetTypeInfo(self: *const T, index: u32, ppTInfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetTypeInfo(@ptrCast(*const ITypeLib, self), index, ppTInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetTypeInfoType(self: *const T, index: u32, pTKind: ?*TYPEKIND) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetTypeInfoType(@ptrCast(*const ITypeLib, self), index, pTKind); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetTypeInfoOfGuid(self: *const T, guid: ?*const Guid, ppTinfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetTypeInfoOfGuid(@ptrCast(*const ITypeLib, self), guid, ppTinfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetLibAttr(self: *const T, ppTLibAttr: ?*?*TLIBATTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetLibAttr(@ptrCast(*const ITypeLib, self), ppTLibAttr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetTypeComp(self: *const T, ppTComp: ?*?*ITypeComp) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetTypeComp(@ptrCast(*const ITypeLib, self), ppTComp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_GetDocumentation(self: *const T, index: i32, pBstrName: ?*?BSTR, pBstrDocString: ?*?BSTR, pdwHelpContext: ?*u32, pBstrHelpFile: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).GetDocumentation(@ptrCast(*const ITypeLib, self), index, pBstrName, pBstrDocString, pdwHelpContext, pBstrHelpFile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_IsName(self: *const T, szNameBuf: ?PWSTR, lHashVal: u32, pfName: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).IsName(@ptrCast(*const ITypeLib, self), szNameBuf, lHashVal, pfName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_FindName(self: *const T, szNameBuf: ?PWSTR, lHashVal: u32, ppTInfo: [*]?*ITypeInfo, rgMemId: [*]i32, pcFound: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib.VTable, self.vtable).FindName(@ptrCast(*const ITypeLib, self), szNameBuf, lHashVal, ppTInfo, rgMemId, pcFound); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib_ReleaseTLibAttr(self: *const T, pTLibAttr: ?*TLIBATTR) callconv(.Inline) void { return @ptrCast(*const ITypeLib.VTable, self.vtable).ReleaseTLibAttr(@ptrCast(*const ITypeLib, self), pTLibAttr); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeLib2_Value = @import("../zig.zig").Guid.initString("00020411-0000-0000-c000-000000000046"); pub const IID_ITypeLib2 = &IID_ITypeLib2_Value; pub const ITypeLib2 = extern struct { pub const VTable = extern struct { base: ITypeLib.VTable, GetCustData: fn( self: *const ITypeLib2, guid: ?*const Guid, pVarVal: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLibStatistics: fn( self: *const ITypeLib2, pcUniqueNames: ?*u32, pcchUniqueNames: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentation2: fn( self: *const ITypeLib2, index: i32, lcid: u32, pbstrHelpString: ?*?BSTR, pdwHelpStringContext: ?*u32, pbstrHelpStringDll: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllCustData: fn( self: *const ITypeLib2, pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITypeLib.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib2_GetCustData(self: *const T, guid: ?*const Guid, pVarVal: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib2.VTable, self.vtable).GetCustData(@ptrCast(*const ITypeLib2, self), guid, pVarVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib2_GetLibStatistics(self: *const T, pcUniqueNames: ?*u32, pcchUniqueNames: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib2.VTable, self.vtable).GetLibStatistics(@ptrCast(*const ITypeLib2, self), pcUniqueNames, pcchUniqueNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib2_GetDocumentation2(self: *const T, index: i32, lcid: u32, pbstrHelpString: ?*?BSTR, pdwHelpStringContext: ?*u32, pbstrHelpStringDll: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib2.VTable, self.vtable).GetDocumentation2(@ptrCast(*const ITypeLib2, self), index, lcid, pbstrHelpString, pdwHelpStringContext, pbstrHelpStringDll); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLib2_GetAllCustData(self: *const T, pCustData: ?*CUSTDATA) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLib2.VTable, self.vtable).GetAllCustData(@ptrCast(*const ITypeLib2, self), pCustData); } };} pub usingnamespace MethodMixin(@This()); }; pub const CHANGEKIND = enum(i32) { ADDMEMBER = 0, DELETEMEMBER = 1, SETNAMES = 2, SETDOCUMENTATION = 3, GENERAL = 4, INVALIDATE = 5, CHANGEFAILED = 6, MAX = 7, }; pub const CHANGEKIND_ADDMEMBER = CHANGEKIND.ADDMEMBER; pub const CHANGEKIND_DELETEMEMBER = CHANGEKIND.DELETEMEMBER; pub const CHANGEKIND_SETNAMES = CHANGEKIND.SETNAMES; pub const CHANGEKIND_SETDOCUMENTATION = CHANGEKIND.SETDOCUMENTATION; pub const CHANGEKIND_GENERAL = CHANGEKIND.GENERAL; pub const CHANGEKIND_INVALIDATE = CHANGEKIND.INVALIDATE; pub const CHANGEKIND_CHANGEFAILED = CHANGEKIND.CHANGEFAILED; pub const CHANGEKIND_MAX = CHANGEKIND.MAX; const IID_ITypeChangeEvents_Value = @import("../zig.zig").Guid.initString("00020410-0000-0000-c000-000000000046"); pub const IID_ITypeChangeEvents = &IID_ITypeChangeEvents_Value; pub const ITypeChangeEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RequestTypeChange: fn( self: *const ITypeChangeEvents, changeKind: CHANGEKIND, pTInfoBefore: ?*ITypeInfo, pStrName: ?PWSTR, pfCancel: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AfterTypeChange: fn( self: *const ITypeChangeEvents, changeKind: CHANGEKIND, pTInfoAfter: ?*ITypeInfo, pStrName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeChangeEvents_RequestTypeChange(self: *const T, changeKind: CHANGEKIND, pTInfoBefore: ?*ITypeInfo, pStrName: ?PWSTR, pfCancel: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeChangeEvents.VTable, self.vtable).RequestTypeChange(@ptrCast(*const ITypeChangeEvents, self), changeKind, pTInfoBefore, pStrName, pfCancel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeChangeEvents_AfterTypeChange(self: *const T, changeKind: CHANGEKIND, pTInfoAfter: ?*ITypeInfo, pStrName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeChangeEvents.VTable, self.vtable).AfterTypeChange(@ptrCast(*const ITypeChangeEvents, self), changeKind, pTInfoAfter, pStrName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IErrorInfo_Value = @import("../zig.zig").Guid.initString("1cf2b120-547d-101b-8e65-08002b2bd119"); pub const IID_IErrorInfo = &IID_IErrorInfo_Value; pub const IErrorInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetGUID: fn( self: *const IErrorInfo, pGUID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSource: fn( self: *const IErrorInfo, pBstrSource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const IErrorInfo, pBstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpFile: fn( self: *const IErrorInfo, pBstrHelpFile: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpContext: fn( self: *const IErrorInfo, pdwHelpContext: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorInfo_GetGUID(self: *const T, pGUID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorInfo.VTable, self.vtable).GetGUID(@ptrCast(*const IErrorInfo, self), pGUID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorInfo_GetSource(self: *const T, pBstrSource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorInfo.VTable, self.vtable).GetSource(@ptrCast(*const IErrorInfo, self), pBstrSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorInfo_GetDescription(self: *const T, pBstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorInfo.VTable, self.vtable).GetDescription(@ptrCast(*const IErrorInfo, self), pBstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorInfo_GetHelpFile(self: *const T, pBstrHelpFile: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorInfo.VTable, self.vtable).GetHelpFile(@ptrCast(*const IErrorInfo, self), pBstrHelpFile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorInfo_GetHelpContext(self: *const T, pdwHelpContext: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorInfo.VTable, self.vtable).GetHelpContext(@ptrCast(*const IErrorInfo, self), pdwHelpContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICreateErrorInfo_Value = @import("../zig.zig").Guid.initString("22f03340-547d-101b-8e65-08002b2bd119"); pub const IID_ICreateErrorInfo = &IID_ICreateErrorInfo_Value; pub const ICreateErrorInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetGUID: fn( self: *const ICreateErrorInfo, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSource: fn( self: *const ICreateErrorInfo, szSource: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDescription: fn( self: *const ICreateErrorInfo, szDescription: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpFile: fn( self: *const ICreateErrorInfo, szHelpFile: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHelpContext: fn( self: *const ICreateErrorInfo, dwHelpContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateErrorInfo_SetGUID(self: *const T, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateErrorInfo.VTable, self.vtable).SetGUID(@ptrCast(*const ICreateErrorInfo, self), rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateErrorInfo_SetSource(self: *const T, szSource: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateErrorInfo.VTable, self.vtable).SetSource(@ptrCast(*const ICreateErrorInfo, self), szSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateErrorInfo_SetDescription(self: *const T, szDescription: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateErrorInfo.VTable, self.vtable).SetDescription(@ptrCast(*const ICreateErrorInfo, self), szDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateErrorInfo_SetHelpFile(self: *const T, szHelpFile: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateErrorInfo.VTable, self.vtable).SetHelpFile(@ptrCast(*const ICreateErrorInfo, self), szHelpFile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICreateErrorInfo_SetHelpContext(self: *const T, dwHelpContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICreateErrorInfo.VTable, self.vtable).SetHelpContext(@ptrCast(*const ICreateErrorInfo, self), dwHelpContext); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISupportErrorInfo_Value = @import("../zig.zig").Guid.initString("df0b3d60-548f-101b-8e65-08002b2bd119"); pub const IID_ISupportErrorInfo = &IID_ISupportErrorInfo_Value; pub const ISupportErrorInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InterfaceSupportsErrorInfo: fn( self: *const ISupportErrorInfo, riid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISupportErrorInfo_InterfaceSupportsErrorInfo(self: *const T, riid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ISupportErrorInfo.VTable, self.vtable).InterfaceSupportsErrorInfo(@ptrCast(*const ISupportErrorInfo, self), riid); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeFactory_Value = @import("../zig.zig").Guid.initString("0000002e-0000-0000-c000-000000000046"); pub const IID_ITypeFactory = &IID_ITypeFactory_Value; pub const ITypeFactory = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateFromTypeInfo: fn( self: *const ITypeFactory, pTypeInfo: ?*ITypeInfo, riid: ?*const Guid, ppv: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeFactory_CreateFromTypeInfo(self: *const T, pTypeInfo: ?*ITypeInfo, riid: ?*const Guid, ppv: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeFactory.VTable, self.vtable).CreateFromTypeInfo(@ptrCast(*const ITypeFactory, self), pTypeInfo, riid, ppv); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeMarshal_Value = @import("../zig.zig").Guid.initString("0000002d-0000-0000-c000-000000000046"); pub const IID_ITypeMarshal = &IID_ITypeMarshal_Value; pub const ITypeMarshal = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Size: fn( self: *const ITypeMarshal, pvType: ?*c_void, dwDestContext: u32, pvDestContext: ?*c_void, pSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Marshal: fn( self: *const ITypeMarshal, pvType: ?*c_void, dwDestContext: u32, pvDestContext: ?*c_void, cbBufferLength: u32, // TODO: what to do with BytesParamIndex 3? pBuffer: ?*u8, pcbWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unmarshal: fn( self: *const ITypeMarshal, pvType: ?*c_void, dwFlags: u32, cbBufferLength: u32, pBuffer: [*:0]u8, pcbRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Free: fn( self: *const ITypeMarshal, pvType: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeMarshal_Size(self: *const T, pvType: ?*c_void, dwDestContext: u32, pvDestContext: ?*c_void, pSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeMarshal.VTable, self.vtable).Size(@ptrCast(*const ITypeMarshal, self), pvType, dwDestContext, pvDestContext, pSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeMarshal_Marshal(self: *const T, pvType: ?*c_void, dwDestContext: u32, pvDestContext: ?*c_void, cbBufferLength: u32, pBuffer: ?*u8, pcbWritten: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeMarshal.VTable, self.vtable).Marshal(@ptrCast(*const ITypeMarshal, self), pvType, dwDestContext, pvDestContext, cbBufferLength, pBuffer, pcbWritten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeMarshal_Unmarshal(self: *const T, pvType: ?*c_void, dwFlags: u32, cbBufferLength: u32, pBuffer: [*:0]u8, pcbRead: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeMarshal.VTable, self.vtable).Unmarshal(@ptrCast(*const ITypeMarshal, self), pvType, dwFlags, cbBufferLength, pBuffer, pcbRead); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeMarshal_Free(self: *const T, pvType: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeMarshal.VTable, self.vtable).Free(@ptrCast(*const ITypeMarshal, self), pvType); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IRecordInfo_Value = @import("../zig.zig").Guid.initString("0000002f-0000-0000-c000-000000000046"); pub const IID_IRecordInfo = &IID_IRecordInfo_Value; pub const IRecordInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RecordInit: fn( self: *const IRecordInfo, pvNew: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RecordClear: fn( self: *const IRecordInfo, pvExisting: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RecordCopy: fn( self: *const IRecordInfo, pvExisting: ?*c_void, pvNew: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGuid: fn( self: *const IRecordInfo, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetName: fn( self: *const IRecordInfo, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSize: fn( self: *const IRecordInfo, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTypeInfo: fn( self: *const IRecordInfo, ppTypeInfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetField: fn( self: *const IRecordInfo, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFieldNoCopy: fn( self: *const IRecordInfo, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT, ppvDataCArray: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutField: fn( self: *const IRecordInfo, wFlags: u32, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutFieldNoCopy: fn( self: *const IRecordInfo, wFlags: u32, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFieldNames: fn( self: *const IRecordInfo, pcNames: ?*u32, rgBstrNames: [*]?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsMatchingType: fn( self: *const IRecordInfo, pRecordInfo: ?*IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) BOOL, RecordCreate: fn( self: *const IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) ?*c_void, RecordCreateCopy: fn( self: *const IRecordInfo, pvSource: ?*c_void, ppvDest: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RecordDestroy: fn( self: *const IRecordInfo, pvRecord: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordInit(self: *const T, pvNew: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordInit(@ptrCast(*const IRecordInfo, self), pvNew); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordClear(self: *const T, pvExisting: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordClear(@ptrCast(*const IRecordInfo, self), pvExisting); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordCopy(self: *const T, pvExisting: ?*c_void, pvNew: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordCopy(@ptrCast(*const IRecordInfo, self), pvExisting, pvNew); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetGuid(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetGuid(@ptrCast(*const IRecordInfo, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetName(@ptrCast(*const IRecordInfo, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetSize(self: *const T, pcbSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetSize(@ptrCast(*const IRecordInfo, self), pcbSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetTypeInfo(self: *const T, ppTypeInfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetTypeInfo(@ptrCast(*const IRecordInfo, self), ppTypeInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetField(self: *const T, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetField(@ptrCast(*const IRecordInfo, self), pvData, szFieldName, pvarField); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetFieldNoCopy(self: *const T, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT, ppvDataCArray: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetFieldNoCopy(@ptrCast(*const IRecordInfo, self), pvData, szFieldName, pvarField, ppvDataCArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_PutField(self: *const T, wFlags: u32, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).PutField(@ptrCast(*const IRecordInfo, self), wFlags, pvData, szFieldName, pvarField); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_PutFieldNoCopy(self: *const T, wFlags: u32, pvData: ?*c_void, szFieldName: ?[*:0]const u16, pvarField: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).PutFieldNoCopy(@ptrCast(*const IRecordInfo, self), wFlags, pvData, szFieldName, pvarField); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_GetFieldNames(self: *const T, pcNames: ?*u32, rgBstrNames: [*]?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).GetFieldNames(@ptrCast(*const IRecordInfo, self), pcNames, rgBstrNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_IsMatchingType(self: *const T, pRecordInfo: ?*IRecordInfo) callconv(.Inline) BOOL { return @ptrCast(*const IRecordInfo.VTable, self.vtable).IsMatchingType(@ptrCast(*const IRecordInfo, self), pRecordInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordCreate(self: *const T) callconv(.Inline) ?*c_void { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordCreate(@ptrCast(*const IRecordInfo, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordCreateCopy(self: *const T, pvSource: ?*c_void, ppvDest: ?*?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordCreateCopy(@ptrCast(*const IRecordInfo, self), pvSource, ppvDest); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRecordInfo_RecordDestroy(self: *const T, pvRecord: ?*c_void) callconv(.Inline) HRESULT { return @ptrCast(*const IRecordInfo.VTable, self.vtable).RecordDestroy(@ptrCast(*const IRecordInfo, self), pvRecord); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IErrorLog_Value = @import("../zig.zig").Guid.initString("3127ca40-446e-11ce-8135-00aa004bb851"); pub const IID_IErrorLog = &IID_IErrorLog_Value; pub const IErrorLog = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddError: fn( self: *const IErrorLog, pszPropName: ?[*:0]const u16, pExcepInfo: ?*EXCEPINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IErrorLog_AddError(self: *const T, pszPropName: ?[*:0]const u16, pExcepInfo: ?*EXCEPINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IErrorLog.VTable, self.vtable).AddError(@ptrCast(*const IErrorLog, self), pszPropName, pExcepInfo); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPropertyBag_Value = @import("../zig.zig").Guid.initString("55272a00-42cb-11ce-8135-00aa004bb851"); pub const IID_IPropertyBag = &IID_IPropertyBag_Value; pub const IPropertyBag = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Read: fn( self: *const IPropertyBag, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT, pErrorLog: ?*IErrorLog, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Write: fn( self: *const IPropertyBag, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyBag_Read(self: *const T, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT, pErrorLog: ?*IErrorLog) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyBag.VTable, self.vtable).Read(@ptrCast(*const IPropertyBag, self), pszPropName, pVar, pErrorLog); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertyBag_Write(self: *const T, pszPropName: ?[*:0]const u16, pVar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertyBag.VTable, self.vtable).Write(@ptrCast(*const IPropertyBag, self), pszPropName, pVar); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeLibRegistrationReader_Value = @import("../zig.zig").Guid.initString("ed6a8a2a-b160-4e77-8f73-aa7435cd5c27"); pub const IID_ITypeLibRegistrationReader = &IID_ITypeLibRegistrationReader_Value; pub const ITypeLibRegistrationReader = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumTypeLibRegistrations: fn( self: *const ITypeLibRegistrationReader, ppEnumUnknown: ?*?*IEnumUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistrationReader_EnumTypeLibRegistrations(self: *const T, ppEnumUnknown: ?*?*IEnumUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistrationReader.VTable, self.vtable).EnumTypeLibRegistrations(@ptrCast(*const ITypeLibRegistrationReader, self), ppEnumUnknown); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITypeLibRegistration_Value = @import("../zig.zig").Guid.initString("76a3e735-02df-4a12-98eb-043ad3600af3"); pub const IID_ITypeLibRegistration = &IID_ITypeLibRegistration_Value; pub const ITypeLibRegistration = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetGuid: fn( self: *const ITypeLibRegistration, pGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVersion: fn( self: *const ITypeLibRegistration, pVersion: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLcid: fn( self: *const ITypeLibRegistration, pLcid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWin32Path: fn( self: *const ITypeLibRegistration, pWin32Path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWin64Path: fn( self: *const ITypeLibRegistration, pWin64Path: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayName: fn( self: *const ITypeLibRegistration, pDisplayName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlags: fn( self: *const ITypeLibRegistration, pFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpDir: fn( self: *const ITypeLibRegistration, pHelpDir: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetGuid(self: *const T, pGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetGuid(@ptrCast(*const ITypeLibRegistration, self), pGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetVersion(self: *const T, pVersion: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetVersion(@ptrCast(*const ITypeLibRegistration, self), pVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetLcid(self: *const T, pLcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetLcid(@ptrCast(*const ITypeLibRegistration, self), pLcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetWin32Path(self: *const T, pWin32Path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetWin32Path(@ptrCast(*const ITypeLibRegistration, self), pWin32Path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetWin64Path(self: *const T, pWin64Path: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetWin64Path(@ptrCast(*const ITypeLibRegistration, self), pWin64Path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetDisplayName(self: *const T, pDisplayName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetDisplayName(@ptrCast(*const ITypeLibRegistration, self), pDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetFlags(self: *const T, pFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetFlags(@ptrCast(*const ITypeLibRegistration, self), pFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITypeLibRegistration_GetHelpDir(self: *const T, pHelpDir: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITypeLibRegistration.VTable, self.vtable).GetHelpDir(@ptrCast(*const ITypeLibRegistration, self), pHelpDir); } };} pub usingnamespace MethodMixin(@This()); }; pub const NUMPARSE = extern struct { cDig: i32, dwInFlags: u32, dwOutFlags: u32, cchUsed: i32, nBaseShift: i32, nPwr10: i32, }; pub const UDATE = extern struct { st: SYSTEMTIME, wDayOfYear: u16, }; pub const REGKIND = enum(i32) { DEFAULT = 0, REGISTER = 1, NONE = 2, }; pub const REGKIND_DEFAULT = REGKIND.DEFAULT; pub const REGKIND_REGISTER = REGKIND.REGISTER; pub const REGKIND_NONE = REGKIND.NONE; pub const PARAMDATA = extern struct { szName: ?PWSTR, vt: u16, }; pub const METHODDATA = extern struct { szName: ?PWSTR, ppdata: ?*PARAMDATA, dispid: i32, iMeth: u32, cc: CALLCONV, cArgs: u32, wFlags: u16, vtReturn: u16, }; pub const INTERFACEDATA = extern struct { pmethdata: ?*METHODDATA, cMembers: u32, }; const IID_IDispatchEx_Value = @import("../zig.zig").Guid.initString("a6ef9860-c720-11d0-9337-00a0c90dcaa9"); pub const IID_IDispatchEx = &IID_IDispatchEx_Value; pub const IDispatchEx = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetDispID: fn( self: *const IDispatchEx, bstrName: ?BSTR, grfdex: u32, pid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeEx: fn( self: *const IDispatchEx, id: i32, lcid: u32, wFlags: u16, pdp: ?*DISPPARAMS, pvarRes: ?*VARIANT, pei: ?*EXCEPINFO, pspCaller: ?*IServiceProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMemberByName: fn( self: *const IDispatchEx, bstrName: ?BSTR, grfdex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteMemberByDispID: fn( self: *const IDispatchEx, id: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMemberProperties: fn( self: *const IDispatchEx, id: i32, grfdexFetch: u32, pgrfdex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMemberName: fn( self: *const IDispatchEx, id: i32, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextDispID: fn( self: *const IDispatchEx, grfdex: u32, id: i32, pid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNameSpaceParent: fn( self: *const IDispatchEx, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_GetDispID(self: *const T, bstrName: ?BSTR, grfdex: u32, pid: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).GetDispID(@ptrCast(*const IDispatchEx, self), bstrName, grfdex, pid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_InvokeEx(self: *const T, id: i32, lcid: u32, wFlags: u16, pdp: ?*DISPPARAMS, pvarRes: ?*VARIANT, pei: ?*EXCEPINFO, pspCaller: ?*IServiceProvider) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).InvokeEx(@ptrCast(*const IDispatchEx, self), id, lcid, wFlags, pdp, pvarRes, pei, pspCaller); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_DeleteMemberByName(self: *const T, bstrName: ?BSTR, grfdex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).DeleteMemberByName(@ptrCast(*const IDispatchEx, self), bstrName, grfdex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_DeleteMemberByDispID(self: *const T, id: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).DeleteMemberByDispID(@ptrCast(*const IDispatchEx, self), id); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_GetMemberProperties(self: *const T, id: i32, grfdexFetch: u32, pgrfdex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).GetMemberProperties(@ptrCast(*const IDispatchEx, self), id, grfdexFetch, pgrfdex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_GetMemberName(self: *const T, id: i32, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).GetMemberName(@ptrCast(*const IDispatchEx, self), id, pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_GetNextDispID(self: *const T, grfdex: u32, id: i32, pid: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).GetNextDispID(@ptrCast(*const IDispatchEx, self), grfdex, id, pid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispatchEx_GetNameSpaceParent(self: *const T, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDispatchEx.VTable, self.vtable).GetNameSpaceParent(@ptrCast(*const IDispatchEx, self), ppunk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispError_Value = @import("../zig.zig").Guid.initString("a6ef9861-c720-11d0-9337-00a0c90dcaa9"); pub const IID_IDispError = &IID_IDispError_Value; pub const IDispError = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryErrorInfo: fn( self: *const IDispError, guidErrorType: Guid, ppde: ?*?*IDispError, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNext: fn( self: *const IDispError, ppde: ?*?*IDispError, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHresult: fn( self: *const IDispError, phr: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSource: fn( self: *const IDispError, pbstrSource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpInfo: fn( self: *const IDispError, pbstrFileName: ?*?BSTR, pdwContext: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const IDispError, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_QueryErrorInfo(self: *const T, guidErrorType: Guid, ppde: ?*?*IDispError) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).QueryErrorInfo(@ptrCast(*const IDispError, self), guidErrorType, ppde); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_GetNext(self: *const T, ppde: ?*?*IDispError) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).GetNext(@ptrCast(*const IDispError, self), ppde); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_GetHresult(self: *const T, phr: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).GetHresult(@ptrCast(*const IDispError, self), phr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_GetSource(self: *const T, pbstrSource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).GetSource(@ptrCast(*const IDispError, self), pbstrSource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_GetHelpInfo(self: *const T, pbstrFileName: ?*?BSTR, pdwContext: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).GetHelpInfo(@ptrCast(*const IDispError, self), pbstrFileName, pdwContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispError_GetDescription(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispError.VTable, self.vtable).GetDescription(@ptrCast(*const IDispError, self), pbstrDescription); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IVariantChangeType_Value = @import("../zig.zig").Guid.initString("a6ef9862-c720-11d0-9337-00a0c90dcaa9"); pub const IID_IVariantChangeType = &IID_IVariantChangeType_Value; pub const IVariantChangeType = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ChangeType: fn( self: *const IVariantChangeType, pvarDst: ?*VARIANT, pvarSrc: ?*VARIANT, lcid: u32, vtNew: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVariantChangeType_ChangeType(self: *const T, pvarDst: ?*VARIANT, pvarSrc: ?*VARIANT, lcid: u32, vtNew: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IVariantChangeType.VTable, self.vtable).ChangeType(@ptrCast(*const IVariantChangeType, self), pvarDst, pvarSrc, lcid, vtNew); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IObjectIdentity_Value = @import("../zig.zig").Guid.initString("ca04b7e6-0d21-11d1-8cc5-00c04fc2b085"); pub const IID_IObjectIdentity = &IID_IObjectIdentity_Value; pub const IObjectIdentity = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, IsEqualObject: fn( self: *const IObjectIdentity, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IObjectIdentity_IsEqualObject(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IObjectIdentity.VTable, self.vtable).IsEqualObject(@ptrCast(*const IObjectIdentity, self), punk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICanHandleException_Value = @import("../zig.zig").Guid.initString("c5598e60-b307-11d1-b27d-006008c3fbfb"); pub const IID_ICanHandleException = &IID_ICanHandleException_Value; pub const ICanHandleException = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CanHandleException: fn( self: *const ICanHandleException, pExcepInfo: ?*EXCEPINFO, pvar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICanHandleException_CanHandleException(self: *const T, pExcepInfo: ?*EXCEPINFO, pvar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICanHandleException.VTable, self.vtable).CanHandleException(@ptrCast(*const ICanHandleException, self), pExcepInfo, pvar); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IProvideRuntimeContext_Value = @import("../zig.zig").Guid.initString("10e2414a-ec59-49d2-bc51-5add2c36febc"); pub const IID_IProvideRuntimeContext = &IID_IProvideRuntimeContext_Value; pub const IProvideRuntimeContext = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCurrentSourceContext: fn( self: *const IProvideRuntimeContext, pdwContext: ?*usize, pfExecutingGlobalCode: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvideRuntimeContext_GetCurrentSourceContext(self: *const T, pdwContext: ?*usize, pfExecutingGlobalCode: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IProvideRuntimeContext.VTable, self.vtable).GetCurrentSourceContext(@ptrCast(*const IProvideRuntimeContext, self), pdwContext, pfExecutingGlobalCode); } };} pub usingnamespace MethodMixin(@This()); }; pub const VARENUM = enum(i32) { EMPTY = 0, NULL = 1, I2 = 2, I4 = 3, R4 = 4, R8 = 5, CY = 6, DATE = 7, BSTR = 8, DISPATCH = 9, ERROR = 10, BOOL = 11, VARIANT = 12, UNKNOWN = 13, DECIMAL = 14, I1 = 16, UI1 = 17, UI2 = 18, UI4 = 19, I8 = 20, UI8 = 21, INT = 22, UINT = 23, VOID = 24, HRESULT = 25, PTR = 26, SAFEARRAY = 27, CARRAY = 28, USERDEFINED = 29, LPSTR = 30, LPWSTR = 31, RECORD = 36, INT_PTR = 37, UINT_PTR = 38, FILETIME = 64, BLOB = 65, STREAM = 66, STORAGE = 67, STREAMED_OBJECT = 68, STORED_OBJECT = 69, BLOB_OBJECT = 70, CF = 71, CLSID = 72, VERSIONED_STREAM = 73, BSTR_BLOB = 4095, VECTOR = 4096, ARRAY = 8192, BYREF = 16384, RESERVED = 32768, ILLEGAL = 65535, // ILLEGALMASKED = 4095, this enum value conflicts with BSTR_BLOB // TYPEMASK = 4095, this enum value conflicts with BSTR_BLOB }; pub const VT_EMPTY = VARENUM.EMPTY; pub const VT_NULL = VARENUM.NULL; pub const VT_I2 = VARENUM.I2; pub const VT_I4 = VARENUM.I4; pub const VT_R4 = VARENUM.R4; pub const VT_R8 = VARENUM.R8; pub const VT_CY = VARENUM.CY; pub const VT_DATE = VARENUM.DATE; pub const VT_BSTR = VARENUM.BSTR; pub const VT_DISPATCH = VARENUM.DISPATCH; pub const VT_ERROR = VARENUM.ERROR; pub const VT_BOOL = VARENUM.BOOL; pub const VT_VARIANT = VARENUM.VARIANT; pub const VT_UNKNOWN = VARENUM.UNKNOWN; pub const VT_DECIMAL = VARENUM.DECIMAL; pub const VT_I1 = VARENUM.I1; pub const VT_UI1 = VARENUM.UI1; pub const VT_UI2 = VARENUM.UI2; pub const VT_UI4 = VARENUM.UI4; pub const VT_I8 = VARENUM.I8; pub const VT_UI8 = VARENUM.UI8; pub const VT_INT = VARENUM.INT; pub const VT_UINT = VARENUM.UINT; pub const VT_VOID = VARENUM.VOID; pub const VT_HRESULT = VARENUM.HRESULT; pub const VT_PTR = VARENUM.PTR; pub const VT_SAFEARRAY = VARENUM.SAFEARRAY; pub const VT_CARRAY = VARENUM.CARRAY; pub const VT_USERDEFINED = VARENUM.USERDEFINED; pub const VT_LPSTR = VARENUM.LPSTR; pub const VT_LPWSTR = VARENUM.LPWSTR; pub const VT_RECORD = VARENUM.RECORD; pub const VT_INT_PTR = VARENUM.INT_PTR; pub const VT_UINT_PTR = VARENUM.UINT_PTR; pub const VT_FILETIME = VARENUM.FILETIME; pub const VT_BLOB = VARENUM.BLOB; pub const VT_STREAM = VARENUM.STREAM; pub const VT_STORAGE = VARENUM.STORAGE; pub const VT_STREAMED_OBJECT = VARENUM.STREAMED_OBJECT; pub const VT_STORED_OBJECT = VARENUM.STORED_OBJECT; pub const VT_BLOB_OBJECT = VARENUM.BLOB_OBJECT; pub const VT_CF = VARENUM.CF; pub const VT_CLSID = VARENUM.CLSID; pub const VT_VERSIONED_STREAM = VARENUM.VERSIONED_STREAM; pub const VT_BSTR_BLOB = VARENUM.BSTR_BLOB; pub const VT_VECTOR = VARENUM.VECTOR; pub const VT_ARRAY = VARENUM.ARRAY; pub const VT_BYREF = VARENUM.BYREF; pub const VT_RESERVED = VARENUM.RESERVED; pub const VT_ILLEGAL = VARENUM.ILLEGAL; pub const VT_ILLEGALMASKED = VARENUM.BSTR_BLOB; pub const VT_TYPEMASK = VARENUM.BSTR_BLOB; //-------------------------------------------------------------------------------- // Section: Functions (402) //-------------------------------------------------------------------------------- pub extern "OLEAUT32" fn BSTR_UserSize( param0: ?*u32, param1: u32, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn BSTR_UserMarshal( param0: ?*u32, param1: ?*u8, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn BSTR_UserUnmarshal( param0: ?*u32, param1: [*:0]u8, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn BSTR_UserFree( param0: ?*u32, param1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLE32" fn HWND_UserSize( param0: ?*u32, param1: u32, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLE32" fn HWND_UserMarshal( param0: ?*u32, param1: ?*u8, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn HWND_UserUnmarshal( param0: ?*u32, param1: [*:0]u8, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn HWND_UserFree( param0: ?*u32, param1: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn VARIANT_UserSize( param0: ?*u32, param1: u32, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn VARIANT_UserMarshal( param0: ?*u32, param1: ?*u8, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn VARIANT_UserUnmarshal( param0: ?*u32, param1: [*:0]u8, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn VARIANT_UserFree( param0: ?*u32, param1: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn BSTR_UserSize64( param0: ?*u32, param1: u32, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn BSTR_UserMarshal64( param0: ?*u32, param1: ?*u8, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn BSTR_UserUnmarshal64( param0: ?*u32, param1: [*:0]u8, param2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn BSTR_UserFree64( param0: ?*u32, param1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLE32" fn HWND_UserSize64( param0: ?*u32, param1: u32, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLE32" fn HWND_UserMarshal64( param0: ?*u32, param1: ?*u8, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn HWND_UserUnmarshal64( param0: ?*u32, param1: [*:0]u8, param2: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn HWND_UserFree64( param0: ?*u32, param1: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn VARIANT_UserSize64( param0: ?*u32, param1: u32, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn VARIANT_UserMarshal64( param0: ?*u32, param1: ?*u8, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn VARIANT_UserUnmarshal64( param0: ?*u32, param1: [*:0]u8, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn VARIANT_UserFree64( param0: ?*u32, param1: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn DosDateTimeToVariantTime( wDosDate: u16, wDosTime: u16, pvtime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "OLEAUT32" fn VariantTimeToDosDateTime( vtime: f64, pwDosDate: ?*u16, pwDosTime: ?*u16, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "OLEAUT32" fn SystemTimeToVariantTime( lpSystemTime: ?*SYSTEMTIME, pvtime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "OLEAUT32" fn VariantTimeToSystemTime( vtime: f64, lpSystemTime: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "OLEAUT32" fn SafeArrayAllocDescriptor( cDims: u32, ppsaOut: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayAllocDescriptorEx( vt: u16, cDims: u32, ppsaOut: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayAllocData( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayCreate( vt: u16, cDims: u32, rgsabound: ?*SAFEARRAYBOUND, ) callconv(@import("std").os.windows.WINAPI) ?*SAFEARRAY; pub extern "OLEAUT32" fn SafeArrayCreateEx( vt: u16, cDims: u32, rgsabound: ?*SAFEARRAYBOUND, pvExtra: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) ?*SAFEARRAY; pub extern "OLEAUT32" fn SafeArrayCopyData( psaSource: ?*SAFEARRAY, psaTarget: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn SafeArrayReleaseDescriptor( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn SafeArrayDestroyDescriptor( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn SafeArrayReleaseData( pData: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn SafeArrayDestroyData( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn SafeArrayAddRef( psa: ?*SAFEARRAY, ppDataToRelease: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayDestroy( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayRedim( psa: ?*SAFEARRAY, psaboundNew: ?*SAFEARRAYBOUND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetDim( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn SafeArrayGetElemsize( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn SafeArrayGetUBound( psa: ?*SAFEARRAY, nDim: u32, plUbound: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetLBound( psa: ?*SAFEARRAY, nDim: u32, plLbound: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayLock( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayUnlock( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayAccessData( psa: ?*SAFEARRAY, ppvData: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayUnaccessData( psa: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetElement( psa: ?*SAFEARRAY, rgIndices: ?*i32, pv: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayPutElement( psa: ?*SAFEARRAY, rgIndices: ?*i32, pv: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayCopy( psa: ?*SAFEARRAY, ppsaOut: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayPtrOfIndex( psa: ?*SAFEARRAY, rgIndices: ?*i32, ppvData: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArraySetRecordInfo( psa: ?*SAFEARRAY, prinfo: ?*IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetRecordInfo( psa: ?*SAFEARRAY, prinfo: ?*?*IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArraySetIID( psa: ?*SAFEARRAY, guid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetIID( psa: ?*SAFEARRAY, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayGetVartype( psa: ?*SAFEARRAY, pvt: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SafeArrayCreateVector( vt: u16, lLbound: i32, cElements: u32, ) callconv(@import("std").os.windows.WINAPI) ?*SAFEARRAY; pub extern "OLEAUT32" fn SafeArrayCreateVectorEx( vt: u16, lLbound: i32, cElements: u32, pvExtra: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) ?*SAFEARRAY; pub extern "OLEAUT32" fn VariantInit( pvarg: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn VariantClear( pvarg: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VariantCopy( pvargDest: ?*VARIANT, pvargSrc: ?*const VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VariantCopyInd( pvarDest: ?*VARIANT, pvargSrc: ?*const VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VariantChangeType( pvargDest: ?*VARIANT, pvarSrc: ?*const VARIANT, wFlags: u16, vt: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VariantChangeTypeEx( pvargDest: ?*VARIANT, pvarSrc: ?*const VARIANT, lcid: u32, wFlags: u16, vt: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VectorFromBstr( bstr: ?BSTR, ppsa: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn BstrFromVector( psa: ?*SAFEARRAY, pbstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromI2( sIn: i16, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromI4( lIn: i32, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromI8( i64In: i64, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromR4( fltIn: f32, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromR8( dblIn: f64, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromCy( cyIn: CY, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromDate( dateIn: f64, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromDisp( pdispIn: ?*IDispatch, lcid: u32, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromBool( boolIn: i16, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromI1( cIn: CHAR, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromUI2( uiIn: u16, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromUI4( ulIn: u32, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromUI8( ui64In: u64, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI1FromDec( pdecIn: ?*const DECIMAL, pbOut: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromUI1( bIn: u8, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromI4( lIn: i32, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromI8( i64In: i64, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromR4( fltIn: f32, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromR8( dblIn: f64, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromCy( cyIn: CY, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromDate( dateIn: f64, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromDisp( pdispIn: ?*IDispatch, lcid: u32, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromBool( boolIn: i16, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromI1( cIn: CHAR, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromUI2( uiIn: u16, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromUI4( ulIn: u32, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromUI8( ui64In: u64, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI2FromDec( pdecIn: ?*const DECIMAL, psOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromUI1( bIn: u8, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromI2( sIn: i16, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromI8( i64In: i64, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromR4( fltIn: f32, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromR8( dblIn: f64, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromCy( cyIn: CY, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromDate( dateIn: f64, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromDisp( pdispIn: ?*IDispatch, lcid: u32, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromBool( boolIn: i16, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromI1( cIn: CHAR, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromUI2( uiIn: u16, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromUI4( ulIn: u32, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromUI8( ui64In: u64, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI4FromDec( pdecIn: ?*const DECIMAL, plOut: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromUI1( bIn: u8, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromI2( sIn: i16, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromR4( fltIn: f32, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromR8( dblIn: f64, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromCy( cyIn: CY, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromDate( dateIn: f64, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromDisp( pdispIn: ?*IDispatch, lcid: u32, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromBool( boolIn: i16, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromI1( cIn: CHAR, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromUI2( uiIn: u16, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromUI4( ulIn: u32, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromUI8( ui64In: u64, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI8FromDec( pdecIn: ?*const DECIMAL, pi64Out: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromUI1( bIn: u8, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromI2( sIn: i16, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromI4( lIn: i32, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromI8( i64In: i64, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromR8( dblIn: f64, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromCy( cyIn: CY, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromDate( dateIn: f64, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromDisp( pdispIn: ?*IDispatch, lcid: u32, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromBool( boolIn: i16, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromI1( cIn: CHAR, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromUI2( uiIn: u16, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromUI4( ulIn: u32, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromUI8( ui64In: u64, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4FromDec( pdecIn: ?*const DECIMAL, pfltOut: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromUI1( bIn: u8, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromI2( sIn: i16, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromI4( lIn: i32, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromI8( i64In: i64, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromR4( fltIn: f32, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromCy( cyIn: CY, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromDate( dateIn: f64, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromDisp( pdispIn: ?*IDispatch, lcid: u32, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromBool( boolIn: i16, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromI1( cIn: CHAR, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromUI2( uiIn: u16, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromUI4( ulIn: u32, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromUI8( ui64In: u64, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8FromDec( pdecIn: ?*const DECIMAL, pdblOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUI1( bIn: u8, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromI2( sIn: i16, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromI4( lIn: i32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromI8( i64In: i64, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromR4( fltIn: f32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromR8( dblIn: f64, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromCy( cyIn: CY, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromDisp( pdispIn: ?*IDispatch, lcid: u32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromBool( boolIn: i16, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromI1( cIn: CHAR, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUI2( uiIn: u16, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUI4( ulIn: u32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUI8( ui64In: u64, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromDec( pdecIn: ?*const DECIMAL, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromUI1( bIn: u8, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromI2( sIn: i16, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromI4( lIn: i32, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromI8( i64In: i64, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromR4( fltIn: f32, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromR8( dblIn: f64, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromDate( dateIn: f64, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromDisp( pdispIn: ?*IDispatch, lcid: u32, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromBool( boolIn: i16, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromI1( cIn: CHAR, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromUI2( uiIn: u16, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromUI4( ulIn: u32, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromUI8( ui64In: u64, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFromDec( pdecIn: ?*const DECIMAL, pcyOut: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromUI1( bVal: u8, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromI2( iVal: i16, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromI4( lIn: i32, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromI8( i64In: i64, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromR4( fltIn: f32, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromR8( dblIn: f64, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromCy( cyIn: CY, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromDate( dateIn: f64, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromDisp( pdispIn: ?*IDispatch, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromBool( boolIn: i16, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromI1( cIn: CHAR, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromUI2( uiIn: u16, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromUI4( ulIn: u32, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromUI8( ui64In: u64, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrFromDec( pdecIn: ?*const DECIMAL, lcid: u32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromUI1( bIn: u8, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromI2( sIn: i16, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromI4( lIn: i32, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromI8( i64In: i64, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromR4( fltIn: f32, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromR8( dblIn: f64, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromDate( dateIn: f64, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromCy( cyIn: CY, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromDisp( pdispIn: ?*IDispatch, lcid: u32, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromI1( cIn: CHAR, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromUI2( uiIn: u16, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromUI4( ulIn: u32, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromUI8( i64In: u64, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBoolFromDec( pdecIn: ?*const DECIMAL, pboolOut: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromUI1( bIn: u8, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromI2( uiIn: i16, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromI4( lIn: i32, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromI8( i64In: i64, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromR4( fltIn: f32, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromR8( dblIn: f64, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromDate( dateIn: f64, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromCy( cyIn: CY, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromDisp( pdispIn: ?*IDispatch, lcid: u32, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromBool( boolIn: i16, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromUI2( uiIn: u16, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromUI4( ulIn: u32, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromUI8( i64In: u64, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarI1FromDec( pdecIn: ?*const DECIMAL, pcOut: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromUI1( bIn: u8, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromI2( uiIn: i16, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromI4( lIn: i32, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromI8( i64In: i64, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromR4( fltIn: f32, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromR8( dblIn: f64, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromDate( dateIn: f64, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromCy( cyIn: CY, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromDisp( pdispIn: ?*IDispatch, lcid: u32, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromBool( boolIn: i16, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromI1( cIn: CHAR, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromUI4( ulIn: u32, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromUI8( i64In: u64, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI2FromDec( pdecIn: ?*const DECIMAL, puiOut: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromUI1( bIn: u8, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromI2( uiIn: i16, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromI4( lIn: i32, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromI8( i64In: i64, plOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromR4( fltIn: f32, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromR8( dblIn: f64, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromDate( dateIn: f64, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromCy( cyIn: CY, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromDisp( pdispIn: ?*IDispatch, lcid: u32, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromBool( boolIn: i16, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromI1( cIn: CHAR, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromUI2( uiIn: u16, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromUI8( ui64In: u64, plOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI4FromDec( pdecIn: ?*const DECIMAL, pulOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromUI1( bIn: u8, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromI2( sIn: i16, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromI8( ui64In: i64, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromR4( fltIn: f32, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromR8( dblIn: f64, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromCy( cyIn: CY, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromDate( dateIn: f64, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromDisp( pdispIn: ?*IDispatch, lcid: u32, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromBool( boolIn: i16, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromI1( cIn: CHAR, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromUI2( uiIn: u16, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromUI4( ulIn: u32, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUI8FromDec( pdecIn: ?*const DECIMAL, pi64Out: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromUI1( bIn: u8, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromI2( uiIn: i16, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromI4( lIn: i32, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromI8( i64In: i64, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromR4( fltIn: f32, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromR8( dblIn: f64, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromDate( dateIn: f64, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromCy( cyIn: CY, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromDisp( pdispIn: ?*IDispatch, lcid: u32, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromBool( boolIn: i16, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromI1( cIn: CHAR, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromUI2( uiIn: u16, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromUI4( ulIn: u32, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFromUI8( ui64In: u64, pdecOut: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarParseNumFromStr( strIn: ?[*:0]const u16, lcid: u32, dwFlags: u32, pnumprs: ?*NUMPARSE, rgbDig: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarNumFromParseNum( pnumprs: ?*NUMPARSE, rgbDig: ?*u8, dwVtBits: u32, pvar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarAdd( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarAnd( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCat( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDiv( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarEqv( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarIdiv( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarImp( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarMod( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarMul( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarOr( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarPow( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarSub( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarXor( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarAbs( pvarIn: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFix( pvarIn: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarInt( pvarIn: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarNeg( pvarIn: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarNot( pvarIn: ?*VARIANT, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarRound( pvarIn: ?*VARIANT, cDecimals: i32, pvarResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCmp( pvarLeft: ?*VARIANT, pvarRight: ?*VARIANT, lcid: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecAdd( pdecLeft: ?*DECIMAL, pdecRight: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecDiv( pdecLeft: ?*DECIMAL, pdecRight: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecMul( pdecLeft: ?*DECIMAL, pdecRight: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecSub( pdecLeft: ?*DECIMAL, pdecRight: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecAbs( pdecIn: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecFix( pdecIn: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecInt( pdecIn: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecNeg( pdecIn: ?*DECIMAL, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecRound( pdecIn: ?*DECIMAL, cDecimals: i32, pdecResult: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecCmp( pdecLeft: ?*DECIMAL, pdecRight: ?*DECIMAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDecCmpR8( pdecLeft: ?*DECIMAL, dblRight: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyAdd( cyLeft: CY, cyRight: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyMul( cyLeft: CY, cyRight: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyMulI4( cyLeft: CY, lRight: i32, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyMulI8( cyLeft: CY, lRight: i64, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCySub( cyLeft: CY, cyRight: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyAbs( cyIn: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyFix( cyIn: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyInt( cyIn: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyNeg( cyIn: CY, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyRound( cyIn: CY, cDecimals: i32, pcyResult: ?*CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyCmp( cyLeft: CY, cyRight: CY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarCyCmpR8( cyLeft: CY, dblRight: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrCat( bstrLeft: ?BSTR, bstrRight: ?BSTR, pbstrResult: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarBstrCmp( bstrLeft: ?BSTR, bstrRight: ?BSTR, lcid: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8Pow( dblLeft: f64, dblRight: f64, pdblResult: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR4CmpR8( fltLeft: f32, dblRight: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarR8Round( dblIn: f64, cDecimals: i32, pdblResult: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUdate( pudateIn: ?*UDATE, dwFlags: u32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarDateFromUdateEx( pudateIn: ?*UDATE, lcid: u32, dwFlags: u32, pdateOut: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarUdateFromDate( dateIn: f64, dwFlags: u32, pudateOut: ?*UDATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn GetAltMonthNames( lcid: u32, prgp: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormat( pvarIn: ?*VARIANT, pstrFormat: ?PWSTR, iFirstDay: i32, iFirstWeek: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormatDateTime( pvarIn: ?*VARIANT, iNamedFormat: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormatNumber( pvarIn: ?*VARIANT, iNumDig: i32, iIncLead: i32, iUseParens: i32, iGroup: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormatPercent( pvarIn: ?*VARIANT, iNumDig: i32, iIncLead: i32, iUseParens: i32, iGroup: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormatCurrency( pvarIn: ?*VARIANT, iNumDig: i32, iIncLead: i32, iUseParens: i32, iGroup: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarWeekdayName( iWeekday: i32, fAbbrev: i32, iFirstDay: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarMonthName( iMonth: i32, fAbbrev: i32, dwFlags: u32, pbstrOut: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarFormatFromTokens( pvarIn: ?*VARIANT, pstrFormat: ?PWSTR, pbTokCur: ?*u8, dwFlags: u32, pbstrOut: ?*?BSTR, lcid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn VarTokenizeFormatString( pstrFormat: ?PWSTR, rgbTok: [*:0]u8, cbTok: i32, iFirstDay: i32, iFirstWeek: i32, lcid: u32, pcbActual: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn LHashValOfNameSysA( syskind: SYSKIND, lcid: u32, szName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn LHashValOfNameSys( syskind: SYSKIND, lcid: u32, szName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn LoadTypeLib( szFile: ?[*:0]const u16, pptlib: ?*?*ITypeLib, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn LoadTypeLibEx( szFile: ?[*:0]const u16, regkind: REGKIND, pptlib: ?*?*ITypeLib, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn LoadRegTypeLib( rguid: ?*const Guid, wVerMajor: u16, wVerMinor: u16, lcid: u32, pptlib: ?*?*ITypeLib, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn QueryPathOfRegTypeLib( guid: ?*const Guid, wMaj: u16, wMin: u16, lcid: u32, lpbstrPathName: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn RegisterTypeLib( ptlib: ?*ITypeLib, szFullPath: ?[*:0]const u16, szHelpDir: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn UnRegisterTypeLib( libID: ?*const Guid, wVerMajor: u16, wVerMinor: u16, lcid: u32, syskind: SYSKIND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn RegisterTypeLibForUser( ptlib: ?*ITypeLib, szFullPath: ?PWSTR, szHelpDir: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn UnRegisterTypeLibForUser( libID: ?*const Guid, wMajorVerNum: u16, wMinorVerNum: u16, lcid: u32, syskind: SYSKIND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn CreateTypeLib( syskind: SYSKIND, szFile: ?[*:0]const u16, ppctlib: ?*?*ICreateTypeLib, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn CreateTypeLib2( syskind: SYSKIND, szFile: ?[*:0]const u16, ppctlib: ?*?*ICreateTypeLib2, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn DispGetParam( pdispparams: ?*DISPPARAMS, position: u32, vtTarg: u16, pvarResult: ?*VARIANT, puArgErr: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn DispGetIDsOfNames( ptinfo: ?*ITypeInfo, rgszNames: [*]?PWSTR, cNames: u32, rgdispid: [*]i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn DispInvoke( _this: ?*c_void, ptinfo: ?*ITypeInfo, dispidMember: i32, wFlags: u16, pparams: ?*DISPPARAMS, pvarResult: ?*VARIANT, pexcepinfo: ?*EXCEPINFO, puArgErr: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn CreateDispTypeInfo( pidata: ?*INTERFACEDATA, lcid: u32, pptinfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn CreateStdDispatch( punkOuter: ?*IUnknown, pvThis: ?*c_void, ptinfo: ?*ITypeInfo, ppunkStdDisp: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn DispCallFunc( pvInstance: ?*c_void, oVft: usize, cc: CALLCONV, vtReturn: u16, cActuals: u32, prgvt: [*:0]u16, prgpvarg: [*]?*VARIANT, pvargResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn RegisterActiveObject( punk: ?*IUnknown, rclsid: ?*const Guid, dwFlags: u32, pdwRegister: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn RevokeActiveObject( dwRegister: u32, pvReserved: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn GetActiveObject( rclsid: ?*const Guid, pvReserved: ?*c_void, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn SetErrorInfo( dwReserved: u32, perrinfo: ?*IErrorInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn GetErrorInfo( dwReserved: u32, pperrinfo: ?*?*IErrorInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn CreateErrorInfo( pperrinfo: ?*?*ICreateErrorInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn GetRecordInfoFromTypeInfo( pTypeInfo: ?*ITypeInfo, ppRecInfo: ?*?*IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn GetRecordInfoFromGuids( rGuidTypeLib: ?*const Guid, uVerMajor: u32, uVerMinor: u32, lcid: u32, rGuidTypeInfo: ?*const Guid, ppRecInfo: ?*?*IRecordInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn OaBuildVersion( ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn ClearCustData( pCustData: ?*CUSTDATA, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn OaEnablePerUserTLibRegistration( ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLE32" fn STGMEDIUM_UserSize( param0: ?*u32, param1: u32, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLE32" fn STGMEDIUM_UserMarshal( param0: ?*u32, param1: ?*u8, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn STGMEDIUM_UserUnmarshal( param0: ?*u32, param1: [*:0]u8, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn STGMEDIUM_UserFree( param0: ?*u32, param1: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLE32" fn STGMEDIUM_UserSize64( param0: ?*u32, param1: u32, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLE32" fn STGMEDIUM_UserMarshal64( param0: ?*u32, param1: ?*u8, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn STGMEDIUM_UserUnmarshal64( param0: ?*u32, param1: [*:0]u8, param2: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLE32" fn STGMEDIUM_UserFree64( param0: ?*u32, param1: ?*STGMEDIUM, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "OLEAUT32" fn OleLoadPictureFile( varFileName: VARIANT, lplpdispPicture: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn OleLoadPictureFileEx( varFileName: VARIANT, xSizeDesired: u32, ySizeDesired: u32, dwFlags: u32, lplpdispPicture: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn OleSavePictureFile( lpdispPicture: ?*IDispatch, bstrFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "OLEAUT32" fn LPSAFEARRAY_UserSize( param0: ?*u32, param1: u32, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "OLEAUT32" fn LPSAFEARRAY_UserMarshal( param0: ?*u32, param1: ?*u8, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn LPSAFEARRAY_UserUnmarshal( param0: ?*u32, param1: [*:0]u8, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) ?*u8; pub extern "OLEAUT32" fn LPSAFEARRAY_UserFree( param0: ?*u32, param1: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn LPSAFEARRAY_UserSize64( param0: ?*u32, param1: u32, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn LPSAFEARRAY_UserMarshal64( param0: ?*u32, param1: ?*u8, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn LPSAFEARRAY_UserUnmarshal64( param0: ?*u32, param1: [*:0]u8, param2: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "OLEAUT32" fn LPSAFEARRAY_UserFree64( param0: ?*u32, param1: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (20) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const BYTE_SIZEDARR = @import("../system/com.zig").BYTE_SIZEDARR; const CHAR = @import("../system/system_services.zig").CHAR; const CY = @import("../system/system_services.zig").CY; const DECIMAL = @import("../system/system_services.zig").DECIMAL; const FLAGGED_WORD_BLOB = @import("../system/com.zig").FLAGGED_WORD_BLOB; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const HYPER_SIZEDARR = @import("../system/com.zig").HYPER_SIZEDARR; const IEnumUnknown = @import("../system/com.zig").IEnumUnknown; const IServiceProvider = @import("../system/system_services.zig").IServiceProvider; const IUnknown = @import("../system/com.zig").IUnknown; const LONG_SIZEDARR = @import("../system/com.zig").LONG_SIZEDARR; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SHORT_SIZEDARR = @import("../system/com.zig").SHORT_SIZEDARR; const STGMEDIUM = @import("../system/com.zig").STGMEDIUM; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPEXCEPFINO_DEFERRED_FILLIN")) { _ = LPEXCEPFINO_DEFERRED_FILLIN; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/system/ole_automation.zig
const print = @import("std").debug.print; const assert = @import("std").debug.assert; const CPU = @import("emu").CPU; const MREQ = CPU.MREQ; const IORQ = CPU.IORQ; const RD = CPU.RD; const WR = CPU.WR; const HALT = CPU.HALT; const INT = CPU.INT; const M1 = CPU.M1; const RETI = CPU.RETI; const B = CPU.B; const C = CPU.C; const D = CPU.D; const E = CPU.E; const H = CPU.H; const L = CPU.L; const F = CPU.F; const A = CPU.A; const BC = CPU.BC; const DE = CPU.DE; const HL = CPU.HL; const FA = CPU.FA; const CF = CPU.CF; const NF = CPU.NF; const VF = CPU.VF; const PF = CPU.PF; const XF = CPU.XF; const HF = CPU.HF; const YF = CPU.YF; const ZF = CPU.ZF; const SF = CPU.SF; // 64 KB memory var mem = [_]u8{0} ** 0x10000; var out_port: u16 = 0; var out_byte: u8 = 0; fn T(cond: bool) void { assert(cond); } fn start(name: []const u8) void { print("=> {s} ... ", .{name}); } fn ok() void { print("OK\n", .{}); } // tick callback which handles memory and IO requests fn tick(num_ticks: usize, pins_in: u64, userdata: usize) u64 { _ = num_ticks; _ = userdata; var pins = pins_in; if ((pins & MREQ) != 0) { if ((pins & RD) != 0) { // a memory read access pins = CPU.setData(pins, mem[CPU.getAddr(pins)]); } else if ((pins & WR) != 0) { // a memory write access mem[CPU.getAddr(pins)] = CPU.getData(pins); } } else if ((pins & IORQ) != 0) { if ((pins & RD) != 0) { // an IO input access (just write the port * 2 back) pins = CPU.setData(pins, @truncate(u8, CPU.getAddr(pins)) *% 2); } else if ((pins & WR) != 0) { // an IO output access out_port = CPU.getAddr(pins); out_byte = CPU.getData(pins); } } return pins; } fn mem16(addr: u16) u16 { const l = mem[addr]; const h = mem[addr +% 1]; return @as(u16,h)<<8 | l; } fn w16(addr: u16, data: u16) void { mem[addr] = @truncate(u8, data); mem[addr +% 1] = @truncate(u8, data >> 8); } fn makeCPU() CPU { var cpu = CPU{ }; cpu.regs[A] = 0xFF; cpu.regs[F] = 0x00; cpu.ex[FA] = 0x00FF; return cpu; } fn copy(start_addr: u16, bytes: []const u8) void { var addr: u16 = start_addr; for (bytes) |byte| { mem[addr] = byte; addr +%= 1; } } fn step(cpu: *CPU) usize { var ticks = cpu.exec(0, .{ .func=tick, .userdata=0 }); while (!cpu.opdone()) { ticks += cpu.exec(0, .{ .func=tick, .userdata=0 }); } return ticks; } fn skip(cpu: *CPU, steps: usize) void { var i: usize = 0; while (i < steps): (i += 1) { _ = step(cpu); } } fn flags(cpu: *CPU, expected: u8) bool { return (cpu.regs[F] & ~(XF|YF)) == expected; } fn LD_A_RI() void { start("LD A,R/I"); const prog = [_]u8 { 0xED, 0x57, // LD A,I 0x97, // SUB A 0xED, 0x5F, // LD A,R }; copy(0x0000, &prog); var cpu = makeCPU(); cpu.iff1 = true; cpu.iff2 = true; cpu.R = 0x34; cpu.I = 0x01; cpu.regs[F] = CF; T(9 == step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, PF|CF)); T(4 == step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(9 == step(&cpu)); T(0x39 == cpu.regs[A]); T(flags(&cpu, PF)); ok(); } fn LD_IR_A() void { start("LD I/R,A"); const prog = [_]u8 { 0x3E, 0x45, // LD A,0x45 0xED, 0x47, // LD I,A 0xED, 0x4F, // LD R,A }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x45 == cpu.regs[A]); T(9==step(&cpu)); T(0x45 == cpu.I); T(9==step(&cpu)); T(0x45 == cpu.R); ok(); } fn LD_r_sn() void { start("LD r,sn"); const prog = [_]u8 { 0x3E, 0x12, // LD A,0x12 0x47, // LD B,A 0x4F, // LD C,A 0x57, // LD D,A 0x5F, // LD E,A 0x67, // LD H,A 0x6F, // LD L,A 0x7F, // LD A,A 0x06, 0x13, // LD B,0x13 0x40, // LD B,B 0x48, // LD C,B 0x50, // LD D,B 0x58, // LD E,B 0x60, // LD H,B 0x68, // LD L,B 0x78, // LD A,B 0x0E, 0x14, // LD C,0x14 0x41, // LD B,C 0x49, // LD C,C 0x51, // LD D,C 0x59, // LD E,C 0x61, // LD H,C 0x69, // LD L,C 0x79, // LD A,C 0x16, 0x15, // LD D,0x15 0x42, // LD B,D 0x4A, // LD C,D 0x52, // LD D,D 0x5A, // LD E,D 0x62, // LD H,D 0x6A, // LD L,D 0x7A, // LD A,D 0x1E, 0x16, // LD E,0x16 0x43, // LD B,E 0x4B, // LD C,E 0x53, // LD D,E 0x5B, // LD E,E 0x63, // LD H,E 0x6B, // LD L,E 0x7B, // LD A,E 0x26, 0x17, // LD H,0x17 0x44, // LD B,H 0x4C, // LD C,H 0x54, // LD D,H 0x5C, // LD E,H 0x64, // LD H,H 0x6C, // LD L,H 0x7C, // LD A,H 0x2E, 0x18, // LD L,0x18 0x45, // LD B,L 0x4D, // LD C,L 0x55, // LD D,L 0x5D, // LD E,L 0x65, // LD H,L 0x6D, // LD L,L 0x7D, // LD A,L }; copy(0x0000, &prog); var cpu = makeCPU(); T(step(&cpu) == 7); T(cpu.regs[A] == 0x12); T(step(&cpu) == 4); T(cpu.regs[B] == 0x12); T(step(&cpu) == 4); T(cpu.regs[C] == 0x12); T(step(&cpu) == 4); T(cpu.regs[D] == 0x12); T(step(&cpu) == 4); T(cpu.regs[E] == 0x12); T(step(&cpu) == 4); T(cpu.regs[H] == 0x12); T(step(&cpu) == 4); T(cpu.regs[L] == 0x12); T(step(&cpu) == 4); T(cpu.regs[A] == 0x12); T(step(&cpu) == 7); T(cpu.regs[B] == 0x13); T(step(&cpu) == 4); T(cpu.regs[B] == 0x13); T(step(&cpu) == 4); T(cpu.regs[C] == 0x13); T(step(&cpu) == 4); T(cpu.regs[D] == 0x13); T(step(&cpu) == 4); T(cpu.regs[E] == 0x13); T(step(&cpu) == 4); T(cpu.regs[H] == 0x13); T(step(&cpu) == 4); T(cpu.regs[L] == 0x13); T(step(&cpu) == 4); T(cpu.regs[A] == 0x13); T(step(&cpu) == 7); T(cpu.regs[C] == 0x14); T(step(&cpu) == 4); T(cpu.regs[B] == 0x14); T(step(&cpu) == 4); T(cpu.regs[C] == 0x14); T(step(&cpu) == 4); T(cpu.regs[D] == 0x14); T(step(&cpu) == 4); T(cpu.regs[E] == 0x14); T(step(&cpu) == 4); T(cpu.regs[H] == 0x14); T(step(&cpu) == 4); T(cpu.regs[L] == 0x14); T(step(&cpu) == 4); T(cpu.regs[A] == 0x14); T(step(&cpu) == 7); T(cpu.regs[D] == 0x15); T(step(&cpu) == 4); T(cpu.regs[B] == 0x15); T(step(&cpu) == 4); T(cpu.regs[C] == 0x15); T(step(&cpu) == 4); T(cpu.regs[D] == 0x15); T(step(&cpu) == 4); T(cpu.regs[E] == 0x15); T(step(&cpu) == 4); T(cpu.regs[H] == 0x15); T(step(&cpu) == 4); T(cpu.regs[L] == 0x15); T(step(&cpu) == 4); T(cpu.regs[A] == 0x15); T(step(&cpu) == 7); T(cpu.regs[E] == 0x16); T(step(&cpu) == 4); T(cpu.regs[B] == 0x16); T(step(&cpu) == 4); T(cpu.regs[C] == 0x16); T(step(&cpu) == 4); T(cpu.regs[D] == 0x16); T(step(&cpu) == 4); T(cpu.regs[E] == 0x16); T(step(&cpu) == 4); T(cpu.regs[H] == 0x16); T(step(&cpu) == 4); T(cpu.regs[L] == 0x16); T(step(&cpu) == 4); T(cpu.regs[A] == 0x16); T(step(&cpu) == 7); T(cpu.regs[H] == 0x17); T(step(&cpu) == 4); T(cpu.regs[B] == 0x17); T(step(&cpu) == 4); T(cpu.regs[C] == 0x17); T(step(&cpu) == 4); T(cpu.regs[D] == 0x17); T(step(&cpu) == 4); T(cpu.regs[E] == 0x17); T(step(&cpu) == 4); T(cpu.regs[H] == 0x17); T(step(&cpu) == 4); T(cpu.regs[L] == 0x17); T(step(&cpu) == 4); T(cpu.regs[A] == 0x17); T(step(&cpu) == 7); T(cpu.regs[L] == 0x18); T(step(&cpu) == 4); T(cpu.regs[B] == 0x18); T(step(&cpu) == 4); T(cpu.regs[C] == 0x18); T(step(&cpu) == 4); T(cpu.regs[D] == 0x18); T(step(&cpu) == 4); T(cpu.regs[E] == 0x18); T(step(&cpu) == 4); T(cpu.regs[H] == 0x18); T(step(&cpu) == 4); T(cpu.regs[L] == 0x18); T(step(&cpu) == 4); T(cpu.regs[A] == 0x18); ok(); } fn LD_r_iHLi() void { start("LD r,(HL)"); const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0x3E, 0x33, // LD A,0x33 0x77, // LD (HL),A 0x3E, 0x22, // LD A,0x22 0x46, // LD B,(HL) 0x4E, // LD C,(HL) 0x56, // LD D,(HL) 0x5E, // LD E,(HL) 0x66, // LD H,(HL) 0x26, 0x10, // LD H,0x10 0x6E, // LD L,(HL) 0x2E, 0x00, // LD L,0x00 0x7E, // LD A,(HL) }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(7==step(&cpu)); T(0x33 == cpu.regs[A]); T(7==step(&cpu)); T(0x33 == mem[0x1000]); T(7==step(&cpu)); T(0x22 == cpu.regs[A]); T(7==step(&cpu)); T(0x33 == cpu.regs[B]); T(7==step(&cpu)); T(0x33 == cpu.regs[C]); T(7==step(&cpu)); T(0x33 == cpu.regs[D]); T(7==step(&cpu)); T(0x33 == cpu.regs[E]); T(7==step(&cpu)); T(0x33 == cpu.regs[H]); T(7==step(&cpu)); T(0x10 == cpu.regs[H]); T(7==step(&cpu)); T(0x33 == cpu.regs[L]); T(7==step(&cpu)); T(0x00 == cpu.regs[L]); T(7==step(&cpu)); T(0x33 == cpu.regs[A]); ok(); } fn LD_iHLi_r() void { start("LD (HL),r"); const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0x3E, 0x12, // LD A,0x12 0x77, // LD (HL),A 0x06, 0x13, // LD B,0x13 0x70, // LD (HL),B 0x0E, 0x14, // LD C,0x14 0x71, // LD (HL),C 0x16, 0x15, // LD D,0x15 0x72, // LD (HL),D 0x1E, 0x16, // LD E,0x16 0x73, // LD (HL),E 0x74, // LD (HL),H 0x75, // LD (HL),L }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(7==step(&cpu)); T(0x12 == cpu.regs[A]); T(7==step(&cpu)); T(0x12 == mem[0x1000]); T(7==step(&cpu)); T(0x13 == cpu.regs[B]); T(7==step(&cpu)); T(0x13 == mem[0x1000]); T(7==step(&cpu)); T(0x14 == cpu.regs[C]); T(7==step(&cpu)); T(0x14 == mem[0x1000]); T(7==step(&cpu)); T(0x15 == cpu.regs[D]); T(7==step(&cpu)); T(0x15 == mem[0x1000]); T(7==step(&cpu)); T(0x16 == cpu.regs[E]); T(7==step(&cpu)); T(0x16 == mem[0x1000]); T(7==step(&cpu)); T(0x10 == mem[0x1000]); T(7==step(&cpu)); T(0x00 == mem[0x1000]); ok(); } fn LD_iHLi_n() void { start("LD (HL),n"); const prog = [_]u8 { 0x21, 0x00, 0x20, // LD HL,0x2000 0x36, 0x33, // LD (HL),0x33 0x21, 0x00, 0x10, // LD HL,0x1000 0x36, 0x65, // LD (HL),0x65 }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x2000 == cpu.r16(HL)); T(10==step(&cpu)); T(0x33 == mem[0x2000]); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(10==step(&cpu)); T(0x65 == mem[0x1000]); ok(); } fn LD_iIXIYi_r() void { start("LD (IX/IY+d),r"); const prog = [_]u8 { 0xDD, 0x21, 0x03, 0x10, // LD IX,0x1003 0x3E, 0x12, // LD A,0x12 0xDD, 0x77, 0x00, // LD (IX+0),A 0x06, 0x13, // LD B,0x13 0xDD, 0x70, 0x01, // LD (IX+1),B 0x0E, 0x14, // LD C,0x14 0xDD, 0x71, 0x02, // LD (IX+2),C 0x16, 0x15, // LD D,0x15 0xDD, 0x72, 0xFF, // LD (IX-1),D 0x1E, 0x16, // LD E,0x16 0xDD, 0x73, 0xFE, // LD (IX-2),E 0x26, 0x17, // LD H,0x17 0xDD, 0x74, 0x03, // LD (IX+3),H 0x2E, 0x18, // LD L,0x18 0xDD, 0x75, 0xFD, // LD (IX-3),L 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x12, // LD A,0x12 0xFD, 0x77, 0x00, // LD (IY+0),A 0x06, 0x13, // LD B,0x13 0xFD, 0x70, 0x01, // LD (IY+1),B 0x0E, 0x14, // LD C,0x14 0xFD, 0x71, 0x02, // LD (IY+2),C 0x16, 0x15, // LD D,0x15 0xFD, 0x72, 0xFF, // LD (IY-1),D 0x1E, 0x16, // LD E,0x16 0xFD, 0x73, 0xFE, // LD (IY-2),E 0x26, 0x17, // LD H,0x17 0xFD, 0x74, 0x03, // LD (IY+3),H 0x2E, 0x18, // LD L,0x18 0xFD, 0x75, 0xFD, // LD (IY-3),L }; copy(0x0000, &prog); var cpu = makeCPU(); T(14==step(&cpu)); T(0x1003 == cpu.IX); T(7 ==step(&cpu)); T(0x12 == cpu.regs[A]); T(19==step(&cpu)); T(0x12 == mem[0x1003]); T(0x1003 == cpu.WZ); T(7 ==step(&cpu)); T(0x13 == cpu.regs[B]); T(19==step(&cpu)); T(0x13 == mem[0x1004]); T(0x1004 == cpu.WZ); T(7 ==step(&cpu)); T(0x14 == cpu.regs[C]); T(19==step(&cpu)); T(0x14 == mem[0x1005]); T(0x1005 == cpu.WZ); T(7 ==step(&cpu)); T(0x15 == cpu.regs[D]); T(19==step(&cpu)); T(0x15 == mem[0x1002]); T(0x1002 == cpu.WZ); T(7 ==step(&cpu)); T(0x16 == cpu.regs[E]); T(19==step(&cpu)); T(0x16 == mem[0x1001]); T(7 ==step(&cpu)); T(0x17 == cpu.regs[H]); T(19==step(&cpu)); T(0x17 == mem[0x1006]); T(7 ==step(&cpu)); T(0x18 == cpu.regs[L]); T(19==step(&cpu)); T(0x18 == mem[0x1000]); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x12 == cpu.regs[A]); T(19==step(&cpu)); T(0x12 == mem[0x1003]); T(7 ==step(&cpu)); T(0x13 == cpu.regs[B]); T(19==step(&cpu)); T(0x13 == mem[0x1004]); T(7 ==step(&cpu)); T(0x14 == cpu.regs[C]); T(19==step(&cpu)); T(0x14 == mem[0x1005]); T(7 ==step(&cpu)); T(0x15 == cpu.regs[D]); T(19==step(&cpu)); T(0x15 == mem[0x1002]); T(7 ==step(&cpu)); T(0x16 == cpu.regs[E]); T(19==step(&cpu)); T(0x16 == mem[0x1001]); T(7 ==step(&cpu)); T(0x17 == cpu.regs[H]); T(19==step(&cpu)); T(0x17 == mem[0x1006]); T(7 ==step(&cpu)); T(0x18 == cpu.regs[L]); T(19==step(&cpu)); T(0x18 == mem[0x1000]); ok(); } fn LD_iIXIYi_n() void { start("LD (IX/IY+d),n"); const prog = [_]u8 { 0xDD, 0x21, 0x00, 0x20, // LD IX,0x2000 0xDD, 0x36, 0x02, 0x33, // LD (IX+2),0x33 0xDD, 0x36, 0xFE, 0x11, // LD (IX-2),0x11 0xFD, 0x21, 0x00, 0x10, // LD IY,0x1000 0xFD, 0x36, 0x01, 0x22, // LD (IY+1),0x22 0xFD, 0x36, 0xFF, 0x44, // LD (IY-1),0x44 }; copy(0x0000, &prog); var cpu = makeCPU(); T(14==step(&cpu)); T(0x2000 == cpu.IX); T(19==step(&cpu)); T(0x33 == mem[0x2002]); T(19==step(&cpu)); T(0x11 == mem[0x1FFE]); T(14==step(&cpu)); T(0x1000 == cpu.IY); T(19==step(&cpu)); T(0x22 == mem[0x1001]); T(19==step(&cpu)); T(0x44 == mem[0x0FFF]); ok(); } fn LD_ddIXIY_nn() void { start("LD dd/IX/IY,nn"); const prog = [_]u8 { 0x01, 0x34, 0x12, // LD BC,0x1234 0x11, 0x78, 0x56, // LD DE,0x5678 0x21, 0xBC, 0x9A, // LD HL,0x9ABC 0x31, 0x68, 0x13, // LD SP,0x1368 0xDD, 0x21, 0x21, 0x43, // LD IX,0x4321 0xFD, 0x21, 0x65, 0x87, // LD IY,0x8765 }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1234 == cpu.r16(BC)); T(10==step(&cpu)); T(0x5678 == cpu.r16(DE)); T(10==step(&cpu)); T(0x9ABC == cpu.r16(HL)); T(10==step(&cpu)); T(0x1368 == cpu.SP); T(14==step(&cpu)); T(0x4321 == cpu.IX); T(14==step(&cpu)); T(0x8765 == cpu.IY); ok(); } fn LD_A_iBCDEnni() void { start("LD A,(BC/DE/nn)"); const data = [_]u8 { 0x11, 0x22, 0x33 }; const prog = [_]u8 { 0x01, 0x00, 0x10, // LD BC,0x1000 0x11, 0x01, 0x10, // LD DE,0x1001 0x0A, // LD A,(BC) 0x1A, // LD A,(DE) 0x3A, 0x02, 0x10, // LD A,(0x1002) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(BC)); T(10==step(&cpu)); T(0x1001 == cpu.r16(DE)); T(7 ==step(&cpu)); T(0x11 == cpu.regs[A]); T(0x1001 == cpu.WZ); T(7 ==step(&cpu)); T(0x22 == cpu.regs[A]); T(0x1002 == cpu.WZ); T(13==step(&cpu)); T(0x33 == cpu.regs[A]); T(0x1003 == cpu.WZ); ok(); } fn LD_iBCDEnni_A() void { start("LD (BC/DE/nn),A"); const prog = [_]u8 { 0x01, 0x00, 0x10, // LD BC,0x1000 0x11, 0x01, 0x10, // LD DE,0x1001 0x3E, 0x77, // LD A,0x77 0x02, // LD (BC),A 0x12, // LD (DE),A 0x32, 0x02, 0x10, // LD (0x1002),A }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(BC)); T(10==step(&cpu)); T(0x1001 == cpu.r16(DE)); T(7 ==step(&cpu)); T(0x77 == cpu.regs[A]); T(7 ==step(&cpu)); T(0x77 == mem[0x1000]); T(0x7701 == cpu.WZ); T(7 ==step(&cpu)); T(0x77 == mem[0x1001]); T(0x7702 == cpu.WZ); T(13==step(&cpu)); T(0x77 == mem[0x1002]); T(0x7703 == cpu.WZ); ok(); } fn LD_HLddIXIY_inni() void { start("LD dd/IX/IY,(nn)"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; const prog = [_]u8 { 0x2A, 0x00, 0x10, // LD HL,(0x1000) 0xED, 0x4B, 0x01, 0x10, // LD BC,(0x1001) 0xED, 0x5B, 0x02, 0x10, // LD DE,(0x1002) 0xED, 0x6B, 0x03, 0x10, // LD HL,(0x1003) undocumented 'long' version 0xED, 0x7B, 0x04, 0x10, // LD SP,(0x1004) 0xDD, 0x2A, 0x05, 0x10, // LD IX,(0x1005) 0xFD, 0x2A, 0x06, 0x10, // LD IY,(0x1006) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(16==step(&cpu)); T(0x0201 == cpu.r16(HL)); T(0x1001 == cpu.WZ); T(20==step(&cpu)); T(0x0302 == cpu.r16(BC)); T(0x1002 == cpu.WZ); T(20==step(&cpu)); T(0x0403 == cpu.r16(DE)); T(0x1003 == cpu.WZ); T(20==step(&cpu)); T(0x0504 == cpu.r16(HL)); T(0x1004 == cpu.WZ); T(20==step(&cpu)); T(0x0605 == cpu.SP); T(0x1005 == cpu.WZ); T(20==step(&cpu)); T(0x0706 == cpu.IX); T(0x1006 == cpu.WZ); T(20==step(&cpu)); T(0x0807 == cpu.IY); T(0x1007 == cpu.WZ); ok(); } fn LD_inni_HLddIXIY() void { start("LD (nn),dd/IX/IY"); const prog = [_]u8 { 0x21, 0x01, 0x02, // LD HL,0x0201 0x22, 0x00, 0x10, // LD (0x1000),HL 0x01, 0x34, 0x12, // LD BC,0x1234 0xED, 0x43, 0x02, 0x10, // LD (0x1002),BC 0x11, 0x78, 0x56, // LD DE,0x5678 0xED, 0x53, 0x04, 0x10, // LD (0x1004),DE 0x21, 0xBC, 0x9A, // LD HL,0x9ABC 0xED, 0x63, 0x06, 0x10, // LD (0x1006),HL undocumented 'long' version 0x31, 0x68, 0x13, // LD SP,0x1368 0xED, 0x73, 0x08, 0x10, // LD (0x1008),SP 0xDD, 0x21, 0x21, 0x43, // LD IX,0x4321 0xDD, 0x22, 0x0A, 0x10, // LD (0x100A),IX 0xFD, 0x21, 0x65, 0x87, // LD IY,0x8765 0xFD, 0x22, 0x0C, 0x10, // LD (0x100C),IY }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x0201 == cpu.r16(HL)); T(16==step(&cpu)); T(0x0201 == mem16(0x1000)); T(0x1001 == cpu.WZ); T(10==step(&cpu)); T(0x1234 == cpu.r16(BC)); T(20==step(&cpu)); T(0x1234 == mem16(0x1002)); T(0x1003 == cpu.WZ); T(10==step(&cpu)); T(0x5678 == cpu.r16(DE)); T(20==step(&cpu)); T(0x5678 == mem16(0x1004)); T(0x1005 == cpu.WZ); T(10==step(&cpu)); T(0x9ABC == cpu.r16(HL)); T(20==step(&cpu)); T(0x9ABC == mem16(0x1006)); T(0x1007 == cpu.WZ); T(10==step(&cpu)); T(0x1368 == cpu.SP); T(20==step(&cpu)); T(0x1368 == mem16(0x1008)); T(0x1009 == cpu.WZ); T(14==step(&cpu)); T(0x4321 == cpu.IX); T(20==step(&cpu)); T(0x4321 == mem16(0x100A)); T(0x100B == cpu.WZ); T(14==step(&cpu)); T(0x8765 == cpu.IY); T(20==step(&cpu)); T(0x8765 == mem16(0x100C)); T(0x100D == cpu.WZ); ok(); } fn LD_SP_HLIXIY() void { start("LD SP,HL/IX/IY"); const prog = [_]u8{ 0x21, 0x34, 0x12, // LD HL,0x1234 0xDD, 0x21, 0x78, 0x56, // LD IX,0x5678 0xFD, 0x21, 0xBC, 0x9A, // LD IY,0x9ABC 0xF9, // LD SP,HL 0xDD, 0xF9, // LD SP,IX 0xFD, 0xF9, // LD SP,IY }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1234 == cpu.r16(HL)); T(14==step(&cpu)); T(0x5678 == cpu.IX); T(14==step(&cpu)); T(0x9ABC == cpu.IY); T(6 ==step(&cpu)); T(0x1234 == cpu.SP); T(10==step(&cpu)); T(0x5678 == cpu.SP); T(10==step(&cpu)); T(0x9ABC == cpu.SP); ok(); } fn PUSH_POP_qqIXIY() void { start("PUSH/POP qqIXIY"); const prog = [_]u8 { 0x01, 0x34, 0x12, // LD BC,0x1234 0x11, 0x78, 0x56, // LD DE,0x5678 0x21, 0xBC, 0x9A, // LD HL,0x9ABC 0x3E, 0xEF, // LD A,0xEF 0xDD, 0x21, 0x45, 0x23, // LD IX,0x2345 0xFD, 0x21, 0x89, 0x67, // LD IY,0x6789 0x31, 0x00, 0x01, // LD SP,0x0100 0xF5, // PUSH AF 0xC5, // PUSH BC 0xD5, // PUSH DE 0xE5, // PUSH HL 0xDD, 0xE5, // PUSH IX 0xFD, 0xE5, // PUSH IY 0xF1, // POP AF 0xC1, // POP BC 0xD1, // POP DE 0xE1, // POP HL 0xDD, 0xE1, // POP IX 0xFD, 0xE1, // POP IY }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1234 == cpu.r16(BC)); T(10==step(&cpu)); T(0x5678 == cpu.r16(DE)); T(10==step(&cpu)); T(0x9ABC == cpu.r16(HL)); T(7 ==step(&cpu)); T(0x00EF == cpu.r16(FA)); T(14==step(&cpu)); T(0x2345 == cpu.IX); T(14==step(&cpu)); T(0x6789 == cpu.IY); T(10==step(&cpu)); T(0x0100 == cpu.SP); T(11==step(&cpu)); T(0xEF00 == mem16(0x00FE)); T(0x00FE == cpu.SP); T(11==step(&cpu)); T(0x1234 == mem16(0x00FC)); T(0x00FC == cpu.SP); T(11==step(&cpu)); T(0x5678 == mem16(0x00FA)); T(0x00FA == cpu.SP); T(11==step(&cpu)); T(0x9ABC == mem16(0x00F8)); T(0x00F8 == cpu.SP); T(15==step(&cpu)); T(0x2345 == mem16(0x00F6)); T(0x00F6 == cpu.SP); T(15==step(&cpu)); T(0x6789 == mem16(0x00F4)); T(0x00F4 == cpu.SP); T(10==step(&cpu)); T(0x8967 == cpu.r16(FA)); T(0x00F6 == cpu.SP); T(10==step(&cpu)); T(0x2345 == cpu.r16(BC)); T(0x00F8 == cpu.SP); T(10==step(&cpu)); T(0x9ABC == cpu.r16(DE)); T(0x00FA == cpu.SP); T(10==step(&cpu)); T(0x5678 == cpu.r16(HL)); T(0x00FC == cpu.SP); T(14==step(&cpu)); T(0x1234 == cpu.IX); T(0x00FE == cpu.SP); T(14==step(&cpu)); T(0xEF00 == cpu.IY); T(0x0100 == cpu.SP); ok(); } fn EX() void { start("EX"); const prog = [_]u8 { 0x21, 0x34, 0x12, // LD HL,0x1234 0x11, 0x78, 0x56, // LD DE,0x5678 0xEB, // EX DE,HL 0x3E, 0x11, // LD A,0x11 0x08, // EX AF,AF' 0x3E, 0x22, // LD A,0x22 0x08, // EX AF,AF' 0x01, 0xBC, 0x9A, // LD BC,0x9ABC 0xD9, // EXX 0x21, 0x11, 0x11, // LD HL,0x1111 0x11, 0x22, 0x22, // LD DE,0x2222 0x01, 0x33, 0x33, // LD BC,0x3333 0xD9, // EXX 0x31, 0x00, 0x01, // LD SP,0x0100 0xD5, // PUSH DE 0xE3, // EX (SP),HL 0xDD, 0x21, 0x99, 0x88, // LD IX,0x8899 0xDD, 0xE3, // EX (SP),IX 0xFD, 0x21, 0x77, 0x66, // LD IY,0x6677 0xFD, 0xE3, // EX (SP),IY }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1234 == cpu.r16(HL)); T(10==step(&cpu)); T(0x5678 == cpu.r16(DE)); T(4 ==step(&cpu)); T(0x1234 == cpu.r16(DE)); T(0x5678 == cpu.r16(HL)); T(7 ==step(&cpu)); T(0x0011 == cpu.r16(FA)); T(0x00FF == cpu.ex[FA]); T(4 ==step(&cpu)); T(0x00FF == cpu.r16(FA)); T(0x0011 == cpu.ex[FA]); T(7 ==step(&cpu)); T(0x0022 == cpu.r16(FA)); T(0x0011 == cpu.ex[FA]); T(4 ==step(&cpu)); T(0x0011 == cpu.r16(FA)); T(0x0022 == cpu.ex[FA]); T(10==step(&cpu)); T(0x9ABC == cpu.r16(BC)); T(4 ==step(&cpu)); T(0xFFFF == cpu.r16(HL)); T(0x5678 == cpu.ex[HL]); T(0xFFFF == cpu.r16(DE)); T(0x1234 == cpu.ex[DE]); T(0xFFFF == cpu.r16(BC)); T(0x9ABC == cpu.ex[BC]); T(10==step(&cpu)); T(0x1111 == cpu.r16(HL)); T(10==step(&cpu)); T(0x2222 == cpu.r16(DE)); T(10==step(&cpu)); T(0x3333 == cpu.r16(BC)); T(4 ==step(&cpu)); T(0x5678 == cpu.r16(HL)); T(0x1111 == cpu.ex[HL]); T(0x1234 == cpu.r16(DE)); T(0x2222 == cpu.ex[DE]); T(0x9ABC == cpu.r16(BC)); T(0x3333 == cpu.ex[BC]); T(10==step(&cpu)); T(0x0100 == cpu.SP); T(11==step(&cpu)); T(0x1234 == mem16(0x00FE)); T(19==step(&cpu)); T(0x1234 == cpu.r16(HL)); T(cpu.WZ == cpu.r16(HL)); T(0x5678 == mem16(0x00FE)); T(14==step(&cpu)); T(0x8899 == cpu.IX); T(23==step(&cpu)); T(0x5678 == cpu.IX); T(cpu.WZ == cpu.IX); T(0x8899 == mem16(0x00FE)); T(14==step(&cpu)); T(0x6677 == cpu.IY); T(23==step(&cpu)); T(0x8899 == cpu.IY); T(cpu.WZ == cpu.IY); T(0x6677 == mem16(0x00FE)); ok(); } fn ADD_rn() void { start("ADD rn"); const prog = [_]u8 { 0x3E, 0x0F, // LD A,0x0F 0x87, // ADD A,A 0x06, 0xE0, // LD B,0xE0 0x80, // ADD A,B 0x3E, 0x81, // LD A,0x81 0x0E, 0x80, // LD C,0x80 0x81, // ADD A,C 0x16, 0xFF, // LD D,0xFF 0x82, // ADD A,D 0x1E, 0x40, // LD E,0x40 0x83, // ADD A,E 0x26, 0x80, // LD H,0x80 0x84, // ADD A,H 0x2E, 0x33, // LD L,0x33 0x85, // ADD A,L 0xC6, 0x44, // ADD A,0x44 }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x0F == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x1E == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xE0 == cpu.regs[B]); T(4==step(&cpu)); T(0xFE == cpu.regs[A]); T(flags(&cpu, SF)); T(7==step(&cpu)); T(0x81 == cpu.regs[A]); T(7==step(&cpu)); T(0x80 == cpu.regs[C]); T(4==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, VF|CF)); T(7==step(&cpu)); T(0xFF == cpu.regs[D]); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|HF|CF)); T(7==step(&cpu)); T(0x40 == cpu.regs[E]); T(4==step(&cpu)); T(0x40 == cpu.regs[A]); T(flags(&cpu, 0)); T(7==step(&cpu)); T(0x80 == cpu.regs[H]); T(4==step(&cpu)); T(0xC0 == cpu.regs[A]); T(flags(&cpu, SF)); T(7==step(&cpu)); T(0x33 == cpu.regs[L]); T(4==step(&cpu)); T(0xF3 == cpu.regs[A]); T(flags(&cpu, SF)); T(7==step(&cpu)); T(0x37 == cpu.regs[A]); T(flags(&cpu, CF)); ok(); } fn ADD_iHLIXIYi() void { start("ADD (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x61, 0x81 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x00, // LD A,0x00 0x86, // ADD A,(HL) 0xDD, 0x86, 0x01, // ADD A,(IX+1) 0xFD, 0x86, 0xFF, // ADD A,(IY-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(14==step(&cpu)); T(0x1000 == cpu.IX); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(7 ==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu,0)); T(19==step(&cpu)); T(0xA2 == cpu.regs[A]); T(flags(&cpu,SF|VF)); T(19==step(&cpu)); T(0x23 == cpu.regs[A]); T(flags(&cpu,VF|CF)); ok(); } fn ADC_rn() void { start("ADC rn"); const prog = [_]u8 { 0x3E, 0x00, // LD A,0x00 0x06, 0x41, // LD B,0x41 0x0E, 0x61, // LD C,0x61 0x16, 0x81, // LD D,0x81 0x1E, 0x41, // LD E,0x41 0x26, 0x61, // LD H,0x61 0x2E, 0x81, // LD L,0x81 0x8F, // ADC A,A 0x88, // ADC A,B 0x89, // ADC A,C 0x8A, // ADC A,D 0x8B, // ADC A,E 0x8C, // ADC A,H 0x8D, // ADC A,L 0xCE, 0x01, // ADC A,0x01 }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x00 == cpu.regs[A]); T(7==step(&cpu)); T(0x41 == cpu.regs[B]); T(7==step(&cpu)); T(0x61 == cpu.regs[C]); T(7==step(&cpu)); T(0x81 == cpu.regs[D]); T(7==step(&cpu)); T(0x41 == cpu.regs[E]); T(7==step(&cpu)); T(0x61 == cpu.regs[H]); T(7==step(&cpu)); T(0x81 == cpu.regs[L]); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF)); T(4==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0xA2 == cpu.regs[A]); T(flags(&cpu, SF|VF)); T(4==step(&cpu)); T(0x23 == cpu.regs[A]); T(flags(&cpu, VF|CF)); T(4==step(&cpu)); T(0x65 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0xC6 == cpu.regs[A]); T(flags(&cpu, SF|VF)); T(4==step(&cpu)); T(0x47 == cpu.regs[A]); T(flags(&cpu, VF|CF)); T(7==step(&cpu)); T(0x49 == cpu.regs[A]); T(flags(&cpu, 0)); ok(); } fn ADC_iHLIXIYi() void { start("ADC (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x61, 0x81, 0x2 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x00, // LD A,0x00 0x86, // ADD A,(HL) 0xDD, 0x8E, 0x01, // ADC A,(IX+1) 0xFD, 0x8E, 0xFF, // ADC A,(IY-1) 0xDD, 0x8E, 0x03, // ADC A,(IX+3) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(14==step(&cpu)); T(0x1000 == cpu.IX); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(7 ==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, 0)); T(19==step(&cpu)); T(0xA2 == cpu.regs[A]); T(flags(&cpu, SF|VF)); T(19==step(&cpu)); T(0x23 == cpu.regs[A]); T(flags(&cpu, VF|CF)); T(19==step(&cpu)); T(0x26 == cpu.regs[A]); T(flags(&cpu, 0)); ok(); } fn SUB_rn() void { start("SUB rn"); const prog = [_]u8 { 0x3E, 0x04, // LD A,0x04 0x06, 0x01, // LD B,0x01 0x0E, 0xF8, // LD C,0xF8 0x16, 0x0F, // LD D,0x0F 0x1E, 0x79, // LD E,0x79 0x26, 0xC0, // LD H,0xC0 0x2E, 0xBF, // LD L,0xBF 0x97, // SUB A,A 0x90, // SUB A,B 0x91, // SUB A,C 0x92, // SUB A,D 0x93, // SUB A,E 0x94, // SUB A,H 0x95, // SUB A,L 0xD6, 0x01, // SUB A,0x01 0xD6, 0xFE, // SUB A,0xFE }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x04 == cpu.regs[A]); T(7==step(&cpu)); T(0x01 == cpu.regs[B]); T(7==step(&cpu)); T(0xF8 == cpu.regs[C]); T(7==step(&cpu)); T(0x0F == cpu.regs[D]); T(7==step(&cpu)); T(0x79 == cpu.regs[E]); T(7==step(&cpu)); T(0xC0 == cpu.regs[H]); T(7==step(&cpu)); T(0xBF == cpu.regs[L]); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x07 == cpu.regs[A]); T(flags(&cpu, NF)); T(4==step(&cpu)); T(0xF8 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x7F == cpu.regs[A]); T(flags(&cpu, HF|VF|NF)); T(4==step(&cpu)); T(0xBF == cpu.regs[A]); T(flags(&cpu, SF|VF|NF|CF)); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(7==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, NF)); ok(); } fn SUB_iHLIXIYi() void { start("SUB (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x61, 0x81 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x00, // LD A,0x00 0x96, // SUB A,(HL) 0xDD, 0x96, 0x01, // SUB A,(IX+1) 0xFD, 0x96, 0xFE, // SUB A,(IY-2) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(14==step(&cpu)); T(0x1000 == cpu.IX); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(7 ==step(&cpu)); T(0xBF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(19==step(&cpu)); T(0x5E == cpu.regs[A]); T(flags(&cpu, VF|NF)); T(19==step(&cpu)); T(0xFD == cpu.regs[A]); T(flags(&cpu, SF|NF|CF)); ok(); } fn SBC_rn() void { start("SBC rn"); const prog = [_]u8 { 0x3E, 0x04, // LD A,0x04 0x06, 0x01, // LD B,0x01 0x0E, 0xF8, // LD C,0xF8 0x16, 0x0F, // LD D,0x0F 0x1E, 0x79, // LD E,0x79 0x26, 0xC0, // LD H,0xC0 0x2E, 0xBF, // LD L,0xBF 0x97, // SUB A,A 0x98, // SBC A,B 0x99, // SBC A,C 0x9A, // SBC A,D 0x9B, // SBC A,E 0x9C, // SBC A,H 0x9D, // SBC A,L 0xDE, 0x01, // SBC A,0x01 0xDE, 0xFE, // SBC A,0xFE }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x06 == cpu.regs[A]); T(flags(&cpu, NF)); T(4==step(&cpu)); T(0xF7 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x7D == cpu.regs[A]); T(flags(&cpu, HF|VF|NF)); T(4==step(&cpu)); T(0xBD == cpu.regs[A]); T(flags(&cpu, SF|VF|NF|CF)); T(4==step(&cpu)); T(0xFD == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(7==step(&cpu)); T(0xFB == cpu.regs[A]); T(flags(&cpu, SF|NF)); T(7==step(&cpu)); T(0xFD == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); ok(); } fn SBC_iHLIXIYi() void { start("SBC (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x61, 0x81 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x00, // LD A,0x00 0x9E, // SBC A,(HL) 0xDD, 0x9E, 0x01, // SBC A,(IX+1) 0xFD, 0x9E, 0xFE, // SBC A,(IY-2) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(14==step(&cpu)); T(0x1000 == cpu.IX); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(7 ==step(&cpu)); T(0xBF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(19==step(&cpu)); T(0x5D == cpu.regs[A]); T(flags(&cpu, VF|NF)); T(19==step(&cpu)); T(0xFC == cpu.regs[A]); T(flags(&cpu, SF|NF|CF)); ok(); } fn CP_rn() void { start("CP rn"); const prog = [_]u8 { 0x3E, 0x04, // LD A,0x04 0x06, 0x05, // LD B,0x05 0x0E, 0x03, // LD C,0x03 0x16, 0xff, // LD D,0xff 0x1E, 0xaa, // LD E,0xaa 0x26, 0x80, // LD H,0x80 0x2E, 0x7f, // LD L,0x7f 0xBF, // CP A 0xB8, // CP B 0xB9, // CP C 0xBA, // CP D 0xBB, // CP E 0xBC, // CP H 0xBD, // CP L 0xFE, 0x04, // CP 0x04 }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x04 == cpu.regs[A]); T(7==step(&cpu)); T(0x05 == cpu.regs[B]); T(7==step(&cpu)); T(0x03 == cpu.regs[C]); T(7==step(&cpu)); T(0xff == cpu.regs[D]); T(7==step(&cpu)); T(0xaa == cpu.regs[E]); T(7==step(&cpu)); T(0x80 == cpu.regs[H]); T(7==step(&cpu)); T(0x7f == cpu.regs[L]); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, NF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, HF|NF|CF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, HF|NF|CF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, SF|VF|NF|CF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(7==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, ZF|NF)) ; ok(); } fn CP_iHLIXIYi() void { start("CP (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x61, 0x22 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0x41, // LD A,0x41 0xBE, // CP (HL) 0xDD, 0xBE, 0x01, // CP (IX+1) 0xFD, 0xBE, 0xFF, // CP (IY-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(14==step(&cpu)); T(0x1000 == cpu.IX); T(14==step(&cpu)); T(0x1003 == cpu.IY); T(7 ==step(&cpu)); T(0x41 == cpu.regs[A]); T(7 ==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(19==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, SF|NF|CF)); T(19==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, HF|NF)); ok(); } fn AND_rn() void { start("AND rn"); const prog = [_]u8 { 0x3E, 0xFF, // LD A,0xFF 0x06, 0x01, // LD B,0x01 0x0E, 0x03, // LD C,0x02 0x16, 0x04, // LD D,0x04 0x1E, 0x08, // LD E,0x08 0x26, 0x10, // LD H,0x10 0x2E, 0x20, // LD L,0x20 0xA0, // AND B 0xF6, 0xFF, // OR 0xFF 0xA1, // AND C 0xF6, 0xFF, // OR 0xFF 0xA2, // AND D 0xF6, 0xFF, // OR 0xFF 0xA3, // AND E 0xF6, 0xFF, // OR 0xFF 0xA4, // AND H 0xF6, 0xFF, // OR 0xFF 0xA5, // AND L 0xF6, 0xFF, // OR 0xFF 0xE6, 0x40, // AND 0x40 0xF6, 0xFF, // OR 0xFF 0xE6, 0xAA, // AND 0xAA }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(4==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(4==step(&cpu)); T(0x03 == cpu.regs[A]); T(flags(&cpu, HF|PF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(4==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(4==step(&cpu)); T(0x08 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(4==step(&cpu)); T(0x10 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(4==step(&cpu)); T(0x20 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(7==step(&cpu)); T(0x40 == cpu.regs[A]); T(flags(&cpu, HF)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(7==step(&cpu)); T(0xAA == cpu.regs[A]); T(flags(&cpu, SF|HF|PF)); ok(); } fn AND_iHLIXIYi() void { start("AND (HL/IX+d/IY+d)"); const data = [_]u8 { 0xFE, 0xAA, 0x99 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x3E, 0xFF, // LD A,0xFF 0xA6, // AND (HL) 0xDD, 0xA6, 0x01, // AND (IX+1) 0xFD, 0xA6, 0xFF, // AND (IX-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 4); T(7 ==step(&cpu)); T(0xFE == cpu.regs[A]); T(flags(&cpu, SF|HF)); T(19==step(&cpu)); T(0xAA == cpu.regs[A]); T(flags(&cpu, SF|HF|PF)); T(19==step(&cpu)); T(0x88 == cpu.regs[A]); T(flags(&cpu, SF|HF|PF)); ok(); } fn XOR_rn() void { start("XOR_rn"); const prog = [_]u8 { 0x97, // SUB A 0x06, 0x01, // LD B,0x01 0x0E, 0x03, // LD C,0x03 0x16, 0x07, // LD D,0x07 0x1E, 0x0F, // LD E,0x0F 0x26, 0x1F, // LD H,0x1F 0x2E, 0x3F, // LD L,0x3F 0xAF, // XOR A 0xA8, // XOR B 0xA9, // XOR C 0xAA, // XOR D 0xAB, // XOR E 0xAC, // XOR H 0xAD, // XOR L 0xEE, 0x7F, // XOR 0x7F 0xEE, 0xFF, // XOR 0xFF }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|PF)); T(4==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x02 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x05 == cpu.regs[A]); T(flags(&cpu, PF)); T(4==step(&cpu)); T(0x0A == cpu.regs[A]); T(flags(&cpu, PF)); T(4==step(&cpu)); T(0x15 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x2A == cpu.regs[A]); T(flags(&cpu, 0)); T(7==step(&cpu)); T(0x55 == cpu.regs[A]); T(flags(&cpu, PF)); T(7==step(&cpu)); T(0xAA == cpu.regs[A]); T(flags(&cpu, SF|PF)); ok(); } fn OR_rn() void { start("OR_rn"); const prog = [_]u8 { 0x97, // SUB A 0x06, 0x01, // LD B,0x01 0x0E, 0x02, // LD C,0x02 0x16, 0x04, // LD D,0x04 0x1E, 0x08, // LD E,0x08 0x26, 0x10, // LD H,0x10 0x2E, 0x20, // LD L,0x20 0xB7, // OR A 0xB0, // OR B 0xB1, // OR C 0xB2, // OR D 0xB3, // OR E 0xB4, // OR H 0xB5, // OR L 0xF6, 0x40, // OR 0x40 0xF6, 0x80, // OR 0x80 }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|PF)); T(4==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x03 == cpu.regs[A]); T(flags(&cpu, PF)); T(4==step(&cpu)); T(0x07 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x0F == cpu.regs[A]); T(flags(&cpu, PF)); T(4==step(&cpu)); T(0x1F == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x3F == cpu.regs[A]); T(flags(&cpu, PF)); T(7==step(&cpu)); T(0x7F == cpu.regs[A]); T(flags(&cpu, 0)); T(7==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|PF)); ok(); } fn OR_XOR_iHLIXIYi() void { start("OR/XOR (HL/IX+d/IY+d)"); const data = [_]u8 { 0x41, 0x62, 0x84 }; const prog = [_]u8 { 0x3E, 0x00, // LD A,0x00 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0xB6, // OR (HL) 0xDD, 0xB6, 0x01, // OR (IX+1) 0xFD, 0xB6, 0xFF, // OR (IY-1) 0xAE, // XOR (HL) 0xDD, 0xAE, 0x01, // XOR (IX+1) 0xFD, 0xAE, 0xFF, // XOR (IY-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 4); T(7 ==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, PF)); T(19==step(&cpu)); T(0x63 == cpu.regs[A]); T(flags(&cpu, PF)); T(19==step(&cpu)); T(0xE7 == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(7 ==step(&cpu)); T(0xA6 == cpu.regs[A]); T(flags(&cpu, SF|PF)); T(19==step(&cpu)); T(0xC4 == cpu.regs[A]); T(flags(&cpu, SF)); T(19==step(&cpu)); T(0x40 == cpu.regs[A]); T(flags(&cpu, 0)); ok(); } fn INC_DEC_r() void { start("INC/DEC r"); const prog = [_]u8 { 0x3e, 0x00, // LD A,0x00 0x06, 0xFF, // LD B,0xFF 0x0e, 0x0F, // LD C,0x0F 0x16, 0x0E, // LD D,0x0E 0x1E, 0x7F, // LD E,0x7F 0x26, 0x3E, // LD H,0x3E 0x2E, 0x23, // LD L,0x23 0x3C, // INC A 0x3D, // DEC A 0x04, // INC B 0x05, // DEC B 0x0C, // INC C 0x0D, // DEC C 0x14, // INC D 0x15, // DEC D 0xFE, 0x01, // CP 0x01 // set carry flag (should be preserved) 0x1C, // INC E 0x1D, // DEC E 0x24, // INC H 0x25, // DEC H 0x2C, // INC L 0x2D, // DEC L }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(0x00 == cpu.regs[A]); T(0xFF == cpu.regs[B]); T(0x0F == cpu.regs[C]); T(0x0E == cpu.regs[D]); T(0x7F == cpu.regs[E]); T(0x3E == cpu.regs[H]); T(0x23 == cpu.regs[L]); T(4==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0x00 == cpu.regs[B]); T(flags(&cpu, ZF|HF)); T(4==step(&cpu)); T(0xFF == cpu.regs[B]); T(flags(&cpu, SF|HF|NF)); T(4==step(&cpu)); T(0x10 == cpu.regs[C]); T(flags(&cpu, HF)); T(4==step(&cpu)); T(0x0F == cpu.regs[C]); T(flags(&cpu, HF|NF)); T(4==step(&cpu)); T(0x0F == cpu.regs[D]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x0E == cpu.regs[D]); T(flags(&cpu, NF)); T(7==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(4==step(&cpu)); T(0x80 == cpu.regs[E]); T(flags(&cpu, SF|HF|VF|CF)); T(4==step(&cpu)); T(0x7F == cpu.regs[E]); T(flags(&cpu, HF|VF|NF|CF)); T(4==step(&cpu)); T(0x3F == cpu.regs[H]); T(flags(&cpu, CF)); T(4==step(&cpu)); T(0x3E == cpu.regs[H]); T(flags(&cpu, NF|CF)); T(4==step(&cpu)); T(0x24 == cpu.regs[L]); T(flags(&cpu, CF)); T(4==step(&cpu)); T(0x23 == cpu.regs[L]); T(flags(&cpu, NF|CF)); ok(); } fn INC_DEC_iHLIXIYi() void { start("INC/DEC (HL/IX+d/IY+d)"); const data = [_]u8 { 0x00, 0x3F, 0x7F }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1000 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0x35, // DEC (HL) 0x34, // INC (HL) 0xDD, 0x34, 0x01, // INC (IX+1) 0xDD, 0x35, 0x01, // DEC (IX+1) 0xFD, 0x34, 0xFF, // INC (IY-1) 0xFD, 0x35, 0xFF, // DEC (IY-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(11==step(&cpu)); T(0xFF == mem[0x1000]); T(flags(&cpu, SF|HF|NF)); T(11==step(&cpu)); T(0x00 == mem[0x1000]); T(flags(&cpu, ZF|HF)); T(23==step(&cpu)); T(0x40 == mem[0x1001]); T(flags(&cpu, HF)); T(23==step(&cpu)); T(0x3F == mem[0x1001]); T(flags(&cpu, HF|NF)); T(23==step(&cpu)); T(0x80 == mem[0x1002]); T(flags(&cpu, SF|HF|VF)); T(23==step(&cpu)); T(0x7F == mem[0x1002]); T(flags(&cpu, HF|PF|NF)); ok(); } fn INC_DEC_ssIXIY() void { start("INC/DEC ss/IX/IY"); const prog = [_]u8 { 0x01, 0x00, 0x00, // LD BC,0x0000 0x11, 0xFF, 0xFF, // LD DE,0xffff 0x21, 0xFF, 0x00, // LD HL,0x00ff 0x31, 0x11, 0x11, // LD SP,0x1111 0xDD, 0x21, 0xFF, 0x0F, // LD IX,0x0fff 0xFD, 0x21, 0x34, 0x12, // LD IY,0x1234 0x0B, // DEC BC 0x03, // INC BC 0x13, // INC DE 0x1B, // DEC DE 0x23, // INC HL 0x2B, // DEC HL 0x33, // INC SP 0x3B, // DEC SP 0xDD, 0x23, // INC IX 0xDD, 0x2B, // DEC IX 0xFD, 0x23, // INC IX 0xFD, 0x2B, // DEC IX }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 6); T(6 ==step(&cpu)); T(0xFFFF == cpu.r16(BC)); T(6 ==step(&cpu)); T(0x0000 == cpu.r16(BC)); T(6 ==step(&cpu)); T(0x0000 == cpu.r16(DE)); T(6 ==step(&cpu)); T(0xFFFF == cpu.r16(DE)); T(6 ==step(&cpu)); T(0x0100 == cpu.r16(HL)); T(6 ==step(&cpu)); T(0x00FF == cpu.r16(HL)); T(6 ==step(&cpu)); T(0x1112 == cpu.SP); T(6 ==step(&cpu)); T(0x1111 == cpu.SP); T(10==step(&cpu)); T(0x1000 == cpu.IX); T(10==step(&cpu)); T(0x0FFF == cpu.IX); T(10==step(&cpu)); T(0x1235 == cpu.IY); T(10==step(&cpu)); T(0x1234 == cpu.IY); ok(); } fn RLCA_RLA_RRCA_RRA() void { start("RLCA/RLA/RRCA/RRA"); const prog = [_]u8 { 0x3E, 0xA0, // LD A,0xA0 0x07, // RLCA 0x07, // RLCA 0x0F, // RRCA 0x0F, // RRCA 0x17, // RLA 0x17, // RLA 0x1F, // RRA 0x1F, // RRA }; copy(0x0000, &prog); var cpu = makeCPU(); cpu.regs[F] = 0xFF; T(7==step(&cpu)); T(0xA0 == cpu.regs[A]); T(4==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF|CF)); T(4==step(&cpu)); T(0x82 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF)); T(4==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF)); T(4==step(&cpu)); T(0xA0 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF|CF)); T(4==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF|CF)); T(4==step(&cpu)); T(0x83 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF)); T(4==step(&cpu)); T(0x41 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF|CF)); T(4==step(&cpu)); T(0xA0 == cpu.regs[A]); T(flags(&cpu, SF|ZF|VF|CF)); ok(); } fn RLC_RL_RRC_RR_r() void { start("RLC/RL/RRC/RR r"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0x06, 0xFF, // LD B,0xFF 0x0E, 0x03, // LD C,0x03 0x16, 0xFE, // LD D,0xFE 0x1E, 0x11, // LD E,0x11 0x26, 0x3F, // LD H,0x3F 0x2E, 0x70, // LD L,0x70 0xCB, 0x0F, // RRC A 0xCB, 0x07, // RLC A 0xCB, 0x08, // RRC B 0xCB, 0x00, // RLC B 0xCB, 0x01, // RLC C 0xCB, 0x09, // RRC C 0xCB, 0x02, // RLC D 0xCB, 0x0A, // RRC D 0xCB, 0x0B, // RRC E 0xCB, 0x03, // RLC E 0xCB, 0x04, // RLC H 0xCB, 0x0C, // RCC H 0xCB, 0x05, // RLC L 0xCB, 0x0D, // RRC L 0xCB, 0x1F, // RR A 0xCB, 0x17, // RL A 0xCB, 0x18, // RR B 0xCB, 0x10, // RL B 0xCB, 0x11, // RL C 0xCB, 0x19, // RR C 0xCB, 0x12, // RL D 0xCB, 0x1A, // RR D 0xCB, 0x1B, // RR E 0xCB, 0x13, // RL E 0xCB, 0x14, // RL H 0xCB, 0x1C, // RR H 0xCB, 0x15, // RL L 0xCB, 0x1D, // RR L }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(8==step(&cpu)); T(0x80 == cpu.regs[A]); T(flags(&cpu, SF|CF)); T(8==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0xFF == cpu.regs[B]); T(flags(&cpu, SF|PF|CF)); T(8==step(&cpu)); T(0xFF == cpu.regs[B]); T(flags(&cpu, SF|PF|CF)); T(8==step(&cpu)); T(0x06 == cpu.regs[C]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x03 == cpu.regs[C]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0xFD == cpu.regs[D]); T(flags(&cpu, SF|CF)); T(8==step(&cpu)); T(0xFE == cpu.regs[D]); T(flags(&cpu, SF|CF)); T(8==step(&cpu)); T(0x88 == cpu.regs[E]); T(flags(&cpu, SF|PF|CF)); T(8==step(&cpu)); T(0x11 == cpu.regs[E]); T(flags(&cpu, PF|CF)); T(8==step(&cpu)); T(0x7E == cpu.regs[H]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x3F == cpu.regs[H]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0xE0 == cpu.regs[L]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0x70 == cpu.regs[L]); T(flags(&cpu, 0)); T(8==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|PF|CF)); T(8==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(8==step(&cpu)); T(0x7F == cpu.regs[B]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0xFF == cpu.regs[B]); T(flags(&cpu, SF|PF)); T(8==step(&cpu)); T(0x06 == cpu.regs[C]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x03 == cpu.regs[C]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0xFC == cpu.regs[D]); T(flags(&cpu, SF|PF|CF)); T(8==step(&cpu)); T(0xFE == cpu.regs[D]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0x08 == cpu.regs[E]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0x11 == cpu.regs[E]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x7E == cpu.regs[H]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x3F == cpu.regs[H]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0xE0 == cpu.regs[L]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0x70 == cpu.regs[L]); T(flags(&cpu, 0)); ok(); } fn RRC_RLC_RR_RL_iHLIXIYi() void { start("RRC/RLC/RR/RL (HL/IX+d/IY+d)"); const data = [_]u8{ 0x01, 0xFF, 0x11 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1001 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0xCB, 0x0E, // RRC (HL) 0x7E, // LD A,(HL) 0xCB, 0x06, // RLC (HL) 0x7E, // LD A,(HL) 0xDD, 0xCB, 0x01, 0x0E, // RRC (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xDD, 0xCB, 0x01, 0x06, // RLC (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xFD, 0xCB, 0xFF, 0x0E, // RRC (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) 0xFD, 0xCB, 0xFF, 0x06, // RLC (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) 0xCB, 0x1E, // RR (HL) 0x7E, // LD A,(HL) 0xCB, 0x16, // RL (HL) 0x7E, // LD A,(HL) 0xDD, 0xCB, 0x01, 0x1E, // RR (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xDD, 0xCB, 0x01, 0x16, // RL (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xFD, 0xCB, 0xFF, 0x16, // RL (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) 0xFD, 0xCB, 0xFF, 0x1E, // RR (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(15==step(&cpu)); T(0x80 == mem[0x1000]); T(flags(&cpu, SF|CF)); T(7 ==step(&cpu)); T(0x80 == cpu.regs[A]); T(15==step(&cpu)); T(0x01 == mem[0x1000]); T(flags(&cpu, CF)); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(23==step(&cpu)); T(0xFF == mem[0x1001]); T(flags(&cpu, SF|PF|CF)); T(19==step(&cpu)); T(0xFF == cpu.regs[A]); T(23==step(&cpu)); T(0xFF == mem[0x1001]); T(flags(&cpu, SF|PF|CF)); T(19==step(&cpu)); T(0xFF == cpu.regs[A]); T(23==step(&cpu)); T(0x88 == mem[0x1002]); T(flags(&cpu, SF|PF|CF)); T(19==step(&cpu)); T(0x88 == cpu.regs[A]); T(23==step(&cpu)); T(0x11 == mem[0x1002]); T(flags(&cpu, PF|CF)); T(19==step(&cpu)); T(0x11 == cpu.regs[A]); T(15==step(&cpu)); T(0x80 == mem[0x1000]); T(flags(&cpu, SF|CF)); T(7 ==step(&cpu)); T(0x80 == cpu.regs[A]); T(15==step(&cpu)); T(0x01 == mem[0x1000]); T(flags(&cpu, CF)); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(23==step(&cpu)); T(0xFF == mem[0x1001]); T(flags(&cpu, SF|PF|CF)); T(19==step(&cpu)); T(0xFF == cpu.regs[A]); T(23==step(&cpu)); T(0xFF == mem[0x1001]); T(flags(&cpu, SF|PF|CF)); T(19==step(&cpu)); T(0xFF == cpu.regs[A]); T(23==step(&cpu)); T(0x23 == mem[0x1002]); T(flags(&cpu, 0)); T(19==step(&cpu)); T(0x23 == cpu.regs[A]); T(23==step(&cpu)); T(0x11 == mem[0x1002]); T(flags(&cpu, PF|CF)); T(19==step(&cpu)); T(0x11 == cpu.regs[A]); ok(); } fn SLA_r() void { start("SLA_r"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0x06, 0x80, // LD B,0x80 0x0E, 0xAA, // LD C,0xAA 0x16, 0xFE, // LD D,0xFE 0x1E, 0x7F, // LD E,0x7F 0x26, 0x11, // LD H,0x11 0x2E, 0x00, // LD L,0x00 0xCB, 0x27, // SLA A 0xCB, 0x20, // SLA B 0xCB, 0x21, // SLA C 0xCB, 0x22, // SLA D 0xCB, 0x23, // SLA E 0xCB, 0x24, // SLA H 0xCB, 0x25, // SLA L }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(8==step(&cpu)); T(0x02 == cpu.regs[A]); T(flags(&cpu, 0)); T(8==step(&cpu)); T(0x00 == cpu.regs[B]); T(flags(&cpu, ZF|PF|CF)); T(8==step(&cpu)); T(0x54 == cpu.regs[C]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0xFC == cpu.regs[D]); T(flags(&cpu, SF|PF|CF)); T(8==step(&cpu)); T(0xFE == cpu.regs[E]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0x22 == cpu.regs[H]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x00 == cpu.regs[L]); T(flags(&cpu, ZF|PF)); ok(); } fn SLA_iHLIXIYi() void { start("SLA (HL/IX+d/IY+d)"); const data = [_]u8 { 0x01, 0x80, 0xAA }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1001 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0xCB, 0x26, // SLA (HL) 0x7E, // LD A,(HL) 0xDD, 0xCB, 0x01, 0x26, // SLA (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xFD, 0xCB, 0xFF, 0x26, // SLA (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) }; copy(0x1000, &data); copy(0x000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(15==step(&cpu)); T(0x02 == mem[0x1000]); T(flags(&cpu, 0)); T(7 ==step(&cpu)); T(0x02 == cpu.regs[A]); T(23==step(&cpu)); T(0x00 == mem[0x1001]); T(flags(&cpu, ZF|PF|CF)); T(19==step(&cpu)); T(0x00 == cpu.regs[A]); T(23==step(&cpu)); T(0x54 == mem[0x1002]); T(flags(&cpu, CF)); T(19==step(&cpu)); T(0x54 == cpu.regs[A]); ok(); } fn SRA_r() void { start("SRA r"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0x06, 0x80, // LD B,0x80 0x0E, 0xAA, // LD C,0xAA 0x16, 0xFE, // LD D,0xFE 0x1E, 0x7F, // LD E,0x7F 0x26, 0x11, // LD H,0x11 0x2E, 0x00, // LD L,0x00 0xCB, 0x2F, // SRA A 0xCB, 0x28, // SRA B 0xCB, 0x29, // SRA C 0xCB, 0x2A, // SRA D 0xCB, 0x2B, // SRA E 0xCB, 0x2C, // SRA H 0xCB, 0x2D, // SRA L }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(8==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|PF|CF)); T(8==step(&cpu)); T(0xC0 == cpu.regs[B]); T(flags(&cpu, SF|PF)); T(8==step(&cpu)); T(0xD5 == cpu.regs[C]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0xFF == cpu.regs[D]); T(flags(&cpu, SF|PF)); T(8==step(&cpu)); T(0x3F == cpu.regs[E]); T(flags(&cpu, PF|CF)); T(8==step(&cpu)); T(0x08 == cpu.regs[H]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0x00 == cpu.regs[L]); T(flags(&cpu, ZF|PF)); ok(); } fn SRA_iHLIXIYi() void { start("SRA (HL/IX+d/IY+d)"); const data = [_]u8 { 0x01, 0x80, 0xAA }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1001 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0xCB, 0x2E, // SRA (HL) 0x7E, // LD A,(HL) 0xDD, 0xCB, 0x01, 0x2E, // SRA (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xFD, 0xCB, 0xFF, 0x2E, // SRA (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) }; copy(0x1000, &data); copy(0x000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(15==step(&cpu)); T(0x00 == mem[0x1000]); T(flags(&cpu, ZF|PF|CF)); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(23==step(&cpu)); T(0xC0 == mem[0x1001]); T(flags(&cpu, SF|PF)); T(19==step(&cpu)); T(0xC0 == cpu.regs[A]); T(23==step(&cpu)); T(0xD5 == mem[0x1002]); T(flags(&cpu, SF)); T(19==step(&cpu)); T(0xD5 == cpu.regs[A]); ok(); } fn SRL_r() void { start("SRL r"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0x06, 0x80, // LD B,0x80 0x0E, 0xAA, // LD C,0xAA 0x16, 0xFE, // LD D,0xFE 0x1E, 0x7F, // LD E,0x7F 0x26, 0x11, // LD H,0x11 0x2E, 0x00, // LD L,0x00 0xCB, 0x3F, // SRL A 0xCB, 0x38, // SRL B 0xCB, 0x39, // SRL C 0xCB, 0x3A, // SRL D 0xCB, 0x3B, // SRL E 0xCB, 0x3C, // SRL H 0xCB, 0x3D, // SRL L }; copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 7); T(8==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|PF|CF)); T(8==step(&cpu)); T(0x40 == cpu.regs[B]); T(flags(&cpu, 0)); T(8==step(&cpu)); T(0x55 == cpu.regs[C]); T(flags(&cpu, PF)); T(8==step(&cpu)); T(0x7F == cpu.regs[D]); T(flags(&cpu, 0)); T(8==step(&cpu)); T(0x3F == cpu.regs[E]); T(flags(&cpu, PF|CF)); T(8==step(&cpu)); T(0x08 == cpu.regs[H]); T(flags(&cpu, CF)); T(8==step(&cpu)); T(0x00 == cpu.regs[L]); T(flags(&cpu, ZF|PF)); ok(); } fn SRL_iHLIXIYi() void { start("SRL (HL/IX+d/IY+d)"); const data = [_]u8 { 0x01, 0x80, 0xAA }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0xDD, 0x21, 0x00, 0x10, // LD IX,0x1001 0xFD, 0x21, 0x03, 0x10, // LD IY,0x1003 0xCB, 0x3E, // SRL (HL) 0x7E, // LD A,(HL) 0xDD, 0xCB, 0x01, 0x3E, // SRL (IX+1) 0xDD, 0x7E, 0x01, // LD A,(IX+1) 0xFD, 0xCB, 0xFF, 0x3E, // SRL (IY-1) 0xFD, 0x7E, 0xFF, // LD A,(IY-1) }; copy(0x1000, &data); copy(0x000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(15==step(&cpu)); T(0x00 == mem[0x1000]); T(flags(&cpu, ZF|PF|CF)); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(23==step(&cpu)); T(0x40 == mem[0x1001]); T(flags(&cpu, 0)); T(19==step(&cpu)); T(0x40 == cpu.regs[A]); T(23==step(&cpu)); T(0x55 == mem[0x1002]); T(flags(&cpu, PF)); T(19==step(&cpu)); T(0x55 == cpu.regs[A]); ok(); } fn RLD_RRD() void { start("RLD/RRD"); const prog = [_]u8 { 0x3E, 0x12, // LD A,0x12 0x21, 0x00, 0x10, // LD HL,0x1000 0x36, 0x34, // LD (HL),0x34 0xED, 0x67, // RRD 0xED, 0x6F, // RLD 0x7E, // LD A,(HL) 0x3E, 0xFE, // LD A,0xFE 0x36, 0x00, // LD (HL),0x00 0xED, 0x6F, // RLD 0xED, 0x67, // RRD 0x7E, // LD A,(HL) 0x3E, 0x01, // LD A,0x01 0x36, 0x00, // LD (HL),0x00 0xED, 0x6F, // RLD 0xED, 0x67, // RRD 0x7E }; copy(0x0000, &prog); var cpu = makeCPU(); T(7 ==step(&cpu)); T(0x12 == cpu.regs[A]); T(10==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(10==step(&cpu)); T(0x34 == mem[0x1000]); T(18==step(&cpu)); T(0x14 == cpu.regs[A]); T(0x23 == mem[0x1000]); T(0x1001 == cpu.WZ); T(18==step(&cpu)); T(0x12 == cpu.regs[A]); T(0x34 == mem[0x1000]); T(0x1001 == cpu.WZ); T(7 ==step(&cpu)); T(0x34 == cpu.regs[A]); T(7 ==step(&cpu)); T(0xFE == cpu.regs[A]); T(10==step(&cpu)); T(0x00 == mem[0x1000]); T(18==step(&cpu)); T(0xF0 == cpu.regs[A]); T(0x0E == mem[0x1000]); T(flags(&cpu, SF|PF)); T(0x1001 == cpu.WZ); T(18==step(&cpu)); T(0xFE == cpu.regs[A]); T(0x00 == mem[0x1000]); T(flags(&cpu, SF)); T(0x1001 == cpu.WZ); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(10==step(&cpu)); T(0x00 == mem[0x1000]); cpu.regs[F] |= CF; T(18==step(&cpu)); T(0x00 == cpu.regs[A]); T(0x01 == mem[0x1000]); T(flags(&cpu, ZF|PF|CF)); T(0x1001 == cpu.WZ); T(18==step(&cpu)); T(0x01 == cpu.regs[A]); T(0x00 == mem[0x1000]); T(flags(&cpu, CF)); T(0x1001 == cpu.WZ); T(7 ==step(&cpu)); T(0x00 == cpu.regs[A]); ok(); } fn HALTx() void { start("HALT"); const prog = [_]u8 { 0x76, // HALT }; copy(0x0000, &prog); var cpu = makeCPU(); T(4==step(&cpu)); T(0x0000 == cpu.PC); T(0 != (cpu.pins & HALT)); T(4==step(&cpu)); T(0x0000 == cpu.PC); T(0 != (cpu.pins & HALT)); T(4==step(&cpu)); T(0x0000 == cpu.PC); T(0 != (cpu.pins & HALT)); ok(); } fn BIT() void { start("BIT"); // FIXME only test cycle count for now const prog = [_]u8 { 0xCB, 0x47, // BIT 0,A 0xCB, 0x46, // BIT 0,(HL) 0xDD, 0xCB, 0x01, 0x46, // BIT 0,(IX+1) 0xFD, 0xCB, 0xFF, 0x46, // BIT 0,(IY-1) 0xDD, 0xCB, 0x02, 0x47, // undocumented: BIT 0,(IX+2),A }; copy(0x0000, &prog); var cpu = makeCPU(); T(8 ==step(&cpu)); T(12==step(&cpu)); T(20==step(&cpu)); T(20==step(&cpu)); T(20==step(&cpu)); ok(); } fn SET() void { start("SET"); // FIXME only test cycle count for now const prog = [_]u8 { 0xCB, 0xC7, // SET 0,A 0xCB, 0xC6, // SET 0,(HL) 0xDD, 0xCB, 0x01, 0xC6, // SET 0,(IX+1) 0xFD, 0xCB, 0xFF, 0xC6, // SET 0,(IY-1) 0xDD, 0xCB, 0x02, 0xC7, // undocumented: SET 0,(IX+2),A }; copy(0x0000, &prog); var cpu = makeCPU(); T(8 ==step(&cpu)); T(15==step(&cpu)); T(23==step(&cpu)); T(23==step(&cpu)); T(23==step(&cpu)); ok(); } fn RES() void { start("RES"); // FIXME only test cycle count for now const prog = [_]u8 { 0xCB, 0x87, // RES 0,A 0xCB, 0x86, // RES 0,(HL) 0xDD, 0xCB, 0x01, 0x86, // RES 0,(IX+1) 0xFD, 0xCB, 0xFF, 0x86, // RES 0,(IY-1) 0xDD, 0xCB, 0x02, 0x87, // undocumented: RES 0,(IX+2),A }; copy(0x0000, &prog); var cpu = makeCPU(); T(8 ==step(&cpu)); T(15==step(&cpu)); T(23==step(&cpu)); T(23==step(&cpu)); T(23==step(&cpu)); ok(); } fn DAA() void { start("DAA"); const prog = [_]u8 { 0x3e, 0x15, // ld a,0x15 0x06, 0x27, // ld b,0x27 0x80, // add a,b 0x27, // daa 0x90, // sub b 0x27, // daa 0x3e, 0x90, // ld a,0x90 0x06, 0x15, // ld b,0x15 0x80, // add a,b 0x27, // daa 0x90, // sub b 0x27 // daa }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x15 == cpu.regs[A]); T(7==step(&cpu)); T(0x27 == cpu.regs[B]); T(4==step(&cpu)); T(0x3C == cpu.regs[A]); T(flags(&cpu, 0)); T(4==step(&cpu)); T(0x42 == cpu.regs[A]); T(flags(&cpu, HF|PF)); T(4==step(&cpu)); T(0x1B == cpu.regs[A]); T(flags(&cpu, HF|NF)); T(4==step(&cpu)); T(0x15 == cpu.regs[A]); T(flags(&cpu, NF)); T(7==step(&cpu)); T(0x90 == cpu.regs[A]); T(flags(&cpu, NF)); T(7==step(&cpu)); T(0x15 == cpu.regs[B]); T(flags(&cpu, NF)); T(4==step(&cpu)); T(0xA5 == cpu.regs[A]); T(flags(&cpu, SF)); T(4==step(&cpu)); T(0x05 == cpu.regs[A]); T(flags(&cpu, PF|CF)); T(4==step(&cpu)); T(0xF0 == cpu.regs[A]); T(flags(&cpu, SF|NF|CF)); T(4==step(&cpu)); T(0x90 == cpu.regs[A]); T(flags(&cpu, SF|PF|NF|CF)); ok(); } fn CPL() void { start("CPL"); const prog = [_]u8 { 0x97, // SUB A 0x2F, // CPL 0x2F, // CPL 0xC6, 0xAA, // ADD A,0xAA 0x2F, // CPL 0x2F, // CPL }; copy(0x0000, &prog); var cpu = makeCPU(); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, ZF|HF|NF)); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|HF|NF)); T(7==step(&cpu)); T(0xAA == cpu.regs[A]); T(flags(&cpu, SF)); T(4==step(&cpu)); T(0x55 == cpu.regs[A]); T(flags(&cpu, SF|HF|NF)); T(4==step(&cpu)); T(0xAA == cpu.regs[A]); T(flags(&cpu, SF|HF|NF)); ok(); } fn CCF_SCF() void { start("CCF/SCF"); const prog = [_]u8{ 0x97, // SUB A 0x37, // SCF 0x3F, // CCF 0xD6, 0xCC, // SUB 0xCC 0x3F, // CCF 0x37, // SCF }; copy(0x0000, &prog); var cpu = makeCPU(); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|CF)); T(4==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|HF)); T(7==step(&cpu)); T(0x34 == cpu.regs[A]); T(flags(&cpu, HF|NF|CF)); T(4==step(&cpu)); T(0x34 == cpu.regs[A]); T(flags(&cpu, HF)); T(4==step(&cpu)); T(0x34 == cpu.regs[A]); T(flags(&cpu, CF)); ok(); } fn NEG() void { start("NEG"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0xED, 0x44, // NEG 0xC6, 0x01, // ADD A,0x01 0xED, 0x44, // NEG 0xD6, 0x80, // SUB A,0x80 0xED, 0x44, // NEG 0xC6, 0x40, // ADD A,0x40 0xED, 0x44, // NEG }; copy(0x0000, &prog); var cpu = makeCPU(); T(7==step(&cpu)); T(0x01 == cpu.regs[A]); T(8==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(7==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|HF|CF)); T(8==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(7==step(&cpu)); T(0x80 == cpu.regs[A]); T(flags(&cpu, SF|PF|NF|CF)); T(8==step(&cpu)); T(0x80 == cpu.regs[A]); T(flags(&cpu, SF|PF|NF|CF)); T(7==step(&cpu)); T(0xC0 == cpu.regs[A]); T(flags(&cpu, SF)); T(8==step(&cpu)); T(0x40 == cpu.regs[A]); T(flags(&cpu, NF|CF)); ok(); } fn LDI() void { start("LDI"); const data = [_]u8 { 0x01, 0x02, 0x03 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0x11, 0x00, 0x20, // LD DE,0x2000 0x01, 0x03, 0x00, // LD BC,0x0003 0xED, 0xA0, // LDI 0xED, 0xA0, // LDI 0xED, 0xA0, // LDI }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(16==step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x2001 == cpu.r16(DE)); T(0x0002 == cpu.r16(BC)); T(0x01 == mem[0x2000]); T(flags(&cpu, PF)); T(16==step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x2002 == cpu.r16(DE)); T(0x0001 == cpu.r16(BC)); T(0x02 == mem[0x2001]); T(flags(&cpu, PF)); T(16==step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x2003 == cpu.r16(DE)); T(0x0000 == cpu.r16(BC)); T(0x03 == mem[0x2002]); T(flags(&cpu, 0)); ok(); } fn LDIR() void { start("LDIR"); const data = [_]u8 { 0x01, 0x02, 0x03, }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0x11, 0x00, 0x20, // LD DE,0x2000 0x01, 0x03, 0x00, // LD BC,0x0003 0xED, 0xB0, // LDIR 0x3E, 0x33, // LD A,0x33 }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(21==step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x2001 == cpu.r16(DE)); T(0x0002 == cpu.r16(BC)); T(0x000A == cpu.WZ); T(0x01 == mem[0x2000]); T(flags(&cpu, PF)); T(21==step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x2002 == cpu.r16(DE)); T(0x0001 == cpu.r16(BC)); T(0x000A == cpu.WZ); T(0x02 == mem[0x2001]); T(flags(&cpu, PF)); T(16==step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x2003 == cpu.r16(DE)); T(0x0000 == cpu.r16(BC)); T(0x02 == mem[0x2001]); T(0x03 == mem[0x2002]); T(flags(&cpu, 0)); T(7==step(&cpu)); T(0x33 == cpu.regs[A]); ok(); } fn LDD() void { start("LDD"); const data = [_]u8 { 0x01, 0x02, 0x03 }; const prog = [_]u8 { 0x21, 0x02, 0x10, // LD HL,0x1002 0x11, 0x02, 0x20, // LD DE,0x2002 0x01, 0x03, 0x00, // LD BC,0x0003 0xED, 0xA8, // LDD 0xED, 0xA8, // LDD 0xED, 0xA8, // LDD }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(16==step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x2001 == cpu.r16(DE)); T(0x0002 == cpu.r16(BC)); T(0x03 == mem[0x2002]); T(flags(&cpu, PF)); T(16==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x2000 == cpu.r16(DE)); T(0x0001 == cpu.r16(BC)); T(0x02 == mem[0x2001]); T(flags(&cpu, PF)); T(16 == step(&cpu)); T(0x0FFF == cpu.r16(HL)); T(0x1FFF == cpu.r16(DE)); T(0x0000 == cpu.r16(BC)); T(0x01 == mem[0x2000]); T(flags(&cpu, 0)); ok(); } fn LDDR() void { start("LDDR"); const data = [_]u8 { 0x01, 0x02, 0x03 }; const prog = [_]u8 { 0x21, 0x02, 0x10, // LD HL,0x1002 0x11, 0x02, 0x20, // LD DE,0x2002 0x01, 0x03, 0x00, // LD BC,0x0003 0xED, 0xB8, // LDDR 0x3E, 0x33, // LD A,0x33 }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(21==step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x2001 == cpu.r16(DE)); T(0x0002 == cpu.r16(BC)); T(0x000A == cpu.WZ); T(0x03 == mem[0x2002]); T(flags(&cpu, PF)); T(21==step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x2000 == cpu.r16(DE)); T(0x0001 == cpu.r16(BC)); T(0x000A == cpu.WZ); T(0x02 == mem[0x2001]); T(flags(&cpu, PF)); T(16==step(&cpu)); T(0x0FFF == cpu.r16(HL)); T(0x1FFF == cpu.r16(DE)); T(0x0000 == cpu.r16(BC)); T(0x000A == cpu.WZ); T(0x01 == mem[0x2000]); T(flags(&cpu, 0)); T(7 == step(&cpu)); T(0x33 == cpu.regs[A]); ok(); } fn CPI() void { start("CPI"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // ld hl,0x1000 0x01, 0x04, 0x00, // ld bc,0x0004 0x3e, 0x03, // ld a,0x03 0xed, 0xa1, // cpi 0xed, 0xa1, // cpi 0xed, 0xa1, // cpi 0xed, 0xa1, // cpi }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(16 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(flags(&cpu, PF|NF)); cpu.regs[F] |= CF; T(16 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(flags(&cpu, PF|NF|CF)); T(16 == step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x0001 == cpu.r16(BC)); T(flags(&cpu, ZF|PF|NF|CF)); T(16 == step(&cpu)); T(0x1004 == cpu.r16(HL)); T(0x0000 == cpu.r16(BC)); T(flags(&cpu, SF|HF|NF|CF)); ok(); } fn CPIR() void { start("CPIR"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // ld hl,0x1000 0x01, 0x04, 0x00, // ld bc,0x0004 0x3e, 0x03, // ld a,0x03 0xed, 0xb1, // cpir 0xed, 0xb1, // cpir }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(flags(&cpu, PF|NF)); cpu.regs[F] |= CF; T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(flags(&cpu, PF|NF|CF)); T(16 == step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x0001 == cpu.r16(BC)); T(flags(&cpu, ZF|PF|NF|CF)); T(16 == step(&cpu)); T(0x1004 == cpu.r16(HL)); T(0x0000 == cpu.r16(BC)); T(flags(&cpu, SF|HF|NF|CF)); ok(); } fn CPD() void { start("CPD"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04 }; const prog = [_]u8 { 0x21, 0x03, 0x10, // ld hl,0x1004 0x01, 0x04, 0x00, // ld bc,0x0004 0x3e, 0x02, // ld a,0x03 0xed, 0xa9, // cpi 0xed, 0xa9, // cpi 0xed, 0xa9, // cpi 0xed, 0xa9, // cpi }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(16 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(flags(&cpu, SF|HF|PF|NF)); cpu.regs[F] |= CF; T(16 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(flags(&cpu, SF|HF|PF|NF|CF)); T(16 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x0001 == cpu.r16(BC)); T(flags(&cpu, ZF|PF|NF|CF)); T(16 == step(&cpu)); T(0x0FFF == cpu.r16(HL)); T(0x0000 == cpu.r16(BC)); T(flags(&cpu, NF|CF)); ok(); } fn CPDR() void{ start("CPDR"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04 }; const prog = [_]u8 { 0x21, 0x03, 0x10, // ld hl,0x1004 0x01, 0x04, 0x00, // ld bc,0x0004 0x3e, 0x02, // ld a,0x03 0xed, 0xb9, // cpdr 0xed, 0xb9, // cpdr }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); skip(&cpu, 3); T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(flags(&cpu, SF|HF|PF|NF)); cpu.regs[F] |= CF; T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(flags(&cpu, SF|HF|PF|NF|CF)); T(16 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x0001 == cpu.r16(BC)); T(flags(&cpu, ZF|PF|NF|CF)); T(16 == step(&cpu)); T(0x0FFF == cpu.r16(HL)); T(0x0000 == cpu.r16(BC)); T(flags(&cpu, NF|CF)); ok(); } fn DI_EI_IM() void { start("DI/EI/IM"); const prog = [_]u8 { 0xF3, // DI 0xFB, // EI 0x00, // NOP 0xF3, // DI 0xFB, // EI 0x00, // NOP 0xED, 0x46, // IM 0 0xED, 0x56, // IM 1 0xED, 0x5E, // IM 2 0xED, 0x46, // IM 0 }; copy(0x0000, &prog); var cpu = makeCPU(); T(4==step(&cpu)); T(!cpu.iff1); T(!cpu.iff2); T(4==step(&cpu)); T(cpu.iff1); T(cpu.iff2); T(4==step(&cpu)); T(cpu.iff1); T(cpu.iff2); T(4==step(&cpu)); T(!cpu.iff1); T(!cpu.iff2); T(4==step(&cpu)); T(cpu.iff1); T(cpu.iff2); T(4==step(&cpu)); T(cpu.iff1); T(cpu.iff2); T(8==step(&cpu)); T(0 == cpu.IM); T(8==step(&cpu)); T(1 == cpu.IM); T(8==step(&cpu)); T(2 == cpu.IM); T(8==step(&cpu)); T(0 == cpu.IM); ok(); } fn JP_cc_nn() void{ start("JP cc,nn"); const prog = [_]u8 { 0x97, // SUB A 0xC2, 0x0C, 0x02, // JP NZ,label0 0xCA, 0x0C, 0x02, // JP Z,label0 0x00, // NOP 0xC6, 0x01, // label0: ADD A,0x01 0xCA, 0x15, 0x02, // JP Z,label1 0xC2, 0x15, 0x02, // JP NZ,label1 0x00, // NOP 0x07, // label1: RLCA 0xEA, 0x1D, 0x02, // JP PE,label2 0xE2, 0x1D, 0x02, // JP PO,label2 0x00, // NOP 0xC6, 0xFD, // label2: ADD A,0xFD 0xF2, 0x26, 0x02, // JP P,label3 0xFA, 0x26, 0x02, // JP M,label3 0x00, // NOP 0xD2, 0x2D, 0x02, // label3: JP NC,label4 0xDA, 0x2D, 0x02, // JP C,label4 0x00, // NOP 0x00, // NOP }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.PC = 0x0204; T(4 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(10==step(&cpu)); T(0x0208 == cpu.PC); T(0x020C == cpu.WZ); T(10==step(&cpu)); T(0x020C == cpu.PC); T(0x020C == cpu.WZ); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(10==step(&cpu)); T(0x0211 == cpu.PC); T(10==step(&cpu)); T(0x0215 == cpu.PC); T(4 ==step(&cpu)); T(0x02 == cpu.regs[A]); T(flags(&cpu, 0)); T(10==step(&cpu)); T(0x0219 == cpu.PC); T(10==step(&cpu)); T(0x021D == cpu.PC); T(7 ==step(&cpu)); T(0xFF == cpu.regs[A]); T(flags(&cpu, SF)); T(10==step(&cpu)); T(0x0222 == cpu.PC); T(10==step(&cpu)); T(0x0226 == cpu.PC); T(10==step(&cpu)); T(0x022D == cpu.PC); ok(); } fn JP_JR() void { start("JP/JR"); const prog = [_]u8 { 0x21, 0x16, 0x02, // LD HL,l3 0xDD, 0x21, 0x19, 0x02, // LD IX,l4 0xFD, 0x21, 0x21, 0x02, // LD IY,l5 0xC3, 0x14, 0x02, // JP l0 0x18, 0x04, // l1: JR l2 0x18, 0xFC, // l0: JR l1 0xDD, 0xE9, // l3: JP (IX) 0xE9, // l2: JP (HL) 0xFD, 0xE9, // l4: JP (IY) 0x18, 0x06, // l6: JR l7 0x00, 0x00, 0x00, 0x00, // 4x NOP 0x18, 0xF8, // l5: JR l6 0x00 // l7: NOP }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.PC = 0x0204; T(10==step(&cpu)); T(0x0216 == cpu.r16(HL)); T(14==step(&cpu)); T(0x0219 == cpu.IX); T(14==step(&cpu)); T(0x0221 == cpu.IY); T(10==step(&cpu)); T(0x0214 == cpu.PC); T(0x0214 == cpu.WZ); T(12==step(&cpu)); T(0x0212 == cpu.PC); T(0x0212 == cpu.WZ); T(12==step(&cpu)); T(0x0218 == cpu.PC); T(0x0218 == cpu.WZ); T(4 ==step(&cpu)); T(0x0216 == cpu.PC); T(0x0218 == cpu.WZ); T(8 ==step(&cpu)); T(0x0219 == cpu.PC); T(0x0218 == cpu.WZ); T(8 ==step(&cpu)); T(0x0221 == cpu.PC); T(0x0218 == cpu.WZ); T(12==step(&cpu)); T(0x021B == cpu.PC); T(0x021B == cpu.WZ); T(12==step(&cpu)); T(0x0223 == cpu.PC); T(0x0223 == cpu.WZ); ok(); } fn JR_cc_d() void { start("JR cc,e"); const prog = [_]u8 { 0x97, // SUB A 0x20, 0x03, // JR NZ,l0 0x28, 0x01, // JR Z,l0 0x00, // NOP 0xC6, 0x01, // l0: ADD A,0x01 0x28, 0x03, // JR Z,l1 0x20, 0x01, // JR NZ,l1 0x00, // NOP 0xD6, 0x03, // l1: SUB 0x03 0x30, 0x03, // JR NC,l2 0x38, 0x01, // JR C,l2 0x00, // NOP 0x00, // l2: NOP }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.PC = 0x0204; T(4 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(flags(&cpu, ZF|NF)); T(7 ==step(&cpu)); T(0x0207 == cpu.PC); T(12==step(&cpu)); T(0x020A == cpu.PC); T(0x020A == cpu.WZ); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, 0)); T(7 ==step(&cpu)); T(0x020E == cpu.PC); T(12==step(&cpu)); T(0x0211 == cpu.PC); T(0x0211 == cpu.WZ); T(7 ==step(&cpu)); T(0xFE == cpu.regs[A]); T(flags(&cpu, SF|HF|NF|CF)); T(7 ==step(&cpu)); T(0x0215 == cpu.PC); T(12==step(&cpu)); T(0x0218 == cpu.PC); T(0x0218 == cpu.WZ); ok(); } fn DJNZ() void { start("DJNZ"); const prog = [_]u8 { 0x06, 0x03, // LD B,0x03 0x97, // SUB A 0x3C, // l0: INC A 0x10, 0xFD, // DJNZ l0 0x00, // NOP }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.PC = 0x0204; T(7 ==step(&cpu)); T(0x03 == cpu.regs[B]); T(4 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(4 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(13==step(&cpu)); T(0x02 == cpu.regs[B]); T(0x0207 == cpu.PC); T(0x0207 == cpu.WZ); T(4 ==step(&cpu)); T(0x02 == cpu.regs[A]); T(13==step(&cpu)); T(0x01 == cpu.regs[B]); T(0x0207 == cpu.PC); T(0x0207 == cpu.WZ); T(4 ==step(&cpu)); T(0x03 == cpu.regs[A]); T(8 ==step(&cpu)); T(0x00 == cpu.regs[B]); T(0x020A == cpu.PC); T(0x0207 == cpu.WZ); ok(); } fn CALL_RET() void { start("CALL/RET"); const prog = [_]u8 { 0xCD, 0x0A, 0x02, // CALL l0 0xCD, 0x0A, 0x02, // CALL l0 0xC9, // l0: RET }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.SP = 0x0100; cpu.PC = 0x0204; T(17 == step(&cpu)); T(0x020A == cpu.PC); T(0x020A == cpu.WZ); T(0x00FE == cpu.SP); T(0x07 == mem[0x00FE]); T(0x02 == mem[0x00FF]); T(10 == step(&cpu)); T(0x0207 == cpu.PC); T(0x0207 == cpu.WZ); T(0x0100 == cpu.SP); T(17 == step(&cpu)); T(0x020A == cpu.PC); T(0x020A == cpu.WZ); T(0x00FE == cpu.SP); T(0x0A == mem[0x00FE]); T(0x02 == mem[0x00FF]); T(10 == step(&cpu)); T(0x020A == cpu.PC); T(0x020A == cpu.WZ); T(0x0100 == cpu.SP); ok(); } fn CALL_RET_cc() void { start("CALL/RET cc"); const prog = [_]u8 { 0x97, // SUB A 0xC4, 0x29, 0x02, // CALL NZ,l0 0xCC, 0x29, 0x02, // CALL Z,l0 0xC6, 0x01, // ADD A,0x01 0xCC, 0x2B, 0x02, // CALL Z,l1 0xC4, 0x2B, 0x02, // CALL NZ,l1 0x07, // RLCA 0xEC, 0x2D, 0x02, // CALL PE,l2 0xE4, 0x2D, 0x02, // CALL PO,l2 0xD6, 0x03, // SUB 0x03 0xF4, 0x2F, 0x02, // CALL P,l3 0xFC, 0x2F, 0x02, // CALL M,l3 0xD4, 0x31, 0x02, // CALL NC,l4 0xDC, 0x31, 0x02, // CALL C,l4 0xC9, // RET 0xC0, // l0: RET NZ 0xC8, // RET Z 0xC8, // l1: RET Z 0xC0, // RET NZ 0xE8, // l2: RET PE 0xE0, // RET PO 0xF0, // l3: RET P 0xF8, // RET M 0xD0, // l4: RET NC 0xD8, // RET C }; copy(0x0204, &prog); var cpu = makeCPU(); cpu.PC = 0x0204; cpu.SP = 0x0100; T(4 ==step(&cpu)); T(0x00 == cpu.regs[A]); T(10==step(&cpu)); T(0x0208 == cpu.PC); T(0x0229 == cpu.WZ); T(17==step(&cpu)); T(0x0229 == cpu.PC); T(0x0229 == cpu.WZ); T(5 ==step(&cpu)); T(0x022A == cpu.PC); T(0x0229 == cpu.WZ); T(11==step(&cpu)); T(0x020B == cpu.PC); T(0x020B == cpu.WZ); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(10==step(&cpu)); T(0x0210 == cpu.PC); T(17==step(&cpu)); T(0x022B == cpu.PC); T(5 ==step(&cpu)); T(0x022C == cpu.PC); T(11==step(&cpu)); T(0x0213 == cpu.PC); T(4 ==step(&cpu)); T(0x02 == cpu.regs[A]); T(10==step(&cpu)); T(0x0217 == cpu.PC); T(17==step(&cpu)); T(0x022D == cpu.PC); T(5 ==step(&cpu)); T(0x022E == cpu.PC); T(11==step(&cpu)); T(0x021A == cpu.PC); T(7 ==step(&cpu)); T(0xFF == cpu.regs[A]); T(10==step(&cpu)); T(0x021F == cpu.PC); T(17==step(&cpu)); T(0x022F == cpu.PC); T(5 ==step(&cpu)); T(0x0230 == cpu.PC); T(11==step(&cpu)); T(0x0222 == cpu.PC); T(10==step(&cpu)); T(0x0225 == cpu.PC); T(17==step(&cpu)); T(0x0231 == cpu.PC); T(5 ==step(&cpu)); T(0x0232 == cpu.PC); T(11==step(&cpu)); T(0x0228 == cpu.PC); ok(); } fn ADD_ADC_SBC_16() void { start("ADD/ADC/SBC HL/IX/IY,rp"); const prog = [_]u8 { 0x21, 0xFC, 0x00, // LD HL,0x00FC 0x01, 0x08, 0x00, // LD BC,0x0008 0x11, 0xFF, 0xFF, // LD DE,0xFFFF 0x09, // ADD HL,BC 0x19, // ADD HL,DE 0xED, 0x4A, // ADC HL,BC 0x29, // ADD HL,HL 0x19, // ADD HL,DE 0xED, 0x42, // SBC HL,BC 0xDD, 0x21, 0xFC, 0x00, // LD IX,0x00FC 0x31, 0x00, 0x10, // LD SP,0x1000 0xDD, 0x09, // ADD IX, BC 0xDD, 0x19, // ADD IX, DE 0xDD, 0x29, // ADD IX, IX 0xDD, 0x39, // ADD IX, SP 0xFD, 0x21, 0xFF, 0xFF, // LD IY,0xFFFF 0xFD, 0x09, // ADD IY,BC 0xFD, 0x19, // ADD IY,DE 0xFD, 0x29, // ADD IY,IY 0xFD, 0x39, // ADD IY,SP }; copy(0x0000, &prog); var cpu = makeCPU(); T(10==step(&cpu)); T(0x00FC == cpu.r16(HL)); T(10==step(&cpu)); T(0x0008 == cpu.r16(BC)); T(10==step(&cpu)); T(0xFFFF == cpu.r16(DE)); T(11==step(&cpu)); T(0x0104 == cpu.r16(HL)); T(flags(&cpu, 0)); T(0x00FD == cpu.WZ); T(11==step(&cpu)); T(0x0103 == cpu.r16(HL)); T(flags(&cpu, HF|CF)); T(0x0105 == cpu.WZ); T(15==step(&cpu)); T(0x010C == cpu.r16(HL)); T(flags(&cpu, 0)); T(0x0104 == cpu.WZ); T(11==step(&cpu)); T(0x0218 == cpu.r16(HL)); T(flags(&cpu, 0)); T(0x010D == cpu.WZ); T(11==step(&cpu)); T(0x0217 == cpu.r16(HL)); T(flags(&cpu, HF|CF)); T(0x0219 == cpu.WZ); T(15==step(&cpu)); T(0x020E == cpu.r16(HL)); T(flags(&cpu, NF)); T(0x0218 == cpu.WZ); T(14==step(&cpu)); T(0x00FC == cpu.IX); T(10==step(&cpu)); T(0x1000 == cpu.SP); T(15==step(&cpu)); T(0x0104 == cpu.IX); T(flags(&cpu, 0)); T(0x00FD == cpu.WZ); T(15==step(&cpu)); T(0x0103 == cpu.IX); T(flags(&cpu, HF|CF)); T(0x0105 == cpu.WZ); T(15==step(&cpu)); T(0x0206 == cpu.IX); T(flags(&cpu, 0)); T(0x0104 == cpu.WZ); T(15==step(&cpu)); T(0x1206 == cpu.IX); T(flags(&cpu, 0)); T(0x0207 == cpu.WZ); T(14==step(&cpu)); T(0xFFFF == cpu.IY); T(15==step(&cpu)); T(0x0007 == cpu.IY); T(flags(&cpu, HF|CF)); T(0x0000 == cpu.WZ); T(15==step(&cpu)); T(0x0006 == cpu.IY); T(flags(&cpu, HF|CF)); T(0x0008 == cpu.WZ); T(15==step(&cpu)); T(0x000C == cpu.IY); T(flags(&cpu, 0)); T(0x0007 == cpu.WZ); T(15==step(&cpu)); T(0x100C == cpu.IY); T(flags(&cpu, 0)); T(0x000D == cpu.WZ); ok(); } fn IN() void { start("IN"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0xDB, 0x03, // IN A,(0x03) 0xDB, 0x04, // IN A,(0x04) 0x01, 0x02, 0x02, // LD BC,0x0202 0xED, 0x78, // IN A,(C) 0x01, 0xFF, 0x05, // LD BC,0x05FF 0xED, 0x50, // IN D,(C) 0x01, 0x05, 0x05, // LD BC,0x0505 0xED, 0x58, // IN E,(C) 0x01, 0x06, 0x01, // LD BC,0x0106 0xED, 0x60, // IN H,(C) 0x01, 0x00, 0x10, // LD BC,0x0000 0xED, 0x68, // IN L,(C) 0xED, 0x40, // IN B,(C) 0xED, 0x48, // IN C,(c) }; copy(0x0000, &prog); var cpu = makeCPU(); cpu.regs[F] = HF|CF; T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(flags(&cpu, HF|CF)); T(11==step(&cpu)); T(0x06 == cpu.regs[A]); T(flags(&cpu, HF|CF)); T(0x0104 == cpu.WZ); T(11==step(&cpu)); T(0x08 == cpu.regs[A]); T(flags(&cpu, HF|CF)); T(0x0605 == cpu.WZ); T(10==step(&cpu)); T(0x0202 == cpu.r16(BC)); T(12==step(&cpu)); T(0x04 == cpu.regs[A]); T(flags(&cpu, CF)); T(0x0203 == cpu.WZ); T(10==step(&cpu)); T(0x05FF == cpu.r16(BC)); T(12==step(&cpu)); T(0xFE == cpu.regs[D]); T(flags(&cpu, SF|CF)); T(0x0600 == cpu.WZ); T(10==step(&cpu)); T(0x0505 == cpu.r16(BC)); T(12==step(&cpu)); T(0x0A == cpu.regs[E]); T(flags(&cpu, PF|CF)); T(0x0506 == cpu.WZ); T(10==step(&cpu)); T(0x0106 == cpu.r16(BC)); T(12==step(&cpu)); T(0x0C == cpu.regs[H]); T(flags(&cpu, PF|CF)); T(0x0107 == cpu.WZ); T(10==step(&cpu)); T(0x1000 == cpu.r16(BC)); T(12==step(&cpu)); T(0x00 == cpu.regs[L]); T(flags(&cpu, ZF|PF|CF)); T(0x1001 == cpu.WZ); T(12==step(&cpu)); T(0x00 == cpu.regs[B]); T(flags(&cpu, ZF|PF|CF)); T(0x1001 == cpu.WZ); T(12==step(&cpu)); T(0x00 == cpu.regs[C]); T(flags(&cpu, ZF|PF|CF)); T(0x0001 == cpu.WZ); ok(); } fn OUT() void { start("OUT"); const prog = [_]u8 { 0x3E, 0x01, // LD A,0x01 0xD3, 0x01, // OUT (0x01),A 0xD3, 0xFF, // OUT (0xFF),A 0x01, 0x34, 0x12, // LD BC,0x1234 0x11, 0x78, 0x56, // LD DE,0x5678 0x21, 0xCD, 0xAB, // LD HL,0xABCD 0xED, 0x79, // OUT (C),A 0xED, 0x41, // OUT (C),B 0xED, 0x49, // OUT (C),C 0xED, 0x51, // OUT (C),D 0xED, 0x59, // OUT (C),E 0xED, 0x61, // OUT (C),H 0xED, 0x69, // OUT (C),L }; copy(0x0000, &prog); var cpu = makeCPU(); T(7 ==step(&cpu)); T(0x01 == cpu.regs[A]); T(11==step(&cpu)); T(0x0101 == out_port); T(0x01 == out_byte); T(0x0102 == cpu.WZ); T(11==step(&cpu)); T(0x01FF == out_port); T(0x01 == out_byte); T(0x0100 == cpu.WZ); T(10==step(&cpu)); T(0x1234 == cpu.r16(BC)); T(10==step(&cpu)); T(0x5678 == cpu.r16(DE)); T(10==step(&cpu)); T(0xABCD == cpu.r16(HL)); T(12==step(&cpu)); T(0x1234 == out_port); T(0x01 == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0x12 == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0x34 == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0x56 == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0x78 == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0xAB == out_byte); T(0x1235 == cpu.WZ); T(12==step(&cpu)); T(0x1234 == out_port); T(0xCD == out_byte); T(0x1235 == cpu.WZ); ok(); } fn INIR_INDR() void { start("INIR/INDR"); const prog = [_]u8{ 0x21, 0x00, 0x10, // LD HL,0x1000 0x01, 0x02, 0x03, // LD BC,0x0302 0xED, 0xB2, // INIR 0x01, 0x03, 0x03, // LD BC,0x0303 0xED, 0xBA // INDR }; copy(0x0000, &prog); var cpu = makeCPU(); T(10 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(10 == step(&cpu)); T(0x0302 == cpu.r16(BC)); T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0202 == cpu.r16(BC)); T(0x04 == mem[0x1000]); T(0 == (cpu.regs[F] & ZF)); T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0102 == cpu.r16(BC)); T(0x04 == mem[0x1001]); T(0 == (cpu.regs[F] & ZF)); T(16 == step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(0x04 == mem[0x1002]); T(0 != (cpu.regs[F] & ZF)); T(10 == step(&cpu)); T(0x0303 == cpu.r16(BC)); T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0203 == cpu.r16(BC)); T(0x06 == mem[0x1003]); T(0 == (cpu.regs[F] & ZF)); T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0103 == cpu.r16(BC)); T(0x06 == mem[0x1002]); T(0 == (cpu.regs[F] & ZF)); T(16 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(0x06 == mem[0x1001]); T(0 != (cpu.regs[F] & ZF)); ok(); } fn OTIR_OTDR() void { start("OTIR/OTDR"); const data = [_]u8 { 0x01, 0x02, 0x03, 0x04 }; const prog = [_]u8 { 0x21, 0x00, 0x10, // LD HL,0x1000 0x01, 0x02, 0x03, // LD BC,0x0302 0xED, 0xB3, // OTIR 0x01, 0x03, 0x03, // LD BC,0x0303 0xED, 0xBB, // OTDR }; copy(0x1000, &data); copy(0x0000, &prog); var cpu = makeCPU(); T(10 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(10 == step(&cpu)); T(0x0302 == cpu.r16(BC)); T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0202 == cpu.r16(BC)); T(0x0202 == out_port); T(0x01 == out_byte); T(0 == (cpu.regs[F] & ZF)); T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0102 == cpu.r16(BC)); T(0x0102 == out_port); T(0x02 == out_byte); T(0 == (cpu.regs[F] & ZF)); T(16 == step(&cpu)); T(0x1003 == cpu.r16(HL)); T(0x0002 == cpu.r16(BC)); T(0x0002 == out_port); T(0x03 == out_byte); T(0 != (cpu.regs[F] & ZF)); T(10 == step(&cpu)); T(0x0303 == cpu.r16(BC)); T(21 == step(&cpu)); T(0x1002 == cpu.r16(HL)); T(0x0203 == cpu.r16(BC)); T(0x0203 == out_port); T(0x04 == out_byte); T(0 == (cpu.regs[F] & ZF)); T(21 == step(&cpu)); T(0x1001 == cpu.r16(HL)); T(0x0103 == cpu.r16(BC)); T(0x0103 == out_port); T(0x03 == out_byte); T(0 == (cpu.regs[F] & ZF)); T(16 == step(&cpu)); T(0x1000 == cpu.r16(HL)); T(0x0003 == cpu.r16(BC)); T(0x0003 == out_port); T(0x02 == out_byte); T(0 != (cpu.regs[F] & ZF)); ok(); } fn IRQ() void { start("IRQ"); // a special version of the tick callback to test interrupt handling const inner = struct { var reti_executed = false; fn inner_tick(num_ticks: usize, pins_in: u64, userdata: usize) u64 { _ = num_ticks; _ = userdata; var pins = pins_in; if ((pins & MREQ) != 0) { if ((pins & RD) != 0) { pins = CPU.setData(pins, mem[CPU.getAddr(pins)]); } else if ((pins & WR) != 0) { mem[CPU.getAddr(pins)] = CPU.getData(pins); } } else if ((pins & IORQ) != 0) { if ((pins & RD) != 0) { pins = CPU.setData(pins, 0xFF); } else if ((pins & WR) != 0) { // request interrupt when a IORQ|WR happens pins |= INT; } else if ((pins & M1) != 0) { // an interrupt ackowledge cycle, need to provide interrupt vector pins = CPU.setData(pins, 0xE0); } } if (0 != (pins & RETI)) { // reti was executed reti_executed = true; pins &= ~RETI; } return pins; } fn step(cpu: *CPU) usize { var ticks = cpu.exec(0, .{ .func=inner_tick, .userdata=0 }); while (!cpu.opdone()) { ticks += cpu.exec(0, .{ .func=inner_tick, .userdata=0 }); } return ticks; } }; // the main program loads I with 0, and executes an OUT, // which triggeres an interrupt, afterwards load some // value into HL const prog = [_]u8 { 0x31, 0x00, 0x03, // LD SP,0x0300 0xFB, // EI 0xED, 0x5E, // IM 2 0xAF, // XOR A 0xED, 0x47, // LD I,A 0xD3, 0x01, // OUT (0x01),A -> this should request an interrupt 0x21, 0x33, 0x33, // LD HL,0x3333 }; copy(0x0100, &prog); // the interrupt service routine const isr = [_]u8 { 0xFB, // EI 0x21, 0x11, 0x11, // LD HL,0x1111 0xED, 0x4D, // RETI }; copy(0x0200, &isr); // interrupt vector at 0x00E0 points to ISR at 0x0200 w16(0x00E0, 0x0200); var cpu = makeCPU(); cpu.PC = 0x0100; T(10 == inner.step(&cpu)); T(cpu.SP == 0x0300); // LD SP, 0x0300) T(4 == inner.step(&cpu)); T(cpu.iff1); // EI T(8 == inner.step(&cpu)); T(cpu.iff2); T(cpu.IM == 2); // IM 2 T(4 == inner.step(&cpu)); T(cpu.regs[A] == 0); // XOR A T(9 == inner.step(&cpu)); T(cpu.I == 0); // LD I,A T(29 == inner.step(&cpu)); T(cpu.PC == 0x0200); T(cpu.iff2 == false); T(cpu.SP == 0x02FE); // OUT (0x01),A T(4 == inner.step(&cpu)); T(cpu.iff2); // EI T(10 == inner.step(&cpu)); T(cpu.r16(HL) == 0x1111); T(cpu.iff2 == true); // LD HL,0x1111 T(14 == inner.step(&cpu)); T(cpu.PC == 0x010B); T(inner.reti_executed); // RETI _ = inner.step(&cpu); T(cpu.r16(HL) == 0x3333); // LD HL,0x3333 ok(); } pub fn main() void { LD_A_RI(); LD_IR_A(); LD_r_sn(); LD_r_iHLi(); LD_iHLi_r(); LD_iHLi_n(); LD_iIXIYi_r(); LD_iIXIYi_n(); LD_ddIXIY_nn(); LD_A_iBCDEnni(); LD_iBCDEnni_A(); LD_HLddIXIY_inni(); LD_inni_HLddIXIY(); LD_SP_HLIXIY(); PUSH_POP_qqIXIY(); EX(); ADD_rn(); ADD_iHLIXIYi(); ADC_rn(); ADC_iHLIXIYi(); SUB_rn(); SUB_iHLIXIYi(); SBC_rn(); SBC_iHLIXIYi(); CP_rn(); CP_iHLIXIYi(); AND_rn(); AND_iHLIXIYi(); XOR_rn(); OR_rn(); OR_XOR_iHLIXIYi(); INC_DEC_r(); INC_DEC_iHLIXIYi(); INC_DEC_ssIXIY(); RLCA_RLA_RRCA_RRA(); RLC_RL_RRC_RR_r(); RRC_RLC_RR_RL_iHLIXIYi(); SLA_r(); SLA_iHLIXIYi(); SRA_r(); SRA_iHLIXIYi(); SRL_r(); SRL_iHLIXIYi(); RLD_RRD(); HALTx(); BIT(); SET(); RES(); DAA(); CPL(); CCF_SCF(); NEG(); LDI(); LDIR(); LDD(); LDDR(); CPI(); CPIR(); CPD(); CPDR(); DI_EI_IM(); JP_cc_nn(); JP_JR(); JR_cc_d(); DJNZ(); CALL_RET(); CALL_RET_cc(); ADD_ADC_SBC_16(); IN(); OUT(); INIR_INDR(); OTIR_OTDR(); IRQ(); }
tests/z80test.zig
const std = @import("std"); pub const builtin = @import("builtin"); pub const SourceLocation = extern struct { ID: c_uint, pub const eq = ZigClangSourceLocation_eq; extern fn ZigClangSourceLocation_eq(a: SourceLocation, b: SourceLocation) bool; }; pub const QualType = extern struct { ptr: ?*c_void, pub const getCanonicalType = ZigClangQualType_getCanonicalType; extern fn ZigClangQualType_getCanonicalType(QualType) QualType; pub const getTypePtr = ZigClangQualType_getTypePtr; extern fn ZigClangQualType_getTypePtr(QualType) *const Type; pub const getTypeClass = ZigClangQualType_getTypeClass; extern fn ZigClangQualType_getTypeClass(QualType) TypeClass; pub const addConst = ZigClangQualType_addConst; extern fn ZigClangQualType_addConst(*QualType) void; pub const eq = ZigClangQualType_eq; extern fn ZigClangQualType_eq(QualType, arg1: QualType) bool; pub const isConstQualified = ZigClangQualType_isConstQualified; extern fn ZigClangQualType_isConstQualified(QualType) bool; pub const isVolatileQualified = ZigClangQualType_isVolatileQualified; extern fn ZigClangQualType_isVolatileQualified(QualType) bool; pub const isRestrictQualified = ZigClangQualType_isRestrictQualified; extern fn ZigClangQualType_isRestrictQualified(QualType) bool; }; pub const APValueLValueBase = extern struct { Ptr: ?*c_void, CallIndex: c_uint, Version: c_uint, pub const dyn_cast_Expr = ZigClangAPValueLValueBase_dyn_cast_Expr; extern fn ZigClangAPValueLValueBase_dyn_cast_Expr(APValueLValueBase) ?*const Expr; }; pub const APValueKind = extern enum { None, Indeterminate, Int, Float, FixedPoint, ComplexInt, ComplexFloat, LValue, Vector, Array, Struct, Union, MemberPointer, AddrLabelDiff, }; pub const APValue = extern struct { Kind: APValueKind, Data: if (builtin.os.tag == .windows and builtin.abi == .msvc) [52]u8 else [68]u8, pub const getKind = ZigClangAPValue_getKind; extern fn ZigClangAPValue_getKind(*const APValue) APValueKind; pub const getInt = ZigClangAPValue_getInt; extern fn ZigClangAPValue_getInt(*const APValue) *const APSInt; pub const getArrayInitializedElts = ZigClangAPValue_getArrayInitializedElts; extern fn ZigClangAPValue_getArrayInitializedElts(*const APValue) c_uint; pub const getArraySize = ZigClangAPValue_getArraySize; extern fn ZigClangAPValue_getArraySize(*const APValue) c_uint; pub const getLValueBase = ZigClangAPValue_getLValueBase; extern fn ZigClangAPValue_getLValueBase(*const APValue) APValueLValueBase; }; pub const ExprEvalResult = extern struct { HasSideEffects: bool, HasUndefinedBehavior: bool, SmallVectorImpl: ?*c_void, Val: APValue, }; pub const AbstractConditionalOperator = opaque { pub const getCond = ZigClangAbstractConditionalOperator_getCond; extern fn ZigClangAbstractConditionalOperator_getCond(*const AbstractConditionalOperator) *const Expr; pub const getTrueExpr = ZigClangAbstractConditionalOperator_getTrueExpr; extern fn ZigClangAbstractConditionalOperator_getTrueExpr(*const AbstractConditionalOperator) *const Expr; pub const getFalseExpr = ZigClangAbstractConditionalOperator_getFalseExpr; extern fn ZigClangAbstractConditionalOperator_getFalseExpr(*const AbstractConditionalOperator) *const Expr; }; pub const APFloat = opaque { pub const toString = ZigClangAPFloat_toString; extern fn ZigClangAPFloat_toString(*const APFloat, precision: c_uint, maxPadding: c_uint, truncateZero: bool) [*:0]const u8; }; pub const APFloatBaseSemantics = extern enum { IEEEhalf, BFloat, IEEEsingle, IEEEdouble, x86DoubleExtended, IEEEquad, PPCDoubleDouble, }; pub const APInt = opaque { pub fn getLimitedValue(self: *const APInt, comptime T: type) T { return @truncate(T, ZigClangAPInt_getLimitedValue(self, std.math.maxInt(T))); } extern fn ZigClangAPInt_getLimitedValue(*const APInt, limit: u64) u64; }; pub const APSInt = opaque { pub const isSigned = ZigClangAPSInt_isSigned; extern fn ZigClangAPSInt_isSigned(*const APSInt) bool; pub const isNegative = ZigClangAPSInt_isNegative; extern fn ZigClangAPSInt_isNegative(*const APSInt) bool; pub const negate = ZigClangAPSInt_negate; extern fn ZigClangAPSInt_negate(*const APSInt) *const APSInt; pub const free = ZigClangAPSInt_free; extern fn ZigClangAPSInt_free(*const APSInt) void; pub const getRawData = ZigClangAPSInt_getRawData; extern fn ZigClangAPSInt_getRawData(*const APSInt) [*:0]const u64; pub const getNumWords = ZigClangAPSInt_getNumWords; extern fn ZigClangAPSInt_getNumWords(*const APSInt) c_uint; pub const lessThanEqual = ZigClangAPSInt_lessThanEqual; extern fn ZigClangAPSInt_lessThanEqual(*const APSInt, rhs: u64) bool; }; pub const ASTContext = opaque { pub const getPointerType = ZigClangASTContext_getPointerType; extern fn ZigClangASTContext_getPointerType(*const ASTContext, T: QualType) QualType; }; pub const ASTUnit = opaque { pub const delete = ZigClangASTUnit_delete; extern fn ZigClangASTUnit_delete(*ASTUnit) void; pub const getASTContext = ZigClangASTUnit_getASTContext; extern fn ZigClangASTUnit_getASTContext(*ASTUnit) *ASTContext; pub const getSourceManager = ZigClangASTUnit_getSourceManager; extern fn ZigClangASTUnit_getSourceManager(*ASTUnit) *SourceManager; pub const visitLocalTopLevelDecls = ZigClangASTUnit_visitLocalTopLevelDecls; extern fn ZigClangASTUnit_visitLocalTopLevelDecls(*ASTUnit, context: ?*c_void, Fn: ?fn (?*c_void, *const Decl) callconv(.C) bool) bool; pub const getLocalPreprocessingEntities_begin = ZigClangASTUnit_getLocalPreprocessingEntities_begin; extern fn ZigClangASTUnit_getLocalPreprocessingEntities_begin(*ASTUnit) PreprocessingRecord.iterator; pub const getLocalPreprocessingEntities_end = ZigClangASTUnit_getLocalPreprocessingEntities_end; extern fn ZigClangASTUnit_getLocalPreprocessingEntities_end(*ASTUnit) PreprocessingRecord.iterator; }; pub const ArraySubscriptExpr = opaque { pub const getBase = ZigClangArraySubscriptExpr_getBase; extern fn ZigClangArraySubscriptExpr_getBase(*const ArraySubscriptExpr) *const Expr; pub const getIdx = ZigClangArraySubscriptExpr_getIdx; extern fn ZigClangArraySubscriptExpr_getIdx(*const ArraySubscriptExpr) *const Expr; }; pub const ArrayType = opaque { pub const getElementType = ZigClangArrayType_getElementType; extern fn ZigClangArrayType_getElementType(*const ArrayType) QualType; }; pub const AttributedType = opaque { pub const getEquivalentType = ZigClangAttributedType_getEquivalentType; extern fn ZigClangAttributedType_getEquivalentType(*const AttributedType) QualType; }; pub const BinaryOperator = opaque { pub const getOpcode = ZigClangBinaryOperator_getOpcode; extern fn ZigClangBinaryOperator_getOpcode(*const BinaryOperator) BO; pub const getBeginLoc = ZigClangBinaryOperator_getBeginLoc; extern fn ZigClangBinaryOperator_getBeginLoc(*const BinaryOperator) SourceLocation; pub const getLHS = ZigClangBinaryOperator_getLHS; extern fn ZigClangBinaryOperator_getLHS(*const BinaryOperator) *const Expr; pub const getRHS = ZigClangBinaryOperator_getRHS; extern fn ZigClangBinaryOperator_getRHS(*const BinaryOperator) *const Expr; pub const getType = ZigClangBinaryOperator_getType; extern fn ZigClangBinaryOperator_getType(*const BinaryOperator) QualType; }; pub const BinaryConditionalOperator = opaque {}; pub const BreakStmt = opaque {}; pub const BuiltinType = opaque { pub const getKind = ZigClangBuiltinType_getKind; extern fn ZigClangBuiltinType_getKind(*const BuiltinType) BuiltinTypeKind; }; pub const CStyleCastExpr = opaque { pub const getBeginLoc = ZigClangCStyleCastExpr_getBeginLoc; extern fn ZigClangCStyleCastExpr_getBeginLoc(*const CStyleCastExpr) SourceLocation; pub const getSubExpr = ZigClangCStyleCastExpr_getSubExpr; extern fn ZigClangCStyleCastExpr_getSubExpr(*const CStyleCastExpr) *const Expr; pub const getType = ZigClangCStyleCastExpr_getType; extern fn ZigClangCStyleCastExpr_getType(*const CStyleCastExpr) QualType; }; pub const CallExpr = opaque { pub const getCallee = ZigClangCallExpr_getCallee; extern fn ZigClangCallExpr_getCallee(*const CallExpr) *const Expr; pub const getNumArgs = ZigClangCallExpr_getNumArgs; extern fn ZigClangCallExpr_getNumArgs(*const CallExpr) c_uint; pub const getArgs = ZigClangCallExpr_getArgs; extern fn ZigClangCallExpr_getArgs(*const CallExpr) [*]const *const Expr; }; pub const CaseStmt = opaque { pub const getLHS = ZigClangCaseStmt_getLHS; extern fn ZigClangCaseStmt_getLHS(*const CaseStmt) *const Expr; pub const getRHS = ZigClangCaseStmt_getRHS; extern fn ZigClangCaseStmt_getRHS(*const CaseStmt) ?*const Expr; pub const getBeginLoc = ZigClangCaseStmt_getBeginLoc; extern fn ZigClangCaseStmt_getBeginLoc(*const CaseStmt) SourceLocation; pub const getSubStmt = ZigClangCaseStmt_getSubStmt; extern fn ZigClangCaseStmt_getSubStmt(*const CaseStmt) *const Stmt; }; pub const CharacterLiteral = opaque { pub const getBeginLoc = ZigClangCharacterLiteral_getBeginLoc; extern fn ZigClangCharacterLiteral_getBeginLoc(*const CharacterLiteral) SourceLocation; pub const getKind = ZigClangCharacterLiteral_getKind; extern fn ZigClangCharacterLiteral_getKind(*const CharacterLiteral) CharacterLiteral_CharacterKind; pub const getValue = ZigClangCharacterLiteral_getValue; extern fn ZigClangCharacterLiteral_getValue(*const CharacterLiteral) c_uint; }; pub const CompoundAssignOperator = opaque { pub const getType = ZigClangCompoundAssignOperator_getType; extern fn ZigClangCompoundAssignOperator_getType(*const CompoundAssignOperator) QualType; pub const getComputationLHSType = ZigClangCompoundAssignOperator_getComputationLHSType; extern fn ZigClangCompoundAssignOperator_getComputationLHSType(*const CompoundAssignOperator) QualType; pub const getComputationResultType = ZigClangCompoundAssignOperator_getComputationResultType; extern fn ZigClangCompoundAssignOperator_getComputationResultType(*const CompoundAssignOperator) QualType; pub const getBeginLoc = ZigClangCompoundAssignOperator_getBeginLoc; extern fn ZigClangCompoundAssignOperator_getBeginLoc(*const CompoundAssignOperator) SourceLocation; pub const getOpcode = ZigClangCompoundAssignOperator_getOpcode; extern fn ZigClangCompoundAssignOperator_getOpcode(*const CompoundAssignOperator) BO; pub const getLHS = ZigClangCompoundAssignOperator_getLHS; extern fn ZigClangCompoundAssignOperator_getLHS(*const CompoundAssignOperator) *const Expr; pub const getRHS = ZigClangCompoundAssignOperator_getRHS; extern fn ZigClangCompoundAssignOperator_getRHS(*const CompoundAssignOperator) *const Expr; }; pub const CompoundLiteralExpr = opaque { pub const getInitializer = ZigClangCompoundLiteralExpr_getInitializer; extern fn ZigClangCompoundLiteralExpr_getInitializer(*const CompoundLiteralExpr) *const Expr; }; pub const CompoundStmt = opaque { pub const body_begin = ZigClangCompoundStmt_body_begin; extern fn ZigClangCompoundStmt_body_begin(*const CompoundStmt) ConstBodyIterator; pub const body_end = ZigClangCompoundStmt_body_end; extern fn ZigClangCompoundStmt_body_end(*const CompoundStmt) ConstBodyIterator; pub const ConstBodyIterator = [*]const *Stmt; }; pub const ConditionalOperator = opaque {}; pub const ConstantArrayType = opaque { pub const getElementType = ZigClangConstantArrayType_getElementType; extern fn ZigClangConstantArrayType_getElementType(*const ConstantArrayType) QualType; pub const getSize = ZigClangConstantArrayType_getSize; extern fn ZigClangConstantArrayType_getSize(*const ConstantArrayType) *const APInt; }; pub const ConstantExpr = opaque {}; pub const ContinueStmt = opaque {}; pub const ConvertVectorExpr = opaque { pub const getSrcExpr = ZigClangConvertVectorExpr_getSrcExpr; extern fn ZigClangConvertVectorExpr_getSrcExpr(*const ConvertVectorExpr) *const Expr; pub const getTypeSourceInfo_getType = ZigClangConvertVectorExpr_getTypeSourceInfo_getType; extern fn ZigClangConvertVectorExpr_getTypeSourceInfo_getType(*const ConvertVectorExpr) QualType; }; pub const DecayedType = opaque { pub const getDecayedType = ZigClangDecayedType_getDecayedType; extern fn ZigClangDecayedType_getDecayedType(*const DecayedType) QualType; }; pub const Decl = opaque { pub const getLocation = ZigClangDecl_getLocation; extern fn ZigClangDecl_getLocation(*const Decl) SourceLocation; pub const castToNamedDecl = ZigClangDecl_castToNamedDecl; extern fn ZigClangDecl_castToNamedDecl(decl: *const Decl) ?*const NamedDecl; pub const getKind = ZigClangDecl_getKind; extern fn ZigClangDecl_getKind(decl: *const Decl) DeclKind; pub const getDeclKindName = ZigClangDecl_getDeclKindName; extern fn ZigClangDecl_getDeclKindName(decl: *const Decl) [*:0]const u8; }; pub const DeclRefExpr = opaque { pub const getDecl = ZigClangDeclRefExpr_getDecl; extern fn ZigClangDeclRefExpr_getDecl(*const DeclRefExpr) *const ValueDecl; pub const getFoundDecl = ZigClangDeclRefExpr_getFoundDecl; extern fn ZigClangDeclRefExpr_getFoundDecl(*const DeclRefExpr) *const NamedDecl; }; pub const DeclStmt = opaque { pub const decl_begin = ZigClangDeclStmt_decl_begin; extern fn ZigClangDeclStmt_decl_begin(*const DeclStmt) const_decl_iterator; pub const decl_end = ZigClangDeclStmt_decl_end; extern fn ZigClangDeclStmt_decl_end(*const DeclStmt) const_decl_iterator; pub const const_decl_iterator = [*]const *Decl; }; pub const DefaultStmt = opaque { pub const getSubStmt = ZigClangDefaultStmt_getSubStmt; extern fn ZigClangDefaultStmt_getSubStmt(*const DefaultStmt) *const Stmt; }; pub const DiagnosticOptions = opaque {}; pub const DiagnosticsEngine = opaque {}; pub const DoStmt = opaque { pub const getCond = ZigClangDoStmt_getCond; extern fn ZigClangDoStmt_getCond(*const DoStmt) *const Expr; pub const getBody = ZigClangDoStmt_getBody; extern fn ZigClangDoStmt_getBody(*const DoStmt) *const Stmt; }; pub const ElaboratedType = opaque { pub const getNamedType = ZigClangElaboratedType_getNamedType; extern fn ZigClangElaboratedType_getNamedType(*const ElaboratedType) QualType; }; pub const EnumConstantDecl = opaque { pub const getInitExpr = ZigClangEnumConstantDecl_getInitExpr; extern fn ZigClangEnumConstantDecl_getInitExpr(*const EnumConstantDecl) ?*const Expr; pub const getInitVal = ZigClangEnumConstantDecl_getInitVal; extern fn ZigClangEnumConstantDecl_getInitVal(*const EnumConstantDecl) *const APSInt; }; pub const EnumDecl = opaque { pub const getCanonicalDecl = ZigClangEnumDecl_getCanonicalDecl; extern fn ZigClangEnumDecl_getCanonicalDecl(*const EnumDecl) ?*const TagDecl; pub const getIntegerType = ZigClangEnumDecl_getIntegerType; extern fn ZigClangEnumDecl_getIntegerType(*const EnumDecl) QualType; pub const getDefinition = ZigClangEnumDecl_getDefinition; extern fn ZigClangEnumDecl_getDefinition(*const EnumDecl) ?*const EnumDecl; pub const getLocation = ZigClangEnumDecl_getLocation; extern fn ZigClangEnumDecl_getLocation(*const EnumDecl) SourceLocation; pub const enumerator_begin = ZigClangEnumDecl_enumerator_begin; extern fn ZigClangEnumDecl_enumerator_begin(*const EnumDecl) enumerator_iterator; pub const enumerator_end = ZigClangEnumDecl_enumerator_end; extern fn ZigClangEnumDecl_enumerator_end(*const EnumDecl) enumerator_iterator; pub const enumerator_iterator = extern struct { ptr: *c_void, pub const next = ZigClangEnumDecl_enumerator_iterator_next; extern fn ZigClangEnumDecl_enumerator_iterator_next(enumerator_iterator) enumerator_iterator; pub const deref = ZigClangEnumDecl_enumerator_iterator_deref; extern fn ZigClangEnumDecl_enumerator_iterator_deref(enumerator_iterator) *const EnumConstantDecl; pub const neq = ZigClangEnumDecl_enumerator_iterator_neq; extern fn ZigClangEnumDecl_enumerator_iterator_neq(enumerator_iterator, enumerator_iterator) bool; }; }; pub const EnumType = opaque { pub const getDecl = ZigClangEnumType_getDecl; extern fn ZigClangEnumType_getDecl(*const EnumType) *const EnumDecl; }; pub const Expr = opaque { pub const getStmtClass = ZigClangExpr_getStmtClass; extern fn ZigClangExpr_getStmtClass(*const Expr) StmtClass; pub const getType = ZigClangExpr_getType; extern fn ZigClangExpr_getType(*const Expr) QualType; pub const getBeginLoc = ZigClangExpr_getBeginLoc; extern fn ZigClangExpr_getBeginLoc(*const Expr) SourceLocation; pub const evaluateAsConstantExpr = ZigClangExpr_EvaluateAsConstantExpr; extern fn ZigClangExpr_EvaluateAsConstantExpr(*const Expr, *ExprEvalResult, Expr_ConstantExprKind, *const ASTContext) bool; }; pub const FieldDecl = opaque { pub const getCanonicalDecl = ZigClangFieldDecl_getCanonicalDecl; extern fn ZigClangFieldDecl_getCanonicalDecl(*const FieldDecl) ?*const FieldDecl; pub const getAlignedAttribute = ZigClangFieldDecl_getAlignedAttribute; extern fn ZigClangFieldDecl_getAlignedAttribute(*const FieldDecl, *const ASTContext) c_uint; pub const isAnonymousStructOrUnion = ZigClangFieldDecl_isAnonymousStructOrUnion; extern fn ZigClangFieldDecl_isAnonymousStructOrUnion(*const FieldDecl) bool; pub const isBitField = ZigClangFieldDecl_isBitField; extern fn ZigClangFieldDecl_isBitField(*const FieldDecl) bool; pub const getType = ZigClangFieldDecl_getType; extern fn ZigClangFieldDecl_getType(*const FieldDecl) QualType; pub const getLocation = ZigClangFieldDecl_getLocation; extern fn ZigClangFieldDecl_getLocation(*const FieldDecl) SourceLocation; pub const getParent = ZigClangFieldDecl_getParent; extern fn ZigClangFieldDecl_getParent(*const FieldDecl) ?*const RecordDecl; }; pub const FileID = opaque {}; pub const FloatingLiteral = opaque { pub const getValueAsApproximateDouble = ZigClangFloatingLiteral_getValueAsApproximateDouble; extern fn ZigClangFloatingLiteral_getValueAsApproximateDouble(*const FloatingLiteral) f64; pub const getBeginLoc = ZigClangIntegerLiteral_getBeginLoc; extern fn ZigClangIntegerLiteral_getBeginLoc(*const FloatingLiteral) SourceLocation; pub const getRawSemantics = ZigClangFloatingLiteral_getRawSemantics; extern fn ZigClangFloatingLiteral_getRawSemantics(*const FloatingLiteral) APFloatBaseSemantics; }; pub const ForStmt = opaque { pub const getInit = ZigClangForStmt_getInit; extern fn ZigClangForStmt_getInit(*const ForStmt) ?*const Stmt; pub const getCond = ZigClangForStmt_getCond; extern fn ZigClangForStmt_getCond(*const ForStmt) ?*const Expr; pub const getInc = ZigClangForStmt_getInc; extern fn ZigClangForStmt_getInc(*const ForStmt) ?*const Expr; pub const getBody = ZigClangForStmt_getBody; extern fn ZigClangForStmt_getBody(*const ForStmt) *const Stmt; }; pub const FullSourceLoc = opaque {}; pub const FunctionDecl = opaque { pub const getType = ZigClangFunctionDecl_getType; extern fn ZigClangFunctionDecl_getType(*const FunctionDecl) QualType; pub const getLocation = ZigClangFunctionDecl_getLocation; extern fn ZigClangFunctionDecl_getLocation(*const FunctionDecl) SourceLocation; pub const hasBody = ZigClangFunctionDecl_hasBody; extern fn ZigClangFunctionDecl_hasBody(*const FunctionDecl) bool; pub const getStorageClass = ZigClangFunctionDecl_getStorageClass; extern fn ZigClangFunctionDecl_getStorageClass(*const FunctionDecl) StorageClass; pub const getParamDecl = ZigClangFunctionDecl_getParamDecl; extern fn ZigClangFunctionDecl_getParamDecl(*const FunctionDecl, i: c_uint) *const ParmVarDecl; pub const getBody = ZigClangFunctionDecl_getBody; extern fn ZigClangFunctionDecl_getBody(*const FunctionDecl) *const Stmt; pub const doesDeclarationForceExternallyVisibleDefinition = ZigClangFunctionDecl_doesDeclarationForceExternallyVisibleDefinition; extern fn ZigClangFunctionDecl_doesDeclarationForceExternallyVisibleDefinition(*const FunctionDecl) bool; pub const isThisDeclarationADefinition = ZigClangFunctionDecl_isThisDeclarationADefinition; extern fn ZigClangFunctionDecl_isThisDeclarationADefinition(*const FunctionDecl) bool; pub const doesThisDeclarationHaveABody = ZigClangFunctionDecl_doesThisDeclarationHaveABody; extern fn ZigClangFunctionDecl_doesThisDeclarationHaveABody(*const FunctionDecl) bool; pub const isInlineSpecified = ZigClangFunctionDecl_isInlineSpecified; extern fn ZigClangFunctionDecl_isInlineSpecified(*const FunctionDecl) bool; pub const isDefined = ZigClangFunctionDecl_isDefined; extern fn ZigClangFunctionDecl_isDefined(*const FunctionDecl) bool; pub const getDefinition = ZigClangFunctionDecl_getDefinition; extern fn ZigClangFunctionDecl_getDefinition(*const FunctionDecl) ?*const FunctionDecl; pub const getSectionAttribute = ZigClangFunctionDecl_getSectionAttribute; extern fn ZigClangFunctionDecl_getSectionAttribute(*const FunctionDecl, len: *usize) ?[*]const u8; pub const getCanonicalDecl = ZigClangFunctionDecl_getCanonicalDecl; extern fn ZigClangFunctionDecl_getCanonicalDecl(*const FunctionDecl) ?*const FunctionDecl; pub const getAlignedAttribute = ZigClangFunctionDecl_getAlignedAttribute; extern fn ZigClangFunctionDecl_getAlignedAttribute(*const FunctionDecl, *const ASTContext) c_uint; }; pub const FunctionProtoType = opaque { pub const isVariadic = ZigClangFunctionProtoType_isVariadic; extern fn ZigClangFunctionProtoType_isVariadic(*const FunctionProtoType) bool; pub const getNumParams = ZigClangFunctionProtoType_getNumParams; extern fn ZigClangFunctionProtoType_getNumParams(*const FunctionProtoType) c_uint; pub const getParamType = ZigClangFunctionProtoType_getParamType; extern fn ZigClangFunctionProtoType_getParamType(*const FunctionProtoType, i: c_uint) QualType; pub const getReturnType = ZigClangFunctionProtoType_getReturnType; extern fn ZigClangFunctionProtoType_getReturnType(*const FunctionProtoType) QualType; }; pub const FunctionType = opaque { pub const getNoReturnAttr = ZigClangFunctionType_getNoReturnAttr; extern fn ZigClangFunctionType_getNoReturnAttr(*const FunctionType) bool; pub const getCallConv = ZigClangFunctionType_getCallConv; extern fn ZigClangFunctionType_getCallConv(*const FunctionType) CallingConv; pub const getReturnType = ZigClangFunctionType_getReturnType; extern fn ZigClangFunctionType_getReturnType(*const FunctionType) QualType; }; pub const GenericSelectionExpr = opaque { pub const getResultExpr = ZigClangGenericSelectionExpr_getResultExpr; extern fn ZigClangGenericSelectionExpr_getResultExpr(*const GenericSelectionExpr) *const Expr; }; pub const IfStmt = opaque { pub const getThen = ZigClangIfStmt_getThen; extern fn ZigClangIfStmt_getThen(*const IfStmt) *const Stmt; pub const getElse = ZigClangIfStmt_getElse; extern fn ZigClangIfStmt_getElse(*const IfStmt) ?*const Stmt; pub const getCond = ZigClangIfStmt_getCond; extern fn ZigClangIfStmt_getCond(*const IfStmt) *const Stmt; }; pub const ImplicitCastExpr = opaque { pub const getBeginLoc = ZigClangImplicitCastExpr_getBeginLoc; extern fn ZigClangImplicitCastExpr_getBeginLoc(*const ImplicitCastExpr) SourceLocation; pub const getCastKind = ZigClangImplicitCastExpr_getCastKind; extern fn ZigClangImplicitCastExpr_getCastKind(*const ImplicitCastExpr) CK; pub const getSubExpr = ZigClangImplicitCastExpr_getSubExpr; extern fn ZigClangImplicitCastExpr_getSubExpr(*const ImplicitCastExpr) *const Expr; }; pub const IncompleteArrayType = opaque { pub const getElementType = ZigClangIncompleteArrayType_getElementType; extern fn ZigClangIncompleteArrayType_getElementType(*const IncompleteArrayType) QualType; }; pub const IntegerLiteral = opaque { pub const EvaluateAsInt = ZigClangIntegerLiteral_EvaluateAsInt; extern fn ZigClangIntegerLiteral_EvaluateAsInt(*const IntegerLiteral, *ExprEvalResult, *const ASTContext) bool; pub const getBeginLoc = ZigClangIntegerLiteral_getBeginLoc; extern fn ZigClangIntegerLiteral_getBeginLoc(*const IntegerLiteral) SourceLocation; pub const isZero = ZigClangIntegerLiteral_isZero; extern fn ZigClangIntegerLiteral_isZero(*const IntegerLiteral, *bool, *const ASTContext) bool; }; /// This is just used as a namespace for a static method on clang's Lexer class; we don't directly /// deal with Lexer objects pub const Lexer = struct { pub const getLocForEndOfToken = ZigClangLexer_getLocForEndOfToken; extern fn ZigClangLexer_getLocForEndOfToken(SourceLocation, *const SourceManager, *const ASTUnit) SourceLocation; }; pub const MacroDefinitionRecord = opaque { pub const getName_getNameStart = ZigClangMacroDefinitionRecord_getName_getNameStart; extern fn ZigClangMacroDefinitionRecord_getName_getNameStart(*const MacroDefinitionRecord) [*:0]const u8; pub const getSourceRange_getBegin = ZigClangMacroDefinitionRecord_getSourceRange_getBegin; extern fn ZigClangMacroDefinitionRecord_getSourceRange_getBegin(*const MacroDefinitionRecord) SourceLocation; pub const getSourceRange_getEnd = ZigClangMacroDefinitionRecord_getSourceRange_getEnd; extern fn ZigClangMacroDefinitionRecord_getSourceRange_getEnd(*const MacroDefinitionRecord) SourceLocation; }; pub const MacroQualifiedType = opaque { pub const getModifiedType = ZigClangMacroQualifiedType_getModifiedType; extern fn ZigClangMacroQualifiedType_getModifiedType(*const MacroQualifiedType) QualType; }; pub const TypeOfType = opaque { pub const getUnderlyingType = ZigClangTypeOfType_getUnderlyingType; extern fn ZigClangTypeOfType_getUnderlyingType(*const TypeOfType) QualType; }; pub const TypeOfExprType = opaque { pub const getUnderlyingExpr = ZigClangTypeOfExprType_getUnderlyingExpr; extern fn ZigClangTypeOfExprType_getUnderlyingExpr(*const TypeOfExprType) *const Expr; }; pub const OffsetOfNode = opaque { pub const getKind = ZigClangOffsetOfNode_getKind; extern fn ZigClangOffsetOfNode_getKind(*const OffsetOfNode) OffsetOfNode_Kind; pub const getArrayExprIndex = ZigClangOffsetOfNode_getArrayExprIndex; extern fn ZigClangOffsetOfNode_getArrayExprIndex(*const OffsetOfNode) c_uint; pub const getField = ZigClangOffsetOfNode_getField; extern fn ZigClangOffsetOfNode_getField(*const OffsetOfNode) *FieldDecl; }; pub const OffsetOfExpr = opaque { pub const getNumComponents = ZigClangOffsetOfExpr_getNumComponents; extern fn ZigClangOffsetOfExpr_getNumComponents(*const OffsetOfExpr) c_uint; pub const getNumExpressions = ZigClangOffsetOfExpr_getNumExpressions; extern fn ZigClangOffsetOfExpr_getNumExpressions(*const OffsetOfExpr) c_uint; pub const getIndexExpr = ZigClangOffsetOfExpr_getIndexExpr; extern fn ZigClangOffsetOfExpr_getIndexExpr(*const OffsetOfExpr, idx: c_uint) *const Expr; pub const getComponent = ZigClangOffsetOfExpr_getComponent; extern fn ZigClangOffsetOfExpr_getComponent(*const OffsetOfExpr, idx: c_uint) *const OffsetOfNode; pub const getBeginLoc = ZigClangOffsetOfExpr_getBeginLoc; extern fn ZigClangOffsetOfExpr_getBeginLoc(*const OffsetOfExpr) SourceLocation; }; pub const MemberExpr = opaque { pub const getBase = ZigClangMemberExpr_getBase; extern fn ZigClangMemberExpr_getBase(*const MemberExpr) *const Expr; pub const isArrow = ZigClangMemberExpr_isArrow; extern fn ZigClangMemberExpr_isArrow(*const MemberExpr) bool; pub const getMemberDecl = ZigClangMemberExpr_getMemberDecl; extern fn ZigClangMemberExpr_getMemberDecl(*const MemberExpr) *const ValueDecl; }; pub const NamedDecl = opaque { pub const getName_bytes_begin = ZigClangNamedDecl_getName_bytes_begin; extern fn ZigClangNamedDecl_getName_bytes_begin(decl: *const NamedDecl) [*:0]const u8; }; pub const None = opaque {}; pub const OpaqueValueExpr = opaque { pub const getSourceExpr = ZigClangOpaqueValueExpr_getSourceExpr; extern fn ZigClangOpaqueValueExpr_getSourceExpr(*const OpaqueValueExpr) ?*const Expr; }; pub const PCHContainerOperations = opaque {}; pub const ParenExpr = opaque { pub const getSubExpr = ZigClangParenExpr_getSubExpr; extern fn ZigClangParenExpr_getSubExpr(*const ParenExpr) *const Expr; }; pub const ParenType = opaque { pub const getInnerType = ZigClangParenType_getInnerType; extern fn ZigClangParenType_getInnerType(*const ParenType) QualType; }; pub const ParmVarDecl = opaque { pub const getOriginalType = ZigClangParmVarDecl_getOriginalType; extern fn ZigClangParmVarDecl_getOriginalType(*const ParmVarDecl) QualType; }; pub const PointerType = opaque {}; pub const PredefinedExpr = opaque { pub const getFunctionName = ZigClangPredefinedExpr_getFunctionName; extern fn ZigClangPredefinedExpr_getFunctionName(*const PredefinedExpr) *const StringLiteral; }; pub const PreprocessedEntity = opaque { pub const getKind = ZigClangPreprocessedEntity_getKind; extern fn ZigClangPreprocessedEntity_getKind(*const PreprocessedEntity) PreprocessedEntity_EntityKind; }; pub const PreprocessingRecord = opaque { pub const iterator = extern struct { I: c_int, Self: *PreprocessingRecord, pub const deref = ZigClangPreprocessingRecord_iterator_deref; extern fn ZigClangPreprocessingRecord_iterator_deref(iterator) *PreprocessedEntity; }; }; pub const RecordDecl = opaque { pub const getCanonicalDecl = ZigClangRecordDecl_getCanonicalDecl; extern fn ZigClangRecordDecl_getCanonicalDecl(*const RecordDecl) ?*const TagDecl; pub const isUnion = ZigClangRecordDecl_isUnion; extern fn ZigClangRecordDecl_isUnion(*const RecordDecl) bool; pub const isStruct = ZigClangRecordDecl_isStruct; extern fn ZigClangRecordDecl_isStruct(*const RecordDecl) bool; pub const isAnonymousStructOrUnion = ZigClangRecordDecl_isAnonymousStructOrUnion; extern fn ZigClangRecordDecl_isAnonymousStructOrUnion(record_decl: ?*const RecordDecl) bool; pub const getPackedAttribute = ZigClangRecordDecl_getPackedAttribute; extern fn ZigClangRecordDecl_getPackedAttribute(*const RecordDecl) bool; pub const getDefinition = ZigClangRecordDecl_getDefinition; extern fn ZigClangRecordDecl_getDefinition(*const RecordDecl) ?*const RecordDecl; pub const getLocation = ZigClangRecordDecl_getLocation; extern fn ZigClangRecordDecl_getLocation(*const RecordDecl) SourceLocation; pub const field_begin = ZigClangRecordDecl_field_begin; extern fn ZigClangRecordDecl_field_begin(*const RecordDecl) field_iterator; pub const field_end = ZigClangRecordDecl_field_end; extern fn ZigClangRecordDecl_field_end(*const RecordDecl) field_iterator; pub const field_iterator = extern struct { ptr: *c_void, pub const next = ZigClangRecordDecl_field_iterator_next; extern fn ZigClangRecordDecl_field_iterator_next(field_iterator) field_iterator; pub const deref = ZigClangRecordDecl_field_iterator_deref; extern fn ZigClangRecordDecl_field_iterator_deref(field_iterator) *const FieldDecl; pub const neq = ZigClangRecordDecl_field_iterator_neq; extern fn ZigClangRecordDecl_field_iterator_neq(field_iterator, field_iterator) bool; }; }; pub const RecordType = opaque { pub const getDecl = ZigClangRecordType_getDecl; extern fn ZigClangRecordType_getDecl(*const RecordType) *const RecordDecl; }; pub const ReturnStmt = opaque { pub const getRetValue = ZigClangReturnStmt_getRetValue; extern fn ZigClangReturnStmt_getRetValue(*const ReturnStmt) ?*const Expr; }; pub const ShuffleVectorExpr = opaque { pub const getNumSubExprs = ZigClangShuffleVectorExpr_getNumSubExprs; extern fn ZigClangShuffleVectorExpr_getNumSubExprs(*const ShuffleVectorExpr) c_uint; pub const getExpr = ZigClangShuffleVectorExpr_getExpr; extern fn ZigClangShuffleVectorExpr_getExpr(*const ShuffleVectorExpr, c_uint) *const Expr; }; pub const SourceManager = opaque { pub const getSpellingLoc = ZigClangSourceManager_getSpellingLoc; extern fn ZigClangSourceManager_getSpellingLoc(*const SourceManager, Loc: SourceLocation) SourceLocation; pub const getFilename = ZigClangSourceManager_getFilename; extern fn ZigClangSourceManager_getFilename(*const SourceManager, SpellingLoc: SourceLocation) ?[*:0]const u8; pub const getSpellingLineNumber = ZigClangSourceManager_getSpellingLineNumber; extern fn ZigClangSourceManager_getSpellingLineNumber(*const SourceManager, Loc: SourceLocation) c_uint; pub const getSpellingColumnNumber = ZigClangSourceManager_getSpellingColumnNumber; extern fn ZigClangSourceManager_getSpellingColumnNumber(*const SourceManager, Loc: SourceLocation) c_uint; pub const getCharacterData = ZigClangSourceManager_getCharacterData; extern fn ZigClangSourceManager_getCharacterData(*const SourceManager, SL: SourceLocation) [*:0]const u8; }; pub const SourceRange = opaque {}; pub const Stmt = opaque { pub const getBeginLoc = ZigClangStmt_getBeginLoc; extern fn ZigClangStmt_getBeginLoc(*const Stmt) SourceLocation; pub const getStmtClass = ZigClangStmt_getStmtClass; extern fn ZigClangStmt_getStmtClass(*const Stmt) StmtClass; pub const classof_Expr = ZigClangStmt_classof_Expr; extern fn ZigClangStmt_classof_Expr(*const Stmt) bool; }; pub const StmtExpr = opaque { pub const getSubStmt = ZigClangStmtExpr_getSubStmt; extern fn ZigClangStmtExpr_getSubStmt(*const StmtExpr) *const CompoundStmt; }; pub const StringLiteral = opaque { pub const getKind = ZigClangStringLiteral_getKind; extern fn ZigClangStringLiteral_getKind(*const StringLiteral) StringLiteral_StringKind; pub const getCodeUnit = ZigClangStringLiteral_getCodeUnit; extern fn ZigClangStringLiteral_getCodeUnit(*const StringLiteral, usize) u32; pub const getLength = ZigClangStringLiteral_getLength; extern fn ZigClangStringLiteral_getLength(*const StringLiteral) c_uint; pub const getCharByteWidth = ZigClangStringLiteral_getCharByteWidth; extern fn ZigClangStringLiteral_getCharByteWidth(*const StringLiteral) c_uint; pub const getString_bytes_begin_size = ZigClangStringLiteral_getString_bytes_begin_size; extern fn ZigClangStringLiteral_getString_bytes_begin_size(*const StringLiteral, *usize) [*]const u8; }; pub const StringRef = opaque {}; pub const SwitchStmt = opaque { pub const getConditionVariableDeclStmt = ZigClangSwitchStmt_getConditionVariableDeclStmt; extern fn ZigClangSwitchStmt_getConditionVariableDeclStmt(*const SwitchStmt) ?*const DeclStmt; pub const getCond = ZigClangSwitchStmt_getCond; extern fn ZigClangSwitchStmt_getCond(*const SwitchStmt) *const Expr; pub const getBody = ZigClangSwitchStmt_getBody; extern fn ZigClangSwitchStmt_getBody(*const SwitchStmt) *const Stmt; pub const isAllEnumCasesCovered = ZigClangSwitchStmt_isAllEnumCasesCovered; extern fn ZigClangSwitchStmt_isAllEnumCasesCovered(*const SwitchStmt) bool; }; pub const TagDecl = opaque { pub const isThisDeclarationADefinition = ZigClangTagDecl_isThisDeclarationADefinition; extern fn ZigClangTagDecl_isThisDeclarationADefinition(*const TagDecl) bool; }; pub const Type = opaque { pub const getTypeClass = ZigClangType_getTypeClass; extern fn ZigClangType_getTypeClass(*const Type) TypeClass; pub const getPointeeType = ZigClangType_getPointeeType; extern fn ZigClangType_getPointeeType(*const Type) QualType; pub const isVoidType = ZigClangType_isVoidType; extern fn ZigClangType_isVoidType(*const Type) bool; pub const isConstantArrayType = ZigClangType_isConstantArrayType; extern fn ZigClangType_isConstantArrayType(*const Type) bool; pub const isRecordType = ZigClangType_isRecordType; extern fn ZigClangType_isRecordType(*const Type) bool; pub const isVectorType = ZigClangType_isVectorType; extern fn ZigClangType_isVectorType(*const Type) bool; pub const isIncompleteOrZeroLengthArrayType = ZigClangType_isIncompleteOrZeroLengthArrayType; extern fn ZigClangType_isIncompleteOrZeroLengthArrayType(*const Type, *const ASTContext) bool; pub const isArrayType = ZigClangType_isArrayType; extern fn ZigClangType_isArrayType(*const Type) bool; pub const isBooleanType = ZigClangType_isBooleanType; extern fn ZigClangType_isBooleanType(*const Type) bool; pub const getTypeClassName = ZigClangType_getTypeClassName; extern fn ZigClangType_getTypeClassName(*const Type) [*:0]const u8; pub const getAsArrayTypeUnsafe = ZigClangType_getAsArrayTypeUnsafe; extern fn ZigClangType_getAsArrayTypeUnsafe(*const Type) *const ArrayType; pub const getAsRecordType = ZigClangType_getAsRecordType; extern fn ZigClangType_getAsRecordType(*const Type) ?*const RecordType; pub const getAsUnionType = ZigClangType_getAsUnionType; extern fn ZigClangType_getAsUnionType(*const Type) ?*const RecordType; }; pub const TypedefNameDecl = opaque { pub const getUnderlyingType = ZigClangTypedefNameDecl_getUnderlyingType; extern fn ZigClangTypedefNameDecl_getUnderlyingType(*const TypedefNameDecl) QualType; pub const getCanonicalDecl = ZigClangTypedefNameDecl_getCanonicalDecl; extern fn ZigClangTypedefNameDecl_getCanonicalDecl(*const TypedefNameDecl) ?*const TypedefNameDecl; pub const getLocation = ZigClangTypedefNameDecl_getLocation; extern fn ZigClangTypedefNameDecl_getLocation(*const TypedefNameDecl) SourceLocation; }; pub const FileScopeAsmDecl = opaque { pub const getAsmString = ZigClangFileScopeAsmDecl_getAsmString; extern fn ZigClangFileScopeAsmDecl_getAsmString(*const FileScopeAsmDecl) *const StringLiteral; }; pub const TypedefType = opaque { pub const getDecl = ZigClangTypedefType_getDecl; extern fn ZigClangTypedefType_getDecl(*const TypedefType) *const TypedefNameDecl; }; pub const UnaryExprOrTypeTraitExpr = opaque { pub const getTypeOfArgument = ZigClangUnaryExprOrTypeTraitExpr_getTypeOfArgument; extern fn ZigClangUnaryExprOrTypeTraitExpr_getTypeOfArgument(*const UnaryExprOrTypeTraitExpr) QualType; pub const getBeginLoc = ZigClangUnaryExprOrTypeTraitExpr_getBeginLoc; extern fn ZigClangUnaryExprOrTypeTraitExpr_getBeginLoc(*const UnaryExprOrTypeTraitExpr) SourceLocation; pub const getKind = ZigClangUnaryExprOrTypeTraitExpr_getKind; extern fn ZigClangUnaryExprOrTypeTraitExpr_getKind(*const UnaryExprOrTypeTraitExpr) UnaryExprOrTypeTrait_Kind; }; pub const UnaryOperator = opaque { pub const getOpcode = ZigClangUnaryOperator_getOpcode; extern fn ZigClangUnaryOperator_getOpcode(*const UnaryOperator) UO; pub const getType = ZigClangUnaryOperator_getType; extern fn ZigClangUnaryOperator_getType(*const UnaryOperator) QualType; pub const getSubExpr = ZigClangUnaryOperator_getSubExpr; extern fn ZigClangUnaryOperator_getSubExpr(*const UnaryOperator) *const Expr; pub const getBeginLoc = ZigClangUnaryOperator_getBeginLoc; extern fn ZigClangUnaryOperator_getBeginLoc(*const UnaryOperator) SourceLocation; }; pub const ValueDecl = opaque { pub const getType = ZigClangValueDecl_getType; extern fn ZigClangValueDecl_getType(*const ValueDecl) QualType; }; pub const VarDecl = opaque { pub const getLocation = ZigClangVarDecl_getLocation; extern fn ZigClangVarDecl_getLocation(*const VarDecl) SourceLocation; pub const hasInit = ZigClangVarDecl_hasInit; extern fn ZigClangVarDecl_hasInit(*const VarDecl) bool; pub const getStorageClass = ZigClangVarDecl_getStorageClass; extern fn ZigClangVarDecl_getStorageClass(*const VarDecl) StorageClass; pub const getType = ZigClangVarDecl_getType; extern fn ZigClangVarDecl_getType(*const VarDecl) QualType; pub const getInit = ZigClangVarDecl_getInit; extern fn ZigClangVarDecl_getInit(*const VarDecl) ?*const Expr; pub const getTLSKind = ZigClangVarDecl_getTLSKind; extern fn ZigClangVarDecl_getTLSKind(*const VarDecl) VarDecl_TLSKind; pub const getCanonicalDecl = ZigClangVarDecl_getCanonicalDecl; extern fn ZigClangVarDecl_getCanonicalDecl(*const VarDecl) ?*const VarDecl; pub const getSectionAttribute = ZigClangVarDecl_getSectionAttribute; extern fn ZigClangVarDecl_getSectionAttribute(*const VarDecl, len: *usize) ?[*]const u8; pub const getAlignedAttribute = ZigClangVarDecl_getAlignedAttribute; extern fn ZigClangVarDecl_getAlignedAttribute(*const VarDecl, *const ASTContext) c_uint; pub const getCleanupAttribute = ZigClangVarDecl_getCleanupAttribute; extern fn ZigClangVarDecl_getCleanupAttribute(*const VarDecl) ?*const FunctionDecl; pub const getTypeSourceInfo_getType = ZigClangVarDecl_getTypeSourceInfo_getType; extern fn ZigClangVarDecl_getTypeSourceInfo_getType(*const VarDecl) QualType; }; pub const VectorType = opaque { pub const getElementType = ZigClangVectorType_getElementType; extern fn ZigClangVectorType_getElementType(*const VectorType) QualType; pub const getNumElements = ZigClangVectorType_getNumElements; extern fn ZigClangVectorType_getNumElements(*const VectorType) c_uint; }; pub const WhileStmt = opaque { pub const getCond = ZigClangWhileStmt_getCond; extern fn ZigClangWhileStmt_getCond(*const WhileStmt) *const Expr; pub const getBody = ZigClangWhileStmt_getBody; extern fn ZigClangWhileStmt_getBody(*const WhileStmt) *const Stmt; }; pub const InitListExpr = opaque { pub const getInit = ZigClangInitListExpr_getInit; extern fn ZigClangInitListExpr_getInit(*const InitListExpr, i: c_uint) *const Expr; pub const getArrayFiller = ZigClangInitListExpr_getArrayFiller; extern fn ZigClangInitListExpr_getArrayFiller(*const InitListExpr) *const Expr; pub const getNumInits = ZigClangInitListExpr_getNumInits; extern fn ZigClangInitListExpr_getNumInits(*const InitListExpr) c_uint; pub const getInitializedFieldInUnion = ZigClangInitListExpr_getInitializedFieldInUnion; extern fn ZigClangInitListExpr_getInitializedFieldInUnion(*const InitListExpr) ?*FieldDecl; }; pub const BO = extern enum { PtrMemD, PtrMemI, Mul, Div, Rem, Add, Sub, Shl, Shr, Cmp, LT, GT, LE, GE, EQ, NE, And, Xor, Or, LAnd, LOr, Assign, MulAssign, DivAssign, RemAssign, AddAssign, SubAssign, ShlAssign, ShrAssign, AndAssign, XorAssign, OrAssign, Comma, }; pub const UO = extern enum { PostInc, PostDec, PreInc, PreDec, AddrOf, Deref, Plus, Minus, Not, LNot, Real, Imag, Extension, Coawait, }; pub const TypeClass = extern enum { Adjusted, Decayed, ConstantArray, DependentSizedArray, IncompleteArray, VariableArray, Atomic, Attributed, BlockPointer, Builtin, Complex, Decltype, Auto, DeducedTemplateSpecialization, DependentAddressSpace, DependentExtInt, DependentName, DependentSizedExtVector, DependentTemplateSpecialization, DependentVector, Elaborated, ExtInt, FunctionNoProto, FunctionProto, InjectedClassName, MacroQualified, ConstantMatrix, DependentSizedMatrix, MemberPointer, ObjCObjectPointer, ObjCObject, ObjCInterface, ObjCTypeParam, PackExpansion, Paren, Pipe, Pointer, LValueReference, RValueReference, SubstTemplateTypeParmPack, SubstTemplateTypeParm, Enum, Record, TemplateSpecialization, TemplateTypeParm, TypeOfExpr, TypeOf, Typedef, UnaryTransform, UnresolvedUsing, Vector, ExtVector, }; const StmtClass = extern enum { NoStmtClass, GCCAsmStmtClass, MSAsmStmtClass, BreakStmtClass, CXXCatchStmtClass, CXXForRangeStmtClass, CXXTryStmtClass, CapturedStmtClass, CompoundStmtClass, ContinueStmtClass, CoreturnStmtClass, CoroutineBodyStmtClass, DeclStmtClass, DoStmtClass, ForStmtClass, GotoStmtClass, IfStmtClass, IndirectGotoStmtClass, MSDependentExistsStmtClass, NullStmtClass, OMPAtomicDirectiveClass, OMPBarrierDirectiveClass, OMPCancelDirectiveClass, OMPCancellationPointDirectiveClass, OMPCriticalDirectiveClass, OMPDepobjDirectiveClass, OMPFlushDirectiveClass, OMPDistributeDirectiveClass, OMPDistributeParallelForDirectiveClass, OMPDistributeParallelForSimdDirectiveClass, OMPDistributeSimdDirectiveClass, OMPForDirectiveClass, OMPForSimdDirectiveClass, OMPMasterTaskLoopDirectiveClass, OMPMasterTaskLoopSimdDirectiveClass, OMPParallelForDirectiveClass, OMPParallelForSimdDirectiveClass, OMPParallelMasterTaskLoopDirectiveClass, OMPParallelMasterTaskLoopSimdDirectiveClass, OMPSimdDirectiveClass, OMPTargetParallelForSimdDirectiveClass, OMPTargetSimdDirectiveClass, OMPTargetTeamsDistributeDirectiveClass, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPTargetTeamsDistributeSimdDirectiveClass, OMPTaskLoopDirectiveClass, OMPTaskLoopSimdDirectiveClass, OMPTeamsDistributeDirectiveClass, OMPTeamsDistributeParallelForDirectiveClass, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPTeamsDistributeSimdDirectiveClass, OMPMasterDirectiveClass, OMPOrderedDirectiveClass, OMPParallelDirectiveClass, OMPParallelMasterDirectiveClass, OMPParallelSectionsDirectiveClass, OMPScanDirectiveClass, OMPSectionDirectiveClass, OMPSectionsDirectiveClass, OMPSingleDirectiveClass, OMPTargetDataDirectiveClass, OMPTargetDirectiveClass, OMPTargetEnterDataDirectiveClass, OMPTargetExitDataDirectiveClass, OMPTargetParallelDirectiveClass, OMPTargetParallelForDirectiveClass, OMPTargetTeamsDirectiveClass, OMPTargetUpdateDirectiveClass, OMPTaskDirectiveClass, OMPTaskgroupDirectiveClass, OMPTaskwaitDirectiveClass, OMPTaskyieldDirectiveClass, OMPTeamsDirectiveClass, ObjCAtCatchStmtClass, ObjCAtFinallyStmtClass, ObjCAtSynchronizedStmtClass, ObjCAtThrowStmtClass, ObjCAtTryStmtClass, ObjCAutoreleasePoolStmtClass, ObjCForCollectionStmtClass, ReturnStmtClass, SEHExceptStmtClass, SEHFinallyStmtClass, SEHLeaveStmtClass, SEHTryStmtClass, CaseStmtClass, DefaultStmtClass, SwitchStmtClass, AttributedStmtClass, BinaryConditionalOperatorClass, ConditionalOperatorClass, AddrLabelExprClass, ArrayInitIndexExprClass, ArrayInitLoopExprClass, ArraySubscriptExprClass, ArrayTypeTraitExprClass, AsTypeExprClass, AtomicExprClass, BinaryOperatorClass, CompoundAssignOperatorClass, BlockExprClass, CXXBindTemporaryExprClass, CXXBoolLiteralExprClass, CXXConstructExprClass, CXXTemporaryObjectExprClass, CXXDefaultArgExprClass, CXXDefaultInitExprClass, CXXDeleteExprClass, CXXDependentScopeMemberExprClass, CXXFoldExprClass, CXXInheritedCtorInitExprClass, CXXNewExprClass, CXXNoexceptExprClass, CXXNullPtrLiteralExprClass, CXXPseudoDestructorExprClass, CXXRewrittenBinaryOperatorClass, CXXScalarValueInitExprClass, CXXStdInitializerListExprClass, CXXThisExprClass, CXXThrowExprClass, CXXTypeidExprClass, CXXUnresolvedConstructExprClass, CXXUuidofExprClass, CallExprClass, CUDAKernelCallExprClass, CXXMemberCallExprClass, CXXOperatorCallExprClass, UserDefinedLiteralClass, BuiltinBitCastExprClass, CStyleCastExprClass, CXXFunctionalCastExprClass, CXXAddrspaceCastExprClass, CXXConstCastExprClass, CXXDynamicCastExprClass, CXXReinterpretCastExprClass, CXXStaticCastExprClass, ObjCBridgedCastExprClass, ImplicitCastExprClass, CharacterLiteralClass, ChooseExprClass, CompoundLiteralExprClass, ConceptSpecializationExprClass, ConvertVectorExprClass, CoawaitExprClass, CoyieldExprClass, DeclRefExprClass, DependentCoawaitExprClass, DependentScopeDeclRefExprClass, DesignatedInitExprClass, DesignatedInitUpdateExprClass, ExpressionTraitExprClass, ExtVectorElementExprClass, FixedPointLiteralClass, FloatingLiteralClass, ConstantExprClass, ExprWithCleanupsClass, FunctionParmPackExprClass, GNUNullExprClass, GenericSelectionExprClass, ImaginaryLiteralClass, ImplicitValueInitExprClass, InitListExprClass, IntegerLiteralClass, LambdaExprClass, MSPropertyRefExprClass, MSPropertySubscriptExprClass, MaterializeTemporaryExprClass, MatrixSubscriptExprClass, MemberExprClass, NoInitExprClass, OMPArraySectionExprClass, OMPArrayShapingExprClass, OMPIteratorExprClass, ObjCArrayLiteralClass, ObjCAvailabilityCheckExprClass, ObjCBoolLiteralExprClass, ObjCBoxedExprClass, ObjCDictionaryLiteralClass, ObjCEncodeExprClass, ObjCIndirectCopyRestoreExprClass, ObjCIsaExprClass, ObjCIvarRefExprClass, ObjCMessageExprClass, ObjCPropertyRefExprClass, ObjCProtocolExprClass, ObjCSelectorExprClass, ObjCStringLiteralClass, ObjCSubscriptRefExprClass, OffsetOfExprClass, OpaqueValueExprClass, UnresolvedLookupExprClass, UnresolvedMemberExprClass, PackExpansionExprClass, ParenExprClass, ParenListExprClass, PredefinedExprClass, PseudoObjectExprClass, RecoveryExprClass, RequiresExprClass, ShuffleVectorExprClass, SizeOfPackExprClass, SourceLocExprClass, StmtExprClass, StringLiteralClass, SubstNonTypeTemplateParmExprClass, SubstNonTypeTemplateParmPackExprClass, TypeTraitExprClass, TypoExprClass, UnaryExprOrTypeTraitExprClass, UnaryOperatorClass, VAArgExprClass, LabelStmtClass, WhileStmtClass, }; pub const CK = extern enum { Dependent, BitCast, LValueBitCast, LValueToRValueBitCast, LValueToRValue, NoOp, BaseToDerived, DerivedToBase, UncheckedDerivedToBase, Dynamic, ToUnion, ArrayToPointerDecay, FunctionToPointerDecay, NullToPointer, NullToMemberPointer, BaseToDerivedMemberPointer, DerivedToBaseMemberPointer, MemberPointerToBoolean, ReinterpretMemberPointer, UserDefinedConversion, ConstructorConversion, IntegralToPointer, PointerToIntegral, PointerToBoolean, ToVoid, VectorSplat, IntegralCast, IntegralToBoolean, IntegralToFloating, FloatingToFixedPoint, FixedPointToFloating, FixedPointCast, FixedPointToIntegral, IntegralToFixedPoint, FixedPointToBoolean, FloatingToIntegral, FloatingToBoolean, BooleanToSignedIntegral, FloatingCast, CPointerToObjCPointerCast, BlockPointerToObjCPointerCast, AnyPointerToBlockPointerCast, ObjCObjectLValueCast, FloatingRealToComplex, FloatingComplexToReal, FloatingComplexToBoolean, FloatingComplexCast, FloatingComplexToIntegralComplex, IntegralRealToComplex, IntegralComplexToReal, IntegralComplexToBoolean, IntegralComplexCast, IntegralComplexToFloatingComplex, ARCProduceObject, ARCConsumeObject, ARCReclaimReturnedObject, ARCExtendBlockObject, AtomicToNonAtomic, NonAtomicToAtomic, CopyAndAutoreleaseBlockObject, BuiltinFnToFnPtr, ZeroToOCLOpaqueType, AddressSpaceConversion, IntToOCLSampler, }; pub const DeclKind = extern enum { AccessSpec, Block, Captured, ClassScopeFunctionSpecialization, Empty, Export, ExternCContext, FileScopeAsm, Friend, FriendTemplate, Import, LifetimeExtendedTemporary, LinkageSpec, Label, Namespace, NamespaceAlias, ObjCCompatibleAlias, ObjCCategory, ObjCCategoryImpl, ObjCImplementation, ObjCInterface, ObjCProtocol, ObjCMethod, ObjCProperty, BuiltinTemplate, Concept, ClassTemplate, FunctionTemplate, TypeAliasTemplate, VarTemplate, TemplateTemplateParm, Enum, Record, CXXRecord, ClassTemplateSpecialization, ClassTemplatePartialSpecialization, TemplateTypeParm, ObjCTypeParam, TypeAlias, Typedef, UnresolvedUsingTypename, Using, UsingDirective, UsingPack, UsingShadow, ConstructorUsingShadow, Binding, Field, ObjCAtDefsField, ObjCIvar, Function, CXXDeductionGuide, CXXMethod, CXXConstructor, CXXConversion, CXXDestructor, MSProperty, NonTypeTemplateParm, Var, Decomposition, ImplicitParam, OMPCapturedExpr, ParmVar, VarTemplateSpecialization, VarTemplatePartialSpecialization, EnumConstant, IndirectField, MSGuid, OMPDeclareMapper, OMPDeclareReduction, TemplateParamObject, UnresolvedUsingValue, OMPAllocate, OMPRequires, OMPThreadPrivate, ObjCPropertyImpl, PragmaComment, PragmaDetectMismatch, RequiresExprBody, StaticAssert, TranslationUnit, }; pub const BuiltinTypeKind = extern enum { OCLImage1dRO, OCLImage1dArrayRO, OCLImage1dBufferRO, OCLImage2dRO, OCLImage2dArrayRO, OCLImage2dDepthRO, OCLImage2dArrayDepthRO, OCLImage2dMSAARO, OCLImage2dArrayMSAARO, OCLImage2dMSAADepthRO, OCLImage2dArrayMSAADepthRO, OCLImage3dRO, OCLImage1dWO, OCLImage1dArrayWO, OCLImage1dBufferWO, OCLImage2dWO, OCLImage2dArrayWO, OCLImage2dDepthWO, OCLImage2dArrayDepthWO, OCLImage2dMSAAWO, OCLImage2dArrayMSAAWO, OCLImage2dMSAADepthWO, OCLImage2dArrayMSAADepthWO, OCLImage3dWO, OCLImage1dRW, OCLImage1dArrayRW, OCLImage1dBufferRW, OCLImage2dRW, OCLImage2dArrayRW, OCLImage2dDepthRW, OCLImage2dArrayDepthRW, OCLImage2dMSAARW, OCLImage2dArrayMSAARW, OCLImage2dMSAADepthRW, OCLImage2dArrayMSAADepthRW, OCLImage3dRW, OCLIntelSubgroupAVCMcePayload, OCLIntelSubgroupAVCImePayload, OCLIntelSubgroupAVCRefPayload, OCLIntelSubgroupAVCSicPayload, OCLIntelSubgroupAVCMceResult, OCLIntelSubgroupAVCImeResult, OCLIntelSubgroupAVCRefResult, OCLIntelSubgroupAVCSicResult, OCLIntelSubgroupAVCImeResultSingleRefStreamout, OCLIntelSubgroupAVCImeResultDualRefStreamout, OCLIntelSubgroupAVCImeSingleRefStreamin, OCLIntelSubgroupAVCImeDualRefStreamin, SveInt8, SveInt16, SveInt32, SveInt64, SveUint8, SveUint16, SveUint32, SveUint64, SveFloat16, SveFloat32, SveFloat64, SveBFloat16, SveInt8x2, SveInt16x2, SveInt32x2, SveInt64x2, SveUint8x2, SveUint16x2, SveUint32x2, SveUint64x2, SveFloat16x2, SveFloat32x2, SveFloat64x2, SveBFloat16x2, SveInt8x3, SveInt16x3, SveInt32x3, SveInt64x3, SveUint8x3, SveUint16x3, SveUint32x3, SveUint64x3, SveFloat16x3, SveFloat32x3, SveFloat64x3, SveBFloat16x3, SveInt8x4, SveInt16x4, SveInt32x4, SveInt64x4, SveUint8x4, SveUint16x4, SveUint32x4, SveUint64x4, SveFloat16x4, SveFloat32x4, SveFloat64x4, SveBFloat16x4, SveBool, VectorQuad, VectorPair, Void, Bool, Char_U, UChar, WChar_U, Char8, Char16, Char32, UShort, UInt, ULong, ULongLong, UInt128, Char_S, SChar, WChar_S, Short, Int, Long, LongLong, Int128, ShortAccum, Accum, LongAccum, UShortAccum, UAccum, ULongAccum, ShortFract, Fract, LongFract, UShortFract, UFract, ULongFract, SatShortAccum, SatAccum, SatLongAccum, SatUShortAccum, SatUAccum, SatULongAccum, SatShortFract, SatFract, SatLongFract, SatUShortFract, SatUFract, SatULongFract, Half, Float, Double, LongDouble, Float16, BFloat16, Float128, NullPtr, ObjCId, ObjCClass, ObjCSel, OCLSampler, OCLEvent, OCLClkEvent, OCLQueue, OCLReserveID, Dependent, Overload, BoundMember, PseudoObject, UnknownAny, BuiltinFn, ARCUnbridgedCast, IncompleteMatrixIdx, OMPArraySection, OMPArrayShaping, OMPIterator, }; pub const CallingConv = extern enum { C, X86StdCall, X86FastCall, X86ThisCall, X86VectorCall, X86Pascal, Win64, X86_64SysV, X86RegCall, AAPCS, AAPCS_VFP, IntelOclBicc, SpirFunction, OpenCLKernel, Swift, PreserveMost, PreserveAll, AArch64VectorCall, }; pub const StorageClass = extern enum { None, Extern, Static, PrivateExtern, Auto, Register, }; pub const APFloat_roundingMode = extern enum(i8) { TowardZero = 0, NearestTiesToEven = 1, TowardPositive = 2, TowardNegative = 3, NearestTiesToAway = 4, Dynamic = 7, Invalid = -1, }; pub const StringLiteral_StringKind = extern enum { Ascii, Wide, UTF8, UTF16, UTF32, }; pub const CharacterLiteral_CharacterKind = extern enum { Ascii, Wide, UTF8, UTF16, UTF32, }; pub const VarDecl_TLSKind = extern enum { None, Static, Dynamic, }; pub const ElaboratedTypeKeyword = extern enum { Struct, Interface, Union, Class, Enum, Typename, None, }; pub const PreprocessedEntity_EntityKind = extern enum { InvalidKind, MacroExpansionKind, MacroDefinitionKind, InclusionDirectiveKind, }; pub const Expr_ConstantExprKind = extern enum { Normal, NonClassTemplateArgument, ClassTemplateArgument, ImmediateInvocation, }; pub const UnaryExprOrTypeTrait_Kind = extern enum { SizeOf, AlignOf, VecStep, OpenMPRequiredSimdAlign, PreferredAlignOf, }; pub const OffsetOfNode_Kind = extern enum { Array, Field, Identifier, Base, }; pub const Stage2ErrorMsg = extern struct { filename_ptr: ?[*]const u8, filename_len: usize, msg_ptr: [*]const u8, msg_len: usize, // valid until the ASTUnit is freed source: ?[*]const u8, // 0 based line: c_uint, // 0 based column: c_uint, // byte offset into source offset: c_uint, pub const delete = ZigClangErrorMsg_delete; extern fn ZigClangErrorMsg_delete(ptr: [*]Stage2ErrorMsg, len: usize) void; }; pub const LoadFromCommandLine = ZigClangLoadFromCommandLine; extern fn ZigClangLoadFromCommandLine( args_begin: [*]?[*]const u8, args_end: [*]?[*]const u8, errors_ptr: *[*]Stage2ErrorMsg, errors_len: *usize, resources_path: [*:0]const u8, ) ?*ASTUnit;
src/clang.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const Value = @import("value.zig").Value; const Type = @import("type.zig").Type; const TypedValue = @import("TypedValue.zig"); const assert = std.debug.assert; const ir = @import("ir.zig"); const zir = @import("zir.zig"); const Module = @import("Module.zig"); const Inst = ir.Inst; const Body = ir.Body; const trace = @import("tracy.zig").trace; const Scope = Module.Scope; const InnerError = Module.InnerError; const Decl = Module.Decl; pub fn analyzeInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst { switch (old_inst.tag) { .alloc => return analyzeInstAlloc(mod, scope, old_inst.castTag(.alloc).?), .alloc_inferred => return analyzeInstAllocInferred(mod, scope, old_inst.castTag(.alloc_inferred).?), .arg => return analyzeInstArg(mod, scope, old_inst.castTag(.arg).?), .bitcast_ref => return analyzeInstBitCastRef(mod, scope, old_inst.castTag(.bitcast_ref).?), .bitcast_result_ptr => return analyzeInstBitCastResultPtr(mod, scope, old_inst.castTag(.bitcast_result_ptr).?), .block => return analyzeInstBlock(mod, scope, old_inst.castTag(.block).?), .@"break" => return analyzeInstBreak(mod, scope, old_inst.castTag(.@"break").?), .breakpoint => return analyzeInstBreakpoint(mod, scope, old_inst.castTag(.breakpoint).?), .breakvoid => return analyzeInstBreakVoid(mod, scope, old_inst.castTag(.breakvoid).?), .call => return analyzeInstCall(mod, scope, old_inst.castTag(.call).?), .coerce_result_block_ptr => return analyzeInstCoerceResultBlockPtr(mod, scope, old_inst.castTag(.coerce_result_block_ptr).?), .coerce_result_ptr => return analyzeInstCoerceResultPtr(mod, scope, old_inst.castTag(.coerce_result_ptr).?), .coerce_to_ptr_elem => return analyzeInstCoerceToPtrElem(mod, scope, old_inst.castTag(.coerce_to_ptr_elem).?), .compileerror => return analyzeInstCompileError(mod, scope, old_inst.castTag(.compileerror).?), .@"const" => return analyzeInstConst(mod, scope, old_inst.castTag(.@"const").?), .dbg_stmt => return analyzeInstDbgStmt(mod, scope, old_inst.castTag(.dbg_stmt).?), .declref => return analyzeInstDeclRef(mod, scope, old_inst.castTag(.declref).?), .declref_str => return analyzeInstDeclRefStr(mod, scope, old_inst.castTag(.declref_str).?), .declval => return analyzeInstDeclVal(mod, scope, old_inst.castTag(.declval).?), .declval_in_module => return analyzeInstDeclValInModule(mod, scope, old_inst.castTag(.declval_in_module).?), .ensure_result_used => return analyzeInstEnsureResultUsed(mod, scope, old_inst.castTag(.ensure_result_used).?), .ensure_result_non_error => return analyzeInstEnsureResultNonError(mod, scope, old_inst.castTag(.ensure_result_non_error).?), .ref => return analyzeInstRef(mod, scope, old_inst.castTag(.ref).?), .ret_ptr => return analyzeInstRetPtr(mod, scope, old_inst.castTag(.ret_ptr).?), .ret_type => return analyzeInstRetType(mod, scope, old_inst.castTag(.ret_type).?), .single_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.single_const_ptr_type).?, false, .One), .single_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.single_mut_ptr_type).?, true, .One), .many_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.many_const_ptr_type).?, false, .Many), .many_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.many_mut_ptr_type).?, true, .Many), .c_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.c_const_ptr_type).?, false, .C), .c_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.c_mut_ptr_type).?, true, .C), .const_slice_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.const_slice_type).?, false, .Slice), .mut_slice_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.mut_slice_type).?, true, .Slice), .ptr_type => return analyzeInstPtrType(mod, scope, old_inst.castTag(.ptr_type).?), .store => return analyzeInstStore(mod, scope, old_inst.castTag(.store).?), .str => return analyzeInstStr(mod, scope, old_inst.castTag(.str).?), .int => { const big_int = old_inst.castTag(.int).?.positionals.int; return mod.constIntBig(scope, old_inst.src, Type.initTag(.comptime_int), big_int); }, .inttype => return analyzeInstIntType(mod, scope, old_inst.castTag(.inttype).?), .loop => return analyzeInstLoop(mod, scope, old_inst.castTag(.loop).?), .param_type => return analyzeInstParamType(mod, scope, old_inst.castTag(.param_type).?), .ptrtoint => return analyzeInstPtrToInt(mod, scope, old_inst.castTag(.ptrtoint).?), .fieldptr => return analyzeInstFieldPtr(mod, scope, old_inst.castTag(.fieldptr).?), .deref => return analyzeInstDeref(mod, scope, old_inst.castTag(.deref).?), .as => return analyzeInstAs(mod, scope, old_inst.castTag(.as).?), .@"asm" => return analyzeInstAsm(mod, scope, old_inst.castTag(.@"asm").?), .@"unreachable" => return analyzeInstUnreachable(mod, scope, old_inst.castTag(.@"unreachable").?, true), .unreach_nocheck => return analyzeInstUnreachable(mod, scope, old_inst.castTag(.unreach_nocheck).?, false), .@"return" => return analyzeInstRet(mod, scope, old_inst.castTag(.@"return").?), .returnvoid => return analyzeInstRetVoid(mod, scope, old_inst.castTag(.returnvoid).?), .@"fn" => return analyzeInstFn(mod, scope, old_inst.castTag(.@"fn").?), .@"export" => return analyzeInstExport(mod, scope, old_inst.castTag(.@"export").?), .primitive => return analyzeInstPrimitive(mod, scope, old_inst.castTag(.primitive).?), .fntype => return analyzeInstFnType(mod, scope, old_inst.castTag(.fntype).?), .intcast => return analyzeInstIntCast(mod, scope, old_inst.castTag(.intcast).?), .bitcast => return analyzeInstBitCast(mod, scope, old_inst.castTag(.bitcast).?), .floatcast => return analyzeInstFloatCast(mod, scope, old_inst.castTag(.floatcast).?), .elemptr => return analyzeInstElemPtr(mod, scope, old_inst.castTag(.elemptr).?), .add => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.add).?), .addwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.addwrap).?), .sub => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.sub).?), .subwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.subwrap).?), .mul => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mul).?), .mulwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mulwrap).?), .div => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.div).?), .mod_rem => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mod_rem).?), .array_cat => return analyzeInstArrayCat(mod, scope, old_inst.castTag(.array_cat).?), .array_mul => return analyzeInstArrayMul(mod, scope, old_inst.castTag(.array_mul).?), .bitand => return analyzeInstBitwise(mod, scope, old_inst.castTag(.bitand).?), .bitor => return analyzeInstBitwise(mod, scope, old_inst.castTag(.bitor).?), .xor => return analyzeInstBitwise(mod, scope, old_inst.castTag(.xor).?), .shl => return analyzeInstShl(mod, scope, old_inst.castTag(.shl).?), .shr => return analyzeInstShr(mod, scope, old_inst.castTag(.shr).?), .cmp_lt => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_lt).?, .lt), .cmp_lte => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_lte).?, .lte), .cmp_eq => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_eq).?, .eq), .cmp_gte => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_gte).?, .gte), .cmp_gt => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_gt).?, .gt), .cmp_neq => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_neq).?, .neq), .condbr => return analyzeInstCondBr(mod, scope, old_inst.castTag(.condbr).?), .isnull => return analyzeInstIsNonNull(mod, scope, old_inst.castTag(.isnull).?, true), .isnonnull => return analyzeInstIsNonNull(mod, scope, old_inst.castTag(.isnonnull).?, false), .iserr => return analyzeInstIsErr(mod, scope, old_inst.castTag(.iserr).?, true), .boolnot => return analyzeInstBoolNot(mod, scope, old_inst.castTag(.boolnot).?), .typeof => return analyzeInstTypeOf(mod, scope, old_inst.castTag(.typeof).?), .optional_type => return analyzeInstOptionalType(mod, scope, old_inst.castTag(.optional_type).?), .unwrap_optional_safe => return analyzeInstUnwrapOptional(mod, scope, old_inst.castTag(.unwrap_optional_safe).?, true), .unwrap_optional_unsafe => return analyzeInstUnwrapOptional(mod, scope, old_inst.castTag(.unwrap_optional_unsafe).?, false), .unwrap_err_safe => return analyzeInstUnwrapErr(mod, scope, old_inst.castTag(.unwrap_err_safe).?, true), .unwrap_err_unsafe => return analyzeInstUnwrapErr(mod, scope, old_inst.castTag(.unwrap_err_unsafe).?, false), .ensure_err_payload_void => return analyzeInstEnsureErrPayloadVoid(mod, scope, old_inst.castTag(.ensure_err_payload_void).?), .array_type => return analyzeInstArrayType(mod, scope, old_inst.castTag(.array_type).?), .array_type_sentinel => return analyzeInstArrayTypeSentinel(mod, scope, old_inst.castTag(.array_type_sentinel).?), .enum_literal => return analyzeInstEnumLiteral(mod, scope, old_inst.castTag(.enum_literal).?), } } pub fn analyzeBody(mod: *Module, scope: *Scope, body: zir.Module.Body) !void { for (body.instructions) |src_inst, i| { const analyzed_inst = try analyzeInst(mod, scope, src_inst); src_inst.analyzed_inst = analyzed_inst; if (analyzed_inst.ty.zigTypeTag() == .NoReturn) { for (body.instructions[i..]) |unreachable_inst| { if (unreachable_inst.castTag(.dbg_stmt)) |dbg_stmt| { return mod.fail(scope, dbg_stmt.base.src, "unreachable code", .{}); } } break; } } } pub fn analyzeBodyValueAsType(mod: *Module, block_scope: *Scope.Block, body: zir.Module.Body) !Type { try analyzeBody(mod, &block_scope.base, body); for (block_scope.instructions.items) |inst| { if (inst.castTag(.ret)) |ret| { const val = try mod.resolveConstValue(&block_scope.base, ret.operand); return val.toType(); } else { return mod.fail(&block_scope.base, inst.src, "unable to resolve comptime value", .{}); } } unreachable; } pub fn analyzeZirDecl(mod: *Module, decl: *Decl, src_decl: *zir.Decl) InnerError!bool { var decl_scope: Scope.DeclAnalysis = .{ .decl = decl, .arena = std.heap.ArenaAllocator.init(mod.gpa), }; errdefer decl_scope.arena.deinit(); decl.analysis = .in_progress; const typed_value = try analyzeConstInst(mod, &decl_scope.base, src_decl.inst); const arena_state = try decl_scope.arena.allocator.create(std.heap.ArenaAllocator.State); var prev_type_has_bits = false; var type_changed = true; if (decl.typedValueManaged()) |tvm| { prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits(); type_changed = !tvm.typed_value.ty.eql(typed_value.ty); tvm.deinit(mod.gpa); } arena_state.* = decl_scope.arena.state; decl.typed_value = .{ .most_recent = .{ .typed_value = typed_value, .arena = arena_state, }, }; decl.analysis = .complete; decl.generation = mod.generation; if (typed_value.ty.hasCodeGenBits()) { // We don't fully codegen the decl until later, but we do need to reserve a global // offset table index for it. This allows us to codegen decls out of dependency order, // increasing how many computations can be done in parallel. try mod.bin_file.allocateDeclIndexes(decl); try mod.work_queue.writeItem(.{ .codegen_decl = decl }); } else if (prev_type_has_bits) { mod.bin_file.freeDecl(decl); } return type_changed; } pub fn resolveZirDecl(mod: *Module, scope: *Scope, src_decl: *zir.Decl) InnerError!*Decl { const zir_module = mod.root_scope.cast(Scope.ZIRModule).?; const entry = zir_module.contents.module.findDecl(src_decl.name).?; return resolveZirDeclHavingIndex(mod, scope, src_decl, entry.index); } fn resolveZirDeclHavingIndex(mod: *Module, scope: *Scope, src_decl: *zir.Decl, src_index: usize) InnerError!*Decl { const name_hash = scope.namespace().fullyQualifiedNameHash(src_decl.name); const decl = mod.decl_table.get(name_hash).?; decl.src_index = src_index; try mod.ensureDeclAnalyzed(decl); return decl; } /// Declares a dependency on the decl. fn resolveCompleteZirDecl(mod: *Module, scope: *Scope, src_decl: *zir.Decl) InnerError!*Decl { const decl = try resolveZirDecl(mod, scope, src_decl); switch (decl.analysis) { .unreferenced => unreachable, .in_progress => unreachable, .outdated => unreachable, .dependency_failure, .sema_failure, .sema_failure_retryable, .codegen_failure, .codegen_failure_retryable, => return error.AnalysisFail, .complete => {}, } return decl; } /// TODO Look into removing this function. The body is only needed for .zir files, not .zig files. pub fn resolveInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst { if (old_inst.analyzed_inst) |inst| return inst; // If this assert trips, the instruction that was referenced did not get properly // analyzed before it was referenced. const zir_module = scope.namespace().cast(Scope.ZIRModule).?; const entry = if (old_inst.cast(zir.Inst.DeclVal)) |declval| blk: { const decl_name = declval.positionals.name; const entry = zir_module.contents.module.findDecl(decl_name) orelse return mod.fail(scope, old_inst.src, "decl '{}' not found", .{decl_name}); break :blk entry; } else blk: { // If this assert trips, the instruction that was referenced did not get // properly analyzed by a previous instruction analysis before it was // referenced by the current one. break :blk zir_module.contents.module.findInstDecl(old_inst).?; }; const decl = try resolveCompleteZirDecl(mod, scope, entry.decl); const decl_ref = try mod.analyzeDeclRef(scope, old_inst.src, decl); // Note: it would be tempting here to store the result into old_inst.analyzed_inst field, // but this would prevent the analyzeDeclRef from happening, which is needed to properly // detect Decl dependencies and dependency failures on updates. return mod.analyzeDeref(scope, old_inst.src, decl_ref, old_inst.src); } fn resolveConstString(mod: *Module, scope: *Scope, old_inst: *zir.Inst) ![]u8 { const new_inst = try resolveInst(mod, scope, old_inst); const wanted_type = Type.initTag(.const_slice_u8); const coerced_inst = try mod.coerce(scope, wanted_type, new_inst); const val = try mod.resolveConstValue(scope, coerced_inst); return val.toAllocatedBytes(scope.arena()); } fn resolveType(mod: *Module, scope: *Scope, old_inst: *zir.Inst) !Type { const new_inst = try resolveInst(mod, scope, old_inst); const wanted_type = Type.initTag(.@"type"); const coerced_inst = try mod.coerce(scope, wanted_type, new_inst); const val = try mod.resolveConstValue(scope, coerced_inst); return val.toType(); } fn resolveInt(mod: *Module, scope: *Scope, old_inst: *zir.Inst, dest_type: Type) !u64 { const new_inst = try resolveInst(mod, scope, old_inst); const coerced = try mod.coerce(scope, dest_type, new_inst); const val = try mod.resolveConstValue(scope, coerced); return val.toUnsignedInt(); } pub fn resolveInstConst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue { const new_inst = try resolveInst(mod, scope, old_inst); const val = try mod.resolveConstValue(scope, new_inst); return TypedValue{ .ty = new_inst.ty, .val = val, }; } fn analyzeInstConst(mod: *Module, scope: *Scope, const_inst: *zir.Inst.Const) InnerError!*Inst { // Move the TypedValue from old memory to new memory. This allows freeing the ZIR instructions // after analysis. const typed_value_copy = try const_inst.positionals.typed_value.copy(scope.arena()); return mod.constInst(scope, const_inst.base.src, typed_value_copy); } fn analyzeConstInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue { const new_inst = try analyzeInst(mod, scope, old_inst); return TypedValue{ .ty = new_inst.ty, .val = try mod.resolveConstValue(scope, new_inst), }; } fn analyzeInstCoerceResultBlockPtr( mod: *Module, scope: *Scope, inst: *zir.Inst.CoerceResultBlockPtr, ) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstCoerceResultBlockPtr", .{}); } fn analyzeInstBitCastRef(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstBitCastRef", .{}); } fn analyzeInstBitCastResultPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstBitCastResultPtr", .{}); } fn analyzeInstCoerceResultPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstCoerceResultPtr", .{}); } /// Equivalent to `as(ptr_child_type(typeof(ptr)), value)`. fn analyzeInstCoerceToPtrElem(mod: *Module, scope: *Scope, inst: *zir.Inst.CoerceToPtrElem) InnerError!*Inst { const ptr = try resolveInst(mod, scope, inst.positionals.ptr); const operand = try resolveInst(mod, scope, inst.positionals.value); return mod.coerce(scope, ptr.ty.elemType(), operand); } fn analyzeInstRetPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstRetPtr", .{}); } fn analyzeInstRef(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); const ptr_type = try mod.simplePtrType(scope, inst.base.src, operand.ty, false, .One); if (operand.value()) |val| { const ref_payload = try scope.arena().create(Value.Payload.RefVal); ref_payload.* = .{ .val = val }; return mod.constInst(scope, inst.base.src, .{ .ty = ptr_type, .val = Value.initPayload(&ref_payload.base), }); } const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addUnOp(b, inst.base.src, ptr_type, .ref, operand); } fn analyzeInstRetType(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, inst.base.src); const fn_ty = b.func.?.owner_decl.typed_value.most_recent.typed_value.ty; const ret_type = fn_ty.fnReturnType(); return mod.constType(scope, inst.base.src, ret_type); } fn analyzeInstEnsureResultUsed(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); switch (operand.ty.zigTypeTag()) { .Void, .NoReturn => return mod.constVoid(scope, operand.src), else => return mod.fail(scope, operand.src, "expression value is ignored", .{}), } } fn analyzeInstEnsureResultNonError(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); switch (operand.ty.zigTypeTag()) { .ErrorSet, .ErrorUnion => return mod.fail(scope, operand.src, "error is discarded", .{}), else => return mod.constVoid(scope, operand.src), } } fn analyzeInstAlloc(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const var_type = try resolveType(mod, scope, inst.positionals.operand); // TODO this should happen only for var allocs if (!var_type.isValidVarType(false)) { return mod.fail(scope, inst.base.src, "variable of type '{}' must be const or comptime", .{var_type}); } const ptr_type = try mod.simplePtrType(scope, inst.base.src, var_type, true, .One); const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addNoOp(b, inst.base.src, ptr_type, .alloc); } fn analyzeInstAllocInferred(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstAllocInferred", .{}); } fn analyzeInstStore(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { const ptr = try resolveInst(mod, scope, inst.positionals.lhs); const value = try resolveInst(mod, scope, inst.positionals.rhs); return mod.storePtr(scope, inst.base.src, ptr, value); } fn analyzeInstParamType(mod: *Module, scope: *Scope, inst: *zir.Inst.ParamType) InnerError!*Inst { const fn_inst = try resolveInst(mod, scope, inst.positionals.func); const arg_index = inst.positionals.arg_index; const fn_ty: Type = switch (fn_inst.ty.zigTypeTag()) { .Fn => fn_inst.ty, .BoundFn => { return mod.fail(scope, fn_inst.src, "TODO implement analyzeInstParamType for method call syntax", .{}); }, else => { return mod.fail(scope, fn_inst.src, "expected function, found '{}'", .{fn_inst.ty}); }, }; // TODO support C-style var args const param_count = fn_ty.fnParamLen(); if (arg_index >= param_count) { return mod.fail(scope, inst.base.src, "arg index {} out of bounds; '{}' has {} argument(s)", .{ arg_index, fn_ty, param_count, }); } // TODO support generic functions const param_type = fn_ty.fnParamType(arg_index); return mod.constType(scope, inst.base.src, param_type); } fn analyzeInstStr(mod: *Module, scope: *Scope, str_inst: *zir.Inst.Str) InnerError!*Inst { // The bytes references memory inside the ZIR module, which can get deallocated // after semantic analysis is complete. We need the memory to be in the new anonymous Decl's arena. var new_decl_arena = std.heap.ArenaAllocator.init(mod.gpa); const arena_bytes = try new_decl_arena.allocator.dupe(u8, str_inst.positionals.bytes); const ty_payload = try scope.arena().create(Type.Payload.Array_u8_Sentinel0); ty_payload.* = .{ .len = arena_bytes.len }; const bytes_payload = try scope.arena().create(Value.Payload.Bytes); bytes_payload.* = .{ .data = arena_bytes }; const new_decl = try mod.createAnonymousDecl(scope, &new_decl_arena, .{ .ty = Type.initPayload(&ty_payload.base), .val = Value.initPayload(&bytes_payload.base), }); return mod.analyzeDeclRef(scope, str_inst.base.src, new_decl); } fn analyzeInstExport(mod: *Module, scope: *Scope, export_inst: *zir.Inst.Export) InnerError!*Inst { const symbol_name = try resolveConstString(mod, scope, export_inst.positionals.symbol_name); const exported_decl = mod.lookupDeclName(scope, export_inst.positionals.decl_name) orelse return mod.fail(scope, export_inst.base.src, "decl '{}' not found", .{export_inst.positionals.decl_name}); try mod.analyzeExport(scope, export_inst.base.src, symbol_name, exported_decl); return mod.constVoid(scope, export_inst.base.src); } fn analyzeInstCompileError(mod: *Module, scope: *Scope, inst: *zir.Inst.CompileError) InnerError!*Inst { return mod.fail(scope, inst.base.src, "{}", .{inst.positionals.msg}); } fn analyzeInstArg(mod: *Module, scope: *Scope, inst: *zir.Inst.Arg) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, inst.base.src); const fn_ty = b.func.?.owner_decl.typed_value.most_recent.typed_value.ty; const param_index = b.instructions.items.len; const param_count = fn_ty.fnParamLen(); if (param_index >= param_count) { return mod.fail(scope, inst.base.src, "parameter index {} outside list of length {}", .{ param_index, param_count, }); } const param_type = fn_ty.fnParamType(param_index); const name = try scope.arena().dupeZ(u8, inst.positionals.name); return mod.addArg(b, inst.base.src, param_type, name); } fn analyzeInstLoop(mod: *Module, scope: *Scope, inst: *zir.Inst.Loop) InnerError!*Inst { const parent_block = scope.cast(Scope.Block).?; // Reserve space for a Loop instruction so that generated Break instructions can // point to it, even if it doesn't end up getting used because the code ends up being // comptime evaluated. const loop_inst = try parent_block.arena.create(Inst.Loop); loop_inst.* = .{ .base = .{ .tag = Inst.Loop.base_tag, .ty = Type.initTag(.noreturn), .src = inst.base.src, }, .body = undefined, }; var child_block: Scope.Block = .{ .parent = parent_block, .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, }; defer child_block.instructions.deinit(mod.gpa); try analyzeBody(mod, &child_block.base, inst.positionals.body); // Loop repetition is implied so the last instruction may or may not be a noreturn instruction. try parent_block.instructions.append(mod.gpa, &loop_inst.base); loop_inst.body = .{ .instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items) }; return &loop_inst.base; } fn analyzeInstBlock(mod: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerError!*Inst { const parent_block = scope.cast(Scope.Block).?; // Reserve space for a Block instruction so that generated Break instructions can // point to it, even if it doesn't end up getting used because the code ends up being // comptime evaluated. const block_inst = try parent_block.arena.create(Inst.Block); block_inst.* = .{ .base = .{ .tag = Inst.Block.base_tag, .ty = undefined, // Set after analysis. .src = inst.base.src, }, .body = undefined, }; var child_block: Scope.Block = .{ .parent = parent_block, .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, // TODO @as here is working around a stage1 miscompilation bug :( .label = @as(?Scope.Block.Label, Scope.Block.Label{ .zir_block = inst, .results = .{}, .block_inst = block_inst, }), }; const label = &child_block.label.?; defer child_block.instructions.deinit(mod.gpa); defer label.results.deinit(mod.gpa); try analyzeBody(mod, &child_block.base, inst.positionals.body); // Blocks must terminate with noreturn instruction. assert(child_block.instructions.items.len != 0); assert(child_block.instructions.items[child_block.instructions.items.len - 1].ty.isNoReturn()); // Need to set the type and emit the Block instruction. This allows machine code generation // to emit a jump instruction to after the block when it encounters the break. try parent_block.instructions.append(mod.gpa, &block_inst.base); block_inst.base.ty = try mod.resolvePeerTypes(scope, label.results.items); block_inst.body = .{ .instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items) }; return &block_inst.base; } fn analyzeInstBreakpoint(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addNoOp(b, inst.base.src, Type.initTag(.void), .breakpoint); } fn analyzeInstBreak(mod: *Module, scope: *Scope, inst: *zir.Inst.Break) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); const block = inst.positionals.block; return analyzeBreak(mod, scope, inst.base.src, block, operand); } fn analyzeInstBreakVoid(mod: *Module, scope: *Scope, inst: *zir.Inst.BreakVoid) InnerError!*Inst { const block = inst.positionals.block; const void_inst = try mod.constVoid(scope, inst.base.src); return analyzeBreak(mod, scope, inst.base.src, block, void_inst); } fn analyzeInstDbgStmt(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addNoOp(b, inst.base.src, Type.initTag(.void), .dbg_stmt); } fn analyzeInstDeclRefStr(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclRefStr) InnerError!*Inst { const decl_name = try resolveConstString(mod, scope, inst.positionals.name); return mod.analyzeDeclRefByName(scope, inst.base.src, decl_name); } fn analyzeInstDeclRef(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclRef) InnerError!*Inst { return mod.analyzeDeclRefByName(scope, inst.base.src, inst.positionals.name); } fn analyzeInstDeclVal(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Inst { const decl = try analyzeDeclVal(mod, scope, inst); const ptr = try mod.analyzeDeclRef(scope, inst.base.src, decl); return mod.analyzeDeref(scope, inst.base.src, ptr, inst.base.src); } fn analyzeInstDeclValInModule(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclValInModule) InnerError!*Inst { const decl = inst.positionals.decl; return mod.analyzeDeclRef(scope, inst.base.src, decl); } fn analyzeInstCall(mod: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerError!*Inst { const func = try resolveInst(mod, scope, inst.positionals.func); if (func.ty.zigTypeTag() != .Fn) return mod.fail(scope, inst.positionals.func.src, "type '{}' not a function", .{func.ty}); const cc = func.ty.fnCallingConvention(); if (cc == .Naked) { // TODO add error note: declared here return mod.fail( scope, inst.positionals.func.src, "unable to call function with naked calling convention", .{}, ); } const call_params_len = inst.positionals.args.len; const fn_params_len = func.ty.fnParamLen(); if (func.ty.fnIsVarArgs()) { if (call_params_len < fn_params_len) { // TODO add error note: declared here return mod.fail( scope, inst.positionals.func.src, "expected at least {} argument(s), found {}", .{ fn_params_len, call_params_len }, ); } return mod.fail(scope, inst.base.src, "TODO implement support for calling var args functions", .{}); } else if (fn_params_len != call_params_len) { // TODO add error note: declared here return mod.fail( scope, inst.positionals.func.src, "expected {} argument(s), found {}", .{ fn_params_len, call_params_len }, ); } if (inst.kw_args.modifier == .compile_time) { return mod.fail(scope, inst.base.src, "TODO implement comptime function calls", .{}); } if (inst.kw_args.modifier != .auto) { return mod.fail(scope, inst.base.src, "TODO implement call with modifier {}", .{inst.kw_args.modifier}); } // TODO handle function calls of generic functions const fn_param_types = try mod.gpa.alloc(Type, fn_params_len); defer mod.gpa.free(fn_param_types); func.ty.fnParamTypes(fn_param_types); const casted_args = try scope.arena().alloc(*Inst, fn_params_len); for (inst.positionals.args) |src_arg, i| { const uncasted_arg = try resolveInst(mod, scope, src_arg); casted_args[i] = try mod.coerce(scope, fn_param_types[i], uncasted_arg); } const ret_type = func.ty.fnReturnType(); const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addCall(b, inst.base.src, ret_type, func, casted_args); } fn analyzeInstFn(mod: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError!*Inst { const fn_type = try resolveType(mod, scope, fn_inst.positionals.fn_type); const fn_zir = blk: { var fn_arena = std.heap.ArenaAllocator.init(mod.gpa); errdefer fn_arena.deinit(); const fn_zir = try scope.arena().create(Module.Fn.ZIR); fn_zir.* = .{ .body = .{ .instructions = fn_inst.positionals.body.instructions, }, .arena = fn_arena.state, }; break :blk fn_zir; }; const new_func = try scope.arena().create(Module.Fn); new_func.* = .{ .analysis = .{ .queued = fn_zir }, .owner_decl = scope.decl().?, }; const fn_payload = try scope.arena().create(Value.Payload.Function); fn_payload.* = .{ .func = new_func }; return mod.constInst(scope, fn_inst.base.src, .{ .ty = fn_type, .val = Value.initPayload(&fn_payload.base), }); } fn analyzeInstIntType(mod: *Module, scope: *Scope, inttype: *zir.Inst.IntType) InnerError!*Inst { return mod.fail(scope, inttype.base.src, "TODO implement inttype", .{}); } fn analyzeInstOptionalType(mod: *Module, scope: *Scope, optional: *zir.Inst.UnOp) InnerError!*Inst { const child_type = try resolveType(mod, scope, optional.positionals.operand); return mod.constType(scope, optional.base.src, try mod.optionalType(scope, child_type)); } fn analyzeInstArrayType(mod: *Module, scope: *Scope, array: *zir.Inst.BinOp) InnerError!*Inst { // TODO these should be lazily evaluated const len = try resolveInstConst(mod, scope, array.positionals.lhs); const elem_type = try resolveType(mod, scope, array.positionals.rhs); return mod.constType(scope, array.base.src, try mod.arrayType(scope, len.val.toUnsignedInt(), null, elem_type)); } fn analyzeInstArrayTypeSentinel(mod: *Module, scope: *Scope, array: *zir.Inst.ArrayTypeSentinel) InnerError!*Inst { // TODO these should be lazily evaluated const len = try resolveInstConst(mod, scope, array.positionals.len); const sentinel = try resolveInstConst(mod, scope, array.positionals.sentinel); const elem_type = try resolveType(mod, scope, array.positionals.elem_type); return mod.constType(scope, array.base.src, try mod.arrayType(scope, len.val.toUnsignedInt(), sentinel.val, elem_type)); } fn analyzeInstEnumLiteral(mod: *Module, scope: *Scope, inst: *zir.Inst.EnumLiteral) InnerError!*Inst { const payload = try scope.arena().create(Value.Payload.Bytes); payload.* = .{ .base = .{ .tag = .enum_literal }, .data = try scope.arena().dupe(u8, inst.positionals.name), }; return mod.constInst(scope, inst.base.src, .{ .ty = Type.initTag(.enum_literal), .val = Value.initPayload(&payload.base), }); } fn analyzeInstUnwrapOptional(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp, safety_check: bool) InnerError!*Inst { const operand = try resolveInst(mod, scope, unwrap.positionals.operand); assert(operand.ty.zigTypeTag() == .Pointer); if (operand.ty.elemType().zigTypeTag() != .Optional) { return mod.fail(scope, unwrap.base.src, "expected optional type, found {}", .{operand.ty.elemType()}); } const child_type = try operand.ty.elemType().optionalChildAlloc(scope.arena()); const child_pointer = try mod.simplePtrType(scope, unwrap.base.src, child_type, operand.ty.isConstPtr(), .One); if (operand.value()) |val| { if (val.isNull()) { return mod.fail(scope, unwrap.base.src, "unable to unwrap null", .{}); } return mod.constInst(scope, unwrap.base.src, .{ .ty = child_pointer, .val = val, }); } const b = try mod.requireRuntimeBlock(scope, unwrap.base.src); if (safety_check and mod.wantSafety(scope)) { const is_non_null = try mod.addUnOp(b, unwrap.base.src, Type.initTag(.bool), .isnonnull, operand); try mod.addSafetyCheck(b, is_non_null, .unwrap_null); } return mod.addUnOp(b, unwrap.base.src, child_pointer, .unwrap_optional, operand); } fn analyzeInstUnwrapErr(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp, safety_check: bool) InnerError!*Inst { return mod.fail(scope, unwrap.base.src, "TODO implement analyzeInstUnwrapErr", .{}); } fn analyzeInstEnsureErrPayloadVoid(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp) InnerError!*Inst { return mod.fail(scope, unwrap.base.src, "TODO implement analyzeInstEnsureErrPayloadVoid", .{}); } fn analyzeInstFnType(mod: *Module, scope: *Scope, fntype: *zir.Inst.FnType) InnerError!*Inst { const return_type = try resolveType(mod, scope, fntype.positionals.return_type); // Hot path for some common function types. if (fntype.positionals.param_types.len == 0) { if (return_type.zigTypeTag() == .NoReturn and fntype.kw_args.cc == .Unspecified) { return mod.constType(scope, fntype.base.src, Type.initTag(.fn_noreturn_no_args)); } if (return_type.zigTypeTag() == .Void and fntype.kw_args.cc == .Unspecified) { return mod.constType(scope, fntype.base.src, Type.initTag(.fn_void_no_args)); } if (return_type.zigTypeTag() == .NoReturn and fntype.kw_args.cc == .Naked) { return mod.constType(scope, fntype.base.src, Type.initTag(.fn_naked_noreturn_no_args)); } if (return_type.zigTypeTag() == .Void and fntype.kw_args.cc == .C) { return mod.constType(scope, fntype.base.src, Type.initTag(.fn_ccc_void_no_args)); } } const arena = scope.arena(); const param_types = try arena.alloc(Type, fntype.positionals.param_types.len); for (fntype.positionals.param_types) |param_type, i| { const resolved = try resolveType(mod, scope, param_type); // TODO skip for comptime params if (!resolved.isValidVarType(false)) { return mod.fail(scope, param_type.src, "parameter of type '{}' must be declared comptime", .{resolved}); } param_types[i] = resolved; } const payload = try arena.create(Type.Payload.Function); payload.* = .{ .cc = fntype.kw_args.cc, .return_type = return_type, .param_types = param_types, }; return mod.constType(scope, fntype.base.src, Type.initPayload(&payload.base)); } fn analyzeInstPrimitive(mod: *Module, scope: *Scope, primitive: *zir.Inst.Primitive) InnerError!*Inst { return mod.constInst(scope, primitive.base.src, primitive.positionals.tag.toTypedValue()); } fn analyzeInstAs(mod: *Module, scope: *Scope, as: *zir.Inst.BinOp) InnerError!*Inst { const dest_type = try resolveType(mod, scope, as.positionals.lhs); const new_inst = try resolveInst(mod, scope, as.positionals.rhs); return mod.coerce(scope, dest_type, new_inst); } fn analyzeInstPtrToInt(mod: *Module, scope: *Scope, ptrtoint: *zir.Inst.UnOp) InnerError!*Inst { const ptr = try resolveInst(mod, scope, ptrtoint.positionals.operand); if (ptr.ty.zigTypeTag() != .Pointer) { return mod.fail(scope, ptrtoint.positionals.operand.src, "expected pointer, found '{}'", .{ptr.ty}); } // TODO handle known-pointer-address const b = try mod.requireRuntimeBlock(scope, ptrtoint.base.src); const ty = Type.initTag(.usize); return mod.addUnOp(b, ptrtoint.base.src, ty, .ptrtoint, ptr); } fn analyzeInstFieldPtr(mod: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr) InnerError!*Inst { const object_ptr = try resolveInst(mod, scope, fieldptr.positionals.object_ptr); const field_name = try resolveConstString(mod, scope, fieldptr.positionals.field_name); const elem_ty = switch (object_ptr.ty.zigTypeTag()) { .Pointer => object_ptr.ty.elemType(), else => return mod.fail(scope, fieldptr.positionals.object_ptr.src, "expected pointer, found '{}'", .{object_ptr.ty}), }; switch (elem_ty.zigTypeTag()) { .Array => { if (mem.eql(u8, field_name, "len")) { const len_payload = try scope.arena().create(Value.Payload.Int_u64); len_payload.* = .{ .int = elem_ty.arrayLen() }; const ref_payload = try scope.arena().create(Value.Payload.RefVal); ref_payload.* = .{ .val = Value.initPayload(&len_payload.base) }; return mod.constInst(scope, fieldptr.base.src, .{ .ty = Type.initTag(.single_const_pointer_to_comptime_int), .val = Value.initPayload(&ref_payload.base), }); } else { return mod.fail( scope, fieldptr.positionals.field_name.src, "no member named '{}' in '{}'", .{ field_name, elem_ty }, ); } }, else => return mod.fail(scope, fieldptr.base.src, "type '{}' does not support field access", .{elem_ty}), } } fn analyzeInstIntCast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { const dest_type = try resolveType(mod, scope, inst.positionals.lhs); const operand = try resolveInst(mod, scope, inst.positionals.rhs); const dest_is_comptime_int = switch (dest_type.zigTypeTag()) { .ComptimeInt => true, .Int => false, else => return mod.fail( scope, inst.positionals.lhs.src, "expected integer type, found '{}'", .{ dest_type, }, ), }; switch (operand.ty.zigTypeTag()) { .ComptimeInt, .Int => {}, else => return mod.fail( scope, inst.positionals.rhs.src, "expected integer type, found '{}'", .{operand.ty}, ), } if (operand.value() != null) { return mod.coerce(scope, dest_type, operand); } else if (dest_is_comptime_int) { return mod.fail(scope, inst.base.src, "unable to cast runtime value to 'comptime_int'", .{}); } return mod.fail(scope, inst.base.src, "TODO implement analyze widen or shorten int", .{}); } fn analyzeInstBitCast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { const dest_type = try resolveType(mod, scope, inst.positionals.lhs); const operand = try resolveInst(mod, scope, inst.positionals.rhs); return mod.bitcast(scope, dest_type, operand); } fn analyzeInstFloatCast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { const dest_type = try resolveType(mod, scope, inst.positionals.lhs); const operand = try resolveInst(mod, scope, inst.positionals.rhs); const dest_is_comptime_float = switch (dest_type.zigTypeTag()) { .ComptimeFloat => true, .Float => false, else => return mod.fail( scope, inst.positionals.lhs.src, "expected float type, found '{}'", .{ dest_type, }, ), }; switch (operand.ty.zigTypeTag()) { .ComptimeFloat, .Float, .ComptimeInt => {}, else => return mod.fail( scope, inst.positionals.rhs.src, "expected float type, found '{}'", .{operand.ty}, ), } if (operand.value() != null) { return mod.coerce(scope, dest_type, operand); } else if (dest_is_comptime_float) { return mod.fail(scope, inst.base.src, "unable to cast runtime value to 'comptime_float'", .{}); } return mod.fail(scope, inst.base.src, "TODO implement analyze widen or shorten float", .{}); } fn analyzeInstElemPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.ElemPtr) InnerError!*Inst { const array_ptr = try resolveInst(mod, scope, inst.positionals.array_ptr); const uncasted_index = try resolveInst(mod, scope, inst.positionals.index); const elem_index = try mod.coerce(scope, Type.initTag(.usize), uncasted_index); if (array_ptr.ty.isSinglePointer() and array_ptr.ty.elemType().zigTypeTag() == .Array) { if (array_ptr.value()) |array_ptr_val| { if (elem_index.value()) |index_val| { // Both array pointer and index are compile-time known. const index_u64 = index_val.toUnsignedInt(); // @intCast here because it would have been impossible to construct a value that // required a larger index. const elem_ptr = try array_ptr_val.elemPtr(scope.arena(), @intCast(usize, index_u64)); const type_payload = try scope.arena().create(Type.Payload.PointerSimple); type_payload.* = .{ .base = .{ .tag = .single_const_pointer }, .pointee_type = array_ptr.ty.elemType().elemType(), }; return mod.constInst(scope, inst.base.src, .{ .ty = Type.initPayload(&type_payload.base), .val = elem_ptr, }); } } } return mod.fail(scope, inst.base.src, "TODO implement more analyze elemptr", .{}); } fn analyzeInstShl(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstShl", .{}); } fn analyzeInstShr(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstShr", .{}); } fn analyzeInstBitwise(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstBitwise", .{}); } fn analyzeInstArrayCat(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstArrayCat", .{}); } fn analyzeInstArrayMul(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstArrayMul", .{}); } fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); const lhs = try resolveInst(mod, scope, inst.positionals.lhs); const rhs = try resolveInst(mod, scope, inst.positionals.rhs); const instructions = &[_]*Inst{ lhs, rhs }; const resolved_type = try mod.resolvePeerTypes(scope, instructions); const casted_lhs = try mod.coerce(scope, resolved_type, lhs); const casted_rhs = try mod.coerce(scope, resolved_type, rhs); const scalar_type = if (resolved_type.zigTypeTag() == .Vector) resolved_type.elemType() else resolved_type; const scalar_tag = scalar_type.zigTypeTag(); if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { return mod.fail(scope, inst.base.src, "vector length mismatch: {} and {}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); } return mod.fail(scope, inst.base.src, "TODO implement support for vectors in analyzeInstBinOp", .{}); } else if (lhs.ty.zigTypeTag() == .Vector or rhs.ty.zigTypeTag() == .Vector) { return mod.fail(scope, inst.base.src, "mixed scalar and vector operands to comparison operator: '{}' and '{}'", .{ lhs.ty, rhs.ty, }); } const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt; const is_float = scalar_tag == .Float or scalar_tag == .ComptimeFloat; if (!is_int and !(is_float and floatOpAllowed(inst.base.tag))) { return mod.fail(scope, inst.base.src, "invalid operands to binary expression: '{}' and '{}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) }); } if (casted_lhs.value()) |lhs_val| { if (casted_rhs.value()) |rhs_val| { return analyzeInstComptimeOp(mod, scope, scalar_type, inst, lhs_val, rhs_val); } } const b = try mod.requireRuntimeBlock(scope, inst.base.src); const ir_tag = switch (inst.base.tag) { .add => Inst.Tag.add, .sub => Inst.Tag.sub, else => return mod.fail(scope, inst.base.src, "TODO implement arithmetic for operand '{}''", .{@tagName(inst.base.tag)}), }; return mod.addBinOp(b, inst.base.src, scalar_type, ir_tag, casted_lhs, casted_rhs); } /// Analyzes operands that are known at comptime fn analyzeInstComptimeOp(mod: *Module, scope: *Scope, res_type: Type, inst: *zir.Inst.BinOp, lhs_val: Value, rhs_val: Value) InnerError!*Inst { // incase rhs is 0, simply return lhs without doing any calculations // TODO Once division is implemented we should throw an error when dividing by 0. if (rhs_val.compareWithZero(.eq)) { return mod.constInst(scope, inst.base.src, .{ .ty = res_type, .val = lhs_val, }); } const is_int = res_type.isInt() or res_type.zigTypeTag() == .ComptimeInt; const value = try switch (inst.base.tag) { .add => blk: { const val = if (is_int) Module.intAdd(scope.arena(), lhs_val, rhs_val) else mod.floatAdd(scope, res_type, inst.base.src, lhs_val, rhs_val); break :blk val; }, .sub => blk: { const val = if (is_int) Module.intSub(scope.arena(), lhs_val, rhs_val) else mod.floatSub(scope, res_type, inst.base.src, lhs_val, rhs_val); break :blk val; }, else => return mod.fail(scope, inst.base.src, "TODO Implement arithmetic operand '{}'", .{@tagName(inst.base.tag)}), }; return mod.constInst(scope, inst.base.src, .{ .ty = res_type, .val = value, }); } fn analyzeInstDeref(mod: *Module, scope: *Scope, deref: *zir.Inst.UnOp) InnerError!*Inst { const ptr = try resolveInst(mod, scope, deref.positionals.operand); return mod.analyzeDeref(scope, deref.base.src, ptr, deref.positionals.operand.src); } fn analyzeInstAsm(mod: *Module, scope: *Scope, assembly: *zir.Inst.Asm) InnerError!*Inst { const return_type = try resolveType(mod, scope, assembly.positionals.return_type); const asm_source = try resolveConstString(mod, scope, assembly.positionals.asm_source); const output = if (assembly.kw_args.output) |o| try resolveConstString(mod, scope, o) else null; const inputs = try scope.arena().alloc([]const u8, assembly.kw_args.inputs.len); const clobbers = try scope.arena().alloc([]const u8, assembly.kw_args.clobbers.len); const args = try scope.arena().alloc(*Inst, assembly.kw_args.args.len); for (inputs) |*elem, i| { elem.* = try resolveConstString(mod, scope, assembly.kw_args.inputs[i]); } for (clobbers) |*elem, i| { elem.* = try resolveConstString(mod, scope, assembly.kw_args.clobbers[i]); } for (args) |*elem, i| { const arg = try resolveInst(mod, scope, assembly.kw_args.args[i]); elem.* = try mod.coerce(scope, Type.initTag(.usize), arg); } const b = try mod.requireRuntimeBlock(scope, assembly.base.src); const inst = try b.arena.create(Inst.Assembly); inst.* = .{ .base = .{ .tag = .assembly, .ty = return_type, .src = assembly.base.src, }, .asm_source = asm_source, .is_volatile = assembly.kw_args.@"volatile", .output = output, .inputs = inputs, .clobbers = clobbers, .args = args, }; try b.instructions.append(mod.gpa, &inst.base); return &inst.base; } fn analyzeInstCmp( mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp, op: std.math.CompareOperator, ) InnerError!*Inst { const lhs = try resolveInst(mod, scope, inst.positionals.lhs); const rhs = try resolveInst(mod, scope, inst.positionals.rhs); const is_equality_cmp = switch (op) { .eq, .neq => true, else => false, }; const lhs_ty_tag = lhs.ty.zigTypeTag(); const rhs_ty_tag = rhs.ty.zigTypeTag(); if (is_equality_cmp and lhs_ty_tag == .Null and rhs_ty_tag == .Null) { // null == null, null != null return mod.constBool(scope, inst.base.src, op == .eq); } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs_ty_tag == .Optional) or rhs_ty_tag == .Null and lhs_ty_tag == .Optional)) { // comparing null with optionals const opt_operand = if (lhs_ty_tag == .Optional) lhs else rhs; if (opt_operand.value()) |opt_val| { const is_null = opt_val.isNull(); return mod.constBool(scope, inst.base.src, if (op == .eq) is_null else !is_null); } const b = try mod.requireRuntimeBlock(scope, inst.base.src); const inst_tag: Inst.Tag = switch (op) { .eq => .isnull, .neq => .isnonnull, else => unreachable, }; return mod.addUnOp(b, inst.base.src, Type.initTag(.bool), inst_tag, opt_operand); } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs.ty.isCPtr()) or (rhs_ty_tag == .Null and lhs.ty.isCPtr()))) { return mod.fail(scope, inst.base.src, "TODO implement C pointer cmp", .{}); } else if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) { const non_null_type = if (lhs_ty_tag == .Null) rhs.ty else lhs.ty; return mod.fail(scope, inst.base.src, "comparison of '{}' with null", .{non_null_type}); } else if (is_equality_cmp and ((lhs_ty_tag == .EnumLiteral and rhs_ty_tag == .Union) or (rhs_ty_tag == .EnumLiteral and lhs_ty_tag == .Union))) { return mod.fail(scope, inst.base.src, "TODO implement equality comparison between a union's tag value and an enum literal", .{}); } else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) { if (!is_equality_cmp) { return mod.fail(scope, inst.base.src, "{} operator not allowed for errors", .{@tagName(op)}); } return mod.fail(scope, inst.base.src, "TODO implement equality comparison between errors", .{}); } else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) { // This operation allows any combination of integer and float types, regardless of the // signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for // numeric types. return mod.cmpNumeric(scope, inst.base.src, lhs, rhs, op); } return mod.fail(scope, inst.base.src, "TODO implement more cmp analysis", .{}); } fn analyzeInstTypeOf(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); return mod.constType(scope, inst.base.src, operand.ty); } fn analyzeInstBoolNot(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const uncasted_operand = try resolveInst(mod, scope, inst.positionals.operand); const bool_type = Type.initTag(.bool); const operand = try mod.coerce(scope, bool_type, uncasted_operand); if (try mod.resolveDefinedValue(scope, operand)) |val| { return mod.constBool(scope, inst.base.src, !val.toBool()); } const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addUnOp(b, inst.base.src, bool_type, .not, operand); } fn analyzeInstIsNonNull(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, invert_logic: bool) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); return mod.analyzeIsNull(scope, inst.base.src, operand, invert_logic); } fn analyzeInstIsErr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, invert_logic: bool) InnerError!*Inst { return mod.fail(scope, inst.base.src, "TODO implement analyzeInstIsErr", .{}); } fn analyzeInstCondBr(mod: *Module, scope: *Scope, inst: *zir.Inst.CondBr) InnerError!*Inst { const uncasted_cond = try resolveInst(mod, scope, inst.positionals.condition); const cond = try mod.coerce(scope, Type.initTag(.bool), uncasted_cond); if (try mod.resolveDefinedValue(scope, cond)) |cond_val| { const body = if (cond_val.toBool()) &inst.positionals.then_body else &inst.positionals.else_body; try analyzeBody(mod, scope, body.*); return mod.constVoid(scope, inst.base.src); } const parent_block = try mod.requireRuntimeBlock(scope, inst.base.src); var true_block: Scope.Block = .{ .parent = parent_block, .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, }; defer true_block.instructions.deinit(mod.gpa); try analyzeBody(mod, &true_block.base, inst.positionals.then_body); var false_block: Scope.Block = .{ .parent = parent_block, .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, }; defer false_block.instructions.deinit(mod.gpa); try analyzeBody(mod, &false_block.base, inst.positionals.else_body); const then_body: ir.Body = .{ .instructions = try scope.arena().dupe(*Inst, true_block.instructions.items) }; const else_body: ir.Body = .{ .instructions = try scope.arena().dupe(*Inst, false_block.instructions.items) }; return mod.addCondBr(parent_block, inst.base.src, cond, then_body, else_body); } fn analyzeInstUnreachable( mod: *Module, scope: *Scope, unreach: *zir.Inst.NoOp, safety_check: bool, ) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, unreach.base.src); // TODO Add compile error for @optimizeFor occurring too late in a scope. if (safety_check and mod.wantSafety(scope)) { return mod.safetyPanic(b, unreach.base.src, .unreach); } else { return mod.addNoOp(b, unreach.base.src, Type.initTag(.noreturn), .unreach); } } fn analyzeInstRet(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst { const operand = try resolveInst(mod, scope, inst.positionals.operand); const b = try mod.requireRuntimeBlock(scope, inst.base.src); return mod.addUnOp(b, inst.base.src, Type.initTag(.noreturn), .ret, operand); } fn analyzeInstRetVoid(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst { const b = try mod.requireRuntimeBlock(scope, inst.base.src); if (b.func) |func| { // Need to emit a compile error if returning void is not allowed. const void_inst = try mod.constVoid(scope, inst.base.src); const fn_ty = func.owner_decl.typed_value.most_recent.typed_value.ty; const casted_void = try mod.coerce(scope, fn_ty.fnReturnType(), void_inst); if (casted_void.ty.zigTypeTag() != .Void) { return mod.addUnOp(b, inst.base.src, Type.initTag(.noreturn), .ret, casted_void); } } return mod.addNoOp(b, inst.base.src, Type.initTag(.noreturn), .retvoid); } fn floatOpAllowed(tag: zir.Inst.Tag) bool { // extend this swich as additional operators are implemented return switch (tag) { .add, .sub => true, else => false, }; } fn analyzeBreak( mod: *Module, scope: *Scope, src: usize, zir_block: *zir.Inst.Block, operand: *Inst, ) InnerError!*Inst { var opt_block = scope.cast(Scope.Block); while (opt_block) |block| { if (block.label) |*label| { if (label.zir_block == zir_block) { try label.results.append(mod.gpa, operand); const b = try mod.requireRuntimeBlock(scope, src); return mod.addBr(b, src, label.block_inst, operand); } } opt_block = block.parent; } else unreachable; } fn analyzeDeclVal(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Decl { const decl_name = inst.positionals.name; const zir_module = scope.namespace().cast(Scope.ZIRModule).?; const src_decl = zir_module.contents.module.findDecl(decl_name) orelse return mod.fail(scope, inst.base.src, "use of undeclared identifier '{}'", .{decl_name}); const decl = try resolveCompleteZirDecl(mod, scope, src_decl.decl); return decl; } fn analyzeInstSimplePtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, mutable: bool, size: std.builtin.TypeInfo.Pointer.Size) InnerError!*Inst { const elem_type = try resolveType(mod, scope, inst.positionals.operand); const ty = try mod.simplePtrType(scope, inst.base.src, elem_type, mutable, size); return mod.constType(scope, inst.base.src, ty); } fn analyzeInstPtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.PtrType) InnerError!*Inst { // TODO lazy values const @"align" = if (inst.kw_args.@"align") |some| @truncate(u32, try resolveInt(mod, scope, some, Type.initTag(.u32))) else 0; const bit_offset = if (inst.kw_args.align_bit_start) |some| @truncate(u16, try resolveInt(mod, scope, some, Type.initTag(.u16))) else 0; const host_size = if (inst.kw_args.align_bit_end) |some| @truncate(u16, try resolveInt(mod, scope, some, Type.initTag(.u16))) else 0; if (host_size != 0 and bit_offset >= host_size * 8) return mod.fail(scope, inst.base.src, "bit offset starts after end of host integer", .{}); const sentinel = if (inst.kw_args.sentinel) |some| (try resolveInstConst(mod, scope, some)).val else null; const elem_type = try resolveType(mod, scope, inst.positionals.child_type); const ty = try mod.ptrType( scope, inst.base.src, elem_type, sentinel, @"align", bit_offset, host_size, inst.kw_args.mutable, inst.kw_args.@"allowzero", inst.kw_args.@"volatile", inst.kw_args.size, ); return mod.constType(scope, inst.base.src, ty); }
src-self-hosted/zir_sema.zig
const std = @import("std"); const builtin = @import("builtin"); const llvm = @import("llvm.zig"); const CInt = @import("c_int.zig").CInt; pub const FloatAbi = enum { Hard, Soft, SoftFp, }; pub const Target = union(enum) { Native, Cross: Cross, pub const Cross = struct { arch: builtin.Arch, os: builtin.Os, environ: builtin.Environ, object_format: builtin.ObjectFormat, }; pub fn objFileExt(self: Target) []const u8 { return switch (self.getObjectFormat()) { builtin.ObjectFormat.coff => ".obj", else => ".o", }; } pub fn exeFileExt(self: Target) []const u8 { return switch (self.getOs()) { builtin.Os.windows => ".exe", else => "", }; } pub fn libFileExt(self: Target, is_static: bool) []const u8 { return switch (self.getOs()) { builtin.Os.windows => if (is_static) ".lib" else ".dll", else => if (is_static) ".a" else ".so", }; } pub fn getOs(self: Target) builtin.Os { return switch (self) { Target.Native => builtin.os, @TagType(Target).Cross => |t| t.os, }; } pub fn getArch(self: Target) builtin.Arch { return switch (self) { Target.Native => builtin.arch, @TagType(Target).Cross => |t| t.arch, }; } pub fn getEnviron(self: Target) builtin.Environ { return switch (self) { Target.Native => builtin.environ, @TagType(Target).Cross => |t| t.environ, }; } pub fn getObjectFormat(self: Target) builtin.ObjectFormat { return switch (self) { Target.Native => builtin.object_format, @TagType(Target).Cross => |t| t.object_format, }; } pub fn isWasm(self: Target) bool { return switch (self.getArch()) { builtin.Arch.wasm32, builtin.Arch.wasm64 => true, else => false, }; } pub fn isDarwin(self: Target) bool { return switch (self.getOs()) { builtin.Os.ios, builtin.Os.macosx => true, else => false, }; } pub fn isWindows(self: Target) bool { return switch (self.getOs()) { builtin.Os.windows => true, else => false, }; } /// TODO expose the arch and subarch separately pub fn isArmOrThumb(self: Target) bool { return switch (self.getArch()) { builtin.Arch.armv8_3a, builtin.Arch.armv8_2a, builtin.Arch.armv8_1a, builtin.Arch.armv8, builtin.Arch.armv8r, builtin.Arch.armv8m_baseline, builtin.Arch.armv8m_mainline, builtin.Arch.armv7, builtin.Arch.armv7em, builtin.Arch.armv7m, builtin.Arch.armv7s, builtin.Arch.armv7k, builtin.Arch.armv7ve, builtin.Arch.armv6, builtin.Arch.armv6m, builtin.Arch.armv6k, builtin.Arch.armv6t2, builtin.Arch.armv5, builtin.Arch.armv5te, builtin.Arch.armv4t, builtin.Arch.armebv8_3a, builtin.Arch.armebv8_2a, builtin.Arch.armebv8_1a, builtin.Arch.armebv8, builtin.Arch.armebv8r, builtin.Arch.armebv8m_baseline, builtin.Arch.armebv8m_mainline, builtin.Arch.armebv7, builtin.Arch.armebv7em, builtin.Arch.armebv7m, builtin.Arch.armebv7s, builtin.Arch.armebv7k, builtin.Arch.armebv7ve, builtin.Arch.armebv6, builtin.Arch.armebv6m, builtin.Arch.armebv6k, builtin.Arch.armebv6t2, builtin.Arch.armebv5, builtin.Arch.armebv5te, builtin.Arch.armebv4t, builtin.Arch.thumb, builtin.Arch.thumbeb, => true, else => false, }; } pub fn initializeAll() void { llvm.InitializeAllTargets(); llvm.InitializeAllTargetInfos(); llvm.InitializeAllTargetMCs(); llvm.InitializeAllAsmPrinters(); llvm.InitializeAllAsmParsers(); } pub fn getTriple(self: Target, allocator: *std.mem.Allocator) !std.Buffer { var result = try std.Buffer.initSize(allocator, 0); errdefer result.deinit(); // LLVM WebAssembly output support requires the target to be activated at // build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly. // // LLVM determines the output format based on the environment suffix, // defaulting to an object based on the architecture. The default format in // LLVM 6 sets the wasm arch output incorrectly to ELF. We need to // explicitly set this ourself in order for it to work. // // This is fixed in LLVM 7 and you will be able to get wasm output by // using the target triple `wasm32-unknown-unknown-unknown`. const env_name = if (self.isWasm()) "wasm" else @tagName(self.getEnviron()); var out = &std.io.BufferOutStream.init(&result).stream; try out.print("{}-unknown-{}-{}", @tagName(self.getArch()), @tagName(self.getOs()), env_name); return result; } pub fn is64bit(self: Target) bool { return self.getArchPtrBitWidth() == 64; } pub fn getArchPtrBitWidth(self: Target) u32 { switch (self.getArch()) { builtin.Arch.avr, builtin.Arch.msp430, => return 16, builtin.Arch.arc, builtin.Arch.armv8_3a, builtin.Arch.armv8_2a, builtin.Arch.armv8_1a, builtin.Arch.armv8, builtin.Arch.armv8r, builtin.Arch.armv8m_baseline, builtin.Arch.armv8m_mainline, builtin.Arch.armv7, builtin.Arch.armv7em, builtin.Arch.armv7m, builtin.Arch.armv7s, builtin.Arch.armv7k, builtin.Arch.armv7ve, builtin.Arch.armv6, builtin.Arch.armv6m, builtin.Arch.armv6k, builtin.Arch.armv6t2, builtin.Arch.armv5, builtin.Arch.armv5te, builtin.Arch.armv4t, builtin.Arch.armebv8_3a, builtin.Arch.armebv8_2a, builtin.Arch.armebv8_1a, builtin.Arch.armebv8, builtin.Arch.armebv8r, builtin.Arch.armebv8m_baseline, builtin.Arch.armebv8m_mainline, builtin.Arch.armebv7, builtin.Arch.armebv7em, builtin.Arch.armebv7m, builtin.Arch.armebv7s, builtin.Arch.armebv7k, builtin.Arch.armebv7ve, builtin.Arch.armebv6, builtin.Arch.armebv6m, builtin.Arch.armebv6k, builtin.Arch.armebv6t2, builtin.Arch.armebv5, builtin.Arch.armebv5te, builtin.Arch.armebv4t, builtin.Arch.hexagon, builtin.Arch.le32, builtin.Arch.mips, builtin.Arch.mipsel, builtin.Arch.nios2, builtin.Arch.powerpc, builtin.Arch.r600, builtin.Arch.riscv32, builtin.Arch.sparc, builtin.Arch.sparcel, builtin.Arch.tce, builtin.Arch.tcele, builtin.Arch.thumb, builtin.Arch.thumbeb, builtin.Arch.i386, builtin.Arch.xcore, builtin.Arch.nvptx, builtin.Arch.amdil, builtin.Arch.hsail, builtin.Arch.spir, builtin.Arch.kalimbav3, builtin.Arch.kalimbav4, builtin.Arch.kalimbav5, builtin.Arch.shave, builtin.Arch.lanai, builtin.Arch.wasm32, builtin.Arch.renderscript32, => return 32, builtin.Arch.aarch64, builtin.Arch.aarch64_be, builtin.Arch.mips64, builtin.Arch.mips64el, builtin.Arch.powerpc64, builtin.Arch.powerpc64le, builtin.Arch.riscv64, builtin.Arch.x86_64, builtin.Arch.nvptx64, builtin.Arch.le64, builtin.Arch.amdil64, builtin.Arch.hsail64, builtin.Arch.spir64, builtin.Arch.wasm64, builtin.Arch.renderscript64, builtin.Arch.amdgcn, builtin.Arch.bpfel, builtin.Arch.bpfeb, builtin.Arch.sparcv9, builtin.Arch.s390x, => return 64, } } pub fn getFloatAbi(self: Target) FloatAbi { return switch (self.getEnviron()) { builtin.Environ.gnueabihf, builtin.Environ.eabihf, builtin.Environ.musleabihf, => FloatAbi.Hard, else => FloatAbi.Soft, }; } pub fn getDynamicLinkerPath(self: Target) ?[]const u8 { const env = self.getEnviron(); const arch = self.getArch(); switch (env) { builtin.Environ.android => { if (self.is64bit()) { return "/system/bin/linker64"; } else { return "/system/bin/linker"; } }, builtin.Environ.gnux32 => { if (arch == builtin.Arch.x86_64) { return "/libx32/ld-linux-x32.so.2"; } }, builtin.Environ.musl, builtin.Environ.musleabi, builtin.Environ.musleabihf, => { if (arch == builtin.Arch.x86_64) { return "/lib/ld-musl-x86_64.so.1"; } }, else => {}, } switch (arch) { builtin.Arch.i386, builtin.Arch.sparc, builtin.Arch.sparcel, => return "/lib/ld-linux.so.2", builtin.Arch.aarch64 => return "/lib/ld-linux-aarch64.so.1", builtin.Arch.aarch64_be => return "/lib/ld-linux-aarch64_be.so.1", builtin.Arch.armv8_3a, builtin.Arch.armv8_2a, builtin.Arch.armv8_1a, builtin.Arch.armv8, builtin.Arch.armv8r, builtin.Arch.armv8m_baseline, builtin.Arch.armv8m_mainline, builtin.Arch.armv7, builtin.Arch.armv7em, builtin.Arch.armv7m, builtin.Arch.armv7s, builtin.Arch.armv7k, builtin.Arch.armv7ve, builtin.Arch.armv6, builtin.Arch.armv6m, builtin.Arch.armv6k, builtin.Arch.armv6t2, builtin.Arch.armv5, builtin.Arch.armv5te, builtin.Arch.armv4t, builtin.Arch.thumb, => return switch (self.getFloatAbi()) { FloatAbi.Hard => return "/lib/ld-linux-armhf.so.3", else => return "/lib/ld-linux.so.3", }, builtin.Arch.armebv8_3a, builtin.Arch.armebv8_2a, builtin.Arch.armebv8_1a, builtin.Arch.armebv8, builtin.Arch.armebv8r, builtin.Arch.armebv8m_baseline, builtin.Arch.armebv8m_mainline, builtin.Arch.armebv7, builtin.Arch.armebv7em, builtin.Arch.armebv7m, builtin.Arch.armebv7s, builtin.Arch.armebv7k, builtin.Arch.armebv7ve, builtin.Arch.armebv6, builtin.Arch.armebv6m, builtin.Arch.armebv6k, builtin.Arch.armebv6t2, builtin.Arch.armebv5, builtin.Arch.armebv5te, builtin.Arch.armebv4t, builtin.Arch.thumbeb, => return switch (self.getFloatAbi()) { FloatAbi.Hard => return "/lib/ld-linux-armhf.so.3", else => return "/lib/ld-linux.so.3", }, builtin.Arch.mips, builtin.Arch.mipsel, builtin.Arch.mips64, builtin.Arch.mips64el, => return null, builtin.Arch.powerpc => return "/lib/ld.so.1", builtin.Arch.powerpc64 => return "/lib64/ld64.so.2", builtin.Arch.powerpc64le => return "/lib64/ld64.so.2", builtin.Arch.s390x => return "/lib64/ld64.so.1", builtin.Arch.sparcv9 => return "/lib64/ld-linux.so.2", builtin.Arch.x86_64 => return "/lib64/ld-linux-x86-64.so.2", builtin.Arch.arc, builtin.Arch.avr, builtin.Arch.bpfel, builtin.Arch.bpfeb, builtin.Arch.hexagon, builtin.Arch.msp430, builtin.Arch.nios2, builtin.Arch.r600, builtin.Arch.amdgcn, builtin.Arch.riscv32, builtin.Arch.riscv64, builtin.Arch.tce, builtin.Arch.tcele, builtin.Arch.xcore, builtin.Arch.nvptx, builtin.Arch.nvptx64, builtin.Arch.le32, builtin.Arch.le64, builtin.Arch.amdil, builtin.Arch.amdil64, builtin.Arch.hsail, builtin.Arch.hsail64, builtin.Arch.spir, builtin.Arch.spir64, builtin.Arch.kalimbav3, builtin.Arch.kalimbav4, builtin.Arch.kalimbav5, builtin.Arch.shave, builtin.Arch.lanai, builtin.Arch.wasm32, builtin.Arch.wasm64, builtin.Arch.renderscript32, builtin.Arch.renderscript64, => return null, } } pub fn llvmTargetFromTriple(triple: std.Buffer) !llvm.TargetRef { var result: llvm.TargetRef = undefined; var err_msg: [*]u8 = undefined; if (llvm.GetTargetFromTriple(triple.ptr(), &result, &err_msg) != 0) { std.debug.warn("triple: {s} error: {s}\n", triple.ptr(), err_msg); return error.UnsupportedTarget; } return result; } pub fn cIntTypeSizeInBits(self: Target, id: CInt.Id) u32 { const arch = self.getArch(); switch (self.getOs()) { builtin.Os.freestanding => switch (self.getArch()) { builtin.Arch.msp430 => switch (id) { CInt.Id.Short, CInt.Id.UShort, CInt.Id.Int, CInt.Id.UInt, => return 16, CInt.Id.Long, CInt.Id.ULong, => return 32, CInt.Id.LongLong, CInt.Id.ULongLong, => return 64, }, else => switch (id) { CInt.Id.Short, CInt.Id.UShort, => return 16, CInt.Id.Int, CInt.Id.UInt, => return 32, CInt.Id.Long, CInt.Id.ULong, => return self.getArchPtrBitWidth(), CInt.Id.LongLong, CInt.Id.ULongLong, => return 64, }, }, builtin.Os.linux, builtin.Os.macosx, builtin.Os.openbsd, builtin.Os.zen, => switch (id) { CInt.Id.Short, CInt.Id.UShort, => return 16, CInt.Id.Int, CInt.Id.UInt, => return 32, CInt.Id.Long, CInt.Id.ULong, => return self.getArchPtrBitWidth(), CInt.Id.LongLong, CInt.Id.ULongLong, => return 64, }, builtin.Os.windows => switch (id) { CInt.Id.Short, CInt.Id.UShort, => return 16, CInt.Id.Int, CInt.Id.UInt, => return 32, CInt.Id.Long, CInt.Id.ULong, CInt.Id.LongLong, CInt.Id.ULongLong, => return 64, }, builtin.Os.ananas, builtin.Os.cloudabi, builtin.Os.dragonfly, builtin.Os.freebsd, builtin.Os.fuchsia, builtin.Os.ios, builtin.Os.kfreebsd, builtin.Os.lv2, builtin.Os.netbsd, builtin.Os.solaris, builtin.Os.haiku, builtin.Os.minix, builtin.Os.rtems, builtin.Os.nacl, builtin.Os.cnk, builtin.Os.aix, builtin.Os.cuda, builtin.Os.nvcl, builtin.Os.amdhsa, builtin.Os.ps4, builtin.Os.elfiamcu, builtin.Os.tvos, builtin.Os.watchos, builtin.Os.mesa3d, builtin.Os.contiki, builtin.Os.amdpal, => @panic("TODO specify the C integer type sizes for this OS"), } } pub fn getDarwinArchString(self: Target) []const u8 { const arch = self.getArch(); switch (arch) { builtin.Arch.aarch64 => return "arm64", builtin.Arch.thumb, builtin.Arch.armv8_3a, builtin.Arch.armv8_2a, builtin.Arch.armv8_1a, builtin.Arch.armv8, builtin.Arch.armv8r, builtin.Arch.armv8m_baseline, builtin.Arch.armv8m_mainline, builtin.Arch.armv7, builtin.Arch.armv7em, builtin.Arch.armv7m, builtin.Arch.armv7s, builtin.Arch.armv7k, builtin.Arch.armv7ve, builtin.Arch.armv6, builtin.Arch.armv6m, builtin.Arch.armv6k, builtin.Arch.armv6t2, builtin.Arch.armv5, builtin.Arch.armv5te, builtin.Arch.armv4t, => return "arm", builtin.Arch.powerpc => return "ppc", builtin.Arch.powerpc64 => return "ppc64", builtin.Arch.powerpc64le => return "ppc64le", else => return @tagName(arch), } } };
src-self-hosted/target.zig
const std = @import("std"); const panic = std.debug.panic; const Builder = std.build.Builder; pub fn build(b: *Builder) !void { b.setPreferredReleaseMode(.ReleaseFast); const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const exe = b.addExecutable("furious-fowls", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.linkSystemLibrary("c"); exe.linkSystemLibrary("c++"); exe.addIncludeDir("src"); exe.addIncludeDir("deps/bgfx/3rdparty/renderdoc"); exe.addIncludeDir("deps/bgfx/include"); exe.addIncludeDir("deps/bimg/3rdparty/astc-codec"); exe.addIncludeDir("deps/bimg/3rdparty/astc-codec/include"); exe.addIncludeDir("deps/bimg/include"); exe.addIncludeDir("deps/bx/3rdparty"); exe.addIncludeDir("deps/bx/include"); exe.addIncludeDir("deps/glfw/include"); const glfw_flags = [_][]const u8{"-std=c99"}; const bx_flags = [_][]const u8{ "-std=c++14", "-ffast-math", "-fno-exceptions", "-fno-rtti", // Needed to avoid UB in bx/include/tinystl/buffer.h. "-fno-delete-null-pointer-checks", }; const glfw_files = [_][]const u8{ "deps/glfw/src/context.c", "deps/glfw/src/egl_context.c", "deps/glfw/src/init.c", "deps/glfw/src/input.c", "deps/glfw/src/monitor.c", "deps/glfw/src/osmesa_context.c", "deps/glfw/src/vulkan.c", "deps/glfw/src/window.c", }; const bx_files = [_][]const u8{ "deps/bx/src/allocator.cpp", "deps/bx/src/bx.cpp", "deps/bx/src/commandline.cpp", "deps/bx/src/crtnone.cpp", "deps/bx/src/debug.cpp", "deps/bx/src/dtoa.cpp", "deps/bx/src/easing.cpp", "deps/bx/src/file.cpp", "deps/bx/src/filepath.cpp", "deps/bx/src/hash.cpp", "deps/bx/src/math.cpp", "deps/bx/src/mutex.cpp", "deps/bx/src/os.cpp", "deps/bx/src/process.cpp", "deps/bx/src/semaphore.cpp", "deps/bx/src/settings.cpp", "deps/bx/src/sort.cpp", "deps/bx/src/string.cpp", "deps/bx/src/thread.cpp", "deps/bx/src/timer.cpp", "deps/bx/src/url.cpp", }; const bimg_files = [_][]const u8{ "deps/bimg/3rdparty/astc-codec/src/decoder/astc_file.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/codec.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/endpoint_codec.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/footprint.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/integer_sequence_codec.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/intermediate_astc_block.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/logical_astc_block.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/partition.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/physical_astc_block.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/quantization.cc", "deps/bimg/3rdparty/astc-codec/src/decoder/weight_infill.cc", "deps/bimg/src/image_gnf.cpp", "deps/bimg/src/image.cpp", }; const bgfx_files = [_][]const u8{ "deps/bgfx/src/bgfx.cpp", "deps/bgfx/src/debug_renderdoc.cpp", "deps/bgfx/src/dxgi.cpp", "deps/bgfx/src/glcontext_egl.cpp", "deps/bgfx/src/glcontext_glx.cpp", "deps/bgfx/src/glcontext_html5.cpp", "deps/bgfx/src/glcontext_wgl.cpp", "deps/bgfx/src/nvapi.cpp", "deps/bgfx/src/renderer_d3d11.cpp", "deps/bgfx/src/renderer_d3d12.cpp", "deps/bgfx/src/renderer_d3d9.cpp", "deps/bgfx/src/renderer_gl.cpp", "deps/bgfx/src/renderer_gnm.cpp", "deps/bgfx/src/renderer_noop.cpp", "deps/bgfx/src/renderer_nvn.cpp", "deps/bgfx/src/renderer_vk.cpp", "deps/bgfx/src/renderer_webgpu.cpp", "deps/bgfx/src/shader_dx9bc.cpp", "deps/bgfx/src/shader_dxbc.cpp", "deps/bgfx/src/shader_spirv.cpp", "deps/bgfx/src/shader.cpp", "deps/bgfx/src/topology.cpp", "deps/bgfx/src/vertexlayout.cpp", }; exe.addCSourceFiles(&bx_files ++ &bimg_files, &bx_flags); switch (target.getOsTag()) { .macos => { try b.env_map.set("ZIG_SYSTEM_LINKER_HACK", "1"); exe.addIncludeDir("deps/bx/include/compat/osx"); exe.linkFramework("CoreFoundation"); exe.linkFramework("Cocoa"); exe.linkFramework("IOKit"); exe.linkFramework("QuartzCore"); exe.linkFramework("Metal"); const cocoa_flag = [_][]const u8{"-D_GLFW_COCOA"}; exe.addCSourceFiles( glfw_files ++ &[_][]const u8{ "deps/glfw/src/cocoa_time.c", "deps/glfw/src/posix_thread.c", }, &glfw_flags ++ &cocoa_flag, ); try addObjectiveCFiles( exe, &[_][]const u8{"src/metal.m"}, &[_][]const u8{}, ); try addObjectiveCFiles( exe, &[_][]const u8{ "deps/glfw/src/cocoa_init.m", "deps/glfw/src/cocoa_joystick.m", "deps/glfw/src/cocoa_monitor.m", "deps/glfw/src/cocoa_window.m", "deps/glfw/src/nsgl_context.m", }, &glfw_flags ++ &cocoa_flag, ); const metal_flag = [_][]const u8{"-DBGFX_CONFIG_RENDERER_METAL=1"}; exe.addCSourceFiles(&bgfx_files, &bx_flags ++ &metal_flag); try addObjectiveCFiles( exe, &[_][]const u8{ "deps/bgfx/src/renderer_mtl.mm", }, &bx_flags ++ &metal_flag, ); }, .windows => { if (target.abi != null and target.abi.?.isGnu()) { exe.addIncludeDir("deps/bx/include/compat/mingw"); } else { exe.addIncludeDir("deps/bx/include/compat/msvc"); } exe.linkSystemLibrary("gdi32"); exe.addCSourceFiles( glfw_files ++ &[_][]const u8{ "deps/glfw/src/wgl_context.c", "deps/glfw/src/win32_init.c", "deps/glfw/src/win32_joystick.c", "deps/glfw/src/win32_monitor.c", "deps/glfw/src/win32_thread.c", "deps/glfw/src/win32_time.c", "deps/glfw/src/win32_window.c", }, glfw_flags ++ &[_][]const u8{"-D_GLFW_WIN32"}, ); exe.addCSourceFiles( &bgfx_files, &bx_flags ++ &[_][]const u8{"-DBGFX_CONFIG_RENDERER_DIRECT3D12=1"}, ); }, .linux => { exe.linkSystemLibrary("x11"); exe.linkSystemLibrary("xcursor"); exe.linkSystemLibrary("xi"); exe.linkSystemLibrary("xinerama"); exe.linkSystemLibrary("xrandr"); exe.addCSourceFiles( glfw_files ++ &[_][]const u8{ "deps/glfw/src/glx_context.c", "deps/glfw/src/linux_joystick.c", "deps/glfw/src/posix_thread.c", "deps/glfw/src/posix_time.c", "deps/glfw/src/x11_init.c", "deps/glfw/src/x11_monitor.c", "deps/glfw/src/x11_window.c", "deps/glfw/src/xkb_unicode.c", }, glfw_flags ++ &[_][]const u8{"-D_GLFW_X11"}, ); }, else => |tag| panic("unsupported OS {}", .{tag}), } exe.install(); const tests = b.addTest("src/main.zig"); tests.setTarget(target); tests.setBuildMode(mode); const test_step = b.step("test", "Run all tests"); test_step.dependOn(&tests.step); const run = exe.run(); run.step.dependOn(b.getInstallStep()); if (b.args) |args| { run.addArgs(args); } const run_step = b.step("run", "Launch the game"); run_step.dependOn(&run.step); } fn addObjectiveCFiles( exe: *std.build.LibExeObjStep, files: []const []const u8, flags: []const []const u8, ) !void { const b = exe.builder; const object_dir = try std.fs.path.join( b.allocator, &[_][]const u8{ b.build_root, b.cache_root, "objc" }, ); const cwd = std.fs.cwd(); try cwd.makePath(object_dir); var argv = std.ArrayList([]const u8).init(b.allocator); defer argv.deinit(); try argv.appendSlice(&[_][]const u8{ "clang", "-c", "", "-o", "" }); if (exe.build_mode == .Debug) { try argv.appendSlice(&[_][]const u8{ "-Og", "-g" }); } else { try argv.appendSlice(&[_][]const u8{ "-O2", "-DNDEBUG" }); } for (exe.include_dirs.items) |dir| { switch (dir) { .RawPath => |path| { try argv.append("-I"); try argv.append(path); }, else => {}, } } try argv.appendSlice(flags); for (files) |file| { const object = b.fmt("{s}{s}{s}.o", .{ object_dir, std.fs.path.sep_str, // All .m and .mm files in this project have unique filenames. std.fs.path.basename(file), }); exe.addObjectFile(object); // Only build once. This code shouldn't be changing. cwd.access(object, .{}) catch |err| switch (err) { std.os.AccessError.FileNotFound => { argv.items[2] = file; argv.items[4] = object; const cmd = b.addSystemCommand(argv.items); exe.step.dependOn(&cmd.step); }, else => return err, }; } }
build.zig
const std = @import("std"); const sample_utils = @import("sample_utils.zig"); const c = @import("c.zig").c; const glfw = @import("glfw"); const gpu = @import("gpu"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); const setup = try sample_utils.setup(allocator); const framebuffer_size = try setup.window.getFramebufferSize(); const window_data = try allocator.create(WindowData); window_data.* = .{ .surface = null, .swap_chain = null, .swap_chain_format = undefined, .current_desc = undefined, .target_desc = undefined, }; setup.window.setUserPointer(window_data); // If targeting OpenGL, we can't use the newer WGPUSurface API. Instead, we need to use the // older Dawn-specific API. https://bugs.chromium.org/p/dawn/issues/detail?id=269&q=surface&can=2 const use_legacy_api = setup.backend_type == .opengl or setup.backend_type == .opengles; var descriptor: gpu.SwapChain.Descriptor = undefined; if (!use_legacy_api) { window_data.swap_chain_format = .bgra8_unorm; descriptor = .{ .label = "basic swap chain", .usage = .render_attachment, .format = window_data.swap_chain_format, .width = framebuffer_size.width, .height = framebuffer_size.height, .present_mode = .fifo, .implementation = 0, }; window_data.surface = sample_utils.createSurfaceForWindow( &setup.native_instance, setup.window, comptime sample_utils.detectGLFWOptions(), ); } else { const binding = c.machUtilsCreateBinding(@enumToInt(setup.backend_type), @ptrCast(*c.GLFWwindow, setup.window.handle), @ptrCast(c.WGPUDevice, setup.device.ptr)); if (binding == null) { @panic("failed to create Dawn backend binding"); } descriptor = std.mem.zeroes(gpu.SwapChain.Descriptor); descriptor.implementation = c.machUtilsBackendBinding_getSwapChainImplementation(binding); window_data.swap_chain = setup.device.nativeCreateSwapChain(null, &descriptor); window_data.swap_chain_format = @intToEnum(gpu.Texture.Format, @intCast(u32, c.machUtilsBackendBinding_getPreferredSwapChainTextureFormat(binding))); window_data.swap_chain.?.configure( window_data.swap_chain_format, .render_attachment, framebuffer_size.width, framebuffer_size.height, ); } window_data.current_desc = descriptor; window_data.target_desc = descriptor; const vs = \\ @stage(vertex) fn main( \\ @builtin(vertex_index) VertexIndex : u32 \\ ) -> @builtin(position) vec4<f32> { \\ var pos = array<vec2<f32>, 3>( \\ vec2<f32>( 0.0, 0.5), \\ vec2<f32>(-0.5, -0.5), \\ vec2<f32>( 0.5, -0.5) \\ ); \\ return vec4<f32>(pos[VertexIndex], 0.0, 1.0); \\ } ; const vs_module = setup.device.createShaderModule(&.{ .label = "my vertex shader", .code = .{ .wgsl = vs }, }); const fs = \\ @stage(fragment) fn main() -> @location(0) vec4<f32> { \\ return vec4<f32>(1.0, 0.0, 0.0, 1.0); \\ } ; const fs_module = setup.device.createShaderModule(&.{ .label = "my fragment shader", .code = .{ .wgsl = fs }, }); // Fragment state const blend = gpu.BlendState{ .color = .{ .operation = .add, .src_factor = .one, .dst_factor = .one, }, .alpha = .{ .operation = .add, .src_factor = .one, .dst_factor = .one, }, }; const color_target = gpu.ColorTargetState{ .format = window_data.swap_chain_format, .blend = &blend, .write_mask = .all, }; const fragment = gpu.FragmentState{ .module = fs_module, .entry_point = "main", .targets = &.{color_target}, .constants = null, }; const pipeline_descriptor = gpu.RenderPipeline.Descriptor{ .fragment = &fragment, .layout = null, .depth_stencil = null, .vertex = .{ .module = vs_module, .entry_point = "main", .buffers = null, }, .multisample = .{ .count = 1, .mask = 0xFFFFFFFF, .alpha_to_coverage_enabled = false, }, .primitive = .{ .front_face = .ccw, .cull_mode = .none, .topology = .triangle_list, .strip_index_format = .none, }, }; const pipeline = setup.device.createRenderPipeline(&pipeline_descriptor); vs_module.release(); fs_module.release(); // Reconfigure the swap chain with the new framebuffer width/height, otherwise e.g. the Vulkan // device would be lost after a resize. setup.window.setFramebufferSizeCallback((struct { fn callback(window: glfw.Window, width: u32, height: u32) void { const pl = window.getUserPointer(WindowData); pl.?.target_desc.width = width; pl.?.target_desc.height = height; } }).callback); const queue = setup.device.getQueue(); while (!setup.window.shouldClose()) { try frame(.{ .window = setup.window, .device = setup.device, .pipeline = pipeline, .queue = queue, }); std.time.sleep(16 * std.time.ns_per_ms); } } const WindowData = struct { surface: ?gpu.Surface, swap_chain: ?gpu.SwapChain, swap_chain_format: gpu.Texture.Format, current_desc: gpu.SwapChain.Descriptor, target_desc: gpu.SwapChain.Descriptor, }; const FrameParams = struct { window: glfw.Window, device: gpu.Device, pipeline: gpu.RenderPipeline, queue: gpu.Queue, }; fn frame(params: FrameParams) !void { try glfw.pollEvents(); const pl = params.window.getUserPointer(WindowData).?; if (pl.swap_chain == null or !pl.current_desc.equal(&pl.target_desc)) { const use_legacy_api = pl.surface == null; if (!use_legacy_api) { pl.swap_chain = params.device.nativeCreateSwapChain(pl.surface, &pl.target_desc); } else pl.swap_chain.?.configure( pl.swap_chain_format, .render_attachment, pl.target_desc.width, pl.target_desc.height, ); pl.current_desc = pl.target_desc; } const back_buffer_view = pl.swap_chain.?.getCurrentTextureView(); const color_attachment = gpu.RenderPassColorAttachment{ .view = back_buffer_view, .resolve_target = null, .clear_value = std.mem.zeroes(gpu.Color), .load_op = .clear, .store_op = .store, }; const encoder = params.device.createCommandEncoder(null); const render_pass_info = gpu.RenderPassEncoder.Descriptor{ .color_attachments = &.{color_attachment}, .depth_stencil_attachment = null, }; const pass = encoder.beginRenderPass(&render_pass_info); pass.setPipeline(params.pipeline); pass.draw(3, 1, 0, 0); pass.end(); pass.release(); var command = encoder.finish(null); encoder.release(); params.queue.submit(&.{command}); command.release(); pl.swap_chain.?.present(); back_buffer_view.release(); }
gpu/examples/main.zig
const std = @import("std"); // Remember our old RPG Character struct? A struct is really just a // very convenient way to deal with memory. These fields (gold, // health, experience) are all values of a particular size. Add them // together and you have the size of the struct as a whole. const Character = struct { gold: u32 = 0, health: u8 = 100, experience: u32 = 0, }; // Here we create a character called "the_narrator" that is a constant // (immutable) instance of a Character struct. It is stored in your // program as data, and like the instruction code, it is loaded into // RAM when your program runs. The relative location of this data in // memory is hard-coded and neither the address nor the value changes. const the_narrator = Character{ .gold = 12, .health = 99, .experience = 9000, }; // This "global_wizard" character is very similar. The address for // this data won't change, but the data itself can since this is a var // and not a const. var global_wizard = Character{}; // A function is instruction code at a particular address. Function // parameters in Zig are always immutable. They are stored in "the // stack". A stack is a type of data structure and "the stack" is a // specific bit of RAM reserved for your program. The CPU has special // support for adding and removing things from "the stack", so it is // an extremely efficient place for memory storage. // // Also, when a function executes, the input arguments are often // loaded into the beating heart of the CPU itself in registers. // // Our main() function here has no input parameters, but it will have // a stack entry (called a "frame"). pub fn main() void { // Here, the "glorp" character will be allocated on the stack // because each instance of glorp is mutable and therefore unique // to the invocation of this function. var glorp = Character{ .gold = 30, }; // The "reward_xp" value is interesting. It's an immutable // value, so even though it is local, it can be put in global // data and shared between all invocations. But being such a // small value, it may also simply be inlined as a literal // value in your instruction code where it is used. It's up // to the compiler. const reward_xp: u32 = 200; // Now let's circle back around to that "std" struct we imported // at the top. Since it's just a regular Zig value once it's // imported, we can also assign new names for its fields and // declarations. "debug" refers to another struct and "print" is a // public function namespaced within THAT struct. // // Let's assign the std.debug.print function to a const named // "print" so that we can use this new name later! const print = std.debug.print; // Now let's look at assigning and pointing to values in Zig. // // We'll try three different ways of making a new name to access // our glorp Character and change one of its values. // // "glorp_access1" is incorrectly named! We asked Zig to set aside // memory for another Character struct. So when we assign glorp to // glorp_access1 here, we're actually assigning all of the fields // to make a copy! Now we have two separate characters. // // You don't need to fix this. But notice what gets printed in // your program's output for this one compared to the other two // assignments below! var glorp_access1: Character = glorp; // this is a copy constructor glorp_access1.gold = 111; print("1:{}!. ", .{glorp.gold == glorp_access1.gold}); // NOTE: // // If we tried to do this with a const Character instead of a // var, changing the gold field would give us a compiler error // because const values are immutable! // // "glorp_access2" will do what we want. It points to the original // glorp's address. Also remember that we get one implicit // dereference with struct fields, so accessing the "gold" field // from glorp_access2 looks just like accessing it from glorp // itself. var glorp_access2: *Character = &glorp; glorp_access2.gold = 222; print("2:{}!. ", .{glorp.gold == glorp_access2.gold}); // "glorp_access3" is interesting. It's also a pointer, but it's a // const. Won't that disallow changing the gold value? No! As you // may recall from our earlier pointer experiments, a constant // pointer can't change what it's POINTING AT, but the value at // the address it points to is still mutable! So we CAN change it. const glorp_access3: *Character = &glorp; glorp_access3.gold = 333; print("3:{}!. ", .{glorp.gold == glorp_access3.gold}); // NOTE: // // If we tried to do this with a *const Character pointer, // that would NOT work and we would get a compiler error // because the VALUE becomes immutable! // // Moving along... // // Passing arguments to functions is pretty much exactly like // making an assignment to a const (since Zig enforces that ALL // function parameters are const). // // Knowing this, see if you can make levelUp() work as expected - // it should add the specified amount to the supplied character's // experience points. // print("XP before:{}, ", .{glorp.experience}); // Fix 1 of 2 goes here: levelUp(&glorp, reward_xp); print("after:{}.\n", .{glorp.experience}); } // Fix 2 of 2 goes here: fn levelUp(character_access: *Character, xp: u32) void { character_access.experience += xp; } // And there's more! // // Data segments (allocated at compile time) and "the stack" // (allocated at run time) aren't the only places where program data // can be stored in memory. They're just the most efficient. Sometimes // we don't know how much memory our program will need until the // program is running. Also, there is a limit to the size of stack // memory allotted to programs (often set by your operating system). // For these occasions, we have "the heap". // // You can use as much heap memory as you like (within physical // limitations, of course), but it's much less efficient to manage // because there is no built-in CPU support for adding and removing // items as we have with the stack. Also, depending on the type of // allocation, your program MAY have to do expensive work to manage // the use of heap memory. We'll learn about heap allocators later. // // Whew! This has been a lot of information. You'll be pleased to know // that the next exercise gets us back to learning Zig language // features we can use right away to do more things!
exercises/051_values.zig
pub const DAV_AUTHN_SCHEME_BASIC = @as(u32, 1); pub const DAV_AUTHN_SCHEME_NTLM = @as(u32, 2); pub const DAV_AUTHN_SCHEME_PASSPORT = @as(u32, 4); pub const DAV_AUTHN_SCHEME_DIGEST = @as(u32, 8); pub const DAV_AUTHN_SCHEME_NEGOTIATE = @as(u32, 16); pub const DAV_AUTHN_SCHEME_CERT = @as(u32, 65536); pub const DAV_AUTHN_SCHEME_FBA = @as(u32, 1048576); //-------------------------------------------------------------------------------- // Section: Types (6) //-------------------------------------------------------------------------------- pub const DAV_CALLBACK_AUTH_BLOB = extern struct { pBuffer: ?*anyopaque, ulSize: u32, ulType: u32, }; pub const DAV_CALLBACK_AUTH_UNP = extern struct { pszUserName: ?PWSTR, ulUserNameLength: u32, pszPassword: ?PWSTR, ulPasswordLength: u32, }; pub const DAV_CALLBACK_CRED = extern struct { AuthBlob: DAV_CALLBACK_AUTH_BLOB, UNPBlob: DAV_CALLBACK_AUTH_UNP, bAuthBlobValid: BOOL, bSave: BOOL, }; pub const AUTHNEXTSTEP = enum(i32) { DefaultBehavior = 0, RetryRequest = 1, CancelRequest = 2, }; pub const DefaultBehavior = AUTHNEXTSTEP.DefaultBehavior; pub const RetryRequest = AUTHNEXTSTEP.RetryRequest; pub const CancelRequest = AUTHNEXTSTEP.CancelRequest; pub const PFNDAVAUTHCALLBACK_FREECRED = fn( pbuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNDAVAUTHCALLBACK = fn( lpwzServerName: ?PWSTR, lpwzRemoteName: ?PWSTR, dwAuthScheme: u32, dwFlags: u32, pCallbackCred: ?*DAV_CALLBACK_CRED, NextStep: ?*AUTHNEXTSTEP, pFreeCred: ?*?PFNDAVAUTHCALLBACK_FREECRED, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Functions (11) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavAddConnection( ConnectionHandle: ?*?HANDLE, RemoteName: ?[*:0]const u16, UserName: ?[*:0]const u16, Password: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 5? ClientCert: ?*u8, CertSize: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavDeleteConnection( ConnectionHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavGetUNCFromHTTPPath( Url: ?[*:0]const u16, UncPath: ?[*:0]u16, lpSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavGetHTTPFromUNCPath( UncPath: ?[*:0]const u16, Url: ?[*:0]u16, lpSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "davclnt" fn DavGetTheLockOwnerOfTheFile( FileName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? LockOwnerName: ?PWSTR, LockOwnerNameLengthInBytes: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavGetExtendedError( hFile: ?HANDLE, ExtError: ?*u32, ExtErrorString: [*:0]u16, cChSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DavFlushFile( hFile: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "davclnt" fn DavInvalidateCache( URLName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "davclnt" fn DavCancelConnectionsToServer( lpName: ?PWSTR, fForce: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "davclnt" fn DavRegisterAuthCallback( CallBack: ?PFNDAVAUTHCALLBACK, Version: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "davclnt" fn DavUnregisterAuthCallback( hCallback: u32, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (3) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const HANDLE = @import("../foundation.zig").HANDLE; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNDAVAUTHCALLBACK_FREECRED")) { _ = PFNDAVAUTHCALLBACK_FREECRED; } if (@hasDecl(@This(), "PFNDAVAUTHCALLBACK")) { _ = PFNDAVAUTHCALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/network_management/web_dav.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); fn PackedBoolsArray(comptime size: usize) type { return struct { words: [(size + 63) / 64]u64, fn setAll(self: *@This(), val: bool) void { @memset(@ptrCast([*]u8, &self.words), if (val) @as(u8, 0xFF) else @as(u8, 0x00), @sizeOf(u64) * self.words.len); } fn get(self: *@This(), index: usize) bool { const word = self.words[index / 64]; const bit = @intCast(u6, index % 64); return word & (@as(u64, 1) << bit) != 0; } fn set(self: *@This(), index: usize, val: bool) void { const word = &self.words[index / 64]; const bit = @intCast(u6, index % 64); if (val) { word.* |= (@as(u64, 1) << bit); } else { word.* &= ~(@as(u64, 1) << bit); } } }; } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { _ = input_text; const ans1 = ans: { var last_turn_of = [_]?u16{null} ** 5000; var last_spoken: u16 = undefined; var turn: u16 = undefined; for ([_]u16{ 0, 3, 1, 6, 7, 5 }) |n, i| { turn = @intCast(u16, i + 1); if (i > 0) { last_turn_of[last_spoken] = turn - 1; } last_spoken = n; } while (turn < 2020) : (turn += 1) { //std.debug.print("lastpoken({}): {}\n", .{ last_spoken, last_turn_of[last_spoken] }); const next = if (last_turn_of[last_spoken]) |prev_turn| turn - prev_turn else 0; last_turn_of[last_spoken] = turn; last_spoken = next; //std.debug.print("turn {}: {}\n", .{ turn + 1, last_spoken }); } break :ans last_spoken; }; const ans2 = ans: { // ça marche tranquille en bourrinant. pour voir, tenté avec une std.AutoArrayHashMap(u32, u32), mais c'est plus lent (beaucoup en debug) et pas vraiement moins gros. // (remplissage de last_turn_of = 3611683/30000000) const last_turn_of = try allocator.alloc(u32, 30000000); // 0 unseen, else turn defer allocator.free(last_turn_of); std.mem.set(u32, last_turn_of, 0); const valid_vals = try allocator.create(PackedBoolsArray(30000000)); defer allocator.destroy(valid_vals); valid_vals.setAll(false); var last_spoken: u32 = undefined; var turn: u32 = undefined; for ([_]u32{ 0, 3, 1, 6, 7, 5 }) |n, i| { turn = @intCast(u32, i + 1); if (i > 0) { last_turn_of[last_spoken] = (turn - 1); valid_vals.set(last_spoken, true); } last_spoken = n; } while (turn < 30000000) : (turn += 1) { //std.debug.print("lastpoken({}): {}\n", .{ last_spoken, last_turn_of[last_spoken] }); if (last_spoken < 4096) { // bootstaper ça pour eviter le test ci-dessous dans la boucle? const next = turn - last_turn_of[last_spoken]; last_turn_of[last_spoken] = turn; last_spoken = if (next != turn) next else 0; } else if (valid_vals.get(last_spoken)) { const next = turn - last_turn_of[last_spoken]; last_turn_of[last_spoken] = turn; last_spoken = next; } else { const next = 0; valid_vals.set(last_spoken, true); last_turn_of[last_spoken] = turn; last_spoken = next; } //std.debug.print("turn {}: {}\n", .{ turn + 1, last_spoken }); } break :ans last_spoken; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day14.txt", run);
2020/day15.zig
const std = @import("std"); const Answer = struct { @"0": u32, @"1": u32 }; const dirs = [4][2]i32{ [_]i32{ 0, 1 }, [_]i32{ 0, -1 }, [_]i32{ 1, 0 }, [_]i32{ -1, 0 } }; const Point = struct { x: usize, y: usize }; fn pointEquals(p: Point, q: Point) bool { return p.x == q.x and p.y == q.y; } fn run(filename: []const u8) !Answer { const file = try std.fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()).reader(); var buffer: [4096]u8 = undefined; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var arena = std.heap.ArenaAllocator.init(&gpa.allocator); defer arena.deinit(); var cave = std.ArrayList(std.ArrayList(u32)).init(&arena.allocator); while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| { var row = std.ArrayList(u32).init(&arena.allocator); var i: usize = 0; while (i < line.len) : (i += 1) { try row.append(try std.fmt.parseInt(u32, line[i .. i + 1], 10)); } try cave.append(row); } var total: u32 = 0; var i: usize = 0; while (i < cave.items.len) : (i += 1) { var j: usize = 0; cell_loop: while (j < cave.items[i].items.len) : (j += 1) { for (dirs) |dir| { if (0 <= @intCast(i32, i) + dir[0] and @intCast(i32, i) + dir[0] < cave.items.len and 0 <= @intCast(i32, j) + dir[1] and @intCast(i32, j) + dir[1] < cave.items[i].items.len) { if (cave.items[i].items[j] >= cave.items[@intCast(usize, @intCast(i32, i) + dir[0])].items[@intCast(usize, @intCast(i32, j) + dir[1])]) { continue :cell_loop; } } } total += cave.items[i].items[j] + 1; } } var flows = std.AutoHashMap(Point, Point).init(&gpa.allocator); defer flows.deinit(); var basins = std.AutoHashMap(Point, u32).init(&gpa.allocator); defer basins.deinit(); // var total2: u32 = 0; i = 0; while (i < cave.items.len) : (i += 1) { var j: usize = 0; while (j < cave.items[i].items.len) : (j += 1) { if (cave.items[i].items[j] == 9) { continue; } var min_adj_opt: ?Point = null; for (dirs) |dir| { if (0 <= @intCast(i32, i) + dir[0] and @intCast(i32, i) + dir[0] < cave.items.len and 0 <= @intCast(i32, j) + dir[1] and @intCast(i32, j) + dir[1] < cave.items[i].items.len) { if (min_adj_opt) |min_adj| { if (cave.items[@intCast(usize, @intCast(i32, i) + dir[0])].items[@intCast(usize, @intCast(i32, j) + dir[1])] < cave.items[min_adj.y].items[min_adj.x]) { min_adj_opt = Point{ .x = @intCast(usize, @intCast(i32, j) + dir[1]), .y = @intCast(usize, @intCast(i32, i) + dir[0]), }; } } else { min_adj_opt = Point{ .x = @intCast(usize, @intCast(i32, j) + dir[1]), .y = @intCast(usize, @intCast(i32, i) + dir[0]), }; } } } if (min_adj_opt) |min_adj| { if (cave.items[min_adj.y].items[min_adj.x] < cave.items[i].items[j]) { try flows.put(Point{ .x = j, .y = i, }, min_adj); } else { try flows.put(Point{ .x = j, .y = i, }, Point{ .x = j, .y = i }); } } } } i = 0; while (i < cave.items.len) : (i += 1) { var j: usize = 0; while (j < cave.items[i].items.len) : (j += 1) { var p = Point{ .x = j, .y = i }; if (flows.contains(p)) { while (!pointEquals(p, flows.get(p).?)) : (p = flows.get(p).?) {} if (basins.contains(p)) { try basins.put(p, basins.get(p).? + 1); } else { try basins.put(p, 1); } } } } var basin_sizes = std.ArrayList(u32).init(&gpa.allocator); defer basin_sizes.deinit(); var it = basins.valueIterator(); while (it.next()) |value_ptr| { try basin_sizes.append(value_ptr.*); } const decreasing = (struct { fn decreasing(context: void, a: u32, b: u32) bool { _ = context; return a > b; } }).decreasing; var top_basin_sizes: u32 = 1; std.sort.sort(u32, basin_sizes.items, {}, decreasing); i = 0; while (i < 3) : (i += 1) { top_basin_sizes *= basin_sizes.items[i]; } return Answer{ .@"0" = total, .@"1" = top_basin_sizes }; } pub fn main() !void { const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt"); std.debug.print("{d}\n", .{answer.@"0"}); std.debug.print("{d}\n", .{answer.@"1"}); } test { const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt"); try std.testing.expectEqual(@as(u32, 15), answer.@"0"); try std.testing.expectEqual(@as(u32, 1134), answer.@"1"); }
src/day09.zig
const std = @import("std"); const math = std.math; const expect = std.testing.expect; pub fn __ceilh(x: f16) callconv(.C) f16 { // TODO: more efficient implementation return @floatCast(f16, ceilf(x)); } pub fn ceilf(x: f32) callconv(.C) f32 { var u = @bitCast(u32, x); var e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 23) { return x; } else if (e >= 0) { m = @as(u32, 0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 == 0) { u += m; } u &= ~m; return @bitCast(f32, u); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 != 0) { return -0.0; } else { return 1.0; } } } pub fn ceil(x: f64) callconv(.C) f64 { const f64_toint = 1.0 / math.floatEps(f64); const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52 or x == 0) { return x; } if (u >> 63 != 0) { y = x - f64_toint + f64_toint - x; } else { y = x + f64_toint - f64_toint - x; } if (e <= 0x3FF - 1) { math.doNotOptimizeAway(y); if (u >> 63 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } pub fn __ceilx(x: f80) callconv(.C) f80 { // TODO: more efficient implementation return @floatCast(f80, ceilq(x)); } pub fn ceilq(x: f128) callconv(.C) f128 { const f128_toint = 1.0 / math.floatEps(f128); const u = @bitCast(u128, x); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112 or x == 0) return x; if (u >> 127 != 0) { y = x - f128_toint + f128_toint - x; } else { y = x + f128_toint - f128_toint - x; } if (e <= 0x3FFF - 1) { math.doNotOptimizeAway(y); if (u >> 127 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } pub fn ceill(x: c_longdouble) callconv(.C) c_longdouble { switch (@typeInfo(c_longdouble).Float.bits) { 16 => return __ceilh(x), 32 => return ceilf(x), 64 => return ceil(x), 80 => return __ceilx(x), 128 => return ceilq(x), else => @compileError("unreachable"), } } test "ceil32" { try expect(ceilf(1.3) == 2.0); try expect(ceilf(-1.3) == -1.0); try expect(ceilf(0.2) == 1.0); } test "ceil64" { try expect(ceil(1.3) == 2.0); try expect(ceil(-1.3) == -1.0); try expect(ceil(0.2) == 1.0); } test "ceil128" { try expect(ceilq(1.3) == 2.0); try expect(ceilq(-1.3) == -1.0); try expect(ceilq(0.2) == 1.0); } test "ceil32.special" { try expect(ceilf(0.0) == 0.0); try expect(ceilf(-0.0) == -0.0); try expect(math.isPositiveInf(ceilf(math.inf(f32)))); try expect(math.isNegativeInf(ceilf(-math.inf(f32)))); try expect(math.isNan(ceilf(math.nan(f32)))); } test "ceil64.special" { try expect(ceil(0.0) == 0.0); try expect(ceil(-0.0) == -0.0); try expect(math.isPositiveInf(ceil(math.inf(f64)))); try expect(math.isNegativeInf(ceil(-math.inf(f64)))); try expect(math.isNan(ceil(math.nan(f64)))); } test "ceil128.special" { try expect(ceilq(0.0) == 0.0); try expect(ceilq(-0.0) == -0.0); try expect(math.isPositiveInf(ceilq(math.inf(f128)))); try expect(math.isNegativeInf(ceilq(-math.inf(f128)))); try expect(math.isNan(ceilq(math.nan(f128)))); }
lib/compiler_rt/ceil.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const Parser = @This(); str: [:0]const u8, i: usize = 0, pub fn index(parser: *Parser, comptime T: type) !T { if (!parser.eatChar('[')) return error.InvalidIndex; const res = parser.intWithSign(usize, .pos, ']') catch return error.InvalidIndex; return math.cast(T, res) catch return error.InvalidIndex; } pub fn field(parser: *Parser, comptime name: []const u8) !void { return parser.fieldDedupe(name[0..name.len].*); } fn fieldDedupe(parser: *Parser, comptime name: anytype) !void { comptime std.debug.assert(name.len != 0); if (!parser.startsWith(("." ++ name ++ "[").*) and !parser.startsWith(("." ++ name ++ ".").*) and !parser.startsWith(("." ++ name ++ "=").*)) return error.InvalidField; parser.i += name.len + 1; } pub fn anyField(parser: *Parser) ![]const u8 { if (parser.eat() != '.') return error.InvalidValue; const start = parser.i; while (true) switch (parser.peek()) { '[', '.', '=' => break, 0 => return error.InvalidValue, else => parser.i += 1, }; return parser.str[start..parser.i]; } pub fn value(parser: *Parser) ![:'\n']const u8 { if (parser.eat() != '=') return error.InvalidValue; const start = parser.i; while (true) switch (parser.eat()) { '\n' => break, 0 => return error.InvalidValue, else => {}, }; return parser.str[start .. parser.i - 1 :'\n']; } pub fn enumValue(parser: *Parser, comptime T: type) !T { inline for (@typeInfo(T).Enum.fields) |f| { if (parser.eatString("=" ++ f.name ++ "\n")) return @field(T, f.name); } return error.InvalidEnumValue; } pub fn intValue(parser: *Parser, comptime T: type) !T { if (!parser.eatChar('=')) return error.InvalidIntValue; if (@typeInfo(T).Int.signedness == .signed and parser.eatChar('-')) return parser.intWithSign(T, .neg, '\n') catch return error.InvalidIntValue; return parser.intWithSign(T, .pos, '\n') catch return error.InvalidIntValue; } const Sign = enum { pos, neg }; fn intWithSign(parser: *Parser, comptime T: type, comptime sign: Sign, comptime term: u8) !T { const add = switch (sign) { .pos => math.add, .neg => math.sub, }; const first = parser.eatRange('0', '9') orelse return error.InvalidInt; var res = try math.cast(T, first - '0'); while (true) { const c = parser.eat(); switch (c) { '0'...'9' => { const digit = try math.cast(T, c - '0'); const base = try math.cast(T, @as(u8, 10)); res = try math.mul(T, res, base); res = try add(T, res, digit); }, term => return res, else => return error.InvalidInt, } } } fn eat(parser: *Parser) u8 { defer parser.i += 1; return parser.peek(); } fn eatChar(parser: *Parser, char: u8) bool { if (parser.peek() != char) return false; parser.i += 1; return true; } fn eatRange(parser: *Parser, start: u8, end: u8) ?u8 { const char = parser.peek(); if (char < start or end < char) return null; parser.i += 1; return char; } fn eatString(parser: *Parser, comptime str: []const u8) bool { if (parser.startsWith(str[0..str.len].*)) { parser.i += str.len; return true; } return false; } fn startsWith(parser: Parser, comptime prefix: anytype) bool { if (parser.str.len - parser.i < prefix.len) return false; comptime var i = 0; comptime var blk = 16; inline while (blk != 0) : (blk /= 2) { inline while (i + blk <= prefix.len) : (i += blk) { const Int = std.meta.Int(.unsigned, blk * 8); if (@bitCast(Int, parser.str[parser.i + i ..][0..blk].*) != @bitCast(Int, @as([blk]u8, prefix[i..][0..blk].*))) return false; } } return true; } fn peek(parser: *Parser) u8 { return parser.str[parser.i]; } pub fn rest(parser: Parser) [:0]const u8 { return parser.str[parser.i..]; }
src/Parser.zig
const std = @import("std"); const warn = std.debug.warn; const window = @import("window.zig"); const chip8 = @import("cpu.zig"); const c = @import("c.zig"); const Key = @import("keypad.zig").Keypad.Key; const Thread = @import("std").Thread; const audio = @import("audio.zig"); const test_rom = @embedFile("../assets/roms/test_opcode.ch8"); var cpu: chip8.Cpu = undefined; /// CpuContext is the context running on a different thread const CpuContext = struct { cpu: *chip8.Cpu }; var cpu_context: CpuContext = undefined; /// GLFW key input callback fn keyCallback(win: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void { switch (key) { c.GLFW_KEY_ESCAPE => { if (action == c.GLFW_PRESS) { cpu.stop(); window.shutdown(); } }, c.GLFW_KEY_P => { if (action == c.GLFW_PRESS) { if (cpu.running()) { cpu.stop(); } else { _ = Thread.spawn(cpu_context, startCpu) catch { warn("Could not start the CPU. Exiting...\n", .{}); window.shutdown(); }; } } }, c.GLFW_KEY_R => { if (action == c.GLFW_PRESS) { cpu.reset(); } }, c.GLFW_KEY_A => pressKeypad(action, Key.A), c.GLFW_KEY_B => pressKeypad(action, Key.B), c.GLFW_KEY_C => pressKeypad(action, Key.C), c.GLFW_KEY_D => pressKeypad(action, Key.D), c.GLFW_KEY_E => pressKeypad(action, Key.E), c.GLFW_KEY_F => pressKeypad(action, Key.F), c.GLFW_KEY_1 => pressKeypad(action, Key.One), c.GLFW_KEY_2 => pressKeypad(action, Key.Two), c.GLFW_KEY_3 => pressKeypad(action, Key.Three), c.GLFW_KEY_4 => pressKeypad(action, Key.Four), c.GLFW_KEY_5 => pressKeypad(action, Key.Five), c.GLFW_KEY_6 => pressKeypad(action, Key.Six), c.GLFW_KEY_7 => pressKeypad(action, Key.Seven), c.GLFW_KEY_8 => pressKeypad(action, Key.Eight), c.GLFW_KEY_9 => pressKeypad(action, Key.Nine), c.GLFW_KEY_0 => pressKeypad(action, Key.Zero), c.GLFW_KEY_M => { if (action == c.GLFW_PRESS) { audio.muteOrUnmute(); } }, else => {}, } } /// helper function to call the right keypad function based on the action fn pressKeypad(action: c_int, key: Key) void { if (action == c.GLFW_PRESS) { cpu.keypad.pressKey(key); } else { cpu.keypad.releaseKey(key); } } /// Starts up the program pub fn run() !void { var allocator = std.heap.page_allocator; const file_path = parseArgumentsToFilePath(allocator) catch { warn("Missing filepath argument for ROM\n", .{}); return; }; defer allocator.free(file_path); audio.init("assets/sound/8bitgame10.wav", 1024 * 100) catch { warn("Could not open the audio file, continuing without sound\n", .{}); }; defer audio.deinit(); try window.init(.{ .width = 1200, .height = 600, .title = "Lion", }, keyCallback); defer window.deinit(); cpu = chip8.Cpu.init(.{ .audio_callback = audio.play, .sound_timer = 1, .video_callback = window.update, }); var rom_bytes = try cpu.loadRom(allocator, file_path); defer allocator.free(rom_bytes); cpu_context = CpuContext{ .cpu = &cpu }; _ = try Thread.spawn(cpu_context, startCpu); window.run(); } /// Starts the cpu on a different thread fn startCpu(context: CpuContext) void { context.cpu.run() catch |err| { warn("Error occured while running the cpu: {}\n", .{err}); }; } // parses the given arguments to the executable, // returns MissingArgument if no argument is given for the ROM file path. fn parseArgumentsToFilePath(allocator: *std.mem.Allocator) ![]const u8 { var args = std.process.args(); // skip first argument const exe = try args.next(allocator) orelse unreachable; allocator.free(exe); return args.next(allocator) orelse return error.MissingArgument; }
src/emulator.zig
const std = @import("std"); const interop = @import("../interop.zig"); const iup = @import("../iup.zig"); const Impl = @import("../impl.zig").Impl; const CallbackHandler = @import("../callback_handler.zig").CallbackHandler; const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Handle = iup.Handle; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; const Size = iup.Size; const Margin = iup.Margin; /// /// Creates a label that displays an underlined clickable text. /// It inherits from IupLabel. pub const Link = opaque { pub const CLASS_NAME = "link"; pub const NATIVE_TYPE = iup.NativeType.Control; const Self = @This(); pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void; pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void; pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub const OnActionFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void; /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub const OnMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void; /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnMapFn = fn (self: *Self) anyerror!void; /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub const OnEnterWindowFn = fn (self: *Self) anyerror!void; pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32, arg3: i32, arg4: i32) anyerror!void; pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32) anyerror!void; pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void; /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void; /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnUnmapFn = fn (self: *Self) anyerror!void; /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub const OnButtonFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: [:0]const u8) anyerror!void; /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void; pub const ZOrder = enum { Top, Bottom, }; pub const Expand = enum { Yes, Horizontal, Vertical, HorizontalFree, VerticalFree, No, }; pub const Floating = enum { Yes, Ignore, No, }; pub const Initializer = struct { last_error: ?anyerror = null, ref: *Self, /// /// Returns a pointer to IUP element or an error. /// Only top-level or detached elements needs to be unwraped, pub fn unwrap(self: Initializer) !*Self { if (self.last_error) |e| { return e; } else { return self.ref; } } /// /// Captures a reference into a external variable /// Allows to capture some references even using full declarative API pub fn capture(self: *Initializer, ref: **Self) Initializer { ref.* = self.ref; return self.*; } pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; Self.setStrAttribute(self.ref, attributeName, arg); return self.*; } pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer { if (self.last_error) |_| return self.*; Self.setIntAttribute(self.ref, attributeName, arg); return self.*; } pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer { if (self.last_error) |_| return self.*; Self.setBoolAttribute(self.ref, attributeName, arg); return self.*; } pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer { if (self.last_error) |_| return self.*; Self.setPtrAttribute(self.ref, T, attributeName, value); return self.*; } pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setHandle(self.ref, arg); return self.*; } /// /// FGCOLOR: Text color. /// Default: the global attribute LINKFGCOLOR. pub fn setFgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "FGCOLOR", .{}, rgb); return self.*; } pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg); return self.*; } pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb); return self.*; } pub fn setWordWrap(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "WORDWRAP", .{}, arg); return self.*; } pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPICON", .{}, arg); return self.*; } pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value); return self.*; } pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self.ref, "POSITION", .{}, value); return self.*; } pub fn setIMinActive(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "IMINACTIVE", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setIMinActiveHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "IMINACTIVE", .{}, arg); return self.*; } pub fn setDropFilesTarget(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg); return self.*; } pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIP", .{}, arg); return self.*; } pub fn setCanFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg); return self.*; } pub fn setDragSourceMove(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg); return self.*; } pub fn setVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg); return self.*; } pub fn setSeparator(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "SEPARATOR", .{}, arg); return self.*; } pub fn setImage(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "IMAGE", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "IMAGE", .{}, arg); return self.*; } pub fn setCursor(self: *Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setCursorHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "CURSOR", .{}, arg); return self.*; } pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self.ref, "ZORDER", .{}); } return self.*; } /// /// URL: the default value is "YES". pub fn setUrl(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "URL", .{}, arg); return self.*; } pub fn setDragDrop(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg); return self.*; } pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "THEME", .{}, arg); return self.*; } pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self.ref, "EXPAND", .{}); } return self.*; } pub fn setSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "SIZE", .{}, value); return self.*; } pub fn setPadding(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "PADDING", .{}, value); return self.*; } pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg); return self.*; } pub fn setFontSize(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg); return self.*; } pub fn setDropTypes(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg); return self.*; } pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "USERSIZE", .{}, value); return self.*; } pub fn setTipDelay(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg); return self.*; } pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TITLE", .{}, arg); return self.*; } pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg); return self.*; } pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BGCOLOR", .{}, rgb); return self.*; } pub fn setDropTarget(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg); return self.*; } pub fn setDragSource(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg); return self.*; } pub fn setMarkup(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MARKUP", .{}, arg); return self.*; } pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self.ref, "FLOATING", .{}); } return self.*; } pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg); return self.*; } pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value); return self.*; } pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb); return self.*; } pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg); return self.*; } pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NAME", .{}, arg); return self.*; } pub fn setEllipsis(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "ELLIPSIS", .{}, arg); return self.*; } pub fn setCPadding(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "CPADDING", .{}, value); return self.*; } pub fn setActive(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg); return self.*; } pub fn setTipVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg); return self.*; } pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer { if (self.last_error) |_| return self.*; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg); return self.*; } pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MINSIZE", .{}, value); return self.*; } pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NTHEME", .{}, arg); return self.*; } pub fn setDragTypes(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg); return self.*; } pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg); return self.*; } pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONT", .{}, arg); return self.*; } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg); return self.*; } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg); return self.*; } pub fn setDropMotionCallback(self: *Initializer, callback: ?OnDropMotionFn) Initializer { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragEndCallback(self: *Initializer, callback: ?OnDragEndFn) Initializer { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragBeginCallback(self: *Initializer, callback: ?OnDragBeginFn) Initializer { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub fn setActionCallback(self: *Initializer, callback: ?OnActionFn) Initializer { const Handler = CallbackHandler(Self, OnActionFn, "ACTION"); Handler.setCallback(self.ref, callback); return self.*; } /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub fn setMotionCallback(self: *Initializer, callback: ?OnMotionFn) Initializer { const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDropDataCallback(self: *Initializer, callback: ?OnDropDataFn) Initializer { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragDataCallback(self: *Initializer, callback: ?OnDragDataFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setDragDataSizeCallback(self: *Initializer, callback: ?OnDragDataSizeFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: *Initializer, callback: ?OnDropFilesFn) Initializer { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub fn setButtonCallback(self: *Initializer, callback: ?OnButtonFn) Initializer { const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } }; pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void { interop.setStrAttribute(self, attribute, .{}, arg); } pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 { return interop.getStrAttribute(self, attribute, .{}); } pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void { interop.setIntAttribute(self, attribute, .{}, arg); } pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 { return interop.getIntAttribute(self, attribute, .{}); } pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void { interop.setBoolAttribute(self, attribute, .{}, arg); } pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool { return interop.getBoolAttribute(self, attribute, .{}); } pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T { return interop.getPtrAttribute(T, self, attribute, .{}); } pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void { interop.setPtrAttribute(T, self, attribute, .{}, value); } pub fn setHandle(self: *Self, arg: [:0]const u8) void { interop.setHandle(self, arg); } pub fn fromHandleName(handle_name: [:0]const u8) ?*Self { return interop.fromHandleName(Self, handle_name); } /// /// Creates an interface element given its class name and parameters. /// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible. pub fn init() Initializer { var handle = interop.create(Self); if (handle) |valid| { return .{ .ref = @ptrCast(*Self, valid), }; } else { return .{ .ref = undefined, .last_error = Error.NotInitialized }; } } /// /// Displays a dialog in the current position, or changes a control VISIBLE attribute. /// For dialogs it is equivalent to call IupShowXY using IUP_CURRENT. See IupShowXY for more details. /// For other controls, to call IupShow is the same as setting VISIBLE=YES. pub fn show(self: *Self) !void { try interop.show(self); } /// /// Hides an interface element. This function has the same effect as attributing value "NO" to the interface element’s VISIBLE attribute. /// Once a dialog is hidden, either by means of IupHide or by changing the VISIBLE attribute or by means of a click in the window close button, the elements inside this dialog are not destroyed, so that you can show the dialog again. To destroy dialogs, the IupDestroy function must be called. pub fn hide(self: *Self) void { interop.hide(self); } /// /// Destroys an interface element and all its children. /// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed. pub fn deinit(self: *Self) void { interop.destroy(self); } /// /// Creates (maps) the native interface objects corresponding to the given IUP interface elements. /// It will also called recursively to create the native element of all the children in the element's tree. /// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped. /// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup. /// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog. /// Calling IupMap for an already mapped element that is not a dialog does nothing. /// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout. /// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1). /// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible. /// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14). pub fn map(self: *Self) !void { try interop.map(self); } /// /// pub fn getDialog(self: *Self) ?*iup.Dialog { return interop.getDialog(self); } /// /// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy. /// Works also for children of a menu that is associated with a dialog. pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element { return interop.getDialogChild(self, byName); } /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *Self) void { Impl(Self).refresh(self); } /// /// FGCOLOR: Text color. /// Default: the global attribute LINKFGCOLOR. pub fn getFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "FGCOLOR", .{}); } /// /// FGCOLOR: Text color. /// Default: the global attribute LINKFGCOLOR. pub fn setFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "FGCOLOR", .{}, rgb); } pub fn getHandleName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HANDLENAME", .{}); } pub fn setHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HANDLENAME", .{}, arg); } pub fn getTipBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPBGCOLOR", .{}); } pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPBGCOLOR", .{}, rgb); } pub fn getWordWrap(self: *Self) bool { return interop.getBoolAttribute(self, "WORDWRAP", .{}); } pub fn setWordWrap(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "WORDWRAP", .{}, arg); } pub fn getTipIcon(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPICON", .{}); } pub fn setTipIcon(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPICON", .{}, arg); } pub fn getMaxSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MAXSIZE", .{}); return Size.parse(str); } pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MAXSIZE", .{}, value); } pub fn getScreenPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "SCREENPOSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn getPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "POSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn setPosition(self: *Self, x: i32, y: i32) void { var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self, "POSITION", .{}, value); } pub fn getIMinActive(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "IMINACTIVE", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setIMinActive(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "IMINACTIVE", .{}, arg); } pub fn setIMinActiveHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "IMINACTIVE", .{}, arg); } pub fn getDropFilesTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPFILESTARGET", .{}); } pub fn setDropFilesTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg); } pub fn getTip(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIP", .{}); } pub fn setTip(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIP", .{}, arg); } pub fn getCanFocus(self: *Self) bool { return interop.getBoolAttribute(self, "CANFOCUS", .{}); } pub fn setCanFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CANFOCUS", .{}, arg); } pub fn getDragSourceMove(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{}); } pub fn setDragSourceMove(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg); } pub fn getVisible(self: *Self) bool { return interop.getBoolAttribute(self, "VISIBLE", .{}); } pub fn setVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "VISIBLE", .{}, arg); } pub fn getSeparator(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "SEPARATOR", .{}); } pub fn setSeparator(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "SEPARATOR", .{}, arg); } pub fn getImage(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "IMAGE", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setImage(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "IMAGE", .{}, arg); } pub fn setImageHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "IMAGE", .{}, arg); } pub fn getCursor(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setCursor(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "CURSOR", .{}, arg); } pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "CURSOR", .{}, arg); } pub fn zOrder(self: *Self, arg: ?ZOrder) void { if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self, "ZORDER", .{}); } } pub fn getX(self: *Self) i32 { return interop.getIntAttribute(self, "X", .{}); } pub fn getY(self: *Self) i32 { return interop.getIntAttribute(self, "Y", .{}); } /// /// URL: the default value is "YES". pub fn getUrl(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "URL", .{}); } /// /// URL: the default value is "YES". pub fn setUrl(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "URL", .{}, arg); } pub fn getDragDrop(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGDROP", .{}); } pub fn setDragDrop(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGDROP", .{}, arg); } pub fn getTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "THEME", .{}); } pub fn setTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "THEME", .{}, arg); } pub fn getExpand(self: *Self) ?Expand { var ret = interop.getStrAttribute(self, "EXPAND", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal; if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical; if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree; if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } pub fn setExpand(self: *Self, arg: ?Expand) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self, "EXPAND", .{}); } } pub fn getSize(self: *Self) Size { var str = interop.getStrAttribute(self, "SIZE", .{}); return Size.parse(str); } pub fn setSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "SIZE", .{}, value); } pub fn getPadding(self: *Self) Size { var str = interop.getStrAttribute(self, "PADDING", .{}); return Size.parse(str); } pub fn setPadding(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "PADDING", .{}, value); } pub fn getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } pub fn getTipMarkup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPMARKUP", .{}); } pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPMARKUP", .{}, arg); } pub fn getFontSize(self: *Self) i32 { return interop.getIntAttribute(self, "FONTSIZE", .{}); } pub fn setFontSize(self: *Self, arg: i32) void { interop.setIntAttribute(self, "FONTSIZE", .{}, arg); } pub fn getNaturalSize(self: *Self) Size { var str = interop.getStrAttribute(self, "NATURALSIZE", .{}); return Size.parse(str); } pub fn getDropTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DROPTYPES", .{}); } pub fn setDropTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DROPTYPES", .{}, arg); } pub fn getUserSize(self: *Self) Size { var str = interop.getStrAttribute(self, "USERSIZE", .{}); return Size.parse(str); } pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "USERSIZE", .{}, value); } pub fn getTipDelay(self: *Self) i32 { return interop.getIntAttribute(self, "TIPDELAY", .{}); } pub fn setTipDelay(self: *Self, arg: i32) void { interop.setIntAttribute(self, "TIPDELAY", .{}, arg); } pub fn getTitle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TITLE", .{}); } pub fn setTitle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TITLE", .{}, arg); } pub fn getPropagateFocus(self: *Self) bool { return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{}); } pub fn setPropagateFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg); } pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } pub fn getDropTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPTARGET", .{}); } pub fn setDropTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPTARGET", .{}, arg); } pub fn getDragSource(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCE", .{}); } pub fn setDragSource(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg); } pub fn getMarkup(self: *Self) bool { return interop.getBoolAttribute(self, "MARKUP", .{}); } pub fn setMarkup(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MARKUP", .{}, arg); } pub fn getFloating(self: *Self) ?Floating { var ret = interop.getStrAttribute(self, "FLOATING", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } pub fn setFloating(self: *Self, arg: ?Floating) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self, "FLOATING", .{}); } } pub fn getNormalizerGroup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NORMALIZERGROUP", .{}); } pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg); } pub fn getRasterSize(self: *Self) Size { var str = interop.getStrAttribute(self, "RASTERSIZE", .{}); return Size.parse(str); } pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RASTERSIZE", .{}, value); } pub fn getTipFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPFGCOLOR", .{}); } pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPFGCOLOR", .{}, rgb); } pub fn getFontFace(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTFACE", .{}); } pub fn setFontFace(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTFACE", .{}, arg); } pub fn getName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NAME", .{}); } pub fn setName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NAME", .{}, arg); } pub fn getEllipsis(self: *Self) bool { return interop.getBoolAttribute(self, "ELLIPSIS", .{}); } pub fn setEllipsis(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ELLIPSIS", .{}, arg); } pub fn getCPadding(self: *Self) Size { var str = interop.getStrAttribute(self, "CPADDING", .{}); return Size.parse(str); } pub fn setCPadding(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "CPADDING", .{}, value); } pub fn getActive(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVE", .{}); } pub fn setActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ACTIVE", .{}, arg); } pub fn getTipVisible(self: *Self) bool { return interop.getBoolAttribute(self, "TIPVISIBLE", .{}); } pub fn setTipVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg); } pub fn getExpandWeight(self: *Self) f64 { return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{}); } pub fn setExpandWeight(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg); } pub fn getMinSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MINSIZE", .{}); return Size.parse(str); } pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MINSIZE", .{}, value); } pub fn getNTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NTHEME", .{}); } pub fn setNTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NTHEME", .{}, arg); } pub fn getCharSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CHARSIZE", .{}); return Size.parse(str); } pub fn getDragTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DRAGTYPES", .{}); } pub fn setDragTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DRAGTYPES", .{}, arg); } pub fn getFontStyle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTSTYLE", .{}); } pub fn setFontStyle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTSTYLE", .{}, arg); } pub fn getFont(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONT", .{}); } pub fn setFont(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONT", .{}, arg); } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabImage(self: *Self, index: i32) ?iup.Element { if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg); } pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABIMAGE", .{index}, arg); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 { return interop.getStrAttribute(self, "TABTITLE", .{index}); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABTITLE", .{index}, arg); } pub fn setDropMotionCallback(self: *Self, callback: ?OnDropMotionFn) void { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self, callback); } pub fn setDragEndCallback(self: *Self, callback: ?OnDragEndFn) void { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self, callback); } pub fn setDragBeginCallback(self: *Self, callback: ?OnDragBeginFn) void { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self, callback); } /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub fn setActionCallback(self: *Self, callback: ?OnActionFn) void { const Handler = CallbackHandler(Self, OnActionFn, "ACTION"); Handler.setCallback(self, callback); } /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub fn setMotionCallback(self: *Self, callback: ?OnMotionFn) void { const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB"); Handler.setCallback(self, callback); } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self, callback); } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self, callback); } pub fn setDropDataCallback(self: *Self, callback: ?OnDropDataFn) void { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self, callback); } pub fn setDragDataCallback(self: *Self, callback: ?OnDragDataFn) void { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self, callback); } pub fn setDragDataSizeCallback(self: *Self, callback: ?OnDragDataSizeFn) void { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self, callback); } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: *Self, callback: ?OnDropFilesFn) void { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self, callback); } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self, callback); } /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub fn setButtonCallback(self: *Self, callback: ?OnButtonFn) void { const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB"); Handler.setCallback(self, callback); } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self, callback); } }; test "Link FgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Link HandleName" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setHandleName("Hello").unwrap()); defer item.deinit(); var ret = item.getHandleName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link TipBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Link WordWrap" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setWordWrap(true).unwrap()); defer item.deinit(); var ret = item.getWordWrap(); try std.testing.expect(ret == true); } test "Link TipIcon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getTipIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link MaxSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setMaxSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMaxSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link Position" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setPosition(9, 10).unwrap()); defer item.deinit(); var ret = item.getPosition(); try std.testing.expect(ret.x == 9 and ret.y == 10); } test "Link DropFilesTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDropFilesTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropFilesTarget(); try std.testing.expect(ret == true); } test "Link Tip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link CanFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setCanFocus(true).unwrap()); defer item.deinit(); var ret = item.getCanFocus(); try std.testing.expect(ret == true); } test "Link DragSourceMove" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDragSourceMove(true).unwrap()); defer item.deinit(); var ret = item.getDragSourceMove(); try std.testing.expect(ret == true); } test "Link Visible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setVisible(true).unwrap()); defer item.deinit(); var ret = item.getVisible(); try std.testing.expect(ret == true); } test "Link Separator" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setSeparator("Hello").unwrap()); defer item.deinit(); var ret = item.getSeparator(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link Url" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setUrl("Hello").unwrap()); defer item.deinit(); var ret = item.getUrl(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link DragDrop" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDragDrop(true).unwrap()); defer item.deinit(); var ret = item.getDragDrop(); try std.testing.expect(ret == true); } test "Link Theme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link Expand" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setExpand(.Yes).unwrap()); defer item.deinit(); var ret = item.getExpand(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Link Size" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link Padding" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setPadding(9, 10).unwrap()); defer item.deinit(); var ret = item.getPadding(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link TipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link FontSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFontSize(42).unwrap()); defer item.deinit(); var ret = item.getFontSize(); try std.testing.expect(ret == 42); } test "Link DropTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDropTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDropTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link UserSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setUserSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getUserSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link TipDelay" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipDelay(42).unwrap()); defer item.deinit(); var ret = item.getTipDelay(); try std.testing.expect(ret == 42); } test "Link Title" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTitle("Hello").unwrap()); defer item.deinit(); var ret = item.getTitle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link PropagateFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setPropagateFocus(true).unwrap()); defer item.deinit(); var ret = item.getPropagateFocus(); try std.testing.expect(ret == true); } test "Link BgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Link DropTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDropTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropTarget(); try std.testing.expect(ret == true); } test "Link DragSource" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDragSource(true).unwrap()); defer item.deinit(); var ret = item.getDragSource(); try std.testing.expect(ret == true); } test "Link Markup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setMarkup(true).unwrap()); defer item.deinit(); var ret = item.getMarkup(); try std.testing.expect(ret == true); } test "Link Floating" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFloating(.Yes).unwrap()); defer item.deinit(); var ret = item.getFloating(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Link NormalizerGroup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setNormalizerGroup("Hello").unwrap()); defer item.deinit(); var ret = item.getNormalizerGroup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link RasterSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setRasterSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getRasterSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link TipFgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Link FontFace" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFontFace("Hello").unwrap()); defer item.deinit(); var ret = item.getFontFace(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link Name" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setName("Hello").unwrap()); defer item.deinit(); var ret = item.getName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link Ellipsis" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setEllipsis(true).unwrap()); defer item.deinit(); var ret = item.getEllipsis(); try std.testing.expect(ret == true); } test "Link CPadding" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setCPadding(9, 10).unwrap()); defer item.deinit(); var ret = item.getCPadding(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link Active" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setActive(true).unwrap()); defer item.deinit(); var ret = item.getActive(); try std.testing.expect(ret == true); } test "Link TipVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setTipVisible(true).unwrap()); defer item.deinit(); var ret = item.getTipVisible(); try std.testing.expect(ret == true); } test "Link ExpandWeight" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setExpandWeight(3.14).unwrap()); defer item.deinit(); var ret = item.getExpandWeight(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Link MinSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setMinSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMinSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Link NTheme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setNTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getNTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link DragTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setDragTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDragTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link FontStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFontStyle("Hello").unwrap()); defer item.deinit(); var ret = item.getFontStyle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Link Font" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Link.init().setFont("Hello").unwrap()); defer item.deinit(); var ret = item.getFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); }
src/elements/link.zig
const std = @import("std"); const print = std.debug.print; const warn = std.log.warn; const mem = std.mem; const Args = @This(); const Slot = struct { addr: u8, mod_name: ?[]const u8 = null, mod_path: ?[]const u8 = null, }; help: bool = false, slots: [2]Slot = [_]Slot{ .{ .addr = 0x08 }, .{ .addr = 0x0C } }, file: ?[]const u8 = null, // path to .kcc or .tap file pub fn parse(a: std.mem.Allocator) !Args { var res = Args{}; var arg_iter = std.process.args(); _ = arg_iter.skip(); while (arg_iter.next(a)) |error_or_arg| { const arg = error_or_arg catch |err| { warn("Error parsing arguments: {s}", .{ err }); return err; }; if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "-help") or mem.eql(u8, arg, "--help")) { printHelp(); res.help = true; } else if (mem.eql(u8, arg, "-slot8")) { res.slots[0].mod_name = try arg_iter.next(a) orelse { warn("Expected module name after '-slot8'\n", .{}); return error.InvalidArgs; }; if (!validateModuleName(res.slots[0].mod_name.?)) { warn("Didn't recognize module name: {s}\n", .{ res.slots[0].mod_name }); return error.InvalidArgs; } if (isRomModule(res.slots[0].mod_name.?)) { res.slots[0].mod_path = try arg_iter.next(a) orelse { warn("Expected module file after '-slot8 {s}'\n", .{ res.slots[0].mod_name }); return error.InvalidArgs; }; } } else if (mem.eql(u8, arg, "-slotc")) { res.slots[1].mod_name = try arg_iter.next(a) orelse { warn("Expected module name after '-slotC'\n", .{}); return error.InvalidArgs; }; if (!validateModuleName(res.slots[1].mod_name.?)) { warn("Didn't recognize module name: {s}\n", .{ res.slots[1].mod_name }); return error.InvalidArgs; } if (isRomModule(res.slots[1].mod_name.?)) { res.slots[1].mod_path = try arg_iter.next(a) orelse { warn("Expected module file after '-slotc {s}'\n", .{ res.slots[1].mod_name }); return error.InvalidArgs; }; } } else if (mem.eql(u8, arg, "-file")) { res.file = try arg_iter.next(a) orelse { warn("Expected path to .kcc or .tap file after '-load'\n", .{}); return error.InvalidArgs; }; } else { warn("Unknown argument: {s} (run with '-help' to show valid args)\n", .{ arg }); return error.InvalidArgs; } } return res; } fn printHelp() void { print(\\ \\Command line args: \\ -slot8 [module_name] [rom file]: insert a module into slot 8 \\ -slotc [module_name] [rom file]: insert a module into slot C \\ -file [path to file]: path to .kcc or .tap file \\ \\Valid module names: \\ m006: BASIC ROM for KC85/2 \\ m011: 64 KByte RAM module \\ m012: TEXOR text editor ROM module \\ m022: 16 KByte RAM module \\ m026: FORTH ROM module (needs 'data/forth.853') \\ m027: asm development module (needs 'data/develop.853') \\ \\ , .{}); } fn validateModuleName(name: []const u8) bool { const valid_names = [_][]const u8{ "m006", "m011", "m012", "m022", "m026", "m027" }; for (valid_names) |valid_name| { if (mem.eql(u8, valid_name, name)) { return true; } } else { return false; } } fn isRomModule(name: []const u8) bool { return !(mem.eql(u8, name, "m011") or mem.eql(u8, name, "m022")); }
src/host/Args.zig
const std = @import("std"); const p2z = @import("pcre2zig"); // Value NaN box. pub const Value = u64; // Bit masks // Quite NaN bits const mask_qnan: u64 = 0b0_1111111111111_00_0000000000000000_00000000000000000000000000000000; const mask_sign: u64 = 0b1_0000000000000_00_0000000000000000_00000000000000000000000000000000; // nil, false, and true const mask_nil: u64 = 0b0_0000000000000_00_0000000000000000_00000000000000000000000000000001; const mask_false: u64 = 0b0_0000000000000_00_0000000000000000_00000000000000000000000000000010; const mask_true: u64 = 0b0_0000000000000_00_0000000000000000_00000000000000000000000000000011; // Numbers const mask_uint: u64 = 0b0_0000000000000_01_0000000000000000_00000000000000000000000000000000; const mask_int: u64 = 0b0_0000000000000_10_0000000000000000_00000000000000000000000000000000; // Short Strings (len < 7; max 6 bytes; 48 bits) const mask_str: u64 = 0b0_0000000000000_11_0000000000000000_00000000000000000000000000000000; // Nil pub const val_nil = mask_qnan | mask_nil; // Booleans pub const val_false = mask_qnan | mask_false; pub const val_true = mask_qnan | mask_true; pub fn boolToValue(b: bool) Value { return if (b) val_true else val_false; } pub fn asBool(v: Value) ?bool { return if (isBool(v)) v == val_true else null; } pub fn isBool(v: Value) bool { return val_true == v or val_false == v; } // Floats pub fn floatToValue(f: f64) Value { return @bitCast(Value, f); } pub fn asFloat(v: Value) ?f64 { return if (isFloat(v)) @bitCast(f64, v) else null; } pub fn isFloat(v: Value) bool { return (v & mask_qnan) != mask_qnan; } // Uints pub fn uintToValue(u: u32) Value { return @bitCast(Value, (mask_uint | mask_qnan | u)); } pub fn asUint(v: Value) ?u32 { return if (isUint(v)) @intCast(u32, v & ~(mask_uint | mask_qnan)) else null; } pub fn isUint(v: Value) bool { return (v & (mask_uint | mask_qnan) == (mask_uint | mask_qnan)) and (v & mask_str != mask_str); } // Ints pub fn intToValue(i: i32) Value { return @bitCast(Value, (mask_int | mask_qnan | @bitCast(u32, i))); } pub fn asInt(v: Value) ?i32 { return if (isInt(v)) @bitCast(i32, @truncate(u32, v & ~(mask_int | mask_qnan))) else null; } pub fn isInt(v: Value) bool { return (v & (mask_int | mask_qnan) == (mask_int | mask_qnan)) and (v & mask_str != mask_str); } // Short Strings pub fn strToValue(str: []const u8) Value { std.debug.assert(str.len < 7); var buf = [_]u8{0} ** 8; std.mem.copy(u8, &buf, str); const str_u64 = @bitCast(u64, buf); return mask_str | mask_qnan | str_u64; } // There's no `asStr` because it would require allocation in a function context. // It's more efficient to just do the following: // const str_bits = unboxStr(v).?; // isStr(v) == true // const str = std.mem.asBytes(&str_bits); pub fn unboxStr(v: Value) ?u64 { return if (isStr(v)) v & ~(mask_str | mask_qnan) else null; } pub fn isStr(v: Value) bool { return v & (mask_str | mask_qnan) == (mask_str | mask_qnan); } pub fn isAnyStr(v: Value) bool { if (unboxStr(v)) |_| { return true; } else if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*const Object, addr); return obj_ptr.* == .string; } else { return false; } } // Object pointers pub fn addrToValue(addr: usize) Value { return @bitCast(Value, (mask_sign | mask_qnan | addr)); } pub fn asAddr(v: Value) ?usize { return if (isAddr(v)) @bitCast(usize, v & ~(mask_sign | mask_qnan)) else null; } pub fn isAddr(v: Value) bool { return v & (mask_sign | mask_qnan) == (mask_sign | mask_qnan); } // Object convenience functions. pub fn asFunc(v: Value) ?*Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*Object, addr); if (obj_ptr.* == .func) return obj_ptr; } return null; } pub fn asList(v: Value) ?*Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*Object, addr); if (obj_ptr.* == .list) return obj_ptr; } return null; } pub fn asMap(v: Value) ?*Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*Object, addr); if (obj_ptr.* == .map) return obj_ptr; } return null; } pub fn asMatcher(v: Value) ?*Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*Object, addr); if (obj_ptr.* == .matcher) return obj_ptr; } return null; } pub fn asRange(v: Value) ?*const Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*const Object, addr); if (obj_ptr.* == .range) return obj_ptr; } return null; } pub fn asString(v: Value) ?*const Object { if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*const Object, addr); if (obj_ptr.* == .string) return obj_ptr; } return null; } // Better error messages. pub fn typeOf(v: Value) []const u8 { if (asAddr(v)) |obj_addr| { const obj_ptr = @intToPtr(*const Object, obj_addr); return @tagName(obj_ptr.*); } if (isBool(v)) return "bool"; if (isInt(v)) return "int"; if (isFloat(v)) return "float"; if (isAnyStr(v)) return "string"; if (isUint(v)) return "uint"; return "nil"; } // Value equality fn eqlInner(a: Value, b: Value) bool { if (isAddr(a) and isAddr(b)) return true; if (isFloat(a) and isFloat(b)) return true; if (isInt(a) and isInt(b)) return true; if (isUint(a) and isUint(b)) return true; if (isStr(a) and isStr(b)) return true; return false; } pub fn eql(a: Value, b: Value) bool { // If the bits are equal, they're equal. if (a == b) return true; // Check inner type equality. if (!eqlInner(a, b)) return false; if (asAddr(a)) |obj_addr_a| { // Deep object equality. const obj_ptr_a = @intToPtr(*const Object, obj_addr_a); const obj_ptr_b = @intToPtr(*const Object, asAddr(b).?); return obj_ptr_a.eqlObject(obj_ptr_b.*); } return false; } // Conversions pub fn toFloat(v: Value) ?f64 { if (asFloat(v)) |f| return f; if (asInt(v)) |i| return @intToFloat(f64, i); if (asUint(v)) |u| return @intToFloat(f64, u); if (unboxStr(v)) |u| return if (std.fmt.parseFloat(f64, std.mem.sliceTo(std.mem.asBytes(&u), 0))) |f| f else |_| null; if (asAddr(v)) |addr| { const obj_ptr = @intToPtr(*const Object, addr); if (obj_ptr.* == .string) return if (std.fmt.parseFloat(f64, obj_ptr.string)) |f| f else |_| null; } return null; } fn isFloatStr(str: []const u8) bool { return std.mem.containsAtLeast(u8, str, 1, ".") or std.mem.containsAtLeast(u8, str, 1, "e+") or std.mem.containsAtLeast(u8, str, 1, "e-") or std.mem.containsAtLeast(u8, str, 1, "E+") or std.mem.containsAtLeast(u8, str, 1, "E-") or std.mem.containsAtLeast(u8, str, 1, "p"); } fn strToNum(v: Value, comptime default: comptime_int) Value { std.debug.assert(isAnyStr(v)); var str = if (unboxStr(v)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else asString(v).?.string; if (isFloatStr(str)) { return if (std.fmt.parseFloat(f64, str)) |f| floatToValue(f) else |_| default; } else if ('-' == str[0] or '+' == str[0]) { return if (std.fmt.parseInt(i32, str, 0)) |i| intToValue(i) else |_| default; } else { return if (std.fmt.parseInt(u32, str, 0)) |u| uintToValue(u) else |_| default; } } // Operations // Addition fn addFloat(a: Value, b: Value) Value { if (asFloat(b)) |fb| return floatToValue(asFloat(a).? + fb); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? + fb); } fn addInt(a: Value, b: Value) Value { if (asInt(b)) |ib| return intToValue(asInt(a).? + ib); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? + fb); } fn addUint(a: Value, b: Value) Value { if (asUint(b)) |ub| return uintToValue(asUint(a).? + ub); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? + fb); } pub fn add(a: Value, b: Value) anyerror!Value { if (isFloat(a)) return addFloat(a, b); if (isInt(a)) return addInt(a, b); if (isUint(a)) return addUint(a, b); if (isAnyStr(a)) return add(strToNum(a, 0), b); return error.InvalidAdd; } // Subtraction fn subFloat(a: Value, b: Value) Value { if (asFloat(b)) |fb| return floatToValue(asFloat(a).? - fb); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? - fb); } fn subInt(a: Value, b: Value) Value { if (asInt(b)) |ib| return intToValue(asInt(a).? - ib); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? - fb); } fn subUint(a: Value, b: Value) Value { if (asUint(b)) |ub| return uintToValue(asUint(a).? - ub); const fb: f64 = toFloat(b) orelse 0; return floatToValue(asFloat(a).? - fb); } pub fn sub(a: Value, b: Value) anyerror!Value { if (isFloat(a)) return subFloat(a, b); if (isInt(a)) return subInt(a, b); if (isUint(a)) return subUint(a, b); if (isAnyStr(a)) return sub(strToNum(a, 0), b); return error.InvalidSubtract; } // Multiplication fn mulFloat(a: Value, b: Value) Value { if (asFloat(b)) |fb| return floatToValue(asFloat(a).? * fb); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? * fb); } fn mulInt(a: Value, b: Value) Value { if (asInt(b)) |ib| return intToValue(asInt(a).? * ib); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? * fb); } fn mulUint(a: Value, b: Value) Value { if (asUint(b)) |ub| return uintToValue(asUint(a).? * ub); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? * fb); } pub fn mul(a: Value, b: Value) anyerror!Value { if (isFloat(a)) return mulFloat(a, b); if (isInt(a)) return mulInt(a, b); if (isUint(a)) return mulUint(a, b); if (isAnyStr(a)) return mul(strToNum(a, 1), b); return error.InvalidMultiply; } // Division fn divFloat(a: Value, b: Value) Value { if (asFloat(b)) |fb| return floatToValue(asFloat(a).? / fb); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? / fb); } fn divInt(a: Value, b: Value) Value { if (asInt(b)) |ib| return intToValue(@divFloor(asInt(a).?, ib)); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? / fb); } fn divUint(a: Value, b: Value) Value { if (asUint(b)) |ub| return uintToValue(@divFloor(asUint(a).?, ub)); const fb: f64 = toFloat(b) orelse 1; return floatToValue(asFloat(a).? / fb); } pub fn div(a: Value, b: Value) anyerror!Value { if (isFloat(a)) return divFloat(a, b); if (isInt(a)) return divInt(a, b); if (isUint(a)) return divUint(a, b); if (isAnyStr(a)) return div(strToNum(a, 1), b); return error.InvalidDivide; } // Modulo fn modFloat(a: Value, b: Value) Value { if (asFloat(b)) |fb| return floatToValue(@rem(asFloat(a).?, fb)); const fb: f64 = toFloat(b) orelse 1; return floatToValue(@rem(asFloat(a).?, fb)); } fn modInt(a: Value, b: Value) Value { if (asInt(b)) |ib| return intToValue(@rem(asInt(a).?, ib)); const fb: f64 = toFloat(b) orelse 1; return floatToValue(@rem(asFloat(a).?, fb)); } fn modUint(a: Value, b: Value) Value { if (asUint(b)) |ub| return uintToValue(@rem(asUint(a).?, ub)); const fb: f64 = toFloat(b) orelse 1; return floatToValue(@rem(asFloat(a).?, fb)); } pub fn mod(a: Value, b: Value) anyerror!Value { if (isFloat(a)) return modFloat(a, b); if (isInt(a)) return modInt(a, b); if (isUint(a)) return modUint(a, b); if (isAnyStr(a)) return mod(strToNum(a, 1), b); return error.InvalidModulo; } // Comparison fn cmpFloat(a: Value, b: Value) std.math.Order { if (asFloat(b)) |fb| return std.math.order(asFloat(a).?, fb); const fb: f64 = toFloat(b) orelse 0; return std.math.order(asFloat(a).?, fb); } fn cmpInt(a: Value, b: Value) std.math.Order { if (asInt(b)) |ib| return std.math.order(asInt(a).?, ib); const fb: f64 = toFloat(b) orelse 0; return std.math.order(asFloat(a).?, fb); } fn cmpUint(a: Value, b: Value) std.math.Order { if (asUint(b)) |ub| return std.math.order(asUint(a).?, ub); const fb: f64 = toFloat(b) orelse 0; return std.math.order(asFloat(a).?, fb); } fn cmpStr(a: Value, b: Value) anyerror!std.math.Order { if (isAnyStr(b)) { const a_str = if (unboxStr(a)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else asString(a).?.string; const b_str = if (unboxStr(b)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else asString(b).?.string; return std.mem.order(u8, a_str, b_str); } return cmp(strToNum(a, 0), b); } pub fn cmp(a: Value, b: Value) anyerror!std.math.Order { if (isFloat(a)) return cmpFloat(a, b); if (isInt(a)) return cmpInt(a, b); if (isUint(a)) return cmpUint(a, b); if (isAnyStr(a)) return cmpStr(a, b); return error.InvalidCompare; } pub fn asc(_: void, a: Value, b: Value) bool { return cmp(a, b) catch unreachable == .lt; } pub fn desc(_: void, a: Value, b: Value) bool { return cmp(a, b) catch unreachable == .gt; } // Value copy for global scope. pub fn copy(v: Value, allocator: std.mem.Allocator) anyerror!Value { if (val_nil == v) return v; if (isBool(v)) return v; if (isFloat(v)) return v; if (isInt(v)) return v; if (isUint(v)) return v; if (isStr(v)) return v; if (isAddr(v)) return copyObject(v, allocator); unreachable; } fn copyObject(v: Value, allocator: std.mem.Allocator) anyerror!Value { const obj_addr = asAddr(v).?; const obj_ptr = @intToPtr(*const Object, obj_addr); return switch (obj_ptr.*) { .func => |f| copyFunc(allocator, f), .list => |l| copyList(allocator, l), .map => |m| copyMap(allocator, m), .matcher => |m| copyMatcher(allocator, m), .range => |r| copyRange(allocator, r), .string => |s| copyString(allocator, s), }; } fn copyFunc(allocator: std.mem.Allocator, func: Function) anyerror!Value { var params: ?[]u16 = null; if (func.params) |fparams| { var params_copy = try allocator.alloc(u16, fparams.len); for (fparams) |param, i| params_copy[i] = param; params = params_copy; } var bytecode: ?[]const u8 = null; if (func.bytecode) |bc| bytecode = try allocator.dupe(u8, bc); const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .func = .{ .str = try allocator.dupe(u8, func.str), .name = if (func.name) |name| try allocator.dupe(u8, name) else null, .params = params, .bytecode = bytecode, } }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } fn copyList(allocator: std.mem.Allocator, list: std.ArrayList(Value)) anyerror!Value { var list_copy = try std.ArrayList(Value).initCapacity(allocator, list.items.len); for (list.items) |item| list_copy.appendAssumeCapacity(try copy(item, allocator)); const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .list = list_copy }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } fn copyMap(allocator: std.mem.Allocator, map: std.StringHashMap(Value)) anyerror!Value { var map_copy = std.StringHashMap(Value).init(allocator); try map_copy.ensureTotalCapacity(map.count()); var iter = map.iterator(); while (iter.next()) |entry| { const key_copy = try allocator.dupe(u8, entry.key_ptr.*); map_copy.putAssumeCapacity(key_copy, try copy(entry.value_ptr.*, allocator)); } const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .map = map_copy }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } fn copyMatcher(allocator: std.mem.Allocator, m: p2z.MatchIterator) anyerror!Value { const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .matcher = .{ .code = m.code, .data = m.data, .ovector = null, .subject = try allocator.dupe(u8, m.subject), } }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } fn copyRange(allocator: std.mem.Allocator, r: [2]u32) anyerror!Value { const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .range = [2]u32{ r[0], r[1] } }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } fn copyString(allocator: std.mem.Allocator, str: []const u8) anyerror!Value { const str_copy = try allocator.dupe(u8, str); const obj_ptr = try allocator.create(Object); obj_ptr.* = .{ .string = str_copy }; const obj_addr = @ptrToInt(obj_ptr); return addrToValue(obj_addr); } // Format interface pub fn print(v: Value, writer: anytype) !void { if (asBool(v)) |b| _ = try writer.print("{}", .{b}); if (asFloat(v)) |f| _ = try writer.print("{d}", .{f}); if (asInt(v)) |i| _ = try writer.print("{}", .{i}); if (asUint(v)) |u| _ = try writer.print("{}", .{u}); if (unboxStr(v)) |u| _ = try writer.writeAll(std.mem.sliceTo(std.mem.asBytes(&u), 0)); if (isAddr(v)) try printObject(v, writer); } fn printObject(v: Value, writer: anytype) !void { const obj_addr = asAddr(v).?; const obj_ptr = @intToPtr(*const Object, obj_addr); switch (obj_ptr.*) { .func => try writer.writeAll("fn()"), .list => |l| try printList(l, writer), .map => |m| try printMap(m, writer), .matcher => |m| _ = try writer.print("MatchIterator on \"{s}\"", .{m.subject}), .range => |r| _ = try writer.print("{} ..< {}", .{ r[0], r[1] }), .string => |s| try writer.writeAll(s), } } fn printList(list: std.ArrayList(Value), writer: anytype) !void { try writer.writeByte('['); for (list.items) |item, i| { if (i != 0) try writer.writeAll(", "); _ = try writer.print("{}", .{item}); } try writer.writeByte(']'); } fn printMap(map: std.StringHashMap(Value), writer: anytype) !void { try writer.writeByte('['); var iter = map.iterator(); var i: usize = 0; while (iter.next()) |entry| : (i += 1) { if (i != 0) try writer.writeAll(", "); _ = try writer.print("{s}: {}", .{ entry.key_ptr.*, entry.value_ptr.* }); } try writer.writeByte(']'); } // Values accessed by reference. pub const Object = union(enum) { func: Function, list: std.ArrayList(Value), map: std.StringHashMap(Value), matcher: p2z.MatchIterator, range: [2]u32, string: []const u8, fn eqlTag(a: Object, b: Object) bool { return switch (a) { .func => b == .func, .list => b == .list, .map => b == .map, .matcher => b == .matcher, .range => b == .range, .string => b == .string, }; } pub fn eqlObject(a: Object, b: Object) bool { if (!eqlTag(a, b)) return false; return switch (a) { .func => false, .list => eqlList(a, b), .map => eqlMap(a, b), .matcher => eqlMatcher(a, b), .range => eqlRange(a, b), .string => eqlStr(a, b), }; } fn eqlList(a: Object, b: Object) bool { if (a.list.items.len != b.list.items.len) return false; return for (a.list.items) |item_a, i| { if (!eql(item_a, b.list.items[i])) break false; } else true; } fn eqlMap(a: Object, b: Object) bool { if (a.map.count() != b.map.count()) return false; var iter = a.map.iterator(); return while (iter.next()) |entry_a| { if (b.map.get(entry_a.key_ptr.*)) |vb| { if (!eql(entry_a.value_ptr.*, vb)) break false; } else break false; } else true; } fn eqlMatcher(a: Object, b: Object) bool { return a.matcher.data.ptr == b.matcher.data.ptr; } fn eqlRange(a: Object, b: Object) bool { return a.range[0] == b.range[0] and a.range[1] == b.range[1]; } fn eqlStr(a: Object, b: Object) bool { return std.mem.eql(u8, a.string, b.string); } }; // Runtime function value. pub const Function = struct { str: []const u8, memo: bool = false, name: ?[]const u8, params: ?[]const u16, bytecode: ?[]const u8, };
src/value.zig
const std = @import("std"); const stdx = @import("stdx"); const ds = stdx.ds; const log = stdx.log.scoped(.tokenizer); const trace = stdx.debug.tracy.trace; const document = stdx.textbuf.document; const Document = document.Document; const LineChunk = document.LineChunk; const LineChunkId = document.LineChunkId; const ast = @import("ast.zig"); const LineTokenBuffer = ast.LineTokenBuffer; const TokenListId = ast.TokenListId; const TokenId = ast.TokenId; const Token = ast.Token; const TokenBuffer = ast.TokenBuffer; const parser = @import("parser.zig"); const DebugInfo = parser.DebugInfo; const ParseConfig = parser.ParseConfig; const Source = parser.Source; const grammar = @import("grammar.zig"); const CharSetRange = grammar.CharSetRange; const TokenDecl = grammar.TokenDecl; const TokenMatchOp = grammar.TokenMatchOp; const TokenTag = grammar.TokenTag; const LiteralTokenTag = grammar.LiteralTokenTag; const NullLiteralTokenTag = grammar.NullLiteralTokenTag; const NullToken = stdx.ds.CompactNull(TokenId); pub const Tokenizer = struct { const Self = @This(); decls: []const TokenDecl, main_decls: []const TokenDecl, ops: []const TokenMatchOp, literal_tag_map: stdx.ds.OwnedKeyStringHashMap(LiteralTokenTag), charset_ranges: []const CharSetRange, str_buf: []const u8, pub fn init(g: *const grammar.Grammar) Self { return .{ .decls = g.token_decls.items, .main_decls = g.token_main_decls.items, .ops = g.token_ops.items, .literal_tag_map = g.literal_tag_map, .charset_ranges = g.charset_range_buf.items, .str_buf = g.str_buf.items, }; } pub fn tokenize(self: *Self, comptime Config: ParseConfig, src: Source(Config), buf: *TokenBuffer(Config)) void { const t = trace(@src()); defer t.end(); const State = if (Config.is_incremental) LineSourceState(false) else StringBufferState; const Context = TokenizeContext(State, false); const TConfig: TokenizeConfig = .{ .Context = Context, .debug = false, }; var ctx: Context = undefined; ctx.state.init(src, buf); defer ctx.state.deinit(); self.tokenizeMain(TConfig, &ctx); } // col_idx is the start of the change. pub fn retokenizeChange(self: *Self, doc: *Document, buf: *LineTokenBuffer, line_idx: u32, col_idx: u32, change_size: i32, debug: anytype) void { const t = trace(@src()); defer t.end(); const Debug = @TypeOf(debug) == *DebugInfo; const Context = TokenizeContext(LineSourceState(true), Debug); const TConfig: TokenizeConfig = .{ .Context = Context, .debug = Debug, }; var ctx: Context = undefined; ctx.state.initAtTokenBeforePosition(doc, buf, line_idx, col_idx, change_size); if (Debug) { ctx.debug = debug; } defer ctx.state.deinit(); // log.warn("starting at: \"{s}\":{}", .{ctx.state.line, ctx.state.next_ch_idx}); // log.warn("stopping at: {}", .{ctx.state.stop_ch_idx}); self.tokenizeMain(TConfig, &ctx); } fn tokenizeMain(self: *Self, comptime Config: TokenizeConfig, ctx: *Config.Context) void { while (true) { if (ctx.state.nextAtEnd()) { break; } // log.warn("{}", .{ctx.state.next_ch_idx}); if (Config.Context.State == LineSourceState(true)) { if (ctx.state.next_ch_idx == ctx.state.stop_ch_idx) { // Stop early for incremental tokenize. ctx.state.reconcileCurrentTokenList(Config.debug, ctx.debug, ctx.state.stop_token_id); break; } } const start = ctx.state.mark(); inner: { for (self.main_decls) |it| { // Since token decls can have nested ops but returns only one token, // advanceWithOp only advances next_ch_idx. We create the token afterwards. const op = &self.ops[it.op_id]; if (self.advanceWithOp(&ctx.state, op) == MatchAdvance) { if (it.skip) { // Stop matching and advance. break :inner; } // Attempt to replace this rule match with a different rule. if (it.replace_with != null and self.replace(Config, ctx, start, ctx.state.mark(), it.replace_with.?)) { break :inner; } const next = ctx.state.mark(); const literal_tag = if (it.is_literal) b: { const str = ctx.state.getString(start, next); break :b self.literal_tag_map.get(str).?; } else NullLiteralTokenTag; switch (Config.Context.State) { StringBufferState => { const tok = Token.init(@intCast(u32, it.tag), literal_tag, start, next); ctx.state.appendToken(Config.debug, ctx.debug, tok); }, LineSourceState(false), LineSourceState(true), => { const end_idx = ctx.state.getTokenEndIdxFromStartLine(start, next); const tok = Token.init(@intCast(u32, it.tag), literal_tag, start.next_ch_idx, end_idx); ctx.state.appendToken(Config.debug, ctx.debug, tok); }, else => unreachable, } break :inner; } else { continue; } } // No token was matched, advance so we can still progress. _ = ctx.state.consumeNext(); } } } // Returns whether it was replaced. fn replace(self: *Self, comptime Config: TokenizeConfig, ctx: *Config.Context, start: Config.Context.State.Mark, end: Config.Context.State.Mark, replace_rule_tag: TokenTag) bool { const replace_rule = self.decls[replace_rule_tag]; if (replace_rule.is_literal) { const str = ctx.state.getString(start, end); // If we are replacing with a literal rule then we can just check if it exists in the literal map. const literal_tag = self.literal_tag_map.map.get(str); if (literal_tag == null) { return false; } switch (Config.Context.State) { StringBufferState => { const tok = Token.init(replace_rule_tag, literal_tag.?, start, end); ctx.state.appendToken(Config.debug, ctx.debug, tok); }, LineSourceState(false), LineSourceState(true) => { const end_idx = ctx.state.getTokenEndIdxFromStartLine(start, end); const tok = Token.init(replace_rule_tag, literal_tag.?, start.next_ch_idx, end_idx); ctx.state.appendToken(Config.debug, ctx.debug, tok); }, else => unreachable, } return true; } stdx.panic("TODO: support replace for non literal rules"); // // Save state first. // const save_next = self.next_ch_idx; // const save_end = self.end_idx; // defer { // self.next_ch_idx = save_next; // self.end_idx = save_end; // } // self.next_ch_idx = start; // self.end_idx = end; // const op = &self.ops[replace_rule.op_id]; // if (!self.advanceWithOp(op)) { // return false; // } // // Must match the entire text to replace it. // if (!self.nextAtEnd()) { // return false; // } // const tok = Token.init(replace_rule_tag, NullLiteralTokenTag, self.src[start..end], start, end); // last_token_id.* = self.tokens.insertAfter(last_token_id.*, tok) catch unreachable; // return true; } // Advances the current tokenizer position and returns whether the op matched. fn advanceWithOp(self: *Self, state: anytype, op: *const TokenMatchOp) MatchOpResult { switch (op.*) { .MatchRule => |inner| { const decl = self.decls[inner.tag]; const _op = &self.ops[decl.op_id]; return self.advanceWithOp(state, _op); }, .MatchCharSet => |inner| { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); var i: u32 = inner.ranges.start; while (i < inner.ranges.end) : (i += 1) { const range = self.charset_ranges[i]; if (ch >= range.start and ch <= range.end_incl) { _ = state.consumeNext(); return MatchAdvance; } } if (stdx.string.indexOf(inner.resolved_charset, ch) != null) { _ = state.consumeNext(); return MatchAdvance; } else { return NoMatch; } }, .MatchNotCharSet => |inner| { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); var i: u32 = inner.ranges.start; while (i < inner.ranges.end) : (i += 1) { const range = self.charset_ranges[i]; if (ch >= range.start and ch <= range.end_incl) { return NoMatch; } } if (stdx.string.indexOf(inner.resolved_charset, ch) == null) { _ = state.consumeNext(); return MatchAdvance; } else { return NoMatch; } }, .MatchText => |inner| { const mark = state.mark(); var i = inner.str.start; while (i < inner.str.end) : (i += 1) { const exp_ch = self.str_buf[i]; if (state.nextAtEnd()) { state.gotoMark(mark); return NoMatch; } var ch = state.consumeNext(); if (ch != exp_ch) { state.gotoMark(mark); return NoMatch; } } return MatchAdvance; }, .MatchUntilChar => |m| { const mark = state.mark(); while (true) { if (state.nextAtEnd()) { state.gotoMark(mark); return NoMatch; } var ch = state.consumeNext(); if (ch == m.ch) { return MatchAdvance; } } }, .MatchNotChar => |m| { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); if (ch == m.ch) { return NoMatch; } else { _ = state.consumeNext(); return MatchAdvance; } }, .MatchExactChar => |inner| { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); if (ch != inner.ch) { return NoMatch; } else { _ = state.consumeNext(); return MatchAdvance; } }, .MatchZeroOrMore => |inner| { // log.warn("MatchZeroOrMore {}", .{state.next_ch_idx}); const inner_op = self.ops[inner.op_id]; var res = MatchNoAdvance; while (true) { const _res = self.advanceWithOp(state, &inner_op); if (_res == MatchAdvance) { // Must have match and advanced to continue or we will enter infinite loop. res = MatchAdvance; continue; } else { return res; } } }, .MatchOneOrMore => |m| { const inner_op = self.ops[m.op_id]; if (self.advanceWithOp(state, &inner_op) != MatchAdvance) { return NoMatch; } while (true) { if (self.advanceWithOp(state, &inner_op) == MatchAdvance) { continue; } else { return MatchAdvance; } } }, .MatchDigit => |m| { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); if (!std.ascii.isDigit(ch)) { return NoMatch; } _ = state.consumeNext(); if (m == .One) { return MatchAdvance; } else if (m == .OneOrMore) { while (!state.nextAtEnd()) { ch = state.peekNext(); if (!std.ascii.isDigit(ch)) { break; } _ = state.consumeNext(); } return MatchAdvance; } }, .MatchAsciiLetter => { if (state.nextAtEnd()) { return NoMatch; } var ch = state.peekNext(); if (!std.ascii.isAlpha(ch)) { return NoMatch; } else { _ = state.consumeNext(); return MatchAdvance; } }, .MatchChoice => |inner| { var i = inner.ops.start; while (i < inner.ops.end) : (i += 1) { const inner_op = &self.ops[i]; const res = self.advanceWithOp(state, inner_op); if (res != NoMatch) { return res; } } return NoMatch; }, .MatchOptional => |m| { const inner_op = &self.ops[m.op_id]; const res = self.advanceWithOp(state, inner_op); if (res != NoMatch) { return res; } else { return MatchNoAdvance; } }, .MatchNegLookahead => |m| { // Returns no match if inner op matches and resets position. // Returns match if inner op doesn't match but does not advance the position. const inner_op = &self.ops[m.op_id]; const mark = state.mark(); const res = self.advanceWithOp(state, inner_op); switch (res) { NoMatch => return MatchNoAdvance, MatchAdvance => { state.gotoMark(mark); return NoMatch; }, MatchNoAdvance => return NoMatch, else => unreachable, } }, .MatchPosLookahead => |m| { // Returns match if inner op matches but does not advance the position. // Returns no match if inner op doesn't match. const inner_op = &self.ops[m.op_id]; const mark = state.mark(); const res = self.advanceWithOp(state, inner_op); switch (res) { NoMatch => return NoMatch, MatchAdvance => { state.gotoMark(mark); return MatchNoAdvance; }, MatchNoAdvance => return MatchNoAdvance, else => unreachable, } }, .MatchSeq => |inner| { var i = inner.ops.start; var res = NoMatch; const mark = state.mark(); while (i < inner.ops.end) : (i += 1) { const inner_op = &self.ops[i]; // log.warn("op {}", .{inner_op}); const _res = self.advanceWithOp(state, inner_op); if (_res == NoMatch) { state.gotoMark(mark); return NoMatch; } else { res |= _res; } } return res; }, .MatchRegexChar, .MatchRangeChar, => stdx.panicFmt("unsupported rule: {s}", .{@tagName(op.*)}), } unreachable; } }; const MatchOpResult = u2; const NoMatch: MatchOpResult = 0b0_0; // Matched but didn't advance the pointer. (eg. Optional, ZeroOrMore matchers) const MatchNoAdvance: MatchOpResult = 0b1_0; // Matched and advanced the pointer. const MatchAdvance: MatchOpResult = 0b1_1; const StringBufferState = struct { const Self = @This(); const Mark = u32; const Type = StateType{ .StringBuffer = {}, }; next_ch_idx: u32, end_idx: u32, src: []const u8, buf: *std.ArrayList(Token), fn init(self: *Self, src: []const u8, buf: *std.ArrayList(Token)) void { self.* = .{ .src = src, .end_idx = @intCast(u32, src.len), .next_ch_idx = 0, .buf = buf, }; } fn deinit(self: *Self) void { _ = self; } inline fn appendToken(self: *Self, comptime Debug: bool, debug: anytype, token: Token) void { _ = Debug; _ = debug; self.buf.append(token) catch unreachable; } inline fn mark(self: *const Self) u32 { return self.next_ch_idx; } inline fn gotoMark(self: *Self, _mark: u32) void { self.next_ch_idx = _mark; } inline fn nextAtEnd(self: *const Self) bool { return self.next_ch_idx >= self.end_idx; } inline fn peekNext(self: *Self) u8 { return self.src[self.next_ch_idx]; } inline fn getString(self: *Self, start: u32, end: u32) []const u8 { return self.src[start..end]; } inline fn consumeNext(self: *Self) u8 { const ch = self.src[self.next_ch_idx]; self.next_ch_idx += 1; return ch; } }; // This is fast at iterating a document line tree since it will track the current leaf and continue to the next. // This also means that it won't pick up inserts/deletes from the document during parsing. // TODO: move Incremental into inner function comptime. fn LineSourceState(comptime Incremental: bool) type { return struct { const Self = @This(); const Type = StateType{ .LineSource = .{ .is_incremental = Incremental, } }; const Mark = struct { next_ch_idx: u32, leaf_id: document.NodeId, chunk_line_idx: u32, }; doc: *Document, // Current line data. next_ch_idx: u32, end_ch_idx: u32, leaf_id: document.NodeId, chunk: []document.LineId, chunk_line_idx: u32, line: []const u8, last_leaf_id: document.NodeId, last_chunk_size: u32, cur_token_list_last: TokenId, buf: *LineTokenBuffer, //// For incremental. inc_offset: i32, stop_line_loc: document.LineLocation, stop_ch_idx: u32, stop_token_id: TokenId, // Detached token sublist that needs to be reconciled with updated list once we're done with the current line. cur_detached_token: TokenId, fn init(self: *Self, doc: *Document, buf: *LineTokenBuffer) void { const leaf_id = doc.getFirstLeaf(); const last_leaf_id = doc.getLastLeaf(); const last_leaf = doc.getNode(last_leaf_id); // Ensure doc line map is big enough. buf.lines.resize(doc.lines.size()) catch unreachable; self.* = .{ .doc = doc, .next_ch_idx = 0, .chunk = doc.getLeafLineChunkSlice(leaf_id), .leaf_id = leaf_id, .end_ch_idx = undefined, .chunk_line_idx = 0, .line = undefined, .last_leaf_id = last_leaf_id, .last_chunk_size = last_leaf.Leaf.chunk.size, .buf = buf, .cur_token_list_last = undefined, .stop_line_loc = undefined, .stop_ch_idx = undefined, .stop_token_id = undefined, .cur_detached_token = undefined, .inc_offset = undefined, }; if (self.chunk.len > 0) { self.line = doc.getLineById(self.chunk[self.chunk_line_idx]); self.end_ch_idx = @intCast(u8, self.line.len); } else { self.end_ch_idx = 0; } self.cur_token_list_last = self.buf.temp_head_id; } fn initAtTokenBeforePosition(self: *Self, doc: *Document, buf: *LineTokenBuffer, line_idx: u32, col_idx: u32, change_size: i32) void { const loc = doc.findLineLoc(line_idx); self.* = .{ .doc = doc, .buf = buf, .leaf_id = loc.leaf_id, .chunk_line_idx = loc.chunk_line_idx, .chunk = self.doc.getLeafLineChunkSlice(loc.leaf_id), .next_ch_idx = undefined, .end_ch_idx = undefined, .line = undefined, .last_leaf_id = undefined, .last_chunk_size = undefined, .cur_token_list_last = undefined, .stop_ch_idx = undefined, .stop_line_loc = undefined, .stop_token_id = undefined, .cur_detached_token = undefined, .inc_offset = change_size, }; // Find stop first before the token list is segmented. self.seekStopToFirstTokenFromLine(loc); if (std.meta.eql(self.stop_line_loc, loc) and self.stop_token_id != NullToken) { // For inserts, change end is where the change starts. // For deletes, change end is where the change starts + deleted characters. const change_end_col = if (change_size > 0) col_idx else col_idx + std.math.absCast(change_size); self.seekStopToFirstTokenAtAfterChangeEndCol(change_end_col); } const mb_prev_id = self.seekToFirstTokenBeforePos(col_idx); if (mb_prev_id) |prev_id| { self.cur_token_list_last = prev_id; self.cur_detached_token = self.buf.tokens.detachAfter(prev_id) catch unreachable; } else { self.cur_token_list_last = self.buf.temp_head_id; self.cur_detached_token = NullToken; } } usingnamespace if (Incremental) struct { pub fn reconcileCurrentTokenList(self: *Self, comptime Debug: bool, debug: anytype, reuse_token_id: TokenId) void { // log.warn("reuse: {}", .{reuse_token_id}); // log.warn("detached: {}", .{self.cur_detached_token}); // log.warn("last: {}", .{self.cur_token_list_last}); // Removes tokens from detached end sublist that are not reused. var cur_token_id = self.cur_detached_token; while (cur_token_id != reuse_token_id) { const next = self.buf.tokens.getNodeAssumeExists(cur_token_id).next; self.buf.tokens.removeDetached(cur_token_id); cur_token_id = next; if (Debug) { debug.stats.inc_tokens_removed += 1; } } // Update reusable sublist with pos offset. cur_token_id = reuse_token_id; while (cur_token_id != NullToken) { const cur = self.buf.tokens.getNodePtrAssumeExists(cur_token_id); cur.data.loc.start +%= @bitCast(u32, self.inc_offset); cur.data.loc.end +%= @bitCast(u32, self.inc_offset); cur_token_id = cur.next; } // Reattach resusable end sublist. if (reuse_token_id != NullToken) { self.buf.tokens.setDetachedToEnd(self.cur_token_list_last, reuse_token_id); } } // Assumes stop_token_id already refers to a token on the same line. pub fn seekStopToFirstTokenAtAfterChangeEndCol(self: *Self, col_idx: u32) void { while (true) { const token = self.buf.tokens.get(self.stop_token_id).?; if (token.loc.start >= col_idx) { self.stop_ch_idx = token.loc.start +% @bitCast(u32, self.inc_offset); return; } self.stop_token_id = self.buf.tokens.getNextIdNoCheck(self.stop_token_id); if (self.stop_token_id == NullToken) { const line_id = self.doc.getLineIdByLoc(self.stop_line_loc); const line = self.doc.getLineById(line_id); self.stop_ch_idx = @intCast(u32, line.len) +% @bitCast(u32, self.inc_offset); return; } } } pub fn seekStopToNextToken(self: *Self) void { while (true) { const token = self.buf.tokens.get(self.stop_token_id).?; if (token.loc.start +% @bitCast(u32, self.inc_offset) >= self.next_ch_idx) { self.stop_ch_idx = token.loc.start +% @bitCast(u32, self.inc_offset); return; } self.stop_token_id = self.buf.tokens.getNextIdNoCheck(self.stop_token_id); if (self.stop_token_id == NullToken) { const line_id = self.doc.getLineIdByLoc(self.stop_line_loc); const line = self.doc.getLineById(line_id); self.stop_ch_idx = @intCast(u32, line.len); return; } } } pub fn seekStopToFirstTokenFromLine(self: *Self, loc: document.LineLocation) void { self.stop_line_loc = loc; var chunk = self.doc.getLeafLineChunkSlice(self.stop_line_loc.leaf_id); while (true) { const line_id = chunk[self.stop_line_loc.chunk_line_idx]; if (self.buf.lines.items[line_id]) |list_id| { self.stop_token_id = self.buf.tokens.getListHead(list_id).?; self.stop_ch_idx = self.buf.tokens.getNoCheck(self.stop_token_id).loc.start; return; } if (self.stop_line_loc.leaf_id == self.last_leaf_id and self.stop_line_loc.chunk_line_idx == self.last_chunk_size) { self.stop_token_id = NullToken; self.stop_ch_idx = @intCast(u32, self.doc.getLine(line_id).len); } self.stop_line_loc.chunk_line_idx += 1; if (self.stop_line_loc.chunk_line_idx == chunk.len) { // Advance chunk. self.stop_line_loc.leaf_id = self.doc.getNextLeafNode(self.stop_line_loc.leaf_id).?; self.stop_line_loc.chunk_line_idx = 0; } } } // Assumes line loc is already on the same line as col pos. // Returns the token that precedes the token seeked to. Useful for caller to detach list. pub fn seekToFirstTokenBeforePos(self: *Self, col_idx: u32) ?TokenId { const line_id = self.chunk[self.chunk_line_idx]; if (self.buf.lines.items[line_id]) |list_id| { // Find first token in the line at or precedes col_idx. const head = self.buf.tokens.getListHead(list_id); var prev: ?TokenId = null; var cur_token_id = head.?; var cur_item = self.buf.tokens.getNodeAssumeExists(cur_token_id); if (cur_item.data.loc.start < col_idx) { // First token is before col_idx. while (cur_item.next != NullToken) { const next = self.buf.tokens.getNodeAssumeExists(cur_item.next); if (next.data.loc.start >= col_idx) { // Found starting point. break; } prev = cur_token_id; cur_token_id = cur_item.next; cur_item = next; } self.next_ch_idx = cur_item.data.loc.start; self.line = self.doc.getLineById(line_id); self.end_ch_idx = @intCast(u32, self.line.len); return prev; } } var list_id = self.seekToPrevLineWithTokens(); if (list_id == null) { // Start at first line. if (self.chunk.len > 0) { self.next_ch_idx = 0; self.line = self.doc.getLineById(self.chunk[self.chunk_line_idx]); self.end_ch_idx = @intCast(u32, self.line.len); return null; } else { unreachable; } } else { // Start at last token in the list. stdx.panic("TODO"); } } // Returns list id if found. // Returns null if we reached top. pub fn seekToPrevLineWithTokens(self: *Self) ?TokenListId { const first_leaf = self.doc.getFirstLeaf(); while (true) { if (self.leaf_id == first_leaf and self.chunk_line_idx == 0) { return null; } if (self.chunk_line_idx == 0) { // Step back one chunk. self.leaf_id = self.doc.getPrevLeafNode(self.leaf_id).?; self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id); self.chunk_line_idx = @intCast(u32, self.chunk.len) - 1; } else { self.chunk_line_idx -= 1; } const line_id = self.chunk[self.chunk_line_idx]; if (self.buf.lines.items[line_id]) |list_id| { return list_id; } } } } else struct {}; fn deinit(_: *Self) void { // Nop. } inline fn appendToken(self: *Self, comptime Debug: bool, debug: anytype, token: Token) void { // log.warn("appendToken: {} {s}", .{token.loc, self.doc.getSubstringFromLineLoc(.{.leaf_id = self.leaf_id, .chunk_line_idx = self.chunk_line_idx}, token.loc.start, token.loc.end)}); self.cur_token_list_last = self.buf.tokens.insertAfter(self.cur_token_list_last, token) catch unreachable; if (Debug) { debug.stats.inc_tokens_added += 1; } if (Incremental) { if (self.next_ch_idx > self.stop_ch_idx) { // Token exceeded stop pos, seek to next stop pos. self.seekStopToNextToken(); } } } inline fn mark(self: *const Self) Mark { return .{ .next_ch_idx = self.next_ch_idx, .leaf_id = self.leaf_id, .chunk_line_idx = self.chunk_line_idx, }; } inline fn gotoMark(self: *Self, m: Mark) void { // log.warn("goto mark {}", .{m}); self.next_ch_idx = m.next_ch_idx; self.leaf_id = m.leaf_id; self.chunk_line_idx = m.chunk_line_idx; self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id); self.line = self.doc.getLineById(self.chunk[self.chunk_line_idx]); self.end_ch_idx = @intCast(u8, self.line.len); } inline fn nextAtEnd(self: *const Self) bool { return self.leaf_id == self.last_leaf_id and self.chunk_line_idx == self.last_chunk_size; } inline fn peekNext(self: *Self) u8 { if (self.next_ch_idx == self.line.len) { return '\n'; } else { return self.line[self.next_ch_idx]; } } fn beforeNextLine(self: *Self) void { if (Incremental) { stdx.panic("TODO"); } else { if (self.cur_token_list_last != self.buf.temp_head_id) { // Add accumulated token list and map it from doc line id. const head = self.buf.tokens.getNextIdNoCheck(self.buf.temp_head_id); const list_id = self.buf.tokens.addListWithDetachedHead(head) catch unreachable; const line_id = self.doc.getLineIdByLoc(.{ .leaf_id = self.leaf_id, .chunk_line_idx = self.chunk_line_idx }); self.buf.lines.items[line_id] = list_id; _ = self.buf.tokens.detachAfter(self.buf.temp_head_id) catch unreachable; self.cur_token_list_last = self.buf.temp_head_id; // log.warn("set token list to line {} {} {}", .{line_id, self.leaf_id, self.chunk_line_idx}); } } } fn consumeNext(self: *Self) u8 { if (self.next_ch_idx == self.end_ch_idx) { self.next_ch_idx = 0; if (self.chunk_line_idx == self.chunk.len) { // Advance to the next line chunk. if (self.doc.getNextLeafNode(self.leaf_id)) |next| { stdx.debug.abort(); self.beforeNextLine(); self.leaf_id = next; self.chunk = self.doc.getLeafLineChunkSlice(self.leaf_id); self.chunk_line_idx = 0; if (self.chunk.len > 0) { self.line = self.doc.getLineById(self.chunk[0]); self.end_ch_idx = @intCast(u32, self.line.len); } else { unreachable; } } else { unreachable; } } else { self.beforeNextLine(); self.chunk_line_idx += 1; } return '\n'; } const ch = self.line[self.next_ch_idx]; self.next_ch_idx += 1; return ch; } inline fn getString(self: *Self, start: Mark, end: Mark) []const u8 { return self.doc.getString( start.leaf_id, start.chunk_line_idx, start.next_ch_idx, end.leaf_id, end.chunk_line_idx, end.next_ch_idx, ); } // From given start line, get the end token idx by adding all the missing chars inbetween. fn getTokenEndIdxFromStartLine(self: *Self, start: Mark, end: Mark) u32 { if (start.leaf_id == end.leaf_id and start.chunk_line_idx == end.chunk_line_idx) { return end.next_ch_idx; } else { var res = end.next_ch_idx; // Add up all previous lines. var leaf_id = start.leaf_id; var chunk = self.doc.getLeafLineChunkSlice(leaf_id); var chunk_line_idx = start.chunk_line_idx; while (true) { if (leaf_id == end.leaf_id and chunk_line_idx == end.chunk_line_idx) { break; } const line = self.doc.getLineById(chunk[chunk_line_idx]); res += @intCast(u32, line.len) + 1; chunk_line_idx += 1; if (chunk_line_idx == chunk.len) { // Advance chunk. leaf_id = self.doc.getNextLeafNode(leaf_id).?; chunk = self.doc.getLeafLineChunkSlice(leaf_id); chunk_line_idx = 0; } } return res; } } }; } const StateType = union(enum) { LineSource: struct { is_incremental: bool, }, StringBuffer: void, }; const TokenizeConfig = struct { Context: type, debug: bool, }; fn TokenizeContext(comptime State: type, debug: bool) type { return struct { const State = State; state: State, debug: if (debug) *DebugInfo else void, }; }
parser/tokenizer.zig
const js = @import("js.zig"); const std = @import("std"); const zalgebra = @import("zalgebra"); const Thread = std.Thread; const Allocator = std.mem.Allocator; pub const ShaderError = error{ ShaderCompileError, InvalidContextError }; /// The type used for meshes's elements pub const MeshElementType = c.GLuint; pub const Mesh = struct { // OpenGL related variables vao: c.GLuint = 0, vbo: c.GLuint, ebo: ?c.GLuint, /// how many elements this Mesh has elements: usize, vertices: usize, pub fn create(vertices: []f32, elements: ?[]c.GLuint) Mesh { return undefined; } }; /// Color defined to be a 3 component vector /// X value is red, Y value is blue and Z value is green. pub const Color = zalgebra.vec3; pub const Material = struct { texture: ?AssetHandle = null, ambient: Color = Color.zero(), diffuse: Color = Color.one(), specular: Color = Color.one(), shininess: f32 = 32.0, pub const default = Material{}; }; pub const ShaderProgram = struct { id: c.GLuint, vao: c.GLuint, vertex: c.GLuint, fragment: c.GLuint, allocator: Allocator = std.heap.page_allocator, uniformLocations: std.StringHashMap(c.GLint), /// Hashes of the current values of uniforms. Used to avoid expensive glUniform uniformHashes: std.StringHashMap(u32), pub fn createFromFile(allocator: Allocator, vertPath: []const u8, fragPath: []const u8) !ShaderProgram { return undefined; } pub fn create(allocator: Allocator, vert: [:0]const u8, frag: [:0]const u8) !ShaderProgram { return undefined; } pub fn bind(self: *const ShaderProgram) void { } fn getUniformLocation(self: *ShaderProgram, name: [:0]const u8) c.GLint { if (self.uniformLocations.get(name)) |location| { return location; } else { const location = -1; if (location == -1) { std.log.scoped(.didot).warn("Shader uniform not found: {s}", .{name}); } else { //std.log.scoped(.didot).debug("Uniform location of {s} is {}", .{name, location}); } self.uniformLocations.put(name, location) catch {}; // as this is a cache, not being able to put the entry can be and should be discarded return location; } } fn isUniformSame(self: *ShaderProgram, name: [:0]const u8, bytes: []const u8) bool { const hash = std.hash.Crc32.hash(bytes); defer { self.uniformHashes.put(name, hash) catch {}; // again, as this is an optimization, it is not fatal if we can't put it in the map } if (self.uniformHashes.get(name)) |expected| { return expected == hash; } else { return false; } } /// Set an OpenGL uniform to the following 4x4 matrix. pub fn setUniformMat4(self: *ShaderProgram, name: [:0]const u8, val: zalgebra.mat4) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); //c.glUniformMatrix4fv(uniform, 1, c.GL_FALSE, val.get_data()); } /// Set an OpenGL uniform to the following boolean. pub fn setUniformBool(self: *ShaderProgram, name: [:0]const u8, val: bool) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); var v: c.GLint = if (val) 1 else 0; //c.glUniform1i(uniform, v); } /// Set an OpenGL uniform to the following float. pub fn setUniformFloat(self: *ShaderProgram, name: [:0]const u8, val: f32) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); //c.glUniform1f(uniform, val); } /// Set an OpenGL uniform to the following 3D float vector. pub fn setUniformVec3(self: *ShaderProgram, name: [:0]const u8, val: zalgebra.vec3) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); //c.glUniform3f(uniform, val.x, val.y, val.z); } fn checkError(shader: c.GLuint) ShaderError!void { var status: c.GLint = undefined; const err = c.glGetError(); if (err != c.GL_NO_ERROR) { std.log.scoped(.didot).err("GL error while initializing shaders: {}", .{err}); } //c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &status); if (status != c.GL_TRUE) { var buf: [2048]u8 = undefined; var totalLen: c.GLsizei = -1; //c.glGetShaderInfoLog(shader, 2048, &totalLen, buf[0..]); if (totalLen == -1) { // the length of the infolog seems to not be set // when a GL context isn't set (so when the window isn't created) return ShaderError.InvalidContextError; } var totalSize: usize = @intCast(usize, totalLen); std.log.scoped(.didot).alert("shader compilation errror:\n{s}", .{buf[0..totalSize]}); return ShaderError.ShaderCompileError; } } pub fn deinit(self: *ShaderProgram) void { self.uniformLocations.deinit(); self.uniformHashes.deinit(); } }; const image = @import("didot-image"); const Image = image.Image; pub const CubemapSettings = struct { right: AssetHandle, left: AssetHandle, top: AssetHandle, bottom: AssetHandle, front: AssetHandle, back: AssetHandle }; pub const Texture = struct { id: c.GLuint, width: usize = 0, height: usize = 0, tiling: zalgebra.vec2 = zalgebra.vec2.new(1, 1), pub fn createEmptyCubemap() Texture { var id: c.GLuint = undefined; return Texture { .id = id }; } pub fn createEmpty2D() Texture { var id: c.GLuint = undefined; return Texture { .id = id }; } pub fn bind(self: *const Texture) void { } pub fn deinit(self: *const Texture) void { } }; // Image asset loader pub const TextureAsset = struct { pub fn init2D(allocator: Allocator, format: []const u8) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.tiling = zalgebra.vec2.new(0, 0); data.cubemap = null; data.format = format; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } /// Memory is caller owned pub fn init(allocator: Allocator, original: TextureAssetLoaderData) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.* = original; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } /// Memory is caller owned pub fn initCubemap(allocator: Allocator, cb: CubemapSettings) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.cubemap = cb; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } }; pub const TextureAssetLoaderData = struct { cubemap: ?CubemapSettings = null, format: []const u8, tiling: zalgebra.vec2 = zalgebra.vec2.new(1, 1) }; pub const TextureAssetLoaderError = error{InvalidFormat}; fn textureLoadImage(allocator: Allocator, stream: *AssetStream, format: []const u8) !Image { if (std.mem.eql(u8, format, "png")) { return try image.png.read(allocator, stream.reader()); } else if (std.mem.eql(u8, format, "bmp")) { return try image.bmp.read(allocator, stream.reader(), stream.seekableStream()); } return TextureAssetLoaderError.InvalidFormat; } fn getTextureFormat(format: image.ImageFormat) c.GLuint { if (std.meta.eql(format, image.ImageFormat.RGB24)) { return c.GL_RGB; } else if (std.meta.eql(format, image.ImageFormat.BGR24)) { return c.GL_BGR; } else if (std.meta.eql(format, image.ImageFormat.RGBA32)) { return c.GL_RGBA; } else { unreachable; // TODO convert the source image to RGB } } pub fn textureAssetLoader(allocator: Allocator, dataPtr: usize, stream: *AssetStream) !usize { var data = @intToPtr(*TextureAssetLoaderData, dataPtr); if (data.cubemap) |cb| { const texMutex = windowContextLock(); var texture = Texture.createEmptyCubemap(); texMutex.unlock(); const targets = [_]c.GLuint { c.GL_TEXTURE_CUBE_MAP_POSITIVE_X, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }; const names = [_][]const u8 {"X+", "X-", "Y+", "Y-", "Z+", "Z-"}; var frames: [6]@Frame(AssetHandle.getPointer) = undefined; comptime var i = 0; inline for (@typeInfo(CubemapSettings).Struct.fields) |field| { const handle = @field(cb, field.name); frames[i] = async handle.getPointer(allocator); i += 1; } i = 0; inline for (@typeInfo(CubemapSettings).Struct.fields) |field| { const ptr = try await frames[i]; const tex = @intToPtr(*Texture, ptr); var tmp = try allocator.alloc(u8, tex.width * tex.height * 3); const mutex = windowContextLock(); tex.bind(); allocator.free(tmp); mutex.unlock(); std.log.scoped(.didot).debug("Loaded cubemap {s}", .{names[i]}); i += 1; } var t = try allocator.create(Texture); t.* = texture; return @ptrToInt(t); } else { var img = try textureLoadImage(allocator, stream, data.format); const mutex = windowContextLock(); var texture = Texture.createEmpty2D(); defer mutex.unlock(); texture.tiling = data.tiling; texture.width = img.width; texture.height = img.height; img.deinit(); std.log.scoped(.didot).debug("Loaded texture (format={}, size={}x{})", .{img.format, img.width, img.height}); var t = try allocator.create(Texture); t.* = texture; return @ptrToInt(t); } } const objects = @import("../didot-objects/objects.zig"); // hacky hack til i found a way for graphics to depend on objects const Scene = objects.Scene; const GameObject = objects.GameObject; const Camera = objects.Camera; const AssetManager = objects.AssetManager; const Asset = objects.Asset; const AssetStream = objects.AssetStream; const AssetHandle = objects.AssetHandle; /// Set this function to replace normal pre-render behaviour (GL state, clear, etc.), it happens after viewport pub var preRender: ?fn() void = null; /// Set this function to replace normal viewport behaviour pub var viewport: ?fn() zalgebra.vec4 = null; pub fn renderScene(scene: *Scene, window: Window) !void { const size = window.getFramebufferSize(); try renderSceneOffscreen(scene, if (viewport) |func| func() else zalgebra.vec4.new(0, 0, size.x, size.y)); } var renderMutex: ?std.Thread.Mutex = undefined; /// Internal method for rendering a game scene. /// This method is here as it uses graphics API-dependent code (it's the rendering part afterall) pub fn renderSceneOffscreen(scene: *Scene, vp: zalgebra.vec4) !void { renderMutex = windowContextLock(); defer renderMutex.unlock(); if (preRender) |func| { func(); } else { c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT); c.glEnable(c.GL_DEPTH_TEST); c.glEnable(c.GL_FRAMEBUFFER_SRGB); //c.glEnable(c.GL_CULL_FACE); } var assets = &scene.assetManager; if (scene.camera) |cameraObject| { const camera = cameraObject.getComponent(Camera).?; const projMatrix = switch (camera.projection) { .Perspective => |p| zalgebra.mat4.perspective(p.fov, vp.z / vp.w, p.near, p.far), .Orthographic => |p| zalgebra.mat4.orthographic(p.left, p.right, p.bottom, p.top, p.near, p.far) }; // create the direction vector to be used with the view matrix. const transform = cameraObject.getComponent(objects.Transform).?; const euler = transform.rotation.extract_rotation(); const yaw = zalgebra.to_radians(euler.x); const pitch = zalgebra.to_radians(euler.y); const direction = zalgebra.vec3.new( std.math.cos(yaw) * std.math.cos(pitch), std.math.sin(pitch), std.math.sin(yaw) * std.math.cos(pitch) ).norm(); const viewMatrix = zalgebra.mat4.look_at(transform.position, transform.position.add(direction), zalgebra.vec3.new(0.0, 1.0, 0.0)); //const viewMatrix = zalgebra.mat4.from_translate(transform.position.scale(-1)) // .mult(transform.rotation.to_mat4()); //const viewMatrix = zalgebra.mat4.from_translate(transform.position).mult(zalgebra.mat4.identity()); if (camera.skybox) |*skybox| { skybox.shader.bind(); const view = zalgebra.mat4.identity() .mult(zalgebra.mat4.from_euler_angle(viewMatrix.extract_rotation())); skybox.shader.setUniformMat4("view", view); skybox.shader.setUniformMat4("projection", projMatrix); try renderSkybox(skybox, assets, camera); } camera.shader.bind(); camera.shader.setUniformMat4("projMatrix", projMatrix); camera.shader.setUniformMat4("viewMatrix", viewMatrix); if (scene.pointLight) |light| { const lightData = light.getComponent(objects.PointLight).?; camera.shader.setUniformVec3("light.position", light.getComponent(objects.Transform).?.position); camera.shader.setUniformVec3("light.color", lightData.color); camera.shader.setUniformFloat("light.constant", lightData.constant); camera.shader.setUniformFloat("light.linear", lightData.linear); camera.shader.setUniformFloat("light.quadratic", lightData.quadratic); camera.shader.setUniformBool("useLight", true); } else { camera.shader.setUniformBool("useLight", false); } camera.shader.setUniformVec3("viewPos", transform.position); const held = scene.treeLock.acquire(); for (scene.objects.items) |gameObject| { try renderObject(gameObject, assets, camera, zalgebra.mat4.identity()); } held.release(); } } fn renderSkybox(skybox: *objects.Skybox, assets: *AssetManager, camera: *Camera) !void { var mesh = try skybox.mesh.get(Mesh, assets.allocator); renderMutex.unlock(); const texture = try skybox.cubemap.get(Texture, assets.allocator); renderMutex = windowContextLock(); } // TODO: remake parent matrix with the new system fn renderObject(gameObject: *GameObject, assets: *AssetManager, camera: *Camera, parentMatrix: zalgebra.mat4) anyerror!void { if (gameObject.getComponent(objects.Transform)) |transform| { const matrix = zalgebra.mat4.recompose(transform.position, transform.rotation, transform.scale); if (gameObject.mesh) |handle| { renderMutex.unlock(); const mesh = try handle.get(Mesh, assets.allocator); renderMutex = windowContextLock(); const material = gameObject.material; if (material.texture) |asset| { renderMutex.unlock(); const texture = try asset.get(Texture, assets.allocator); renderMutex = windowContextLock(); texture.bind(); camera.shader.setUniformFloat("xTiling", if (texture.tiling.x == 0) 1 else transform.scale.x / texture.tiling.x); camera.shader.setUniformFloat("yTiling", if (texture.tiling.y == 0) 1 else transform.scale.z / texture.tiling.y); camera.shader.setUniformBool("useTex", true); } else { camera.shader.setUniformBool("useTex", false); } camera.shader.setUniformVec3("material.ambient", material.ambient); camera.shader.setUniformVec3("material.diffuse", material.diffuse); camera.shader.setUniformVec3("material.specular", material.specular); var s: f32 = std.math.clamp(material.shininess, 1.0, 128.0); camera.shader.setUniformFloat("material.shininess", s); camera.shader.setUniformMat4("modelMatrix", matrix); } } } pub usingnamespace @import("didot-window"); comptime { std.testing.refAllDecls(@This()); std.testing.refAllDecls(ShaderProgram); std.testing.refAllDecls(Texture); }
didot-webgl/graphics.zig
const std = @import("std"); const os = std.os; const io = std.io; const net = std.net; const fs = std.fs; pub const io_mode = .evented; const pulse = @cImport({ @cInclude("pulse/pulseaudio.h"); }); const CHUNK_SIZE: u32 = 1280; const CONNECTION_READ_TIMEOUT: i64 = 5000; // Time in ms pub fn main() !void { var err: c_int = undefined; std.debug.warn("Starting\n", .{}); const allocator = std.heap.c_allocator; const req_listen_addr = try net.Address.parseIp4("0.0.0.0", 5988); const loop = std.event.Loop.instance.?; // loop.beginOneEvent(); // Hotfix for program exiting without it. Might be unecessary? // defer loop.finishOneEvent(); var props = pulse.pa_proplist_new(); defer pulse.pa_proplist_free(props); var sndServer = SndServer{ .clients = std.AutoHashMap(*Client, void).init(allocator), .lock = std.Thread.Mutex{}, // .pulseLock = std.Mutex{}, .mainloop = pulse.pa_threaded_mainloop_new().?, .mainloop_api = undefined, .context = undefined, .checkStalledFrame = undefined, }; //TODO: Is there a better way to do this? // sndServer.announcerFrame = async sndServer.announcer(); sndServer.checkStalledFrame = async sndServer.checkStalled(); sndServer.mainloop_api = pulse.pa_threaded_mainloop_get_api(sndServer.mainloop).?; sndServer.context = pulse.pa_context_new_with_proplist(sndServer.mainloop_api, "zig-sndrecv", props).?; err = pulse.pa_context_connect(sndServer.context, null, pulse.pa_context_flags.PA_CONTEXT_NOFLAGS, null); std.debug.assert(err == 0); // Start mainloop err = pulse.pa_threaded_mainloop_start(sndServer.mainloop); std.debug.assert(err == 0); // Starting TCP Listener var server = net.StreamServer.init(net.StreamServer.Options{}); defer server.deinit(); try server.listen(req_listen_addr); std.debug.warn("Listening at {}\n", .{server.listen_address.getPort()}); while (true) { const client_con = try server.accept(); std.debug.warn("Client connected!\n", .{}); const client = try allocator.create(Client); client.* = Client{ .con = client_con, .frame = async client.handle(&sndServer), .last_read = std.time.milliTimestamp(), }; var held_lock = sndServer.lock.acquire(); defer held_lock.release(); try sndServer.clients.putNoClobber(client, {}); } } const SndServer = struct { clients: std.AutoHashMap(*Client, void), lock: std.Thread.Mutex, // pulseLock: std.Mutex, mainloop: *pulse.pa_threaded_mainloop, mainloop_api: *pulse.pa_mainloop_api, context: *pulse.pa_context, // announcerFrame: @Frame(announcer), checkStalledFrame: @Frame(checkStalled), // fn announcer(self: *SndServer) !void { // // TODO Send UDP announcements // } fn checkStalled(self: *SndServer) !void { const loop = std.event.Loop.instance.?; while (true) { loop.sleep(2000000000); var held_lock = self.lock.acquire(); defer held_lock.release(); var it = self.clients.iterator(); var current_time = std.time.milliTimestamp(); while (it.next()) |entry| { if (current_time - entry.key_ptr.*.last_read > CONNECTION_READ_TIMEOUT) { // 5 seconds after last read // std.debug.warn("Detected stalled connection. Closing broken connections is WIP\n", .{}); // entry.key.con.file.close(); // entry.key.con.stream.close(); } } } } }; const Client = struct { con: net.StreamServer.Connection, frame: @Frame(handle), last_read: i64, fn handle(self: *Client, server: *SndServer) !void { defer { var held_lock = server.lock.acquire(); _ = server.clients.remove(self); held_lock.release(); } var err: c_int = undefined; _ = try self.con.stream.write("SNDStream v0.1\n"); // Is irrelevant for normal connections, but helps debugging :) // Getting AudioStream // TODO: Might also need server lock // var pulse_lock = server.pulseLock.acquire(); pulse.pa_threaded_mainloop_lock(server.mainloop); var ss = pulse.pa_sample_spec{ .format = pulse.pa_sample_format.PA_SAMPLE_S16LE, .rate = 48000, .channels = 2, }; //TODO: make name the ip address of the client // Name seems to be irrelevant for at least GNOMEs Settings. Might have to create a new context per connection? var stream = pulse.pa_stream_new(server.context, "", &ss, null); defer { pulse.pa_threaded_mainloop_lock(server.mainloop); _ = pulse.pa_stream_disconnect(stream); // Error here is irrelevant pulse.pa_stream_unref(stream); // Should free this stream, since there should only be one ref but who knows... pulse.pa_threaded_mainloop_unlock(server.mainloop); } err = pulse.pa_stream_connect_playback(stream, null, null, pulse.pa_stream_flags.PA_STREAM_NOFLAGS, null, null); pulse.pa_threaded_mainloop_unlock(server.mainloop); // pulse_lock.release(); if (err != 0) { // Some error. What error exactly, i don't know but when it happens but it at least does not crash everything std.debug.warn("Error while connecting audio stream {}\n", .{err}); return; } while (true) { var buf: [CHUNK_SIZE * 3]u8 = undefined; const amt = try self.con.stream.read(&buf); self.last_read = std.time.milliTimestamp(); if (amt == 0) { //Peer disconnected std.debug.warn("Peer disconnected!\n", .{}); break; } const msg = buf[0..amt]; // pulse_lock = server.pulseLock.acquire(); pulse.pa_threaded_mainloop_lock(server.mainloop); defer pulse.pa_threaded_mainloop_unlock(server.mainloop); err = pulse.pa_stream_write(stream, msg.ptr, msg.len, null, 0, pulse.pa_seek_mode.PA_SEEK_RELATIVE); if (err != 0) { // Again I don't know when this happends, but I will just break the connection std.debug.warn("Error while writing audio stream {}\n", .{err}); return; } // pulse_lock.release(); } } };
src/main.zig
const std = @import("std"); const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const stdout = std.io.getStdOut().outStream(); const print = stdout.print; const allocPrint0 = std.fmt.allocPrint0; const err = @import("error.zig"); const errorAt = err.errorAt; const errorAtToken = err.errorAtToken; const tokenize = @import("tokenize.zig"); const Token = tokenize.Token; const TokenKind = tokenize.TokenKind; const atoi = tokenize.atoi; const streq = tokenize.streq; const allocator = @import("allocator.zig"); const getAllocator = allocator.getAllocator; const typezig = @import("type.zig"); const TypeKind = typezig.TypeKind; const Type = typezig.Type; const copyType = typezig.copyType; const addType = typezig.addType; const alignToI32 = @import("codegen.zig").alignTo; pub const NodeKind = enum { NdAdd, // + NdSub, // - NdMul, // * NdDiv, // / NdNeg, // unary - NdEq, // == NdNe, // != NdLt, // < NdLe, // <= NdAssign, // = NdComma, // , NdMember, // . (struct member access) NdAddr, // 単項演算子の& NdDeref, // 単項演算子の* NdReturn, // return NdBlock, // { ... } NdIf, // if NdFor, // "for" or "while" NdFuncall, // 関数呼出 NdExprStmt, // expression statement NdStmtExpr, // statement expression NdVar, // 変数 NdNum, // 数値 NdCast, // Type Cast }; pub const Node = struct { kind: NodeKind, // 種別 next: ?*Node, // 次のノード。NdExprStmtのときに使う ty: ?*Type, // 型情報 tok: *Token, // エラー情報の補足のためにトークンの代表値を持っておく lhs: ?*Node, // Left-hand side rhs: ?*Node, // Right-hand side body: ?*Node, // NdBlockのときに使う // if, for, while 文で使う cond: ?*Node, then: ?*Node, els: ?*Node, init: ?*Node, inc: ?*Node, // Structのメンバ member: ?*Member, // 関数呼出のときに使う funcname: ?[:0]u8, func_ty: ?*Type, args: ?*Node, variable: ?*Obj, // 変数、NdVarのときに使う val: ?[:0]u8, // NdNumのときに使われる pub fn init(kind: NodeKind, tok: *Token) Node { return Node{ .kind = kind, .next = null, .ty = null, .tok = tok, .lhs = null, .rhs = null, .body = null, .cond = null, .then = null, .els = null, .init = null, .inc = null, .member = null, .funcname = null, .func_ty = null, .args = null, .variable = null, .val = null, }; } pub fn allocInit(kind: NodeKind, tok: *Token) *Node { var node = getAllocator().create(Node) catch @panic("cannot allocate Node"); node.* = Node.init(kind, tok); return node; } }; pub const Member = struct { next: ?*Member, ty: ?*Type, name: *Token, offset: usize, pub fn init(name: *Token) Member { return Member{ .next = null, .ty = null, .name = name, .offset = 0, }; } pub fn allocInit(name: *Token) *Member { var m = getAllocator().create(Member) catch @panic("cannot allocate Member"); m.* = Member.init(name); return m; } }; // 変数 or 関数 pub const Obj = struct { name: [:0]u8, ty: ?*Type, is_local: bool, is_function: bool, is_definition: bool, // ローカル変数のとき offset: i32, // RBPからのオフセット // グローバル変数のとき init_data: [:0]u8, // 関数のとき params: ?ArrayList(*Obj), body: *Node, // 関数の開始ノード locals: ?ArrayList(*Obj), stack_size: i32, pub fn initVar(is_local: bool, name: [:0]u8, ty: *Type) Obj { return Obj{ .name = name, .ty = ty, .is_local = is_local, .is_function = false, .is_definition = false, .offset = 0, .init_data = "", .params = null, .body = undefined, .locals = null, .stack_size = 0, }; } pub fn allocVar(is_local: bool, name: [:0]u8, ty: *Type) *Obj { var f = getAllocator().create(Obj) catch @panic("cannot allocate Var"); f.* = Obj.initVar(is_local, name, ty); return f; } pub fn initFunc(name: [:0]u8, params: ArrayList(*Obj), body: *Node) Obj { return Obj{ .name = name, .is_local = true, .is_fuction = true, .kind = .ObjFunc, .offset = null, .params = params, .body = body, .locals = ArrayList(*Obj).init(getAllocator()), .stack_size = 0, }; } pub fn allocFunc(name: [:0]u8, params: ArrayList(*Obj), body: *Node) *Obj { var f = getAllocator().create(*Obj) catch @panic("cannot allocate Func"); f.* = Obj.initFunc(name, params, body); return f; } }; // ローカル変数、グローバル変数, typedefのスコープ const VarScope = struct { next: ?*VarScope, name: [:0]u8, variable: ?*Obj, type_def: ?*Type, pub fn init(name: [:0]u8) VarScope { return VarScope{ .next = null, .name = name, .variable = null, .type_def = null, }; } pub fn allocInit(name: [:0]u8) *VarScope { var vs = getAllocator().create(VarScope) catch @panic("cannot allocate VarScope"); vs.* = VarScope.init(name); return vs; } }; // typedef や externで使う変数の属性 const VarAttr = struct { is_typedef: bool, pub fn init() VarAttr { return VarAttr{ .is_typedef = false }; } pub fn allocInit() *VarAttr { var vs = getAllocator().create(VarAttr) catch @panic("cannot allocate VarAttr"); vs.* = VarAttr.init(); return vs; } }; // 構造体、ユニオンのタグ名のスコープ const TagScope = struct { next: ?*TagScope, name: [:0]u8, ty: ?*Type, pub fn init(name: [:0]u8) TagScope { return TagScope{ .next = null, .name = name, .ty = null, }; } pub fn allocInit(name: [:0]u8) *TagScope { var s = getAllocator().create(TagScope) catch @panic("cannot allocate TagScope"); s.* = TagScope.init(name); return s; } }; // ブロックのスコープ const Scope = struct { next: ?*Scope, vars: ?*VarScope, tags: ?*TagScope, pub fn allocInit() *Scope { var sc = getAllocator().create(Scope) catch @panic("cannot allocate Scope"); sc.* = Scope{ .next = null, .vars = null, .tags = null }; return sc; } }; fn pushScope(name: [:0]u8) *VarScope { var vs = VarScope.allocInit(name); vs.*.next = current_scope.*.vars; current_scope.*.vars = vs; return vs; } fn pushTagScope(tok: *Token, ty: *Type) void { var ts = TagScope.allocInit(tok.*.val); ts.*.ty = ty; ts.*.next = current_scope.*.tags; current_scope.*.tags = ts; } pub fn newBinary(kind: NodeKind, lhs: *Node, rhs: *Node, tok: *Token) *Node { var node = Node.allocInit(kind, tok); node.*.lhs = lhs; node.*.rhs = rhs; return node; } pub fn newUnary(kind: NodeKind, lhs: *Node, tok: *Token) *Node { var node = Node.allocInit(kind, tok); node.*.lhs = lhs; return node; } fn newNum(val: [:0]u8, tok: *Token) *Node { var node = Node.allocInit(.NdNum, tok); node.*.val = val; return node; } fn newLong(val: [:0]u8, tok: *Token) *Node { var node = Node.allocInit(.NdNum, tok); node.*.val = val; node.*.ty = Type.typeLong(); return node; } pub fn newCast(e: *Node, ty: *Type) *Node { addType(e); var node = Node.allocInit(.NdCast, e.*.tok); node.*.lhs = e; node.*.ty = copyType(ty); return node; } fn newVarNode(v: *Obj, tok: *Token) *Node { var node = Node.allocInit(.NdVar, tok); node.*.variable = v; node.*.ty = v.ty; return node; } fn newBlockNode(n: ?*Node, tok: *Token) *Node { var node = Node.allocInit(.NdBlock, tok); node.*.body = n; return node; } fn newStringLiteral(s: [:0]u8, ty: *Type) *Obj { var gv = newAnonGvar(ty); gv.init_data = s; return gv; } fn newAnonGvar(ty: *Type) *Obj { return newGvar(newUniqueName(), ty); } var unique_id: isize = -1; fn newUniqueName() [:0]u8 { unique_id += 1; return allocPrint0(getAllocator(), ".L..{}", .{unique_id}) catch @panic("cannot allocate unique name"); } // 引数のリストを一時的に保有するためのグローバル変数 var fn_args: ArrayList(*Obj) = undefined; // ローカル変数のリストを一時的に保有するためのグローバル変数 var locals: ArrayList(*Obj) = undefined; // グローバル変数のリストを一時的に保有するためのグローバル変数 var globals: ArrayList(*Obj) = undefined; // 現在のスコープを保持するためのグローバル変数 var current_scope: *Scope = undefined; // 現在のfunctionを保持するためのグローバル変数 var current_fn: *Obj = undefined; fn newLvar(name: [:0]u8, ty: *Type) *Obj { var v = Obj.allocVar(true, name, ty); var sc = pushScope(name); sc.*.variable = v; locals.append(v) catch @panic("ローカル変数のパースに失敗しました"); return v; } fn newGvar(name: [:0]u8, ty: *Type) *Obj { var v = Obj.allocVar(false, name, ty); var sc = pushScope(name); sc.*.variable = v; globals.append(v) catch @panic("グローバル変数のパースに失敗しました"); return v; } fn enterScope() void { var sc = Scope.allocInit(); sc.*.next = current_scope; current_scope = sc; } fn leaveScope() void { current_scope = current_scope.*.next.?; } fn findVar(token: Token) ?*VarScope { var sc: ?*Scope = current_scope; while (sc != null) : (sc = sc.?.*.next) { var sv = sc.?.*.vars; while (sv != null) : (sv = sv.?.*.next) { if (streq(token.val, sv.?.*.name)) { return sv; } } } return null; } fn findTag(token: *Token) ?*Type { var s: ?*Scope = current_scope; while (s != null) : (s = s.?.*.next) { var t = s.?.*.tags; while (t != null) : (t = t.?.*.next) { if (streq(token.*.val, t.?.*.name)) return t.?.*.ty; } } return null; } fn getOrLast(tokens: []Token, ti: *usize) *Token { if (ti.* < tokens.len) { return &tokens[ti.*]; } return &tokens[tokens.len - 1]; } fn findTypedef(tokens: []Token, ti: *usize) ?*Type { if (ti.* >= tokens.len) { errorAtToken(getOrLast(tokens, ti), "Unexpected EOF"); } const token = tokens[ti.*]; if (token.kind == TokenKind.TkIdent) { var sc = findVar(token); if (sc != null) return sc.?.*.type_def; } return null; } fn parseTypedef(tokens: []Token, ti: *usize, basety: *Type) void { var first = true; while (!consumeTokVal(tokens, ti, ";")) { if (!first) skip(tokens, ti, ","); first = false; var ty = declarator(tokens, ti, basety); pushScope(ty.*.name.?.*.val).*.type_def = ty; } } // program = (typedef | function-definition | global-variable)* pub fn parse(tokens: []Token, ti: *usize) !ArrayList(*Obj) { Type.initGlobals(); globals = ArrayList(*Obj).init(getAllocator()); current_scope = Scope.allocInit(); while (ti.* < tokens.len) { var attr = VarAttr.init(); const basety = declspec(tokens, ti, &attr); // Typedef if (attr.is_typedef) { parseTypedef(tokens, ti, basety); continue; } if (isFunction(tokens, ti)) { function(tokens, ti, basety); } else { globalVariable(tokens, ti, basety); } } return globals; } fn isFunction(tokens: []Token, ti: *usize) bool { const tok = &tokens[ti.*]; const original_ti = ti.*; if (streq(tok.*.val, ";")) return false; const ty = declarator(tokens, ti, Type.typeInt()); ti.* = original_ti; return ty.*.kind == TypeKind.TyFunc; } // function = declarator ident { compound_stmt } fn function(tokens: []Token, ti: *usize, basety: *Type) void { locals = ArrayList(*Obj).init(getAllocator()); const ty = declarator(tokens, ti, basety); const is_definition = !consumeTokVal(tokens, ti, ";"); var f = newGvar(ty.*.name.?.*.val, ty); f.*.is_function = true; f.*.is_definition = is_definition; if (!f.*.is_definition) { return; } current_fn = f; enterScope(); createParamLvars(ty.*.params); var params = ArrayList(*Obj).init(getAllocator()); for (locals.items) |lc| { params.append(lc) catch @panic("cannot append params"); } f.*.params = params; skip(tokens, ti, "{"); f.*.body = compoundStmt(tokens, ti); f.*.locals = locals; leaveScope(); } fn globalVariable(tokens: []Token, ti: *usize, basety: *Type) void { var first = true; while (!consumeTokVal(tokens, ti, ";")) { if (!first) skip(tokens, ti, ","); first = false; const ty = declarator(tokens, ti, basety); _ = newGvar(ty.*.name.?.*.val, ty); } } // stmt = "return" expr ";" // | "if" "(" expr ")" stmt ("else" stmt)? // | "for" "(" expr-stmt expr? ";" expr? ")" stmt // | "while" "(" expr ")" stmt // | "{" compound-stmt // | expr-stmt pub fn stmt(tokens: []Token, ti: *usize) *Node { if (consumeTokVal(tokens, ti, "return")) { const node = Node.allocInit(.NdReturn, getOrLast(tokens, ti)); var exp = expr(tokens, ti); skip(tokens, ti, ";"); addType(exp); node.*.lhs = newCast(exp, current_fn.*.ty.?.*.return_ty.?); return node; } if (consumeTokVal(tokens, ti, "if")) { const node = Node.allocInit(.NdIf, getOrLast(tokens, ti)); skip(tokens, ti, "("); node.*.cond = expr(tokens, ti); skip(tokens, ti, ")"); node.*.then = stmt(tokens, ti); if (consumeTokVal(tokens, ti, "else")) { node.*.els = stmt(tokens, ti); } return node; } if (consumeTokVal(tokens, ti, "for")) { const node = Node.allocInit(.NdFor, getOrLast(tokens, ti)); skip(tokens, ti, "("); node.*.init = exprStmt(tokens, ti); if (!consumeTokVal(tokens, ti, ";")) { node.*.cond = expr(tokens, ti); skip(tokens, ti, ";"); } if (!consumeTokVal(tokens, ti, ")")) { node.*.inc = expr(tokens, ti); skip(tokens, ti, ")"); } node.*.then = stmt(tokens, ti); return node; } if (consumeTokVal(tokens, ti, "while")) { const node = Node.allocInit(.NdFor, getOrLast(tokens, ti)); skip(tokens, ti, "("); node.*.cond = expr(tokens, ti); skip(tokens, ti, ")"); node.*.then = stmt(tokens, ti); return node; } if (consumeTokVal(tokens, ti, "{")) { return compoundStmt(tokens, ti); } return exprStmt(tokens, ti); } // compound-stmt = (declaration | stmt)* "}" fn compoundStmt(tokens: []Token, ti: *usize) *Node { var head = Node.init(.NdNum, getOrLast(tokens, ti)); var cur: *Node = &head; var end = false; enterScope(); while (ti.* < tokens.len) { if (consumeTokVal(tokens, ti, "}")) { end = true; break; } if (isTypeName(tokens, ti)) { var attr = VarAttr.init(); var basety = declspec(tokens, ti, &attr); if (attr.is_typedef) { parseTypedef(tokens, ti, basety); continue; } cur.*.next = declaration(tokens, ti, basety); } else { cur.*.next = stmt(tokens, ti); } cur = cur.*.next.?; addType(cur); } leaveScope(); if (!end) { errorAtToken(&tokens[tokens.len - 1], " } がありません"); } return newBlockNode(head.next, getOrLast(tokens, ti)); } // expr-stmt = expr? ";" fn exprStmt(tokens: []Token, ti: *usize) *Node { if (consumeTokVal(tokens, ti, ";")) { return newBlockNode(null, getOrLast(tokens, ti)); } const node = newUnary(.NdExprStmt, expr(tokens, ti), getOrLast(tokens, ti)); skip(tokens, ti, ";"); return node; } // declaration = declspec (declarator ("=" expr)? ("," declarator ("=" expr)?)*)? ";" fn declaration(tokens: []Token, ti: *usize, basety: *Type) *Node { if (tokens.len <= ti.*) { errorAtToken(&tokens[tokens.len - 1], "Unexpected EOF"); } var token = &tokens[ti.*]; var head = Node.init(.NdNum, token); var cur = &head; var first: bool = true; while (ti.* < tokens.len and !consumeTokVal(tokens, ti, ";")) { if (!first) { skip(tokens, ti, ","); } else { first = false; } var ty = declarator(tokens, ti, basety); if (ty.*.kind == TypeKind.TyVoid) { errorAtToken(&tokens[ti.*], "変数がvoidとして宣言されています"); } var variable = newLvar(ty.*.name.?.*.val, ty); if (!consumeTokVal(tokens, ti, "=")) continue; var lhs = newVarNode(variable, ty.*.name.?); var rhs = assign(tokens, ti); token = &tokens[ti.*]; var node = newBinary(.NdAssign, lhs, rhs, token); cur.*.next = newUnary(.NdExprStmt, node, token); cur = cur.*.next.?; } var node = Node.allocInit(.NdBlock, token); node.*.body = head.next; return node; } // declarator = "*"* ("(" ident ")" | "(" declarator ")" | ident) type-suffix fn declarator(tokens: []Token, ti: *usize, typ: *Type) *Type { var ty = typ; while (consumeTokVal(tokens, ti, "*")) { ty = Type.pointerTo(ty); } if (consumeTokVal(tokens, ti, "(")) { const start = ti.*; while (!consumeTokVal(tokens, ti, ")")) { ti.* += 1; } ty = typeSuffix(tokens, ti, ty); const end = ti.*; ti.* = start; ty = declarator(tokens, ti, ty); ti.* = end; return ty; } var tok = &tokens[ti.*]; if (tok.*.kind != .TkIdent) { errorAtToken(tok, "expected a variable name"); } ti.* += 1; ty = typeSuffix(tokens, ti, ty); ty.*.name = tok; return ty; } // declspec = ("void" | "char" | "short" | "int" | "long" // | "typedef" // | struct-decl | union-decl | typedef-name)+ // // The order of typenames in a type-specifier doesn't matter. For // example, `int long static` means the same as `static long int`. // That can also be written as `static long` because you can omit // `int` if `long` or `short` are specified. However, something like // `char int` is not a valid type specifier. We have to accept only a // limited combinations of the typenames. // // In this function, we count the number of occurrences of each typename // while keeping the "current" type object that the typenames up // until that point represent. When we reach a non-typename token, // we returns the current type object. fn declspec(tokens: []Token, ti: *usize, attr: ?*VarAttr) *Type { // We use a single integer as counters for all typenames. // For example, bits 0 and 1 represents how many times we saw the // keyword "void" so far. With this, we can use a switch statement // as you can see below. const TypeMax = enum(usize) { Void = 1 << 0, Char = 1 << 2, Short = 1 << 4, Int = 1 << 6, Long = 1 << 8, Other = 1 << 10, }; var ty = Type.typeInt(); var counter: usize = 0; while (isTypeName(tokens, ti)) { if (consumeTokVal(tokens, ti, "typedef")) { if (attr == null) errorAtToken(getOrLast(tokens, ti), "不正なストレージクラス指定子です"); attr.?.*.is_typedef = true; continue; } var ty2 = findTypedef(tokens, ti); var typeMaxOther = false; var token = getOrLast(tokens, ti); if (streq(token.val, "struct") or streq(token.val, "union") or ty2 != null) { if (counter > 0) { break; } if (consumeTokVal(tokens, ti, "struct")) { ty = structDecl(tokens, ti); } else if (consumeTokVal(tokens, ti, "union")) { ty = unionDecl(tokens, ti); } else { ty = ty2.?; ti.* += 1; } counter += @enumToInt(TypeMax.Other); continue; } if (consumeTokVal(tokens, ti, "void")) { counter += @enumToInt(TypeMax.Void); } else if (consumeTokVal(tokens, ti, "char")) { counter += @enumToInt(TypeMax.Char); } else if (consumeTokVal(tokens, ti, "short")) { counter += @enumToInt(TypeMax.Short); } else if (consumeTokVal(tokens, ti, "int")) { counter += @enumToInt(TypeMax.Int); } else if (consumeTokVal(tokens, ti, "long")) { counter += @enumToInt(TypeMax.Long); } else { unreachable; } switch (counter) { @enumToInt(TypeMax.Void) => ty = Type.typeVoid(), @enumToInt(TypeMax.Char) => ty = Type.typeChar(), @enumToInt(TypeMax.Short), @enumToInt(TypeMax.Short) + @enumToInt(TypeMax.Int) => ty = Type.typeShort(), @enumToInt(TypeMax.Int) => ty = Type.typeInt(), @enumToInt(TypeMax.Long), @enumToInt(TypeMax.Long) + @enumToInt(TypeMax.Int), @enumToInt(TypeMax.Long) + @enumToInt(TypeMax.Long), @enumToInt(TypeMax.Long) + @enumToInt(TypeMax.Long) + @enumToInt(TypeMax.Int), => ty = Type.typeLong(), else => errorAtToken(getOrLast(tokens, ti), "不正な型名です"), } } return ty; } // struct-union-decl = ident? ("{" struct-members)? fn structUnionDecl(tokens: []Token, ti: *usize, typeKind: TypeKind) *Type { var tok = getOrLast(tokens, ti); // 構造体タグ名を読む var tag: ?*Token = null; if (tok.*.kind == TokenKind.TkIdent) { tag = tok; ti.* += 1; } if (!consumeTokVal(tokens, ti, "{") and tag != null) { var tyTag = findTag(tag.?); if (tyTag == null) errorAtToken(&tokens[ti.*], "Unknown struct type"); return tyTag.?; } // construct struct object var ty = Type.allocInit(typeKind); structMembers(tokens, ti, ty); ty.*.alignment = 1; if (tag != null) pushTagScope(tag.?, ty); return ty; } // struct-decl = struct-union-decl fn structDecl(tokens: []Token, ti: *usize) *Type { var ty = structUnionDecl(tokens, ti, .TyStruct); // Assign offsets within the struct tomembers var offset: usize = 0; var m = ty.*.members; while (m != null) : (m = m.?.*.next) { offset = alignTo(offset, m.?.*.ty.?.*.alignment); m.?.*.offset = offset; offset += m.?.*.ty.?.*.size; if (ty.*.alignment < m.?.*.ty.?.*.alignment) ty.*.alignment = m.?.*.ty.?.*.alignment; } ty.*.size = alignTo(offset, ty.*.alignment); return ty; } // union-decl = struct-union-decl fn unionDecl(tokens: []Token, ti: *usize) *Type { var ty = structUnionDecl(tokens, ti, .TyUnion); // If union, we don't have to assign offsets because they // are already initialized to zero. We need to compute the // alignment and the size though. var m = ty.*.members; while (m != null) : (m = m.?.*.next) { if (ty.*.alignment < m.?.*.ty.?.*.alignment) ty.*.alignment = m.?.*.ty.?.*.alignment; if (ty.*.size < m.?.*.ty.?.*.size) ty.*.size = m.?.*.ty.?.*.size; } ty.*.size = alignTo(ty.*.size, ty.*.alignment); return ty; } // struct-members = (declspec declarator ("," declarator)* ";")* fn structMembers(tokens: []Token, ti: *usize, ty: *Type) void { var head = Member.init(&tokens[ti.*]); var cur: *Member = &head; while (!consumeTokVal(tokens, ti, "}")) { var basety = declspec(tokens, ti, null); var first: bool = true; while (!consumeTokVal(tokens, ti, ";")) { if (!first) skip(tokens, ti, ","); first = false; var t = declarator(tokens, ti, basety); var m = Member.allocInit(t.*.name.?); m.ty = t; cur.*.next = m; cur = cur.*.next.?; } } ty.*.members = head.next; } // type-suffix = "(" func-params // | "[" num "]" type-suffix // | ε fn typeSuffix(tokens: []Token, ti: *usize, ty: *Type) *Type { if (consumeTokVal(tokens, ti, "(")) return funcParams(tokens, ti, ty); if (consumeTokVal(tokens, ti, "[")) { var sz = getNumber(tokens, ti); skip(tokens, ti, "]"); return Type.arrayOf(typeSuffix(tokens, ti, ty), @intCast(usize, sz)); } return ty; } // func-params = (param ("," param)*)? ")" // param = declspec declarator fn funcParams(tokens: []Token, ti: *usize, ty: *Type) *Type { var head = Type.init(TypeKind.TyInt); var cur = &head; while (!consumeTokVal(tokens, ti, ")")) { if (cur != &head) skip(tokens, ti, ","); var basety = declspec(tokens, ti, null); cur.*.next = declarator(tokens, ti, basety); cur = cur.*.next.?; } var tp = Type.funcType(ty); tp.*.params = head.next; return tp; } // expr = assign ("," expr)? pub fn expr(tokens: []Token, ti: *usize) *Node { var node = assign(tokens, ti); if (consumeTokVal(tokens, ti, ",")) return newBinary(.NdComma, node, expr(tokens, ti), &tokens[ti.* - 1]); return node; } // assign = equality ("=" assign)? pub fn assign(tokens: []Token, ti: *usize) *Node { var node = equality(tokens, ti); if (consumeTokVal(tokens, ti, "=")) { node = newBinary(.NdAssign, node, assign(tokens, ti), getOrLast(tokens, ti)); } return node; } // equality = relational ("==" relational | "!=" relational)* pub fn equality(tokens: []Token, ti: *usize) *Node { var node = relational(tokens, ti); while (ti.* < tokens.len) { const token = tokens[ti.*]; if (consumeTokVal(tokens, ti, "==")) { node = newBinary(.NdEq, node, relational(tokens, ti), getOrLast(tokens, ti)); } else if (consumeTokVal(tokens, ti, "!=")) { node = newBinary(.NdNe, node, relational(tokens, ti), getOrLast(tokens, ti)); } else { break; } } return node; } // relational = add ("<" add | "<=" add | ">" add | ">=" add)* pub fn relational(tokens: []Token, ti: *usize) *Node { var node = add(tokens, ti); while (ti.* < tokens.len) { const token = tokens[ti.*]; if (consumeTokVal(tokens, ti, "<")) { node = newBinary(.NdLt, node, add(tokens, ti), getOrLast(tokens, ti)); } else if (consumeTokVal(tokens, ti, "<=")) { node = newBinary(.NdLe, node, add(tokens, ti), getOrLast(tokens, ti)); } else if (consumeTokVal(tokens, ti, ">")) { node = newBinary(.NdLt, add(tokens, ti), node, getOrLast(tokens, ti)); } else if (consumeTokVal(tokens, ti, ">=")) { node = newBinary(.NdLe, add(tokens, ti), node, getOrLast(tokens, ti)); } else { break; } } return node; } // add = mul ("+" mul | "-" mul)* pub fn add(tokens: []Token, ti: *usize) *Node { var node = mul(tokens, ti); while (ti.* < tokens.len) { const token = tokens[ti.*]; if (consumeTokVal(tokens, ti, "+")) { node = newAdd(node, mul(tokens, ti), getOrLast(tokens, ti)); } else if (consumeTokVal(tokens, ti, "-")) { node = newSub(node, mul(tokens, ti), getOrLast(tokens, ti)); } else { break; } } return node; } // mul = cast ("*" cast | "/" cast)* pub fn mul(tokens: []Token, ti: *usize) *Node { var node = cast(tokens, ti); while (ti.* < tokens.len) { const token = tokens[ti.*]; if (streq(token.val, "*")) { ti.* += 1; node = newBinary(.NdMul, node, cast(tokens, ti), getOrLast(tokens, ti)); } else if (streq(token.val, "/")) { ti.* += 1; node = newBinary(.NdDiv, node, cast(tokens, ti), getOrLast(tokens, ti)); } else { break; } } return node; } // cast = "(" type-name ")" cast | unary fn cast(tokens: []Token, ti: *usize) *Node { if (consumeTokVal(tokens, ti, "(")) { if (isTypeName(tokens, ti)) { var start = ti.* - 1; var ty = typename(tokens, ti); skip(tokens, ti, ")"); var node = newCast(cast(tokens, ti), ty); node.*.tok = &tokens[start]; return node; } else { ti.* -= 1; } } return unary(tokens, ti); } // unary = ("+" | "-" | "*" | "&") cast // | postfix fn unary(tokens: []Token, ti: *usize) *Node { const token = tokens[ti.*]; if (consumeTokVal(tokens, ti, "+")) { return cast(tokens, ti); } if (consumeTokVal(tokens, ti, "-")) { return newUnary(.NdNeg, cast(tokens, ti), getOrLast(tokens, ti)); } if (consumeTokVal(tokens, ti, "&")) { return newUnary(.NdAddr, cast(tokens, ti), getOrLast(tokens, ti)); } if (consumeTokVal(tokens, ti, "*")) { return newUnary(.NdDeref, cast(tokens, ti), getOrLast(tokens, ti)); } return postfix(tokens, ti); } // postfix = primary ("[" expr "]" | "." ident | "->" ident)* fn postfix(tokens: []Token, ti: *usize) *Node { var node = primary(tokens, ti); while (true) { if (consumeTokVal(tokens, ti, "[")) { var start = &tokens[ti.* - 1]; var idx = expr(tokens, ti); skip(tokens, ti, "]"); node = newUnary(.NdDeref, newAdd(node, idx, start), start); continue; } if (consumeTokVal(tokens, ti, ".")) { node = structRef(tokens, ti, node); ti.* += 1; continue; } if (consumeTokVal(tokens, ti, "->")) { node = newUnary(.NdDeref, node, getOrLast(tokens, ti)); node = structRef(tokens, ti, node); ti.* += 1; continue; } return node; } } fn structRef(tokens: []Token, ti: *usize, lhs: *Node) *Node { addType(lhs); if (lhs.*.ty.?.*.kind != TypeKind.TyStruct and lhs.*.ty.?.*.kind != TypeKind.TyUnion) errorAtToken(lhs.*.tok, "構造体でもユニオンでもありません"); var node = newUnary(.NdMember, lhs, getOrLast(tokens, ti)); node.*.member = getStructMember(tokens, ti, lhs.*.ty.?); return node; } fn getStructMember(tokens: []Token, ti: *usize, ty: *Type) *Member { var m = ty.*.members; var tok = &tokens[ti.*]; while (m != null) : (m = m.?.*.next) { if (streq(m.?.*.name.*.val, tok.*.val)) return m.?; } errorAtToken(tok, "no such member"); } // primary = "(" "{" stmt+ "}" ")" // | "(" expr ")" // | "sizeof" "(" type-name ")" // | "sizeof" unary // | ident func-args? // | str // | num fn primary(tokens: []Token, ti: *usize) *Node { const start = ti.*; var token = tokens[ti.*]; if (streq(token.val, "(") and ti.* + 1 < tokens.len and streq(tokens[ti.* + 1].val, "{")) { // This is a GNU statement expression var node = Node.allocInit(.NdStmtExpr, &tokens[ti.*]); ti.* += 2; node.*.body = compoundStmt(tokens, ti).*.body; skip(tokens, ti, ")"); return node; } if (streq(token.val, "(")) { ti.* += 1; const node = expr(tokens, ti); skip(tokens, ti, ")"); return node; } var t2: usize = ti.*; var ti2 = &t2; if (consumeTokVal(tokens, ti2, "sizeof") and consumeTokVal(tokens, ti2, "(") and isTypeName(tokens, ti2)) { var ty = typename(tokens, ti2); skip(tokens, ti2, ")"); ti.* = ti2.*; const sizeStr = allocPrint0(getAllocator(), "{}", .{ty.*.size}) catch @panic("cannot allocate string for size"); return newNum(sizeStr, &tokens[start]); } if (consumeTokVal(tokens, ti, "sizeof")) { const tok = &tokens[ti.*]; var node = unary(tokens, ti); addType(node); const sizeStr = allocPrint0(getAllocator(), "{}", .{node.*.ty.?.*.size}) catch @panic("cannot allocate sizeof"); return newNum(sizeStr, tok); } if (token.kind == TokenKind.TkIdent) { // 関数呼出のとき if (ti.* + 1 < tokens.len and consumeTokVal(tokens, &(ti.* + 1), "(")) { return funcall(tokens, ti); } // 変数 var sc = findVar(token); if (sc == null or sc.?.*.variable == null) { errorAtToken(&token, "変数が未定義です"); } ti.* += 1; return newVarNode(sc.?.*.variable.?, getOrLast(tokens, ti)); } if (token.kind == TokenKind.TkStr) { const tok = getOrLast(tokens, ti); ti.* += 1; return newVarNode(newStringLiteral(tok.*.val, tok.*.ty.?), tok); } if (token.kind == TokenKind.TkNum) { ti.* += 1; return newNum(token.val, getOrLast(tokens, ti)); } errorAtToken(&token, "expected an expression"); } fn typename(tokens: []Token, ti: *usize) *Type { var ty = declspec(tokens, ti, null); return abstractDeclarator(tokens, ti, ty); } // abstract-declarator = "*"* ("(" abstract-declarator ")")? type-suffix fn abstractDeclarator(tokens: []Token, ti: *usize, basety: *Type) *Type { var ty = basety; while (consumeTokVal(tokens, ti, "*")) { ty = Type.pointerTo(ty); } if (consumeTokVal(tokens, ti, "(")) { var start = ti.*; var ignore = Type.typeInt(); _ = abstractDeclarator(tokens, ti, ignore); skip(tokens, ti, ")"); ty = typeSuffix(tokens, ti, ty); return abstractDeclarator(tokens, &start, ty); } return typeSuffix(tokens, ti, ty); } // funcall = ident "(" (assign ("," assign)*)? ")" fn funcall(tokens: []Token, ti: *usize) *Node { var start = &tokens[ti.*]; ti.* += 2; const startTi = ti.*; var sc = findVar(start.*); if (sc == null) errorAtToken(start, "implicit declaration of a function"); if (sc.?.*.variable == null or sc.?.*.variable.?.*.ty.?.*.kind != TypeKind.TyFunc) errorAtToken(start, "not a function"); var ty = sc.?.*.variable.?.*.ty; var param_ty = ty.?.*.params; var head = Node.init(.NdNum, start); var cur = &head; while (!consumeTokVal(tokens, ti, ")")) { if (startTi != ti.*) skip(tokens, ti, ","); var arg = assign(tokens, ti); addType(arg); if (param_ty != null) { if (param_ty.?.*.kind == TypeKind.TyStruct or param_ty.?.*.kind == TypeKind.TyUnion) errorAtToken(arg.*.tok, "passing struct or union is not supported yet"); arg = newCast(arg, param_ty.?); param_ty = param_ty.?.*.next; } cur.*.next = arg; cur = cur.*.next.?; } var node = Node.allocInit(.NdFuncall, start); node.*.funcname = start.*.val; node.*.func_ty = ty; node.*.ty = ty.?.*.return_ty; node.*.args = head.next; return node; } fn skip(tokens: []Token, ti: *usize, s: [:0]const u8) void { if (tokens.len <= ti.*) { errorAt(tokens.len, null, "予期せず入力が終了しました。最後に ; を入力してください。"); } var token = tokens[ti.*]; if (streq(token.val, s)) { ti.* += 1; } else { const string = allocPrint0(getAllocator(), "期待した文字列 {} がありません", .{s}) catch "期待した文字列がありません"; errorAtToken(&token, string); } } fn getNumber(tokens: []Token, ti: *usize) i64 { if (tokens.len <= ti.*) { errorAt(ti.*, null, "数値ではありません"); } var tok = tokens[ti.*]; if (tok.kind != TokenKind.TkNum) errorAtToken(&tok, "数値ではありません"); ti.* += 1; return atoi(tok.val); } fn consumeTokVal(tokens: []Token, ti: *usize, s: [:0]const u8) bool { if (tokens.len <= ti.*) { return false; } const token = tokens[ti.*]; if (streq(token.val, s)) { ti.* += 1; return true; } return false; } fn newAdd(lhs: *Node, rhs: *Node, tok: *Token) *Node { addType(lhs); addType(rhs); // num + num if (lhs.*.ty.?.*.isInteger() and rhs.*.ty.?.*.isInteger()) return newBinary(.NdAdd, lhs, rhs, tok); // ptr + ptr はエラー if (lhs.*.ty.?.*.base != null and rhs.*.ty.?.*.base != null) errorAtToken(tok, "invalid operands"); var l = lhs; var r = rhs; // num + ptrを ptr + numにそろえる if (lhs.*.ty.?.*.base == null and rhs.*.ty.?.*.base != null) { l = rhs; r = lhs; } // ptr + num const num = allocPrint0(getAllocator(), "{}", .{l.*.ty.?.*.base.?.*.size}) catch @panic("cannot allocate newNum"); r = newBinary(.NdMul, r, newLong(num, tok), tok); addType(r); var n = newBinary(.NdAdd, l, r, tok); addType(n); return n; } fn newSub(lhs: *Node, rhs: *Node, tok: *Token) *Node { addType(lhs); addType(rhs); // num - num if (lhs.*.ty.?.*.isInteger() and rhs.*.ty.?.*.isInteger()) return newBinary(.NdSub, lhs, rhs, tok); // ptr - ptr はポインタ間にいくつ要素(ポインタの指す型)があるかを返す if (lhs.*.ty.?.*.base != null and rhs.*.ty.?.*.base != null) { const node = newBinary(.NdSub, lhs, rhs, tok); node.*.ty = Type.typeInt(); const num = allocPrint0(getAllocator(), "{}", .{lhs.*.ty.?.*.base.?.*.size}) catch @panic("cannot allocate newNum"); return newBinary(.NdDiv, node, newNum(num, tok), tok); } // ptr - num if (lhs.*.ty.?.*.base != null and rhs.*.ty.?.*.base == null) { const num = allocPrint0(getAllocator(), "{}", .{lhs.*.ty.?.*.base.?.*.size}) catch @panic("cannot allocate newNum"); var r = newBinary(.NdMul, rhs, newLong(num, tok), tok); addType(r); var n = newBinary(.NdSub, lhs, r, tok); n.*.ty = lhs.*.ty; return n; } errorAtToken(tok, "Invalid operands"); } fn createParamLvars(param: ?*Type) void { if (param == null) { return; } const prm = param.?; createParamLvars(prm.*.next); _ = newLvar(prm.*.name.?.*.val, prm); } fn isTypeName(tokens: []Token, ti: *usize) bool { if (tokens.len <= ti.*) { errorAt(ti.*, null, "Unexpected EOF"); } const tok = tokens[ti.*]; var types = [_][:0]const u8{ "void", "char", "int", "short", "long", "struct", "union", "typedef" }; for (types) |t| { if (streq(tok.val, t)) { return true; } } return findTypedef(tokens, ti) != null; } fn alignTo(n: usize, a: usize) usize { return @intCast(usize, alignToI32(@intCast(i32, n), @intCast(i32, a))); }
src/parse.zig
const std = @import("std"); const ship = @import("./ship.zig"); const Hull = ship.Hull; const Pos = ship.Pos; const Computer = @import("./computer.zig").Computer; pub fn main() !void { const out = std.io.getStdOut().writer(); const inp = std.io.getStdIn().reader(); var buf: [20480]u8 = undefined; var count: u32 = 0; while (try inp.readUntilDelimiterOrEof(&buf, '\n')) |line| { count += 1; var hull = Hull.init(Hull.Color.White); defer hull.deinit(); var computer = Computer.init(true); defer computer.deinit(); computer.parse(line); while (!computer.halted) { const color = hull.get_current_color(); const input = @enumToInt(color); // std.debug.warn("SHIP enqueuing {}\n", color); computer.enqueueInput(input); computer.run(); var state: usize = 0; while (state < 2) : (state += 1) { const output = computer.getOutput(); if (output == null) { if (computer.halted) break; } else if (state == 0) { const next_color = @intToEnum(Hull.Color, @intCast(u8, output.?)); // std.debug.warn("SHIP painting {}\n", next_color); hull.paint(next_color); } else { const next_rotation = @intToEnum(Hull.Rotation, @intCast(u8, output.?)); // std.debug.warn("SHIP rotating {}\n", next_rotation); hull.move(next_rotation); } } } try out.print("Line {}, painted {} cells\n", .{ count, hull.painted }); try out.print("Bounds: {} {} - {} {}\n", .{ hull.pmin.x, hull.pmin.y, hull.pmax.x, hull.pmax.y }); var pos: Pos = undefined; pos.y = hull.pmax.y; while (pos.y >= hull.pmin.y) : (pos.y -= 1) { pos.x = hull.pmin.x; while (pos.x <= hull.pmax.x) : (pos.x += 1) { const color = hull.get_color(pos); switch (color) { Hull.Color.Black => try out.print(" ", .{}), Hull.Color.White => try out.print("\u{2588}", .{}), } } try out.print("\n", .{}); } } try out.print("Read {} lines\n", .{count}); }
2019/p11/p11b.zig
const base = @import("../base.zig"); const gen = @import("../gen.zig"); const cal_gr = @import("gregorian.zig"); const COMMON = [_:null]?base.Segment{ .{ .offset = 28 * 0, .month = 1, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 1, .month = 2, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 2, .month = 3, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 3, .month = 4, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 4, .month = 5, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 5, .month = 6, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 6, .month = 7, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 7, .month = 8, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 8, .month = 9, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 9, .month = 10, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 10, .month = 11, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 11, .month = 12, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 12, .month = 13, .day_start = 1, .day_end = 29 }, }; const LEAP = [_:null]?base.Segment{ .{ .offset = 28 * 0, .month = 1, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 1, .month = 2, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 2, .month = 3, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 3, .month = 4, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 4, .month = 5, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 5, .month = 6, .day_start = 1, .day_end = 29 }, .{ .offset = 28 * 6 + 1, .month = 7, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 7 + 1, .month = 8, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 8 + 1, .month = 9, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 9 + 1, .month = 10, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 10 + 1, .month = 11, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 11 + 1, .month = 12, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 12 + 1, .month = 13, .day_start = 1, .day_end = 29 }, }; const IC = [_:null]?base.Intercalary{ gen.initIc(.{ .month = 13, .day = 29, .name_i = 0, }, COMMON[0..COMMON.len], LEAP[0..LEAP.len]), gen.initIc(.{ .month = 6, .day = 29, .name_i = 1, }, LEAP[0..LEAP.len], LEAP[0..LEAP.len]), }; var ic_var: [IC.len:null]?base.Intercalary = IC; var common_var: [COMMON.len:null]?base.Segment = COMMON; var leap_var: [LEAP.len:null]?base.Segment = LEAP; pub const cotsworth = base.Cal{ .intercalary_list = @as([*:null]?base.Intercalary, &ic_var), .common_lookup_list = @as([*:null]?base.Segment, &common_var), .leap_lookup_list = @as([*:null]?base.Segment, &leap_var), .leap_cycle = cal_gr.gregorian.leap_cycle, .week = .{ .start = @enumToInt(base.Weekday7.Sunday), .length = gen.lastOfEnum(base.Weekday7), .continuous = false, }, .epoch_mjd = cal_gr.gregorian.epoch_mjd, .common_month_max = gen.monthMax(COMMON[0..COMMON.len]), .leap_month_max = gen.monthMax(LEAP[0..LEAP.len]), .year0 = true, };
src/cal/cotsworth.zig
const std = @import("std"); const builtin = @import("builtin"); const dbg = std.debug.print; pub const GlobError = error{ ParseError, AbsolutePathRequired, }; const MatchType = enum { // We didn't match. Mismatch, // We didn't fully match the glob, but nothing in our input caused an explicit mismatch. PartialMatch, // We got a good old match. Match, }; const Glob = struct { parts: [][]const u8, wants_directory: bool, recursive: bool, len: usize, }; const GlobMatches = struct { caller_allocator: *std.mem.Allocator, arena: std.heap.ArenaAllocator, allocator: *std.mem.Allocator, glob: Glob, buffered_matches: std.ArrayList([]const u8), dir_queue: std.ArrayList([]const u8), realpath_buf: [std.fs.MAX_PATH_BYTES]u8, path_buf: std.ArrayList(u8), pub fn init(caller_allocator: *std.mem.Allocator, glob_s: []const u8) !*GlobMatches { var self: *GlobMatches = try caller_allocator.create(GlobMatches); errdefer caller_allocator.destroy(self); self.caller_allocator = caller_allocator; self.arena = std.heap.ArenaAllocator.init(caller_allocator); self.allocator = &self.arena.allocator; self.glob = try parseGlob(self.allocator, glob_s); self.buffered_matches = std.ArrayList([]const u8).init(self.allocator); self.dir_queue = std.ArrayList([]const u8).init(self.allocator); self.realpath_buf = undefined; self.path_buf = std.ArrayList(u8).init(self.allocator); try self.dir_queue.append(try self.allocator.dupe(u8, extractBasedir(glob_s))); return self; } pub fn deinit(self: *GlobMatches) void { self.arena.deinit(); var caller_allocator = self.caller_allocator; caller_allocator.destroy(self); } pub fn next(self: *GlobMatches) !?[]const u8 { while (true) { if (self.buffered_matches.items.len > 0) { return self.buffered_matches.pop(); } // Out of results and out of places to search. End of the line. if (self.dir_queue.items.len == 0) { return null; } // Work on finding more matches var dir = self.dir_queue.pop(); var match = try matchPath(self.allocator, &self.glob, dir); if (match == MatchType.Mismatch) { continue; } if (match == MatchType.Match) { try self.buffered_matches.append(try self.allocator.dupe(u8, if (dir.len == 0) std.fs.path.sep_str else dir)); // If the glob was recursive, there might be matches further down the tree. if (!self.glob.recursive) { continue; } } var dir_handle = std.fs.openDirAbsolute(if (dir.len == 0) std.fs.path.sep_str else dir, .{ .iterate = true }) catch |err| { std.log.debug("Skipped unreadable directory {s}: {}", .{ dir, err }); continue; }; defer dir_handle.close(); var iter = dir_handle.iterate(); while (try iter.next()) |entry| { if (std.mem.eql(u8, entry.name, ".") or std.mem.eql(u8, entry.name, "..")) { continue; } self.path_buf.clearRetainingCapacity(); try self.path_buf.appendSlice(dir); try self.path_buf.append(std.fs.path.sep); try self.path_buf.appendSlice(entry.name); var is_directory = false; if (std.fs.openFileAbsolute(self.path_buf.items, .{})) |fd| { if (fd.stat()) |stat| { is_directory = (stat.kind == std.fs.Dir.Entry.Kind.Directory); fd.close(); if (stat.kind == std.fs.Dir.Entry.Kind.SymLink) { if (std.fs.realpath(self.path_buf.items, &self.realpath_buf)) |realpath| { if (std.fs.openFileAbsolute(realpath, .{})) |link_fd| { is_directory = (try link_fd.stat()).kind == std.fs.Dir.Entry.Kind.Directory; link_fd.close(); } else |err| { std.log.debug("Failure opening symlink target: {s} (symlink: {s}): {}", .{ realpath, self.path_buf.items, err }); } } else |err| { std.log.debug("Failure calling realpath on: {s}: {}", .{ self.path_buf.items, err }); } } } else |err| { std.log.debug("Could not stat path: {s}: {}", .{ self.path_buf.items, err }); } } else |err| { std.log.debug("Could not open file: {s}: {}", .{ self.path_buf.items, err }); } var entryMatch = try matchPath(self.allocator, &self.glob, self.path_buf.items); if (!is_directory and self.glob.wants_directory) { // Glob only matches directories due to its trailing slash } else if (is_directory) { try self.dir_queue.append(try self.allocator.dupe(u8, self.path_buf.items)); } else { if (entryMatch == MatchType.Match) { try self.buffered_matches.append(try self.allocator.dupe(u8, self.path_buf.items)); } } } } } }; pub fn listFiles(caller_allocator: *std.mem.Allocator, glob_s: []const u8) !*GlobMatches { if (glob_s.len > 0 and glob_s[0] != std.fs.path.sep) { return GlobError.AbsolutePathRequired; } return GlobMatches.init(caller_allocator, glob_s); } fn extractBasedir(glob_s: []const u8) []const u8 { var wildcard_pos = std.mem.indexOf(u8, glob_s, "*") orelse glob_s.len; var last_dir_pos = std.mem.lastIndexOf(u8, glob_s[0..wildcard_pos], std.fs.path.sep_str).?; return glob_s[0..last_dir_pos]; } fn parseGlob(allocator: *std.mem.Allocator, glob_s: []const u8) !Glob { var glob = std.ArrayList([]const u8).init(allocator); if (glob_s.len > 0 and glob_s[0] == '*') { // Glob always gets a leading slash try glob.append(""); } var recursive = false; var it = std.mem.split(glob_s, std.fs.path.sep_str); while (it.next()) |s| { if (s.len == 0 and glob.items.len > 0 and (glob.items[glob.items.len - 1].len == 0)) { // ignore repeated separators continue; } if (std.mem.eql(u8, s, "**")) { recursive = true; } try glob.append(try allocator.dupe(u8, s)); } var wants_directory = false; if (glob.items.len > 1 and glob.items[glob.items.len - 1].len == 0) { _ = glob.pop(); wants_directory = true; } return Glob{ .parts = glob.items, .len = glob.items.len, .wants_directory = wants_directory, .recursive = recursive }; } fn matchPath(caller_allocator: *std.mem.Allocator, glob: *Glob, path_s: []const u8) !MatchType { var arena = std.heap.ArenaAllocator.init(caller_allocator); defer arena.deinit(); var allocator = &arena.allocator; var path = try std.ArrayList([]const u8).initCapacity(allocator, 8); { var it = std.mem.split(path_s, std.fs.path.sep_str); while (it.next()) |s| { if (s.len == 0 and path.items.len > 0 and (path.items[path.items.len - 1].len == 0)) { // ignore repeated separators continue; } try path.append(s); } } // If our path had a trailing slash, ignore it unless it was the root directory. if (path.items.len > 1 and path.items[path.items.len - 1].len == 0) { _ = path.pop(); } return try matchLoop(allocator, glob, path.items); } const MatchPosition = struct { glob_idx: usize, input_idx: usize, }; fn pathComponentMatch(allocator: *std.mem.Allocator, glob: []const u8, s: []const u8) !bool { if (std.mem.eql(u8, glob, s)) { return true; } var possible_match_starts = std.ArrayList(MatchPosition).init(allocator); try possible_match_starts.append(MatchPosition{ .glob_idx = 0, .input_idx = 0, }); while (possible_match_starts.items.len > 0) { var possible_match = possible_match_starts.pop(); if (possible_match.glob_idx == glob.len or possible_match.input_idx == s.len) { // We've run out of glob or we've run out of letters. Either is no match. continue; } if ((possible_match.glob_idx + 1) == glob.len and glob[possible_match.glob_idx] == '*') { // Glob ends in '*', which matches all remaining input. Instant win! return true; } else if (glob[possible_match.glob_idx] == '*') { // Hit a wildcard. Scan forward to find potential positions of remaining matches // and queue them up. var next_required_char = glob[possible_match.glob_idx + 1]; if (next_required_char == '*') { return GlobError.ParseError; } var possible_start_idx = possible_match.input_idx; while (possible_start_idx < s.len) { if (s[possible_start_idx] == next_required_char) { try possible_match_starts.append(MatchPosition{ .glob_idx = possible_match.glob_idx + 1, .input_idx = possible_start_idx, }); } possible_start_idx += 1; } } else { // Non-wildcard if (glob[possible_match.glob_idx] != s[possible_match.input_idx]) { // Mismatch on literal continue; } if ((possible_match.glob_idx + 1) == glob.len) { if ((possible_match.input_idx + 1) == s.len) { // We're out of glob and we're out of input. That's a win. return true; } else { continue; } } else { // Consume one char from our glob; one from our input try possible_match_starts.append(MatchPosition{ .glob_idx = possible_match.glob_idx + 1, .input_idx = possible_match.input_idx + 1, }); } } } return false; } fn matchLoop(allocator: *std.mem.Allocator, glob: *Glob, path: [][]const u8) !MatchType { var candidates = std.ArrayList(MatchPosition).init(allocator); try candidates.append(MatchPosition{ .glob_idx = 0, .input_idx = 0, }); var candidate_idx: usize = 0; var found_partial_match = false; while (candidates.items.len > 0) { var candidate = candidates.pop(); var glob_idx = candidate.glob_idx; var path_idx = candidate.input_idx; while (true) { if (glob_idx == glob.len) { if (path_idx == path.len) { return MatchType.Match; } break; } if (path_idx == path.len) { // Ran out of input before we ran out of glob. found_partial_match = true; break; } if (std.mem.eql(u8, glob.parts[glob_idx], "*")) { glob_idx += 1; path_idx += 1; } else if (std.mem.eql(u8, glob.parts[glob_idx], "**")) { found_partial_match = true; if ((glob_idx + 1) == glob.len) { // Trailing glob is an instant win return MatchType.Match; } { var test_idx = path_idx; while (test_idx < path.len) { try candidates.append(MatchPosition{ .glob_idx = glob_idx + 1, .input_idx = test_idx }); test_idx += 1; } } break; } else if (try pathComponentMatch(allocator, glob.parts[glob_idx], path[path_idx])) { glob_idx += 1; path_idx += 1; } else { break; } } } if (found_partial_match) { return MatchType.PartialMatch; } else { return MatchType.Mismatch; } } //// Testing const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "pathComponentMatch" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; try expect(try pathComponentMatch(allocator, "test", "test")); try expect(try pathComponentMatch(allocator, "*est", "test")); try expect(try pathComponentMatch(allocator, "*es*", "test")); try expect(try pathComponentMatch(allocator, "h*l*o", "hello")); try expect(try pathComponentMatch(allocator, "*", "whatever")); try expect(!try pathComponentMatch(allocator, "mismatch", "test")); try expect(!try pathComponentMatch(allocator, "", "whatever")); } fn testMatchPath(glob_s: []const u8, path_s: []const u8) !MatchType { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; if (std.fs.path.sep != '/') { var adjusted = try allocator.dupe(path_s); std.mem.replace(u8, path_s, "/", path.sep_str, adjusted); path_s = adjusted; } return try matchPath(allocator, &try parseGlob(allocator, glob_s), path_s); } test "matchPath full matches" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; try expectEqual(MatchType.Match, try testMatchPath("*/**/pants", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("*/*/foo/*", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/", "/")); try expectEqual(MatchType.Match, try testMatchPath("/**/**/*/hello/*", "/home/mst/foo/pants/some/thing/else/foopants/mst/and/more/hello/there")); try expectEqual(MatchType.Match, try testMatchPath("/**/pants", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home", "/home")); try expectEqual(MatchType.Match, try testMatchPath("/home/*", "/home/mst")); try expectEqual(MatchType.Match, try testMatchPath("/home/**/pants", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/**/pants/**/mst", "/home/mst/foo/pants/some/thing/else/mst")); try expectEqual(MatchType.Match, try testMatchPath("/home/**/pants/**/mst/**/*/more/hello", "/home/mst/foo/pants/some/thing/else/foopants/mst/and/more/hello")); try expectEqual(MatchType.Match, try testMatchPath("/home/**/pants/**/mst/**/hello", "/home/mst/foo/pants/some/thing/else/foopants/mst/and/more/hello")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/*", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/*ant*", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/foo/pants", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/*s", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/p*", "/home/mst/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/*.js", "/home/mst/foo/foo.js")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/*/*.git", "/home/mst/foo/hello.git")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/p*nts", "/home/mst/pointpants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/**", "/home/mst/pretty/much/anything")); try expectEqual(MatchType.Match, try testMatchPath("/home/foo/*/qux", "/home/foo/bar/qux")); try expectEqual(MatchType.Match, try testMatchPath("**/pants", "/any/thing/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/**/pants", "/any/thing/foo/pants")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/**", "/home/mst/subdir")); try expectEqual(MatchType.Match, try testMatchPath("/home/mst/projects/foo/bar/*/*.md", "/home/mst/projects/foo/bar/something/somefile.md")); } test "matchPath mismatches" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; try expectEqual(MatchType.Mismatch, try testMatchPath("/home/mst/**/pants", "/wrong/start/foo/pants")); try expectEqual(MatchType.Mismatch, try testMatchPath("/home/mst/foo/pants", "/home/mst/foo/wrong")); try expectEqual(MatchType.Mismatch, try testMatchPath("/home/mst/foo/pants", "/home/mst/foo/pants2")); } test "matchPath partial matches" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/foo/bar/qux", "/home/foo")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/*", "/home")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/**/pants", "/home/mst/foo/wrong")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/**/pants/**/mst", "/home/mst/foo/pants/some/thing/else/foopants/wrong")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/mst/**", "/home/mst")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/home/foo/*/qux", "/home/foo/bar")); try expectEqual(MatchType.PartialMatch, try testMatchPath("/*", "/")); } fn countMatches(glob_parts: [][]const u8) !usize { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var list = try listFiles(std.testing.allocator, try std.fs.path.join(allocator, glob_parts)); defer list.deinit(); var count: usize = 0; while (try list.next()) |entry| { count += 1; } return count; } test "iterator" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; var test_dir_path: []const u8 = try std.fs.path.join(allocator, &[_][]const u8{ std.fs.path.dirname(@src().file).?, "..", "test_files" }); var testdir = try std.fs.openDirAbsolute(test_dir_path, .{}); defer testdir.close(); test_dir_path = try testdir.realpathAlloc(allocator, "."); try expectEqual(@intCast(usize, 4), try countMatches(&[_][]const u8{ test_dir_path, "**", "*.txt" })); try expectEqual(@intCast(usize, 10), try countMatches(&[_][]const u8{ test_dir_path, "**", "*" })); try expectEqual(@intCast(usize, 1), try countMatches(&[_][]const u8{ test_dir_path, "**", "*hidde*" })); try expectEqual(@intCast(usize, 4), try countMatches(&[_][]const u8{ test_dir_path, "**", "*", "" })); try expectEqual(@intCast(usize, 0), try countMatches(&[_][]const u8{ test_dir_path, "*", "willnevermatch", "**" })); }
src/globby.zig
const std = @import("std"); /// rgb color tuple with 8 bit color values. pub const RGB = packed struct { r: u8, g: u8, b: u8, }; pub const Header = packed struct { id: u8 = 0x0A, version: u8, compression: u8, bpp: u8, xmin: u16, ymin: u16, xmax: u16, ymax: u16, horizontalDPI: u16, verticalDPI: u16, builtinPalette: [16 * 3]u8, _reserved0: u8 = 0, planes: u8, stride: u16, paletteInformation: u16, screenWidth: u16, screenHeight: u16, var padding: [54]u8 = undefined; comptime { std.debug.assert(@sizeOf(@This()) == 74); } }; fn SubImage(comptime Pixel: type) type { return struct { const Self = @This(); const PaletteType = switch (Pixel) { u1 => [2]RGB, u4 => [16]RGB, u8 => [256]RGB, RGB => void, else => @compileError(@typeName(Pixel) ++ " not supported yet!"), }; allocator: std.mem.Allocator, pixels: []Pixel, width: usize, height: usize, palette: ?*PaletteType, pub fn initLinear(allocator: std.mem.Allocator, header: Header, file: *std.fs.File, stream: anytype) !Self { const width = @as(usize, header.xmax - header.xmin + 1); const height = @as(usize, header.ymax - header.ymin + 1); var img = Self{ .allocator = allocator, .pixels = try allocator.alloc(Pixel, width * height), .width = width, .height = height, .palette = null, }; errdefer img.deinit(); var decoder = RLEDecoder.init(stream); var y: usize = 0; while (y < img.height) : (y += 1) { var offset: usize = 0; var x: usize = 0; // read all pixels from the current row while (offset < header.stride and x < img.width) : (offset += 1) { const byte = try decoder.readByte(); switch (Pixel) { u1 => {}, u4 => { img.pixels[y * img.width + x + 0] = @truncate(u4, byte); x += 1; if (x < img.width - 1) { img.pixels[y * img.width + x + 1] = @truncate(u4, byte >> 4); x += 1; } }, u8 => { img.pixels[y * img.width + x] = byte; x += 1; }, RGB => {}, else => @compileError(@typeName(Pixel) ++ " not supported yet!"), } } // discard the rest of the bytes in the current row while (offset < header.stride) : (offset += 1) { _ = try decoder.readByte(); } } try decoder.finish(); if (Pixel != RGB) { var pal = try allocator.create(PaletteType); errdefer allocator.destroy(pal); var i: usize = 0; while (i < std.math.min(pal.len, header.builtinPalette.len / 3)) : (i += 1) { pal[i].r = header.builtinPalette[3 * i + 0]; pal[i].g = header.builtinPalette[3 * i + 1]; pal[i].b = header.builtinPalette[3 * i + 2]; } if (Pixel == u8) { try file.seekFromEnd(-769); if ((try stream.readByte()) != 0x0C) return error.MissingPalette; for (pal) |*c| { c.r = try stream.readByte(); c.g = try stream.readByte(); c.b = try stream.readByte(); } } img.palette = pal; } return img; } pub fn deinit(self: Self) void { if (self.palette) |pal| { self.allocator.destroy(pal); } self.allocator.free(self.pixels); } }; } pub const Format = enum { bpp1, bpp4, bpp8, bpp24, }; pub const Image = union(Format) { bpp1: SubImage(u1), bpp4: SubImage(u4), bpp8: SubImage(u8), bpp24: SubImage(RGB), pub fn deinit(image: Image) void { switch (image) { .bpp1 => |img| img.deinit(), .bpp4 => |img| img.deinit(), .bpp8 => |img| img.deinit(), .bpp24 => |img| img.deinit(), } } }; pub fn load(allocator: std.mem.Allocator, file: *std.fs.File) !Image { var stream = file.reader(); var header: Header = undefined; try stream.readNoEof(std.mem.asBytes(&header)); try stream.readNoEof(&Header.padding); if (header.id != 0x0A) return error.InvalidFileFormat; if (header.planes != 1) return error.UnsupportedFormat; var img: Image = undefined; switch (header.bpp) { 1 => img = Image{ .bpp1 = try SubImage(u1).initLinear(allocator, header, file, stream), }, 4 => img = Image{ .bpp4 = try SubImage(u4).initLinear(allocator, header, file, stream), }, 8 => img = Image{ .bpp8 = try SubImage(u8).initLinear(allocator, header, file, stream), }, 24 => img = Image{ .bpp24 = try SubImage(RGB).initLinear(allocator, header, file, stream), }, else => return error.UnsupportedFormat, } return img; } const RLEDecoder = struct { const Run = struct { value: u8, remaining: usize, }; stream: std.fs.File.Reader, currentRun: ?Run, fn init(stream: std.fs.File.Reader) RLEDecoder { return RLEDecoder{ .stream = stream, .currentRun = null, }; } fn readByte(self: *RLEDecoder) !u8 { if (self.currentRun) |*run| { var result = run.value; run.remaining -= 1; if (run.remaining == 0) self.currentRun = null; return result; } else { while (true) { var byte = try self.stream.readByte(); if (byte == 0xC0) // skip over "zero length runs" continue; if ((byte & 0xC0) == 0xC0) { const len = byte & 0x3F; std.debug.assert(len > 0); const result = try self.stream.readByte(); if (len > 1) { // we only need to store a run in the decoder if it is longer than 1 self.currentRun = .{ .value = result, .remaining = len - 1, }; } return result; } else { return byte; } } } } fn finish(decoder: RLEDecoder) !void { if (decoder.currentRun != null) return error.RLEStreamIncomplete; } }; test "PCX bpp1 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp1.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp1); std.debug.assert(img.bpp1.width == 27); std.debug.assert(img.bpp1.height == 27); std.debug.assert(img.bpp1.palette != null); std.debug.assert(img.bpp1.palette.?.len == 2); } test "PCX bpp4 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp4.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp4); std.debug.assert(img.bpp4.width == 27); std.debug.assert(img.bpp4.height == 27); std.debug.assert(img.bpp4.palette != null); std.debug.assert(img.bpp4.palette.?.len == 16); } test "PCX bpp8 (linear)" { var file = try std.fs.cwd().openRead("test/test-bpp8.pcx"); defer file.close(); var img = try load(std.debug.global_allocator, &file); errdefer img.deinit(); std.debug.assert(img == .bpp8); std.debug.assert(img.bpp8.width == 27); std.debug.assert(img.bpp8.height == 27); std.debug.assert(img.bpp8.palette != null); std.debug.assert(img.bpp8.palette.?.len == 256); } // TODO: reimplement as soon as planar mode is implemented // test "PCX bpp24 (planar)" { // var file = try std.fs.cwd().openRead("test/test-bpp24.pcx"); // defer file.close(); // var img = try load(std.debug.global_allocator, &file); // errdefer img.deinit(); // std.debug.assert(img == .bpp24); // std.debug.assert(img.bpp24.width == 27); // std.debug.assert(img.bpp24.height == 27); // std.debug.assert(img.bpp24.palette == null); // }
tools/bit-loader/pcx.zig
const std = @import("std"); const print = std.debug.print; const List = std.ArrayList; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day04.txt"); pub fn main() !void { var lines = try util.toStrSlice(data, "\n"); var numbers = try util.toIntSlice(u8, lines[0], ","); var boards = List(?[5][5]?u8).init(gpa); defer boards.deinit(); var board: [5][5]?u8 = undefined; for (lines[1..]) |line, i| { var row = try util.toStrSlice(line, " "); var j: usize = 0; for (row) |num| { if (num.len == 0) continue; board[i % 5][j] = try std.fmt.parseInt(u8, num, 10); j += 1; } if (i % 5 == 4) { try boards.append(board); } } var num_winners: usize = 0; for (numbers) |num| { for (boards.items) |*b, i| { if (b.* == null) continue; markBoard(&b.*.?, num); } for (boards.items) |*b, i| { if (b.* == null) continue; if (checkBoard(b.*.?)) { num_winners += 1; if (num_winners == 1) print("{d}\n", .{sumBoard(b.*.?) * num}); if (num_winners == boards.items.len) print("{d}\n", .{sumBoard(b.*.?) * num}); b.* = null; } } } } fn markBoard(board: *[5][5]?u8, num: u8) void { for (board) |*row| { for (row) |*n| { if (n.* == num) n.* = null; } } } fn checkBoard(board: [5][5]?u8) bool { // check rows for (board) |row| { var all = true; for (row) |n| { if (n != null) all = false; } if (all) return true; } // check cols var i: usize = 0; while (i < board.len) : (i += 1) { var j: usize = 0; var all = true; while (j < board[i].len) : (j += 1) { if (board[j][i] != null) all = false; } if (all) return true; } return false; } fn sumBoard(board: [5][5]?u8) u32 { var sum: u32 = 0; for (board) |row| { for (row) |n| { if (n) |num| sum += num; } } return sum; }
2021/src/day04.zig
const std = @import("std"); const memcpy = std.zig.c_builtins.__builtin_memcpy; const dlsym = std.c.dlsym; const coz_counter_t = extern struct { count: usize, backoff: usize, }; const coz_get_counter_t = ?fn (c_int, [*c]const u8) callconv(.C) [*c]coz_counter_t; fn _call_coz_get_counter(arg_type_1: c_int, arg_name: [*c]const u8) callconv(.C) [*c]coz_counter_t { var type_1 = arg_type_1; var name = arg_name; const _initialized = struct { var static: u8 = 0; }; const @"fn" = struct { var static: coz_get_counter_t = @import("std").mem.zeroes(coz_get_counter_t); }; if (!(_initialized.static != 0)) { var p: ?*c_void = dlsym(@intToPtr(?*c_void, @as(c_int, 0)), "_coz_get_counter"); _ = memcpy(@ptrCast(?*c_void, &@"fn".static), @ptrCast(?*const c_void, &p), @sizeOf(?*c_void)); _initialized.static = 1; } if (@"fn".static != null) return @"fn".static.?(type_1, name) else return null; return null; } const coz_get_arrivals_t = ?fn (...) callconv(.C) [*c]usize; fn _call_coz_get_local_arrivals() callconv(.C) [*c]usize { const _initialized = struct { var static: u8 = 0; }; const @"fn" = struct { var static: coz_get_arrivals_t = @import("std").mem.zeroes(coz_get_arrivals_t); }; if (!(_initialized.static != 0)) { var p: ?*c_void = dlsym(@intToPtr(?*c_void, @as(c_int, 0)), "_coz_get_local_arrivals"); _ = memcpy(@ptrCast(?*c_void, &@"fn".static), @ptrCast(?*const c_void, &p), @sizeOf(?*c_void)); _initialized.static = 1; } if (@"fn".static != null) return @"fn".static.?() else return null; return null; } fn _call_coz_get_global_arrivals() callconv(.C) [*c]usize { const _initialized = struct { var static: u8 = 0; }; const @"fn" = struct { var static: coz_get_arrivals_t = @import("std").mem.zeroes(coz_get_arrivals_t); }; if (!(_initialized.static != 0)) { var p: ?*c_void = dlsym(@intToPtr(?*c_void, @as(c_int, 0)), "_coz_get_global_arrivals"); _ = memcpy(@ptrCast(?*c_void, &@"fn".static), @ptrCast(?*const c_void, &p), @sizeOf(?*c_void)); _initialized.static = 1; } if (@"fn".static != null) return @"fn".static.?() else return null; return null; } fn _coz_wrapper_increment_counter(counter_type: c_int, name: [:0]const u8) void { const _initialized = struct { var static: u8 = 0; }; const _counter = struct { var static: [*c]coz_counter_t = null; }; if (!(_initialized.static != 0)) { _counter.static = _call_coz_get_counter(counter_type, name); _initialized.static = 1; } if (_counter.static != null) { _ = @atomicRmw(@TypeOf(_counter.static.*.count), &_counter.static.*.count, .Add, 1, .Monotonic); } } /// Specify a progress point for throughput profiling pub fn progress(name: [:0]const u8) void { _coz_wrapper_increment_counter(1, name); } /// Specify the begin of a transaction for latency profiling pub fn begin(name: [:0]const u8) void { _coz_wrapper_increment_counter(2, name); } /// Specify the end of a transaction for latency profiling pub fn end(name: [:0]const u8) void { _coz_wrapper_increment_counter(3, name); }
bridge/coz.zig
// This implementation supports the page based devices. const std = @import("std"); const sys = @import("../sys.zig"); const Sha256 = std.crypto.hash.sha2.Sha256; // For now, the sizes are all hard coded. pub const page_size = @as(usize, sys.flash.page_size); pub const page_shift = std.math.log2_int(usize, page_size); // The largest number of pages the image portion of the data can be. pub const max_pages = sys.flash.max_pages; // The largest number of work steps for a given phase of work. The // latest amount of work is the swap, which has two operations per // page of data. const max_work = 2 * sys.flash.max_pages; // The number of hash bytes to use. This value is a tradeoff. // Collisions will require all of the data to be recomputed. Only // pages that will occupy the same location are of concern, which // means adjacent pages in slot 0, and page-n and page-n+1 in slot 0 // compared with page-n in slot 1. This means for a 32-bit hash (4 // bytes), we would expect a collision about every '2^32/(3*max_page)' // erase operations. This is better than 1 in a million, which means // it is rare, but probably will happen at some point. pub const hash_bytes = 4; const Hash = [hash_bytes]u8; // This is the state for a flash operation. This contains all of the // buffers for our data, along with the work and state of this work. // On-target, there will be generally one of these, as multi-image // updates will happen sequentially, and will use the same state. pub const State = struct { const Self = @This(); // A temporary buffer, used to read data. tmp: [page_size]u8 = undefined, tmp2: [page_size]u8 = undefined, // The sizes of the pertinent images. sizes: [2]usize, // The flash areas themselves. areas: [2]*sys.flash.FlashArea, // These are all of the hashes. hashes: [2][max_pages]Hash = undefined, // This is a prefix, used before each hash operation. If we // perform the hashes and have a collision, we can start over with // a different prefix. prefix: [4]u8, // The work itself. The first index is the phase, and the second // is the work itself. work: [2][max_work]Work = undefined, work_len: [2]usize = .{ 0, 0 }, // Initialze this state. The sim must outlive this struct. The // prefix is used as a seed to the hash function. If the // operations detect a hash collision, this can be restarted with // a different prefix, which will possibly remove the collision. pub fn init(sim: *sys.flash.SimFlash, sizeA: usize, sizeB: usize, prefix: u32) !State { var a = try sim.open(0); // TODO: Better numbers. var b = try sim.open(1); var bprefix: [4]u8 = undefined; std.mem.copy(u8, bprefix[0..], std.mem.asBytes(&prefix)); return State{ .areas = [2]*sys.flash.FlashArea{ a, b }, .sizes = [2]usize{ sizeA, sizeB }, .prefix = bprefix, }; } // On an initial run, compute the hashes. The hash of the last // possibly partial page is only partially computed. pub fn computeHashes(self: *Self) !void { try self.oneHash(0); try self.oneHash(1); } fn oneHash(self: *Self, index: usize) !void { var pos: usize = 0; var page: usize = 0; while (pos < self.sizes[index]) : (pos += page_size) { var hh = Sha256.init(.{}); hh.update(self.prefix[0..]); var count: usize = page_size; if (count > self.sizes[index] - pos) count = self.sizes[index] - pos; try self.areas[index].read(pos, self.tmp[0..count]); hh.update(self.tmp[0..count]); var hash: [32]u8 = undefined; // TODO: magic number hh.final(hash[0..]); std.mem.copy(u8, self.hashes[index][page][0..], hash[0..hash_bytes]); // std.log.info("hash: {} 0x{any}", .{ page, self.hashes[index][page] }); page += 1; } } // Compute the work for sliding slot 0 down by one. pub fn workSlide0(self: *Self) !void { const bound = self.calcBound(0); // pos is the destination of each page. var pos: usize = bound.last; while (pos > 0) : (pos -= 1) { var size = page_size; if (pos == bound.last) size = bound.partial; if (pos < bound.last and try self.validateSame(.{ 0, 0 }, .{ pos - 1, pos }, size)) continue; try self.workPush(0, .{ .src_slot = 0, .dest_slot = 0, .size = @intCast(u16, size), .src_page = pos - 1, .dest_page = pos, .hash = self.hashes[0][pos - 1], }); } } // Compute the work for swapping the two images. For a layout // such as this: // slot 0 | slot 1 // X | A1 // A0 | B1 // B0 | C1 // C0 | D1 // we want to move A1 to slot 0, and A0 to slot 1. This continues // stopping either the left or right movement when we have // exceeded the size for that side. pub fn workSwap(self: *Self) !void { const bound0 = self.calcBound(0); const bound1 = self.calcBound(1); std.log.info("---- Phase 2 ----", .{}); // At a given pos, we move slot 1,pos to slot 0,pos, and slot // 0,pos+1 to slot1,pos. var pos: usize = 0; while (pos < bound0.last or pos < bound1.last) : (pos += 1) { // Move slot 1 to 0. if (pos < bound1.last) { var size = page_size; if (pos == bound1.last) size = bound1.partial; if (pos < bound0.last and try self.validateSame(.{ 1, 0 }, .{ pos, pos }, size)) continue; try self.workPush(1, .{ .src_slot = 1, .dest_slot = 0, .size = @intCast(u16, size), .src_page = pos, .dest_page = pos, .hash = self.hashes[1][pos], }); } // Move slot 0 to 1. if (pos < bound0.last) { var size = page_size; if (pos == bound0.last) size = bound0.partial; if (pos < bound1.last and try self.validateSame(.{ 0, 1 }, .{ pos + 1, pos }, size)) continue; try self.workPush(1, .{ .src_slot = 0, .dest_slot = 1, .size = @intCast(u16, size), .src_page = pos + 1, .dest_page = pos, .hash = self.hashes[0][pos], }); } } } // Perform the work. pub fn performWork(self: *Self) !void { std.log.info("---- Running work ----", .{}); for (self.work) |work, i| { for (work[0..self.work_len[i]]) |*item| { // std.log.info("do: {any}", .{item}); try self.areas[item.dest_slot].erase(item.dest_page << page_shift, page_size); try self.areas[item.src_slot].read(item.src_page << page_shift, self.tmp[0..]); try self.areas[item.dest_slot].write(item.dest_page << page_shift, self.tmp[0..]); } } } fn workPush(self: *Self, phase: usize, work: Work) !void { if (self.work_len[phase] >= self.work[phase].len) return error.WorkOverflow; // std.log.info("push work {}: {any}", .{ self.work_len[phase], work }); self.work[phase][self.work_len[phase]] = work; self.work_len[phase] += 1; } const Bound = struct { // The last page to be moved in the given region. last: usize, // The number of bytes in the last page. Will be page_size if // this image is a multiple of the page size. partial: usize, }; fn calcBound(self: *const Self, slot: usize) Bound { const last = (self.sizes[slot] + page_size - 1) >> page_shift; var partial = self.sizes[slot] & (page_size - 1); if (partial == 0) partial = page_size; std.log.info("slot:{}, bytes:{}, last:{}, partial:{}", .{ slot, self.sizes[slot], last, partial, }); return Bound{ .last = last, .partial = partial, }; } // Ensure that two pages that have the same hash are actually the // same. Returns error.HashCollision if the differ, which will // result in the top level code retrying with a different prefix. fn validateSame(self: *Self, slots: [2]u8, pages: [2]usize, len: usize) !bool { // std.log.info("Compare: {any} with {any} {any} {any}", .{ // slots, pages, self.hashes[slots[0]][pages[0]], // self.hashes[slots[1]][pages[1]], // }); if (std.mem.eql( u8, self.hashes[slots[0]][pages[0]][0..], self.hashes[slots[1]][pages[1]][0..], )) { // If the hashes match, compare the page contents. _ = len; unreachable; } else { return false; } } // Return an iterator over all of the hashes. pub fn iterHashes(self: *Self) HashIter { return .{ .state = self, .phase = 0, .pos = 0, }; } // For testing, set 'sizes' and fill in some hashes for the given // image "sizes". pub fn fakeHashes(self: *Self, sizes: [2]usize) !void { self.sizes = sizes; self.prefix = [4]u8{ 1, 2, 3, 4 }; var slot: usize = 0; while (slot < 2) : (slot += 1) { var pos: usize = 0; var page: usize = 0; while (pos < self.sizes[slot]) : (pos += page_size) { var hh = Sha256.init(.{}); hh.update(self.prefix[0..]); const num: usize = slot * max_pages * page_size + pos; hh.update(std.mem.asBytes(&num)); var hash: [32]u8 = undefined; // TODO: magic number hh.final(hash[0..]); std.mem.copy(u8, self.hashes[slot][page][0..], hash[0..hash_bytes]); // std.log.warn("hash: {} 0x{any}", .{ page, self.hashes[slot][page] }); page += 1; } } } // For testing, compare the generated sizes and hashes to make // sure they have been recovered correctly. pub fn checkFakeHashes(self: *Self, sizes: [2]usize) !void { try std.testing.expectEqualSlices(usize, sizes[0..], self.sizes[0..]); try std.testing.expectEqual([4]u8{ 1, 2, 3, 4 }, self.prefix); var slot: usize = 0; while (slot < 2) : (slot += 1) { var pos: usize = 0; var page: usize = 0; while (pos < self.sizes[slot]) : (pos += page_size) { var hh = Sha256.init(.{}); hh.update(self.prefix[0..]); const num: usize = slot * max_pages * page_size + pos; hh.update(std.mem.asBytes(&num)); var hash: [32]u8 = undefined; hh.final(hash[0..]); // std.log.warn("Checking: {} in slot {}", .{ page, slot }); try std.testing.expectEqualSlices(u8, hash[0..hash_bytes], self.hashes[slot][page][0..]); page += 1; } } } }; pub const HashIter = struct { const Self = @This(); state: *State, phase: usize, pos: usize, pub fn next(self: *Self) ?*[hash_bytes]u8 { while (true) { if (self.phase >= 2) return null; if (self.pos >= asPages(self.state.sizes[self.phase])) { self.pos = 0; self.phase += 1; } else { break; } } const result = &self.state.hashes[self.phase][self.pos]; //std.log.info("returning: {any} (phase:{}, pos:{}, sizes:{any})", .{ // result.*, // self.phase, // self.pos, // self.state.sizes[self.phase], //}); self.pos += 1; return result; } }; fn asPages(value: usize) usize { return (value + page_size - 1) >> page_shift; } // Calculate the has of a given block of data, returning the shortened // version. pub fn calcHash(data: []const u8) [hash_bytes]u8 { var hh = Sha256.init(.{}); hh.update(data); var hash: [32]u8 = undefined; hh.final(hash[0..]); var result: [hash_bytes]u8 = undefined; std.mem.copy(u8, result[0..], hash[0..4]); return result; } // A single unit of work. // Zig theoretically will reorder structures for better padding, but // this doesn't appear to be happening, so this is ordered to make it // compact. // This describes the move of one page of data. It describes an erase // of the destination, and a copy of the data from the source into // that dest. The hash should match the data in the src slot. // size will normally be page_size, except for the final page, where // it may be smaller, as we don't has data past the extent of the real // image. const Work = struct { src_slot: u8, dest_slot: u8, size: u16, src_page: usize, dest_page: usize, hash: Hash, };
src/sim/swap-hash.zig
const std = @import("std"); const string = []const u8; const input = @embedFile("../input/day10.txt"); pub fn main() !void { // part 1 { var iter = std.mem.split(u8, input, "\n"); var sum: u32 = 0; while (iter.next()) |line| { if (line.len == 0) continue; Parser.parseOnly(line) catch |err| switch (err) { error.IllegalParen => sum += 3, error.IllegalSquarBracket => sum += 57, error.IllegalCurlyBracket => sum += 1197, error.IllegalAngleBracket => sum += 25137, }; } std.debug.print("{d}\n", .{sum}); } // part 2 { var iter = std.mem.split(u8, input, "\n"); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var all_scores = std.ArrayList(u64).init(alloc); defer all_scores.deinit(); while (iter.next()) |line| { if (line.len == 0) continue; const completion = Parser.parse(alloc, line) catch |err| switch (err) { error.IllegalParen => "", error.IllegalSquarBracket => "", error.IllegalCurlyBracket => "", error.IllegalAngleBracket => "", error.OutOfMemory => return err, }; if (completion.len == 0) { continue; } var score: u64 = 0; for (completion) |c| { score *= 5; score += switch (c) { ')' => @as(u8, 1), ']' => @as(u8, 2), '}' => @as(u8, 3), '>' => @as(u8, 4), else => unreachable, }; } try all_scores.append(score); } var the_scores = all_scores.toOwnedSlice(); const asc = comptime std.sort.asc(u64); std.sort.sort(u64, the_scores, {}, asc); const middle_score = the_scores[(the_scores.len - 1) / 2]; std.debug.print("{d}\n", .{middle_score}); } } const Parser = struct { buf: string, index: usize, alloc: *std.mem.Allocator, tryBail: bool, bail: bool, const Error = error{ IllegalParen, IllegalSquarBracket, IllegalCurlyBracket, IllegalAngleBracket, }; const FullError = std.mem.Allocator.Error || Error; pub fn parseOnly(src: string) Error!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var p = Parser{ .buf = src, .index = 0, .alloc = alloc, .tryBail = false, .bail = false, }; _ = p.do(null) catch |err| switch (err) { error.OutOfMemory => unreachable, else => |es| return es, }; return; } pub fn parse(alloc: *std.mem.Allocator, src: string) FullError!string { var p = Parser{ .buf = src, .index = 0, .alloc = alloc, .tryBail = true, .bail = false, }; return try p.do(null); } fn do(self: *Parser, start: ?u8) FullError!string { const tok = start orelse self.eat(); var completion = try switch (tok) { '(' => self.doChunk(')'), '[' => self.doChunk(']'), '{' => self.doChunk('}'), '<' => self.doChunk('>'), else => @panic(""), }; if (self.tryBail) { if (self.bail) { return try std.mem.concat(self.alloc, u8, &[_]string{ completion, &[_]u8{closers[std.mem.indexOfScalar(u8, openers, tok).?]} }); } } return completion; } fn doChunk(self: *Parser, end: u8) FullError!string { while (true) { if (self.index == self.buf.len) { // incomplete sequence self.bail = true; return ""; } const next = self.eat(); if (next == end) return ""; if (std.mem.indexOfScalar(u8, openers, next)) |_| { const comp = try self.do(next); if (self.bail) return comp; continue; } if (std.mem.indexOfScalar(u8, closers, next)) |_| { return switch (next) { ')' => error.IllegalParen, ']' => error.IllegalSquarBracket, '}' => error.IllegalCurlyBracket, '>' => error.IllegalAngleBracket, else => unreachable, }; } @panic(""); } return ""; } const openers = "([{<"; const closers = ")]}>"; fn peek(self: Parser) u8 { return self.buf[self.index]; } fn eat(self: *Parser) u8 { const r = self.peek(); self.index += 1; return r; } };
src/day10.zig
const std = @import("std"); const LinearFifo = std.fifo.LinearFifo; const Case = std.fmt.Case; const testing = std.testing; // https://www.oilshell.org/release/latest/doc/qsn.html const Decoder = struct { // This stores at most one UTF-8-encoded character which will be returned in the future. const Pending = LinearFifo(u8, .{ .Static = 4 }); pending: Pending, state: enum { start, inner, escape, unicode, unicode_digits, hex, } = .start, pub const Error = error{ UnexpectedEndOfStream, StartConditionFailed, UnexpectedEscape, UnicodeStartConditionError, CodepointTooLong, EmptyCodepoint, InvalidUnicodeDigit, InvalidHexDigit, }; const Self = @This(); pub fn init() Self { return Self{ .pending = Pending.init() }; } pub fn next(self: *Self, reader: anytype) !?u8 { if (self.pending.count != 0) { return self.pending.readItem().?; } var offset: usize = 0; // Hexadecimal escapes accept exactly 2 digits. var hex_buffer: u8 = 0; // QSN Unicode codepoints accept at most 6 hexadecimal digits (24 bits). var unicode_buffer: u24 = 0; while (true) { const c = reader.readByte() catch |err| switch (err) { error.EndOfStream => { return Error.UnexpectedEndOfStream; }, else => { return err; }, }; switch (self.state) { .start => switch (c) { '\'' => { self.state = .inner; }, else => { return Error.StartConditionFailed; }, }, .inner => switch (c) { '\\' => { self.state = .escape; }, '\'' => { return null; }, else => { return c; }, }, .escape => { switch (c) { 'x' => { self.state = .hex; }, 'u' => { self.state = .unicode; }, 'n' => { self.state = .inner; return '\n'; }, 'r' => { self.state = .inner; return '\r'; }, 't' => { self.state = .inner; return '\t'; }, '\\' => { self.state = .inner; return '\\'; }, '0' => { self.state = .inner; return '\x00'; }, '\'' => { self.state = .inner; return '\''; }, '"' => { self.state = .inner; return '"'; }, else => { return Error.UnexpectedEscape; }, } }, .unicode => { switch (c) { '{' => { self.state = .unicode_digits; }, else => { return Error.UnicodeStartConditionError; }, } }, .unicode_digits => { switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => { unicode_buffer <<= 4; unicode_buffer |= try std.fmt.parseInt(u4, &[_]u8{c}, 16); offset += 1; if (offset > 5) { return Error.CodepointTooLong; } }, '}' => { if (offset == 0) { return Error.EmptyCodepoint; } var buffer: [4]u8 = undefined; const len = try std.unicode.utf8Encode(try std.math.cast(u21, unicode_buffer), &buffer); if (len > buffer.len) { @panic("Buffer length exceeded"); } for (buffer[0..len]) |elem| { try self.pending.writeItem(elem); } self.state = .inner; offset = 0; unicode_buffer = 0; return self.pending.readItem().?; }, else => { return Error.InvalidUnicodeDigit; }, } }, .hex => { switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => { hex_buffer <<= 4; hex_buffer |= try std.fmt.parseInt(u4, &[_]u8{c}, 16); offset += 1; if (offset == 2) { self.state = .inner; offset = 0; return hex_buffer; } if (offset > 2) { unreachable; } }, else => { return Error.InvalidHexDigit; }, } }, } } } }; fn decodeEqual(comptime in: []const u8, out: []const u8) !bool { const reader = std.io.fixedBufferStream(in).reader(); var decoder = Decoder.init(); var i: usize = 0; while (try decoder.next(reader)) |c| : (i += 1) { if (i >= out.len or out[i] != c) { return false; } } return true; } test "decode simple string" { try testing.expect(try decodeEqual( "'my favorite song.mp3'", "my favorite song.mp3", )); } test "decode simple escapes" { try testing.expect(try decodeEqual( "'bob\\t1.0\\ncarol\\t2.0\\n'", "bob\t1.0\ncarol\t2.0\n", )); } test "decode hexadecimal escapes" { try testing.expect(try decodeEqual( "'Hello W\\x6frld'", "Hello World", )); } test "decode Unicode escapes" { try testing.expect(try decodeEqual( "'Hello W\\u{6f}rld'", "Hello World", )); } test "decode Unicode escapes with leading zeros" { try testing.expect(try decodeEqual( "'Hello W\\u{006f}rld'", "Hello World", )); } test "decode large Unicode escapes" { try testing.expect(try decodeEqual( "'goblin \\u{1f47a}'", "goblin \u{1f47a}", )); } test "decode multiple hexadecimal escapes" { try testing.expect(try decodeEqual( "'goblin \\xf0\\x9f\\x91\\xba'", "goblin \u{1f47a}", )); } test "decode quote escapes" { try testing.expect(try decodeEqual( "'it\\'s 6AM'", "it's 6AM", )); } pub const UnicodeMode = enum { unicode, hex, raw, }; pub const UnicodeOptions = struct { mode: UnicodeMode = .raw, padding: usize = 2, }; pub fn Encoder(case: Case, unicode_options: UnicodeOptions) type { if (unicode_options.padding < 2 or unicode_options.padding > 6) { @compileError("unicode escapes must use a padding amount between 2 and 6"); } return struct { // This stores QSN-encoded versions of byte sequences which will be returned in the future. // It will be able to store the following values: // * "\\x00" for simple bytes // * "\\x00" ** the length of the UTF-8 sequence (<= 16 bytes) // * "\\u{000000}" // * raw UTF-8 const Pending = LinearFifo(u8, .{ .Static = 16 }); // This keeps track of any remaining bytes of an invalid UTF-8 sequence. const Reread = LinearFifo(u8, .{ .Static = 3 }); pending: Pending, reread: Reread, state: enum { start, inner, unicode, end, } = .start, const Self = @This(); pub fn init() Self { return Self{ .pending = Pending.init(), .reread = Reread.init() }; } fn formatHex(value: u8, writer: anytype) !void { _ = try writer.write("\\x"); try std.fmt.formatInt(value, 16, case, .{ .width = 2, .fill = '0' }, writer); } fn formatUnicode(value: u21, writer: anytype) !void { _ = try writer.write("\\u{"); try std.fmt.formatInt(value, 16, case, .{ .width = unicode_options.padding, .fill = '0' }, writer); _ = try writer.write("}"); } pub fn next(self: *Self, reader: anytype) !?u8 { if (self.pending.count != 0) { return self.pending.readItem().?; } var curr_unicode: struct { buffer: [4]u8 = undefined, index: usize = 0, len: usize = 0, } = .{}; while (true) { const c = if (self.reread.count != 0) self.reread.readItem().? else if (self.state == .inner or self.state == .unicode and curr_unicode.len > curr_unicode.index) reader.readByte() catch |err| switch (err) { error.EndOfStream => { self.state = .end; return '\''; }, else => { return err; }, } else null; switch (self.state) { .start => { self.state = .inner; return '\''; }, .inner => { if (std.ascii.isASCII(c.?)) { if (!std.ascii.isGraph(c.?) and !std.ascii.isSpace(c.?)) { // Not visually representable in ASCII. try Self.formatHex(c.?, self.pending.writer()); return self.pending.readItem().?; } else { const suffix: ?u8 = switch (c.?) { '\n' => 'n', '\r' => 'r', '\t' => 't', '\\' => '\\', '\x00' => '0', '\'' => '\'', '"' => '"', else => null, }; if (suffix == null) { // An ASCII character. return c.?; } else { // An ASCII escape. const writer = self.pending.writer(); try writer.writeByte('\\'); try writer.writeByte(suffix.?); return self.pending.readItem().?; } } } else if (unicode_options.mode == .unicode or unicode_options.mode == .raw) { curr_unicode.len = std.unicode.utf8ByteSequenceLength(c.?) catch { // A raw byte, not unicode or ASCII. try Self.formatHex(c.?, self.pending.writer()); return self.pending.readItem().?; }; curr_unicode.buffer[curr_unicode.index] = c.?; curr_unicode.index += 1; self.state = .unicode; continue; } else { try Self.formatHex(c.?, self.pending.writer()); return self.pending.readItem().?; } }, .unicode => { if (curr_unicode.len > curr_unicode.index) { curr_unicode.buffer[curr_unicode.index] = c.?; curr_unicode.index += 1; } else { // The maximum amount of unicode bytes has been reached. const decoded = std.unicode.utf8Decode(curr_unicode.buffer[0..curr_unicode.len]) catch { try Self.formatHex(curr_unicode.buffer[0], self.pending.writer()); if (curr_unicode.len > 1) { // The remaining bytes should be reread to not dismiss any potential ASCII/Unicode characters. _ = try self.reread.writer().write(curr_unicode.buffer[1..curr_unicode.len]); } self.state = .inner; return self.pending.readItem().?; }; switch (unicode_options.mode) { .hex => { for (curr_unicode.buffer) |uc| { try Self.formatHex(uc, self.pending.writer()); } }, .unicode => { try Self.formatUnicode(decoded, self.pending.writer()); }, .raw => { _ = try self.pending.writer().write(curr_unicode.buffer[0..]); }, } self.state = .inner; return self.pending.readItem().?; } }, .end => { return null; }, } } } }; } fn encodeEqual(comptime in: []const u8, out: []const u8, comptime case: Case, comptime unicode_options: UnicodeOptions) !bool { const reader = std.io.fixedBufferStream(in).reader(); var encoder = Encoder(case, unicode_options).init(); var i: usize = 0; while (try encoder.next(reader)) |c| : (i += 1) { if (i >= out.len or out[i] != c) { return false; } } return true; } test "encode simple string" { try testing.expect(try encodeEqual( "my favorite song.mp3", "'my favorite song.mp3'", .lower, .{ .mode = .hex, .padding = 2 }, )); } test "encode simple escapes" { try testing.expect(try encodeEqual( "bob\t1.0\ncarol\t2.0\n", "'bob\\t1.0\\ncarol\\t2.0\\n'", .lower, .{ .mode = .hex, .padding = 2 }, )); } test "encode lowercase hexadecimal escapes" { try testing.expect(try encodeEqual( "Hello World\x7f", "'Hello World\\x7f'", .lower, .{ .mode = .hex, .padding = 2 }, )); } test "encode uppercase hexadecimal escapes" { try testing.expect(try encodeEqual( "Hello World\x7F", "'Hello World\\x7F'", .upper, .{ .mode = .hex, .padding = 2 }, )); } test "encode lowercase Unicode escapes" { try testing.expect(try encodeEqual( "Hello W\u{f6}rld", "'Hello W\\u{f6}rld'", .lower, .{ .mode = .unicode, .padding = 2 }, )); } test "encode uppercase Unicode escapes" { try testing.expect(try encodeEqual( "Hello W\u{F6}rld", "'Hello W\\u{F6}rld'", .upper, .{ .mode = .unicode, .padding = 2 }, )); } test "encode raw UTF-8" { try testing.expect(try encodeEqual( "goblin \u{1f47a}", "'goblin \u{1f47a}'", .lower, .{ .mode = .raw, .padding = 2 }, )); } test "encode large Unicode escapes" { try testing.expect(try encodeEqual( "goblin \u{1f47a}", "'goblin \\u{1f47a}'", .lower, .{ .mode = .unicode, .padding = 2 }, )); } test "encode Unicode nonsense" { try testing.expect(try encodeEqual( "goblin \xf0\xff\xff\xfe", "'goblin \\xf0\\xff\\xff\\xfe'", .lower, .{ .mode = .unicode, .padding = 2 }, )); } test "encode Unicode nonsense with valid ASCII" { try testing.expect(try encodeEqual( "goblin \xf0abc", "'goblin \\xf0abc'", .lower, .{ .mode = .unicode, .padding = 2 }, )); } test "encode multiple hexadecimal escapes" { try testing.expect(try encodeEqual( "goblin \xf0\x9f\x91\xba", "'goblin \\xf0\\x9f\\x91\\xba'", .lower, .{ .mode = .hex, .padding = 2 }, )); } test "encode quote escapes" { try testing.expect(try encodeEqual( "it's 6AM", "'it\\'s 6AM'", .lower, .{ .mode = .hex, .padding = 2 }, )); }
src/qsn.zig
const Serial = @import("../io.zig").Serial; const PortIO = @import("../io.zig").PortIO; pub const magic_req = "sL5DdSMmkekro\n"; pub const magic_ack = "z6IHG7cYDID6o\n"; pub const Commands = enum(u8) { abort = 0, load = 1, jump = 2, _, }; pub const ack_success = 'K'; pub const ack_crcerror = 'C'; pub const ack_unknown = 'U'; pub const ack_error = 'E'; pub const Error = error { Timeout, Cancelled, Abort, UnknownCommand, }; payload_length: u8, crc: u16, cmd: u8, payload: [255]u8, const Self = @This(); pub fn receive(port: usize) !Self { var frame: Self = undefined; frame.payload_length = try Serial.read(port); frame.crc = @as(u16, try Serial.read(port)) | @as(u16, try Serial.read(port)) << 8; frame.cmd = try Serial.read(port); var i: usize = 0; const payload: [*]u8 = &frame.payload; while (i < frame.payload_length) : (i += 1) { payload[i] = try Serial.read(port); } // TODO check crc16 return frame; } const Timer = struct { pub fn oneShot(val: u16) void { // Counter 0, Mode 0 PortIO.out(u8, 0x43, 0b00110000); PortIO.out(u8, 0x40, @truncate(u8, val)); PortIO.out(u8, 0x40, @truncate(u8, val>>8)); } pub fn read() u16 { // Counter 0, latch PortIO.out(u8, 0x43, 0b00000000); const val: u16 = @as(u16, PortIO.in(u8, 0x40)) | @as(u16, PortIO.in(u8, 0x40)) << 8; return val; } }; fn isCancelled(c: u8) bool { return c == 'Q' or c == '\x1b'; } pub fn checkAck(port: usize) !void { var i: usize = 0; Timer.oneShot(0xFFFF); while (true) { if (try Serial.is_data_available(port)) { const c = try Serial.read(port); if (isCancelled(c)) { return Error.Cancelled; } else if (magic_ack[i] == c) { i += 1; if (i == magic_ack.len) { break; } } else { i = if (magic_ack[0] == c) 1 else 0; } } // Read timer if (Timer.read() == 0) return Error.Timeout; } } pub fn clean(port: usize) !void { Timer.oneShot(0xFFFF); while (true) { if (try Serial.is_data_available(port)) { _ = try Serial.read(port); Timer.oneShot(0xFFFF); } // Read timer if (Timer.read() == 0) break; } }
src/utils/sfl.zig
const std = @import("std"); fn buildRaylib(b: *std.build.Builder) void { const cmake = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", "ext/raylib/build", "-S", "ext/raylib", "-DCMAKE_BUILD_TYPE=Release", "-DOpenGL_GL_PREFERENCE=GLVND", "-DBUILD_EXAMPLES=OFF", }); cmake.step.make() catch {}; const cmake_build = b.addSystemCommand(&[_][]const u8{ "cmake", "--build", "ext/raylib/build", "--", "-j", "16", }); cmake_build.step.make() catch {}; } fn buildChipmunk(b: *std.build.Builder) void { const cmake = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", "ext/Chipmunk2D/build", "-S", "ext/Chipmunk2D", "-DCMAKE_BUILD_TYPE=Release", "-DBUILD_DEMOS=OFF", "-DBUILD_SHARED=OFF", }); cmake.step.make() catch {}; const cmake_build = b.addSystemCommand(&[_][]const u8{ "cmake", "--build", "ext/Chipmunk2D/build", "--", "-j", "16", }); cmake_build.step.make() catch {}; } fn buildCurl(b: *std.build.Builder) void { const cmake = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", "ext/curl/build", "-S", "ext/curl", "-DCMAKE_BUILD_TYPE=Release", "-DHTTP_ONLY=ON", "-DBUILD_CURL_EXE=OFF", "-DBUILD_SHARED_LIBS=OFF", "-DCMAKE_USE_OPENSSL=OFF", "-DCMAKE_USE_LIBSSH2=OFF", "-DCMAKE_USE_LIBSSH=OFF", "-DCURL_ZLIB=OFF", }); cmake.step.make() catch {}; const cmake_build = b.addSystemCommand(&[_][]const u8{ "cmake", "--build", "ext/curl/build", "--", "-j", "16", }); cmake_build.step.make() catch {}; } pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); buildRaylib(b); buildChipmunk(b); buildCurl(b); const exe = b.addExecutable("tractorz", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addIncludeDir("ext/Chipmunk2D/include"); exe.addIncludeDir("ext/curl/include"); exe.addLibPath("ext/Chipmunk2D/build/src"); exe.addLibPath("ext/raylib/build/raylib"); exe.addLibPath("ext/curl/build/lib"); exe.linkSystemLibraryName("chipmunk"); exe.linkSystemLibraryName("raylib"); exe.linkSystemLibraryName("curl"); exe.linkLibC(); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const test_step = b.step("test", "Run Tests"); const tests = b.addTest("src/tractor.zig"); tests.setBuildMode(mode); tests.addIncludeDir("ext/Chipmunk2D/include"); tests.addIncludeDir("ext/curl/include"); tests.addLibPath("ext/Chipmunk2D/build/src"); tests.addLibPath("ext/raylib/build/raylib"); tests.addLibPath("ext/curl/build/lib"); tests.linkSystemLibraryName("chipmunk"); tests.linkSystemLibraryName("raylib"); tests.linkSystemLibraryName("curl"); tests.linkLibC(); test_step.dependOn(&tests.step); }
build.zig
pub const _FACDXGI = @as(u32, 2170); pub const DXGI_CPU_ACCESS_NONE = @as(u32, 0); pub const DXGI_CPU_ACCESS_DYNAMIC = @as(u32, 1); pub const DXGI_CPU_ACCESS_READ_WRITE = @as(u32, 2); pub const DXGI_CPU_ACCESS_SCRATCH = @as(u32, 3); pub const DXGI_CPU_ACCESS_FIELD = @as(u32, 15); pub const DXGI_FORMAT_DEFINED = @as(u32, 1); pub const DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN = @as(u32, 4294967295); pub const DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN = @as(u32, 4294967294); //-------------------------------------------------------------------------------- // Section: Types (15) //-------------------------------------------------------------------------------- pub const DXGI_RATIONAL = extern struct { Numerator: u32, Denominator: u32, }; pub const DXGI_SAMPLE_DESC = extern struct { Count: u32, Quality: u32, }; pub const DXGI_COLOR_SPACE_TYPE = enum(i32) { RGB_FULL_G22_NONE_P709 = 0, RGB_FULL_G10_NONE_P709 = 1, RGB_STUDIO_G22_NONE_P709 = 2, RGB_STUDIO_G22_NONE_P2020 = 3, RESERVED = 4, YCBCR_FULL_G22_NONE_P709_X601 = 5, YCBCR_STUDIO_G22_LEFT_P601 = 6, YCBCR_FULL_G22_LEFT_P601 = 7, YCBCR_STUDIO_G22_LEFT_P709 = 8, YCBCR_FULL_G22_LEFT_P709 = 9, YCBCR_STUDIO_G22_LEFT_P2020 = 10, YCBCR_FULL_G22_LEFT_P2020 = 11, RGB_FULL_G2084_NONE_P2020 = 12, YCBCR_STUDIO_G2084_LEFT_P2020 = 13, RGB_STUDIO_G2084_NONE_P2020 = 14, YCBCR_STUDIO_G22_TOPLEFT_P2020 = 15, YCBCR_STUDIO_G2084_TOPLEFT_P2020 = 16, RGB_FULL_G22_NONE_P2020 = 17, YCBCR_STUDIO_GHLG_TOPLEFT_P2020 = 18, YCBCR_FULL_GHLG_TOPLEFT_P2020 = 19, RGB_STUDIO_G24_NONE_P709 = 20, RGB_STUDIO_G24_NONE_P2020 = 21, YCBCR_STUDIO_G24_LEFT_P709 = 22, YCBCR_STUDIO_G24_LEFT_P2020 = 23, YCBCR_STUDIO_G24_TOPLEFT_P2020 = 24, CUSTOM = -1, }; pub const DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = DXGI_COLOR_SPACE_TYPE.RGB_FULL_G22_NONE_P709; pub const DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = DXGI_COLOR_SPACE_TYPE.RGB_FULL_G10_NONE_P709; pub const DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = DXGI_COLOR_SPACE_TYPE.RGB_STUDIO_G22_NONE_P709; pub const DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = DXGI_COLOR_SPACE_TYPE.RGB_STUDIO_G22_NONE_P2020; pub const DXGI_COLOR_SPACE_RESERVED = DXGI_COLOR_SPACE_TYPE.RESERVED; pub const DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = DXGI_COLOR_SPACE_TYPE.YCBCR_FULL_G22_NONE_P709_X601; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G22_LEFT_P601; pub const DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = DXGI_COLOR_SPACE_TYPE.YCBCR_FULL_G22_LEFT_P601; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G22_LEFT_P709; pub const DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = DXGI_COLOR_SPACE_TYPE.YCBCR_FULL_G22_LEFT_P709; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G22_LEFT_P2020; pub const DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_FULL_G22_LEFT_P2020; pub const DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 = DXGI_COLOR_SPACE_TYPE.RGB_FULL_G2084_NONE_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G2084_LEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G2084_LEFT_P2020; pub const DXGI_COLOR_SPACE_RGB_STUDIO_G2084_NONE_P2020 = DXGI_COLOR_SPACE_TYPE.RGB_STUDIO_G2084_NONE_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_TOPLEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G22_TOPLEFT_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G2084_TOPLEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G2084_TOPLEFT_P2020; pub const DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P2020 = DXGI_COLOR_SPACE_TYPE.RGB_FULL_G22_NONE_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_GHLG_TOPLEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_GHLG_TOPLEFT_P2020; pub const DXGI_COLOR_SPACE_YCBCR_FULL_GHLG_TOPLEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_FULL_GHLG_TOPLEFT_P2020; pub const DXGI_COLOR_SPACE_RGB_STUDIO_G24_NONE_P709 = DXGI_COLOR_SPACE_TYPE.RGB_STUDIO_G24_NONE_P709; pub const DXGI_COLOR_SPACE_RGB_STUDIO_G24_NONE_P2020 = DXGI_COLOR_SPACE_TYPE.RGB_STUDIO_G24_NONE_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G24_LEFT_P709 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G24_LEFT_P709; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G24_LEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G24_LEFT_P2020; pub const DXGI_COLOR_SPACE_YCBCR_STUDIO_G24_TOPLEFT_P2020 = DXGI_COLOR_SPACE_TYPE.YCBCR_STUDIO_G24_TOPLEFT_P2020; pub const DXGI_COLOR_SPACE_CUSTOM = DXGI_COLOR_SPACE_TYPE.CUSTOM; pub const DXGI_FORMAT = enum(u32) { UNKNOWN = 0, R32G32B32A32_TYPELESS = 1, R32G32B32A32_FLOAT = 2, R32G32B32A32_UINT = 3, R32G32B32A32_SINT = 4, R32G32B32_TYPELESS = 5, R32G32B32_FLOAT = 6, R32G32B32_UINT = 7, R32G32B32_SINT = 8, R16G16B16A16_TYPELESS = 9, R16G16B16A16_FLOAT = 10, R16G16B16A16_UNORM = 11, R16G16B16A16_UINT = 12, R16G16B16A16_SNORM = 13, R16G16B16A16_SINT = 14, R32G32_TYPELESS = 15, R32G32_FLOAT = 16, R32G32_UINT = 17, R32G32_SINT = 18, R32G8X24_TYPELESS = 19, D32_FLOAT_S8X24_UINT = 20, R32_FLOAT_X8X24_TYPELESS = 21, X32_TYPELESS_G8X24_UINT = 22, R10G10B10A2_TYPELESS = 23, R10G10B10A2_UNORM = 24, R10G10B10A2_UINT = 25, R11G11B10_FLOAT = 26, R8G8B8A8_TYPELESS = 27, R8G8B8A8_UNORM = 28, R8G8B8A8_UNORM_SRGB = 29, R8G8B8A8_UINT = 30, R8G8B8A8_SNORM = 31, R8G8B8A8_SINT = 32, R16G16_TYPELESS = 33, R16G16_FLOAT = 34, R16G16_UNORM = 35, R16G16_UINT = 36, R16G16_SNORM = 37, R16G16_SINT = 38, R32_TYPELESS = 39, D32_FLOAT = 40, R32_FLOAT = 41, R32_UINT = 42, R32_SINT = 43, R24G8_TYPELESS = 44, D24_UNORM_S8_UINT = 45, R24_UNORM_X8_TYPELESS = 46, X24_TYPELESS_G8_UINT = 47, R8G8_TYPELESS = 48, R8G8_UNORM = 49, R8G8_UINT = 50, R8G8_SNORM = 51, R8G8_SINT = 52, R16_TYPELESS = 53, R16_FLOAT = 54, D16_UNORM = 55, R16_UNORM = 56, R16_UINT = 57, R16_SNORM = 58, R16_SINT = 59, R8_TYPELESS = 60, R8_UNORM = 61, R8_UINT = 62, R8_SNORM = 63, R8_SINT = 64, A8_UNORM = 65, R1_UNORM = 66, R9G9B9E5_SHAREDEXP = 67, R8G8_B8G8_UNORM = 68, G8R8_G8B8_UNORM = 69, BC1_TYPELESS = 70, BC1_UNORM = 71, BC1_UNORM_SRGB = 72, BC2_TYPELESS = 73, BC2_UNORM = 74, BC2_UNORM_SRGB = 75, BC3_TYPELESS = 76, BC3_UNORM = 77, BC3_UNORM_SRGB = 78, BC4_TYPELESS = 79, BC4_UNORM = 80, BC4_SNORM = 81, BC5_TYPELESS = 82, BC5_UNORM = 83, BC5_SNORM = 84, B5G6R5_UNORM = 85, B5G5R5A1_UNORM = 86, B8G8R8A8_UNORM = 87, B8G8R8X8_UNORM = 88, R10G10B10_XR_BIAS_A2_UNORM = 89, B8G8R8A8_TYPELESS = 90, B8G8R8A8_UNORM_SRGB = 91, B8G8R8X8_TYPELESS = 92, B8G8R8X8_UNORM_SRGB = 93, BC6H_TYPELESS = 94, BC6H_UF16 = 95, BC6H_SF16 = 96, BC7_TYPELESS = 97, BC7_UNORM = 98, BC7_UNORM_SRGB = 99, AYUV = 100, Y410 = 101, Y416 = 102, NV12 = 103, P010 = 104, P016 = 105, @"420_OPAQUE" = 106, YUY2 = 107, Y210 = 108, Y216 = 109, NV11 = 110, AI44 = 111, IA44 = 112, P8 = 113, A8P8 = 114, B4G4R4A4_UNORM = 115, P208 = 130, V208 = 131, V408 = 132, SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189, SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190, FORCE_UINT = 4294967295, }; pub const DXGI_FORMAT_UNKNOWN = DXGI_FORMAT.UNKNOWN; pub const DXGI_FORMAT_R32G32B32A32_TYPELESS = DXGI_FORMAT.R32G32B32A32_TYPELESS; pub const DXGI_FORMAT_R32G32B32A32_FLOAT = DXGI_FORMAT.R32G32B32A32_FLOAT; pub const DXGI_FORMAT_R32G32B32A32_UINT = DXGI_FORMAT.R32G32B32A32_UINT; pub const DXGI_FORMAT_R32G32B32A32_SINT = DXGI_FORMAT.R32G32B32A32_SINT; pub const DXGI_FORMAT_R32G32B32_TYPELESS = DXGI_FORMAT.R32G32B32_TYPELESS; pub const DXGI_FORMAT_R32G32B32_FLOAT = DXGI_FORMAT.R32G32B32_FLOAT; pub const DXGI_FORMAT_R32G32B32_UINT = DXGI_FORMAT.R32G32B32_UINT; pub const DXGI_FORMAT_R32G32B32_SINT = DXGI_FORMAT.R32G32B32_SINT; pub const DXGI_FORMAT_R16G16B16A16_TYPELESS = DXGI_FORMAT.R16G16B16A16_TYPELESS; pub const DXGI_FORMAT_R16G16B16A16_FLOAT = DXGI_FORMAT.R16G16B16A16_FLOAT; pub const DXGI_FORMAT_R16G16B16A16_UNORM = DXGI_FORMAT.R16G16B16A16_UNORM; pub const DXGI_FORMAT_R16G16B16A16_UINT = DXGI_FORMAT.R16G16B16A16_UINT; pub const DXGI_FORMAT_R16G16B16A16_SNORM = DXGI_FORMAT.R16G16B16A16_SNORM; pub const DXGI_FORMAT_R16G16B16A16_SINT = DXGI_FORMAT.R16G16B16A16_SINT; pub const DXGI_FORMAT_R32G32_TYPELESS = DXGI_FORMAT.R32G32_TYPELESS; pub const DXGI_FORMAT_R32G32_FLOAT = DXGI_FORMAT.R32G32_FLOAT; pub const DXGI_FORMAT_R32G32_UINT = DXGI_FORMAT.R32G32_UINT; pub const DXGI_FORMAT_R32G32_SINT = DXGI_FORMAT.R32G32_SINT; pub const DXGI_FORMAT_R32G8X24_TYPELESS = DXGI_FORMAT.R32G8X24_TYPELESS; pub const DXGI_FORMAT_D32_FLOAT_S8X24_UINT = DXGI_FORMAT.D32_FLOAT_S8X24_UINT; pub const DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = DXGI_FORMAT.R32_FLOAT_X8X24_TYPELESS; pub const DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = DXGI_FORMAT.X32_TYPELESS_G8X24_UINT; pub const DXGI_FORMAT_R10G10B10A2_TYPELESS = DXGI_FORMAT.R10G10B10A2_TYPELESS; pub const DXGI_FORMAT_R10G10B10A2_UNORM = DXGI_FORMAT.R10G10B10A2_UNORM; pub const DXGI_FORMAT_R10G10B10A2_UINT = DXGI_FORMAT.R10G10B10A2_UINT; pub const DXGI_FORMAT_R11G11B10_FLOAT = DXGI_FORMAT.R11G11B10_FLOAT; pub const DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS; pub const DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM; pub const DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB; pub const DXGI_FORMAT_R8G8B8A8_UINT = DXGI_FORMAT.R8G8B8A8_UINT; pub const DXGI_FORMAT_R8G8B8A8_SNORM = DXGI_FORMAT.R8G8B8A8_SNORM; pub const DXGI_FORMAT_R8G8B8A8_SINT = DXGI_FORMAT.R8G8B8A8_SINT; pub const DXGI_FORMAT_R16G16_TYPELESS = DXGI_FORMAT.R16G16_TYPELESS; pub const DXGI_FORMAT_R16G16_FLOAT = DXGI_FORMAT.R16G16_FLOAT; pub const DXGI_FORMAT_R16G16_UNORM = DXGI_FORMAT.R16G16_UNORM; pub const DXGI_FORMAT_R16G16_UINT = DXGI_FORMAT.R16G16_UINT; pub const DXGI_FORMAT_R16G16_SNORM = DXGI_FORMAT.R16G16_SNORM; pub const DXGI_FORMAT_R16G16_SINT = DXGI_FORMAT.R16G16_SINT; pub const DXGI_FORMAT_R32_TYPELESS = DXGI_FORMAT.R32_TYPELESS; pub const DXGI_FORMAT_D32_FLOAT = DXGI_FORMAT.D32_FLOAT; pub const DXGI_FORMAT_R32_FLOAT = DXGI_FORMAT.R32_FLOAT; pub const DXGI_FORMAT_R32_UINT = DXGI_FORMAT.R32_UINT; pub const DXGI_FORMAT_R32_SINT = DXGI_FORMAT.R32_SINT; pub const DXGI_FORMAT_R24G8_TYPELESS = DXGI_FORMAT.R24G8_TYPELESS; pub const DXGI_FORMAT_D24_UNORM_S8_UINT = DXGI_FORMAT.D24_UNORM_S8_UINT; pub const DXGI_FORMAT_R24_UNORM_X8_TYPELESS = DXGI_FORMAT.R24_UNORM_X8_TYPELESS; pub const DXGI_FORMAT_X24_TYPELESS_G8_UINT = DXGI_FORMAT.X24_TYPELESS_G8_UINT; pub const DXGI_FORMAT_R8G8_TYPELESS = DXGI_FORMAT.R8G8_TYPELESS; pub const DXGI_FORMAT_R8G8_UNORM = DXGI_FORMAT.R8G8_UNORM; pub const DXGI_FORMAT_R8G8_UINT = DXGI_FORMAT.R8G8_UINT; pub const DXGI_FORMAT_R8G8_SNORM = DXGI_FORMAT.R8G8_SNORM; pub const DXGI_FORMAT_R8G8_SINT = DXGI_FORMAT.R8G8_SINT; pub const DXGI_FORMAT_R16_TYPELESS = DXGI_FORMAT.R16_TYPELESS; pub const DXGI_FORMAT_R16_FLOAT = DXGI_FORMAT.R16_FLOAT; pub const DXGI_FORMAT_D16_UNORM = DXGI_FORMAT.D16_UNORM; pub const DXGI_FORMAT_R16_UNORM = DXGI_FORMAT.R16_UNORM; pub const DXGI_FORMAT_R16_UINT = DXGI_FORMAT.R16_UINT; pub const DXGI_FORMAT_R16_SNORM = DXGI_FORMAT.R16_SNORM; pub const DXGI_FORMAT_R16_SINT = DXGI_FORMAT.R16_SINT; pub const DXGI_FORMAT_R8_TYPELESS = DXGI_FORMAT.R8_TYPELESS; pub const DXGI_FORMAT_R8_UNORM = DXGI_FORMAT.R8_UNORM; pub const DXGI_FORMAT_R8_UINT = DXGI_FORMAT.R8_UINT; pub const DXGI_FORMAT_R8_SNORM = DXGI_FORMAT.R8_SNORM; pub const DXGI_FORMAT_R8_SINT = DXGI_FORMAT.R8_SINT; pub const DXGI_FORMAT_A8_UNORM = DXGI_FORMAT.A8_UNORM; pub const DXGI_FORMAT_R1_UNORM = DXGI_FORMAT.R1_UNORM; pub const DXGI_FORMAT_R9G9B9E5_SHAREDEXP = DXGI_FORMAT.R9G9B9E5_SHAREDEXP; pub const DXGI_FORMAT_R8G8_B8G8_UNORM = DXGI_FORMAT.R8G8_B8G8_UNORM; pub const DXGI_FORMAT_G8R8_G8B8_UNORM = DXGI_FORMAT.G8R8_G8B8_UNORM; pub const DXGI_FORMAT_BC1_TYPELESS = DXGI_FORMAT.BC1_TYPELESS; pub const DXGI_FORMAT_BC1_UNORM = DXGI_FORMAT.BC1_UNORM; pub const DXGI_FORMAT_BC1_UNORM_SRGB = DXGI_FORMAT.BC1_UNORM_SRGB; pub const DXGI_FORMAT_BC2_TYPELESS = DXGI_FORMAT.BC2_TYPELESS; pub const DXGI_FORMAT_BC2_UNORM = DXGI_FORMAT.BC2_UNORM; pub const DXGI_FORMAT_BC2_UNORM_SRGB = DXGI_FORMAT.BC2_UNORM_SRGB; pub const DXGI_FORMAT_BC3_TYPELESS = DXGI_FORMAT.BC3_TYPELESS; pub const DXGI_FORMAT_BC3_UNORM = DXGI_FORMAT.BC3_UNORM; pub const DXGI_FORMAT_BC3_UNORM_SRGB = DXGI_FORMAT.BC3_UNORM_SRGB; pub const DXGI_FORMAT_BC4_TYPELESS = DXGI_FORMAT.BC4_TYPELESS; pub const DXGI_FORMAT_BC4_UNORM = DXGI_FORMAT.BC4_UNORM; pub const DXGI_FORMAT_BC4_SNORM = DXGI_FORMAT.BC4_SNORM; pub const DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS; pub const DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM; pub const DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM; pub const DXGI_FORMAT_B5G6R5_UNORM = DXGI_FORMAT.B5G6R5_UNORM; pub const DXGI_FORMAT_B5G5R5A1_UNORM = DXGI_FORMAT.B5G5R5A1_UNORM; pub const DXGI_FORMAT_B8G8R8A8_UNORM = DXGI_FORMAT.B8G8R8A8_UNORM; pub const DXGI_FORMAT_B8G8R8X8_UNORM = DXGI_FORMAT.B8G8R8X8_UNORM; pub const DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = DXGI_FORMAT.R10G10B10_XR_BIAS_A2_UNORM; pub const DXGI_FORMAT_B8G8R8A8_TYPELESS = DXGI_FORMAT.B8G8R8A8_TYPELESS; pub const DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = DXGI_FORMAT.B8G8R8A8_UNORM_SRGB; pub const DXGI_FORMAT_B8G8R8X8_TYPELESS = DXGI_FORMAT.B8G8R8X8_TYPELESS; pub const DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = DXGI_FORMAT.B8G8R8X8_UNORM_SRGB; pub const DXGI_FORMAT_BC6H_TYPELESS = DXGI_FORMAT.BC6H_TYPELESS; pub const DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16; pub const DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16; pub const DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS; pub const DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM; pub const DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB; pub const DXGI_FORMAT_AYUV = DXGI_FORMAT.AYUV; pub const DXGI_FORMAT_Y410 = DXGI_FORMAT.Y410; pub const DXGI_FORMAT_Y416 = DXGI_FORMAT.Y416; pub const DXGI_FORMAT_NV12 = DXGI_FORMAT.NV12; pub const DXGI_FORMAT_P010 = DXGI_FORMAT.P010; pub const DXGI_FORMAT_P016 = DXGI_FORMAT.P016; pub const DXGI_FORMAT_420_OPAQUE = DXGI_FORMAT.@"420_OPAQUE"; pub const DXGI_FORMAT_YUY2 = DXGI_FORMAT.YUY2; pub const DXGI_FORMAT_Y210 = DXGI_FORMAT.Y210; pub const DXGI_FORMAT_Y216 = DXGI_FORMAT.Y216; pub const DXGI_FORMAT_NV11 = DXGI_FORMAT.NV11; pub const DXGI_FORMAT_AI44 = DXGI_FORMAT.AI44; pub const DXGI_FORMAT_IA44 = DXGI_FORMAT.IA44; pub const DXGI_FORMAT_P8 = DXGI_FORMAT.P8; pub const DXGI_FORMAT_A8P8 = DXGI_FORMAT.A8P8; pub const DXGI_FORMAT_B4G4R4A4_UNORM = DXGI_FORMAT.B4G4R4A4_UNORM; pub const DXGI_FORMAT_P208 = DXGI_FORMAT.P208; pub const DXGI_FORMAT_V208 = DXGI_FORMAT.V208; pub const DXGI_FORMAT_V408 = DXGI_FORMAT.V408; pub const DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = DXGI_FORMAT.SAMPLER_FEEDBACK_MIN_MIP_OPAQUE; pub const DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = DXGI_FORMAT.SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE; pub const DXGI_FORMAT_FORCE_UINT = DXGI_FORMAT.FORCE_UINT; pub const DXGI_RGB = extern struct { Red: f32, Green: f32, Blue: f32, }; pub const DXGI_GAMMA_CONTROL = extern struct { Scale: DXGI_RGB, Offset: DXGI_RGB, GammaCurve: [1025]DXGI_RGB, }; pub const DXGI_GAMMA_CONTROL_CAPABILITIES = extern struct { ScaleAndOffsetSupported: BOOL, MaxConvertedValue: f32, MinConvertedValue: f32, NumGammaControlPoints: u32, ControlPointPositions: [1025]f32, }; pub const DXGI_MODE_SCANLINE_ORDER = enum(i32) { UNSPECIFIED = 0, PROGRESSIVE = 1, UPPER_FIELD_FIRST = 2, LOWER_FIELD_FIRST = 3, }; pub const DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = DXGI_MODE_SCANLINE_ORDER.UNSPECIFIED; pub const DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = DXGI_MODE_SCANLINE_ORDER.PROGRESSIVE; pub const DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = DXGI_MODE_SCANLINE_ORDER.UPPER_FIELD_FIRST; pub const DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = DXGI_MODE_SCANLINE_ORDER.LOWER_FIELD_FIRST; pub const DXGI_MODE_SCALING = enum(i32) { UNSPECIFIED = 0, CENTERED = 1, STRETCHED = 2, }; pub const DXGI_MODE_SCALING_UNSPECIFIED = DXGI_MODE_SCALING.UNSPECIFIED; pub const DXGI_MODE_SCALING_CENTERED = DXGI_MODE_SCALING.CENTERED; pub const DXGI_MODE_SCALING_STRETCHED = DXGI_MODE_SCALING.STRETCHED; pub const DXGI_MODE_ROTATION = enum(i32) { UNSPECIFIED = 0, IDENTITY = 1, ROTATE90 = 2, ROTATE180 = 3, ROTATE270 = 4, }; pub const DXGI_MODE_ROTATION_UNSPECIFIED = DXGI_MODE_ROTATION.UNSPECIFIED; pub const DXGI_MODE_ROTATION_IDENTITY = DXGI_MODE_ROTATION.IDENTITY; pub const DXGI_MODE_ROTATION_ROTATE90 = DXGI_MODE_ROTATION.ROTATE90; pub const DXGI_MODE_ROTATION_ROTATE180 = DXGI_MODE_ROTATION.ROTATE180; pub const DXGI_MODE_ROTATION_ROTATE270 = DXGI_MODE_ROTATION.ROTATE270; pub const DXGI_MODE_DESC = extern struct { Width: u32, Height: u32, RefreshRate: DXGI_RATIONAL, Format: DXGI_FORMAT, ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER, Scaling: DXGI_MODE_SCALING, }; pub const DXGI_JPEG_DC_HUFFMAN_TABLE = extern struct { CodeCounts: [12]u8, CodeValues: [12]u8, }; pub const DXGI_JPEG_AC_HUFFMAN_TABLE = extern struct { CodeCounts: [16]u8, CodeValues: [162]u8, }; pub const DXGI_JPEG_QUANTIZATION_TABLE = extern struct { Elements: [64]u8, }; pub const DXGI_ALPHA_MODE = enum(u32) { UNSPECIFIED = 0, PREMULTIPLIED = 1, STRAIGHT = 2, IGNORE = 3, FORCE_DWORD = 4294967295, }; pub const DXGI_ALPHA_MODE_UNSPECIFIED = DXGI_ALPHA_MODE.UNSPECIFIED; pub const DXGI_ALPHA_MODE_PREMULTIPLIED = DXGI_ALPHA_MODE.PREMULTIPLIED; pub const DXGI_ALPHA_MODE_STRAIGHT = DXGI_ALPHA_MODE.STRAIGHT; pub const DXGI_ALPHA_MODE_IGNORE = DXGI_ALPHA_MODE.IGNORE; pub const DXGI_ALPHA_MODE_FORCE_DWORD = DXGI_ALPHA_MODE.FORCE_DWORD; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (1) //-------------------------------------------------------------------------------- const BOOL = @import("../../foundation.zig").BOOL; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/graphics/dxgi/common.zig
const std = @import("std"); const fs = std.fs; const mem = std.mem; const Builder = std.build.Builder; const FileSource = std.build.FileSource; const Pkg = std.build.Pkg; const win32 = Pkg{ .name = "win32", .path = FileSource.relative("deps/zigwin32/win32.zig") }; const nfd = Pkg{ .name = "nfd", .path = FileSource.relative("deps/nfd-zig/src/lib.zig") }; const nanovg = Pkg{ .name = "nanovg", .path = FileSource.relative("deps/nanovg/src/nanovg.zig") }; const gui = Pkg{ .name = "gui", .path = FileSource.relative("src/gui/gui.zig"), .dependencies = &.{nanovg} }; pub fn build(b: *Builder) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const exe = b.addExecutable("minipixel", "src/main.zig"); exe.setBuildMode(mode); exe.setTarget(target); if (exe.target.isWindows()) { exe.addVcpkgPaths(.dynamic) catch @panic("vcpkg not installed"); if (exe.vcpkg_bin_path) |bin_path| { for (&[_][]const u8{ "SDL2.dll", "libpng16.dll", "zlib1.dll" }) |dll| { const src_dll = try std.fs.path.join(b.allocator, &.{ bin_path, dll }); b.installBinFile(src_dll, dll); } } exe.subsystem = .Windows; exe.linkSystemLibrary("shell32"); exe.addObjectFile("minipixel.o"); // add icon exe.want_lto = false; // workaround for https://github.com/ziglang/zig/issues/8531 } else if (exe.target.isDarwin()) { exe.addCSourceFile("src/c/sdl_hacks.m", &.{}); } exe.addIncludeDir("lib/nanovg/src"); exe.addIncludeDir("lib/gl2/include"); const c_flags = &.{ "-std=c99", "-D_CRT_SECURE_NO_WARNINGS" }; exe.addCSourceFile("src/c/png_image.c", &.{"-std=c99"}); exe.addCSourceFile("lib/gl2/src/glad.c", c_flags); exe.addCSourceFile("lib/nanovg/src/nanovg.c", c_flags); exe.addCSourceFile("deps/nanovg/src/c/nanovg_gl2_impl.c", c_flags); exe.addPackage(win32); exe.addPackage(nfd); exe.addPackage(nanovg); exe.addPackage(gui); const nfd_lib = try @import("deps/nfd-zig/build.zig").makeLib(b, mode, target, "deps/nfd-zig/"); exe.linkLibrary(nfd_lib); exe.linkSystemLibrary("SDL2"); exe.linkSystemLibrary("libpng16"); if (exe.target.isDarwin()) { exe.linkFramework("OpenGL"); } else if (exe.target.isWindows()) { exe.linkSystemLibrary("opengl32"); } else if (exe.target.isLinux()) { exe.linkSystemLibrary("gl"); exe.linkSystemLibrary("X11"); } exe.linkLibC(); if (b.is_release) exe.strip = true; exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run VectorZig"); run_step.dependOn(&run_cmd.step); // if (exe.target.isWindows()) { // const sdk_bin_dir = "C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.18362.0\\x64\\"; // const mt_exe = sdk_bin_dir ++ "mt.exe"; // //const rc_exe = sdk_bin_dir ++ "rc.exe"; // //b.addSystemCommand(&[_][]const u8{ rc_exe, "/fo", "vector_ico.o", "vector.rc" }); // const outputresource = try std.mem.join(b.allocator, "", &.{ "-outputresource:", "zig-cache\\bin\\", exe.out_filename, ";1" }); // const manifest_cmd = b.addSystemCommand(&.{ mt_exe, "-manifest", "app.manifest", outputresource }); // manifest_cmd.step.dependOn(b.getInstallStep()); // const manifest_step = b.step("manifest", "Embed manifest"); // manifest_step.dependOn(&manifest_cmd.step); // run_cmd.step.dependOn(&manifest_cmd.step); // } }
build.zig
const std = @import("std"); const helper = @import("helper.zig"); const Allocator = std.mem.Allocator; const Vec3 = @Vector(3, i32); const ArrayList = std.ArrayList; const HashMap = std.AutoHashMap; const input = @embedFile("../inputs/day19.txt"); pub fn run(alloc: Allocator, stdout_: anytype) !void { _ = stdout_; var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); const arena_alloc = arena.allocator(); const scanners: []Scanner = try parseScanners(arena_alloc, input); try matchScanners(scanners); const assemble_res = try assembleMap(arena_alloc, scanners); const map = assemble_res.map; const positions = assemble_res.positions; const res1 = map.count(); const res2 = maxDistance(positions); if (stdout_) |stdout| { try stdout.print("Part 1: {}\n", .{res1}); try stdout.print("Part 2: {}\n", .{res2}); } } fn matchScanners(scanners: []Scanner) !void { for (scanners) |*scanner1, i| { var j: usize = i + 1; while (j < scanners.len) : (j += 1) { const scanner2 = &scanners[j]; try scanner1.matches(scanner2); } } } const AssembleRes = struct { map: HashMap(Vec3, void), positions: []?Vec3, }; fn maxDistance(positions: []?Vec3) i32 { var dist: i32 = std.math.minInt(i32); for (positions) |pos1, i| { var j: usize = i + 1; while (j < positions.len) : (j += 1) { const curr: [3]i32 = pos1.? - positions[j].?; dist = std.math.max(dist, abs(curr[0]) + abs(curr[1]) + abs(curr[2])); } } return dist; } fn assembleMap(alloc: Allocator, scanners: []const Scanner) !AssembleRes { var map = HashMap(Vec3, void).init(alloc); const reached = try alloc.alloc(?Vec3, scanners.len); try assembleMapInner(scanners, &map, reached, 0, rots[0], [3]i32{ 0, 0, 0 }); return AssembleRes{ .map = map, .positions = reached }; } fn assembleMapInner( scanners: []const Scanner, map: *HashMap(Vec3, void), reached: []?Vec3, idx: usize, mat: Mat3, offset: Vec3, ) Allocator.Error!void { const scanner = scanners[idx]; reached[idx] = offset; // store the scanner's offset, aka its position :) var points_iter = scanner.points.keyIterator(); while (points_iter.next()) |point| { const translated = mulVec(mat, point.*) + offset; try map.put(translated, {}); } for (scanner.match_data.items) |match| { const match_idx = match.scanner_idx; if (reached[match_idx] != null) continue; const new_mat = mulMat(mat, rots[match.mat_idx]); const new_offset = mulVec(mat, match.offset) + offset; try assembleMapInner(scanners, map, reached, match_idx, new_mat, new_offset); } } fn parseScanners(alloc: Allocator, inp: []const u8) ![]Scanner { var lines = helper.getlines(inp); _ = lines.next(); // get rid of the first line var scanners = ArrayList(Scanner).init(alloc); var idx: usize = 0; while (lines.rest().len > 0) : (idx += 1) { const scanner = try scanners.addOne(); scanner.* = Scanner.init(alloc, idx); while (lines.next()) |line| { if (std.mem.startsWith(u8, line, "---")) break; const vec = try parseVec(line); try scanner.addPoint(vec); } } return scanners.toOwnedSlice(); } fn parseVec(line: []const u8) !Vec3 { var splut = split(u8, line, ","); var vals: [3]i32 = undefined; for (vals) |*val| { val.* = try parseInt(i32, splut.next().?, 10); } const vec: Vec3 = vals; return vec; } const DiffMap = HashMap(Vec3, ArrayList([2]Vec3)); const MatchInfo = struct { scanner_idx: usize, mat_idx: usize, offset: Vec3 }; const Scanner = struct { idx: usize, points: HashMap(Vec3, void), diffs: DiffMap, match_data: ArrayList(MatchInfo), // how to get *from* other *to* self alloc: Allocator, const Self = @This(); pub fn init(alloc: Allocator, idx: usize) Self { return Self{ .idx = idx, .points = HashMap(Vec3, void).init(alloc), .diffs = DiffMap.init(alloc), .match_data = ArrayList(MatchInfo).init(alloc), .alloc = alloc, }; } fn getDiffArr(self: Self, diff: Vec3) ?*ArrayList([2]Vec3) { if (self.diffs.getPtr(diff)) |arr| return arr; if (self.diffs.getPtr(-diff)) |arr| return arr; return null; } pub fn addPoint(self: *Self, point: Vec3) !void { const res = try self.points.fetchPut(point, {}); if (res != null) return; var keys = self.points.keyIterator(); while (keys.next()) |key| { if (vecAll(key.* == point)) continue; const diff = key.* - point; const arr = if (self.getDiffArr(diff)) |val| val else blk: { const entry = try self.diffs.getOrPutValue( diff, ArrayList([2]Vec3).init(self.alloc), ); break :blk entry.value_ptr; }; try arr.append(.{ key.*, point }); } } pub fn matches(self: *Self, other: *Self) !void { for (rots) |_, rot| { if (self.matchesRot(other, rot)) |offset| { // other/self are switched here because i'm stupid try self.match_data.append(MatchInfo{ .scanner_idx = other.idx, .mat_idx = rot, .offset = offset, }); try other.match_data.append(MatchInfo{ .scanner_idx = self.idx, .mat_idx = inv_indices[rot], .offset = -mulVec(rots[inv_indices[rot]], offset), }); } } } /// Return value is the offset of other, after rotating, where the match occurs. fn matchesRot(self: *const Self, other: *const Self, rot: usize) ?Vec3 { // other is manipulated w.r.t self, that is, shifted and rotated. if (!self.hasEnoughMatchingPairs(other, rot)) return null; var other_diffs = other.diffs.iterator(); while (other_diffs.next()) |entry| { const diff = entry.key_ptr.*; const other_arr = entry.value_ptr.items; const rotated = mulVec(rots[rot], diff); const my_arr = self.diffs.get(rotated) orelse continue; for (my_arr.items) |my_pair| for (other_arr) |other_pair| { const v1 = mulVec(rots[rot], other_pair[0]); const v2 = mulVec(rots[rot], other_pair[1]); const offset = calculateOffset(my_pair, .{ v1, v2 }); if (self.matchesRotOffset(other, rot, offset)) return offset; }; } return null; } fn matchesRotOffset(self: *const Self, other: *const Self, rot: usize, offset: Vec3) bool { var other_points = other.points.keyIterator(); var match_sum: i32 = 0; while (other_points.next()) |other_point| { const translated = mulVec(rots[rot], other_point.*) + offset; if (self.points.contains(translated)) match_sum += 1; } return match_sum >= 12; } fn calculateOffset(pair1: [2]Vec3, pair2: [2]Vec3) Vec3 { const diff1 = pair1[0] - pair1[0]; const diff2 = pair2[0] - pair2[1]; if (vecAll(diff1 == diff2)) { return pair1[0] - pair2[0]; } else { // diff1 == -diff2 return pair1[1] - pair2[1]; } } fn hasEnoughMatchingPairs(self: *const Self, other: *const Self, rot: usize) bool { var other_diffs = other.diffs.iterator(); var match_sum: usize = 0; while (other_diffs.next()) |entry| { const diff = entry.key_ptr.*; const other_len = entry.value_ptr.items.len; const rotated = mulVec(rots[rot], diff); if (self.diffs.get(rotated)) |arr| { match_sum += std.math.min(other_len, arr.items.len); } } return match_sum >= 6; // less than 6 matching *pairs* } }; const Mat3 = [3]Vec3; // an array of rows fn transpose(mat: Mat3) Mat3 { const rows: [3][3]i32 = .{ mat[0], mat[1], mat[2] }; return .{ [3]i32{ rows[0][0], rows[1][0], rows[2][0] }, [3]i32{ rows[0][1], rows[1][1], rows[2][1] }, [3]i32{ rows[0][2], rows[1][2], rows[2][2] }, }; } fn mulVec(mat: Mat3, vec: Vec3) Vec3 { const out: Vec3 = .{ vecSum(mat[0] * vec), vecSum(mat[1] * vec), vecSum(mat[2] * vec), }; return out; } fn mulMat(mat1: Mat3, mat2: Mat3) Mat3 { const cols2 = transpose(mat2); return Mat3{ [3]i32{ vecSum(mat1[0] * cols2[0]), vecSum(mat1[0] * cols2[1]), vecSum(mat1[0] * cols2[2]) }, [3]i32{ vecSum(mat1[1] * cols2[0]), vecSum(mat1[1] * cols2[1]), vecSum(mat1[1] * cols2[2]) }, [3]i32{ vecSum(mat1[2] * cols2[0]), vecSum(mat1[2] * cols2[1]), vecSum(mat1[2] * cols2[2]) }, }; } fn vecSum(vec: Vec3) i32 { const arr: [3]i32 = vec; return arr[0] + arr[1] + arr[2]; } fn vecAll(vec: @Vector(3, bool)) bool { const arr: [3]bool = vec; return arr[0] and arr[1] and arr[2]; } const rots: [24]Mat3 = .{ .{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, 1 } }, .{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, 1 } }, .{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, -1 } }, .{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, -1 } }, .{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 0, 1, 0 } }, .{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 0, 1, 0 } }, .{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 0, -1, 0 } }, .{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 0, -1, 0 } }, .{ [3]i32{ 0, -1, 0 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, 1 } }, .{ [3]i32{ 0, 1, 0 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, 1 } }, .{ [3]i32{ 0, 1, 0 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, -1 } }, .{ [3]i32{ 0, -1, 0 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, -1 } }, .{ [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 1, 0, 0 } }, .{ [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 1, 0, 0 } }, .{ [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ -1, 0, 0 } }, .{ [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ -1, 0, 0 } }, .{ [3]i32{ 0, 0, 1 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 1, 0 } }, .{ [3]i32{ 0, 0, -1 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 1, 0 } }, .{ [3]i32{ 0, 0, -1 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, -1, 0 } }, .{ [3]i32{ 0, 0, 1 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, -1, 0 } }, .{ [3]i32{ 0, 0, -1 }, [3]i32{ 0, 1, 0 }, [3]i32{ 1, 0, 0 } }, .{ [3]i32{ 0, 0, 1 }, [3]i32{ 0, -1, 0 }, [3]i32{ 1, 0, 0 } }, .{ [3]i32{ 0, 0, 1 }, [3]i32{ 0, 1, 0 }, [3]i32{ -1, 0, 0 } }, .{ [3]i32{ 0, 0, -1 }, [3]i32{ 0, -1, 0 }, [3]i32{ -1, 0, 0 } }, }; const inv_indices: [24]usize = blk: { var idxs: [24]usize = undefined; @setEvalBranchQuota(2000); for (idxs) |*idx, i| { // the inverse of an orthogonal real matrix is its transpose const trans = transpose(rots[i]); for (rots) |rot, j| { if (vecAll(rot[0] == trans[0]) and vecAll(rot[1] == trans[1]) and vecAll(rot[2] == trans[2])) { idx.* = j; } } } break :blk idxs; }; const abs = helper.abs; const eql = std.mem.eql; const tokenize = std.mem.tokenize; const split = std.mem.split; const count = std.mem.count; const parseUnsigned = std.fmt.parseUnsigned; const parseInt = std.fmt.parseInt; const sort = std.sort.sort;
src/day19.zig
const std = @import("std"); const c = @import("c.zig"); pub fn decode( pemData: []const u8, comptime UserDataType: type, userData: UserDataType, callback: fn(userData: UserDataType, data: []const u8) anyerror!void, allocator: std.mem.Allocator) !void { var state = PemState { .success = true, .list = std.ArrayList(u8).init(allocator), }; defer state.list.deinit(); var context: c.br_pem_decoder_context = undefined; c.br_pem_decoder_init(&context); c.br_pem_decoder_setdest(&context, pemCallbackC, &state); var remaining = pemData; while (state.success and remaining.len > 0) { const n = c.br_pem_decoder_push(&context, &remaining[0], remaining.len); if (n == 0) { while (true) { const event = c.br_pem_decoder_event(&context); switch (event) { 0 => break, c.BR_PEM_BEGIN_OBJ => { state.list.clearRetainingCapacity(); }, c.BR_PEM_END_OBJ => { try callback(userData, state.list.items); }, c.BR_PEM_ERROR => { return error.PemDecodeErrorEvent; }, else => { return error.PemDecodeUnexpectedEvent; }, } } } else { remaining = remaining[n..]; } } if (!state.success) { return error.PemDecodeError; } if (state.list.items.len > 0) { try callback(userData, state.list.items); } } const PemState = struct { success: bool, list: std.ArrayList(u8), }; fn pemCallbackC(userData: ?*anyopaque, data: ?*const anyopaque, len: usize) callconv(.C) void { var state = @ptrCast(*PemState, @alignCast(@alignOf(*PemState), userData)); const bytes = @ptrCast([*]const u8, data); const slice = bytes[0..len]; state.list.appendSlice(slice) catch |err| { std.log.err("pemCallbackC error {}", .{err}); state.success = false; }; }
src/pem.zig
// TODO: Inline and fix cross once #3893 is fixed upstream const std = @import("std"); const sqrt = std.math.sqrt; const cos = std.math.cos; const sin = std.math.sin; const tan = std.math.tan; const max = std.math.max; const min = std.math.min; pub fn clamp(v: anytype, lo: anytype, hi: anytype) @TypeOf(v) { return max(min(v, hi), lo); } /// Mathematical vector types fn Vector(comptime d: usize) type { return extern struct { vals: [d]f32, const Self = @This(); // Constructors pub fn fill(v: f32) Self { var vals: [d]f32 = undefined; comptime var i = 0; inline while (i < d) : (i += 1) { vals[i] = v; } return Self{ .vals = vals }; } pub fn zeros() Self { return Self.fill(0.0); } pub fn ones() Self { return Self.fill(1.0); } // Math Operations pub fn sum(self: Self) f32 { var total: f32 = 0.0; for (self.vals) |val| { total += val; } return total; } pub fn add(self: Self, other: Self) Self { const vs: @Vector(d, f32) = self.vals; const vo: @Vector(d, f32) = other.vals; return Self{ .vals = vs + vo }; } pub fn sub(self: Self, other: Self) Self { const vs: @Vector(d, f32) = self.vals; const vo: @Vector(d, f32) = other.vals; return Self{ .vals = vs - vo }; } pub fn mul(self: Self, other: Self) Self { const vs: @Vector(d, f32) = self.vals; const vo: @Vector(d, f32) = other.vals; return Self{ .vals = vs * vo }; } pub fn mulScalar(self: Self, other: f32) Self { const vs: @Vector(d, f32) = self.vals; const vo: @Vector(d, f32) = Self.fill(other).vals; return Self{ .vals = vs * vo }; } pub fn div(self: Self, other: Self) Self { const vs: @Vector(d, f32) = self.vals; const vo: @Vector(d, f32) = other.vals; return Self{ .vals = vs / vo }; } pub fn dot(self: Self, other: Self) f32 { const product = self.mul(other); return product.sum(); } pub fn normSq(self: Self) f32 { return self.dot(self); } pub fn norm(self: Self) f32 { return sqrt(self.normSq()); } pub fn normalize(self: Self) Self { const n = self.norm(); var vals = self.vals; for (vals) |*val| { val.* /= n; } return Self{ .vals = vals }; } pub fn cross(self: Self, other: Self) Self { if (d != 3) { // @compileError("Cross product only defined for 3D vectors"); // https://github.com/ziglang/zig/issues/3893 // Silently fail for now return Self.zeros(); } const vals = [3]f32{ self.vals[1] * other.vals[2] - self.vals[2] * other.vals[1], self.vals[2] * other.vals[0] - self.vals[0] * other.vals[2], self.vals[0] * other.vals[1] - self.vals[1] * other.vals[0], }; return Self{ .vals = vals }; } }; } pub const Vec2 = Vector(2); pub const Vec3 = Vector(3); pub const Vec4 = Vector(4); pub fn vec3(x: f32, y: f32, z: f32) Vec3 { return Vec3{ .vals = [3]f32{ x, y, z } }; } /// Square matrix type with columnar memory layout fn Matrix(comptime d: usize) type { return extern struct { vals: [d][d]f32, const Self = @This(); pub fn zeros() Self { var vals: [d][d]f32 = undefined; comptime var i = 0; inline while (i < d) : (i += 1) { comptime var j = 0; inline while (j < d) : (j += 1) { vals[i][j] = 0.0; } } return Self{ .vals = vals }; } pub fn identity() Self { var vals: [d][d]f32 = undefined; comptime var i = 0; inline while (i < d) : (i += 1) { comptime var j = 0; inline while (j < d) : (j += 1) { vals[i][j] = if (i == j) 1.0 else 0.0; } } return Self{ .vals = vals }; } pub fn transpose(self: Self) Self { var vals: [d][d]f32 = undefined; comptime var i = 0; inline while (i < d) : (i += 1) { comptime var j = 0; inline while (j < d) : (j += 1) { vals[i][j] = self.vals[j][i]; } } return Self{ .vals = vals }; } pub fn matmul(self: Self, other: Self) Self { var vals: [d][d]f32 = undefined; const a = self.transpose(); const b = other; comptime var i = 0; inline while (i < d) : (i += 1) { comptime var j = 0; inline while (j < d) : (j += 1) { const row: @Vector(d, f32) = a.vals[j]; const col: @Vector(d, f32) = b.vals[i]; const prod: [d]f32 = row * col; var sum: f32 = 0; for (prod) |p| { sum += p; } vals[i][j] = sum; } } return Self{ .vals = vals }; } // while std.testing.expectEqual is broken pub fn expectEqual(self: Self, other: Self) void { comptime var i = 0; inline while (i < d) : (i += 1) { std.testing.expectEqual(self.vals[i], other.vals[i]); } } }; } pub const Mat2 = Matrix(2); pub const Mat3 = Matrix(3); pub const Mat4 = Matrix(4); /// Transformation matrix for translation by v pub fn translation(v: Vec3) Mat4 { return Mat4{ .vals = [4][4]f32{ .{ 1.0, 0.0, 0.0, 0.0 }, .{ 0.0, 1.0, 0.0, 0.0 }, .{ 0.0, 0.0, 1.0, 0.0 }, .{ v.vals[0], v.vals[1], v.vals[2], 1.0 }, }, }; } /// Transformation matrix for rotation around the z axis by a radians pub fn rotation(angle: f32, axis: Vec3) Mat4 { const unit = axis.normalize(); const x = unit.vals[0]; const y = unit.vals[1]; const z = unit.vals[2]; const a = cos(angle) + x * x * (1 - cos(angle)); const b = y * x * (1 - cos(angle)) + z * sin(angle); const c = z * x * (1 - cos(angle)) - y * sin(angle); const d = x * y * (1 - cos(angle)) - z * sin(angle); const e = cos(angle) + y * y * (1 - cos(angle)); const f = z * y * (1 - cos(angle)) + x * sin(angle); const h = x * z * (1 - cos(angle)) + y * sin(angle); const i = y * z * (1 - cos(angle)) - x * sin(angle); const j = cos(angle) + z * z * (1 - cos(angle)); return Mat4{ .vals = [4][4]f32{ .{ a, b, c, 0.0 }, .{ d, e, f, 0.0 }, .{ h, i, j, 0.0 }, .{ 0.0, 0.0, 0.0, 1.0 }, }, }; } pub fn scale(magnitude: Vec3) Mat4 { return Mat4{ .vals = [4][4]f32{ .{ magnitude.vals[0], 0.0, 0.0, 0.0 }, .{ 0.0, magnitude.vals[1], 0.0, 0.0 }, .{ 0.0, 0.0, magnitude.vals[2], 0.0 }, .{ 0.0, 0.0, 0.0, 1.0 }, }, }; } /// View matrix for camera at eye, looking at center, oriented by up pub fn lookAt(eye: Vec3, center: Vec3, up: Vec3) Mat4 { const f = center.sub(eye).normalize(); const s = f.cross(up).normalize(); const u = s.cross(f); return Mat4{ .vals = [4][4]f32{ .{ s.vals[0], u.vals[0], -f.vals[0], 0.0 }, .{ s.vals[1], u.vals[1], -f.vals[1], 0.0 }, .{ s.vals[2], u.vals[2], -f.vals[2], 0.0 }, .{ -s.dot(eye), -u.dot(eye), f.dot(eye), 1.0 }, }, }; } /// Perspective projection matrix pub fn perspective(fovy: f32, aspect: f32, znear: f32, zfar: f32) Mat4 { const tanhalffovy = tan(fovy / 2.0); const a = 1.0 / (aspect * tanhalffovy); const b = 1.0 / tanhalffovy; const c = -(zfar + znear) / (zfar - znear); const d = -(2.0 * zfar * znear) / (zfar - znear); return Mat4{ .vals = [4][4]f32{ .{ a, 0.0, 0.0, 0.0 }, .{ 0.0, b, 0.0, 0.0 }, .{ 0.0, 0.0, c, -1.0 }, .{ 0.0, 0.0, d, 0.0 }, }, }; } /// Orthographic projection matrix pub fn ortho(left: f32, right: f32, bottom: f32, top: f32, znear: f32, zfar: f32) Mat4 { const a = 2.0 / (right - left); const b = 2.0 / (top - bottom); const c = -2.0 / (zfar - znear); const d = -(right + left) / (right - left); const e = -(top + bottom) / (top - bottom); const f = -(zfar + znear) / (zfar - znear); return Mat4{ .vals = [4][4]f32{ .{ a, 0.0, 0.0, 0.0 }, .{ 0.0, b, 0.0, 0.0 }, .{ 0.0, 0.0, c, -1.0 }, .{ d, e, f, 0.0 }, }, }; }
src/glm.zig
const std = @import("std.zig"); const builtin = @import("builtin"); pub const Ordering = std.builtin.AtomicOrder; pub const Stack = @import("atomic/stack.zig").Stack; pub const Queue = @import("atomic/queue.zig").Queue; pub const Atomic = @import("atomic/Atomic.zig").Atomic; test "std.atomic" { _ = @import("atomic/stack.zig"); _ = @import("atomic/queue.zig"); _ = @import("atomic/Atomic.zig"); } pub inline fn fence(comptime ordering: Ordering) void { switch (ordering) { .Acquire, .Release, .AcqRel, .SeqCst => { @fence(ordering); }, else => { @compileLog(ordering, " only applies to a given memory location"); }, } } pub inline fn compilerFence(comptime ordering: Ordering) void { switch (ordering) { .Acquire, .Release, .AcqRel, .SeqCst => asm volatile ("" ::: "memory"), else => @compileLog(ordering, " only applies to a given memory location"), } } test "fence/compilerFence" { inline for (.{ .Acquire, .Release, .AcqRel, .SeqCst }) |ordering| { compilerFence(ordering); fence(ordering); } } /// Signals to the processor that the caller is inside a busy-wait spin-loop. pub inline fn spinLoopHint() void { switch (builtin.target.cpu.arch) { // No-op instruction that can hint to save (or share with a hardware-thread) // pipelining/power resources // https://software.intel.com/content/www/us/en/develop/articles/benefitting-power-and-performance-sleep-loops.html .i386, .x86_64 => asm volatile ("pause" ::: "memory"), // No-op instruction that serves as a hardware-thread resource yield hint. // https://stackoverflow.com/a/7588941 .powerpc64, .powerpc64le => asm volatile ("or 27, 27, 27" ::: "memory"), // `isb` appears more reliable for releasing execution resources than `yield` // on common aarch64 CPUs. // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604 // https://bugs.mysql.com/bug.php?id=100664 .aarch64, .aarch64_be, .aarch64_32 => asm volatile ("isb" ::: "memory"), // `yield` was introduced in v6k but is also available on v6m. // https://www.keil.com/support/man/docs/armasm/armasm_dom1361289926796.htm .arm, .armeb, .thumb, .thumbeb => { const can_yield = comptime std.Target.arm.featureSetHasAny(builtin.target.cpu.features, .{ .has_v6k, .has_v6m, }); if (can_yield) { asm volatile ("yield" ::: "memory"); } else { asm volatile ("" ::: "memory"); } }, // Memory barrier to prevent the compiler from optimizing away the spin-loop // even if no hint_instruction was provided. else => asm volatile ("" ::: "memory"), } } test "spinLoopHint" { var i: usize = 10; while (i > 0) : (i -= 1) { spinLoopHint(); } } /// The estimated size of the CPU's cache line when atomically updating memory. /// Add this much padding or align to this boundary to avoid atomically-updated /// memory from forcing cache invalidations on near, but non-atomic, memory. /// // https://en.wikipedia.org/wiki/False_sharing // https://github.com/golang/go/search?q=CacheLinePadSize pub const cache_line = switch (builtin.cpu.arch) { // x86_64: Starting from Intel's Sandy Bridge, the spatial prefetcher pulls in pairs of 64-byte cache lines at a time. // - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf // - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107 // // aarch64: Some big.LITTLE ARM archs have "big" cores with 128-byte cache lines: // - https://www.mono-project.com/news/2016/09/12/arm64-icache/ // - https://cpufun.substack.com/p/more-m1-fun-hardware-information // // powerpc64: PPC has 128-byte cache lines // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9 .x86_64, .aarch64, .powerpc64 => 128, // These platforms reportedly have 32-byte cache lines // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_riscv64.go#L7 .arm, .mips, .mips64, .riscv64 => 32, // This platform reportedly has 256-byte cache lines // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7 .s390x => 256, // Other x86 and WASM platforms have 64-byte cache lines. // The rest of the architectures are assumed to be similar. // - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7 else => 64, };
lib/std/atomic.zig
const libpoke = @import("../src/pokemon/index.zig"); const utils = @import("../src/utils/index.zig"); const fakes = @import("fake_roms.zig"); const std = @import("std"); const fun = @import("../lib/fun-with-zig/src/index.zig"); // TODO: Package stuff const heap = std.heap; const os = std.os; const debug = std.debug; const rand = std.rand; const math = std.math; const time = os.time; const loop = fun.loop; const max_alloc = 100 * 1024 * 1024; const Randomizer = @import("../src/randomizer.zig").Randomizer; const Options = @import("../src/randomizer.zig").Options; test "Fake rom: Api" { var direct_alloc = heap.DirectAllocator.init(); const buf = try direct_alloc.allocator.alloc(u8, max_alloc); defer direct_alloc.allocator.free(buf); var gen_alloc = heap.FixedBufferAllocator.init(buf); const roms_files = try fakes.generateFakeRoms(&gen_alloc.allocator); defer fakes.deleteFakeRoms(&gen_alloc.allocator); var timer = try time.Timer.start(); debug.warn("\n"); for (roms_files) |file_name, i| { var fix_buf_alloc = heap.FixedBufferAllocator.init(buf[gen_alloc.end_index..]); const allocator = &fix_buf_alloc.allocator; debug.warn("Testing api ({}/{}): '{}':\n", i + 1, roms_files.len, file_name); defer debug.warn("Ok\n"); var file = try os.File.openRead(file_name); defer file.close(); timer.reset(); var game = try libpoke.Game.load(file, allocator); defer game.deinit(); const time_to_load = timer.read(); debug.warn("* Rom size: {B}\n", file.getEndPos()); debug.warn("* Mem allocated: {B}\n", fix_buf_alloc.end_index); debug.warn("* Time taken: {}ms\n", time_to_load / 1000000); { const pokemons = game.pokemons(); debug.assert(pokemons.len() > 0); var it = pokemons.iterator(); while (try it.next()) |pair| { const pokemon = pair.value; debug.assert(pokemon.hp().* == fakes.hp); debug.assert(pokemon.attack().* == fakes.attack); debug.assert(pokemon.defense().* == fakes.defense); debug.assert(pokemon.speed().* == fakes.speed); debug.assert(pokemon.spAttack().* == fakes.sp_attack); debug.assert(pokemon.spDefense().* == fakes.sp_defense); debug.assert(pokemon.types()[0] == fakes.ptype); debug.assert(pokemon.types()[1] == fakes.ptype); const lvl_moves = pokemon.levelUpMoves(); debug.assert(lvl_moves.len() == 1); const lvl_move = lvl_moves.at(0); debug.assert(lvl_move.moveId() == fakes.move); debug.assert(lvl_move.level() == fakes.level); const tms = pokemon.tmLearnset(); const hms = pokemon.hmLearnset(); debug.assert(tms.len() > 0); debug.assert(hms.len() > 0); var tm_it = tms.iterator(); var hm_it = hms.iterator(); while (tm_it.next()) |can_learn| debug.assert(!can_learn.value); while (hm_it.next()) |can_learn| debug.assert(!can_learn.value); } } { const trainers = game.trainers(); debug.assert(trainers.len() > 0); var it = trainers.iterator(); while (try it.next()) |pair| { const trainer = pair.value; const party = trainer.party(); debug.assert(party.len() > 0); var party_it = party.iterator(); while (party_it.next()) |party_pair| { const party_member = party_pair.value; debug.assert(party_member.level() == fakes.level); debug.assert(party_member.species() == fakes.species); if (party_member.moves()) |moves| { debug.assert(moves.at(0) == fakes.move); debug.assert(moves.at(1) == fakes.move); debug.assert(moves.at(2) == fakes.move); debug.assert(moves.at(3) == fakes.move); } if (party_member.item()) |item| { debug.assert(fakes.item == item); } } } } { const moves = game.moves(); debug.assert(moves.len() > 0); var it = moves.iterator(); while (try it.next()) |pair| { const move = pair.value; debug.assert(move.power().* == fakes.power); debug.assert(move.pp().* == fakes.pp); for (move.types().*) |t| debug.assert(t == fakes.ptype); } } { const tms = game.tms(); const hms = game.hms(); debug.assert(tms.len() > 0); debug.assert(hms.len() > 0); var tm_it = tms.iterator(); var hm_it = hms.iterator(); while (tm_it.next()) |move_id| debug.assert(move_id.value == fakes.move); while (hm_it.next()) |move_id| debug.assert(move_id.value == fakes.move); } { const zones = game.zones(); debug.assert(zones.len() > 0); var zone_it = zones.iterator(); while (try zone_it.next()) |zone| { const wild_pokemons = zone.value.getWildPokemons(); debug.assert(wild_pokemons.len() > 0); var wild_it = wild_pokemons.iterator(); while (try wild_it.next()) |wild_mon| { debug.assert(wild_mon.value.getSpecies() == fakes.species); debug.assert(wild_mon.value.getMinLevel() == fakes.level); debug.assert(wild_mon.value.getMaxLevel() == fakes.level); } } } } } fn randomEnum(random: *rand.Random, comptime Enum: type) Enum { const info = @typeInfo(Enum).Enum; const f = info.fields[random.range(usize, 0, info.fields.len)]; return @intToEnum(Enum, @intCast(info.tag_type, f.value)); } test "Fake rom: Randomizer" { var direct_alloc = heap.DirectAllocator.init(); const buf = try direct_alloc.allocator.alloc(u8, max_alloc); defer direct_alloc.allocator.free(buf); var gen_alloc = heap.FixedBufferAllocator.init(buf); const roms_files = try fakes.generateFakeRoms(&gen_alloc.allocator); defer fakes.deleteFakeRoms(&gen_alloc.allocator); var timer = try time.Timer.start(); debug.warn("\n"); for (roms_files) |file_name, i| { debug.warn("Testing randomizer ({}/{}): '{}':\n", i + 1, roms_files.len, file_name); defer debug.warn("Ok\n"); const game_buf = buf[gen_alloc.end_index..]; var game_alloc = heap.FixedBufferAllocator.init(game_buf); var file = try os.File.openRead(file_name); defer file.close(); var game = try libpoke.Game.load(file, &game_alloc.allocator); defer game.deinit(); var max_mem: usize = 0; var max_time: u64 = 0; var random = &rand.DefaultPrng.init(0).random; for (loop.to(20)) |_| { debug.warn("."); var options = Options{ .trainer = Options.Trainer{ .pokemon = randomEnum(random, Options.Trainer.Pokemon), .same_total_stats = random.scalar(bool), .held_items = randomEnum(random, Options.Trainer.HeldItems), .moves = randomEnum(random, Options.Trainer.Moves), .level_modifier = random.float(f64) * 2, }, }; var rand_alloc = heap.FixedBufferAllocator.init(game_buf[game_alloc.end_index..]); var r = Randomizer.init(game, random, &rand_alloc.allocator); timer.reset(); try r.randomize(options); max_time = math.max(max_time, timer.read()); max_mem = math.max(max_mem, rand_alloc.end_index); } debug.warn("\n"); debug.warn("* Max mem allocated: {B}\n", max_mem); debug.warn("* Max time taken: {}ms\n", max_time / 1000000); } }
test/index.zig
const std = @import("std"); const warn = std.debug.warn; const builtin = @import("builtin"); const TypeId = builtin.TypeId; pub fn ArgParser(comptime T: type) type { return struct { values: T, available: std.StringHashMap(bool), const Self = @This(); const memberCt = @memberCount(T); pub fn init(a: *std.mem.Allocator) !Self { var self = Self{ .values = T{}, .available = std.StringHashMap(bool).init(a), }; inline for (@typeInfo(T).Struct.fields) |f| { _ = try self.available.put(f.name, false); } return self; } pub fn parse(self: *Self, a: *std.mem.Allocator) !void { // Loop over user struct member names and look for case sensitive matching // names on command line, optionally stripping leading hyphens. // Have to do this the inefficient, hard way in order to have comptime // known i for @memberType(T, i) var buf: [1024]u8 = undefined; const fa = &std.heap.FixedBufferAllocator.init(buf[0..]).allocator; const args = try std.process.argsAlloc(fa); defer std.process.argsFree(fa, args); inline for (@typeInfo(T).Struct.fields) |f, i| { const fieldName = f.name; var arg_idx = blk: { var j = usize(0); while (j < args.len) : (j += 1) { var arg = args[j]; // strip off one or two hyphens if (arg[0] == '-') arg = arg[1..]; if (arg[0] == '-') arg = arg[1..]; if (std.mem.eql(u8, arg, fieldName)) { break :blk j; } } break :blk std.math.maxInt(usize); }; if (arg_idx < args.len) { arg_idx += 1; // * i has to be comptime known here const typ = @memberType(T, i); const ti = @typeInfo(typ); switch (ti) { TypeId.Float => { @field(self.values, fieldName) = try std.fmt.parseFloat(typ, args[arg_idx]); }, TypeId.Int => { @field(self.values, fieldName) = try std.fmt.parseInt(typ, args[arg_idx], 10); }, TypeId.Bool => { @field(self.values, fieldName) = true; }, TypeId.Array => { const cti = @typeInfo(typ.Child); var fi = usize(0); while (fi < typ.len and arg_idx + fi < args.len) : (fi += 1) { switch (cti) { TypeId.Float => { @field(self.values, fieldName)[fi] = std.fmt.parseFloat(typ.Child, args[arg_idx + fi]) catch break; }, TypeId.Int => { @field(self.values, fieldName)[fi] = std.fmt.parseInt(typ.Child, args[arg_idx + fi], 10) catch break; }, TypeId.Bool => { @field(self.values, fieldName)[fi] = std.fmt.parseBool(args[arg_idx + fi], 10) catch break; }, else => { warn("ERROR: unsupported array type " ++ @typeName(tpy.Child) ++ "\n"); break; }, } } }, TypeId.Pointer => { switch (ti.Pointer.size) { builtin.TypeInfo.Pointer.Size.Slice => { @field(self.values, fieldName) = try std.mem.dupe(a, ti.Pointer.child, args[arg_idx]); }, builtin.TypeInfo.Pointer.Size.One, builtin.TypeInfo.Pointer.Size.Many, builtin.TypeInfo.Pointer.Size.C, => { warn("ERROR: unsupported non-slice pointer type found\n"); continue; }, } }, else => { warn("ERROR: unsupported type " ++ @typeName(typ) ++ " ignored\n"); }, } _ = try self.available.put(fieldName, true); } } } pub fn show(self: Self) void { inline for (@typeInfo(T).Struct.fields) |f| { const fieldName = f.name; var me = self.available.get(fieldName); if (me) |e| { if (e.value) { switch (@typeInfo(f.field_type)) { TypeId.Array => { warn(fieldName ++ ": "); for (@field(self.values, fieldName)) |x| warn("{}, ", x); warn("\n"); }, else => { warn("{}: {}\n", e.key, @field(self.values, fieldName)); }, } } } } } }; }
src/parser.zig
const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const HRESULT = windows.HRESULT; const WINAPI = windows.WINAPI; const GUID = windows.GUID; const UINT = windows.UINT; const BOOL = windows.BOOL; pub const GPU_BASED_VALIDATION_FLAGS = UINT; pub const GPU_BASED_VALIDATION_FLAG_NONE = 0; pub const GPU_BASED_VALIDATION_FLAG_DISABLE_STATE_TRACKING = 0x1; pub const IDebug = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn EnableDebugLayer(self: *T) void { self.v.debug.EnableDebugLayer(self); } }; } fn VTable(comptime T: type) type { return extern struct { EnableDebugLayer: fn (*T) callconv(WINAPI) void, }; } }; pub const IDebug1 = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug1: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn EnableDebugLayer(self: *T) void { self.v.debug1.EnableDebugLayer(self); } pub inline fn SetEnableGPUBasedValidation(self: *T, enable: BOOL) void { self.v.debug1.SetEnableGPUBasedValidation(self, enable); } pub inline fn SetEnableSynchronizedCommandQueueValidation(self: *T, enable: BOOL) void { self.v.debug1.SetEnableSynchronizedCommandQueueValidation(self, enable); } }; } fn VTable(comptime T: type) type { return extern struct { EnableDebugLayer: fn (*T) callconv(WINAPI) void, SetEnableGPUBasedValidation: fn (*T, BOOL) callconv(WINAPI) void, SetEnableSynchronizedCommandQueueValidation: fn (*T, BOOL) callconv(WINAPI) void, }; } }; pub const IDebug2 = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug2: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn SetGPUBasedValidationFlags(self: *T, flags: GPU_BASED_VALIDATION_FLAGS) void { self.v.debug2.SetGPUBasedValidationFlags(self, flags); } }; } fn VTable(comptime T: type) type { return extern struct { SetGPUBasedValidationFlags: fn (*T, GPU_BASED_VALIDATION_FLAGS) callconv(WINAPI) void, }; } }; pub const IDebug3 = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug: IDebug.VTable(Self), debug3: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDebug.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn SetEnableGPUBasedValidation(self: *T, enable: BOOL) void { self.v.debug3.SetEnableGPUBasedValidation(self, enable); } pub inline fn SetEnableSynchronizedCommandQueueValidation(self: *T, enable: BOOL) void { self.v.debug3.SetEnableSynchronizedCommandQueueValidation(self, enable); } pub inline fn SetGPUBasedValidationFlags(self: *T, flags: GPU_BASED_VALIDATION_FLAGS) void { self.v.debug3.SetGPUBasedValidationFlags(self, flags); } }; } fn VTable(comptime T: type) type { return extern struct { SetEnableGPUBasedValidation: fn (*T, BOOL) callconv(WINAPI) void, SetEnableSynchronizedCommandQueueValidation: fn (*T, BOOL) callconv(WINAPI) void, SetGPUBasedValidationFlags: fn (*T, GPU_BASED_VALIDATION_FLAGS) callconv(WINAPI) void, }; } }; pub const IDebug4 = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug: IDebug.VTable(Self), debug3: IDebug3.VTable(Self), debug4: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDebug.Methods(Self); usingnamespace IDebug3.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn DisableDebugLayer(self: *T) void { self.v.debug4.DisableDebugLayer(self); } }; } fn VTable(comptime T: type) type { return extern struct { DisableDebugLayer: fn (*T) callconv(WINAPI) void, }; } }; pub const IDebug5 = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), debug: IDebug.VTable(Self), debug3: IDebug3.VTable(Self), debug4: IDebug4.VTable(Self), debug5: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDebug.Methods(Self); usingnamespace IDebug3.Methods(Self); usingnamespace IDebug4.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn SetEnableAutoName(self: *T, enable: BOOL) void { self.v.debug5.SetEnableAutoName(self, enable); } }; } fn VTable(comptime T: type) type { return extern struct { SetEnableAutoName: fn (*T, BOOL) callconv(WINAPI) void, }; } }; pub const MESSAGE_CATEGORY = enum(UINT) { APPLICATION_DEFINED = 0, MISCELLANEOUS = 1, INITIALIZATION = 2, CLEANUP = 3, COMPILATION = 4, STATE_CREATION = 5, STATE_SETTING = 6, STATE_GETTING = 7, RESOURCE_MANIPULATION = 8, EXECUTION = 9, SHADER = 10, }; pub const MESSAGE_SEVERITY = enum(UINT) { CORRUPTION = 0, ERROR = 1, WARNING = 2, INFO = 3, MESSAGE = 4, }; pub const MESSAGE_ID = enum(UINT) { CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE = 820, COMMAND_LIST_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL = 209, CREATEGRAPHICSPIPELINESTATE_DEPTHSTENCILVIEW_NOT_SET = 680, }; pub const INFO_QUEUE_FILTER_DESC = extern struct { NumCategories: u32, pCategoryList: ?[*]MESSAGE_CATEGORY, NumSeverities: u32, pSeverityList: ?[*]MESSAGE_SEVERITY, NumIDs: u32, pIDList: ?[*]MESSAGE_ID, }; pub const INFO_QUEUE_FILTER = extern struct { AllowList: INFO_QUEUE_FILTER_DESC, DenyList: INFO_QUEUE_FILTER_DESC, }; pub const IInfoQueue = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), info: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn AddStorageFilterEntries(self: *T, filter: *INFO_QUEUE_FILTER) HRESULT { return self.v.info.AddStorageFilterEntries(self, filter); } pub inline fn PushStorageFilter(self: *T, filter: *INFO_QUEUE_FILTER) HRESULT { return self.v.info.PushStorageFilter(self, filter); } pub inline fn PopStorageFilter(self: *T) void { self.v.info.PopStorageFilter(self); } pub inline fn SetMuteDebugOutput(self: *T, mute: BOOL) void { self.v.info.SetMuteDebugOutput(self, mute); } }; } fn VTable(comptime T: type) type { return extern struct { SetMessageCountLimit: *anyopaque, ClearStoredMessages: *anyopaque, GetMessage: *anyopaque, GetNumMessagesAllowedByStorageFilter: *anyopaque, GetNumMessagesDeniedByStorageFilter: *anyopaque, GetNumStoredMessages: *anyopaque, GetNumStoredMessagesAllowedByRetrievalFilter: *anyopaque, GetNumMessagesDiscardedByMessageCountLimit: *anyopaque, GetMessageCountLimit: *anyopaque, AddStorageFilterEntries: fn (*T, *INFO_QUEUE_FILTER) callconv(WINAPI) HRESULT, GetStorageFilter: *anyopaque, ClearStorageFilter: *anyopaque, PushEmptyStorageFilter: *anyopaque, PushCopyOfStorageFilter: *anyopaque, PushStorageFilter: fn (*T, *INFO_QUEUE_FILTER) callconv(WINAPI) HRESULT, PopStorageFilter: fn (*T) callconv(WINAPI) void, GetStorageFilterStackSize: *anyopaque, AddRetrievalFilterEntries: *anyopaque, GetRetrievalFilter: *anyopaque, ClearRetrievalFilter: *anyopaque, PushEmptyRetrievalFilter: *anyopaque, PushCopyOfRetrievalFilter: *anyopaque, PushRetrievalFilter: *anyopaque, PopRetrievalFilter: *anyopaque, GetRetrievalFilterStackSize: *anyopaque, AddMessage: *anyopaque, AddApplicationMessage: *anyopaque, SetBreakOnCategory: *anyopaque, SetBreakOnSeverity: *anyopaque, SetBreakOnID: *anyopaque, GetBreakOnCategory: *anyopaque, GetBreakOnSeverity: *anyopaque, GetBreakOnID: *anyopaque, SetMuteDebugOutput: fn (*T, BOOL) callconv(WINAPI) void, GetMuteDebugOutput: *anyopaque, }; } }; pub const IID_IDebug = GUID{ .Data1 = 0x344488b7, .Data2 = 0x6846, .Data3 = 0x474b, .Data4 = .{ 0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0 }, }; pub const IID_IDebug1 = GUID{ .Data1 = 0xaffaa4ca, .Data2 = 0x63fe, .Data3 = 0x4d8e, .Data4 = .{ 0xb8, 0xad, 0x15, 0x90, 0x00, 0xaf, 0x43, 0x04 }, }; pub const IID_IDebug2 = GUID{ .Data1 = 0x93a665c4, .Data2 = 0xa3b2, .Data3 = 0x4e5d, .Data4 = .{ 0xb6, 0x92, 0xa2, 0x6a, 0xe1, 0x4e, 0x33, 0x74 }, }; pub const IID_IDebug3 = GUID{ .Data1 = 0x5cf4e58f, .Data2 = 0xf671, .Data3 = 0x4ff0, .Data4 = .{ 0xa5, 0x42, 0x36, 0x86, 0xe3, 0xd1, 0x53, 0xd1 }, }; pub const IID_IDebug4 = GUID{ .Data1 = 0x014b816e, .Data2 = 0x9ec5, .Data3 = 0x4a2f, .Data4 = .{ 0xa8, 0x45, 0xff, 0xbe, 0x44, 0x1c, 0xe1, 0x3a }, }; pub const IID_IDebug5 = GUID{ .Data1 = 0x548d6b12, .Data2 = 0x09fa, .Data3 = 0x40e0, .Data4 = .{ 0x90, 0x69, 0x5d, 0xcd, 0x58, 0x9a, 0x52, 0xc9 }, }; pub const IID_IInfoQueue = GUID{ .Data1 = 0x0742a90b, .Data2 = 0xc387, .Data3 = 0x483f, .Data4 = .{ 0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58 }, };
modules/platform/vendored/zwin32/src/d3d12sdklayers.zig
const std = @import("std"); const stdx = @import("stdx"); const Duration = stdx.time.Duration; const platform = @import("platform"); const KeyDownEvent = platform.KeyDownEvent; const graphics = @import("graphics"); const FontGroupId = graphics.FontGroupId; const Color = graphics.Color; const ui = @import("../ui.zig"); const Node = ui.Node; const ScrollView = ui.widgets.ScrollView; const log = stdx.log.scoped(.text_editor); /// Note: This widget is very incomplete. It could borrow some techniques used in TextField. /// Also this will be renamed to TextArea and expose a maxLines property as well as things that might be useful for an advanced TextEditor. pub const TextEditor = struct { props: struct { init_val: []const u8, font_family: graphics.FontFamily = graphics.FontFamily.Default, width: f32 = 400, height: f32 = 300, text_color: Color = Color.Black, bg_color: Color = Color.White, }, lines: std.ArrayList(Line), caret_line: u32, caret_col: u32, inner: ui.WidgetRef(TextEditorInner), scroll_view: ui.WidgetRef(ScrollView), // Current font group used. font_gid: FontGroupId, font_size: f32, font_vmetrics: graphics.VMetrics, font_line_height: u32, font_line_offset_y: f32, // y offset to first text line is drawn ctx: *ui.CommonContext, node: *Node, const Self = @This(); pub fn init(self: *Self, c: *ui.InitContext) void { const props = self.props; self.font_gid = c.getFontGroupByFamily(self.props.font_family); self.lines = std.ArrayList(Line).init(c.alloc); self.caret_line = 0; self.caret_col = 0; self.inner = .{}; self.scroll_view = .{}; self.ctx = c.common; self.node = c.node; self.setFontSize(24); var iter = std.mem.split(u8, props.init_val, "\n"); self.lines = std.ArrayList(Line).init(c.alloc); while (iter.next()) |it| { var line = Line.init(c.alloc); line.buf.appendSubStr(it) catch @panic("error"); self.lines.append(line) catch unreachable; line.width = c.measureText(self.font_gid, self.font_size, line.buf.buf.items).width; } // Ensure at least one line. if (self.lines.items.len == 0) { const line = Line.init(c.alloc); self.lines.append(line) catch unreachable; } c.addKeyDownHandler(self, Self.handleKeyDownEvent); } pub fn deinit(node: *Node, _: std.mem.Allocator) void { const self = node.getWidget(Self); for (self.lines.items) |line| { line.deinit(); } self.lines.deinit(); } pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { return c.decl(ScrollView, .{ .bind = &self.scroll_view, .bg_color = self.props.bg_color, .onContentMouseDown = c.funcExt(self, onMouseDown), .child = c.decl(TextEditorInner, .{ .bind = &self.inner, .editor = self, }), }); } pub fn postPropsUpdate(self: *Self) void { const new_font_gid = self.ctx.getFontGroupByFamily(self.props.font_family); if (new_font_gid != self.font_gid) { self.font_gid = new_font_gid; self.remeasureText(); } } fn onMouseDown(self: *Self, e: platform.MouseDownEvent) void { self.requestFocus(); // Map mouse pos to caret pos. const scroll_view = self.scroll_view.getWidget(); const xf = @intToFloat(f32, e.x) - self.node.abs_pos.x + scroll_view.scroll_x; const yf = @intToFloat(f32, e.y) - self.node.abs_pos.y + scroll_view.scroll_y; const loc = self.toCaretLoc(self.ctx, xf, yf); self.caret_line = loc.line_idx; self.caret_col = loc.col_idx; self.postCaretUpdate(); } /// Request focus on the TextEditor. pub fn requestFocus(self: *Self) void { self.ctx.requestFocus(self.node, onBlur); const inner = self.inner.getWidget(); inner.setFocused(); // std.crypto.hash.Md5.hash(self.buf.items, &self.last_buf_hash, .{}); } fn onBlur(node: *Node, ctx: *ui.CommonContext) void { _ = ctx; const self = node.getWidget(Self); self.inner.getWidget().focused = false; // var hash: [16]u8 = undefined; // std.crypto.hash.Md5.hash(self.buf.items, &hash, .{}); // if (!std.mem.eql(u8, &hash, &self.last_buf_hash)) { // self.fireOnChangeEnd(); // } } fn toCaretLoc(self: *Self, ctx: *ui.CommonContext, x: f32, y: f32) DocLocation { if (y < 0) { return .{ .line_idx = 0, .col_idx = 0, }; } const line_idx = @floatToInt(u32, y / @intToFloat(f32, self.font_line_height)); if (line_idx >= self.lines.items.len) { return .{ .line_idx = @intCast(u32, self.lines.items.len - 1), .col_idx = @intCast(u32, self.lines.items[self.lines.items.len-1].buf.num_chars), }; } var iter = ctx.textGlyphIter(self.font_gid, self.font_size, self.lines.items[line_idx].buf.buf.items); if (iter.nextCodepoint()) { if (x < iter.state.advance_width/2) { return .{ .line_idx = line_idx, .col_idx = 0, }; } } else { return .{ .line_idx = line_idx, .col_idx = 0, }; } var cur_x: f32 = iter.state.advance_width; var col: u32 = 1; while (iter.nextCodepoint()) { if (x < cur_x + iter.state.advance_width/2) { return .{ .line_idx = line_idx, .col_idx = col, }; } cur_x = @round(cur_x + iter.state.kern); cur_x += iter.state.advance_width; col += 1; } return .{ .line_idx = line_idx, .col_idx = col, }; } fn remeasureText(self: *Self) void { const font_vmetrics = self.ctx.getPrimaryFontVMetrics(self.font_gid, self.font_size); // log.warn("METRICS {}", .{font_vmetrics}); const font_line_height_factor: f32 = 1.2; const font_line_height = @round(font_line_height_factor * self.font_size); const font_line_offset_y = (font_line_height - font_vmetrics.height) / 2; // log.warn("{} {} {}", .{font_vmetrics.height, font_line_height, font_line_offset_y}); self.font_vmetrics = font_vmetrics; self.font_line_height = @floatToInt(u32, font_line_height); self.font_line_offset_y = font_line_offset_y; for (self.lines.items) |*line| { line.width = self.ctx.measureText(self.font_gid, self.font_size, line.buf.buf.items).width; } if (self.inner.binded) { const w = self.inner.getWidget(); w.to_caret_width = self.ctx.measureText(self.font_gid, self.font_size, w.to_caret_str).width; } } pub fn setFontSize(self: *Self, font_size: f32) void { self.font_size = font_size; self.remeasureText(); } fn getCaretBottomY(self: *Self) f32 { return @intToFloat(f32, self.caret_line + 1) * @intToFloat(f32, self.font_line_height); } fn getCaretTopY(self: *Self) f32 { return @intToFloat(f32, self.caret_line) * @intToFloat(f32, self.font_line_height); } fn getCaretX(self: *Self) f32 { return self.inner.getWidget().to_caret_width; } fn postLineUpdate(self: *Self, idx: usize) void { const line = &self.lines.items[idx]; line.width = self.ctx.measureText(self.font_gid, self.font_size, line.buf.buf.items).width; self.inner.getWidget().resetCaretAnimation(); } fn postCaretUpdate(self: *Self) void { self.inner.getWidget().postCaretUpdate(); // Scroll to caret. const S = struct { fn cb(self_: *Self) void { const sv = self_.scroll_view.getWidget(); const svn = self_.scroll_view.node; const caret_x = self_.getCaretX(); const caret_bottom_y = self_.getCaretBottomY(); const caret_top_y = self_.getCaretTopY(); const view_width = self_.scroll_view.getWidth(); const view_height = self_.scroll_view.getHeight(); if (caret_bottom_y > sv.scroll_y + view_height) { // Below current view sv.setScrollPosAfterLayout(svn, sv.scroll_x, caret_bottom_y - view_height); } else if (caret_top_y < sv.scroll_y) { // Above current view sv.setScrollPosAfterLayout(svn, sv.scroll_x, caret_top_y); } if (caret_x > sv.scroll_x + view_width) { // Right of current view sv.setScrollPosAfterLayout(svn, caret_x - view_width, sv.scroll_y); } else if (caret_x < sv.scroll_x) { // Left of current view sv.setScrollPosAfterLayout(svn, caret_x, sv.scroll_y); } } }; self.ctx.nextPostLayout(self, S.cb); } fn handleKeyDownEvent(self: *Self, e: ui.Event(KeyDownEvent)) void { _ = self; const c = e.ctx.common; const val = e.val; const line = &self.lines.items[self.caret_line]; if (val.code == .Backspace) { if (self.caret_col > 0) { if (line.buf.num_chars == self.caret_col) { line.buf.removeChar(line.buf.num_chars-1); } else { line.buf.removeChar(self.caret_col-1); } self.postLineUpdate(self.caret_line); self.caret_col -= 1; self.postCaretUpdate(); } else if (self.caret_line > 0) { // Join current line with previous. var prev_line = &self.lines.items[self.caret_line-1]; self.caret_col = prev_line.buf.num_chars; prev_line.buf.appendSubStr(line.buf.buf.items) catch @panic("error"); line.deinit(); _ = self.lines.orderedRemove(self.caret_line); self.postLineUpdate(self.caret_line-1); self.caret_line -= 1; self.postCaretUpdate(); } } else if (val.code == .Delete) { if (self.caret_col < line.buf.num_chars) { line.buf.removeChar(self.caret_col); self.postLineUpdate(self.caret_line); } else { // Append next line. if (self.caret_line < self.lines.items.len-1) { line.buf.appendSubStr(self.lines.items[self.caret_line+1].buf.buf.items) catch @panic("error"); self.lines.items[self.caret_line+1].deinit(); _ = self.lines.orderedRemove(self.caret_line+1); self.postLineUpdate(self.caret_line); } } } else if (val.code == .Enter) { const new_line = Line.init(c.alloc); self.lines.insert(self.caret_line + 1, new_line) catch unreachable; // Requery current line since insert could have resized array. const cur_line = &self.lines.items[self.caret_line]; if (self.caret_col < cur_line.buf.num_chars) { // Move text after caret to the new line. const after_text = cur_line.buf.getSubStr(self.caret_col, cur_line.buf.num_chars); self.lines.items[self.caret_line+1].buf.appendSubStr(after_text) catch @panic("error"); cur_line.buf.removeSubStr(self.caret_col, cur_line.buf.num_chars); self.postLineUpdate(self.caret_line); } self.postLineUpdate(self.caret_line + 1); self.caret_line += 1; self.caret_col = 0; self.postCaretUpdate(); } else if (val.code == .ArrowLeft) { if (self.caret_col > 0) { self.caret_col -= 1; self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } else { if (self.caret_line > 0) { self.caret_line -= 1; self.caret_col = self.lines.items[self.caret_line].buf.num_chars; self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } } } else if (val.code == .ArrowRight) { if (self.caret_col < line.buf.num_chars) { self.caret_col += 1; self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } else { if (self.caret_line < self.lines.items.len-1) { self.caret_line += 1; self.caret_col = 0; self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } } } else if (val.code == .ArrowUp) { if (self.caret_line > 0) { self.caret_line -= 1; if (self.caret_col > self.lines.items[self.caret_line].buf.num_chars) { self.caret_col = self.lines.items[self.caret_line].buf.num_chars; } self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } } else if (val.code == .ArrowDown) { if (self.caret_line < self.lines.items.len-1) { self.caret_line += 1; if (self.caret_col > self.lines.items[self.caret_line].buf.num_chars) { self.caret_col = self.lines.items[self.caret_line].buf.num_chars; } self.postCaretUpdate(); self.inner.getWidget().resetCaretAnimation(); } } else { if (val.getPrintChar()) |ch| { if (self.caret_col == line.buf.num_chars) { line.buf.appendCodepoint(ch) catch @panic("error"); } else { line.buf.insertCodepoint(self.caret_col, ch) catch @panic("error"); } self.postLineUpdate(self.caret_line); self.caret_col += 1; self.postCaretUpdate(); } } } }; const Line = struct { const Self = @This(); alloc: std.mem.Allocator, buf: stdx.textbuf.TextBuffer, /// Computed width. width: f32, fn init(alloc: std.mem.Allocator) Self { return .{ .alloc = alloc, .buf = stdx.textbuf.TextBuffer.init(alloc, "") catch @panic("error"), .width = 0, }; } fn deinit(self: Self) void { self.buf.deinit(); } }; pub const TextEditorInner = struct { props: struct { editor: *TextEditor, }, caret_anim_show_toggle: bool, caret_anim_id: ui.IntervalId, to_caret_str: []const u8, to_caret_width: f32, editor: *TextEditor, ctx: *ui.CommonContext, focused: bool, const Self = @This(); pub fn init(self: *Self, c: *ui.InitContext) void { const props = self.props; self.caret_anim_id = c.addInterval(Duration.initSecsF(0.6), self, Self.handleCaretInterval); self.caret_anim_show_toggle = true; self.editor = props.editor; self.ctx = c.common; self.focused = false; self.to_caret_str = ""; self.to_caret_width = 0; } fn setFocused(self: *Self) void { self.focused = true; self.resetCaretAnimation(); } fn resetCaretAnimation(self: *Self) void { self.caret_anim_show_toggle = true; self.ctx.resetInterval(self.caret_anim_id); } fn postCaretUpdate(self: *Self) void { const line = self.editor.lines.items[self.editor.caret_line]; self.to_caret_str = line.buf.getSubStr(0, self.editor.caret_col); self.to_caret_width = self.ctx.measureText(self.props.editor.font_gid, self.props.editor.font_size, self.to_caret_str).width; } fn handleCaretInterval(self: *Self, e: ui.IntervalEvent) void { _ = e; self.caret_anim_show_toggle = !self.caret_anim_show_toggle; } pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = self; _ = c; return ui.NullFrameId; } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { _ = c; var height: f32 = 0; var max_width: f32 = 0; for (self.editor.lines.items) |it| { const width = it.width; if (width > max_width) { max_width = width; } height += @intToFloat(f32, self.editor.font_line_height); } return ui.LayoutSize.init(max_width, height); } pub fn render(self: *Self, c: *ui.RenderContext) void { _ = self; const editor = self.editor; const lo = c.getAbsLayout(); const g = c.getGraphics(); const line_height = @intToFloat(f32, editor.font_line_height); g.setFontGroup(editor.font_gid, editor.font_size); g.setFillColor(self.editor.props.text_color); // TODO: Use binary search when word wrap is enabled and we can't determine the first visible line with O(1) const scroll_view = editor.scroll_view.getWidget(); const visible_start_idx = std.math.max(0, @floatToInt(i32, @floor(scroll_view.scroll_y / line_height))); const visible_end_idx = std.math.min(editor.lines.items.len, @floatToInt(i32, @ceil((scroll_view.scroll_y + editor.scroll_view.getHeight()) / line_height))); // log.warn("{} {}", .{visible_start_idx, visible_end_idx}); const line_offset_y = editor.font_line_offset_y; var i: usize = @intCast(usize, visible_start_idx); while (i < visible_end_idx) : (i += 1) { const line = editor.lines.items[i]; g.fillText(lo.x, lo.y + line_offset_y + @intToFloat(f32, i) * line_height, line.buf.buf.items); } if (self.focused) { // Draw caret. if (self.caret_anim_show_toggle) { g.setFillColor(self.editor.props.text_color); // log.warn("width {d:2}", .{width}); const height = self.editor.font_vmetrics.height; g.fillRect(@round(lo.x + self.to_caret_width), lo.y + line_offset_y + @intToFloat(f32, self.editor.caret_line) * line_height, 1, height); } } } }; const DocLocation = struct { line_idx: u32, col_idx: u32, };
ui/src/widgets/text_editor.zig
const std = @import("std"); const stdx = @import("stdx"); const ds = stdx.ds; const graphics = @import("../../graphics.zig"); const FontGroupId = graphics.FontGroupId; const FontId = graphics.FontId; const Font = graphics.Font; const VMetrics = graphics.VMetrics; const RenderFont = graphics.gpu.RenderFont; const FontGroup = graphics.FontGroup; const gpu = graphics.gpu; const Glyph = gpu.Glyph; const TextMetrics = graphics.TextMetrics; const FontAtlas = @import("font_atlas.zig").FontAtlas; const Batcher = @import("batcher.zig").Batcher; const font_renderer = @import("font_renderer.zig"); const FontDesc = graphics.FontDesc; const log = std.log.scoped(.font_cache); pub const RenderFontId = u32; const RenderFontDesc = struct { font_id: RenderFontId, font_size: u16, }; const RenderFontKey = struct { font_id: FontId, font_size: u16, }; // Once we support SDFs we can increase this to 2^16 pub const MaxRenderFontSize = 256; // 2^8 pub const MinRenderFontSize = 1; // Used to insert initial RenderFontDesc mru that will always be a cache miss. const NullFontSize: u16 = 0; pub const FontCache = struct { const Self = @This(); alloc: std.mem.Allocator, fonts: std.ArrayList(Font), // Most recently used bm font indexed by FontId. This is checked before reaching for render_font_map. // When font is first, the render_font_size will be set to NullFontSize to force a cache miss. render_font_mru: std.ArrayList(RenderFontDesc), // Map to query from FontId + bitmap font size render_font_map: std.AutoHashMap(RenderFontKey, RenderFontId), render_fonts: std.ArrayList(RenderFont), font_groups: ds.CompactUnorderedList(FontGroupId, FontGroup), fonts_by_lname: ds.OwnedKeyStringHashMap(FontId), /// For outline glyphs and color bitmaps. Linear filtering enabled. main_atlas: FontAtlas, /// For bitmap font glyphs. Linear filtering disabled. bitmap_atlas: FontAtlas, // System fallback fonts. Used when user fallback fonts was not enough. system_fonts: std.ArrayList(FontId), pub fn init(self: *Self, alloc: std.mem.Allocator, gctx: *gpu.Graphics) void { self.* = .{ .alloc = alloc, .main_atlas = undefined, .bitmap_atlas = undefined, .fonts = std.ArrayList(Font).init(alloc), .render_fonts = std.ArrayList(RenderFont).init(alloc), .render_font_mru = std.ArrayList(RenderFontDesc).init(alloc), .render_font_map = std.AutoHashMap(RenderFontKey, RenderFontId).init(alloc), .font_groups = ds.CompactUnorderedList(FontGroupId, FontGroup).init(alloc), .fonts_by_lname = ds.OwnedKeyStringHashMap(FontId).init(alloc), .system_fonts = std.ArrayList(FontId).init(alloc), }; // For testing resizing: // const main_atlas_width = 128; // const main_atlas_height = 128; // Start with a larger width since we currently just grow the height. const main_atlas_width = 1024; const main_atlas_height = 1024; self.main_atlas.init(alloc, gctx, main_atlas_width, main_atlas_height, true); self.bitmap_atlas.init(alloc, gctx, 256, 256, false); } pub fn deinit(self: *Self) void { self.main_atlas.dumpBufferToDisk("main_atlas.bmp"); self.bitmap_atlas.dumpBufferToDisk("bitmap_atlas.bmp"); self.main_atlas.deinit(); self.bitmap_atlas.deinit(); var iter = self.font_groups.iterator(); while (iter.next()) |*it| { it.deinit(); } for (self.fonts.items) |*it| { it.deinit(self.alloc); } self.fonts.deinit(); for (self.render_fonts.items) |*it| { it.deinit(); } self.render_fonts.deinit(); self.render_font_mru.deinit(); self.render_font_map.deinit(); self.fonts_by_lname.deinit(); self.system_fonts.deinit(); self.font_groups.deinit(); } pub fn addSystemFont(self: *Self, id: FontId) !void { try self.system_fonts.append(id); } pub fn getPrimaryFontVMetrics(self: *Self, font_gid: FontGroupId, font_size: f32) VMetrics { const fgroup = self.getFontGroup(font_gid); var req_font_size = font_size; const render_font_size = computeRenderFontSize(fgroup.primary_font_desc, &req_font_size); const render_font = self.getOrCreateRenderFont(fgroup.primary_font, render_font_size); return render_font.getVerticalMetrics(req_font_size); } pub fn getFontVMetrics(self: *Self, font_id: FontId, font_size: f32) VMetrics { var req_font_size = font_size; const font = self.getFont(font_id); const desc = FontDesc{ .font_type = font.font_type, .bmfont_scaler = font.bmfont_scaler, }; const render_font_size = computeRenderFontSize(desc, &req_font_size); const render_font = self.getOrCreateRenderFont(font, render_font_size); return render_font.getVerticalMetrics(req_font_size); } // If a glyph is loaded, this will queue a gpu buffer upload. pub fn getOrLoadFontGroupGlyph(self: *Self, g: *gpu.Graphics, font_grp: *FontGroup, render_font_size: u16, cp: u21) GlyphResult { // Find glyph by iterating fonts until the glyph is found. for (font_grp.fonts) |font_id| { const render_font = self.getOrCreateRenderFont(font_id, render_font_size); const fnt = self.getFont(font_id); if (font_renderer.getOrLoadGlyph(g, fnt, render_font, cp)) |glyph| { return .{ .font = fnt, .render_font = render_font, .glyph = glyph, }; } } // Find glyph in system fonts. for (self.system_fonts.items) |font_id| { const render_font = self.getOrCreateRenderFont(font_id, render_font_size); const fnt = self.getFont(font_id); if (font_renderer.getOrLoadGlyph(g, fnt, render_font, cp)) |glyph| { return .{ .font = fnt, .render_font = render_font, .glyph = glyph, }; } } // If we still can't find it. Return the special missing glyph for the first user font. const font_id = font_grp.fonts[0]; const render_font = self.getOrCreateRenderFont(font_id, render_font_size); const fnt = self.getFont(font_id); const glyph = font_renderer.getOrLoadMissingGlyph(g, fnt, render_font); return .{ .font = fnt, .render_font = render_font, .glyph = glyph, }; } // Assumes render_font_size is a valid size. pub fn getOrCreateRenderFont(self: *Self, font_id: FontId, render_font_size: u16) *RenderFont { const mru = self.render_font_mru.items[font_id]; if (mru.font_size == render_font_size) { return &self.render_fonts.items[mru.font_id]; } else { if (self.render_font_map.get(.{ .font_id = font_id, .font_size = render_font_size })) |render_font_id| { self.render_font_mru.items[font_id] = .{ .font_id = render_font_id, .font_size = render_font_size, }; return &self.render_fonts.items[render_font_id]; } else { // Create. const render_font_id = @intCast(RenderFontId, self.render_fonts.items.len); const render_font = self.render_fonts.addOne() catch unreachable; const font = self.getFont(font_id); const ot_font = font.getOtFontBySize(render_font_size); switch (font.font_type) { .Outline => render_font.initOutline(self.alloc, font.id, ot_font, render_font_size), .Bitmap => render_font.initBitmap(self.alloc, font.id, ot_font, render_font_size), } self.render_font_map.put(.{ .font_id = font_id, .font_size = render_font_size }, render_font_id) catch unreachable; self.render_font_mru.items[font_id] = .{ .font_id = render_font_id, .font_size = render_font_size, }; return render_font; } } } // TODO: Use a hashmap. fn getFontId(self: *Self, name: []const u8) ?FontId { for (self.fonts) |it| { if (std.mem.eql(u8, it.name, name)) { return it.id; } } return null; } pub fn getFont(self: *Self, id: FontId) *Font { return &self.fonts.items[id]; } pub fn getFontGroup(self: *const Self, id: FontGroupId) *FontGroup { return self.font_groups.getPtrNoCheck(id); } fn getFontGroupId(self: *Self, font_seq: []const FontId) ?FontGroupId { var iter = self.font_groups.iterator(); while (iter.next()) |it| { if (it.fonts.len != font_seq.len) { continue; } var match = true; for (font_seq) |needle, i| { if (it.fonts[i] != needle) { match = false; break; } } if (match) { return iter.cur_id; } } return null; } pub fn getOrLoadFontGroupByNameSeq(self: *Self, names: []const []const u8) ?FontGroupId { var font_id_seq = std.ArrayList(FontId).init(self.alloc); defer font_id_seq.deinit(); var buf: [256]u8 = undefined; for (names) |name| { const len = std.math.min(buf.len, name.len); const lname = std.ascii.lowerString(buf[0..len], name[0..len]); const font_id = self.getOrLoadFontByLname(lname); font_id_seq.append(font_id) catch unreachable; } if (font_id_seq.items.len == 0) { return null; } return self.getOrLoadFontGroup(font_id_seq.items); } pub fn getOrLoadFontGroup(self: *Self, font_seq: []const FontId) FontGroupId { if (self.getFontGroupId(font_seq)) |font_gid| { return font_gid; } else { // Load font group. return self._addFontGroup(font_seq); } } fn _addFontGroup(self: *Self, font_seq: []const FontId) FontGroupId { var group: FontGroup = undefined; group.init(self.alloc, font_seq, self.fonts.items); return self.font_groups.add(group) catch unreachable; } pub fn addFontGroup(self: *Self, font_seq: []const FontId) ?FontGroupId { // Make sure that this font group doesn't already exist. if (self.getFontGroupId(font_seq) != null) { return null; } return self._addFontGroup(font_seq); } fn getOrLoadFontByLname(self: *Self, lname: []const u8) FontId { if (self.fonts_by_lname.get(lname)) |id| { return id; } else { unreachable; } } pub fn getOrLoadFontFromDataByLName(self: *Self, lname: []const u8, data: []const u8) FontId { if (self.fonts_by_lname.get(lname)) |id| { return id; } else { return self.addFont(data); } } pub fn addFontOTB(self: *Self, data: []const graphics.BitmapFontData) FontId { const next_id = @intCast(u32, self.fonts.items.len); var font: Font = undefined; font.initOTB(self.alloc, next_id, data); const lname = std.ascii.allocLowerString(self.alloc, font.name) catch unreachable; defer self.alloc.free(lname); self.fonts.append(font) catch unreachable; const mru = self.render_font_mru.addOne() catch unreachable; // Set to value to force cache miss. mru.font_size = NullFontSize; self.fonts_by_lname.put(lname, next_id) catch unreachable; return next_id; } pub fn addFontTTF(self: *Self, data: []const u8) FontId { const next_id = @intCast(u32, self.fonts.items.len); var font: Font = undefined; font.initTTF(self.alloc, next_id, data); const lname = std.ascii.allocLowerString(self.alloc, font.name) catch unreachable; defer self.alloc.free(lname); self.fonts.append(font) catch unreachable; const mru = self.render_font_mru.addOne() catch unreachable; // Set to value to force cache miss. mru.font_size = NullFontSize; self.fonts_by_lname.put(lname, next_id) catch unreachable; return next_id; } }; // Glyph with font that owns it. pub const GlyphResult = struct { font: *Font, render_font: *RenderFont, glyph: *Glyph, }; // Computes bitmap font size and also updates the requested font size if necessary. pub fn computeRenderFontSize(desc: FontDesc, font_size: *f32) u16 { switch (desc.font_type) { .Outline => { if (font_size.* <= 16) { if (font_size.* < MinRenderFontSize) { font_size.* = MinRenderFontSize; return MinRenderFontSize; } else { // Smaller font sizes are rounded up and get an exact bitmap font. font_size.* = @ceil(font_size.*); return @floatToInt(u16, font_size.*); } } else { if (font_size.* > MaxRenderFontSize) { font_size.* = MaxRenderFontSize; return MaxRenderFontSize; } else { var next_pow = @floatToInt(u4, @ceil(std.math.log2(font_size.*))); return @as(u16, 1) << next_pow; } } }, .Bitmap => { if (font_size.* < MinRenderFontSize) { font_size.* = MinRenderFontSize; } else if (font_size.* > MaxRenderFontSize) { font_size.* = MaxRenderFontSize; } // First take floor. const req_font_size = @floatToInt(u32, font_size.*); if (req_font_size >= desc.bmfont_scaler.mapping.len) { // Look at the last mapping and scale upwards. const mapping = desc.bmfont_scaler.mapping[desc.bmfont_scaler.mapping.len-1]; const scale = req_font_size / mapping.render_font_size; font_size.* = @intToFloat(f32, mapping.render_font_size * scale); return mapping.render_font_size; } else { const mapping = desc.bmfont_scaler.mapping[req_font_size]; font_size.* = @intToFloat(f32, mapping.final_font_size); return mapping.render_font_size; } }, } }
graphics/src/backend/gpu/font_cache.zig
const std = @import("std"); const Chunk = @import("./chunk.zig").Chunk; const OpCode = @import("./chunk.zig").OpCode; const Value = @import("./value.zig").Value; pub fn disassembleChunk(chunk: *Chunk, comptime name: []const u8) void { std.debug.print("=== {s} ===\n", .{name}); const code = chunk.code; var offset: usize = 0; while (offset < code.count) { disassembleInstruction(chunk, offset); offset = calcOffset(code.items[offset], offset); } } fn calcOffset(instruction_code: u8, current_offset: usize) usize { const instruction = OpCode.fromU8(instruction_code); return current_offset + instruction.operands() + 1; } pub fn disassembleInstruction(chunk: *Chunk, offset: usize) void { std.debug.print("{d:0>4} ", .{offset}); const code = chunk.code; const lines = chunk.lines; if (offset > 0 and lines.items[offset] == lines.items[offset - 1]) { std.debug.print(" | ", .{}); } else { std.debug.print("{d: >4} ", .{lines.items[offset]}); } const instruction = OpCode.fromU8(code.items[offset]); switch(instruction) { .op_constant => constantInstruction("OP_CONSTANT", chunk, offset), .op_negate => simpleInstruction("OP_NEGATE"), .op_add => simpleInstruction("OP_ADD"), .op_subtract => simpleInstruction("OP_SUBTRACT"), .op_multiply => simpleInstruction("OP_MULTIPLY"), .op_divide => simpleInstruction("OP_DIVIDE"), .op_return => simpleInstruction("OP_RETURN"), } } fn simpleInstruction(comptime name: []const u8) void { std.debug.print("{s}\n", .{name}); } fn constantInstruction(name: []const u8, chunk: *Chunk, offset: usize) void { const constant_idx = chunk.code.items[offset + 1]; const constant = chunk.constants.items[constant_idx]; std.debug.print("{s: <16} '{}'\n", .{ name, constant }); } pub fn printValue(value: Value) void { std.debug.print("{d}", .{value}); } pub fn printStack(stack: []Value) void { std.debug.print(" ", .{}); for (stack) |value| { std.debug.print("[{}]", .{value}); } std.debug.print("\n", .{}); }
src/debug.zig
const std = @import("../std.zig"); const builtin = std.builtin; const math = std.math; const assert = std.debug.assert; const mem = std.mem; const testing = std.testing; pub fn Reader( comptime Context: type, comptime ReadError: type, /// Returns the number of bytes read. It may be less than buffer.len. /// If the number of bytes read is 0, it means end of stream. /// End of stream is not an error condition. comptime readFn: fn (context: Context, buffer: []u8) ReadError!usize, ) type { return struct { pub const Error = ReadError; context: Context, const Self = @This(); /// Returns the number of bytes read. It may be less than buffer.len. /// If the number of bytes read is 0, it means end of stream. /// End of stream is not an error condition. pub fn read(self: Self, buffer: []u8) Error!usize { return readFn(self.context, buffer); } /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. pub fn readAll(self: Self, buffer: []u8) Error!usize { var index: usize = 0; while (index != buffer.len) { const amt = try self.read(buffer[index..]); if (amt == 0) return index; index += amt; } return index; } /// If the number read would be smaller than `buf.len`, `error.EndOfStream` is returned instead. pub fn readNoEof(self: Self, buf: []u8) !void { const amt_read = try self.readAll(buf); if (amt_read < buf.len) return error.EndOfStream; } pub const readAllBuffer = @compileError("deprecated; use readAllArrayList()"); /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found. /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned /// and the `std.ArrayList` has exactly `max_append_size` bytes appended. pub fn readAllArrayList(self: Self, array_list: *std.ArrayList(u8), max_append_size: usize) !void { try array_list.ensureCapacity(math.min(max_append_size, 4096)); const original_len = array_list.items.len; var start_index: usize = original_len; while (true) { array_list.expandToCapacity(); const dest_slice = array_list.span()[start_index..]; const bytes_read = try self.readAll(dest_slice); start_index += bytes_read; if (start_index - original_len > max_append_size) { array_list.shrink(original_len + max_append_size); return error.StreamTooLong; } if (bytes_read != dest_slice.len) { array_list.shrink(start_index); return; } // This will trigger ArrayList to expand superlinearly at whatever its growth rate is. try array_list.ensureCapacity(start_index + 1); } } /// Allocates enough memory to hold all the contents of the stream. If the allocated /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. pub fn readAllAlloc(self: Self, allocator: *mem.Allocator, max_size: usize) ![]u8 { var array_list = std.ArrayList(u8).init(allocator); defer array_list.deinit(); try self.readAllArrayList(&array_list, max_size); return array_list.toOwnedSlice(); } /// Replaces the `std.ArrayList` contents by reading from the stream until `delimiter` is found. /// Does not include the delimiter in the result. /// If the `std.ArrayList` length would exceed `max_size`, `error.StreamTooLong` is returned and the /// `std.ArrayList` is populated with `max_size` bytes from the stream. pub fn readUntilDelimiterArrayList( self: Self, array_list: *std.ArrayList(u8), delimiter: u8, max_size: usize, ) !void { array_list.shrink(0); while (true) { var byte: u8 = try self.readByte(); if (byte == delimiter) { return; } if (array_list.items.len == max_size) { return error.StreamTooLong; } try array_list.append(byte); } } /// Allocates enough memory to read until `delimiter`. If the allocated /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. pub fn readUntilDelimiterAlloc( self: Self, allocator: *mem.Allocator, delimiter: u8, max_size: usize, ) ![]u8 { var array_list = std.ArrayList(u8).init(allocator); defer array_list.deinit(); try self.readUntilDelimiterArrayList(&array_list, delimiter, max_size); return array_list.toOwnedSlice(); } /// Reads from the stream until specified byte is found. If the buffer is not /// large enough to hold the entire contents, `error.StreamTooLong` is returned. /// If end-of-stream is found, returns the rest of the stream. If this /// function is called again after that, returns null. /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The /// delimiter byte is not included in the returned slice. pub fn readUntilDelimiterOrEof(self: Self, buf: []u8, delimiter: u8) !?[]u8 { var index: usize = 0; while (true) { const byte = self.readByte() catch |err| switch (err) { error.EndOfStream => { if (index == 0) { return null; } else { return buf[0..index]; } }, else => |e| return e, }; if (byte == delimiter) return buf[0..index]; if (index >= buf.len) return error.StreamTooLong; buf[index] = byte; index += 1; } } /// Reads from the stream until specified byte is found, discarding all data, /// including the delimiter. /// If end-of-stream is found, this function succeeds. pub fn skipUntilDelimiterOrEof(self: Self, delimiter: u8) !void { while (true) { const byte = self.readByte() catch |err| switch (err) { error.EndOfStream => return, else => |e| return e, }; if (byte == delimiter) return; } } /// Reads 1 byte from the stream or returns `error.EndOfStream`. pub fn readByte(self: Self) !u8 { var result: [1]u8 = undefined; const amt_read = try self.read(result[0..]); if (amt_read < 1) return error.EndOfStream; return result[0]; } /// Same as `readByte` except the returned byte is signed. pub fn readByteSigned(self: Self) !i8 { return @bitCast(i8, try self.readByte()); } /// Reads exactly `num_bytes` bytes and returns as an array. /// `num_bytes` must be comptime-known pub fn readBytesNoEof(self: Self, comptime num_bytes: usize) ![num_bytes]u8 { var bytes: [num_bytes]u8 = undefined; try self.readNoEof(&bytes); return bytes; } /// Reads a native-endian integer pub fn readIntNative(self: Self, comptime T: type) !T { const bytes = try self.readBytesNoEof((T.bit_count + 7) / 8); return mem.readIntNative(T, &bytes); } /// Reads a foreign-endian integer pub fn readIntForeign(self: Self, comptime T: type) !T { const bytes = try self.readBytesNoEof((T.bit_count + 7) / 8); return mem.readIntForeign(T, &bytes); } pub fn readIntLittle(self: Self, comptime T: type) !T { const bytes = try self.readBytesNoEof((T.bit_count + 7) / 8); return mem.readIntLittle(T, &bytes); } pub fn readIntBig(self: Self, comptime T: type) !T { const bytes = try self.readBytesNoEof((T.bit_count + 7) / 8); return mem.readIntBig(T, &bytes); } pub fn readInt(self: Self, comptime T: type, endian: builtin.Endian) !T { const bytes = try self.readBytesNoEof((T.bit_count + 7) / 8); return mem.readInt(T, &bytes, endian); } pub fn readVarInt(self: Self, comptime ReturnType: type, endian: builtin.Endian, size: usize) !ReturnType { assert(size <= @sizeOf(ReturnType)); var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined; const bytes = bytes_buf[0..size]; try self.readNoEof(bytes); return mem.readVarInt(ReturnType, bytes, endian); } pub fn skipBytes(self: Self, num_bytes: u64) !void { var i: u64 = 0; while (i < num_bytes) : (i += 1) { _ = try self.readByte(); } } /// Reads `slice.len` bytes from the stream and returns if they are the same as the passed slice pub fn isBytes(self: Self, slice: []const u8) !bool { var i: usize = 0; var matches = true; while (i < slice.len) : (i += 1) { if (slice[i] != try self.readByte()) { matches = false; } } return matches; } pub fn readStruct(self: Self, comptime T: type) !T { // Only extern and packed structs have defined in-memory layout. comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto); var res: [1]T = undefined; try self.readNoEof(mem.sliceAsBytes(res[0..])); return res[0]; } /// Reads an integer with the same size as the given enum's tag type. If the integer matches /// an enum tag, casts the integer to the enum tag and returns it. Otherwise, returns an error. /// TODO optimization taking advantage of most fields being in order pub fn readEnum(self: Self, comptime Enum: type, endian: builtin.Endian) !Enum { const E = error{ /// An integer was read, but it did not match any of the tags in the supplied enum. InvalidValue, }; const type_info = @typeInfo(Enum).Enum; const tag = try self.readInt(type_info.tag_type, endian); inline for (std.meta.fields(Enum)) |field| { if (tag == field.value) { return @field(Enum, field.name); } } return E.InvalidValue; } }; } test "Reader" { var buf = "a\x02".*; const reader = std.io.fixedBufferStream(&buf).reader(); testing.expect((try reader.readByte()) == 'a'); testing.expect((try reader.readEnum(enum(u8) { a = 0, b = 99, c = 2, d = 3, }, undefined)) == .c); testing.expectError(error.EndOfStream, reader.readByte()); } test "Reader.isBytes" { const reader = std.io.fixedBufferStream("foobar").reader(); testing.expectEqual(true, try reader.isBytes("foo")); testing.expectEqual(false, try reader.isBytes("qux")); }
lib/std/io/reader.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const testing = std.testing; const SegmentedList = std.SegmentedList; const mem = std.mem; const Token = std.zig.Token; pub const TokenIndex = usize; pub const Tree = struct { source: []const u8, tokens: TokenList, root_node: *Node.Root, arena_allocator: std.heap.ArenaAllocator, errors: ErrorList, pub const TokenList = SegmentedList(Token, 64); pub const ErrorList = SegmentedList(Error, 0); pub fn deinit(self: *Tree) void { // Here we copy the arena allocator into stack memory, because // otherwise it would destroy itself while it was still working. var arena_allocator = self.arena_allocator; arena_allocator.deinit(); // self is destroyed } pub fn renderError(self: *Tree, parse_error: *Error, stream: var) !void { return parse_error.render(&self.tokens, stream); } pub fn tokenSlice(self: *Tree, token_index: TokenIndex) []const u8 { return self.tokenSlicePtr(self.tokens.at(token_index)); } pub fn tokenSlicePtr(self: *Tree, token: *const Token) []const u8 { return self.source[token.start..token.end]; } pub fn getNodeSource(self: *const Tree, node: *const Node) []const u8 { const first_token = self.tokens.at(node.firstToken()); const last_token = self.tokens.at(node.lastToken()); return self.source[first_token.start..last_token.end]; } pub const Location = struct { line: usize, column: usize, line_start: usize, line_end: usize, }; /// Return the Location of the token relative to the offset specified by `start_index`. pub fn tokenLocationPtr(self: *Tree, start_index: usize, token: *const Token) Location { var loc = Location{ .line = 0, .column = 0, .line_start = start_index, .line_end = self.source.len, }; const token_start = token.start; for (self.source[start_index..]) |c, i| { if (i + start_index == token_start) { loc.line_end = i + start_index; while (loc.line_end < self.source.len and self.source[loc.line_end] != '\n') : (loc.line_end += 1) {} return loc; } if (c == '\n') { loc.line += 1; loc.column = 0; loc.line_start = i + 1; } else { loc.column += 1; } } return loc; } pub fn tokenLocation(self: *Tree, start_index: usize, token_index: TokenIndex) Location { return self.tokenLocationPtr(start_index, self.tokens.at(token_index)); } pub fn tokensOnSameLine(self: *Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool { return self.tokensOnSameLinePtr(self.tokens.at(token1_index), self.tokens.at(token2_index)); } pub fn tokensOnSameLinePtr(self: *Tree, token1: *const Token, token2: *const Token) bool { return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null; } pub fn dump(self: *Tree) void { self.root_node.base.dump(0); } /// Skips over comments pub fn prevToken(self: *Tree, token_index: TokenIndex) TokenIndex { var index = token_index - 1; while (self.tokens.at(index).id == Token.Id.LineComment) { index -= 1; } return index; } /// Skips over comments pub fn nextToken(self: *Tree, token_index: TokenIndex) TokenIndex { var index = token_index + 1; while (self.tokens.at(index).id == Token.Id.LineComment) { index += 1; } return index; } }; pub const Error = union(enum) { InvalidToken: InvalidToken, ExpectedContainerMembers: ExpectedContainerMembers, ExpectedStringLiteral: ExpectedStringLiteral, ExpectedIntegerLiteral: ExpectedIntegerLiteral, ExpectedPubItem: ExpectedPubItem, ExpectedIdentifier: ExpectedIdentifier, ExpectedStatement: ExpectedStatement, ExpectedVarDeclOrFn: ExpectedVarDeclOrFn, ExpectedVarDecl: ExpectedVarDecl, ExpectedReturnType: ExpectedReturnType, ExpectedAggregateKw: ExpectedAggregateKw, UnattachedDocComment: UnattachedDocComment, ExpectedEqOrSemi: ExpectedEqOrSemi, ExpectedSemiOrLBrace: ExpectedSemiOrLBrace, ExpectedSemiOrElse: ExpectedSemiOrElse, ExpectedLabelOrLBrace: ExpectedLabelOrLBrace, ExpectedLBrace: ExpectedLBrace, ExpectedColonOrRParen: ExpectedColonOrRParen, ExpectedLabelable: ExpectedLabelable, ExpectedInlinable: ExpectedInlinable, ExpectedAsmOutputReturnOrType: ExpectedAsmOutputReturnOrType, ExpectedCall: ExpectedCall, ExpectedCallOrFnProto: ExpectedCallOrFnProto, ExpectedSliceOrRBracket: ExpectedSliceOrRBracket, ExtraAlignQualifier: ExtraAlignQualifier, ExtraConstQualifier: ExtraConstQualifier, ExtraVolatileQualifier: ExtraVolatileQualifier, ExtraAllowZeroQualifier: ExtraAllowZeroQualifier, ExpectedTypeExpr: ExpectedTypeExpr, ExpectedPrimaryTypeExpr: ExpectedPrimaryTypeExpr, ExpectedParamType: ExpectedParamType, ExpectedExpr: ExpectedExpr, ExpectedPrimaryExpr: ExpectedPrimaryExpr, ExpectedToken: ExpectedToken, ExpectedCommaOrEnd: ExpectedCommaOrEnd, ExpectedParamList: ExpectedParamList, ExpectedPayload: ExpectedPayload, ExpectedBlockOrAssignment: ExpectedBlockOrAssignment, ExpectedBlockOrExpression: ExpectedBlockOrExpression, ExpectedExprOrAssignment: ExpectedExprOrAssignment, ExpectedPrefixExpr: ExpectedPrefixExpr, ExpectedLoopExpr: ExpectedLoopExpr, ExpectedDerefOrUnwrap: ExpectedDerefOrUnwrap, ExpectedSuffixOp: ExpectedSuffixOp, pub fn render(self: *const Error, tokens: *Tree.TokenList, stream: var) !void { switch (self.*) { .InvalidToken => |*x| return x.render(tokens, stream), .ExpectedContainerMembers => |*x| return x.render(tokens, stream), .ExpectedStringLiteral => |*x| return x.render(tokens, stream), .ExpectedIntegerLiteral => |*x| return x.render(tokens, stream), .ExpectedPubItem => |*x| return x.render(tokens, stream), .ExpectedIdentifier => |*x| return x.render(tokens, stream), .ExpectedStatement => |*x| return x.render(tokens, stream), .ExpectedVarDeclOrFn => |*x| return x.render(tokens, stream), .ExpectedVarDecl => |*x| return x.render(tokens, stream), .ExpectedReturnType => |*x| return x.render(tokens, stream), .ExpectedAggregateKw => |*x| return x.render(tokens, stream), .UnattachedDocComment => |*x| return x.render(tokens, stream), .ExpectedEqOrSemi => |*x| return x.render(tokens, stream), .ExpectedSemiOrLBrace => |*x| return x.render(tokens, stream), .ExpectedSemiOrElse => |*x| return x.render(tokens, stream), .ExpectedLabelOrLBrace => |*x| return x.render(tokens, stream), .ExpectedLBrace => |*x| return x.render(tokens, stream), .ExpectedColonOrRParen => |*x| return x.render(tokens, stream), .ExpectedLabelable => |*x| return x.render(tokens, stream), .ExpectedInlinable => |*x| return x.render(tokens, stream), .ExpectedAsmOutputReturnOrType => |*x| return x.render(tokens, stream), .ExpectedCall => |*x| return x.render(tokens, stream), .ExpectedCallOrFnProto => |*x| return x.render(tokens, stream), .ExpectedSliceOrRBracket => |*x| return x.render(tokens, stream), .ExtraAlignQualifier => |*x| return x.render(tokens, stream), .ExtraConstQualifier => |*x| return x.render(tokens, stream), .ExtraVolatileQualifier => |*x| return x.render(tokens, stream), .ExtraAllowZeroQualifier => |*x| return x.render(tokens, stream), .ExpectedTypeExpr => |*x| return x.render(tokens, stream), .ExpectedPrimaryTypeExpr => |*x| return x.render(tokens, stream), .ExpectedParamType => |*x| return x.render(tokens, stream), .ExpectedExpr => |*x| return x.render(tokens, stream), .ExpectedPrimaryExpr => |*x| return x.render(tokens, stream), .ExpectedToken => |*x| return x.render(tokens, stream), .ExpectedCommaOrEnd => |*x| return x.render(tokens, stream), .ExpectedParamList => |*x| return x.render(tokens, stream), .ExpectedPayload => |*x| return x.render(tokens, stream), .ExpectedBlockOrAssignment => |*x| return x.render(tokens, stream), .ExpectedBlockOrExpression => |*x| return x.render(tokens, stream), .ExpectedExprOrAssignment => |*x| return x.render(tokens, stream), .ExpectedPrefixExpr => |*x| return x.render(tokens, stream), .ExpectedLoopExpr => |*x| return x.render(tokens, stream), .ExpectedDerefOrUnwrap => |*x| return x.render(tokens, stream), .ExpectedSuffixOp => |*x| return x.render(tokens, stream), } } pub fn loc(self: *const Error) TokenIndex { switch (self.*) { .InvalidToken => |x| return x.token, .ExpectedContainerMembers => |x| return x.token, .ExpectedStringLiteral => |x| return x.token, .ExpectedIntegerLiteral => |x| return x.token, .ExpectedPubItem => |x| return x.token, .ExpectedIdentifier => |x| return x.token, .ExpectedStatement => |x| return x.token, .ExpectedVarDeclOrFn => |x| return x.token, .ExpectedVarDecl => |x| return x.token, .ExpectedReturnType => |x| return x.token, .ExpectedAggregateKw => |x| return x.token, .UnattachedDocComment => |x| return x.token, .ExpectedEqOrSemi => |x| return x.token, .ExpectedSemiOrLBrace => |x| return x.token, .ExpectedSemiOrElse => |x| return x.token, .ExpectedLabelOrLBrace => |x| return x.token, .ExpectedLBrace => |x| return x.token, .ExpectedColonOrRParen => |x| return x.token, .ExpectedLabelable => |x| return x.token, .ExpectedInlinable => |x| return x.token, .ExpectedAsmOutputReturnOrType => |x| return x.token, .ExpectedCall => |x| return x.node.firstToken(), .ExpectedCallOrFnProto => |x| return x.node.firstToken(), .ExpectedSliceOrRBracket => |x| return x.token, .ExtraAlignQualifier => |x| return x.token, .ExtraConstQualifier => |x| return x.token, .ExtraVolatileQualifier => |x| return x.token, .ExtraAllowZeroQualifier => |x| return x.token, .ExpectedTypeExpr => |x| return x.token, .ExpectedPrimaryTypeExpr => |x| return x.token, .ExpectedParamType => |x| return x.token, .ExpectedExpr => |x| return x.token, .ExpectedPrimaryExpr => |x| return x.token, .ExpectedToken => |x| return x.token, .ExpectedCommaOrEnd => |x| return x.token, .ExpectedParamList => |x| return x.token, .ExpectedPayload => |x| return x.token, .ExpectedBlockOrAssignment => |x| return x.token, .ExpectedBlockOrExpression => |x| return x.token, .ExpectedExprOrAssignment => |x| return x.token, .ExpectedPrefixExpr => |x| return x.token, .ExpectedLoopExpr => |x| return x.token, .ExpectedDerefOrUnwrap => |x| return x.token, .ExpectedSuffixOp => |x| return x.token, } } pub const InvalidToken = SingleTokenError("Invalid token '{}'"); pub const ExpectedContainerMembers = SingleTokenError("Expected test, comptime, var decl, or container field, found '{}'"); pub const ExpectedStringLiteral = SingleTokenError("Expected string literal, found '{}'"); pub const ExpectedIntegerLiteral = SingleTokenError("Expected integer literal, found '{}'"); pub const ExpectedIdentifier = SingleTokenError("Expected identifier, found '{}'"); pub const ExpectedStatement = SingleTokenError("Expected statement, found '{}'"); pub const ExpectedVarDeclOrFn = SingleTokenError("Expected variable declaration or function, found '{}'"); pub const ExpectedVarDecl = SingleTokenError("Expected variable declaration, found '{}'"); pub const ExpectedReturnType = SingleTokenError("Expected 'var' or return type expression, found '{}'"); pub const ExpectedAggregateKw = SingleTokenError("Expected '" ++ Token.Id.Keyword_struct.symbol() ++ "', '" ++ Token.Id.Keyword_union.symbol() ++ "', or '" ++ Token.Id.Keyword_enum.symbol() ++ "', found '{}'"); pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found '{}'"); pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found '{}'"); pub const ExpectedSemiOrElse = SingleTokenError("Expected ';' or 'else', found '{}'"); pub const ExpectedLBrace = SingleTokenError("Expected '{{', found '{}'"); pub const ExpectedLabelOrLBrace = SingleTokenError("Expected label or '{{', found '{}'"); pub const ExpectedColonOrRParen = SingleTokenError("Expected ':' or ')', found '{}'"); pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found '{}'"); pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found '{}'"); pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or '" ++ Token.Id.Identifier.symbol() ++ "', found '{}'"); pub const ExpectedSliceOrRBracket = SingleTokenError("Expected ']' or '..', found '{}'"); pub const ExpectedTypeExpr = SingleTokenError("Expected type expression, found '{}'"); pub const ExpectedPrimaryTypeExpr = SingleTokenError("Expected primary type expression, found '{}'"); pub const ExpectedExpr = SingleTokenError("Expected expression, found '{}'"); pub const ExpectedPrimaryExpr = SingleTokenError("Expected primary expression, found '{}'"); pub const ExpectedParamList = SingleTokenError("Expected parameter list, found '{}'"); pub const ExpectedPayload = SingleTokenError("Expected loop payload, found '{}'"); pub const ExpectedBlockOrAssignment = SingleTokenError("Expected block or assignment, found '{}'"); pub const ExpectedBlockOrExpression = SingleTokenError("Expected block or expression, found '{}'"); pub const ExpectedExprOrAssignment = SingleTokenError("Expected expression or assignment, found '{}'"); pub const ExpectedPrefixExpr = SingleTokenError("Expected prefix expression, found '{}'"); pub const ExpectedLoopExpr = SingleTokenError("Expected loop expression, found '{}'"); pub const ExpectedDerefOrUnwrap = SingleTokenError("Expected pointer dereference or optional unwrap, found '{}'"); pub const ExpectedSuffixOp = SingleTokenError("Expected pointer dereference, optional unwrap, or field access, found '{}'"); pub const ExpectedParamType = SimpleError("Expected parameter type"); pub const ExpectedPubItem = SimpleError("Expected function or variable declaration after pub"); pub const UnattachedDocComment = SimpleError("Unattached documentation comment"); pub const ExtraAlignQualifier = SimpleError("Extra align qualifier"); pub const ExtraConstQualifier = SimpleError("Extra const qualifier"); pub const ExtraVolatileQualifier = SimpleError("Extra volatile qualifier"); pub const ExtraAllowZeroQualifier = SimpleError("Extra allowzero qualifier"); pub const ExpectedCall = struct { node: *Node, pub fn render(self: *const ExpectedCall, tokens: *Tree.TokenList, stream: var) !void { return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id)); } }; pub const ExpectedCallOrFnProto = struct { node: *Node, pub fn render(self: *const ExpectedCallOrFnProto, tokens: *Tree.TokenList, stream: var) !void { return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id)); } }; pub const ExpectedToken = struct { token: TokenIndex, expected_id: Token.Id, pub fn render(self: *const ExpectedToken, tokens: *Tree.TokenList, stream: var) !void { const found_token = tokens.at(self.token); switch (found_token.id) { .Invalid_ampersands => { return stream.print("`&&` is invalid. Note that `and` is boolean AND."); }, .Invalid => { return stream.print("expected '{}', found invalid bytes", self.expected_id.symbol()); }, else => { const token_name = found_token.id.symbol(); return stream.print("expected '{}', found '{}'", self.expected_id.symbol(), token_name); }, } } }; pub const ExpectedCommaOrEnd = struct { token: TokenIndex, end_id: Token.Id, pub fn render(self: *const ExpectedCommaOrEnd, tokens: *Tree.TokenList, stream: var) !void { const actual_token = tokens.at(self.token); return stream.print("expected ',' or '{}', found '{}'", self.end_id.symbol(), actual_token.id.symbol()); } }; fn SingleTokenError(comptime msg: []const u8) type { return struct { const ThisError = @This(); token: TokenIndex, pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void { const actual_token = tokens.at(self.token); return stream.print(msg, actual_token.id.symbol()); } }; } fn SimpleError(comptime msg: []const u8) type { return struct { const ThisError = @This(); token: TokenIndex, pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void { return stream.write(msg); } }; } }; pub const Node = struct { id: Id, pub const Id = enum { // Top level Root, Use, TestDecl, // Statements VarDecl, Defer, // Operators InfixOp, PrefixOp, SuffixOp, // Control flow Switch, While, For, If, ControlFlowExpression, Suspend, // Type expressions VarType, ErrorType, FnProto, AnyFrameType, // Primary expressions IntegerLiteral, FloatLiteral, EnumLiteral, StringLiteral, MultilineStringLiteral, CharLiteral, BoolLiteral, NullLiteral, UndefinedLiteral, Unreachable, Identifier, GroupedExpression, BuiltinCall, ErrorSetDecl, ContainerDecl, Asm, Comptime, Block, // Misc DocComment, SwitchCase, SwitchElse, Else, Payload, PointerPayload, PointerIndexPayload, ContainerField, ErrorTag, AsmInput, AsmOutput, ParamDecl, FieldInitializer, }; pub fn cast(base: *Node, comptime T: type) ?*T { if (base.id == comptime typeToId(T)) { return @fieldParentPtr(T, "base", base); } return null; } pub fn iterate(base: *Node, index: usize) ?*Node { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).iterate(index); } } unreachable; } pub fn firstToken(base: *const Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).firstToken(); } } unreachable; } pub fn lastToken(base: *const Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).lastToken(); } } unreachable; } pub fn typeToId(comptime T: type) Id { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (T == @field(Node, @memberName(Id, i))) { return @field(Id, @memberName(Id, i)); } } unreachable; } pub fn requireSemiColon(base: *const Node) bool { var n = base; while (true) { switch (n.id) { Id.Root, Id.ContainerField, Id.ParamDecl, Id.Block, Id.Payload, Id.PointerPayload, Id.PointerIndexPayload, Id.Switch, Id.SwitchCase, Id.SwitchElse, Id.FieldInitializer, Id.DocComment, Id.TestDecl, => return false, Id.While => { const while_node = @fieldParentPtr(While, "base", n); if (while_node.@"else") |@"else"| { n = &@"else".base; continue; } return while_node.body.id != Id.Block; }, Id.For => { const for_node = @fieldParentPtr(For, "base", n); if (for_node.@"else") |@"else"| { n = &@"else".base; continue; } return for_node.body.id != Id.Block; }, Id.If => { const if_node = @fieldParentPtr(If, "base", n); if (if_node.@"else") |@"else"| { n = &@"else".base; continue; } return if_node.body.id != Id.Block; }, Id.Else => { const else_node = @fieldParentPtr(Else, "base", n); n = else_node.body; continue; }, Id.Defer => { const defer_node = @fieldParentPtr(Defer, "base", n); return defer_node.expr.id != Id.Block; }, Id.Comptime => { const comptime_node = @fieldParentPtr(Comptime, "base", n); return comptime_node.expr.id != Id.Block; }, Id.Suspend => { const suspend_node = @fieldParentPtr(Suspend, "base", n); if (suspend_node.body) |body| { return body.id != Id.Block; } return true; }, else => return true, } } } pub fn dump(self: *Node, indent: usize) void { { var i: usize = 0; while (i < indent) : (i += 1) { std.debug.warn(" "); } } std.debug.warn("{}\n", @tagName(self.id)); var child_i: usize = 0; while (self.iterate(child_i)) |child| : (child_i += 1) { child.dump(indent + 2); } } pub const Root = struct { base: Node, decls: DeclList, eof_token: TokenIndex, pub const DeclList = SegmentedList(*Node, 4); pub fn iterate(self: *Root, index: usize) ?*Node { if (index < self.decls.len) { return self.decls.at(index).*; } return null; } pub fn firstToken(self: *const Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(0).*).firstToken(); } pub fn lastToken(self: *const Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1).*).lastToken(); } }; pub const VarDecl = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, thread_local_token: ?TokenIndex, name_token: TokenIndex, eq_token: TokenIndex, mut_token: TokenIndex, comptime_token: ?TokenIndex, extern_export_token: ?TokenIndex, lib_name: ?*Node, type_node: ?*Node, align_node: ?*Node, section_node: ?*Node, init_node: ?*Node, semicolon_token: TokenIndex, pub fn iterate(self: *VarDecl, index: usize) ?*Node { var i = index; if (self.type_node) |type_node| { if (i < 1) return type_node; i -= 1; } if (self.align_node) |align_node| { if (i < 1) return align_node; i -= 1; } if (self.section_node) |section_node| { if (i < 1) return section_node; i -= 1; } if (self.init_node) |init_node| { if (i < 1) return init_node; i -= 1; } return null; } pub fn firstToken(self: *const VarDecl) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.thread_local_token) |thread_local_token| return thread_local_token; if (self.comptime_token) |comptime_token| return comptime_token; if (self.extern_export_token) |extern_export_token| return extern_export_token; assert(self.lib_name == null); return self.mut_token; } pub fn lastToken(self: *const VarDecl) TokenIndex { return self.semicolon_token; } }; pub const Use = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, use_token: TokenIndex, expr: *Node, semicolon_token: TokenIndex, pub fn iterate(self: *Use, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Use) TokenIndex { if (self.visib_token) |visib_token| return visib_token; return self.use_token; } pub fn lastToken(self: *const Use) TokenIndex { return self.semicolon_token; } }; pub const ErrorSetDecl = struct { base: Node, error_token: TokenIndex, decls: DeclList, rbrace_token: TokenIndex, pub const DeclList = SegmentedList(*Node, 2); pub fn iterate(self: *ErrorSetDecl, index: usize) ?*Node { var i = index; if (i < self.decls.len) return self.decls.at(i).*; i -= self.decls.len; return null; } pub fn firstToken(self: *const ErrorSetDecl) TokenIndex { return self.error_token; } pub fn lastToken(self: *const ErrorSetDecl) TokenIndex { return self.rbrace_token; } }; pub const ContainerDecl = struct { base: Node, layout_token: ?TokenIndex, kind_token: TokenIndex, init_arg_expr: InitArg, fields_and_decls: DeclList, lbrace_token: TokenIndex, rbrace_token: TokenIndex, pub const DeclList = Root.DeclList; pub const InitArg = union(enum) { None, Enum: ?*Node, Type: *Node, }; pub fn iterate(self: *ContainerDecl, index: usize) ?*Node { var i = index; switch (self.init_arg_expr) { InitArg.Type => |t| { if (i < 1) return t; i -= 1; }, InitArg.None, InitArg.Enum => {}, } if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*; i -= self.fields_and_decls.len; return null; } pub fn firstToken(self: *const ContainerDecl) TokenIndex { if (self.layout_token) |layout_token| { return layout_token; } return self.kind_token; } pub fn lastToken(self: *const ContainerDecl) TokenIndex { return self.rbrace_token; } }; pub const ContainerField = struct { base: Node = Node{ .id = .ContainerField }, doc_comments: ?*DocComment, comptime_token: ?TokenIndex, name_token: TokenIndex, type_expr: ?*Node, value_expr: ?*Node, align_expr: ?*Node, pub fn iterate(self: *ContainerField, index: usize) ?*Node { var i = index; if (self.type_expr) |type_expr| { if (i < 1) return type_expr; i -= 1; } if (self.value_expr) |value_expr| { if (i < 1) return value_expr; i -= 1; } return null; } pub fn firstToken(self: *const ContainerField) TokenIndex { return self.comptime_token orelse self.name_token; } pub fn lastToken(self: *const ContainerField) TokenIndex { if (self.value_expr) |value_expr| { return value_expr.lastToken(); } if (self.type_expr) |type_expr| { return type_expr.lastToken(); } return self.name_token; } }; pub const ErrorTag = struct { base: Node, doc_comments: ?*DocComment, name_token: TokenIndex, pub fn iterate(self: *ErrorTag, index: usize) ?*Node { var i = index; if (self.doc_comments) |comments| { if (i < 1) return &comments.base; i -= 1; } return null; } pub fn firstToken(self: *const ErrorTag) TokenIndex { return self.name_token; } pub fn lastToken(self: *const ErrorTag) TokenIndex { return self.name_token; } }; pub const Identifier = struct { base: Node, token: TokenIndex, pub fn iterate(self: *Identifier, index: usize) ?*Node { return null; } pub fn firstToken(self: *const Identifier) TokenIndex { return self.token; } pub fn lastToken(self: *const Identifier) TokenIndex { return self.token; } }; pub const FnProto = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, fn_token: TokenIndex, name_token: ?TokenIndex, params: ParamList, return_type: ReturnType, var_args_token: ?TokenIndex, extern_export_inline_token: ?TokenIndex, cc_token: ?TokenIndex, body_node: ?*Node, lib_name: ?*Node, // populated if this is an extern declaration align_expr: ?*Node, // populated if align(A) is present section_expr: ?*Node, // populated if linksection(A) is present pub const ParamList = SegmentedList(*Node, 2); pub const ReturnType = union(enum) { Explicit: *Node, InferErrorSet: *Node, }; pub fn iterate(self: *FnProto, index: usize) ?*Node { var i = index; if (self.lib_name) |lib_name| { if (i < 1) return lib_name; i -= 1; } if (i < self.params.len) return self.params.at(self.params.len - i - 1).*; i -= self.params.len; if (self.align_expr) |align_expr| { if (i < 1) return align_expr; i -= 1; } if (self.section_expr) |section_expr| { if (i < 1) return section_expr; i -= 1; } switch (self.return_type) { // TODO allow this and next prong to share bodies since the types are the same ReturnType.Explicit => |node| { if (i < 1) return node; i -= 1; }, ReturnType.InferErrorSet => |node| { if (i < 1) return node; i -= 1; }, } if (self.body_node) |body_node| { if (i < 1) return body_node; i -= 1; } return null; } pub fn firstToken(self: *const FnProto) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token; assert(self.lib_name == null); if (self.cc_token) |cc_token| return cc_token; return self.fn_token; } pub fn lastToken(self: *const FnProto) TokenIndex { if (self.body_node) |body_node| return body_node.lastToken(); switch (self.return_type) { // TODO allow this and next prong to share bodies since the types are the same ReturnType.Explicit => |node| return node.lastToken(), ReturnType.InferErrorSet => |node| return node.lastToken(), } } }; pub const AnyFrameType = struct { base: Node, anyframe_token: TokenIndex, result: ?Result, pub const Result = struct { arrow_token: TokenIndex, return_type: *Node, }; pub fn iterate(self: *AnyFrameType, index: usize) ?*Node { var i = index; if (self.result) |result| { if (i < 1) return result.return_type; i -= 1; } return null; } pub fn firstToken(self: *const AnyFrameType) TokenIndex { return self.anyframe_token; } pub fn lastToken(self: *const AnyFrameType) TokenIndex { if (self.result) |result| return result.return_type.lastToken(); return self.anyframe_token; } }; pub const ParamDecl = struct { base: Node, doc_comments: ?*DocComment, comptime_token: ?TokenIndex, noalias_token: ?TokenIndex, name_token: ?TokenIndex, type_node: *Node, var_args_token: ?TokenIndex, pub fn iterate(self: *ParamDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.type_node; i -= 1; return null; } pub fn firstToken(self: *const ParamDecl) TokenIndex { if (self.comptime_token) |comptime_token| return comptime_token; if (self.noalias_token) |noalias_token| return noalias_token; if (self.name_token) |name_token| return name_token; return self.type_node.firstToken(); } pub fn lastToken(self: *const ParamDecl) TokenIndex { if (self.var_args_token) |var_args_token| return var_args_token; return self.type_node.lastToken(); } }; pub const Block = struct { base: Node, label: ?TokenIndex, lbrace: TokenIndex, statements: StatementList, rbrace: TokenIndex, pub const StatementList = Root.DeclList; pub fn iterate(self: *Block, index: usize) ?*Node { var i = index; if (i < self.statements.len) return self.statements.at(i).*; i -= self.statements.len; return null; } pub fn firstToken(self: *const Block) TokenIndex { if (self.label) |label| { return label; } return self.lbrace; } pub fn lastToken(self: *const Block) TokenIndex { return self.rbrace; } }; pub const Defer = struct { base: Node, defer_token: TokenIndex, expr: *Node, pub fn iterate(self: *Defer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Defer) TokenIndex { return self.defer_token; } pub fn lastToken(self: *const Defer) TokenIndex { return self.expr.lastToken(); } }; pub const Comptime = struct { base: Node, doc_comments: ?*DocComment, comptime_token: TokenIndex, expr: *Node, pub fn iterate(self: *Comptime, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Comptime) TokenIndex { return self.comptime_token; } pub fn lastToken(self: *const Comptime) TokenIndex { return self.expr.lastToken(); } }; pub const Payload = struct { base: Node, lpipe: TokenIndex, error_symbol: *Node, rpipe: TokenIndex, pub fn iterate(self: *Payload, index: usize) ?*Node { var i = index; if (i < 1) return self.error_symbol; i -= 1; return null; } pub fn firstToken(self: *const Payload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const Payload) TokenIndex { return self.rpipe; } }; pub const PointerPayload = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, value_symbol: *Node, rpipe: TokenIndex, pub fn iterate(self: *PointerPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; i -= 1; return null; } pub fn firstToken(self: *const PointerPayload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const PointerPayload) TokenIndex { return self.rpipe; } }; pub const PointerIndexPayload = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, value_symbol: *Node, index_symbol: ?*Node, rpipe: TokenIndex, pub fn iterate(self: *PointerIndexPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; i -= 1; if (self.index_symbol) |index_symbol| { if (i < 1) return index_symbol; i -= 1; } return null; } pub fn firstToken(self: *const PointerIndexPayload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const PointerIndexPayload) TokenIndex { return self.rpipe; } }; pub const Else = struct { base: Node, else_token: TokenIndex, payload: ?*Node, body: *Node, pub fn iterate(self: *Else, index: usize) ?*Node { var i = index; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.body; i -= 1; return null; } pub fn firstToken(self: *const Else) TokenIndex { return self.else_token; } pub fn lastToken(self: *const Else) TokenIndex { return self.body.lastToken(); } }; pub const Switch = struct { base: Node, switch_token: TokenIndex, expr: *Node, /// these must be SwitchCase nodes cases: CaseList, rbrace: TokenIndex, pub const CaseList = SegmentedList(*Node, 2); pub fn iterate(self: *Switch, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; if (i < self.cases.len) return self.cases.at(i).*; i -= self.cases.len; return null; } pub fn firstToken(self: *const Switch) TokenIndex { return self.switch_token; } pub fn lastToken(self: *const Switch) TokenIndex { return self.rbrace; } }; pub const SwitchCase = struct { base: Node, items: ItemList, arrow_token: TokenIndex, payload: ?*Node, expr: *Node, pub const ItemList = SegmentedList(*Node, 1); pub fn iterate(self: *SwitchCase, index: usize) ?*Node { var i = index; if (i < self.items.len) return self.items.at(i).*; i -= self.items.len; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const SwitchCase) TokenIndex { return (self.items.at(0).*).firstToken(); } pub fn lastToken(self: *const SwitchCase) TokenIndex { return self.expr.lastToken(); } }; pub const SwitchElse = struct { base: Node, token: TokenIndex, pub fn iterate(self: *SwitchElse, index: usize) ?*Node { return null; } pub fn firstToken(self: *const SwitchElse) TokenIndex { return self.token; } pub fn lastToken(self: *const SwitchElse) TokenIndex { return self.token; } }; pub const While = struct { base: Node, label: ?TokenIndex, inline_token: ?TokenIndex, while_token: TokenIndex, condition: *Node, payload: ?*Node, continue_expr: ?*Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *While, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; i -= 1; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (self.continue_expr) |continue_expr| { if (i < 1) return continue_expr; i -= 1; } if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const While) TokenIndex { if (self.label) |label| { return label; } if (self.inline_token) |inline_token| { return inline_token; } return self.while_token; } pub fn lastToken(self: *const While) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const For = struct { base: Node, label: ?TokenIndex, inline_token: ?TokenIndex, for_token: TokenIndex, array_expr: *Node, payload: *Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *For, index: usize) ?*Node { var i = index; if (i < 1) return self.array_expr; i -= 1; if (i < 1) return self.payload; i -= 1; if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const For) TokenIndex { if (self.label) |label| { return label; } if (self.inline_token) |inline_token| { return inline_token; } return self.for_token; } pub fn lastToken(self: *const For) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const If = struct { base: Node, if_token: TokenIndex, condition: *Node, payload: ?*Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *If, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; i -= 1; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const If) TokenIndex { return self.if_token; } pub fn lastToken(self: *const If) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const InfixOp = struct { base: Node, op_token: TokenIndex, lhs: *Node, op: Op, rhs: *Node, pub const Op = union(enum) { Add, AddWrap, ArrayCat, ArrayMult, Assign, AssignBitAnd, AssignBitOr, AssignBitShiftLeft, AssignBitShiftRight, AssignBitXor, AssignDiv, AssignMinus, AssignMinusWrap, AssignMod, AssignPlus, AssignPlusWrap, AssignTimes, AssignTimesWarp, BangEqual, BitAnd, BitOr, BitShiftLeft, BitShiftRight, BitXor, BoolAnd, BoolOr, Catch: ?*Node, Div, EqualEqual, ErrorUnion, GreaterOrEqual, GreaterThan, LessOrEqual, LessThan, MergeErrorSets, Mod, Mult, MultWrap, Period, Range, Sub, SubWrap, UnwrapOptional, }; pub fn iterate(self: *InfixOp, index: usize) ?*Node { var i = index; if (i < 1) return self.lhs; i -= 1; switch (self.op) { Op.Catch => |maybe_payload| { if (maybe_payload) |payload| { if (i < 1) return payload; i -= 1; } }, Op.Add, Op.AddWrap, Op.ArrayCat, Op.ArrayMult, Op.Assign, Op.AssignBitAnd, Op.AssignBitOr, Op.AssignBitShiftLeft, Op.AssignBitShiftRight, Op.AssignBitXor, Op.AssignDiv, Op.AssignMinus, Op.AssignMinusWrap, Op.AssignMod, Op.AssignPlus, Op.AssignPlusWrap, Op.AssignTimes, Op.AssignTimesWarp, Op.BangEqual, Op.BitAnd, Op.BitOr, Op.BitShiftLeft, Op.BitShiftRight, Op.BitXor, Op.BoolAnd, Op.BoolOr, Op.Div, Op.EqualEqual, Op.ErrorUnion, Op.GreaterOrEqual, Op.GreaterThan, Op.LessOrEqual, Op.LessThan, Op.MergeErrorSets, Op.Mod, Op.Mult, Op.MultWrap, Op.Period, Op.Range, Op.Sub, Op.SubWrap, Op.UnwrapOptional, => {}, } if (i < 1) return self.rhs; i -= 1; return null; } pub fn firstToken(self: *const InfixOp) TokenIndex { return self.lhs.firstToken(); } pub fn lastToken(self: *const InfixOp) TokenIndex { return self.rhs.lastToken(); } }; pub const PrefixOp = struct { base: Node = Node{ .id = .PrefixOp }, op_token: TokenIndex, op: Op, rhs: *Node, pub const Op = union(enum) { AddressOf, ArrayType: ArrayInfo, Await, BitNot, BoolNot, Cancel, OptionalType, Negation, NegationWrap, Resume, PtrType: PtrInfo, SliceType: PtrInfo, Try, }; pub const ArrayInfo = struct { len_expr: *Node, sentinel: ?*Node, }; pub const PtrInfo = struct { allowzero_token: ?TokenIndex = null, align_info: ?Align = null, const_token: ?TokenIndex = null, volatile_token: ?TokenIndex = null, sentinel: ?*Node = null, pub const Align = struct { node: *Node, bit_range: ?BitRange, pub const BitRange = struct { start: *Node, end: *Node, }; }; }; pub fn iterate(self: *PrefixOp, index: usize) ?*Node { var i = index; switch (self.op) { // TODO https://github.com/ziglang/zig/issues/1107 Op.SliceType => |addr_of_info| { if (addr_of_info.sentinel) |sentinel| { if (i < 1) return sentinel; i -= 1; } if (addr_of_info.align_info) |align_info| { if (i < 1) return align_info.node; i -= 1; } }, Op.PtrType => |addr_of_info| { if (addr_of_info.align_info) |align_info| { if (i < 1) return align_info.node; i -= 1; } }, Op.ArrayType => |array_info| { if (i < 1) return array_info.len_expr; i -= 1; if (array_info.sentinel) |sentinel| { if (i < 1) return sentinel; i -= 1; } }, Op.AddressOf, Op.Await, Op.BitNot, Op.BoolNot, Op.Cancel, Op.OptionalType, Op.Negation, Op.NegationWrap, Op.Try, Op.Resume, => {}, } if (i < 1) return self.rhs; i -= 1; return null; } pub fn firstToken(self: *const PrefixOp) TokenIndex { return self.op_token; } pub fn lastToken(self: *const PrefixOp) TokenIndex { return self.rhs.lastToken(); } }; pub const FieldInitializer = struct { base: Node, period_token: TokenIndex, name_token: TokenIndex, expr: *Node, pub fn iterate(self: *FieldInitializer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const FieldInitializer) TokenIndex { return self.period_token; } pub fn lastToken(self: *const FieldInitializer) TokenIndex { return self.expr.lastToken(); } }; pub const SuffixOp = struct { base: Node, lhs: Lhs, op: Op, rtoken: TokenIndex, pub const Lhs = union(enum) { node: *Node, dot: TokenIndex, }; pub const Op = union(enum) { Call: Call, ArrayAccess: *Node, Slice: Slice, ArrayInitializer: InitList, StructInitializer: InitList, Deref, UnwrapOptional, pub const InitList = SegmentedList(*Node, 2); pub const Call = struct { params: ParamList, async_token: ?TokenIndex, pub const ParamList = SegmentedList(*Node, 2); }; pub const Slice = struct { start: *Node, end: ?*Node, }; }; pub fn iterate(self: *SuffixOp, index: usize) ?*Node { var i = index; switch (self.lhs) { .node => |node| { if (i == 0) return node; i -= 1; }, .dot => {}, } switch (self.op) { .Call => |*call_info| { if (i < call_info.params.len) return call_info.params.at(i).*; i -= call_info.params.len; }, .ArrayAccess => |index_expr| { if (i < 1) return index_expr; i -= 1; }, .Slice => |range| { if (i < 1) return range.start; i -= 1; if (range.end) |end| { if (i < 1) return end; i -= 1; } }, .ArrayInitializer => |*exprs| { if (i < exprs.len) return exprs.at(i).*; i -= exprs.len; }, .StructInitializer => |*fields| { if (i < fields.len) return fields.at(i).*; i -= fields.len; }, .UnwrapOptional, .Deref, => {}, } return null; } pub fn firstToken(self: *const SuffixOp) TokenIndex { switch (self.op) { .Call => |*call_info| if (call_info.async_token) |async_token| return async_token, else => {}, } switch (self.lhs) { .node => |node| return node.firstToken(), .dot => |dot| return dot, } } pub fn lastToken(self: *const SuffixOp) TokenIndex { return self.rtoken; } }; pub const GroupedExpression = struct { base: Node, lparen: TokenIndex, expr: *Node, rparen: TokenIndex, pub fn iterate(self: *GroupedExpression, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const GroupedExpression) TokenIndex { return self.lparen; } pub fn lastToken(self: *const GroupedExpression) TokenIndex { return self.rparen; } }; pub const ControlFlowExpression = struct { base: Node, ltoken: TokenIndex, kind: Kind, rhs: ?*Node, pub const Kind = union(enum) { Break: ?*Node, Continue: ?*Node, Return, }; pub fn iterate(self: *ControlFlowExpression, index: usize) ?*Node { var i = index; switch (self.kind) { Kind.Break => |maybe_label| { if (maybe_label) |label| { if (i < 1) return label; i -= 1; } }, Kind.Continue => |maybe_label| { if (maybe_label) |label| { if (i < 1) return label; i -= 1; } }, Kind.Return => {}, } if (self.rhs) |rhs| { if (i < 1) return rhs; i -= 1; } return null; } pub fn firstToken(self: *const ControlFlowExpression) TokenIndex { return self.ltoken; } pub fn lastToken(self: *const ControlFlowExpression) TokenIndex { if (self.rhs) |rhs| { return rhs.lastToken(); } switch (self.kind) { Kind.Break => |maybe_label| { if (maybe_label) |label| { return label.lastToken(); } }, Kind.Continue => |maybe_label| { if (maybe_label) |label| { return label.lastToken(); } }, Kind.Return => return self.ltoken, } return self.ltoken; } }; pub const Suspend = struct { base: Node, suspend_token: TokenIndex, body: ?*Node, pub fn iterate(self: *Suspend, index: usize) ?*Node { var i = index; if (self.body) |body| { if (i < 1) return body; i -= 1; } return null; } pub fn firstToken(self: *const Suspend) TokenIndex { return self.suspend_token; } pub fn lastToken(self: *const Suspend) TokenIndex { if (self.body) |body| { return body.lastToken(); } return self.suspend_token; } }; pub const IntegerLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *IntegerLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const IntegerLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const IntegerLiteral) TokenIndex { return self.token; } }; pub const EnumLiteral = struct { base: Node, dot: TokenIndex, name: TokenIndex, pub fn iterate(self: *EnumLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const EnumLiteral) TokenIndex { return self.dot; } pub fn lastToken(self: *const EnumLiteral) TokenIndex { return self.name; } }; pub const FloatLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *FloatLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const FloatLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const FloatLiteral) TokenIndex { return self.token; } }; pub const BuiltinCall = struct { base: Node, builtin_token: TokenIndex, params: ParamList, rparen_token: TokenIndex, pub const ParamList = SegmentedList(*Node, 2); pub fn iterate(self: *BuiltinCall, index: usize) ?*Node { var i = index; if (i < self.params.len) return self.params.at(i).*; i -= self.params.len; return null; } pub fn firstToken(self: *const BuiltinCall) TokenIndex { return self.builtin_token; } pub fn lastToken(self: *const BuiltinCall) TokenIndex { return self.rparen_token; } }; pub const StringLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *StringLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const StringLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const StringLiteral) TokenIndex { return self.token; } }; pub const MultilineStringLiteral = struct { base: Node, lines: LineList, pub const LineList = SegmentedList(TokenIndex, 4); pub fn iterate(self: *MultilineStringLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const MultilineStringLiteral) TokenIndex { return self.lines.at(0).*; } pub fn lastToken(self: *const MultilineStringLiteral) TokenIndex { return self.lines.at(self.lines.len - 1).*; } }; pub const CharLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *CharLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const CharLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const CharLiteral) TokenIndex { return self.token; } }; pub const BoolLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *BoolLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const BoolLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const BoolLiteral) TokenIndex { return self.token; } }; pub const NullLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *NullLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const NullLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const NullLiteral) TokenIndex { return self.token; } }; pub const UndefinedLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *UndefinedLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const UndefinedLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const UndefinedLiteral) TokenIndex { return self.token; } }; pub const AsmOutput = struct { base: Node, lbracket: TokenIndex, symbolic_name: *Node, constraint: *Node, kind: Kind, rparen: TokenIndex, pub const Kind = union(enum) { Variable: *Identifier, Return: *Node, }; pub fn iterate(self: *AsmOutput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; i -= 1; if (i < 1) return self.constraint; i -= 1; switch (self.kind) { Kind.Variable => |variable_name| { if (i < 1) return &variable_name.base; i -= 1; }, Kind.Return => |return_type| { if (i < 1) return return_type; i -= 1; }, } return null; } pub fn firstToken(self: *const AsmOutput) TokenIndex { return self.lbracket; } pub fn lastToken(self: *const AsmOutput) TokenIndex { return self.rparen; } }; pub const AsmInput = struct { base: Node, lbracket: TokenIndex, symbolic_name: *Node, constraint: *Node, expr: *Node, rparen: TokenIndex, pub fn iterate(self: *AsmInput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; i -= 1; if (i < 1) return self.constraint; i -= 1; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const AsmInput) TokenIndex { return self.lbracket; } pub fn lastToken(self: *const AsmInput) TokenIndex { return self.rparen; } }; pub const Asm = struct { base: Node, asm_token: TokenIndex, volatile_token: ?TokenIndex, template: *Node, outputs: OutputList, inputs: InputList, clobbers: ClobberList, rparen: TokenIndex, pub const OutputList = SegmentedList(*AsmOutput, 2); pub const InputList = SegmentedList(*AsmInput, 2); pub const ClobberList = SegmentedList(*Node, 2); pub fn iterate(self: *Asm, index: usize) ?*Node { var i = index; if (i < self.outputs.len) return &self.outputs.at(index).*.base; i -= self.outputs.len; if (i < self.inputs.len) return &self.inputs.at(index).*.base; i -= self.inputs.len; return null; } pub fn firstToken(self: *const Asm) TokenIndex { return self.asm_token; } pub fn lastToken(self: *const Asm) TokenIndex { return self.rparen; } }; pub const Unreachable = struct { base: Node, token: TokenIndex, pub fn iterate(self: *Unreachable, index: usize) ?*Node { return null; } pub fn firstToken(self: *const Unreachable) TokenIndex { return self.token; } pub fn lastToken(self: *const Unreachable) TokenIndex { return self.token; } }; pub const ErrorType = struct { base: Node, token: TokenIndex, pub fn iterate(self: *ErrorType, index: usize) ?*Node { return null; } pub fn firstToken(self: *const ErrorType) TokenIndex { return self.token; } pub fn lastToken(self: *const ErrorType) TokenIndex { return self.token; } }; pub const VarType = struct { base: Node = Node{ .id = .VarType }, token: TokenIndex, pub fn iterate(self: *VarType, index: usize) ?*Node { return null; } pub fn firstToken(self: *const VarType) TokenIndex { return self.token; } pub fn lastToken(self: *const VarType) TokenIndex { return self.token; } }; pub const DocComment = struct { base: Node, lines: LineList, pub const LineList = SegmentedList(TokenIndex, 4); pub fn iterate(self: *DocComment, index: usize) ?*Node { return null; } pub fn firstToken(self: *const DocComment) TokenIndex { return self.lines.at(0).*; } pub fn lastToken(self: *const DocComment) TokenIndex { return self.lines.at(self.lines.len - 1).*; } }; pub const TestDecl = struct { base: Node, doc_comments: ?*DocComment, test_token: TokenIndex, name: *Node, body_node: *Node, pub fn iterate(self: *TestDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.body_node; i -= 1; return null; } pub fn firstToken(self: *const TestDecl) TokenIndex { return self.test_token; } pub fn lastToken(self: *const TestDecl) TokenIndex { return self.body_node.lastToken(); } }; }; test "iterate" { var root = Node.Root{ .base = Node{ .id = Node.Id.Root }, .decls = Node.Root.DeclList.init(std.debug.global_allocator), .eof_token = 0, }; var base = &root.base; testing.expect(base.iterate(0) == null); }
lib/std/zig/ast.zig
const std = @import("../std.zig"); const assert = std.debug.assert; ////////////////////////// //// IPC structures //// ////////////////////////// pub const Message = struct { sender: MailboxId, receiver: MailboxId, code: usize, args: [5]usize, payload: ?[]const u8, pub fn from(mailbox_id: MailboxId) Message { return Message{ .sender = MailboxId.Undefined, .receiver = mailbox_id, .code = undefined, .args = undefined, .payload = null, }; } pub fn to(mailbox_id: MailboxId, msg_code: usize, args: ...) Message { var message = Message{ .sender = MailboxId.This, .receiver = mailbox_id, .code = msg_code, .args = undefined, .payload = null, }; assert(args.len <= message.args.len); comptime var i = 0; inline while (i < args.len) : (i += 1) { message.args[i] = args[i]; } return message; } pub fn as(self: Message, sender: MailboxId) Message { var message = self; message.sender = sender; return message; } pub fn withPayload(self: Message, payload: []const u8) Message { var message = self; message.payload = payload; return message; } }; pub const MailboxId = union(enum) { Undefined, This, Kernel, Port: u16, Thread: u16, }; ////////////////////////////////////// //// Ports reserved for servers //// ////////////////////////////////////// pub const Server = struct { pub const Keyboard = MailboxId{ .Port = 0 }; pub const Terminal = MailboxId{ .Port = 1 }; }; //////////////////////// //// POSIX things //// //////////////////////// // Standard streams. pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; // FIXME: let's borrow Linux's error numbers for now. usingnamespace @import("bits/linux/errno-generic.zig"); // Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } // TODO: implement this correctly. pub fn read(fd: i32, buf: [*]u8, count: usize) usize { switch (fd) { STDIN_FILENO => { var i: usize = 0; while (i < count) : (i += 1) { send(&Message.to(Server.Keyboard, 0)); // FIXME: we should be certain that we are receiving from Keyboard. var message = Message.from(MailboxId.This); receive(&message); buf[i] = @intCast(u8, message.args[0]); } }, else => unreachable, } return count; } // TODO: implement this correctly. pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { switch (fd) { STDOUT_FILENO, STDERR_FILENO => { send(&Message.to(Server.Terminal, 1).withPayload(buf[0..count])); }, else => unreachable, } return count; } /////////////////////////// //// Syscall numbers //// /////////////////////////// pub const Syscall = enum(usize) { exit = 0, send = 1, receive = 2, subscribeIRQ = 3, inb = 4, outb = 5, map = 6, createThread = 7, }; //////////////////// //// Syscalls //// //////////////////// pub fn exit(status: i32) noreturn { _ = syscall1(Syscall.exit, @bitCast(usize, @as(isize, status))); unreachable; } pub fn send(message: *const Message) void { _ = syscall1(Syscall.send, @ptrToInt(message)); } pub fn receive(destination: *Message) void { _ = syscall1(Syscall.receive, @ptrToInt(destination)); } pub fn subscribeIRQ(irq: u8, mailbox_id: *const MailboxId) void { _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id)); } pub fn inb(port: u16) u8 { return @intCast(u8, syscall1(Syscall.inb, port)); } pub fn outb(port: u16, value: u8) void { _ = syscall2(Syscall.outb, port, value); } pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { return syscall4(Syscall.map, v_addr, p_addr, size, @boolToInt(writable)) != 0; } pub fn createThread(function: fn () void) u16 { return @as(u16, syscall1(Syscall.createThread, @ptrToInt(function))); } ///////////////////////// //// Syscall stubs //// ///////////////////////// inline fn syscall0(number: Syscall) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number) ); } inline fn syscall1(number: Syscall, arg1: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1) ); } inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2) ); } inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3) ); } inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4) ); } inline fn syscall5( number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, ) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4), [arg5] "{edi}" (arg5) ); } inline fn syscall6( number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), [arg1] "{ecx}" (arg1), [arg2] "{edx}" (arg2), [arg3] "{ebx}" (arg3), [arg4] "{esi}" (arg4), [arg5] "{edi}" (arg5), [arg6] "{ebp}" (arg6) ); }
lib/std/os/zen.zig
const Wasm = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const fs = std.fs; const leb = std.debug.leb; const Module = @import("../Module.zig"); const codegen = @import("../codegen/wasm.zig"); const link = @import("../link.zig"); /// Various magic numbers defined by the wasm spec const spec = struct { const magic = [_]u8{ 0x00, 0x61, 0x73, 0x6D }; // \0asm const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; // version 1 const custom_id = 0; const types_id = 1; const imports_id = 2; const funcs_id = 3; const tables_id = 4; const memories_id = 5; const globals_id = 6; const exports_id = 7; const start_id = 8; const elements_id = 9; const code_id = 10; const data_id = 11; }; pub const base_tag = link.File.Tag.wasm; pub const FnData = struct { /// Generated code for the type of the function functype: std.ArrayListUnmanaged(u8) = .{}, /// Generated code for the body of the function code: std.ArrayListUnmanaged(u8) = .{}, /// Locations in the generated code where function indexes must be filled in. /// This must be kept ordered by offset. idx_refs: std.ArrayListUnmanaged(struct { offset: u32, decl: *Module.Decl }) = .{}, }; base: link.File, /// List of all function Decls to be written to the output file. The index of /// each Decl in this list at the time of writing the binary is used as the /// function index. /// TODO: can/should we access some data structure in Module directly? funcs: std.ArrayListUnmanaged(*Module.Decl) = .{}, pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: link.Options) !*link.File { assert(options.object_format == .wasm); // TODO: read the file and keep vaild parts instead of truncating const file = try dir.createFile(sub_path, .{ .truncate = true, .read = true }); errdefer file.close(); const wasm = try allocator.create(Wasm); errdefer allocator.destroy(wasm); try file.writeAll(&(spec.magic ++ spec.version)); wasm.* = .{ .base = .{ .tag = .wasm, .options = options, .file = file, .allocator = allocator, }, }; return &wasm.base; } pub fn deinit(self: *Wasm) void { for (self.funcs.items) |decl| { decl.fn_link.wasm.?.functype.deinit(self.base.allocator); decl.fn_link.wasm.?.code.deinit(self.base.allocator); decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator); } self.funcs.deinit(self.base.allocator); } // Generate code for the Decl, storing it in memory to be later written to // the file on flush(). pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { if (decl.typed_value.most_recent.typed_value.ty.zigTypeTag() != .Fn) return error.TODOImplementNonFnDeclsForWasm; if (decl.fn_link.wasm) |*fn_data| { fn_data.functype.items.len = 0; fn_data.code.items.len = 0; fn_data.idx_refs.items.len = 0; } else { decl.fn_link.wasm = .{}; try self.funcs.append(self.base.allocator, decl); } const fn_data = &decl.fn_link.wasm.?; var managed_functype = fn_data.functype.toManaged(self.base.allocator); var managed_code = fn_data.code.toManaged(self.base.allocator); try codegen.genFunctype(&managed_functype, decl); try codegen.genCode(&managed_code, decl); fn_data.functype = managed_functype.toUnmanaged(); fn_data.code = managed_code.toUnmanaged(); } pub fn updateDeclExports( self: *Wasm, module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, ) !void {} pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { // TODO: remove this assert when non-function Decls are implemented assert(decl.typed_value.most_recent.typed_value.ty.zigTypeTag() == .Fn); _ = self.funcs.swapRemove(self.getFuncidx(decl).?); decl.fn_link.wasm.?.functype.deinit(self.base.allocator); decl.fn_link.wasm.?.code.deinit(self.base.allocator); decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator); decl.fn_link.wasm = null; } pub fn flush(self: *Wasm, module: *Module) !void { const file = self.base.file.?; const header_size = 5 + 1; // No need to rewrite the magic/version header try file.setEndPos(@sizeOf(@TypeOf(spec.magic ++ spec.version))); try file.seekTo(@sizeOf(@TypeOf(spec.magic ++ spec.version))); // Type section { const header_offset = try reserveVecSectionHeader(file); for (self.funcs.items) |decl| { try file.writeAll(decl.fn_link.wasm.?.functype.items); } try writeVecSectionHeader( file, header_offset, spec.types_id, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.funcs.items.len), ); } // Function section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.funcs.items) |_, typeidx| try leb.writeULEB128(writer, @intCast(u32, typeidx)); try writeVecSectionHeader( file, header_offset, spec.funcs_id, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.funcs.items.len), ); } // Export section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); var count: u32 = 0; for (module.decl_exports.entries.items) |entry| { for (entry.value) |exprt| { // Export name length + name try leb.writeULEB128(writer, @intCast(u32, exprt.options.name.len)); try writer.writeAll(exprt.options.name); switch (exprt.exported_decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) { .Fn => { // Type of the export try writer.writeByte(0x00); // Exported function index try leb.writeULEB128(writer, self.getFuncidx(exprt.exported_decl).?); }, else => return error.TODOImplementNonFnDeclsForWasm, } count += 1; } } try writeVecSectionHeader( file, header_offset, spec.exports_id, @intCast(u32, (try file.getPos()) - header_offset - header_size), count, ); } // Code section { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); for (self.funcs.items) |decl| { const fn_data = &decl.fn_link.wasm.?; // Write the already generated code to the file, inserting // function indexes where required. var current: u32 = 0; for (fn_data.idx_refs.items) |idx_ref| { try writer.writeAll(fn_data.code.items[current..idx_ref.offset]); current = idx_ref.offset; // Use a fixed width here to make calculating the code size // in codegen.wasm.genCode() simpler. var buf: [5]u8 = undefined; leb.writeUnsignedFixed(5, &buf, self.getFuncidx(idx_ref.decl).?); try writer.writeAll(&buf); } try writer.writeAll(fn_data.code.items[current..]); } try writeVecSectionHeader( file, header_offset, spec.code_id, @intCast(u32, (try file.getPos()) - header_offset - header_size), @intCast(u32, self.funcs.items.len), ); } } /// Get the current index of a given Decl in the function list /// TODO: we could maintain a hash map to potentially make this fn getFuncidx(self: Wasm, decl: *Module.Decl) ?u32 { return for (self.funcs.items) |func, idx| { if (func == decl) break @intCast(u32, idx); } else null; } fn reserveVecSectionHeader(file: fs.File) !u64 { // section id + fixed leb contents size + fixed leb vector length const header_size = 1 + 5 + 5; // TODO: this should be a single lseek(2) call, but fs.File does not // currently provide a way to do this. try file.seekBy(header_size); return (try file.getPos()) - header_size; } fn writeVecSectionHeader(file: fs.File, offset: u64, section: u8, size: u32, items: u32) !void { var buf: [1 + 5 + 5]u8 = undefined; buf[0] = section; leb.writeUnsignedFixed(5, buf[1..6], size); leb.writeUnsignedFixed(5, buf[6..], items); try file.pwriteAll(&buf, offset); }
src-self-hosted/link/Wasm.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "compile time recursion" { try expect(some_data.len == 21); } var some_data: [@intCast(usize, fibonacci(7))]u8 = undefined; fn fibonacci(x: i32) i32 { if (x <= 1) return 1; return fibonacci(x - 1) + fibonacci(x - 2); } fn unwrapAndAddOne(blah: ?i32) i32 { return blah.? + 1; } const should_be_1235 = unwrapAndAddOne(1234); test "static add one" { try expect(should_be_1235 == 1235); } test "inlined loop" { comptime var i = 0; comptime var sum = 0; inline while (i <= 5) : (i += 1) sum += i; try expect(sum == 15); } fn gimme1or2(comptime a: bool) i32 { const x: i32 = 1; const y: i32 = 2; comptime var z: i32 = if (a) x else y; return z; } test "inline variable gets result of const if" { try expect(gimme1or2(true) == 1); try expect(gimme1or2(false) == 2); } test "static function evaluation" { try expect(statically_added_number == 3); } const statically_added_number = staticAdd(1, 2); fn staticAdd(a: i32, b: i32) i32 { return a + b; } test "const expr eval on single expr blocks" { try expect(constExprEvalOnSingleExprBlocksFn(1, true) == 3); comptime try expect(constExprEvalOnSingleExprBlocksFn(1, true) == 3); } fn constExprEvalOnSingleExprBlocksFn(x: i32, b: bool) i32 { const literal = 3; const result = if (b) b: { break :b literal; } else b: { break :b x; }; return result; } test "constant expressions" { var array: [array_size]u8 = undefined; try expect(@sizeOf(@TypeOf(array)) == 20); } const array_size: u8 = 20; fn max(comptime T: type, a: T, b: T) T { if (T == bool) { return a or b; } else if (a > b) { return a; } else { return b; } } fn letsTryToCompareBools(a: bool, b: bool) bool { return max(bool, a, b); } test "inlined block and runtime block phi" { try expect(letsTryToCompareBools(true, true)); try expect(letsTryToCompareBools(true, false)); try expect(letsTryToCompareBools(false, true)); try expect(!letsTryToCompareBools(false, false)); comptime { try expect(letsTryToCompareBools(true, true)); try expect(letsTryToCompareBools(true, false)); try expect(letsTryToCompareBools(false, true)); try expect(!letsTryToCompareBools(false, false)); } } test "eval @setRuntimeSafety at compile-time" { const result = comptime fnWithSetRuntimeSafety(); try expect(result == 1234); } fn fnWithSetRuntimeSafety() i32 { @setRuntimeSafety(true); return 1234; } test "compile-time downcast when the bits fit" { comptime { const spartan_count: u16 = 255; const byte = @intCast(u8, spartan_count); try expect(byte == 255); } } test "pointer to type" { comptime { var T: type = i32; try expect(T == i32); var ptr = &T; try expect(@TypeOf(ptr) == *type); ptr.* = f32; try expect(T == f32); try expect(*T == *f32); } } test "no undeclared identifier error in unanalyzed branches" { if (false) { lol_this_doesnt_exist = nonsense; } }
test/behavior/eval.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub fn Permutator(comptime T: type) type { return struct { const Self = @This(); const Elements = std.ArrayList(T); elements: Elements, started: bool = undefined, completed: bool = undefined, c: [32]usize = undefined, i: usize = undefined, pub fn init(allocator: Allocator) !Self { var permutator = Self { .elements = Elements.init(allocator) }; permutator.reset(); return permutator; } pub fn fromHashMapKeys(allocator: Allocator, comptime M: type, map: M) !Self { var permutator = try init(allocator); var iterator = map.iterator(); while (iterator.next()) |kv| { try permutator.elements.append(kv.key_ptr.*); } return permutator; } pub fn reset(self: *Self) void { self.started = false; self.completed = false; self.c = [_]usize{0} ** 32; self.i = 0; } // Heap's Algorithm // TODO make it async when https://github.com/ziglang/zig/issues/6917 gets resolved pub fn next(self: *Self) ?[]const T { if (self.completed) { return null; } if (!self.started) { self.started = true; return self.elements.items; } while (self.i < self.elements.items.len) { if (self.c[self.i] < self.i) { if (self.i % 2 == 0) { self.swap(0, self.i); } else { self.swap(self.c[self.i], self.i); } self.c[self.i] += 1; self.i = 0; return self.elements.items; } else { self.c[self.i] = 0; self.i += 1; } } self.completed = true; return null; } fn swap(self: *Self, a: usize, b: usize) void { var tmp = self.elements.items[a]; self.elements.items[a] = self.elements.items[b]; self.elements.items[b] = tmp; } pub fn deinit(self: *Self) void { self.elements.deinit(); } }; }
src/main/zig/lib/permutator.zig
const std = @import("std"); const Builder = std.build.Builder; const examples = [_][]const u8{ "get", "post", "download", "evented" }; const packages = @import("deps.zig"); pub fn build(b: *Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); inline for (examples) |name| { const example = b.addExecutable(name, name ++ ".zig"); example.setBuildMode(mode); example.setTarget(target); example.install(); if (@hasDecl(packages, "use_submodules")) { example.addPackage(getPackage(b) catch unreachable); } else { if (@hasDecl(packages, "addAllTo")) { // zigmod packages.addAllTo(example); } else if (@hasDecl(packages, "pkgs") and @hasDecl(packages.pkgs, "addAllTo")) { // gyro packages.pkgs.addAllTo(example); } } const example_step = b.step(name, "Build the " ++ name ++ " example"); example_step.dependOn(&example.step); const example_run_step = b.step("run-" ++ name, "Run the " ++ name ++ " example"); const example_run = example.run(); example_run_step.dependOn(&example_run.step); } } // we can't use zfetch_build.getPackage() because its outside of this build's package path fn getBuildPrefix() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } fn getDependency(comptime name: []const u8, comptime root: []const u8) !std.build.Pkg { const path = getBuildPrefix() ++ "/../libs/" ++ name ++ "/" ++ root; // Make sure that the dependency has been checked out. std.fs.cwd().access(path, .{}) catch |err| switch (err) { error.FileNotFound => { std.log.err("zfetch: dependency '{s}' not checked out", .{name}); return err; }, else => return err, }; return std.build.Pkg{ .name = name, .path = .{ .path = path }, }; } pub fn getPackage(b: *Builder) !std.build.Pkg { var dependencies = b.allocator.alloc(std.build.Pkg, 4) catch unreachable; dependencies[0] = try getDependency("iguanaTLS", "src/main.zig"); dependencies[1] = try getDependency("network", "network.zig"); dependencies[2] = try getDependency("uri", "uri.zig"); dependencies[3] = try getDependency("hzzp", "src/main.zig"); return std.build.Pkg{ .name = "zfetch", .path = .{ .path = getBuildPrefix() ++ "/src/main.zig" }, .dependencies = dependencies, }; }
examples/build.zig
const clzsi2 = @import("clzsi2.zig"); const testing = @import("std").testing; fn test__clzsi2(a: u32, expected: i32) void { // XXX At high optimization levels this test may be horribly miscompiled if // one of the naked implementations is selected. var nakedClzsi2 = clzsi2.__clzsi2; var actualClzsi2 = @ptrCast(fn (a: i32) callconv(.C) i32, nakedClzsi2); var x = @bitCast(i32, a); var result = actualClzsi2(x); testing.expectEqual(expected, result); } test "clzsi2" { test__clzsi2(0x00800000, 8); test__clzsi2(0x01000000, 7); test__clzsi2(0x02000000, 6); test__clzsi2(0x03000000, 6); test__clzsi2(0x04000000, 5); test__clzsi2(0x05000000, 5); test__clzsi2(0x06000000, 5); test__clzsi2(0x07000000, 5); test__clzsi2(0x08000000, 4); test__clzsi2(0x09000000, 4); test__clzsi2(0x0A000000, 4); test__clzsi2(0x0B000000, 4); test__clzsi2(0x0C000000, 4); test__clzsi2(0x0D000000, 4); test__clzsi2(0x0E000000, 4); test__clzsi2(0x0F000000, 4); test__clzsi2(0x10000000, 3); test__clzsi2(0x11000000, 3); test__clzsi2(0x12000000, 3); test__clzsi2(0x13000000, 3); test__clzsi2(0x14000000, 3); test__clzsi2(0x15000000, 3); test__clzsi2(0x16000000, 3); test__clzsi2(0x17000000, 3); test__clzsi2(0x18000000, 3); test__clzsi2(0x19000000, 3); test__clzsi2(0x1A000000, 3); test__clzsi2(0x1B000000, 3); test__clzsi2(0x1C000000, 3); test__clzsi2(0x1D000000, 3); test__clzsi2(0x1E000000, 3); test__clzsi2(0x1F000000, 3); test__clzsi2(0x20000000, 2); test__clzsi2(0x21000000, 2); test__clzsi2(0x22000000, 2); test__clzsi2(0x23000000, 2); test__clzsi2(0x24000000, 2); test__clzsi2(0x25000000, 2); test__clzsi2(0x26000000, 2); test__clzsi2(0x27000000, 2); test__clzsi2(0x28000000, 2); test__clzsi2(0x29000000, 2); test__clzsi2(0x2A000000, 2); test__clzsi2(0x2B000000, 2); test__clzsi2(0x2C000000, 2); test__clzsi2(0x2D000000, 2); test__clzsi2(0x2E000000, 2); test__clzsi2(0x2F000000, 2); test__clzsi2(0x30000000, 2); test__clzsi2(0x31000000, 2); test__clzsi2(0x32000000, 2); test__clzsi2(0x33000000, 2); test__clzsi2(0x34000000, 2); test__clzsi2(0x35000000, 2); test__clzsi2(0x36000000, 2); test__clzsi2(0x37000000, 2); test__clzsi2(0x38000000, 2); test__clzsi2(0x39000000, 2); test__clzsi2(0x3A000000, 2); test__clzsi2(0x3B000000, 2); test__clzsi2(0x3C000000, 2); test__clzsi2(0x3D000000, 2); test__clzsi2(0x3E000000, 2); test__clzsi2(0x3F000000, 2); test__clzsi2(0x40000000, 1); test__clzsi2(0x41000000, 1); test__clzsi2(0x42000000, 1); test__clzsi2(0x43000000, 1); test__clzsi2(0x44000000, 1); test__clzsi2(0x45000000, 1); test__clzsi2(0x46000000, 1); test__clzsi2(0x47000000, 1); test__clzsi2(0x48000000, 1); test__clzsi2(0x49000000, 1); test__clzsi2(0x4A000000, 1); test__clzsi2(0x4B000000, 1); test__clzsi2(0x4C000000, 1); test__clzsi2(0x4D000000, 1); test__clzsi2(0x4E000000, 1); test__clzsi2(0x4F000000, 1); test__clzsi2(0x50000000, 1); test__clzsi2(0x51000000, 1); test__clzsi2(0x52000000, 1); test__clzsi2(0x53000000, 1); test__clzsi2(0x54000000, 1); test__clzsi2(0x55000000, 1); test__clzsi2(0x56000000, 1); test__clzsi2(0x57000000, 1); test__clzsi2(0x58000000, 1); test__clzsi2(0x59000000, 1); test__clzsi2(0x5A000000, 1); test__clzsi2(0x5B000000, 1); test__clzsi2(0x5C000000, 1); test__clzsi2(0x5D000000, 1); test__clzsi2(0x5E000000, 1); test__clzsi2(0x5F000000, 1); test__clzsi2(0x60000000, 1); test__clzsi2(0x61000000, 1); test__clzsi2(0x62000000, 1); test__clzsi2(0x63000000, 1); test__clzsi2(0x64000000, 1); test__clzsi2(0x65000000, 1); test__clzsi2(0x66000000, 1); test__clzsi2(0x67000000, 1); test__clzsi2(0x68000000, 1); test__clzsi2(0x69000000, 1); test__clzsi2(0x6A000000, 1); test__clzsi2(0x6B000000, 1); test__clzsi2(0x6C000000, 1); test__clzsi2(0x6D000000, 1); test__clzsi2(0x6E000000, 1); test__clzsi2(0x6F000000, 1); test__clzsi2(0x70000000, 1); test__clzsi2(0x71000000, 1); test__clzsi2(0x72000000, 1); test__clzsi2(0x73000000, 1); test__clzsi2(0x74000000, 1); test__clzsi2(0x75000000, 1); test__clzsi2(0x76000000, 1); test__clzsi2(0x77000000, 1); test__clzsi2(0x78000000, 1); test__clzsi2(0x79000000, 1); test__clzsi2(0x7A000000, 1); test__clzsi2(0x7B000000, 1); test__clzsi2(0x7C000000, 1); test__clzsi2(0x7D000000, 1); test__clzsi2(0x7E000000, 1); test__clzsi2(0x7F000000, 1); test__clzsi2(0x80000000, 0); test__clzsi2(0x81000000, 0); test__clzsi2(0x82000000, 0); test__clzsi2(0x83000000, 0); test__clzsi2(0x84000000, 0); test__clzsi2(0x85000000, 0); test__clzsi2(0x86000000, 0); test__clzsi2(0x87000000, 0); test__clzsi2(0x88000000, 0); test__clzsi2(0x89000000, 0); test__clzsi2(0x8A000000, 0); test__clzsi2(0x8B000000, 0); test__clzsi2(0x8C000000, 0); test__clzsi2(0x8D000000, 0); test__clzsi2(0x8E000000, 0); test__clzsi2(0x8F000000, 0); test__clzsi2(0x90000000, 0); test__clzsi2(0x91000000, 0); test__clzsi2(0x92000000, 0); test__clzsi2(0x93000000, 0); test__clzsi2(0x94000000, 0); test__clzsi2(0x95000000, 0); test__clzsi2(0x96000000, 0); test__clzsi2(0x97000000, 0); test__clzsi2(0x98000000, 0); test__clzsi2(0x99000000, 0); test__clzsi2(0x9A000000, 0); test__clzsi2(0x9B000000, 0); test__clzsi2(0x9C000000, 0); test__clzsi2(0x9D000000, 0); test__clzsi2(0x9E000000, 0); test__clzsi2(0x9F000000, 0); test__clzsi2(0xA0000000, 0); test__clzsi2(0xA1000000, 0); test__clzsi2(0xA2000000, 0); test__clzsi2(0xA3000000, 0); test__clzsi2(0xA4000000, 0); test__clzsi2(0xA5000000, 0); test__clzsi2(0xA6000000, 0); test__clzsi2(0xA7000000, 0); test__clzsi2(0xA8000000, 0); test__clzsi2(0xA9000000, 0); test__clzsi2(0xAA000000, 0); test__clzsi2(0xAB000000, 0); test__clzsi2(0xAC000000, 0); test__clzsi2(0xAD000000, 0); test__clzsi2(0xAE000000, 0); test__clzsi2(0xAF000000, 0); test__clzsi2(0xB0000000, 0); test__clzsi2(0xB1000000, 0); test__clzsi2(0xB2000000, 0); test__clzsi2(0xB3000000, 0); test__clzsi2(0xB4000000, 0); test__clzsi2(0xB5000000, 0); test__clzsi2(0xB6000000, 0); test__clzsi2(0xB7000000, 0); test__clzsi2(0xB8000000, 0); test__clzsi2(0xB9000000, 0); test__clzsi2(0xBA000000, 0); test__clzsi2(0xBB000000, 0); test__clzsi2(0xBC000000, 0); test__clzsi2(0xBD000000, 0); test__clzsi2(0xBE000000, 0); test__clzsi2(0xBF000000, 0); test__clzsi2(0xC0000000, 0); test__clzsi2(0xC1000000, 0); test__clzsi2(0xC2000000, 0); test__clzsi2(0xC3000000, 0); test__clzsi2(0xC4000000, 0); test__clzsi2(0xC5000000, 0); test__clzsi2(0xC6000000, 0); test__clzsi2(0xC7000000, 0); test__clzsi2(0xC8000000, 0); test__clzsi2(0xC9000000, 0); test__clzsi2(0xCA000000, 0); test__clzsi2(0xCB000000, 0); test__clzsi2(0xCC000000, 0); test__clzsi2(0xCD000000, 0); test__clzsi2(0xCE000000, 0); test__clzsi2(0xCF000000, 0); test__clzsi2(0xD0000000, 0); test__clzsi2(0xD1000000, 0); test__clzsi2(0xD2000000, 0); test__clzsi2(0xD3000000, 0); test__clzsi2(0xD4000000, 0); test__clzsi2(0xD5000000, 0); test__clzsi2(0xD6000000, 0); test__clzsi2(0xD7000000, 0); test__clzsi2(0xD8000000, 0); test__clzsi2(0xD9000000, 0); test__clzsi2(0xDA000000, 0); test__clzsi2(0xDB000000, 0); test__clzsi2(0xDC000000, 0); test__clzsi2(0xDD000000, 0); test__clzsi2(0xDE000000, 0); test__clzsi2(0xDF000000, 0); test__clzsi2(0xE0000000, 0); test__clzsi2(0xE1000000, 0); test__clzsi2(0xE2000000, 0); test__clzsi2(0xE3000000, 0); test__clzsi2(0xE4000000, 0); test__clzsi2(0xE5000000, 0); test__clzsi2(0xE6000000, 0); test__clzsi2(0xE7000000, 0); test__clzsi2(0xE8000000, 0); test__clzsi2(0xE9000000, 0); test__clzsi2(0xEA000000, 0); test__clzsi2(0xEB000000, 0); test__clzsi2(0xEC000000, 0); test__clzsi2(0xED000000, 0); test__clzsi2(0xEE000000, 0); test__clzsi2(0xEF000000, 0); test__clzsi2(0xF0000000, 0); test__clzsi2(0xF1000000, 0); test__clzsi2(0xF2000000, 0); test__clzsi2(0xF3000000, 0); test__clzsi2(0xF4000000, 0); test__clzsi2(0xF5000000, 0); test__clzsi2(0xF6000000, 0); test__clzsi2(0xF7000000, 0); test__clzsi2(0xF8000000, 0); test__clzsi2(0xF9000000, 0); test__clzsi2(0xFA000000, 0); test__clzsi2(0xFB000000, 0); test__clzsi2(0xFC000000, 0); test__clzsi2(0xFD000000, 0); test__clzsi2(0xFE000000, 0); test__clzsi2(0xFF000000, 0); test__clzsi2(0x00000001, 31); test__clzsi2(0x00000002, 30); test__clzsi2(0x00000004, 29); test__clzsi2(0x00000008, 28); test__clzsi2(0x00000010, 27); test__clzsi2(0x00000020, 26); test__clzsi2(0x00000040, 25); test__clzsi2(0x00000080, 24); test__clzsi2(0x00000100, 23); test__clzsi2(0x00000200, 22); test__clzsi2(0x00000400, 21); test__clzsi2(0x00000800, 20); test__clzsi2(0x00001000, 19); test__clzsi2(0x00002000, 18); test__clzsi2(0x00004000, 17); test__clzsi2(0x00008000, 16); test__clzsi2(0x00010000, 15); test__clzsi2(0x00020000, 14); test__clzsi2(0x00040000, 13); test__clzsi2(0x00080000, 12); test__clzsi2(0x00100000, 11); test__clzsi2(0x00200000, 10); test__clzsi2(0x00400000, 9); }
lib/std/special/compiler_rt/clzsi2_test.zig
const std = @import("std"); const ascii = std.ascii; const debug = std.debug; const fs = std.fs; const math = std.math; const mem = std.mem; const unicode = std.unicode; // This was ported from termbox https://github.com/nsf/termbox (not complete) pub const Key = struct { pub const Type = u64; pub const unknown = 0xffffffffffffffff; pub const f1 = ctrl | (0xffff - 0); pub const f2 = ctrl | (0xffff - 1); pub const f3 = ctrl | (0xffff - 2); pub const f4 = ctrl | (0xffff - 3); pub const f5 = ctrl | (0xffff - 4); pub const f6 = ctrl | (0xffff - 5); pub const f7 = ctrl | (0xffff - 6); pub const f8 = ctrl | (0xffff - 7); pub const f9 = ctrl | (0xffff - 8); pub const f10 = ctrl | (0xffff - 9); pub const f11 = ctrl | (0xffff - 10); pub const f12 = ctrl | (0xffff - 11); pub const insert = ctrl | (0xffff - 12); pub const delete = ctrl | (0xffff - 13); pub const home = ctrl | (0xffff - 14); pub const end = ctrl | (0xffff - 15); pub const page_up = ctrl | (0xffff - 16); pub const page_down = ctrl | (0xffff - 17); pub const arrow_up = ctrl | (0xffff - 18); pub const arrow_down = ctrl | (0xffff - 19); pub const arrow_left = ctrl | (0xffff - 20); pub const arrow_right = ctrl | (0xffff - 21); pub const ctrl_arrow_up = ctrl | (0xffff - 22); pub const ctrl_arrow_down = ctrl | (0xffff - 23); pub const ctrl_arrow_left = ctrl | (0xffff - 24); pub const ctrl_arrow_right = ctrl | (0xffff - 25); pub const shift_arrow_up = ctrl | (0xffff - 26); pub const shift_arrow_down = ctrl | (0xffff - 27); pub const shift_arrow_left = ctrl | (0xffff - 28); pub const shift_arrow_right = ctrl | (0xffff - 29); pub const ctrl_tilde = ctrl | 0x00; pub const ctrl_2 = ctrl_tilde; pub const ctrl_a = ctrl | 0x01; pub const ctrl_b = ctrl | 0x02; pub const ctrl_c = ctrl | 0x03; pub const ctrl_d = ctrl | 0x04; pub const ctrl_e = ctrl | 0x05; pub const ctrl_f = ctrl | 0x06; pub const ctrl_g = ctrl | 0x07; pub const backspace = ctrl | 0x08; pub const ctrl_h = backspace; pub const tab = ctrl | 0x09; pub const ctrl_i = tab; pub const ctrl_j = ctrl | 0x0a; pub const ctrl_k = ctrl | 0x0b; pub const ctrl_l = ctrl | 0x0c; pub const enter = ctrl | 0x0d; pub const ctrl_m = enter; pub const ctrl_n = ctrl | 0x0e; pub const ctrl_o = ctrl | 0x0f; pub const ctrl_p = ctrl | 0x10; pub const ctrl_q = ctrl | 0x11; pub const ctrl_r = ctrl | 0x12; pub const ctrl_s = ctrl | 0x13; pub const ctrl_t = ctrl | 0x14; pub const ctrl_u = ctrl | 0x15; pub const ctrl_v = ctrl | 0x16; pub const ctrl_w = ctrl | 0x17; pub const ctrl_x = ctrl | 0x18; pub const ctrl_y = ctrl | 0x19; pub const ctrl_z = ctrl | 0x1a; pub const escape = ctrl | 0x1b; pub const ctrl_lsq_bracket = escape; pub const ctrl_3 = escape; pub const ctrl_4 = ctrl | 0x1c; pub const ctrl_backslash = ctrl_4; pub const ctrl_5 = ctrl | 0x1d; pub const ctrl_rsq_bracket = ctrl_5; pub const ctrl_6 = ctrl | 0x1e; pub const ctrl_7 = ctrl | 0x1f; pub const ctrl_slash = ctrl_7; pub const ctrl_underscore = ctrl_7; pub const space = ctrl | 0x20; pub const backspace2 = ctrl | 0x7f; pub const ctrl_8 = backspace2; pub const alt = 1 << 63; const ctrl = 1 << 62; pub const Pick = enum { NotCtrl, // picks non ctrl keys over ctrl keys CtrlAlphaNum, // picks ctrl_a-z and ctrl_0-9 over other ctrl keys CtrlSpecial1, // picks ctrl_{tidle, lsq/rsq_bracket, backslash, slash} over other ctrl keys CtrlSpecial2, // picks ctrl_{tidle, lsq/rsq_bracket, backslash, undscore} over other ctrl keys }; /// Returns null terminated array pub fn toStr(key: Key.Type, pick: Pick) [32:0]u8 { if (key == Key.unknown) return ("???" ++ ("\x00" ** 29)).*; const modi_str = switch (key & alt) { alt => "alt+", else => "", }; var utf8_buf: [4]u8 = undefined; const key_no_modi = key & ~@as(Type, alt); const key_str = switch (key_no_modi) { f1 => "f1", f2 => "f2", f3 => "f3", f4 => "f4", f5 => "f5", f6 => "f6", f7 => "f7", f8 => "f8", f9 => "f9", f10 => "f10", f11 => "f11", f12 => "f12", insert => "insert", delete => "delete", home => "home", end => "end", backspace => switch (pick) { .NotCtrl => "backspace", else => "ctrl+h", }, tab => switch (pick) { .NotCtrl => "tab", else => "ctrl+i", }, enter => switch (pick) { .NotCtrl => "enter", else => "ctrl+m", }, escape => switch (pick) { .NotCtrl => "escape", .CtrlAlphaNum => "ctrl+3", else => "ctrl+???", // TODO: ctrl_lsq_bracket }, space => "space", backspace2 => switch (pick) { .NotCtrl => "backspace2", else => "ctrl+8", }, page_up => "page_up", page_down => "page_down", arrow_up => "arrow_up", arrow_down => "arrow_down", arrow_left => "arrow_left", arrow_right => "arrow_right", ctrl_arrow_up => "ctrl+arrow_up", ctrl_arrow_down => "ctrl+arrow_down", ctrl_arrow_left => "ctrl+arrow_left", ctrl_arrow_right => "ctrl+arrow_right", shift_arrow_up => "shift+arrow_up", shift_arrow_down => "shift+arrow_down", shift_arrow_left => "shift+arrow_left", shift_arrow_right => "shift+arrow_right", ctrl_a => "ctrl+a", ctrl_b => "ctrl+b", ctrl_c => "ctrl+c", ctrl_d => "ctrl+d", ctrl_e => "ctrl+e", ctrl_f => "ctrl+f", ctrl_g => "ctrl+g", ctrl_j => "ctrl+j", ctrl_k => "ctrl+k", ctrl_l => "ctrl+l", ctrl_n => "ctrl+n", ctrl_o => "ctrl+o", ctrl_p => "ctrl+p", ctrl_q => "ctrl+q", ctrl_r => "ctrl+r", ctrl_s => "ctrl+s", ctrl_t => "ctrl+t", ctrl_u => "ctrl+u", ctrl_v => "ctrl+v", ctrl_w => "ctrl+w", ctrl_x => "ctrl+x", ctrl_y => "ctrl+y", ctrl_z => "ctrl+z", ctrl_2 => switch (pick) { .NotCtrl, .CtrlAlphaNum => "ctrl+2", else => "ctrl+~", }, ctrl_4 => switch (pick) { .NotCtrl, .CtrlAlphaNum => "ctrl+4", else => "ctrl+\\", }, ctrl_5 => switch (pick) { .NotCtrl, .CtrlAlphaNum => "ctrl+5", else => "ctrl+???", // TODO: ctrl_rsq_bracket }, ctrl_6 => "ctrl+6", ctrl_7 => switch (pick) { .NotCtrl, .CtrlAlphaNum => "ctrl+7", .CtrlSpecial1 => "ctrl+/", .CtrlSpecial2 => "ctrl+_", }, else => blk: { if ((key & 0xffffffff00000000) != 0) break :blk "???"; const codepoint = @intCast(u21, key & 0x00000000ffffffff); const len = unicode.utf8Encode(codepoint, &utf8_buf) catch unreachable; break :blk utf8_buf[0..len]; }, }; var res = ("\x00" ** 32).*; mem.copy(u8, res[0..], modi_str); mem.copy(u8, res[modi_str.len..], key_str); return res; } }; // TODO: this is not the exact escape keys for my terminal const esc_keys = [_][]const u8{ "\x1bOP", "\x1bOQ", "\x1bOR", "\x1bOS", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[H", "\x1b[F", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", "\x1b[1;5A", "\x1b[1;5B", "\x1b[1;5D", "\x1b[1;5C", "\x1b[1;2A", "\x1b[1;2B", "\x1b[1;2D", "\x1b[1;2C", }; fn parseKey(key: []const u8) Key.Type { if (key.len == 1 and key[0] == '\x1b') return Key.escape; if (key[0] == '\x1b') { for (esc_keys) |esc_key, i| { if (mem.startsWith(u8, key, esc_key)) return Key.f1 - i; } return Key.alt | parseKey(key[1..]); } if (key[0] <= (Key.space & ~@as(Key.Type, Key.ctrl))) return Key.ctrl | @as(Key.Type, key[0]); if (key[0] == (Key.backspace2 & ~@as(Key.Type, Key.ctrl))) return Key.ctrl | @as(Key.Type, key[0]); const len = unicode.utf8ByteSequenceLength(key[0]) catch return Key.unknown; if (key.len <= len) return unicode.utf8Decode(key[0..len]) catch return Key.unknown; return Key.unknown; } pub fn readKey(stdin: fs.File) !Key.Type { var buf: [10]u8 = undefined; var len: usize = 0; while (len == 0) len = try stdin.read(&buf); return parseKey(buf[0..len]); }
src/input.zig
const std = @import("std"); const vk = @import("vk"); const endian = std.builtin.endian; pub const CC = std.builtin.CallingConvention.C; pub const IntBool = c_int; pub const Point = struct { x: i32, y: i32 }; pub const FPoint = struct { x: f32, y: f32 }; pub const Rect = struct { x: i32, y: i32, w: i32, h: i32 }; pub const FRect = struct { x: f32, y: f32, w: f32, h: f32 }; pub const RWops = extern struct { pub const Whence = extern enum(c_int) { seek_set = 0, seek_cur = 1, seek_end = 2, _, }; sizeFn: ?fn(context: *RWops) callconv(CC) i64, seekFn: ?fn(context: *RWops, offset: i64, whence: Whence) callconv(CC) i64, readFn: ?fn(context: *RWops, ptr: *c_void, size: usize, maxnum: usize) callconv(CC) usize, writeFn: ?fn(context: *RWops, ptr: *c_void, size: usize, num: usize) callconv(CC) usize, closeFn: ?fn(context: *RWops) callconv(CC) i32, type: extern enum(u32) { unknown, winfile, stdfile, jnifile, memory, memory_readonly, }, hidden: extern union { androidio: extern struct { asset: ?*c_void, }, windowsio: ( if (std.builtin.os.tag == .windows) extern struct { append: IntBool, h: ?*c_void, buffer: extern struct { data: ?*c_void, size: usize, left: usize, }, } else extern struct {} ), stdio: extern struct { autoclose: IntBool, fp: ?*c_void, // FILE* }, mem: extern struct { base: [*]u8, here: [*]u8, stop: [*]u8, }, unknown: extern struct { data1: ?*c_void, data2: ?*c_void, }, }, }; pub const audio = struct { pub const Format = packed struct { bit_size: u8 align(2), is_float: bool, __pad0: u3 = 0, is_big_endian: bool, __pad1: u2 = 0, is_signed: bool, pub const U8: Format = .{ .bit_size = 8, .is_float = false, .is_big_endian = false, .is_signed = false }; pub const S8: Format = .{ .bit_size = 8, .is_float = false, .is_big_endian = false, .is_signed = true }; pub const U16LSB: Format = .{ .bit_size = 16, .is_float = false, .is_big_endian = false, .is_signed = false }; pub const S16LSB: Format = .{ .bit_size = 16, .is_float = false, .is_big_endian = false, .is_signed = true }; pub const U16MSB: Format = .{ .bit_size = 16, .is_float = false, .is_big_endian = true, .is_signed = false }; pub const S16MSB: Format = .{ .bit_size = 16, .is_float = false, .is_big_endian = true, .is_signed = true }; pub const U16 = U16LSB; pub const S16 = S16LSB; pub const S32LSB: Format = .{ .bit_size = 32, .is_float = false, .is_big_endian = false, .is_signed = true }; pub const S32MSB: Format = .{ .bit_size = 32, .is_float = false, .is_big_endian = true, .is_signed = true }; pub const S32 = S32LSB; pub const F32LSB: Format = .{ .bit_size = 32, .is_float = true, .is_big_endian = false, .is_signed = true }; pub const F32MSB: Format = .{ .bit_size = 32, .is_float = true, .is_big_endian = true, .is_signed = true }; pub const F32 = F32LSB; pub const U16SYS = if (endian == .Little) U16LSB else U16MSB; pub const S16SYS = if (endian == .Little) S16LSB else S16MSB; pub const S32SYS = if (endian == .Little) S32LSB else S32MSB; pub const F32SYS = if (endian == .Little) F32LSB else F32MSB; pub fn toInt(self: Format) FormatInt { return @bitCast(FormatInt, self); } pub fn fromInt(int: FormatInt) Format { return @bitCast(Format, int); } }; pub const FormatInt = u16; pub const AllowChangeFlags = packed struct { frequency: bool align(4) = false, format: bool = false, channels: bool = false, samples: bool = false, __pad0: u28 = 9, }; pub const Callback = fn(user_data: ?*c_void, stream: [*]u8, len: c_int) callconv(CC) void; pub const Spec = extern struct { freq: i32, format: Format, channels: u8, silence: u8 = 0, samples: u16, padding: u16 = 0, size: u32 = 0, callback: ?Callback = null, user_data: ?*c_void = null, }; pub const Filter = fn(cvt: ?*CVT, format: u16) callconv(CC) void; pub const CVT_MAX_FILTERS = 9; pub const CVT = extern struct { needed: i32, src_format: Format, dst_format: Format, rate_incr: f64 align(4), buf: ?[*]u8 align(4), len: i32, len_cvt: i32, len_mult: i32, len_ratio: f64 align(4), filters: [CVT_MAX_FILTERS + 1]?Filter align(4), filter_index: i32, }; pub const DeviceID = extern enum(u32) { invalid = 0, default = 1, _, }; pub const Status = extern enum (i32) { stopped, playing, paused, _, }; pub const Stream = opaque{}; pub const MIX_MAXVOLUME = 128; }; // TODO: make this an enum pub const PixelFormatEnum = packed struct { const Self = @This(); pub const unknown = fromInt(0); pub const index_1_lsb = init(.index_1, .@"4321", .none, 1, 0); pub const index_1_msb = init(.index_1, .@"1234", .none, 1, 0); pub const index_4_lsb = init(.index_4, .@"4321", .none, 4, 0); pub const index_4_msb = init(.index_4, .@"1234", .none, 4, 0); pub const index_8 = init(.index_8, .none, .none, 8, 1); pub const rgb332 = init(.packed_8, .xrgb, .@"332", 8, 1); pub const xrgb4444 = init(.packed_16, .xrgb, .@"4444", 12, 2); pub const xbgr4444 = init(.packed_16, .xbgr, .@"4444", 12, 2); pub const xrgb1555 = init(.packed_16, .xrgb, .@"1555", 15, 2); pub const xbgr1555 = init(.packed_16, .xbgr, .@"1555", 15, 2); pub const rgb444 = xrgb4444; pub const bgr444 = xbgr4444; pub const rgb555 = xrgb1555; pub const bgr555 = xbgr1555; pub const argb4444 = init(.packed_16, .argb, .@"4444", 16, 2); pub const rgba4444 = init(.packed_16, .rgba, .@"4444", 16, 2); pub const abgr4444 = init(.packed_16, .abgr, .@"4444", 16, 2); pub const bgra4444 = init(.packed_16, .bgra, .@"4444", 16, 2); pub const argb1555 = init(.packed_16, .argb, .@"1555", 16, 2); pub const rgba5551 = init(.packed_16, .rgba, .@"5551", 16, 2); pub const abgr1555 = init(.packed_16, .abgr, .@"1555", 16, 2); pub const bgra5551 = init(.packed_16, .bgra, .@"5551", 16, 2); pub const rgb565 = init(.packed_16, .xrgb, .@"565", 16, 2); pub const bgr565 = init(.packed_16, .xbgr, .@"565", 16, 2); pub const rgb24 = init(.array_u8, .rgb, .none, 24, 3); pub const bgr24 = init(.array_u8, .bgr, .none, 24, 3); pub const xrgb8888 = init(.packed_32, .xrgb, .@"8888", 24, 4); pub const rgbx8888 = init(.packed_32, .rgbx, .@"8888", 24, 4); pub const xbgr8888 = init(.packed_32, .xbgr, .@"8888", 24, 4); pub const bgrx8888 = init(.packed_32, .bgrx, .@"8888", 24, 4); pub const rgb888 = xrgb8888; pub const bgr888 = xbgr8888; pub const argb8888 = init(.packed_32, .argb, .@"8888", 32, 4); pub const rgba8888 = init(.packed_32, .rgba, .@"8888", 32, 4); pub const abgr8888 = init(.packed_32, .abgr, .@"8888", 32, 4); pub const bgra8888 = init(.packed_32, .bgra, .@"8888", 32, 4); pub const argb2101010 = init(.packed_32, .argb, .@"2101010", 32, 4); pub const rgba32 = if (endian == .Little) abgr8888 else rgba8888; pub const argb32 = if (endian == .Little) bgra8888 else argb8888; pub const bgra32 = if (endian == .Little) argb8888 else bgra8888; pub const abgr32 = if (endian == .Little) rgba8888 else abgr8888; pub const YV12 = fourcc("YV12"); pub const IYUV = fourcc("IYUV"); pub const YUY2 = fourcc("YUY2"); pub const UYVY = fourcc("UYVY"); pub const YVYU = fourcc("YVYU"); pub const NV12 = fourcc("NV12"); pub const NV21 = fourcc("NV21"); pub const external_oes = fourcc("OES "); pub fn isFourCC(self: Self) bool { return (self.toInt() != 0 and self._is_raw != 1); } pub fn bitsPerPixel(self: Self) u8 { return self._bits; } pub fn bytesPerPixel(self: Self) u8 { if (self.isFourCC()) { return if ( self.equals(YUY2) or self.equals(UYVY) or self.equals(YVYU) ) 2 else 1; } else { return self._bytes; } } pub fn isIndexed(self: Self) bool { return !self.isFourCC() and self._type.isIndexedType(); } pub fn isPacked(self: Self) bool { return !self.isFourCC() and self._type.isPackedType(); } pub fn isArray(self: Self) bool { return !self.isFourCC() and self._type.isArrayType(); } pub fn isAlpha(self: Self) bool { if (self.isPacked()) { const fmt = @intToEnum(PackedOrder, self._order); return fmt == .argb or fmt == .rgba or fmt == .abgr or fmt == .bgra; } else if (self.isArray()) { const fmt = @intToEnum(ArrayOrder, self._order); return fmt == .argb or fmt == .rgba or fmt == .abgr or fmt == .bgra; } return false; } _bytes: u8 align(4), _bits: u8, _layout: PackedLayout, _order: u4, // BitmapOrder, PackedOrder, or ArrayOrder, depending on _type. _type: Type, _is_raw: u4 = 1, pub const Type = enum (u4) { unknown, index_1, index_4, index_8, packed_8, packed_16, packed_32, array_u8, array_u16, array_u32, array_f16, array_f32, _, pub fn isIndexedType(self: Type) bool { return self == .index_1 or self == .index_4 or self == .index_8; } pub fn isPackedType(self: Type) bool { return self == .packed_8 or self == .packed_16 or self == .packed_32; } pub fn isArrayType(self: Type) bool { return self == .array_u8 or self == .array_u16 or self == .array_u32 or self == .array_f16 or self == .array_f32; } }; pub const BitmapOrder = enum (u4) { none, @"4321", @"1234", _, }; pub const PackedOrder = enum (u4) { none, xrgb, rgbx, argb, rgba, xbgr, bgrx, abgr, bgra, _, }; pub const ArrayOrder = enum (u4) { none, rgb, rgba, argb, bgr, bgra, abgr, _, }; pub fn OrderOf(comptime _type: Type) type { if (_type.isBitmapType()) return BitmapOrder; if (_type.isPackedType()) return PackedOrder; if (_type.isArrayType()) return ArrayOrder; @compileError("No known order type for format type "++@tagName(_type)); } pub const PackedLayout = enum (u4) { none, @"332", @"4444", @"1555", @"5551", @"565", @"8888", @"2101010", @"1010102", _, }; pub const Int = u32; pub fn fromInt(int: Int) @This() { return @bitCast(@This(), int); } pub fn toInt(fmt: @This()) Int { return @bitCast(Int, fmt); } pub fn fourcc(str: *const [4]u8) Self { return fromInt(std.mem.readIntLittle(u32, str)); } pub fn init( comptime _type: Type, order: OrderOf(_type), layout: PackedLayout, bits: u8, bytes: u8 ) Self { return .{ ._bytes = bytes, ._bits = bits, ._layout = layout, ._order = @enumToInt(order), ._type = type, }; } pub fn equals(self: @This(), other: @This()) bool { return self.toInt() == other.toInt(); } }; pub const Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; pub const Colour = Color; pub const Palette = extern struct { ncolors: i32, colors: ?[*]Color, version: u32, refcount: i32, }; pub const PixelFormat = extern struct { format: PixelFormatEnum, palette: ?*Palette, bitsPerPixel: u8, bytesPerPixel: u8, padding: u16 = 0, rMask: u32, gMask: u32, bMask: u32, aMask: u32, rLoss: u8, gLoss: u8, bLoss: u8, aLoss: u8, rShift: u8, gShift: u8, bShift: u8, aShift: u8, refcount: i32, next: ?*const @This(), }; pub const Window = opaque{ pub const Flags = packed struct { fullscreen: bool align(4) = false, opengl: bool = false, shown: bool = false, hidden: bool = false, borderless: bool = false, resizable: bool = false, minimized: bool = false, maximized: bool = false, input_grabbed: bool = false, input_focus: bool = false, mouse_focus: bool = false, foreign: bool = false, desktop: bool = false, // use with fullscreen for fullscreen desktop allow_highdpi: bool = false, mouse_capture: bool = false, always_on_top: bool = false, skip_taskbar: bool = false, utility: bool = false, tooltip: bool = false, popup_menu: bool = false, __pad0: u4 = 0, __pad1: u4 = 0, vulkan: bool = false, metal: bool = false, __pad2: u2 = 0, pub fn fromInt(int: Int) @This() { return @bitCast(@This(), int); } pub fn toInt(flags: @This()) Int { return @bitCast(Int, flags); } pub const Int = u32; }; pub const pos_undefined = posUndefinedDisplay(0); pub const pos_undefined_mask = 0x1fff_0000; pub fn posUndefinedDisplay(x: i32) i32 { return pos_undefined_mask | x; } pub fn posIsUndefined(p: i32) bool { return @bitCast(u32, p) & 0xFFFF_0000 == pos_undefined_mask; } pub const pos_centered = posCenteredDisplay(0); pub const pos_centered_mask = 0x2FFF_0000; pub fn posCenteredDisplay(x: i32) i32 { return pos_centered_mask | x; } pub fn posIsCentered(p: i32) bool { return @bitCast(u32, p) & 0xFFFF_0000 == pos_centered_mask; } pub const HitTestResult = extern enum { normal, draggable, resize_topleft, resize_top, resize_topright, resize_right, resize_bottomright, resize_bottom, resize_bottomleft, resize_left, _, }; pub const HitTest = fn( win: *Window, area: ?*const Point, data: ?*c_void ) callconv(CC) HitTestResult; pub fn create(title: ?[*:0]const u8, x: i32, y: i32, w: i32, h: i32, flags: Flags) callconv(.Inline) !*Window { return raw.SDL_CreateWindow(title, x, y, w, h, flags.toInt()) orelse error.SDL_ERROR; } pub fn createFrom(data: ?*c_void) callconv(.Inline) !*Window { return raw.SDL_CreateWindowFrom(data) orelse error.SDL_ERROR; } pub const getFromID = raw.SDL_GetWindowFromID; pub const getGrabbed = raw.SDL_GetGrabbedWindow; pub const destroy = raw.SDL_DestroyWindow; pub fn getDisplayIndex(window: *Window) callconv(.Inline) !u32 { const index = raw.SDL_GetWindowDisplayIndex(window); if (index < 0) return error.SDL_ERROR; return @intCast(u32, index); } pub fn setDisplayMode(window: *Window, mode: video.DisplayMode) callconv(.Inline) !void { const rc = raw.SDL_SetWindowDisplayMode(window, &mode); if (rc < 0) return error.SDL_ERROR; } pub fn getDisplayMode(window: *Window) callconv(.Inline) !video.DisplayMode { var mode: video.DisplayMode = undefined; const rc = raw.SDL_GetWindowDisplayMode(window, &mode); if (rc < 0) return error.SDL_ERROR; return mode; } pub fn getPixelFormat(window: *Window) callconv(.Inline) !PixelFormatEnum { const int = raw.SDL_GetWindowPixelFormat(window); if (int == 0) return error.SDL_ERROR; return PixelFormatEnum.fromInt(int); } pub const getID = raw.SDL_GetWindowID; pub fn getFlags(window: *Window) callconv(.Inline) Flags { return Flags.fromInt(raw.SDL_GetWindowFlags(window)); } pub const setTitle = raw.SDL_SetWindowTitle; pub const getTitle = raw.SDL_GetWindowTitle; pub const setIcon = raw.SDL_SetWindowIcon; pub const setData = raw.SDL_SetWindowData; pub const getData = raw.SDL_GetWindowData; pub const setPosition = raw.SDL_SetWindowPosition; pub fn getPosition(window: *Window) callconv(.Inline) Point { var p: Point = undefined; raw.SDL_GetWindowPosition(window, &p.x, &p.y); return p; } pub const setSize = raw.SDL_SetWindowSize; pub fn getSize(window: *Window) callconv(.Inline) Point { var p: Point = undefined; raw.SDL_GetWindowSize(window, &p.x, &p.y); return p; } pub const Borders = struct { top: i32, left: i32, bottom: i32, right: i32 }; pub fn getBordersSize(window: *Window) callconv(.Inline) !Borders { var b: Borders = undefined; const rc = raw.SDL_GetWindowBordersSize(window, &b.top, &b.left, &b.bottom, &b.right); if (rc < 0) return error.SDL_ERROR; return b; } pub const setMinimumSize = raw.SDL_SetWindowMinimumSize; pub fn getMinimumSize(window: *Window) callconv(.Inline) Point { var p: Point = undefined; raw.SDL_GetWindowMinimumSize(window, &p.x, &p.y); return p; } pub const setMaximumSize = raw.SDL_SetWindowMaximumSize; pub fn getMaximumSize(window: *Window) callconv(.Inline) Point { var p: Point = undefined; raw.SDL_GetWindowMaximumSize(window, &p.x, &p.y); return p; } pub fn setBordered(window: *Window, bordered: bool) callconv(.Inline) void { raw.SDL_SetWindowBordered(window, @boolToInt(bordered)); } pub fn setResizable(window: *Window, resizable: bool) callconv(.Inline) void { raw.SDL_SetWindowResizable(window, @boolToInt(resizable)); } pub const show = raw.SDL_ShowWindow; pub const hide = raw.SDL_HideWindow; pub const raise = raw.SDL_RaiseWindow; pub const maximize = raw.SDL_MaximizeWindow; pub const minimize = raw.SDL_MinimizeWindow; pub const restore = raw.SDL_RestoreWindow; pub fn setFullscreen(window: *Window, flags: Flags) callconv(.Inline) !void { const rc = raw.SDL_SetWindowFullscreen(window, flags.toInt()); if (rc < 0) return error.SDL_ERROR; } pub fn getSurface(window: *Window) callconv(.Inline) !*Surface { return raw.SDL_GetWindowSurface(window) orelse error.SDL_ERROR; } pub fn updateSurface(window: *Window) callconv(.Inline) !void { const rc = raw.SDL_UpdateWindowSurface(window); if (rc < 0) return error.SDL_ERROR; } pub fn updateSurfaceRects(window: *Window, rects: []const Rect) callconv(.Inline) !void { const rc = raw.SDL_UpdateWindowSurfaceRects(window, rects.ptr, @intCast(i32, rects.len)); if (rc < 0) return error.SDL_ERROR; } pub fn setGrab(window: *Window, grabbed: bool) callconv(.Inline) void { raw.SDL_SetWindowGrab(window, @boolToInt(grabbed)); } pub fn getGrab(window: *Window) callconv(.Inline) bool { return raw.SDL_GetWindowGrab(window) != 0; } pub fn setBrightness(window: *Window, brightness: f32) callconv(.Inline) !void { const rc = raw.SDL_SetWindowBrightness(window, brightness); if (rc < 0) return error.SDL_ERROR; } pub const getBrightness = raw.SDL_GetWindowBrightness; pub fn setOpacity(window: *Window, opacity: f32) callconv(.Inline) !void { const rc = raw.SDL_SetWindowOpacity(window, opacity); if (rc < 0) return error.SDL_ERROR; } pub fn getOpacity(window: *Window) callconv(.Inline) !f32 { var opacity: f32 = undefined; const rc = raw.SDL_GetWindowOpacity(window, &opacity); if (rc < 0) return error.SDL_ERROR; return opacity; } pub fn setModalFor(modal_window: *Window, parent_window: *Window) callconv(.Inline) !void { const rc = raw.SDL_SetWindowModalFor(modal_window, parent_window); if (rc < 0) return error.SDL_ERROR; } pub fn setInputFocus(window: *Window) callconv(.Inline) !void { const rc = raw.SDL_SetWindowInputFocus(window); if (rc < 0) return error.SDL_ERROR; } pub fn setGammaRamp(window: *Window, red: ?*const [256]u16, green: ?*const [256]u16, blue: ?*const [256]u16) callconv(.Inline) !void { const rc = raw.SDL_SetWindowGammaRamp(window, red, green, blue); if (rc < 0) return error.SDL_ERROR; } pub fn getGammaRamp(window: *Window, red: ?*[256]u16, green: ?*[256]u16, blue: ?*[256]u16) callconv(.Inline) !void { const rc = raw.SDL_GetWindowGammaRamp(window, red, green, blue); if (rc < 0) return error.SDL_ERROR; } pub fn setHitTest( window: *Window, comptime DataPtrT: type, comptime callback: fn(win: *Window, area: ?*const Point, data: DataPtrT) HitTestResult, callback_data: DataPtrT ) callconv(.Inline) !void { comptime var ptr_info = @typeInfo(DataPtrT); if (ptr_info == .Optional) { ptr_info = @typeInfo(ptr_info.child); } if (ptr_info != .Pointer or ptr_info.Pointer.size == .Slice) { @compileError("DataPtrT must be a pointer type, but is "++@typeName(DataPtrT)); } if (@sizeOf(DataPtrT) != @sizeOf(?*c_void)) { @compileError("DataPtrT must be a real pointer, but is "++@typeName(DataPtrT)); } const gen = struct { fn hitTestCallback(win: *Window, area: ?*const Point, data: ?*c_void) callconv(CC) HitTestResult { const ptr = @intToPtr(DataPtrT, @ptrToInt(data)); return callback(win, area, ptr); } }; const erased = @intToPtr(?*c_void, @ptrToInt(data)); const rc = raw.SDL_SetWindowHitTest(window, gen.hitTestCallback, erased); if (rc < 0) return error.SDL_ERROR; } }; pub const video = struct { pub const DisplayMode = extern struct { format: PixelFormatEnum, w: i32, h: i32, refresh_rate: i32 = 0, driverdata: ?*c_void = null, }; pub const WindowEvent = extern enum { none, shown, hidden, exposed, moved, resized, size_changed, minimized, maximized, restored, enter, leave, focus_gained, focus_lost, close, take_focus, hit_test, _, }; pub const DisplayEvent = extern enum { none, orientation, connected, disconnected, _, }; pub const DisplayOrientation = extern enum { unknown, landscape, landscape_flipped, portrait, portrait_flipped, _, }; }; pub const gl = struct { pub const Context = *opaque{}; pub const Attr = extern enum { RED_SIZE, GREEN_SIZE, BLUE_SIZE, ALPHA_SIZE, BUFFER_SIZE, DOUBLEBUFFER, DEPTH_SIZE, STENCIL_SIZE, ACCUM_RED_SIZE, ACCUM_GREEN_SIZE, ACCUM_BLUE_SIZE, ACCUM_ALPHA_SIZE, STEREO, MULTISAMPLEBUFFERS, MULTISAMPLESAMPLES, ACCELERATED_VISUAL, RETAINED_BACKING, CONTEXT_MAJOR_VERSION, CONTEXT_MINOR_VERSION, CONTEXT_EGL, CONTEXT_FLAGS, CONTEXT_PROFILE_MASK, SHARE_WITH_CURRENT_CONTEXT, FRAMEBUFFER_SRGB_CAPABLE, CONTEXT_RELEASE_BEHAVIOR, CONTEXT_RESET_NOTIFICATION, CONTEXT_NO_ERROR, _, }; pub const Profile = packed struct { core: bool align(2) = false, compatibility: bool = false, es: bool = false, __pad0: u13 = 0, }; pub const ContextFlags = packed struct { debug: bool align(2) = false, forward_compatible: bool = false, robust_access: bool = false, reset_isolation: bool = false, __pad0: u12 = 0, }; pub const ContextReleaseFlags = packed struct { flush: bool = false, __pad0: u15 = 0, }; pub const ContextResetNotification = packed struct { lose_context: bool = false, __pad0: u15 = 0, }; pub const SwapInterval = extern enum (c_int) { late_swaps = -1, vsync_off = 0, vsync_on = 1, _, }; }; pub const Scancode = extern enum (c_int) { UNKNOWN = 0, A = 4, B = 5, C = 6, D = 7, E = 8, F = 9, G = 10, H = 11, I = 12, J = 13, K = 14, L = 15, M = 16, N = 17, O = 18, P = 19, Q = 20, R = 21, S = 22, T = 23, U = 24, V = 25, W = 26, X = 27, Y = 28, Z = 29, @"1" = 30, @"2" = 31, @"3" = 32, @"4" = 33, @"5" = 34, @"6" = 35, @"7" = 36, @"8" = 37, @"9" = 38, @"0" = 39, RETURN = 40, ESCAPE = 41, BACKSPACE = 42, TAB = 43, SPACE = 44, MINUS = 45, EQUALS = 46, LEFTBRACKET = 47, RIGHTBRACKET = 48, BACKSLASH = 49, NONUSHASH = 50, SEMICOLON = 51, APOSTROPHE = 52, GRAVE = 53, COMMA = 54, PERIOD = 55, SLASH = 56, CAPSLOCK = 57, F1 = 58, F2 = 59, F3 = 60, F4 = 61, F5 = 62, F6 = 63, F7 = 64, F8 = 65, F9 = 66, F10 = 67, F11 = 68, F12 = 69, PRINTSCREEN = 70, SCROLLLOCK = 71, PAUSE = 72, INSERT = 73, HOME = 74, PAGEUP = 75, DELETE = 76, END = 77, PAGEDOWN = 78, RIGHT = 79, LEFT = 80, DOWN = 81, UP = 82, NUMLOCKCLEAR = 83, KP_DIVIDE = 84, KP_MULTIPLY = 85, KP_MINUS = 86, KP_PLUS = 87, KP_ENTER = 88, KP_1 = 89, KP_2 = 90, KP_3 = 91, KP_4 = 92, KP_5 = 93, KP_6 = 94, KP_7 = 95, KP_8 = 96, KP_9 = 97, KP_0 = 98, KP_PERIOD = 99, NONUSBACKSLASH = 100, APPLICATION = 101, POWER = 102, KP_EQUALS = 103, F13 = 104, F14 = 105, F15 = 106, F16 = 107, F17 = 108, F18 = 109, F19 = 110, F20 = 111, F21 = 112, F22 = 113, F23 = 114, F24 = 115, EXECUTE = 116, HELP = 117, MENU = 118, SELECT = 119, STOP = 120, AGAIN = 121, UNDO = 122, CUT = 123, COPY = 124, PASTE = 125, FIND = 126, MUTE = 127, VOLUMEUP = 128, VOLUMEDOWN = 129, KP_COMMA = 133, KP_EQUALSAS400 = 134, INTERNATIONAL1 = 135, INTERNATIONAL2 = 136, INTERNATIONAL3 = 137, INTERNATIONAL4 = 138, INTERNATIONAL5 = 139, INTERNATIONAL6 = 140, INTERNATIONAL7 = 141, INTERNATIONAL8 = 142, INTERNATIONAL9 = 143, LANG1 = 144, LANG2 = 145, LANG3 = 146, LANG4 = 147, LANG5 = 148, LANG6 = 149, LANG7 = 150, LANG8 = 151, LANG9 = 152, ALTERASE = 153, SYSREQ = 154, CANCEL = 155, CLEAR = 156, PRIOR = 157, RETURN2 = 158, SEPARATOR = 159, OUT = 160, OPER = 161, CLEARAGAIN = 162, CRSEL = 163, EXSEL = 164, KP_00 = 176, KP_000 = 177, THOUSANDSSEPARATOR = 178, DECIMALSEPARATOR = 179, CURRENCYUNIT = 180, CURRENCYSUBUNIT = 181, KP_LEFTPAREN = 182, KP_RIGHTPAREN = 183, KP_LEFTBRACE = 184, KP_RIGHTBRACE = 185, KP_TAB = 186, KP_BACKSPACE = 187, KP_A = 188, KP_B = 189, KP_C = 190, KP_D = 191, KP_E = 192, KP_F = 193, KP_XOR = 194, KP_POWER = 195, KP_PERCENT = 196, KP_LESS = 197, KP_GREATER = 198, KP_AMPERSAND = 199, KP_DBLAMPERSAND = 200, KP_VERTICALBAR = 201, KP_DBLVERTICALBAR = 202, KP_COLON = 203, KP_HASH = 204, KP_SPACE = 205, KP_AT = 206, KP_EXCLAM = 207, KP_MEMSTORE = 208, KP_MEMRECALL = 209, KP_MEMCLEAR = 210, KP_MEMADD = 211, KP_MEMSUBTRACT = 212, KP_MEMMULTIPLY = 213, KP_MEMDIVIDE = 214, KP_PLUSMINUS = 215, KP_CLEAR = 216, KP_CLEARENTRY = 217, KP_BINARY = 218, KP_OCTAL = 219, KP_DECIMAL = 220, KP_HEXADECIMAL = 221, LCTRL = 224, LSHIFT = 225, LALT = 226, LGUI = 227, RCTRL = 228, RSHIFT = 229, RALT = 230, RGUI = 231, MODE = 257, AUDIONEXT = 258, AUDIOPREV = 259, AUDIOSTOP = 260, AUDIOPLAY = 261, AUDIOMUTE = 262, MEDIASELECT = 263, WWW = 264, MAIL = 265, CALCULATOR = 266, COMPUTER = 267, AC_SEARCH = 268, AC_HOME = 269, AC_BACK = 270, AC_FORWARD = 271, AC_STOP = 272, AC_REFRESH = 273, AC_BOOKMARKS = 274, BRIGHTNESSDOWN = 275, BRIGHTNESSUP = 276, DISPLAYSWITCH = 277, KBDILLUMTOGGLE = 278, KBDILLUMDOWN = 279, KBDILLUMUP = 280, EJECT = 281, SLEEP = 282, APP1 = 283, APP2 = 284, AUDIOREWIND = 285, AUDIOFASTFORWARD = 286, NUM_SCANCODES = 512, _, }; pub const Keycode = extern enum (i32) { UNKNOWN = 0, RETURN = '\r', ESCAPE = '\x1b', BACKSPACE = '\x08', TAB = '\t', SPACE = ' ', EXCLAIM = '!', QUOTEDBL = '"', HASH = '#', PERCENT = '%', DOLLAR = '$', AMPERSAND = '&', QUOTE = '\'', LEFTPAREN = '(', RIGHTPAREN = ')', ASTERISK = '*', PLUS = '+', COMMA = ',', MINUS = '-', PERIOD = '.', SLASH = '/', @"0" = '0', @"1" = '1', @"2" = '2', @"3" = '3', @"4" = '4', @"5" = '5', @"6" = '6', @"7" = '7', @"8" = '8', @"9" = '9', COLON = ':', SEMICOLON = ';', LESS = '<', EQUALS = '=', GREATER = '>', QUESTION = '?', AT = '@', LEFTBRACKET = '[', BACKSLASH = '\\', RIGHTBRACKET = ']', CARET = '^', UNDERSCORE = '_', BACKQUOTE = '`', a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j', k = 'k', l = 'l', m = 'm', n = 'n', o = 'o', p = 'p', q = 'q', r = 'r', s = 's', t = 't', u = 'u', v = 'v', w = 'w', x = 'x', y = 'y', z = 'z', CAPSLOCK = intValueFromScancode(.CAPSLOCK), F1 = intValueFromScancode(.F1), F2 = intValueFromScancode(.F2), F3 = intValueFromScancode(.F3), F4 = intValueFromScancode(.F4), F5 = intValueFromScancode(.F5), F6 = intValueFromScancode(.F6), F7 = intValueFromScancode(.F7), F8 = intValueFromScancode(.F8), F9 = intValueFromScancode(.F9), F10 = intValueFromScancode(.F10), F11 = intValueFromScancode(.F11), F12 = intValueFromScancode(.F12), PRINTSCREEN = intValueFromScancode(.PRINTSCREEN), SCROLLLOCK = intValueFromScancode(.SCROLLLOCK), PAUSE = intValueFromScancode(.PAUSE), INSERT = intValueFromScancode(.INSERT), HOME = intValueFromScancode(.HOME), PAGEUP = intValueFromScancode(.PAGEUP), DELETE = '\x7f', END = intValueFromScancode(.END), PAGEDOWN = intValueFromScancode(.PAGEDOWN), RIGHT = intValueFromScancode(.RIGHT), LEFT = intValueFromScancode(.LEFT), DOWN = intValueFromScancode(.DOWN), UP = intValueFromScancode(.UP), NUMLOCKCLEAR = intValueFromScancode(.NUMLOCKCLEAR), KP_DIVIDE = intValueFromScancode(.KP_DIVIDE), KP_MULTIPLY = intValueFromScancode(.KP_MULTIPLY), KP_MINUS = intValueFromScancode(.KP_MINUS), KP_PLUS = intValueFromScancode(.KP_PLUS), KP_ENTER = intValueFromScancode(.KP_ENTER), KP_1 = intValueFromScancode(.KP_1), KP_2 = intValueFromScancode(.KP_2), KP_3 = intValueFromScancode(.KP_3), KP_4 = intValueFromScancode(.KP_4), KP_5 = intValueFromScancode(.KP_5), KP_6 = intValueFromScancode(.KP_6), KP_7 = intValueFromScancode(.KP_7), KP_8 = intValueFromScancode(.KP_8), KP_9 = intValueFromScancode(.KP_9), KP_0 = intValueFromScancode(.KP_0), KP_PERIOD = intValueFromScancode(.KP_PERIOD), APPLICATION = intValueFromScancode(.APPLICATION), POWER = intValueFromScancode(.POWER), KP_EQUALS = intValueFromScancode(.KP_EQUALS), F13 = intValueFromScancode(.F13), F14 = intValueFromScancode(.F14), F15 = intValueFromScancode(.F15), F16 = intValueFromScancode(.F16), F17 = intValueFromScancode(.F17), F18 = intValueFromScancode(.F18), F19 = intValueFromScancode(.F19), F20 = intValueFromScancode(.F20), F21 = intValueFromScancode(.F21), F22 = intValueFromScancode(.F22), F23 = intValueFromScancode(.F23), F24 = intValueFromScancode(.F24), EXECUTE = intValueFromScancode(.EXECUTE), HELP = intValueFromScancode(.HELP), MENU = intValueFromScancode(.MENU), SELECT = intValueFromScancode(.SELECT), STOP = intValueFromScancode(.STOP), AGAIN = intValueFromScancode(.AGAIN), UNDO = intValueFromScancode(.UNDO), CUT = intValueFromScancode(.CUT), COPY = intValueFromScancode(.COPY), PASTE = intValueFromScancode(.PASTE), FIND = intValueFromScancode(.FIND), MUTE = intValueFromScancode(.MUTE), VOLUMEUP = intValueFromScancode(.VOLUMEUP), VOLUMEDOWN = intValueFromScancode(.VOLUMEDOWN), KP_COMMA = intValueFromScancode(.KP_COMMA), KP_EQUALSAS400 = intValueFromScancode(.KP_EQUALSAS400), ALTERASE = intValueFromScancode(.ALTERASE), SYSREQ = intValueFromScancode(.SYSREQ), CANCEL = intValueFromScancode(.CANCEL), CLEAR = intValueFromScancode(.CLEAR), PRIOR = intValueFromScancode(.PRIOR), RETURN2 = intValueFromScancode(.RETURN2), SEPARATOR = intValueFromScancode(.SEPARATOR), OUT = intValueFromScancode(.OUT), OPER = intValueFromScancode(.OPER), CLEARAGAIN = intValueFromScancode(.CLEARAGAIN), CRSEL = intValueFromScancode(.CRSEL), EXSEL = intValueFromScancode(.EXSEL), KP_00 = intValueFromScancode(.KP_00), KP_000 = intValueFromScancode(.KP_000), THOUSANDSSEPARATOR = intValueFromScancode(.THOUSANDSSEPARATOR), DECIMALSEPARATOR = intValueFromScancode(.DECIMALSEPARATOR), CURRENCYUNIT = intValueFromScancode(.CURRENCYUNIT), CURRENCYSUBUNIT = intValueFromScancode(.CURRENCYSUBUNIT), KP_LEFTPAREN = intValueFromScancode(.KP_LEFTPAREN), KP_RIGHTPAREN = intValueFromScancode(.KP_RIGHTPAREN), KP_LEFTBRACE = intValueFromScancode(.KP_LEFTBRACE), KP_RIGHTBRACE = intValueFromScancode(.KP_RIGHTBRACE), KP_TAB = intValueFromScancode(.KP_TAB), KP_BACKSPACE = intValueFromScancode(.KP_BACKSPACE), KP_A = intValueFromScancode(.KP_A), KP_B = intValueFromScancode(.KP_B), KP_C = intValueFromScancode(.KP_C), KP_D = intValueFromScancode(.KP_D), KP_E = intValueFromScancode(.KP_E), KP_F = intValueFromScancode(.KP_F), KP_XOR = intValueFromScancode(.KP_XOR), KP_POWER = intValueFromScancode(.KP_POWER), KP_PERCENT = intValueFromScancode(.KP_PERCENT), KP_LESS = intValueFromScancode(.KP_LESS), KP_GREATER = intValueFromScancode(.KP_GREATER), KP_AMPERSAND = intValueFromScancode(.KP_AMPERSAND), KP_DBLAMPERSAND = intValueFromScancode(.KP_DBLAMPERSAND), KP_VERTICALBAR = intValueFromScancode(.KP_VERTICALBAR), KP_DBLVERTICALBAR = intValueFromScancode(.KP_DBLVERTICALBAR), KP_COLON = intValueFromScancode(.KP_COLON), KP_HASH = intValueFromScancode(.KP_HASH), KP_SPACE = intValueFromScancode(.KP_SPACE), KP_AT = intValueFromScancode(.KP_AT), KP_EXCLAM = intValueFromScancode(.KP_EXCLAM), KP_MEMSTORE = intValueFromScancode(.KP_MEMSTORE), KP_MEMRECALL = intValueFromScancode(.KP_MEMRECALL), KP_MEMCLEAR = intValueFromScancode(.KP_MEMCLEAR), KP_MEMADD = intValueFromScancode(.KP_MEMADD), KP_MEMSUBTRACT = intValueFromScancode(.KP_MEMSUBTRACT), KP_MEMMULTIPLY = intValueFromScancode(.KP_MEMMULTIPLY), KP_MEMDIVIDE = intValueFromScancode(.KP_MEMDIVIDE), KP_PLUSMINUS = intValueFromScancode(.KP_PLUSMINUS), KP_CLEAR = intValueFromScancode(.KP_CLEAR), KP_CLEARENTRY = intValueFromScancode(.KP_CLEARENTRY), KP_BINARY = intValueFromScancode(.KP_BINARY), KP_OCTAL = intValueFromScancode(.KP_OCTAL), KP_DECIMAL = intValueFromScancode(.KP_DECIMAL), KP_HEXADECIMAL = intValueFromScancode(.KP_HEXADECIMAL), LCTRL = intValueFromScancode(.LCTRL), LSHIFT = intValueFromScancode(.LSHIFT), LALT = intValueFromScancode(.LALT), LGUI = intValueFromScancode(.LGUI), RCTRL = intValueFromScancode(.RCTRL), RSHIFT = intValueFromScancode(.RSHIFT), RALT = intValueFromScancode(.RALT), RGUI = intValueFromScancode(.RGUI), MODE = intValueFromScancode(.MODE), AUDIONEXT = intValueFromScancode(.AUDIONEXT), AUDIOPREV = intValueFromScancode(.AUDIOPREV), AUDIOSTOP = intValueFromScancode(.AUDIOSTOP), AUDIOPLAY = intValueFromScancode(.AUDIOPLAY), AUDIOMUTE = intValueFromScancode(.AUDIOMUTE), MEDIASELECT = intValueFromScancode(.MEDIASELECT), WWW = intValueFromScancode(.WWW), MAIL = intValueFromScancode(.MAIL), CALCULATOR = intValueFromScancode(.CALCULATOR), COMPUTER = intValueFromScancode(.COMPUTER), AC_SEARCH = intValueFromScancode(.AC_SEARCH), AC_HOME = intValueFromScancode(.AC_HOME), AC_BACK = intValueFromScancode(.AC_BACK), AC_FORWARD = intValueFromScancode(.AC_FORWARD), AC_STOP = intValueFromScancode(.AC_STOP), AC_REFRESH = intValueFromScancode(.AC_REFRESH), AC_BOOKMARKS = intValueFromScancode(.AC_BOOKMARKS), BRIGHTNESSDOWN = intValueFromScancode(.BRIGHTNESSDOWN), BRIGHTNESSUP = intValueFromScancode(.BRIGHTNESSUP), DISPLAYSWITCH = intValueFromScancode(.DISPLAYSWITCH), KBDILLUMTOGGLE = intValueFromScancode(.KBDILLUMTOGGLE), KBDILLUMDOWN = intValueFromScancode(.KBDILLUMDOWN), KBDILLUMUP = intValueFromScancode(.KBDILLUMUP), EJECT = intValueFromScancode(.EJECT), SLEEP = intValueFromScancode(.SLEEP), APP1 = intValueFromScancode(.APP1), APP2 = intValueFromScancode(.APP2), AUDIOREWIND = intValueFromScancode(.AUDIOREWIND), AUDIOFASTFORWARD = intValueFromScancode(.AUDIOFASTFORWARD), pub fn intValueFromScancode(code: Scancode) i32 { return @intCast(i32, @enumToInt(code)) | (1<<30); } }; pub const Keymod = packed struct { lshift: bool align(2) = false, rshift: bool = false, __pad0: u4 = 0, lctrl: bool = false, rctrl: bool = false, lalt: bool = false, ralt: bool = false, lgui: bool = false, rgui: bool = false, num: bool = false, caps: bool = false, mode: bool = false, reserved: bool = false, pub fn ctrl(self: Keymod) bool { return self.lctrl or self.rctrl; } pub fn shift(self: Keymod) bool { return self.lshift or self.rshift; } pub fn alt(self: Keymod) bool { return self.lalt or self.ralt; } pub fn gui(self: Keymod) bool { return self.lgui or self.rgui; } pub fn fromInt(int: KeymodInt) Keymod { return @bitCast(Keymod, int); } pub fn toInt(self: Keymod) KeymodInt { return @bitCast(KeymodInt, self); } }; pub const KeymodInt = u16; pub const Keysym = extern struct { scancode: Scancode, sym: Keycode, mod: Keymod, unused: u32 = 0, }; pub const Joystick = opaque { pub const GUID = extern struct { data: [16]u8, }; pub const ID = extern enum(i32) { invalid = -1, _ }; pub const Type = extern enum { unknown, gamecontroller, wheel, arcade_stick, flight_stick, dance_pad, guitar, drum_kit, arcade_pad, throttle, }; pub const PowerLevel = extern enum { unknown = -1, empty, low, medium, full, wired, max, }; pub const IPHONE_MAX_GFORCE = 5.0; pub const AXIS_MAX = 32767; pub const AXIS_MIN = -32768; pub const Hat = extern enum (u8) { centered = 0, up = 1, right = 2, down = 4, left = 8, rightup = 3, rightdown = 6, leftup = 9, leftdown = 12, pub fn hasLeft(self: Hat) bool { return @enumToInt(self) & @enumToInt(Hat.left) != 0; } pub fn hasRight(self: Hat) bool { return @enumToInt(self) & @enumToInt(Hat.right) != 0; } pub fn hasUp(self: Hat) bool { return @enumToInt(self) & @enumToInt(Hat.up) != 0; } pub fn hasDown(self: Hat) bool { return @enumToInt(self) & @enumToInt(Hat.down) != 0; } }; }; pub const TouchID = extern enum(i64) { mouse = -1, _ }; pub const FingerID = extern enum(i64) { _ }; pub const TouchDeviceType = extern enum { invalid = -1, direct, indirect_absolute, indirect_relative, _, }; pub const Finger = struct { id: FingerID, x: f32, y: f32, pressure: f32, }; pub const TOUCH_MOUSEID = ~@as(u32, 0); pub const GestureID = extern enum(i64) { _ }; pub const Event = extern union { type: Type, common: CommonEvent, display: DisplayEvent, window: WindowEvent, key: KeyboardEvent, edit: TextEditingEvent, text: TextInputEvent, motion: MouseMotionEvent, button: MouseButtonEvent, wheel: MouseWheelEvent, jaxis: JoyAxisEvent, jball: JoyBallEvent, jhat: JoyHatEvent, jbutton: JoyButtonEvent, jdevice: JoyDeviceEvent, caxis: ControllerAxisEvent, cbutton: ControllerButtonEvent, cdevice: ControllerDeviceEvent, ctouchpad: ControllerTouchpadEvent, csensor: ControllerSensorEvent, adevice: AudioDeviceEvent, sensor: SensorEvent, quit: QuitEvent, user: UserEvent, syswm: SysWMEvent, tfinger: TouchFingerEvent, mgesture: MultiGestureEvent, dgesture: DollarGestureEvent, drop: DropEvent, padding: [56]u8, pub const Type = extern enum(u32) { FIRSTEVENT = 0, QUIT = 0x100, APP_TERMINATING, APP_LOWMEMORY, APP_WILLENTERBACKGROUND, APP_DIDENTERBACKGROUND, APP_WILLENTERFOREGROUND, APP_DIDENTERFOREGROUND, LOCALECHANGED, DISPLAYEVENT = 0x150, WINDOWEVENT = 0x200, SYSWMEVENT, KEYDOWN = 0x300, KEYUP, TEXTEDITING, TEXTINPUT, KEYMAPCHANGED, MOUSEMOTION = 0x400, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEWHEEL, JOYAXISMOTION = 0x600, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONDOWN, JOYBUTTONUP, JOYDEVICEADDED, JOYDEVICEREMOVED, CONTROLLERAXISMOTION = 0x650, CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP, CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, CONTROLLERDEVICEREMAPPED, CONTROLLERTOUCHPADDOWN, CONTROLLERTOUCHPADMOTION, CONTROLLERTOUCHPADUP, CONTROLLERSENSORUPDATE, FINGERDOWN = 0x700, FINGERUP, FINGERMOTION, DOLLARGESTURE = 0x800, DOLLARRECORD, MULTIGESTURE, CLIPBOARDUPDATE = 0x900, DROPFILE = 0x1000, DROPTEXT, DROPBEGIN, DROPCOMPLETE, AUDIODEVICEADDED = 0x1100, AUDIODEVICEREMOVED, SENSORUPDATE = 0x1200, RENDER_TARGETS_RESET = 0x2000, RENDER_DEVICE_RESET, USEREVENT = 0x8000, LASTEVENT = 0xFFFF, }; pub const CommonEvent = extern struct { type: Type, timestamp: u32, }; pub const DisplayEvent = extern struct { type: Type, timestamp: u32, display: u32, event: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, data1: i32, }; pub const WindowEvent = extern struct { type: Type, timestamp: u32, windowID: u32, event: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, data1: i32, data2: i32, }; pub const KeyboardEvent = extern struct { type: Type, timestamp: u32, windowID: u32, state: u8, repeat: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, keysym: Keysym, }; pub const TEXTEDITINGEVENT_TEXT_SIZE = 32; pub const TextEditingEvent = extern struct { type: Type, timestamp: u32, windowID: u32, text: [TEXTEDITINGEVENT_TEXT_SIZE]u8, start: i32, length: i32, }; pub const TEXTINPUTEVENT_TEXT_SIZE = 32; pub const TextInputEvent = extern struct { type: Type, timestamp: u32, windowID: u32, text: [TEXTINPUTEVENT_TEXT_SIZE]u8, }; pub const MouseMotionEvent = extern struct { type: Type, timestamp: u32, windowID: u32, which: u32, state: u32, x: i32, y: i32, xrel: i32, yrel: i32, }; pub const MouseButtonEvent = extern struct { type: Type, timestamp: u32, windowID: u32, which: u32, button: u8, state: u8, clicks: u8, padding1: u8 = 0, x: i32, y: i32, }; pub const MouseWheelEvent = extern struct { type: Type, timestamp: u32, windowID: u32, which: u32, x: i32, y: i32, direction: u32, }; pub const JoyAxisEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, axis: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, value: i16, padding4: u16 = 0, }; pub const JoyBallEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, ball: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, xrel: i16, yrel: i16, }; pub const JoyHatEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, hat: u8, value: Joystick.Hat, padding2: u8 = 0, padding3: u8 = 0, }; pub const JoyButtonEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, button: u8, state: u8, padding2: u8 = 0, padding3: u8 = 0, }; pub const JoyDeviceEvent = extern struct { type: Type, timestamp: u32, which: i32, }; pub const ControllerAxisEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, axis: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, value: i16, padding4: u16 = 0, }; pub const ControllerButtonEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, button: u8, state: u8, padding1: u8 = 0, padding2: u8 = 0, }; pub const ControllerDeviceEvent = extern struct { type: Type, timestamp: u32, which: i32, }; pub const ControllerTouchpadEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, touchpad: i32, finger: i32, x: f32, y: f32, pressure: f32, }; pub const ControllerSensorEvent = extern struct { type: Type, timestamp: u32, which: Joystick.ID, sensor: i32, data: [3]f32, }; pub const AudioDeviceEvent = extern struct { type: Type, timestamp: u32, which: u32, iscapture: u8, padding1: u8 = 0, padding2: u8 = 0, padding3: u8 = 0, }; pub const TouchFingerEvent = extern struct { type: Type, timestamp: u32, touchId: TouchID, fingerId: FingerID, x: f32, y: f32, dx: f32, dy: f32, pressure: f32, windowID: u32, }; pub const MultiGestureEvent = extern struct { type: Type, timestamp: u32, touchId: TouchID, dTheta: f32, dDist: f32, x: f32, y: f32, numFingers: u16, padding: u16 = 0, }; pub const DollarGestureEvent = extern struct { type: Type, timestamp: u32, touchId: TouchID, gestureId: GestureID, numFingers: u32, @"error": f32, x: f32, y: f32, }; pub const DropEvent = extern struct { type: Type, timestamp: u32, file: ?[*:0]u8, windowID: u32, }; pub const SensorEvent = extern struct { type: Type, timestamp: u32, which: i32, data: [6]f32, }; pub const QuitEvent = extern struct { type: Type, timestamp: u32, }; pub const OSEvent = extern struct { type: Type, timestamp: u32, }; pub const UserEvent = extern struct { type: Type, timestamp: u32, windowID: u32, code: i32, data1: ?*c_void, data2: ?*c_void, }; pub const SysWMEvent = extern struct { type: Type, timestamp: u32, msg: ?*SysWMmsg, pub const SysWMmsg = opaque{}; }; pub const Action = extern enum { add, peek, get, _, }; pub const State = extern enum { query = -1, ignore = 0, disable = 0, enable = 1, }; pub const Filter = fn(userdata: ?*c_void, event: *Event) callconv(CC) IntBool; comptime { if (@sizeOf(Event) != 56) @compileError("sdl.Event must be exactly 56 bytes"); } }; pub const vulkan = struct { pub fn loadLibrary(path: ?[*:0]const u8) callconv(.Inline) !void { const rc = raw.SDL_Vulkan_LoadLibrary(path); if (rc < 0) return error.SDL_ERROR; } pub const unloadLibrary = raw.SDL_Vulkan_UnloadLibrary; pub fn getVkGetInstanceProcAddr() callconv(.Inline) !@TypeOf(vk.vkGetInstanceProcAddr) { const ptr = raw.SDL_Vulkan_GetVkGetInstanceProcAddr(); if (ptr == null) return error.SDL_ERROR; return @ptrCast(@TypeOf(vk.vkGetInstanceProcAddr), ptr.?); } pub fn getInstanceExtensionsCount(window: *Window) !u32 { var count: u32 = 0; const rc = raw.SDL_Vulkan_GetInstanceExtensions(window, &count, null); if (rc == 0) return error.SDL_ERROR; return count; } pub fn getInstanceExtensions(window: *Window, buf: [][*:0]const u8) ![][*:0]const u8 { var count: u32 = @intCast(u32, buf.len); const rc = raw.SDL_Vulkan_GetInstanceExtensions(window, &count, buf.ptr); if (rc == 0) return error.SDL_ERROR; return buf[0..count]; } pub fn getInstanceExtensionsAlloc(window: *Window, allocator: *std.mem.Allocator) ![][*:0]const u8 { var count: u32 = @intCast(u32, buf.len); const rc = raw.SDL_Vulkan_GetInstanceExtensions(window, &count, buf.ptr); if (rc == 0) return error.SDL_ERROR; var buf = try allocator.alloc([*:0]const u8, count); errdefer allocator.free(buf); const rc = raw.SDL_Vulkan_GetInstanceExtensions(window, &count, buf.ptr); if (rc == 0) return error.SDL_ERROR; if (count < buf.len) { buf = allocator.shrink(buf, count); } return buf; } pub fn createSurface(window: *Window, instance: vk.Instance) callconv(.Inline) !vk.SurfaceKHR { var surface: vk.SurfaceKHR = undefined; const rc = raw.SDL_Vulkan_CreateSurface(window, instance, &surface); if (rc == 0) return error.SDL_ERROR; return surface; } pub fn getDrawableSize(window: *Window) callconv(.Inline) Point { var p: Point = undefined; raw.SDL_Vulkan_GetDrawableSize(window, &p.x, &p.y); return p; } }; pub const TimerID = extern enum (c_int) { invalid = 0, _ }; pub const TimerCallback = fn(interval: u32, param: ?*c_void) callconv(CC) u32; pub const getTicks = raw.SDL_GetTicks; pub const pumpEvents = raw.SDL_PumpEvents; pub fn peepEvents(buf: []Event, action: Event.Action, minType: Event.Type, maxType: Event.Type) callconv(.Inline) ![]Event { const rc = raw.SDL_PeepEvents(buf.ptr, @intCast(i32, buf.len), action, minType, maxType); if (rc < 0) return error.SDL_ERROR; return buf[0..@intCast(u32, rc)]; } pub fn hasEvent(@"type": Event.Type) callconv(.Inline) bool { return raw.SDL_HasEvent(@"type") != 0; } pub fn hasEvents(minType: Event.Type, maxType: Event.Type) callconv(.Inline) bool { return raw.SDL_HasEvents(minType, maxType) != 0; } pub const flushEvent = raw.SDL_FlushEvent; pub const flushEvents = raw.SDL_FlushEvents; pub fn pollEvent() callconv(.Inline) ?Event { var e: Event = undefined; const rc = raw.SDL_PollEvent(&e); if (rc <= 0) return null; return e; } pub fn waitEvent() callconv(.Inline) !Event { var e: Event = undefined; const rc = raw.SDL_WaitEvent(&e); if (rc <= 0) return error.SDL_ERROR; return e; } pub fn waitEventTimeout(timeout: i32) callconv(.Inline) ?Event { var e: Event = undefined; const rc = raw.SDL_WaitEventTimeout(&e, timeout); if (rc <= 0) return null; return e; } pub fn pushEvent(e: Event) callconv(.Inline) !bool { const rc = raw.SDL_PushEvent(e); if (rc < 0) return error.SDL_ERROR; return rc != 0; } pub const InitFlags = packed struct { timer: bool align(4) = false, __pad0: u3 = 0, audio: bool = false, video: bool = false, // implies events __pad1: u2 = 0, __pad2: u1 = 0, joystick: bool = false, // implies events __pad3: u2 = 0, haptic: bool = false, gamecontroller: bool = false, // implies joystick events: bool = false, sensor: bool = false, __pad4: u4 = 0, noparachute: bool = false, // backwards compat, ignored __pad5: u3 = 0, __pad6: u8 = 0, pub const everything: InitFlags = .{ .timer = true, .audio = true, .video = true, .events = true, .joystick = true, .haptic = true, .gamecontroller = true, .sensor = true, }; pub fn fromInt(int: InitFlagsInt) InitFlags { return @bitCast(InitFlags, int); } pub fn toInt(self: InitFlags) InitFlagsInt { return @bitCast(InitFlagsInt, self); } comptime { if (@alignOf(InitFlags) != @alignOf(InitFlagsInt)) @compileError("InitFlags must be 4 byte aligned"); if (@sizeOf(InitFlags) != @sizeOf(InitFlagsInt)) @compileError("InitFlags must be 4 bytes long"); if (@bitSizeOf(InitFlags) != @bitSizeOf(InitFlagsInt)) @compileError("InitFlags must be 32 bits long"); } }; pub const InitFlagsInt = u32; pub fn Init(flags: InitFlags) !void { const rc = raw.SDL_Init(flags.toInt()); if (rc < 0) return error.SDL_ERROR; } pub const Quit = raw.SDL_Quit; pub const raw = struct { // --------------------------- SDL.h -------------------------- pub extern fn SDL_Init(flags: InitFlagsInt) callconv(CC) c_int; pub extern fn SDL_InitSubSystem(flags: InitFlagsInt) callconv(CC) c_int; pub extern fn SDL_QuitSubSystem(flags: InitFlagsInt) callconv(CC) void; pub extern fn SDL_WasInit(flags: InitFlagsInt) callconv(CC) InitFlagsInt; pub extern fn SDL_Quit() callconv(CC) void; // --------------------------- SDL_error.h -------------------------- pub extern fn SDL_SetError(fmt: [*:0]const u8, ...) callconv(CC) c_int; pub extern fn SDL_GetError() callconv(CC) ?[*:0]const u8; pub extern fn SDL_GetErrorMsg(errstr: [*]u8, maxlen: u32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_ClearError() callconv(CC) void; // --------------------------- SDL_rwops.h -------------------------- pub extern fn SDL_RWFromFile(file: ?[*:0]const u8, mode: ?[*:0]const u8) callconv(CC) ?*RWops; pub extern fn SDL_RWFromFP(fp: ?*c_void, autoclose: IntBool) callconv(CC) ?*RWops; pub extern fn SDL_RWFromMem(mem: ?*c_void, size: i32) callconv(CC) ?*RWops; pub extern fn SDL_RWFromConstMem(mem: ?*const c_void, size: i32) callconv(CC) ?*RWops; pub extern fn SDL_AllocRW() callconv(CC) ?*RWops; pub extern fn SDL_FreeRW(area: *RWops) callconv(CC) void; pub extern fn SDL_RWsize(context: *RWops) callconv(CC) i64; pub extern fn SDL_RWseek(context: *RWops, offset: i64, whence: RWops.Whence) callconv(CC) i64; pub extern fn SDL_RWtell(context: *RWops) callconv(CC) i64; pub extern fn SDL_RWread(context: *RWops, ptr: ?*c_void, size: usize, maxnum: usize) callconv(CC) usize; pub extern fn SDL_RWwrite(context: *RWops, ptr: ?*c_void, size: usize, num: usize) callconv(CC) usize; pub extern fn SDL_RWclose(context: *RWops) callconv(CC) i32; pub extern fn SDL_LoadFile_RW(src: *RWops, datasize: ?*usize, freesrc: i32) callconv(CC) ?*c_void; pub extern fn SDL_LoadFile(file: ?[*:0]const u8, datasize: ?*usize) callconv(CC) ?*c_void; pub extern fn SDL_ReadU8(src: *RWops) callconv(CC) u8; pub extern fn SDL_ReadLE16(src: *RWops) callconv(CC) u16; pub extern fn SDL_ReadBE16(src: *RWops) callconv(CC) u16; pub extern fn SDL_ReadLE32(src: *RWops) callconv(CC) u32; pub extern fn SDL_ReadBE32(src: *RWops) callconv(CC) u32; pub extern fn SDL_ReadLE64(src: *RWops) callconv(CC) u64; pub extern fn SDL_ReadBE64(src: *RWops) callconv(CC) u64; pub extern fn SDL_WriteU8(dst: *RWops, value: u8) callconv(CC) usize; pub extern fn SDL_WriteLE16(dst: *RWops, value: u16) callconv(CC) usize; pub extern fn SDL_WriteBE16(dst: *RWops, value: u16) callconv(CC) usize; pub extern fn SDL_WriteLE32(dst: *RWops, value: u32) callconv(CC) usize; pub extern fn SDL_WriteBE32(dst: *RWops, value: u32) callconv(CC) usize; pub extern fn SDL_WriteLE64(dst: *RWops, value: u64) callconv(CC) usize; pub extern fn SDL_WriteBE64(dst: *RWops, value: u64) callconv(CC) usize; // --------------------------- SDL_audio.h -------------------------- pub extern fn SDL_GetNumAudioDrivers() callconv(CC) i32; pub extern fn SDL_GetAudioDriver(index: i32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_AudioInit(driver_name: ?[*:0]const u8) callconv(CC) i32; pub extern fn SDL_AudioQuit() callconv(CC) void; pub extern fn SDL_GetCurrentAudioDriver() callconv(CC) ?[*:0]const u8; pub extern fn SDL_OpenAudio(desired: *audio.Spec, obtained: ?*audio.Spec) callconv(CC) i32; pub extern fn SDL_GetNumAudioDevices(iscapture: i32) callconv(CC) i32; pub extern fn SDL_GetAudioDeviceName(index: i32, iscapture: i32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_OpenAudioDevice( device: ?[*:0]const u8, iscapture: i32, desired: *const audio.Spec, obtained: ?*const audio.Spec, allowed_changes: i32, ) callconv(CC) audio.DeviceID; pub extern fn SDL_GetAudioDeviceStatus(device: audio.DeviceID) callconv(CC) audio.Status; pub extern fn SDL_PauseAudio(pause_on: i32) callconv(CC) void; pub extern fn SDL_PauseAudioDevice(device: audio.DeviceID, pause_on: i32) callconv(CC) void; pub extern fn SDL_LoadWAV_RW(src: *RWops, freesrc: i32, spec: *audio.Spec, audio_buf: *?[*]u8, audio_len: *u32) callconv(CC) ?*audio.Spec; pub fn SDL_LoadWAV(file: ?[*:0]const u8, spec: *audio.Spec, audio_buf: *?[*]u8, audio_len: *u32) callconv(.Inline) ?*audio.Spec { return SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb").?, 1, spec, audio_buf, audio_len); } pub extern fn SDL_FreeWAV(audio_buf: ?[*]u8) callconv(CC) void; pub extern fn SDL_BuildAudioCVT( cvt: *audio.CVT, src_format: audio.FormatInt, src_channels: u8, src_rate: i32, dst_format: audio.FormatInt, dst_channels: u8, dst_rate: i32, ) callconv(CC) i32; pub extern fn SDL_ConvertAudio(cvt: *audio.CVT) callconv(CC) i32; pub extern fn SDL_NewAudioStream( src_format: audio.FormatInt, src_channels: u8, src_rate: i32, dst_format: audio.FormatInt, dst_channels: u8, dst_rate: i32, ) callconv(CC) ?*audio.Stream; pub extern fn SDL_AudioStreamPut(stream: *audio.Stream, buf: ?*c_void, len: i32) callconv(CC) i32; pub extern fn SDL_AudioStreamGet(stream: *audio.Stream, buf: ?*c_void, len: i32) callconv(CC) i32; pub extern fn SDL_AudioStreamAvailable(stream: *audio.Stream) callconv(CC) i32; pub extern fn SDL_AudioStreamFlush(stream: *audio.Stream) callconv(CC) i32; pub extern fn SDL_AudioStreamClear(stream: *audio.Stream) callconv(CC) void; pub extern fn SDL_FreeAudioStream(stream: *audio.Stream) callconv(CC) void; pub extern fn SDL_MixAudio(dst: [*]u8, src: [*]const u8, len: u32, volume: c_int) callconv(CC) void; pub extern fn SDL_MixAudioFormat(dst: [*]u8, src: [*]const u8, format: audio.FormatInt, len: u32, volume: c_int) callconv(CC) void; pub extern fn SDL_QueueAudio(device: audio.DeviceID, data: ?*c_void, len: u32) callconv(CC) c_int; pub extern fn SDL_DequeueAudio(device: audio.DeviceID, data: ?*c_void, len: u32) callconv(CC) c_int; pub extern fn SDL_GetQueuedAudioSize(dev: audio.DeviceID) callconv(CC) u32; pub extern fn SDL_ClearQueuedAudio(dev: audio.DeviceID) callconv(CC) void; pub extern fn SDL_LockAudio() callconv(CC) void; pub extern fn SDL_LockAudioDevice(dev: audio.DeviceID) callconv(CC) void; pub extern fn SDL_UnlockAudio() callconv(CC) void; pub extern fn SDL_UnlockAudioDevice(dev: audio.DeviceID) callconv(CC) void; pub extern fn SDL_CloseAudio() callconv(CC) void; pub extern fn SDL_CloseAudioDevice(dev: audio.DeviceID) callconv(CC) void; // --------------------------- SDL_events.h -------------------------- pub extern fn SDL_PumpEvents() callconv(CC) void; pub extern fn SDL_PeepEvents(events: [*]Event, numevents: i32, action: Event.Action, minType: Event.Type, maxType: Event.Type) callconv(CC) i32; pub extern fn SDL_HasEvent(@"type": Event.Type) callconv(CC) IntBool; pub extern fn SDL_HasEvents(minType: Event.Type, maxType: Event.Type) callconv(CC) IntBool; pub extern fn SDL_FlushEvent(@"type": Event.Type) callconv(CC) void; pub extern fn SDL_FlushEvents(minType: Event.Type, maxType: Event.Type) callconv(CC) void; pub extern fn SDL_PollEvent(event: *Event) callconv(CC) IntBool; pub extern fn SDL_WaitEvent(event: *Event) callconv(CC) IntBool; pub extern fn SDL_WaitEventTimeout(event: *Event, timeout: i32) callconv(CC) IntBool; pub extern fn SDL_PushEvent(event: *Event) callconv(CC) IntBool; pub extern fn SDL_SetEventFilter(filter: ?Event.Filter, userdata: ?*c_void) callconv(CC) void; pub extern fn SDL_GetEventFilter(filter: *?Event.Filter, userdata: *?*c_void) callconv(CC) IntBool; pub extern fn SDL_AddEventWatch(filter: Event.Filter, userdata: ?*c_void) callconv(CC) void; pub extern fn SDL_DelEventWatch(filter: Event.Filter, userdata: ?*c_void) callconv(CC) void; pub extern fn SDL_FilterEvents(filter: Event.Filter, userdata: ?*c_void) callconv(CC) void; pub extern fn SDL_EventState(@"type": Event.Type, state: Event.State) callconv(CC) u8; pub fn SDL_GetEventState(@"type": Event.Type) callconv(.Inline) Event.State { return @intToEnum(Event.State, @intCast(c_int, SDL_EventState(@"type", .query))); } pub extern fn SDL_RegisterEvents(numevents: i32) callconv(CC) u32; // --------------------------- SDL_gesture.h -------------------------- pub extern fn SDL_RecordGesture(touchId: TouchID) callconv(CC) i32; pub extern fn SDL_SaveAllDollarTemplates(dst: *RWops) callconv(CC) i32; pub extern fn SDL_SaveDollarTemplate(gestureId: GestureID, dst: *RWops) callconv(CC) i32; pub extern fn SDL_LoadDollarTemplates(touchId: TouchID, src: *RWops) callconv(CC) i32; // --------------------------- SDL_joystick.h -------------------------- pub extern fn SDL_LockJoysticks() callconv(CC) void; pub extern fn SDL_UnlockJoysticks() callconv(CC) void; pub extern fn SDL_NumJoysticks() callconv(CC) i32; pub extern fn SDL_JoystickNameForIndex(device_index: i32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_JoystickGetDevicePlayerIndex(device_index: i32) callconv(CC) i32; /// Note: On some platforms this may not be correctly handled at the ABI layer. /// TODO: Wrap this with a C stub. pub extern fn SDL_JoystickGetDeviceGUID(device_index: i32) callconv(CC) Joystick.GUID; pub extern fn SDL_JoystickGetDeviceVendor(device_index: i32) callconv(CC) u16; pub extern fn SDL_JoystickGetDeviceProduct(device_index: i32) callconv(CC) u16; pub extern fn SDL_JoystickGetDeviceType(device_index: i32) callconv(CC) Joystick.Type; pub extern fn SDL_JoystickGetDeviceInstanceID(device_index: i32) callconv(CC) Joystick.ID; pub extern fn SDL_JoystickOpen(device_index: i32) callconv(CC) ?*Joystick; pub extern fn SDL_JoystickFromInstanceID(instance_id: Joystick.ID) callconv(CC) ?*Joystick; pub extern fn SDL_JoystickFromPlayerIndex(player_index: i32) callconv(CC) ?*Joystick; pub extern fn SDL_JoystickAttachVirtual(@"type": SDL_JoystickType, naxes: i32, nbuttons: i32, nhats: i32) callconv(CC) i32; pub extern fn SDL_JoystickDetachVirtual(device_index: i32) callconv(CC) i32; pub extern fn SDL_JoystickIsVirtual(device_index: i32) callconv(CC) IntBool; pub extern fn SDL_JoystickSetVirtualAxis(joystick: *Joystick, axis: i32, value: i16) callconv(CC) i32; pub extern fn SDL_JoystickSetVirtualButton(joystick: *Joystick, button: i32, value: u8) callconv(CC) i32; pub extern fn SDL_JoystickSetVirtualHat(joystick: *Joystick, hat: i32, value: Joystick.Hat) callconv(CC) i32; pub extern fn SDL_JoystickName(joystick: *Joystick) callconv(CC) ?[*:0]const u8; pub extern fn SDL_JoystickGetPlayerIndex(joystick: *Joystick) callconv(CC) i32; pub extern fn SDL_JoystickSetPlayerIndex(joystick: *Joystick, player_index: i32) callconv(CC) void; pub extern fn SDL_JoystickGetGUID(joystick: *Joystick) callconv(CC) Joystick.GUID; pub extern fn SDL_JoystickGetVendor(joystick: *Joystick) callconv(CC) u16; pub extern fn SDL_JoystickGetProduct(joystick: *Joystick) callconv(CC) u16; pub extern fn SDL_JoystickGetProductVersion(joystick: *Joystick) callconv(CC) u16; pub extern fn SDL_JoystickGetSerial(joystick: *Joystick) callconv(CC) ?[*:0]const u8; pub extern fn SDL_JoystickGetType(joystick: *Joystick) callconv(CC) Joystick.Type; pub extern fn SDL_JoystickGetGUIDString(guid: Joystick.GUID, pszGUID: *[33]u8, cbGUID: i32) callconv(CC) void; pub extern fn SDL_JoystickGetGUIDFromString(pchGUID: [*:0]const u8) callconv(CC) Joystick.GUID; pub extern fn SDL_JoystickGetAttached(joystick: *Joystick) callconv(CC) IntBool; pub extern fn SDL_JoystickInstanceID(joystick: *Joystick) callconv(CC) Joystick.ID; pub extern fn SDL_JoystickNumAxes(joystick: *Joystick) callconv(CC) i32; pub extern fn SDL_JoystickNumBalls(joystick: *Joystick) callconv(CC) i32; pub extern fn SDL_JoystickNumHats(joystick: *Joystick) callconv(CC) i32; pub extern fn SDL_JoystickNumButtons(joystick: *Joystick) callconv(CC) i32; pub extern fn SDL_JoystickUpdate() callconv(CC) void; pub extern fn SDL_JoystickEventState(state: Event.State) callconv(CC) i32; pub extern fn SDL_JoystickGetAxis(joystick: *Joystick, axis: i32) callconv(CC) i16; pub extern fn SDL_JoystickGetAxisInitialState(joystick: *Joystick, axis: i32, state: *i16) callconv(CC) IntBool; pub extern fn SDL_JoystickGetHat(joystick: *Joystick, hat: i32) callconv(CC) Joystick.Hat; pub extern fn SDL_JoystickGetBall(joystick: *Joystick, ball: i32, dx: *i32, dy: *i32) callconv(CC) i32; pub extern fn SDL_JoystickGetButton(joystick: *Joystick, button: i32) callconv(CC) u8; pub extern fn SDL_JoystickRumble(joystick: *Joystick, low_frequency_rumble: u16, high_frequency_rumble: u16, duration_ms: u32) callconv(CC) i32; pub extern fn SDL_JoystickRumbleTriggers(joystick: *Joystick, left_rumble: u16, right_rumble: u16, duration_ms: u32) callconv(CC) i32; pub extern fn SDL_JoystickHasLED(joystick: *Joystick) callconv(CC) IntBool; pub extern fn SDL_JoystickSetLED(joystick: *Joystick, red: u8, green: u8, blue: u8) callconv(CC) i32; pub extern fn SDL_JoystickClose(joystick: *Joystick) callconv(CC) void; pub extern fn SDL_JoystickCurrentPowerLevel(joystick: *Joystick) callconv(CC) Joystick.PowerLevel; // --------------------------- SDL_keyboard.h -------------------------- pub extern fn SDL_GetKeyboardFocus() callconv(CC) ?*Window; pub extern fn SDL_GetKeyboardState(numkeys: ?*i32) callconv(CC) ?[*]const u8; pub extern fn SDL_GetModState() callconv(CC) KeymodInt; pub extern fn SDL_SetModState(modstate: KeymodInt) callconv(CC) void; pub extern fn SDL_GetKeyFromScancode(scancode: Scancode) callconv(CC) Keycode; pub extern fn SDL_GetScancodeFromKey(key: Keycode) callconv(CC) Scancode; pub extern fn SDL_GetScancodeName(scancode: Scancode) callconv(CC) ?[*:0]const u8; pub extern fn SDL_GetScancodeFromName(name: ?[*:0]const u8) callconv(CC) Scancode; pub extern fn SDL_GetKeyName(key: Keycode) callconv(CC) ?[*:0]const u8; pub extern fn SDL_GetKeyFromName(name: ?[*:0]const u8) callconv(CC) Keycode; pub extern fn SDL_StartTextInput() callconv(CC) void; pub extern fn SDL_IsTextInputActive() callconv(CC) IntBool; pub extern fn SDL_StopTextInput() callconv(CC) void; pub extern fn SDL_SetTextInputRect(rect: *Rect) callconv(CC) void; pub extern fn SDL_HasScreenKeyboardSupport() callconv(CC) IntBool; pub extern fn SDL_IsScreenKeyboardShown(window: *Window) callconv(CC) IntBool; // --------------------------- SDL_pixels.h -------------------------- pub extern fn SDL_GetPixelFormatName(format: PixelFormatEnum.Int) callconv(CC) ?[*:0]const u8; pub extern fn SDL_PixelFormatEnumToMasks(format: PixelFormatEnum.Int, bpp: *i32, rMask: *u32, gMask: *u32, bMask: *u32, aMask: *u32) callconv(CC) IntBool; pub extern fn SDL_MasksToPixelFormatEnum(bpp: i32, rMask: u32, gMask: u32, bMask: u32, aMask: u32) callconv(CC) PixelFormatEnum.Int; pub extern fn SDL_AllocFormat(pixel_format: PixelFormatEnum.Int) callconv(CC) ?*const PixelFormat; pub extern fn SDL_FreeFormat(format: *const PixelFormat) callconv(CC) void; pub extern fn SDL_AllocPalette(ncolors: i32) callconv(CC) ?*const Palette; pub extern fn SDL_SetPixelFormatPalette(format: *const PixelFormat, palette: *const Palette) callconv(CC) c_int; pub extern fn SDL_SetPaletteColors(palette: *const Palette, colors: [*]const Color, firstcolor: i32, ncolors: i32) callconv(CC) c_int; pub extern fn SDL_FreePalette(palette: *const Palette) callconv(CC) void; pub extern fn SDL_MapRGB(format: *const PixelFormat, r: u8, g: u8, b: u8) callconv(CC) u32; pub extern fn SDL_MapRGBA(format: *const PixelFormat, r: u8, g: u8, b: u8, a: u8) callconv(CC) u32; pub extern fn SDL_GetRGB(pixel: u32, format: *const PixelFormat, r: *u8, g: *u8, b: *u8) callconv(CC) void; pub extern fn SDL_GetRGBA(pixel: u32, format: *const PixelFormat, r: *u8, g: *u8, b: *u8, a: *u8) callconv(CC) void; pub extern fn SDL_CalculateGammaRamp(gamma: f32, ramp: *[256]u16) callconv(CC) void; // --------------------------- SDL_rect.h -------------------------- pub fn SDL_PointInRect(p: *const Point, r: *const Rect) callconv(.Inline) bool { return ((p.x >= r.x) and (p.x < (r.x + r.w)) and (p.y >= r.y) and (p.y < (r.y + r.h))); } pub fn SDL_RectEmpty(r: ?*const Rect) callconv(.Inline) bool { return (r == null) or (r.?.w <= 0) or (r.?.h <= 0); } pub fn SDL_RectEquals(a: ?*const Rect, b: ?*const Rect) callconv(.Inline) bool { return a != null and b != null and (a.?.x == b.?.x) and (a.?.y == b.?.y) and (a.?.w == b.?.w) and (a.?.h == b.?.h); } pub extern fn SDL_HasIntersection(a: *const Rect, b: *const Rect) callconv(CC) IntBool; pub extern fn SDL_IntersectRect(a: *const Rect, b: *const Rect, result: *Rect) callconv(CC) IntBool; pub extern fn SDL_UnionRect(a: *const Rect, b: *const Rect, result: *Rect) callconv(CC) void; pub extern fn SDL_EnclosePoints(points: ?[*]const Point, count: i32, clip: ?*const Rect, result: *Rect) callconv(CC) IntBool; pub extern fn SDL_IntersectRectAndLine(rect: *const Rect, x1: *i32, y1: *i32, x2: *i32, y2: *i32) callconv(CC) IntBool; // --------------------------- SDL_timer.h -------------------------- pub extern fn SDL_GetTicks() callconv(CC) u32; pub fn SDL_TICKS_PASSED(a: u32, b: u32) callconv(.Inline) bool { return @bitCast(i32, b) - @bitCast(i32, a) <= 0; } pub extern fn SDL_GetPerformanceCounter() callconv(CC) u64; pub extern fn SDL_GetPerformanceFrequency() callconv(CC) u64; pub extern fn SDL_Delay(ms: u32) callconv(CC) void; pub extern fn SDL_AddTimer(interval: u32, callback: TimerCallback, param: ?*c_void) callconv(CC) TimerID; pub extern fn SDL_RemoveTimer(id: TimerID) IntBool; // --------------------------- SDL_touch.h -------------------------- pub extern fn SDL_GetNumTouchDevices() callconv(CC) i32; pub extern fn SDL_GetTouchDevice(index: i32) callconv(CC) TouchID; pub extern fn SDL_GetTouchDeviceType(touchID: TouchID) callconv(CC) TouchDeviceType; pub extern fn SDL_GetNumTouchFingers(touchID: TouchID) callconv(CC) i32; pub extern fn SDL_GetTouchFinger(touchID: TouchID, index: i32) callconv(CC) ?*Finger; // --------------------------- SDL_video.h -------------------------- pub extern fn SDL_GetNumVideoDrivers() callconv(CC) i32; pub extern fn SDL_GetVideoDriver(index: i32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_VideoInit(driver_name: ?[*:0]const u8) callconv(CC) c_int; pub extern fn SDL_VideoQuit() callconv(CC) void; pub extern fn SDL_GetCurrentVideoDriver() callconv(CC) ?[*:0]const u8; pub extern fn SDL_GetNumVideoDisplays() callconv(CC) i32; pub extern fn SDL_GetDisplayName(displayIndex: i32) callconv(CC) ?[*:0]const u8; pub extern fn SDL_GetDisplayBounds(displayIndex: i32, rect: *Rect) callconv(CC) c_int; pub extern fn SDL_GetDisplayUsableBounds(displayIndex: i32, rect: *Rect) callconv(CC) c_int; pub extern fn SDL_GetDisplayDPI(displayIndex: i32, ddpi: *f32, hdpi: *f32, vdpi: *f32) callconv(CC) c_int; pub extern fn SDL_GetDisplayOrientation(displayIndex: i32) callconv(CC) DisplayOrientation.Int; pub extern fn SDL_GetNumDisplayModes(displayIndex: i32) callconv(CC) i32; pub extern fn SDL_GetDisplayMode(displayIndex: i32, modeIndex: i32, mode: *video.DisplayMode) callconv(CC) c_int; pub extern fn SDL_GetDesktopDisplayMode(displayIndex: i32, mode: *video.DisplayMode) callconv(CC) c_int; pub extern fn SDL_GetCurrentDisplayMode(displayIndex: i32, mode: *video.DisplayMode) callconv(CC) c_int; pub extern fn SDL_GetClosestDisplayMode(displayIndex: i32, mode: *const video.DisplayMode, closest: *video.DisplayMode) callconv(CC) ?*video.DisplayMode; pub extern fn SDL_GetWindowDisplayIndex(window: *Window) callconv(CC) c_int; pub extern fn SDL_SetWindowDisplayMode(window: *Window, mode: *const video.DisplayMode) callconv(CC) c_int; pub extern fn SDL_GetWindowDisplayMode(window: *Window, mode: *video.DisplayMode) callconv(CC) c_int; pub extern fn SDL_GetWindowPixelFormat(window: *Window) callconv(CC) PixelFormatEnum.Int; pub extern fn SDL_CreateWindow(title: ?[*:0]const u8, x: i32, y: i32, w: i32, h: i32, flags: Window.Flags.Int) callconv(CC) ?*Window; pub extern fn SDL_CreateWindowFrom(data: ?*c_void) callconv(CC) ?*Window; pub extern fn SDL_GetWindowID(window: *Window) callconv(CC) u32; pub extern fn SDL_GetWindowFromID(id: u32) callconv(CC) ?*Window; pub extern fn SDL_GetWindowFlags(window: *Window) callconv(CC) Window.Flags.Int; pub extern fn SDL_SetWindowTitle(window: *Window, title: ?[*:0]const u8) callconv(CC) void; pub extern fn SDL_GetWindowTitle(window: *Window) callconv(CC) ?[*:0]const u8; pub extern fn SDL_SetWindowIcon(window: *Window, icon: *Surface) callconv(CC) void; pub extern fn SDL_SetWindowData(window: *Window, name: [*:0]const u8, userdata: ?*c_void) callconv(CC) ?*c_void; pub extern fn SDL_GetWindowData(window: *Window, name: [*:0]const u8) callconv(CC) ?*c_void; pub extern fn SDL_SetWindowPosition(window: *Window, x: i32, y: i32) callconv(CC) void; pub extern fn SDL_GetWindowPosition(window: *Window, x: ?*i32, y: ?*i32) callconv(CC) void; pub extern fn SDL_SetWindowSize(window: *Window, w: i32, h: i32) callconv(CC) void; pub extern fn SDL_GetWindowSize(window: *Window, w: ?*i32, h: ?*i32) callconv(CC) void; pub extern fn SDL_GetWindowBordersSize(window: *Window, top: ?*i32, left: ?*i32, bottom: ?*i32, right: ?*i32) callconv(CC) c_int; pub extern fn SDL_SetWindowMinimumSize(window: *Window, min_w: i32, min_h: i32) callconv(CC) void; pub extern fn SDL_GetWindowMinimumSize(window: *Window, w: ?*i32, h: ?*i32) callconv(CC) void; pub extern fn SDL_SetWindowMaximumSize(window: *Window, max_w: i32, max_h: i32) callconv(CC) void; pub extern fn SDL_GetWindowMaximumSize(window: *Window, w: ?*i32, h: ?*i32) callconv(CC) void; pub extern fn SDL_SetWindowBordered(window: *Window, bordered: IntBool) callconv(CC) void; pub extern fn SDL_SetWindowResizable(window: *Window, resizable: IntBool) callconv(CC) void; pub extern fn SDL_ShowWindow(window: *Window) callconv(CC) void; pub extern fn SDL_HideWindow(window: *Window) callconv(CC) void; pub extern fn SDL_RaiseWindow(window: *Window) callconv(CC) void; pub extern fn SDL_MaximizeWindow(window: *Window) callconv(CC) void; pub extern fn SDL_MinimizeWindow(window: *Window) callconv(CC) void; pub extern fn SDL_RestoreWindow(window: *Window) callconv(CC) void; pub extern fn SDL_SetWindowFullscreen(window: *Window, flags: Window.Flags.Int) callconv(CC) c_int; pub extern fn SDL_GetWindowSurface(window: *Window) callconv(CC) ?*Surface; pub extern fn SDL_UpdateWindowSurface(window: *Window) callconv(CC) c_int; pub extern fn SDL_UpdateWindowSurfaceRects(window: *Window, rects: ?[*]const Rect, numrects: i32) callconv(CC) c_int; pub extern fn SDL_SetWindowGrab(window: *Window, grabbed: IntBool) callconv(CC) void; pub extern fn SDL_GetWindowGrab(window: *Window) callconv(CC) IntBool; pub extern fn SDL_GetGrabbedWindow() callconv(CC) ?*Window; pub extern fn SDL_SetWindowBrightness(window: *Window, brightness: f32) callconv(CC) c_int; pub extern fn SDL_GetWindowBrightness(window: *Window) callconv(CC) f32; pub extern fn SDL_SetWindowOpacity(window: *Window, opacity: f32) callconv(CC) c_int; pub extern fn SDL_GetWindowOpacity(window: *Window, out_opacity: *f32) callconv(CC) c_int; pub extern fn SDL_SetWindowModalFor(modal_window: *Window, parent_window: *Window) callconv(CC) c_int; pub extern fn SDL_SetWindowInputFocus(window: *Window) callconv(CC) c_int; pub extern fn SDL_SetWindowGammaRamp(window: *Window, red: ?*const [256]u16, green: ?*const [256]u16, blue: ?*const [256]u16) callconv(CC) c_int; pub extern fn SDL_GetWindowGammaRamp(window: *Window, red: ?*[256]u16, green: ?*[256]u16, blue: ?*[256]u16) callconv(CC) c_int; pub extern fn SDL_SetWindowHitTest(window: *Window, callback: ?window.HitTest, callback_data: ?*c_void) callconv(CC) c_int; pub extern fn SDL_DestroyWindow(window: *Window) callconv(CC) void; pub extern fn SDL_IsScreenSaverEnabled() callconv(CC) IntBool; pub extern fn SDL_EnableScreenSaver() callconv(CC) void; pub extern fn SDL_DisableScreenSaver() callconv(CC) void; pub extern fn SDL_GL_LoadLibrary(path: ?[*:0]const u8) callconv(CC) c_int; pub extern fn SDL_GL_GetProcAddress(proc: [*:0]const u8) callconv(CC) ?*c_void; pub extern fn SDL_GL_UnloadLibrary() callconv(CC) void; pub extern fn SDL_GL_ExtensionSupported(extension: [*:0]const u8) callconv(CC) IntBool; pub extern fn SDL_GL_ResetAttributes() callconv(CC) void; pub extern fn SDL_GL_SetAttribute(attr: gl.Attr, value: i32) callconv(CC) c_int; pub extern fn SDL_GL_GetAttribute(attr: gl.Attr, value: *i32) callconv(CC) c_int; pub extern fn SDL_GL_CreateContext(window: *Window) callconv(CC) ?gl.Context; pub extern fn SDL_GL_MakeCurrent(window: *Window, context: gl.Context) callconv(CC) c_int; pub extern fn SDL_GL_GetCurrentWindow() callconv(CC) ?*Window; pub extern fn SDL_GL_GetCurrentContext() callconv(CC) ?gl.Context; pub extern fn SDL_GL_GetDrawableSize(window: *Window, w: ?*i32, h: ?*i32) callconv(CC) void; pub extern fn SDL_GL_SetSwapInterval(interval: gl.SwapInterval) callconv(CC) c_int; pub extern fn SDL_GL_GetSwapInterval() callconv(CC) gl.SwapInterval; pub extern fn SDL_GL_SwapWindow(window: *Window) callconv(CC) void; pub extern fn SDL_GL_DeleteContext(context: gl.Context) callconv(CC) void; // --------------------------- SDL_vulkan.h -------------------------- pub extern fn SDL_Vulkan_LoadLibrary(path: ?[*:0]const u8) callconv(CC) c_int; pub extern fn SDL_Vulkan_GetVkGetInstanceProcAddr() callconv(CC) ?*c_void; pub extern fn SDL_Vulkan_UnloadLibrary() callconv(CC) void; pub extern fn SDL_Vulkan_GetInstanceExtensions(window: *Window, pCount: *u32, pNames: ?[*][*:0]const u8) callconv(CC) IntBool; pub extern fn SDL_Vulkan_CreateSurface(window: *Window, instance: vk.Instance, surface: *vk.SurfaceKHR) callconv(CC) IntBool; pub extern fn SDL_Vulkan_GetDrawableSize(window: *Window, w: *i32, h: *i32) callconv(CC) void; };
include/sdl.zig
const std = @import("std"); const zang = @import("zang"); const f = @import("zang-12tet"); const common = @import("common.zig"); const c = @import("common/c.zig"); const util = @import("common/util.zig"); pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb; pub const AUDIO_SAMPLE_RATE = 48000; pub const AUDIO_BUFFER_SIZE = 1024; pub const DESCRIPTION = \\example_song \\ \\Plays a canned melody (Bach's Toccata and Fugue in D \\Minor). \\ \\Press spacebar to restart the song. ; const a4 = 440.0; const NOTE_DURATION = 0.15; // everything comes out of the text file in this format const MyNoteParams = struct { freq: f32, note_on: bool, }; const Pedal = struct { const Module = @import("modules.zig").PMOscInstrument; fn initModule() Module { return Module.init(0.4); } fn makeParams(sample_rate: f32, src: MyNoteParams) Module.Params { return .{ .sample_rate = sample_rate, .freq = src.freq * 0.5, .note_on = src.note_on, }; } const polyphony = 3; const num_columns = 2; }; const RegularOrgan = struct { const Module = @import("modules.zig").NiceInstrument; fn initModule() Module { return Module.init(0.25); } fn makeParams(sample_rate: f32, src: MyNoteParams) Module.Params { return .{ .sample_rate = sample_rate, .freq = src.freq, .note_on = src.note_on, }; } const polyphony = 10; const num_columns = 8; }; const WeirdOrgan = struct { const Module = @import("modules.zig").NiceInstrument; fn initModule() Module { return Module.init(0.1); } fn makeParams(sample_rate: f32, src: MyNoteParams) Module.Params { return .{ .sample_rate = sample_rate, .freq = src.freq, .note_on = src.note_on, }; } const polyphony = 4; const num_columns = 2; }; // note: i would prefer for this to be an array of types (so i don't have to // give meaningless names to the fields), but it's also being used as an // instance type. you can't do that with an array of types. and without // reification features i can't generate a struct procedurally. (it needs to be // a struct because the elements/fields have different types) const Voices = struct { voice0: Voice(Pedal), voice1: Voice(RegularOrgan), voice2: Voice(WeirdOrgan), }; // this parallels the Voices struct. these values are not necessarily the same // as the polyphony amount. they're just a parsing detail const COLUMNS_PER_VOICE = [@typeInfo(Voices).Struct.fields.len]usize{ Pedal.num_columns, RegularOrgan.num_columns, WeirdOrgan.num_columns, }; const TOTAL_COLUMNS = blk: { var sum: usize = 0; for (COLUMNS_PER_VOICE) |v| sum += v; break :blk sum; }; const NUM_INSTRUMENTS = COLUMNS_PER_VOICE.len; // note we can't put params straight into Module.Params because that requires // sample_rate which is only known at runtime var all_notes_arr: [NUM_INSTRUMENTS][20000]zang.Notes(MyNoteParams).SongEvent = undefined; var all_notes: [NUM_INSTRUMENTS][]zang.Notes(MyNoteParams).SongEvent = undefined; fn makeSongNote( t: f32, id: usize, freq: f32, note_on: bool, ) zang.Notes(MyNoteParams).SongEvent { return .{ .t = t, .note_id = id, .params = .{ .freq = freq, .note_on = note_on, }, }; } const Parser = @import("common/songparse1.zig").Parser(TOTAL_COLUMNS); // NOTE about polyphony: if you retrigger a note at the same frequency, it will // be played in a separate voice (won't cut off the previous note). polyphony // doesn't look at note frequency at all, just the on/off events. fn doParse(parser: *Parser) !void { const LastNote = struct { freq: f32, id: usize, }; var column_last_note = [1]?LastNote{null} ** TOTAL_COLUMNS; var instrument_num_notes = [1]usize{0} ** NUM_INSTRUMENTS; var next_id: usize = 1; var t: f32 = 0; var rate: f32 = 1.0; var tempo: f32 = 1.0; while (try parser.parseToken()) |token| { if (token.isWord("start")) { t = 0.0; var i: usize = 0; while (i < NUM_INSTRUMENTS) : (i += 1) { instrument_num_notes[i] = 0; } // TODO what about column_last_note? } else if (token.isWord("rate")) { rate = try parser.requireNumber(); } else if (token.isWord("tempo")) { tempo = try parser.requireNumber(); } else { switch (token) { .notes => |notes| { const old_instrument_num_notes = instrument_num_notes; for (notes) |note, col| { const instrument_index = blk: { var first_column: usize = 0; for (COLUMNS_PER_VOICE) |num_columns, track_index| { if (col < first_column + num_columns) { break :blk track_index; } first_column += num_columns; } unreachable; }; var note_ptr = &all_notes_arr[instrument_index][instrument_num_notes[instrument_index]]; switch (note) { .idle => {}, .freq => |freq| { // note-off of previous note in this column // (if present) if (column_last_note[col]) |last_note| { note_ptr.* = makeSongNote( t, last_note.id, last_note.freq, false, ); instrument_num_notes[instrument_index] += 1; note_ptr = &all_notes_arr[instrument_index][instrument_num_notes[instrument_index]]; } // note-on event for the new frequency note_ptr.* = makeSongNote(t, next_id, freq, true); instrument_num_notes[instrument_index] += 1; column_last_note[col] = LastNote{ .id = next_id, .freq = freq, }; next_id += 1; }, .off => { if (column_last_note[col]) |last_note| { note_ptr.* = makeSongNote( t, last_note.id, last_note.freq, false, ); instrument_num_notes[instrument_index] += 1; column_last_note[col] = null; } }, } } t += NOTE_DURATION / (rate * tempo); // sort the events at this time frame by note id. this // puts note-offs before note-ons var i: usize = 0; while (i < NUM_INSTRUMENTS) : (i += 1) { const start = old_instrument_num_notes[i]; const end = instrument_num_notes[i]; std.sort.sort( zang.Notes(MyNoteParams).SongEvent, all_notes_arr[i][start..end], struct { fn compare( a: zang.Notes(MyNoteParams).SongEvent, b: zang.Notes(MyNoteParams).SongEvent, ) bool { return a.note_id < b.note_id; } }.compare, ); } }, else => return error.BadToken, } } } // now for each of the 3 instruments, we have chronological list of all // note on and off events (with a lot of overlapping). the notes need to // be identified by their frequency, which kind of sucks. i should // probably change the parser above to assign them unique IDs. var i: usize = 0; while (i < NUM_INSTRUMENTS) : (i += 1) { all_notes[i] = all_notes_arr[i][0..instrument_num_notes[i]]; } //i = 0; while (i < NUM_INSTRUMENTS) : (i += 1) { // if (i == 1) { // std.debug.warn("instrument {}:\n", .{ i }); // for (all_notes[i]) |note| { // std.debug.warn("t={} id={} freq={} note_on={}\n", .{ // note.t, // note.id, // note.params.freq, // note.params.note_on, // }); // } // } //} } fn parse() void { var buffer: [150000]u8 = undefined; const contents = util.readFile(buffer[0..]) catch { std.debug.warn("failed to read file\n", .{}); return; }; var parser = Parser{ .a4 = a4, .contents = contents, .index = 0, .line_index = 0, }; doParse(&parser) catch { std.debug.warn("parse failed on line {}\n", .{parser.line_index + 1}); }; } // polyphonic instrument, encapsulating note tracking (uses `all_notes` global) fn Voice(comptime T: type) type { return struct { pub const num_outputs = T.Module.num_outputs; pub const num_temps = T.Module.num_temps; const SubVoice = struct { module: T.Module, trigger: zang.Trigger(MyNoteParams), }; tracker: zang.Notes(MyNoteParams).NoteTracker, dispatcher: zang.Notes(MyNoteParams).PolyphonyDispatcher(T.polyphony), sub_voices: [T.polyphony]SubVoice, fn init(track_index: usize) @This() { var self: @This() = .{ .tracker = zang.Notes(MyNoteParams).NoteTracker.init(all_notes[track_index]), .dispatcher = zang.Notes(MyNoteParams).PolyphonyDispatcher(T.polyphony).init(), .sub_voices = undefined, }; var i: usize = 0; while (i < T.polyphony) : (i += 1) { self.sub_voices[i] = .{ .module = T.initModule(), .trigger = zang.Trigger(MyNoteParams).init(), }; } return self; } fn reset(self: *@This()) void { self.tracker.reset(); self.dispatcher.reset(); for (self.sub_voices) |*sub_voice| { sub_voice.trigger.reset(); } } fn paint( self: *@This(), span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { const iap = self.tracker.consume( AUDIO_SAMPLE_RATE, span.end - span.start, ); const poly_iap = self.dispatcher.dispatch(iap); for (self.sub_voices) |*sub_voice, i| { var ctr = sub_voice.trigger.counter(span, poly_iap[i]); while (sub_voice.trigger.next(&ctr)) |result| { sub_voice.module.paint( result.span, outputs, temps, result.note_id_changed, T.makeParams(AUDIO_SAMPLE_RATE, result.params), ); } } } }; } pub const MainModule = struct { pub const num_outputs = 1; pub const num_temps = blk: { comptime var n: usize = 0; inline for (@typeInfo(Voices).Struct.fields) |field| { n = std.math.max(n, @field(field.field_type, "num_temps")); } break :blk n; }; pub const output_audio = common.AudioOut{ .mono = 0 }; pub const output_visualize = 0; voices: Voices, pub fn init() MainModule { parse(); var mod: MainModule = .{ .voices = undefined, }; inline for (@typeInfo(Voices).Struct.fields) |field, track_index| { @field(mod.voices, field.name) = field.field_type.init(track_index); } return mod; } pub fn paint( self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { inline for (@typeInfo(Voices).Struct.fields) |field| { const VoiceType = field.field_type; @field(self.voices, field.name).paint( span, outputs, util.subarray(temps, VoiceType.num_temps), ); } } pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool { if (down and key == c.SDLK_SPACE) { inline for (@typeInfo(Voices).Struct.fields) |field| { @field(self.voices, field.name).reset(); } } return false; } };
examples/example_song.zig
const std = @import("std"); const fft = @import("common/fft.zig").fft; const example = @import(@import("build_options").example); const Recorder = @import("recorder.zig").Recorder; const fontdata = @embedFile("font.dat"); const fontchar_w = 8; const fontchar_h = 13; pub const Screen = struct { width: usize, height: usize, pixels: []u32, pitch: usize, }; // guaranteed to already be clipped to within the screen's bounds pub const ClipRect = struct { x: usize, y: usize, w: usize, h: usize }; fn clipRect(screen: Screen, x: usize, y: usize, w: usize, h: usize) ?ClipRect { if (x >= screen.width or y >= screen.height) return null; if (w == 0 or h == 0) return null; return ClipRect{ .x = x, .y = y, .w = std.math.min(w, screen.width - x), .h = std.math.min(h, screen.height - y), }; } fn drawFill(screen: Screen, rect: ClipRect, color: u32) void { var i: usize = 0; while (i < rect.h) : (i += 1) { const start = (rect.y + i) * screen.pitch + rect.x; std.mem.set(u32, screen.pixels[start .. start + rect.w], color); } } fn drawString(screen: Screen, rect: ClipRect, s: []const u8) void { const color: u32 = 0xAAAAAAAA; var x = rect.x; var y = rect.y; for (s) |ch| { if (ch != '\n' and (ch < 32 or ch >= 128)) { continue; } // wrap long lines if (ch == '\n' or x + fontchar_w >= rect.x + rect.w) { x = rect.x; y += fontchar_h + 1; if (ch == '\n') { continue; } } if (y >= rect.y + rect.h) { break; } if (x >= rect.x + rect.w) { continue; } const index = @intCast(usize, ch - 32) * fontchar_h; var out_index = y * screen.pitch + x; var sy: usize = 0; const sy_end = std.math.min(fontchar_h, rect.y + rect.h - y); while (sy < sy_end) : (sy += 1) { const fontrow = fontdata[index + sy]; var bit: u8 = 1; var sx: usize = 0; const sx_end = std.math.min(fontchar_w, rect.x + rect.w - x); while (sx < sx_end) : (sx += 1) { if ((fontrow & bit) != 0) { screen.pixels[out_index + sx] = color; } bit <<= 1; } out_index += screen.pitch; } x += fontchar_w + 1; } } fn stringWidth(s: []const u8) usize { if (s.len == 0) return 0; return s.len * (fontchar_w + 1) - 1; } fn hueToRgb(p: f32, q: f32, t_: f32) f32 { var t = t_; if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t; if (t < 1.0 / 2.0) return q; if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6; return p; } fn hslToRgb(h: f32, s: f32, l: f32) u32 { var r: f32 = undefined; var g: f32 = undefined; var b: f32 = undefined; if (s == 0.0) { r = 1.0; g = 1.0; b = 1.0; } else { const q = if (l < 0.5) l * (1 + s) else l + s - l * s; const p = 2 * l - q; r = hueToRgb(p, q, h + 1.0 / 3.0); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1.0 / 3.0); } // kludge const sqrt_h = std.math.sqrt(h); r *= sqrt_h; g *= sqrt_h; b *= sqrt_h; return @as(u32, 0xFF000000) | (@floatToInt(u32, b * 255) << 16) | (@floatToInt(u32, g * 255) << 8) | (@floatToInt(u32, r * 255)); } fn scrollBlit(screen: Screen, x: usize, y: usize, w: usize, h: usize, buffer: []const u32, drawindex: usize) void { var i: usize = 0; while (i < h) : (i += 1) { const dest_start = (y + i) * screen.pitch + x; const dest = screen.pixels[dest_start .. dest_start + w]; const src_start = i * w; const src = buffer[src_start .. src_start + w]; std.mem.copy(u32, dest[w - drawindex ..], src[0..drawindex]); std.mem.copy(u32, dest[0 .. w - drawindex], src[drawindex..]); } } fn getFFTValue(f_: f32, in_fft: []const f32, logarithmic: bool) f32 { var f = f_; if (logarithmic) { const exp = 10.0; f = (std.math.pow(f32, exp, f) - 1.0) / (exp - 1.0); } f *= 511.5; const f_floor = std.math.floor(f); const index0 = @floatToInt(usize, f_floor); const index1 = std.math.min(511, index0 + 1); const frac = f - f_floor; const fft_value0 = in_fft[index0]; const fft_value1 = in_fft[index1]; return fft_value0 * (1.0 - frac) + fft_value1 * frac; } pub const BlitContext = struct { recorder_state: @TagType(Recorder.State), }; pub const VTable = struct { offset: usize, // offset of `vtable: *const VTable` in instance object delFn: fn (self: **const VTable, allocator: *std.mem.Allocator) void, plotFn: fn (self: **const VTable, samples: []const f32, mul: f32, logarithmic: bool, sr: f32, oscil_freq: ?[]const f32) bool, blitFn: fn (self: **const VTable, screen: Screen, ctx: BlitContext) void, }; fn makeVTable(comptime T: type) VTable { const S = struct { const vtable = VTable{ .offset = blk: { inline for (@typeInfo(T).Struct.fields) |field| { if (comptime std.mem.eql(u8, field.name, "vtable")) { break :blk field.offset.?; } } @compileError("missing vtable field"); }, .delFn = delFn, .plotFn = plotFn, .blitFn = blitFn, }; fn delFn(self: **const VTable, allocator: *std.mem.Allocator) void { @intToPtr(*T, @ptrToInt(self) - self.*.offset).del(allocator); } fn plotFn(self: **const VTable, samples: []const f32, mul: f32, logarithmic: bool, sr: f32, oscil_freq: ?[]const f32) bool { if (!@hasDecl(T, "plot")) return false; return @intToPtr(*T, @ptrToInt(self) - self.*.offset).plot(samples, mul, logarithmic, sr, oscil_freq); } fn blitFn(self: **const VTable, screen: Screen, ctx: BlitContext) void { @intToPtr(*T, @ptrToInt(self) - self.*.offset).blit(screen, ctx); } }; return S.vtable; } // area chart where x=frequency and y=amplitude pub const DrawSpectrum = struct { const _vtable = makeVTable(@This()); vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, old_y: []u32, fft_real: []f32, fft_imag: []f32, fft_out: []f32, logarithmic: bool, state: enum { up_to_date, needs_blit, needs_full_reblit }, pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize) !*DrawSpectrum { var self = try allocator.create(DrawSpectrum); errdefer allocator.destroy(self); var old_y = try allocator.alloc(u32, width); errdefer allocator.free(old_y); var fft_real = try allocator.alloc(f32, 1024); errdefer allocator.free(fft_real); var fft_imag = try allocator.alloc(f32, 1024); errdefer allocator.free(fft_imag); var fft_out = try allocator.alloc(f32, 512); errdefer allocator.free(fft_out); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .old_y = old_y, .fft_real = fft_real, .fft_imag = fft_imag, .fft_out = fft_out, .logarithmic = false, .state = .needs_full_reblit, }; // old_y doesn't need to be initialized as long as state is .needs_full_reblit std.mem.set(f32, self.fft_out, 0.0); return self; } pub fn del(self: *DrawSpectrum, allocator: *std.mem.Allocator) void { allocator.free(self.old_y); allocator.free(self.fft_real); allocator.free(self.fft_imag); allocator.free(self.fft_out); allocator.destroy(self); } pub fn plot(self: *DrawSpectrum, samples: []const f32, _mul: f32, logarithmic: bool, _sr: f32, _oscil_freq: ?[]const f32) bool { std.debug.assert(samples.len == 1024); // FIXME std.mem.copy(f32, self.fft_real, samples); std.mem.set(f32, self.fft_imag, 0.0); fft(1024, self.fft_real, self.fft_imag); var i: usize = 0; while (i < 512) : (i += 1) { const v = std.math.fabs(self.fft_real[i]) * (1.0 / 1024.0); const v2 = std.math.sqrt(v); // kludge for visibility self.fft_out[i] = v2; } self.logarithmic = logarithmic; if (self.state == .up_to_date) { self.state = .needs_blit; } return true; } pub fn blit(self: *DrawSpectrum, screen: Screen, _context: BlitContext) void { if (self.state == .up_to_date) return; defer self.state = .up_to_date; const background_color: u32 = 0x00000000; const color: u32 = 0xFF444444; var i: usize = 0; while (i < self.width) : (i += 1) { const fi = @intToFloat(f32, i) / @intToFloat(f32, self.width - 1); const fv = getFFTValue(fi, self.fft_out, self.logarithmic) * @intToFloat(f32, self.height); const value = @floatToInt(u32, std.math.floor(fv)); const value_clipped = std.math.min(value, self.height - 1); // new_y is where the graph will transition from background to foreground color const new_y = @intCast(u32, self.height - value_clipped); // the transition pixel will have a blended color value const frac = fv - std.math.floor(fv); const co: u32 = @floatToInt(u32, 0x44 * frac); const transition_color = @as(u32, 0xFF000000) | (co << 16) | (co << 8) | co; const sx = self.x + i; var sy = self.y; if (self.state == .needs_full_reblit) { // redraw fully while (sy < self.y + new_y) : (sy += 1) { screen.pixels[sy * screen.pitch + sx] = background_color; } if (sy < self.y + self.height) { screen.pixels[sy * screen.pitch + sx] = transition_color; sy += 1; } while (sy < self.y + self.height) : (sy += 1) { screen.pixels[sy * screen.pitch + sx] = color; } } else { const old_y = self.old_y[i]; if (old_y < new_y) { // new_y is lower down. fill in the overlap with background color sy += old_y; while (sy < self.y + new_y) : (sy += 1) { screen.pixels[sy * screen.pitch + sx] = background_color; } if (sy < self.y + self.height) { screen.pixels[sy * screen.pitch + sx] = transition_color; sy += 1; } } else if (old_y > new_y) { // new_y is higher up. fill in the overlap with foreground color sy += new_y; if (sy < self.y + self.height) { screen.pixels[sy * screen.pitch + sx] = transition_color; sy += 1; } // add one to cover up the old transition pixel const until = std.math.min(old_y + 1, self.height); while (sy < self.y + until) : (sy += 1) { screen.pixels[sy * screen.pitch + sx] = color; } } } self.old_y[i] = new_y; } } }; // scrolling 2d color plot of FFT data pub const DrawSpectrumFull = struct { const _vtable = makeVTable(@This()); vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, fft_real: []f32, fft_imag: []f32, buffer: []u32, logarithmic: bool, drawindex: usize, pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize) !*DrawSpectrumFull { var self = try allocator.create(DrawSpectrumFull); errdefer allocator.destroy(self); var fft_real = try allocator.alloc(f32, 1024); errdefer allocator.free(fft_real); var fft_imag = try allocator.alloc(f32, 1024); errdefer allocator.free(fft_imag); var buffer = try allocator.alloc(u32, width * height); errdefer allocator.free(buffer); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .fft_real = fft_real, .fft_imag = fft_imag, .buffer = buffer, .logarithmic = false, .drawindex = 0, }; std.mem.set(u32, self.buffer, 0); return self; } pub fn del(self: *DrawSpectrumFull, allocator: *std.mem.Allocator) void { allocator.free(self.fft_real); allocator.free(self.fft_imag); allocator.free(self.buffer); allocator.destroy(self); } pub fn plot(self: *DrawSpectrumFull, samples: []const f32, _mul: f32, logarithmic: bool, _sr: f32, _oscil_freq: ?[]const f32) bool { if (self.logarithmic != logarithmic) { self.logarithmic = logarithmic; std.mem.set(u32, self.buffer, 0.0); self.drawindex = 0; } std.debug.assert(samples.len == 1024); // FIXME std.mem.copy(f32, self.fft_real, samples); std.mem.set(f32, self.fft_imag, 0.0); fft(1024, self.fft_real, self.fft_imag); var i: usize = 0; while (i < self.height) : (i += 1) { const f = @intToFloat(f32, i) / @intToFloat(f32, self.height - 1); const fft_value = getFFTValue(f, self.fft_real, logarithmic); // sqrt is a kludge to make things more visible const v = std.math.sqrt(std.math.fabs(fft_value) * (1.0 / 1024.0)); self.buffer[(self.height - 1 - i) * self.width + self.drawindex] = hslToRgb(v, 1.0, 0.5); } self.drawindex += 1; if (self.drawindex == self.width) { self.drawindex = 0; } return true; } pub fn blit(self: *DrawSpectrumFull, screen: Screen, _ctx: BlitContext) void { scrollBlit(screen, self.x, self.y, self.width, self.height, self.buffer, self.drawindex); } }; // scrolling waveform view pub const DrawWaveform = struct { const _vtable = makeVTable(@This()); vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, buffer: []u32, drawindex: usize, dirty: bool, const background_color: u32 = 0x18181818; const waveform_color: u32 = 0x44444444; const clipped_color: u32 = 0xFFFF0000; const center_line_color: u32 = 0x66666666; pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize) !*DrawWaveform { var self = try allocator.create(DrawWaveform); errdefer allocator.destroy(self); var buffer = try allocator.alloc(u32, width * height); errdefer allocator.free(buffer); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .buffer = buffer, .drawindex = 0, .dirty = true, }; std.mem.set(u32, self.buffer, background_color); const start = height / 2 * width; std.mem.set(u32, self.buffer[start .. start + width], center_line_color); return self; } pub fn del(self: *DrawWaveform, allocator: *std.mem.Allocator) void { allocator.free(self.buffer); allocator.destroy(self); } pub fn plot(self: *DrawWaveform, samples: []const f32, mul: f32, _logarithmic: bool, _sr: f32, _oscil_freq: ?[]const f32) bool { var sample_min = samples[0]; var sample_max = samples[0]; for (samples[1..]) |sample| { if (sample < sample_min) sample_min = sample; if (sample > sample_max) sample_max = sample; } sample_min *= mul; sample_max *= mul; const y_mid = self.height / 2; const fy_mid = @intToFloat(f32, y_mid); const fy_max = @intToFloat(f32, self.height - 1); const y0 = @floatToInt(usize, std.math.clamp(fy_mid - sample_max * fy_mid, 0, fy_max) + 0.5); const y1 = @floatToInt(usize, std.math.clamp(fy_mid - sample_min * fy_mid, 0, fy_max) + 0.5); var sx = self.drawindex; var sy: usize = 0; var until: usize = undefined; if (sample_max >= 1.0) { self.buffer[sy * self.width + sx] = clipped_color; sy += 1; } until = std.math.min(y0, y_mid); while (sy < until) : (sy += 1) { self.buffer[sy * self.width + sx] = background_color; } until = std.math.min(y1, y_mid); while (sy < until) : (sy += 1) { self.buffer[sy * self.width + sx] = waveform_color; } while (sy < y_mid) : (sy += 1) { self.buffer[sy * self.width + sx] = background_color; } self.buffer[sy * self.width + sx] = center_line_color; sy += 1; if (y0 > y_mid) { until = std.math.min(y0, self.height); while (sy < until) : (sy += 1) { self.buffer[sy * self.width + sx] = background_color; } } until = std.math.min(y1, self.height); while (sy < until) : (sy += 1) { self.buffer[sy * self.width + sx] = waveform_color; } while (sy < self.height) : (sy += 1) { self.buffer[sy * self.width + sx] = background_color; } if (sample_min <= -1.0) { sy -= 1; self.buffer[sy * self.width + sx] = clipped_color; } self.dirty = true; self.drawindex += 1; if (self.drawindex == self.width) { self.drawindex = 0; } return true; } pub fn blit(self: *DrawWaveform, screen: Screen, _ctx: BlitContext) void { if (!self.dirty) return; self.dirty = false; scrollBlit(screen, self.x, self.y, self.width, self.height, self.buffer, self.drawindex); } }; pub const DrawOscilloscope = struct { const _vtable = makeVTable(@This()); const PaintedSpan = struct { y0: usize, y1: usize, }; vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, mul: f32, samples: []f32, buffered_samples: []f32, num_buffered_samples: usize, painted_spans: []PaintedSpan, accum: f32, state: enum { up_to_date, needs_blit, needs_full_reblit }, const background_color: u32 = 0xFF181818; const waveform_color: u32 = 0xFFAAAAAA; pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize) !*DrawOscilloscope { var self = try allocator.create(DrawOscilloscope); errdefer allocator.destroy(self); var samples = try allocator.alloc(f32, width); errdefer allocator.free(samples); var buffered_samples = try allocator.alloc(f32, width); errdefer allocator.free(buffered_samples); var painted_spans = try allocator.alloc(PaintedSpan, width); errdefer allocator.free(old_y); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .mul = 1.0, .samples = samples, .buffered_samples = buffered_samples, .num_buffered_samples = 0, .painted_spans = painted_spans, .accum = 0, .state = .needs_full_reblit, }; std.mem.set(f32, samples, 0.0); return self; } pub fn del(self: *DrawOscilloscope, allocator: *std.mem.Allocator) void { allocator.free(self.samples); allocator.free(self.buffered_samples); allocator.free(self.painted_spans); allocator.destroy(self); } pub fn plot(self: *DrawOscilloscope, samples: []const f32, mul: f32, _logarithmic: bool, sr: f32, oscil_freq: ?[]const f32) bool { self.mul = mul; // meh // TODO can i refactor this into two classes? - one doesn't know about buffering. // the other wraps it and implements buffering. would that work? const inv_sr = 1.0 / sr; var n: usize = 0; var drain_buffer = false; if (oscil_freq) |freq| { // sync to oscil_freq for (samples) |_, i| { self.accum += freq[i] * inv_sr; // if frequency is so high that self.accum >= 2.0, you have bigger problems... if (self.accum >= 1.0) { n = i; self.accum -= 1.0; drain_buffer = true; } } } else { // no syncing n = samples.len; drain_buffer = true; } // `n` is the number of new samples to move from `samples` to `self.samples`. const num_to_push = n + (if (drain_buffer) self.num_buffered_samples else 0); // move down existing self.samples to make room for the new stuff. if (num_to_push < self.samples.len) { const diff = self.samples.len - num_to_push; std.mem.copy(f32, self.samples[0..diff], self.samples[num_to_push..]); } // now add in buffered samples if (drain_buffer) { if (n >= self.samples.len) { // buffered samples will be immediately pushed all the way off by new samples } else { const buf = self.buffered_samples[0..self.num_buffered_samples]; if (buf.len + n <= self.samples.len) { // whole of buf fits in self.samples const start = self.samples.len - n - buf.len; std.mem.copy(f32, self.samples[start .. start + buf.len], buf); } else { // only the latter part of buf will fit in self.samples const num_to_copy = self.samples.len - n; const b_start = buf.len - num_to_copy; std.mem.copy(f32, self.samples[0..num_to_copy], buf[b_start..]); } } self.num_buffered_samples = 0; } // now add in new samples if (n <= self.samples.len) { // whole of new samples fits in self.samples const start = self.samples.len - n; std.mem.copy(f32, self.samples[start..], samples[0..n]); } else { // only the latter part of new samples will fit in self.samples std.mem.copy(f32, self.samples, samples[n - self.samples.len .. n]); } // everything after `n`, we add to self.buffered_samples. // it's possible there are still some old buffered_samples there. if (n < samples.len) { const to_buffer = samples[n..]; const nbs = self.num_buffered_samples; if (nbs + to_buffer.len <= self.buffered_samples.len) { // there's empty space to fit all of it, just append it. std.mem.copy(f32, self.buffered_samples[nbs .. nbs + to_buffer.len], to_buffer); self.num_buffered_samples += to_buffer.len; } else if (to_buffer.len >= self.buffered_samples.len) { // new stuff will take up the entire buffer const start = to_buffer.len - self.buffered_samples.len; std.mem.copy(f32, self.buffered_samples, to_buffer[start..]); self.num_buffered_samples = self.buffered_samples.len; } else { // new stuff fits but has to push back old stuff. const to_keep = self.buffered_samples.len - to_buffer.len; std.mem.copy(f32, self.buffered_samples[0..to_keep], self.buffered_samples[nbs - to_keep .. 0]); std.mem.copy(f32, self.buffered_samples[to_keep..], to_buffer); self.num_buffered_samples = self.buffered_samples.len; } } if (self.state == .up_to_date) { self.state = .needs_blit; } return true; } pub fn blit(self: *DrawOscilloscope, screen: Screen, _ctx: BlitContext) void { if (self.state == .up_to_date) return; defer self.state = .up_to_date; const y_mid = self.height / 2; var old_y: usize = undefined; var i: usize = 0; while (i < self.width) : (i += 1) { const sx = self.x + i; const sample = std.math.max(-1.0, std.math.min(1.0, self.samples[i] * self.mul)); const y = @floatToInt(usize, @intToFloat(f32, y_mid) - sample * @intToFloat(f32, self.height / 2) + 0.5); const y_0 = if (i == 0) y else old_y; const y_1 = y; const y0 = std.math.min(y_0, y_1); const y1 = if (y_0 == y_1) std.math.min(y_0 + 1, self.height) else std.math.max(y_0, y_1); if (self.state == .needs_full_reblit) { var sy: usize = 0; while (sy < y0) : (sy += 1) { screen.pixels[(self.y + sy) * screen.pitch + sx] = background_color; } while (sy < y1) : (sy += 1) { screen.pixels[(self.y + sy) * screen.pitch + sx] = waveform_color; } while (sy < self.height) : (sy += 1) { screen.pixels[(self.y + sy) * screen.pitch + sx] = background_color; } } else { const old_span = self.painted_spans[i]; var sy = old_span.y0; while (sy < old_span.y1) : (sy += 1) { screen.pixels[(self.y + sy) * screen.pitch + sx] = background_color; } sy = y0; while (sy < y1) : (sy += 1) { screen.pixels[(self.y + sy) * screen.pitch + sx] = waveform_color; } } self.painted_spans[i] = .{ .y0 = y0, .y1 = y1 }; old_y = y; } } }; pub const DrawStaticString = struct { const _vtable = makeVTable(@This()); vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, drawn: bool, string: []const u8, bgcolor: u32, pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize, string: []const u8, bgcolor: u32) !*DrawStaticString { var self = try allocator.create(DrawStaticString); errdefer allocator.destroy(self); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .drawn = false, .string = string, .bgcolor = bgcolor, }; return self; } pub fn del(self: *DrawStaticString, allocator: *std.mem.Allocator) void { allocator.destroy(self); } pub fn blit(self: *DrawStaticString, screen: Screen, ctx: BlitContext) void { if (self.drawn) return; self.drawn = true; const rect = clipRect(screen, self.x, self.y, self.width, self.height) orelse return; drawFill(screen, rect, self.bgcolor); drawString(screen, rect, self.string); } }; pub const DrawRecorderState = struct { const _vtable = makeVTable(@This()); vtable: *const VTable, x: usize, y: usize, width: usize, height: usize, recorder_state: @TagType(Recorder.State), pub fn new(allocator: *std.mem.Allocator, x: usize, y: usize, width: usize, height: usize) !*DrawRecorderState { var self = try allocator.create(DrawRecorderState); errdefer allocator.destroy(self); self.* = .{ .vtable = &_vtable, .x = x, .y = y, .width = width, .height = height, .recorder_state = .idle, }; return self; } pub fn del(self: *DrawRecorderState, allocator: *std.mem.Allocator) void { allocator.destroy(self); } pub fn blit(self: *DrawRecorderState, screen: Screen, ctx: BlitContext) void { if (self.recorder_state == ctx.recorder_state) return; self.recorder_state = ctx.recorder_state; const rect = clipRect(screen, self.x, self.y, self.width, self.height) orelse return; drawFill(screen, rect, 0); drawString(screen, rect, switch (ctx.recorder_state) { .idle => "", .recording => "RECORDING", .playing => "PLAYING BACK", }); } }; pub const Visuals = struct { const State = enum { help, main, oscil, full_fft, }; allocator: *std.mem.Allocator, screen_w: usize, screen_h: usize, state: State, clear: bool, widgets: std.ArrayList(**const VTable), logarithmic_fft: bool, script_error: ?[]const u8, pub fn init(allocator: *std.mem.Allocator, screen_w: usize, screen_h: usize) !Visuals { var self: Visuals = .{ .allocator = allocator, .screen_w = screen_w, .screen_h = screen_h, .state = .main, .clear = true, .widgets = std.ArrayList(**const VTable).init(allocator), .logarithmic_fft = false, .script_error = null, }; self.setState(.main); return self; } pub fn deinit(self: *Visuals) void { self.clearWidgets(); self.widgets.deinit(); } fn clearWidgets(self: *Visuals) void { while (self.widgets.popOrNull()) |widget| { widget.*.delFn(widget, self.allocator); } } fn addWidget(self: *Visuals, inew: var) !void { var instance = try inew; self.widgets.append(&instance.vtable) catch |err| { instance.del(self.allocator); return err; }; } fn addWidgets(self: *Visuals) !void { const fft_height = 128; const waveform_height = 81; const bottom_padding = fontchar_h; const str0 = "F1:Help "; try self.addWidget(DrawStaticString.new( self.allocator, 0, 0, stringWidth(str0), fontchar_h, str0, if (self.state == .help) 0xFF444444 else 0, )); const str1 = "F2:Waveform "; try self.addWidget(DrawStaticString.new( self.allocator, stringWidth(str0), 0, stringWidth(str1), fontchar_h, str1, if (self.state == .main) 0xFF444444 else 0, )); const str2 = "F3:Oscillo "; try self.addWidget(DrawStaticString.new( self.allocator, stringWidth(str0) + stringWidth(str1), 0, stringWidth(str2), fontchar_h, str2, if (self.state == .oscil) 0xFF444444 else 0, )); const str3 = "F4:Spectrum "; try self.addWidget(DrawStaticString.new( self.allocator, stringWidth(str0) + stringWidth(str1) + stringWidth(str2), 0, stringWidth(str3), fontchar_h, str3, if (self.state == .full_fft) 0xFF444444 else 0, )); switch (self.state) { .help => { const help_h = 247; try self.addWidget(DrawStaticString.new( self.allocator, 12, fontchar_h + 13, self.screen_w - 12 * 2, help_h, example.DESCRIPTION, 0, )); const text = \\----------------------------------------------------- \\ \\Help reference \\ \\Press F1, F2, F3, or F4 to change the visualization \\mode. Stay in this mode for the fastest performance. \\ \\Press F5 to toggle between linear and logarithmic \\spectrum display. \\ \\Press ` (backquote/tilde) to record and play back \\keypresses (if applicable to the loaded example). \\ \\Press Enter to reload the loaded example. \\ \\Press Escape to quit. \\ \\----------------------------------------------------- ; try self.addWidget(DrawStaticString.new( self.allocator, 12, help_h, self.screen_w - 12 * 2, self.screen_h - bottom_padding - help_h, text, 0, )); }, .main => { if (self.script_error) |script_error| { try self.addWidget(DrawStaticString.new( self.allocator, 12, fontchar_h + 13, self.screen_w - 12 * 2, self.screen_h - bottom_padding - waveform_height - (fontchar_h + 13), script_error, 0, )); } else { try self.addWidget(DrawStaticString.new( self.allocator, 12, fontchar_h + 13, self.screen_w - 12 * 2, self.screen_h - bottom_padding - waveform_height - (fontchar_h + 13), example.DESCRIPTION, 0, )); } try self.addWidget(DrawWaveform.new( self.allocator, 0, self.screen_h - bottom_padding - waveform_height, self.screen_w, waveform_height, )); try self.addWidget(DrawSpectrum.new( self.allocator, 0, self.screen_h - bottom_padding - waveform_height - fft_height, self.screen_w, fft_height, )); }, .oscil => { const height = 350; try self.addWidget(DrawOscilloscope.new( self.allocator, 0, self.screen_h - bottom_padding - height, self.screen_w, height, )); }, .full_fft => { try self.addWidget(DrawSpectrumFull.new( self.allocator, 0, fontchar_h, self.screen_w, self.screen_h - fontchar_h - fontchar_h, )); }, } try self.addWidget(DrawRecorderState.new( self.allocator, 0, self.screen_h - fontchar_h, self.screen_w, fontchar_h, )); } pub fn setState(self: *Visuals, state: State) void { self.clearWidgets(); self.state = state; self.addWidgets() catch |err| { std.debug.warn("error while initializing widgets: {}\n", .{err}); }; self.clear = true; } pub fn toggleLogarithmicFFT(self: *Visuals) void { self.logarithmic_fft = !self.logarithmic_fft; } pub fn setScriptError(self: *Visuals, script_error: ?[]const u8) void { self.script_error = script_error; } // called on the audio thread. // return true if a redraw should be triggered pub fn newInput(self: *Visuals, samples: []const f32, mul: f32, sr: f32, oscil_freq: ?[]const f32) bool { var redraw = false; var j: usize = 0; while (j < samples.len / 1024) : (j += 1) { const output = samples[j * 1024 .. j * 1024 + 1024]; for (self.widgets.items) |widget| { if (widget.*.plotFn(widget, output, mul, self.logarithmic_fft, sr, oscil_freq)) { redraw = true; } } } return redraw; } // called on the main thread with the audio thread locked pub fn blit(self: *Visuals, screen: Screen, ctx: BlitContext) void { if (self.clear) { self.clear = false; drawFill(screen, .{ .x = 0, .y = 0, .w = screen.width, .h = screen.height }, 0); } for (self.widgets.items) |widget| { widget.*.blitFn(widget, screen, ctx); } } };
examples/visual.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const interface = @import("interface.zig"); //; const HunkSide = struct { const Self = @This(); const VTable = struct { alloc: fn (*Self, usize, u29) Allocator.Error![]u8, deinitMemory: fn (*Self, usize) void, }; impl: interface.Impl, vtable: *const VTable, hunk: *Hunk, allocator: Allocator, mark: usize, pub fn init(hunk: *Hunk, impl: interface.Impl, vtable: *const VTable) Self { return .{ .impl = impl, .vtable = vtable, .hunk = hunk, .allocator = .{ .allocFn = allocFn, .resizeFn = resizeFn, }, .mark = 0, }; } pub fn getMark(self: *Self) usize { return self.mark; } pub fn freeToMark(self: *Self, mark: usize) void { assert(mark <= self.mark); if (mark == self.mark) return; if (builtin.mode == builtin.Mode.Debug) { self.vtable.deinitMemory(self, mark); } self.mark = mark; } fn allocFn( allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize, ) Allocator.Error![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const real_len = if (len_align == 0) len else blk: { break :blk std.mem.alignBackwardAnyAlign(len, len_align); }; return self.vtable.alloc(self, real_len, ptr_align); } fn resizeFn( allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize, ) Allocator.Error!usize { if (new_len == 0) { return 0; } else if (new_len <= buf.len) { return std.mem.alignAllocLen(buf.len, new_len, len_align); } else { // TODO interesting idea would be to allow this if resizing the last allocation // only works for low hunk // but would allow for fast realloc of an ArrayList return error.OutOfMemory; } } }; const Hunk = struct { const Self = @This(); const Low = struct { fn alloc(side: *HunkSide, len: usize, ptr_align: u29) Allocator.Error![]u8 { const hunk = side.hunk; const buf_start = @ptrToInt(hunk.buffer.ptr); const adj_idx = std.mem.alignForward(buf_start + hunk.low.mark, ptr_align) - buf_start; const next_mark = adj_idx + len; if (next_mark > hunk.buffer.len - hunk.high.mark) { return error.OutOfMemory; } const ret = hunk.buffer[adj_idx..next_mark]; hunk.low.mark += len; return ret; } fn deinitMemory(side: *HunkSide, mark: usize) void { const hunk = side.hunk; std.mem.set(u8, hunk.buffer[mark..side.mark], undefined); } pub fn hunkSide(hunk: *Hunk) HunkSide { return HunkSide.init( hunk, interface.Impl.init(&Low{}), &comptime HunkSide.VTable{ .alloc = alloc, .deinitMemory = deinitMemory, }, ); } }; const High = struct { pub fn alloc(side: *HunkSide, len: usize, ptr_align: u29) Allocator.Error![]u8 { const hunk = side.hunk; const buf_start = @ptrToInt(hunk.buffer.ptr); const buf_end = buf_start + hunk.buffer.len; const adj_idx = std.mem.alignBackward(buf_end - hunk.high.mark, ptr_align) - buf_start; const next_mark = adj_idx - len; if (next_mark < hunk.low.mark) { return error.OutOfMemory; } const ret = hunk.buffer[next_mark..adj_idx]; hunk.high.mark += len; return ret; } pub fn deinitMemory(side: *HunkSide, mark: usize) void { const hunk = side.hunk; const start = hunk.buffer.len - side.mark; const end = hunk.buffer.len - mark; std.mem.set(u8, hunk.buffer[start..end], undefined); } pub fn hunkSide(hunk: *Hunk) HunkSide { return HunkSide.init( hunk, interface.Impl.init(&High{}), &comptime HunkSide.VTable{ .alloc = alloc, .deinitMemory = deinitMemory, }, ); } }; buffer: []u8, low: HunkSide, high: HunkSide, pub fn init(self: *Self, buffer: []u8) void { self.buffer = buffer; self.low = Low.hunkSide(self); self.high = High.hunkSide(self); } }; // tests === const testing = std.testing; const expect = testing.expect; test "hunk" { var buffer: [20]u8 = undefined; var hunk: Hunk = undefined; hunk.init(buffer[0..]); { expect(hunk.high.getMark() == 0); _ = try hunk.high.allocator.alloc(u8, 3); expect(hunk.high.getMark() == 3); const mark = hunk.high.getMark(); _ = try hunk.high.allocator.alloc(u8, 3); expect(hunk.high.getMark() == 6); hunk.high.freeToMark(mark); expect(hunk.high.getMark() == 3); } { expect(hunk.low.getMark() == 0); _ = try hunk.low.allocator.alloc(u8, 3); expect(hunk.low.getMark() == 3); const mark = hunk.low.getMark(); _ = try hunk.low.allocator.alloc(u8, 3); expect(hunk.low.getMark() == 6); hunk.low.freeToMark(mark); expect(hunk.low.getMark() == 3); } hunk.low.freeToMark(0); hunk.high.freeToMark(0); { _ = try hunk.low.allocator.alloc(u8, 10); const mark = hunk.high.getMark(); _ = try hunk.high.allocator.alloc(u8, 10); testing.expectError(error.OutOfMemory, hunk.high.allocator.alloc(u8, 1)); testing.expectError(error.OutOfMemory, hunk.low.allocator.alloc(u8, 1)); hunk.high.freeToMark(mark); _ = try hunk.high.allocator.alloc(u8, 1); _ = try hunk.low.allocator.alloc(u8, 1); } }
src/hunk.zig
const std = @import("std"); const mem = std.mem; const ascii = std.ascii; const fmt = std.fmt; const warn = std.debug.warn; const svd = @import("svd.zig"); var line_buffer: [1024 * 1024]u8 = undefined; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; var args = std.process.args(); _ = args.next(allocator); // skip application name // Note memory will be freed on exit since using arena const file_name = try args.next(allocator) orelse return error.MandatoryFilenameArgumentNotGiven; const file = try std.fs.cwd().openFile(file_name, .{ .read = true, .write = false }); const stream = &file.inStream(); var state = SvdParseState.Device; var dev = try svd.Device.init(allocator); while (try stream.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| { if (line.len == 0) { break; } var chunk = getChunk(line) orelse continue; switch (state) { .Device => { if (ascii.eqlIgnoreCase(chunk.tag, "/device")) { state = .Finished; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { try dev.name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "version")) { if (chunk.data) |data| { try dev.version.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "description")) { if (chunk.data) |data| { try dev.description.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "cpu")) { var cpu = try svd.Cpu.init(allocator); dev.cpu = cpu; state = .Cpu; } else if (ascii.eqlIgnoreCase(chunk.tag, "addressUnitBits")) { if (chunk.data) |data| { dev.address_unit_bits = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "width")) { if (chunk.data) |data| { dev.max_bit_width = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "size")) { if (chunk.data) |data| { dev.reg_default_size = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "resetValue")) { if (chunk.data) |data| { dev.reg_default_reset_value = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "resetMask")) { if (chunk.data) |data| { dev.reg_default_reset_mask = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "peripherals")) { state = .Peripherals; } }, .Cpu => { if (ascii.eqlIgnoreCase(chunk.tag, "/cpu")) { state = .Device; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { try dev.cpu.?.name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "revision")) { if (chunk.data) |data| { try dev.cpu.?.revision.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "endian")) { if (chunk.data) |data| { try dev.cpu.?.endian.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "mpuPresent")) { if (chunk.data) |data| { dev.cpu.?.mpu_present = textToBool(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "fpuPresent")) { if (chunk.data) |data| { dev.cpu.?.fpu_present = textToBool(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "nvicPrioBits")) { if (chunk.data) |data| { dev.cpu.?.nvic_prio_bits = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "vendorSystickConfig")) { if (chunk.data) |data| { dev.cpu.?.vendor_systick_config = textToBool(data); } } }, .Peripherals => { if (ascii.eqlIgnoreCase(chunk.tag, "/peripherals")) { state = .Device; } else if (ascii.eqlIgnoreCase(chunk.tag, "peripheral")) { if (chunk.derivedFrom) |derivedFrom| { for (dev.peripherals.toSliceConst()) |periph_being_checked| { if (periph_being_checked.name.eql(derivedFrom)) { try dev.peripherals.append(try periph_being_checked.copy(allocator)); state = .Peripheral; break; } } } else { var periph = try svd.Peripheral.init(allocator); try dev.peripherals.append(periph); state = .Peripheral; } } }, .Peripheral => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); if (ascii.eqlIgnoreCase(chunk.tag, "/peripheral")) { state = .Peripherals; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { // periph could be copy, must update periph name in sub-fields try cur_periph.name.replaceContents(data); for (cur_periph.registers.toSlice()) |*reg| { try reg.periph_containing.replaceContents(data); for (reg.fields.toSlice()) |*field| { try field.periph.replaceContents(data); } } } } else if (ascii.eqlIgnoreCase(chunk.tag, "description")) { if (chunk.data) |data| { try cur_periph.description.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "groupName")) { if (chunk.data) |data| { try cur_periph.group_name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "baseAddress")) { if (chunk.data) |data| { cur_periph.base_address = parseHexLiteral(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "addressBlock")) { if (cur_periph.address_block) |x| { // do nothing } else { var block = try svd.AddressBlock.init(allocator); cur_periph.address_block = block; } state = .AddressBlock; } else if (ascii.eqlIgnoreCase(chunk.tag, "interrupt")) { var interrupt = try svd.Interrupt.init(allocator); try dev.interrupts.append(interrupt); state = .Interrupt; } else if (ascii.eqlIgnoreCase(chunk.tag, "registers")) { state = .Registers; } }, .AddressBlock => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); var address_block = &cur_periph.address_block.?; if (ascii.eqlIgnoreCase(chunk.tag, "/addressBlock")) { state = .Peripheral; } else if (ascii.eqlIgnoreCase(chunk.tag, "offset")) { if (chunk.data) |data| { address_block.offset = parseHexLiteral(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "size")) { if (chunk.data) |data| { address_block.size = parseHexLiteral(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "usage")) { if (chunk.data) |data| { try address_block.usage.replaceContents(data); } } }, .Interrupt => { const int_slice = dev.interrupts.toSlice(); var cur_interrupt = &int_slice[int_slice.len - 1]; if (ascii.eqlIgnoreCase(chunk.tag, "/interrupt")) { state = .Peripheral; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { try cur_interrupt.name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "description")) { if (chunk.data) |data| { try cur_interrupt.description.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "value")) { if (chunk.data) |data| { cur_interrupt.value = fmt.parseInt(u32, data, 10) catch null; } } }, .Registers => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); if (ascii.eqlIgnoreCase(chunk.tag, "/registers")) { state = .Peripheral; } else if (ascii.eqlIgnoreCase(chunk.tag, "register")) { if (cur_periph.base_address == null) break; const base_address = cur_periph.base_address.?; const reset_value = dev.reg_default_reset_value orelse 0; const size = dev.reg_default_size orelse 32; var register = try svd.Register.init(allocator, cur_periph.name.toSliceConst(), base_address, reset_value, size); try cur_periph.registers.append(register); state = .Register; } }, .Register => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); var cur_reg = cur_periph.registers.ptrAt(cur_periph.registers.toSliceConst().len - 1); if (ascii.eqlIgnoreCase(chunk.tag, "/register")) { state = .Registers; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { try cur_reg.name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "displayName")) { if (chunk.data) |data| { try cur_reg.display_name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "description")) { if (chunk.data) |data| { try cur_reg.description.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "addressOffset")) { if (chunk.data) |data| { cur_reg.address_offset = parseHexLiteral(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "size")) { if (chunk.data) |data| { cur_reg.size = parseHexLiteral(data) orelse cur_reg.size; } } else if (ascii.eqlIgnoreCase(chunk.tag, "access")) { if (chunk.data) |data| { cur_reg.access = parseAccessValue(data) orelse cur_reg.access; } } else if (ascii.eqlIgnoreCase(chunk.tag, "resetValue")) { if (chunk.data) |data| { cur_reg.reset_value = parseHexLiteral(data) orelse cur_reg.reset_value; // TODO: test orelse break } } else if (ascii.eqlIgnoreCase(chunk.tag, "fields")) { state = .Fields; } }, .Fields => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); var cur_reg = cur_periph.registers.ptrAt(cur_periph.registers.toSliceConst().len - 1); if (ascii.eqlIgnoreCase(chunk.tag, "/fields")) { state = .Register; } else if (ascii.eqlIgnoreCase(chunk.tag, "field")) { var field = try svd.Field.init(allocator, cur_periph.name.toSliceConst(), cur_reg.name.toSliceConst()); try cur_reg.fields.append(field); state = .Field; } }, .Field => { var cur_periph = dev.peripherals.ptrAt(dev.peripherals.toSliceConst().len - 1); var cur_reg = cur_periph.registers.ptrAt(cur_periph.registers.toSliceConst().len - 1); var cur_field = cur_reg.fields.ptrAt(cur_reg.fields.toSliceConst().len - 1); if (ascii.eqlIgnoreCase(chunk.tag, "/field")) { state = .Fields; } else if (ascii.eqlIgnoreCase(chunk.tag, "name")) { if (chunk.data) |data| { try cur_field.name.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "description")) { if (chunk.data) |data| { try cur_field.description.replaceContents(data); } } else if (ascii.eqlIgnoreCase(chunk.tag, "bitOffset")) { if (chunk.data) |data| { cur_field.bit_offset = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "bitWidth")) { if (chunk.data) |data| { cur_field.bit_width = fmt.parseInt(u32, data, 10) catch null; } } else if (ascii.eqlIgnoreCase(chunk.tag, "access")) { if (chunk.data) |data| { cur_field.access = parseAccessValue(data) orelse cur_field.access; } } }, .Finished => { // wait for EOF }, } } if (state == .Finished) { try std.io.getStdOut().outStream().print("{}\n", .{dev}); } else { return error.InvalidXML; } } const SvdParseState = enum { Device, Cpu, Peripherals, Peripheral, AddressBlock, Interrupt, Registers, Register, Fields, Field, Finished, }; const XmlChunk = struct { tag: []const u8, data: ?[]const u8, derivedFrom: ?[]const u8, }; fn getChunk(line: []const u8) ?XmlChunk { var chunk = XmlChunk{ .tag = undefined, .data = null, .derivedFrom = null, }; var trimmed = mem.trim(u8, line, " \n"); var toker = mem.tokenize(trimmed, "<>"); //" =\n<>\""); if (toker.next()) |maybe_tag| { var tag_toker = mem.tokenize(maybe_tag, " =\""); chunk.tag = tag_toker.next() orelse return null; if (tag_toker.next()) |maybe_tag_property| { if (ascii.eqlIgnoreCase(maybe_tag_property, "derivedFrom")) { chunk.derivedFrom = tag_toker.next(); } } } else { return null; } if (toker.next()) |chunk_data| { chunk.data = chunk_data; } return chunk; } test "getChunk" { const valid_xml = " <name>STM32F7x7</name> \n"; const expected_chunk = XmlChunk{ .tag = "name", .data = "STM32F7x7", .derivedFrom = null }; const chunk = getChunk(valid_xml).?; std.testing.expectEqualSlices(u8, chunk.tag, expected_chunk.tag); std.testing.expectEqualSlices(u8, chunk.data.?, expected_chunk.data.?); const no_data_xml = " <name> \n"; const expected_no_data_chunk = XmlChunk{ .tag = "name", .data = null, .derivedFrom = null }; const no_data_chunk = getChunk(no_data_xml).?; std.testing.expectEqualSlices(u8, no_data_chunk.tag, expected_no_data_chunk.tag); std.testing.expectEqual(no_data_chunk.data, expected_no_data_chunk.data); const comments_xml = "<description>Auxiliary Cache Control register</description>"; const expected_comments_chunk = XmlChunk{ .tag = "description", .data = "Auxiliary Cache Control register", .derivedFrom = null }; const comments_chunk = getChunk(comments_xml).?; std.testing.expectEqualSlices(u8, comments_chunk.tag, expected_comments_chunk.tag); std.testing.expectEqualSlices(u8, comments_chunk.data.?, expected_comments_chunk.data.?); const derived = " <peripheral derivedFrom=\"TIM10\">"; const expected_derived_chunk = XmlChunk{ .tag = "peripheral", .data = null, .derivedFrom = "TIM10" }; const derived_chunk = getChunk(derived).?; std.testing.expectEqualSlices(u8, derived_chunk.tag, expected_derived_chunk.tag); std.testing.expectEqualSlices(u8, derived_chunk.derivedFrom.?, expected_derived_chunk.derivedFrom.?); std.testing.expectEqual(derived_chunk.data, expected_derived_chunk.data); } fn textToBool(data: []const u8) ?bool { if (ascii.eqlIgnoreCase(data, "true")) { return true; } else if (ascii.eqlIgnoreCase(data, "false")) { return false; } else { return null; } } fn parseHexLiteral(data: []const u8) ?u32 { if (data.len <= 2) return null; return fmt.parseInt(u32, data[2..], 16) catch null; } fn parseAccessValue(data: []const u8) ?svd.Access { if (ascii.eqlIgnoreCase(data, "read-write")) { return .ReadWrite; } else if (ascii.eqlIgnoreCase(data, "read-only")) { return .ReadOnly; } else if (ascii.eqlIgnoreCase(data, "write-only")) { return .WriteOnly; } return null; }
src/main.zig
const std = @import("std"); const ArrayList = std.ArrayList; const md5 = std.crypto.hash.Md5; const VEC_SIZE = 8; const Vec = std.meta.Vector(VEC_SIZE, f64); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var global_allocator = gpa.allocator(); pub fn main() !void { const n = try get_n(); const size = (n + VEC_SIZE - 1) / VEC_SIZE * VEC_SIZE; const chunk_size = size / VEC_SIZE; const inv = 2.0 / @intToFloat(f64, size); var xloc = ArrayList(Vec).init(global_allocator); try xloc.ensureTotalCapacityPrecise(chunk_size); var i: usize = 0; while (i < chunk_size) : (i += 1) { const offset = i * VEC_SIZE; const v = Vec{ init_xloc(offset, inv), init_xloc(offset + 1, inv), init_xloc(offset + 2, inv), init_xloc(offset + 3, inv), init_xloc(offset + 4, inv), init_xloc(offset + 5, inv), init_xloc(offset + 6, inv), init_xloc(offset + 7, inv), }; try xloc.append(v); } const stdout = std.io.getStdOut().writer(); try stdout.print("P4\n{d} {d}\n", .{ size, size }); var pixels = ArrayList(u8).init(global_allocator); try pixels.ensureTotalCapacityPrecise(size * chunk_size); var y: usize = 0; while (y < size) : (y += 1) { const ci = @intToFloat(f64, y) * inv - 1.0; var x: usize = 0; while (x < chunk_size) : (x += 1) { const r = mbrot8(xloc.items[x], ci); try pixels.append(r); } } // try stdout.print("{}\n", .{pixels}); var hash: [16]u8 = undefined; md5.hash(pixels.items, &hash, .{}); try stdout.print("{}\n", .{std.fmt.fmtSliceHexLower(&hash)}); } fn mbrot8(cr: Vec, civ: f64) u8 { const ci = @splat(VEC_SIZE, civ); const zero: f64 = 0.0; var zr = @splat(VEC_SIZE, zero); var zi = @splat(VEC_SIZE, zero); var tr = @splat(VEC_SIZE, zero); var ti = @splat(VEC_SIZE, zero); var absz = @splat(VEC_SIZE, zero); var _i: u8 = 0; while (_i < 10) : (_i += 1) { var _j: u8 = 0; while (_j < 5) : (_j += 1) { zi = (zr + zr) * zi + ci; zr = tr - ti + cr; tr = zr * zr; ti = zi * zi; } absz = tr + ti; var terminate = true; var i: u8 = 0; while (i < VEC_SIZE) : (i += 1) { if (absz[i] <= 4.0) { terminate = false; break; } } if (terminate) { return 0; } } var accu: u8 = 0; var i: u8 = 0; while (i < VEC_SIZE) : (i += 1) { if (absz[i] <= 4.0) { const lhs: u8 = 0x80; accu |= (lhs >> @intCast(u3, i)); } } return accu; } fn init_xloc(i: usize, inv: f64) f64 { return @intToFloat(f64, i) * inv - 1.5; } fn get_n() !usize { var arg_it = std.process.args(); _ = arg_it.skip(); const arg = arg_it.next() orelse return 200; return try std.fmt.parseInt(usize, arg, 10); }
bench/algorithm/mandelbrot/1.zig
const uefi = @import("std").os.uefi; const fmt = @import("std").fmt; const GraphicsOutputProtocol = uefi.protocols.GraphicsOutputProtocol; const GraphicsOutputBltPixel = uefi.protocols.GraphicsOutputBltPixel; const GraphicsOutputBltOperation = uefi.protocols.GraphicsOutputBltOperation; // Assigned in main(). var con_out: *uefi.protocols.SimpleTextOutputProtocol = undefined; // We need to print each character in an [_]u8 individually because EFI // encodes strings as UCS-2. fn puts(msg: []const u8) void { for (msg) |c| { const c_ = [2]u16{ c, 0 }; // work around https://github.com/ziglang/zig/issues/4372 _ = con_out.outputString(@ptrCast(*const [1:0]u16, &c_)); } } fn printf(buf: []u8, comptime format: []const u8, args: anytype) void { puts(fmt.bufPrint(buf, format, args) catch unreachable); } pub fn main() void { con_out = uefi.system_table.con_out.?; const boot_services = uefi.system_table.boot_services.?; _ = con_out.reset(false); // We're going to use this buffer to format strings. var buf: [100]u8 = undefined; // Graphics output? var graphics_output_protocol: ?*uefi.protocols.GraphicsOutputProtocol = undefined; if (boot_services.locateProtocol(&uefi.protocols.GraphicsOutputProtocol.guid, null, @ptrCast(*?*c_void, &graphics_output_protocol)) == uefi.Status.Success) { puts("*** graphics output protocol is supported!\r\n"); // Check supported resolutions: _ = graphics_output_protocol.?.setMode(23); const mode = graphics_output_protocol.?.mode; printf(buf[0..], " current mode = {}\r\n", .{graphics_output_protocol.?.mode.mode}); var j : u32 = 0; var c = [1]GraphicsOutputBltPixel{GraphicsOutputBltPixel{ .blue = 0x00, .green = 0xaa, .red = 0x00, .reserved = 0 }}; while (j < 16) : (j += 1) { _ = graphics_output_protocol.?.blt(&c, GraphicsOutputBltOperation.BltVideoFill, 0, 0, j * mode.info.horizontal_resolution / 16, j * mode.info.horizontal_resolution / 16, mode.info.horizontal_resolution / 16, mode.info.vertical_resolution / 16, 0); } } else { puts("*** graphics output protocol is NOT supported :(\r\n"); } _ = boot_services.stall(20 * 1000 * 1000); }
boot/efi_x86_64/main.zig
const std = @import("std"); usingnamespace @import("util"); usingnamespace @import("source.zig"); usingnamespace @import("log.zig"); const Allocator = std.mem.Allocator; pub const Token = struct { class: Class, text: []const u8, line: Source.Line, pub const Class = enum { invalid, symbol, name, keyword, builtin, number, comment, space, line_end, }; const Self = @This(); pub fn sourceToken(self: Self) Source.Token { return self.line.tokenFromSlice(self.text); } pub const keywords = [_][]const u8{ "let", "vert", "frag", "out", }; pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { const sw = ansi.styledWriter(writer); if (self.class == .line_end) { try sw.write("\n"); } else { switch(self.class) { .invalid => try sw.foreground(.red_light), .symbol => try sw.foreground(.yellow), .name => try sw.foreground(.green), .keyword => try sw.foreground(.blue_light), .builtin => try sw.foreground(.cyan_light), .number => try sw.foreground(.magenta), .comment => try sw.foreground(.black_light), else => {}, } for (self.text) |char| { const is_printable = std.ascii.isGraph(char) or char == ' '; if (is_printable) { try sw.print("{c}", .{char}); } else { try sw.invert(); try sw.print("[{X:0>2}]", .{char}); try sw.noInvert(); } } // try ansi.printEscaped(writer, style, "{}", .{ log.esc(self.text) }); try sw.none(); } } }; pub const TokenStream = struct { source: Source.Ptr, token: Token, rest_text: []const u8, log_errors: bool = true, const Self = @This(); pub fn initFromSource(source: Source.Ptr) Self { return init(source, source.text); } pub fn iniFromLine(line: Source.Line) Self { return init(line.source, line.text()); } fn init(source: Source.Ptr, text: []const u8) Self { var token_text: []const u8 = source.text; token_text.len = 0; return Self { .source = source, .rest_text = text, .token = Token { .class = .invalid, .text = token_text, .line = Source.Line { .source = source, .index = 0, .start = 0, }, }, }; } pub fn deinit(self: *Self) void { } /// advance stream index by `len` /// if remaining text is shorter than `len`, advance to the end fn advance(self: *Self, len: usize) void { const actual_len = std.math.min(len, self.rest_text.len); if (self.token.text.len == 0) { self.token.text = self.rest_text[0..actual_len]; } else { self.token.text.len += actual_len; } self.rest_text = self.rest_text[actual_len..]; } /// consume and return the next up to `len` characters of the remaining text /// if remaining text is shorter than len, consume and return the entire remaining text fn read(self: *Self, len: usize) []const u8 { const result = self.peek(len); defer self.advance(result.len); return result; } /// return the next `len` available characters of the remaining text /// if remaining text is shorter than len, return the entire remaining text /// no text is consumed, the index does not move fn peek(self: Self, len: usize) []const u8 { const actual_len = std.math.min(len, self.rest_text.len); return self.rest_text[0..actual_len]; } pub fn next(self: *Self) ?Token { if (self.rest_text.len == 0) { return null; } else { self.advance(1); const char = self.token.text[0]; switch (char) { 0 => return self.emitInvalid("null byte", .{}), '\n', '\r' => { if (char == '\n' or self.matchOptionalString("\n")) { return self.emit(.line_end); } else { return self.emitInvalid("lone carriage return", .{}); } }, '\t' => return self.emitInvalid("tab characters are not allowed", .{}), ' ' => { _ = self.matchManyChar(' '); return self.emit(.space); }, '`' => { _ = self.matchManyClass(charclass.notLineEnd); return self.emit(.comment); }, '(', ')', '{', '}', ',', '.', ':', '+', '-', '*', '/', '=', => return self.emit(.symbol), '0'...'9' => { if (char == '0' and self.matchOptionalString("x")) { // hex if (self.matchManyClass(charclass.hexDigit).len == 0) { return self.emitInvalid("hex number literal missing digits", .{}); } return self.emit(.number); } else { // decimal _ = self.matchManyClass(charclass.digit); if (self.matchOptionalString(".")) { if (self.matchManyClass(charclass.digit).len == 0) { return self.emitInvalid("decimal number literal missing fractional digits", .{}); } } return self.emit(.number); } }, else => { if (charclass.name(char) or char == '@') { _ = self.matchManyClass(charclass.name); if (char == '@') { return self.emit(.builtin); } else { inline for (Token.keywords) |keyword| { if (std.mem.eql(u8, keyword, self.token.text)) { return self.emit(.keyword); } } return self.emit(.name); } } else { if (std.ascii.isGraph(char)) { return self.emitInvalid("invalid character", .{}); } else { return self.emitInvalid("invalid character byte '\\x{X}'", .{char}); } } }, } } } /// lex the rest of the file, logging any errors found pub fn rest(self: *Self) void { while (self.next()) |_| {} } pub const charclass = struct { pub fn valid(char: u8) bool { return std.ascii.isGraph(char) or char == ' '; } pub fn name(char: u8) bool { return switch (char) { 'a'...'z', 'A'...'Z', '0'...'9', '_' => true, else => false, }; } pub fn digit(char: u8) bool { return char >= '0' and char <= '9'; } pub fn hexDigit(char: u8) bool { return switch (char) { '0'...'9', 'a'...'f', 'A'...'F', => true, else => false, }; } pub fn lineEnd(char: u8) bool { return switch (char) { '\n', '\r' => true, else => false, }; } pub fn notLineEnd(char: u8) bool { return valid(char) and !lineEnd(char); } }; const CharClass = fn (u8) bool; fn matchManyClass(self: *Self, comptime char_class: CharClass) []const u8 { var len: usize = undefined; for (self.rest_text) |char, i| { len = i; if (!char_class(char)) { break; } } return self.read(len); } fn matchManyChar(self: *Self, comptime char: u8) []const u8 { return self.matchManyClass(struct { fn _(c: u8) bool { return c == char; } }._); } fn matchOptionalString(self: *Self, string: []const u8) bool { if (std.mem.eql(u8, string, self.peek(string.len))) { self.advance(string.len); return true; } else { return false; } } fn emit(self: *Self, comptime class: Token.Class) Token { var result = self.token; result.class = class; if (class == .line_end) { self.token.line.index += 1; self.token.line.start = @ptrToInt(self.rest_text.ptr) - @ptrToInt(self.source.text.ptr); } self.token.text = self.rest_text[0..0]; return result; } fn emitInvalid(self: *Self, comptime fmt: []const u8, args: anytype) Token { if (self.log_errors) { log.logSourceToken(.err, self.token.sourceToken(), fmt, args) catch unreachable; } return self.emit(.invalid); } }; const st = std.testing; test { // const source = try Source.createFromBytes(st.allocator, "foo bar baz"); const source = try Source.createFromFile(st.allocator, "sample/sample.umbra"); defer source.destroy(); var tokens = TokenStream.initFromSource(source); defer tokens.deinit(); tokens.log_errors = false; const writer = std.io.getStdErr().writer(); while (tokens.next()) |token| { try writer.print("{}", .{token}); } try writer.writeByte('\n'); var tokens_errors = TokenStream.initFromSource(source); defer tokens_errors.deinit(); tokens_errors.rest(); }
src/compile/token.zig
const std = @import("std"); const Allocator = std.mem.Allocator; //; const lib = @import("lib.zig"); usingnamespace lib; const builtins = @import("builtins.zig"); pub fn readFile(allocator: *Allocator, filename: []const u8) ![]u8 { var file = try std.fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); return file.readToEndAlloc(allocator, std.math.maxInt(usize)); } pub fn something(allocator: *Allocator) !void { var to_load: ?[:0]u8 = null; var i: usize = 0; var args = std.process.args(); while (args.next(allocator)) |arg_err| { const arg = try arg_err; if (i == 1) { to_load = arg; } else { allocator.free(arg); } i += 1; } var vm = try VM.init(allocator); defer vm.deinit(); try vm.installBaseLib(); //; var f = try readFile(allocator, to_load orelse "tests/test.orth"); defer allocator.free(f); var t = try vm.loadString(f); defer t.deinit(); // t.enable_tco = false; while (true) { var running = t.step() catch |err| { switch (err) { error.WordNotFound => { std.log.warn("word not found: {}", .{t.error_info.word_not_found}); t.printStackTrace(); return; // return err; }, else => { std.log.warn("err: {}", .{err}); t.printStackTrace(); // return; return err; }, } }; if (!running) break; } // std.debug.print("max stack: {}\n", .{t.stack.max}); // std.debug.print("max ret stack: {}\n", .{t.return_stack.max}); // std.debug.print("max res stack: {}\n", .{t.restore_stack.max}); if (to_load) |l| { allocator.free(l); } } test "main" { std.debug.print("\n", .{}); try something(std.testing.allocator); } pub fn main() !void { try something(std.heap.c_allocator); }
src/main.zig
const std = @import("std"); const audiometa = @import("audiometa"); const fmtUtf8SliceEscapeUpper = audiometa.util.fmtUtf8SliceEscapeUpper; const meta = audiometa.metadata; const AllMetadata = meta.AllMetadata; const MetadataMap = meta.MetadataMap; const Allocator = std.mem.Allocator; const start_testing_at_prefix = ""; // ffmpeg fails to parse unsynchronised tags correctly // in these files, its a MCDI frame followed by a TLEN frame // ffmpeg reads len bytes directly instead of unsynching and then reading len bytes // so it falls (num unsynched bytes in the frame) short when reading the next frame // this is the relevant bug but it was closed as invalid (incorrectly, AFAICT): // https://trac.ffmpeg.org/ticket/4 const ffmpeg_unsync_bugged_files = std.ComptimeStringMap(void, .{ .{"Doomed Future Today/14 - Bombs (Version).mp3"}, .{"Living Through The End Time/13 - Imaginary Friend.mp3"}, }); const ffprobe_unusable_output_files = std.ComptimeStringMap(void, .{ // TODO: possible outputting issue, ? in ffprobe output .{"Simbiose - 2009 - Fake Dimension/13-simbiose-evolucao_e_regressao.mp3"}, }); test "music folder" { const allocator = std.testing.allocator; var dir = try std.fs.cwd().openDir("/media/drive4/music/", .{ .iterate = true }); var walker = try dir.walk(allocator); defer walker.deinit(); var testing_started = false; while (try walker.next()) |entry| { if (!testing_started) { if (std.mem.startsWith(u8, entry.path, start_testing_at_prefix)) { testing_started = true; } else { continue; } } if (entry.kind != .File) continue; if (ffmpeg_unsync_bugged_files.has(entry.path)) continue; if (ffprobe_unusable_output_files.has(entry.path)) continue; // TODO: fairly unsolvable, these use a TXXX field with "album " as the name, which is impossible // to distinguish from "album" when parsing the ffprobe output. Maybe using ffmpeg -f ffmetadata // might be better? if (std.mem.startsWith(u8, entry.path, "Sonic Cathedrals Vol. XLVI Curated by Age of Collapse/")) continue; const extension = std.fs.path.extension(entry.basename); const is_mp3 = std.mem.eql(u8, extension, ".mp3"); const is_flac = std.mem.eql(u8, extension, ".flac"); const readable = is_mp3 or is_flac; if (!readable) continue; std.debug.print("\n{s}\n", .{fmtUtf8SliceEscapeUpper(entry.path)}); var expected_metadata = getFFProbeMetadata(allocator, entry.dir, entry.basename) catch |e| switch (e) { error.NoMetadataFound => MetadataArray.init(allocator), else => return e, }; defer expected_metadata.deinit(); var file = try entry.dir.openFile(entry.basename, .{}); defer file.close(); // skip zero sized files const size = (try file.stat()).size; if (size == 0) continue; var stream_source = std.io.StreamSource{ .file = file }; var metadata = try meta.readAll(allocator, &stream_source); defer metadata.deinit(); var coalesced_metadata = try coalesceMetadata(allocator, &metadata); defer coalesced_metadata.deinit(); try compareMetadata(allocator, &expected_metadata, &coalesced_metadata); } } const ignored_fields = std.ComptimeStringMap(void, .{ .{"encoder"}, .{"comment"}, // TODO .{"UNSYNCEDLYRICS"}, // TODO multiline ffprobe parsing .{"unsyncedlyrics"}, // ^ .{"LYRICS"}, // ^ .{"COVERART"}, // multiline but also binary, so probably more than just multiline parsing is needed, see Deathrats - 7 inch/ .{"CODING_HISTORY"}, // TODO multiline ffprobe parsing, see Miserable-Uncontrollable-2016-WEB-FLAC/05 Stranger.flac .{"genre"}, // TODO parse (n) at start and convert it to genre .{"Track"}, // weird Track:Comment field name that explodes things .{"ID3v1 Comment"}, // this came from a COMM frame .{"MusicMatch_TrackArtist"}, // this came from a COMM frame .{"CDDB Disc ID"}, // this came from a COMM frame .{"ID3v1"}, // this came from a COMM frame .{"c0"}, // this came from a COMM frame .{"Media Jukebox"}, // this came from a COMM frame .{"l assault cover"}, // this came from a weird COMM frame .{"http"}, // this came from a weird COMM frame .{"MusicMatch_Preference"}, // this came from a COMM frame .{"Songs-DB_Custom1"}, // this came from a COMM frame .{"Comments"}, // this came from a COMM frame .{"Checksum"}, // this came from a COMM frame .{"Songs-DB_Custom5"}, // this came from a COMM frame .{"oso"}, // this came from a COMM frame }); pub fn coalesceMetadata(allocator: Allocator, metadata: *AllMetadata) !MetadataMap { var coalesced = meta.MetadataMap.init(allocator); errdefer coalesced.deinit(); if (metadata.flac) |*flac_metadata| { // since flac allows for duplicate fields, ffmpeg concats them with ; // because ffmpeg has a 'no duplicate fields' rule var names_it = flac_metadata.map.name_to_indexes.keyIterator(); while (names_it.next()) |raw_name| { // vorbis metadata fields are case-insensitive, so convert to uppercase // for the lookup var upper_field = try std.ascii.allocUpperString(allocator, raw_name.*); defer allocator.free(upper_field); const name = flac_field_names.get(upper_field) orelse raw_name.*; var joined_value = (try flac_metadata.map.getJoinedAlloc(allocator, raw_name.*, ";")).?; defer allocator.free(joined_value); try coalesced.put(name, joined_value); } } if (coalesced.entries.items.len == 0) { if (metadata.all_id3v2) |all_id3v2| { // Here's an overview of how ffmpeg does things: // 1. add all fields with their unconverted ID without overwriting // (this means that all duplicate fields are ignored) // 2. once all tags are finished reading, convert IDs to their 'ffmpeg name', // allowing overwrites // also it seems like empty values are exempt from overwriting things // even if they would otherwise? I'm not sure where this is coming from, but // it seems like that's the case from the output of ffprobe // // So, we need to basically do the same thing here using a temporary // MetadataMap var metadata_tmp = meta.MetadataMap.init(allocator); defer metadata_tmp.deinit(); for (all_id3v2.tags) |*id3v2_metadata_container| { const id3v2_metadata = &id3v2_metadata_container.metadata.map; for (id3v2_metadata.entries.items) |entry| { if (metadata_tmp.contains(entry.name)) continue; try metadata_tmp.put(entry.name, entry.value); } } for (metadata_tmp.entries.items) |entry| { const converted_name = convertIdToName(entry.name); const name = converted_name orelse entry.name; try coalesced.putOrReplaceFirst(name, entry.value); } try mergeDate(&coalesced); } } if (coalesced.entries.items.len == 0) { if (metadata.id3v1) |*id3v1_metadata| { // just a clone for (id3v1_metadata.map.entries.items) |entry| { try coalesced.put(entry.name, entry.value); } } } return coalesced; } const date_format = "YYYY-MM-DD hh:mm"; fn isValidDateComponent(maybe_date: ?[]const u8) bool { if (maybe_date == null) return false; const date = maybe_date.?; if (date.len != 4) return false; // only 0-9 allowed for (date) |byte| switch (byte) { '0'...'9' => {}, else => return false, }; return true; } fn mergeDate(metadata: *MetadataMap) !void { var date_buf: [date_format.len]u8 = undefined; var date: []u8 = date_buf[0..0]; var year = metadata.getFirst("TYER") orelse metadata.getFirst("TYE"); if (!isValidDateComponent(year)) return; date = date_buf[0..4]; std.mem.copy(u8, date, (year.?)[0..4]); var maybe_daymonth = metadata.getFirst("TDAT") orelse metadata.getFirst("TDA"); if (isValidDateComponent(maybe_daymonth)) { const daymonth = maybe_daymonth.?; date = date_buf[0..10]; // TDAT is DDMM, we want -MM-DD var day = daymonth[0..2]; var month = daymonth[2..4]; _ = try std.fmt.bufPrint(date[4..10], "-{s}-{s}", .{ month, day }); var maybe_time = metadata.getFirst("TIME") orelse metadata.getFirst("TIM"); if (isValidDateComponent(maybe_time)) { const time = maybe_time.?; date = date_buf[0..]; // TIME is HHMM var hours = time[0..2]; var mins = time[2..4]; _ = try std.fmt.bufPrint(date[10..], " {s}:{s}", .{ hours, mins }); } } try metadata.putOrReplaceFirst("date", date); } const flac_field_names = std.ComptimeStringMap([]const u8, .{ .{ "ALBUMARTIST", "album_artist" }, .{ "TRACKNUMBER", "track" }, .{ "DISCNUMBER", "disc" }, .{ "DESCRIPTION", "comment" }, }); const id3v2_34_name_lookup = std.ComptimeStringMap([]const u8, .{ .{ "TALB", "album" }, .{ "TCOM", "composer" }, .{ "TCON", "genre" }, .{ "TCOP", "copyright" }, .{ "TENC", "encoded_by" }, .{ "TIT2", "title" }, .{ "TLAN", "language" }, .{ "TPE1", "artist" }, .{ "TPE2", "album_artist" }, .{ "TPE3", "performer" }, .{ "TPOS", "disc" }, .{ "TPUB", "publisher" }, .{ "TRCK", "track" }, .{ "TSSE", "encoder" }, .{ "USLT", "lyrics" }, }); const id3v2_4_name_lookup = std.ComptimeStringMap([]const u8, .{ .{ "TCMP", "compilation" }, .{ "TDRC", "date" }, .{ "TDRL", "date" }, .{ "TDEN", "creation_time" }, .{ "TSOA", "album-sort" }, .{ "TSOP", "artist-sort" }, .{ "TSOT", "title-sort" }, }); const id3v2_2_name_lookup = std.ComptimeStringMap([]const u8, .{ .{ "TAL", "album" }, .{ "TCO", "genre" }, .{ "TCP", "compilation" }, .{ "TT2", "title" }, .{ "TEN", "encoded_by" }, .{ "TP1", "artist" }, .{ "TP2", "album_artist" }, .{ "TP3", "performer" }, .{ "TRK", "track" }, }); fn convertIdToName(id: []const u8) ?[]const u8 { // this is the order of precedence that ffmpeg does this // it also does not care about the major version, it just converts things unconditionally return id3v2_34_name_lookup.get(id) orelse id3v2_2_name_lookup.get(std.mem.sliceTo(id, '\x00')) orelse id3v2_4_name_lookup.get(id); } fn compareMetadata(allocator: Allocator, expected: *MetadataArray, actual: *MetadataMap) !void { for (expected.array.items) |field| { if (ignored_fields.get(field.name) != null) continue; if (std.mem.startsWith(u8, field.name, "id3v2_priv.")) continue; if (std.mem.startsWith(u8, field.name, "lyrics")) continue; if (std.mem.startsWith(u8, field.name, "iTun")) continue; if (std.mem.startsWith(u8, field.name, "Songs-DB")) continue; if (actual.contains(field.name)) { var num_values = actual.valueCount(field.name).?; // all duplicates should already be coalesced, since ffmpeg hates duplicates std.testing.expectEqual(num_values, 1) catch |e| { std.debug.print("\nexpected:\n", .{}); for (expected.array.items) |_field| { if (std.mem.eql(u8, _field.name, field.name)) { std.debug.print("{s} = {s}\n", .{ fmtUtf8SliceEscapeUpper(_field.name), fmtUtf8SliceEscapeUpper(_field.value) }); } } std.debug.print("\nactual:\n", .{}); var values = (try actual.getAllAlloc(allocator, field.name)).?; defer allocator.free(values); for (values) |val| { std.debug.print("{s} = {s}\n", .{ fmtUtf8SliceEscapeUpper(field.name), fmtUtf8SliceEscapeUpper(val) }); } return e; }; var actual_value = actual.getFirst(field.name).?; std.testing.expectEqualStrings(field.value, actual_value) catch |e| { std.debug.print("field: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); std.debug.print("\nexpected:\n", .{}); for (expected.array.items) |_field| { std.debug.print("{s} = {s}\n", .{ fmtUtf8SliceEscapeUpper(_field.name), fmtUtf8SliceEscapeUpper(_field.value) }); } std.debug.print("\nactual:\n", .{}); actual.dump(); return e; }; } else { std.debug.print("\nmissing field {s}\n", .{field.name}); std.debug.print("\nexpected:\n", .{}); for (expected.array.items) |_field| { std.debug.print("{s} = {s}\n", .{ fmtUtf8SliceEscapeUpper(_field.name), fmtUtf8SliceEscapeUpper(_field.value) }); } std.debug.print("\nactual:\n", .{}); actual.dump(); return error.MissingField; } } } const MetadataArray = struct { allocator: Allocator, array: std.ArrayList(Field), const Field = struct { name: []const u8, value: []const u8, }; pub fn init(allocator: Allocator) MetadataArray { return .{ .allocator = allocator, .array = std.ArrayList(Field).init(allocator), }; } pub fn deinit(self: *MetadataArray) void { for (self.array.items) |field| { self.allocator.free(field.name); self.allocator.free(field.value); } self.array.deinit(); } pub fn append(self: *MetadataArray, field: Field) !void { return self.array.append(field); } }; fn getFFProbeMetadata(allocator: Allocator, cwd: ?std.fs.Dir, filepath: []const u8) !MetadataArray { var metadata = MetadataArray.init(allocator); errdefer metadata.deinit(); const result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &[_][]const u8{ "ffprobe", "-hide_banner", filepath, }, .cwd_dir = cwd, }); defer allocator.free(result.stdout); defer allocator.free(result.stderr); const metadata_start_string = "Metadata:\n"; const maybe_metadata_start = std.mem.indexOf(u8, result.stderr, metadata_start_string); if (maybe_metadata_start == null) { return error.NoMetadataFound; } const metadata_line_start = (std.mem.lastIndexOfScalar(u8, result.stderr[0..maybe_metadata_start.?], '\n') orelse 0) + 1; const metadata_line_indent_size = maybe_metadata_start.? - metadata_line_start; const metadata_start = maybe_metadata_start.? + metadata_start_string.len; const metadata_text = result.stderr[metadata_start..]; var indentation = try allocator.alloc(u8, metadata_line_indent_size + 2); defer allocator.free(indentation); std.mem.set(u8, indentation, ' '); var line_it = std.mem.split(u8, metadata_text, "\n"); while (line_it.next()) |line| { if (!std.mem.startsWith(u8, line, indentation)) break; var field_it = std.mem.split(u8, line, ":"); var name = std.mem.trim(u8, field_it.next().?, " "); if (name.len == 0) continue; // TODO multiline values var value = field_it.rest()[1..]; try metadata.append(MetadataArray.Field{ .name = try allocator.dupe(u8, name), .value = try allocator.dupe(u8, value), }); } return metadata; } test "ffprobe compare" { const allocator = std.testing.allocator; const filepath = "/media/drive4/music/Doomed Future Today/14 - Bombs (Version).mp3"; var probed_metadata = getFFProbeMetadata(allocator, null, filepath) catch |e| switch (e) { error.NoMetadataFound => MetadataArray.init(allocator), else => return e, }; defer probed_metadata.deinit(); var file = try std.fs.cwd().openFile(filepath, .{}); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var metadata = try meta.readAll(allocator, &stream_source); defer metadata.deinit(); var coalesced_metadata = try coalesceMetadata(allocator, &metadata); defer coalesced_metadata.deinit(); try compareMetadata(allocator, &probed_metadata, &coalesced_metadata); }
test/test_against_ffprobe.zig