code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const fs = std.fs; const Image = @import("../image.zig").Image; const upaya = @import("../upaya.zig"); const math = upaya.math; const stb = upaya.stb; pub const TexturePacker = struct { pub const Size = struct { width: u16, height: u16, }; pub const Sprite = struct { name: []const u8, source: math.Rect, origin: math.Point, }; pub const Animation = struct { name: []const u8, indexes: []usize, }; pub const Atlas = struct { sprites: []Sprite, width: u16, height: u16, image: upaya.Image = undefined, heightmap: upaya.Image = undefined, pub fn init(frames: []stb.stbrp_rect, origins: []math.Point, files: [][]const u8, images: []upaya.Image, heightmaps: []upaya.Image, size: Size) Atlas { std.debug.assert(frames.len == files.len and frames.len == origins.len and frames.len == images.len); var res_atlas = Atlas{ .sprites = upaya.mem.allocator.alloc(Sprite, images.len) catch unreachable, .width = size.width, .height = size.height, }; // convert to upaya rects for (frames) |frame, i| { res_atlas.sprites[i].source = .{ .x = frame.x, .y = frame.y, .width = frame.w, .height = frame.h }; res_atlas.sprites[i].name = std.mem.dupe(upaya.mem.allocator, u8, files[i]) catch unreachable; res_atlas.sprites[i].origin = origins[i]; } // generate the atlas var image = upaya.Image.init(size.width, size.height); image.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent); for (images) |img, i| { image.blit(img, frames[i].x, frames[i].y); } var heightmap = upaya.Image.init(size.width, size.height); heightmap.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent); for (heightmaps) |img, i| { heightmap.blit(img, frames[i].x, frames[i].y); } upaya.mem.allocator.free(images); upaya.mem.allocator.free(files); upaya.mem.allocator.free(frames); upaya.mem.allocator.free(origins); res_atlas.image = image; res_atlas.heightmap = heightmap; return res_atlas; } pub fn deinit(self: Atlas) void { for (self.sprites) |sprite| { upaya.mem.allocator.free(sprite.name); } upaya.mem.allocator.free(self.sprites); self.image.deinit(); } /// saves the atlas image and a json file with the atlas details. filename should be only the name with no extension. pub fn save(self: Atlas, folder: []const u8, filename: []const u8) void { const img_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, ".png" }) catch unreachable; const heightmap_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, "_h.png" }) catch unreachable; const atlas_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, ".atlas" }) catch unreachable; var out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, img_filename }) catch unreachable; self.image.save(out_file); out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, heightmap_filename }) catch unreachable; self.heightmap.save(out_file); out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, atlas_filename }) catch unreachable; var handle = std.fs.cwd().createFile(out_file, .{}) catch unreachable; defer handle.close(); const out_stream = handle.writer(); const options = std.json.StringifyOptions{ .whitespace = .{} }; std.json.stringify(.{ .sprites = self.sprites }, options, out_stream) catch unreachable; } }; pub fn runRectPacker(frames: []stb.stbrp_rect) ?Size { var ctx: stb.stbrp_context = undefined; const node_count = 4096 * 2; var nodes: [node_count]stb.stbrp_node = undefined; const texture_sizes = [_][2]c_int{ [_]c_int{ 256, 256 }, [_]c_int{ 512, 256 }, [_]c_int{ 256, 512 }, [_]c_int{ 512, 512 }, [_]c_int{ 1024, 512 }, [_]c_int{ 512, 1024 }, [_]c_int{ 1024, 1024 }, [_]c_int{ 2048, 1024 }, [_]c_int{ 1024, 2048 }, [_]c_int{ 2048, 2048 }, [_]c_int{ 4096, 2048 }, [_]c_int{ 2048, 4096 }, [_]c_int{ 4096, 4096 }, [_]c_int{ 8192, 4096 }, [_]c_int{ 4096, 8192 }, }; for (texture_sizes) |tex_size| { stb.stbrp_init_target(&ctx, tex_size[0], tex_size[1], &nodes, node_count); stb.stbrp_setup_heuristic(&ctx, stb.STBRP_HEURISTIC_Skyline_BL_sortHeight); if (stb.stbrp_pack_rects(&ctx, frames.ptr, @intCast(c_int, frames.len)) == 1) { return Size{ .width = @intCast(u16, tex_size[0]), .height = @intCast(u16, tex_size[1]) }; } } return null; } };
src/utils/texture_packer.zig
const std = @import("std"); const unistd = @cImport(@cInclude("unistd.h")); const Coordinate = struct { x: f64, y: f64, z: f64, fn eql(left: Coordinate, right: Coordinate) bool { return left.x == right.x and left.y == right.y and left.z == right.z; } }; const TestStruct = struct { coordinates: []Coordinate, }; fn notify(msg: []const u8) void { const addr = std.net.Address.parseIp("127.0.0.1", 9001) catch unreachable; if (std.net.tcpConnectToAddress(addr)) |stream| { defer stream.close(); _ = stream.write(msg) catch unreachable; } else |_| {} } fn readFile(alloc: *std.mem.Allocator, filename: []const u8) ![]const u8 { const file = try std.fs.cwd().openFile(filename, std.fs.File.OpenFlags{}); defer file.close(); const size = try file.getEndPos(); const text = try alloc.alloc(u8, size); _ = try file.readAll(text); return text; } fn calc(alloc: *std.mem.Allocator, text: []const u8) Coordinate { var stream = std.json.TokenStream.init(text); const opts = std.json.ParseOptions{ .allocator = alloc, .ignore_unknown_fields = true, }; const obj = std.json.parse(TestStruct, &stream, opts) catch unreachable; var x: f64 = 0.0; var y: f64 = 0.0; var z: f64 = 0.0; for (obj.coordinates) |item| { x += item.x; y += item.y; z += item.z; } const len = @intToFloat(f64, obj.coordinates.len); return Coordinate{ .x = x / len, .y = y / len, .z = z / len }; } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); var alloc: *std.mem.Allocator = &arena.allocator; const right = Coordinate{ .x = 2.0, .y = 0.5, .z = 0.25 }; const vals = [_][]const u8{ "{\"coordinates\":[{\"x\":2.0,\"y\":0.5,\"z\":0.25}]}", "{\"coordinates\":[{\"y\":0.5,\"x\":2.0,\"z\":0.25}]}", }; for (vals) |v| { const left = calc(alloc, v); if (!Coordinate.eql(left, right)) { std.debug.panic("{} != {}\n", .{ left, right }); } } const text = try readFile(alloc, "/tmp/1.json"); const pid = unistd.getpid(); const pid_str = try std.fmt.allocPrint(alloc, "Zig\t{d}", .{pid}); notify(pid_str); const results = calc(alloc, text); notify("stop"); std.debug.print("{}\n", .{results}); }
json/test.zig
const std = @import("std"); const debug = std.debug; const testing = std.testing; // taken from https://github.com/libntl/ntl/blob/main/src/ZZ.cpp // Compute s, t, d such that aa * s + bb * t = d = gcd(a,b) pub fn xgcd(d: *i64, s: *i64, t: *i64, aa: i64, bb: i64) void { var u: i64 = undefined; var v: i64 = undefined; var uu0: i64 = undefined; var v0: i64 = undefined; var uu1: i64 = undefined; var v1: i64 = undefined; var uu2: i64 = undefined; var v2: i64 = undefined; var q: i64 = undefined; var r: i64 = undefined; var aneg = false; var bneg = false; var a = aa; var b = bb; if (a < 0) { a = -a; aneg = true; } if (b < 0) { b = -b; bneg = true; } uu1 = 1; v1 = 0; uu2 = 0; v2 = 1; u = a; v = b; while (v != 0) { q = @divFloor(u, v); r = @mod(u, v); u = v; v = r; uu0 = uu2; v0 = v2; uu2 = uu1 - q * uu2; v2 = v1 - q * v2; uu1 = uu0; v1 = v0; } if (aneg) uu1 = -uu1; if (bneg) v1 = -v1; d.* = u; s.* = uu1; t.* = v1; } // NTL pub fn inv_mod(a: i64, n: i64) ?i64 { var d: i64 = undefined; var s: i64 = undefined; var t: i64 = undefined; xgcd(&d, &s, &t, a, n); if (d != 1) { return null; } if (s < 0) { return s + n; } else { return s; } } // https://www.geeksforgeeks.org/how-to-avoid-overflow-in-modular-multiplication/ pub fn mul_mod(a: i64, b: i64, n: i64) i64 { var res: i64 = 0; var a2 = @mod(a, n); var b2 = @mod(b, n); while (b2 > 0) { // If b is odd, add 'a' to result if (@mod(b2, 2) == 1) res = @mod(res + a2, n); // Multiply 'a' with 2 a2 = @mod(a2 * 2, n); // Divide b by 2 b2 = @divFloor(b2, 2); } return res; } // NTL pub fn power_mod(a: i64, e: i64, n: i64) i64 { var x: i64 = 1; var y = a; var ee: u64 = if (e >= 0) @intCast(u64, e) else @intCast(u64, -e); while (ee != 0) { if (ee & 1 != 0) x = mul_mod(x, y, n); y = mul_mod(y, y, n); ee = ee >> 1; } if (e < 0) x = inv_mod(x, n).?; return x; } test "inv_mod" { testing.expectEqual(@as(i64, 2), inv_mod(3, 5).?); testing.expectEqual(@as(i64, 3), inv_mod(2, 5).?); testing.expectEqual(@as(i64, 77695236753), inv_mod(6003722857, 77695236973).?); // Worst case set of numbers are the two largest fibonacci numbers: < 2^63 a = 4660046610375530309 , n = 7540113804746346429 , which will take 90 loops. In this case, (1/a mod n) == a. testing.expectEqual(@as(i64, 4660046610375530309), inv_mod(4660046610375530309, 7540113804746346429).?); } test "mul_mod" { const a: i64 = 9223372036854775807; const b: i64 = 9223372036854775807; testing.expectEqual(@as(i64, 84232501249), mul_mod(a, b, 100000000000)); testing.expectEqual(@as(i64, 4), mul_mod(@as(i64, -2), @as(i64, 3), @as(i64, 10))); } test "power_mod" { // Fermat const p: i64 = 17; testing.expectEqual(@as(i64, 1), power_mod(2, p - 1, p)); }
share/zig/numtheory.zig
const wlr = @import("../wlroots.zig"); const os = @import("std").os; const wl = @import("wayland").server.wl; const pixman = @import("pixman"); pub const ShmAttributes = extern struct { fd: c_int, format: u32, width: c_int, height: c_int, stride: c_int, offset: os.off_t, }; pub const Buffer = extern struct { pub const data_ptr_access_flag = struct { pub const read = 1 << 0; pub const write = 1 << 1; }; pub const Impl = extern struct { destroy: fn (buffer: *Buffer) callconv(.C) void, get_dmabuf: fn (buffer: *Buffer, attribs: *wlr.DmabufAttributes) callconv(.C) bool, get_shm: fn (buffer: *Buffer, attribs: *wlr.ShmAttributes) callconv(.C) bool, begin_data_ptr_access: fn (buffer: *Buffer, flags: u32, data: **anyopaque, format: *u32, stride: *usize) callconv(.C) bool, end_data_ptr_access: fn (buffer: *Buffer) callconv(.C) void, }; pub const ResourceInterface = extern struct { name: [*:0]const u8, is_instance: fn (resource: *wl.Resource) callconv(.C) bool, from_resource: fn (resource: *wl.Resource) callconv(.C) ?*Buffer, }; impl: *const Impl, width: c_int, height: c_int, dropped: bool, n_locks: usize, accessing_data_ptr: bool, events: extern struct { destroy: wl.Signal(void), release: wl.Signal(void), }, addons: wlr.AddonSet, extern fn wlr_buffer_init(buffer: *Buffer, impl: *const Buffer.Impl, width: c_int, height: c_int) void; pub const init = wlr_buffer_init; extern fn wlr_buffer_drop(buffer: *Buffer) void; pub const drop = wlr_buffer_drop; extern fn wlr_buffer_lock(buffer: *Buffer) *Buffer; pub const lock = wlr_buffer_lock; extern fn wlr_buffer_unlock(buffer: *Buffer) void; pub const unlock = wlr_buffer_unlock; extern fn wlr_buffer_get_dmabuf(buffer: *Buffer, attribs: *wlr.DmabufAttributes) bool; pub const getDmabuf = wlr_buffer_get_dmabuf; extern fn wlr_buffer_get_shm(buffer: *Buffer, attribs: *wlr.ShmAttributes) bool; pub const getShm = wlr_buffer_get_shm; extern fn wlr_buffer_register_resource_interface(iface: *const ResourceInterface) void; pub const registerResourceInterface = wlr_buffer_register_resource_interface; extern fn wlr_buffer_from_resource(resource: *wl.Buffer) ?*Buffer; pub const fromWlBuffer = wlr_buffer_from_resource; extern fn wlr_buffer_begin_data_ptr_access(buffer: *Buffer, flags: u32, data: **anyopaque, format: *u32, stride: *usize) bool; pub const beginDataPtrAccess = wlr_buffer_begin_data_ptr_access; extern fn wlr_buffer_end_data_ptr_access(buffer: *Buffer) void; pub const endDataPtrAccess = wlr_buffer_end_data_ptr_access; }; pub const ClientBuffer = extern struct { base: Buffer, texture: ?*wlr.Texture, source: ?*wlr.Buffer, // private state source_destroy: wl.Listener(void), shm_source_format: u32, extern fn wlr_client_buffer_create(buffer: *wlr.Buffer, renderer: *wlr.Renderer) ?*ClientBuffer; pub const create = wlr_client_buffer_create; extern fn wlr_client_buffer_get(buffer: *wlr.Buffer) ?*ClientBuffer; pub const get = wlr_client_buffer_get; extern fn wlr_client_buffer_apply_damage(buffer: *ClientBuffer, next: *wlr.Buffer, damage: *pixman.Region32) bool; pub const applyDamage = wlr_client_buffer_apply_damage; };
src/types/buffer.zig
const clap = @import("clap"); const format = @import("format"); const it = @import("ziter"); const std = @import("std"); const ston = @import("ston"); const util = @import("util"); 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 rand = std.rand; const testing = std.testing; const unicode = std.unicode; const escape = util.escape; const Utf8 = util.unicode.Utf8View; const Program = @This(); allocator: mem.Allocator, options: struct { seed: u64, replace_cheap: bool, }, max_evolutions: usize = 0, pokedex: Set = Set{}, items: Items = Items{}, pokeball_items: PokeballItems = PokeballItems{}, pokemons: Pokemons = Pokemons{}, pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Changes all Pokémons to evolve using new evolution stones. These stones evolve a Pokémon \\to a random new Pokémon that upholds the requirements of the stone. Here is a list of all \\stones: \\* Chance Stone: Evolves a Pokémon into random Pokémon. \\* Stat Stone: Evolves a Pokémon into random Pokémon with the same total stats. \\* Growth Stone: Evolves a Pokémon into random Pokémon with the same growth rate. \\* Form Stone: Evolves a Pokémon into random Pokémon with a common type. \\* Skill Stone: Evolves a Pokémon into random Pokémon with a common ability. \\* Breed Stone: Evolves a Pokémon into random Pokémon in the same egg group. \\* Buddy Stone: Evolves a Pokémon into random Pokémon with the same base friendship. \\ \\This command will try to get as many of these stones into the game as possible, but beware, \\that all stones might not exist. Also beware, that the stones might have different (but \\simular) names in cases where the game does not support long item names. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help text and exit. ") catch unreachable, clap.parseParam("-r, --replace-cheap-items Replaces cheap items in pokeballs with stones.") catch unreachable, clap.parseParam("-s, --seed <INT> The seed to use for random numbers. A random seed will be picked if this is not specified.") catch unreachable, clap.parseParam("-v, --version Output version information and exit. ") catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) !Program { return Program{ .allocator = allocator, .options = .{ .seed = try util.args.seed(args), .replace_cheap = args.flag("--replace-cheap-items"), }, }; } pub fn run( program: *Program, comptime Reader: type, comptime Writer: type, stdio: util.CustomStdIoStreams(Reader, Writer), ) anyerror!void { try format.io(program.allocator, stdio.in, stdio.out, program, useGame); try program.randomize(); try program.output(stdio.out); } fn output(program: *Program, writer: anytype) !void { for (program.pokemons.values()) |pokemon, i| { const species = program.pokemons.keys()[i]; try ston.serialize(writer, .{ .pokemons = ston.index(species, .{ .evos = pokemon.evos, }) }); } for (program.items.values()) |item, i| { const item_id = program.items.keys()[i]; try ston.serialize(writer, .{ .items = ston.index(item_id, .{ .name = ston.string(escape.default.escapeFmt(item.name)), .description = ston.string(escape.default.escapeFmt(item.desc)), }) }); } try ston.serialize(writer, .{ .pokeball_items = program.pokeball_items }); } fn useGame(program: *Program, parsed: format.Game) !void { const allocator = program.allocator; switch (parsed) { .pokedex => |pokedex| { _ = try program.pokedex.put(allocator, pokedex.index, {}); return error.DidNotConsumeData; }, .pokemons => |pokemons| { const pokemon = (try program.pokemons.getOrPutValue(allocator, pokemons.index, .{})).value_ptr; switch (pokemons.value) { .catch_rate => |catch_rate| pokemon.catch_rate = catch_rate, .pokedex_entry => |pokedex_entry| pokemon.pokedex_entry = pokedex_entry, .base_friendship => |base_friendship| pokemon.base_friendship = base_friendship, .growth_rate => |growth_rate| pokemon.growth_rate = growth_rate, .stats => |stats| pokemon.stats[@enumToInt(stats)] = stats.value(), .types => |types| _ = try pokemon.types.put(allocator, types.value, {}), .abilities => |abilities| _ = try pokemon.abilities.put(allocator, abilities.value, {}), .egg_groups => |egg_groups| _ = try pokemon.egg_groups.put(allocator, @enumToInt(egg_groups.value), {}), .evos => |evos| { program.max_evolutions = math.max(program.max_evolutions, evos.index + 1); const evo = (try pokemon.evos.getOrPutValue(allocator, evos.index, .{})).value_ptr; format.setField(evo, evos.value); return; }, .base_exp_yield, .ev_yield, .items, .gender_ratio, .egg_cycles, .color, .moves, .tms, .hms, .name, => return error.DidNotConsumeData, } return error.DidNotConsumeData; }, .items => |items| { const item = (try program.items.getOrPutValue(allocator, items.index, .{})).value_ptr; switch (items.value) { .name => |str| { item.name = try Utf8.init(try util.escape.default.unescapeAlloc(allocator, str)); return; }, .description => |desc| { item.desc = try Utf8.init(try util.escape.default.unescapeAlloc(allocator, desc)); return; }, .price => |price| item.price = price, .battle_effect, .pocket, => return error.DidNotConsumeData, } return error.DidNotConsumeData; }, .pokeball_items => |items| switch (items.value) { .item => |item| if (program.options.replace_cheap) { _ = try program.pokeball_items.put(allocator, items.index, .{ .item = item }); return; } else return error.DidNotConsumeData, .amount => return error.DidNotConsumeData, }, .version, .game_title, .gamecode, .instant_text, .starters, .text_delays, .trainers, .moves, .abilities, .types, .tms, .hms, .maps, .wild_pokemons, .static_pokemons, .given_pokemons, .hidden_hollows, .text, => return error.DidNotConsumeData, } unreachable; } fn randomize(program: *Program) !void { @setEvalBranchQuota(1000000000); const allocator = program.allocator; const random = rand.DefaultPrng.init(program.options.seed).random(); // First, let's find items that are used for evolving Pokémons. // We will use these items as our stones. var stones = Set{}; for (program.pokemons.values()) |*pokemon| { for (pokemon.evos.values()) |evo| { if (evo.method == .use_item) _ = try stones.put(allocator, evo.param, {}); } // Reset evolutions. We don't need the old anymore. pokemon.evos.clearRetainingCapacity(); } // Find the maximum length of a line. Used to split descs into lines. var max_line_len: usize = 0; for (program.items.values()) |item| { var desc = item.desc; while (mem.indexOf(u8, desc.bytes, "\n")) |index| { const line = Utf8.init(desc.bytes[0..index]) catch unreachable; max_line_len = math.max(line.len, max_line_len); desc = Utf8.init(desc.bytes[index + 1 ..]) catch unreachable; } max_line_len = math.max(desc.len, max_line_len); } // HACK: The games does not used mono fonts, so actually, using the // max_line_len to destribute newlines will not actually be totally // correct. The best I can do here is to just reduce the max_line_len // by some amount and hope it is enough for all strings. max_line_len = math.sub(usize, max_line_len, 5) catch max_line_len; const species = try pokedexPokemons(allocator, program.pokemons, program.pokedex); const pokemons_by_stats = try filterBy(allocator, species, program.pokemons, statsFilter); const pokemons_by_base_friendship = try filterBy(allocator, species, program.pokemons, friendshipFilter); const pokemons_by_type = try filterBy(allocator, species, program.pokemons, typeFilter); const pokemons_by_ability = try filterBy(allocator, species, program.pokemons, abilityFilter); const pokemons_by_egg_group = try filterBy(allocator, species, program.pokemons, eggGroupFilter); const pokemons_by_growth_rate = try filterBy(allocator, species, program.pokemons, growthRateFilter); // Make sure these indexs line up with the array below const chance_stone = 0; const stat_stone = 1; const growth_stone = 2; const form_stone = 3; const skill_stone = 4; const breed_stone = 5; const buddy_stone = 6; const stone_strings = [_]struct { names: []const Utf8, descs: []const Utf8, }{ .{ .names = &[_]Utf8{ comptime Utf8.init("Chance Stone") catch unreachable, comptime Utf8.init("Chance Rock") catch unreachable, comptime Utf8.init("Luck Rock") catch unreachable, comptime Utf8.init("Luck Rck") catch unreachable, comptime Utf8.init("C Stone") catch unreachable, comptime Utf8.init("C Rock") catch unreachable, comptime Utf8.init("C Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Stat Stone") catch unreachable, comptime Utf8.init("Stat Rock") catch unreachable, comptime Utf8.init("St Stone") catch unreachable, comptime Utf8.init("St Rock") catch unreachable, comptime Utf8.init("St Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same total stats.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon with same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same total stats") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same stats") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Growth Stone") catch unreachable, comptime Utf8.init("Growth Rock") catch unreachable, comptime Utf8.init("Rate Stone") catch unreachable, comptime Utf8.init("Rate Rock") catch unreachable, comptime Utf8.init("G Stone") catch unreachable, comptime Utf8.init("G Rock") catch unreachable, comptime Utf8.init("G Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same growth rate.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with same growth rate.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon with same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same growth rate") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same growth rate") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Form Stone") catch unreachable, comptime Utf8.init("Form Rock") catch unreachable, comptime Utf8.init("Form Rck") catch unreachable, comptime Utf8.init("T Stone") catch unreachable, comptime Utf8.init("T Rock") catch unreachable, comptime Utf8.init("T Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with a common type.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random a common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("A common type") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same type") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Skill Stone") catch unreachable, comptime Utf8.init("Skill Rock") catch unreachable, comptime Utf8.init("Skill Rck") catch unreachable, comptime Utf8.init("S Stone") catch unreachable, comptime Utf8.init("S Rock") catch unreachable, comptime Utf8.init("S Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with a common ability.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random a common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("A common ability") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same ability") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Breed Stone") catch unreachable, comptime Utf8.init("Breed Rock") catch unreachable, comptime Utf8.init("Egg Stone") catch unreachable, comptime Utf8.init("Egg Rock") catch unreachable, comptime Utf8.init("Egg Rck") catch unreachable, comptime Utf8.init("E Stone") catch unreachable, comptime Utf8.init("E Rock") catch unreachable, comptime Utf8.init("E Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon in the same egg group.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon into random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon to random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve a Pokémon to random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon in the same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, in same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon in same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, in same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random in same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("In same egg group") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same egg group") catch unreachable), }, }, .{ .names = &[_]Utf8{ comptime Utf8.init("Buddy Stone") catch unreachable, comptime Utf8.init("Buddy Rock") catch unreachable, comptime Utf8.init("Buddy Rck") catch unreachable, comptime Utf8.init("F Stone") catch unreachable, comptime Utf8.init("F Rock") catch unreachable, comptime Utf8.init("F Rck") catch unreachable, }, .descs = &[_]Utf8{ try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same base friendship.") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same base friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same base friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves a Pokémon into random Pokémon with the same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with the same base friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with the same base friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same base friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolves to random Pokémon with the same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with the same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Evolve to random Pokémon with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with the same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Into random Pokémon with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("To random Pokémon with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon, same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random Pokémon same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random with same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random, same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Random same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("In same friendship") catch unreachable), try util.unicode.splitIntoLines(allocator, max_line_len, comptime Utf8.init("Same friendship") catch unreachable), }, }, }; for (stone_strings) |strs, stone| { if (program.max_evolutions <= stone or stones.count() <= stone) break; const item_id = stones.keys()[stone]; const item = program.items.getPtr(item_id).?; // We have no idea as to how long the name/desc can be in the game we // are working on. Our best guess will therefor be to use the current // items name/desc as the limits and pick something that fits. item.* = Item{ .name = pickString(item.name.len, strs.names), .desc = pickString(item.desc.len, strs.descs), }; } const num_pokemons = species.count(); for (species.keys()) |pokemon_id| { const pokemon = program.pokemons.getPtr(pokemon_id).?; for (stone_strings) |_, stone| { if (program.max_evolutions <= stone or stones.count() <= stone) break; const item_id = stones.keys()[stone]; const pick = switch (stone) { chance_stone => while (num_pokemons > 1) { const pick = util.random.item(random, species.keys()).?.*; if (pick != pokemon_id) break pick; } else pokemon_id, form_stone, skill_stone, breed_stone => blk: { const map = switch (stone) { form_stone => pokemons_by_type, skill_stone => pokemons_by_ability, breed_stone => pokemons_by_egg_group, else => unreachable, }; const set = switch (stone) { form_stone => pokemon.types, skill_stone => pokemon.abilities, breed_stone => pokemon.egg_groups, else => unreachable, }; if (map.count() == 0 or set.count() == 0) break :blk pokemon_id; const picked_id = switch (stone) { // Assume that ability 0 means that there is no ability, and // don't pick that. skill_stone => while (set.count() != 1) { const pick = util.random.item(random, set.keys()).?.*; if (pick != 0) break pick; } else set.keys()[0], form_stone, breed_stone => util.random.item(random, set.keys()).?.*, else => unreachable, }; const pokemon_set = map.get(picked_id).?; const pokemons = pokemon_set.count(); while (pokemons != 1) { const pick = util.random.item(random, pokemon_set.keys()).?.*; if (pick != pokemon_id) break :blk pick; } break :blk pokemon_id; }, stat_stone, growth_stone, buddy_stone => blk: { const map = switch (stone) { stat_stone => pokemons_by_stats, growth_stone => pokemons_by_growth_rate, buddy_stone => pokemons_by_base_friendship, else => unreachable, }; const number = switch (stone) { stat_stone => it.fold(&pokemon.stats, @as(u16, 0), foldu8), growth_stone => @enumToInt(pokemon.growth_rate), buddy_stone => pokemon.base_friendship, else => unreachable, }; if (map.count() == 0) break :blk pokemon_id; const pokemon_set = map.get(number).?; const pokemons = pokemon_set.count(); while (pokemons != 1) { const pick = util.random.item(random, pokemon_set.keys()).?.*; if (pick != pokemon_id) break :blk pick; } break :blk pokemon_id; }, else => unreachable, }; _ = try pokemon.evos.put(allocator, @intCast(u8, stone), Evolution{ .method = .use_item, .param = item_id, .target = pick, }); } } // Replace cheap pokeball items with random stones. for (program.pokeball_items.values()) |*ball| { const item = program.items.get(ball.item) orelse continue; if (item.price == 0 or item.price > 600) continue; ball.item = util.random.item(random, stones.keys()).?.*; } } fn pickString(len: usize, strings: []const Utf8) Utf8 { var pick = strings[0]; for (strings) |str| { pick = str; if (str.len <= len) break; } return pick.slice(0, len); } fn filterBy( allocator: mem.Allocator, species: Set, pokemons: Pokemons, filter: fn (Pokemon, []u16) []const u16, ) !PokemonBy { var buf: [16]u16 = undefined; var pokemons_by = PokemonBy{}; for (species.keys()) |id| { const pokemon = pokemons.get(id).?; for (filter(pokemon, &buf)) |key| { const set = (try pokemons_by.getOrPutValue(allocator, key, .{})).value_ptr; _ = try set.put(allocator, id, {}); } } return pokemons_by; } fn statsFilter(pokemon: Pokemon, buf: []u16) []const u16 { buf[0] = it.fold(&pokemon.stats, @as(u16, 0), foldu8); return buf[0..1]; } fn friendshipFilter(pokemon: Pokemon, buf: []u16) []const u16 { buf[0] = pokemon.base_friendship; return buf[0..1]; } fn growthRateFilter(pokemon: Pokemon, buf: []u16) []const u16 { buf[0] = @enumToInt(pokemon.growth_rate); return buf[0..1]; } fn typeFilter(pokemon: Pokemon, buf: []u16) []const u16 { return setFilter("types", pokemon, buf); } fn abilityFilter(pokemon: Pokemon, buf: []u16) []const u16 { return setFilter("abilities", pokemon, buf); } fn eggGroupFilter(pokemon: Pokemon, buf: []u16) []const u16 { return setFilter("egg_groups", pokemon, buf); } fn setFilter(comptime field: []const u8, pokemon: Pokemon, buf: []u16) []const u16 { const keys = @field(pokemon, field).keys(); for (keys) |item, i| buf[i] = item; return buf[0..keys.len]; } fn foldu8(a: u16, b: u8) u16 { return a + b; } const Evolutions = std.AutoArrayHashMapUnmanaged(u8, Evolution); const Items = std.AutoArrayHashMapUnmanaged(u16, Item); const PokeballItems = std.AutoArrayHashMapUnmanaged(u16, PokeballItem); const PokemonBy = std.AutoArrayHashMapUnmanaged(u16, Set); const Pokemons = std.AutoArrayHashMapUnmanaged(u16, Pokemon); const Set = std.AutoArrayHashMapUnmanaged(u16, void); fn pokedexPokemons(allocator: mem.Allocator, pokemons: Pokemons, pokedex: Set) !Set { var res = Set{}; errdefer res.deinit(allocator); for (pokemons.values()) |pokemon, i| { if (pokemon.catch_rate == 0) continue; if (pokedex.get(pokemon.pokedex_entry) == null) continue; _ = try res.put(allocator, pokemons.keys()[i], {}); } return res; } const Pokemon = struct { evos: Evolutions = Evolutions{}, stats: [6]u8 = [_]u8{0} ** 6, growth_rate: format.GrowthRate = .fast, base_friendship: u16 = 0, catch_rate: u16 = 1, pokedex_entry: u16 = math.maxInt(u16), abilities: Set = Set{}, types: Set = Set{}, egg_groups: Set = Set{}, }; const Item = struct { name: Utf8 = Utf8.init("") catch unreachable, desc: Utf8 = Utf8.init("") catch unreachable, price: usize = 0, }; const Evolution = struct { method: format.Evolution.Method = .unused, param: u16 = 0, target: u16 = 0, }; const PokeballItem = struct { item: u16, }; test "tm35-random stones" { // TODO: Tests }
src/randomizers/tm35-random-stones.zig
const std = @import("std"); const assert = std.debug.assert; const warn = std.debug.warn; const mem = std.mem; const math = std.math; const Queue = std.atomic.Queue; const Timer = std.os.time.Timer; const builtin = @import("builtin"); const AtomicOrder = builtin.AtomicOrder; const AtomicRmwOp = builtin.AtomicRmwOp; const linux = switch(builtin.os) { builtin.Os.linux => std.os.linux, else => @compileError("Only builtin.os.linux is supported"), }; pub use switch(builtin.arch) { builtin.Arch.x86_64 => @import("../zig/std/os/linux/x86_64.zig"), else => @compileError("unsupported arch"), }; pub fn futex_wait(pVal: *i32, expected_value: u32) void { //warn("futex_wait: {*}\n", pVal); _ = syscall4(SYS_futex, @ptrToInt(pVal), linux.FUTEX_WAIT, expected_value, 0); } pub fn futex_wake(pVal: *i32, num_threads_to_wake: u32) void { //warn("futex_wake: {*}\n", pVal); _ = syscall4(SYS_futex, @ptrToInt(pVal), linux.FUTEX_WAKE, num_threads_to_wake, 0); } const ThreadContext = struct { const Self = this; counter: u128, pub fn init(pSelf: *Self) void { pSelf.counter = 0; } }; var gProducer_context: ThreadContext = undefined; var gConsumer_context: ThreadContext = undefined; const consumeSignal = 0; const produceSignal = 1; var produce: i32 = consumeSignal; var gCounter: u64 = 0; var gProducer_wait_count: u64 = 0; var gConsumer_wait_count: u64 = 0; var gProducer_wake_count: u64 = 0; var gConsumer_wake_count: u64 = 0; const max_counter = 10000000; const stallCountWait: u32 = 10000; const stallCountWake: u32 = 2000; fn producer(pContext: *ThreadContext) void { while (pContext.counter < max_counter) { // Stall to see if the consumer changes produce to produceSignal var count = stallCountWait; var produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); while ((produce_val != produceSignal) and (count > 0)) { produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); count -= 1; } // If consumer hasn't changed it call futex_wait until it does while (produce_val != produceSignal) { gProducer_wait_count += 1; futex_wait(&produce, consumeSignal); produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); } // Produce as produce == produceSignal _ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); pContext.counter += 1; // Set produce to consumeSignal _ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, consumeSignal, AtomicOrder.SeqCst); // Stall to see if consumer changes produce to produceSignal count = stallCountWake; produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); while ((produce_val != produceSignal) and (count > 0)) { produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); count -= 1; } // If consumer hasn't changed it call futex_wake and continue if (produce_val != produceSignal) { gProducer_wake_count += 1; futex_wake(&produce, 1); } } } fn consumer(pContext: *ThreadContext) void { while (pContext.counter < max_counter) { // Set produce to produceSignal _ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, produceSignal, AtomicOrder.SeqCst); // Stall to see if the producer changes produce to consumeSignal var count = stallCountWake; var produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); while ((produce_val != consumeSignal) and (count > 0)) { produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); count -= 1; } // If producer hasn't changed it call futex_wake and continue if (produce_val != consumeSignal) { gConsumer_wake_count += 1; futex_wake(&produce, 1); } // Stall to see if the producer changes produce to consumeSignal count = stallCountWait; produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); while ((produce_val != consumeSignal) and (count > 0)) { produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); count -= 1; } // If producer hasn't changed it call futex_wait until it does while (produce_val != consumeSignal) { gConsumer_wait_count += 1; futex_wait(&produce, produceSignal); produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.SeqCst); } // Consume as produce == consumeSignal _ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); pContext.counter += 1; } } test "Futex" { warn("\ntest Futex:+\n"); defer warn("test Futex:- futex_wait counts={} futex_wake counts={}\n", gProducer_wait_count + gConsumer_wait_count, gProducer_wake_count + gConsumer_wake_count); gProducer_context.init(); gConsumer_context.init(); var timer = try Timer.start(); var start_time = timer.read(); var producer_thread = try std.os.spawnThread(&gProducer_context, producer); var consumer_thread = try std.os.spawnThread(&gConsumer_context, consumer); producer_thread.wait(); consumer_thread.wait(); var end_time = timer.read(); var duration = end_time - start_time; warn("test Futex: time={.6}\n", @intToFloat(f64, end_time - start_time) / @intToFloat(f64, std.os.time.ns_per_s)); assert(gCounter == max_counter * 2); }
futex.zig
const std = @import("std"); const json = @import("./zson/src/main.zig"); const mem = std.mem; const warn = std.debug.warn; const Channel = std.event.Channel; const ArenaAllocator = std.heap.ArenaAllocator; pub const json_rpc_version = "2.0"; /// JSON is an interface for encoding/decoding json values. We use ArenaAllocator /// here for consistency and making it easy to free memory after the /// encoding/decoding is done.. /// /// It is recommended to use the allocator passed for all allocations done by /// memebers which implement this interface. pub const JSON = struct { marshalJSON: fn (self: *JSON, a: *ArenaAllocator) !json.Value, }; /// Value wraps JSON interface and json.Value togather. pub const Value = union(enum) { value: json.Value, json: *JSON, }; pub const RequestMessage = struct { jsonrpc: []const u8, id: ID, params: ?json.Value, pub fn toJson(self: RequestMessage, a: *ArenaAllocator) !json.Value { var obj = json.ObjectMap.init(&a.allocator); const rpc_version_value = json.Value{ .String = self.jsonrpc }; const id_value = self.id.toJson(a); _ = try obj.put("jsonrpc", rpc_version_value); _ = try obj.put("id", id_value); if (self.params != null) { _ = try obj.put("params", self.params.?); } return json.Value{ .Object = obj }; } }; test "RequestMessage.encode" { var b = try std.Buffer.init(std.debug.global_allocator, ""); var buf = &b; defer buf.deinit(); var stream = &std.io.BufferOutStream.init(buf).stream; const req = RequestMessage{ .jsonrpc = json_rpc_version, .id = ID{ .Number = 10 }, .params = null, }; var arena = ArenaAllocator.init(std.debug.global_allocator); const value = try req.toJson(&arena); try value.dump(stream); warn("{}\n", buf.toSlice()); } pub const ID = union(enum) { String: []const u8, Number: i64, Null, pub fn toJson(self: ID, a: *ArenaAllocator) json.Value { switch (self) { ID.String => |v| { return json.Value{ .String = v }; }, ID.Number => |v| { return json.Value{ .Integer = v }; }, ID.Null => |v| { return json.Value.Null; }, else => unreachable, } } }; pub const ResponseMessage = struct { jsonrpc: []const u8, id: ID, result: ?json.Value, error_value: ?ResponseError, }; pub const ErrorCode = enum(i64) { ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603, ServerErrorStart = -32099, ServerErrorEnd = -32000, ServerNotInitialized = -32002, UnknownErrorCode = -32001, RequestCancelled = -32800, }; pub const ResponseError = struct { code: ErrorCode, message: []const u8, data: ?json.Value, }; pub const NotificationMessage = struct { jsonrpc: []const u8, id: ID, method: []const u8, params: ?json.Value, }; pub const CancelParam = struct { id: ID, }; /// Header is the first part of the lsp protocol message. This is delimited with /// \r\r. /// /// It is a must to have at least one field. pub const Header = struct { /// The length of the content part in bytes content_length: u64, /// The mime type of the content part. Defaults to /// application/vscode-jsonrpc; charset=utf-8 content_type: ?[]const u8, }; // Message defines a json-rpc message. This consist of a header and content. // Make sure you cann deinit after you are done with the messsage to freeup // resources. pub const Message = struct { header: Header, content: ?json.ValueTree, }; pub const MessageChannel = Channel(Message); // Bus stores async i/o for rpc messages. pub const Bus = struct { in: *MessageChannel, out: *MessageChannel, pub fn init(loop: *std.event.Loop) anyerror!Bus { return Bus{ .in = try MessageChannel.create(loop, 10), .out = try MessageChannel.create(loop, 10), }; } };
src/protocol.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const meta = std.meta; const trait = meta.trait; const testing = std.testing; /// Creates a new Deserializer type for the given reader type pub fn Deserializer(comptime ReaderType: type) type { return struct { const Self = @This(); /// Reader that is being read from while deserializing reader: ReaderType, gpa: *Allocator, /// Last character that was read from the stream last_char: u8, pub const Error = ReaderType.Error || std.fmt.ParseIntError || error{ OutOfMemory, UnsupportedType, EndOfStream, InvalidLength }; const Pair = struct { key: []const u8, value: Value }; /// Represents a bencode value const Value = union(enum) { bytes: []u8, int: usize, list: []Value, dictionary: []Pair, fn deinit(self: Value, gpa: *Allocator) void { switch (self) { .bytes => |bytes| gpa.free(bytes), .int => {}, .list => |list| { for (list) |item| item.deinit(gpa); gpa.free(list); }, .dictionary => |dict| { for (dict) |pair| { gpa.free(pair.key); pair.value.deinit(gpa); } gpa.free(dict); }, } } /// Attempts to convert a `Value` into given zig type `T` fn toZigType(self: Value, comptime T: type, gpa: *Allocator) Error!T { if (T == []u8 or T == []const u8) return self.bytes; switch (@typeInfo(T)) { .Struct => { var struct_value: T = undefined; inline for (meta.fields(T)) |field| { if (self.getField(field.name)) |pair| { const field_value = try pair.value.toZigType(field.field_type, gpa); @field(struct_value, field.name) = @as(field.field_type, field_value); } } return struct_value; }, .Int => return @as(T, self.int), .Optional => |opt| return try self.toZigType(opt.child, gpa), .Pointer => |ptr| switch (ptr.size) { .Slice => { const ChildType = meta.Child(T); var list = std.ArrayList(ChildType).init(gpa); defer list.deinit(); for (self.list) |item| { const element = try item.toZigType(ChildType, gpa); try list.append(element); } return @as(T, list.toOwnedSlice()); }, .One => try self.toZigType(ptr.child, gpa), else => return error.Unsupported, }, else => return error.UnsupportedType, } } /// Asserts `Value` is Dictionary and returns dictionary pair if it contains given key /// else returns null fn getField(self: Value, key: []const u8) ?Pair { return for (self.dictionary) |pair| { if (eql(key, pair.key)) break pair; } else null; } /// Checks if a field name equals that of a key /// replaces '_' with a ' ' if needed as bencode allows keys to have spaces fn eql(field: []const u8, key: []const u8) bool { if (field.len != key.len) return false; return for (field) |c, i| { if (c != key[i]) { if (c == '_' and key[i] == ' ') continue; break false; } } else true; } }; pub fn init(gpa: *Allocator, reader: ReaderType) Self { return .{ .reader = reader, .gpa = gpa, .last_char = undefined }; } /// Deserializes the current reader's stream into the given type `T` /// Rather than supplier a buffer, it will allocate the data it has read /// and can be freed upon calling `deinit` afterwards. pub fn deserialize(self: *Self, comptime T: type) Error!T { if (@typeInfo(T) != .Struct) @compileError("T must be a struct Type."); try self.nextByte(); // go to first byte const result = try self.deserializeValue(); std.debug.assert(self.last_char == 'e'); return try result.toZigType(T, self.gpa); } /// Reads the next byte from the reader and returns it fn nextByte(self: *Self) Error!void { const byte = try self.reader.readByte(); self.last_char = byte; while (byte == '\n') { try self.nextByte(); } return; } fn deserializeValue(self: *Self) Error!Value { return switch (self.last_char) { '0'...'9' => |c| Value{ .bytes = try self.deserializeBytes() }, 'i' => blk: { try self.nextByte(); // skip 'i' break :blk Value{ .int = try self.deserializeLength() }; }, 'l' => Value{ .list = try self.deserializeList() }, 'd' => Value{ .dictionary = try self.deserializeDict() }, ' ', '\n' => return try self.deserializeValue(), else => unreachable, }; } /// Deserializes a slice of bytes fn deserializeBytes(self: *Self) Error![]u8 { const len = try self.deserializeLength(); if (len == 0) return error.InvalidLength; const value = try self.gpa.alloc(u8, len); try self.reader.readNoEof(value); self.last_char = value[len - 1]; return value; } /// Reads until it finds ':' and returns the integer value in front of it fn deserializeLength(self: *Self) Error!usize { var list = std.ArrayList(u8).init(self.gpa); defer list.deinit(); while (self.last_char >= '0' and self.last_char <= '9') : (try self.nextByte()) { try list.append(self.last_char); } // All integers in Bencode are radix 10 const integer = try std.fmt.parseInt(usize, list.items, 10); return integer; } /// Deserializes into a slice of `Value` until it finds the 'e' fn deserializeList(self: *Self) Error![]Value { var list = std.ArrayList(Value).init(self.gpa); defer list.deinit(); errdefer for (list.items) |item| item.deinit(self.gpa); try self.nextByte(); // skip 'l' while (self.last_char != 'e') : (try self.nextByte()) { const value = try self.deserializeValue(); try list.append(value); } return list.toOwnedSlice(); } /// Deserializes a dictionary bencode object into a slice of `Pair` fn deserializeDict(self: *Self) Error![]Pair { var list = std.ArrayList(Pair).init(self.gpa); defer list.deinit(); errdefer for (list.items) |pair| { self.gpa.free(pair.key); pair.value.deinit(self.gpa); }; // go to first byte after 'd' try self.nextByte(); while (self.last_char != 'e') : (try self.nextByte()) { const key = try self.deserializeBytes(); try self.nextByte(); const value = try self.deserializeValue(); try list.append(.{ .key = key, .value = value }); } return list.toOwnedSlice(); } }; } /// Returns a new deserializer for the given `reader` pub fn deserializer(gpa: *Allocator, reader: anytype) Deserializer(@TypeOf(reader)) { return Deserializer(@TypeOf(reader)).init(gpa, reader); } /// Creates a Serializer type for the given writer type pub fn Serializer(comptime WriterType: anytype) type { return struct { writer: WriterType, const Self = @This(); pub const Error = WriterType.Error || error{OutOfMemory}; /// Creates new instance of the Serializer type pub fn init(writer: WriterType) Self { return .{ .writer = writer }; } /// Serializes the given value to bencode and writes the result to the writer pub fn serialize(self: Self, value: anytype) Error!void { const T = @TypeOf(value); if (T == []u8 or T == []const u8) { return try self.serializeString(value); } switch (@typeInfo(T)) { .Struct => try self.serializeStruct(value), .Int => try self.serializeInt(value), .Pointer => |ptr| switch (ptr.size) { .Slice => try self.serializeList(value), .One => try self.serialize(value.*), .C, .Many => unreachable, // unsupported }, .Optional => if (value) |val| try self.serialize(val), else => unreachable, // unsupported types } } /// Serializes a struct into bencode fn serializeStruct(self: Self, value: anytype) Error!void { try self.writer.writeByte('d'); inline for (meta.fields(@TypeOf(value))) |field| { // make sure to not write null fields if (@typeInfo(field.field_type) != .Optional or @field(value, field.name) != null) { try self.writer.print("{d}:{s}", .{ field.name.len, &encodeFieldName(field.name) }); try self.serialize(@field(value, field.name)); } } try self.writer.writeByte('e'); } /// Encodes a field name to bencode field by replacing underscores to spaces fn encodeFieldName(comptime name: []const u8) [name.len]u8 { var result: [name.len]u8 = undefined; for (name) |c, i| { const actual = if (c == '_') ' ' else c; result[i] = actual; } return result; } /// Serializes an integer to bencode integer fn serializeInt(self: Self, value: anytype) Error!void { try self.writer.print("i{d}e", .{value}); } /// Serializes a slice of bytes to bencode string fn serializeString(self: Self, value: []const u8) Error!void { try self.writer.print("{d}:{s}", .{ value.len, value }); } /// Serializes a slice of elements to bencode list fn serializeList(self: Self, value: anytype) Error!void { try self.writer.writeByte('l'); for (value) |element| try self.serialize(element); try self.writer.writeByte('e'); } }; } /// Creates a new serializer instance with a Serializer type based on the given writer pub fn serializer(writer: anytype) Serializer(@TypeOf(writer)) { return Serializer(@TypeOf(writer)).init(writer); } test "Deserialize Bencode to Zig struct" { // allow newlines to increase readability of test var bencode_string = "d8:announce41:http://bttracker.debian.org:6969/announce" ++ "7:comment35:\"Debian CD from cdimage.debian.org\"13:creation date" ++ "i1573903810e4:infod6:lengthi351272960e4:name31:debian-10.2.0-amd64-netinst.iso" ++ "12:piece lengthi262144eee"; const Info = struct { length: ?usize, name: []const u8, piece_length: usize, }; const Announce = struct { announce: []const u8, comment: []const u8, creation_date: usize, info: Info, }; const expected = Announce{ .announce = "http://bttracker.debian.org:6969/announce", .comment = "\"Debian CD from cdimage.debian.org\"", .creation_date = 1573903810, .info = Info{ .length = 351272960, .name = "debian-10.2.0-amd64-netinst.iso", .piece_length = 262144, }, }; var in = std.io.fixedBufferStream(bencode_string); var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var des = deserializer(&arena.allocator, in.reader()); const result = try des.deserialize(Announce); testing.expectEqual(expected.creation_date, result.creation_date); testing.expectEqualStrings(expected.announce, result.announce); testing.expectEqualStrings(expected.info.name, result.info.name); testing.expectEqualStrings(expected.comment, result.comment); testing.expectEqual(expected.info.length, result.info.length); } test "Serialize Zig value to Bencode" { const Child = struct { field: []const u8, }; const TestStruct = struct { name: []const u8, length: usize, child: Child, }; const value = TestStruct{ .name = "<NAME>", .length = 1236, .child = .{ .field = "other value" }, }; var list = std.ArrayList(u8).init(testing.allocator); defer list.deinit(); var ser = serializer(list.writer()); try ser.serialize(value); const expected = "d4:name12:random value6:lengthi1236e5:childd5:field11:other valueee"; testing.expectEqualStrings(expected, list.items); }
src/bencode.zig
const builtin = @import("builtin"); const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const warn = std.debug.warn; const gl = @import("modules/zig-sdl2/src/index.zig"); const ie = @import("input_events.zig"); const wdw = @import("window.zig"); const WindowState = struct { window: wdw.Window, quit: bool, leftMouseButtonDown: bool, ei: ie.EventInterface, bg_color: u32, fg_color: u32, width: usize, height: usize, }; fn handleKeyEvent(pThing: *c_void, event: *gl.SDL_Event) ie.EventResult { var pWs = @intToPtr(*WindowState, @ptrToInt(pThing)); switch (event.type) { gl.SDL_KEYUP => { if (event.key.keysym.sym == gl.SDLK_ESCAPE) { pWs.quit = true; return ie.EventResult.Quit; } }, else => {}, } return ie.EventResult.Continue; } fn handleMouseEvent(pThing: *c_void, event: *gl.SDL_Event) ie.EventResult { var pWs = @intToPtr(*WindowState, @ptrToInt(pThing)); switch (event.type) { gl.SDL_MOUSEBUTTONUP => { assert(gl.SDL_BUTTON_LMASK == 1); if (event.button.button == gl.SDL_BUTTON_LEFT) { pWs.leftMouseButtonDown = false; } }, gl.SDL_MOUSEBUTTONDOWN => { if (event.button.button == gl.SDL_BUTTON_LEFT) { pWs.leftMouseButtonDown = true; } }, gl.SDL_MOUSEMOTION => { if (pWs.leftMouseButtonDown) { var mouse_x: usize = @intCast(usize, event.motion.x); var mouse_y: usize = @intCast(usize, event.motion.y); pWs.window.putPixel(mouse_x, mouse_y, pWs.fg_color); } }, else => {}, } return ie.EventResult.Continue; } fn handleOtherEvent(pThing: *c_void, event: *gl.SDL_Event) ie.EventResult { return ie.EventResult.Continue; } pub fn main() u8 { var direct_allocator = std.heap.DirectAllocator.init(); var arena_allocator = std.heap.ArenaAllocator.init(&direct_allocator.allocator); defer arena_allocator.deinit(); var pAllocator = &arena_allocator.allocator; var ws = WindowState{ .window = undefined, .quit = false, .leftMouseButtonDown = false, .ei = ie.EventInterface{ .event = undefined, .handleKeyEvent = handleKeyEvent, .handleMouseEvent = handleMouseEvent, .handleOtherEvent = handleOtherEvent, }, .bg_color = 0x00000000, // black .fg_color = 0xffffffff, // white .width = 640, .height = 480, }; ws.window = wdw.Window.init(pAllocator, ws.width, ws.height, "zig-3d-soft-engine") catch |e| { warn("Could not init window: {}\n", e); return 1; }; defer ws.window.deinit(); while (!ws.quit) { // Process all events noEvents: while (true) { switch (ie.pollInputEvent(&ws, &ws.ei)) { ie.EventResult.NoEvents => { break :noEvents; }, ie.EventResult.Quit => { ws.quit = true; break :noEvents; }, ie.EventResult.Continue => {}, } } // Update display ws.window.present(); } return 0; }
src/main.zig
const std = @import("std"); const mem = std.mem; const print = std.debug.print; const assert = std.debug.assert; pub const CsvTokenType = enum { field, row_end }; pub const CsvToken = union(CsvTokenType) { field: []const u8, row_end: void }; pub const CsvError = error{ ShortBuffer, MisplacedQuote, NoSeparatorAfterField }; pub const CsvConfig = struct { col_sep: u8 = ',', row_sep: u8 = '\n', quote: u8 = '"' }; const QuoteFieldReadResult = struct { value: []u8, contains_quotes: bool }; fn CsvReader(comptime Reader: type) type { // TODO comptime return struct { buffer: []u8, current: []u8, reader: Reader, all_read: bool = false, const Self = @This(); pub fn init(reader: Reader, buffer: []u8) Self { return .{ .buffer = buffer, .current = buffer[0..0], .reader = reader, }; } inline fn empty(self: *Self) bool { return self.current.len == 0; } pub fn char(self: *Self) !?u8 { if (!try self.ensureData()) { return null; } const c = self.current[0]; self.current = self.current[1..]; return c; } pub inline fn peek(self: *Self) !?u8 { if (!try self.ensureData()) { return null; } return self.current[0]; } pub fn until(self: *Self, terminators: []const u8) !?[]u8 { if (!try self.ensureData()) { return null; } for (self.current) |c, pos| { // TODO inline for (terminators) |ct| { if (c == ct) { const s = self.current[0..pos]; self.current = self.current[pos..]; // print("{}|{}", .{ s, self.current }); return s; } } } // print("ALL_READ: {}\n", .{self.all_read}); return null; } pub fn untilClosingQuote(self: *Self, quote: u8) !?QuoteFieldReadResult { if (!try self.ensureData()) { return null; } var idx: usize = 0; var contains_quotes: bool = false; while (idx < self.current.len) : (idx += 1) { const c = self.current[idx]; // print("IDX QUOTED: {}={c}\n", .{ idx, c }); if (c == quote) { // double quotes, shift forward // print("PEEK {c}\n", .{buffer[idx + 1]}); if (idx < self.current.len - 1 and self.current[idx + 1] == '"') { // print("DOUBLE QUOTES\n", .{}); contains_quotes = true; idx += 1; } else { // print("ALL_READ {}\n", .{self.all_read}); if (!self.all_read and idx == self.current.len - 1) { return null; } const s = self.current[0..idx]; self.current = self.current[idx..]; return QuoteFieldReadResult{ .value = s, .contains_quotes = contains_quotes }; } } } return null; } /// Tries to read more data from an underlying reader if buffer is not already full. /// If anything was read returns true, otherwise false. pub fn read(self: *Self) !bool { const current_len = self.current.len; if (current_len == self.buffer.len) { return false; } if (current_len > 0) { mem.copy(u8, self.buffer, self.current); } const read_len = try self.reader.read(self.buffer[current_len..]); // print("READ: current_len={} read_len={}\n", .{ current_len, read_len }); self.current = self.buffer[0 .. current_len + read_len]; self.all_read = read_len == 0; return read_len > 0; } // Ensures that there are some data in the buffer. Returns false if no data are available pub inline fn ensureData(self: *Self) !bool { if (!self.empty()) { return true; } if (self.all_read) { return false; } return self.read(); } }; } /// Tokenizes input from reader into stream of CsvTokens pub fn CsvTokenizer(comptime Reader: type) type { const Status = enum { initial, row_start, field, quoted_field_end, row_end, eof }; return struct { const Self = @This(); config: CsvConfig, terminal_chars: [3]u8 = undefined, reader: CsvReader(Reader), status: Status = .initial, pub fn init(reader: Reader, buffer: []u8, config: CsvConfig) !Self { return Self{ .config = config, .terminal_chars = [_]u8{ config.col_sep, config.row_sep, '"' }, .reader = CsvReader(Reader).init(reader, buffer), }; } pub fn next(self: *Self) !?CsvToken { var next_status: ?Status = self.status; // Cannot use anonymous enum literals for Status // https://github.com/ziglang/zig/issues/4255 while (next_status) |status| { // print("STATUS: {}\n", .{self.status}); next_status = switch (status) { .initial => if (try self.reader.read()) Status.row_start else Status.eof, .row_start => if (!try self.reader.ensureData()) Status.eof else Status.field, .field => blk: { if (!try self.reader.ensureData()) { break :blk .row_end; } return try self.parseField(); }, .quoted_field_end => blk: { // read closing quotes const quote = try self.reader.char(); assert(quote == self.config.quote); if (!try self.reader.ensureData()) { break :blk Status.row_end; } const c = (try self.reader.peek()); if (c) |value| { // print("END: {}\n", .{value}); if (value == self.config.col_sep) { // TODO write repro for assert with optional // const col_sep = try self.reader.char(); // assert(col_sep == self.config.col_sep); const col_sep = (try self.reader.char()).?; assert(col_sep == self.config.col_sep); break :blk Status.field; } if (value == self.config.row_sep) { break :blk Status.row_end; } // quote means that it did not fit into buffer and it cannot be analyzed as "" if (value == self.config.quote) { return CsvError.ShortBuffer; } } else { break :blk Status.eof; } return CsvError.NoSeparatorAfterField; }, .row_end => { if (!try self.reader.ensureData()) { self.status = Status.eof; return CsvToken{ .row_end = {} }; } const rowSep = try self.reader.char(); assert(rowSep == self.config.row_sep); self.status = Status.row_start; return CsvToken{ .row_end = {} }; }, .eof => { return null; }, }; // make the transition and also ensure that next_status is set at this point self.status = next_status.?; } unreachable; } fn parseField(self: *Self) !CsvToken { const first = (try self.reader.peek()).?; if (first != '"') { var field = try self.reader.until(&self.terminal_chars); if (field == null) { // force read - maybe separator was not read yet const hasData = try self.reader.read(); if (!hasData) { return CsvError.ShortBuffer; } field = try self.reader.until(&self.terminal_chars); if (field == null) { return CsvError.ShortBuffer; } } const terminator = (try self.reader.peek()).?; if (terminator == self.config.col_sep) { _ = try self.reader.char(); return CsvToken{ .field = field.? }; } if (terminator == self.config.row_sep) { self.status = .row_end; return CsvToken{ .field = field.? }; } if (terminator == self.config.quote) { return CsvError.MisplacedQuote; } return CsvError.ShortBuffer; } else { // consume opening quote _ = try self.reader.char(); var quoted_field = try self.reader.untilClosingQuote(self.config.quote); if (quoted_field == null) { // force read - maybe separator was not read yet const hasData = try self.reader.read(); if (!hasData) { return CsvError.ShortBuffer; } // this read will fill the buffer quoted_field = try self.reader.untilClosingQuote(self.config.quote); if (quoted_field == null) { return CsvError.ShortBuffer; } } self.status = .quoted_field_end; const field = quoted_field.?; if (!field.contains_quotes) { return CsvToken{ .field = field.value }; } else { // walk the field and remove double quotes by shifting bytes const value = field.value; var diff: u64 = 0; var idx: usize = 0; while (idx < value.len) : (idx += 1) { const c = value[idx]; value[idx - diff] = c; if (c == self.config.quote) { diff += 1; idx += 1; } } return CsvToken{ .field = value[0 .. value.len - diff] }; } } } }; }
src/main.zig
const std = @import("std"); const time = std.time; const math = @import("./math.zig"); fn print_row(stdout: anytype, f: []const u8, v: f32, t: f64) void { stdout.print("{s: >8} {d: >5.2} {d: >5.2}s {d: >5.3}s\n", .{ f, v, t, t }) catch unreachable; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); var prng = std.rand.DefaultPrng.init(@intCast(u64, time.milliTimestamp())); const M = 2 << 16; const N = 1024; var start: i128 = undefined; var end: i128 = undefined; var acc: i128 = undefined; var i: usize = undefined; var j: usize = undefined; var X: [N]f32 = undefined; var Y: [N]f32 = undefined; // tests rewritten until results confirmed hypothesis i = 0; while (i < N) : (i += 1) { X[i] = prng.random.float(f32); } stdout.print("{}\n", .{X[0]}) catch unreachable; stdout.print("{s: <8} {s: <5} {s: <7}\n", .{ "function", "value", "time" }) catch unreachable; i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = @sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "@sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = std.math.sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = math.a_sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "a_sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = math.f_sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "f_sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = 1 / @sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "1/@sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = 1 / std.math.sqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "1/sqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = math.a_isqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "a_isqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); i = 0; start = time.nanoTimestamp(); while (i < M) : (i += 1) { j = 0; while (j < N) : (j += 1) { Y[j] = math.f_isqrt(X[j]); } } end = time.nanoTimestamp(); print_row(stdout, "f_isqrt", Y[0], (@intToFloat(f64, end - start) / 1_000_000_000.0)); }
src/time.zig
const std = @import("std"); const ascii = std.ascii; const fmt = std.fmt; const mem = std.mem; const io = std.io; const assert = std.debug.assert; const base = @import("../main.zig").base; usingnamespace @import("common.zig"); const AllocError = mem.Allocator.Error; pub fn create(options: RequestOptions, reader: anytype, writer: anytype) AllocError!Request(@TypeOf(reader), @TypeOf(writer)) { return Request(@TypeOf(reader), @TypeOf(writer)).init(options, reader, writer); } const RequestLogger = std.log.scoped(.request); pub fn Request(comptime Reader: type, comptime Writer: type) type { const ReaderError = if (@typeInfo(Reader) == .Pointer) @typeInfo(Reader).Pointer.child.Error else Reader.Error; const WriterError = if (@typeInfo(Writer) == .Pointer) @typeInfo(Writer).Pointer.child.Error else Writer.Error; return struct { const Self = @This(); pub const SendError = WriterError || error{ RequestAlreadySent, InvalidRequest }; pub const ReadRequestError = InternalClient.ReadError || AllocError || error{ ConnectionClosed, InvalidResponse }; pub const ReadNextChunkError = InternalClient.ReadError || AllocError || error{ ConnectionClosed, UnconsumedRequestHead, InvalidResponse }; pub const ReadChunkError = ReadNextChunkError; pub const Chunk = base.ChunkEvent; pub const InternalClient = base.Client.Client(Reader, Writer); pub const ChunkReader = io.Reader(*Self, ReadChunkError, readChunkBuffer); options: RequestOptions, read_buffer: []u8, arena: std.heap.ArenaAllocator, internal: InternalClient, sent: bool = false, status: RequestStatus, headers: std.http.Headers, payload_index: usize = 0, payload_size: usize = 0, pub fn init(options: RequestOptions, input: Reader, output: Writer) AllocError!Self { var buffer = try options.allocator.alloc(u8, options.read_buffer_size); return Self{ .options = options, .arena = std.heap.ArenaAllocator.init(options.allocator), .read_buffer = buffer, .internal = InternalClient.init(buffer, input, output), .status = undefined, .headers = std.http.Headers.init(options.allocator), }; } pub fn deinit(self: *Self) void { self.internal = undefined; self.headers.deinit(); self.arena.deinit(); self.options.allocator.free(self.read_buffer); } pub fn prepare(self: *Self) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHead(self.options.method, self.options.path); try self.internal.writeHeaderValue("Host", self.options.host); } pub fn addHeaderValue(self: *Self, name: []const u8, value: []const u8) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHeaderValue(name, value); } pub fn addHeaderValueFormat(self: *Self, name: []const u8, comptime format: []const u8, args: anytype) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHeaderValueFormat(name, format, args); } pub fn addHeader(self: *Self, header: base.Header) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHeader(header); } pub fn addHeaders(self: *Self, headers: base.Headers) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHeaders(headers); } pub fn addStdHeaders(self: *Self, headers: std.http.Headers) SendError!void { if (self.internal.head_sent) return error.RequestAlreadySent; try self.internal.writeHeaders(headers.toSlice()); } pub fn finish(self: *Self) SendError!void { if (self.sent) return error.RequestAlreadySent; try self.internal.writeHeadComplete(); self.sent = true; } pub fn send(self: *Self, chunk: []const u8) SendError!void { if (self.sent) return error.RequestAlreadySent; if (self.internal.send_encoding == .unknown) { try self.internal.writeHeaderValueFormat("Content-Length", "{d}", .{chunk.len}); } else if (self.internal.send_encoding == .chunked) { return error.InvalidRequest; } try self.internal.writeHeadComplete(); try self.internal.writeChunk(chunk); self.sent = true; } pub fn sendChunked(self: *Self, chunk: ?[]const u8) SendError!void { if (self.sent) return error.RequestAlreadySent; if (self.internal.send_encoding == .unknown) { try self.internal.writeHeaderValue("Transfer-Encoding", "chunked"); } else if (self.internal.send_encoding == .length) { return error.InvalidRequest; } try self.internal.writeHeadComplete(); try self.internal.writeChunk(chunk); } pub fn readRequest(self: *Self) ReadRequestError!void { if (self.internal.state == .payload) return; while (try self.internal.readEvent()) |event| { switch (event) { .status => |data| { self.status = RequestStatus.init(data.code); }, .header => |header| { var value = try self.arena.allocator.dupe(u8, header.value); try self.headers.append(header.name, value, null); }, .head_complete => break, .end, .closed => return error.ConnectionClosed, .invalid => |data| { RequestLogger.warn("invalid response while reading {}: {}", .{ @tagName(data.state), data.message }); return error.InvalidResponse; }, .chunk => unreachable, } } } fn readNextChunk(self: *Self) ReadNextChunkError!?Chunk { if (self.internal.state != .payload) return error.UnconsumedRequestHead; if (try self.internal.readEvent()) |event| { switch (event) { .status, .header, .head_complete => unreachable, .chunk => |chunk| return chunk, .end => return null, .closed => return error.ConnectionClosed, .invalid => |data| { RequestLogger.warn("invalid response while reading {}: {}", .{ @tagName(data.state), data.message }); return error.InvalidResponse; }, } } } pub fn readChunkBuffer(self: *Self, dest: []u8) ReadChunkError!usize { if (self.payload_index >= self.payload_size) { if (try self.internal.readEvent()) |event| { switch (event) { .status, .header, .head_complete => unreachable, .chunk => |chunk| { const size = std.math.min(dest.len, chunk.data.len); mem.copy(u8, dest[0..size], chunk.data[0..size]); self.payload_size = chunk.data.len; self.payload_index = size; return size; }, .end => return 0, .closed => return error.ConnectionClosed, .invalid => |data| { RequestLogger.warn("invalid response while reading {}: {}", .{ @tagName(data.state), data.message }); return error.InvalidResponse; }, } } else { return error.ConnectionClosed; } } else { const start = self.payload_index; const size = std.math.min(dest.len, self.payload_size - start); const end = start + size; mem.copy(u8, dest[0..size], self.read_buffer[start..end]); self.payload_index = end; return size; } } pub fn payloadReader(self: *Self) ChunkReader { return .{ .context = self }; } }; } const testing = std.testing; test "test" { var the_void: [1024]u8 = undefined; var response = "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ngood"; const allocator = testing.allocator; var reader = io.fixedBufferStream(response).reader(); var writer = io.fixedBufferStream(&the_void).writer(); var request = try create(.{ .allocator = allocator, .method = "GET", .path = "/", .host = "www.example.com", }, reader, writer); defer request.deinit(); try request.prepare(); try request.addHeader(.{ .name = "X-Header", .value = "value" }); try request.addHeaderValue("X-Header-value", "value"); try request.addHeaderValueFormat("X-Header-Fmt", "random number={d}", .{42}); try request.finish(); try request.readRequest(); testing.expect(request.status.code == 200); testing.expect(request.status.kind == .success); var payload_reader = request.payloadReader(); var payload = try payload_reader.readAllAlloc(allocator, 8); defer allocator.free(payload); testing.expectEqualStrings("good", payload); }
lib/hzzp/src/basic/request.zig
const std = @import("std"); const use_test_input = false; const filename = if (use_test_input) "day-5_test-input" else "day-5_real-input"; const edge_length = if (use_test_input) 10 else 1000; const line_count = if (use_test_input) 10 else 500; pub fn main() !void { std.debug.print("--- Day 5 ---\n", .{}); var file = try std.fs.cwd().openFile(filename, .{}); var vent_counts = [_]i32 {0} ** (edge_length * edge_length); { var buffer: [3]u8 = undefined; var line_index: usize = 0; while (line_index < line_count):(line_index += 1) { const x1_string = try file.reader().readUntilDelimiter(buffer[0..], ','); const x1 = try std.fmt.parseInt(i32, x1_string, 10); const y1_string = try file.reader().readUntilDelimiter(buffer[0..], ' '); const y1 = try std.fmt.parseInt(i32, y1_string, 10); _ = try file.reader().readUntilDelimiter(buffer[0..], ' '); const x2_string = try file.reader().readUntilDelimiter(buffer[0..], ','); const x2 = try std.fmt.parseInt(i32, x2_string, 10); const y2_string = try file.reader().readUntilDelimiter(buffer[0..], '\n'); const y2 = try std.fmt.parseInt(i32, y2_string, 10); { var x_increment: i32 = 0; var y_increment: i32 = 0; if (x1 != x2) { x_increment = if (x1 < x2) 1 else -1; } if (y1 != y2) { y_increment = if (y1 < y2) 1 else -1; } var x = x1; var y = y1; while (true) { const i = @intCast(usize, y * edge_length + x); vent_counts[i] += 1; x += x_increment; y += y_increment; if (x == x2 + x_increment and y == y2 + y_increment) { break; } } } } } var at_least_two: u32 = 0; { var y: usize = 0; while (y < edge_length):(y += 1) { var x: usize = 0; while (x < edge_length):(x += 1) { const i = y * edge_length + x; if (vent_counts[i] >= 2) { at_least_two += 1; } } } } std.debug.print("at {} points do at least two lines overlap\n", .{ at_least_two }); }
day-5.zig
const std = @import("std"); const math = std.math; const Module = @import("module.zig").Module; const Range = @import("common.zig").Range; const Validator = @import("validator.zig").Validator; const ValueType = @import("common.zig").ValueType; const LocalType = @import("common.zig").LocalType; const ArrayList = std.ArrayList; const opcode = @import("opcode.zig"); const Opcode = @import("opcode.zig").Opcode; const valueTypeFromBlockType = @import("common.zig").valueTypeFromBlockType; // Runtime opcodes (wasm opcodes + optimisations) pub const RuntimeOpcode = enum(u8) { @"unreachable" = 0x0, nop = 0x01, block = 0x02, loop = 0x03, @"if" = 0x04, @"else" = 0x05, if_no_else = 0x06, end = 0x0b, br = 0x0c, br_if = 0x0d, br_table = 0x0e, @"return" = 0x0f, call = 0x10, call_indirect = 0x11, fast_call = 0x12, drop = 0x1a, select = 0x1b, @"local.get" = 0x20, @"local.set" = 0x21, @"local.tee" = 0x22, @"global.get" = 0x23, @"global.set" = 0x24, @"i32.load" = 0x28, @"i64.load" = 0x29, @"f32.load" = 0x2a, @"f64.load" = 0x2b, @"i32.load8_s" = 0x2c, @"i32.load8_u" = 0x2d, @"i32.load16_s" = 0x2e, @"i32.load16_u" = 0x2f, @"i64.load8_s" = 0x30, @"i64.load8_u" = 0x31, @"i64.load16_s" = 0x32, @"i64.load16_u" = 0x33, @"i64.load32_s" = 0x34, @"i64.load32_u" = 0x35, @"i32.store" = 0x36, @"i64.store" = 0x37, @"f32.store" = 0x38, @"f64.store" = 0x39, @"i32.store8" = 0x3a, @"i32.store16" = 0x3b, @"i64.store8" = 0x3c, @"i64.store16" = 0x3d, @"i64.store32" = 0x3e, @"memory.size" = 0x3f, @"memory.grow" = 0x40, @"i32.const" = 0x41, @"i64.const" = 0x42, @"f32.const" = 0x43, @"f64.const" = 0x44, @"i32.eqz" = 0x45, @"i32.eq" = 0x46, @"i32.ne" = 0x47, @"i32.lt_s" = 0x48, @"i32.lt_u" = 0x49, @"i32.gt_s" = 0x4a, @"i32.gt_u" = 0x4b, @"i32.le_s" = 0x4c, @"i32.le_u" = 0x4d, @"i32.ge_s" = 0x4e, @"i32.ge_u" = 0x4f, @"i64.eqz" = 0x50, @"i64.eq" = 0x51, @"i64.ne" = 0x52, @"i64.lt_s" = 0x53, @"i64.lt_u" = 0x54, @"i64.gt_s" = 0x55, @"i64.gt_u" = 0x56, @"i64.le_s" = 0x57, @"i64.le_u" = 0x58, @"i64.ge_s" = 0x59, @"i64.ge_u" = 0x5a, @"f32.eq" = 0x5b, @"f32.ne" = 0x5c, @"f32.lt" = 0x5d, @"f32.gt" = 0x5e, @"f32.le" = 0x5f, @"f32.ge" = 0x60, @"f64.eq" = 0x61, @"f64.ne" = 0x62, @"f64.lt" = 0x63, @"f64.gt" = 0x64, @"f64.le" = 0x65, @"f64.ge" = 0x66, @"i32.clz" = 0x67, @"i32.ctz" = 0x68, @"i32.popcnt" = 0x69, @"i32.add" = 0x6a, @"i32.sub" = 0x6b, @"i32.mul" = 0x6c, @"i32.div_s" = 0x6d, @"i32.div_u" = 0x6e, @"i32.rem_s" = 0x6f, @"i32.rem_u" = 0x70, @"i32.and" = 0x71, @"i32.or" = 0x72, @"i32.xor" = 0x73, @"i32.shl" = 0x74, @"i32.shr_s" = 0x75, @"i32.shr_u" = 0x76, @"i32.rotl" = 0x77, @"i32.rotr" = 0x78, @"i64.clz" = 0x79, @"i64.ctz" = 0x7a, @"i64.popcnt" = 0x7b, @"i64.add" = 0x7c, @"i64.sub" = 0x7d, @"i64.mul" = 0x7e, @"i64.div_s" = 0x7f, @"i64.div_u" = 0x80, @"i64.rem_s" = 0x81, @"i64.rem_u" = 0x82, @"i64.and" = 0x83, @"i64.or" = 0x84, @"i64.xor" = 0x85, @"i64.shl" = 0x86, @"i64.shr_s" = 0x87, @"i64.shr_u" = 0x88, @"i64.rotl" = 0x89, @"i64.rotr" = 0x8a, @"f32.abs" = 0x8b, @"f32.neg" = 0x8c, @"f32.ceil" = 0x8d, @"f32.floor" = 0x8e, @"f32.trunc" = 0x8f, @"f32.nearest" = 0x90, @"f32.sqrt" = 0x91, @"f32.add" = 0x92, @"f32.sub" = 0x93, @"f32.mul" = 0x94, @"f32.div" = 0x95, @"f32.min" = 0x96, @"f32.max" = 0x97, @"f32.copysign" = 0x98, @"f64.abs" = 0x99, @"f64.neg" = 0x9a, @"f64.ceil" = 0x9b, @"f64.floor" = 0x9c, @"f64.trunc" = 0x9d, @"f64.nearest" = 0x9e, @"f64.sqrt" = 0x9f, @"f64.add" = 0xa0, @"f64.sub" = 0xa1, @"f64.mul" = 0xa2, @"f64.div" = 0xa3, @"f64.min" = 0xa4, @"f64.max" = 0xa5, @"f64.copysign" = 0xa6, @"i32.wrap_i64" = 0xa7, @"i32.trunc_f32_s" = 0xa8, @"i32.trunc_f32_u" = 0xa9, @"i32.trunc_f64_s" = 0xaa, @"i32.trunc_f64_u" = 0xab, @"i64.extend_i32_s" = 0xac, @"i64.extend_i32_u" = 0xad, @"i64.trunc_f32_s" = 0xae, @"i64.trunc_f32_u" = 0xaf, @"i64.trunc_f64_s" = 0xb0, @"i64.trunc_f64_u" = 0xb1, @"f32.convert_i32_s" = 0xb2, @"f32.convert_i32_u" = 0xb3, @"f32.convert_i64_s" = 0xb4, @"f32.convert_i64_u" = 0xb5, @"f32.demote_f64" = 0xb6, @"f64.convert_i32_s" = 0xb7, @"f64.convert_i32_u" = 0xb8, @"f64.convert_i64_s" = 0xb9, @"f64.convert_i64_u" = 0xba, @"f64.promote_f32" = 0xbb, @"i32.reinterpret_f32" = 0xbc, @"i64.reinterpret_f64" = 0xbd, @"f32.reinterpret_i32" = 0xbe, @"f64.reinterpret_i64" = 0xbf, @"i32.extend8_s" = 0xc0, @"i32.extend16_s" = 0xc1, @"i64.extend8_s" = 0xc2, @"i64.extend16_s" = 0xc3, @"i64.extend32_s" = 0xc4, trunc_sat = 0xfc, }; pub const Instruction = union(RuntimeOpcode) { @"unreachable": void, nop: void, block: struct { param_arity: u16, return_arity: u16, branch_target: u32, }, loop: struct { param_arity: u16, return_arity: u16, branch_target: u32, }, @"if": struct { param_arity: u16, return_arity: u16, branch_target: u32, else_ip: u32, }, @"else": void, if_no_else: struct { param_arity: u16, return_arity: u16, branch_target: u32, }, end: void, br: u32, br_if: u32, br_table: struct { ls: Range, ln: u32, }, @"return": void, call: usize, // u32? call_indirect: struct { @"type": u32, table: u32, }, fast_call: struct { start: u32, locals: u16, params: u16, results: u16, required_stack_space: u16, }, drop: void, select: void, @"local.get": u32, @"local.set": u32, @"local.tee": u32, @"global.get": u32, @"global.set": u32, @"i32.load": struct { alignment: u32, offset: u32, }, @"i64.load": struct { alignment: u32, offset: u32, }, @"f32.load": struct { alignment: u32, offset: u32, }, @"f64.load": struct { alignment: u32, offset: u32, }, @"i32.load8_s": struct { alignment: u32, offset: u32, }, @"i32.load8_u": struct { alignment: u32, offset: u32, }, @"i32.load16_s": struct { alignment: u32, offset: u32, }, @"i32.load16_u": struct { alignment: u32, offset: u32, }, @"i64.load8_s": struct { alignment: u32, offset: u32, }, @"i64.load8_u": struct { alignment: u32, offset: u32, }, @"i64.load16_s": struct { alignment: u32, offset: u32, }, @"i64.load16_u": struct { alignment: u32, offset: u32, }, @"i64.load32_s": struct { alignment: u32, offset: u32, }, @"i64.load32_u": struct { alignment: u32, offset: u32, }, @"i32.store": struct { alignment: u32, offset: u32, }, @"i64.store": struct { alignment: u32, offset: u32, }, @"f32.store": struct { alignment: u32, offset: u32, }, @"f64.store": struct { alignment: u32, offset: u32, }, @"i32.store8": struct { alignment: u32, offset: u32, }, @"i32.store16": struct { alignment: u32, offset: u32, }, @"i64.store8": struct { alignment: u32, offset: u32, }, @"i64.store16": struct { alignment: u32, offset: u32, }, @"i64.store32": struct { alignment: u32, offset: u32, }, @"memory.size": u32, @"memory.grow": u32, @"i32.const": i32, @"i64.const": i64, @"f32.const": f32, @"f64.const": f64, @"i32.eqz": void, @"i32.eq": void, @"i32.ne": void, @"i32.lt_s": void, @"i32.lt_u": void, @"i32.gt_s": void, @"i32.gt_u": void, @"i32.le_s": void, @"i32.le_u": void, @"i32.ge_s": void, @"i32.ge_u": void, @"i64.eqz": void, @"i64.eq": void, @"i64.ne": void, @"i64.lt_s": void, @"i64.lt_u": void, @"i64.gt_s": void, @"i64.gt_u": void, @"i64.le_s": void, @"i64.le_u": void, @"i64.ge_s": void, @"i64.ge_u": void, @"f32.eq": void, @"f32.ne": void, @"f32.lt": void, @"f32.gt": void, @"f32.le": void, @"f32.ge": void, @"f64.eq": void, @"f64.ne": void, @"f64.lt": void, @"f64.gt": void, @"f64.le": void, @"f64.ge": void, @"i32.clz": void, @"i32.ctz": void, @"i32.popcnt": void, @"i32.add": void, @"i32.sub": void, @"i32.mul": void, @"i32.div_s": void, @"i32.div_u": void, @"i32.rem_s": void, @"i32.rem_u": void, @"i32.and": void, @"i32.or": void, @"i32.xor": void, @"i32.shl": void, @"i32.shr_s": void, @"i32.shr_u": void, @"i32.rotl": void, @"i32.rotr": void, @"i64.clz": void, @"i64.ctz": void, @"i64.popcnt": void, @"i64.add": void, @"i64.sub": void, @"i64.mul": void, @"i64.div_s": void, @"i64.div_u": void, @"i64.rem_s": void, @"i64.rem_u": void, @"i64.and": void, @"i64.or": void, @"i64.xor": void, @"i64.shl": void, @"i64.shr_s": void, @"i64.shr_u": void, @"i64.rotl": void, @"i64.rotr": void, @"f32.abs": void, @"f32.neg": void, @"f32.ceil": void, @"f32.floor": void, @"f32.trunc": void, @"f32.nearest": void, @"f32.sqrt": void, @"f32.add": void, @"f32.sub": void, @"f32.mul": void, @"f32.div": void, @"f32.min": void, @"f32.max": void, @"f32.copysign": void, @"f64.abs": void, @"f64.neg": void, @"f64.ceil": void, @"f64.floor": void, @"f64.trunc": void, @"f64.nearest": void, @"f64.sqrt": void, @"f64.add": void, @"f64.sub": void, @"f64.mul": void, @"f64.div": void, @"f64.min": void, @"f64.max": void, @"f64.copysign": void, @"i32.wrap_i64": void, @"i32.trunc_f32_s": void, @"i32.trunc_f32_u": void, @"i32.trunc_f64_s": void, @"i32.trunc_f64_u": void, @"i64.extend_i32_s": void, @"i64.extend_i32_u": void, @"i64.trunc_f32_s": void, @"i64.trunc_f32_u": void, @"i64.trunc_f64_s": void, @"i64.trunc_f64_u": void, @"f32.convert_i32_s": void, @"f32.convert_i32_u": void, @"f32.convert_i64_s": void, @"f32.convert_i64_u": void, @"f32.demote_f64": void, @"f64.convert_i32_s": void, @"f64.convert_i32_u": void, @"f64.convert_i64_s": void, @"f64.convert_i64_u": void, @"f64.promote_f32": void, @"i32.reinterpret_f32": void, @"i64.reinterpret_f64": void, @"f32.reinterpret_i32": void, @"f64.reinterpret_i64": void, @"i32.extend8_s": void, @"i32.extend16_s": void, @"i64.extend8_s": void, @"i64.extend16_s": void, @"i64.extend32_s": void, trunc_sat: u32, }; const EMPTY = [0]ValueType{} ** 0; const I32_OUT = [1]ValueType{.I32} ** 1; const I64_OUT = [1]ValueType{.I64} ** 1; const F32_OUT = [1]ValueType{.F32} ** 1; const F64_OUT = [1]ValueType{.F64} ** 1; pub const ParseIterator = struct { function: []const u8, code: []const u8, code_ptr: usize, parsed: *ArrayList(Instruction), module: *Module, validator: Validator, params: ?[]const ValueType, locals: ?[]LocalType, continuation_stack: []usize, continuation_stack_ptr: usize, pub fn init(module: *Module, function: []const u8, parsed_code: *ArrayList(Instruction), continuation_stack: []usize) ParseIterator { return ParseIterator{ .code = function, .code_ptr = parsed_code.items.len, .function = function, .parsed = parsed_code, .module = module, .params = null, .locals = null, // TODO: what type of allocator is this? // we want to free this every function parse, so we // want a general purpose allocator, not an arena allocator .validator = Validator.init(module.alloc), .continuation_stack = continuation_stack, .continuation_stack_ptr = 0, }; } // pushFunction initiliase the validator for the current function pub fn pushFunction(self: *ParseIterator, locals: []LocalType, func_index: usize) !void { const function = self.module.functions.list.items[@intCast(usize, func_index)]; const function_type = self.module.types.list.items[@intCast(usize, function.typeidx)]; self.params = function_type.params; self.locals = locals; try self.validator.pushControlFrame( .nop, // block? function_type.params[0..0], function_type.results, ); } fn pushContinuationStack(self: *ParseIterator, offset: usize) !void { defer self.continuation_stack_ptr += 1; if (self.continuation_stack_ptr >= self.continuation_stack.len) return error.ContinuationStackOverflow; self.continuation_stack[self.continuation_stack_ptr] = offset; } fn peekContinuationStack(self: *ParseIterator) usize { return self.continuation_stack[self.continuation_stack_ptr - 1]; } fn popContinuationStack(self: *ParseIterator) !usize { if (self.continuation_stack_ptr <= 0) return error.ContinuationStackUnderflow; self.continuation_stack_ptr -= 1; return self.continuation_stack[self.continuation_stack_ptr]; } pub fn next(self: *ParseIterator) !?Instruction { defer self.code_ptr += 1; if (self.code.len == 0) return null; // 1. Get the instruction we're going to return and increment code const instr = @intToEnum(Opcode, self.code[0]); self.code = self.code[1..]; var rt_instr: Instruction = undefined; // 2. Find the start of the next instruction switch (instr) { .@"unreachable" => rt_instr = Instruction.@"unreachable", .nop => rt_instr = Instruction.nop, .block => { const block_type = try opcode.readILEB128Mem(i32, &self.code); var block_params: u16 = 0; var block_returns: u16 = if (block_type == -0x40) 0 else 1; if (block_type >= 0) { const func_type = self.module.types.list.items[@intCast(usize, block_type)]; block_params = try math.cast(u16, func_type.params.len); block_returns = try math.cast(u16, func_type.results.len); try self.validator.validateBlock(func_type.params, func_type.results); } else { if (block_type == -0x40) { try self.validator.validateBlock(EMPTY[0..], EMPTY[0..]); } else { switch (try valueTypeFromBlockType(block_type)) { .I32 => try self.validator.validateBlock(EMPTY[0..], I32_OUT[0..]), .I64 => try self.validator.validateBlock(EMPTY[0..], I64_OUT[0..]), .F32 => try self.validator.validateBlock(EMPTY[0..], F32_OUT[0..]), .F64 => try self.validator.validateBlock(EMPTY[0..], F64_OUT[0..]), } } } try self.pushContinuationStack(self.code_ptr); rt_instr = Instruction{ .block = .{ .param_arity = block_params, .return_arity = block_returns, .branch_target = 0, }, }; }, .loop => { const block_type = try opcode.readILEB128Mem(i32, &self.code); var block_params: u16 = 0; var block_returns: u16 = if (block_type == -0x40) 0 else 1; if (block_type >= 0) { const func_type = self.module.types.list.items[@intCast(usize, block_type)]; block_params = try math.cast(u16, func_type.params.len); block_returns = try math.cast(u16, func_type.results.len); try self.validator.validateLoop(func_type.params, func_type.results); } else { if (block_type == -0x40) { try self.validator.validateLoop(EMPTY[0..], EMPTY[0..]); } else { switch (try valueTypeFromBlockType(block_type)) { .I32 => try self.validator.validateLoop(EMPTY[0..], I32_OUT[0..]), .I64 => try self.validator.validateLoop(EMPTY[0..], I64_OUT[0..]), .F32 => try self.validator.validateLoop(EMPTY[0..], F32_OUT[0..]), .F64 => try self.validator.validateLoop(EMPTY[0..], F64_OUT[0..]), } } } try self.pushContinuationStack(self.code_ptr); rt_instr = Instruction{ .loop = .{ .param_arity = block_params, .return_arity = block_params, .branch_target = try math.cast(u32, self.code_ptr), }, }; }, .@"if" => { const block_type = try opcode.readILEB128Mem(i32, &self.code); // 1. First assume the number of block params is 0 // 2. The number of return values is 0 if block_type == -0x40 // otherwise assume temporarily that 1 value is returned // 3. If block_type >= 0 then we reference a function type, // so look it up and update the params / returns count to match var block_params: u16 = 0; var block_returns: u16 = if (block_type == -0x40) 0 else 1; if (block_type >= 0) { const func_type = self.module.types.list.items[@intCast(usize, block_type)]; block_params = try math.cast(u16, func_type.params.len); block_returns = try math.cast(u16, func_type.results.len); try self.validator.validateIf(func_type.params, func_type.results); } else { if (block_type == -0x40) { try self.validator.validateIf(EMPTY[0..], EMPTY[0..]); } else { switch (try valueTypeFromBlockType(block_type)) { .I32 => try self.validator.validateIf(EMPTY[0..], I32_OUT[0..]), .I64 => try self.validator.validateIf(EMPTY[0..], I64_OUT[0..]), .F32 => try self.validator.validateIf(EMPTY[0..], F32_OUT[0..]), .F64 => try self.validator.validateIf(EMPTY[0..], F64_OUT[0..]), } } } try self.pushContinuationStack(self.code_ptr); rt_instr = Instruction{ .if_no_else = .{ .param_arity = block_params, .return_arity = block_returns, .branch_target = 0, }, }; }, .@"else" => { const parsed_code_offset = self.peekContinuationStack(); switch (self.parsed.items[parsed_code_offset]) { .if_no_else => |*b| { self.parsed.items[parsed_code_offset] = Instruction{ .@"if" = .{ .param_arity = b.param_arity, .return_arity = b.return_arity, .branch_target = 0, .else_ip = try math.cast(u32, self.code_ptr + 1), }, }; }, else => return error.UnexpectedInstruction, } rt_instr = Instruction.@"else"; }, .end => { // If we're not looking at the `end` of a function if (self.code.len != 0) { const parsed_code_offset = try self.popContinuationStack(); switch (self.parsed.items[parsed_code_offset]) { .block => |*b| b.branch_target = try math.cast(u32, self.code_ptr + 1), .loop => {}, .@"if" => |*b| { b.branch_target = try math.cast(u32, self.code_ptr + 1); }, .if_no_else => |*b| { // We have an if with no else, check that this works arity-wise and replace with fast if if (b.param_arity -% b.return_arity != 0) return error.ValidatorElseBranchExpected; b.branch_target = try math.cast(u32, self.code_ptr + 1); }, else => return error.UnexpectedInstruction, } } rt_instr = Instruction.end; }, .br => { const label = try opcode.readULEB128Mem(u32, &self.code); try self.validator.validateBr(label); rt_instr = Instruction{ .br = label }; }, .br_if => { const label = try opcode.readULEB128Mem(u32, &self.code); try self.validator.validateBrIf(label); rt_instr = Instruction{ .br_if = label }; }, .br_table => { const label_start = self.module.br_table_indices.items.len; const label_count = try opcode.readULEB128Mem(u32, &self.code); var j: usize = 0; while (j < label_count) : (j += 1) { const tmp_label = try opcode.readULEB128Mem(u32, &self.code); try self.module.br_table_indices.append(tmp_label); } const ln = try opcode.readULEB128Mem(u32, &self.code); const l_star = self.module.br_table_indices.items[label_start .. label_start + j]; try self.validator.validateBrTable(l_star, ln); rt_instr = Instruction{ .br_table = .{ .ls = Range{ .offset = label_start, .count = label_count }, .ln = ln, }, }; }, .@"return" => rt_instr = Instruction.@"return", .call => { const function_index = try opcode.readULEB128Mem(u32, &self.code); if (function_index >= self.module.functions.list.items.len) return error.ValidatorCallInvalidFunctionIndex; const function = self.module.functions.list.items[@intCast(usize, function_index)]; const function_type = self.module.types.list.items[@intCast(usize, function.typeidx)]; try self.validator.validateCall(function_type); rt_instr = Instruction{ .call = function_index }; // TODO: do the replacement at instantiate-time for a fastcall if in same module? // rt_instr = Instruction{ .fast_call = .{ .ip_start = 0, .params = 1, .locals = 0, .results = 1 } }; }, .call_indirect => { const type_index = try opcode.readULEB128Mem(u32, &self.code); const table_reserved = try opcode.readByte(&self.code); if (type_index >= self.module.types.list.items.len) return error.ValidatorCallIndirectInvalidTypeIndex; if (self.module.tables.list.items.len != 1) return error.ValidatorCallIndirectNoTable; const function_type = self.module.types.list.items[@intCast(usize, type_index)]; try self.validator.validateCallIndirect(function_type); if (table_reserved != 0) return error.MalformedCallIndirectReserved; rt_instr = Instruction{ .call_indirect = .{ .@"type" = type_index, .table = table_reserved, }, }; }, .drop => rt_instr = Instruction.drop, .select => rt_instr = Instruction.select, .@"global.get" => { const index = try opcode.readULEB128Mem(u32, &self.code); // TODO: add a getGlobal to module? if (index >= self.module.globals.list.items.len) return error.ValidatorUnknownGlobal; const global = self.module.globals.list.items[@intCast(usize, index)]; try self.validator.validateGlobalGet(global); rt_instr = Instruction{ .@"global.get" = index }; }, .@"global.set" => { const index = try opcode.readULEB128Mem(u32, &self.code); const global = self.module.globals.list.items[@intCast(usize, index)]; try self.validator.validateGlobalSet(global); rt_instr = Instruction{ .@"global.set" = index }; }, .@"local.get" => { const index = try opcode.readULEB128Mem(u32, &self.code); const params = self.params orelse return error.ValidatorConstantExpressionRequired; const locals = self.locals orelse return error.ValidatorConstantExpressionRequired; if (index < params.len) { try self.validator.validateLocalGet(params[index]); } else { const local_index = index - params.len; var local_type: ?ValueType = null; var count: usize = 0; for (locals) |l| { if (local_index < count + l.count) { local_type = l.value_type; break; } count += l.count; } if (local_type) |ltype| { try self.validator.validateLocalGet(ltype); } else { return error.LocalGetIndexOutOfBounds; } } rt_instr = Instruction{ .@"local.get" = index }; }, .@"local.set" => { const index = try opcode.readULEB128Mem(u32, &self.code); const params = self.params orelse return error.ValidatorConstantExpressionRequired; const locals = self.locals orelse return error.ValidatorConstantExpressionRequired; if (index < params.len) { try self.validator.validateLocalSet(params[index]); } else { const local_index = index - params.len; var local_type: ?ValueType = null; var count: usize = 0; for (locals) |l| { if (local_index < count + l.count) { local_type = l.value_type; break; } count += l.count; } if (local_type) |ltype| { try self.validator.validateLocalSet(ltype); } else { return error.LocalSetIndexOutOfBounds; } } rt_instr = Instruction{ .@"local.set" = index }; }, .@"local.tee" => { const index = try opcode.readULEB128Mem(u32, &self.code); const params = self.params orelse return error.ValidatorConstantExpressionRequired; const locals = self.locals orelse return error.ValidatorConstantExpressionRequired; if (index < params.len) { try self.validator.validateLocalTee(params[index]); } else { const local_index = index - params.len; var local_type: ?ValueType = null; var count: usize = 0; for (locals) |l| { if (local_index < count + l.count) { local_type = l.value_type; break; } count += l.count; } if (local_type) |ltype| { try self.validator.validateLocalTee(ltype); } else { return error.LocalTeeIndexOutOfBounds; } } rt_instr = Instruction{ .@"local.tee" = index }; }, .@"memory.size" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const memory_index = try opcode.readByte(&self.code); if (memory_index != 0) return error.MalformedMemoryReserved; rt_instr = Instruction{ .@"memory.size" = memory_index }; }, .@"memory.grow" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const memory_index = try opcode.readByte(&self.code); if (memory_index != 0) return error.MalformedMemoryReserved; rt_instr = Instruction{ .@"memory.grow" = memory_index }; }, .@"i32.const" => { const i32_const = try opcode.readILEB128Mem(i32, &self.code); rt_instr = Instruction{ .@"i32.const" = i32_const }; }, .@"i64.const" => { const i64_const = try opcode.readILEB128Mem(i64, &self.code); rt_instr = Instruction{ .@"i64.const" = i64_const }; }, .@"f32.const" => { const float_const = @bitCast(f32, try opcode.readU32(&self.code)); rt_instr = Instruction{ .@"f32.const" = float_const }; }, .@"f64.const" => { const float_const = @bitCast(f64, try opcode.readU64(&self.code)); rt_instr = Instruction{ .@"f64.const" = float_const }; }, .@"i32.load" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.load" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 64) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"f32.load" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"f32.load" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"f64.load" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 64) return error.InvalidAlignment; rt_instr = Instruction{ .@"f64.load" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.load8_s" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.load8_s" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.load8_u" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.load8_u" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.load16_s" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.load16_s" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.load16_u" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.load16_u" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load8_s" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load8_s" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load8_u" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load8_u" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load16_s" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load16_s" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load16_u" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load16_u" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load32_s" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load32_s" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.load32_u" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.load32_u" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.store" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.store" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.store" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 64) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.store" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"f32.store" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"f32.store" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"f64.store" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 64) return error.InvalidAlignment; rt_instr = Instruction{ .@"f64.store" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.store8" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.store8" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.store16" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i32.store16" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.store8" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 8) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.store8" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.store16" => { if (self.module.memories.list.items.len != 1) return error.ValidatorUnknownMemory; const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 16) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.store16" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i64.store32" => { const alignment = try opcode.readULEB128Mem(u32, &self.code); const offset = try opcode.readULEB128Mem(u32, &self.code); if (8 * try std.math.powi(u32, 2, alignment) > 32) return error.InvalidAlignment; rt_instr = Instruction{ .@"i64.store32" = .{ .alignment = alignment, .offset = offset, }, }; }, .@"i32.eqz" => rt_instr = Instruction.@"i32.eqz", .@"i32.eq" => rt_instr = Instruction.@"i32.eq", .@"i32.ne" => rt_instr = Instruction.@"i32.ne", .@"i32.lt_s" => rt_instr = Instruction.@"i32.lt_s", .@"i32.lt_u" => rt_instr = Instruction.@"i32.lt_u", .@"i32.gt_s" => rt_instr = Instruction.@"i32.gt_s", .@"i32.gt_u" => rt_instr = Instruction.@"i32.gt_u", .@"i32.le_s" => rt_instr = Instruction.@"i32.le_s", .@"i32.le_u" => rt_instr = Instruction.@"i32.le_u", .@"i32.ge_s" => rt_instr = Instruction.@"i32.ge_s", .@"i32.ge_u" => rt_instr = Instruction.@"i32.ge_u", .@"i64.eqz" => rt_instr = Instruction.@"i64.eqz", .@"i64.eq" => rt_instr = Instruction.@"i64.eq", .@"i64.ne" => rt_instr = Instruction.@"i64.ne", .@"i64.lt_s" => rt_instr = Instruction.@"i64.lt_s", .@"i64.lt_u" => rt_instr = Instruction.@"i64.lt_u", .@"i64.gt_s" => rt_instr = Instruction.@"i64.gt_s", .@"i64.gt_u" => rt_instr = Instruction.@"i64.gt_u", .@"i64.le_s" => rt_instr = Instruction.@"i64.le_s", .@"i64.le_u" => rt_instr = Instruction.@"i64.le_u", .@"i64.ge_s" => rt_instr = Instruction.@"i64.ge_s", .@"i64.ge_u" => rt_instr = Instruction.@"i64.ge_u", .@"f32.eq" => rt_instr = Instruction.@"f32.eq", .@"f32.ne" => rt_instr = Instruction.@"f32.ne", .@"f32.lt" => rt_instr = Instruction.@"f32.lt", .@"f32.gt" => rt_instr = Instruction.@"f32.gt", .@"f32.le" => rt_instr = Instruction.@"f32.le", .@"f32.ge" => rt_instr = Instruction.@"f32.ge", .@"f64.eq" => rt_instr = Instruction.@"f64.eq", .@"f64.ne" => rt_instr = Instruction.@"f64.ne", .@"f64.lt" => rt_instr = Instruction.@"f64.lt", .@"f64.gt" => rt_instr = Instruction.@"f64.gt", .@"f64.le" => rt_instr = Instruction.@"f64.le", .@"f64.ge" => rt_instr = Instruction.@"f64.ge", .@"i32.clz" => rt_instr = Instruction.@"i32.clz", .@"i32.ctz" => rt_instr = Instruction.@"i32.ctz", .@"i32.popcnt" => rt_instr = Instruction.@"i32.popcnt", .@"i32.add" => rt_instr = Instruction.@"i32.add", .@"i32.sub" => rt_instr = Instruction.@"i32.sub", .@"i32.mul" => rt_instr = Instruction.@"i32.mul", .@"i32.div_s" => rt_instr = Instruction.@"i32.div_s", .@"i32.div_u" => rt_instr = Instruction.@"i32.div_u", .@"i32.rem_s" => rt_instr = Instruction.@"i32.rem_s", .@"i32.rem_u" => rt_instr = Instruction.@"i32.rem_u", .@"i32.and" => rt_instr = Instruction.@"i32.and", .@"i32.or" => rt_instr = Instruction.@"i32.or", .@"i32.xor" => rt_instr = Instruction.@"i32.xor", .@"i32.shl" => rt_instr = Instruction.@"i32.shl", .@"i32.shr_s" => rt_instr = Instruction.@"i32.shr_s", .@"i32.shr_u" => rt_instr = Instruction.@"i32.shr_u", .@"i32.rotl" => rt_instr = Instruction.@"i32.rotl", .@"i32.rotr" => rt_instr = Instruction.@"i32.rotr", .@"i64.clz" => rt_instr = Instruction.@"i64.clz", .@"i64.ctz" => rt_instr = Instruction.@"i64.ctz", .@"i64.popcnt" => rt_instr = Instruction.@"i64.popcnt", .@"i64.add" => rt_instr = Instruction.@"i64.add", .@"i64.sub" => rt_instr = Instruction.@"i64.sub", .@"i64.mul" => rt_instr = Instruction.@"i64.mul", .@"i64.div_s" => rt_instr = Instruction.@"i64.div_s", .@"i64.div_u" => rt_instr = Instruction.@"i64.div_u", .@"i64.rem_s" => rt_instr = Instruction.@"i64.rem_s", .@"i64.rem_u" => rt_instr = Instruction.@"i64.rem_u", .@"i64.and" => rt_instr = Instruction.@"i64.and", .@"i64.or" => rt_instr = Instruction.@"i64.or", .@"i64.xor" => rt_instr = Instruction.@"i64.xor", .@"i64.shl" => rt_instr = Instruction.@"i64.shl", .@"i64.shr_s" => rt_instr = Instruction.@"i64.shr_s", .@"i64.shr_u" => rt_instr = Instruction.@"i64.shr_u", .@"i64.rotl" => rt_instr = Instruction.@"i64.rotl", .@"i64.rotr" => rt_instr = Instruction.@"i64.rotr", .@"f32.abs" => rt_instr = Instruction.@"f32.abs", .@"f32.neg" => rt_instr = Instruction.@"f32.neg", .@"f32.ceil" => rt_instr = Instruction.@"f32.ceil", .@"f32.floor" => rt_instr = Instruction.@"f32.floor", .@"f32.trunc" => rt_instr = Instruction.@"f32.trunc", .@"f32.nearest" => rt_instr = Instruction.@"f32.nearest", .@"f32.sqrt" => rt_instr = Instruction.@"f32.sqrt", .@"f32.add" => rt_instr = Instruction.@"f32.add", .@"f32.sub" => rt_instr = Instruction.@"f32.sub", .@"f32.mul" => rt_instr = Instruction.@"f32.mul", .@"f32.div" => rt_instr = Instruction.@"f32.div", .@"f32.min" => rt_instr = Instruction.@"f32.min", .@"f32.max" => rt_instr = Instruction.@"f32.max", .@"f32.copysign" => rt_instr = Instruction.@"f32.copysign", .@"f64.abs" => rt_instr = Instruction.@"f64.abs", .@"f64.neg" => rt_instr = Instruction.@"f64.neg", .@"f64.ceil" => rt_instr = Instruction.@"f64.ceil", .@"f64.floor" => rt_instr = Instruction.@"f64.floor", .@"f64.trunc" => rt_instr = Instruction.@"f64.trunc", .@"f64.nearest" => rt_instr = Instruction.@"f64.nearest", .@"f64.sqrt" => rt_instr = Instruction.@"f64.sqrt", .@"f64.add" => rt_instr = Instruction.@"f64.add", .@"f64.sub" => rt_instr = Instruction.@"f64.sub", .@"f64.mul" => rt_instr = Instruction.@"f64.mul", .@"f64.div" => rt_instr = Instruction.@"f64.div", .@"f64.min" => rt_instr = Instruction.@"f64.min", .@"f64.max" => rt_instr = Instruction.@"f64.max", .@"f64.copysign" => rt_instr = Instruction.@"f64.copysign", .@"i32.wrap_i64" => rt_instr = Instruction.@"i32.wrap_i64", .@"i32.trunc_f32_s" => rt_instr = Instruction.@"i32.trunc_f32_s", .@"i32.trunc_f32_u" => rt_instr = Instruction.@"i32.trunc_f32_u", .@"i32.trunc_f64_s" => rt_instr = Instruction.@"i32.trunc_f64_s", .@"i32.trunc_f64_u" => rt_instr = Instruction.@"i32.trunc_f64_u", .@"i64.extend_i32_s" => rt_instr = Instruction.@"i64.extend_i32_s", .@"i64.extend_i32_u" => rt_instr = Instruction.@"i64.extend_i32_u", .@"i64.trunc_f32_s" => rt_instr = Instruction.@"i64.trunc_f32_s", .@"i64.trunc_f32_u" => rt_instr = Instruction.@"i64.trunc_f32_u", .@"i64.trunc_f64_s" => rt_instr = Instruction.@"i64.trunc_f64_s", .@"i64.trunc_f64_u" => rt_instr = Instruction.@"i64.trunc_f64_u", .@"f32.convert_i32_s" => rt_instr = Instruction.@"f32.convert_i32_s", .@"f32.convert_i32_u" => rt_instr = Instruction.@"f32.convert_i32_u", .@"f32.convert_i64_s" => rt_instr = Instruction.@"f32.convert_i64_s", .@"f32.convert_i64_u" => rt_instr = Instruction.@"f32.convert_i64_u", .@"f32.demote_f64" => rt_instr = Instruction.@"f32.demote_f64", .@"f64.convert_i32_s" => rt_instr = Instruction.@"f64.convert_i32_s", .@"f64.convert_i32_u" => rt_instr = Instruction.@"f64.convert_i32_u", .@"f64.convert_i64_s" => rt_instr = Instruction.@"f64.convert_i64_s", .@"f64.convert_i64_u" => rt_instr = Instruction.@"f64.convert_i64_u", .@"f64.promote_f32" => rt_instr = Instruction.@"f64.promote_f32", .@"i32.reinterpret_f32" => rt_instr = Instruction.@"i32.reinterpret_f32", .@"i64.reinterpret_f64" => rt_instr = Instruction.@"i64.reinterpret_f64", .@"f32.reinterpret_i32" => rt_instr = Instruction.@"f32.reinterpret_i32", .@"f64.reinterpret_i64" => rt_instr = Instruction.@"f64.reinterpret_i64", .@"i32.extend8_s" => rt_instr = Instruction.@"i32.extend8_s", .@"i32.extend16_s" => rt_instr = Instruction.@"i32.extend16_s", .@"i64.extend8_s" => rt_instr = Instruction.@"i64.extend8_s", .@"i64.extend16_s" => rt_instr = Instruction.@"i64.extend16_s", .@"i64.extend32_s" => rt_instr = Instruction.@"i64.extend32_s", .trunc_sat => { const version = try opcode.readULEB128Mem(u32, &self.code); try self.validator.validateTrunc(version); rt_instr = Instruction{ .trunc_sat = version }; }, } // Validate the instruction. Some instructions, e.g. block, loop // are validate separately above. switch (instr) { .block, .loop, .@"if", .br, .br_if, .br_table, .call, .call_indirect, .@"global.get", .@"global.set", .@"local.get", .@"local.set", .@"local.tee", .trunc_sat, => {}, else => try self.validator.validate(instr), } return rt_instr; } }; const testing = std.testing;
src/instruction.zig
const std = @import("std"); const headless = @import("headless.zig"); const glfw = @import("glfw.zig"); const drm = @import("drm.zig"); const HeadlessBackend = @import("headless.zig").HeadlessBackend; const HeadlessOutput = @import("headless.zig").HeadlessOutput; const GLFWBackend = @import("glfw.zig").GLFWBackend; const GLFWOutput = @import("glfw.zig").GLFWOutput; const DRMBackend = @import("drm.zig").DRMBackend; const DRMOutput = @import("drm.zig").DRMOutput; pub const BackendType = enum { Headless, GLFW, DRM, }; pub const OutputBackend = union(BackendType) { Headless: HeadlessOutput, GLFW: GLFWOutput, DRM: DRMOutput, }; pub fn BackendOutput(comptime T: type) type { return struct { backend: OutputBackend, data: T, const Self = @This(); pub fn begin(self: Self) !void { switch (self.backend) { BackendType.Headless => |headless_output| headless_output.begin(), BackendType.GLFW => |glfw_output| glfw_output.begin(), BackendType.DRM => |drm_output| drm_output.begin(), } } pub fn end(self: Self) void { return switch (self.backend) { BackendType.Headless => |headless_output| headless_output.end(), BackendType.GLFW => |glfw_output| glfw_output.end(), BackendType.DRM => |drm_output| drm_output.end(), }; } pub fn swap(self: *Self) !void { return switch (self.backend) { BackendType.Headless => |headless_output| headless_output.swap(), BackendType.GLFW => |glfw_output| glfw_output.swap(), BackendType.DRM => |*drm_output| try drm_output.swap(), }; } pub fn isPageFlipScheduled(self: *Self) bool { return switch (self.backend) { BackendType.Headless => |headless_output| false, BackendType.GLFW => |glfw_output| false, BackendType.DRM => |drm_output| drm_output.isPageFlipScheduled(), }; } pub fn getWidth(self: Self) i32 { return switch (self.backend) { BackendType.Headless => |headless_output| headless_output.getWidth(), BackendType.GLFW => |glfw_output| glfw_output.getWidth(), BackendType.DRM => |drm_output| drm_output.getWidth(), }; } pub fn getHeight(self: Self) i32 { return switch (self.backend) { BackendType.Headless => |headless_output| headless_output.getHeight(), BackendType.GLFW => |glfw_output| glfw_output.getHeight(), BackendType.DRM => |drm_output| drm_output.getHeight(), }; } pub fn shouldClose(self: Self) bool { return switch (self.backend) { BackendType.Headless => |headless_output| headless_output.shouldClose(), BackendType.GLFW => |glfw_output| glfw_output.shouldClose(), BackendType.DRM => |drm_output| drm_output.shouldClose(), }; } pub fn addToEpoll(self: *Self) !void { return switch (self.backend) { BackendType.Headless => {}, BackendType.GLFW => {}, BackendType.DRM => |*drm_output| try drm_output.addToEpoll(), }; } pub fn deinit(self: *Self) !void { try self.data.deinit(); return switch (self.backend) { BackendType.Headless => |*headless_output| headless_output.deinit(), BackendType.GLFW => |*glfw_output| glfw_output.deinit(), BackendType.DRM => |*drm_output| drm_output.deinit(), }; } }; } pub fn Backend(comptime T: type) type { return union(BackendType) { Headless: HeadlessBackend, GLFW: GLFWBackend, DRM: DRMBackend, const Self = @This(); pub fn new(backend_type: BackendType) !Self { return switch (backend_type) { BackendType.Headless => Self{ .Headless = try headless.new() }, BackendType.GLFW => Self{ .GLFW = try glfw.new() }, BackendType.DRM => Self{ .DRM = try drm.new() }, }; } pub fn init(self: *Self) !void { return switch (self.*) { BackendType.Headless => |*backend| backend.init(), BackendType.GLFW => |*backend| backend.init(), BackendType.DRM => |*backend| backend.init(), }; } pub fn wait(self: Self) i32 { return switch (self) { BackendType.Headless => |headless_backend| -1, BackendType.GLFW => |glfw_backend| 10, BackendType.DRM => -1, }; } pub fn name(self: Self) []const u8 { return switch (self) { BackendType.Headless => "Headless", BackendType.GLFW => "GLFW", BackendType.DRM => "DRM", }; } pub fn newOutput(self: *Backend(T), w: i32, h: i32) !BackendOutput(T) { var output_backend = switch (self.*) { BackendType.Headless => |*headless_backend| OutputBackend{ .Headless = try headless_backend.newOutput(w, h) }, BackendType.GLFW => |*glfw_backend| OutputBackend{ .GLFW = try glfw_backend.newOutput(w, h) }, BackendType.DRM => |*drm_backend| OutputBackend{ .DRM = try drm_backend.newOutput() }, }; return BackendOutput(T){ .backend = output_backend, .data = undefined, }; } pub fn deinit(self: *Self) void { return switch (self.*) { BackendType.Headless => |*headless_backend| headless_backend.deinit(), BackendType.GLFW => |*glfw_backend| glfw_backend.deinit(), BackendType.DRM => |*drm_backend| drm_backend.deinit(), }; } }; } pub fn detect() BackendType { if (std.os.getenv("DISPLAY")) |display| { return BackendType.GLFW; } return BackendType.DRM; } pub const BackendFns = struct { keyboard: ?fn (u32, u32, u32) anyerror!void, mouseClick: ?fn (u32, u32, u32) anyerror!void, mouseMove: ?fn (u32, f64, f64) anyerror!void, mouseAxis: ?fn (u32, u32, f64) anyerror!void, pageFlip: ?fn () anyerror!void, }; pub var BACKEND_FNS: BackendFns = makeBackendFns(); fn makeBackendFns() BackendFns { return BackendFns{ .keyboard = null, .mouseClick = null, .mouseMove = null, .mouseAxis = null, .pageFlip = null, }; }
src/backend/backend.zig
pub const HeaderValue = struct { const Error = error{ Invalid, }; pub fn parse(value: []const u8) Error![]const u8 { if (value.len == 0) { return error.Invalid; } for (value) |char| { if (!HEADER_VALUE_MAP[char]) { return error.Invalid; } } return value; } }; // ASCII codes accepted for an header's value // Cf: Borrowed from Seamonstar's httparse library // https://github.com/seanmonstar/httparse/blob/01e68542605d8a24a707536561c27a336d4090dc/src/lib.rs#L120 const HEADER_VALUE_MAP = [_]bool{ false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, // \0 \t \n \r false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // commands true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // \s ! " # $ % & ' ( ) * + , - . / true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 0 1 2 3 4 5 6 7 8 9 : ; < = > ? true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // @ A B C D E F G H I J K L M N O true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // P Q R S T U V W X Y Z [ \ ] ^ _ true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // ` a b c d e f g h i j k l m n o true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, // p q r s t u v w x y z { | } ~ del // ====== Extended ASCII (aka. obs-text) ====== true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, }; const std = @import("std"); const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; test "Parse - Success" { var value = try HeaderValue.parse("A tasty cookie"); try expectEqualStrings(value, "A tasty cookie"); } test "Parse - Invalid character returns an error" { const fail = HeaderValue.parse("A invalid\rcookie"); try expectError(error.Invalid, fail); } test "Parse - Empty value is invalid" { const fail = HeaderValue.parse(""); try expectError(error.Invalid, fail); }
src/headers/value.zig
const std = @import("std"); const jpeg = @import("jpeg_writer.zig"); const multi_threaded = true; const width = 1024; const height = 768; const fov: f32 = std.math.pi / 3.0; const out_filename = "out.jpg"; const out_quality = 100; fn vec3(x: f32, y: f32, z: f32) Vec3f { return Vec3f{ .x = x, .y = y, .z = z }; } const Vec3f = Vec3(f32); fn Vec3(comptime T: type) type { return struct { const Self = @This(); x: T, y: T, z: T, fn mul(u: Self, v: Self) T { return u.x * v.x + u.y * v.y + u.z * v.z; } fn mulScalar(u: Self, k: T) Self { return vec3(u.x * k, u.y * k, u.z * k); } fn add(u: Self, v: Self) Self { return vec3(u.x + v.x, u.y + v.y, u.z + v.z); } fn sub(u: Self, v: Self) Self { return vec3(u.x - v.x, u.y - v.y, u.z - v.z); } fn negate(u: Self) Self { return vec3(-u.x, -u.y, -u.z); } fn norm(u: Self) T { return std.math.sqrt(u.x * u.x + u.y * u.y + u.z * u.z); } fn normalize(u: Self) Self { return u.mulScalar(1 / u.norm()); } fn cross(u: Vec3f, v: Vec3f) Vec3f { return vec3( u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x, ); } }; } const Light = struct { position: Vec3f, intensity: f32, }; const Material = struct { refractive_index: f32, albedo: [4]f32, diffuse_color: Vec3f, specular_exponent: f32, pub fn default() Material { return Material{ .refractive_index = 1, .albedo = [_]f32{ 1, 0, 0, 0 }, .diffuse_color = vec3(0, 0, 0), .specular_exponent = 0, }; } }; const Sphere = struct { center: Vec3f, radius: f32, material: Material, fn rayIntersect(self: Sphere, origin: Vec3f, direction: Vec3f, t0: *f32) bool { const l = self.center.sub(origin); const tca = l.mul(direction); const d2 = l.mul(l) - tca * tca; if (d2 > self.radius * self.radius) { return false; } const thc = std.math.sqrt(self.radius * self.radius - d2); t0.* = tca - thc; const t1 = tca + thc; if (t0.* < 0) t0.* = t1; return t0.* >= 0; } }; fn reflect(i: Vec3f, normal: Vec3f) Vec3f { return i.sub(normal.mulScalar(2).mulScalar(i.mul(normal))); } fn refract(i: Vec3f, normal: Vec3f, refractive_index: f32) Vec3f { var cosi = -std.math.max(-1, std.math.min(1, i.mul(normal))); var etai: f32 = 1; var etat = refractive_index; var n = normal; if (cosi < 0) { cosi = -cosi; std.mem.swap(f32, &etai, &etat); n = normal.negate(); } const eta = etai / etat; const k = 1 - eta * eta * (1 - cosi * cosi); return if (k < 0) vec3(0, 0, 0) else i.mulScalar(eta).add(n.mulScalar(eta * cosi - std.math.sqrt(k))); } fn sceneIntersect(origin: Vec3f, direction: Vec3f, spheres: []const Sphere, hit: *Vec3f, normal: *Vec3f, material: *Material) bool { var spheres_dist: f32 = std.math.f32_max; for (spheres) |s| { var dist_i: f32 = undefined; if (s.rayIntersect(origin, direction, &dist_i) and dist_i < spheres_dist) { spheres_dist = dist_i; hit.* = origin.add(direction.mulScalar(dist_i)); normal.* = hit.sub(s.center).normalize(); material.* = s.material; } } // Floor plane var checkerboard_dist: f32 = std.math.f32_max; if (std.math.fabs(direction.y) > 1e-3) { const d = -(origin.y + 4) / direction.y; const pt = origin.add(direction.mulScalar(d)); if (d > 0 and std.math.fabs(pt.x) < 10 and pt.z < -10 and pt.z > -30 and d < spheres_dist) { checkerboard_dist = d; hit.* = pt; normal.* = vec3(0, 1, 0); const diffuse = @floatToInt(i32, 0.5 * hit.x + 1000) + @floatToInt(i32, 0.5 * hit.z); const diffuse_color = if (@mod(diffuse, 2) == 1) vec3(1, 1, 1) else vec3(1, 0.7, 0.3); material.diffuse_color = diffuse_color.mulScalar(0.3); } } return std.math.min(spheres_dist, checkerboard_dist) < 1000; } fn castRay(origin: Vec3f, direction: Vec3f, spheres: []const Sphere, lights: []const Light, depth: i32) Vec3f { var point: Vec3f = undefined; var normal: Vec3f = undefined; var material = Material.default(); if (depth > 4 or !sceneIntersect(origin, direction, spheres, &point, &normal, &material)) { return vec3(0.2, 0.7, 0.8); // Background color } const reflect_dir = reflect(direction, normal).normalize(); const refract_dir = refract(direction, normal, material.refractive_index).normalize(); const nn = normal.mulScalar(1e-3); const reflect_origin = if (reflect_dir.mul(normal) < 0) point.sub(nn) else point.add(nn); const refract_origin = if (refract_dir.mul(normal) < 0) point.sub(nn) else point.add(nn); const reflect_color = castRay(reflect_origin, reflect_dir, spheres, lights, depth + 1); const refract_color = castRay(refract_origin, refract_dir, spheres, lights, depth + 1); var diffuse_light_intensity: f32 = 0; var specular_light_intensity: f32 = 0; for (lights) |l| { const light_dir = l.position.sub(point).normalize(); const light_distance = l.position.sub(point).norm(); const shadow_origin = if (light_dir.mul(normal) < 0) point.sub(nn) else point.add(nn); var shadow_pt: Vec3f = undefined; var shadow_n: Vec3f = undefined; var _unused: Material = undefined; if (sceneIntersect(shadow_origin, light_dir, spheres, &shadow_pt, &shadow_n, &_unused) and shadow_pt.sub(shadow_origin).norm() < light_distance) { continue; } diffuse_light_intensity += l.intensity * std.math.max(0, light_dir.mul(normal)); specular_light_intensity += std.math.pow(f32, std.math.max(0, -reflect(light_dir.negate(), normal).mul(direction)), material.specular_exponent) * l.intensity; } const p1 = material.diffuse_color.mulScalar(diffuse_light_intensity * material.albedo[0]); const p2 = vec3(1, 1, 1).mulScalar(specular_light_intensity).mulScalar(material.albedo[1]); const p3 = reflect_color.mulScalar(material.albedo[2]); const p4 = refract_color.mulScalar(material.albedo[3]); return p1.add(p2.add(p3.add(p4))); } const RenderContext = struct { pixmap: []u8, start: usize, end: usize, spheres: []const Sphere, lights: []const Light, }; fn renderFramebufferSegment(context: RenderContext) void { var j: usize = context.start; while (j < context.end) : (j += 1) { var i: usize = 0; while (i < width) : (i += 1) { const x = (2 * (@intToFloat(f32, i) + 0.5) / width - 1) * std.math.tan(fov / 2.0) * width / height; const y = -(2 * (@intToFloat(f32, j) + 0.5) / height - 1) * std.math.tan(fov / 2.0); const direction = vec3(x, y, -1).normalize(); var c = castRay(vec3(0, 0, 0), direction, context.spheres, context.lights, 0); var max = std.math.max(c.x, std.math.max(c.y, c.z)); if (max > 1) c = c.mulScalar(1 / max); const T = @typeInfo(Vec3f).Struct; inline for (T.fields) |field, k| { const pixel = @floatToInt(u8, 255 * std.math.max(0, std.math.min(1, @field(c, field.name)))); context.pixmap[3 * (i + j * width) + k] = pixel; } } } } fn renderMulti(allocator: *std.mem.Allocator, spheres: []const Sphere, lights: []const Light) !void { var pixmap = std.ArrayList(u8).init(allocator); defer pixmap.deinit(); try pixmap.resize(3 * width * height); const cpu_count = try std.Thread.cpuCount(); const batch_size = height / cpu_count; var threads = std.ArrayList(*std.Thread).init(allocator); defer threads.deinit(); var j: usize = 0; while (j < height) : (j += batch_size) { const context = RenderContext{ .pixmap = pixmap.toSlice(), .start = j, .end = j + batch_size, .spheres = spheres, .lights = lights, }; try threads.append(try std.Thread.spawn(context, renderFramebufferSegment)); } for (threads.toSliceConst()) |thread| { thread.wait(); } try jpeg.writeToFile(out_filename, width, height, 3, pixmap.toSliceConst(), out_quality); } fn render(allocator: *std.mem.Allocator, spheres: []const Sphere, lights: []const Light) !void { var pixmap = std.ArrayList(u8).init(allocator); defer pixmap.deinit(); try pixmap.resize(3 * width * height); var j: usize = 0; while (j < height) : (j += 1) { var i: usize = 0; while (i < width) : (i += 1) { const x = (2 * (@intToFloat(f32, i) + 0.5) / width - 1) * std.math.tan(fov / 2.0) * width / height; const y = -(2 * (@intToFloat(f32, j) + 0.5) / height - 1) * std.math.tan(fov / 2.0); const direction = vec3(x, y, -1).normalize(); var c = castRay(vec3(0, 0, 0), direction, spheres, lights, 0); var max = std.math.max(c.x, std.math.max(c.y, c.z)); if (max > 1) c = c.mulScalar(1 / max); const T = @typeInfo(Vec3f).Struct; inline for (T.fields) |field, k| { const pixel = @floatToInt(u8, 255 * std.math.max(0, std.math.min(1, @field(c, field.name)))); pixmap.set(3 * (i + j * width) + k, pixel); } } } try jpeg.writeToFile(out_filename, width, height, 3, pixmap.toSliceConst(), out_quality); } pub fn main() !void { const ivory = Material{ .refractive_index = 1.0, .albedo = [_]f32{ 0.6, 0.3, 0.1, 0.0 }, .diffuse_color = vec3(0.4, 0.4, 0.3), .specular_exponent = 50, }; const glass = Material{ .refractive_index = 1.5, .albedo = [_]f32{ 0.0, 0.5, 0.1, 0.8 }, .diffuse_color = vec3(0.6, 0.7, 0.8), .specular_exponent = 125, }; const red_rubber = Material{ .refractive_index = 1.0, .albedo = [_]f32{ 0.9, 0.1, 0.0, 0.0 }, .diffuse_color = vec3(0.3, 0.1, 0.1), .specular_exponent = 10, }; const mirror = Material{ .refractive_index = 1.0, .albedo = [_]f32{ 0.0, 10.0, 0.8, 0.0 }, .diffuse_color = vec3(1.0, 1.0, 1.0), .specular_exponent = 1425, }; const spheres = [_]Sphere{ Sphere{ .center = vec3(-3, 0, -16), .radius = 1.3, .material = ivory, }, Sphere{ .center = vec3(3, -1.5, -12), .radius = 2, .material = glass, }, Sphere{ .center = vec3(1.5, -0.5, -18), .radius = 3, .material = red_rubber, }, Sphere{ .center = vec3(9, 5, -18), .radius = 3.7, .material = mirror, }, }; const lights = [_]Light{ Light{ .position = vec3(-10, 23, 20), .intensity = 1.1, }, Light{ .position = vec3(17, 50, -25), .intensity = 1.8, }, Light{ .position = vec3(30, 20, 30), .intensity = 1.7, }, }; var direct = std.heap.DirectAllocator.init(); if (multi_threaded) { try renderMulti(&direct.allocator, spheres, lights); } else { try render(&direct.allocator, spheres, lights); } }
raytrace.zig
const std = @import("std"); const maxInt = std.math.maxInt; const log = std.debug.warn; const c = @import("c.zig"); const gw = c.gw; const gmp = c.gmp; const glue = @import("glue.zig"); pub fn create_gwhandle(ctx: *gw.gwhandle, threads: u8, k: u32, n: u32) void { gw.gwinit2(ctx, @sizeOf(gw.gwhandle), gw.GWNUM_VERSION); // features ctx.use_large_pages = 1; ctx.num_threads = threads; ctx.will_hyperthread = threads; ctx.bench_num_cores = threads; // safety //ctx.larger_fftlen_count = 0; //ctx.safety_margin = 0.3; // we do the careful squating explicitly //gw.gwset_square_carefully_count(ctx, 50); //ctx.use_irrational_general_mod = 1; ctx.sum_inputs_checking = 1; ctx.will_error_check = 1; const _na = gw.gwsetup(ctx, @intToFloat(f64, k), 2, n, -1); } pub fn benchmark_threads(u0_gmp: gmp.mpz_t, k: u32, n: u32) u8 { const max_threads: u32 = 8; const iterations: u32 = 1000; var best_speed: u64 = 0xffffffffffffffff; var best_threadcount: u8 = 0; var warmup: bool = true; var i: u8 = 1; while (i <= max_threads) { var ctx: gw.gwhandle = undefined; create_gwhandle(&ctx, i, k, n); var u: gw.gwnum = gw.gwalloc(&ctx); glue.gmp_to_gw(u0_gmp, u, &ctx); const start = std.time.milliTimestamp(); gw.gwsetaddin(&ctx, -2); var j: u32 = 0; while (j < iterations) : (j += 1) { gw.gwsquare2(&ctx, u, u); gw.gwstartnextfft(&ctx, 1); } const delta = std.time.milliTimestamp() - start; // larger threadcount has to be at least 5% better if (@intToFloat(f64, delta) < (@intToFloat(f64, best_speed) * 0.95)) { best_speed = delta; best_threadcount = i; } if (warmup) { warmup = false; continue; } log("threads {} took {}ms for {} iterations\n", .{ i, delta, iterations }); i += 1; } log("using fastest threadcount {}\n", .{best_threadcount}); return best_threadcount; } pub fn min(comptime T: type, a: T, b: T) T { return if (a <= b) a else b; } /// /// copied from official Zig docs /// https://ziglang.org/documentation/master/#toc-Error-Union-Type /// pub fn parseU64(buf: []const u8, radix: u8) !u64 { var x: u64 = 0; for (buf) |ch| { const digit = charToDigit(ch); if (digit >= radix) { return error.InvalidChar; } // x *= radix if (@mulWithOverflow(u64, x, radix, &x)) { return error.Overflow; } // x += digit if (@addWithOverflow(u64, x, digit, &x)) { return error.Overflow; } } return x; } fn charToDigit(ch: u8) u8 { return switch (ch) { '0'...'9' => ch - '0', 'A'...'Z' => ch - 'A' + 10, 'a'...'z' => ch - 'a' + 10, else => maxInt(u8), }; }
helper.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const Ship = struct { const Instruction = struct { action: u8, value: isize, }; ship_coord: aoc.Coord2D = aoc.Coord2D.init(.{0, 0}), waypoint_coord: aoc.Coord2D, target_ship: bool, fn init(waypoint_x: isize, waypoint_y: isize, target_ship: bool) Ship { return Ship { .waypoint_coord = aoc.Coord2D.init(.{waypoint_x, waypoint_y}), .target_ship = target_ship, }; } fn go(self: *Ship, instruction: Instruction) void { const target_movement = if (self.target_ship) &self.ship_coord else &self.waypoint_coord; switch (instruction.action) { 'N' => target_movement.y -= instruction.value, 'S' => target_movement.y += instruction.value, 'E' => target_movement.x += instruction.value, 'W' => target_movement.x -= instruction.value, 'L' => self.rotateWaypoint(instruction.value, aoc.Coord2D.mutRotate90DegreesCounterclockwise), 'R' => self.rotateWaypoint(instruction.value, aoc.Coord2D.mutRotate90DegreesClockwise), 'F' => self.ship_coord.mutAdd(self.waypoint_coord.multiply(instruction.value)), else => unreachable } } fn rotateWaypoint(self: *Ship, degrees: isize, call: anytype) void { var i: usize = 0; while (i < @intCast(usize, degrees) / 90) : (i += 1) { @call(.{}, call, .{&self.waypoint_coord}); } } fn getShipDistance(self: *const Ship) usize { return self.ship_coord.distanceFromOrigin(); } fn parseInstruction(line: []const u8) !Instruction { return Instruction { .action = line[0], .value = try std.fmt.parseInt(isize, line[1..], 10), }; } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var ship1 = Ship.init(1, 0, true); var ship2 = Ship.init(10, -1, false); while (problem.line()) |line| { const instruction = try Ship.parseInstruction(line); ship1.go(instruction); ship2.go(instruction); } return problem.solution(ship1.getShipDistance(), ship2.getShipDistance()); }
src/main/zig/2020/day12.zig
const BufferUsage = @import("enums.zig").BufferUsage; const Buffer = @This(); /// The type erased pointer to the Buffer implementation /// Equal to c.WGPUBuffer for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, destroy: fn (ptr: *anyopaque) void, getConstMappedRange: fn (ptr: *anyopaque, offset: usize, size: usize) []const u8, getMappedRange: fn (ptr: *anyopaque, offset: usize, size: usize) []u8, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, mapAsync: fn ( ptr: *anyopaque, mode: MapMode, offset: usize, size: usize, callback: *MapCallback, ) void, unmap: fn (ptr: *anyopaque) void, }; pub inline fn reference(buf: Buffer) void { buf.vtable.reference(buf.ptr); } pub inline fn release(buf: Buffer) void { buf.vtable.release(buf.ptr); } pub inline fn destroy(buf: Buffer) void { buf.vtable.destroy(buf.ptr); } pub inline fn getConstMappedRange(buf: Buffer, comptime T: type, offset: usize, len: usize) []const T { const data = buf.vtable.getConstMappedRange(buf.ptr, offset, @sizeOf(T) * len); return @ptrCast(*const T, &data[0])[0..len]; } pub inline fn getMappedRange(buf: Buffer, comptime T: type, offset: usize, len: usize) []T { const data = buf.vtable.getMappedRange(buf.ptr, offset, @sizeOf(T) * len); return @ptrCast(*T, &data[0])[0..len]; } pub inline fn setLabel(buf: Buffer, label: [:0]const u8) void { buf.vtable.setLabel(buf.ptr, label); } pub inline fn mapAsync( buf: Buffer, mode: MapMode, offset: usize, size: usize, callback: *MapCallback, ) void { buf.vtable.mapAsync(buf.ptr, mode, offset, size, callback); } pub const MapCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, status: MapAsyncStatus) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, status: MapAsyncStatus) void, ) MapCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, status: MapAsyncStatus) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(@alignOf(Context), type_erased_ctx)), status); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; pub inline fn unmap(buf: Buffer) void { buf.vtable.unmap(buf.ptr); } pub const Descriptor = extern struct { reserved: ?*anyopaque = null, label: ?[*:0]const u8 = null, usage: BufferUsage, size: usize, mapped_at_creation: bool, }; pub const BindingType = enum(u32) { none = 0x00000000, uniform = 0x00000001, storage = 0x00000002, read_only_storage = 0x00000003, }; pub const BindingLayout = extern struct { reserved: ?*anyopaque = null, type: BindingType, has_dynamic_offset: bool, min_binding_size: u64, }; pub const MapAsyncStatus = enum(u32) { success = 0x00000000, err = 0x00000001, unknown = 0x00000002, device_lost = 0x00000003, destroyed_before_callback = 0x00000004, unmapped_before_callback = 0x00000005, }; pub const MapMode = enum(u32) { none = 0x00000000, read = 0x00000001, write = 0x00000002, }; test { _ = VTable; _ = reference; _ = release; _ = destroy; _ = getConstMappedRange; _ = getMappedRange; _ = setLabel; _ = Descriptor; _ = BindingType; _ = BindingLayout; _ = MapAsyncStatus; _ = MapMode; }
gpu/src/Buffer.zig
const std = @import("std"); const interpret = @import("interpret.zig"); const LispExpr = interpret.LispExpr; const LispInterpreter = interpret.LispInterpreter; pub const LispToken = struct { id: Id, start: usize, end: usize, pub const Id = enum { identifier, string_literal, integer_literal, float_literal, line_comment, open_paren, close_paren, }; }; pub const LispTokenizer = struct { source: []const u8, index: usize, pub fn init(source: []const u8) LispTokenizer { return LispTokenizer{ .source = source, .index = 0, }; } const State = enum { start, identifier, string_literal, unclosed_string_literal, unclosed_string_literal_backslash, integer_literal, float_fraction, sign, period, line_comment, open_paren, close_paren, }; pub fn next(self: *LispTokenizer) !?LispToken { const start_index = self.index; var state = State.start; var result = LispToken{ .id = undefined, .start = start_index, .end = undefined, }; while (self.index < self.source.len) : (self.index += 1) { const c = self.source[self.index]; switch (state) { .start => switch (c) { ' ', '\t', '\r', '\n' => result.start = self.index + 1, '"' => state = .unclosed_string_literal, '(' => { state = .open_paren; result.id = .open_paren; self.index += 1; break; }, ')' => { state = .close_paren; result.id = .close_paren; self.index += 1; break; }, '0'...'9' => { state = .integer_literal; result.id = .integer_literal; }, '+', '-' => state = .sign, '.' => state = .period, ';' => { state = .line_comment; result.id = .line_comment; }, else => { state = .identifier; result.id = .identifier; }, }, .string_literal => break, .unclosed_string_literal => { switch (c) { '\\' => state = .unclosed_string_literal_backslash, '"' => { state = .string_literal; result.id = .string_literal; }, else => {}, } }, .unclosed_string_literal_backslash => state = .unclosed_string_literal, .integer_literal => { switch (c) { '0'...'9' => {}, '.' => { state = .float_fraction; result.id = .float_literal; }, ' ', '\t', '\r', '\n', '(', ')', ';' => break, else => { state = .identifier; result.id = .identifier; }, } }, .float_fraction => { switch (c) { '0'...'9' => {}, ' ', '\t', '\r', '\n', '(', ')', ';' => break, else => { state = .identifier; result.id = .identifier; }, } }, .sign => { switch (c) { '0'...'9' => { state = .integer_literal; result.id = .integer_literal; }, '.' => { state = .float_fraction; result.id = .float_literal; }, ' ', '\t', '\r', '\n', '(', ')', ';' => { result.id = .identifier; break; }, else => { state = .identifier; result.id = .identifier; }, } }, .period => { switch (c) { '0'...'9' => { state = .float_fraction; result.id = .float_literal; }, ' ', '\t', '\r', '\n', '(', ')', ';' => { result.id = .identifier; break; }, else => { state = .identifier; result.id = .identifier; }, } }, .line_comment => { switch (c) { '\r', '\n' => break, else => {}, } }, .identifier => { switch (c) { ' ', '\t', '\r', '\n', '(', ')', ';' => break, else => {}, } }, else => unreachable, } } result.end = self.index; switch (state) { .start => return null, .unclosed_string_literal, .unclosed_string_literal_backslash, => return error.TokenizerUnclosedStringLiteral, else => return result, } } }; pub const LispParser = struct { interpreter: *LispInterpreter, source: []const u8, tokens: []LispToken, index: usize, pub fn init(interpreter: *LispInterpreter, source: []const u8, tokens: []LispToken) LispParser { return LispParser{ .interpreter = interpreter, .source = source, .tokens = tokens, .index = 0, }; } pub fn next(self: *LispParser) anyerror!?LispExpr { if (self.index >= self.tokens.len) return null; const t = self.tokens[self.index]; self.index += 1; switch (t.id) { .line_comment => return try self.next(), .identifier => { var list = try self.interpreter.allocator.create(std.ArrayList(u8)); errdefer self.interpreter.allocator.destroy(list); list.* = std.ArrayList(u8).init(self.interpreter.allocator); errdefer list.deinit(); try list.appendSlice(self.source[t.start..t.end]); return try self.interpreter.store(LispExpr{ .identifier = list }); }, .string_literal => { var list = try self.interpreter.allocator.create(std.ArrayList(u8)); errdefer self.interpreter.allocator.destroy(list); list.* = try std.ArrayList(u8).initCapacity(self.interpreter.allocator, (t.end - t.start - 2) / 2); errdefer list.deinit(); var backslash = false; for (self.source[t.start + 1 .. t.end - 1]) |string_c| { if (backslash) { switch (string_c) { 'n' => try list.append('\n'), 't' => try list.append('\t'), else => try list.append(string_c), } backslash = false; } else { if (string_c == '\\') { backslash = true; } else { try list.append(string_c); } } } return try self.interpreter.store(LispExpr{ .string = list }); }, .integer_literal, .float_literal => { const num = try std.fmt.parseInt(isize, self.source[t.start..t.end], 10); return LispExpr{ .number = num }; }, .open_paren => { var list = try self.interpreter.allocator.create(std.ArrayList(LispExpr)); errdefer self.interpreter.allocator.destroy(list); list.* = std.ArrayList(LispExpr).init(self.interpreter.allocator); errdefer list.deinit(); errdefer for (list.items) |branch| branch.deinit(); while (self.tokens[self.index].id != .close_paren) { if (try self.next()) |expr| { try list.append(expr); } else { return error.ParserUnclosedParen; } } self.index += 1; return try self.interpreter.store(LispExpr{ .list = list }); }, .close_paren => return error.ParserOverclosedParen, } } };
src/parse.zig
const std = @import("std"); const testing = std.testing; const Timer = std.time.Timer; const log = std.log.scoped(.bench); const words = @embedFile("testdata/words.txt"); const gpa = testing.allocator; pub fn main() !void { comptime var radix = @import("main.zig").StringRadixTree(u32){}; comptime { @setEvalBranchQuota(10_000); comptime var index: usize = 0; comptime var count: u32 = 0; for (words) |c, i| { if (c == '\n') { _ = radix.insert(words[index..i], count); count += 1; index = i + 1; } } _ = radix.insert(words[index..], count); } var map = std.StringHashMap(u32).init(gpa); var array_map = std.StringArrayHashMap(u32).init(gpa); var map_results: [3]u64 = undefined; var array_map_results: [3]u64 = undefined; var radix_results: [3]u64 = undefined; const loops = 50_000; defer map.deinit(); var it = std.mem.split(words, "\n"); var i: u32 = 0; while (it.next()) |val| : (i += 1) { try map.putNoClobber(val, i); try array_map.putNoClobber(val, i); } log.alert("Start benching {} words\t[0]\t[1]\t[2]", .{i}); std.debug.assert(radix.size == i); for (map_results) |*r| { var timer = try Timer.start(); for (@as([loops]u8, undefined)) |_| { it.index = 0; while (it.next()) |val| { _ = map.get(val).?; } } r.* = timer.read(); } log.alert("StringHashMap\t\t{:0>4}ms\t{:0>4}ms\t{:0>4}ms", .{ map_results[0] / 1_000_000, map_results[1] / 1_000_000, map_results[2] / 1_000_000, }); for (array_map_results) |*r| { var timer = try Timer.start(); for (@as([loops]u8, undefined)) |_| { it.index = 0; while (it.next()) |val| { _ = array_map.get(val).?; } } r.* = timer.read(); } log.alert("StringArrayHashMap\t{:0>4}ms\t{:0>4}ms\t{:0>4}ms", .{ array_map_results[0] / 1_000_000, array_map_results[1] / 1_000_000, array_map_results[2] / 1_000_000, }); for (radix_results) |*r| { var timer = try Timer.start(); for (@as([loops]u8, undefined)) |_| { it.index = 0; while (it.next()) |val| { _ = radix.get(val).?; } } r.* = timer.read(); } log.alert("RadixTree\t\t\t{:0>4}ms\t{:0>4}ms\t{:0>4}ms", .{ radix_results[0] / 1_000_000, radix_results[1] / 1_000_000, radix_results[2] / 1_000_000, }); }
src/bench.zig
const std = @import("std"); const meta = std.meta; const trait = meta.trait; const max = std.math.maxInt; const assert = std.debug.assert; /// Supported types to be serialized const Format = enum(u8) { fixint_base = 0x00, fixint_max = 0x7F, fixmap_base = 0x80, fixmap_max = 0x8F, fixarray_base = 0x90, fixarray_max = 0x9F, fixstr_base = 0xA0, fixstr_max = 0xBF, nil = 0xC0, @"false" = 0xC2, @"true" = 0xC3, bin_8 = 0xC4, bin_16 = 0xC5, bin_32 = 0xC6, ext_8 = 0xC7, ext_16 = 0xC8, ext_32 = 0xC9, float_32 = 0xCA, float_64 = 0xCB, uint_8 = 0xCC, uint_16 = 0xCD, uint_32 = 0xCE, uint_64 = 0xCF, int_8 = 0xD0, int_16 = 0xD1, int_32 = 0xD2, int_64 = 0xD3, fixext_1 = 0xD4, fixext_2 = 0xD5, fixext_4 = 0xD6, fixext_8 = 0xD7, fixext_16 = 0xD8, str_8 = 0xD9, str_16 = 0xDA, str_32 = 0xDB, array_16 = 0xDC, array_32 = 0xDD, map_16 = 0xDE, map_32 = 0xDF, negfixint_base = 0xE0, negfixint_max = 0xFF, _, }; /// Returns the integer value of `Format`. /// allows you to use format(.bin_8) for readability. fn format(format_enum: Format) u8 { return @enumToInt(format_enum); } /// Returns the fixmap value based on the input `value` fn fixmap(value: u4) u8 { return value + @enumToInt(Format.fixmap_base); } /// Returns the fixstr value based on the input `value` fn fixstr(value: u5) u8 { return value + @enumToInt(Format.fixstr_base); } /// Returns the fixarray value based on the input `value` fn fixarray(value: u4) u8 { return value + @enumToInt(Format.fixarray_base); } /// Returns the negative fixint value based on the input `value` fn negint(value: i5) u8 { return @intCast(u8, value) + @enumToInt(Format.negfixint_base); } fn fromByte(byte: u8) Format { return @intToEnum(Format, byte); } /// Represents a timestamp that can be (de)serialized pub const Timestamp = struct { sec: u32, nsec: i64 }; /// Creates a generic Deserializater over the given ReaderType. /// Allows for deserializing msgpack data streams into given types using a buffer /// of given `size`. /// /// It is possible to define your custom deserialization function for a given type /// by defining a `deserialize(*Self, anytype)` function pub fn Deserializer(comptime ReaderType: type, comptime size: usize) type { return struct { reader: ReaderType, buffer: [size]u8, index: usize, const Self = @This(); pub const ReadError = error{ MismatchingFormatType, EndOfStream, BufferTooSmall, } || ReaderType.Error; /// Initializes a new instance wrapper around the given `reader` pub fn init(reader: ReaderType) Self { return Self{ .reader = reader, .index = 0, .buffer = undefined }; } /// Deserializes the msgpack stream into a value of type `T` /// use `deserializeInto` if the length written to `buffer` is required /// Note: Sets `index` to 0 to reuse the buffer and will overwrite all old data pub fn deserialize(self: *Self, comptime T: type) ReadError!T { var value: T = undefined; _ = try self.deserializeInto(&value); return value; } /// Deserializes the msgpack data stream into the given pointer. /// asserts `ptr` is a pointer pub fn deserializeInto(self: *Self, ptr: anytype) ReadError!void { const T = @TypeOf(ptr); comptime assert(trait.is(.Pointer)(T)); const C = comptime meta.Child(T); if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self); ptr.* = switch (C) { []const u8 => try self.deserializeString(), []u8 => try self.deserializeBin(), else => switch (@typeInfo(C)) { .Struct => try self.deserializeStruct(C), .Bool => try self.deserializeBool(), .Int => try self.deserializeInt(C), .Float => try self.deserializeFloat(C), .Array => try self.deserializeArray(C), .Pointer => try self.deserializePointer(C), .Null => try self.deserializeNull(), else => @compileError("Unsupported deserialization type " ++ @typeName(C) ++ "\n"), }, }; } /// Deserializes a pointer to one or multiple items pub fn deserializePointer(self: *Self, comptime T: type) ReadError!T { return switch (@typeInfo(T).Pointer.size) { .One => try self.deserialize(T), .Slice => try self.deserializeArray(T), .Many => try self.deserializeArray(T), .C => @compileError("Unsupported pointer type C"), }; } /// Deserializes a timestamp into a struct of sec(u32) and nsec(i64) pub fn deserializeTimestamp(self: *Self) ReadError!Timestamp { const byte = try self.reader.readByte(); switch (byte) { format(.fixext_4) => { _ = try self.reader.readByte(); // skip '-1' byte const sec = try self.reader.readIntBig(u32); return Timestamp{ .sec = sec, .nsec = 0 }; }, format(.fixext_8) => { _ = try self.reader.readByte(); // skip '-1' byte const data = try self.reader.readIntBig(u64); return Timestamp{ .sec = @intCast(u32, data & 0x00000003ffffffff), .nsec = @intCast(i64, data >> 34) }; }, format(.ext_8) => { _ = try self.reader.readIntBig(u16); // skip first 2 bytes const sec = try self.reader.readIntBig(u32); const nsec = try self.reader.readIntBig(i64); return Timestamp{ .sec = sec, .nsec = nsec }; }, else => return error.MismatchingFormatType, } } /// Deserializes the data stream to `null`. Returns an error /// if the data does not correspond to the right format pub fn deserializeNull(self: *Self) ReadError!null { const byte = try self.reader.readByte(); if (byte != format(.nil)) return error.MismatchingFormatType; return null; } /// Deserializes a msgpack map into the given struct of type `T` pub fn deserializeStruct(self: *Self, comptime T: type) ReadError!T { const info = @typeInfo(T); if (info != .Struct) @compileError("Given type '" ++ @typeName(T) ++ "' is not a struct"); const byte = try self.reader.readByte(); const len: u32 = switch (byte) { format(.fixmap_base)...format(.fixmap_max) => byte - format(.fixmap_base), format(.map_16) => try self.reader.readIntBig(u16), format(.map_32) => try self.reader.readIntBig(u32), else => return error.MismatchingFormatType, }; var value: T = undefined; var i: usize = 0; loop: while (i < len) : (i += 1) { const key = try self.deserializeString(); inline for (meta.fields(T)) |struct_field| { if (std.mem.eql(u8, struct_field.name, key)) { try self.deserializeInto(&@field(value, struct_field.name)); continue :loop; } } return error.MismatchingFormatType; } return value; } /// Deserializes a msgpack array into the given type `T`. pub fn deserializeArray(self: *Self, comptime T: type) ReadError!T { const info = @typeInfo(T); if (comptime !trait.isSlice(T) and info != .Array) @compileError("Expected given type to be an array or slice, but instead got '" ++ @typeName(T) ++ "'"); const byte = try self.reader.readByte(); const len: u32 = switch (byte) { format(.fixarray_base)...format(.fixarray_max) => byte - format(.fixarray_base), format(.array_16) => try self.reader.readIntBig(u16), format(.array_32) => try self.reader.readIntBig(u32), else => return error.MismatchingFormatType, }; if (comptime trait.isSlice(T)) { const t_buf = std.mem.bytesAsSlice( meta.Child(T), self.buffer[self.index..][0 .. len * @sizeOf(meta.Child(T))], ); self.index += len * @sizeOf(meta.Child(T)); for (t_buf) |*v, i| { try self.deserializeInto(v); if (i == len - 1) break; } return @alignCast(@alignOf([]meta.Child(T)), t_buf); } else { const array_len = info.Array.len; var t_buf: [array_len]info.Array.child = undefined; for (t_buf) |*v| try self.deserializeInto(v); return t_buf; } } /// Deserializes a msgpack string into a string pub fn deserializeString(self: *Self) ReadError![]const u8 { const string_byte = try self.reader.readByte(); const len: u32 = switch (string_byte) { format(.fixstr_base)...format(.fixstr_max) => string_byte - format(.fixstr_base), format(.str_8) => try self.reader.readByte(), format(.str_16) => try self.reader.readIntBig(u16), format(.str_32) => try self.reader.readIntBig(u32), else => return error.MismatchingFormatType, }; if (len > size - self.index) return error.BufferTooSmall; const old = self.index; self.index += try self.reader.readAll(self.buffer[self.index .. self.index + len]); return self.buffer[old..self.index]; } /// Deserializes a msgpack binary data format serialized stream into a slice of bytes pub fn deserializeBin(self: *Self) ReadError![]u8 { const byte = try self.reader.readByte(); const len: u32 = switch (byte) { format(.bin_8) => try self.reader.readByte(), format(.bin_16) => try self.reader.readIntBig(u16), format(.bin_32) => try self.reader.readIntBig(u32), else => return error.MismatchingFormatType, }; if (len > size - self.index) return error.BufferTooSmall; const old = self.index; self.index += try self.reader.readAll(self.buffer[self.index .. self.index + len]); return self.buffer[old..self.index]; } /// Deserializes the msgpack data into a boolean. pub fn deserializeBool(self: *Self) ReadError!bool { return switch (try self.reader.readByte()) { format(.@"true") => true, format(.@"false") => false, else => return error.MismatchingFormatType, }; } /// Deserializes the data stream into an integer of type `T`. /// Returns `error.MismatchingFormatType` when the stream contains a different /// data type than `T`. pub fn deserializeInt(self: *Self, comptime T: type) ReadError!T { if (@typeInfo(T) != .Int) @compileError("Expected integer type, but found type '" ++ @typeName(T) ++ "'"); return if (comptime trait.isSignedInt(T)) self.deserializeSignedInt(T) else self.deserializeUnsignedInt(T); } /// Deserializes the data into an unsigned integer of type `T` pub fn deserializeUnsignedInt(self: *Self, comptime T: type) ReadError!T { if (comptime !trait.isUnsignedInt(T)) @compileError("Given type '" ++ @typeName(T) ++ "' is not an unsigned integer"); const byte = try self.reader.readByte(); const bits = meta.bitCount(T); switch (byte) { format(.fixint_base)...format(.fixint_max) => return if (bits > 7) @intCast(T, byte) else @truncate(T, byte), format(.uint_8) => { const result = try self.reader.readByte(); return if (bits > 8) @intCast(T, result) else @truncate(T, result); }, format(.uint_16) => { const result = try self.reader.readIntBig(u16); return if (bits > 16) @intCast(T, result) else @truncate(T, result); }, format(.uint_32) => { const result = try self.reader.readIntBig(u32); return if (bits > 32) @intCast(T, result) else @truncate(T, result); }, format(.uint_64) => { const result = try self.reader.readIntBig(u64); return if (bits > 64) @intCast(T, result) else @truncate(T, result); }, else => return error.MismatchingFormatType, } } /// Deserializes the data into a signed integer of type `T` pub fn deserializeSignedInt(self: *Self, comptime T: type) ReadError!T { if (comptime !trait.isSignedInt(T)) @compileError("Given type '" ++ @typeName(T) ++ "' is not a signed integer"); const byte = try self.reader.readByte(); const bits = meta.bitCount(T); switch (byte) { format(.negfixint_base)...format(.negfixint_max) => return if (bits > 5) @intCast(T, byte) else @truncate(T, byte), format(.int_8) => { const result = try self.reader.readIntBig(i8); return if (bits > 8) @intCast(T, result) else @truncate(T, result); }, format(.int_16) => { const result = try self.reader.readIntBig(i16); return if (bits > 16) @intCast(T, result) else @truncate(T, result); }, format(.int_32) => { const result = try self.reader.readIntBig(i32); return if (bits > 32) @intCast(T, result) else @truncate(T, result); }, format(.int_64) => { const result = try self.reader.readIntBig(i64); return if (bits > 64) @intCast(T, result) else @truncate(T, result); }, else => return error.MismatchingFormatType, } } /// Desiserializes the serialized data into `T` which must be of type `f32` or `f64` pub fn deserializeFloat(self: *Self, comptime T: type) ReadError!T { comptime assert(trait.isFloat(T)); const float = try self.reader.readByte(); switch (float) { format(.float_32) => { if (T != f32) return error.MismatchingFormatType; return @bitCast(T, try self.reader.readIntBig(u32)); }, format(.float_64) => { if (T != f64) return error.MismatchingFormatType; return @bitCast(T, try self.reader.readIntBig(u64)); }, else => return error.MismatchingFormatType, } } /// Deserializes extension data and sets the given `type` value pub fn deserializeExt(self: *Self, data_type: *i8) ReadError![]const u8 { const reader = self.reader; const byte = try reader.readByte(); const len: u32 = switch (byte) { format(.fixext_1) => 1, format(.fixext_2) => 2, format(.fixext_4) => 4, format(.fixext_8) => 8, format(.fixext_16) => 16, format(.ext_8) => try reader.readByte(), format(.ext_16) => try reader.readIntBig(u16), format(.ext_32) => try reader.readIntBig(u32), else => return error.MismatchingFormatType, }; data_type.* = try reader.readIntBig(i8); const old = self.index; self.index += try reader.readAll(self.buffer[old .. old + len]); return self.buffer[old..self.index]; } /// Resets the internal buffer of `Self`. Calling any of the deserializing functions /// after this will rewrite the buffer starting at index 0. pub fn reset(self: *Self) void { self.index = 0; } }; } /// returns a new `Deserializer` for the type of the given `reader` pub fn deserializer(reader: anytype, comptime size: usize) Deserializer(@TypeOf(reader), size) { return Deserializer(@TypeOf(reader), size).init(reader); } /// Generic function that wraps around the given `WriterType`. /// Serializes given values into msgpack format /// /// Custom serialization functions can be provided by declaring /// `serialize(*Self, anytype)!void` function pub fn Serializer(comptime WriterType: type) type { return struct { const Self = @This(); writer: WriterType, pub const WriteError = error{ SliceTooLong, integerTooBig, InvalidFloatSize } || WriterType.Error; /// Initializes a new instance of `Serializer(WriterType)` pub fn init(writer: WriterType) Self { return .{ .writer = writer }; } /// Serializes the given value into msgpack format and writes it `WriterType` pub fn serialize(self: *Self, value: anytype) WriteError!void { try self.serializeTyped(@TypeOf(value), value); } /// Serializes the given type `S` into msgpack format and writes it to the writer /// of type `WriterType` pub fn serializeTyped(self: *Self, comptime S: type, value: S) WriteError!void { if (comptime trait.hasFn("serialize")(S)) return value.serialize(self); switch (S) { []const u8 => try self.serializeString(value), []u8 => try self.serializeBin(value), else => switch (@typeInfo(S)) { .Int => try self.serializeInt(S, value), .Bool => try self.serializeBool(value), .Float => try self.serializeFloat(S, value), .Null => try self.serializeNull(), .Struct => try self.serializeStruct(S, value), .Array => try self.serializeArray(S, value), .Pointer => try self.serializePointer(S, value), .Optional => |opt| try self.serializeOptional(opt.child, value), else => @compileError("Unsupported type '" ++ @typeName(S) ++ "'"), }, } } /// Serializes a 'nil' byte pub fn serializeNull(self: *Self) WriteError!void { try self.writer.writeByte(format(.nil)); } /// Serializes a timestamp for the given `timestamp` value pub fn serializeTimestamp(self: *Self, timestamp: Timestamp) WriteError!void { const writer = self.writer; if (@as(u64, timestamp.sec) >> 34 == 0) { const data: u64 = (@intCast(u64, timestamp.nsec) << 34) | timestamp.sec; if (data & 0xffffffff00000000 == 0) { try writer.writeByte(format(.fixext_4)); try writer.writeIntBig(i8, -1); try writer.writeIntBig(u32, @intCast(u32, data)); } else { try writer.writeByte(format(.fixext_8)); try writer.writeIntBig(i8, -1); try writer.writeIntBig(u64, data); } } else { try writer.writeByte(format(.ext_8)); try writer.writeByte(12); try writer.writeIntBig(i8, -1); try writer.writeIntBig(u32, timestamp.sec); try writer.writeIntBig(i64, timestamp.nsec); } } /// Serializes a string or byte array and writes it to the given `writer` pub fn serializeString(self: *Self, value: []const u8) WriteError!void { const len = value.len; if (len == 0) return; if (len > max(u32)) return error.SliceTooLong; switch (len) { 0...max(u5) => try self.writer.writeByte(fixstr(@intCast(u5, len))), max(u5) + 1...max(u8) => { try self.writer.writeByte(format(.str_8)); try self.writer.writeByte(@intCast(u8, len)); }, max(u8) + 1...max(u16) => { try self.writer.writeByte(format(.str_16)); try self.writer.writeIntBig(u16, @intCast(u16, len)); }, max(u16) + 1...max(u32) => { try self.writer.writeByte(format(.str_32)); try self.writer.writeIntBig(u32, @intCast(u32, len)); }, else => unreachable, } try self.writer.writeAll(value); } /// Serializes a signed or unsigned integer pub fn serializeInt(self: *Self, comptime S: type, value: S) WriteError!void { return if (comptime trait.isSignedInt(S)) self.serializeSignedInt(S, value) else self.serializeUnsignedInt(S, value); } /// Serializes an unsigned integer pub fn serializeUnsignedInt(self: *Self, comptime S: type, value: S) WriteError!void { if (comptime !trait.isUnsignedInt(S)) compileError("Expected unsigned integer, but instead found type '" ++ @typeName(S) ++ "'"); switch (comptime meta.bitCount(S)) { 0...7 => try self.writer.writeByte(value), 8 => { try self.writer.writeByte(format(.uint_8)); try self.writer.writeByte(value); }, 9...16 => { try self.writer.writeByte(format(.uint_16)); try self.writer.writeIntBig(u16, value); }, 17...32 => { try self.writer.writeByte(format(.uint_32)); try self.writer.writeIntBig(u32, value); }, 33...64 => { try self.writer.writeByte(format(.uint_64)); try self.writer.writeIntBig(u64, value); }, else => return error.integerTooBig, } } /// Serializes and checks a signed integer pub fn serializeSignedInt(self: *Self, comptime S: type, value: S) WriteError!void { if (comptime !trait.isSignedInt(S)) compileError("Expected signed integer, but instead found type '" ++ @typeName(S) ++ "'"); switch (comptime meta.bitCount(S)) { 0...5 => try self.writer.writeByte(negint(value)), 5...8 => { try self.writer.writeByte(format(.int_8)); try self.writer.writeIntBig(i8, value); }, 8...16 => { try self.writer.writeByte(format(.int_16)); try self.writer.writeIntBig(i16, value); }, 16...32 => { try self.writer.writeByte(format(.int_32)); try self.writer.writeIntBig(i32, value); }, 32...64 => { try self.writer.writeByte(format(.int_64)); try self.writer.writeIntBig(i64, value); }, else => return error.integerTooBig, } } /// Serializes and writes the booleans value to the `writer` pub fn serializeBool(self: *Self, value: bool) WriteError!void { try self.writer.writeByte(if (value) format(.@"true") else format(.@"false")); } /// Serializes a 32 -or 64bit float and writes it to the `writer` /// TODO ensure big-endian byte order pub fn serializeFloat(self: *Self, comptime S: type, value: S) WriteError!void { comptime assert(trait.isFloat(S)); switch (@typeInfo(S).Float.bits) { 32 => { try self.writer.writeByte(format(.float_32)); try self.writer.writeIntBig(u32, @bitCast(u32, value)); }, 64 => { try self.writer.writeByte(format(.float_64)); try self.writer.writeIntBig(u64, @bitCast(u64, value)); }, else => { return error.InvalidFloatSize; }, } } /// Serializes and writes a raw byte slice to the given `writer` pub fn serializeBin(self: *Self, value: []const u8) WriteError!void { const len = value.len; if (len == 0) return; if (len > max(u32)) return error.SliceTooLong; const writer = self.writer; switch (len) { 0...max(u8) => try writer.writeByte(@intCast(u8, len)), max(u8) + 1...max(u8) => { try writer.writeByte(format(.bin_8)); try writer.writeByte(@intCast(u8, len)); }, max(u8) + 1...max(u16) => { try writer.writeByte(format(.bin_16)); try writer.writeIntBig(u16, @intCast(u16, len)); }, max(u16) + 1...max(u32) => { try writer.writeByte(format(.bin_32)); try writer.writeIntBig(u32, @intCast(u32, len)); }, else => unreachable, } try writer.writeAll(value); } /// Serializes the value as an array and writes each element to the `writer` pub fn serializeArray(self: *Self, comptime S: type, value: S) WriteError!void { const len = value.len; if (len == 0) return; if (len > max(u32)) return error.SliceTooLong; const writer = self.writer; switch (len) { 0...max(u4) => try writer.writeByte(fixarray(@intCast(u4, len))), max(u4) + 1...max(u16) => { try writer.writeByte(format(.array_16)); try writer.writeIntBig(u16, @intCast(u16, len)); }, max(u16) + 1...max(u32) => { try writer.writeByte(format(.array_32)); try writer.writeIntBig(u32, @intCast(u32, len)); }, else => unreachable, } for (value) |val| try self.serializeTyped(meta.Child(S), val); } /// Serializes a pointer and writes its internal value to the `writer` pub fn serializePointer(self: *Self, comptime S: type, value: S) WriteError!void { switch (@typeInfo(S).Pointer.size) { .One => try self.serializeTyped(S, value), .Many, .C, .Slice => try self.serializeArray(S, value), } } /// Serializes the given value to 'nil' if `null` or typed if the optional is not `null` pub fn serializeOptional(self: *Self, comptime S: type, value: ?S) WriteError!void { if (value) |val| try self.serializeTyped(S, val) else try self.writer.writeByte(format(.nil)); } /// Serializes a struct into a map type and writes its to the given `writer` pub fn serializeStruct(self: *Self, comptime S: type, value: S) WriteError!void { comptime assert(@typeInfo(S) == .Struct); const fields = meta.fields(S); const fields_len = fields.len; comptime assert(fields_len <= max(u32)); if (fields_len == 0) return; const writer = self.writer; switch (fields_len) { 0...max(u4) => try writer.writeByte(fixmap(@intCast(u4, fields_len))), max(u4) + 1...max(u16) => { try writer.writeByte(format(.map_16)); try writer.writeIntBig(u16, @intCast(u16, len)); }, max(u16) + 1...max(u32) => { try writer.writeByte(format(.array_32)); try writer.writeIntBig(u32, @intCast(u32, len)); }, } inline for (fields) |field| { try self.serializeString(field.name); try self.serializeTyped(field.field_type, @field(value, field.name)); } } /// Serializes extension data pub fn serializeExt( self: *Self, data_type: i8, data: []const u8, ) WriteError!void { const writer = self.writer; const format_byte = if (data.len <= 16 and std.math.isPowerOfTwo(data.len)) switch (data.len) { 1 => format(.fixext_1), 2 => format(.fixext_2), 4 => format(.fixext_4), 8 => format(.fixext_8), 16 => format(.fixext_16), else => unreachable, } else switch (data.len) { 0...max(u8) => format(.ext_8), max(u8) + 1...max(u16) => format(.ext_16), max(u16) + 1...max(u32) => format(.ext_32), else => return error.SliceTooLong, }; try writer.writeByte(format_byte); if (data.len > 16 or !std.math.isPowerOfTwo(data.len)) { switch (data.len) { 0...max(u8) => try writer.writeByte(@intCast(u8, data.len)), max(u8) + 1...max(u16) => try writer.writeIntBig(u16, @intCast(u16, data.len)), max(u16) + 1...max(u32) => try writer.writeIntBig(u32, @intCast(u32, data.len)), else => unreachable, } } try writer.writeIntBig(i8, data_type); try writer.writeAll(data); } }; } /// Function that creates a new generic that wraps around the given writer. /// Serializes given values into msgpack format /// /// Custom serialization functions can be provided by declaring /// `serialize(*Self, anytype)!void` function pub fn serializer(writer: anytype) Serializer(@TypeOf(writer)) { return Serializer(@TypeOf(writer)).init(writer); } test { _ = @import("tests.zig"); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const panic = std.debug.panic; const Allocator = std.mem.Allocator; const cwd = std.fs.cwd; const OpenFlags = std.fs.File.OpenFlags; const glm = @import("glm.zig"); const Mat4 = glm.Mat4; const Vec3 = glm.Vec3; usingnamespace @import("c.zig"); pub const Shader = struct { id: c_uint, pub fn init(allocator: *Allocator, vertexPath: []const u8, fragmentPath: []const u8) !Shader { // 1. retrieve the vertex/fragment source code from filePath const vShaderFile = try cwd().openFile(vertexPath, OpenFlags{ .read = true, .write = false }); defer vShaderFile.close(); const fShaderFile = try cwd().openFile(fragmentPath, OpenFlags{ .read = true, .write = false }); defer fShaderFile.close(); var vertexCode = try allocator.alloc(u8, try vShaderFile.getEndPos()); defer allocator.free(vertexCode); var fragmentCode = try allocator.alloc(u8, try fShaderFile.getEndPos()); defer allocator.free(fragmentCode); const vLen = try vShaderFile.read(vertexCode); const fLen = try fShaderFile.read(fragmentCode); // 2. compile shaders // vertex shader const vertex = glCreateShader(GL_VERTEX_SHADER); const vertexSrcPtr: ?[*]const u8 = vertexCode.ptr; glShaderSource(vertex, 1, &vertexSrcPtr, null); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader const fragment = glCreateShader(GL_FRAGMENT_SHADER); const fragmentSrcPtr: ?[*]const u8 = fragmentCode.ptr; glShaderSource(fragment, 1, &fragmentSrcPtr, null); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // shader Program const id = glCreateProgram(); glAttachShader(id, vertex); glAttachShader(id, fragment); glLinkProgram(id); checkCompileErrors(id, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); return Shader{ .id = id }; } pub fn use(self: Shader) void { glUseProgram(self.id); } pub fn setBool(self: Shader, name: [:0]const u8, val: bool) void { // glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } pub fn setInt(self: Shader, name: [:0]const u8, val: c_int) void { glUniform1i(glGetUniformLocation(self.id, name), val); } pub fn setFloat(self: Shader, name: [:0]const u8, val: f32) void { glUniform1f(glGetUniformLocation(self.id, name), val); } pub fn setMat4(self: Shader, name: [:0]const u8, val: Mat4) void { glUniformMatrix4fv(glGetUniformLocation(self.id, name), 1, GL_FALSE, &val.vals[0][0]); } pub fn setVec3(self: Shader, name: [:0]const u8, val: Vec3) void { glUniform3f(glGetUniformLocation(self.id, name), val.vals[0], val.vals[1], val.vals[2]); } fn checkCompileErrors(shader: c_uint, errType: []const u8) void { var success: c_int = undefined; var infoLog: [1024]u8 = undefined; if (!std.mem.eql(u8, errType, "PROGRAM")) { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (success == 0) { glGetShaderInfoLog(shader, 1024, null, &infoLog); panic("ERROR::SHADER::{s}::COMPILATION_FAILED\n{s}\n", .{ errType, infoLog }); } } else { glGetShaderiv(shader, GL_LINK_STATUS, &success); if (success == 0) { glGetShaderInfoLog(shader, 1024, null, &infoLog); panic("ERROR::SHADER::LINKING_FAILED\n{s}\n", .{infoLog}); } } } };
src/shader.zig
const std = @import("std"); const assert = std.debug.assert; /// An intrusive first in/first out linked list. /// The element type T must have a field called "next" of type ?*T pub fn FIFO(comptime T: type) type { return struct { const Self = @This(); in: ?*T = null, out: ?*T = null, pub fn push(self: *Self, elem: *T) void { assert(elem.next == null); if (self.in) |in| { in.next = elem; self.in = elem; } else { assert(self.out == null); self.in = elem; self.out = elem; } } pub fn pop(self: *Self) ?*T { const ret = self.out orelse return null; self.out = ret.next; ret.next = null; if (self.in == ret) self.in = null; return ret; } pub fn peek(self: Self) ?*T { return self.out; } /// Remove an element from the FIFO. Asserts that the element is /// in the FIFO. This operation is O(N), if this is done often you /// probably want a different data structure. pub fn remove(self: *Self, to_remove: *T) void { if (to_remove == self.out) { _ = self.pop(); return; } var it = self.out; while (it) |elem| : (it = elem.next) { if (to_remove == elem.next) { elem.next = to_remove.next; to_remove.next = null; break; } } else unreachable; } }; } test "push/pop/peek/remove" { const testing = @import("std").testing; const Foo = struct { next: ?*@This() = null }; var one: Foo = .{}; var two: Foo = .{}; var three: Foo = .{}; var fifo: FIFO(Foo) = .{}; fifo.push(&one); testing.expectEqual(@as(?*Foo, &one), fifo.peek()); fifo.push(&two); fifo.push(&three); testing.expectEqual(@as(?*Foo, &one), fifo.peek()); fifo.remove(&one); testing.expectEqual(@as(?*Foo, &two), fifo.pop()); testing.expectEqual(@as(?*Foo, &three), fifo.pop()); testing.expectEqual(@as(?*Foo, null), fifo.pop()); fifo.push(&one); fifo.push(&two); fifo.push(&three); fifo.remove(&two); testing.expectEqual(@as(?*Foo, &one), fifo.pop()); testing.expectEqual(@as(?*Foo, &three), fifo.pop()); testing.expectEqual(@as(?*Foo, null), fifo.pop()); fifo.push(&one); fifo.push(&two); fifo.push(&three); fifo.remove(&three); testing.expectEqual(@as(?*Foo, &one), fifo.pop()); testing.expectEqual(@as(?*Foo, &two), fifo.pop()); testing.expectEqual(@as(?*Foo, null), fifo.pop()); }
src/fifo.zig
const std = @import("std"); const warn = std.debug.warn; pub const CommandType = enum(u8) { PASS, NICK, USER, SERVER, OPER, QUIT, SQUIT, JOIN, PART, MODE, TOPIC, NAMES, LIST, INVITE, KICK, VERSION, STATS, LINKS, TIME, CONNECT, TRACE, ADMIN, INFO, PRIVMSG, NOTICE, WHO, WHOIS, WHOWAS, KILL, PING, PONG, ERROR, AWAY, REHASH, RESTART, SUMMON, USERS, WALLOPS, USERHOST, ISON, }; // <message> ::= [':' <prefix> <SPACE> ] <command> <params> <crlf> // <prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ] // <command> ::= <letter> { <letter> } | <number> <number> <number> // <SPACE> ::= ' ' { ' ' } // <params> ::= <SPACE> [ ':' <trailing> | <middle> <params> ] // <middle> ::= <Any *non-empty* sequence of octets not including SPACE // or NUL or CR or LF, the first of which may not be ':'> // <trailing> ::= <Any, possibly *empty*, sequence of octets not including // NUL or CR or LF> // <crlf> ::= CR LF pub const Message = struct { prefix: ?struct { servername: ?[]const u8 = null, nick: ?[]const u8 = null, user: ?[]const u8 = null, host: ?[]const u8 = null, } = null, command_text: ?[]const u8 = null, command: ?CommandType = null, params: ?[]const u8 = null, pub fn parse(input: []const u8) ?Message { if (input.len == 0) return null; var m = Message{}; var len: usize = 0; if (input[0] == ':') { // parse prefix m.prefix = .{}; len += 1; if (strtok(input[len..], ' ')) |prefix| { if (strtok(prefix, '!')) |nick| { m.prefix.?.nick = nick; len += nick.len + 1; if (strtok(input[len..], '@')) |user| { m.prefix.?.user = user; len += user.len + 1; if (strtok(input[len..], ' ')) |host| { m.prefix.?.host = host; len += host.len + 1; } } } else { m.prefix.?.servername = prefix; len += prefix.len + 1; } } } // parse command, params if (strtok(input[len..], ' ')) |command_text| { m.command_text = command_text; m.command = std.meta.stringToEnum(CommandType, command_text); len += command_text.len + 1; m.params = input[len..]; len += m.params.?.len; } return m; } }; /// return text up to but not inclding delimiter /// if delimiter is null, return all input pub fn strtok(_in: []const u8, _delim: ?u8) ?[]const u8 { const delim = _delim orelse return _in; var in = _in; while (in.len > 0) : (in = in[1..]) { if (in[0] == delim) return _in[0 .. _in.len - in.len]; } return null; } test "strtok" { const nick = strtok(":nick!"[1..], '!') orelse return error.StrtokFailure; assert(std.mem.eql(u8, nick, "nick")); assert(strtok("asdf", '.') == null); } pub fn strtoks(_in: []const u8, _delims: []?u8) ?[]const u8 { for (_delims) |delim| if (strtok(_in, delim)) |res| return res; return null; } const assert = std.debug.assert; test "parse PRIVMSG" { const _m = Message.parse(":nick!~user@host PRIVMSG #channel :message (could contain the word PRIVMSG)"); assert(_m != null); const m = _m.?; assert(std.mem.eql(u8, m.prefix.?.nick.?, "nick")); assert(std.mem.eql(u8, m.command_text.?, "PRIVMSG")); assert(m.command.? == .PRIVMSG); assert(std.mem.eql(u8, m.prefix.?.user.?, "~user")); assert(std.mem.eql(u8, m.prefix.?.host.?, "host")); } test "welcome messages" { const input = \\:tmi.twitch.tv 001 nickname :Welcome, GLHF! \\:tmi.twitch.tv 002 nickname :Your host is tmi.twitch.tv \\:tmi.twitch.tv 003 nickname :This server is rather new \\:tmi.twitch.tv 004 nickname :- \\:tmi.twitch.tv 375 nickname :- \\:tmi.twitch.tv 372 nickname :You are in a maze of twisty passages, all alike. \\:tmi.twitch.tv 376 nickname :> \\:[email protected] JOIN #channel \\:nickname.tmi.twitch.tv 353 nickname = #channel :nickname \\:nickname.tmi.twitch.tv 366 nickname #channel :End of /NAMES list \\:[email protected] PRIVMSG #channel :hello chat \\PING :tmi.twitch.tv ; var itr = std.mem.separate(input, "\n"); while (itr.next()) |in| { const m = Message.parse(in); assert(m != null); if (m.?.command != null and m.?.command.? != .PING) { assert(m.?.prefix != null); assert(m.?.prefix.?.host != null); } // std.debug.warn("{}, .command_text = {}, .command = {}, .params = {}\n", .{ m.?.prefix, m.?.command_text, m.?.command, m.?.params }); } }
src/message.zig
const std = @import("std"); const time = std.time; const Window = @import("window_sdl.zig").Window; const irom = @import("rom.zig"); const immu = @import("mmu.zig"); const icpu = @import("cpu.zig"); const igpu = @import("gpu.zig"); const imbc = @import("mbc.zig"); pub const Gb = struct { mem: [0x10000]u8, window: Window, mmu: immu.Mmu, cpu: icpu.Z80, gpu: igpu.Gpu(Window), rom: irom.Rom, prng: std.rand.DefaultPrng, pub fn init(rom_binary: []u8) !Gb { var buf: [4]u8 = undefined; try std.crypto.randomBytes(buf[0..]); const seed = std.mem.readIntSliceLittle(u32, buf[0..4]); var gb: Gb = undefined; gb.rom = try irom.Rom.load(rom_binary); gb.mmu = immu.Mmu.init(gb.mem[0..], &gb.rom); gb.cpu = icpu.Z80.init(&gb.mmu); gb.gpu = igpu.Gpu(Window).init(&gb.mmu, &gb.window); gb.prng = std.rand.DefaultPrng.init(seed); gb.window = try Window.init(&gb.mmu); gb.rom.header.debugPrint(); return gb; } pub fn deinit(gb: *Gb) void { gb.window.deinit(); } pub fn run(gb: *Gb) void { // Having a specific boot mbc avoids an extra branch on every ROM/RAM access. const original_mbc = gb.mmu.mbc; gb.mmu.mbc = imbc.Mbc{ .Boot = imbc.MbcBoot.init() }; // TODO: Handle boot rom write to ROM/RAM while (gb.cpu.r2[icpu.PC] != 0x100) { const frame_end_ticks = gb.cpu.ticks + igpu.frame_cycle_time; while (gb.cpu.total_ticks < frame_end_ticks) { const opcode = gb.cpu.read8(gb.cpu.r2[icpu.PC]); gb.cpu.r2[icpu.PC] +%= 1; const cycles = gb.cpu.step(opcode); gb.gpu.step(cycles); } gb.window.handleEvents() catch return; time.sleep(16 * time.millisecond); // time.ns_per_s * icpu.clock_speed / igpu.frame_cycle_time); } gb.mmu.mbc = original_mbc; gb.prng.random.bytes(gb.mmu.mem[256..0xe000]); std.mem.copy(u8, gb.mmu.mem[0xe000..0xfdff], gb.mmu.mem[0xc000..0xddff]); gb.cpu.r2[icpu.AF] = 0x01b0; gb.cpu.r2[icpu.BC] = 0x0013; gb.cpu.r2[icpu.DE] = 0x00d8; gb.cpu.r2[icpu.HL] = 0x014d; gb.cpu.r2[icpu.SP] = 0xfffe; const A = immu.addresses; gb.mmu.mem[A.TIMA] = 0x00; gb.mmu.mem[A.TMA_] = 0x00; gb.mmu.mem[A.TAC_] = 0x00; gb.mmu.mem[A.NR10] = 0x80; gb.mmu.mem[A.NR11] = 0xbf; gb.mmu.mem[A.NR12] = 0xf3; gb.mmu.mem[A.NR14] = 0xbf; gb.mmu.mem[A.NR21] = 0x3f; gb.mmu.mem[A.NR22] = 0x00; gb.mmu.mem[A.NR24] = 0xbf; gb.mmu.mem[A.NR30] = 0x7f; gb.mmu.mem[A.NR31] = 0xff; gb.mmu.mem[A.NR32] = 0x9f; gb.mmu.mem[A.NR33] = 0xbf; gb.mmu.mem[A.NR41] = 0xff; gb.mmu.mem[A.NR42] = 0x00; gb.mmu.mem[A.NR43] = 0x00; gb.mmu.mem[A.NR44] = 0xbf; gb.mmu.mem[A.NR50] = 0x77; gb.mmu.mem[A.NR51] = 0xf3; gb.mmu.mem[A.NR52] = 0xf1; gb.mmu.mem[A.LCDC] = 0x91; gb.mmu.mem[A.SCY_] = 0x00; gb.mmu.mem[A.SCX_] = 0x00; gb.mmu.mem[A.LYC_] = 0x00; gb.mmu.mem[A.BGP_] = 0xfc; gb.mmu.mem[A.OBP0] = 0xff; gb.mmu.mem[A.OBP1] = 0xff; gb.mmu.mem[A.WY__] = 0x00; gb.mmu.mem[A.WX__] = 0x00; gb.mmu.mem[A.IE__] = 0x00; while (true) { const frame_end_ticks = gb.cpu.ticks + igpu.frame_cycle_time; while (gb.cpu.total_ticks < frame_end_ticks) { const opcode = gb.cpu.read8(gb.cpu.r2[icpu.PC]); gb.cpu.r2[icpu.PC] +%= 1; const cycles = gb.cpu.step(opcode); gb.gpu.step(cycles); } gb.window.handleEvents() catch return; time.sleep(16 * time.millisecond); //time.ns_per_s * icpu.clock_speed / igpu.frame_cycle_time); } } };
src/gameboy.zig
const std = @import("std"); const c = @import("c.zig"); const Mat4 = @import("math3d.zig").Mat4; const Vec3 = @import("math3d.zig").Vec3; const glsl = @cImport({ @cInclude("sokol/sokol_gfx.h"); @cInclude("shaders/instancing.glsl.h"); }); const rand = @import("std").rand; const SampleCount = 4; const NumParticlesEmittedPerFrame = 10; const MaxParticles: u32 = 512 * 2014; const State = struct { pass_action: c.sg_pass_action, main_pipeline: c.sg_pipeline, main_bindings: c.sg_bindings, }; var rndgen = rand.DefaultPrng.init(42); var ry: f32 = 0.0; var state: State = undefined; var cur_num_particles: u32 = 0; var pos: [MaxParticles]Vec3 = undefined; var vel: [MaxParticles]Vec3 = undefined; fn frnd(range: f32) f32 { return rndgen.random.float(f32) * range; } export fn init() void { var desc = std.mem.zeroes(c.sg_desc); desc.context = c.sapp_sgcontext(); c.sg_setup(&desc); c.stm_setup(); state.pass_action.colors[0].action = .SG_ACTION_CLEAR; state.pass_action.colors[0].value = c.sg_color{ .r = 0.2, .g = 0.2, .b = 0.2, .a = 1.0 }; const r = 0.05; const vertices = [_]f32{ // positions colors 0.0, -r, 0.0, 1.0, 0.0, 0.0, 1.0, r, 0.0, r, 0.0, 1.0, 0.0, 1.0, r, 0.0, -r, 0.0, 0.0, 1.0, 1.0, -r, 0.0, -r, 1.0, 1.0, 0.0, 1.0, -r, 0.0, r, 0.0, 1.0, 1.0, 1.0, 0.0, r, 0.0, 1.0, 0.0, 1.0, 1.0, }; const indices = [_]u16{ 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1, 5, 1, 2, 5, 2, 3, 5, 3, 4, 5, 4, 1, }; var vertex_buffer_desc = std.mem.zeroes(c.sg_buffer_desc); vertex_buffer_desc.size = vertices.len * @sizeOf(f32); vertex_buffer_desc.data = .{ .ptr = &vertices[0], .size = vertex_buffer_desc.size }; state.main_bindings.vertex_buffers[0] = c.sg_make_buffer(&vertex_buffer_desc); var index_buffer_desc = std.mem.zeroes(c.sg_buffer_desc); index_buffer_desc.type = .SG_BUFFERTYPE_INDEXBUFFER; index_buffer_desc.size = indices.len * @sizeOf(u16); index_buffer_desc.data = .{ .ptr = &indices[0], .size = index_buffer_desc.size }; state.main_bindings.index_buffer = c.sg_make_buffer(&index_buffer_desc); var instance_buffer_desc = std.mem.zeroes(c.sg_buffer_desc); instance_buffer_desc.size = MaxParticles * @sizeOf(Vec3); instance_buffer_desc.usage = .SG_USAGE_STREAM; state.main_bindings.vertex_buffers[1] = c.sg_make_buffer(&instance_buffer_desc); const shader_desc = @ptrCast([*]const c.sg_shader_desc, glsl.instancing_shader_desc(glsl.sg_query_backend())); const shader = c.sg_make_shader(shader_desc); var pipeline_desc = std.mem.zeroes(c.sg_pipeline_desc); pipeline_desc.layout.attrs[glsl.ATTR_vs_pos].format = .SG_VERTEXFORMAT_FLOAT3; pipeline_desc.layout.attrs[glsl.ATTR_vs_color0].format = .SG_VERTEXFORMAT_FLOAT4; pipeline_desc.layout.attrs[glsl.ATTR_vs_inst_pos].format = .SG_VERTEXFORMAT_FLOAT3; pipeline_desc.layout.attrs[glsl.ATTR_vs_inst_pos].buffer_index = 1; pipeline_desc.layout.buffers[1].step_func = .SG_VERTEXSTEP_PER_INSTANCE; pipeline_desc.shader = shader; pipeline_desc.index_type = .SG_INDEXTYPE_UINT16; pipeline_desc.depth.compare = .SG_COMPAREFUNC_LESS_EQUAL; pipeline_desc.depth.write_enabled = true; pipeline_desc.cull_mode = .SG_CULLMODE_BACK; state.main_pipeline = c.sg_make_pipeline(&pipeline_desc); } export fn update() void { const width = c.sapp_width(); const height = c.sapp_height(); const w: f32 = @intToFloat(f32, width); const h: f32 = @intToFloat(f32, height); const radians: f32 = 1.0472; //60 degrees const frame_time = 1.0 / 60.0; // emit new particles var i: u32 = 0; while (i < NumParticlesEmittedPerFrame) : (i += 1) { if (cur_num_particles < MaxParticles) { pos[cur_num_particles] = Vec3.new(0, 0, 0); vel[cur_num_particles] = Vec3.new(frnd(1) - 0.5, frnd(1) * 0.5 + 2.0, frnd(1) - 0.5); cur_num_particles += 1; } else { break; } } i = 0; // update particle positions while (i < cur_num_particles) : (i += 1) { vel[i].y -= 1.0 * frame_time; pos[i].x += vel[i].x * frame_time; pos[i].y += vel[i].y * frame_time; pos[i].z += vel[i].z * frame_time; // bounce back from 'ground' if (pos[i].y < -2.0) { pos[i].y = -1.8; vel[i].y = -vel[i].y; vel[i].x *= 0.8; vel[i].y *= 0.8; vel[i].z *= 0.8; } } // update instance data c.sg_update_buffer(state.main_bindings.vertex_buffers[1], &c.sg_range{ .ptr = &pos[0], .size = cur_num_particles * @sizeOf(Vec3), }); var proj: Mat4 = Mat4.createPerspective(radians, w / h, 0.01, 100.0); var view: Mat4 = Mat4.createLookAt(Vec3.new(0.0, 1.5, 12.0), Vec3.new(0.0, 0.0, 0.0), Vec3.new(0.0, 1.0, 0.0)); var view_proj = Mat4.mul(proj, view); ry += 2.0 / 400.0; var vs_params = glsl.vs_params_t{ .mvp = Mat4.mul(view_proj, Mat4.createAngleAxis(Vec3.new(0, 1, 0), ry)).toArray(), }; c.sg_begin_default_pass(&state.pass_action, width, height); c.sg_apply_pipeline(state.main_pipeline); c.sg_apply_bindings(&state.main_bindings); c.sg_apply_uniforms(.SG_SHADERSTAGE_VS, glsl.SLOT_vs_params, &.{ .ptr = &vs_params, .size = @sizeOf(glsl.vs_params_t) }); c.sg_draw(0, 24, @intCast(c_int, cur_num_particles)); c.sg_end_pass(); c.sg_commit(); } export fn cleanup() void { c.sg_shutdown(); } pub fn main() void { var app_desc = std.mem.zeroes(c.sapp_desc); app_desc.width = 1280; app_desc.height = 720; app_desc.init_cb = init; app_desc.frame_cb = update; app_desc.cleanup_cb = cleanup; app_desc.sample_count = SampleCount; app_desc.window_title = "Instancing (sokol-zig)"; _ = c.sapp_run(&app_desc); }
src/example_instancing.zig
const zervo = @import("zervo"); const std = @import("std"); const ssl = @import("ssl"); const RenderContext = zervo.renderer.RenderContext(GraphicsBackend); const imr = zervo.markups.imr; const os = std.os; const net = std.net; const warn = std.debug.warn; const Allocator = std.mem.Allocator; const zgt = @import("zgt.zig"); const GraphicsBackend = zgt.GraphicsBackend; const DISABLE_IPV6 = false; var gpa = std.heap.GeneralPurposeAllocator(.{}) {}; const allocator = &gpa.allocator; var currentUrl: ?zervo.Url = null; var addressBar: [:0]u8 = undefined; var addressBarFocused: bool = false; var renderCtx: RenderContext = undefined; var firstLoad: bool = true; const LoadResult = union(enum) { Document: imr.Document, Download: []const u8 }; const LoadErrorDetails = union(enum) { Input: []const u8 }; fn loadGemini(addr: net.Address, url: zervo.Url, loadErrorDetails: *LoadErrorDetails) !LoadResult { _ = loadErrorDetails; var errorDetails: zervo.protocols.gemini.GeminiErrorDetails = undefined; var response = zervo.protocols.gemini.request(allocator, addr, url, &errorDetails) catch |err| switch (err) { error.KnownError, error.InputRequired => { errorDetails.deinit(); switch (errorDetails) { .Input => { return error.InputRequired; }, .PermanentFailure => { return error.NotFound; }, else => unreachable } }, else => return err }; defer response.deinit(); if (response.statusCode != 20 and false) { std.log.err("Request error:\nStatus code: {} {s}", .{response.statusCode, response.meta}); return zervo.protocols.gemini.GeminiError.InvalidStatus; } const mime = response.meta; if (try zervo.markups.from_mime(allocator, url, mime, response.content)) |doc| { return LoadResult { .Document = doc }; } else { return LoadResult { .Download = try allocator.dupe(u8, response.content) }; } } fn loadHttps(addr: net.Address, url: zervo.Url, loadErrorDetails: *LoadErrorDetails) !LoadResult { _ = loadErrorDetails; var headers = zervo.protocols.http.HeaderMap.init(allocator); defer headers.deinit(); try headers.put("Connection", "close"); const rst = zervo.protocols.http.HttpRequest { .headers = headers, .secure = true, .host = url.host, .path = url.path }; var response = zervo.protocols.http.request(allocator, addr, rst) catch |err| switch (err) { else => return err }; defer response.deinit(); // if (response.statusCode != 20 and false) { // std.log.err("Request error:\nStatus code: {} {s}", .{response.statusCode, response.meta}); // return zervo.protocols.gemini.GeminiError.InvalidStatus; // } const mime = response.headers.get("Content-Type") orelse "text/html"; std.log.info("mime: {s}", .{ mime }); if (try zervo.markups.from_mime(allocator, url, mime, response.content)) |doc| { return LoadResult { .Document = doc }; } else { return LoadResult { .Download = try allocator.dupe(u8, response.content) }; } } fn loadPage(url: zervo.Url) !LoadResult { std.log.debug("Loading web page at {} host = {s}", .{url, url.host}); var defaultPort: u16 = 80; if (std.mem.eql(u8, url.scheme, "gemini")) defaultPort = 1965; if (std.mem.eql(u8, url.scheme, "https")) defaultPort = 443; const list = try net.getAddressList(allocator, url.host, url.port orelse defaultPort); defer list.deinit(); if (list.addrs.len == 0) return error.UnknownHostName; var addr = list.addrs[0]; if (DISABLE_IPV6) { var i: u32 = 1; while (addr.any.family == os.AF_INET6) : (i += 1) { addr = list.addrs[i]; } } std.log.debug("Resolved address of {s}: {}", .{url.host, addr}); if (std.mem.eql(u8, url.scheme, "gemini")) { var details: LoadErrorDetails = undefined; const doc = try loadGemini(addr, url, &details); return doc; } else if (std.mem.eql(u8, url.scheme, "https")) { var details: LoadErrorDetails = undefined; const doc = try loadHttps(addr, url, &details); return doc; } else { std.log.err("No handler for URL scheme {s}", .{url.scheme}); return error.UnhandledUrlScheme; } } fn loadPageChecked(url: zervo.Url) ?LoadResult { const doc = loadPage(url) catch |err| { const name = @errorName(err); const path = std.mem.concat(allocator, u8, &[_][]const u8 {"res/errors/", name, ".gmi"}) catch unreachable; defer allocator.free(path); const file = std.fs.cwd().openFile(path, .{}) catch { std.log.err("Missing error page for error {s}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return null; }; const full = file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch unreachable; const errorDoc = zervo.markups.gemini.parse(allocator, url, full) catch unreachable; return LoadResult { .Document = errorDoc }; }; return doc; } // Handlers fn openPage(ctx: *RenderContext, url: zervo.Url) !void { if (loadPageChecked(url)) |result| { switch (result) { .Document => |doc| { if (currentUrl) |u| { u.deinit(); } currentUrl = try url.dupe(allocator); if (!firstLoad) allocator.free(addressBar); addressBar = try std.fmt.allocPrintZ(allocator, "{}", .{currentUrl}); if (!firstLoad) ctx.document.deinit(); ctx.document = doc; ctx.layout_requested = true; ctx.offsetY = 0; ctx.offsetYTarget = 0; firstLoad = false; }, .Download => |content| { defer allocator.free(content); const lastSlash = std.mem.lastIndexOfScalar(u8, url.path, '/').?; var name = url.path[lastSlash+1..]; if (std.mem.eql(u8, name, "")) { name = "index"; } const file = try std.fs.cwd().createFile(name, .{}); try file.writeAll(content); file.close(); std.log.info("Saved to {s}", .{name}); var xdg = try std.ChildProcess.init(&[_][]const u8 {"xdg-open", name}, allocator); defer xdg.deinit(); _ = try xdg.spawnAndWait(); } } } } fn windowResize(_: *GraphicsBackend, _: f64, _: f64) void { renderCtx.layout_requested = true; } var backend: GraphicsBackend = GraphicsBackend { .ctx = undefined }; var setupped: bool = false; pub fn draw(widget: *zgt.Canvas_Impl, ctx: zgt.DrawContext) !void { backend.ctx = ctx; const width = @intToFloat(f64, widget.getWidth()); const height = @intToFloat(f64, widget.getHeight()); if (backend.width != width or backend.height != height) { renderCtx.layout_requested = true; } backend.width = width; backend.height = height; backend.clear(); renderCtx.graphics = &backend; if (!setupped) { renderCtx.setup(); setupped = true; } renderCtx.render(); } pub fn mouseButton(_: *zgt.Canvas_Impl, button: zgt.MouseButton, pressed: bool, x: u32, y: u32) !void { _ = button; backend.cursorX = @intToFloat(f64, x); backend.cursorY = @intToFloat(f64, y); RenderContext.mouseButtonCallback(&backend, .Left, pressed); } pub fn mouseScroll(_: *zgt.Canvas_Impl, _: f32, dy: f32) !void { RenderContext.mouseScrollCallback(&backend, -dy); } pub fn main() !void { try zgt.backend.init(); defer _ = gpa.deinit(); var window = try zgt.Window.init(); try ssl.init(); defer ssl.deinit(); const url = try zervo.Url.parse("gemini://gemini.circumlunar.space/"); //const url = try zervo.Url.parse("https://bellard.org/quickjs/"); renderCtx = RenderContext { .graphics = undefined, .document = undefined, .linkCallback = openPage, .allocator = allocator }; try openPage(&renderCtx, url); defer renderCtx.document.deinit(); defer currentUrl.?.deinit(); var view = zgt.ZervoView(); _ = try view.addDrawHandler(draw); try view.addMouseButtonHandler(mouseButton); try view.addScrollHandler(mouseScroll); try window.set( zgt.Column(.{}, .{ zgt.Row(.{}, .{ zgt.TextField(.{ .text = "gemini://gemini.circumlunar.space/" }) }), zgt.Expanded(&view) }) ); window.resize(800, 600); window.show(); while (zgt.stepEventLoop(.Asynchronous)) { if (backend.request_next_frame) { backend.frame_requested = true; backend.request_next_frame = false; } if (backend.frame_requested) { try view.requestDraw(); backend.frame_requested = false; } } }
src/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/day03.txt"); pub fn main() !void { try part1(); try part2(); } pub fn part2() !void { } pub fn part1() !void { var iter = tokenize(u8, data, "\n"); var num_lines : u32 = 0; var char_ctr : u32 = 0; var episilon_int : u32 = 0; var sigma_int : u32 = 0; var arr = [_]u32{0} ** 12; var sigma = [_]u8{0} ** 12; var epsilon = [_]u8{0} ** 12; while(iter.next()) |tok| { char_ctr = 0; var str = trim(u8, tok, " \t\n"); for (str) |c| { if(c == '1') { arr[char_ctr] += 1; } char_ctr += 1; } num_lines += 1; } char_ctr = 0; for(arr) |num_ones| { print("Run {d} num_ones = {d}\n", .{char_ctr, num_ones}); if(num_ones > (num_lines/2)) { sigma[char_ctr] = '1'; epsilon[char_ctr] = '0'; } else { sigma[char_ctr] = '0'; epsilon[char_ctr] = '1'; } char_ctr+=1; } sigma_int = parseInt(u32, &sigma, 2) catch |err| { print("I dun goofed 1?! Sigma = {s} {any}", .{sigma, err}); return; }; print("Sigma: {d}\n", .{sigma_int}); episilon_int = parseInt(u32, &epsilon, 2) catch |err| { print("I dun goofed 2?! Epsilon = {s} {any}", .{epsilon, err}); return; }; print("Epsilon: {d}\n", .{episilon_int}); print("Part 1: {d}\n", .{episilon_int * sigma_int}); } // 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/day03.zig
const builtin = @import("builtin"); const std = @import("std"); const is_nvptx = builtin.cpu.arch == .nvptx64; const CallingConvention = @import("std").builtin.CallingConvention; const PtxKernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified; const cu = @import("cudaz").cu; // stage2 seems unable to compile math.min, so we roll out our own clamp fn clamp(x: i32, min: i32, max: i32) i32 { if (x < min) return min; if (x >= max) return max - 1; return x; } pub const Mat3 = struct { data: [*]const u8, shape: [3]i32, pub fn getClamped(self: Mat3, x: i32, y: i32, z: i32) u8 { return self.data[self.idxClamped(x, y, z)]; } pub fn idx(self: Mat3, x: i32, y: i32, z: i32) usize { const i = (x * self.shape[1] + y) * self.shape[2] + z; return @intCast(usize, i); } pub fn idxClamped(self: Mat3, x: i32, y: i32, z: i32) usize { return self.idx( clamp(x, 0, self.shape[0]), clamp(y, 0, self.shape[1]), clamp(z, 0, self.shape[2]), ); } }; pub const Mat2Float = struct { data: [*]f32, shape: [2]i32, pub fn getClamped(self: Mat2Float, x: i32, y: i32) f32 { return self.data[self.idxClamped(x, y)]; } pub fn idx(self: Mat2Float, x: i32, y: i32) usize { const i = x * self.shape[1] + y; return @intCast(usize, i); } pub fn idxClamped(self: Mat2Float, x: i32, y: i32) usize { return self.idx( clamp(x, 0, self.shape[0]), clamp(y, 0, self.shape[1]), ); } }; inline fn clampedOffset(x: i32, step: i32, n: i32) i32 { if (step < 0 and -step > x) return 0; const x_step = x + step; if (x_step >= n) return n - 1; return x_step; } pub const GaussianBlurArgs = struct { img: Mat3, filter: []const f32, filter_width: i32, output: [*]u8, }; pub export fn gaussianBlurStruct(args: GaussianBlurArgs) callconv(PtxKernel) void { return gaussianBlurVerbose( args.img.data, args.img.shape[0], args.img.shape[1], args.filter.ptr, args.filter_width, args.output, ); } pub export fn gaussianBlurVerbose( raw_input: [*]const u8, num_cols: i32, num_rows: i32, filter: [*]const f32, filter_width: i32, output: [*]u8, ) callconv(PtxKernel) void { const id = getId_3D(); const input = Mat3{ .data = raw_input, .shape = [_]i32{ num_cols, num_rows, 3 } }; if (id.x >= num_cols or id.y >= num_rows) return; const channel_id = @intCast(usize, input.idx(id.x, id.y, id.z)); const half_width: i32 = filter_width >> 1; var pixel: f32 = 0.0; var r = -half_width; while (r <= half_width) : (r += 1) { var c = -half_width; while (c <= half_width) : (c += 1) { const weight = filter[@intCast(usize, (r + half_width) * filter_width + c + half_width)]; pixel += weight * @intToFloat(f32, input.getClamped(id.x + c, id.y + r, id.z)); } } output[channel_id] = @floatToInt(u8, pixel); } pub export fn gaussianBlur( input: Mat3, filter: Mat2Float, output: []u8, ) callconv(PtxKernel) void { const id = getId_3D(); if (id.x >= input.shape[0] or id.y >= input.shape[1]) return; const channel_id = @intCast(usize, input.idx(id.x, id.y, id.z)); const half_width: i32 = filter.shape[0] >> 1; var pixel: f32 = 0.0; var r = -half_width; while (r <= half_width) : (r += 1) { var c = -half_width; while (c <= half_width) : (c += 1) { const weight = filter.getClamped(r + half_width, c + half_width); pixel += weight * @intToFloat(f32, input.getClamped(id.x + c, id.y + r, id.z)); } } output[channel_id] = @floatToInt(u8, pixel); } /// threadId.x inline fn threadIdX() i32 { if (!is_nvptx) return 0; var tid = asm volatile ("mov.s32 \t$0, %tid.x;" : [ret] "=r" (-> i32), ); return @intCast(i32, tid); } /// threadId.y inline fn threadIdY() i32 { if (!is_nvptx) return 0; var tid = asm volatile ("mov.s32 \t$0, %tid.y;" : [ret] "=r" (-> i32), ); return @intCast(i32, tid); } /// threadId.z inline fn threadIdZ() i32 { if (!is_nvptx) return 0; var tid = asm volatile ("mov.s32 \t$0, %tid.z;" : [ret] "=r" (-> i32), ); return @intCast(i32, tid); } /// threadDim.x inline fn threadDimX() i32 { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.s32 \t$0, %ntid.x;" : [ret] "=r" (-> i32), ); return @intCast(i32, ntid); } /// threadDim.y inline fn threadDimY() i32 { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.s32 \t$0, %ntid.y;" : [ret] "=r" (-> i32), ); return @intCast(i32, ntid); } /// threadDim.z inline fn threadDimZ() i32 { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.s32 \t$0, %ntid.z;" : [ret] "=r" (-> i32), ); return @intCast(i32, ntid); } /// gridId.x inline fn gridIdX() i32 { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.s32 \t$0, %ctaid.x;" : [ret] "=r" (-> i32), ); return @intCast(i32, ctaid); } /// gridId.y inline fn gridIdY() i32 { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.s32 \t$0, %ctaid.y;" : [ret] "=r" (-> i32), ); return @intCast(i32, ctaid); } /// gridId.z inline fn gridIdZ() i32 { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.s32 \t$0, %ctaid.z;" : [ret] "=r" (-> i32), ); return @intCast(i32, ctaid); } /// gridDim.x inline fn gridDimX() i32 { if (!is_nvptx) return 0; var nctaid = asm volatile ("mov.s32 \t$0, %nctaid.x;" : [ret] "=r" (-> i32), ); return @intCast(i32, nctaid); } /// gridDim.y inline fn gridDimY() i32 { if (!is_nvptx) return 0; var nctaid = asm volatile ("mov.s32 \t$0, %nctaid.y;" : [ret] "=r" (-> i32), ); return @intCast(i32, nctaid); } /// gridDim.z inline fn gridDimZ() i32 { if (!is_nvptx) return 0; var nctaid = asm volatile ("mov.s32 \t$0, %nctaid.z;" : [ret] "=r" (-> i32), ); return @intCast(i32, nctaid); } inline fn getId_1D() i32 { return threadIdX() + threadDimX() * gridIdX(); } const Dim2 = struct { x: i32, y: i32 }; pub fn getId_2D() Dim2 { return Dim2{ .x = threadIdX() + threadDimX() * gridIdX(), .y = threadIdY() + threadDimY() * gridIdY(), }; } const Dim3 = struct { x: i32, y: i32, z: i32 }; pub fn getId_3D() Dim3 { return Dim3{ .x = threadIdX() + threadDimX() * gridIdX(), .y = threadIdY() + threadDimY() * gridIdY(), .z = threadIdZ() + threadDimZ() * gridIdZ(), }; }
CS344/src/hw2_pure_kernel.zig
const std = @import("std"); const c_allocator = std.heap.c_allocator; const StringHashMap = std.StringHashMap; // For dynamic files // const GenerateFileError = error{ OutOfMemory, GenericError }; // pub const callback_generate_file = fn (uid: u32, url: []const u8) GenerateFileError![]const u8; // pub const callback_done_with = fn (data: []const u8) void; const FileData = struct { dynamic: bool, mime_type: ?[]const u8, data: union { // if dynamic = false static_data: []const u8, // if dynamic = true // dynamic_file_data: struct { // uid: u32, callback: callback_generate_file, callback_done_with: callback_done_with // } } }; var files_map: StringHashMap(FileData) = undefined; pub fn init() void { files_map = StringHashMap(FileData).init(c_allocator); } // Pointers must remain valid pub fn addStaticFile(url: []const u8, data: []const u8, mime_type: ?[]const u8) !void { _ = try files_map.put(url, FileData{ .dynamic = false, .mime_type = mime_type, .data = .{ .static_data = data }, }); } var uid_counter: u32 = 0; // Pointer must remain valid // Returns unique id that is passed to the callback // pub fn addDynamicFile(url: []const u8, cb_generate_file: callback_generate_file, cb_done_with: callback_done_with) !u32 { // _ = try files_map.put(url, FileData{ // .dynamic = true, // .data = .{ // .dynamic_file_data = .{ // .uid = uid_counter, // .callback = cb_generate_file, // .callback_done_with = cb_done_with, // }, // }, // }); // uid_counter += 1; // return uid_counter - 1; // } // Returns contents of static file at URL pub fn getFile(url: []const u8, mime_type: *(?[]const u8)) ?[]const u8 { const kv = files_map.get(url); if (kv == null) { return null; } // if (kv.?.value.dynamic) { // return kv.?.value.data.dynamic_file_data.callback(kv.?.value.data.dynamic_file_data.uid, url) catch { // return "ERROR"; // }; // } else { // Static file mime_type.* = kv.?.value.mime_type; return kv.?.value.data.static_data; // } // return null; } // pub fn writeDone(data: []const u8) void { // const callback = @intToPtr(callback_done_with); // callback(data); // }
src/Files.zig
const std = @import("std"); const root = @import("root"); /// Queues a build job for the C code of Wasm3. /// This builds a static library that depends on libc, so make sure to link that into your exe! pub fn compile(b: *std.build.Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget, wasm3_root: []const u8) *std.build.LibExeObjStep { const lib = b.addStaticLibrary("wasm3", null); lib.setBuildMode(mode); lib.setTarget(target); lib.linkLibC(); lib.disable_sanitize_c = true; lib.defineCMacro("d_m3HasWASI"); const src_dir = std.fs.path.join(b.allocator, &.{wasm3_root, "source"}) catch unreachable; var src_dir_handle = std.fs.cwd().openDir(src_dir, .{.iterate = true}) catch unreachable; defer src_dir_handle.close(); lib.c_std = .C99; const cflags = [_][]const u8 { "-Wall", "-Wextra", "-Wparentheses", "-Wundef", "-Wpointer-arith", "-Wstrict-aliasing=2", "-Werror=implicit-function-declaration", "-Wno-unused-function", "-Wno-unused-variable", "-Wno-unused-parameter", "-Wno-missing-field-initializers", }; const cflags_with_windows_posix_aliases = cflags ++ [_][]const u8 { "-Dlseek(fd,off,whence)=_lseek(fd,off,whence)", "-Dfileno(stream)=_fileno(stream)", "-Dsetmode(fd,mode)=_setmode(fd,mode)", }; var core_src_file: ?[]const u8 = undefined; var iter = src_dir_handle.iterate(); while(iter.next() catch unreachable) |ent| { if(ent.kind == .File) { if(std.ascii.endsWithIgnoreCase(ent.name, ".c")) { const path = std.fs.path.join(b.allocator, &[_][]const u8{src_dir, ent.name}) catch unreachable; if(std.ascii.eqlIgnoreCase(ent.name, "m3_core.c")) { core_src_file = path; continue; } if( target.isWindows() and std.ascii.eqlIgnoreCase(ent.name, "m3_api_wasi.c") ) { lib.addCSourceFile(path, &cflags_with_windows_posix_aliases); } else { lib.addCSourceFile(path, &cflags); } } } } std.debug.assert(core_src_file != null); { // Patch source files. // wasm3 has a built-in limit for what it thinks should be the maximum sane length for a utf-8 string // It's 2000 characters, which seems reasonable enough. // // Here's the thing - C++ is not reasonable. // libc++'s rtti symbols exceed four-freakin'-thousand characters sometimes. // In order to support compiled C++ programs, we patch this value. // // It's kind of ugly, but it works! var build_root_handle = std.fs.cwd().openDir(wasm3_root, .{}) catch unreachable; defer build_root_handle.close(); std.fs.cwd().copyFile(core_src_file.?, build_root_handle, "m3_core.c", .{}) catch unreachable; lib.addCSourceFile(std.fs.path.join(b.allocator, &[_][]const u8{wasm3_root, "m3_core.c"}) catch unreachable, &cflags); build_root_handle.writeFile("m3_core.h", "#include <m3_core.h>\n" ++ "#undef d_m3MaxSaneUtf8Length\n" ++ "#define d_m3MaxSaneUtf8Length 10000\n") catch unreachable; } lib.addIncludeDir(src_dir); lib.addCSourceFile(std.fs.path.join(b.allocator, &[_][]const u8{ std.fs.path.dirname(@src().file).?, "src", "wasm3_extra.c" }) catch unreachable, &cflags); return lib; } /// Compiles Wasm3 and links it into the provided exe. /// If you use this API, you do not need to also use the compile() function. pub fn addTo(exe: *std.build.LibExeObjStep, wasm3_root: []const u8) void { var lib = compile(exe.builder, exe.build_mode, exe.target, wasm3_root); exe.linkLibC(); exe.linkLibrary(lib); } var file_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; pub fn pkg(name: ?[]const u8) std.build.Pkg { var fba = std.heap.FixedBufferAllocator.init(&file_buf); return .{ .name = name orelse "wasm3", .path = std.fs.path.join(&fba.allocator, &[_][]const u8{std.fs.path.dirname(@src().file).?, "src", "main.zig"}) catch unreachable, }; }
submod_build_plugin.zig
pub fn isBasicLatin(cp: u21) bool { if (cp < 0x0 or cp > 0x7f) return false; return switch (cp) { 0x0...0x7f => true, else => false, }; } pub fn isLatin1Supplement(cp: u21) bool { if (cp < 0x80 or cp > 0xff) return false; return switch (cp) { 0x80...0xff => true, else => false, }; } pub fn isLatinExtendedA(cp: u21) bool { if (cp < 0x100 or cp > 0x17f) return false; return switch (cp) { 0x100...0x17f => true, else => false, }; } pub fn isLatinExtendedB(cp: u21) bool { if (cp < 0x180 or cp > 0x24f) return false; return switch (cp) { 0x180...0x24f => true, else => false, }; } pub fn isIpaExtensions(cp: u21) bool { if (cp < 0x250 or cp > 0x2af) return false; return switch (cp) { 0x250...0x2af => true, else => false, }; } pub fn isSpacingModifierLetters(cp: u21) bool { if (cp < 0x2b0 or cp > 0x2ff) return false; return switch (cp) { 0x2b0...0x2ff => true, else => false, }; } pub fn isCombiningDiacriticalMarks(cp: u21) bool { if (cp < 0x300 or cp > 0x36f) return false; return switch (cp) { 0x300...0x36f => true, else => false, }; } pub fn isGreekAndCoptic(cp: u21) bool { if (cp < 0x370 or cp > 0x3ff) return false; return switch (cp) { 0x370...0x3ff => true, else => false, }; } pub fn isCyrillic(cp: u21) bool { if (cp < 0x400 or cp > 0x4ff) return false; return switch (cp) { 0x400...0x4ff => true, else => false, }; } pub fn isCyrillicSupplement(cp: u21) bool { if (cp < 0x500 or cp > 0x52f) return false; return switch (cp) { 0x500...0x52f => true, else => false, }; } pub fn isArmenian(cp: u21) bool { if (cp < 0x530 or cp > 0x58f) return false; return switch (cp) { 0x530...0x58f => true, else => false, }; } pub fn isHebrew(cp: u21) bool { if (cp < 0x590 or cp > 0x5ff) return false; return switch (cp) { 0x590...0x5ff => true, else => false, }; } pub fn isArabic(cp: u21) bool { if (cp < 0x600 or cp > 0x6ff) return false; return switch (cp) { 0x600...0x6ff => true, else => false, }; } pub fn isSyriac(cp: u21) bool { if (cp < 0x700 or cp > 0x74f) return false; return switch (cp) { 0x700...0x74f => true, else => false, }; } pub fn isArabicSupplement(cp: u21) bool { if (cp < 0x750 or cp > 0x77f) return false; return switch (cp) { 0x750...0x77f => true, else => false, }; } pub fn isThaana(cp: u21) bool { if (cp < 0x780 or cp > 0x7bf) return false; return switch (cp) { 0x780...0x7bf => true, else => false, }; } pub fn isNko(cp: u21) bool { if (cp < 0x7c0 or cp > 0x7ff) return false; return switch (cp) { 0x7c0...0x7ff => true, else => false, }; } pub fn isSamaritan(cp: u21) bool { if (cp < 0x800 or cp > 0x83f) return false; return switch (cp) { 0x800...0x83f => true, else => false, }; } pub fn isMandaic(cp: u21) bool { if (cp < 0x840 or cp > 0x85f) return false; return switch (cp) { 0x840...0x85f => true, else => false, }; } pub fn isSyriacSupplement(cp: u21) bool { if (cp < 0x860 or cp > 0x86f) return false; return switch (cp) { 0x860...0x86f => true, else => false, }; } pub fn isArabicExtendedB(cp: u21) bool { if (cp < 0x870 or cp > 0x89f) return false; return switch (cp) { 0x870...0x89f => true, else => false, }; } pub fn isArabicExtendedA(cp: u21) bool { if (cp < 0x8a0 or cp > 0x8ff) return false; return switch (cp) { 0x8a0...0x8ff => true, else => false, }; } pub fn isDevanagari(cp: u21) bool { if (cp < 0x900 or cp > 0x97f) return false; return switch (cp) { 0x900...0x97f => true, else => false, }; } pub fn isBengali(cp: u21) bool { if (cp < 0x980 or cp > 0x9ff) return false; return switch (cp) { 0x980...0x9ff => true, else => false, }; } pub fn isGurmukhi(cp: u21) bool { if (cp < 0xa00 or cp > 0xa7f) return false; return switch (cp) { 0xa00...0xa7f => true, else => false, }; } pub fn isGujarati(cp: u21) bool { if (cp < 0xa80 or cp > 0xaff) return false; return switch (cp) { 0xa80...0xaff => true, else => false, }; } pub fn isOriya(cp: u21) bool { if (cp < 0xb00 or cp > 0xb7f) return false; return switch (cp) { 0xb00...0xb7f => true, else => false, }; } pub fn isTamil(cp: u21) bool { if (cp < 0xb80 or cp > 0xbff) return false; return switch (cp) { 0xb80...0xbff => true, else => false, }; } pub fn isTelugu(cp: u21) bool { if (cp < 0xc00 or cp > 0xc7f) return false; return switch (cp) { 0xc00...0xc7f => true, else => false, }; } pub fn isKannada(cp: u21) bool { if (cp < 0xc80 or cp > 0xcff) return false; return switch (cp) { 0xc80...0xcff => true, else => false, }; } pub fn isMalayalam(cp: u21) bool { if (cp < 0xd00 or cp > 0xd7f) return false; return switch (cp) { 0xd00...0xd7f => true, else => false, }; } pub fn isSinhala(cp: u21) bool { if (cp < 0xd80 or cp > 0xdff) return false; return switch (cp) { 0xd80...0xdff => true, else => false, }; } pub fn isThai(cp: u21) bool { if (cp < 0xe00 or cp > 0xe7f) return false; return switch (cp) { 0xe00...0xe7f => true, else => false, }; } pub fn isLao(cp: u21) bool { if (cp < 0xe80 or cp > 0xeff) return false; return switch (cp) { 0xe80...0xeff => true, else => false, }; } pub fn isTibetan(cp: u21) bool { if (cp < 0xf00 or cp > 0xfff) return false; return switch (cp) { 0xf00...0xfff => true, else => false, }; } pub fn isMyanmar(cp: u21) bool { if (cp < 0x1000 or cp > 0x109f) return false; return switch (cp) { 0x1000...0x109f => true, else => false, }; } pub fn isGeorgian(cp: u21) bool { if (cp < 0x10a0 or cp > 0x10ff) return false; return switch (cp) { 0x10a0...0x10ff => true, else => false, }; } pub fn isHangulJamo(cp: u21) bool { if (cp < 0x1100 or cp > 0x11ff) return false; return switch (cp) { 0x1100...0x11ff => true, else => false, }; } pub fn isEthiopic(cp: u21) bool { if (cp < 0x1200 or cp > 0x137f) return false; return switch (cp) { 0x1200...0x137f => true, else => false, }; } pub fn isEthiopicSupplement(cp: u21) bool { if (cp < 0x1380 or cp > 0x139f) return false; return switch (cp) { 0x1380...0x139f => true, else => false, }; } pub fn isCherokee(cp: u21) bool { if (cp < 0x13a0 or cp > 0x13ff) return false; return switch (cp) { 0x13a0...0x13ff => true, else => false, }; } pub fn isUnifiedCanadianAboriginalSyllabics(cp: u21) bool { if (cp < 0x1400 or cp > 0x167f) return false; return switch (cp) { 0x1400...0x167f => true, else => false, }; } pub fn isOgham(cp: u21) bool { if (cp < 0x1680 or cp > 0x169f) return false; return switch (cp) { 0x1680...0x169f => true, else => false, }; } pub fn isRunic(cp: u21) bool { if (cp < 0x16a0 or cp > 0x16ff) return false; return switch (cp) { 0x16a0...0x16ff => true, else => false, }; } pub fn isTagalog(cp: u21) bool { if (cp < 0x1700 or cp > 0x171f) return false; return switch (cp) { 0x1700...0x171f => true, else => false, }; } pub fn isHanunoo(cp: u21) bool { if (cp < 0x1720 or cp > 0x173f) return false; return switch (cp) { 0x1720...0x173f => true, else => false, }; } pub fn isBuhid(cp: u21) bool { if (cp < 0x1740 or cp > 0x175f) return false; return switch (cp) { 0x1740...0x175f => true, else => false, }; } pub fn isTagbanwa(cp: u21) bool { if (cp < 0x1760 or cp > 0x177f) return false; return switch (cp) { 0x1760...0x177f => true, else => false, }; } pub fn isKhmer(cp: u21) bool { if (cp < 0x1780 or cp > 0x17ff) return false; return switch (cp) { 0x1780...0x17ff => true, else => false, }; } pub fn isMongolian(cp: u21) bool { if (cp < 0x1800 or cp > 0x18af) return false; return switch (cp) { 0x1800...0x18af => true, else => false, }; } pub fn isUnifiedCanadianAboriginalSyllabicsExtended(cp: u21) bool { if (cp < 0x18b0 or cp > 0x18ff) return false; return switch (cp) { 0x18b0...0x18ff => true, else => false, }; } pub fn isLimbu(cp: u21) bool { if (cp < 0x1900 or cp > 0x194f) return false; return switch (cp) { 0x1900...0x194f => true, else => false, }; } pub fn isTaiLe(cp: u21) bool { if (cp < 0x1950 or cp > 0x197f) return false; return switch (cp) { 0x1950...0x197f => true, else => false, }; } pub fn isNewTaiLue(cp: u21) bool { if (cp < 0x1980 or cp > 0x19df) return false; return switch (cp) { 0x1980...0x19df => true, else => false, }; } pub fn isKhmerSymbols(cp: u21) bool { if (cp < 0x19e0 or cp > 0x19ff) return false; return switch (cp) { 0x19e0...0x19ff => true, else => false, }; } pub fn isBuginese(cp: u21) bool { if (cp < 0x1a00 or cp > 0x1a1f) return false; return switch (cp) { 0x1a00...0x1a1f => true, else => false, }; } pub fn isTaiTham(cp: u21) bool { if (cp < 0x1a20 or cp > 0x1aaf) return false; return switch (cp) { 0x1a20...0x1aaf => true, else => false, }; } pub fn isCombiningDiacriticalMarksExtended(cp: u21) bool { if (cp < 0x1ab0 or cp > 0x1aff) return false; return switch (cp) { 0x1ab0...0x1aff => true, else => false, }; } pub fn isBalinese(cp: u21) bool { if (cp < 0x1b00 or cp > 0x1b7f) return false; return switch (cp) { 0x1b00...0x1b7f => true, else => false, }; } pub fn isSundanese(cp: u21) bool { if (cp < 0x1b80 or cp > 0x1bbf) return false; return switch (cp) { 0x1b80...0x1bbf => true, else => false, }; } pub fn isBatak(cp: u21) bool { if (cp < 0x1bc0 or cp > 0x1bff) return false; return switch (cp) { 0x1bc0...0x1bff => true, else => false, }; } pub fn isLepcha(cp: u21) bool { if (cp < 0x1c00 or cp > 0x1c4f) return false; return switch (cp) { 0x1c00...0x1c4f => true, else => false, }; } pub fn isOlChiki(cp: u21) bool { if (cp < 0x1c50 or cp > 0x1c7f) return false; return switch (cp) { 0x1c50...0x1c7f => true, else => false, }; } pub fn isCyrillicExtendedC(cp: u21) bool { if (cp < 0x1c80 or cp > 0x1c8f) return false; return switch (cp) { 0x1c80...0x1c8f => true, else => false, }; } pub fn isGeorgianExtended(cp: u21) bool { if (cp < 0x1c90 or cp > 0x1cbf) return false; return switch (cp) { 0x1c90...0x1cbf => true, else => false, }; } pub fn isSundaneseSupplement(cp: u21) bool { if (cp < 0x1cc0 or cp > 0x1ccf) return false; return switch (cp) { 0x1cc0...0x1ccf => true, else => false, }; } pub fn isVedicExtensions(cp: u21) bool { if (cp < 0x1cd0 or cp > 0x1cff) return false; return switch (cp) { 0x1cd0...0x1cff => true, else => false, }; } pub fn isPhoneticExtensions(cp: u21) bool { if (cp < 0x1d00 or cp > 0x1d7f) return false; return switch (cp) { 0x1d00...0x1d7f => true, else => false, }; } pub fn isPhoneticExtensionsSupplement(cp: u21) bool { if (cp < 0x1d80 or cp > 0x1dbf) return false; return switch (cp) { 0x1d80...0x1dbf => true, else => false, }; } pub fn isCombiningDiacriticalMarksSupplement(cp: u21) bool { if (cp < 0x1dc0 or cp > 0x1dff) return false; return switch (cp) { 0x1dc0...0x1dff => true, else => false, }; } pub fn isLatinExtendedAdditional(cp: u21) bool { if (cp < 0x1e00 or cp > 0x1eff) return false; return switch (cp) { 0x1e00...0x1eff => true, else => false, }; } pub fn isGreekExtended(cp: u21) bool { if (cp < 0x1f00 or cp > 0x1fff) return false; return switch (cp) { 0x1f00...0x1fff => true, else => false, }; } pub fn isGeneralPunctuation(cp: u21) bool { if (cp < 0x2000 or cp > 0x206f) return false; return switch (cp) { 0x2000...0x206f => true, else => false, }; } pub fn isSuperscriptsAndSubscripts(cp: u21) bool { if (cp < 0x2070 or cp > 0x209f) return false; return switch (cp) { 0x2070...0x209f => true, else => false, }; } pub fn isCurrencySymbols(cp: u21) bool { if (cp < 0x20a0 or cp > 0x20cf) return false; return switch (cp) { 0x20a0...0x20cf => true, else => false, }; } pub fn isCombiningDiacriticalMarksForSymbols(cp: u21) bool { if (cp < 0x20d0 or cp > 0x20ff) return false; return switch (cp) { 0x20d0...0x20ff => true, else => false, }; } pub fn isLetterlikeSymbols(cp: u21) bool { if (cp < 0x2100 or cp > 0x214f) return false; return switch (cp) { 0x2100...0x214f => true, else => false, }; } pub fn isNumberForms(cp: u21) bool { if (cp < 0x2150 or cp > 0x218f) return false; return switch (cp) { 0x2150...0x218f => true, else => false, }; } pub fn isArrows(cp: u21) bool { if (cp < 0x2190 or cp > 0x21ff) return false; return switch (cp) { 0x2190...0x21ff => true, else => false, }; } pub fn isMathematicalOperators(cp: u21) bool { if (cp < 0x2200 or cp > 0x22ff) return false; return switch (cp) { 0x2200...0x22ff => true, else => false, }; } pub fn isMiscellaneousTechnical(cp: u21) bool { if (cp < 0x2300 or cp > 0x23ff) return false; return switch (cp) { 0x2300...0x23ff => true, else => false, }; } pub fn isControlPictures(cp: u21) bool { if (cp < 0x2400 or cp > 0x243f) return false; return switch (cp) { 0x2400...0x243f => true, else => false, }; } pub fn isOpticalCharacterRecognition(cp: u21) bool { if (cp < 0x2440 or cp > 0x245f) return false; return switch (cp) { 0x2440...0x245f => true, else => false, }; } pub fn isEnclosedAlphanumerics(cp: u21) bool { if (cp < 0x2460 or cp > 0x24ff) return false; return switch (cp) { 0x2460...0x24ff => true, else => false, }; } pub fn isBoxDrawing(cp: u21) bool { if (cp < 0x2500 or cp > 0x257f) return false; return switch (cp) { 0x2500...0x257f => true, else => false, }; } pub fn isBlockElements(cp: u21) bool { if (cp < 0x2580 or cp > 0x259f) return false; return switch (cp) { 0x2580...0x259f => true, else => false, }; } pub fn isGeometricShapes(cp: u21) bool { if (cp < 0x25a0 or cp > 0x25ff) return false; return switch (cp) { 0x25a0...0x25ff => true, else => false, }; } pub fn isMiscellaneousSymbols(cp: u21) bool { if (cp < 0x2600 or cp > 0x26ff) return false; return switch (cp) { 0x2600...0x26ff => true, else => false, }; } pub fn isDingbats(cp: u21) bool { if (cp < 0x2700 or cp > 0x27bf) return false; return switch (cp) { 0x2700...0x27bf => true, else => false, }; } pub fn isMiscellaneousMathematicalSymbolsA(cp: u21) bool { if (cp < 0x27c0 or cp > 0x27ef) return false; return switch (cp) { 0x27c0...0x27ef => true, else => false, }; } pub fn isSupplementalArrowsA(cp: u21) bool { if (cp < 0x27f0 or cp > 0x27ff) return false; return switch (cp) { 0x27f0...0x27ff => true, else => false, }; } pub fn isBraillePatterns(cp: u21) bool { if (cp < 0x2800 or cp > 0x28ff) return false; return switch (cp) { 0x2800...0x28ff => true, else => false, }; } pub fn isSupplementalArrowsB(cp: u21) bool { if (cp < 0x2900 or cp > 0x297f) return false; return switch (cp) { 0x2900...0x297f => true, else => false, }; } pub fn isMiscellaneousMathematicalSymbolsB(cp: u21) bool { if (cp < 0x2980 or cp > 0x29ff) return false; return switch (cp) { 0x2980...0x29ff => true, else => false, }; } pub fn isSupplementalMathematicalOperators(cp: u21) bool { if (cp < 0x2a00 or cp > 0x2aff) return false; return switch (cp) { 0x2a00...0x2aff => true, else => false, }; } pub fn isMiscellaneousSymbolsAndArrows(cp: u21) bool { if (cp < 0x2b00 or cp > 0x2bff) return false; return switch (cp) { 0x2b00...0x2bff => true, else => false, }; } pub fn isGlagolitic(cp: u21) bool { if (cp < 0x2c00 or cp > 0x2c5f) return false; return switch (cp) { 0x2c00...0x2c5f => true, else => false, }; } pub fn isLatinExtendedC(cp: u21) bool { if (cp < 0x2c60 or cp > 0x2c7f) return false; return switch (cp) { 0x2c60...0x2c7f => true, else => false, }; } pub fn isCoptic(cp: u21) bool { if (cp < 0x2c80 or cp > 0x2cff) return false; return switch (cp) { 0x2c80...0x2cff => true, else => false, }; } pub fn isGeorgianSupplement(cp: u21) bool { if (cp < 0x2d00 or cp > 0x2d2f) return false; return switch (cp) { 0x2d00...0x2d2f => true, else => false, }; } pub fn isTifinagh(cp: u21) bool { if (cp < 0x2d30 or cp > 0x2d7f) return false; return switch (cp) { 0x2d30...0x2d7f => true, else => false, }; } pub fn isEthiopicExtended(cp: u21) bool { if (cp < 0x2d80 or cp > 0x2ddf) return false; return switch (cp) { 0x2d80...0x2ddf => true, else => false, }; } pub fn isCyrillicExtendedA(cp: u21) bool { if (cp < 0x2de0 or cp > 0x2dff) return false; return switch (cp) { 0x2de0...0x2dff => true, else => false, }; } pub fn isSupplementalPunctuation(cp: u21) bool { if (cp < 0x2e00 or cp > 0x2e7f) return false; return switch (cp) { 0x2e00...0x2e7f => true, else => false, }; } pub fn isCjkRadicalsSupplement(cp: u21) bool { if (cp < 0x2e80 or cp > 0x2eff) return false; return switch (cp) { 0x2e80...0x2eff => true, else => false, }; } pub fn isKangxiRadicals(cp: u21) bool { if (cp < 0x2f00 or cp > 0x2fdf) return false; return switch (cp) { 0x2f00...0x2fdf => true, else => false, }; } pub fn isIdeographicDescriptionCharacters(cp: u21) bool { if (cp < 0x2ff0 or cp > 0x2fff) return false; return switch (cp) { 0x2ff0...0x2fff => true, else => false, }; } pub fn isCjkSymbolsAndPunctuation(cp: u21) bool { if (cp < 0x3000 or cp > 0x303f) return false; return switch (cp) { 0x3000...0x303f => true, else => false, }; } pub fn isHiragana(cp: u21) bool { if (cp < 0x3040 or cp > 0x309f) return false; return switch (cp) { 0x3040...0x309f => true, else => false, }; } pub fn isKatakana(cp: u21) bool { if (cp < 0x30a0 or cp > 0x30ff) return false; return switch (cp) { 0x30a0...0x30ff => true, else => false, }; } pub fn isBopomofo(cp: u21) bool { if (cp < 0x3100 or cp > 0x312f) return false; return switch (cp) { 0x3100...0x312f => true, else => false, }; } pub fn isHangulCompatibilityJamo(cp: u21) bool { if (cp < 0x3130 or cp > 0x318f) return false; return switch (cp) { 0x3130...0x318f => true, else => false, }; } pub fn isKanbun(cp: u21) bool { if (cp < 0x3190 or cp > 0x319f) return false; return switch (cp) { 0x3190...0x319f => true, else => false, }; } pub fn isBopomofoExtended(cp: u21) bool { if (cp < 0x31a0 or cp > 0x31bf) return false; return switch (cp) { 0x31a0...0x31bf => true, else => false, }; } pub fn isCjkStrokes(cp: u21) bool { if (cp < 0x31c0 or cp > 0x31ef) return false; return switch (cp) { 0x31c0...0x31ef => true, else => false, }; } pub fn isKatakanaPhoneticExtensions(cp: u21) bool { if (cp < 0x31f0 or cp > 0x31ff) return false; return switch (cp) { 0x31f0...0x31ff => true, else => false, }; } pub fn isEnclosedCjkLettersAndMonths(cp: u21) bool { if (cp < 0x3200 or cp > 0x32ff) return false; return switch (cp) { 0x3200...0x32ff => true, else => false, }; } pub fn isCjkCompatibility(cp: u21) bool { if (cp < 0x3300 or cp > 0x33ff) return false; return switch (cp) { 0x3300...0x33ff => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionA(cp: u21) bool { if (cp < 0x3400 or cp > 0x4dbf) return false; return switch (cp) { 0x3400...0x4dbf => true, else => false, }; } pub fn isYijingHexagramSymbols(cp: u21) bool { if (cp < 0x4dc0 or cp > 0x4dff) return false; return switch (cp) { 0x4dc0...0x4dff => true, else => false, }; } pub fn isCjkUnifiedIdeographs(cp: u21) bool { if (cp < 0x4e00 or cp > 0x9fff) return false; return switch (cp) { 0x4e00...0x9fff => true, else => false, }; } pub fn isYiSyllables(cp: u21) bool { if (cp < 0xa000 or cp > 0xa48f) return false; return switch (cp) { 0xa000...0xa48f => true, else => false, }; } pub fn isYiRadicals(cp: u21) bool { if (cp < 0xa490 or cp > 0xa4cf) return false; return switch (cp) { 0xa490...0xa4cf => true, else => false, }; } pub fn isLisu(cp: u21) bool { if (cp < 0xa4d0 or cp > 0xa4ff) return false; return switch (cp) { 0xa4d0...0xa4ff => true, else => false, }; } pub fn isVai(cp: u21) bool { if (cp < 0xa500 or cp > 0xa63f) return false; return switch (cp) { 0xa500...0xa63f => true, else => false, }; } pub fn isCyrillicExtendedB(cp: u21) bool { if (cp < 0xa640 or cp > 0xa69f) return false; return switch (cp) { 0xa640...0xa69f => true, else => false, }; } pub fn isBamum(cp: u21) bool { if (cp < 0xa6a0 or cp > 0xa6ff) return false; return switch (cp) { 0xa6a0...0xa6ff => true, else => false, }; } pub fn isModifierToneLetters(cp: u21) bool { if (cp < 0xa700 or cp > 0xa71f) return false; return switch (cp) { 0xa700...0xa71f => true, else => false, }; } pub fn isLatinExtendedD(cp: u21) bool { if (cp < 0xa720 or cp > 0xa7ff) return false; return switch (cp) { 0xa720...0xa7ff => true, else => false, }; } pub fn isSylotiNagri(cp: u21) bool { if (cp < 0xa800 or cp > 0xa82f) return false; return switch (cp) { 0xa800...0xa82f => true, else => false, }; } pub fn isCommonIndicNumberForms(cp: u21) bool { if (cp < 0xa830 or cp > 0xa83f) return false; return switch (cp) { 0xa830...0xa83f => true, else => false, }; } pub fn isPhagsPa(cp: u21) bool { if (cp < 0xa840 or cp > 0xa87f) return false; return switch (cp) { 0xa840...0xa87f => true, else => false, }; } pub fn isSaurashtra(cp: u21) bool { if (cp < 0xa880 or cp > 0xa8df) return false; return switch (cp) { 0xa880...0xa8df => true, else => false, }; } pub fn isDevanagariExtended(cp: u21) bool { if (cp < 0xa8e0 or cp > 0xa8ff) return false; return switch (cp) { 0xa8e0...0xa8ff => true, else => false, }; } pub fn isKayahLi(cp: u21) bool { if (cp < 0xa900 or cp > 0xa92f) return false; return switch (cp) { 0xa900...0xa92f => true, else => false, }; } pub fn isRejang(cp: u21) bool { if (cp < 0xa930 or cp > 0xa95f) return false; return switch (cp) { 0xa930...0xa95f => true, else => false, }; } pub fn isHangulJamoExtendedA(cp: u21) bool { if (cp < 0xa960 or cp > 0xa97f) return false; return switch (cp) { 0xa960...0xa97f => true, else => false, }; } pub fn isJavanese(cp: u21) bool { if (cp < 0xa980 or cp > 0xa9df) return false; return switch (cp) { 0xa980...0xa9df => true, else => false, }; } pub fn isMyanmarExtendedB(cp: u21) bool { if (cp < 0xa9e0 or cp > 0xa9ff) return false; return switch (cp) { 0xa9e0...0xa9ff => true, else => false, }; } pub fn isCham(cp: u21) bool { if (cp < 0xaa00 or cp > 0xaa5f) return false; return switch (cp) { 0xaa00...0xaa5f => true, else => false, }; } pub fn isMyanmarExtendedA(cp: u21) bool { if (cp < 0xaa60 or cp > 0xaa7f) return false; return switch (cp) { 0xaa60...0xaa7f => true, else => false, }; } pub fn isTaiViet(cp: u21) bool { if (cp < 0xaa80 or cp > 0xaadf) return false; return switch (cp) { 0xaa80...0xaadf => true, else => false, }; } pub fn isMeeteiMayekExtensions(cp: u21) bool { if (cp < 0xaae0 or cp > 0xaaff) return false; return switch (cp) { 0xaae0...0xaaff => true, else => false, }; } pub fn isEthiopicExtendedA(cp: u21) bool { if (cp < 0xab00 or cp > 0xab2f) return false; return switch (cp) { 0xab00...0xab2f => true, else => false, }; } pub fn isLatinExtendedE(cp: u21) bool { if (cp < 0xab30 or cp > 0xab6f) return false; return switch (cp) { 0xab30...0xab6f => true, else => false, }; } pub fn isCherokeeSupplement(cp: u21) bool { if (cp < 0xab70 or cp > 0xabbf) return false; return switch (cp) { 0xab70...0xabbf => true, else => false, }; } pub fn isMeeteiMayek(cp: u21) bool { if (cp < 0xabc0 or cp > 0xabff) return false; return switch (cp) { 0xabc0...0xabff => true, else => false, }; } pub fn isHangulSyllables(cp: u21) bool { if (cp < 0xac00 or cp > 0xd7af) return false; return switch (cp) { 0xac00...0xd7af => true, else => false, }; } pub fn isHangulJamoExtendedB(cp: u21) bool { if (cp < 0xd7b0 or cp > 0xd7ff) return false; return switch (cp) { 0xd7b0...0xd7ff => true, else => false, }; } pub fn isHighSurrogates(cp: u21) bool { if (cp < 0xd800 or cp > 0xdb7f) return false; return switch (cp) { 0xd800...0xdb7f => true, else => false, }; } pub fn isHighPrivateUseSurrogates(cp: u21) bool { if (cp < 0xdb80 or cp > 0xdbff) return false; return switch (cp) { 0xdb80...0xdbff => true, else => false, }; } pub fn isLowSurrogates(cp: u21) bool { if (cp < 0xdc00 or cp > 0xdfff) return false; return switch (cp) { 0xdc00...0xdfff => true, else => false, }; } pub fn isPrivateUseArea(cp: u21) bool { if (cp < 0xe000 or cp > 0xf8ff) return false; return switch (cp) { 0xe000...0xf8ff => true, else => false, }; } pub fn isCjkCompatibilityIdeographs(cp: u21) bool { if (cp < 0xf900 or cp > 0xfaff) return false; return switch (cp) { 0xf900...0xfaff => true, else => false, }; } pub fn isAlphabeticPresentationForms(cp: u21) bool { if (cp < 0xfb00 or cp > 0xfb4f) return false; return switch (cp) { 0xfb00...0xfb4f => true, else => false, }; } pub fn isArabicPresentationFormsA(cp: u21) bool { if (cp < 0xfb50 or cp > 0xfdff) return false; return switch (cp) { 0xfb50...0xfdff => true, else => false, }; } pub fn isVariationSelectors(cp: u21) bool { if (cp < 0xfe00 or cp > 0xfe0f) return false; return switch (cp) { 0xfe00...0xfe0f => true, else => false, }; } pub fn isVerticalForms(cp: u21) bool { if (cp < 0xfe10 or cp > 0xfe1f) return false; return switch (cp) { 0xfe10...0xfe1f => true, else => false, }; } pub fn isCombiningHalfMarks(cp: u21) bool { if (cp < 0xfe20 or cp > 0xfe2f) return false; return switch (cp) { 0xfe20...0xfe2f => true, else => false, }; } pub fn isCjkCompatibilityForms(cp: u21) bool { if (cp < 0xfe30 or cp > 0xfe4f) return false; return switch (cp) { 0xfe30...0xfe4f => true, else => false, }; } pub fn isSmallFormVariants(cp: u21) bool { if (cp < 0xfe50 or cp > 0xfe6f) return false; return switch (cp) { 0xfe50...0xfe6f => true, else => false, }; } pub fn isArabicPresentationFormsB(cp: u21) bool { if (cp < 0xfe70 or cp > 0xfeff) return false; return switch (cp) { 0xfe70...0xfeff => true, else => false, }; } pub fn isHalfwidthAndFullwidthForms(cp: u21) bool { if (cp < 0xff00 or cp > 0xffef) return false; return switch (cp) { 0xff00...0xffef => true, else => false, }; } pub fn isSpecials(cp: u21) bool { if (cp < 0xfff0 or cp > 0xffff) return false; return switch (cp) { 0xfff0...0xffff => true, else => false, }; } pub fn isLinearBSyllabary(cp: u21) bool { if (cp < 0x10000 or cp > 0x1007f) return false; return switch (cp) { 0x10000...0x1007f => true, else => false, }; } pub fn isLinearBIdeograms(cp: u21) bool { if (cp < 0x10080 or cp > 0x100ff) return false; return switch (cp) { 0x10080...0x100ff => true, else => false, }; } pub fn isAegeanNumbers(cp: u21) bool { if (cp < 0x10100 or cp > 0x1013f) return false; return switch (cp) { 0x10100...0x1013f => true, else => false, }; } pub fn isAncientGreekNumbers(cp: u21) bool { if (cp < 0x10140 or cp > 0x1018f) return false; return switch (cp) { 0x10140...0x1018f => true, else => false, }; } pub fn isAncientSymbols(cp: u21) bool { if (cp < 0x10190 or cp > 0x101cf) return false; return switch (cp) { 0x10190...0x101cf => true, else => false, }; } pub fn isPhaistosDisc(cp: u21) bool { if (cp < 0x101d0 or cp > 0x101ff) return false; return switch (cp) { 0x101d0...0x101ff => true, else => false, }; } pub fn isLycian(cp: u21) bool { if (cp < 0x10280 or cp > 0x1029f) return false; return switch (cp) { 0x10280...0x1029f => true, else => false, }; } pub fn isCarian(cp: u21) bool { if (cp < 0x102a0 or cp > 0x102df) return false; return switch (cp) { 0x102a0...0x102df => true, else => false, }; } pub fn isCopticEpactNumbers(cp: u21) bool { if (cp < 0x102e0 or cp > 0x102ff) return false; return switch (cp) { 0x102e0...0x102ff => true, else => false, }; } pub fn isOldItalic(cp: u21) bool { if (cp < 0x10300 or cp > 0x1032f) return false; return switch (cp) { 0x10300...0x1032f => true, else => false, }; } pub fn isGothic(cp: u21) bool { if (cp < 0x10330 or cp > 0x1034f) return false; return switch (cp) { 0x10330...0x1034f => true, else => false, }; } pub fn isOldPermic(cp: u21) bool { if (cp < 0x10350 or cp > 0x1037f) return false; return switch (cp) { 0x10350...0x1037f => true, else => false, }; } pub fn isUgaritic(cp: u21) bool { if (cp < 0x10380 or cp > 0x1039f) return false; return switch (cp) { 0x10380...0x1039f => true, else => false, }; } pub fn isOldPersian(cp: u21) bool { if (cp < 0x103a0 or cp > 0x103df) return false; return switch (cp) { 0x103a0...0x103df => true, else => false, }; } pub fn isDeseret(cp: u21) bool { if (cp < 0x10400 or cp > 0x1044f) return false; return switch (cp) { 0x10400...0x1044f => true, else => false, }; } pub fn isShavian(cp: u21) bool { if (cp < 0x10450 or cp > 0x1047f) return false; return switch (cp) { 0x10450...0x1047f => true, else => false, }; } pub fn isOsmanya(cp: u21) bool { if (cp < 0x10480 or cp > 0x104af) return false; return switch (cp) { 0x10480...0x104af => true, else => false, }; } pub fn isOsage(cp: u21) bool { if (cp < 0x104b0 or cp > 0x104ff) return false; return switch (cp) { 0x104b0...0x104ff => true, else => false, }; } pub fn isElbasan(cp: u21) bool { if (cp < 0x10500 or cp > 0x1052f) return false; return switch (cp) { 0x10500...0x1052f => true, else => false, }; } pub fn isCaucasianAlbanian(cp: u21) bool { if (cp < 0x10530 or cp > 0x1056f) return false; return switch (cp) { 0x10530...0x1056f => true, else => false, }; } pub fn isVithkuqi(cp: u21) bool { if (cp < 0x10570 or cp > 0x105bf) return false; return switch (cp) { 0x10570...0x105bf => true, else => false, }; } pub fn isLinearA(cp: u21) bool { if (cp < 0x10600 or cp > 0x1077f) return false; return switch (cp) { 0x10600...0x1077f => true, else => false, }; } pub fn isLatinExtendedF(cp: u21) bool { if (cp < 0x10780 or cp > 0x107bf) return false; return switch (cp) { 0x10780...0x107bf => true, else => false, }; } pub fn isCypriotSyllabary(cp: u21) bool { if (cp < 0x10800 or cp > 0x1083f) return false; return switch (cp) { 0x10800...0x1083f => true, else => false, }; } pub fn isImperialAramaic(cp: u21) bool { if (cp < 0x10840 or cp > 0x1085f) return false; return switch (cp) { 0x10840...0x1085f => true, else => false, }; } pub fn isPalmyrene(cp: u21) bool { if (cp < 0x10860 or cp > 0x1087f) return false; return switch (cp) { 0x10860...0x1087f => true, else => false, }; } pub fn isNabataean(cp: u21) bool { if (cp < 0x10880 or cp > 0x108af) return false; return switch (cp) { 0x10880...0x108af => true, else => false, }; } pub fn isHatran(cp: u21) bool { if (cp < 0x108e0 or cp > 0x108ff) return false; return switch (cp) { 0x108e0...0x108ff => true, else => false, }; } pub fn isPhoenician(cp: u21) bool { if (cp < 0x10900 or cp > 0x1091f) return false; return switch (cp) { 0x10900...0x1091f => true, else => false, }; } pub fn isLydian(cp: u21) bool { if (cp < 0x10920 or cp > 0x1093f) return false; return switch (cp) { 0x10920...0x1093f => true, else => false, }; } pub fn isMeroiticHieroglyphs(cp: u21) bool { if (cp < 0x10980 or cp > 0x1099f) return false; return switch (cp) { 0x10980...0x1099f => true, else => false, }; } pub fn isMeroiticCursive(cp: u21) bool { if (cp < 0x109a0 or cp > 0x109ff) return false; return switch (cp) { 0x109a0...0x109ff => true, else => false, }; } pub fn isKharoshthi(cp: u21) bool { if (cp < 0x10a00 or cp > 0x10a5f) return false; return switch (cp) { 0x10a00...0x10a5f => true, else => false, }; } pub fn isOldSouthArabian(cp: u21) bool { if (cp < 0x10a60 or cp > 0x10a7f) return false; return switch (cp) { 0x10a60...0x10a7f => true, else => false, }; } pub fn isOldNorthArabian(cp: u21) bool { if (cp < 0x10a80 or cp > 0x10a9f) return false; return switch (cp) { 0x10a80...0x10a9f => true, else => false, }; } pub fn isManichaean(cp: u21) bool { if (cp < 0x10ac0 or cp > 0x10aff) return false; return switch (cp) { 0x10ac0...0x10aff => true, else => false, }; } pub fn isAvestan(cp: u21) bool { if (cp < 0x10b00 or cp > 0x10b3f) return false; return switch (cp) { 0x10b00...0x10b3f => true, else => false, }; } pub fn isInscriptionalParthian(cp: u21) bool { if (cp < 0x10b40 or cp > 0x10b5f) return false; return switch (cp) { 0x10b40...0x10b5f => true, else => false, }; } pub fn isInscriptionalPahlavi(cp: u21) bool { if (cp < 0x10b60 or cp > 0x10b7f) return false; return switch (cp) { 0x10b60...0x10b7f => true, else => false, }; } pub fn isPsalterPahlavi(cp: u21) bool { if (cp < 0x10b80 or cp > 0x10baf) return false; return switch (cp) { 0x10b80...0x10baf => true, else => false, }; } pub fn isOldTurkic(cp: u21) bool { if (cp < 0x10c00 or cp > 0x10c4f) return false; return switch (cp) { 0x10c00...0x10c4f => true, else => false, }; } pub fn isOldHungarian(cp: u21) bool { if (cp < 0x10c80 or cp > 0x10cff) return false; return switch (cp) { 0x10c80...0x10cff => true, else => false, }; } pub fn isHanifiRohingya(cp: u21) bool { if (cp < 0x10d00 or cp > 0x10d3f) return false; return switch (cp) { 0x10d00...0x10d3f => true, else => false, }; } pub fn isRumiNumeralSymbols(cp: u21) bool { if (cp < 0x10e60 or cp > 0x10e7f) return false; return switch (cp) { 0x10e60...0x10e7f => true, else => false, }; } pub fn isYezidi(cp: u21) bool { if (cp < 0x10e80 or cp > 0x10ebf) return false; return switch (cp) { 0x10e80...0x10ebf => true, else => false, }; } pub fn isOldSogdian(cp: u21) bool { if (cp < 0x10f00 or cp > 0x10f2f) return false; return switch (cp) { 0x10f00...0x10f2f => true, else => false, }; } pub fn isSogdian(cp: u21) bool { if (cp < 0x10f30 or cp > 0x10f6f) return false; return switch (cp) { 0x10f30...0x10f6f => true, else => false, }; } pub fn isOldUyghur(cp: u21) bool { if (cp < 0x10f70 or cp > 0x10faf) return false; return switch (cp) { 0x10f70...0x10faf => true, else => false, }; } pub fn isChorasmian(cp: u21) bool { if (cp < 0x10fb0 or cp > 0x10fdf) return false; return switch (cp) { 0x10fb0...0x10fdf => true, else => false, }; } pub fn isElymaic(cp: u21) bool { if (cp < 0x10fe0 or cp > 0x10fff) return false; return switch (cp) { 0x10fe0...0x10fff => true, else => false, }; } pub fn isBrahmi(cp: u21) bool { if (cp < 0x11000 or cp > 0x1107f) return false; return switch (cp) { 0x11000...0x1107f => true, else => false, }; } pub fn isKaithi(cp: u21) bool { if (cp < 0x11080 or cp > 0x110cf) return false; return switch (cp) { 0x11080...0x110cf => true, else => false, }; } pub fn isSoraSompeng(cp: u21) bool { if (cp < 0x110d0 or cp > 0x110ff) return false; return switch (cp) { 0x110d0...0x110ff => true, else => false, }; } pub fn isChakma(cp: u21) bool { if (cp < 0x11100 or cp > 0x1114f) return false; return switch (cp) { 0x11100...0x1114f => true, else => false, }; } pub fn isMahajani(cp: u21) bool { if (cp < 0x11150 or cp > 0x1117f) return false; return switch (cp) { 0x11150...0x1117f => true, else => false, }; } pub fn isSharada(cp: u21) bool { if (cp < 0x11180 or cp > 0x111df) return false; return switch (cp) { 0x11180...0x111df => true, else => false, }; } pub fn isSinhalaArchaicNumbers(cp: u21) bool { if (cp < 0x111e0 or cp > 0x111ff) return false; return switch (cp) { 0x111e0...0x111ff => true, else => false, }; } pub fn isKhojki(cp: u21) bool { if (cp < 0x11200 or cp > 0x1124f) return false; return switch (cp) { 0x11200...0x1124f => true, else => false, }; } pub fn isMultani(cp: u21) bool { if (cp < 0x11280 or cp > 0x112af) return false; return switch (cp) { 0x11280...0x112af => true, else => false, }; } pub fn isKhudawadi(cp: u21) bool { if (cp < 0x112b0 or cp > 0x112ff) return false; return switch (cp) { 0x112b0...0x112ff => true, else => false, }; } pub fn isGrantha(cp: u21) bool { if (cp < 0x11300 or cp > 0x1137f) return false; return switch (cp) { 0x11300...0x1137f => true, else => false, }; } pub fn isNewa(cp: u21) bool { if (cp < 0x11400 or cp > 0x1147f) return false; return switch (cp) { 0x11400...0x1147f => true, else => false, }; } pub fn isTirhuta(cp: u21) bool { if (cp < 0x11480 or cp > 0x114df) return false; return switch (cp) { 0x11480...0x114df => true, else => false, }; } pub fn isSiddham(cp: u21) bool { if (cp < 0x11580 or cp > 0x115ff) return false; return switch (cp) { 0x11580...0x115ff => true, else => false, }; } pub fn isModi(cp: u21) bool { if (cp < 0x11600 or cp > 0x1165f) return false; return switch (cp) { 0x11600...0x1165f => true, else => false, }; } pub fn isMongolianSupplement(cp: u21) bool { if (cp < 0x11660 or cp > 0x1167f) return false; return switch (cp) { 0x11660...0x1167f => true, else => false, }; } pub fn isTakri(cp: u21) bool { if (cp < 0x11680 or cp > 0x116cf) return false; return switch (cp) { 0x11680...0x116cf => true, else => false, }; } pub fn isAhom(cp: u21) bool { if (cp < 0x11700 or cp > 0x1174f) return false; return switch (cp) { 0x11700...0x1174f => true, else => false, }; } pub fn isDogra(cp: u21) bool { if (cp < 0x11800 or cp > 0x1184f) return false; return switch (cp) { 0x11800...0x1184f => true, else => false, }; } pub fn isWarangCiti(cp: u21) bool { if (cp < 0x118a0 or cp > 0x118ff) return false; return switch (cp) { 0x118a0...0x118ff => true, else => false, }; } pub fn isDivesAkuru(cp: u21) bool { if (cp < 0x11900 or cp > 0x1195f) return false; return switch (cp) { 0x11900...0x1195f => true, else => false, }; } pub fn isNandinagari(cp: u21) bool { if (cp < 0x119a0 or cp > 0x119ff) return false; return switch (cp) { 0x119a0...0x119ff => true, else => false, }; } pub fn isZanabazarSquare(cp: u21) bool { if (cp < 0x11a00 or cp > 0x11a4f) return false; return switch (cp) { 0x11a00...0x11a4f => true, else => false, }; } pub fn isSoyombo(cp: u21) bool { if (cp < 0x11a50 or cp > 0x11aaf) return false; return switch (cp) { 0x11a50...0x11aaf => true, else => false, }; } pub fn isUnifiedCanadianAboriginalSyllabicsExtendedA(cp: u21) bool { if (cp < 0x11ab0 or cp > 0x11abf) return false; return switch (cp) { 0x11ab0...0x11abf => true, else => false, }; } pub fn isPauCinHau(cp: u21) bool { if (cp < 0x11ac0 or cp > 0x11aff) return false; return switch (cp) { 0x11ac0...0x11aff => true, else => false, }; } pub fn isBhaiksuki(cp: u21) bool { if (cp < 0x11c00 or cp > 0x11c6f) return false; return switch (cp) { 0x11c00...0x11c6f => true, else => false, }; } pub fn isMarchen(cp: u21) bool { if (cp < 0x11c70 or cp > 0x11cbf) return false; return switch (cp) { 0x11c70...0x11cbf => true, else => false, }; } pub fn isMasaramGondi(cp: u21) bool { if (cp < 0x11d00 or cp > 0x11d5f) return false; return switch (cp) { 0x11d00...0x11d5f => true, else => false, }; } pub fn isGunjalaGondi(cp: u21) bool { if (cp < 0x11d60 or cp > 0x11daf) return false; return switch (cp) { 0x11d60...0x11daf => true, else => false, }; } pub fn isMakasar(cp: u21) bool { if (cp < 0x11ee0 or cp > 0x11eff) return false; return switch (cp) { 0x11ee0...0x11eff => true, else => false, }; } pub fn isLisuSupplement(cp: u21) bool { if (cp < 0x11fb0 or cp > 0x11fbf) return false; return switch (cp) { 0x11fb0...0x11fbf => true, else => false, }; } pub fn isTamilSupplement(cp: u21) bool { if (cp < 0x11fc0 or cp > 0x11fff) return false; return switch (cp) { 0x11fc0...0x11fff => true, else => false, }; } pub fn isCuneiform(cp: u21) bool { if (cp < 0x12000 or cp > 0x123ff) return false; return switch (cp) { 0x12000...0x123ff => true, else => false, }; } pub fn isCuneiformNumbersAndPunctuation(cp: u21) bool { if (cp < 0x12400 or cp > 0x1247f) return false; return switch (cp) { 0x12400...0x1247f => true, else => false, }; } pub fn isEarlyDynasticCuneiform(cp: u21) bool { if (cp < 0x12480 or cp > 0x1254f) return false; return switch (cp) { 0x12480...0x1254f => true, else => false, }; } pub fn isCyproMinoan(cp: u21) bool { if (cp < 0x12f90 or cp > 0x12fff) return false; return switch (cp) { 0x12f90...0x12fff => true, else => false, }; } pub fn isEgyptianHieroglyphs(cp: u21) bool { if (cp < 0x13000 or cp > 0x1342f) return false; return switch (cp) { 0x13000...0x1342f => true, else => false, }; } pub fn isEgyptianHieroglyphFormatControls(cp: u21) bool { if (cp < 0x13430 or cp > 0x1343f) return false; return switch (cp) { 0x13430...0x1343f => true, else => false, }; } pub fn isAnatolianHieroglyphs(cp: u21) bool { if (cp < 0x14400 or cp > 0x1467f) return false; return switch (cp) { 0x14400...0x1467f => true, else => false, }; } pub fn isBamumSupplement(cp: u21) bool { if (cp < 0x16800 or cp > 0x16a3f) return false; return switch (cp) { 0x16800...0x16a3f => true, else => false, }; } pub fn isMro(cp: u21) bool { if (cp < 0x16a40 or cp > 0x16a6f) return false; return switch (cp) { 0x16a40...0x16a6f => true, else => false, }; } pub fn isTangsa(cp: u21) bool { if (cp < 0x16a70 or cp > 0x16acf) return false; return switch (cp) { 0x16a70...0x16acf => true, else => false, }; } pub fn isBassaVah(cp: u21) bool { if (cp < 0x16ad0 or cp > 0x16aff) return false; return switch (cp) { 0x16ad0...0x16aff => true, else => false, }; } pub fn isPahawhHmong(cp: u21) bool { if (cp < 0x16b00 or cp > 0x16b8f) return false; return switch (cp) { 0x16b00...0x16b8f => true, else => false, }; } pub fn isMedefaidrin(cp: u21) bool { if (cp < 0x16e40 or cp > 0x16e9f) return false; return switch (cp) { 0x16e40...0x16e9f => true, else => false, }; } pub fn isMiao(cp: u21) bool { if (cp < 0x16f00 or cp > 0x16f9f) return false; return switch (cp) { 0x16f00...0x16f9f => true, else => false, }; } pub fn isIdeographicSymbolsAndPunctuation(cp: u21) bool { if (cp < 0x16fe0 or cp > 0x16fff) return false; return switch (cp) { 0x16fe0...0x16fff => true, else => false, }; } pub fn isTangut(cp: u21) bool { if (cp < 0x17000 or cp > 0x187ff) return false; return switch (cp) { 0x17000...0x187ff => true, else => false, }; } pub fn isTangutComponents(cp: u21) bool { if (cp < 0x18800 or cp > 0x18aff) return false; return switch (cp) { 0x18800...0x18aff => true, else => false, }; } pub fn isKhitanSmallScript(cp: u21) bool { if (cp < 0x18b00 or cp > 0x18cff) return false; return switch (cp) { 0x18b00...0x18cff => true, else => false, }; } pub fn isTangutSupplement(cp: u21) bool { if (cp < 0x18d00 or cp > 0x18d7f) return false; return switch (cp) { 0x18d00...0x18d7f => true, else => false, }; } pub fn isKanaExtendedB(cp: u21) bool { if (cp < 0x1aff0 or cp > 0x1afff) return false; return switch (cp) { 0x1aff0...0x1afff => true, else => false, }; } pub fn isKanaSupplement(cp: u21) bool { if (cp < 0x1b000 or cp > 0x1b0ff) return false; return switch (cp) { 0x1b000...0x1b0ff => true, else => false, }; } pub fn isKanaExtendedA(cp: u21) bool { if (cp < 0x1b100 or cp > 0x1b12f) return false; return switch (cp) { 0x1b100...0x1b12f => true, else => false, }; } pub fn isSmallKanaExtension(cp: u21) bool { if (cp < 0x1b130 or cp > 0x1b16f) return false; return switch (cp) { 0x1b130...0x1b16f => true, else => false, }; } pub fn isNushu(cp: u21) bool { if (cp < 0x1b170 or cp > 0x1b2ff) return false; return switch (cp) { 0x1b170...0x1b2ff => true, else => false, }; } pub fn isDuployan(cp: u21) bool { if (cp < 0x1bc00 or cp > 0x1bc9f) return false; return switch (cp) { 0x1bc00...0x1bc9f => true, else => false, }; } pub fn isShorthandFormatControls(cp: u21) bool { if (cp < 0x1bca0 or cp > 0x1bcaf) return false; return switch (cp) { 0x1bca0...0x1bcaf => true, else => false, }; } pub fn isZnamennyMusicalNotation(cp: u21) bool { if (cp < 0x1cf00 or cp > 0x1cfcf) return false; return switch (cp) { 0x1cf00...0x1cfcf => true, else => false, }; } pub fn isByzantineMusicalSymbols(cp: u21) bool { if (cp < 0x1d000 or cp > 0x1d0ff) return false; return switch (cp) { 0x1d000...0x1d0ff => true, else => false, }; } pub fn isMusicalSymbols(cp: u21) bool { if (cp < 0x1d100 or cp > 0x1d1ff) return false; return switch (cp) { 0x1d100...0x1d1ff => true, else => false, }; } pub fn isAncientGreekMusicalNotation(cp: u21) bool { if (cp < 0x1d200 or cp > 0x1d24f) return false; return switch (cp) { 0x1d200...0x1d24f => true, else => false, }; } pub fn isMayanNumerals(cp: u21) bool { if (cp < 0x1d2e0 or cp > 0x1d2ff) return false; return switch (cp) { 0x1d2e0...0x1d2ff => true, else => false, }; } pub fn isTaiXuanJingSymbols(cp: u21) bool { if (cp < 0x1d300 or cp > 0x1d35f) return false; return switch (cp) { 0x1d300...0x1d35f => true, else => false, }; } pub fn isCountingRodNumerals(cp: u21) bool { if (cp < 0x1d360 or cp > 0x1d37f) return false; return switch (cp) { 0x1d360...0x1d37f => true, else => false, }; } pub fn isMathematicalAlphanumericSymbols(cp: u21) bool { if (cp < 0x1d400 or cp > 0x1d7ff) return false; return switch (cp) { 0x1d400...0x1d7ff => true, else => false, }; } pub fn isSuttonSignwriting(cp: u21) bool { if (cp < 0x1d800 or cp > 0x1daaf) return false; return switch (cp) { 0x1d800...0x1daaf => true, else => false, }; } pub fn isLatinExtendedG(cp: u21) bool { if (cp < 0x1df00 or cp > 0x1dfff) return false; return switch (cp) { 0x1df00...0x1dfff => true, else => false, }; } pub fn isGlagoliticSupplement(cp: u21) bool { if (cp < 0x1e000 or cp > 0x1e02f) return false; return switch (cp) { 0x1e000...0x1e02f => true, else => false, }; } pub fn isNyiakengPuachueHmong(cp: u21) bool { if (cp < 0x1e100 or cp > 0x1e14f) return false; return switch (cp) { 0x1e100...0x1e14f => true, else => false, }; } pub fn isToto(cp: u21) bool { if (cp < 0x1e290 or cp > 0x1e2bf) return false; return switch (cp) { 0x1e290...0x1e2bf => true, else => false, }; } pub fn isWancho(cp: u21) bool { if (cp < 0x1e2c0 or cp > 0x1e2ff) return false; return switch (cp) { 0x1e2c0...0x1e2ff => true, else => false, }; } pub fn isEthiopicExtendedB(cp: u21) bool { if (cp < 0x1e7e0 or cp > 0x1e7ff) return false; return switch (cp) { 0x1e7e0...0x1e7ff => true, else => false, }; } pub fn isMendeKikakui(cp: u21) bool { if (cp < 0x1e800 or cp > 0x1e8df) return false; return switch (cp) { 0x1e800...0x1e8df => true, else => false, }; } pub fn isAdlam(cp: u21) bool { if (cp < 0x1e900 or cp > 0x1e95f) return false; return switch (cp) { 0x1e900...0x1e95f => true, else => false, }; } pub fn isIndicSiyaqNumbers(cp: u21) bool { if (cp < 0x1ec70 or cp > 0x1ecbf) return false; return switch (cp) { 0x1ec70...0x1ecbf => true, else => false, }; } pub fn isOttomanSiyaqNumbers(cp: u21) bool { if (cp < 0x1ed00 or cp > 0x1ed4f) return false; return switch (cp) { 0x1ed00...0x1ed4f => true, else => false, }; } pub fn isArabicMathematicalAlphabeticSymbols(cp: u21) bool { if (cp < 0x1ee00 or cp > 0x1eeff) return false; return switch (cp) { 0x1ee00...0x1eeff => true, else => false, }; } pub fn isMahjongTiles(cp: u21) bool { if (cp < 0x1f000 or cp > 0x1f02f) return false; return switch (cp) { 0x1f000...0x1f02f => true, else => false, }; } pub fn isDominoTiles(cp: u21) bool { if (cp < 0x1f030 or cp > 0x1f09f) return false; return switch (cp) { 0x1f030...0x1f09f => true, else => false, }; } pub fn isPlayingCards(cp: u21) bool { if (cp < 0x1f0a0 or cp > 0x1f0ff) return false; return switch (cp) { 0x1f0a0...0x1f0ff => true, else => false, }; } pub fn isEnclosedAlphanumericSupplement(cp: u21) bool { if (cp < 0x1f100 or cp > 0x1f1ff) return false; return switch (cp) { 0x1f100...0x1f1ff => true, else => false, }; } pub fn isEnclosedIdeographicSupplement(cp: u21) bool { if (cp < 0x1f200 or cp > 0x1f2ff) return false; return switch (cp) { 0x1f200...0x1f2ff => true, else => false, }; } pub fn isMiscellaneousSymbolsAndPictographs(cp: u21) bool { if (cp < 0x1f300 or cp > 0x1f5ff) return false; return switch (cp) { 0x1f300...0x1f5ff => true, else => false, }; } pub fn isEmoticons(cp: u21) bool { if (cp < 0x1f600 or cp > 0x1f64f) return false; return switch (cp) { 0x1f600...0x1f64f => true, else => false, }; } pub fn isOrnamentalDingbats(cp: u21) bool { if (cp < 0x1f650 or cp > 0x1f67f) return false; return switch (cp) { 0x1f650...0x1f67f => true, else => false, }; } pub fn isTransportAndMapSymbols(cp: u21) bool { if (cp < 0x1f680 or cp > 0x1f6ff) return false; return switch (cp) { 0x1f680...0x1f6ff => true, else => false, }; } pub fn isAlchemicalSymbols(cp: u21) bool { if (cp < 0x1f700 or cp > 0x1f77f) return false; return switch (cp) { 0x1f700...0x1f77f => true, else => false, }; } pub fn isGeometricShapesExtended(cp: u21) bool { if (cp < 0x1f780 or cp > 0x1f7ff) return false; return switch (cp) { 0x1f780...0x1f7ff => true, else => false, }; } pub fn isSupplementalArrowsC(cp: u21) bool { if (cp < 0x1f800 or cp > 0x1f8ff) return false; return switch (cp) { 0x1f800...0x1f8ff => true, else => false, }; } pub fn isSupplementalSymbolsAndPictographs(cp: u21) bool { if (cp < 0x1f900 or cp > 0x1f9ff) return false; return switch (cp) { 0x1f900...0x1f9ff => true, else => false, }; } pub fn isChessSymbols(cp: u21) bool { if (cp < 0x1fa00 or cp > 0x1fa6f) return false; return switch (cp) { 0x1fa00...0x1fa6f => true, else => false, }; } pub fn isSymbolsAndPictographsExtendedA(cp: u21) bool { if (cp < 0x1fa70 or cp > 0x1faff) return false; return switch (cp) { 0x1fa70...0x1faff => true, else => false, }; } pub fn isSymbolsForLegacyComputing(cp: u21) bool { if (cp < 0x1fb00 or cp > 0x1fbff) return false; return switch (cp) { 0x1fb00...0x1fbff => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionB(cp: u21) bool { if (cp < 0x20000 or cp > 0x2a6df) return false; return switch (cp) { 0x20000...0x2a6df => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionC(cp: u21) bool { if (cp < 0x2a700 or cp > 0x2b73f) return false; return switch (cp) { 0x2a700...0x2b73f => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionD(cp: u21) bool { if (cp < 0x2b740 or cp > 0x2b81f) return false; return switch (cp) { 0x2b740...0x2b81f => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionE(cp: u21) bool { if (cp < 0x2b820 or cp > 0x2ceaf) return false; return switch (cp) { 0x2b820...0x2ceaf => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionF(cp: u21) bool { if (cp < 0x2ceb0 or cp > 0x2ebef) return false; return switch (cp) { 0x2ceb0...0x2ebef => true, else => false, }; } pub fn isCjkCompatibilityIdeographsSupplement(cp: u21) bool { if (cp < 0x2f800 or cp > 0x2fa1f) return false; return switch (cp) { 0x2f800...0x2fa1f => true, else => false, }; } pub fn isCjkUnifiedIdeographsExtensionG(cp: u21) bool { if (cp < 0x30000 or cp > 0x3134f) return false; return switch (cp) { 0x30000...0x3134f => true, else => false, }; } pub fn isTags(cp: u21) bool { if (cp < 0xe0000 or cp > 0xe007f) return false; return switch (cp) { 0xe0000...0xe007f => true, else => false, }; } pub fn isVariationSelectorsSupplement(cp: u21) bool { if (cp < 0xe0100 or cp > 0xe01ef) return false; return switch (cp) { 0xe0100...0xe01ef => true, else => false, }; } pub fn isSupplementaryPrivateUseAreaA(cp: u21) bool { if (cp < 0xf0000 or cp > 0xfffff) return false; return switch (cp) { 0xf0000...0xfffff => true, else => false, }; } pub fn isSupplementaryPrivateUseAreaB(cp: u21) bool { if (cp < 0x100000 or cp > 0x10ffff) return false; return switch (cp) { 0x100000...0x10ffff => true, else => false, }; }
.gyro/ziglyph-jecolon-github.com-c37d93b6/pkg/src/autogen/blocks.zig
const std = @import("std"); const prot = @import("../protocols.zig"); const clients = @import("../client.zig"); const windows = @import("../window.zig"); const regions = @import("../region.zig"); const views = @import("../view.zig"); const Context = @import("../client.zig").Context; const Object = @import("../client.zig").Object; const Region = @import("../region.zig").Region; const Window = @import("../window.zig").Window; fn get_clients(context: *Context, fw_control: Object) anyerror!void { var it = clients.CLIENTS.iterator(); while(it.next()) |client| { try prot.fw_control_send_client(fw_control, @intCast(u32, client.getIndexOf())); } try prot.fw_control_send_done(fw_control); } fn get_windows(context: *Context, fw_control: Object) anyerror!void { for (windows.WINDOWS) |*window| { if (!window.in_use) continue; var surface_type: u32 = 0; if (window.wl_subsurface_id) |wl_subsurface_id| { surface_type = @enumToInt(prot.fw_control_surface_type.wl_subsurface); } if (window.xdg_toplevel_id) |xdg_toplevel_id| { surface_type = @enumToInt(prot.fw_control_surface_type.xdg_toplevel); } if (window.xdg_popup_id) |xdg_popup_id| { surface_type = @enumToInt(prot.fw_control_surface_type.xdg_popup); } try prot.fw_control_send_window( fw_control, @intCast(u32, window.index), (if (window.parent) |parent| @intCast(i32, parent.index) else -1), window.wl_surface_id, surface_type, window.current().x, window.current().y, window.width, window.height, (if (window.current().siblings.prev) |prev| @intCast(i32, prev.index) else -1), (if (window.current().siblings.next) |next| @intCast(i32, next.index) else -1), (if (window.current().children.prev) |prev| @intCast(i32, prev.index) else -1), (if (window.current().children.next) |next| @intCast(i32, next.index) else -1), (if (window.current().input_region) |region| region.wl_region_id else 0), ); if (window.current().input_region) |input_region| { var slice = input_region.rectangles.readableSlice(0); for(slice) |rect| { try prot.fw_control_send_region_rect( fw_control, @intCast(u32, regions.REGIONS.getIndexOf(input_region)), rect.rectangle.x, rect.rectangle.y, rect.rectangle.width, rect.rectangle.height, if (rect.op == .Add) 1 else 0, ); } } } try prot.fw_control_send_done(fw_control); } fn get_window_trees(context: *Context, fw_control: Object) anyerror!void { var view = views.CURRENT_VIEW; var it = view.back(); while(it) |window| : (it = window.toplevel.next) { var surface_type: u32 = 0; if (window.wl_subsurface_id) |wl_subsurface_id| { surface_type = @enumToInt(prot.fw_control_surface_type.wl_subsurface); } if (window.xdg_toplevel_id) |xdg_toplevel_id| { surface_type = @enumToInt(prot.fw_control_surface_type.xdg_toplevel); } if (window.xdg_popup_id) |xdg_popup_id| { surface_type = @enumToInt(prot.fw_control_surface_type.xdg_popup); } try prot.fw_control_send_toplevel_window( fw_control, @intCast(u32, window.index), (if (window.parent) |parent| @intCast(i32, parent.index) else -1), window.wl_surface_id, surface_type, window.current().x, window.current().y, window.width, window.height, (if (window.current().input_region) |region| region.wl_region_id else 0), ); try window_tree(fw_control, window); } try prot.fw_control_send_done(fw_control); } fn window_tree(fw_control: Object, window: *Window) anyerror!void { var win_it = window.backwardIterator(); while(win_it.prev()) |subwindow| { if (window == subwindow) { var subsurface_type: u32 = 0; if (subwindow.wl_subsurface_id) |wl_subsurface_id| { subsurface_type = @enumToInt(prot.fw_control_surface_type.wl_subsurface); } if (subwindow.xdg_toplevel_id) |xdg_toplevel_id| { subsurface_type = @enumToInt(prot.fw_control_surface_type.xdg_toplevel); } if (subwindow.xdg_popup_id) |xdg_popup_id| { subsurface_type = @enumToInt(prot.fw_control_surface_type.xdg_popup); } try prot.fw_control_send_window( fw_control, @intCast(u32, subwindow.index), (if (subwindow.parent) |parent| @intCast(i32, parent.index) else -1), subwindow.wl_surface_id, subsurface_type, subwindow.current().x, subwindow.current().y, subwindow.width, subwindow.height, (if (subwindow.current().siblings.prev) |prev| @intCast(i32, prev.index) else -1), (if (subwindow.current().siblings.next) |next| @intCast(i32, next.index) else -1), (if (subwindow.current().children.prev) |prev| @intCast(i32, prev.index) else -1), (if (subwindow.current().children.next) |next| @intCast(i32, next.index) else -1), (if (subwindow.current().input_region) |region| region.wl_region_id else 0), ); } else { try window_tree(fw_control, subwindow); } } } fn destroy(context: *Context, fw_control: Object) anyerror!void { try prot.wl_display_send_delete_id(context.client.wl_display, fw_control.id); try context.unregister(fw_control); } pub fn init() void { prot.FW_CONTROL = prot.fw_control_interface{ .get_clients = get_clients, .get_windows = get_windows, .get_window_trees = get_window_trees, .destroy = destroy, }; }
src/implementations/fw_control.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const testing = std.testing; const mustache = @import("../mustache.zig"); const TemplateOptions = mustache.options.TemplateOptions; const parsing = @import("parsing.zig"); pub fn Trimmer(comptime TextScanner: type, comptime TrimmingIndex: type) type { return if (@typeInfo(TrimmingIndex) == .Union) struct { const Self = @This(); // Simple state-machine to track left and right line breaks while scanning the text const LeftLFState = union(enum) { Scanning, NotFound, Found: u32 }; const RightLFState = union(enum) { Waiting, NotFound, Found: u32 }; const Chars = struct { pub const cr = '\r'; pub const lf = '\n'; pub const tab = '\t'; pub const space = ' '; pub const null_char = '\x00'; }; text_scanner: *const TextScanner, has_pending_cr: bool = false, left_lf: LeftLFState = .Scanning, right_lf: RightLFState = .Waiting, pub fn init(text_scanner: *TextScanner) Self { return .{ .text_scanner = text_scanner, }; } pub fn move(self: *Self) void { const index = self.text_scanner.index; const char = self.text_scanner.content[index]; if (char != Chars.lf) { self.has_pending_cr = (char == Chars.cr); } switch (char) { Chars.cr, Chars.space, Chars.tab, Chars.null_char => {}, Chars.lf => { assert(index >= self.text_scanner.block_index); const lf_index = @intCast(u32, index - self.text_scanner.block_index); if (self.left_lf == .Scanning) { self.left_lf = .{ .Found = lf_index }; self.right_lf = .{ .Found = lf_index }; } else if (self.right_lf != .Waiting) { self.right_lf = .{ .Found = lf_index }; } }, else => { if (self.left_lf == .Scanning) { self.left_lf = .NotFound; self.right_lf = .NotFound; } else if (self.right_lf != .Waiting) { self.right_lf = .NotFound; } }, } } pub fn getLeftTrimmingIndex(self: Self) TrimmingIndex { return switch (self.left_lf) { .Scanning, .NotFound => .PreserveWhitespaces, .Found => |index| .{ .AllowTrimming = .{ .index = index, .stand_alone = true, }, }, }; } pub fn getRightTrimmingIndex(self: Self) TrimmingIndex { return switch (self.right_lf) { .Waiting => blk: { // If there are only whitespaces, it can be trimmed right // It depends on the previous text block to be an standalone tag if (self.left_lf == .Scanning) { break :blk TrimmingIndex{ .AllowTrimming = .{ .index = 0, .stand_alone = false, }, }; } else { break :blk .PreserveWhitespaces; } }, .NotFound => .PreserveWhitespaces, .Found => |index| TrimmingIndex{ .AllowTrimming = .{ .index = index + 1, .stand_alone = true, }, }, }; } } else struct { const Self = @This(); pub inline fn init(text_scanner: *TextScanner) Self { _ = text_scanner; return .{}; } pub inline fn move(self: *Self) void { _ = self; } pub inline fn getLeftTrimmingIndex(self: Self) TrimmingIndex { _ = self; return .PreserveWhitespaces; } pub inline fn getRightTrimmingIndex(self: Self) TrimmingIndex { _ = self; return .PreserveWhitespaces; } }; } const testing_options = TemplateOptions{ .source = .{ .String = .{} }, .output = .Render, }; const Node = parsing.Node(testing_options); const TestingTextScanner = parsing.TextScanner(Node, testing_options); const TestingTrimmingIndex = parsing.TrimmingIndex(testing_options); test "Line breaks" { const allocator = testing.allocator; // 2 7 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \nABC\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \nABC\n ", block.?.content.slice); // Trim all white-spaces, including the first line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the last line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 7), block.?.trimming.right.AllowTrimming.index); } test "Line breaks \\r\\n" { const allocator = testing.allocator; // 3 9 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \r\nABC\r\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \r\nABC\r\n ", block.?.content.slice); // Trim all white-spaces, including the first line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the last line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 9), block.?.trimming.right.AllowTrimming.index); } test "Multiple line breaks" { const allocator = testing.allocator; // 2 11 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \nABC\nABC\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \nABC\nABC\n ", block.?.content.slice); // Trim all white-spaces, including the first line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the last line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 11), block.?.trimming.right.AllowTrimming.index); block.?.trimLeft(); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.left); try testing.expectEqualStrings("ABC\nABC\n ", block.?.content.slice); var indentation = block.?.trimRight(); try testing.expect(indentation != null); try testing.expectEqualStrings(" ", indentation.?.slice); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.right); try testing.expectEqualStrings("ABC\nABC\n", block.?.content.slice); } test "Multiple line breaks \\r\\n" { const allocator = testing.allocator; // 3 14 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \r\nABC\r\nABC\r\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \r\nABC\r\nABC\r\n ", block.?.content.slice); // Trim all white-spaces, including the first line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the last line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 14), block.?.trimming.right.AllowTrimming.index); block.?.trimLeft(); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.left); try testing.expectEqualStrings("ABC\r\nABC\r\n ", block.?.content.slice); var indentation = block.?.trimRight(); try testing.expect(indentation != null); try testing.expectEqualStrings(" ", indentation.?.slice); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.right); try testing.expectEqualStrings("ABC\r\nABC\r\n", block.?.content.slice); } test "Whitespace text trimming" { const allocator = testing.allocator; // 2 3 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \n ", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.right.AllowTrimming.index); block.?.trimLeft(); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.left); try testing.expectEqualStrings(" ", block.?.content.slice); var indentation = block.?.trimRight(); try testing.expect(indentation != null); try testing.expectEqualStrings(" ", indentation.?.slice); try testing.expectEqual(TestingTrimmingIndex.Trimmed, block.?.trimming.right); try testing.expect(block.?.content.slice.len == 0); } test "Whitespace text trimming \\r\\n" { const allocator = testing.allocator; // 3 4 // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \r\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \r\n ", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 4), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Tabs text trimming" { const allocator = testing.allocator; // 2 3 // ↓ ↓ var text_scanner = try TestingTextScanner.init("\t\t\n\t\t"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\t\t\n\t\t", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Trim all white-spaces, after the line break try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Whitespace left trimming" { const allocator = testing.allocator; // 2 EOF // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \n", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Whitespace left trimming \\r\\n" { const allocator = testing.allocator; // 3 EOF // ↓ ↓ var text_scanner = try TestingTextScanner.init(" \r\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \r\n", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.left.AllowTrimming.index); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Tabs left trimming" { const allocator = testing.allocator; // 2 EOF // ↓ ↓ var text_scanner = try TestingTextScanner.init("\t\t\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\t\t\n", block.?.content.slice); // Trim all white-spaces, including the line break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.left.AllowTrimming.index); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Whitespace right trimming" { const allocator = testing.allocator; // 0 1 // ↓ ↓ var text_scanner = try TestingTextScanner.init("\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\n ", block.?.content.slice); // line break belongs to the left side try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 0), block.?.trimming.left.AllowTrimming.index); // only white-spaces on the right side try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 1), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Whitespace right trimming \\r\\n" { const allocator = testing.allocator; // 1 2 // ↓ ↓ var text_scanner = try TestingTextScanner.init("\r\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\r\n ", block.?.content.slice); // line break belongs to the left side try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 1), block.?.trimming.left.AllowTrimming.index); // only white-spaces on the right side try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 2), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Tabs right trimming" { const allocator = testing.allocator; // 0 1 // ↓ ↓ var text_scanner = try TestingTextScanner.init("\n\t\t"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\n\t\t", block.?.content.slice); // line break belongs to the left side try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 0), block.?.trimming.left.AllowTrimming.index); // only white-spaces on the right side try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 1), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Single line break" { const allocator = testing.allocator; // 0 EOF // ↓ ↓ var text_scanner = try TestingTextScanner.init("\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\n", block.?.content.slice); // Trim the line-break try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 0), block.?.trimming.left.AllowTrimming.index); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Single line break \\r\\n" { const allocator = testing.allocator; // 0 EOF // ↓ ↓ var text_scanner = try TestingTextScanner.init("\r\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\r\n", block.?.content.slice); try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 1), block.?.trimming.left.AllowTrimming.index); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "No trimming" { const allocator = testing.allocator; var text_scanner = try TestingTextScanner.init(" ABC\nABC "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" ABC\nABC ", block.?.content.slice); // No trimming try testing.expect(block.?.trimming.left == .PreserveWhitespaces); try testing.expect(block.?.trimming.right == .PreserveWhitespaces); } test "No trimming, no whitespace" { const allocator = testing.allocator; // EOF // ↓ var text_scanner = try TestingTextScanner.init("|\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("|\n", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "No trimming, no whitespace \\r\\n" { const allocator = testing.allocator; // EOF // ↓ var text_scanner = try TestingTextScanner.init("|\r\n"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("|\r\n", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); // Nothing to trim right (index == len) try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(block.?.content.slice.len, block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "No trimming \\r\\n" { const allocator = testing.allocator; var text_scanner = try TestingTextScanner.init(" ABC\r\nABC "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" ABC\r\nABC ", block.?.content.slice); // No trimming both left and right try testing.expect(block.?.trimming.left == .PreserveWhitespaces); try testing.expect(block.?.trimming.right == .PreserveWhitespaces); } test "No whitespace" { const allocator = testing.allocator; // // var text_scanner = try TestingTextScanner.init("ABC"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("ABC", block.?.content.slice); // No trimming both left and right try testing.expect(block.?.trimming.left == .PreserveWhitespaces); try testing.expect(block.?.trimming.right == .PreserveWhitespaces); } test "Trimming left only" { const allocator = testing.allocator; // 3 // ↓ var text_scanner = try TestingTextScanner.init(" \nABC "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \nABC ", block.?.content.slice); try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 3), block.?.trimming.left.AllowTrimming.index); // No trimming right try testing.expect(block.?.trimming.right == .PreserveWhitespaces); } test "Trimming left only \\r\\n" { const allocator = testing.allocator; // 4 // ↓ var text_scanner = try TestingTextScanner.init(" \r\nABC "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" \r\nABC ", block.?.content.slice); try testing.expect(block.?.trimming.left == .AllowTrimming); try testing.expectEqual(@as(usize, 4), block.?.trimming.left.AllowTrimming.index); // No trimming tight try testing.expect(block.?.trimming.right == .PreserveWhitespaces); } test "Trimming right only" { const allocator = testing.allocator; // 7 // ↓ var text_scanner = try TestingTextScanner.init(" ABC\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" ABC\n ", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 7), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Trimming right only \\r\\n" { const allocator = testing.allocator; // 8 // ↓ var text_scanner = try TestingTextScanner.init(" ABC\r\n "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" ABC\r\n ", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 8), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(true, block.?.trimming.right.AllowTrimming.stand_alone); } test "Only whitespace" { const allocator = testing.allocator; // 0 // ↓ var text_scanner = try TestingTextScanner.init(" "); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings(" ", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); // Trim right from the begin can be allowed if the tag is stand-alone try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 0), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(false, block.?.trimming.right.AllowTrimming.stand_alone); } test "Only tabs" { const allocator = testing.allocator; // 0 // ↓ var text_scanner = try TestingTextScanner.init("\t\t\t"); defer text_scanner.deinit(allocator); try text_scanner.setDelimiters(.{}); var block = try text_scanner.next(allocator); try testing.expect(block != null); try testing.expectEqualStrings("\t\t\t", block.?.content.slice); // No trimming left try testing.expect(block.?.trimming.left == .PreserveWhitespaces); // Trim right from the begin can be allowed if the tag is stand-alone try testing.expect(block.?.trimming.right == .AllowTrimming); try testing.expectEqual(@as(usize, 0), block.?.trimming.right.AllowTrimming.index); try testing.expectEqual(false, block.?.trimming.right.AllowTrimming.stand_alone); }
src/parsing/trimmer.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const assert = std.debug.assert; const testing = std.testing; const mustache = @import("../mustache.zig"); const TemplateOptions = mustache.options.TemplateOptions; pub fn RefCountedSlice(comptime options: TemplateOptions) type { return struct { slice: []const u8, ref_counter: RefCounter(options), }; } pub fn RefCounter(comptime options: TemplateOptions) type { return if (options.isRefCounted()) RefCounterImpl else NoOpRefCounter; } const RefCounterImpl = struct { const Self = @This(); const State = struct { counter: usize, buffer: []const u8, }; pub const null_ref = Self{}; state: ?*State = null, pub fn create(allocator: Allocator, buffer: []const u8) Allocator.Error!Self { var state = try allocator.create(State); state.* = .{ .counter = 1, .buffer = buffer, }; return Self{ .state = state }; } pub fn ref(self: Self) Self { if (self.state) |state| { assert(state.counter != 0); state.counter += 1; return .{ .state = state }; } else { return null_ref; } } pub fn unRef(self: *Self, allocator: Allocator) void { if (self.state) |state| { assert(state.counter != 0); self.state = null; state.counter -= 1; if (state.counter == 0) { allocator.free(state.buffer); allocator.destroy(state); } } } }; const NoOpRefCounter = struct { const Self = @This(); pub const null_ref = Self{}; pub inline fn init(allocator: Allocator, buffer: []const u8) Allocator.Error!Self { _ = allocator; _ = buffer; return null_ref; } pub inline fn ref(self: Self) Self { _ = self; return null_ref; } pub inline fn unRef(self: Self, allocator: Allocator) void { _ = self; _ = allocator; } }; const testing_options = TemplateOptions{ .source = .{ .Stream = .{} }, .output = .Render, }; test "ref and free" { const allocator = testing.allocator; // No defer here, should be freed by the ref_counter const some_text = try allocator.dupe(u8, "some text"); var counter_1 = try RefCounter(testing_options).create(allocator, some_text); var counter_2 = counter_1.ref(); var counter_3 = counter_2.ref(); try testing.expect(counter_1.state != null); try testing.expect(counter_1.state.?.counter == 3); try testing.expect(counter_2.state != null); try testing.expect(counter_2.state.?.counter == 3); try testing.expect(counter_3.state != null); try testing.expect(counter_3.state.?.counter == 3); counter_1.unRef(allocator); try testing.expect(counter_1.state == null); try testing.expect(counter_2.state != null); try testing.expect(counter_2.state.?.counter == 2); try testing.expect(counter_3.state != null); try testing.expect(counter_3.state.?.counter == 2); counter_2.unRef(allocator); try testing.expect(counter_1.state == null); try testing.expect(counter_2.state == null); try testing.expect(counter_3.state != null); try testing.expect(counter_3.state.?.counter == 1); counter_3.unRef(allocator); try testing.expect(counter_1.state == null); try testing.expect(counter_2.state == null); try testing.expect(counter_3.state == null); }
src/parsing/ref_counter.zig
const Lock = @This(); const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const log = std.log; const mem = std.mem; const os = std.os; const wayland = @import("wayland"); const wl = wayland.client.wl; const wp = wayland.client.wp; const ext = wayland.client.ext; const xkb = @import("xkbcommon"); const auth = @import("auth.zig"); const Output = @import("Output.zig"); const Seat = @import("Seat.zig"); const gpa = std.heap.c_allocator; pub const Color = enum { init, input, fail, }; pub const Options = struct { init_color: u32 = 0xff002b36, input_color: u32 = 0xff6c71c4, fail_color: u32 = 0xffdc322f, fn argb(options: Options, color: Color) u32 { return switch (color) { .init => options.init_color, .input => options.input_color, .fail => options.fail_color, }; } }; state: enum { /// The session lock object has not yet been created. initializing, /// The session lock object has been created but the locked event has not been recieved. locking, /// The compositor has sent the locked event indicating that the session is locked. locked, /// Gracefully exiting and cleaning up resources. This could happen because the compositor /// did not grant waylock's request to lock the screen or because the user or compositor /// has unlocked the session. exiting, } = .initializing, color: Color = .init, pollfds: [2]os.pollfd, display: *wl.Display, shm: ?*wl.Shm = null, compositor: ?*wl.Compositor = null, session_lock_manager: ?*ext.SessionLockManagerV1 = null, session_lock: ?*ext.SessionLockV1 = null, viewporter: ?*wp.Viewporter = null, buffers: [3]*wl.Buffer, seats: std.SinglyLinkedList(Seat) = .{}, outputs: std.SinglyLinkedList(Output) = .{}, xkb_context: *xkb.Context, password: std.BoundedArray(u8, auth.password_size_max) = .{ .buffer = undefined }, auth_connection: auth.Connection, pub fn run(options: Options) void { var lock: Lock = .{ .pollfds = undefined, .display = wl.Display.connect(null) catch |err| { fatal("failed to connect to a wayland compositor: {s}", .{@errorName(err)}); }, .xkb_context = xkb.Context.new(.no_flags) orelse fatal_oom(), .auth_connection = auth.fork_child() catch |err| { fatal("failed to fork child authentication process: {s}", .{@errorName(err)}); }, .buffers = undefined, }; defer lock.deinit(); const poll_wayland = 0; const poll_auth = 1; lock.pollfds[poll_wayland] = .{ .fd = lock.display.getFd(), .events = os.POLL.IN, .revents = 0, }; lock.pollfds[poll_auth] = .{ .fd = lock.auth_connection.read_fd, .events = os.POLL.IN, .revents = 0, }; const registry = lock.display.getRegistry() catch fatal_oom(); defer registry.destroy(); registry.setListener(*Lock, registry_listener, &lock); { const errno = lock.display.roundtrip(); if (errno != .SUCCESS) { fatal("initial roundtrip failed: {s}", .{@tagName(errno)}); } } if (lock.shm == null) fatal_not_advertised(wl.Shm); if (lock.compositor == null) fatal_not_advertised(wl.Compositor); if (lock.session_lock_manager == null) fatal_not_advertised(ext.SessionLockManagerV1); if (lock.viewporter == null) fatal_not_advertised(wp.Viewporter); lock.buffers = create_buffers(lock.shm.?, options) catch |err| { fatal("failed to create buffers: {s}", .{@errorName(err)}); }; lock.shm.?.destroy(); lock.shm = null; lock.session_lock = lock.session_lock_manager.?.lock() catch fatal_oom(); lock.session_lock.?.setListener(*Lock, session_lock_listener, &lock); lock.session_lock_manager.?.destroy(); lock.session_lock_manager = null; // From this point onwards we may no longer handle OOM by exiting. assert(lock.state == .initializing); lock.state = .locking; { var it = lock.outputs.first; while (it) |node| { // Do this up front in case the node gets removed. it = node.next; node.data.create_surface() catch { log.err("out of memory", .{}); // Removes the node from the list. node.data.destroy(); continue; }; } } while (lock.state != .exiting) { lock.flush_wayland_and_prepare_read(); _ = os.poll(&lock.pollfds, -1) catch |err| { fatal("poll() failed: {s}", .{@errorName(err)}); }; if (lock.pollfds[poll_wayland].revents & os.POLL.IN != 0) { const errno = lock.display.readEvents(); if (errno != .SUCCESS) { fatal("error reading wayland events: {s}", .{@tagName(errno)}); } } else { lock.display.cancelRead(); } if (lock.pollfds[poll_auth].revents & os.POLL.IN != 0) { const byte = lock.auth_connection.reader().readByte() catch |err| { fatal("failed to read response from child authentication process: {s}", .{@errorName(err)}); }; switch (byte) { @boolToInt(true) => { lock.session_lock.?.unlockAndDestroy(); lock.session_lock = null; lock.state = .exiting; }, @boolToInt(false) => { lock.set_color(.fail); }, else => { fatal("unexpected response recieved from child authentication process: {d}", .{byte}); }, } } else if (lock.pollfds[poll_auth].revents & os.POLL.HUP != 0) { fatal("child authentication process exited unexpectedly", .{}); } } lock.flush_wayland_and_prepare_read(); } /// This function does the following: /// 1. Dispatch buffered wayland events to their listener callbacks. /// 2. Prepare the wayland connection for reading. /// 3. Send all buffered wayland requests to the server. /// After this function has been called, either wl.Display.readEvents() or /// wl.Display.cancelRead() read must be called. fn flush_wayland_and_prepare_read(lock: *Lock) void { while (!lock.display.prepareRead()) { const errno = lock.display.dispatchPending(); if (errno != .SUCCESS) { fatal("failed to dispatch pending wayland events: E{s}", .{@tagName(errno)}); } } while (true) { const errno = lock.display.flush(); switch (errno) { .SUCCESS => return, .PIPE => { // libwayland uses this error to indicate that the wayland server // closed its side of the wayland socket. We want to continue to // read any buffered messages from the server though as there is // likely a protocol error message we'd like libwayland to log. _ = lock.display.readEvents(); fatal("connection to wayland server unexpectedly terminated", .{}); }, .AGAIN => { // The socket buffer is full, so wait for it to become writable again. var wayland_out = [_]os.pollfd{.{ .fd = lock.display.getFd(), .events = os.POLL.OUT, .revents = 0, }}; _ = os.poll(&wayland_out, -1) catch |err| { fatal("poll() failed: {s}", .{@errorName(err)}); }; // No need to check for POLLHUP/POLLERR here, just fall // through to the next flush() to handle them in one place. }, else => { fatal("failed to flush wayland requests: E{s}", .{@tagName(errno)}); }, } } } /// Clean up resources just so we can better use tooling such as valgrind to check for leaks. fn deinit(lock: *Lock) void { if (lock.compositor) |compositor| compositor.destroy(); if (lock.viewporter) |viewporter| viewporter.destroy(); for (lock.buffers) |buffer| buffer.destroy(); assert(lock.shm == null); assert(lock.session_lock_manager == null); assert(lock.session_lock == null); while (lock.seats.first) |node| node.data.destroy(); while (lock.outputs.first) |node| node.data.destroy(); lock.display.disconnect(); lock.xkb_context.unref(); assert(lock.password.len == 0); lock.* = undefined; } fn registry_listener(registry: *wl.Registry, event: wl.Registry.Event, lock: *Lock) void { lock.registry_event(registry, event) catch |err| switch (err) { error.OutOfMemory => { log.err("out of memory", .{}); return; }, }; } fn registry_event(lock: *Lock, registry: *wl.Registry, event: wl.Registry.Event) !void { switch (event) { .global => |ev| { if (std.cstr.cmp(ev.interface, wl.Shm.getInterface().name) == 0) { lock.shm = try registry.bind(ev.name, wl.Shm, 1); } else if (std.cstr.cmp(ev.interface, wl.Compositor.getInterface().name) == 0) { // Version 4 required for wl_surface.damage_buffer if (ev.version < 4) { fatal("advertised wl_compositor version too old, version 4 required", .{}); } lock.compositor = try registry.bind(ev.name, wl.Compositor, 4); } else if (std.cstr.cmp(ev.interface, ext.SessionLockManagerV1.getInterface().name) == 0) { lock.session_lock_manager = try registry.bind(ev.name, ext.SessionLockManagerV1, 1); } else if (std.cstr.cmp(ev.interface, wl.Output.getInterface().name) == 0) { // Version 3 required for wl_output.release if (ev.version < 3) { fatal("advertised wl_output version too old, version 3 required", .{}); } const wl_output = try registry.bind(ev.name, wl.Output, 3); errdefer wl_output.release(); const node = try gpa.create(std.SinglyLinkedList(Output).Node); errdefer node.data.destroy(); node.data = .{ .lock = lock, .name = ev.name, .wl_output = wl_output, }; lock.outputs.prepend(node); switch (lock.state) { .initializing, .exiting => {}, .locking, .locked => try node.data.create_surface(), } } else if (std.cstr.cmp(ev.interface, wl.Seat.getInterface().name) == 0) { // Version 5 required for wl_seat.release if (ev.version < 5) { fatal("advertised wl_seat version too old, version 5 required.", .{}); } const wl_seat = try registry.bind(ev.name, wl.Seat, 5); errdefer wl_seat.release(); const node = try gpa.create(std.SinglyLinkedList(Seat).Node); errdefer gpa.destroy(node); node.data.init(lock, ev.name, wl_seat); lock.seats.prepend(node); } else if (std.cstr.cmp(ev.interface, wp.Viewporter.getInterface().name) == 0) { lock.viewporter = try registry.bind(ev.name, wp.Viewporter, 1); } }, .global_remove => |ev| { { var it = lock.outputs.first; while (it) |node| : (it = node.next) { if (node.data.name == ev.name) { node.data.destroy(); break; } } } { var it = lock.seats.first; while (it) |node| : (it = node.next) { if (node.data.name == ev.name) { node.data.destroy(); break; } } } }, } } fn session_lock_listener(_: *ext.SessionLockV1, event: ext.SessionLockV1.Event, lock: *Lock) void { switch (event) { .locked => { assert(lock.state == .locking); lock.state = .locked; }, .finished => { switch (lock.state) { .initializing => unreachable, .locking => { log.err("the wayland compositor has denied our attempt to lock the session, " ++ "is another ext-session-lock client already running?", .{}); lock.state = .exiting; }, .locked => { log.info("the wayland compositor has unlocked the session, exiting", .{}); lock.state = .exiting; }, .exiting => unreachable, } }, } } pub fn submit_password(lock: *Lock) void { assert(lock.state == .locked); lock.send_password_to_auth() catch |err| { fatal("failed to send password to child authentication process: {s}", .{@errorName(err)}); }; } fn send_password_to_auth(lock: *Lock) !void { defer lock.clear_password(); const writer = lock.auth_connection.writer(); try writer.writeIntNative(u32, @intCast(u32, lock.password.len)); try writer.writeAll(lock.password.slice()); } pub fn clear_password(lock: *Lock) void { std.crypto.utils.secureZero(u8, &lock.password.buffer); lock.password.len = 0; } pub fn set_color(lock: *Lock, color: Color) void { if (lock.color == color) return; lock.color = color; var it = lock.outputs.first; while (it) |node| : (it = node.next) { node.data.attach_buffer(lock.buffers[@enumToInt(lock.color)]); } } fn fatal(comptime format: []const u8, args: anytype) noreturn { log.err(format, args); os.exit(1); } fn fatal_oom() noreturn { fatal("out of memory during initialization", .{}); } fn fatal_not_advertised(comptime Global: type) noreturn { fatal("{s} not advertised", .{Global.getInterface().name}); } /// Create 3 1x1 buffers backed by the same shared memory fn create_buffers(shm: *wl.Shm, options: Options) ![3]*wl.Buffer { const shm_size = 3 * @sizeOf(u32); const fd = try shm_fd_create(); defer os.close(fd); try os.ftruncate(fd, shm_size); const pool = try shm.createPool(fd, shm_size); defer pool.destroy(); const backing_memory = mem.bytesAsSlice( u32, try os.mmap(null, shm_size, os.PROT.READ | os.PROT.WRITE, os.MAP.SHARED, fd, 0), ); var buffers: [3]*wl.Buffer = undefined; for ([_]Color{ .init, .input, .fail }) |color| { const i: u31 = @enumToInt(color); backing_memory[i] = options.argb(color); buffers[i] = try pool.createBuffer(i * @sizeOf(u32), 1, 1, @sizeOf(u32), .argb8888); } return buffers; } fn shm_fd_create() !os.fd_t { switch (builtin.target.os.tag) { .linux => { return os.memfd_createZ("waylock-shm", os.linux.MFD_CLOEXEC); }, .freebsd => { // TODO upstream this to the zig standard library const freebsd = struct { const MFD_CLOEXEC = 1; extern fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int; }; const ret = freebsd.memfd_create("waylock-shm", freebsd.MFD_CLOEXEC); switch (os.errno(ret)) { .SUCCESS => return ret, .BADF => unreachable, .INVAL => unreachable, .NFILE => return error.SystemFdQuotaExceeded, .MFILE => return error.ProcessFdQuotaExceeded, else => |err| return os.unexpectedErrno(err), } }, else => @compileError("Target OS not supported"), } }
src/Lock.zig
//-------------------------------------------------------------------------------- // Section: Types (3) //-------------------------------------------------------------------------------- pub const GRAPHICS_EFFECT_PROPERTY_MAPPING = enum(i32) { UNKNOWN = 0, DIRECT = 1, VECTORX = 2, VECTORY = 3, VECTORZ = 4, VECTORW = 5, RECT_TO_VECTOR4 = 6, RADIANS_TO_DEGREES = 7, COLORMATRIX_ALPHA_MODE = 8, COLOR_TO_VECTOR3 = 9, COLOR_TO_VECTOR4 = 10, }; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_UNKNOWN = GRAPHICS_EFFECT_PROPERTY_MAPPING.UNKNOWN; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT = GRAPHICS_EFFECT_PROPERTY_MAPPING.DIRECT; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_VECTORX = GRAPHICS_EFFECT_PROPERTY_MAPPING.VECTORX; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_VECTORY = GRAPHICS_EFFECT_PROPERTY_MAPPING.VECTORY; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_VECTORZ = GRAPHICS_EFFECT_PROPERTY_MAPPING.VECTORZ; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_VECTORW = GRAPHICS_EFFECT_PROPERTY_MAPPING.VECTORW; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_RECT_TO_VECTOR4 = GRAPHICS_EFFECT_PROPERTY_MAPPING.RECT_TO_VECTOR4; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_RADIANS_TO_DEGREES = GRAPHICS_EFFECT_PROPERTY_MAPPING.RADIANS_TO_DEGREES; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_COLORMATRIX_ALPHA_MODE = GRAPHICS_EFFECT_PROPERTY_MAPPING.COLORMATRIX_ALPHA_MODE; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_COLOR_TO_VECTOR3 = GRAPHICS_EFFECT_PROPERTY_MAPPING.COLOR_TO_VECTOR3; pub const GRAPHICS_EFFECT_PROPERTY_MAPPING_COLOR_TO_VECTOR4 = GRAPHICS_EFFECT_PROPERTY_MAPPING.COLOR_TO_VECTOR4; const IID_IGraphicsEffectD2D1Interop_Value = Guid.initString("2fc57384-a068-44d7-a331-30982fcf7177"); pub const IID_IGraphicsEffectD2D1Interop = &IID_IGraphicsEffectD2D1Interop_Value; pub const IGraphicsEffectD2D1Interop = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetEffectId: fn( self: *const IGraphicsEffectD2D1Interop, id: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNamedPropertyMapping: fn( self: *const IGraphicsEffectD2D1Interop, name: ?[*:0]const u16, index: ?*u32, mapping: ?*GRAPHICS_EFFECT_PROPERTY_MAPPING, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyCount: fn( self: *const IGraphicsEffectD2D1Interop, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const IGraphicsEffectD2D1Interop, index: u32, value: ?**struct{comment: []const u8 = "MissingClrType IPropertyValue.Windows.Foundation"}, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSource: fn( self: *const IGraphicsEffectD2D1Interop, index: u32, source: ?**struct{comment: []const u8 = "MissingClrType IGraphicsEffectSource.Windows.Graphics.Effects"}, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSourceCount: fn( self: *const IGraphicsEffectD2D1Interop, count: ?*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 IGraphicsEffectD2D1Interop_GetEffectId(self: *const T, id: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetEffectId(@ptrCast(*const IGraphicsEffectD2D1Interop, self), id); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGraphicsEffectD2D1Interop_GetNamedPropertyMapping(self: *const T, name: ?[*:0]const u16, index: ?*u32, mapping: ?*GRAPHICS_EFFECT_PROPERTY_MAPPING) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetNamedPropertyMapping(@ptrCast(*const IGraphicsEffectD2D1Interop, self), name, index, mapping); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGraphicsEffectD2D1Interop_GetPropertyCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetPropertyCount(@ptrCast(*const IGraphicsEffectD2D1Interop, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGraphicsEffectD2D1Interop_GetProperty(self: *const T, index: u32, value: ?**struct{comment: []const u8 = "MissingClrType IPropertyValue.Windows.Foundation"}) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetProperty(@ptrCast(*const IGraphicsEffectD2D1Interop, self), index, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGraphicsEffectD2D1Interop_GetSource(self: *const T, index: u32, source: ?**struct{comment: []const u8 = "MissingClrType IGraphicsEffectSource.Windows.Graphics.Effects"}) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetSource(@ptrCast(*const IGraphicsEffectD2D1Interop, self), index, source); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGraphicsEffectD2D1Interop_GetSourceCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IGraphicsEffectD2D1Interop.VTable, self.vtable).GetSourceCount(@ptrCast(*const IGraphicsEffectD2D1Interop, self), count); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IGeometrySource2DInterop_Value = Guid.initString("0657af73-53fd-47cf-84ff-c8492d2a80a3"); pub const IID_IGeometrySource2DInterop = &IID_IGeometrySource2DInterop_Value; pub const IGeometrySource2DInterop = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetGeometry: fn( self: *const IGeometrySource2DInterop, value: ?*?*ID2D1Geometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TryGetGeometryUsingFactory: fn( self: *const IGeometrySource2DInterop, factory: ?*ID2D1Factory, value: ?*?*ID2D1Geometry, ) 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 IGeometrySource2DInterop_GetGeometry(self: *const T, value: ?*?*ID2D1Geometry) callconv(.Inline) HRESULT { return @ptrCast(*const IGeometrySource2DInterop.VTable, self.vtable).GetGeometry(@ptrCast(*const IGeometrySource2DInterop, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGeometrySource2DInterop_TryGetGeometryUsingFactory(self: *const T, factory: ?*ID2D1Factory, value: ?*?*ID2D1Geometry) callconv(.Inline) HRESULT { return @ptrCast(*const IGeometrySource2DInterop.VTable, self.vtable).TryGetGeometryUsingFactory(@ptrCast(*const IGeometrySource2DInterop, self), factory, value); } };} 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 (6) //-------------------------------------------------------------------------------- const Guid = @import("../../../zig.zig").Guid; const HRESULT = @import("../../../foundation.zig").HRESULT; const ID2D1Factory = @import("../../../graphics/direct2d.zig").ID2D1Factory; const ID2D1Geometry = @import("../../../graphics/direct2d.zig").ID2D1Geometry; const IUnknown = @import("../../../system/com.zig").IUnknown; const PWSTR = @import("../../../foundation.zig").PWSTR; 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/graphics/direct2d.zig
const std = @import("std"); const snowFlake = struct { startTime: u64, lastvalue: u64=0, const Self = @This(); const worker_mask = 0x3ff; pub fn init(startTime: u64, workerId: u64) Self { var v :Self = .{.startTime = startTime, .lastvalue = workerId <<12}; return v; } inline fn extractWorkerId(value: u64) u64{ return (value >> 12) & worker_mask; } inline fn extractTimestamp(value: u64) u64{ return (value >> 22); } inline fn extractSequence(value: u64) u64{ return (value & 0xfff); } pub fn format(value: *const Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try std.fmt.format(writer, "{} {{ .startTime = {}, .workerId = {}, .timestamp = {}, .sequence = {} }}", .{comptime @typeName(Self) ++ "{ ", value.startTime, extractWorkerId(value.lastvalue), extractTimestamp(value.lastvalue), extractSequence(value.lastvalue)}); } fn tryGen(startTime:u64, value: u64) u64 { var curr_ts = @bitCast(u64, std.time.milliTimestamp()) - startTime; const prev_ts = extractTimestamp(value); var sequence = extractSequence(value); const workerId = extractWorkerId(value); var mask = ~@intCast(u64, worker_mask); if((value & mask) == 0){ sequence = 0; } else if (curr_ts == prev_ts) { sequence = sequence + 1; if(sequence >= 0x1000){ sequence = 0; var now = curr_ts; while(curr_ts == now){ now = @bitCast(u64, std.time.milliTimestamp()) - startTime; } curr_ts = now; } } else { sequence = 0; } return (curr_ts<<22) | ((workerId <<12)& (worker_mask<<12)) | (sequence & 0x0fff); } pub fn get(self: *Self) u64 { var old_value = self.lastvalue; while(true){ var new_value = tryGen(self.startTime, old_value); var o = @cmpxchgWeak(u64, &self.lastvalue, old_value, new_value, .Acquire, .Acquire); if(o)|v|{ old_value = v; continue; } return new_value; } } };
snowFlake.zig
pub const RELEASE = 0; pub const PRESS = 1; pub const REPEAT = 2; pub const MOUSE_BUTTON_1 = 0; pub const MOUSE_BUTTON_2 = 1; pub const MOUSE_BUTTON_3 = 2; pub const MOUSE_BUTTON_4 = 3; pub const MOUSE_BUTTON_5 = 4; pub const MOUSE_BUTTON_6 = 5; pub const MOUSE_BUTTON_7 = 6; pub const MOUSE_BUTTON_8 = 7; pub const MOUSE_BUTTON_LAST = MOUSE_BUTTON_8; pub const MOUSE_BUTTON_RIGHT = MOUSE_BUTTON_2; // Keyboard pub const KEY_F7 = 296; pub const KEY_X = 88; pub const KEY_1 = 49; pub const KEY_F2 = 291; pub const KEY_LEFT_ALT = 342; pub const KEY_ESCAPE = 256; pub const KEY_F17 = 306; pub const KEY_RIGHT_SHIFT = 344; pub const KEY_F21 = 310; pub const KEY_LEFT_CONTROL = 341; pub const KEY_RIGHT = 262; pub const KEY_4 = 52; pub const KEY_APOSTROPHE = 39; pub const KEY_R = 82; pub const KEY_RIGHT_BRACKET = 93; pub const KEY_F24 = 313; pub const KEY_CAPS_LOCK = 280; pub const KEY_KP_MULTIPLY = 332; pub const KEY_LEFT_SHIFT = 340; pub const KEY_MINUS = 45; pub const KEY_WORLD_2 = 162; pub const KEY_KP_3 = 323; pub const KEY_M = 77; pub const KEY_KP_6 = 326; pub const KEY_EQUAL = 61; pub const KEY_9 = 57; pub const KEY_G = 71; pub const KEY_UP = 265; pub const KEY_KP_DIVIDE = 331; pub const KEY_SPACE = 32; pub const KEY_F5 = 294; pub const KEY_Z = 90; pub const KEY_F14 = 303; pub const KEY_3 = 51; pub const KEY_Q = 81; pub const KEY_F11 = 300; pub const KEY_PAGE_DOWN = 267; pub const KEY_F23 = 312; pub const KEY_SEMICOLON = 59; pub const KEY_COMMA = 44; pub const KEY_6 = 54; pub const KEY_TAB = 258; pub const MOD_SHIFT = 1; pub const KEY_T = 84; pub const KEY_H = 72; pub const KEY_KP_5 = 325; pub const KEY_O = 79; pub const KEY_KP_ADD = 334; pub const KEY_KP_8 = 328; pub const KEY_SLASH = 47; pub const KEY_B = 66; pub const KEY_PAUSE = 284; pub const KEY_LEFT_SUPER = 343; pub const KEY_LEFT = 263; pub const KEY_PRINT_SCREEN = 283; pub const KEY_F8 = 297; pub const KEY_NUM_LOCK = 282; pub const KEY_Y = 89; pub const KEY_F19 = 308; pub const MOD_NUM_LOCK = 32; pub const KEY_HOME = 268; pub const KEY_F3 = 292; pub const KEY_F16 = 305; pub const KEY_ENTER = 257; pub const KEY_5 = 53; pub const KEY_S = 83; pub const KEY_F13 = 302; pub const KEY_F25 = 314; pub const KEY_UNKNOWN = -1; pub const KEY_V = 86; pub const KEY_WORLD_1 = 161; pub const KEY_KP_0 = 320; pub const KEY_KP_DECIMAL = 330; pub const KEY_RIGHT_CONTROL = 345; pub const KEY_J = 74; pub const KEY_KP_7 = 327; pub const KEY_A = 65; pub const KEY_INSERT = 260; pub const KEY_D = 68; pub const KEY_RIGHT_SUPER = 347; pub const KEY_DELETE = 261; pub const KEY_F6 = 295; pub const KEY_END = 269; pub const MOD_CONTROL = 2; pub const KEY_KP_ENTER = 335; pub const KEY_GRAVE_ACCENT = 96; pub const KEY_0 = 48; pub const MOD_SUPER = 8; pub const KEY_F1 = 290; pub const KEY_F10 = 299; pub const KEY_LAST = KEY_MENU; pub const KEY_DOWN = 264; pub const KEY_F20 = 309; pub const KEY_7 = 55; pub const KEY_U = 85; pub const KEY_I = 73; pub const KEY_KP_2 = 322; pub const KEY_BACKSPACE = 259; pub const KEY_LEFT_BRACKET = 91; pub const KEY_L = 76; pub const KEY_KP_9 = 329; pub const KEY_C = 67; pub const MOD_ALT = 4; pub const KEY_PAGE_UP = 266; pub const KEY_8 = 56; pub const KEY_F9 = 298; pub const KEY_PERIOD = 46; pub const KEY_F = 70; pub const KEY_F18 = 307; pub const KEY_MENU = 348; pub const KEY_BACKSLASH = 92; pub const KEY_F4 = 293; pub const KEY_F15 = 304; pub const KEY_KP_SUBTRACT = 333; pub const KEY_2 = 50; pub const KEY_P = 80; pub const KEY_F12 = 301; pub const KEY_F22 = 311; pub const KEY_W = 87; pub const KEY_KP_1 = 321; pub const KEY_K = 75; pub const KEY_KP_4 = 324; pub const KEY_SCROLL_LOCK = 281; pub const KEY_KP_EQUAL = 336; pub const KEY_N = 78; pub const KEY_RIGHT_ALT = 346; pub const MOD_CAPS_LOCK = 16; pub const KEY_E = 69;
src/WindowGraphicsInput/Constants.zig
pub const Location = enum { Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, LeftOf1, // Number key row, 123...0 NumberKey1, NumberKey2, NumberKey3, NumberKey4, NumberKey5, NumberKey6, NumberKey7, NumberKey8, NumberKey9, NumberKey0, RightOf0, LeftOfBackspace, Backspace, // Top line, QWERTY: QWERTY... Tab, Line1_1, Line1_2, Line1_3, Line1_4, Line1_5, Line1_6, Line1_7, Line1_8, Line1_9, Line1_10, Line1_11, Line1_12, Line1_13, // Middle line, QWERTY: ASDFGH... CapsLock, Line2_1, Line2_2, Line2_3, Line2_4, Line2_5, Line2_6, Line2_7, Line2_8, Line2_9, Line2_10, Line2_11, Line2_12, Enter, // Bottom line, QWERTY: ZXCVBN... LeftShift, RightOfLeftShift, Line3_1, Line3_2, Line3_3, Line3_4, Line3_5, Line3_6, Line3_7, Line3_8, Line3_9, Line3_10, RightShift, // Control keys along the bottom LeftCtrl, RightCtrl, LeftSuper, RightSuper, LeftAlt, RightAlt, Spacebar, OptionKey, // Between right super and right control // Directional keys ArrowUp, ArrowLeft, ArrowDown, ArrowRight, // Group above directional keys PrintScreen, PauseBreak, ScrollLock, Insert, Home, PageUp, Delete, End, PageDown, // Numpad NumLock, NumpadDivision, NumpadMultiplication, Numpad7, Numpad8, Numpad9, NumpadSubtraction, Numpad4, Numpad5, Numpad6, NumpadAddition, Numpad1, Numpad2, Numpad3, Numpad0, NumpadPoint, NumpadEnter, // Multimedia keys MediaStop, MediaRewind, MediaPausePlay, MediaForward, MediaMute, MediaVolumeUp, MediaVolumeDown, }; /// Represent the intent of pressing the key, affected by keyboard layout pub const Input = enum { // Traditional numbers @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"0", // Traditional letters Q, W, E, R, T, Y, U, I, O, P, A, S, D, F, G, H, J, K, L, Z, X, C, V, B, N, M, // Control keys Spacebar, OptionKey, Backspace, Tab, Escape, CapsLock, Enter, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, // Modifier keys LeftShift, RightShift, LeftCtrl, RightCtrl, LeftSuper, RightSuper, LeftAlt, RightAlt, // The buttons traditionally above the arrow keys PrintScreen, PauseBreak, ScrollLock, Insert, Home, PageUp, Delete, End, PageDown, // Arrow keys ArrowUp, ArrowLeft, ArrowDown, ArrowRight, // Punctuation ExclamationMark, QuotationMark, Hash, CurrencySign, Percent, Ampersand, Forwardslash, Backslash, Questionmark, At, DollarCurrency, Caret, Asterisk, Period, Comma, Colon, Semicolon, Plus, Minus, Underscore, Equals, VerticalBar, Tilde, Backtick, Apostrophe, PoundCurrency, Plusminus, Acute, Umlaut, EuroCurrency, YenCurrency, ParagraphSign, SectionSign, OpenSqBracket, CloseSqBracket, OpenCurlyBrace, CloseCurlyBrace, OpenParen, CloseParen, LessThan, GreaterThan, // Numpad NumLock, NumpadDivision, NumpadMultiplication, Numpad7, Numpad8, Numpad9, NumpadSubtraction, Numpad4, Numpad5, Numpad6, NumpadAddition, Numpad1, Numpad2, Numpad3, Numpad0, NumpadPoint, NumpadEnter, // Multimedia keys MediaStop, MediaRewind, MediaPausePlay, MediaForward, MediaMute, MediaVolumeUp, MediaVolumeDown, // International letters AWithUmlaut, OWithUmlaut, AWithRing, SlashedO, Ash, }; const wasd_directional = .{ .up = KeyLocation.Line1_2, .left = KeyLocation.Line2_1, .down = KeyLocation.Line2_2, .right = KeyLocation.Line2_3, }; const arrow_directional = .{ .up = KeyLocation.ArrowUp, .left = KeyLocation.ArrowLeft, .down = KeyLocation.ArrowDown, .right = KeyLocation.ArrowRight, }; const numpad_directional = .{ .up = KeyLocation.Numpad8, .left = KeyLocation.Numpad4, .down = KeyLocation.Numpad2, .right = KeyLocation.Numpad6, };
src/drivers/hid/keyboard_keys.zig
const platform = @import("platform.zig"); const mem = @import("std").mem; const gdt = @import("gdt.zig"); const interrupts = @import("interrupts.zig"); const isr = @import("isr.zig"); const serial = @import("../../debug/serial.zig"); pub const IDTFlags = struct { gate_type: u4, storage_segment: u1, privilege: u2, present: u1, fn fromRaw(val: u8) IDTFlags {} }; pub const InterruptGateFlags = IDTFlags{ .gate_type = 0xE, .storage_segment = 0, .privilege = 0, .present = 1, }; // u32, u32, u32 // offset_low, selector // flags, offset_mid // offset_high const IDTEntry = packed struct { offset_low: u16, // 0..15 selector: u16, flags: u16, offset_mid: u16, // 16..31 offset_high: u32, // 31..63 zero: u32 = 0, fn setFlags(self: *IDTEntry, flags: IDTFlags) void { const flags_low: u8 = (@as(u8, flags.present) << 7) | (@as(u8, flags.privilege) << 5) | (@as(u8, flags.storage_segment) << 4) | flags.gate_type; self.flags = mem.nativeToBig(u16, flags_low | (0x0 << 8)); // TODO(Ryan): lol, just build correctly the flags. 0x0 := ist,zero_1. } fn setOffset(self: *IDTEntry, offset: u64) void { self.offset_low = @truncate(u16, offset); self.offset_mid = @truncate(u16, offset >> 16); self.offset_high = @truncate(u32, offset >> 32); } }; const IDTRegister = packed struct { limit: u16, base: *[256]IDTEntry, }; var idt: [256]IDTEntry = undefined; const idtr = IDTRegister{ .limit = @as(u16, @sizeOf(@TypeOf(idt))), .base = &idt }; pub fn setGate(n: u8, flags: IDTFlags, offset: fn () callconv(.C) void) void { var buf: [4096]u8 = undefined; const intOffset = @ptrToInt(offset); idt[n].setOffset(intOffset); idt[n].setFlags(flags); idt[n].selector = gdt.KERNEL_CODE; } // Load a new IDT fn lidt(idt_ptr: usize) void { asm volatile ("lidt (%[idtr])" : : [idtr] "r" (idt_ptr) ); } fn sidt() IDTRegister { var ptr = IDTRegister{ .limit = undefined, .base = undefined }; asm volatile ("sidt %[ptr]" : [ptr] "=m" (ptr) ); return ptr; } pub fn initialize() void { serial.writeText("IDT initializing...\n"); interrupts.initialize(); interrupts.register(0, divide_by_zero); interrupts.register(1, debug_trap); interrupts.register(14, page_fault_handler); lidt(@ptrToInt(&idtr)); serial.writeText("IDT initialized.\n"); runtimeTests(); } fn divide_by_zero(ctx: *platform.Context) usize { serial.writeText("divide by zero!\n"); return @ptrToInt(ctx); } fn debug_trap(ctx: *platform.Context) usize { serial.writeText("debug fault/trap\n"); return @ptrToInt(ctx); } fn page_fault_handler(ctx: *platform.Context) usize { serial.writeText("page fault handler\n"); return @ptrToInt(ctx); } fn rt_loadedIDTProperly() void { const loaded_idt = sidt(); if (idtr.limit != loaded_idt.limit) { @panic("Fatal error: IDT limit is not loaded properly: 0x{x} != 0x{x}\n"); } if (idtr.base != loaded_idt.base) { @panic("Fatal error: IDT base is not loaded properly"); } serial.writeText("Runtime tests: IDT loading tested succesfully.\n"); } fn runtimeTests() void { rt_loadedIDTProperly(); }
src/kernel/arch/x86/idt.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/day15.txt"); const asc = std.sort.asc(usize); const Pos = struct { x: usize, y: usize, density: u8, risk: ?u32 = null, prev: ?*Pos = null, }; pub fn main() !void { var map = blk: { var map_array = List([]Pos).init(gpa); var lines = try util.toStrSlice(data, "\n"); for (lines) |line, j| { var row = List(Pos).init(gpa); for (line) |c, i| { try row.append(.{ .x = i, .y = j, .density = c - '0' }); } try map_array.append(row.toOwnedSlice()); } break :blk map_array.toOwnedSlice(); }; defer { for (map) |line| { gpa.free(line); } gpa.free(map); } const size = map.len; { // risk of start is 0 map[0][0].risk = 0; var queue = std.PriorityDequeue(*Pos).init(gpa, sort); defer queue.deinit(); for (map) |line| { for (line) |*pos| { try queue.add(pos); } } while (queue.items.len > 0) { var min = queue.removeMin(); // set v's distance for each (min, v) in the graph // this is simplified due to this being a grid // left if (min.x > 0) { var v = &map[min.y][min.x - 1]; // TODO: this is a case where v can be inferred to be not-null correct? if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // up if (min.y > 0) { var v = &map[min.y - 1][min.x]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // right if (min.x < size - 1) { var v = &map[min.y][min.x + 1]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // down if (min.y < size - 1) { var v = &map[min.y + 1][min.x]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } } print("{}\n", .{map[size - 1][size - 1].risk.?}); } // alloc full map var full_map = try gpa.alloc([]Pos, size * 5); for (full_map) |*row, j| { row.* = try gpa.alloc(Pos, size * 5); } for (map) |row, j| { for (row) |pos, i| { var y: usize = 0; while (y < 5) : (y += 1) { var x: usize = 0; while (x < 5) : (x += 1) { var density = map[j][i].density + x + y; while (density > 9) { density -= 9; } var p: Pos = .{ .x = i + size * x, .y = j + size * y, .density = @intCast(u8, density) }; full_map[j + size * y][i + size * x] = p; } } } } { const full_size = size * 5; // risk of start is 0 full_map[0][0].risk = 0; var queue = std.PriorityDequeue(*Pos).init(gpa, sort); defer queue.deinit(); for (full_map) |line| { for (line) |*pos| { try queue.add(pos); } } var num: usize = 1; while (queue.items.len > 0) : (num += 1) { if (num % 1000 == 0) print("visiting node={}\n", .{num}); // var min = popSmallest(&queue); var min = queue.removeMin(); // set v's distance for each (min, v) in the graph // this is simplified due to this being a grid // left if (min.x > 0) { var v = &full_map[min.y][min.x - 1]; // TODO: this is a case where v can be inferred to be not-null correct? if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // up if (min.y > 0) { var v = &full_map[min.y - 1][min.x]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // right if (min.x < full_size - 1) { var v = &full_map[min.y][min.x + 1]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } // down if (min.y < full_size - 1) { var v = &full_map[min.y + 1][min.x]; if (v.risk == null or v.risk.? > min.risk.? + v.density) { v.risk = min.risk.? + v.density; v.prev = min; queue.update(v, v) catch {}; } } } print("{}\n", .{full_map[full_size - 1][full_size - 1].risk.?}); } } const Order = std.math.Order; fn sort(a: *Pos, b: *Pos) Order { if (a.risk == null and b.risk == null) return Order.eq; if (a.risk != null and b.risk == null) return Order.lt; if (a.risk == null and b.risk != null) return Order.gt; if (a.risk.? == b.risk.?) return Order.eq; return if (a.risk.? < b.risk.?) Order.lt else Order.gt; } // This code was the result of assuming the submarine can only travel down and right. // But all 4 directions are possible. I'm still super happy with this code so I'll // leave it below :) // const Pos = struct { // density: u8, // risk: u32 = 0, // prev: struct { // y: usize, // x: usize, // } = .{ .x = 0, .y = 0 }, // }; // pub fn main() !void { // var map = blk: { // var map_array = List([]Pos).init(gpa); // var lines = try util.toStrSlice(data, "\n"); // for (lines) |line| { // var row = List(Pos).init(gpa); // for (line) |c| { // try row.append(.{ .density = c - '0', .risk = 0 }); // } // try map_array.append(row.toOwnedSlice()); // } // break :blk map_array.toOwnedSlice(); // }; // defer { // for (map) |line| { // gpa.free(line); // } // gpa.free(map); // } // // top // for (map[0][1..]) |*pos, i| { // pos.risk = map[0][i].risk + pos.density; // pos.prev.y = 0; // pos.prev.x = i; // } // // left column // for (map[1..]) |row, i| { // row[0].risk = map[i][0].risk + row[0].density; // pos.prev.y = i; // pos.prev.x = 0; // } // for (map) |row, j| { // if (j == 0) continue; // for (row) |*pos, i| { // if (i == 0) continue; // // edit distance? // var left = map[j][i - 1].risk + pos.density; // var up = map[j - 1][i].risk + pos.density; // if (left < up) { // pos.risk = left; // pos.prev.y = j; // pos.prev.x = i - 1; // } else { // pos.risk = up; // pos.prev.y = j - 1; // pos.prev.x = i; // } // } // } // print("{}\n", .{map[map.len - 1][map.len - 1].risk}); // }
2021/src/day15.zig
const std = @import("std"); const fun = @import("fun"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const scan = fun.scan.scan; pub fn main() !void { const stdin = &(try io.getStdIn()).inStream().stream; const stdout = &(try io.getStdOut()).outStream().stream; var ps = io.PeekStream(1, os.File.InStream.Error).init(stdin); var direct_allocator = heap.DirectAllocator.init(); const allocator = &direct_allocator.allocator; defer direct_allocator.deinit(); const points = try readPoints(allocator, &ps); try stdout.print("{}\n", try findBiggestFiniteArea(allocator, points)); try stdout.print("{}\n", try findRegionAreaFromDistanceToPoints(10000, points)); } fn readPoints(allocator: *mem.Allocator, ps: var) ![]Point { var points = std.ArrayList(Point).init(allocator); defer points.deinit(); while (scan(ps, "{}, {}\n", Point)) |point| { try points.append(point); } else |err| switch (err) { error.EndOfStream => {}, else => return err, } return points.toOwnedSlice(); } fn findBiggestFiniteArea(allocator: *mem.Allocator, points: []const Point) !isize { if (points.len == 0) return error.NoInput; const infinit: isize = math.minInt(isize); const size = max(Point, points, Point.lessThan) orelse return error.NoInput; const areas = try allocator.alloc(isize, points.len); defer allocator.free(areas); mem.set(isize, areas, 0); var x: usize = 0; while (x < size.x) : (x += 1) { var y: usize = 0; while (y < size.y) : (y += 1) { const p = Point{ .x = x, .y = y }; const i = closestPoint(p, points) orelse continue; if (x == 0 or y == 0 or x == size.x - 1 or y == size.y - 1) { areas[i] = infinit; } else { areas[i] += 1; } } } return mem.max(isize, areas); } fn findRegionAreaFromDistanceToPoints(max_dist: usize, points: []const Point) !usize { var area: usize = 0; const size = max(Point, points, Point.lessThan) orelse return error.NoInput; var x: usize = 0; while (x < size.x) : (x += 1) { var y: usize = 0; while (y < size.y) : (y += 1) { const p1 = Point{ .x = x, .y = y }; var dist: usize = 0; for (points) |p2| { dist += p1.distance(p2); } if (dist < max_dist) area += 1; } } return area; } fn max(comptime T: type, slice: []const T, comptime lessThan: fn (T, T) bool) ?T { if (slice.len == 0) return null; var res = slice[0]; for (slice) |item| { if (lessThan(res, item)) res = item; } return res; } fn closestPoint(point: Point, points: []const Point) ?usize { if (points.len == 0) return null; var min_i: ?usize = null; var min_dist: usize = math.maxInt(usize); for (points[0..]) |item, i| { const item_dist = item.distance(point); if (item_dist == min_dist) { min_i = null; } else if (item_dist < min_dist) { min_dist = item_dist; min_i = i; } } return min_i; } const Point = struct { x: usize, y: usize, const zero = Point{ .x = 0, .y = 0 }; fn lessThan(a: Point, b: Point) bool { return a.distance(zero) < b.distance(zero); } fn distance(a: Point, b: Point) u64 { return (math.sub(u64, a.x, b.x) catch b.x - a.x) + (math.sub(u64, a.y, b.y) catch b.y - a.y); } };
src/day6.zig
const std = @import("std"); const os = std.os; const Builder = std.build.Builder; const Target = std.Target; const CrossTarget = std.zig.CrossTarget; const LibExeObjStep = std.build.LibExeObjStep; const FileSource = std.build.FileSource; const builtin = @import("builtin"); const cflags = .{ "-std=c11", //"-pedantic", "-Wall", "-Wextra" }; pub fn build(b: *Builder) void { const target = CrossTarget{ .cpu_arch = Target.Cpu.Arch.riscv32, .cpu_model = .{ .explicit = &Target.riscv.cpu.sifive_e31 }, .os_tag = Target.Os.Tag.freestanding, .abi = Target.Abi.none, }; const kernel = b.addExecutable("kernel.elf", "src/start.zig"); { kernel.setBuildMode(b.standardReleaseOptions()); kernel.setTarget(target); kernel.setLinkerScriptPath(FileSource.relative("src/target/board/hifive1-revb/linker.ld")); // https://github.com/ziglang/zig/issues/5558 kernel.code_model = .medium; add_lua(kernel); add_libc(b, target, kernel); kernel.install(); } b.default_step.dependOn(&kernel.step); const debug_step = b.step("debug", "Debug connected HiFive1 Rev B board"); const debug_cmd = b.addSystemCommand(&[_][]const u8{ "ugdb", "--command", "src/target/board/hifive1-revb/gdbcommands", "--layout", "s-c", // Don't add expressions table and terminal panels. "zig-out/bin/kernel.elf", }); debug_cmd.step.dependOn(b.getInstallStep()); debug_step.dependOn(&debug_cmd.step); } fn add_lua(item: *LibExeObjStep) void { const lua_src_dir = "deps/lua-5.4.3/src/"; const lua_c_files = .{ "lapi.c", "lcode.c", "lctype.c", "ldebug.c", "ldo.c", "ldump.c", "lfunc.c", "lgc.c", "llex.c", "lmem.c", "lobject.c", "lopcodes.c", "lparser.c", "lstate.c", "lstring.c", "ltable.c", "ltm.c", "lundump.c", "lvm.c", "lzio.c", // "lauxlib.c", // "lbaselib.c", // "lcorolib.c", // "ldblib.c", // "liolib.c", // "lmathlib.c", // "loadlib.c", // "loslib.c", // "lstrlib.c", // "ltablib.c", // "lutf8lib.c", // "linit.c", }; inline for (lua_c_files) |c_file| { item.addCSourceFile(lua_src_dir ++ c_file, &cflags); } item.addIncludeDir(lua_src_dir); item.addIncludeDir("src/libc/include"); item.defineCMacro("lua_getlocaledecpoint()", "(\".\")"); item.defineCMacro("LUA_USE_APICHECK", "1"); item.defineCMacro("LUAI_ASSERT", "1"); } fn add_libc(b: *Builder, target: CrossTarget, item: *LibExeObjStep) void { const libc_src_dir = "src/libc/"; const libc_files = .{ .{ "string", "string.zig" }, .{ "stdlib", "stdlib.zig" }, .{ "time", "time.zig" }, .{ "math", "math.zig" }, .{ "setjmp", "setjmp.zig" }, .{ "ctype", "ctype.zig" }, .{ "assert", "assert.zig" }, }; inline for (libc_files) |file| { const obj = b.addObject(file.@"0", libc_src_dir ++ file.@"1"); obj.setTarget(target); obj.addIncludeDir("src/libc/include"); item.addObject(obj); } item.addCSourceFile(libc_src_dir ++ "snprintf.c", &cflags); }
build.zig
const std = @import("std"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const Pkg = std.build.Pkg; const CrossTarget = std.zig.CrossTarget; const Mode = std.builtin.Mode; const KC85Model = enum { KC85_2, KC85_3, KC85_4, }; pub fn build(b: *Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const sokol = buildSokol(b, target, mode, ""); addKC85(b, sokol, target, mode, .KC85_2); addKC85(b, sokol, target, mode, .KC85_3); addKC85(b, sokol, target, mode, .KC85_4); addZ80Test(b, target, mode); addZ80ZEXDOC(b, target, mode); addZ80ZEXALL(b, target, mode); addTests(b); } fn addKC85(b: *Builder, sokol: *LibExeObjStep, target: CrossTarget, mode: Mode, comptime kc85_model: KC85Model) void { const name = switch (kc85_model) { .KC85_2 => "kc852", .KC85_3 => "kc853", .KC85_4 => "kc854" }; const exe = b.addExecutable(name, "src/main.zig"); const exe_options = b.addOptions(); exe.addOptions("build_options", exe_options); exe_options.addOption(KC85Model, "kc85_model", kc85_model); const pkg_sokol = Pkg{ .name = "sokol", .path = .{ .path = "src/sokol/sokol.zig" }, }; const pkg_host = Pkg{ .name = "host", .path = .{ .path = "src/host/host.zig" }, .dependencies = &[_]Pkg{ pkg_sokol } }; const pkg_emu = Pkg{ .name = "emu", .path = .{ .path = "src/emu/emu.zig" }, .dependencies = &[_]Pkg{ exe_options.getPackage("build_options") } }; exe.addPackage(pkg_sokol); exe.addPackage(pkg_emu); exe.addPackage(pkg_host); exe.linkLibrary(sokol); exe.setTarget(target); exe.setBuildMode(mode); 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-" ++ name, "Run " ++ name); run_step.dependOn(&run_cmd.step); } fn addTests(b: *Builder) void { const tests = b.addTest("src/tests.zig"); const test_step = b.step("tests", "Run all tests"); test_step.dependOn(&tests.step); } fn addZ80Test(b: *Builder, target: CrossTarget, mode: Mode) void { const exe = b.addExecutable("z80test", "tests/z80test.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addPackagePath("emu", "src/emu/emu.zig"); 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("z80test", "Run the Z80 CPU test"); run_step.dependOn(&run_cmd.step); } fn addZ80ZEXDOC(b: *Builder, target: CrossTarget, mode: Mode) void { const exe = b.addExecutable("z80zexdoc", "tests/z80zex.zig"); exe.setTarget(target); exe.setBuildMode(mode); const exe_options = b.addOptions(); exe.addOptions("build_options", exe_options); exe_options.addOption(bool, "zexdoc", true); exe_options.addOption(bool, "zexall", false); exe.addPackagePath("emu", "src/emu/emu.zig"); 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("z80zexdoc", "Run the Z80 ZEXDOC test"); run_step.dependOn(&run_cmd.step); } fn addZ80ZEXALL(b: *Builder, target: CrossTarget, mode: Mode) void { const exe = b.addExecutable("z80zexall", "tests/z80zex.zig"); exe.setTarget(target); exe.setBuildMode(mode); const exe_options = b.addOptions(); exe.addOptions("build_options", exe_options); exe_options.addOption(bool, "zexdoc", true); exe_options.addOption(bool, "zexall", false); exe.addPackagePath("emu", "src/emu/emu.zig"); 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("z80zexall", "Run the Z80 ZEXALL test"); run_step.dependOn(&run_cmd.step); } fn buildSokol(b: *Builder, target: CrossTarget, mode: Mode, comptime prefix_path: []const u8) *LibExeObjStep { const lib = b.addStaticLibrary("sokol", null); lib.setTarget(target); lib.setBuildMode(mode); lib.linkLibC(); const sokol_path = prefix_path ++ "src/sokol/c/"; const csources = [_][]const u8 { "sokol_app.c", "sokol_gfx.c", "sokol_time.c", "sokol_audio.c", }; if (lib.target.isDarwin()) { inline for (csources) |csrc| { lib.addCSourceFile(sokol_path ++ csrc, &[_][]const u8{"-ObjC", "-DIMPL"}); } lib.linkFramework("MetalKit"); lib.linkFramework("Metal"); lib.linkFramework("Cocoa"); lib.linkFramework("QuartzCore"); lib.linkFramework("AudioToolbox"); } else { inline for (csources) |csrc| { lib.addCSourceFile(sokol_path ++ csrc, &[_][]const u8{"-DIMPL"}); } if (lib.target.isLinux()) { lib.linkSystemLibrary("X11"); lib.linkSystemLibrary("Xi"); lib.linkSystemLibrary("Xcursor"); lib.linkSystemLibrary("GL"); lib.linkSystemLibrary("asound"); } else if (lib.target.isWindows()) { lib.linkSystemLibrary("kernel32"); lib.linkSystemLibrary("user32"); lib.linkSystemLibrary("gdi32"); lib.linkSystemLibrary("ole32"); lib.linkSystemLibrary("d3d11"); lib.linkSystemLibrary("dxgi"); } } return lib; }
build.zig
const sokol = @import("sokol"); const sg = sokol.gfx; const sapp = sokol.app; const sgapp = sokol.app_gfx_glue; const shd = @import("shaders/shaders.glsl.zig"); const KC85DisplayWidth = 320; const KC85DisplayHeight = 256; const KC85NumPixels = KC85DisplayWidth * KC85DisplayHeight; const BorderWidth = 10; const BorderHeight = 10; pub const WindowWidth = 2 * KC85DisplayWidth + 2 * BorderWidth; pub const WindowHeight = 2 * KC85DisplayHeight + 2 * BorderHeight; pub var pixel_buffer: [KC85NumPixels]u32 = undefined; const state = struct { const upscale = struct { var pip: sg.Pipeline = .{ }; var bind: sg.Bindings = .{ }; var pass: sg.Pass = .{ }; var pass_action: sg.PassAction = .{ }; }; const display = struct { var pip: sg.Pipeline = .{ }; var bind: sg.Bindings = .{ }; var pass_action: sg.PassAction = .{ }; }; }; pub fn setup() void { // setup sokol-gfx and sokol-text sg.setup(.{ .buffer_pool_size = 8, .image_pool_size = 8, .shader_pool_size = 8, .pipeline_pool_size = 8, .context_pool_size = 1, .context = sgapp.context(), }); state.upscale.pass_action.colors[0] = .{ .action = .DONTCARE }; state.display.pass_action.colors[0] = .{ .action = .CLEAR, .value = .{ .r=0.05, .g=0.05, .b=0.05, .a=1.0 } }; // fullscreen triangle vertices const verts = [_]f32{ 0.0, 0.0, 2.0, 0.0, 0.0, 2.0, }; state.upscale.bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(verts) }); state.display.bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(verts) }); // 2 pipeline state objects for rendering to display and upscaling var pip_desc = sg.PipelineDesc{ .shader = sg.makeShader(shd.displayShaderDesc(sg.queryBackend())), }; pip_desc.layout.attrs[0].format = .FLOAT2; state.display.pip = sg.makePipeline(pip_desc); pip_desc.shader = sg.makeShader(shd.upscaleShaderDesc(sg.queryBackend())); pip_desc.depth.pixel_format = .NONE; state.upscale.pip = sg.makePipeline(pip_desc); // a texture with the emulator's raw pixel data state.upscale.bind.fs_images[0] = sg.makeImage(.{ .width = KC85DisplayWidth, .height = KC85DisplayHeight, .pixel_format = .RGBA8, .usage = .STREAM, .min_filter = .NEAREST, .mag_filter = .NEAREST, .wrap_u = .CLAMP_TO_EDGE, .wrap_v = .CLAMP_TO_EDGE }); // a 2x upscaled render target texture state.display.bind.fs_images[0] = sg.makeImage(.{ .render_target = true, .width = 2 * KC85DisplayWidth, .height = 2 * KC85DisplayHeight, .min_filter = .LINEAR, .mag_filter = .LINEAR, .wrap_u = .CLAMP_TO_EDGE, .wrap_v = .CLAMP_TO_EDGE }); // a render pass for 2x upscaling var pass_desc = sg.PassDesc{ }; pass_desc.color_attachments[0].image = state.display.bind.fs_images[0]; state.upscale.pass = sg.makePass(pass_desc); } pub fn shutdown() void { sg.shutdown(); } pub fn draw() void { // copy emulator pixel data into upscaling source texture var image_data = sg.ImageData{ }; image_data.subimage[0][0] = sg.asRange(pixel_buffer); sg.updateImage(state.upscale.bind.fs_images[0], image_data); // upscale the source texture 2x with nearest filtering sg.beginPass(state.upscale.pass, state.upscale.pass_action); sg.applyPipeline(state.upscale.pip); sg.applyBindings(state.upscale.bind); sg.draw(0, 3, 1); sg.endPass(); // draw the display pass with linear filtering const w = sapp.widthf(); const h = sapp.heightf(); sg.beginDefaultPassf(state.display.pass_action, w, h); applyViewport(w, h); sg.applyPipeline(state.display.pip); sg.applyBindings(state.display.bind); sg.draw(0, 3, 1); sg.applyViewportf(0, 0, w, h, true); sg.endPass(); sg.commit(); } fn applyViewport(canvas_width: f32, canvas_height: f32) void { const canvas_aspect = canvas_width / canvas_height; const fb_aspect = @as(f32, KC85DisplayWidth) / @as(f32, KC85DisplayHeight); const frame_x = @as(f32, BorderWidth); const frame_y = @as(f32, BorderHeight); var vp_x: f32 = 0.0; var vp_y: f32 = 0.0; var vp_w: f32 = 0.0; var vp_h: f32 = 0.0; if (fb_aspect < canvas_aspect) { vp_y = frame_y; vp_h = canvas_height - (2.0 * frame_y); vp_w = (canvas_height * fb_aspect) - (2.0 * frame_x); vp_x = (canvas_width - vp_w) / 2.0; } else { vp_x = frame_x; vp_w = canvas_width - (2.0 * frame_x); vp_h = (canvas_width / fb_aspect) - (2.0 * frame_y); vp_y = frame_y; } sg.applyViewportf(vp_x, vp_y, vp_w, vp_h, true); }
src/host/gfx.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); pub const syscall_bits = switch (builtin.stage2_arch) { .x86_64 => @import("plan9/x86_64.zig"), else => @compileError("more plan9 syscall implementations (needs more inline asm in stage2"), }; pub const SYS = enum(usize) { SYSR1 = 0, _ERRSTR = 1, BIND = 2, CHDIR = 3, CLOSE = 4, DUP = 5, ALARM = 6, EXEC = 7, EXITS = 8, _FSESSION = 9, FAUTH = 10, _FSTAT = 11, SEGBRK = 12, _MOUNT = 13, OPEN = 14, _READ = 15, OSEEK = 16, SLEEP = 17, _STAT = 18, RFORK = 19, _WRITE = 20, PIPE = 21, CREATE = 22, FD2PATH = 23, BRK_ = 24, REMOVE = 25, _WSTAT = 26, _FWSTAT = 27, NOTIFY = 28, NOTED = 29, SEGATTACH = 30, SEGDETACH = 31, SEGFREE = 32, SEGFLUSH = 33, RENDEZVOUS = 34, UNMOUNT = 35, _WAIT = 36, SEMACQUIRE = 37, SEMRELEASE = 38, SEEK = 39, FVERSION = 40, ERRSTR = 41, STAT = 42, FSTAT = 43, WSTAT = 44, FWSTAT = 45, MOUNT = 46, AWAIT = 47, PREAD = 50, PWRITE = 51, TSEMACQUIRE = 52, _NSEC = 53, }; pub fn pwrite(fd: usize, buf: [*]const u8, count: usize, offset: usize) usize { return syscall_bits.syscall4(.PWRITE, fd, @ptrToInt(buf), count, offset); } pub fn open(path: [*:0]const u8, omode: OpenMode) usize { return syscall_bits.syscall2(.OPEN, @ptrToInt(path), @enumToInt(omode)); } pub fn create(path: [*:0]const u8, omode: OpenMode, perms: usize) usize { return syscall_bits.syscall3(.CREATE, @ptrToInt(path), @enumToInt(omode), perms); } pub fn exits(status: ?[*:0]const u8) void { _ = syscall_bits.syscall1(.EXITS, if (status) |s| @ptrToInt(s) else 0); } pub fn close(fd: usize) usize { return syscall_bits.syscall1(.CLOSE, fd); } pub const OpenMode = enum(usize) { OREAD = 0, //* open for read OWRITE = 1, //* write ORDWR = 2, //* read and write OEXEC = 3, //* execute, == read but check execute permission OTRUNC = 16, //* or'ed in (except for exec), truncate file first OCEXEC = 32, //* or'ed in (per file descriptor), close on exec ORCLOSE = 64, //* or'ed in, remove on close OEXCL = 0x1000, //* or'ed in, exclusive create };
lib/std/os/plan9.zig
const std = @import("std.zig"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const mem = std.mem; const maxInt = std.math.maxInt; pub const WriteStream = @import("json/write_stream.zig").WriteStream; pub const writeStream = @import("json/write_stream.zig").writeStream; const StringEscapes = union(enum) { None, Some: struct { size_diff: isize, }, }; /// Checks to see if a string matches what it would be as a json-encoded string /// Assumes that `encoded` is a well-formed json string fn encodesTo(decoded: []const u8, encoded: []const u8) bool { var i: usize = 0; var j: usize = 0; while (i < decoded.len) { if (j >= encoded.len) return false; if (encoded[j] != '\\') { if (decoded[i] != encoded[j]) return false; j += 1; i += 1; } else { const escape_type = encoded[j + 1]; if (escape_type != 'u') { const t: u8 = switch (escape_type) { '\\' => '\\', '/' => '/', 'n' => '\n', 'r' => '\r', 't' => '\t', 'f' => 12, 'b' => 8, '"' => '"', else => unreachable, }; if (decoded[i] != t) return false; j += 2; i += 1; } else { var codepoint = std.fmt.parseInt(u21, encoded[j + 2 .. j + 6], 16) catch unreachable; j += 6; if (codepoint >= 0xD800 and codepoint < 0xDC00) { // surrogate pair assert(encoded[j] == '\\'); assert(encoded[j + 1] == 'u'); const low_surrogate = std.fmt.parseInt(u21, encoded[j + 2 .. j + 6], 16) catch unreachable; codepoint = 0x10000 + (((codepoint & 0x03ff) << 10) | (low_surrogate & 0x03ff)); j += 6; } var buf: [4]u8 = undefined; const len = std.unicode.utf8Encode(codepoint, &buf) catch unreachable; if (i + len > decoded.len) return false; if (!mem.eql(u8, decoded[i .. i + len], buf[0..len])) return false; i += len; } } } assert(i == decoded.len); assert(j == encoded.len); return true; } test "encodesTo" { // same testing.expectEqual(true, encodesTo("false", "false")); // totally different testing.expectEqual(false, encodesTo("false", "true")); // different lengths testing.expectEqual(false, encodesTo("false", "other")); // with escape testing.expectEqual(true, encodesTo("\\", "\\\\")); testing.expectEqual(true, encodesTo("with\nescape", "with\\nescape")); // with unicode testing.expectEqual(true, encodesTo("ą", "\\u0105")); testing.expectEqual(true, encodesTo("😂", "\\ud83d\\ude02")); testing.expectEqual(true, encodesTo("withąunicode😂", "with\\u0105unicode\\ud83d\\ude02")); } /// A single token slice into the parent string. /// /// Use `token.slice()` on the input at the current position to get the current slice. pub const Token = union(enum) { ObjectBegin, ObjectEnd, ArrayBegin, ArrayEnd, String: struct { /// How many bytes the token is. count: usize, /// Whether string contains an escape sequence and cannot be zero-copied escapes: StringEscapes, pub fn decodedLength(self: @This()) usize { return self.count +% switch (self.escapes) { .None => 0, .Some => |s| @bitCast(usize, s.size_diff), }; } /// Slice into the underlying input string. pub fn slice(self: @This(), input: []const u8, i: usize) []const u8 { return input[i - self.count .. i]; } }, Number: struct { /// How many bytes the token is. count: usize, /// Whether number is simple and can be represented by an integer (i.e. no `.` or `e`) is_integer: bool, /// Slice into the underlying input string. pub fn slice(self: @This(), input: []const u8, i: usize) []const u8 { return input[i - self.count .. i]; } }, True, False, Null, }; /// A small streaming JSON parser. This accepts input one byte at a time and returns tokens as /// they are encountered. No copies or allocations are performed during parsing and the entire /// parsing state requires ~40-50 bytes of stack space. /// /// Conforms strictly to RFC8259. /// /// For a non-byte based wrapper, consider using TokenStream instead. pub const StreamingParser = struct { // Current state state: State, // How many bytes we have counted for the current token count: usize, // What state to follow after parsing a string (either property or value string) after_string_state: State, // What state to follow after parsing a value (either top-level or value end) after_value_state: State, // If we stopped now, would the complete parsed string to now be a valid json string complete: bool, // Current token flags to pass through to the next generated, see Token. string_escapes: StringEscapes, // When in .String states, was the previous character a high surrogate? string_last_was_high_surrogate: bool, // Used inside of StringEscapeHexUnicode* states string_unicode_codepoint: u21, // The first byte needs to be stored to validate 3- and 4-byte sequences. sequence_first_byte: u8 = undefined, // When in .Number states, is the number a (still) valid integer? number_is_integer: bool, // Bit-stack for nested object/map literals (max 255 nestings). stack: u256, stack_used: u8, const object_bit = 0; const array_bit = 1; const max_stack_size = maxInt(u8); pub fn init() StreamingParser { var p: StreamingParser = undefined; p.reset(); return p; } pub fn reset(p: *StreamingParser) void { p.state = .TopLevelBegin; p.count = 0; // Set before ever read in main transition function p.after_string_state = undefined; p.after_value_state = .ValueEnd; // handle end of values normally p.stack = 0; p.stack_used = 0; p.complete = false; p.string_escapes = undefined; p.string_last_was_high_surrogate = undefined; p.string_unicode_codepoint = undefined; p.number_is_integer = undefined; } pub const State = enum { // These must be first with these explicit values as we rely on them for indexing the // bit-stack directly and avoiding a branch. ObjectSeparator = 0, ValueEnd = 1, TopLevelBegin, TopLevelEnd, ValueBegin, ValueBeginNoClosing, String, StringUtf8Byte2Of2, StringUtf8Byte2Of3, StringUtf8Byte3Of3, StringUtf8Byte2Of4, StringUtf8Byte3Of4, StringUtf8Byte4Of4, StringEscapeCharacter, StringEscapeHexUnicode4, StringEscapeHexUnicode3, StringEscapeHexUnicode2, StringEscapeHexUnicode1, Number, NumberMaybeDotOrExponent, NumberMaybeDigitOrDotOrExponent, NumberFractionalRequired, NumberFractional, NumberMaybeExponent, NumberExponent, NumberExponentDigitsRequired, NumberExponentDigits, TrueLiteral1, TrueLiteral2, TrueLiteral3, FalseLiteral1, FalseLiteral2, FalseLiteral3, FalseLiteral4, NullLiteral1, NullLiteral2, NullLiteral3, // Only call this function to generate array/object final state. pub fn fromInt(x: anytype) State { debug.assert(x == 0 or x == 1); const T = @TagType(State); return @intToEnum(State, @intCast(T, x)); } }; pub const Error = error{ InvalidTopLevel, TooManyNestedItems, TooManyClosingItems, InvalidValueBegin, InvalidValueEnd, UnbalancedBrackets, UnbalancedBraces, UnexpectedClosingBracket, UnexpectedClosingBrace, InvalidNumber, InvalidSeparator, InvalidLiteral, InvalidEscapeCharacter, InvalidUnicodeHexSymbol, InvalidUtf8Byte, InvalidTopLevelTrailing, InvalidControlCharacter, }; /// Give another byte to the parser and obtain any new tokens. This may (rarely) return two /// tokens. token2 is always null if token1 is null. /// /// There is currently no error recovery on a bad stream. pub fn feed(p: *StreamingParser, c: u8, token1: *?Token, token2: *?Token) Error!void { token1.* = null; token2.* = null; p.count += 1; // unlikely if (try p.transition(c, token1)) { _ = try p.transition(c, token2); } } // Perform a single transition on the state machine and return any possible token. fn transition(p: *StreamingParser, c: u8, token: *?Token) Error!bool { switch (p.state) { .TopLevelBegin => switch (c) { '{' => { p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ObjectSeparator; token.* = Token.ObjectBegin; }, '[' => { p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ValueEnd; token.* = Token.ArrayBegin; }, '-' => { p.number_is_integer = true; p.state = .Number; p.after_value_state = .TopLevelEnd; p.count = 0; }, '0' => { p.number_is_integer = true; p.state = .NumberMaybeDotOrExponent; p.after_value_state = .TopLevelEnd; p.count = 0; }, '1'...'9' => { p.number_is_integer = true; p.state = .NumberMaybeDigitOrDotOrExponent; p.after_value_state = .TopLevelEnd; p.count = 0; }, '"' => { p.state = .String; p.after_value_state = .TopLevelEnd; // We don't actually need the following since after_value_state should override. p.after_string_state = .ValueEnd; p.string_escapes = .None; p.string_last_was_high_surrogate = false; p.count = 0; }, 't' => { p.state = .TrueLiteral1; p.after_value_state = .TopLevelEnd; p.count = 0; }, 'f' => { p.state = .FalseLiteral1; p.after_value_state = .TopLevelEnd; p.count = 0; }, 'n' => { p.state = .NullLiteral1; p.after_value_state = .TopLevelEnd; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidTopLevel; }, }, .TopLevelEnd => switch (c) { 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidTopLevelTrailing; }, }, .ValueBegin => switch (c) { // NOTE: These are shared in ValueEnd as well, think we can reorder states to // be a bit clearer and avoid this duplication. '}' => { // unlikely if (p.stack & 1 != object_bit) { return error.UnexpectedClosingBrace; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = .ValueBegin; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; switch (p.stack_used) { 0 => { p.complete = true; p.state = .TopLevelEnd; }, else => { p.state = .ValueEnd; }, } token.* = Token.ObjectEnd; }, ']' => { if (p.stack & 1 != array_bit) { return error.UnexpectedClosingBracket; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = .ValueBegin; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; switch (p.stack_used) { 0 => { p.complete = true; p.state = .TopLevelEnd; }, else => { p.state = .ValueEnd; }, } token.* = Token.ArrayEnd; }, '{' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ObjectSeparator; token.* = Token.ObjectBegin; }, '[' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ValueEnd; token.* = Token.ArrayBegin; }, '-' => { p.number_is_integer = true; p.state = .Number; p.count = 0; }, '0' => { p.number_is_integer = true; p.state = .NumberMaybeDotOrExponent; p.count = 0; }, '1'...'9' => { p.number_is_integer = true; p.state = .NumberMaybeDigitOrDotOrExponent; p.count = 0; }, '"' => { p.state = .String; p.string_escapes = .None; p.string_last_was_high_surrogate = false; p.count = 0; }, 't' => { p.state = .TrueLiteral1; p.count = 0; }, 'f' => { p.state = .FalseLiteral1; p.count = 0; }, 'n' => { p.state = .NullLiteral1; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueBegin; }, }, // TODO: A bit of duplication here and in the following state, redo. .ValueBeginNoClosing => switch (c) { '{' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ObjectSeparator; token.* = Token.ObjectBegin; }, '[' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = .ValueBegin; p.after_string_state = .ValueEnd; token.* = Token.ArrayBegin; }, '-' => { p.number_is_integer = true; p.state = .Number; p.count = 0; }, '0' => { p.number_is_integer = true; p.state = .NumberMaybeDotOrExponent; p.count = 0; }, '1'...'9' => { p.number_is_integer = true; p.state = .NumberMaybeDigitOrDotOrExponent; p.count = 0; }, '"' => { p.state = .String; p.string_escapes = .None; p.string_last_was_high_surrogate = false; p.count = 0; }, 't' => { p.state = .TrueLiteral1; p.count = 0; }, 'f' => { p.state = .FalseLiteral1; p.count = 0; }, 'n' => { p.state = .NullLiteral1; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueBegin; }, }, .ValueEnd => switch (c) { ',' => { p.after_string_state = State.fromInt(p.stack & 1); p.state = .ValueBeginNoClosing; }, ']' => { if (p.stack & 1 != array_bit) { return error.UnexpectedClosingBracket; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = .ValueEnd; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; if (p.stack_used == 0) { p.complete = true; p.state = .TopLevelEnd; } token.* = Token.ArrayEnd; }, '}' => { // unlikely if (p.stack & 1 != object_bit) { return error.UnexpectedClosingBrace; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = .ValueEnd; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; if (p.stack_used == 0) { p.complete = true; p.state = .TopLevelEnd; } token.* = Token.ObjectEnd; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueEnd; }, }, .ObjectSeparator => switch (c) { ':' => { p.state = .ValueBegin; p.after_string_state = .ValueEnd; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidSeparator; }, }, .String => switch (c) { 0x00...0x1F => { return error.InvalidControlCharacter; }, '"' => { p.state = p.after_string_state; if (p.after_value_state == .TopLevelEnd) { p.state = .TopLevelEnd; p.complete = true; } token.* = .{ .String = .{ .count = p.count - 1, .escapes = p.string_escapes, }, }; p.string_escapes = undefined; p.string_last_was_high_surrogate = undefined; }, '\\' => { p.state = .StringEscapeCharacter; switch (p.string_escapes) { .None => { p.string_escapes = .{ .Some = .{ .size_diff = 0 } }; }, .Some => {}, } }, 0x20, 0x21, 0x23...0x5B, 0x5D...0x7F => { // non-control ascii p.string_last_was_high_surrogate = false; }, 0xC2...0xDF => { p.state = .StringUtf8Byte2Of2; }, 0xE0...0xEF => { p.state = .StringUtf8Byte2Of3; p.sequence_first_byte = c; }, 0xF0...0xF4 => { p.state = .StringUtf8Byte2Of4; p.sequence_first_byte = c; }, else => { return error.InvalidUtf8Byte; }, }, .StringUtf8Byte2Of2 => switch (c >> 6) { 0b10 => p.state = .String, else => return error.InvalidUtf8Byte, }, .StringUtf8Byte2Of3 => { switch (p.sequence_first_byte) { 0xE0 => switch (c) { 0xA0...0xBF => {}, else => return error.InvalidUtf8Byte, }, 0xE1...0xEF => switch (c) { 0x80...0xBF => {}, else => return error.InvalidUtf8Byte, }, else => return error.InvalidUtf8Byte, } p.state = .StringUtf8Byte3Of3; }, .StringUtf8Byte3Of3 => switch (c) { 0x80...0xBF => p.state = .String, else => return error.InvalidUtf8Byte, }, .StringUtf8Byte2Of4 => { switch (p.sequence_first_byte) { 0xF0 => switch (c) { 0x90...0xBF => {}, else => return error.InvalidUtf8Byte, }, 0xF1...0xF3 => switch (c) { 0x80...0xBF => {}, else => return error.InvalidUtf8Byte, }, 0xF4 => switch (c) { 0x80...0x8F => {}, else => return error.InvalidUtf8Byte, }, else => return error.InvalidUtf8Byte, } p.state = .StringUtf8Byte3Of4; }, .StringUtf8Byte3Of4 => switch (c) { 0x80...0xBF => p.state = .StringUtf8Byte4Of4, else => return error.InvalidUtf8Byte, }, .StringUtf8Byte4Of4 => switch (c) { 0x80...0xBF => p.state = .String, else => return error.InvalidUtf8Byte, }, .StringEscapeCharacter => switch (c) { // NOTE: '/' is allowed as an escaped character but it also is allowed // as unescaped according to the RFC. There is a reported errata which suggests // removing the non-escaped variant but it makes more sense to simply disallow // it as an escape code here. // // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { p.string_escapes.Some.size_diff -= 1; p.state = .String; p.string_last_was_high_surrogate = false; }, 'u' => { p.state = .StringEscapeHexUnicode4; }, else => { return error.InvalidEscapeCharacter; }, }, .StringEscapeHexUnicode4 => { var codepoint: u21 = undefined; switch (c) { else => return error.InvalidUnicodeHexSymbol, '0'...'9' => { codepoint = c - '0'; }, 'A'...'F' => { codepoint = c - 'A' + 10; }, 'a'...'f' => { codepoint = c - 'a' + 10; }, } p.state = .StringEscapeHexUnicode3; p.string_unicode_codepoint = codepoint << 12; }, .StringEscapeHexUnicode3 => { var codepoint: u21 = undefined; switch (c) { else => return error.InvalidUnicodeHexSymbol, '0'...'9' => { codepoint = c - '0'; }, 'A'...'F' => { codepoint = c - 'A' + 10; }, 'a'...'f' => { codepoint = c - 'a' + 10; }, } p.state = .StringEscapeHexUnicode2; p.string_unicode_codepoint |= codepoint << 8; }, .StringEscapeHexUnicode2 => { var codepoint: u21 = undefined; switch (c) { else => return error.InvalidUnicodeHexSymbol, '0'...'9' => { codepoint = c - '0'; }, 'A'...'F' => { codepoint = c - 'A' + 10; }, 'a'...'f' => { codepoint = c - 'a' + 10; }, } p.state = .StringEscapeHexUnicode1; p.string_unicode_codepoint |= codepoint << 4; }, .StringEscapeHexUnicode1 => { var codepoint: u21 = undefined; switch (c) { else => return error.InvalidUnicodeHexSymbol, '0'...'9' => { codepoint = c - '0'; }, 'A'...'F' => { codepoint = c - 'A' + 10; }, 'a'...'f' => { codepoint = c - 'a' + 10; }, } p.state = .String; p.string_unicode_codepoint |= codepoint; if (p.string_unicode_codepoint < 0xD800 or p.string_unicode_codepoint >= 0xE000) { // not part of surrogate pair p.string_escapes.Some.size_diff -= @as(isize, 6 - (std.unicode.utf8CodepointSequenceLength(p.string_unicode_codepoint) catch unreachable)); p.string_last_was_high_surrogate = false; } else if (p.string_unicode_codepoint < 0xDC00) { // 'high' surrogate // takes 3 bytes to encode a half surrogate pair into wtf8 p.string_escapes.Some.size_diff -= 6 - 3; p.string_last_was_high_surrogate = true; } else { // 'low' surrogate p.string_escapes.Some.size_diff -= 6; if (p.string_last_was_high_surrogate) { // takes 4 bytes to encode a full surrogate pair into utf8 // 3 bytes are already reserved by high surrogate p.string_escapes.Some.size_diff -= -1; } else { // takes 3 bytes to encode a half surrogate pair into wtf8 p.string_escapes.Some.size_diff -= -3; } p.string_last_was_high_surrogate = false; } p.string_unicode_codepoint = undefined; }, .Number => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '0' => { p.state = .NumberMaybeDotOrExponent; }, '1'...'9' => { p.state = .NumberMaybeDigitOrDotOrExponent; }, else => { return error.InvalidNumber; }, } }, .NumberMaybeDotOrExponent => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '.' => { p.number_is_integer = false; p.state = .NumberFractionalRequired; }, 'e', 'E' => { p.number_is_integer = false; p.state = .NumberExponent; }, else => { p.state = p.after_value_state; token.* = .{ .Number = .{ .count = p.count, .is_integer = p.number_is_integer, }, }; p.number_is_integer = undefined; return true; }, } }, .NumberMaybeDigitOrDotOrExponent => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '.' => { p.number_is_integer = false; p.state = .NumberFractionalRequired; }, 'e', 'E' => { p.number_is_integer = false; p.state = .NumberExponent; }, '0'...'9' => { // another digit }, else => { p.state = p.after_value_state; token.* = .{ .Number = .{ .count = p.count, .is_integer = p.number_is_integer, }, }; return true; }, } }, .NumberFractionalRequired => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '0'...'9' => { p.state = .NumberFractional; }, else => { return error.InvalidNumber; }, } }, .NumberFractional => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '0'...'9' => { // another digit }, 'e', 'E' => { p.number_is_integer = false; p.state = .NumberExponent; }, else => { p.state = p.after_value_state; token.* = .{ .Number = .{ .count = p.count, .is_integer = p.number_is_integer, }, }; return true; }, } }, .NumberMaybeExponent => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { 'e', 'E' => { p.number_is_integer = false; p.state = .NumberExponent; }, else => { p.state = p.after_value_state; token.* = .{ .Number = .{ .count = p.count, .is_integer = p.number_is_integer, }, }; return true; }, } }, .NumberExponent => switch (c) { '-', '+' => { p.complete = false; p.state = .NumberExponentDigitsRequired; }, '0'...'9' => { p.complete = p.after_value_state == .TopLevelEnd; p.state = .NumberExponentDigits; }, else => { return error.InvalidNumber; }, }, .NumberExponentDigitsRequired => switch (c) { '0'...'9' => { p.complete = p.after_value_state == .TopLevelEnd; p.state = .NumberExponentDigits; }, else => { return error.InvalidNumber; }, }, .NumberExponentDigits => { p.complete = p.after_value_state == .TopLevelEnd; switch (c) { '0'...'9' => { // another digit }, else => { p.state = p.after_value_state; token.* = .{ .Number = .{ .count = p.count, .is_integer = p.number_is_integer, }, }; return true; }, } }, .TrueLiteral1 => switch (c) { 'r' => p.state = .TrueLiteral2, else => return error.InvalidLiteral, }, .TrueLiteral2 => switch (c) { 'u' => p.state = .TrueLiteral3, else => return error.InvalidLiteral, }, .TrueLiteral3 => switch (c) { 'e' => { p.state = p.after_value_state; p.complete = p.state == .TopLevelEnd; token.* = Token.True; }, else => { return error.InvalidLiteral; }, }, .FalseLiteral1 => switch (c) { 'a' => p.state = .FalseLiteral2, else => return error.InvalidLiteral, }, .FalseLiteral2 => switch (c) { 'l' => p.state = .FalseLiteral3, else => return error.InvalidLiteral, }, .FalseLiteral3 => switch (c) { 's' => p.state = .FalseLiteral4, else => return error.InvalidLiteral, }, .FalseLiteral4 => switch (c) { 'e' => { p.state = p.after_value_state; p.complete = p.state == .TopLevelEnd; token.* = Token.False; }, else => { return error.InvalidLiteral; }, }, .NullLiteral1 => switch (c) { 'u' => p.state = .NullLiteral2, else => return error.InvalidLiteral, }, .NullLiteral2 => switch (c) { 'l' => p.state = .NullLiteral3, else => return error.InvalidLiteral, }, .NullLiteral3 => switch (c) { 'l' => { p.state = p.after_value_state; p.complete = p.state == .TopLevelEnd; token.* = Token.Null; }, else => { return error.InvalidLiteral; }, }, } return false; } }; /// A small wrapper over a StreamingParser for full slices. Returns a stream of json Tokens. pub const TokenStream = struct { i: usize, slice: []const u8, parser: StreamingParser, token: ?Token, pub const Error = StreamingParser.Error || error{UnexpectedEndOfJson}; pub fn init(slice: []const u8) TokenStream { return TokenStream{ .i = 0, .slice = slice, .parser = StreamingParser.init(), .token = null, }; } pub fn next(self: *TokenStream) Error!?Token { if (self.token) |token| { self.token = null; return token; } var t1: ?Token = undefined; var t2: ?Token = undefined; while (self.i < self.slice.len) { try self.parser.feed(self.slice[self.i], &t1, &t2); self.i += 1; if (t1) |token| { self.token = t2; return token; } } // Without this a bare number fails, the streaming parser doesn't know the input ended try self.parser.feed(' ', &t1, &t2); self.i += 1; if (t1) |token| { return token; } else if (self.parser.complete) { return null; } else { return error.UnexpectedEndOfJson; } } }; fn checkNext(p: *TokenStream, id: std.meta.TagType(Token)) void { const token = (p.next() catch unreachable).?; debug.assert(std.meta.activeTag(token) == id); } test "json.token" { const s = \\{ \\ "Image": { \\ "Width": 800, \\ "Height": 600, \\ "Title": "View from 15th Floor", \\ "Thumbnail": { \\ "Url": "http://www.example.com/image/481989943", \\ "Height": 125, \\ "Width": 100 \\ }, \\ "Animated" : false, \\ "IDs": [116, 943, 234, 38793] \\ } \\} ; var p = TokenStream.init(s); checkNext(&p, .ObjectBegin); checkNext(&p, .String); // Image checkNext(&p, .ObjectBegin); checkNext(&p, .String); // Width checkNext(&p, .Number); checkNext(&p, .String); // Height checkNext(&p, .Number); checkNext(&p, .String); // Title checkNext(&p, .String); checkNext(&p, .String); // Thumbnail checkNext(&p, .ObjectBegin); checkNext(&p, .String); // Url checkNext(&p, .String); checkNext(&p, .String); // Height checkNext(&p, .Number); checkNext(&p, .String); // Width checkNext(&p, .Number); checkNext(&p, .ObjectEnd); checkNext(&p, .String); // Animated checkNext(&p, .False); checkNext(&p, .String); // IDs checkNext(&p, .ArrayBegin); checkNext(&p, .Number); checkNext(&p, .Number); checkNext(&p, .Number); checkNext(&p, .Number); checkNext(&p, .ArrayEnd); checkNext(&p, .ObjectEnd); checkNext(&p, .ObjectEnd); testing.expect((try p.next()) == null); } test "json.token mismatched close" { var p = TokenStream.init("[102, 111, 111 }"); checkNext(&p, .ArrayBegin); checkNext(&p, .Number); checkNext(&p, .Number); checkNext(&p, .Number); testing.expectError(error.UnexpectedClosingBrace, p.next()); } /// Validate a JSON string. This does not limit number precision so a decoder may not necessarily /// be able to decode the string even if this returns true. pub fn validate(s: []const u8) bool { var p = StreamingParser.init(); for (s) |c, i| { var token1: ?Token = undefined; var token2: ?Token = undefined; p.feed(c, &token1, &token2) catch |err| { return false; }; } return p.complete; } test "json.validate" { testing.expectEqual(true, validate("{}")); testing.expectEqual(true, validate("[]")); testing.expectEqual(true, validate("[{[[[[{}]]]]}]")); testing.expectEqual(false, validate("{]")); testing.expectEqual(false, validate("[}")); testing.expectEqual(false, validate("{{{{[]}}}]")); } const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const StringHashMap = std.StringHashMap; pub const ValueTree = struct { arena: ArenaAllocator, root: Value, pub fn deinit(self: *ValueTree) void { self.arena.deinit(); } }; pub const ObjectMap = StringHashMap(Value); pub const Array = ArrayList(Value); /// Represents a JSON value /// Currently only supports numbers that fit into i64 or f64. pub const Value = union(enum) { Null, Bool: bool, Integer: i64, Float: f64, String: []const u8, Array: Array, Object: ObjectMap, pub fn jsonStringify( value: @This(), options: StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { switch (value) { .Null => try stringify(null, options, out_stream), .Bool => |inner| try stringify(inner, options, out_stream), .Integer => |inner| try stringify(inner, options, out_stream), .Float => |inner| try stringify(inner, options, out_stream), .String => |inner| try stringify(inner, options, out_stream), .Array => |inner| try stringify(inner.items, options, out_stream), .Object => |inner| { try out_stream.writeByte('{'); var field_output = false; var child_options = options; if (child_options.whitespace) |*child_whitespace| { child_whitespace.indent_level += 1; } var it = inner.iterator(); while (it.next()) |entry| { if (!field_output) { field_output = true; } else { try out_stream.writeByte(','); } if (child_options.whitespace) |child_whitespace| { try out_stream.writeByte('\n'); try child_whitespace.outputIndent(out_stream); } try stringify(entry.key, options, out_stream); try out_stream.writeByte(':'); if (child_options.whitespace) |child_whitespace| { if (child_whitespace.separator) { try out_stream.writeByte(' '); } } try stringify(entry.value, child_options, out_stream); } if (field_output) { if (options.whitespace) |whitespace| { try out_stream.writeByte('\n'); try whitespace.outputIndent(out_stream); } } try out_stream.writeByte('}'); }, } } pub fn dump(self: Value) void { var held = std.debug.getStderrMutex().acquire(); defer held.release(); const stderr = std.io.getStdErr().writer(); std.json.stringify(self, std.json.StringifyOptions{ .whitespace = null }, stderr) catch return; } }; test "Value.jsonStringify" { { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try @as(Value, .Null).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "null"); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try (Value{ .Bool = true }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "true"); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try (Value{ .Integer = 42 }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "42"); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try (Value{ .Float = 42 }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01"); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try (Value{ .String = "weeee" }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\""); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); var vals = [_]Value{ .{ .Integer = 1 }, .{ .Integer = 2 }, .{ .Integer = 3 }, }; try (Value{ .Array = Array.fromOwnedSlice(undefined, &vals), }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]"); } { var buffer: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); var obj = ObjectMap.init(testing.allocator); defer obj.deinit(); try obj.putNoClobber("a", .{ .String = "b" }); try (Value{ .Object = obj }).jsonStringify(.{}, fbs.outStream()); testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}"); } } pub const ParseOptions = struct { allocator: ?*Allocator = null, /// Behaviour when a duplicate field is encountered. duplicate_field_behavior: enum { UseFirst, Error, UseLast, } = .Error, }; fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options: ParseOptions) !T { switch (@typeInfo(T)) { .Bool => { return switch (token) { .True => true, .False => false, else => error.UnexpectedToken, }; }, .Float, .ComptimeFloat => { const numberToken = switch (token) { .Number => |n| n, else => return error.UnexpectedToken, }; return try std.fmt.parseFloat(T, numberToken.slice(tokens.slice, tokens.i - 1)); }, .Int, .ComptimeInt => { const numberToken = switch (token) { .Number => |n| n, else => return error.UnexpectedToken, }; if (!numberToken.is_integer) return error.UnexpectedToken; return try std.fmt.parseInt(T, numberToken.slice(tokens.slice, tokens.i - 1), 10); }, .Optional => |optionalInfo| { if (token == .Null) { return null; } else { return try parseInternal(optionalInfo.child, token, tokens, options); } }, .Enum => |enumInfo| { switch (token) { .Number => |numberToken| { if (!numberToken.is_integer) return error.UnexpectedToken; const n = try std.fmt.parseInt(enumInfo.tag_type, numberToken.slice(tokens.slice, tokens.i - 1), 10); return try std.meta.intToEnum(T, n); }, .String => |stringToken| { const source_slice = stringToken.slice(tokens.slice, tokens.i - 1); switch (stringToken.escapes) { .None => return std.meta.stringToEnum(T, source_slice) orelse return error.InvalidEnumTag, .Some => { inline for (enumInfo.fields) |field| { if (field.name.len == stringToken.decodedLength() and encodesTo(field.name, source_slice)) { return @field(T, field.name); } } return error.InvalidEnumTag; }, } }, else => return error.UnexpectedToken, } }, .Union => |unionInfo| { if (unionInfo.tag_type) |_| { // try each of the union fields until we find one that matches inline for (unionInfo.fields) |u_field| { // take a copy of tokens so we can withhold mutations until success var tokens_copy = tokens.*; if (parseInternal(u_field.field_type, token, &tokens_copy, options)) |value| { tokens.* = tokens_copy; return @unionInit(T, u_field.name, value); } else |err| { // Bubble up error.OutOfMemory // Parsing some types won't have OutOfMemory in their // error-sets, for the condition to be valid, merge it in. if (@as(@TypeOf(err) || error{OutOfMemory}, err) == error.OutOfMemory) return err; // otherwise continue through the `inline for` } } return error.NoUnionMembersMatched; } else { @compileError("Unable to parse into untagged union '" ++ @typeName(T) ++ "'"); } }, .Struct => |structInfo| { switch (token) { .ObjectBegin => {}, else => return error.UnexpectedToken, } var r: T = undefined; var fields_seen = [_]bool{false} ** structInfo.fields.len; errdefer { inline for (structInfo.fields) |field, i| { if (fields_seen[i]) { parseFree(field.field_type, @field(r, field.name), options); } } } while (true) { switch ((try tokens.next()) orelse return error.UnexpectedEndOfJson) { .ObjectEnd => break, .String => |stringToken| { const key_source_slice = stringToken.slice(tokens.slice, tokens.i - 1); var found = false; inline for (structInfo.fields) |field, i| { // TODO: using switches here segfault the compiler (#2727?) if ((stringToken.escapes == .None and mem.eql(u8, field.name, key_source_slice)) or (stringToken.escapes == .Some and (field.name.len == stringToken.decodedLength() and encodesTo(field.name, key_source_slice)))) { // if (switch (stringToken.escapes) { // .None => mem.eql(u8, field.name, key_source_slice), // .Some => (field.name.len == stringToken.decodedLength() and encodesTo(field.name, key_source_slice)), // }) { if (fields_seen[i]) { // switch (options.duplicate_field_behavior) { // .UseFirst => {}, // .Error => {}, // .UseLast => {}, // } if (options.duplicate_field_behavior == .UseFirst) { break; } else if (options.duplicate_field_behavior == .Error) { return error.DuplicateJSONField; } else if (options.duplicate_field_behavior == .UseLast) { parseFree(field.field_type, @field(r, field.name), options); } } @field(r, field.name) = try parse(field.field_type, tokens, options); fields_seen[i] = true; found = true; break; } } if (!found) return error.UnknownField; }, else => return error.UnexpectedToken, } } inline for (structInfo.fields) |field, i| { if (!fields_seen[i]) { if (field.default_value) |default| { @field(r, field.name) = default; } else { return error.MissingField; } } } return r; }, .Array => |arrayInfo| { switch (token) { .ArrayBegin => { var r: T = undefined; var i: usize = 0; errdefer { while (true) : (i -= 1) { parseFree(arrayInfo.child, r[i], options); if (i == 0) break; } } while (i < r.len) : (i += 1) { r[i] = try parse(arrayInfo.child, tokens, options); } const tok = (try tokens.next()) orelse return error.UnexpectedEndOfJson; switch (tok) { .ArrayEnd => {}, else => return error.UnexpectedToken, } return r; }, .String => |stringToken| { if (arrayInfo.child != u8) return error.UnexpectedToken; var r: T = undefined; const source_slice = stringToken.slice(tokens.slice, tokens.i - 1); switch (stringToken.escapes) { .None => mem.copy(u8, &r, source_slice), .Some => try unescapeString(&r, source_slice), } return r; }, else => return error.UnexpectedToken, } }, .Pointer => |ptrInfo| { const allocator = options.allocator orelse return error.AllocatorRequired; switch (ptrInfo.size) { .One => { const r: T = try allocator.create(ptrInfo.child); r.* = try parseInternal(ptrInfo.child, token, tokens, options); return r; }, .Slice => { switch (token) { .ArrayBegin => { var arraylist = std.ArrayList(ptrInfo.child).init(allocator); errdefer { while (arraylist.popOrNull()) |v| { parseFree(ptrInfo.child, v, options); } arraylist.deinit(); } while (true) { const tok = (try tokens.next()) orelse return error.UnexpectedEndOfJson; switch (tok) { .ArrayEnd => break, else => {}, } try arraylist.ensureCapacity(arraylist.items.len + 1); const v = try parseInternal(ptrInfo.child, tok, tokens, options); arraylist.appendAssumeCapacity(v); } return arraylist.toOwnedSlice(); }, .String => |stringToken| { if (ptrInfo.child != u8) return error.UnexpectedToken; const source_slice = stringToken.slice(tokens.slice, tokens.i - 1); switch (stringToken.escapes) { .None => return allocator.dupe(u8, source_slice), .Some => |some_escapes| { const output = try allocator.alloc(u8, stringToken.decodedLength()); errdefer allocator.free(output); try unescapeString(output, source_slice); return output; }, } }, else => return error.UnexpectedToken, } }, else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"), } }, else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"), } unreachable; } pub fn parse(comptime T: type, tokens: *TokenStream, options: ParseOptions) !T { const token = (try tokens.next()) orelse return error.UnexpectedEndOfJson; return parseInternal(T, token, tokens, options); } /// Releases resources created by `parse`. /// Should be called with the same type and `ParseOptions` that were passed to `parse` pub fn parseFree(comptime T: type, value: T, options: ParseOptions) void { switch (@typeInfo(T)) { .Bool, .Float, .ComptimeFloat, .Int, .ComptimeInt, .Enum => {}, .Optional => { if (value) |v| { return parseFree(@TypeOf(v), v, options); } }, .Union => |unionInfo| { if (unionInfo.tag_type) |UnionTagType| { inline for (unionInfo.fields) |u_field| { if (value == @field(UnionTagType, u_field.name)) { parseFree(u_field.field_type, @field(value, u_field.name), options); break; } } } else { unreachable; } }, .Struct => |structInfo| { inline for (structInfo.fields) |field| { parseFree(field.field_type, @field(value, field.name), options); } }, .Array => |arrayInfo| { for (value) |v| { parseFree(arrayInfo.child, v, options); } }, .Pointer => |ptrInfo| { const allocator = options.allocator orelse unreachable; switch (ptrInfo.size) { .One => { parseFree(ptrInfo.child, value.*, options); allocator.destroy(value); }, .Slice => { for (value) |v| { parseFree(ptrInfo.child, v, options); } allocator.free(value); }, else => unreachable, } }, else => unreachable, } } test "parse" { testing.expectEqual(false, try parse(bool, &TokenStream.init("false"), ParseOptions{})); testing.expectEqual(true, try parse(bool, &TokenStream.init("true"), ParseOptions{})); testing.expectEqual(@as(u1, 1), try parse(u1, &TokenStream.init("1"), ParseOptions{})); testing.expectError(error.Overflow, parse(u1, &TokenStream.init("50"), ParseOptions{})); testing.expectEqual(@as(u64, 42), try parse(u64, &TokenStream.init("42"), ParseOptions{})); testing.expectEqual(@as(f64, 42), try parse(f64, &TokenStream.init("42.0"), ParseOptions{})); testing.expectEqual(@as(?bool, null), try parse(?bool, &TokenStream.init("null"), ParseOptions{})); testing.expectEqual(@as(?bool, true), try parse(?bool, &TokenStream.init("true"), ParseOptions{})); testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("\"foo\""), ParseOptions{})); testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("[102, 111, 111]"), ParseOptions{})); } test "parse into enum" { const T = extern enum { Foo = 42, Bar, @"with\\escape", }; testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("\"Foo\""), ParseOptions{})); testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("42"), ParseOptions{})); testing.expectEqual(@as(T, .@"with\\escape"), try parse(T, &TokenStream.init("\"with\\\\escape\""), ParseOptions{})); testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("5"), ParseOptions{})); testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("\"Qux\""), ParseOptions{})); } test "parse into that allocates a slice" { testing.expectError(error.AllocatorRequired, parse([]u8, &TokenStream.init("\"foo\""), ParseOptions{})); const options = ParseOptions{ .allocator = testing.allocator }; { const r = try parse([]u8, &TokenStream.init("\"foo\""), options); defer parseFree([]u8, r, options); testing.expectEqualSlices(u8, "foo", r); } { const r = try parse([]u8, &TokenStream.init("[102, 111, 111]"), options); defer parseFree([]u8, r, options); testing.expectEqualSlices(u8, "foo", r); } { const r = try parse([]u8, &TokenStream.init("\"with\\\\escape\""), options); defer parseFree([]u8, r, options); testing.expectEqualSlices(u8, "with\\escape", r); } } test "parse into tagged union" { { const T = union(enum) { int: i32, float: f64, string: []const u8, }; testing.expectEqual(T{ .float = 1.5 }, try parse(T, &TokenStream.init("1.5"), ParseOptions{})); } { // if union matches string member, fails with NoUnionMembersMatched rather than AllocatorRequired // Note that this behaviour wasn't necessarily by design, but was // what fell out of the implementation and may result in interesting // API breakage if changed const T = union(enum) { int: i32, float: f64, string: []const u8, }; testing.expectError(error.NoUnionMembersMatched, parse(T, &TokenStream.init("\"foo\""), ParseOptions{})); } { // failing allocations should be bubbled up instantly without trying next member var fail_alloc = testing.FailingAllocator.init(testing.allocator, 0); const options = ParseOptions{ .allocator = &fail_alloc.allocator }; const T = union(enum) { // both fields here match the input string: []const u8, array: [3]u8, }; testing.expectError(error.OutOfMemory, parse(T, &TokenStream.init("[1,2,3]"), options)); } { // if multiple matches possible, takes first option const T = union(enum) { x: u8, y: u8, }; testing.expectEqual(T{ .x = 42 }, try parse(T, &TokenStream.init("42"), ParseOptions{})); } { // needs to back out when first union member doesn't match const T = union(enum) { A: struct { x: u32 }, B: struct { y: u32 }, }; testing.expectEqual(T{ .B = .{ .y = 42 } }, try parse(T, &TokenStream.init("{\"y\":42}"), ParseOptions{})); } } test "parseFree descends into tagged union" { var fail_alloc = testing.FailingAllocator.init(testing.allocator, 1); const options = ParseOptions{ .allocator = &fail_alloc.allocator }; const T = union(enum) { int: i32, float: f64, string: []const u8, }; // use a string with unicode escape so we know result can't be a reference to global constant const r = try parse(T, &TokenStream.init("\"with\\u0105unicode\""), options); testing.expectEqual(@TagType(T).string, @as(@TagType(T), r)); testing.expectEqualSlices(u8, "withąunicode", r.string); testing.expectEqual(@as(usize, 0), fail_alloc.deallocations); parseFree(T, r, options); testing.expectEqual(@as(usize, 1), fail_alloc.deallocations); } test "parse into struct with no fields" { const T = struct {}; testing.expectEqual(T{}, try parse(T, &TokenStream.init("{}"), ParseOptions{})); } test "parse into struct with misc fields" { @setEvalBranchQuota(10000); const options = ParseOptions{ .allocator = testing.allocator }; const T = struct { int: i64, float: f64, @"with\\escape": bool, @"withąunicode😂": bool, language: []const u8, optional: ?bool, default_field: i32 = 42, static_array: [3]f64, dynamic_array: []f64, complex: struct { nested: []const u8, }, veryComplex: []struct { foo: []const u8, }, a_union: Union, const Union = union(enum) { x: u8, float: f64, string: []const u8, }; }; const r = try parse(T, &TokenStream.init( \\{ \\ "int": 420, \\ "float": 3.14, \\ "with\\escape": true, \\ "with\u0105unicode\ud83d\ude02": false, \\ "language": "zig", \\ "optional": null, \\ "static_array": [66.6, 420.420, 69.69], \\ "dynamic_array": [66.6, 420.420, 69.69], \\ "complex": { \\ "nested": "zig" \\ }, \\ "veryComplex": [ \\ { \\ "foo": "zig" \\ }, { \\ "foo": "rocks" \\ } \\ ], \\ "a_union": 100000 \\} ), options); defer parseFree(T, r, options); testing.expectEqual(@as(i64, 420), r.int); testing.expectEqual(@as(f64, 3.14), r.float); testing.expectEqual(true, r.@"with\\escape"); testing.expectEqual(false, r.@"withąunicode😂"); testing.expectEqualSlices(u8, "zig", r.language); testing.expectEqual(@as(?bool, null), r.optional); testing.expectEqual(@as(i32, 42), r.default_field); testing.expectEqual(@as(f64, 66.6), r.static_array[0]); testing.expectEqual(@as(f64, 420.420), r.static_array[1]); testing.expectEqual(@as(f64, 69.69), r.static_array[2]); testing.expectEqual(@as(usize, 3), r.dynamic_array.len); testing.expectEqual(@as(f64, 66.6), r.dynamic_array[0]); testing.expectEqual(@as(f64, 420.420), r.dynamic_array[1]); testing.expectEqual(@as(f64, 69.69), r.dynamic_array[2]); testing.expectEqualSlices(u8, r.complex.nested, "zig"); testing.expectEqualSlices(u8, "zig", r.veryComplex[0].foo); testing.expectEqualSlices(u8, "rocks", r.veryComplex[1].foo); testing.expectEqual(T.Union{ .float = 100000 }, r.a_union); } /// A non-stream JSON parser which constructs a tree of Value's. pub const Parser = struct { allocator: *Allocator, state: State, copy_strings: bool, // Stores parent nodes and un-combined Values. stack: Array, const State = enum { ObjectKey, ObjectValue, ArrayValue, Simple, }; pub fn init(allocator: *Allocator, copy_strings: bool) Parser { return Parser{ .allocator = allocator, .state = .Simple, .copy_strings = copy_strings, .stack = Array.init(allocator), }; } pub fn deinit(p: *Parser) void { p.stack.deinit(); } pub fn reset(p: *Parser) void { p.state = .Simple; p.stack.shrink(0); } pub fn parse(p: *Parser, input: []const u8) !ValueTree { var s = TokenStream.init(input); var arena = ArenaAllocator.init(p.allocator); errdefer arena.deinit(); while (try s.next()) |token| { try p.transition(&arena.allocator, input, s.i - 1, token); } debug.assert(p.stack.items.len == 1); return ValueTree{ .arena = arena, .root = p.stack.items[0], }; } // Even though p.allocator exists, we take an explicit allocator so that allocation state // can be cleaned up on error correctly during a `parse` on call. fn transition(p: *Parser, allocator: *Allocator, input: []const u8, i: usize, token: Token) !void { switch (p.state) { .ObjectKey => switch (token) { .ObjectEnd => { if (p.stack.items.len == 1) { return; } var value = p.stack.pop(); try p.pushToParent(&value); }, .String => |s| { try p.stack.append(try p.parseString(allocator, s, input, i)); p.state = .ObjectValue; }, else => { // The streaming parser would return an error eventually. // To prevent invalid state we return an error now. // TODO make the streaming parser return an error as soon as it encounters an invalid object key return error.InvalidLiteral; }, }, .ObjectValue => { var object = &p.stack.items[p.stack.items.len - 2].Object; var key = p.stack.items[p.stack.items.len - 1].String; switch (token) { .ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = .ObjectKey; }, .ArrayBegin => { try p.stack.append(Value{ .Array = Array.init(allocator) }); p.state = .ArrayValue; }, .String => |s| { _ = try object.put(key, try p.parseString(allocator, s, input, i)); _ = p.stack.pop(); p.state = .ObjectKey; }, .Number => |n| { _ = try object.put(key, try p.parseNumber(n, input, i)); _ = p.stack.pop(); p.state = .ObjectKey; }, .True => { _ = try object.put(key, Value{ .Bool = true }); _ = p.stack.pop(); p.state = .ObjectKey; }, .False => { _ = try object.put(key, Value{ .Bool = false }); _ = p.stack.pop(); p.state = .ObjectKey; }, .Null => { _ = try object.put(key, Value.Null); _ = p.stack.pop(); p.state = .ObjectKey; }, .ObjectEnd, .ArrayEnd => { unreachable; }, } }, .ArrayValue => { var array = &p.stack.items[p.stack.items.len - 1].Array; switch (token) { .ArrayEnd => { if (p.stack.items.len == 1) { return; } var value = p.stack.pop(); try p.pushToParent(&value); }, .ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = .ObjectKey; }, .ArrayBegin => { try p.stack.append(Value{ .Array = Array.init(allocator) }); p.state = .ArrayValue; }, .String => |s| { try array.append(try p.parseString(allocator, s, input, i)); }, .Number => |n| { try array.append(try p.parseNumber(n, input, i)); }, .True => { try array.append(Value{ .Bool = true }); }, .False => { try array.append(Value{ .Bool = false }); }, .Null => { try array.append(Value.Null); }, .ObjectEnd => { unreachable; }, } }, .Simple => switch (token) { .ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = .ObjectKey; }, .ArrayBegin => { try p.stack.append(Value{ .Array = Array.init(allocator) }); p.state = .ArrayValue; }, .String => |s| { try p.stack.append(try p.parseString(allocator, s, input, i)); }, .Number => |n| { try p.stack.append(try p.parseNumber(n, input, i)); }, .True => { try p.stack.append(Value{ .Bool = true }); }, .False => { try p.stack.append(Value{ .Bool = false }); }, .Null => { try p.stack.append(Value.Null); }, .ObjectEnd, .ArrayEnd => { unreachable; }, }, } } fn pushToParent(p: *Parser, value: *const Value) !void { switch (p.stack.items[p.stack.items.len - 1]) { // Object Parent -> [ ..., object, <key>, value ] Value.String => |key| { _ = p.stack.pop(); var object = &p.stack.items[p.stack.items.len - 1].Object; _ = try object.put(key, value.*); p.state = .ObjectKey; }, // Array Parent -> [ ..., <array>, value ] Value.Array => |*array| { try array.append(value.*); p.state = .ArrayValue; }, else => { unreachable; }, } } fn parseString(p: *Parser, allocator: *Allocator, s: std.meta.TagPayloadType(Token, Token.String), input: []const u8, i: usize) !Value { const slice = s.slice(input, i); switch (s.escapes) { .None => return Value{ .String = if (p.copy_strings) try allocator.dupe(u8, slice) else slice }, .Some => |some_escapes| { const output = try allocator.alloc(u8, s.decodedLength()); errdefer allocator.free(output); try unescapeString(output, slice); return Value{ .String = output }; }, } } fn parseNumber(p: *Parser, n: std.meta.TagPayloadType(Token, Token.Number), input: []const u8, i: usize) !Value { return if (n.is_integer) Value{ .Integer = try std.fmt.parseInt(i64, n.slice(input, i), 10) } else Value{ .Float = try std.fmt.parseFloat(f64, n.slice(input, i)) }; } }; // Unescape a JSON string // Only to be used on strings already validated by the parser // (note the unreachable statements and lack of bounds checking) fn unescapeString(output: []u8, input: []const u8) !void { var inIndex: usize = 0; var outIndex: usize = 0; while (inIndex < input.len) { if (input[inIndex] != '\\') { // not an escape sequence output[outIndex] = input[inIndex]; inIndex += 1; outIndex += 1; } else if (input[inIndex + 1] != 'u') { // a simple escape sequence output[outIndex] = @as(u8, switch (input[inIndex + 1]) { '\\' => '\\', '/' => '/', 'n' => '\n', 'r' => '\r', 't' => '\t', 'f' => 12, 'b' => 8, '"' => '"', else => unreachable, }); inIndex += 2; outIndex += 1; } else { // a unicode escape sequence const firstCodeUnit = std.fmt.parseInt(u16, input[inIndex + 2 .. inIndex + 6], 16) catch unreachable; // guess optimistically that it's not a surrogate pair if (std.unicode.utf8Encode(firstCodeUnit, output[outIndex..])) |byteCount| { outIndex += byteCount; inIndex += 6; } else |err| { // it might be a surrogate pair if (err != error.Utf8CannotEncodeSurrogateHalf) { return error.InvalidUnicodeHexSymbol; } // check if a second code unit is present if (inIndex + 7 >= input.len or input[inIndex + 6] != '\\' or input[inIndex + 7] != 'u') { return error.InvalidUnicodeHexSymbol; } const secondCodeUnit = std.fmt.parseInt(u16, input[inIndex + 8 .. inIndex + 12], 16) catch unreachable; const utf16le_seq = [2]u16{ mem.nativeToLittle(u16, firstCodeUnit), mem.nativeToLittle(u16, secondCodeUnit), }; if (std.unicode.utf16leToUtf8(output[outIndex..], &utf16le_seq)) |byteCount| { outIndex += byteCount; inIndex += 12; } else |_| { return error.InvalidUnicodeHexSymbol; } } } } assert(outIndex == output.len); } test "json.parser.dynamic" { var p = Parser.init(testing.allocator, false); defer p.deinit(); const s = \\{ \\ "Image": { \\ "Width": 800, \\ "Height": 600, \\ "Title": "View from 15th Floor", \\ "Thumbnail": { \\ "Url": "http://www.example.com/image/481989943", \\ "Height": 125, \\ "Width": 100 \\ }, \\ "Animated" : false, \\ "IDs": [116, 943, 234, 38793], \\ "ArrayOfObject": [{"n": "m"}], \\ "double": 1.3412 \\ } \\} ; var tree = try p.parse(s); defer tree.deinit(); var root = tree.root; var image = root.Object.get("Image").?; const width = image.Object.get("Width").?; testing.expect(width.Integer == 800); const height = image.Object.get("Height").?; testing.expect(height.Integer == 600); const title = image.Object.get("Title").?; testing.expect(mem.eql(u8, title.String, "View from 15th Floor")); const animated = image.Object.get("Animated").?; testing.expect(animated.Bool == false); const array_of_object = image.Object.get("ArrayOfObject").?; testing.expect(array_of_object.Array.items.len == 1); const obj0 = array_of_object.Array.items[0].Object.get("n").?; testing.expect(mem.eql(u8, obj0.String, "m")); const double = image.Object.get("double").?; testing.expect(double.Float == 1.3412); } test "import more json tests" { _ = @import("json/test.zig"); _ = @import("json/write_stream.zig"); } test "write json then parse it" { var out_buffer: [1000]u8 = undefined; var fixed_buffer_stream = std.io.fixedBufferStream(&out_buffer); const out_stream = fixed_buffer_stream.outStream(); var jw = writeStream(out_stream, 4); try jw.beginObject(); try jw.objectField("f"); try jw.emitBool(false); try jw.objectField("t"); try jw.emitBool(true); try jw.objectField("int"); try jw.emitNumber(1234); try jw.objectField("array"); try jw.beginArray(); try jw.arrayElem(); try jw.emitNull(); try jw.arrayElem(); try jw.emitNumber(12.34); try jw.endArray(); try jw.objectField("str"); try jw.emitString("hello"); try jw.endObject(); var parser = Parser.init(testing.allocator, false); defer parser.deinit(); var tree = try parser.parse(fixed_buffer_stream.getWritten()); defer tree.deinit(); testing.expect(tree.root.Object.get("f").?.Bool == false); testing.expect(tree.root.Object.get("t").?.Bool == true); testing.expect(tree.root.Object.get("int").?.Integer == 1234); testing.expect(tree.root.Object.get("array").?.Array.items[0].Null == {}); testing.expect(tree.root.Object.get("array").?.Array.items[1].Float == 12.34); testing.expect(mem.eql(u8, tree.root.Object.get("str").?.String, "hello")); } fn test_parse(arena_allocator: *std.mem.Allocator, json_str: []const u8) !Value { var p = Parser.init(arena_allocator, false); return (try p.parse(json_str)).root; } test "parsing empty string gives appropriate error" { var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_allocator.deinit(); testing.expectError(error.UnexpectedEndOfJson, test_parse(&arena_allocator.allocator, "")); } test "integer after float has proper type" { var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_allocator.deinit(); const json = try test_parse(&arena_allocator.allocator, \\{ \\ "float": 3.14, \\ "ints": [1, 2, 3] \\} ); std.testing.expect(json.Object.get("ints").?.Array.items[0] == .Integer); } test "escaped characters" { var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_allocator.deinit(); const input = \\{ \\ "backslash": "\\", \\ "forwardslash": "\/", \\ "newline": "\n", \\ "carriagereturn": "\r", \\ "tab": "\t", \\ "formfeed": "\f", \\ "backspace": "\b", \\ "doublequote": "\"", \\ "unicode": "\u0105", \\ "surrogatepair": "\ud83d\ude02" \\} ; const obj = (try test_parse(&arena_allocator.allocator, input)).Object; testing.expectEqualSlices(u8, obj.get("backslash").?.String, "\\"); testing.expectEqualSlices(u8, obj.get("forwardslash").?.String, "/"); testing.expectEqualSlices(u8, obj.get("newline").?.String, "\n"); testing.expectEqualSlices(u8, obj.get("carriagereturn").?.String, "\r"); testing.expectEqualSlices(u8, obj.get("tab").?.String, "\t"); testing.expectEqualSlices(u8, obj.get("formfeed").?.String, "\x0C"); testing.expectEqualSlices(u8, obj.get("backspace").?.String, "\x08"); testing.expectEqualSlices(u8, obj.get("doublequote").?.String, "\""); testing.expectEqualSlices(u8, obj.get("unicode").?.String, "ą"); testing.expectEqualSlices(u8, obj.get("surrogatepair").?.String, "😂"); } test "string copy option" { const input = \\{ \\ "noescape": "aą😂", \\ "simple": "\\\/\n\r\t\f\b\"", \\ "unicode": "\u0105", \\ "surrogatepair": "\ud83d\ude02" \\} ; var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_allocator.deinit(); const tree_nocopy = try Parser.init(&arena_allocator.allocator, false).parse(input); const obj_nocopy = tree_nocopy.root.Object; const tree_copy = try Parser.init(&arena_allocator.allocator, true).parse(input); const obj_copy = tree_copy.root.Object; for ([_][]const u8{ "noescape", "simple", "unicode", "surrogatepair" }) |field_name| { testing.expectEqualSlices(u8, obj_nocopy.get(field_name).?.String, obj_copy.get(field_name).?.String); } const nocopy_addr = &obj_nocopy.get("noescape").?.String[0]; const copy_addr = &obj_copy.get("noescape").?.String[0]; var found_nocopy = false; for (input) |_, index| { testing.expect(copy_addr != &input[index]); if (nocopy_addr == &input[index]) { found_nocopy = true; } } testing.expect(found_nocopy); } pub const StringifyOptions = struct { pub const Whitespace = struct { /// How many indentation levels deep are we? indent_level: usize = 0, /// What character(s) should be used for indentation? indent: union(enum) { Space: u8, Tab: void, } = .{ .Space = 4 }, /// After a colon, should whitespace be inserted? separator: bool = true, pub fn outputIndent( whitespace: @This(), out_stream: anytype, ) @TypeOf(out_stream).Error!void { var char: u8 = undefined; var n_chars: usize = undefined; switch (whitespace.indent) { .Space => |n_spaces| { char = ' '; n_chars = n_spaces; }, .Tab => { char = '\t'; n_chars = 1; }, } n_chars *= whitespace.indent_level; try out_stream.writeByteNTimes(char, n_chars); } }; /// Controls the whitespace emitted whitespace: ?Whitespace = null, string: StringOptions = StringOptions{ .String = .{} }, /// Should []u8 be serialised as a string? or an array? pub const StringOptions = union(enum) { Array, String: StringOutputOptions, /// String output options const StringOutputOptions = struct { /// Should '/' be escaped in strings? escape_solidus: bool = false, /// Should unicode characters be escaped in strings? escape_unicode: bool = false, }; }; }; fn outputUnicodeEscape( codepoint: u21, out_stream: anytype, ) !void { if (codepoint <= 0xFFFF) { // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), // then it may be represented as a six-character sequence: a reverse solidus, followed // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. try out_stream.writeAll("\\u"); try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); } else { assert(codepoint <= 0x10FFFF); // To escape an extended character that is not in the Basic Multilingual Plane, // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair. const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800; const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00; try out_stream.writeAll("\\u"); try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); try out_stream.writeAll("\\u"); try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); } } pub fn stringify( value: anytype, options: StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { const T = @TypeOf(value); switch (@typeInfo(T)) { .Float, .ComptimeFloat => { return std.fmt.formatFloatScientific(value, std.fmt.FormatOptions{}, out_stream); }, .Int, .ComptimeInt => { return std.fmt.formatIntValue(value, "", std.fmt.FormatOptions{}, out_stream); }, .Bool => { return out_stream.writeAll(if (value) "true" else "false"); }, .Null => { return out_stream.writeAll("null"); }, .Optional => { if (value) |payload| { return try stringify(payload, options, out_stream); } else { return try stringify(null, options, out_stream); } }, .Enum => { if (comptime std.meta.trait.hasFn("jsonStringify")(T)) { return value.jsonStringify(options, out_stream); } @compileError("Unable to stringify enum '" ++ @typeName(T) ++ "'"); }, .Union => { if (comptime std.meta.trait.hasFn("jsonStringify")(T)) { return value.jsonStringify(options, out_stream); } const info = @typeInfo(T).Union; if (info.tag_type) |UnionTagType| { inline for (info.fields) |u_field| { if (value == @field(UnionTagType, u_field.name)) { return try stringify(@field(value, u_field.name), options, out_stream); } } } else { @compileError("Unable to stringify untagged union '" ++ @typeName(T) ++ "'"); } }, .Struct => |S| { if (comptime std.meta.trait.hasFn("jsonStringify")(T)) { return value.jsonStringify(options, out_stream); } try out_stream.writeByte('{'); comptime var field_output = false; var child_options = options; if (child_options.whitespace) |*child_whitespace| { child_whitespace.indent_level += 1; } inline for (S.fields) |Field, field_i| { // don't include void fields if (Field.field_type == void) continue; if (!field_output) { field_output = true; } else { try out_stream.writeByte(','); } if (child_options.whitespace) |child_whitespace| { try out_stream.writeByte('\n'); try child_whitespace.outputIndent(out_stream); } try stringify(Field.name, options, out_stream); try out_stream.writeByte(':'); if (child_options.whitespace) |child_whitespace| { if (child_whitespace.separator) { try out_stream.writeByte(' '); } } try stringify(@field(value, Field.name), child_options, out_stream); } if (field_output) { if (options.whitespace) |whitespace| { try out_stream.writeByte('\n'); try whitespace.outputIndent(out_stream); } } try out_stream.writeByte('}'); return; }, .ErrorSet => return stringify(@as([]const u8, @errorName(value)), options, out_stream), .Pointer => |ptr_info| switch (ptr_info.size) { .One => switch (@typeInfo(ptr_info.child)) { .Array => { const Slice = []const std.meta.Elem(ptr_info.child); return stringify(@as(Slice, value), options, out_stream); }, else => { // TODO: avoid loops? return stringify(value.*, options, out_stream); }, }, // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972) .Slice => { if (ptr_info.child == u8 and options.string == .String and std.unicode.utf8ValidateSlice(value)) { try out_stream.writeByte('\"'); var i: usize = 0; while (i < value.len) : (i += 1) { switch (value[i]) { // normal ascii character 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => |c| try out_stream.writeByte(c), // only 2 characters that *must* be escaped '\\' => try out_stream.writeAll("\\\\"), '\"' => try out_stream.writeAll("\\\""), // solidus is optional to escape '/' => { if (options.string.String.escape_solidus) { try out_stream.writeAll("\\/"); } else { try out_stream.writeByte('/'); } }, // control characters with short escapes // TODO: option to switch between unicode and 'short' forms? 0x8 => try out_stream.writeAll("\\b"), 0xC => try out_stream.writeAll("\\f"), '\n' => try out_stream.writeAll("\\n"), '\r' => try out_stream.writeAll("\\r"), '\t' => try out_stream.writeAll("\\t"), else => { const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable; // control characters (only things left with 1 byte length) should always be printed as unicode escapes if (ulen == 1 or options.string.String.escape_unicode) { const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable; try outputUnicodeEscape(codepoint, out_stream); } else { try out_stream.writeAll(value[i .. i + ulen]); } i += ulen - 1; }, } } try out_stream.writeByte('\"'); return; } try out_stream.writeByte('['); var child_options = options; if (child_options.whitespace) |*whitespace| { whitespace.indent_level += 1; } for (value) |x, i| { if (i != 0) { try out_stream.writeByte(','); } if (child_options.whitespace) |child_whitespace| { try out_stream.writeByte('\n'); try child_whitespace.outputIndent(out_stream); } try stringify(x, child_options, out_stream); } if (value.len != 0) { if (options.whitespace) |whitespace| { try out_stream.writeByte('\n'); try whitespace.outputIndent(out_stream); } } try out_stream.writeByte(']'); return; }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), }, .Array => return stringify(&value, options, out_stream), .Vector => |info| { const array: [info.len]info.child = value; return stringify(&array, options, out_stream); }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), } unreachable; } fn teststringify(expected: []const u8, value: anytype, options: StringifyOptions) !void { const ValidationOutStream = struct { const Self = @This(); pub const OutStream = std.io.OutStream(*Self, Error, write); pub const Error = error{ TooMuchData, DifferentData, }; expected_remaining: []const u8, fn init(exp: []const u8) Self { return .{ .expected_remaining = exp }; } pub fn outStream(self: *Self) OutStream { return .{ .context = self }; } fn write(self: *Self, bytes: []const u8) Error!usize { if (self.expected_remaining.len < bytes.len) { std.debug.warn( \\====== expected this output: ========= \\{} \\======== instead found this: ========= \\{} \\====================================== , .{ self.expected_remaining, bytes, }); return error.TooMuchData; } if (!mem.eql(u8, self.expected_remaining[0..bytes.len], bytes)) { std.debug.warn( \\====== expected this output: ========= \\{} \\======== instead found this: ========= \\{} \\====================================== , .{ self.expected_remaining[0..bytes.len], bytes, }); return error.DifferentData; } self.expected_remaining = self.expected_remaining[bytes.len..]; return bytes.len; } }; var vos = ValidationOutStream.init(expected); try stringify(value, options, vos.outStream()); if (vos.expected_remaining.len > 0) return error.NotEnoughData; } test "stringify basic types" { try teststringify("false", false, StringifyOptions{}); try teststringify("true", true, StringifyOptions{}); try teststringify("null", @as(?u8, null), StringifyOptions{}); try teststringify("null", @as(?*u32, null), StringifyOptions{}); try teststringify("42", 42, StringifyOptions{}); try teststringify("4.2e+01", 42.0, StringifyOptions{}); try teststringify("42", @as(u8, 42), StringifyOptions{}); try teststringify("42", @as(u128, 42), StringifyOptions{}); try teststringify("4.2e+01", @as(f32, 42), StringifyOptions{}); try teststringify("4.2e+01", @as(f64, 42), StringifyOptions{}); try teststringify("\"ItBroke\"", @as(anyerror, error.ItBroke), StringifyOptions{}); } test "stringify string" { try teststringify("\"hello\"", "hello", StringifyOptions{}); try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{}); try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{}); try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{80}\"", "with unicode\u{80}", StringifyOptions{}); try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", StringifyOptions{}); try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{100}\"", "with unicode\u{100}", StringifyOptions{}); try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{800}\"", "with unicode\u{800}", StringifyOptions{}); try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", StringifyOptions{}); try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", StringifyOptions{}); try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", StringifyOptions{}); try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", StringifyOptions{}); try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"/\"", "/", StringifyOptions{}); try teststringify("\"\\/\"", "/", StringifyOptions{ .string = .{ .String = .{ .escape_solidus = true } } }); } test "stringify tagged unions" { try teststringify("42", union(enum) { Foo: u32, Bar: bool, }{ .Foo = 42 }, StringifyOptions{}); } test "stringify struct" { try teststringify("{\"foo\":42}", struct { foo: u32, }{ .foo = 42 }, StringifyOptions{}); } test "stringify struct with indentation" { try teststringify( \\{ \\ "foo": 42, \\ "bar": [ \\ 1, \\ 2, \\ 3 \\ ] \\} , struct { foo: u32, bar: [3]u32, }{ .foo = 42, .bar = .{ 1, 2, 3 }, }, StringifyOptions{ .whitespace = .{}, }, ); try teststringify( "{\n\t\"foo\":42,\n\t\"bar\":[\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}", struct { foo: u32, bar: [3]u32, }{ .foo = 42, .bar = .{ 1, 2, 3 }, }, StringifyOptions{ .whitespace = .{ .indent = .Tab, .separator = false, }, }, ); } test "stringify struct with void field" { try teststringify("{\"foo\":42}", struct { foo: u32, bar: void = {}, }{ .foo = 42 }, StringifyOptions{}); } test "stringify array of structs" { const MyStruct = struct { foo: u32, }; try teststringify("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{ MyStruct{ .foo = 42 }, MyStruct{ .foo = 100 }, MyStruct{ .foo = 1000 }, }, StringifyOptions{}); } test "stringify struct with custom stringifier" { try teststringify("[\"something special\",42]", struct { foo: u32, const Self = @This(); pub fn jsonStringify( value: Self, options: StringifyOptions, out_stream: anytype, ) !void { try out_stream.writeAll("[\"something special\","); try stringify(42, options, out_stream); try out_stream.writeByte(']'); } }{ .foo = 42 }, StringifyOptions{}); } test "stringify vector" { try teststringify("[1,1]", @splat(2, @as(u32, 1)), StringifyOptions{}); }
lib/std/json.zig
const builtin = @import("builtin"); test { _ = @import("behavior/align.zig"); _ = @import("behavior/alignof.zig"); _ = @import("behavior/array.zig"); _ = @import("behavior/bit_shifting.zig"); _ = @import("behavior/bool.zig"); _ = @import("behavior/bugs/394.zig"); _ = @import("behavior/bugs/655.zig"); _ = @import("behavior/bugs/656.zig"); _ = @import("behavior/bugs/679.zig"); _ = @import("behavior/bugs/1111.zig"); _ = @import("behavior/bugs/1277.zig"); _ = @import("behavior/bugs/1310.zig"); _ = @import("behavior/bugs/1381.zig"); _ = @import("behavior/bugs/1486.zig"); _ = @import("behavior/bugs/1500.zig"); _ = @import("behavior/bugs/1735.zig"); _ = @import("behavior/bugs/2006.zig"); _ = @import("behavior/bugs/2346.zig"); _ = @import("behavior/bugs/3112.zig"); _ = @import("behavior/bugs/3367.zig"); _ = @import("behavior/bugs/6850.zig"); _ = @import("behavior/bugs/7250.zig"); _ = @import("behavior/cast.zig"); _ = @import("behavior/comptime_memory.zig"); _ = @import("behavior/fn_in_struct_in_comptime.zig"); _ = @import("behavior/hasdecl.zig"); _ = @import("behavior/hasfield.zig"); _ = @import("behavior/namespace_depends_on_compile_var.zig"); _ = @import("behavior/optional_llvm.zig"); _ = @import("behavior/prefetch.zig"); _ = @import("behavior/pub_enum.zig"); _ = @import("behavior/slice_sentinel_comptime.zig"); _ = @import("behavior/type.zig"); _ = @import("behavior/truncate.zig"); _ = @import("behavior/struct.zig"); if (builtin.zig_backend != .stage2_arm and builtin.zig_backend != .stage2_x86_64) { // Tests that pass for stage1, llvm backend, C backend, wasm backend. _ = @import("behavior/basic.zig"); _ = @import("behavior/bitcast.zig"); _ = @import("behavior/bugs/624.zig"); _ = @import("behavior/bugs/704.zig"); _ = @import("behavior/bugs/1076.zig"); _ = @import("behavior/bugs/2692.zig"); _ = @import("behavior/bugs/2889.zig"); _ = @import("behavior/bugs/3046.zig"); _ = @import("behavior/bugs/3586.zig"); _ = @import("behavior/bugs/4560.zig"); _ = @import("behavior/bugs/4769_a.zig"); _ = @import("behavior/bugs/4769_b.zig"); _ = @import("behavior/bugs/4954.zig"); _ = @import("behavior/byval_arg_var.zig"); _ = @import("behavior/call.zig"); _ = @import("behavior/defer.zig"); _ = @import("behavior/enum.zig"); _ = @import("behavior/error.zig"); _ = @import("behavior/for.zig"); _ = @import("behavior/generics.zig"); _ = @import("behavior/if.zig"); _ = @import("behavior/import.zig"); _ = @import("behavior/incomplete_struct_param_tld.zig"); _ = @import("behavior/inttoptr.zig"); _ = @import("behavior/member_func.zig"); _ = @import("behavior/null.zig"); _ = @import("behavior/optional.zig"); _ = @import("behavior/pointers.zig"); _ = @import("behavior/ptrcast.zig"); _ = @import("behavior/ref_var_in_if_after_if_2nd_switch_prong.zig"); _ = @import("behavior/src.zig"); _ = @import("behavior/this.zig"); _ = @import("behavior/try.zig"); _ = @import("behavior/type_info.zig"); _ = @import("behavior/undefined.zig"); _ = @import("behavior/underscore.zig"); _ = @import("behavior/union.zig"); _ = @import("behavior/usingnamespace.zig"); _ = @import("behavior/void.zig"); _ = @import("behavior/while.zig"); if (builtin.zig_backend != .stage2_wasm) { // Tests that pass for stage1, llvm backend, C backend _ = @import("behavior/cast_int.zig"); _ = @import("behavior/int128.zig"); _ = @import("behavior/translate_c_macros.zig"); if (builtin.zig_backend != .stage2_c) { // Tests that pass for stage1 and the llvm backend. _ = @import("behavior/array_llvm.zig"); _ = @import("behavior/atomics.zig"); _ = @import("behavior/bugs/1025.zig"); _ = @import("behavior/bugs/1741.zig"); _ = @import("behavior/bugs/1914.zig"); _ = @import("behavior/bugs/2578.zig"); _ = @import("behavior/bugs/3007.zig"); _ = @import("behavior/bugs/9584.zig"); _ = @import("behavior/cast_llvm.zig"); _ = @import("behavior/error_llvm.zig"); _ = @import("behavior/eval.zig"); _ = @import("behavior/floatop.zig"); _ = @import("behavior/fn.zig"); _ = @import("behavior/math.zig"); _ = @import("behavior/maximum_minimum.zig"); _ = @import("behavior/merge_error_sets.zig"); _ = @import("behavior/null_llvm.zig"); _ = @import("behavior/popcount.zig"); _ = @import("behavior/saturating_arithmetic.zig"); _ = @import("behavior/sizeof_and_typeof.zig"); _ = @import("behavior/slice.zig"); _ = @import("behavior/struct_llvm.zig"); _ = @import("behavior/switch.zig"); _ = @import("behavior/widening.zig"); if (builtin.zig_backend == .stage1) { // Tests that only pass for the stage1 backend. if (builtin.os.tag != .wasi) { _ = @import("behavior/asm.zig"); _ = @import("behavior/async_fn.zig"); } _ = @import("behavior/await_struct.zig"); _ = @import("behavior/bitreverse.zig"); _ = @import("behavior/bugs/421.zig"); _ = @import("behavior/bugs/529.zig"); _ = @import("behavior/bugs/718.zig"); _ = @import("behavior/bugs/726.zig"); _ = @import("behavior/bugs/828.zig"); _ = @import("behavior/bugs/920.zig"); _ = @import("behavior/bugs/1120.zig"); _ = @import("behavior/bugs/1421.zig"); _ = @import("behavior/bugs/1442.zig"); _ = @import("behavior/bugs/1607.zig"); _ = @import("behavior/bugs/1851.zig"); _ = @import("behavior/bugs/2114.zig"); _ = @import("behavior/bugs/3384.zig"); _ = @import("behavior/bugs/3742.zig"); _ = @import("behavior/bugs/3779.zig"); _ = @import("behavior/bugs/4328.zig"); _ = @import("behavior/bugs/5398.zig"); _ = @import("behavior/bugs/5413.zig"); _ = @import("behavior/bugs/5474.zig"); _ = @import("behavior/bugs/5487.zig"); _ = @import("behavior/bugs/6456.zig"); _ = @import("behavior/bugs/6781.zig"); _ = @import("behavior/bugs/7003.zig"); _ = @import("behavior/bugs/7027.zig"); _ = @import("behavior/bugs/7047.zig"); _ = @import("behavior/bugs/10147.zig"); _ = @import("behavior/byteswap.zig"); _ = @import("behavior/const_slice_child.zig"); _ = @import("behavior/export_self_referential_type_info.zig"); _ = @import("behavior/field_parent_ptr.zig"); _ = @import("behavior/floatop_stage1.zig"); _ = @import("behavior/fn_delegation.zig"); _ = @import("behavior/ir_block_deps.zig"); _ = @import("behavior/misc.zig"); _ = @import("behavior/muladd.zig"); _ = @import("behavior/null_stage1.zig"); _ = @import("behavior/optional_stage1.zig"); _ = @import("behavior/popcount_stage1.zig"); _ = @import("behavior/reflection.zig"); _ = @import("behavior/select.zig"); _ = @import("behavior/shuffle.zig"); _ = @import("behavior/sizeof_and_typeof_stage1.zig"); _ = @import("behavior/slice_stage1.zig"); _ = @import("behavior/struct_contains_null_ptr_itself.zig"); _ = @import("behavior/struct_contains_slice_of_itself.zig"); _ = @import("behavior/switch_prong_err_enum.zig"); _ = @import("behavior/switch_prong_implicit_cast.zig"); _ = @import("behavior/truncate_stage1.zig"); _ = @import("behavior/tuple.zig"); _ = @import("behavior/type_stage1.zig"); _ = @import("behavior/typename.zig"); _ = @import("behavior/union_stage1.zig"); _ = @import("behavior/union_with_members.zig"); _ = @import("behavior/var_args.zig"); _ = @import("behavior/vector.zig"); if (builtin.target.cpu.arch == .wasm32) { _ = @import("behavior/wasm.zig"); } } } } } }
test/behavior.zig
const std = @import("std"); const builtin = std.builtin; const debug = std.debug; const warn = debug.warn; const build = std.build; const CrossTarget = std.zig.CrossTarget; const io = std.io; const fs = std.fs; const mem = std.mem; const fmt = std.fmt; const ArrayList = std.ArrayList; const Mode = builtin.Mode; const LibExeObjStep = build.LibExeObjStep; // Cases const compare_output = @import("compare_output.zig"); const standalone = @import("standalone.zig"); const stack_traces = @import("stack_traces.zig"); const compile_errors = @import("compile_errors.zig"); const assemble_and_link = @import("assemble_and_link.zig"); const runtime_safety = @import("runtime_safety.zig"); const translate_c = @import("translate_c.zig"); const run_translated_c = @import("run_translated_c.zig"); const gen_h = @import("gen_h.zig"); // Implementations pub const TranslateCContext = @import("src/translate_c.zig").TranslateCContext; pub const RunTranslatedCContext = @import("src/run_translated_c.zig").RunTranslatedCContext; pub const CompareOutputContext = @import("src/compare_output.zig").CompareOutputContext; const TestTarget = struct { target: CrossTarget = @as(CrossTarget, .{}), mode: builtin.Mode = .Debug, link_libc: bool = false, single_threaded: bool = false, disable_native: bool = false, }; const test_targets = blk: { // getBaselineCpuFeatures calls populateDependencies which has a O(N ^ 2) algorithm // (where N is roughly 160, which technically makes it O(1), but it adds up to a // lot of branches) @setEvalBranchQuota(50000); break :blk [_]TestTarget{ TestTarget{}, TestTarget{ .link_libc = true, }, TestTarget{ .single_threaded = true, }, TestTarget{ .target = .{ .cpu_arch = .wasm32, .os_tag = .wasi, }, .link_libc = false, .single_threaded = true, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .none, }, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .linux, .abi = .none, }, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .linux, .abi = .musl, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .linux, .abi = .gnu, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .none, }, }, TestTarget{ .target = .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .musl, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .aarch64, .os_tag = .linux, .abi = .gnu, }, .link_libc = true, }, TestTarget{ .target = CrossTarget.parse(.{ .arch_os_abi = "arm-linux-none", .cpu_features = "generic+v8a", }) catch unreachable, }, TestTarget{ .target = CrossTarget.parse(.{ .arch_os_abi = "arm-linux-musleabihf", .cpu_features = "generic+v8a", }) catch unreachable, .link_libc = true, }, // https://github.com/ziglang/zig/issues/3287 //TestTarget{ // .target = CrossTarget.parse(.{ // .arch_os_abi = "arm-linux-gnueabihf", // .cpu_features = "generic+v8a", // }) catch unreachable, // .link_libc = true, //}, // https://github.com/ziglang/zig/issues/8155 //TestTarget{ // .target = .{ // .cpu_arch = .mips, // .os_tag = .linux, // .abi = .none, // }, //}, // https://github.com/ziglang/zig/issues/8155 //TestTarget{ // .target = .{ // .cpu_arch = .mips, // .os_tag = .linux, // .abi = .musl, // }, // .link_libc = true, //}, // https://github.com/ziglang/zig/issues/4927 //TestTarget{ // .target = .{ // .cpu_arch = .mips, // .os_tag = .linux, // .abi = .gnu, // }, // .link_libc = true, //}, // https://github.com/ziglang/zig/issues/8155 //TestTarget{ // .target = .{ // .cpu_arch = .mipsel, // .os_tag = .linux, // .abi = .none, // }, //}, // https://github.com/ziglang/zig/issues/8155 //TestTarget{ // .target = .{ // .cpu_arch = .mipsel, // .os_tag = .linux, // .abi = .musl, // }, // .link_libc = true, //}, // https://github.com/ziglang/zig/issues/4927 //TestTarget{ // .target = .{ // .cpu_arch = .mipsel, // .os_tag = .linux, // .abi = .gnu, // }, // .link_libc = true, //}, TestTarget{ .target = .{ .cpu_arch = .powerpc, .os_tag = .linux, .abi = .none, }, }, TestTarget{ .target = .{ .cpu_arch = .powerpc, .os_tag = .linux, .abi = .musl, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .riscv64, .os_tag = .linux, .abi = .none, }, }, TestTarget{ .target = .{ .cpu_arch = .riscv64, .os_tag = .linux, .abi = .musl, }, .link_libc = true, }, // https://github.com/ziglang/zig/issues/3340 //TestTarget{ // .target = .{ // .cpu_arch = .riscv64, // .os = .linux, // .abi = .gnu, // }, // .link_libc = true, //}, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .macos, .abi = .gnu, }, // https://github.com/ziglang/zig/issues/3295 .disable_native = true, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .windows, .abi = .msvc, }, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .windows, .abi = .msvc, }, }, TestTarget{ .target = .{ .cpu_arch = .i386, .os_tag = .windows, .abi = .gnu, }, .link_libc = true, }, TestTarget{ .target = .{ .cpu_arch = .x86_64, .os_tag = .windows, .abi = .gnu, }, .link_libc = true, }, // Do the release tests last because they take a long time TestTarget{ .mode = .ReleaseFast, }, TestTarget{ .link_libc = true, .mode = .ReleaseFast, }, TestTarget{ .mode = .ReleaseFast, .single_threaded = true, }, TestTarget{ .mode = .ReleaseSafe, }, TestTarget{ .link_libc = true, .mode = .ReleaseSafe, }, TestTarget{ .mode = .ReleaseSafe, .single_threaded = true, }, TestTarget{ .mode = .ReleaseSmall, }, TestTarget{ .link_libc = true, .mode = .ReleaseSmall, }, TestTarget{ .mode = .ReleaseSmall, .single_threaded = true, }, }; }; const max_stdout_size = 1 * 1024 * 1024; // 1 MB pub fn addCompareOutputTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, .step = b.step("test-compare-output", "Run the compare output tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; compare_output.addCases(cases); return cases.step; } pub fn addStackTraceTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(StackTracesContext) catch unreachable; cases.* = StackTracesContext{ .b = b, .step = b.step("test-stack-traces", "Run the stack trace tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; stack_traces.addCases(cases); return cases.step; } pub fn addRuntimeSafetyTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, .step = b.step("test-runtime-safety", "Run the runtime safety tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; runtime_safety.addCases(cases); return cases.step; } pub fn addCompileErrorTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(CompileErrorContext) catch unreachable; cases.* = CompileErrorContext{ .b = b, .step = b.step("test-compile-errors", "Run the compile error tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; compile_errors.addCases(cases); return cases.step; } pub fn addStandaloneTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(StandaloneContext) catch unreachable; cases.* = StandaloneContext{ .b = b, .step = b.step("test-standalone", "Run the standalone tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; standalone.addCases(cases); return cases.step; } pub fn addCliTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const step = b.step("test-cli", "Test the command line interface"); const exe = b.addExecutable("test-cli", "test/cli.zig"); const run_cmd = exe.run(); run_cmd.addArgs(&[_][]const u8{ fs.realpathAlloc(b.allocator, b.zig_exe) catch unreachable, b.pathFromRoot(b.cache_root), }); step.dependOn(&run_cmd.step); return step; } pub fn addAssembleAndLinkTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, .step = b.step("test-asm-link", "Run the assemble and link tests"), .test_index = 0, .test_filter = test_filter, .modes = modes, }; assemble_and_link.addCases(cases); return cases.step; } pub fn addTranslateCTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(TranslateCContext) catch unreachable; cases.* = TranslateCContext{ .b = b, .step = b.step("test-translate-c", "Run the C transation tests"), .test_index = 0, .test_filter = test_filter, }; translate_c.addCases(cases); return cases.step; } pub fn addRunTranslatedCTests( b: *build.Builder, test_filter: ?[]const u8, target: std.zig.CrossTarget, ) *build.Step { const cases = b.allocator.create(RunTranslatedCContext) catch unreachable; cases.* = .{ .b = b, .step = b.step("test-run-translated-c", "Run the Run-Translated-C tests"), .test_index = 0, .test_filter = test_filter, .target = target, }; run_translated_c.addCases(cases); return cases.step; } pub fn addGenHTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(GenHContext) catch unreachable; cases.* = GenHContext{ .b = b, .step = b.step("test-gen-h", "Run the C header file generation tests"), .test_index = 0, .test_filter = test_filter, }; gen_h.addCases(cases); return cases.step; } pub fn addPkgTests( b: *build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, modes: []const Mode, skip_single_threaded: bool, skip_non_native: bool, skip_libc: bool, is_wine_enabled: bool, is_qemu_enabled: bool, is_wasmtime_enabled: bool, is_darling_enabled: bool, glibc_dir: ?[]const u8, ) *build.Step { const step = b.step(b.fmt("test-{s}", .{name}), desc); for (test_targets) |test_target| { if (skip_non_native and !test_target.target.isNative()) continue; if (skip_libc and test_target.link_libc) continue; if (test_target.link_libc and test_target.target.getOs().requiresLibC()) { // This would be a redundant test. continue; } if (skip_single_threaded and test_target.single_threaded) continue; const ArchTag = std.meta.Tag(std.Target.Cpu.Arch); if (test_target.disable_native and test_target.target.getOsTag() == std.Target.current.os.tag and test_target.target.getCpuArch() == std.Target.current.cpu.arch) { continue; } const want_this_mode = for (modes) |m| { if (m == test_target.mode) break true; } else false; if (!want_this_mode) continue; const libc_prefix = if (test_target.target.getOs().requiresLibC()) "" else if (test_target.link_libc) "c" else "bare"; const triple_prefix = test_target.target.zigTriple(b.allocator) catch unreachable; const these_tests = b.addTest(root_src); const single_threaded_txt = if (test_target.single_threaded) "single" else "multi"; these_tests.setNamePrefix(b.fmt("{s}-{s}-{s}-{s}-{s} ", .{ name, triple_prefix, @tagName(test_target.mode), libc_prefix, single_threaded_txt, })); these_tests.single_threaded = test_target.single_threaded; these_tests.setFilter(test_filter); these_tests.setBuildMode(test_target.mode); these_tests.setTarget(test_target.target); if (test_target.link_libc) { these_tests.linkSystemLibrary("c"); } these_tests.overrideZigLibDir("lib"); these_tests.enable_wine = is_wine_enabled; these_tests.enable_qemu = is_qemu_enabled; these_tests.enable_wasmtime = is_wasmtime_enabled; these_tests.enable_darling = is_darling_enabled; these_tests.glibc_multi_install_dir = glibc_dir; these_tests.addIncludeDir("test"); step.dependOn(&these_tests.step); } return step; } pub const StackTracesContext = struct { b: *build.Builder, step: *build.Step, test_index: usize, test_filter: ?[]const u8, modes: []const Mode, const Expect = [@typeInfo(Mode).Enum.fields.len][]const u8; pub fn addCase(self: *StackTracesContext, config: anytype) void { if (@hasField(@TypeOf(config), "exclude")) { if (config.exclude.exclude()) return; } if (@hasField(@TypeOf(config), "exclude_arch")) { const exclude_arch: []const std.Target.Cpu.Arch = &config.exclude_arch; for (exclude_arch) |arch| if (arch == builtin.cpu.arch) return; } if (@hasField(@TypeOf(config), "exclude_os")) { const exclude_os: []const std.Target.Os.Tag = &config.exclude_os; for (exclude_os) |os| if (os == builtin.os.tag) return; } for (self.modes) |mode| { switch (mode) { .Debug => { if (@hasField(@TypeOf(config), "Debug")) { self.addExpect(config.name, config.source, mode, config.Debug); } }, .ReleaseSafe => { if (@hasField(@TypeOf(config), "ReleaseSafe")) { self.addExpect(config.name, config.source, mode, config.ReleaseSafe); } }, .ReleaseFast => { if (@hasField(@TypeOf(config), "ReleaseFast")) { self.addExpect(config.name, config.source, mode, config.ReleaseFast); } }, .ReleaseSmall => { if (@hasField(@TypeOf(config), "ReleaseSmall")) { self.addExpect(config.name, config.source, mode, config.ReleaseSmall); } }, } } } fn addExpect( self: *StackTracesContext, name: []const u8, source: []const u8, mode: Mode, mode_config: anytype, ) void { if (@hasField(@TypeOf(mode_config), "exclude")) { if (mode_config.exclude.exclude()) return; } if (@hasField(@TypeOf(mode_config), "exclude_arch")) { const exclude_arch: []const std.Target.Cpu.Arch = &mode_config.exclude_arch; for (exclude_arch) |arch| if (arch == builtin.cpu.arch) return; } if (@hasField(@TypeOf(mode_config), "exclude_os")) { const exclude_os: []const std.Target.Os.Tag = &mode_config.exclude_os; for (exclude_os) |os| if (os == builtin.os.tag) return; } const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s} ({s})", .{ "stack-trace", name, @tagName(mode), }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const b = self.b; const src_basename = "source.zig"; const write_src = b.addWriteFile(src_basename, source); const exe = b.addExecutableFromWriteFileStep("test", write_src, src_basename); exe.setBuildMode(mode); const run_and_compare = RunAndCompareStep.create( self, exe, annotated_case_name, mode, mode_config.expect, ); self.step.dependOn(&run_and_compare.step); } const RunAndCompareStep = struct { step: build.Step, context: *StackTracesContext, exe: *LibExeObjStep, name: []const u8, mode: Mode, expect_output: []const u8, test_index: usize, pub fn create( context: *StackTracesContext, exe: *LibExeObjStep, name: []const u8, mode: Mode, expect_output: []const u8, ) *RunAndCompareStep { const allocator = context.b.allocator; const ptr = allocator.create(RunAndCompareStep) catch unreachable; ptr.* = RunAndCompareStep{ .step = build.Step.init(.Custom, "StackTraceCompareOutputStep", allocator, make), .context = context, .exe = exe, .name = name, .mode = mode, .expect_output = expect_output, .test_index = context.test_index, }; ptr.step.dependOn(&exe.step); context.test_index += 1; return ptr; } fn make(step: *build.Step) !void { const self = @fieldParentPtr(RunAndCompareStep, "step", step); const b = self.context.b; const full_exe_path = self.exe.getOutputPath(); var args = ArrayList([]const u8).init(b.allocator); defer args.deinit(); args.append(full_exe_path) catch unreachable; warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); const child = std.ChildProcess.init(args.items, b.allocator) catch unreachable; defer child.deinit(); child.stdin_behavior = .Ignore; child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; child.env_map = b.env_map; if (b.verbose) { printInvocation(args.items); } child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) }); const stdout = child.stdout.?.reader().readAllAlloc(b.allocator, max_stdout_size) catch unreachable; defer b.allocator.free(stdout); const stderrFull = child.stderr.?.reader().readAllAlloc(b.allocator, max_stdout_size) catch unreachable; defer b.allocator.free(stderrFull); var stderr = stderrFull; const term = child.wait() catch |err| { debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) }); }; switch (term) { .Exited => |code| { const expect_code: u32 = 1; if (code != expect_code) { warn("Process {s} exited with error code {d} but expected code {d}\n", .{ full_exe_path, code, expect_code, }); printInvocation(args.items); return error.TestFailed; } }, .Signal => |signum| { warn("Process {s} terminated on signal {d}\n", .{ full_exe_path, signum }); printInvocation(args.items); return error.TestFailed; }, .Stopped => |signum| { warn("Process {s} stopped on signal {d}\n", .{ full_exe_path, signum }); printInvocation(args.items); return error.TestFailed; }, .Unknown => |code| { warn("Process {s} terminated unexpectedly with error code {d}\n", .{ full_exe_path, code }); printInvocation(args.items); return error.TestFailed; }, } // process result // - keep only basename of source file path // - replace address with symbolic string // - replace function name with symbolic string when mode != .Debug // - skip empty lines const got: []const u8 = got_result: { var buf = ArrayList(u8).init(b.allocator); defer buf.deinit(); if (stderr.len != 0 and stderr[stderr.len - 1] == '\n') stderr = stderr[0 .. stderr.len - 1]; var it = mem.split(stderr, "\n"); process_lines: while (it.next()) |line| { if (line.len == 0) continue; // offset search past `[drive]:` on windows var pos: usize = if (std.Target.current.os.tag == .windows) 2 else 0; // locate delims/anchor const delims = [_][]const u8{ ":", ":", ":", " in ", "(", ")" }; var marks = [_]usize{0} ** delims.len; for (delims) |delim, i| { marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse { // unexpected pattern: emit raw line and cont try buf.appendSlice(line); try buf.appendSlice("\n"); continue :process_lines; }; pos = marks[i] + delim.len; } // locate source basename pos = mem.lastIndexOfScalar(u8, line[0..marks[0]], fs.path.sep) orelse { // unexpected pattern: emit raw line and cont try buf.appendSlice(line); try buf.appendSlice("\n"); continue :process_lines; }; // end processing if source basename changes if (!mem.eql(u8, "source.zig", line[pos + 1 .. marks[0]])) break; // emit substituted line try buf.appendSlice(line[pos + 1 .. marks[2] + delims[2].len]); try buf.appendSlice(" [address]"); if (self.mode == .Debug) { if (mem.lastIndexOfScalar(u8, line[marks[4]..marks[5]], '.')) |idot| { // On certain platforms (windows) or possibly depending on how we choose to link main // the object file extension may be present so we simply strip any extension. try buf.appendSlice(line[marks[3] .. marks[4] + idot]); try buf.appendSlice(line[marks[5]..]); } else { try buf.appendSlice(line[marks[3]..]); } } else { try buf.appendSlice(line[marks[3] .. marks[3] + delims[3].len]); try buf.appendSlice("[function]"); } try buf.appendSlice("\n"); } break :got_result buf.toOwnedSlice(); }; if (!mem.eql(u8, self.expect_output, got)) { warn( \\ \\========= Expected this output: ========= \\{s} \\================================================ \\{s} \\ , .{ self.expect_output, got }); return error.TestFailed; } warn("OK\n", .{}); } }; }; pub const CompileErrorContext = struct { b: *build.Builder, step: *build.Step, test_index: usize, test_filter: ?[]const u8, modes: []const Mode, const TestCase = struct { name: []const u8, sources: ArrayList(SourceFile), expected_errors: ArrayList([]const u8), expect_exact: bool, link_libc: bool, is_exe: bool, is_test: bool, target: CrossTarget = CrossTarget{}, const SourceFile = struct { filename: []const u8, source: []const u8, }; pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } pub fn addExpectedError(self: *TestCase, text: []const u8) void { self.expected_errors.append(text) catch unreachable; } }; const CompileCmpOutputStep = struct { step: build.Step, context: *CompileErrorContext, name: []const u8, test_index: usize, case: *const TestCase, build_mode: Mode, write_src: *build.WriteFileStep, const ErrLineIter = struct { lines: mem.SplitIterator, const source_file = "tmp.zig"; fn init(input: []const u8) ErrLineIter { return ErrLineIter{ .lines = mem.split(input, "\n") }; } fn next(self: *ErrLineIter) ?[]const u8 { while (self.lines.next()) |line| { if (mem.indexOf(u8, line, source_file) != null) return line; } return null; } }; pub fn create( context: *CompileErrorContext, name: []const u8, case: *const TestCase, build_mode: Mode, write_src: *build.WriteFileStep, ) *CompileCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(CompileCmpOutputStep) catch unreachable; ptr.* = CompileCmpOutputStep{ .step = build.Step.init(.Custom, "CompileCmpOutput", allocator, make), .context = context, .name = name, .test_index = context.test_index, .case = case, .build_mode = build_mode, .write_src = write_src, }; context.test_index += 1; return ptr; } fn make(step: *build.Step) !void { const self = @fieldParentPtr(CompileCmpOutputStep, "step", step); const b = self.context.b; var zig_args = ArrayList([]const u8).init(b.allocator); zig_args.append(b.zig_exe) catch unreachable; if (self.case.is_exe) { try zig_args.append("build-exe"); } else if (self.case.is_test) { try zig_args.append("test"); } else { try zig_args.append("build-obj"); } const root_src_basename = self.case.sources.items[0].filename; try zig_args.append(self.write_src.getOutputPath(root_src_basename)); zig_args.append("--name") catch unreachable; zig_args.append("test") catch unreachable; if (!self.case.target.isNative()) { try zig_args.append("-target"); try zig_args.append(try self.case.target.zigTriple(b.allocator)); } zig_args.append("-O") catch unreachable; zig_args.append(@tagName(self.build_mode)) catch unreachable; warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); if (b.verbose) { printInvocation(zig_args.items); } const child = std.ChildProcess.init(zig_args.items, b.allocator) catch unreachable; defer child.deinit(); child.env_map = b.env_map; child.stdin_behavior = .Ignore; child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) }); var stdout_buf = ArrayList(u8).init(b.allocator); var stderr_buf = ArrayList(u8).init(b.allocator); child.stdout.?.reader().readAllArrayList(&stdout_buf, max_stdout_size) catch unreachable; child.stderr.?.reader().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) }); }; switch (term) { .Exited => |code| { if (code == 0) { printInvocation(zig_args.items); return error.CompilationIncorrectlySucceeded; } }, else => { warn("Process {s} terminated unexpectedly\n", .{b.zig_exe}); printInvocation(zig_args.items); return error.TestFailed; }, } const stdout = stdout_buf.items; const stderr = stderr_buf.items; if (stdout.len != 0) { warn( \\ \\Expected empty stdout, instead found: \\================================================ \\{s} \\================================================ \\ , .{stdout}); return error.TestFailed; } var ok = true; if (self.case.expect_exact) { var err_iter = ErrLineIter.init(stderr); var i: usize = 0; ok = while (err_iter.next()) |line| : (i += 1) { if (i >= self.case.expected_errors.items.len) break false; const expected = self.case.expected_errors.items[i]; if (mem.indexOf(u8, line, expected) == null) break false; continue; } else true; ok = ok and i == self.case.expected_errors.items.len; if (!ok) { warn("\n======== Expected these compile errors: ========\n", .{}); for (self.case.expected_errors.items) |expected| { warn("{s}\n", .{expected}); } } } else { for (self.case.expected_errors.items) |expected| { if (mem.indexOf(u8, stderr, expected) == null) { warn( \\ \\=========== Expected compile error: ============ \\{s} \\ , .{expected}); ok = false; break; } } } if (!ok) { warn( \\================= Full output: ================= \\{s} \\ , .{stderr}); return error.TestFailed; } warn("OK\n", .{}); } }; pub fn create( self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8, ) *TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; tc.* = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_errors = ArrayList([]const u8).init(self.b.allocator), .expect_exact = false, .link_libc = false, .is_exe = false, .is_test = false, }; tc.addSourceFile("tmp.zig", source); var arg_i: usize = 0; while (arg_i < expected_lines.len) : (arg_i += 1) { tc.addExpectedError(expected_lines[arg_i]); } return tc; } pub fn addC(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8) void { var tc = self.create(name, source, expected_lines); tc.link_libc = true; self.addCase(tc); } pub fn addExe( self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8, ) void { var tc = self.create(name, source, expected_lines); tc.is_exe = true; self.addCase(tc); } pub fn add( self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8, ) void { const tc = self.create(name, source, expected_lines); self.addCase(tc); } pub fn addTest( self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8, ) void { const tc = self.create(name, source, expected_lines); tc.is_test = true; self.addCase(tc); } pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void { const b = self.b; const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {s}", .{ case.name, }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const write_src = b.addWriteFiles(); for (case.sources.items) |src_file| { write_src.add(src_file.filename, src_file.source); } const compile_and_cmp_errors = CompileCmpOutputStep.create(self, annotated_case_name, case, .Debug, write_src); compile_and_cmp_errors.step.dependOn(&write_src.step); self.step.dependOn(&compile_and_cmp_errors.step); } }; pub const StandaloneContext = struct { b: *build.Builder, step: *build.Step, test_index: usize, test_filter: ?[]const u8, modes: []const Mode, pub fn addC(self: *StandaloneContext, root_src: []const u8) void { self.addAllArgs(root_src, true); } pub fn add(self: *StandaloneContext, root_src: []const u8) void { self.addAllArgs(root_src, false); } pub fn addBuildFile(self: *StandaloneContext, build_file: []const u8) void { const b = self.b; const annotated_case_name = b.fmt("build {s} (Debug)", .{build_file}); if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } var zig_args = ArrayList([]const u8).init(b.allocator); const rel_zig_exe = fs.path.relative(b.allocator, b.build_root, b.zig_exe) catch unreachable; zig_args.append(rel_zig_exe) catch unreachable; zig_args.append("build") catch unreachable; zig_args.append("--build-file") catch unreachable; zig_args.append(b.pathFromRoot(build_file)) catch unreachable; zig_args.append("test") catch unreachable; if (b.verbose) { zig_args.append("--verbose") catch unreachable; } const run_cmd = b.addSystemCommand(zig_args.items); const log_step = b.addLog("PASS {s}\n", .{annotated_case_name}); log_step.step.dependOn(&run_cmd.step); self.step.dependOn(&log_step.step); } pub fn addAllArgs(self: *StandaloneContext, root_src: []const u8, link_libc: bool) void { const b = self.b; for (self.modes) |mode| { const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {s} ({s})", .{ root_src, @tagName(mode), }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } const exe = b.addExecutable("test", root_src); exe.setBuildMode(mode); if (link_libc) { exe.linkSystemLibrary("c"); } const log_step = b.addLog("PASS {s}\n", .{annotated_case_name}); log_step.step.dependOn(&exe.step); self.step.dependOn(&log_step.step); } } }; pub const GenHContext = struct { b: *build.Builder, step: *build.Step, test_index: usize, test_filter: ?[]const u8, const TestCase = struct { name: []const u8, sources: ArrayList(SourceFile), expected_lines: ArrayList([]const u8), const SourceFile = struct { filename: []const u8, source: []const u8, }; pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } pub fn addExpectedLine(self: *TestCase, text: []const u8) void { self.expected_lines.append(text) catch unreachable; } }; const GenHCmpOutputStep = struct { step: build.Step, context: *GenHContext, obj: *LibExeObjStep, name: []const u8, test_index: usize, case: *const TestCase, pub fn create( context: *GenHContext, obj: *LibExeObjStep, name: []const u8, case: *const TestCase, ) *GenHCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(GenHCmpOutputStep) catch unreachable; ptr.* = GenHCmpOutputStep{ .step = build.Step.init(.Custom, "ParseCCmpOutput", allocator, make), .context = context, .obj = obj, .name = name, .test_index = context.test_index, .case = case, }; ptr.step.dependOn(&obj.step); context.test_index += 1; return ptr; } fn make(step: *build.Step) !void { const self = @fieldParentPtr(GenHCmpOutputStep, "step", step); const b = self.context.b; warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name }); const full_h_path = self.obj.getOutputHPath(); const actual_h = try io.readFileAlloc(b.allocator, full_h_path); for (self.case.expected_lines.items) |expected_line| { if (mem.indexOf(u8, actual_h, expected_line) == null) { warn( \\ \\========= Expected this output: ================ \\{s} \\========= But found: =========================== \\{s} \\ , .{ expected_line, actual_h }); return error.TestFailed; } } warn("OK\n", .{}); } }; fn printInvocation(args: []const []const u8) void { for (args) |arg| { warn("{s} ", .{arg}); } warn("\n", .{}); } pub fn create( self: *GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: []const []const u8, ) *TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; tc.* = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_lines = ArrayList([]const u8).init(self.b.allocator), }; tc.addSourceFile(filename, source); var arg_i: usize = 0; while (arg_i < expected_lines.len) : (arg_i += 1) { tc.addExpectedLine(expected_lines[arg_i]); } return tc; } pub fn add(self: *GenHContext, name: []const u8, source: []const u8, expected_lines: []const []const u8) void { const tc = self.create("test.zig", name, source, expected_lines); self.addCase(tc); } pub fn addCase(self: *GenHContext, case: *const TestCase) void { const b = self.b; const mode = builtin.Mode.Debug; const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {s} ({s})", .{ case.name, @tagName(mode) }) catch unreachable; if (self.test_filter) |filter| { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const write_src = b.addWriteFiles(); for (case.sources.items) |src_file| { write_src.add(src_file.filename, src_file.source); } const obj = b.addObjectFromWriteFileStep("test", write_src, case.sources.items[0].filename); obj.setBuildMode(mode); const cmp_h = GenHCmpOutputStep.create(self, obj, annotated_case_name, case); self.step.dependOn(&cmp_h.step); } }; fn printInvocation(args: []const []const u8) void { for (args) |arg| { warn("{s} ", .{arg}); } warn("\n", .{}); }
test/tests.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const Allocator = mem.Allocator; const debug = std.debug; const assert = debug.assert; const testing = std.testing; pub const LinearFifoBufferType = union(enum) { /// The buffer is internal to the fifo; it is of the specified size. Static: usize, /// The buffer is passed as a slice to the initialiser. Slice, /// The buffer is managed dynamically using a `mem.Allocator`. Dynamic, }; pub fn LinearFifo( comptime T: type, comptime buffer_type: LinearFifoBufferType, ) type { const autoalign = false; const powers_of_two = switch (buffer_type) { .Static => std.math.isPowerOfTwo(buffer_type.Static), .Slice => false, // Any size slice could be passed in .Dynamic => true, // This could be configurable in future }; return struct { allocator: if (buffer_type == .Dynamic) *Allocator else void, buf: if (buffer_type == .Static) [buffer_type.Static]T else []T, head: usize, count: usize, const Self = @This(); // Type of Self argument for slice operations. // If buffer is inline (Static) then we need to ensure we haven't // returned a slice into a copy on the stack const SliceSelfArg = if (buffer_type == .Static) *Self else Self; pub usingnamespace switch (buffer_type) { .Static => struct { pub fn init() Self { return .{ .allocator = {}, .buf = undefined, .head = 0, .count = 0, }; } }, .Slice => struct { pub fn init(buf: []T) Self { return .{ .allocator = {}, .buf = buf, .head = 0, .count = 0, }; } }, .Dynamic => struct { pub fn init(allocator: *Allocator) Self { return .{ .allocator = allocator, .buf = &[_]T{}, .head = 0, .count = 0, }; } }, }; pub fn deinit(self: Self) void { if (buffer_type == .Dynamic) self.allocator.free(self.buf); } pub fn realign(self: *Self) void { if (self.buf.len - self.head >= self.count) { // this copy overlaps mem.copy(T, self.buf[0..self.count], self.buf[self.head..][0..self.count]); self.head = 0; } else { var tmp: [mem.page_size / 2 / @sizeOf(T)]T = undefined; while (self.head != 0) { const n = math.min(self.head, tmp.len); const m = self.buf.len - n; mem.copy(T, tmp[0..n], self.buf[0..n]); // this middle copy overlaps; the others here don't mem.copy(T, self.buf[0..m], self.buf[n..][0..m]); mem.copy(T, self.buf[m..], tmp[0..n]); self.head -= n; } } { // set unused area to undefined const unused = mem.sliceAsBytes(self.buf[self.count..]); @memset(unused.ptr, undefined, unused.len); } } /// Reduce allocated capacity to `size`. pub fn shrink(self: *Self, size: usize) void { assert(size >= self.count); if (buffer_type == .Dynamic) { self.realign(); self.buf = self.allocator.realloc(self.buf, size) catch |e| switch (e) { error.OutOfMemory => return, // no problem, capacity is still correct then. }; } } /// Ensure that the buffer can fit at least `size` items pub fn ensureCapacity(self: *Self, size: usize) !void { if (self.buf.len >= size) return; if (buffer_type == .Dynamic) { self.realign(); const new_size = if (powers_of_two) math.ceilPowerOfTwo(usize, size) catch return error.OutOfMemory else size; self.buf = try self.allocator.realloc(self.buf, new_size); } else { return error.OutOfMemory; } } /// Makes sure at least `size` items are unused pub fn ensureUnusedCapacity(self: *Self, size: usize) error{OutOfMemory}!void { if (self.writableLength() >= size) return; return try self.ensureCapacity(math.add(usize, self.count, size) catch return error.OutOfMemory); } /// Returns number of items currently in fifo pub fn readableLength(self: Self) usize { return self.count; } /// Returns a writable slice from the 'read' end of the fifo fn readableSliceMut(self: SliceSelfArg, offset: usize) []T { if (offset > self.count) return &[_]T{}; var start = self.head + offset; if (start >= self.buf.len) { start -= self.buf.len; return self.buf[start .. self.count - offset]; } else { const end = math.min(self.head + self.count, self.buf.len); return self.buf[start..end]; } } /// Returns a readable slice from `offset` pub fn readableSlice(self: SliceSelfArg, offset: usize) []const T { return self.readableSliceMut(offset); } /// Discard first `count` items in the fifo pub fn discard(self: *Self, count: usize) void { assert(count <= self.count); { // set old range to undefined. Note: may be wrapped around const slice = self.readableSliceMut(0); if (slice.len >= count) { const unused = mem.sliceAsBytes(slice[0..count]); @memset(unused.ptr, undefined, unused.len); } else { const unused = mem.sliceAsBytes(slice[0..]); @memset(unused.ptr, undefined, unused.len); const unused2 = mem.sliceAsBytes(self.readableSliceMut(slice.len)[0 .. count - slice.len]); @memset(unused2.ptr, undefined, unused2.len); } } if (autoalign and self.count == count) { self.head = 0; self.count = 0; } else { var head = self.head + count; if (powers_of_two) { head &= self.buf.len - 1; } else { head %= self.buf.len; } self.head = head; self.count -= count; } } /// Read the next item from the fifo pub fn readItem(self: *Self) !T { if (self.count == 0) return error.EndOfStream; const c = self.buf[self.head]; self.discard(1); return c; } /// Read data from the fifo into `dst`, returns number of items copied. pub fn read(self: *Self, dst: []T) usize { var dst_left = dst; while (dst_left.len > 0) { const slice = self.readableSlice(0); if (slice.len == 0) break; const n = math.min(slice.len, dst_left.len); mem.copy(T, dst_left, slice[0..n]); self.discard(n); dst_left = dst_left[n..]; } return dst.len - dst_left.len; } /// Returns number of items available in fifo pub fn writableLength(self: Self) usize { return self.buf.len - self.count; } /// Returns the first section of writable buffer /// Note that this may be of length 0 pub fn writableSlice(self: SliceSelfArg, offset: usize) []T { if (offset > self.buf.len) return &[_]T{}; const tail = self.head + offset + self.count; if (tail < self.buf.len) { return self.buf[tail..]; } else { return self.buf[tail - self.buf.len ..][0 .. self.writableLength() - offset]; } } /// Returns a writable buffer of at least `size` items, allocating memory as needed. /// Use `fifo.update` once you've written data to it. pub fn writableWithSize(self: *Self, size: usize) ![]T { try self.ensureUnusedCapacity(size); // try to avoid realigning buffer var slice = self.writableSlice(0); if (slice.len < size) { self.realign(); slice = self.writableSlice(0); } return slice; } /// Update the tail location of the buffer (usually follows use of writable/writableWithSize) pub fn update(self: *Self, count: usize) void { assert(self.count + count <= self.buf.len); self.count += count; } /// Appends the data in `src` to the fifo. /// You must have ensured there is enough space. pub fn writeAssumeCapacity(self: *Self, src: []const T) void { assert(self.writableLength() >= src.len); var src_left = src; while (src_left.len > 0) { const writable_slice = self.writableSlice(0); assert(writable_slice.len != 0); const n = math.min(writable_slice.len, src_left.len); mem.copy(T, writable_slice, src_left[0..n]); self.update(n); src_left = src_left[n..]; } } /// Write a single item to the fifo pub fn writeItem(self: *Self, item: T) !void { try self.ensureUnusedCapacity(1); var tail = self.head + self.count; if (powers_of_two) { tail &= self.buf.len - 1; } else { tail %= self.buf.len; } self.buf[tail] = item; self.update(1); } /// Appends the data in `src` to the fifo. /// Allocates more memory as necessary pub fn write(self: *Self, src: []const T) !void { try self.ensureUnusedCapacity(src.len); return self.writeAssumeCapacity(src); } pub usingnamespace if (T == u8) struct { const OutStream = std.io.OutStream(*Self, Error, appendWrite); const Error = error{OutOfMemory}; /// Same as `write` except it returns the number of bytes written, which is always the same /// as `bytes.len`. The purpose of this function existing is to match `std.io.OutStream` API. pub fn appendWrite(fifo: *Self, bytes: []const u8) Error!usize { try fifo.write(bytes); return bytes.len; } pub fn outStream(self: *Self) OutStream { return .{ .context = self }; } } else struct {}; /// Make `count` items available before the current read location fn rewind(self: *Self, count: usize) void { assert(self.writableLength() >= count); var head = self.head + (self.buf.len - count); if (powers_of_two) { head &= self.buf.len - 1; } else { head %= self.buf.len; } self.head = head; self.count += count; } /// Place data back into the read stream pub fn unget(self: *Self, src: []const T) !void { try self.ensureUnusedCapacity(src.len); self.rewind(src.len); const slice = self.readableSliceMut(0); if (src.len < slice.len) { mem.copy(T, slice, src); } else { mem.copy(T, slice, src[0..slice.len]); const slice2 = self.readableSliceMut(slice.len); mem.copy(T, slice2, src[slice.len..]); } } /// Peek at the item at `offset` pub fn peekItem(self: Self, offset: usize) error{EndOfStream}!T { if (offset >= self.count) return error.EndOfStream; var index = self.head + offset; if (powers_of_two) { index &= self.buf.len - 1; } else { index %= self.buf.len; } return self.buf[index]; } }; } test "LinearFifo(u8, .Dynamic)" { var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator); defer fifo.deinit(); try fifo.write("HELLO"); testing.expectEqual(@as(usize, 5), fifo.readableLength()); testing.expectEqualSlices(u8, "HELLO", fifo.readableSlice(0)); { var i: usize = 0; while (i < 5) : (i += 1) { try fifo.write(&[_]u8{try fifo.peekItem(i)}); } testing.expectEqual(@as(usize, 10), fifo.readableLength()); testing.expectEqualSlices(u8, "HELLOHELLO", fifo.readableSlice(0)); } { testing.expectEqual(@as(u8, 'H'), try fifo.readItem()); testing.expectEqual(@as(u8, 'E'), try fifo.readItem()); testing.expectEqual(@as(u8, 'L'), try fifo.readItem()); testing.expectEqual(@as(u8, 'L'), try fifo.readItem()); testing.expectEqual(@as(u8, 'O'), try fifo.readItem()); } testing.expectEqual(@as(usize, 5), fifo.readableLength()); { // Writes that wrap around testing.expectEqual(@as(usize, 11), fifo.writableLength()); testing.expectEqual(@as(usize, 6), fifo.writableSlice(0).len); fifo.writeAssumeCapacity("6<chars<11"); testing.expectEqualSlices(u8, "HELLO6<char", fifo.readableSlice(0)); testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(11)); fifo.discard(11); testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(0)); fifo.discard(4); testing.expectEqual(@as(usize, 0), fifo.readableLength()); } { const buf = try fifo.writableWithSize(12); testing.expectEqual(@as(usize, 12), buf.len); var i: u8 = 0; while (i < 10) : (i += 1) { buf[i] = i + 'a'; } fifo.update(10); testing.expectEqualSlices(u8, "abcdefghij", fifo.readableSlice(0)); } { try fifo.unget("prependedstring"); var result: [30]u8 = undefined; testing.expectEqualSlices(u8, "prependedstringabcdefghij", result[0..fifo.read(&result)]); try fifo.unget("b"); try fifo.unget("a"); testing.expectEqualSlices(u8, "ab", result[0..fifo.read(&result)]); } fifo.shrink(0); { try fifo.outStream().print("{}, {}!", .{ "Hello", "World" }); var result: [30]u8 = undefined; testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]); testing.expectEqual(@as(usize, 0), fifo.readableLength()); } } test "LinearFifo" { inline for ([_]type{ u1, u8, u16, u64 }) |T| { inline for ([_]LinearFifoBufferType{ LinearFifoBufferType{ .Static = 32 }, .Slice, .Dynamic }) |bt| { const FifoType = LinearFifo(T, bt); var buf: if (bt == .Slice) [32]T else void = undefined; var fifo = switch (bt) { .Static => FifoType.init(), .Slice => FifoType.init(buf[0..]), .Dynamic => FifoType.init(testing.allocator), }; defer fifo.deinit(); try fifo.write(&[_]T{ 0, 1, 1, 0, 1 }); testing.expectEqual(@as(usize, 5), fifo.readableLength()); { testing.expectEqual(@as(T, 0), try fifo.readItem()); testing.expectEqual(@as(T, 1), try fifo.readItem()); testing.expectEqual(@as(T, 1), try fifo.readItem()); testing.expectEqual(@as(T, 0), try fifo.readItem()); testing.expectEqual(@as(T, 1), try fifo.readItem()); testing.expectEqual(@as(usize, 0), fifo.readableLength()); } { try fifo.writeItem(1); try fifo.writeItem(1); try fifo.writeItem(1); testing.expectEqual(@as(usize, 3), fifo.readableLength()); } { var readBuf: [3]T = undefined; const n = fifo.read(&readBuf); testing.expectEqual(@as(usize, 3), n); // NOTE: It should be the number of items. } } } }
lib/std/fifo.zig
const std = @import("std"); const mem = std.mem; const builtin = @import("builtin"); const Target = @import("target.zig").Target; const Compilation = @import("compilation.zig").Compilation; const introspect = @import("introspect.zig"); const assertOrPanic = std.debug.assertOrPanic; const errmsg = @import("errmsg.zig"); const ZigCompiler = @import("compilation.zig").ZigCompiler; var ctx: TestContext = undefined; test "stage2" { try ctx.init(); defer ctx.deinit(); try @import("../test/stage2/compile_errors.zig").addCases(&ctx); try @import("../test/stage2/compare_output.zig").addCases(&ctx); try ctx.run(); } const file1 = "1.zig"; const allocator = std.heap.c_allocator; pub const TestContext = struct { loop: std.event.Loop, zig_compiler: ZigCompiler, zig_lib_dir: []u8, file_index: std.atomic.Int(usize), group: std.event.Group(error!void), any_err: error!void, const tmp_dir_name = "stage2_test_tmp"; fn init(self: *TestContext) !void { self.* = TestContext{ .any_err = {}, .loop = undefined, .zig_compiler = undefined, .zig_lib_dir = undefined, .group = undefined, .file_index = std.atomic.Int(usize).init(0), }; try self.loop.initSingleThreaded(allocator); errdefer self.loop.deinit(); self.zig_compiler = try ZigCompiler.init(&self.loop); errdefer self.zig_compiler.deinit(); self.group = std.event.Group(error!void).init(&self.loop); errdefer self.group.deinit(); self.zig_lib_dir = try introspect.resolveZigLibDir(allocator); errdefer allocator.free(self.zig_lib_dir); try std.os.makePath(allocator, tmp_dir_name); errdefer std.os.deleteTree(allocator, tmp_dir_name) catch {}; } fn deinit(self: *TestContext) void { std.os.deleteTree(allocator, tmp_dir_name) catch {}; allocator.free(self.zig_lib_dir); self.zig_compiler.deinit(); self.loop.deinit(); } fn run(self: *TestContext) !void { const handle = try self.loop.call(waitForGroup, self); defer cancel handle; self.loop.run(); return self.any_err; } async fn waitForGroup(self: *TestContext) void { self.any_err = await (async self.group.wait() catch unreachable); } fn testCompileError( self: *TestContext, source: []const u8, path: []const u8, line: usize, column: usize, msg: []const u8, ) !void { var file_index_buf: [20]u8 = undefined; const file_index = try std.fmt.bufPrint(file_index_buf[0..], "{}", self.file_index.incr()); const file1_path = try std.os.path.join(allocator, tmp_dir_name, file_index, file1); if (std.os.path.dirname(file1_path)) |dirname| { try std.os.makePath(allocator, dirname); } // TODO async I/O try std.io.writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, "test", file1_path, Target.Native, Compilation.Kind.Obj, builtin.Mode.Debug, true, // is_static self.zig_lib_dir, ); errdefer comp.destroy(); comp.start(); try self.group.call(getModuleEvent, comp, source, path, line, column, msg); } fn testCompareOutputLibC( self: *TestContext, source: []const u8, expected_output: []const u8, ) !void { var file_index_buf: [20]u8 = undefined; const file_index = try std.fmt.bufPrint(file_index_buf[0..], "{}", self.file_index.incr()); const file1_path = try std.os.path.join(allocator, tmp_dir_name, file_index, file1); const output_file = try std.fmt.allocPrint(allocator, "{}-out{}", file1_path, Target(Target.Native).exeFileExt()); if (std.os.path.dirname(file1_path)) |dirname| { try std.os.makePath(allocator, dirname); } // TODO async I/O try std.io.writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, "test", file1_path, Target.Native, Compilation.Kind.Exe, builtin.Mode.Debug, false, self.zig_lib_dir, ); errdefer comp.destroy(); _ = try comp.addLinkLib("c", true); comp.link_out_file = output_file; comp.start(); try self.group.call(getModuleEventSuccess, comp, output_file, expected_output); } async fn getModuleEventSuccess( comp: *Compilation, exe_file: []const u8, expected_output: []const u8, ) !void { // TODO this should not be necessary const exe_file_2 = try std.mem.dupe(allocator, u8, exe_file); defer comp.destroy(); const build_event = await (async comp.events.get() catch unreachable); switch (build_event) { Compilation.Event.Ok => { const argv = []const []const u8{exe_file_2}; // TODO use event loop const child = try std.os.ChildProcess.exec(allocator, argv, null, null, 1024 * 1024); switch (child.term) { std.os.ChildProcess.Term.Exited => |code| { if (code != 0) { return error.BadReturnCode; } }, else => { return error.Crashed; }, } if (!mem.eql(u8, child.stdout, expected_output)) { return error.OutputMismatch; } }, Compilation.Event.Error => |err| return err, Compilation.Event.Fail => |msgs| { var stderr = try std.io.getStdErr(); try stderr.write("build incorrectly failed:\n"); for (msgs) |msg| { defer msg.destroy(); try msg.printToFile(stderr, errmsg.Color.Auto); } }, } } async fn getModuleEvent( comp: *Compilation, source: []const u8, path: []const u8, line: usize, column: usize, text: []const u8, ) !void { defer comp.destroy(); const build_event = await (async comp.events.get() catch unreachable); switch (build_event) { Compilation.Event.Ok => { @panic("build incorrectly succeeded"); }, Compilation.Event.Error => |err| { @panic("build incorrectly failed"); }, Compilation.Event.Fail => |msgs| { assertOrPanic(msgs.len != 0); for (msgs) |msg| { if (mem.endsWith(u8, msg.realpath, path) and mem.eql(u8, msg.text, text)) { const span = msg.getSpan(); const first_token = msg.getTree().tokens.at(span.first); const last_token = msg.getTree().tokens.at(span.first); const start_loc = msg.getTree().tokenLocationPtr(0, first_token); if (start_loc.line + 1 == line and start_loc.column + 1 == column) { return; } } } std.debug.warn( "\n=====source:=======\n{}\n====expected:========\n{}:{}:{}: error: {}\n", source, path, line, column, text, ); std.debug.warn("\n====found:========\n"); var stderr = try std.io.getStdErr(); for (msgs) |msg| { defer msg.destroy(); try msg.printToFile(stderr, errmsg.Color.Auto); } std.debug.warn("============\n"); return error.TestFailed; }, } } };
src-self-hosted/test.zig
const std = @import("std"); const c = @import("c.zig"); const types = @import("types.zig"); const Glyph = @import("Glyph.zig"); const Outline = @import("Outline.zig"); const Bitmap = @import("Bitmap.zig"); const Error = @import("error.zig").Error; const intToError = @import("error.zig").intToError; const GlyphSlot = @This(); pub const SubGlyphInfo = struct { index: i32, flags: u32, arg1: i32, arg2: i32, transform: types.Matrix, }; handle: c.FT_GlyphSlot, pub fn init(handle: c.FT_GlyphSlot) GlyphSlot { return GlyphSlot{ .handle = handle }; } pub fn render(self: GlyphSlot, render_mode: types.RenderMode) Error!void { return intToError(c.FT_Render_Glyph(self.handle, @enumToInt(render_mode))); } pub fn subGlyphInfo(self: GlyphSlot, sub_index: u32) Error!SubGlyphInfo { var info = std.mem.zeroes(SubGlyphInfo); try intToError(c.FT_Get_SubGlyph_Info(self.handle, sub_index, &info.index, &info.flags, &info.arg1, &info.arg2, @ptrCast(*c.FT_Matrix, &info.transform))); return info; } pub fn glyph(self: GlyphSlot) Error!Glyph { var out = std.mem.zeroes(c.FT_Glyph); try intToError(c.FT_Get_Glyph(self.handle, &out)); return Glyph.init(out); } pub fn outline(self: GlyphSlot) ?Outline { return if (self.format() == .outline) Outline.init(&self.handle.*.outline) else null; } pub fn bitmap(self: GlyphSlot) Bitmap { return Bitmap.init(self.handle.*.bitmap); } pub fn bitmapLeft(self: GlyphSlot) i32 { return self.handle.*.bitmap_left; } pub fn bitmapTop(self: GlyphSlot) i32 { return self.handle.*.bitmap_top; } pub fn linearHoriAdvance(self: GlyphSlot) i64 { return self.handle.*.linearHoriAdvance; } pub fn linearVertAdvance(self: GlyphSlot) i64 { return self.handle.*.linearVertAdvance; } pub fn advance(self: GlyphSlot) types.Vector { return @ptrCast(*types.Vector, &self.handle.*.advance).*; } pub fn format(self: GlyphSlot) Glyph.GlyphFormat { return @intToEnum(Glyph.GlyphFormat, self.handle.*.format); } pub fn metrics(self: GlyphSlot) Glyph.GlyphMetrics { return self.handle.*.metrics; }
freetype/src/GlyphSlot.zig
const std = @import("std.zig"); const builtin = @import("builtin"); pub const SpinLock = struct { state: State, const State = enum(u8) { Unlocked, Locked, }; pub const Held = struct { spinlock: *SpinLock, pub fn release(self: Held) void { @atomicStore(State, &self.spinlock.state, .Unlocked, .Release); } }; pub fn init() SpinLock { return SpinLock{ .state = .Unlocked }; } pub fn deinit(self: *SpinLock) void { self.* = undefined; } pub fn tryAcquire(self: *SpinLock) ?Held { return switch (@atomicRmw(State, &self.state, .Xchg, .Locked, .Acquire)) { .Unlocked => Held{ .spinlock = self }, .Locked => null, }; } pub fn acquire(self: *SpinLock) Held { while (true) { return self.tryAcquire() orelse { yield(); continue; }; } } pub fn yield() void { // On native windows, SwitchToThread is too expensive, // and yielding for 380-410 iterations was found to be // a nice sweet spot. Posix systems on the other hand, // especially linux, perform better by yielding the thread. switch (builtin.os) { .windows => loopHint(400), else => std.os.sched_yield() catch loopHint(1), } } /// Hint to the cpu that execution is spinning /// for the given amount of iterations. pub fn loopHint(iterations: usize) void { var i = iterations; while (i != 0) : (i -= 1) { switch (builtin.arch) { // these instructions use a memory clobber as they // flush the pipeline of any speculated reads/writes. .i386, .x86_64 => asm volatile ("pause" ::: "memory"), .arm, .aarch64 => asm volatile ("yield" ::: "memory"), else => std.os.sched_yield() catch {}, } } } }; test "spinlock" { var lock = SpinLock.init(); defer lock.deinit(); const held = lock.acquire(); defer held.release(); }
lib/std/spinlock.zig
/// combiningClass maps the code point to its combining class value. pub fn combiningClass(cp: u21) u8 { return switch (cp) { 0x334...0x338 => 1, 0x1CD4 => 1, 0x1CE2...0x1CE8 => 1, 0x20D2...0x20D3 => 1, 0x20D8...0x20DA => 1, 0x20E5...0x20E6 => 1, 0x20EA...0x20EB => 1, 0x10A39 => 1, 0x16AF0...0x16AF4 => 1, 0x1BC9E => 1, 0x1D167...0x1D169 => 1, 0x16FF0...0x16FF1 => 6, 0x93C => 7, 0x9BC => 7, 0xA3C => 7, 0xABC => 7, 0xB3C => 7, 0xC3C => 7, 0xCBC => 7, 0x1037 => 7, 0x1B34 => 7, 0x1BE6 => 7, 0x1C37 => 7, 0xA9B3 => 7, 0x110BA => 7, 0x11173 => 7, 0x111CA => 7, 0x11236 => 7, 0x112E9 => 7, 0x1133B...0x1133C => 7, 0x11446 => 7, 0x114C3 => 7, 0x115C0 => 7, 0x116B7 => 7, 0x1183A => 7, 0x11943 => 7, 0x11D42 => 7, 0x1E94A => 7, 0x3099...0x309A => 8, 0x94D => 9, 0x9CD => 9, 0xA4D => 9, 0xACD => 9, 0xB4D => 9, 0xBCD => 9, 0xC4D => 9, 0xCCD => 9, 0xD3B...0xD3C => 9, 0xD4D => 9, 0xDCA => 9, 0xE3A => 9, 0xEBA => 9, 0xF84 => 9, 0x1039...0x103A => 9, 0x1714 => 9, 0x1715 => 9, 0x1734 => 9, 0x17D2 => 9, 0x1A60 => 9, 0x1B44 => 9, 0x1BAA => 9, 0x1BAB => 9, 0x1BF2...0x1BF3 => 9, 0x2D7F => 9, 0xA806 => 9, 0xA82C => 9, 0xA8C4 => 9, 0xA953 => 9, 0xA9C0 => 9, 0xAAF6 => 9, 0xABED => 9, 0x10A3F => 9, 0x11046 => 9, 0x11070 => 9, 0x1107F => 9, 0x110B9 => 9, 0x11133...0x11134 => 9, 0x111C0 => 9, 0x11235 => 9, 0x112EA => 9, 0x1134D => 9, 0x11442 => 9, 0x114C2 => 9, 0x115BF => 9, 0x1163F => 9, 0x116B6 => 9, 0x1172B => 9, 0x11839 => 9, 0x1193D => 9, 0x1193E => 9, 0x119E0 => 9, 0x11A34 => 9, 0x11A47 => 9, 0x11A99 => 9, 0x11C3F => 9, 0x11D44...0x11D45 => 9, 0x11D97 => 9, 0x5B0 => 10, 0x5B1 => 11, 0x5B2 => 12, 0x5B3 => 13, 0x5B4 => 14, 0x5B5 => 15, 0x5B6 => 16, 0x5B7 => 17, 0x5B8 => 18, 0x5C7 => 18, 0x5B9...0x5BA => 19, 0x5BB => 20, 0x5BC => 21, 0x5BD => 22, 0x5BF => 23, 0x5C1 => 24, 0x5C2 => 25, 0xFB1E => 26, 0x64B => 27, 0x8F0 => 27, 0x64C => 28, 0x8F1 => 28, 0x64D => 29, 0x8F2 => 29, 0x618 => 30, 0x64E => 30, 0x619 => 31, 0x64F => 31, 0x61A => 32, 0x650 => 32, 0x651 => 33, 0x652 => 34, 0x670 => 35, 0x711 => 36, 0xC55 => 84, 0xC56 => 91, 0xE38...0xE39 => 103, 0xE48...0xE4B => 107, 0xEB8...0xEB9 => 118, 0xEC8...0xECB => 122, 0xF71 => 129, 0xF72 => 130, 0xF7A...0xF7D => 130, 0xF80 => 130, 0xF74 => 132, 0x321...0x322 => 202, 0x327...0x328 => 202, 0x1DD0 => 202, 0x1DCE => 214, 0x31B => 216, 0xF39 => 216, 0x1D165...0x1D166 => 216, 0x1D16E...0x1D172 => 216, 0x1DFA => 218, 0x302A => 218, 0x316...0x319 => 220, 0x31C...0x320 => 220, 0x323...0x326 => 220, 0x329...0x333 => 220, 0x339...0x33C => 220, 0x347...0x349 => 220, 0x34D...0x34E => 220, 0x353...0x356 => 220, 0x359...0x35A => 220, 0x591 => 220, 0x596 => 220, 0x59B => 220, 0x5A2...0x5A7 => 220, 0x5AA => 220, 0x5C5 => 220, 0x655...0x656 => 220, 0x65C => 220, 0x65F => 220, 0x6E3 => 220, 0x6EA => 220, 0x6ED => 220, 0x731 => 220, 0x734 => 220, 0x737...0x739 => 220, 0x73B...0x73C => 220, 0x73E => 220, 0x742 => 220, 0x744 => 220, 0x746 => 220, 0x748 => 220, 0x7F2 => 220, 0x7FD => 220, 0x859...0x85B => 220, 0x899...0x89B => 220, 0x8CF...0x8D3 => 220, 0x8E3 => 220, 0x8E6 => 220, 0x8E9 => 220, 0x8ED...0x8EF => 220, 0x8F6 => 220, 0x8F9...0x8FA => 220, 0x952 => 220, 0xF18...0xF19 => 220, 0xF35 => 220, 0xF37 => 220, 0xFC6 => 220, 0x108D => 220, 0x193B => 220, 0x1A18 => 220, 0x1A7F => 220, 0x1AB5...0x1ABA => 220, 0x1ABD => 220, 0x1ABF...0x1AC0 => 220, 0x1AC3...0x1AC4 => 220, 0x1ACA => 220, 0x1B6C => 220, 0x1CD5...0x1CD9 => 220, 0x1CDC...0x1CDF => 220, 0x1CED => 220, 0x1DC2 => 220, 0x1DCA => 220, 0x1DCF => 220, 0x1DF9 => 220, 0x1DFD => 220, 0x1DFF => 220, 0x20E8 => 220, 0x20EC...0x20EF => 220, 0xA92B...0xA92D => 220, 0xAAB4 => 220, 0xFE27...0xFE2D => 220, 0x101FD => 220, 0x102E0 => 220, 0x10A0D => 220, 0x10A3A => 220, 0x10AE6 => 220, 0x10F46...0x10F47 => 220, 0x10F4B => 220, 0x10F4D...0x10F50 => 220, 0x10F83 => 220, 0x10F85 => 220, 0x1D17B...0x1D182 => 220, 0x1D18A...0x1D18B => 220, 0x1E8D0...0x1E8D6 => 220, 0x59A => 222, 0x5AD => 222, 0x1939 => 222, 0x302D => 222, 0x302E...0x302F => 224, 0x1D16D => 226, 0x5AE => 228, 0x18A9 => 228, 0x1DF7...0x1DF8 => 228, 0x302B => 228, 0x300...0x314 => 230, 0x33D...0x344 => 230, 0x346 => 230, 0x34A...0x34C => 230, 0x350...0x352 => 230, 0x357 => 230, 0x35B => 230, 0x363...0x36F => 230, 0x483...0x487 => 230, 0x592...0x595 => 230, 0x597...0x599 => 230, 0x59C...0x5A1 => 230, 0x5A8...0x5A9 => 230, 0x5AB...0x5AC => 230, 0x5AF => 230, 0x5C4 => 230, 0x610...0x617 => 230, 0x653...0x654 => 230, 0x657...0x65B => 230, 0x65D...0x65E => 230, 0x6D6...0x6DC => 230, 0x6DF...0x6E2 => 230, 0x6E4 => 230, 0x6E7...0x6E8 => 230, 0x6EB...0x6EC => 230, 0x730 => 230, 0x732...0x733 => 230, 0x735...0x736 => 230, 0x73A => 230, 0x73D => 230, 0x73F...0x741 => 230, 0x743 => 230, 0x745 => 230, 0x747 => 230, 0x749...0x74A => 230, 0x7EB...0x7F1 => 230, 0x7F3 => 230, 0x816...0x819 => 230, 0x81B...0x823 => 230, 0x825...0x827 => 230, 0x829...0x82D => 230, 0x898 => 230, 0x89C...0x89F => 230, 0x8CA...0x8CE => 230, 0x8D4...0x8E1 => 230, 0x8E4...0x8E5 => 230, 0x8E7...0x8E8 => 230, 0x8EA...0x8EC => 230, 0x8F3...0x8F5 => 230, 0x8F7...0x8F8 => 230, 0x8FB...0x8FF => 230, 0x951 => 230, 0x953...0x954 => 230, 0x9FE => 230, 0xF82...0xF83 => 230, 0xF86...0xF87 => 230, 0x135D...0x135F => 230, 0x17DD => 230, 0x193A => 230, 0x1A17 => 230, 0x1A75...0x1A7C => 230, 0x1AB0...0x1AB4 => 230, 0x1ABB...0x1ABC => 230, 0x1AC1...0x1AC2 => 230, 0x1AC5...0x1AC9 => 230, 0x1ACB...0x1ACE => 230, 0x1B6B => 230, 0x1B6D...0x1B73 => 230, 0x1CD0...0x1CD2 => 230, 0x1CDA...0x1CDB => 230, 0x1CE0 => 230, 0x1CF4 => 230, 0x1CF8...0x1CF9 => 230, 0x1DC0...0x1DC1 => 230, 0x1DC3...0x1DC9 => 230, 0x1DCB...0x1DCC => 230, 0x1DD1...0x1DF5 => 230, 0x1DFB => 230, 0x1DFE => 230, 0x20D0...0x20D1 => 230, 0x20D4...0x20D7 => 230, 0x20DB...0x20DC => 230, 0x20E1 => 230, 0x20E7 => 230, 0x20E9 => 230, 0x20F0 => 230, 0x2CEF...0x2CF1 => 230, 0x2DE0...0x2DFF => 230, 0xA66F => 230, 0xA674...0xA67D => 230, 0xA69E...0xA69F => 230, 0xA6F0...0xA6F1 => 230, 0xA8E0...0xA8F1 => 230, 0xAAB0 => 230, 0xAAB2...0xAAB3 => 230, 0xAAB7...0xAAB8 => 230, 0xAABE...0xAABF => 230, 0xAAC1 => 230, 0xFE20...0xFE26 => 230, 0xFE2E...0xFE2F => 230, 0x10376...0x1037A => 230, 0x10A0F => 230, 0x10A38 => 230, 0x10AE5 => 230, 0x10D24...0x10D27 => 230, 0x10EAB...0x10EAC => 230, 0x10F48...0x10F4A => 230, 0x10F4C => 230, 0x10F82 => 230, 0x10F84 => 230, 0x11100...0x11102 => 230, 0x11366...0x1136C => 230, 0x11370...0x11374 => 230, 0x1145E => 230, 0x16B30...0x16B36 => 230, 0x1D185...0x1D189 => 230, 0x1D1AA...0x1D1AD => 230, 0x1D242...0x1D244 => 230, 0x1E000...0x1E006 => 230, 0x1E008...0x1E018 => 230, 0x1E01B...0x1E021 => 230, 0x1E023...0x1E024 => 230, 0x1E026...0x1E02A => 230, 0x1E130...0x1E136 => 230, 0x1E2AE => 230, 0x1E2EC...0x1E2EF => 230, 0x1E944...0x1E949 => 230, 0x315 => 232, 0x31A => 232, 0x358 => 232, 0x1DF6 => 232, 0x302C => 232, 0x35C => 233, 0x35F => 233, 0x362 => 233, 0x1DFC => 233, 0x35D...0x35E => 234, 0x360...0x361 => 234, 0x1DCD => 234, 0x345 => 240, else => 0, }; }
src/components/autogen/CombiningMap.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; //; // TODO // check if graph has a node/edge at idx or not // debug.assert indices are in bounds // node and edge iterators pub const NodeIndex = usize; pub const EdgeIndex = usize; pub const Direction = enum(usize) { const Self = @This(); Outgoing, Incoming, fn opposite(self: Self) Self { return @intToEnum(Self, (@enumToInt(self) + 1) % 2); } }; // stable graph /// data can be accessed by going like graph.nodes.items[some_idx] pub fn Graph(comptime N: type, comptime E: type) type { return struct { const Self = @This(); pub const SortError = error{CycleDetected} || Allocator.Error; pub const Node = struct { weight: N, next: ?NodeIndex, in_use: bool, edges: [2]?EdgeIndex, }; pub const Edge = struct { weight: E, start_node: NodeIndex, end_node: NodeIndex, next: [2]?EdgeIndex, in_use: bool, }; pub const EdgeReference = struct { idx: EdgeIndex, edge: *Edge, }; pub const EdgeIter = struct { graph: *const Self, curr_idx: ?EdgeIndex, direction: Direction, pub fn next(self: *EdgeIter) ?EdgeReference { const idx = self.curr_idx orelse return null; const edge = &self.graph.edges.items[idx]; self.curr_idx = edge.next[@enumToInt(self.direction)]; return EdgeReference{ .edge = edge, .idx = idx, }; } }; //; nodes: ArrayList(Node), edges: ArrayList(Edge), next_node: ?NodeIndex, next_edge: ?EdgeIndex, pub fn init(allocator: *std.mem.Allocator) Self { return Self{ .nodes = ArrayList(Node).init(allocator), .edges = ArrayList(Edge).init(allocator), .next_node = null, .next_edge = null, }; } pub fn deinit(self: *Self) void { self.edges.deinit(); self.nodes.deinit(); } pub fn clone(self: Self, allocator: *Allocator) Allocator.Error!Self { var nodes = try ArrayList(Node).initCapacity(allocator, self.nodes.items.len); errdefer nodes.deinit(); nodes.items.len = self.nodes.items.len; for (self.nodes.items) |node, i| nodes.items[i] = node; var edges = try ArrayList(Edge).initCapacity(allocator, self.edges.items.len); errdefer edges.deinit(); edges.items.len = self.edges.items.len; for (self.edges.items) |edge, i| edges.items[i] = edge; return Self{ .nodes = nodes, .edges = edges, .next_node = self.next_node, .next_edge = self.next_edge, }; } //; fn removeEdgeFromNode( self: *Self, node_idx: NodeIndex, edge_idx: EdgeIndex, direction: Direction, ) void { const edge = &self.edges.items[edge_idx]; var node = &self.nodes.items[node_idx]; const dir = @enumToInt(direction); if (node.edges[dir]) |head_idx| { if (head_idx == edge_idx) { node.edges[dir] = edge.next[dir]; } else { var find_idx: ?usize = head_idx; while (find_idx) |find_idx_| { var find_edge = self.edges.items[find_idx_]; if (find_edge.next[dir] == edge_idx) { find_edge.next = edge.next; break; } find_idx = find_edge.next[dir]; } } } } pub fn addNode(self: *Self, weight: N) Allocator.Error!NodeIndex { const idx = if (self.next_node) |idx| blk: { var node = &self.nodes.items[idx]; self.next_node = node.next; break :blk idx; } else blk: { const idx = self.nodes.items.len; try self.nodes.append(undefined); break :blk idx; }; self.nodes.items[idx] = .{ .weight = weight, .next = null, .in_use = true, .edges = .{ null, null }, }; return idx; } pub fn removeNode(self: *Self, idx: NodeIndex) void { { var iter = self.edgesDirected(idx, .Outgoing); while (iter.next()) |ref| { self.removeEdgeFromNode(ref.edge.end_node, ref.idx, .Incoming); } } { var iter = self.edgesDirected(idx, .Incoming); while (iter.next()) |ref| { self.removeEdgeFromNode(ref.edge.start_node, ref.idx, .Outgoing); } } var dead_node = &self.nodes.items[idx]; dead_node.in_use = false; dead_node.next = self.next_node; self.next_node = idx; } pub fn addEdge( self: *Self, start_idx: NodeIndex, end_idx: NodeIndex, weight: E, ) Allocator.Error!EdgeIndex { var node_start = &self.nodes.items[start_idx]; var node_end = &self.nodes.items[end_idx]; const idx = if (self.next_edge) |idx| blk: { var edge = &self.edges.items[idx]; self.next_edge = edge.next[0]; break :blk idx; } else blk: { const idx = self.edges.items.len; try self.edges.append(undefined); break :blk idx; }; self.edges.items[idx] = .{ .weight = weight, .start_node = start_idx, .end_node = end_idx, .next = .{ node_start.edges[@enumToInt(Direction.Outgoing)], node_end.edges[@enumToInt(Direction.Incoming)], }, .in_use = true, }; node_start.edges[@enumToInt(Direction.Outgoing)] = idx; node_end.edges[@enumToInt(Direction.Incoming)] = idx; return idx; } pub fn removeEdge(self: *Self, idx: EdgeIndex) void { var dead_edge = &self.edges.items[idx]; self.removeEdgeFromNode(dead_edge.start_node, idx, .Outgoing); self.removeEdgeFromNode(dead_edge.start_node, idx, .Incoming); self.removeEdgeFromNode(dead_edge.end_node, idx, .Outgoing); self.removeEdgeFromNode(dead_edge.end_node, idx, .Incoming); dead_edge.next[0] = self.next_edge; dead_edge.in_use = false; self.next_edge = idx; } pub fn edgesDirected( self: Self, idx: NodeIndex, direction: Direction, ) EdgeIter { const node = self.nodes.items[idx]; const start_idx = node.edges[@enumToInt(direction)]; return EdgeIter{ .graph = &self, .curr_idx = start_idx, .direction = direction, }; } pub fn toposort( self: Self, allocator: *Allocator, workspace_allocator: *Allocator, ) SortError![]NodeIndex { if (self.nodes.items.len == 0) { return try allocator.alloc(NodeIndex, 0); } const node_ct = self.nodes.items.len; var ret: ArrayList(NodeIndex) = ArrayList(NodeIndex).init(allocator); errdefer ret.deinit(); var marked = try workspace_allocator.alloc(bool, node_ct); defer workspace_allocator.free(marked); var visited = try workspace_allocator.alloc(bool, node_ct); defer workspace_allocator.free(visited); { var i: usize = 0; while (i < node_ct) : (i += 1) { marked[i] = false; visited[i] = false; } } var stack = try ArrayList(NodeIndex).initCapacity(workspace_allocator, node_ct); defer stack.deinit(); var check_idx: usize = 0; while (check_idx < node_ct) : (check_idx += 1) { if (!self.nodes.items[check_idx].in_use or visited[check_idx]) { continue; } try stack.append(check_idx); while (stack.items.len > 0) { const idx = stack.items[stack.items.len - 1]; marked[idx] = true; const node = self.nodes.items[idx]; var children_to_check = false; if (node.edges[@enumToInt(Direction.Outgoing)]) |_| { var edge_iter = self.edgesDirected(idx, .Outgoing); while (edge_iter.next()) |ref| { const child_idx = ref.edge.end_node; if (marked[child_idx]) { if (!visited[child_idx]) { return error.CycleDetected; } } else { try stack.append(ref.edge.end_node); children_to_check = true; } } } if (!children_to_check) { _ = stack.pop(); try ret.append(idx); visited[idx] = true; } } } std.mem.reverse(NodeIndex, ret.items); return ret.toOwnedSlice(); } }; } // tests === // TODO better tests const testing = std.testing; const expect = testing.expect; test "graph" { const alloc = testing.allocator; var g = Graph(u8, u8).init(alloc); defer g.deinit(); const a = try g.addNode('a'); const b = try g.addNode('b'); const c = try g.addNode('c'); const d = try g.addNode('d'); const e = try g.addNode('e'); const e1 = try g.addEdge(b, a, 1); const e2 = try g.addEdge(a, d, 2); const e3 = try g.addEdge(c, e, 3); const e4 = try g.addEdge(d, e, 4); // const e5 = try g.addEdge(e, a, 5); // g.removeEdge(e4); var edges = g.edgesDirected(a, .Outgoing); while (edges.next()) |ref| { // std.log.warn("\n{}\n", .{ref.edge}); } const sort = try g.toposort(alloc, alloc); defer alloc.free(sort); for (sort) |idx| { const node = g.nodes.items[idx]; // std.log.warn("{c}\n", .{node.weight}); } }
src/graph.zig
const builtin = @import("builtin"); const std = @import("std"); const mem = std.mem; const print = std.debug.print; const fs = std.fs; const ChildProcess = std.ChildProcess; const process = std.process; const render_utils = @import("render_utils.zig"); pub const TestCommand = struct { name: ?[]const u8 = null, is_inline: bool = false, mode: builtin.Mode = .Debug, link_objects: []const []const u8 = &[0][]u8{}, // target_str: ?[]const u8 = null, link_libc: bool = false, disable_cache: bool = false, // TODO make sure it's used somewhere tmp_dir_name: []const u8, // TODO, maybe this should be automated at a different level? expected_outcome: union(enum) { Success, Failure: []const u8 } = .Success, max_doc_file_size: usize = 1024 * 1024 * 1, // 1MB TODO: change? pub const obj_ext = (std.zig.CrossTarget{}).oFileExt(); }; pub fn runTest( allocator: *mem.Allocator, input_bytes: []const u8, out: anytype, env_map: *std.BufMap, zig_exe: []const u8, cmd: TestCommand, ) !void { const name = cmd.name orelse "test"; const name_plus_ext = try std.fmt.allocPrint(allocator, "{s}.zig", .{name}); const tmp_source_file_name = try fs.path.join( allocator, &[_][]const u8{ cmd.tmp_dir_name, name_plus_ext }, ); try fs.cwd().writeFile(tmp_source_file_name, input_bytes); var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); try test_args.appendSlice(&[_][]const u8{ zig_exe, "test", "--color", "on", tmp_source_file_name, }); try out.print("<pre><code class=\"shell\">$ zig test {s}.zig", .{name}); switch (cmd.mode) { .Debug => {}, else => { try test_args.appendSlice(&[_][]const u8{ "-O", @tagName(cmd.mode) }); try out.print(" -O {s}", .{@tagName(cmd.mode)}); }, } if (cmd.link_libc) { try test_args.append("-lc"); try out.print(" -lc", .{}); } // if (cmd.target_str) |triple| { // try test_args.appendSlice(&[_][]const u8{ "-target", triple }); // try out.print(" -target {}", .{triple}); // } // TODO: signal stuff var exited_with_signal = false; const result = if (cmd.expected_outcome == .Failure) ko: { const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = test_args.items, .env_map = env_map, .max_output_bytes = cmd.max_doc_file_size, }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr}); render_utils.dumpArgs(test_args.items); // return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{}); return; } }, .Signal => exited_with_signal = true, else => {}, } break :ko result; } else ok: { break :ok try render_utils.exec(allocator, env_map, cmd.max_doc_file_size, test_args.items); }; if (cmd.expected_outcome == .Failure) { const error_match = cmd.expected_outcome.Failure; if (mem.indexOf(u8, result.stderr, error_match) == null) { print("Expected to find '{s}' in stderr\n{s}\n", .{ error_match, result.stderr }); return error.ErrorMismatch; } } const escaped_stderr = try render_utils.escapeHtml(allocator, result.stderr); const escaped_stdout = try render_utils.escapeHtml(allocator, result.stdout); const colored_stderr = try render_utils.termColor(allocator, escaped_stderr); const colored_stdout = try render_utils.termColor(allocator, escaped_stdout); try out.print("\n{s}{s}</code></pre>\n", .{ colored_stderr, colored_stdout }); }
src/doctest/test.zig
const std = @import("std"); const List = std.ArrayList; const util = @import("util.zig"); const gpa = util.gpa; const tokenize = std.mem.tokenize; const parseInt = std.fmt.parseInt; const print = std.debug.print; const assert = std.debug.assert; const data = @embedFile("../data/day03.txt"); const inputType = u12; const inputBits = @typeInfo(inputType).Int.bits; const inputCounterType = std.math.Log2IntCeil(inputType); const machineType = enum { Oxygen, CO2, }; pub fn main() !void { // Parse input var inputList: List(inputType) = List(inputType).init(gpa); defer inputList.deinit(); var it = std.mem.tokenize(u8, data, "\n"); while (it.next()) |line| { if (line.len == 0) continue; const input = try parseInt(inputType, line, 2); try inputList.append(input); } assert(inputList.items[0] == 2093); // Sort the list std.sort.sort(inputType, inputList.items, {}, comptime std.sort.desc(inputType)); // Part 1 var gammaCounter: [12]usize = [_]usize{0} ** 12; var gammaThreshold = inputList.items.len / 2; for (inputList.items) |input| { var i: inputCounterType = 0; while (i < inputBits) : (i += 1) { gammaCounter[i] += (input >> i) & 1; } } var gamma: inputType = 0; var i: inputCounterType = 0; while (i < inputBits) : (i += 1) { if (gammaCounter[i] >= gammaThreshold) { gamma = gamma | (@as(inputType, 1) << i); } } assert(gamma == 1337); const result = @as(u32, gamma) * @as(u32, ~gamma); print("Gamma {} Epsilon {} Result {}\n", .{ gamma, ~gamma, result }); // Part 2 var oxygenOutput = findValue(inputList.items, .Oxygen); assert(oxygenOutput == 1599); print("Oxygen {}\n", .{oxygenOutput}); var co2Output = findValue(inputList.items, .CO2); assert(co2Output == 2756); print("CO2 {}\n", .{co2Output}); var lifeSupport = @as(u32, oxygenOutput) * @as(u32, co2Output); print("Life Support {}\n", .{lifeSupport}); assert(lifeSupport == 4406844); } fn findInputSplit(input: []inputType, bit: inputCounterType) ?usize { var mask = (@as(inputType, 1) << bit); for (input) |item, index| { if ((item & mask) != mask) { return index; } } return null; } fn findValue(input: []inputType, machine: machineType) inputType { var i: inputCounterType = inputBits; var items: []inputType = input[0..]; while (i > 0) { i -= 1; if (items.len == 1) { return items[0]; } var threshold = (items.len + 1) / 2; var index = findInputSplit(items, i) orelse continue; if (index >= threshold) { if (machine == .Oxygen) { items = items[0..index]; } else { items = items[index..]; } } else { if (machine == .Oxygen) { items = items[index..]; } else { items = items[0..index]; } } } assert(items.len == 1); return items[0]; }
src/day03.zig
const std = @import("std"); const io = std.io; const math = std.math; const mem = std.mem; const testing = std.testing; fn testBfMethod(comptime method: anytype, comptime program: []const u8, result: []const u8) !void { var in = [_]u8{0} ** 1024; var out = [_]u8{0} ** 1024; var tape = [_]u8{0} ** 1024; var reader = io.fixedBufferStream(&in); var writer = io.fixedBufferStream(&out); try method(program, &tape, reader.reader(), writer.writer()); try testing.expect(mem.startsWith(u8, &out, result)); } fn load(m: []const u8, ptr: usize) !u8 { if (m.len <= ptr) return error.OutOfBounds; return m[ptr]; } fn store(m: []u8, ptr: usize, v: u8) !void { if (m.len <= ptr) return error.OutOfBounds; m[ptr] = v; } fn add(m: []u8, ptr: usize, v: u8) !void { var res: u8 = try load(m, ptr); store(m, ptr, res +% v) catch unreachable; } fn sub(m: []u8, ptr: usize, v: u8) !void { var res: u8 = try load(m, ptr); store(m, ptr, res -% v) catch unreachable; } pub fn interpret(program: []const u8, tape: []u8, reader: anytype, writer: anytype) !void { var ip: usize = 0; var mp: usize = 0; while (ip < program.len) : (ip += 1) { switch (try load(program, ip)) { '>' => mp = math.add(usize, mp, 1) catch return error.OutOfBounds, '<' => mp = math.sub(usize, mp, 1) catch return error.OutOfBounds, '+' => try add(tape, mp, 1), '-' => try sub(tape, mp, 1), '.' => try writer.writeByte(try load(tape, mp)), ',' => try store(tape, mp, try reader.readByte()), '[' => { if ((try load(tape, mp)) == 0) { var skips: usize = 1; while (skips != 0) { ip = math.add(usize, ip, 1) catch return error.OutOfBounds; switch (try load(program, ip)) { '[' => skips += 1, ']' => skips -= 1, else => {}, } } } }, ']' => { if ((try load(tape, mp)) != 0) { var skips: usize = 1; while (skips != 0) { ip = math.sub(usize, ip, 1) catch return error.OutOfBounds; switch (try load(program, ip)) { '[' => skips -= 1, ']' => skips += 1, else => {}, } } } }, else => {}, } } } test "bf.interpret" { try testBfMethod( interpret, "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.", "Hello World!\n", ); } pub fn compile(comptime program: []const u8, tape: []u8, reader: anytype, writer: anytype) !void { var mp: usize = 0; return try compileHelper(program, &mp, tape, reader, writer); } fn compileHelper(comptime program: []const u8, mp: *usize, tape: []u8, reader: anytype, writer: anytype) !void { comptime var ip = 0; inline while (ip < program.len) : (ip += 1) { switch (program[ip]) { '>' => mp.* = math.add(usize, mp.*, 1) catch return error.OutOfBounds, '<' => mp.* = math.sub(usize, mp.*, 1) catch return error.OutOfBounds, '+' => try add(tape, mp.*, 1), '-' => try sub(tape, mp.*, 1), '.' => try writer.writeByte(try load(tape, mp.*)), ',' => try store(tape, mp.*, try reader.readByte()), '[' => { const start = ip + 1; const end = comptime blk: { var skips: usize = 1; while (skips != 0) { ip += 1; switch (program[ip]) { '[' => skips += 1, ']' => skips -= 1, else => {}, } } break :blk ip; }; while ((try load(tape, mp.*)) != 0) { try compileHelper(program[start..end], mp, tape, reader, writer); } }, ']' => comptime unreachable, else => {}, } } } test "bf.compile" { try testBfMethod( compile, "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.", "Hello World!\n", ); }
bf.zig
//! Xoroshiro128+ - http://xoroshiro.di.unimi.it/ //! //! PRNG const std = @import("std"); const Random = std.rand.Random; const math = std.math; const Xoroshiro128 = @This(); random: Random, s: [2]u64, pub fn init(init_s: u64) Xoroshiro128 { var x = Xoroshiro128{ .random = Random{ .fillFn = fill }, .s = undefined, }; x.seed(init_s); return x; } fn next(self: *Xoroshiro128) u64 { const s0 = self.s[0]; var s1 = self.s[1]; const r = s0 +% s1; s1 ^= s0; self.s[0] = math.rotl(u64, s0, @as(u8, 55)) ^ s1 ^ (s1 << 14); self.s[1] = math.rotl(u64, s1, @as(u8, 36)); return r; } // Skip 2^64 places ahead in the sequence fn jump(self: *Xoroshiro128) void { var s0: u64 = 0; var s1: u64 = 0; const table = [_]u64{ 0xbeac0467eba5facb, 0xd86b048b86aa9922, }; inline for (table) |entry| { var b: usize = 0; while (b < 64) : (b += 1) { if ((entry & (@as(u64, 1) << @intCast(u6, b))) != 0) { s0 ^= self.s[0]; s1 ^= self.s[1]; } _ = self.next(); } } self.s[0] = s0; self.s[1] = s1; } pub fn seed(self: *Xoroshiro128, init_s: u64) void { // Xoroshiro requires 128-bits of seed. var gen = std.rand.SplitMix64.init(init_s); self.s[0] = gen.next(); self.s[1] = gen.next(); } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Xoroshiro128, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 8 byte segments. while (i < aligned_len) : (i += 8) { var n = self.next(); comptime var j: usize = 0; inline while (j < 8) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 8; } } } test "xoroshiro sequence" { var r = Xoroshiro128.init(0); r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; const seq1 = [_]u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, 0xabe633c971efa045, 0x9ac19f9706ca3cac, 0xf62b426578c1e3fb, }; for (seq1) |s| { std.testing.expect(s == r.next()); } r.jump(); const seq2 = [_]u64{ 0x95344a13556d3e22, 0xb4fb32dafa4d00df, 0xb2011d9ccdcfe2dd, 0x05679a9b2119b908, 0xa860a1da7c9cd8a0, 0x658a96efe3f86550, }; for (seq2) |s| { std.testing.expect(s == r.next()); } }
lib/std/rand/Xoroshiro128.zig
const std = @import("std"); const main = @import("main.zig"); const builtin = std.builtin; const executeLine = main.executeLine; const shigError = main.shigError; const BuiltinType = enum { cd, @"export", exit, type, }; fn builtinCd(ally: *std.mem.Allocator, argv: [][]const u8) !void { const stdout = std.io.getStdOut().writer(); std.debug.assert(std.mem.eql(u8, "cd", argv[0])); // cd was called wrong var operand: []const u8 = undefined; for (argv[1..]) |a| { if (a[0] != '-') { // without a dash it's an operand operand = a; } else if (std.mem.eql(u8, a, "-")) { // singular dash means go back to previous directory const newdir = main.env_map.get("OLDPWD"); if (newdir) |nd| { const d = try std.mem.dupe(ally, u8, nd); defer ally.free(d); try stdout.print("{s}\n", .{d}); try cd(ally, d); } else { try shigError("cd: OLDPWD not set", .{}); } return; } else { // Otherwise it's a flag try shigError("cd: TODO illegal option {s} (flags are not supported yet)", .{a}); return; } } if (argv.len == 1) { const home = std.process.getEnvVarOwned(ally, "HOME") catch |e| { switch (e) { error.EnvironmentVariableNotFound => try shigError("cd: HOME not set", .{}), else => try shigError("cd: {s}: TODO", .{@errorName(e)}), } return; }; defer ally.free(home); try cd(ally, home); return; } std.debug.assert(argv.len >= 2); // we have already handled the case where we cd home if (argv.len != 2) { try shigError("cd: too many arguments", .{}); } else { try cd(ally, operand); } } fn cd(ally: *std.mem.Allocator, p: []const u8) !void { const cwd = try std.process.getCwdAlloc(ally); defer ally.free(cwd); try main.env_map.put("OLDPWD", cwd); std.process.changeCurDir(p) catch |e| switch (e) { error.AccessDenied => try shigError("cd: {s}: Permission denied", .{p}), error.FileNotFound => try shigError("cd: {s}: No such file or directory", .{p}), error.NotDir => try shigError("cd: {s}: Not a directory", .{p}), // TODO // error.FileSystem => {}, // error.SymLinkLoop => {}, // error.NameTooLong => {}, // error.SystemResources => {}, // error.BadPathName => {}, else => try shigError("cd: {s}: TODO", .{@errorName(e)}), }; } fn builtinExit(argv: [][]const u8) !void { std.debug.assert(std.mem.eql(u8, "exit", argv[0])); // exit was called wrong if (argv.len > 2) { try shigError("exit: too many arguments", .{}); } else if (argv.len == 1) { std.process.exit(0); } else { const exit_num = std.fmt.parseInt(u8, argv[1], 10) catch |e| switch (e) { error.Overflow => std.process.exit(std.math.maxInt(u8)), error.InvalidCharacter => std.process.exit(0), }; std.process.exit(exit_num); } } fn builtinExport(argv: [][]const u8) !void { std.debug.assert(std.mem.eql(u8, "export", argv[0])); // export was called wrong const stdout = std.io.getStdOut().writer(); if (argv.len == 1) { var env_iter = main.env_map.iterator(); while (env_iter.next()) |envvar| { try stdout.print("{s}={s}\n", .{ envvar.key_ptr.*, envvar.value_ptr.* }); } } else { for (argv[1..]) |a| { const eql_position = std.mem.indexOf(u8, a, "="); if (eql_position) |pos| { const name = a[0..pos]; const word = a[pos + 1 ..]; try main.env_map.put(name, word); } else { try shigError("export: TODO export existing variables", .{}); } } } } fn builtinType(ally: *std.mem.Allocator, argv: [][]const u8) !void { std.debug.assert(std.mem.eql(u8, "type", argv[0])); // type was called wrong const stdout = std.io.getStdOut().writer(); if (argv.len == 1) { return; } else { for (argv[1..]) |a| { // TODO aliases first if (std.meta.stringToEnum(BuiltinType, a) != null) { try stdout.print("{s} is a shell builtin\n", .{a}); continue; } if (try main.getProgFromPath(ally, a)) |p| { try stdout.print("{s} is {s}\n", .{ a, p }); ally.free(p); continue; } try shigError("{s}: not found", .{a}); // TODO functions } } } /// true if it used a builtin, false if not pub fn handleBuiltin(argv: [][]const u8, ally: *std.mem.Allocator) !bool { std.debug.assert(argv.len > 0); switch (std.meta.stringToEnum(BuiltinType, argv[0]) orelse return false) { .cd => try builtinCd(ally, argv), .@"export" => try builtinExport(argv), .exit => try builtinExit(argv), .type => try builtinType(ally, argv), } return true; } test "cd" { const ally = std.testing.allocator; try main.init(ally); defer main.deinit(); const old_cwd = try std.process.getCwdAlloc(ally); defer ally.free(old_cwd); try executeLine(ally, "cd"); try executeLine(ally, "cd -"); try executeLine(ally, "cd /tmp"); try executeLine(ally, "cd -"); const new_cwd = try std.process.getCwdAlloc(ally); defer ally.free(new_cwd); try std.testing.expectEqualStrings(new_cwd, old_cwd); } test "export" { const ally = std.testing.allocator; try main.init(ally); defer main.deinit(); try std.testing.expect(main.env_map.get("SHIG_TEST_ENV_VAR") == null); try executeLine(ally, "export SHIG_TEST_ENV_VAR=shig_sucess"); try std.testing.expectEqualStrings(main.env_map.get("SHIG_TEST_ENV_VAR").?, "shig_sucess"); }
src/builtins.zig
const c = @import("c.zig"); const utils = @import("utils.zig"); /// Error set pub const Error = error{ InvalidBinding, NoEmptyBinding }; /// Input info pub const Info = struct { /// States pub const State = enum { none = 0, pressed, down, released }; /// For managing key / button states /// I prefer call them as bindings pub const BindingManager = struct { status: State = State.none, key: i16 = empty_binding, }; /// Maximum key count pub const max_key_count: u8 = 50; /// Maximum mouse button count pub const max_mbutton_count: u8 = 5; /// Empty binding pub const empty_binding: i16 = -1; /// Binded key list key_list: [max_key_count]BindingManager = undefined, /// Binded mouse button list mbutton_list: [max_mbutton_count]BindingManager = undefined, /// Clears the key bindings pub fn clearKeyBindings(self: *Info) void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { l[i] = BindingManager{}; } } /// Clears the mouse button bindings pub fn clearMButtonBindings(self: *Info) void { var i: u8 = 0; var l = &self.mbutton_list; while (i < max_mbutton_count) : (i += 1) { l[i] = BindingManager{}; } } /// Clears all the bindings pub fn clearAllBindings(self: *Info) void { self.clearKeyBindings(); self.clearMButtonBindings(); } /// Binds a key pub fn bindKey(self: *Info, key: i16) Error!void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (i == empty_binding) { continue; } else if (l[i].key == empty_binding) { l[i].key = key; l[i].status = State.none; return; } } return Error.NoEmptyBinding; } /// Unbinds a key pub fn unbindKey(self: *Info, key: i16) Error!void { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { l[i] = BindingManager{}; return; } } return Error.InvalidBinding; } /// Binds a mouse button pub fn bindMButton(self: *Info, key: i16) Error!void { var i: u8 = 0; var l = &self.mbutton_list; while (i < max_mbutton_count) : (i += 1) { if (i == empty_binding) { continue; } else if (l[i].key == empty_binding) { l[i].key = key; l[i].status = State.none; return; } } return Error.NoEmptyBinding; } /// Unbinds a mouse button pub fn unbindMButton(self: *Info, key: i16) Error!void { var i: u8 = 0; var l = &self.mbutton_list; while (i < max_mbutton_count) : (i += 1) { if (l[i].key == key) { l[i] = BindingManager{}; return; } } return Error.InvalidBinding; } /// Returns a binded key state pub fn keyState(self: *Info, key: i16) Error!State { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { return l[i].status; } } return Error.InvalidBinding; } /// Returns a const reference to a binded key state pub fn keyStatePtr(self: *Info, key: i16) Error!*const State { var i: u8 = 0; var l = &self.key_list; while (i < max_key_count) : (i += 1) { if (l[i].key == key) { return &l[i].status; } } return Error.InvalidBinding; } /// Returns a binded key state pub fn mbuttonState(self: *Info, key: i16) Error!State { var i: u8 = 0; var l = &self.mbutton_list; while (i < max_mbutton_count) : (i += 1) { if (l[i].key == key) { return l[i].status; } } return Error.InvalidBinding; } /// Returns a const reference to a binded key state pub fn mbuttonStatePtr(self: *Info, key: i16) Error!*const State { var i: u8 = 0; var l = &self.mbutton_list; while (i < max_mbutton_count) : (i += 1) { if (l[i].key == key) { return &l[i].status; } } return Error.InvalidBinding; } /// Returns a value based on the given states pub fn getValue(comptime rtype: type, left: State, right: State) rtype { var r: rtype = undefined; if (left == .down) r -= 1; if (right == .down) r += 1; return r; } /// Handles the inputs /// Warning: Call just before polling/processing the events /// Keep in mind binding states will be useless after polling events pub fn handle(self: *Info) void { var i: u8 = 0; while (i < max_key_count) : (i += 1) { if (i < max_mbutton_count) { var l = &self.mbutton_list[i]; if (l.key == empty_binding) {} else if (l.status == State.released) { l.status = State.none; } else if (l.status == State.pressed) { l.status = State.down; } } var l = &self.key_list[i]; if (l.key == empty_binding) { continue; } else if (l.status == State.released) { l.status = State.none; } else if (l.status == State.pressed) { l.status = State.down; } } } /// Handles the keyboard inputs pub fn handleKeyboard(input: *Info, key: i32, ac: i32) !void { var l = &input.key_list; var i: u8 = 0; while (i < Info.max_key_count) : (i += 1) { if (l[i].key != key) { continue; } switch (ac) { 0 => { if (l[i].status == Info.State.released) { l[i].status = Info.State.none; } else if (l[i].status == Info.State.down) { l[i].status = Info.State.released; } }, 1, 2 => { if (l[i].status != Info.State.down) l[i].status = Info.State.pressed; }, else => { try utils.check(true, "kira/input -> unknown action!", .{}); }, } } } /// Handles the mouse button inputs pub fn handleMButton(input: *Info, key: i32, ac: i32) !void { var l = &input.mbutton_list; var i: u8 = 0; while (i < Info.max_mbutton_count) : (i += 1) { if (l[i].key != key) { continue; } switch (ac) { 0 => { if (l[i].status == Info.State.released) { l[i].status = Info.State.none; } else if (l[i].status == Info.State.down) { l[i].status = Info.State.released; } }, 1, 2 => { if (l[i].status != Info.State.down) l[i].status = Info.State.pressed; }, else => { try utils.check(true, "kira/input -> unknown action!", .{}); }, } } } };
src/kiragine/kira/input.zig
// This is an implementation of the default "tiled" layout of dwm and the // 3 other orientations thereof. This code is written for the main stack // to the left and then the input/output values are adjusted to apply // the necessary transformations to derive the other orientations. // // With 4 views and one main on the left, the layout looks something like this: // // +-----------------------+------------+ // | | | // | | | // | | | // | +------------+ // | | | // | | | // | | | // | +------------+ // | | | // | | | // | | | // +-----------------------+------------+ const std = @import("std"); const mem = std.mem; const math = std.math; const os = std.os; const assert = std.debug.assert; const wayland = @import("wayland"); const wl = wayland.client.wl; const river = wayland.client.river; const flags = @import("flags"); const usage = \\usage: rivertile [options] \\ \\ -h Print this help message and exit. \\ -version Print the version number and exit. \\ -view-padding Set the padding around views in pixels. (Default 6) \\ -outer-padding Set the padding around the edge of the layout area in \\ pixels. (Default 6) \\ -main-location Set the initial location of the main area in the \\ layout. (Default left) \\ -main-count Set the initial number of views in the main area of the \\ layout. (Default 1) \\ -main-ratio Set the initial ratio of main area to total layout \\ area. (Default: 0.6) \\ ; const Command = enum { @"main-location", @"main-count", @"main-ratio", }; const Location = enum { top, right, bottom, left, }; // Configured through command line options var view_padding: u32 = 6; var outer_padding: u32 = 6; var default_main_location: Location = .left; var default_main_count: u32 = 1; var default_main_ratio: f64 = 0.6; /// We don't free resources on exit, only when output globals are removed. const gpa = std.heap.c_allocator; const Context = struct { initialized: bool = false, layout_manager: ?*river.LayoutManagerV3 = null, outputs: std.TailQueue(Output) = .{}, fn addOutput(context: *Context, registry: *wl.Registry, name: u32) !void { const wl_output = try registry.bind(name, wl.Output, 3); errdefer wl_output.release(); const node = try gpa.create(std.TailQueue(Output).Node); errdefer gpa.destroy(node); try node.data.init(context, wl_output, name); context.outputs.append(node); } }; const Output = struct { wl_output: *wl.Output, name: u32, main_location: Location, main_count: u32, main_ratio: f64, layout: *river.LayoutV3 = undefined, fn init(output: *Output, context: *Context, wl_output: *wl.Output, name: u32) !void { output.* = .{ .wl_output = wl_output, .name = name, .main_location = default_main_location, .main_count = default_main_count, .main_ratio = default_main_ratio, }; if (context.initialized) try output.getLayout(context); } fn getLayout(output: *Output, context: *Context) !void { assert(context.initialized); output.layout = try context.layout_manager.?.getLayout(output.wl_output, "rivertile"); output.layout.setListener(*Output, layoutListener, output); } fn deinit(output: *Output) void { output.wl_output.release(); output.layout.destroy(); } fn layoutListener(layout: *river.LayoutV3, event: river.LayoutV3.Event, output: *Output) void { switch (event) { .namespace_in_use => fatal("namespace 'rivertile' already in use.", .{}), .user_command => |ev| { var it = mem.tokenize(mem.span(ev.command), " "); const raw_cmd = it.next() orelse { std.log.err("not enough arguments", .{}); return; }; const raw_arg = it.next() orelse { std.log.err("not enough arguments", .{}); return; }; if (it.next() != null) { std.log.err("too many arguments", .{}); return; } const cmd = std.meta.stringToEnum(Command, raw_cmd) orelse { std.log.err("unknown command: {s}", .{raw_cmd}); return; }; switch (cmd) { .@"main-location" => { output.main_location = std.meta.stringToEnum(Location, raw_arg) orelse { std.log.err("unknown location: {s}", .{raw_arg}); return; }; }, .@"main-count" => { const arg = std.fmt.parseInt(i32, raw_arg, 10) catch |err| { std.log.err("failed to parse argument: {}", .{err}); return; }; switch (raw_arg[0]) { '+' => output.main_count = math.add( u32, output.main_count, @intCast(u32, arg), ) catch math.maxInt(u32), '-' => { const result = @as(i33, output.main_count) + arg; if (result >= 0) output.main_count = @intCast(u32, result); }, else => output.main_count = @intCast(u32, arg), } }, .@"main-ratio" => { const arg = std.fmt.parseFloat(f64, raw_arg) catch |err| { std.log.err("failed to parse argument: {}", .{err}); return; }; switch (raw_arg[0]) { '+', '-' => { output.main_ratio = math.clamp(output.main_ratio + arg, 0.1, 0.9); }, else => output.main_ratio = math.clamp(arg, 0.1, 0.9), } }, } }, .layout_demand => |ev| { const main_count = math.clamp(output.main_count, 1, ev.view_count); const secondary_count = if (ev.view_count > main_count) ev.view_count - main_count else 0; const usable_width = switch (output.main_location) { .left, .right => ev.usable_width - 2 * outer_padding, .top, .bottom => ev.usable_height - 2 * outer_padding, }; const usable_height = switch (output.main_location) { .left, .right => ev.usable_height - 2 * outer_padding, .top, .bottom => ev.usable_width - 2 * outer_padding, }; // to make things pixel-perfect, we make the first main and first secondary // view slightly larger if the height is not evenly divisible var main_width: u32 = undefined; var main_height: u32 = undefined; var main_height_rem: u32 = undefined; var secondary_width: u32 = undefined; var secondary_height: u32 = undefined; var secondary_height_rem: u32 = undefined; if (main_count > 0 and secondary_count > 0) { main_width = @floatToInt(u32, output.main_ratio * @intToFloat(f64, usable_width)); main_height = usable_height / main_count; main_height_rem = usable_height % main_count; secondary_width = usable_width - main_width; secondary_height = usable_height / secondary_count; secondary_height_rem = usable_height % secondary_count; } else if (main_count > 0) { main_width = usable_width; main_height = usable_height / main_count; main_height_rem = usable_height % main_count; } else if (secondary_width > 0) { main_width = 0; secondary_width = usable_width; secondary_height = usable_height / secondary_count; secondary_height_rem = usable_height % secondary_count; } var i: u32 = 0; while (i < ev.view_count) : (i += 1) { var x: i32 = undefined; var y: i32 = undefined; var width: u32 = undefined; var height: u32 = undefined; if (i < main_count) { x = 0; y = @intCast(i32, (i * main_height) + if (i > 0) main_height_rem else 0); width = main_width; height = main_height + if (i == 0) main_height_rem else 0; } else { x = @intCast(i32, main_width); y = @intCast(i32, (i - main_count) * secondary_height + if (i > main_count) secondary_height_rem else 0); width = secondary_width; height = secondary_height + if (i == main_count) secondary_height_rem else 0; } x += @intCast(i32, view_padding); y += @intCast(i32, view_padding); width -= 2 * view_padding; height -= 2 * view_padding; switch (output.main_location) { .left => layout.pushViewDimensions( x + @intCast(i32, outer_padding), y + @intCast(i32, outer_padding), width, height, ev.serial, ), .right => layout.pushViewDimensions( @intCast(i32, usable_width - width) - x + @intCast(i32, outer_padding), y + @intCast(i32, outer_padding), width, height, ev.serial, ), .top => layout.pushViewDimensions( y + @intCast(i32, outer_padding), x + @intCast(i32, outer_padding), height, width, ev.serial, ), .bottom => layout.pushViewDimensions( y + @intCast(i32, outer_padding), @intCast(i32, usable_width - width) - x + @intCast(i32, outer_padding), height, width, ev.serial, ), } } switch (output.main_location) { .left => layout.commit("rivertile - left", ev.serial), .right => layout.commit("rivertile - right", ev.serial), .top => layout.commit("rivertile - top", ev.serial), .bottom => layout.commit("rivertile - bottom", ev.serial), } }, } } }; pub fn main() !void { // https://github.com/ziglang/zig/issues/7807 const argv: [][*:0]const u8 = os.argv; const result = flags.parse(argv[1..], &[_]flags.Flag{ .{ .name = "-h", .kind = .boolean }, .{ .name = "-version", .kind = .boolean }, .{ .name = "-view-padding", .kind = .arg }, .{ .name = "-outer-padding", .kind = .arg }, .{ .name = "-main-location", .kind = .arg }, .{ .name = "-main-count", .kind = .arg }, .{ .name = "-main-ratio", .kind = .arg }, }) catch { try std.io.getStdErr().writeAll(usage); os.exit(1); }; if (result.boolFlag("-h")) { try std.io.getStdOut().writeAll(usage); os.exit(0); } if (result.args.len != 0) fatalPrintUsage("unknown option '{s}'", .{result.args[0]}); if (result.boolFlag("-version")) { try std.io.getStdOut().writeAll(@import("build_options").version ++ "\n"); os.exit(0); } if (result.argFlag("-view-padding")) |raw| { view_padding = std.fmt.parseUnsigned(u32, mem.span(raw), 10) catch fatalPrintUsage("invalid value '{s}' provided to -view-padding", .{raw}); } if (result.argFlag("-outer-padding")) |raw| { outer_padding = std.fmt.parseUnsigned(u32, mem.span(raw), 10) catch fatalPrintUsage("invalid value '{s}' provided to -outer-padding", .{raw}); } if (result.argFlag("-main-location")) |raw| { default_main_location = std.meta.stringToEnum(Location, mem.span(raw)) orelse fatalPrintUsage("invalid value '{s}' provided to -main-location", .{raw}); } if (result.argFlag("-main-count")) |raw| { default_main_count = std.fmt.parseUnsigned(u32, mem.span(raw), 10) catch fatalPrintUsage("invalid value '{s}' provided to -main-count", .{raw}); } if (result.argFlag("-main-ratio")) |raw| { default_main_ratio = std.fmt.parseFloat(f64, mem.span(raw)) catch fatalPrintUsage("invalid value '{s}' provided to -main-ratio", .{raw}); } const display = wl.Display.connect(null) catch { std.debug.warn("Unable to connect to Wayland server.\n", .{}); os.exit(1); }; defer display.disconnect(); var context: Context = .{}; const registry = try display.getRegistry(); registry.setListener(*Context, registryListener, &context); _ = try display.roundtrip(); if (context.layout_manager == null) { fatal("wayland compositor does not support river-layout-v3.\n", .{}); } context.initialized = true; var it = context.outputs.first; while (it) |node| : (it = node.next) { const output = &node.data; try output.getLayout(&context); } while (true) _ = try display.dispatch(); } fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, context: *Context) void { switch (event) { .global => |global| { if (std.cstr.cmp(global.interface, river.LayoutManagerV3.getInterface().name) == 0) { context.layout_manager = registry.bind(global.name, river.LayoutManagerV3, 1) catch return; } else if (std.cstr.cmp(global.interface, wl.Output.getInterface().name) == 0) { context.addOutput(registry, global.name) catch |err| fatal("failed to bind output: {}", .{err}); } }, .global_remove => |ev| { var it = context.outputs.first; while (it) |node| : (it = node.next) { const output = &node.data; if (output.name == ev.name) { context.outputs.remove(node); output.deinit(); gpa.destroy(node); break; } } }, } } fn fatal(comptime format: []const u8, args: anytype) noreturn { std.log.err(format, args); os.exit(1); } fn fatalPrintUsage(comptime format: []const u8, args: anytype) noreturn { std.log.err(format, args); std.io.getStdErr().writeAll(usage) catch {}; os.exit(1); }
source/river-0.1.0/rivertile/main.zig
const std = @import("std"); const testing = std.testing; const print = std.debug.print; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const input = @embedFile("./input.txt"); pub fn main() anyerror!void { print("--- Part One ---\n", .{}); print("Result: {d}\n", .{part1()}); print("--- Part Two ---\n", .{}); print("Result: {d}\n", .{part2()}); } /// /// --- Part One --- /// fn part1() !u64 { var report = try readReport(input); var numbers = try parseNumbers(report); var bit: u64 = report[0].len; const master_mask = std.math.pow(u64, 2, bit) - 1; var mask = master_mask + 1; var gamma: u64 = 0; while (bit > 0) : (bit -= 1) { mask /= 2; var count: u64 = 0; for (numbers) |number| { if (number & mask != 0) { count += 1; } } if (2 * count >= numbers.len) { gamma |= mask; } } return gamma * (master_mask - gamma); } test "day03.part1" { try testing.expectEqual(@as(u64, 3985686), try part1()); } /// /// --- Part Two --- /// fn part2() !u64 { var report = try readReport(input); var numbers = try parseNumbers(report); var oxygen = try determineRating(report[0].len, numbers, 1); var co2 = try determineRating(report[0].len, numbers, 0); return oxygen * co2; } test "day03.part2" { try testing.expectEqual(@as(u64, 2555739), try part2()); } fn readReport(whole_input: []const u8) ![][]const u8 { var report = ArrayList([]const u8).init(std.heap.page_allocator); defer report.deinit(); var lines_iter = std.mem.split(u8, std.mem.trimRight(u8, whole_input, "\n"), "\n"); while (lines_iter.next()) |line| { try report.append(line); } return report.toOwnedSlice(); } fn parseNumbers(report: [][]const u8) ![]u64 { var numbers = ArrayList(u64).init(std.heap.page_allocator); defer numbers.deinit(); for (report) |line| { try numbers.append(try std.fmt.parseInt(u64, line, 2)); } return numbers.toOwnedSlice(); } fn determineRating(len: u64, numbers: []u64, crit: u1) !u64 { var bit = len; var rating = numbers; while (rating.len > 1 and bit > 0) : (bit -= 1) { var mask = std.math.pow(u64, 2, bit - 1); var rating_one = ArrayList(u64).init(std.heap.page_allocator); defer rating_one.deinit(); var rating_nil = ArrayList(u64).init(std.heap.page_allocator); defer rating_nil.deinit(); for (rating) |r| { if (r & mask == 0) { try rating_nil.append(r); } else { try rating_one.append(r); } } if (rating_one.items.len >= rating_nil.items.len) { rating = if (crit == 1) rating_one.toOwnedSlice() else rating_nil.toOwnedSlice(); } else { rating = if (crit == 1) rating_nil.toOwnedSlice() else rating_one.toOwnedSlice(); } } return rating[0]; }
src/day03/day03.zig
const std = @import("std"); const zt = @import("zt"); const sling = @import("sling.zig"); const ig = @import("imgui"); const menu = @import("editor/menu.zig"); const console = @import("editor/console.zig"); var demoOpen: bool = false; pub fn editorUI() void { controls(); menu.update(); if (sling.scene) |scene| { if (sling.room == null) { objectEditor(scene); } } if (sling.settings.hideConsoleInRooms) { if (sling.room == null) { console.update(); } } else { console.update(); } } fn controls() void { const Key = sling.input.Key; var io = ig.igGetIO(); if (sling.input.mwheel != 0) { var newZoom = std.math.clamp(sling.render.camera.zoom + sling.input.mwheel, 1, 12); sling.render.camera.setZoom(newZoom); } if (Key.mmb.down()) { sling.render.camera.setPosition(sling.render.camera.position.sub(io.*.MouseDelta.scaleDiv(sling.render.camera.zoom))); } } fn objectEditor(scene: *sling.Scene) void { if (ig.igBegin(sling.dictionary.windowTitleSceneEditor.ptr, null, ig.ImGuiWindowFlags_None)) { switch (scene.baseObject.data) { .Singleton => { scene.baseObject.data.Singleton.editor(scene.baseObject); }, .Collection => { var max = scene.baseObject.data.Collection.getCount(scene.baseObject); var i: usize = 0; while (i < max) : (i += 1) { scene.baseObject.data.Collection.editor(scene.baseObject, i); } }, } } ig.igEnd(); ig.igPushStyleVar_Vec2(ig.ImGuiStyleVar_WindowPadding, .{ .x = 2, .y = 2 }); if (ig.igBegin(sling.dictionary.windowTitlePalette.ptr, null, ig.ImGuiWindowFlags_None)) { ig.igPushStyleVar_Vec2(ig.ImGuiStyleVar_FramePadding, .{}); for (scene.childObjects) |interface, i| { ig.igPushID_Int(@intCast(c_int, i)); defer ig.igPopID(); switch (interface.data) { .Singleton => { if (ig.igSelectable_Bool(interface.information.name.ptr, i == scene.editorData.selectedObjectGroup, ig.ImGuiSelectableFlags_SpanAvailWidth, .{})) { scene.editorData.selectedObjectGroup = i; scene.editorData.selectedEntity = 0; } }, .Collection => { if (scene.editorData.selectedObjectGroup == i) { ig.igSetNextItemOpen(true, ig.ImGuiCond_Once); } var open = ig.igTreeNode_Str(interface.information.name.ptr); var s: ig.ImVec2 = undefined; var ws: ig.ImVec2 = undefined; ig.igGetItemRectSize(&s); ig.igGetWindowSize(&ws); ig.igSameLine(ws.x - 22, 0); if (ig.igButton(sling.dictionary.addNew.ptr, .{ .x = 20, .y = s.y })) { interface.data.Collection.append(interface); scene.editorData.selectedObjectGroup = i; } if (scene.editorData.selectedObjectGroup == i and interface.data.Collection.getCount(interface) > 0) { ig.igSameLine(ws.x - 44, 0); if (ig.igButton(sling.dictionary.duplicate.ptr, .{ .x = 20, .y = s.y })) { interface.data.Collection.append(interface); interface.data.Collection.copyFromTo(interface, scene.editorData.selectedEntity, interface.data.Collection.getCount(interface) - 1); } if (ig.igIsItemHovered(ig.ImGuiHoveredFlags_None)) { ig.igBeginTooltip(); ig.igText("Duplicate the currently selected entity."); ig.igEndTooltip(); } } if (open) { var max = interface.data.Collection.getCount(interface); var j: usize = 0; while (j < max) : (j += 1) { ig.igPushID_Int(@intCast(c_int, j)); var txt = interface.data.Collection.getName(interface, j); var openNode = ig.igSelectable_Bool(txt.ptr, i == scene.editorData.selectedObjectGroup and j == scene.editorData.selectedEntity, ig.ImGuiSelectableFlags_SpanAvailWidth, .{}); if (ig.igBeginPopupContextItem("ENTITY_POPUP_CONTEXT", ig.ImGuiPopupFlags_MouseButtonRight)) { if (ig.igSelectable_Bool("Delete", false, ig.ImGuiSelectableFlags_None, .{ .x = 110 })) { interface.data.Collection.remove(interface, j); max -= 1; } if (ig.igSelectable_Bool("Duplicate", false, ig.ImGuiSelectableFlags_None, .{ .x = 110 })) { interface.data.Collection.append(interface); interface.data.Collection.copyFromTo(interface, j, interface.data.Collection.getCount(interface) - 1); } ig.igEndPopup(); } if (openNode) { scene.editorData.selectedObjectGroup = i; scene.editorData.selectedEntity = j; } ig.igPopID(); } ig.igTreePop(); } }, } } ig.igPopStyleVar(1); } ig.igEnd(); ig.igPopStyleVar(1); if (ig.igBegin(sling.dictionary.windowTitleObjectEditor.ptr, null, ig.ImGuiWindowFlags_None)) { if (scene.editorData.selectedObjectGroup < scene.childObjects.len) { var currentInterface = scene.childObjects[scene.editorData.selectedObjectGroup]; switch (currentInterface.data) { .Singleton => { currentInterface.data.Singleton.editor(currentInterface); }, .Collection => { var count = currentInterface.data.Collection.getCount(currentInterface); if (count > 0 and scene.editorData.selectedEntity < count) { currentInterface.data.Collection.editor(currentInterface, scene.editorData.selectedEntity); } }, } } } ig.igEnd(); }
src/editor.zig
const std = @import("std"); const c_args = [_][]const u8{ "-D_MSC_VER", "-std=c11", "-fno-sanitize=undefined", }; const cpp_args = [_][]const u8{ "-std=c++17", "-fno-sanitize=undefined", }; 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(); const exe = b.addExecutable("LabSound-c", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addIncludeDir("./"); exe.addIncludeDir("../LabSound/include"); exe.addIncludeDir("../LabSound/src"); exe.addIncludeDir("../LabSound/third_party"); exe.addIncludeDir("../LabSound/third_party/libnyquist/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/include/libnyquist"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/FLAC/src/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/libogg/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/libvorbis/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/libvorbis/src"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/musepack/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/celt"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/libopus/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/opusfile/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/opusfile/src/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/silk"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/opus/silk/float"); exe.addIncludeDir("../LabSound/third_party/libnyquist/third_party/wavpack/include"); exe.addIncludeDir("../LabSound/third_party/libnyquist/src"); exe.addCSourceFile("labsound-c.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/backends/RtAudio/AudioDevice_RtAudio.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/backends/RtAudio/RtAudio.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/_SoundPipe_FFT.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AnalyserNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioBasicInspectorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioBasicProcessorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioBus.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioChannel.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioContext.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioDevice.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioHardwareDeviceNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioHardwareInputNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioListener.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioParam.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/AudioParamTimeline.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/BiquadFilterNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/ChannelMergerNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/ChannelSplitterNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/ConvolverNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/DelayNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/DynamicsCompressorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/GainNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/NullDeviceNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/OscillatorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/PannerNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/RealtimeAnalyser.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/SampledAudioNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/StereoPannerNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/WaveShaperNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/core/WaveTable.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/ADSRNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/AudioFileReader.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/BPMDelay.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/ClipNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/DiodeNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/FunctionNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/GranulationNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/LabSound.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/NoiseNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PdNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PeakCompNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PingPongDelayNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PolyBLEPNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PowerMonitorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/PWMNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/RecorderNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/Registry.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/SfxrNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/SpatializationNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/SpectralMonitorNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/extended/SuperSawNode.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/AudioDSPKernelProcessor.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/AudioUtilities.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/Biquad.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/Cone.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/DelayDSPKernel.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/DelayProcessor.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/Distance.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/DynamicsCompressor.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/DynamicsCompressorKernel.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/EqualPowerPanner.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/FFTConvolver.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/FFTFrame.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/FFTFrameKissFFT.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/HRTFDatabase.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/HRTFDatabaseLoader.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/HRTFElevation.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/HRTFKernel.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/HRTFPanner.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/VectorMath.cpp", &cpp_args); exe.addCSourceFile("../LabSound/src/internal/src/ZeroPole.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/Common.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/Encoders.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/FlacDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/FlacDependencies.c", &c_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/Mp3Decoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/MusepackDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/MusepackDependencies.c", &c_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/OpusDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/OpusDependencies.c", &c_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/VorbisDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/VorbisDependencies.c", &c_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/WavDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/libnyquist/src/WavPackDecoder.cpp", &cpp_args); exe.addCSourceFile("../LabSound/third_party/ooura/src/fftsg.cpp", &cpp_args); exe.addCSourceFile("flecs.c", &c_args); exe.linkLibC(); exe.linkLibCpp(); exe.linkSystemLibrary("c"); 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 exe_tests = b.addTest("src/main.zig"); exe_tests.setBuildMode(mode); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
build.zig
pub const c = @cImport({ @cInclude("zig_wwise.h"); }); const std = @import("std"); const builtin = @import("builtin"); const FixedBufferAllocator = std.heap.FixedBufferAllocator; pub const Wwise = struct { pub const AkCallbackFunction = c.ZigAkCallbackFunc; pub const AkCallbackInfo = c.ZigAkCallbackInfo; pub const AkEventCallbackInfo = c.ZigAkEventCallbackInfo; pub const AkMarkerCallbackInfo = c.ZigAkMarkerCallbackInfo; pub const AkCurveInterpolation = c.ZigAkCurveInterpolation; pub const InvalidGameObject = @bitCast(u64, @as(i64, -1)); pub const InitError = error{ MemoryManagerFailed, StreamManagerFailed, LowLevelIOFailed, SoundEngineFailed, CommunicationFailed, }; pub const AkCallbackType = struct { pub const EndOfEvent = 0x0001; pub const EndOfDynamicSequenceItem = 0x0002; pub const Marker = 0x0004; pub const Duration = 0x0008; pub const SpeakerVolumeMatrix = 0x0010; pub const Starvation = 0x0020; pub const MusicPlaylistSelect = 0x0040; pub const MusicPlayStarted = 0x0080; pub const MusicSyncBeat = 0x0100; pub const MusicSyncBar = 0x0200; pub const MusicSyncEntry = 0x0400; pub const MusicSyncExit = 0x0800; pub const MusicSyncGrid = 0x1000; pub const MusicSyncUserCue = 0x2000; pub const MusicSyncPoint = 0x4000; pub const MusicSyncAll = 0x7f00; pub const MIDIEvent = 0x10000; pub const CallbackBits = 0xfffff; pub const EnableGetSourcePlayPosition = 0x100000; pub const EnableGetMusicPlayPosition = 0x200000; pub const EnableGetSourceStreamBuffering = 0x400000; }; pub fn init() InitError!void { switch (c.ZigAk_Init()) { c.ZigAkInitResultSuccess => return, c.ZigAkInitResultMemoryManagerFailed => return InitError.MemoryManagerFailed, c.ZigAkInitResultStreamManagerFailed => return InitError.StreamManagerFailed, c.ZigAkInitResultLowLevelIOFailed => return InitError.LowLevelIOFailed, c.ZigAkInitResultSoundEngineFailed => return InitError.SoundEngineFailed, c.ZigAkInitResultCommunicationFailed => return InitError.CommunicationFailed, else => {}, } } pub fn deinit() void { c.ZigAk_Deinit(); } pub fn renderAudio() void { c.ZigAk_RenderAudio(); } pub fn setIOHookBasePath(path: []const u8) !void { var stackString = StackString.init(); const nativePath = try stackString.toOSChar(path); c.ZigAk_SetIOBasePath(nativePath); } pub fn loadBankByString(bankName: []const u8) !u32 { var stackString = StackString.init(); const nativeBankName = try stackString.toOSChar(bankName); var bankID: u32 = 0; const result = c.ZigAk_LoadBankByString(nativeBankName, &bankID); switch (result) { c.ZigAKRESULTSuccess => return bankID, c.ZigAKRESULTInsufficientMemory => return error.InsufficientMemory, c.ZigAKRESULTBankReadError => return error.BankReadError, c.ZigAKRESULTWrongBankVersion => return error.WrongBankVersion, c.ZigAKRESULTInvalidFile => return error.InvalidFile, c.ZigAKRESULTInvalidParameter => return error.InvalidParameter, else => return error.Fail, } } pub fn unloadBankByID(bankID: u32) bool { const result = c.ZigAk_UnloadBankByID(bankID, null); return switch (result) { c.ZigAKRESULTSuccess => return true, else => return false, }; } pub fn unloadBankByString(bankName: []const u8) !void { var stackString = StackString.init(); const nativeBankName = try stackString.toOSChar(bankName); const result = c.ZigAk_UnloadBankByString(nativeBankName); switch (result) { c.ZigAKRESULTSuccess => return, else => return error.Fail, } } pub fn registerGameObj(gameObjectID: u64, objectName: ?[]const u8) !void { if (objectName) |name| { var stackString = StackString.init(); const nativeObjectName = try stackString.toCString(name); return switch (c.ZigAk_RegisterGameObj(gameObjectID, nativeObjectName)) { c.ZigAKRESULTSuccess => return, else => error.Fail, }; } else { return switch (c.ZigAk_RegisterGameObj(gameObjectID, null)) { c.ZigAKRESULTSuccess => return, else => error.Fail, }; } } pub fn unregisterGameObj(gameObjectID: u64) void { _ = c.ZigAk_UnregisterGameObj(gameObjectID); } pub fn postEvent(eventName: []const u8, gameObjectID: u64) !u32 { var stackString = StackString.init(); const nativeEventName = try stackString.toCString(eventName); return c.ZigAk_PostEventByString(nativeEventName, gameObjectID); } pub fn postEventWithCallback(eventName: []const u8, gameObjectID: u64, callbackType: u32, callback: AkCallbackFunction, cookie: ?*c_void) !u32 { var stackString = StackString.init(); const nativeEventName = try stackString.toCString(eventName); return c.ZigAk_PostEventByStringCallback(nativeEventName, gameObjectID, callbackType, callback, cookie); } pub fn setRTPCValueByString(rtpcName: []const u8, value: f32, gameObjectID: u64) !void { var stackString = StackString.init(); const nativeRtpcName = try stackString.toCString(rtpcName); return switch (c.ZigAk_SetRTPCValueByString(nativeRtpcName, value, gameObjectID)) { c.ZigAKRESULTSuccess => {}, c.ZigAKRESULTInvalidFloatValue => error.InvalidFloatValue, else => error.Fail, }; } pub fn setRTPCValueByStringInterpolate(rtpcName: []const u8, value: f32, gameObjectID: u64, timeMs: i32, fadeCurve: AkCurveInterpolation, bypassIntervalValueInterpolation: bool) !void { var stackString = StackString.init(); const nativeRtpcName = try stackString.toCString(rtpcName); return switch (c.ZigAk_SetRTPCValueByStringInterpolate(nativeRtpcName, value, gameObjectID, timeMs, fadeCurve, bypassIntervalValueInterpolation)) { c.ZigAKRESULTSuccess => {}, c.ZigAKRESULTInvalidFloatValue => error.InvalidFloatValue, else => error.Fail, }; } pub fn setRTPCValue(rtpcID: u32, value: f32, gameObjectID: u64) !void { return switch (c.ZigAk_SetRTPCValue(rtpcID, value, gameObjectID)) { c.ZigAKRESULTSuccess => {}, c.ZigAKRESULTInvalidFloatValue => error.InvalidFloatValue, else => error.Fail, }; } pub fn setRTPCValueInterpolate(rtpcID: u32, value: f32, gameObjectID: u64, timeMs: i32, fadeCurve: AkCurveInterpolation, bypassIntervalValueInterpolation: bool) !void { return switch (c.ZigAk_SetRTPCValueInterpolate(rtpcID, value, gameObjectID, timeMs, fadeCurve, bypassIntervalValueInterpolation)) { c.ZigAKRESULTSuccess => {}, c.ZigAKRESULTInvalidFloatValue => error.InvalidFloatValue, else => error.Fail, }; } pub fn getSourcePlayPosition(playingId: u32, extrapolate: bool) !i32 { var result: i32 = 0; var akResult = c.ZigAk_GetSourcePlayPosition(playingId, &result, extrapolate); return switch (akResult) { c.ZigAKRESULTSuccess => return result, c.ZigAKRESULTInvalidParameter => return error.InvalidParameter, else => return error.Fail, }; } pub fn stopPlayingID(playingId: u32) void { stopPlayingIDWithTransition(playingId, 0, AkCurveInterpolation.Linear); } pub fn stopPlayingIDWithTransition(playingId: u32, timeMs: i32, fadeCurve: AkCurveInterpolation) void { c.ZigAk_StopPlayingID(playingId, timeMs, fadeCurve); } pub fn stopAllOnGameObject(gameObjectID: u64) void { c.ZigAk_StopAll(gameObjectID); } pub fn stopAll() void { c.ZigAk_StopAll(InvalidGameObject); } pub fn setDefaultListeners(listeners: []const u64) void { c.ZigAk_SetDefaultListeners(&listeners[0], @intCast(c_ulong, listeners.len)); } pub fn setCurrentLanguage(language: []const u8) !void { var stackString = StackString.init(); const nativeLanguage = try stackString.toOSChar(language); c.ZigAk_StreamMgr_SetCurrentLanguage(nativeLanguage); } pub fn setSwitchByID(group: u32, value: u32, game_object: u64) void { c.ZigAk_SetSwitchByID(group, value, game_object); } pub fn getIDFromString(input: []const u8) !u32 { var stackString = StackString.init(); const nativeInput = try stackString.toCString(input); return c.ZigAk_GetIDFromString(nativeInput); } pub const toOSChar = blk: { if (builtin.os.tag == .windows) { break :blk utf16ToOsChar; } else { break :blk utf8ToOsChar; } }; pub fn utf16ToOsChar(allocator: std.mem.Allocator, value: []const u8) ![:0]u16 { return std.unicode.utf8ToUtf16LeWithNull(allocator, value); } pub fn utf8ToOsChar(allocator: std.mem.Allocator, value: []const u8) ![:0]u8 { return std.cstr.addNullByte(allocator, value); } const StackString = struct { buffer: [4 * 1024]u8 = undefined, fixedAlloc: FixedBufferAllocator = undefined, const Self = @This(); pub fn init() Self { var result = Self{}; result.fixedAlloc = FixedBufferAllocator.init(&result.buffer); return result; } pub fn toOSChar(self: *Self, value: []const u8) @typeInfo(@TypeOf(Wwise.toOSChar)).Fn.return_type.? { return Wwise.toOSChar(self.fixedAlloc.allocator(), value); } pub fn toCString(self: *Self, value: []const u8) ![:0]u8 { return Wwise.utf8ToOsChar(self.fixedAlloc.allocator(), value); } }; };
src/wwise.zig
const std = @import("std"); pub const Format = enum(u8) { rgb = 3, rgba = 4, }; pub const Colorspace = enum(u8) { srgb = 0, linear = 1, }; pub const Image = struct { width: u32, height: u32, data: []const u8, format: Format = .rgba, colorspace: Colorspace = .srgb, }; const Result = struct { bytes: []u8, len: usize, }; const Color = packed struct { r: u8, g: u8, b: u8, a: u8, fn hash(color: Color) u8 { return @truncate( u8, ((@as(u32, color.r) * 3) + (@as(u32, color.g) * 5) + (@as(u32, color.b) * 7) + (@as(u32, color.a) * 11)) % 64, ); } }; const header_len = 14; const magic = [4]u8{ 'q', 'o', 'i', 'f' }; const end_marker = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 1 }; const op_index: u8 = 0b00000000; const op_diff: u8 = 0b01000000; const op_luma: u8 = 0b10000000; const op_run: u8 = 0b11000000; const op_rgb: u8 = 0b11111110; const op_rgba: u8 = 0b11111111; const mask_op_code: u8 = 0b11000000; const mask_index: u8 = 0b00111111; const mask_diff_r: u8 = 0b00110000; const mask_diff_g: u8 = 0b00001100; const mask_diff_b: u8 = 0b00000011; const mask_luma_r: u8 = 0b11110000; const mask_luma_g: u8 = 0b00111111; const mask_luma_b: u8 = 0b00001111; const mask_run: u8 = 0b00111111; const max_bytes: usize = 4000000000; pub fn encode(image: Image, allocator: std.mem.Allocator) !Result { const max_size = image.width * image.height * (@enumToInt(image.format) + 1) + header_len + end_marker.len; if (max_size > max_bytes) { return error.MaxBytesExceeded; } const bytes = try allocator.alloc(u8, max_size); errdefer allocator.free(bytes); // encode header std.mem.copy(u8, bytes[0..4], &magic); std.mem.writeIntBig(u32, bytes[4..8], image.width); std.mem.writeIntBig(u32, bytes[8..12], image.height); bytes[12] = @enumToInt(image.format); bytes[13] = @enumToInt(image.colorspace); // encode each pixel var bytes_index: usize = header_len; var run: u8 = 0; var lut: [64]Color = std.mem.zeroes([64]Color); var prev_pixel: Color = .{ .r = 0, .g = 0, .b = 0, .a = 255 }; const pixels = std.mem.bytesAsSlice(Color, image.data); for (pixels) |pixel| { if (@bitCast(u32, pixel) == @bitCast(u32, prev_pixel)) { // if the pixel matches the prev pixel, we are in a run run += 1; // if we hit the max length of a run, reset the run if (run == 62) { try writeBytes(bytes, &bytes_index, &[_]u8{op_run | run - 1}); run = 0; } } else { // otherwise, we have a new pixel // end an existing run if necessary if (run > 0) { try writeBytes(bytes, &bytes_index, &[_]u8{op_run | run - 1}); run = 0; } // see if the new pixel is in the lookup table const hash = pixel.hash(); if (@bitCast(u32, pixel) == @bitCast(u32, lut[hash])) { // if we are, write the hash try writeBytes(bytes, &bytes_index, &[_]u8{op_index | hash}); } else { // otherwise write the pixel to the lookup table lut[hash] = pixel; // check if we can encode RGB diff or luma if (pixel.a == prev_pixel.a) { const diff_r = @as(i16, pixel.r) - @as(i16, prev_pixel.r); const diff_g = @as(i16, pixel.g) - @as(i16, prev_pixel.g); const diff_b = @as(i16, pixel.b) - @as(i16, prev_pixel.b); const diff_rg = diff_r - diff_g; const diff_rb = diff_b - diff_g; if (diff_r >= -2 and diff_r <= 1 and diff_g >= -2 and diff_g <= 1 and diff_b >= -2 and diff_b <= 1) { // we can encode using a diff (only takes 1 byte) try writeBytes( bytes, &bytes_index, &[_]u8{op_diff | (@intCast(u8, diff_r + 2) << 4) | (@intCast(u8, diff_g + 2) << 2) | (@intCast(u8, diff_b + 2) << 0)}, ); } else if (diff_g >= -32 and diff_g <= 31 and diff_rg >= -8 and diff_rg <= 7 and diff_rb >= -8 and diff_rb <= 7) { // we can encode using luma (only takes 2 bytes) try writeBytes( bytes, &bytes_index, &[_]u8{ op_luma | @intCast(u8, diff_g + 32), @intCast(u8, diff_rg + 8) << 4 | @intCast(u8, diff_rb + 8) << 0, }, ); } else { // otherwise, we encode using rgb (4 bytes) try writeBytes( bytes, &bytes_index, &[_]u8{ op_rgb, pixel.r, pixel.g, pixel.b }, ); } } else { // unique alpha channel requires encoding rgba (5 bytes) try writeBytes( bytes, &bytes_index, &[_]u8{ op_rgba, pixel.r, pixel.g, pixel.b, pixel.a }, ); } } } prev_pixel = pixel; } if (run > 0) { try writeBytes(bytes, &bytes_index, &[_]u8{op_run | run - 1}); run = 0; } // encode end marker try writeBytes(bytes, &bytes_index, &end_marker); return Result{ .bytes = bytes, .len = bytes_index, }; } fn writeBytes(bytes: []u8, bytes_index: *usize, data: []const u8) !void { if (bytes_index.* + data.len > bytes.len) { return error.InvalidData; } std.mem.copy(u8, bytes[bytes_index.*..], data); bytes_index.* += data.len; } pub fn decode(data: []const u8, allocator: std.mem.Allocator) !Image { if (data.len < header_len) { return error.InvalidData; } // decode header if (!std.mem.eql(u8, data[0..4], magic[0..4])) { return error.InvalidMagic; } const width = std.mem.readIntBig(u32, data[4..8]); const height = std.mem.readIntBig(u32, data[8..12]); const format = data[12]; const colorspace = data[13]; _ = std.meta.intToEnum(Format, format) catch return error.InvalidHeader; _ = std.meta.intToEnum(Colorspace, colorspace) catch return error.InvalidHeader; if (width * height * format > max_bytes) { return error.MaxBytesExceeded; } const bytes = try allocator.alloc(u8, width * height * format); errdefer allocator.free(bytes); // decode each pixel of the image var lut: [64]Color = std.mem.zeroes([64]Color); var pixel: Color = .{ .r = 0, .g = 0, .b = 0, .a = 255 }; var data_index: usize = header_len; var bytes_index: usize = 0; while (bytes_index < bytes.len) { if (data_index + 1 > data.len) { return error.InvalidData; } const op = data[data_index]; if (op == op_rgb) { if (data_index + 4 > data.len) { return error.InvalidData; } pixel.r = data[data_index + 1]; pixel.g = data[data_index + 2]; pixel.b = data[data_index + 3]; data_index += 4; } else if (op == op_rgba) { if (data_index + 5 > data.len) { return error.InvalidData; } pixel.r = data[data_index + 1]; pixel.g = data[data_index + 2]; pixel.b = data[data_index + 3]; pixel.a = data[data_index + 4]; data_index += 5; } else { const op_code = op & mask_op_code; if (op_code == op_index) { pixel = lut[op & mask_index]; data_index += 1; } else if (op_code == op_diff) { // use wrapping adds to match the spec // even though the diffs are signed ints, they are still twos complement // numbers and the wrapping arithmetic works out the same. pixel.r +%= ((op & mask_diff_r) >> 4) -% 2; pixel.g +%= ((op & mask_diff_g) >> 2) -% 2; pixel.b +%= ((op & mask_diff_b) >> 0) -% 2; data_index += 1; } else if (op_code == op_luma) { if (data_index + 2 > data.len) { return error.InvalidData; } // use wrapping adds to match the spec // even though the diffs are signed ints, they are still twos complement // numbers and the wrapping arithmetic works out the same. const diff_g = (op & mask_luma_g) -% 32; const op_rb = data[data_index + 1]; pixel.r +%= diff_g +% ((op_rb & mask_luma_r) >> 4) -% 8; pixel.g +%= diff_g; pixel.b +%= diff_g +% ((op_rb & mask_luma_b) >> 0) -% 8; data_index += 2; } else if (op_code == op_run) { // a run is a continuous stream of the same pixel var run = (op & mask_run) + 1; if (bytes_index + format * (run - 1) > bytes.len) { return error.InvalidData; } while (run > 1) : (run -= 1) { std.mem.copy(u8, bytes[bytes_index..], std.mem.asBytes(&pixel)[0..format]); bytes_index += format; } data_index += 1; } } lut[pixel.hash()] = pixel; if (bytes_index + format > bytes.len) { return error.InvalidData; } std.mem.copy(u8, bytes[bytes_index..], std.mem.asBytes(&pixel)[0..format]); bytes_index += format; } // decode end marker if (data_index + 8 != data.len or !std.mem.eql(u8, data[data_index..], &end_marker)) { return error.InvalidEndMarker; } return Image{ .width = width, .height = height, .data = bytes }; }
src/qoi.zig
const std = @import("std"); const mem = std.mem; const heap = std.heap; const giz = @import("./giz.zig"); pub fn main() !void { const stdout = std.io.getStdOut(); const w = stdout.writer(); var giz_config: giz.config.Config = giz.config.default(); // TODO Check if this config is working and ansi escape codes are actually not been written out if (!stdout.isTty()) { std.log.warn("your console is not a tty. disabling giz color mode.", .{}); giz_config.color_mode = giz.config.ColorMode.no_color; } if (!stdout.supportsAnsiEscapeCodes()) { std.log.warn("your console doesn't support ansi escape codes. disabling giz color mode.", .{}); giz_config.color_mode = giz.config.ColorMode.no_color; } // TODO add imperative API examples (multiple writes / state machine) // TODO add fluent API examples (inline style builder) // You can use this temporary stack buffer to avoid unnecessary allocations var tmpBuf: [100]u8 = undefined; try w.writeAll("┌─────────────────────────────────────────────┐\n"); try w.writeAll("│ Chalk Demo - https://github.com/chalk/chalk │\n"); try w.writeAll("└─────────────────────────────────────────────┘\n"); // Full customization with fmtStyle, which writes to a buffer the scapings codes according to your styles try w.print("{s} ", .{try giz.fmtStyle(tmpBuf[0..], "bold", .{ .bold = true })}); try w.print("{s} ", .{try giz.fmtStyle(tmpBuf[0..], "dim", .{ .dim = true })}); try w.print("{s} ", .{try giz.fmtStyle(tmpBuf[0..], "italic", .{ .italic = true })}); try w.print("{s} ", .{try giz.fmtStyle(tmpBuf[0..], "underline", .{ .underline = true })}); try w.print("{s} ", .{try giz.fmtStyle(tmpBuf[0..], "inverse", .{ .inverse = true })}); try w.print("{s}\n", .{try giz.fmtStyle(tmpBuf[0..], "strikethrough", .{ .strikethrough = true })}); // Or you could use handy methods for common colors like red, green, blue, ... try w.print("{s} ", .{try giz.red(tmpBuf[0..], "red")}); try w.print("{s} ", .{try giz.green(tmpBuf[0..], "green")}); try w.print("{s} ", .{try giz.yellow(tmpBuf[0..], "yellow")}); try w.print("{s} ", .{try giz.blue(tmpBuf[0..], "blue")}); try w.print("{s} ", .{try giz.magenta(tmpBuf[0..], "magenta")}); try w.print("{s} ", .{try giz.cyan(tmpBuf[0..], "cyan")}); try w.print("{s} ", .{try giz.white(tmpBuf[0..], "white")}); // TODO grey try w.print("{s}\n", .{try giz.black(tmpBuf[0..], "black")}); // Background colors also have handy methods for common colors! try w.print("{s} ", .{try giz.bgRed(tmpBuf[0..], "bgRed")}); try w.print("{s} ", .{try giz.bgGreen(tmpBuf[0..], "bgGreen")}); try w.print("{s} ", .{try giz.bgYellow(tmpBuf[0..], "bgYellow")}); try w.print("{s} ", .{try giz.bgBlue(tmpBuf[0..], "bgBlue")}); try w.print("{s} ", .{try giz.bgMagenta(tmpBuf[0..], "bgMagenta")}); try w.print("{s} ", .{try giz.bgCyan(tmpBuf[0..], "bgCyan")}); try w.print("{s} ", .{try giz.bgWhite(tmpBuf[0..], "bgWhite")}); // TODO grey try w.print("{s}\n\n", .{try giz.bgBlack(tmpBuf[0..], "bgBlack")}); try w.writeAll("┌──────────────┐\n"); try w.writeAll("│ Hicolor Demo │\n"); try w.writeAll("└──────────────┘\n"); // RGB's support demo try w.print("{s} ", .{try giz.fmtForegroundRGBStr(tmpBuf[0..], "247", "164", "29", "Zig")}); try w.print("{s}\n", .{try giz.fmtBackgroundRGBStr(tmpBuf[0..], "247", "164", "29", "Zag")}); try w.print("{s} ", .{try giz.fmtForegroundRGB(tmpBuf[0..], 247, 164, 29, "Zig")}); try w.print("{s}\n\n", .{try giz.fmtBackgroundRGB(tmpBuf[0..], 247, 164, 29, "Zag")}); try w.writeAll("┌────────────┐\n"); try w.writeAll("│ Misc. │\n"); try w.writeAll("└────────────┘\n"); // Full customization declarative API const ibmStyle: giz.Style = .{ .fgColor = giz.Color.Yellow, // just .Yellow also works .bgColor = giz.Color.Blue, // just .Blue also works .bold = true, .underline = true, }; try w.print("{s}\n\n", .{try giz.fmtStyle(tmpBuf[0..], "IBM Style", ibmStyle)}); try w.writeAll("┌─────────────┐\n"); try w.writeAll("│ Cursor Demo │\n"); try w.writeAll("└─────────────┘\n"); // TODO finish cursor implementation and demo // try giz.cursor.move(tmpBuf[0..], 0, 0); // try giz.cursor.up(tmpBuf[0..], 1); try w.writeAll("TODO\n"); try giz.resetGraphics(); std.log.info("Resetting works", .{}); }
src/main.zig
pub const CVT_SECONDS = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (105) //-------------------------------------------------------------------------------- pub const TOKEN_PRIVILEGES_ATTRIBUTES = enum(u32) { ENABLED = 2, ENABLED_BY_DEFAULT = 1, REMOVED = 4, USED_FOR_ACCESS = 2147483648, _, pub fn initFlags(o: struct { ENABLED: u1 = 0, ENABLED_BY_DEFAULT: u1 = 0, REMOVED: u1 = 0, USED_FOR_ACCESS: u1 = 0, }) TOKEN_PRIVILEGES_ATTRIBUTES { return @intToEnum(TOKEN_PRIVILEGES_ATTRIBUTES, (if (o.ENABLED == 1) @enumToInt(TOKEN_PRIVILEGES_ATTRIBUTES.ENABLED) else 0) | (if (o.ENABLED_BY_DEFAULT == 1) @enumToInt(TOKEN_PRIVILEGES_ATTRIBUTES.ENABLED_BY_DEFAULT) else 0) | (if (o.REMOVED == 1) @enumToInt(TOKEN_PRIVILEGES_ATTRIBUTES.REMOVED) else 0) | (if (o.USED_FOR_ACCESS == 1) @enumToInt(TOKEN_PRIVILEGES_ATTRIBUTES.USED_FOR_ACCESS) else 0) ); } }; pub const SE_PRIVILEGE_ENABLED = TOKEN_PRIVILEGES_ATTRIBUTES.ENABLED; pub const SE_PRIVILEGE_ENABLED_BY_DEFAULT = TOKEN_PRIVILEGES_ATTRIBUTES.ENABLED_BY_DEFAULT; pub const SE_PRIVILEGE_REMOVED = TOKEN_PRIVILEGES_ATTRIBUTES.REMOVED; pub const SE_PRIVILEGE_USED_FOR_ACCESS = TOKEN_PRIVILEGES_ATTRIBUTES.USED_FOR_ACCESS; pub const LOGON32_PROVIDER = enum(u32) { DEFAULT = 0, WINNT50 = 3, WINNT40 = 2, }; pub const LOGON32_PROVIDER_DEFAULT = LOGON32_PROVIDER.DEFAULT; pub const LOGON32_PROVIDER_WINNT50 = LOGON32_PROVIDER.WINNT50; pub const LOGON32_PROVIDER_WINNT40 = LOGON32_PROVIDER.WINNT40; pub const CREATE_RESTRICTED_TOKEN_FLAGS = enum(u32) { DISABLE_MAX_PRIVILEGE = 1, SANDBOX_INERT = 2, LUA_TOKEN = 4, WRITE_RESTRICTED = 8, _, pub fn initFlags(o: struct { DISABLE_MAX_PRIVILEGE: u1 = 0, SANDBOX_INERT: u1 = 0, LUA_TOKEN: u1 = 0, WRITE_RESTRICTED: u1 = 0, }) CREATE_RESTRICTED_TOKEN_FLAGS { return @intToEnum(CREATE_RESTRICTED_TOKEN_FLAGS, (if (o.DISABLE_MAX_PRIVILEGE == 1) @enumToInt(CREATE_RESTRICTED_TOKEN_FLAGS.DISABLE_MAX_PRIVILEGE) else 0) | (if (o.SANDBOX_INERT == 1) @enumToInt(CREATE_RESTRICTED_TOKEN_FLAGS.SANDBOX_INERT) else 0) | (if (o.LUA_TOKEN == 1) @enumToInt(CREATE_RESTRICTED_TOKEN_FLAGS.LUA_TOKEN) else 0) | (if (o.WRITE_RESTRICTED == 1) @enumToInt(CREATE_RESTRICTED_TOKEN_FLAGS.WRITE_RESTRICTED) else 0) ); } }; pub const DISABLE_MAX_PRIVILEGE = CREATE_RESTRICTED_TOKEN_FLAGS.DISABLE_MAX_PRIVILEGE; pub const SANDBOX_INERT = CREATE_RESTRICTED_TOKEN_FLAGS.SANDBOX_INERT; pub const LUA_TOKEN = CREATE_RESTRICTED_TOKEN_FLAGS.LUA_TOKEN; pub const WRITE_RESTRICTED = CREATE_RESTRICTED_TOKEN_FLAGS.WRITE_RESTRICTED; pub const LOGON32_LOGON = enum(u32) { BATCH = 4, INTERACTIVE = 2, NETWORK = 3, NETWORK_CLEARTEXT = 8, NEW_CREDENTIALS = 9, SERVICE = 5, UNLOCK = 7, }; pub const LOGON32_LOGON_BATCH = LOGON32_LOGON.BATCH; pub const LOGON32_LOGON_INTERACTIVE = LOGON32_LOGON.INTERACTIVE; pub const LOGON32_LOGON_NETWORK = LOGON32_LOGON.NETWORK; pub const LOGON32_LOGON_NETWORK_CLEARTEXT = LOGON32_LOGON.NETWORK_CLEARTEXT; pub const LOGON32_LOGON_NEW_CREDENTIALS = LOGON32_LOGON.NEW_CREDENTIALS; pub const LOGON32_LOGON_SERVICE = LOGON32_LOGON.SERVICE; pub const LOGON32_LOGON_UNLOCK = LOGON32_LOGON.UNLOCK; pub const ACE_FLAGS = enum(u32) { CONTAINER_INHERIT_ACE = 2, FAILED_ACCESS_ACE_FLAG = 128, INHERIT_ONLY_ACE = 8, INHERITED_ACE = 16, NO_PROPAGATE_INHERIT_ACE = 4, OBJECT_INHERIT_ACE = 1, SUCCESSFUL_ACCESS_ACE_FLAG = 64, SUB_CONTAINERS_AND_OBJECTS_INHERIT = 3, // SUB_CONTAINERS_ONLY_INHERIT = 2, this enum value conflicts with CONTAINER_INHERIT_ACE // SUB_OBJECTS_ONLY_INHERIT = 1, this enum value conflicts with OBJECT_INHERIT_ACE // INHERIT_NO_PROPAGATE = 4, this enum value conflicts with NO_PROPAGATE_INHERIT_ACE // INHERIT_ONLY = 8, this enum value conflicts with INHERIT_ONLY_ACE NO_INHERITANCE = 0, // INHERIT_ONLY_ACE_ = 8, this enum value conflicts with INHERIT_ONLY_ACE _, pub fn initFlags(o: struct { CONTAINER_INHERIT_ACE: u1 = 0, FAILED_ACCESS_ACE_FLAG: u1 = 0, INHERIT_ONLY_ACE: u1 = 0, INHERITED_ACE: u1 = 0, NO_PROPAGATE_INHERIT_ACE: u1 = 0, OBJECT_INHERIT_ACE: u1 = 0, SUCCESSFUL_ACCESS_ACE_FLAG: u1 = 0, SUB_CONTAINERS_AND_OBJECTS_INHERIT: u1 = 0, NO_INHERITANCE: u1 = 0, }) ACE_FLAGS { return @intToEnum(ACE_FLAGS, (if (o.CONTAINER_INHERIT_ACE == 1) @enumToInt(ACE_FLAGS.CONTAINER_INHERIT_ACE) else 0) | (if (o.FAILED_ACCESS_ACE_FLAG == 1) @enumToInt(ACE_FLAGS.FAILED_ACCESS_ACE_FLAG) else 0) | (if (o.INHERIT_ONLY_ACE == 1) @enumToInt(ACE_FLAGS.INHERIT_ONLY_ACE) else 0) | (if (o.INHERITED_ACE == 1) @enumToInt(ACE_FLAGS.INHERITED_ACE) else 0) | (if (o.NO_PROPAGATE_INHERIT_ACE == 1) @enumToInt(ACE_FLAGS.NO_PROPAGATE_INHERIT_ACE) else 0) | (if (o.OBJECT_INHERIT_ACE == 1) @enumToInt(ACE_FLAGS.OBJECT_INHERIT_ACE) else 0) | (if (o.SUCCESSFUL_ACCESS_ACE_FLAG == 1) @enumToInt(ACE_FLAGS.SUCCESSFUL_ACCESS_ACE_FLAG) else 0) | (if (o.SUB_CONTAINERS_AND_OBJECTS_INHERIT == 1) @enumToInt(ACE_FLAGS.SUB_CONTAINERS_AND_OBJECTS_INHERIT) else 0) | (if (o.NO_INHERITANCE == 1) @enumToInt(ACE_FLAGS.NO_INHERITANCE) else 0) ); } }; pub const CONTAINER_INHERIT_ACE = ACE_FLAGS.CONTAINER_INHERIT_ACE; pub const FAILED_ACCESS_ACE_FLAG = ACE_FLAGS.FAILED_ACCESS_ACE_FLAG; pub const INHERIT_ONLY_ACE = ACE_FLAGS.INHERIT_ONLY_ACE; pub const INHERITED_ACE = ACE_FLAGS.INHERITED_ACE; pub const NO_PROPAGATE_INHERIT_ACE = ACE_FLAGS.NO_PROPAGATE_INHERIT_ACE; pub const OBJECT_INHERIT_ACE = ACE_FLAGS.OBJECT_INHERIT_ACE; pub const SUCCESSFUL_ACCESS_ACE_FLAG = ACE_FLAGS.SUCCESSFUL_ACCESS_ACE_FLAG; pub const SUB_CONTAINERS_AND_OBJECTS_INHERIT = ACE_FLAGS.SUB_CONTAINERS_AND_OBJECTS_INHERIT; pub const SUB_CONTAINERS_ONLY_INHERIT = ACE_FLAGS.CONTAINER_INHERIT_ACE; pub const SUB_OBJECTS_ONLY_INHERIT = ACE_FLAGS.OBJECT_INHERIT_ACE; pub const INHERIT_NO_PROPAGATE = ACE_FLAGS.NO_PROPAGATE_INHERIT_ACE; pub const INHERIT_ONLY = ACE_FLAGS.INHERIT_ONLY_ACE; pub const NO_INHERITANCE = ACE_FLAGS.NO_INHERITANCE; pub const INHERIT_ONLY_ACE_ = ACE_FLAGS.INHERIT_ONLY_ACE; pub const OBJECT_SECURITY_INFORMATION = enum(u32) { ATTRIBUTE_SECURITY_INFORMATION = 32, BACKUP_SECURITY_INFORMATION = 65536, DACL_SECURITY_INFORMATION = 4, GROUP_SECURITY_INFORMATION = 2, LABEL_SECURITY_INFORMATION = 16, OWNER_SECURITY_INFORMATION = 1, PROTECTED_DACL_SECURITY_INFORMATION = 2147483648, PROTECTED_SACL_SECURITY_INFORMATION = 1073741824, SACL_SECURITY_INFORMATION = 8, SCOPE_SECURITY_INFORMATION = 64, UNPROTECTED_DACL_SECURITY_INFORMATION = 536870912, UNPROTECTED_SACL_SECURITY_INFORMATION = 268435456, _, pub fn initFlags(o: struct { ATTRIBUTE_SECURITY_INFORMATION: u1 = 0, BACKUP_SECURITY_INFORMATION: u1 = 0, DACL_SECURITY_INFORMATION: u1 = 0, GROUP_SECURITY_INFORMATION: u1 = 0, LABEL_SECURITY_INFORMATION: u1 = 0, OWNER_SECURITY_INFORMATION: u1 = 0, PROTECTED_DACL_SECURITY_INFORMATION: u1 = 0, PROTECTED_SACL_SECURITY_INFORMATION: u1 = 0, SACL_SECURITY_INFORMATION: u1 = 0, SCOPE_SECURITY_INFORMATION: u1 = 0, UNPROTECTED_DACL_SECURITY_INFORMATION: u1 = 0, UNPROTECTED_SACL_SECURITY_INFORMATION: u1 = 0, }) OBJECT_SECURITY_INFORMATION { return @intToEnum(OBJECT_SECURITY_INFORMATION, (if (o.ATTRIBUTE_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.ATTRIBUTE_SECURITY_INFORMATION) else 0) | (if (o.BACKUP_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.BACKUP_SECURITY_INFORMATION) else 0) | (if (o.DACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION) else 0) | (if (o.GROUP_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION) else 0) | (if (o.LABEL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.LABEL_SECURITY_INFORMATION) else 0) | (if (o.OWNER_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION) else 0) | (if (o.PROTECTED_DACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION) else 0) | (if (o.PROTECTED_SACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION) else 0) | (if (o.SACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.SACL_SECURITY_INFORMATION) else 0) | (if (o.SCOPE_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.SCOPE_SECURITY_INFORMATION) else 0) | (if (o.UNPROTECTED_DACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION) else 0) | (if (o.UNPROTECTED_SACL_SECURITY_INFORMATION == 1) @enumToInt(OBJECT_SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION) else 0) ); } }; pub const ATTRIBUTE_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.ATTRIBUTE_SECURITY_INFORMATION; pub const BACKUP_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.BACKUP_SECURITY_INFORMATION; pub const DACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION; pub const GROUP_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION; pub const LABEL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.LABEL_SECURITY_INFORMATION; pub const OWNER_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION; pub const PROTECTED_DACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION; pub const PROTECTED_SACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.PROTECTED_SACL_SECURITY_INFORMATION; pub const SACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.SACL_SECURITY_INFORMATION; pub const SCOPE_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.SCOPE_SECURITY_INFORMATION; pub const UNPROTECTED_DACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.UNPROTECTED_DACL_SECURITY_INFORMATION; pub const UNPROTECTED_SACL_SECURITY_INFORMATION = OBJECT_SECURITY_INFORMATION.UNPROTECTED_SACL_SECURITY_INFORMATION; pub const SECURITY_AUTO_INHERIT_FLAGS = enum(u32) { AVOID_OWNER_CHECK = 16, AVOID_OWNER_RESTRICTION = 4096, AVOID_PRIVILEGE_CHECK = 8, DACL_AUTO_INHERIT = 1, DEFAULT_DESCRIPTOR_FOR_OBJECT = 4, DEFAULT_GROUP_FROM_PARENT = 64, DEFAULT_OWNER_FROM_PARENT = 32, MACL_NO_EXECUTE_UP = 1024, MACL_NO_READ_UP = 512, MACL_NO_WRITE_UP = 256, SACL_AUTO_INHERIT = 2, _, pub fn initFlags(o: struct { AVOID_OWNER_CHECK: u1 = 0, AVOID_OWNER_RESTRICTION: u1 = 0, AVOID_PRIVILEGE_CHECK: u1 = 0, DACL_AUTO_INHERIT: u1 = 0, DEFAULT_DESCRIPTOR_FOR_OBJECT: u1 = 0, DEFAULT_GROUP_FROM_PARENT: u1 = 0, DEFAULT_OWNER_FROM_PARENT: u1 = 0, MACL_NO_EXECUTE_UP: u1 = 0, MACL_NO_READ_UP: u1 = 0, MACL_NO_WRITE_UP: u1 = 0, SACL_AUTO_INHERIT: u1 = 0, }) SECURITY_AUTO_INHERIT_FLAGS { return @intToEnum(SECURITY_AUTO_INHERIT_FLAGS, (if (o.AVOID_OWNER_CHECK == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.AVOID_OWNER_CHECK) else 0) | (if (o.AVOID_OWNER_RESTRICTION == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.AVOID_OWNER_RESTRICTION) else 0) | (if (o.AVOID_PRIVILEGE_CHECK == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.AVOID_PRIVILEGE_CHECK) else 0) | (if (o.DACL_AUTO_INHERIT == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.DACL_AUTO_INHERIT) else 0) | (if (o.DEFAULT_DESCRIPTOR_FOR_OBJECT == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_DESCRIPTOR_FOR_OBJECT) else 0) | (if (o.DEFAULT_GROUP_FROM_PARENT == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_GROUP_FROM_PARENT) else 0) | (if (o.DEFAULT_OWNER_FROM_PARENT == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_OWNER_FROM_PARENT) else 0) | (if (o.MACL_NO_EXECUTE_UP == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_EXECUTE_UP) else 0) | (if (o.MACL_NO_READ_UP == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_READ_UP) else 0) | (if (o.MACL_NO_WRITE_UP == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_WRITE_UP) else 0) | (if (o.SACL_AUTO_INHERIT == 1) @enumToInt(SECURITY_AUTO_INHERIT_FLAGS.SACL_AUTO_INHERIT) else 0) ); } }; pub const SEF_AVOID_OWNER_CHECK = SECURITY_AUTO_INHERIT_FLAGS.AVOID_OWNER_CHECK; pub const SEF_AVOID_OWNER_RESTRICTION = SECURITY_AUTO_INHERIT_FLAGS.AVOID_OWNER_RESTRICTION; pub const SEF_AVOID_PRIVILEGE_CHECK = SECURITY_AUTO_INHERIT_FLAGS.AVOID_PRIVILEGE_CHECK; pub const SEF_DACL_AUTO_INHERIT = SECURITY_AUTO_INHERIT_FLAGS.DACL_AUTO_INHERIT; pub const SEF_DEFAULT_DESCRIPTOR_FOR_OBJECT = SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_DESCRIPTOR_FOR_OBJECT; pub const SEF_DEFAULT_GROUP_FROM_PARENT = SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_GROUP_FROM_PARENT; pub const SEF_DEFAULT_OWNER_FROM_PARENT = SECURITY_AUTO_INHERIT_FLAGS.DEFAULT_OWNER_FROM_PARENT; pub const SEF_MACL_NO_EXECUTE_UP = SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_EXECUTE_UP; pub const SEF_MACL_NO_READ_UP = SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_READ_UP; pub const SEF_MACL_NO_WRITE_UP = SECURITY_AUTO_INHERIT_FLAGS.MACL_NO_WRITE_UP; pub const SEF_SACL_AUTO_INHERIT = SECURITY_AUTO_INHERIT_FLAGS.SACL_AUTO_INHERIT; pub const ACE_REVISION = enum(u32) { N = 2, _DS = 4, }; pub const ACL_REVISION = ACE_REVISION.N; pub const ACL_REVISION_DS = ACE_REVISION._DS; pub const TOKEN_MANDATORY_POLICY_ID = enum(u32) { OFF = 0, NO_WRITE_UP = 1, NEW_PROCESS_MIN = 2, VALID_MASK = 3, }; pub const TOKEN_MANDATORY_POLICY_OFF = TOKEN_MANDATORY_POLICY_ID.OFF; pub const TOKEN_MANDATORY_POLICY_NO_WRITE_UP = TOKEN_MANDATORY_POLICY_ID.NO_WRITE_UP; pub const TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN = TOKEN_MANDATORY_POLICY_ID.NEW_PROCESS_MIN; pub const TOKEN_MANDATORY_POLICY_VALID_MASK = TOKEN_MANDATORY_POLICY_ID.VALID_MASK; pub const SYSTEM_AUDIT_OBJECT_ACE_FLAGS = enum(u32) { OBJECT_TYPE_PRESENT = 1, INHERITED_OBJECT_TYPE_PRESENT = 2, _, pub fn initFlags(o: struct { OBJECT_TYPE_PRESENT: u1 = 0, INHERITED_OBJECT_TYPE_PRESENT: u1 = 0, }) SYSTEM_AUDIT_OBJECT_ACE_FLAGS { return @intToEnum(SYSTEM_AUDIT_OBJECT_ACE_FLAGS, (if (o.OBJECT_TYPE_PRESENT == 1) @enumToInt(SYSTEM_AUDIT_OBJECT_ACE_FLAGS.OBJECT_TYPE_PRESENT) else 0) | (if (o.INHERITED_OBJECT_TYPE_PRESENT == 1) @enumToInt(SYSTEM_AUDIT_OBJECT_ACE_FLAGS.INHERITED_OBJECT_TYPE_PRESENT) else 0) ); } }; pub const ACE_OBJECT_TYPE_PRESENT = SYSTEM_AUDIT_OBJECT_ACE_FLAGS.OBJECT_TYPE_PRESENT; pub const ACE_INHERITED_OBJECT_TYPE_PRESENT = SYSTEM_AUDIT_OBJECT_ACE_FLAGS.INHERITED_OBJECT_TYPE_PRESENT; pub const CLAIM_SECURITY_ATTRIBUTE_FLAGS = enum(u32) { NON_INHERITABLE = 1, VALUE_CASE_SENSITIVE = 2, USE_FOR_DENY_ONLY = 4, DISABLED_BY_DEFAULT = 8, DISABLED = 16, MANDATORY = 32, _, pub fn initFlags(o: struct { NON_INHERITABLE: u1 = 0, VALUE_CASE_SENSITIVE: u1 = 0, USE_FOR_DENY_ONLY: u1 = 0, DISABLED_BY_DEFAULT: u1 = 0, DISABLED: u1 = 0, MANDATORY: u1 = 0, }) CLAIM_SECURITY_ATTRIBUTE_FLAGS { return @intToEnum(CLAIM_SECURITY_ATTRIBUTE_FLAGS, (if (o.NON_INHERITABLE == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.NON_INHERITABLE) else 0) | (if (o.VALUE_CASE_SENSITIVE == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.VALUE_CASE_SENSITIVE) else 0) | (if (o.USE_FOR_DENY_ONLY == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.USE_FOR_DENY_ONLY) else 0) | (if (o.DISABLED_BY_DEFAULT == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.DISABLED_BY_DEFAULT) else 0) | (if (o.DISABLED == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.DISABLED) else 0) | (if (o.MANDATORY == 1) @enumToInt(CLAIM_SECURITY_ATTRIBUTE_FLAGS.MANDATORY) else 0) ); } }; pub const CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE = CLAIM_SECURITY_ATTRIBUTE_FLAGS.NON_INHERITABLE; pub const CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE = CLAIM_SECURITY_ATTRIBUTE_FLAGS.VALUE_CASE_SENSITIVE; pub const CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY = CLAIM_SECURITY_ATTRIBUTE_FLAGS.USE_FOR_DENY_ONLY; pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT = CLAIM_SECURITY_ATTRIBUTE_FLAGS.DISABLED_BY_DEFAULT; pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED = CLAIM_SECURITY_ATTRIBUTE_FLAGS.DISABLED; pub const CLAIM_SECURITY_ATTRIBUTE_MANDATORY = CLAIM_SECURITY_ATTRIBUTE_FLAGS.MANDATORY; pub const CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE = enum(u16) { INT64 = 1, UINT64 = 2, STRING = 3, OCTET_STRING = 16, FQBN = 4, SID = 5, BOOLEAN = 6, }; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64 = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.INT64; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64 = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.UINT64; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.STRING; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.OCTET_STRING; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.FQBN; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_SID = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.SID; pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN = CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE.BOOLEAN; pub const PLSA_AP_CALL_PACKAGE_UNTRUSTED = fn( ClientRequest: ?*?*anyopaque, // TODO: what to do with BytesParamIndex 3? ProtocolSubmitBuffer: ?*anyopaque, ClientBufferBase: ?*anyopaque, SubmitBufferLength: u32, ProtocolReturnBuffer: ?*?*anyopaque, ReturnBufferLength: ?*u32, ProtocolStatus: ?*i32, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; pub const SEC_THREAD_START = fn( lpThreadParameter: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const TOKEN_ACCESS_MASK = enum(u32) { DELETE = 65536, READ_CONTROL = 131072, WRITE_DAC = 262144, WRITE_OWNER = 524288, ACCESS_SYSTEM_SECURITY = 16777216, ASSIGN_PRIMARY = 1, DUPLICATE = 2, IMPERSONATE = 4, QUERY = 8, QUERY_SOURCE = 16, ADJUST_PRIVILEGES = 32, ADJUST_GROUPS = 64, ADJUST_DEFAULT = 128, ADJUST_SESSIONID = 256, ALL_ACCESS = 983295, _, pub fn initFlags(o: struct { DELETE: u1 = 0, READ_CONTROL: u1 = 0, WRITE_DAC: u1 = 0, WRITE_OWNER: u1 = 0, ACCESS_SYSTEM_SECURITY: u1 = 0, ASSIGN_PRIMARY: u1 = 0, DUPLICATE: u1 = 0, IMPERSONATE: u1 = 0, QUERY: u1 = 0, QUERY_SOURCE: u1 = 0, ADJUST_PRIVILEGES: u1 = 0, ADJUST_GROUPS: u1 = 0, ADJUST_DEFAULT: u1 = 0, ADJUST_SESSIONID: u1 = 0, ALL_ACCESS: u1 = 0, }) TOKEN_ACCESS_MASK { return @intToEnum(TOKEN_ACCESS_MASK, (if (o.DELETE == 1) @enumToInt(TOKEN_ACCESS_MASK.DELETE) else 0) | (if (o.READ_CONTROL == 1) @enumToInt(TOKEN_ACCESS_MASK.READ_CONTROL) else 0) | (if (o.WRITE_DAC == 1) @enumToInt(TOKEN_ACCESS_MASK.WRITE_DAC) else 0) | (if (o.WRITE_OWNER == 1) @enumToInt(TOKEN_ACCESS_MASK.WRITE_OWNER) else 0) | (if (o.ACCESS_SYSTEM_SECURITY == 1) @enumToInt(TOKEN_ACCESS_MASK.ACCESS_SYSTEM_SECURITY) else 0) | (if (o.ASSIGN_PRIMARY == 1) @enumToInt(TOKEN_ACCESS_MASK.ASSIGN_PRIMARY) else 0) | (if (o.DUPLICATE == 1) @enumToInt(TOKEN_ACCESS_MASK.DUPLICATE) else 0) | (if (o.IMPERSONATE == 1) @enumToInt(TOKEN_ACCESS_MASK.IMPERSONATE) else 0) | (if (o.QUERY == 1) @enumToInt(TOKEN_ACCESS_MASK.QUERY) else 0) | (if (o.QUERY_SOURCE == 1) @enumToInt(TOKEN_ACCESS_MASK.QUERY_SOURCE) else 0) | (if (o.ADJUST_PRIVILEGES == 1) @enumToInt(TOKEN_ACCESS_MASK.ADJUST_PRIVILEGES) else 0) | (if (o.ADJUST_GROUPS == 1) @enumToInt(TOKEN_ACCESS_MASK.ADJUST_GROUPS) else 0) | (if (o.ADJUST_DEFAULT == 1) @enumToInt(TOKEN_ACCESS_MASK.ADJUST_DEFAULT) else 0) | (if (o.ADJUST_SESSIONID == 1) @enumToInt(TOKEN_ACCESS_MASK.ADJUST_SESSIONID) else 0) | (if (o.ALL_ACCESS == 1) @enumToInt(TOKEN_ACCESS_MASK.ALL_ACCESS) else 0) ); } }; pub const TOKEN_DELETE = TOKEN_ACCESS_MASK.DELETE; pub const TOKEN_READ_CONTROL = TOKEN_ACCESS_MASK.READ_CONTROL; pub const TOKEN_WRITE_DAC = TOKEN_ACCESS_MASK.WRITE_DAC; pub const TOKEN_WRITE_OWNER = TOKEN_ACCESS_MASK.WRITE_OWNER; pub const TOKEN_ACCESS_SYSTEM_SECURITY = TOKEN_ACCESS_MASK.ACCESS_SYSTEM_SECURITY; pub const TOKEN_ASSIGN_PRIMARY = TOKEN_ACCESS_MASK.ASSIGN_PRIMARY; pub const TOKEN_DUPLICATE = TOKEN_ACCESS_MASK.DUPLICATE; pub const TOKEN_IMPERSONATE = TOKEN_ACCESS_MASK.IMPERSONATE; pub const TOKEN_QUERY = TOKEN_ACCESS_MASK.QUERY; pub const TOKEN_QUERY_SOURCE = TOKEN_ACCESS_MASK.QUERY_SOURCE; pub const TOKEN_ADJUST_PRIVILEGES = TOKEN_ACCESS_MASK.ADJUST_PRIVILEGES; pub const TOKEN_ADJUST_GROUPS = TOKEN_ACCESS_MASK.ADJUST_GROUPS; pub const TOKEN_ADJUST_DEFAULT = TOKEN_ACCESS_MASK.ADJUST_DEFAULT; pub const TOKEN_ADJUST_SESSIONID = TOKEN_ACCESS_MASK.ADJUST_SESSIONID; pub const TOKEN_ALL_ACCESS = TOKEN_ACCESS_MASK.ALL_ACCESS; pub const HDIAGNOSTIC_DATA_QUERY_SESSION = isize; pub const HDIAGNOSTIC_REPORT = isize; pub const HDIAGNOSTIC_EVENT_TAG_DESCRIPTION = isize; pub const HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION = isize; pub const HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION = isize; pub const HDIAGNOSTIC_RECORD = isize; pub const NCRYPT_DESCRIPTOR_HANDLE = isize; pub const NCRYPT_STREAM_HANDLE = isize; pub const SAFER_LEVEL_HANDLE = isize; pub const SC_HANDLE = isize; pub const SECURITY_ATTRIBUTES = extern struct { nLength: u32, lpSecurityDescriptor: ?*anyopaque, bInheritHandle: BOOL, }; pub const ENUM_PERIOD = enum(i32) { INVALID = -1, SECONDS = 0, MINUTES = 1, HOURS = 2, DAYS = 3, WEEKS = 4, MONTHS = 5, YEARS = 6, }; pub const ENUM_PERIOD_INVALID = ENUM_PERIOD.INVALID; pub const ENUM_PERIOD_SECONDS = ENUM_PERIOD.SECONDS; pub const ENUM_PERIOD_MINUTES = ENUM_PERIOD.MINUTES; pub const ENUM_PERIOD_HOURS = ENUM_PERIOD.HOURS; pub const ENUM_PERIOD_DAYS = ENUM_PERIOD.DAYS; pub const ENUM_PERIOD_WEEKS = ENUM_PERIOD.WEEKS; pub const ENUM_PERIOD_MONTHS = ENUM_PERIOD.MONTHS; pub const ENUM_PERIOD_YEARS = ENUM_PERIOD.YEARS; pub const LLFILETIME = extern struct { Anonymous: extern union { ll: i64, ft: FILETIME, }, }; pub const GENERIC_MAPPING = extern struct { GenericRead: u32, GenericWrite: u32, GenericExecute: u32, GenericAll: u32, }; pub const LUID_AND_ATTRIBUTES = extern struct { Luid: LUID, Attributes: TOKEN_PRIVILEGES_ATTRIBUTES, }; pub const SID_IDENTIFIER_AUTHORITY = extern struct { Value: [6]u8, }; pub const SID = extern struct { Revision: u8, SubAuthorityCount: u8, IdentifierAuthority: SID_IDENTIFIER_AUTHORITY, SubAuthority: [1]u32, }; pub const SE_SID = extern union { Sid: SID, Buffer: [68]u8, }; pub const SID_NAME_USE = enum(i32) { User = 1, Group = 2, Domain = 3, Alias = 4, WellKnownGroup = 5, DeletedAccount = 6, Invalid = 7, Unknown = 8, Computer = 9, Label = 10, LogonSession = 11, }; pub const SidTypeUser = SID_NAME_USE.User; pub const SidTypeGroup = SID_NAME_USE.Group; pub const SidTypeDomain = SID_NAME_USE.Domain; pub const SidTypeAlias = SID_NAME_USE.Alias; pub const SidTypeWellKnownGroup = SID_NAME_USE.WellKnownGroup; pub const SidTypeDeletedAccount = SID_NAME_USE.DeletedAccount; pub const SidTypeInvalid = SID_NAME_USE.Invalid; pub const SidTypeUnknown = SID_NAME_USE.Unknown; pub const SidTypeComputer = SID_NAME_USE.Computer; pub const SidTypeLabel = SID_NAME_USE.Label; pub const SidTypeLogonSession = SID_NAME_USE.LogonSession; pub const SID_AND_ATTRIBUTES = extern struct { Sid: ?PSID, Attributes: u32, }; pub const SID_AND_ATTRIBUTES_HASH = extern struct { SidCount: u32, SidAttr: ?*SID_AND_ATTRIBUTES, Hash: [32]usize, }; pub const WELL_KNOWN_SID_TYPE = enum(i32) { NullSid = 0, WorldSid = 1, LocalSid = 2, CreatorOwnerSid = 3, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorGroupServerSid = 6, NtAuthoritySid = 7, DialupSid = 8, NetworkSid = 9, BatchSid = 10, InteractiveSid = 11, ServiceSid = 12, AnonymousSid = 13, ProxySid = 14, EnterpriseControllersSid = 15, SelfSid = 16, AuthenticatedUserSid = 17, RestrictedCodeSid = 18, TerminalServerSid = 19, RemoteLogonIdSid = 20, LogonIdsSid = 21, LocalSystemSid = 22, LocalServiceSid = 23, NetworkServiceSid = 24, BuiltinDomainSid = 25, BuiltinAdministratorsSid = 26, BuiltinUsersSid = 27, BuiltinGuestsSid = 28, BuiltinPowerUsersSid = 29, BuiltinAccountOperatorsSid = 30, BuiltinSystemOperatorsSid = 31, BuiltinPrintOperatorsSid = 32, BuiltinBackupOperatorsSid = 33, BuiltinReplicatorSid = 34, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinRemoteDesktopUsersSid = 36, BuiltinNetworkConfigurationOperatorsSid = 37, AccountAdministratorSid = 38, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountDomainAdminsSid = 41, AccountDomainUsersSid = 42, AccountDomainGuestsSid = 43, AccountComputersSid = 44, AccountControllersSid = 45, AccountCertAdminsSid = 46, AccountSchemaAdminsSid = 47, AccountEnterpriseAdminsSid = 48, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, NTLMAuthenticationSid = 51, DigestAuthenticationSid = 52, SChannelAuthenticationSid = 53, ThisOrganizationSid = 54, OtherOrganizationSid = 55, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinPerfMonitoringUsersSid = 57, BuiltinPerfLoggingUsersSid = 58, BuiltinAuthorizationAccessSid = 59, BuiltinTerminalServerLicenseServersSid = 60, BuiltinDCOMUsersSid = 61, BuiltinIUsersSid = 62, IUserSid = 63, BuiltinCryptoOperatorsSid = 64, UntrustedLabelSid = 65, LowLabelSid = 66, MediumLabelSid = 67, HighLabelSid = 68, SystemLabelSid = 69, WriteRestrictedCodeSid = 70, CreatorOwnerRightsSid = 71, CacheablePrincipalsGroupSid = 72, NonCacheablePrincipalsGroupSid = 73, EnterpriseReadonlyControllersSid = 74, AccountReadonlyControllersSid = 75, BuiltinEventLogReadersGroup = 76, NewEnterpriseReadonlyControllersSid = 77, BuiltinCertSvcDComAccessGroup = 78, MediumPlusLabelSid = 79, LocalLogonSid = 80, ConsoleLogonSid = 81, ThisOrganizationCertificateSid = 82, ApplicationPackageAuthoritySid = 83, BuiltinAnyPackageSid = 84, CapabilityInternetClientSid = 85, CapabilityInternetClientServerSid = 86, CapabilityPrivateNetworkClientServerSid = 87, CapabilityPicturesLibrarySid = 88, CapabilityVideosLibrarySid = 89, CapabilityMusicLibrarySid = 90, CapabilityDocumentsLibrarySid = 91, CapabilitySharedUserCertificatesSid = 92, CapabilityEnterpriseAuthenticationSid = 93, CapabilityRemovableStorageSid = 94, BuiltinRDSRemoteAccessServersSid = 95, BuiltinRDSEndpointServersSid = 96, BuiltinRDSManagementServersSid = 97, UserModeDriversSid = 98, BuiltinHyperVAdminsSid = 99, AccountCloneableControllersSid = 100, BuiltinAccessControlAssistanceOperatorsSid = 101, BuiltinRemoteManagementUsersSid = 102, AuthenticationAuthorityAssertedSid = 103, AuthenticationServiceAssertedSid = 104, LocalAccountSid = 105, LocalAccountAndAdministratorSid = 106, AccountProtectedUsersSid = 107, CapabilityAppointmentsSid = 108, CapabilityContactsSid = 109, AccountDefaultSystemManagedSid = 110, BuiltinDefaultSystemManagedGroupSid = 111, BuiltinStorageReplicaAdminsSid = 112, AccountKeyAdminsSid = 113, AccountEnterpriseKeyAdminsSid = 114, AuthenticationKeyTrustSid = 115, AuthenticationKeyPropertyMFASid = 116, AuthenticationKeyPropertyAttestationSid = 117, AuthenticationFreshKeyAuthSid = 118, BuiltinDeviceOwnersSid = 119, }; pub const WinNullSid = WELL_KNOWN_SID_TYPE.NullSid; pub const WinWorldSid = WELL_KNOWN_SID_TYPE.WorldSid; pub const WinLocalSid = WELL_KNOWN_SID_TYPE.LocalSid; pub const WinCreatorOwnerSid = WELL_KNOWN_SID_TYPE.CreatorOwnerSid; pub const WinCreatorGroupSid = WELL_KNOWN_SID_TYPE.CreatorGroupSid; pub const WinCreatorOwnerServerSid = WELL_KNOWN_SID_TYPE.CreatorOwnerServerSid; pub const WinCreatorGroupServerSid = WELL_KNOWN_SID_TYPE.CreatorGroupServerSid; pub const WinNtAuthoritySid = WELL_KNOWN_SID_TYPE.NtAuthoritySid; pub const WinDialupSid = WELL_KNOWN_SID_TYPE.DialupSid; pub const WinNetworkSid = WELL_KNOWN_SID_TYPE.NetworkSid; pub const WinBatchSid = WELL_KNOWN_SID_TYPE.BatchSid; pub const WinInteractiveSid = WELL_KNOWN_SID_TYPE.InteractiveSid; pub const WinServiceSid = WELL_KNOWN_SID_TYPE.ServiceSid; pub const WinAnonymousSid = WELL_KNOWN_SID_TYPE.AnonymousSid; pub const WinProxySid = WELL_KNOWN_SID_TYPE.ProxySid; pub const WinEnterpriseControllersSid = WELL_KNOWN_SID_TYPE.EnterpriseControllersSid; pub const WinSelfSid = WELL_KNOWN_SID_TYPE.SelfSid; pub const WinAuthenticatedUserSid = WELL_KNOWN_SID_TYPE.AuthenticatedUserSid; pub const WinRestrictedCodeSid = WELL_KNOWN_SID_TYPE.RestrictedCodeSid; pub const WinTerminalServerSid = WELL_KNOWN_SID_TYPE.TerminalServerSid; pub const WinRemoteLogonIdSid = WELL_KNOWN_SID_TYPE.RemoteLogonIdSid; pub const WinLogonIdsSid = WELL_KNOWN_SID_TYPE.LogonIdsSid; pub const WinLocalSystemSid = WELL_KNOWN_SID_TYPE.LocalSystemSid; pub const WinLocalServiceSid = WELL_KNOWN_SID_TYPE.LocalServiceSid; pub const WinNetworkServiceSid = WELL_KNOWN_SID_TYPE.NetworkServiceSid; pub const WinBuiltinDomainSid = WELL_KNOWN_SID_TYPE.BuiltinDomainSid; pub const WinBuiltinAdministratorsSid = WELL_KNOWN_SID_TYPE.BuiltinAdministratorsSid; pub const WinBuiltinUsersSid = WELL_KNOWN_SID_TYPE.BuiltinUsersSid; pub const WinBuiltinGuestsSid = WELL_KNOWN_SID_TYPE.BuiltinGuestsSid; pub const WinBuiltinPowerUsersSid = WELL_KNOWN_SID_TYPE.BuiltinPowerUsersSid; pub const WinBuiltinAccountOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinAccountOperatorsSid; pub const WinBuiltinSystemOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinSystemOperatorsSid; pub const WinBuiltinPrintOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinPrintOperatorsSid; pub const WinBuiltinBackupOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinBackupOperatorsSid; pub const WinBuiltinReplicatorSid = WELL_KNOWN_SID_TYPE.BuiltinReplicatorSid; pub const WinBuiltinPreWindows2000CompatibleAccessSid = WELL_KNOWN_SID_TYPE.BuiltinPreWindows2000CompatibleAccessSid; pub const WinBuiltinRemoteDesktopUsersSid = WELL_KNOWN_SID_TYPE.BuiltinRemoteDesktopUsersSid; pub const WinBuiltinNetworkConfigurationOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinNetworkConfigurationOperatorsSid; pub const WinAccountAdministratorSid = WELL_KNOWN_SID_TYPE.AccountAdministratorSid; pub const WinAccountGuestSid = WELL_KNOWN_SID_TYPE.AccountGuestSid; pub const WinAccountKrbtgtSid = WELL_KNOWN_SID_TYPE.AccountKrbtgtSid; pub const WinAccountDomainAdminsSid = WELL_KNOWN_SID_TYPE.AccountDomainAdminsSid; pub const WinAccountDomainUsersSid = WELL_KNOWN_SID_TYPE.AccountDomainUsersSid; pub const WinAccountDomainGuestsSid = WELL_KNOWN_SID_TYPE.AccountDomainGuestsSid; pub const WinAccountComputersSid = WELL_KNOWN_SID_TYPE.AccountComputersSid; pub const WinAccountControllersSid = WELL_KNOWN_SID_TYPE.AccountControllersSid; pub const WinAccountCertAdminsSid = WELL_KNOWN_SID_TYPE.AccountCertAdminsSid; pub const WinAccountSchemaAdminsSid = WELL_KNOWN_SID_TYPE.AccountSchemaAdminsSid; pub const WinAccountEnterpriseAdminsSid = WELL_KNOWN_SID_TYPE.AccountEnterpriseAdminsSid; pub const WinAccountPolicyAdminsSid = WELL_KNOWN_SID_TYPE.AccountPolicyAdminsSid; pub const WinAccountRasAndIasServersSid = WELL_KNOWN_SID_TYPE.AccountRasAndIasServersSid; pub const WinNTLMAuthenticationSid = WELL_KNOWN_SID_TYPE.NTLMAuthenticationSid; pub const WinDigestAuthenticationSid = WELL_KNOWN_SID_TYPE.DigestAuthenticationSid; pub const WinSChannelAuthenticationSid = WELL_KNOWN_SID_TYPE.SChannelAuthenticationSid; pub const WinThisOrganizationSid = WELL_KNOWN_SID_TYPE.ThisOrganizationSid; pub const WinOtherOrganizationSid = WELL_KNOWN_SID_TYPE.OtherOrganizationSid; pub const WinBuiltinIncomingForestTrustBuildersSid = WELL_KNOWN_SID_TYPE.BuiltinIncomingForestTrustBuildersSid; pub const WinBuiltinPerfMonitoringUsersSid = WELL_KNOWN_SID_TYPE.BuiltinPerfMonitoringUsersSid; pub const WinBuiltinPerfLoggingUsersSid = WELL_KNOWN_SID_TYPE.BuiltinPerfLoggingUsersSid; pub const WinBuiltinAuthorizationAccessSid = WELL_KNOWN_SID_TYPE.BuiltinAuthorizationAccessSid; pub const WinBuiltinTerminalServerLicenseServersSid = WELL_KNOWN_SID_TYPE.BuiltinTerminalServerLicenseServersSid; pub const WinBuiltinDCOMUsersSid = WELL_KNOWN_SID_TYPE.BuiltinDCOMUsersSid; pub const WinBuiltinIUsersSid = WELL_KNOWN_SID_TYPE.BuiltinIUsersSid; pub const WinIUserSid = WELL_KNOWN_SID_TYPE.IUserSid; pub const WinBuiltinCryptoOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinCryptoOperatorsSid; pub const WinUntrustedLabelSid = WELL_KNOWN_SID_TYPE.UntrustedLabelSid; pub const WinLowLabelSid = WELL_KNOWN_SID_TYPE.LowLabelSid; pub const WinMediumLabelSid = WELL_KNOWN_SID_TYPE.MediumLabelSid; pub const WinHighLabelSid = WELL_KNOWN_SID_TYPE.HighLabelSid; pub const WinSystemLabelSid = WELL_KNOWN_SID_TYPE.SystemLabelSid; pub const WinWriteRestrictedCodeSid = WELL_KNOWN_SID_TYPE.WriteRestrictedCodeSid; pub const WinCreatorOwnerRightsSid = WELL_KNOWN_SID_TYPE.CreatorOwnerRightsSid; pub const WinCacheablePrincipalsGroupSid = WELL_KNOWN_SID_TYPE.CacheablePrincipalsGroupSid; pub const WinNonCacheablePrincipalsGroupSid = WELL_KNOWN_SID_TYPE.NonCacheablePrincipalsGroupSid; pub const WinEnterpriseReadonlyControllersSid = WELL_KNOWN_SID_TYPE.EnterpriseReadonlyControllersSid; pub const WinAccountReadonlyControllersSid = WELL_KNOWN_SID_TYPE.AccountReadonlyControllersSid; pub const WinBuiltinEventLogReadersGroup = WELL_KNOWN_SID_TYPE.BuiltinEventLogReadersGroup; pub const WinNewEnterpriseReadonlyControllersSid = WELL_KNOWN_SID_TYPE.NewEnterpriseReadonlyControllersSid; pub const WinBuiltinCertSvcDComAccessGroup = WELL_KNOWN_SID_TYPE.BuiltinCertSvcDComAccessGroup; pub const WinMediumPlusLabelSid = WELL_KNOWN_SID_TYPE.MediumPlusLabelSid; pub const WinLocalLogonSid = WELL_KNOWN_SID_TYPE.LocalLogonSid; pub const WinConsoleLogonSid = WELL_KNOWN_SID_TYPE.ConsoleLogonSid; pub const WinThisOrganizationCertificateSid = WELL_KNOWN_SID_TYPE.ThisOrganizationCertificateSid; pub const WinApplicationPackageAuthoritySid = WELL_KNOWN_SID_TYPE.ApplicationPackageAuthoritySid; pub const WinBuiltinAnyPackageSid = WELL_KNOWN_SID_TYPE.BuiltinAnyPackageSid; pub const WinCapabilityInternetClientSid = WELL_KNOWN_SID_TYPE.CapabilityInternetClientSid; pub const WinCapabilityInternetClientServerSid = WELL_KNOWN_SID_TYPE.CapabilityInternetClientServerSid; pub const WinCapabilityPrivateNetworkClientServerSid = WELL_KNOWN_SID_TYPE.CapabilityPrivateNetworkClientServerSid; pub const WinCapabilityPicturesLibrarySid = WELL_KNOWN_SID_TYPE.CapabilityPicturesLibrarySid; pub const WinCapabilityVideosLibrarySid = WELL_KNOWN_SID_TYPE.CapabilityVideosLibrarySid; pub const WinCapabilityMusicLibrarySid = WELL_KNOWN_SID_TYPE.CapabilityMusicLibrarySid; pub const WinCapabilityDocumentsLibrarySid = WELL_KNOWN_SID_TYPE.CapabilityDocumentsLibrarySid; pub const WinCapabilitySharedUserCertificatesSid = WELL_KNOWN_SID_TYPE.CapabilitySharedUserCertificatesSid; pub const WinCapabilityEnterpriseAuthenticationSid = WELL_KNOWN_SID_TYPE.CapabilityEnterpriseAuthenticationSid; pub const WinCapabilityRemovableStorageSid = WELL_KNOWN_SID_TYPE.CapabilityRemovableStorageSid; pub const WinBuiltinRDSRemoteAccessServersSid = WELL_KNOWN_SID_TYPE.BuiltinRDSRemoteAccessServersSid; pub const WinBuiltinRDSEndpointServersSid = WELL_KNOWN_SID_TYPE.BuiltinRDSEndpointServersSid; pub const WinBuiltinRDSManagementServersSid = WELL_KNOWN_SID_TYPE.BuiltinRDSManagementServersSid; pub const WinUserModeDriversSid = WELL_KNOWN_SID_TYPE.UserModeDriversSid; pub const WinBuiltinHyperVAdminsSid = WELL_KNOWN_SID_TYPE.BuiltinHyperVAdminsSid; pub const WinAccountCloneableControllersSid = WELL_KNOWN_SID_TYPE.AccountCloneableControllersSid; pub const WinBuiltinAccessControlAssistanceOperatorsSid = WELL_KNOWN_SID_TYPE.BuiltinAccessControlAssistanceOperatorsSid; pub const WinBuiltinRemoteManagementUsersSid = WELL_KNOWN_SID_TYPE.BuiltinRemoteManagementUsersSid; pub const WinAuthenticationAuthorityAssertedSid = WELL_KNOWN_SID_TYPE.AuthenticationAuthorityAssertedSid; pub const WinAuthenticationServiceAssertedSid = WELL_KNOWN_SID_TYPE.AuthenticationServiceAssertedSid; pub const WinLocalAccountSid = WELL_KNOWN_SID_TYPE.LocalAccountSid; pub const WinLocalAccountAndAdministratorSid = WELL_KNOWN_SID_TYPE.LocalAccountAndAdministratorSid; pub const WinAccountProtectedUsersSid = WELL_KNOWN_SID_TYPE.AccountProtectedUsersSid; pub const WinCapabilityAppointmentsSid = WELL_KNOWN_SID_TYPE.CapabilityAppointmentsSid; pub const WinCapabilityContactsSid = WELL_KNOWN_SID_TYPE.CapabilityContactsSid; pub const WinAccountDefaultSystemManagedSid = WELL_KNOWN_SID_TYPE.AccountDefaultSystemManagedSid; pub const WinBuiltinDefaultSystemManagedGroupSid = WELL_KNOWN_SID_TYPE.BuiltinDefaultSystemManagedGroupSid; pub const WinBuiltinStorageReplicaAdminsSid = WELL_KNOWN_SID_TYPE.BuiltinStorageReplicaAdminsSid; pub const WinAccountKeyAdminsSid = WELL_KNOWN_SID_TYPE.AccountKeyAdminsSid; pub const WinAccountEnterpriseKeyAdminsSid = WELL_KNOWN_SID_TYPE.AccountEnterpriseKeyAdminsSid; pub const WinAuthenticationKeyTrustSid = WELL_KNOWN_SID_TYPE.AuthenticationKeyTrustSid; pub const WinAuthenticationKeyPropertyMFASid = WELL_KNOWN_SID_TYPE.AuthenticationKeyPropertyMFASid; pub const WinAuthenticationKeyPropertyAttestationSid = WELL_KNOWN_SID_TYPE.AuthenticationKeyPropertyAttestationSid; pub const WinAuthenticationFreshKeyAuthSid = WELL_KNOWN_SID_TYPE.AuthenticationFreshKeyAuthSid; pub const WinBuiltinDeviceOwnersSid = WELL_KNOWN_SID_TYPE.BuiltinDeviceOwnersSid; pub const ACL = extern struct { AclRevision: u8, Sbz1: u8, AclSize: u16, AceCount: u16, Sbz2: u16, }; pub const ACE_HEADER = extern struct { AceType: u8, AceFlags: u8, AceSize: u16, }; pub const ACCESS_ALLOWED_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const ACCESS_DENIED_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_AUDIT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_ALARM_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_RESOURCE_ATTRIBUTE_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_SCOPED_POLICY_ID_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_MANDATORY_LABEL_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_PROCESS_TRUST_LABEL_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_ACCESS_FILTER_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const ACCESS_ALLOWED_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const ACCESS_DENIED_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const SYSTEM_AUDIT_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const SYSTEM_ALARM_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: u32, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const ACCESS_ALLOWED_CALLBACK_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const ACCESS_DENIED_CALLBACK_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_AUDIT_CALLBACK_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const SYSTEM_ALARM_CALLBACK_ACE = extern struct { Header: ACE_HEADER, Mask: u32, SidStart: u32, }; pub const ACCESS_ALLOWED_CALLBACK_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const ACCESS_DENIED_CALLBACK_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const SYSTEM_AUDIT_CALLBACK_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const SYSTEM_ALARM_CALLBACK_OBJECT_ACE = extern struct { Header: ACE_HEADER, Mask: u32, Flags: SYSTEM_AUDIT_OBJECT_ACE_FLAGS, ObjectType: Guid, InheritedObjectType: Guid, SidStart: u32, }; pub const ACL_INFORMATION_CLASS = enum(i32) { RevisionInformation = 1, SizeInformation = 2, }; pub const AclRevisionInformation = ACL_INFORMATION_CLASS.RevisionInformation; pub const AclSizeInformation = ACL_INFORMATION_CLASS.SizeInformation; pub const ACL_REVISION_INFORMATION = extern struct { AclRevision: u32, }; pub const ACL_SIZE_INFORMATION = extern struct { AceCount: u32, AclBytesInUse: u32, AclBytesFree: u32, }; pub const SECURITY_DESCRIPTOR = extern struct { Revision: u8, Sbz1: u8, Control: u16, Owner: ?PSID, Group: ?PSID, Sacl: ?*ACL, Dacl: ?*ACL, }; pub const OBJECT_TYPE_LIST = extern struct { Level: u16, Sbz: u16, ObjectType: ?*Guid, }; pub const AUDIT_EVENT_TYPE = enum(i32) { ObjectAccess = 0, DirectoryServiceAccess = 1, }; pub const AuditEventObjectAccess = AUDIT_EVENT_TYPE.ObjectAccess; pub const AuditEventDirectoryServiceAccess = AUDIT_EVENT_TYPE.DirectoryServiceAccess; pub const PRIVILEGE_SET = extern struct { PrivilegeCount: u32, Control: u32, Privilege: [1]LUID_AND_ATTRIBUTES, }; pub const ACCESS_REASONS = extern struct { Data: [32]u32, }; pub const SE_SECURITY_DESCRIPTOR = extern struct { Size: u32, Flags: u32, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, }; pub const SE_ACCESS_REQUEST = extern struct { Size: u32, SeSecurityDescriptor: ?*SE_SECURITY_DESCRIPTOR, DesiredAccess: u32, PreviouslyGrantedAccess: u32, PrincipalSelfSid: ?PSID, GenericMapping: ?*GENERIC_MAPPING, ObjectTypeListCount: u32, ObjectTypeList: ?*OBJECT_TYPE_LIST, }; pub const SE_ACCESS_REPLY = extern struct { Size: u32, ResultListCount: u32, GrantedAccess: ?*u32, AccessStatus: ?*u32, AccessReason: ?*ACCESS_REASONS, Privileges: ?*?*PRIVILEGE_SET, }; pub const SECURITY_IMPERSONATION_LEVEL = enum(i32) { Anonymous = 0, Identification = 1, Impersonation = 2, Delegation = 3, }; pub const SecurityAnonymous = SECURITY_IMPERSONATION_LEVEL.Anonymous; pub const SecurityIdentification = SECURITY_IMPERSONATION_LEVEL.Identification; pub const SecurityImpersonation = SECURITY_IMPERSONATION_LEVEL.Impersonation; pub const SecurityDelegation = SECURITY_IMPERSONATION_LEVEL.Delegation; pub const TOKEN_TYPE = enum(i32) { Primary = 1, Impersonation = 2, }; pub const TokenPrimary = TOKEN_TYPE.Primary; pub const TokenImpersonation = TOKEN_TYPE.Impersonation; pub const TOKEN_ELEVATION_TYPE = enum(i32) { Default = 1, Full = 2, Limited = 3, }; pub const TokenElevationTypeDefault = TOKEN_ELEVATION_TYPE.Default; pub const TokenElevationTypeFull = TOKEN_ELEVATION_TYPE.Full; pub const TokenElevationTypeLimited = TOKEN_ELEVATION_TYPE.Limited; pub const TOKEN_INFORMATION_CLASS = enum(i32) { TokenUser = 1, TokenGroups = 2, TokenPrivileges = 3, TokenOwner = 4, TokenPrimaryGroup = 5, TokenDefaultDacl = 6, TokenSource = 7, TokenType = 8, TokenImpersonationLevel = 9, TokenStatistics = 10, TokenRestrictedSids = 11, TokenSessionId = 12, TokenGroupsAndPrivileges = 13, TokenSessionReference = 14, TokenSandBoxInert = 15, TokenAuditPolicy = 16, TokenOrigin = 17, TokenElevationType = 18, TokenLinkedToken = 19, TokenElevation = 20, TokenHasRestrictions = 21, TokenAccessInformation = 22, TokenVirtualizationAllowed = 23, TokenVirtualizationEnabled = 24, TokenIntegrityLevel = 25, TokenUIAccess = 26, TokenMandatoryPolicy = 27, TokenLogonSid = 28, TokenIsAppContainer = 29, TokenCapabilities = 30, TokenAppContainerSid = 31, TokenAppContainerNumber = 32, TokenUserClaimAttributes = 33, TokenDeviceClaimAttributes = 34, TokenRestrictedUserClaimAttributes = 35, TokenRestrictedDeviceClaimAttributes = 36, TokenDeviceGroups = 37, TokenRestrictedDeviceGroups = 38, TokenSecurityAttributes = 39, TokenIsRestricted = 40, TokenProcessTrustLevel = 41, TokenPrivateNameSpace = 42, TokenSingletonAttributes = 43, TokenBnoIsolation = 44, TokenChildProcessFlags = 45, TokenIsLessPrivilegedAppContainer = 46, TokenIsSandboxed = 47, MaxTokenInfoClass = 48, }; pub const TokenUser = TOKEN_INFORMATION_CLASS.TokenUser; pub const TokenGroups = TOKEN_INFORMATION_CLASS.TokenGroups; pub const TokenPrivileges = TOKEN_INFORMATION_CLASS.TokenPrivileges; pub const TokenOwner = TOKEN_INFORMATION_CLASS.TokenOwner; pub const TokenPrimaryGroup = TOKEN_INFORMATION_CLASS.TokenPrimaryGroup; pub const TokenDefaultDacl = TOKEN_INFORMATION_CLASS.TokenDefaultDacl; pub const TokenSource = TOKEN_INFORMATION_CLASS.TokenSource; pub const TokenType = TOKEN_INFORMATION_CLASS.TokenType; pub const TokenImpersonationLevel = TOKEN_INFORMATION_CLASS.TokenImpersonationLevel; pub const TokenStatistics = TOKEN_INFORMATION_CLASS.TokenStatistics; pub const TokenRestrictedSids = TOKEN_INFORMATION_CLASS.TokenRestrictedSids; pub const TokenSessionId = TOKEN_INFORMATION_CLASS.TokenSessionId; pub const TokenGroupsAndPrivileges = TOKEN_INFORMATION_CLASS.TokenGroupsAndPrivileges; pub const TokenSessionReference = TOKEN_INFORMATION_CLASS.TokenSessionReference; pub const TokenSandBoxInert = TOKEN_INFORMATION_CLASS.TokenSandBoxInert; pub const TokenAuditPolicy = TOKEN_INFORMATION_CLASS.TokenAuditPolicy; pub const TokenOrigin = TOKEN_INFORMATION_CLASS.TokenOrigin; pub const TokenElevationType = TOKEN_INFORMATION_CLASS.TokenElevationType; pub const TokenLinkedToken = TOKEN_INFORMATION_CLASS.TokenLinkedToken; pub const TokenElevation = TOKEN_INFORMATION_CLASS.TokenElevation; pub const TokenHasRestrictions = TOKEN_INFORMATION_CLASS.TokenHasRestrictions; pub const TokenAccessInformation = TOKEN_INFORMATION_CLASS.TokenAccessInformation; pub const TokenVirtualizationAllowed = TOKEN_INFORMATION_CLASS.TokenVirtualizationAllowed; pub const TokenVirtualizationEnabled = TOKEN_INFORMATION_CLASS.TokenVirtualizationEnabled; pub const TokenIntegrityLevel = TOKEN_INFORMATION_CLASS.TokenIntegrityLevel; pub const TokenUIAccess = TOKEN_INFORMATION_CLASS.TokenUIAccess; pub const TokenMandatoryPolicy = TOKEN_INFORMATION_CLASS.TokenMandatoryPolicy; pub const TokenLogonSid = TOKEN_INFORMATION_CLASS.TokenLogonSid; pub const TokenIsAppContainer = TOKEN_INFORMATION_CLASS.TokenIsAppContainer; pub const TokenCapabilities = TOKEN_INFORMATION_CLASS.TokenCapabilities; pub const TokenAppContainerSid = TOKEN_INFORMATION_CLASS.TokenAppContainerSid; pub const TokenAppContainerNumber = TOKEN_INFORMATION_CLASS.TokenAppContainerNumber; pub const TokenUserClaimAttributes = TOKEN_INFORMATION_CLASS.TokenUserClaimAttributes; pub const TokenDeviceClaimAttributes = TOKEN_INFORMATION_CLASS.TokenDeviceClaimAttributes; pub const TokenRestrictedUserClaimAttributes = TOKEN_INFORMATION_CLASS.TokenRestrictedUserClaimAttributes; pub const TokenRestrictedDeviceClaimAttributes = TOKEN_INFORMATION_CLASS.TokenRestrictedDeviceClaimAttributes; pub const TokenDeviceGroups = TOKEN_INFORMATION_CLASS.TokenDeviceGroups; pub const TokenRestrictedDeviceGroups = TOKEN_INFORMATION_CLASS.TokenRestrictedDeviceGroups; pub const TokenSecurityAttributes = TOKEN_INFORMATION_CLASS.TokenSecurityAttributes; pub const TokenIsRestricted = TOKEN_INFORMATION_CLASS.TokenIsRestricted; pub const TokenProcessTrustLevel = TOKEN_INFORMATION_CLASS.TokenProcessTrustLevel; pub const TokenPrivateNameSpace = TOKEN_INFORMATION_CLASS.TokenPrivateNameSpace; pub const TokenSingletonAttributes = TOKEN_INFORMATION_CLASS.TokenSingletonAttributes; pub const TokenBnoIsolation = TOKEN_INFORMATION_CLASS.TokenBnoIsolation; pub const TokenChildProcessFlags = TOKEN_INFORMATION_CLASS.TokenChildProcessFlags; pub const TokenIsLessPrivilegedAppContainer = TOKEN_INFORMATION_CLASS.TokenIsLessPrivilegedAppContainer; pub const TokenIsSandboxed = TOKEN_INFORMATION_CLASS.TokenIsSandboxed; pub const MaxTokenInfoClass = TOKEN_INFORMATION_CLASS.MaxTokenInfoClass; pub const TOKEN_USER = extern struct { User: SID_AND_ATTRIBUTES, }; pub const TOKEN_GROUPS = extern struct { GroupCount: u32, Groups: [1]SID_AND_ATTRIBUTES, }; pub const TOKEN_PRIVILEGES = extern struct { PrivilegeCount: u32, Privileges: [1]LUID_AND_ATTRIBUTES, }; pub const TOKEN_OWNER = extern struct { Owner: ?PSID, }; pub const TOKEN_PRIMARY_GROUP = extern struct { PrimaryGroup: ?PSID, }; pub const TOKEN_DEFAULT_DACL = extern struct { DefaultDacl: ?*ACL, }; pub const TOKEN_USER_CLAIMS = extern struct { UserClaims: ?*anyopaque, }; pub const TOKEN_DEVICE_CLAIMS = extern struct { DeviceClaims: ?*anyopaque, }; pub const TOKEN_GROUPS_AND_PRIVILEGES = extern struct { SidCount: u32, SidLength: u32, Sids: ?*SID_AND_ATTRIBUTES, RestrictedSidCount: u32, RestrictedSidLength: u32, RestrictedSids: ?*SID_AND_ATTRIBUTES, PrivilegeCount: u32, PrivilegeLength: u32, Privileges: ?*LUID_AND_ATTRIBUTES, AuthenticationId: LUID, }; pub const TOKEN_LINKED_TOKEN = extern struct { LinkedToken: ?HANDLE, }; pub const TOKEN_ELEVATION = extern struct { TokenIsElevated: u32, }; pub const TOKEN_MANDATORY_LABEL = extern struct { Label: SID_AND_ATTRIBUTES, }; pub const TOKEN_MANDATORY_POLICY = extern struct { Policy: TOKEN_MANDATORY_POLICY_ID, }; pub const TOKEN_ACCESS_INFORMATION = extern struct { SidHash: ?*SID_AND_ATTRIBUTES_HASH, RestrictedSidHash: ?*SID_AND_ATTRIBUTES_HASH, Privileges: ?*TOKEN_PRIVILEGES, AuthenticationId: LUID, TokenType: TOKEN_TYPE, ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, MandatoryPolicy: TOKEN_MANDATORY_POLICY, Flags: u32, AppContainerNumber: u32, PackageSid: ?PSID, CapabilitiesHash: ?*SID_AND_ATTRIBUTES_HASH, TrustLevelSid: ?PSID, SecurityAttributes: ?*anyopaque, }; pub const TOKEN_AUDIT_POLICY = extern struct { PerUserPolicy: [30]u8, }; pub const TOKEN_SOURCE = extern struct { SourceName: [8]CHAR, SourceIdentifier: LUID, }; pub const TOKEN_STATISTICS = extern struct { TokenId: LUID, AuthenticationId: LUID, ExpirationTime: LARGE_INTEGER, TokenType: TOKEN_TYPE, ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, DynamicCharged: u32, DynamicAvailable: u32, GroupCount: u32, PrivilegeCount: u32, ModifiedId: LUID, }; pub const TOKEN_CONTROL = extern struct { TokenId: LUID, AuthenticationId: LUID, ModifiedId: LUID, TokenSource: TOKEN_SOURCE, }; pub const TOKEN_ORIGIN = extern struct { OriginatingLogonSession: LUID, }; pub const MANDATORY_LEVEL = enum(i32) { Untrusted = 0, Low = 1, Medium = 2, High = 3, System = 4, SecureProcess = 5, Count = 6, }; pub const MandatoryLevelUntrusted = MANDATORY_LEVEL.Untrusted; pub const MandatoryLevelLow = MANDATORY_LEVEL.Low; pub const MandatoryLevelMedium = MANDATORY_LEVEL.Medium; pub const MandatoryLevelHigh = MANDATORY_LEVEL.High; pub const MandatoryLevelSystem = MANDATORY_LEVEL.System; pub const MandatoryLevelSecureProcess = MANDATORY_LEVEL.SecureProcess; pub const MandatoryLevelCount = MANDATORY_LEVEL.Count; pub const TOKEN_APPCONTAINER_INFORMATION = extern struct { TokenAppContainer: ?PSID, }; pub const CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE = extern struct { Version: u64, Name: ?PWSTR, }; pub const CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE = extern struct { pValue: ?*anyopaque, ValueLength: u32, }; pub const CLAIM_SECURITY_ATTRIBUTE_V1 = extern struct { Name: ?PWSTR, ValueType: CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE, Reserved: u16, Flags: u32, ValueCount: u32, Values: extern union { pInt64: ?*i64, pUint64: ?*u64, ppString: ?*?PWSTR, pFqbn: ?*CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE, pOctetString: ?*CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, }, }; pub const CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 = extern struct { Name: u32, ValueType: CLAIM_SECURITY_ATTRIBUTE_VALUE_TYPE, Reserved: u16, Flags: CLAIM_SECURITY_ATTRIBUTE_FLAGS, ValueCount: u32, Values: extern union { pInt64: [1]u32, pUint64: [1]u32, ppString: [1]u32, pFqbn: [1]u32, pOctetString: [1]u32, }, }; pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION = extern struct { Version: u16, Reserved: u16, AttributeCount: u32, Attribute: extern union { pAttributeV1: ?*CLAIM_SECURITY_ATTRIBUTE_V1, }, }; pub const SECURITY_QUALITY_OF_SERVICE = extern struct { Length: u32, ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, ContextTrackingMode: u8, EffectiveOnly: BOOLEAN, }; pub const SE_IMPERSONATION_STATE = extern struct { Token: ?*anyopaque, CopyOnOpen: BOOLEAN, EffectiveOnly: BOOLEAN, Level: SECURITY_IMPERSONATION_LEVEL, }; pub const SECURITY_CAPABILITIES = extern struct { AppContainerSid: ?PSID, Capabilities: ?*SID_AND_ATTRIBUTES, CapabilityCount: u32, Reserved: u32, }; pub const QUOTA_LIMITS = extern struct { PagedPoolLimit: usize, NonPagedPoolLimit: usize, MinimumWorkingSetSize: usize, MaximumWorkingSetSize: usize, PagefileLimit: usize, TimeLimit: LARGE_INTEGER, }; //-------------------------------------------------------------------------------- // Section: Functions (133) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheck( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ClientToken: ?HANDLE, DesiredAccess: u32, GenericMapping: ?*GENERIC_MAPPING, // TODO: what to do with BytesParamIndex 5? PrivilegeSet: ?*PRIVILEGE_SET, PrivilegeSetLength: ?*u32, GrantedAccess: ?*u32, AccessStatus: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn AccessCheckAndAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ObjectTypeName: ?PWSTR, ObjectName: ?PWSTR, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, DesiredAccess: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: ?*u32, AccessStatus: ?*i32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckByType( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, ClientToken: ?HANDLE, DesiredAccess: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, // TODO: what to do with BytesParamIndex 8? PrivilegeSet: ?*PRIVILEGE_SET, PrivilegeSetLength: ?*u32, GrantedAccess: ?*u32, AccessStatus: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckByTypeResultList( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, ClientToken: ?HANDLE, DesiredAccess: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, // TODO: what to do with BytesParamIndex 8? PrivilegeSet: ?*PRIVILEGE_SET, PrivilegeSetLength: ?*u32, GrantedAccessList: [*]u32, AccessStatusList: [*]u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn AccessCheckByTypeAndAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ObjectTypeName: ?[*:0]const u16, ObjectName: ?[*:0]const u16, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: ?*u32, AccessStatus: ?*i32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn AccessCheckByTypeResultListAndAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ObjectTypeName: ?[*:0]const u16, ObjectName: ?[*:0]const u16, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccessList: [*]u32, AccessStatusList: [*]u32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn AccessCheckByTypeResultListAndAuditAlarmByHandleW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ClientToken: ?HANDLE, ObjectTypeName: ?[*:0]const u16, ObjectName: ?[*:0]const u16, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccessList: [*]u32, AccessStatusList: [*]u32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessAllowedAce( pAcl: ?*ACL, dwAceRevision: u32, AccessMask: u32, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessAllowedAceEx( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessAllowedObjectAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, ObjectTypeGuid: ?*Guid, InheritedObjectTypeGuid: ?*Guid, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessDeniedAce( pAcl: ?*ACL, dwAceRevision: u32, AccessMask: u32, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessDeniedAceEx( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAccessDeniedObjectAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, ObjectTypeGuid: ?*Guid, InheritedObjectTypeGuid: ?*Guid, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAce( pAcl: ?*ACL, dwAceRevision: u32, dwStartingAceIndex: u32, // TODO: what to do with BytesParamIndex 4? pAceList: ?*anyopaque, nAceListLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAuditAccessAce( pAcl: ?*ACL, dwAceRevision: u32, dwAccessMask: u32, pSid: ?PSID, bAuditSuccess: BOOL, bAuditFailure: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAuditAccessAceEx( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, dwAccessMask: u32, pSid: ?PSID, bAuditSuccess: BOOL, bAuditFailure: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AddAuditAccessObjectAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, ObjectTypeGuid: ?*Guid, InheritedObjectTypeGuid: ?*Guid, pSid: ?PSID, bAuditSuccess: BOOL, bAuditFailure: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn AddMandatoryAce( pAcl: ?*ACL, dwAceRevision: ACE_REVISION, AceFlags: ACE_FLAGS, MandatoryPolicy: u32, pLabelSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "KERNEL32" fn AddResourceAttributeAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, pSid: ?PSID, pAttributeInfo: ?*CLAIM_SECURITY_ATTRIBUTES_INFORMATION, pReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "KERNEL32" fn AddScopedPolicyIDAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AccessMask: u32, pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AdjustTokenGroups( TokenHandle: ?HANDLE, ResetToDefault: BOOL, NewState: ?*TOKEN_GROUPS, BufferLength: u32, // TODO: what to do with BytesParamIndex 3? PreviousState: ?*TOKEN_GROUPS, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AdjustTokenPrivileges( TokenHandle: ?HANDLE, DisableAllPrivileges: BOOL, NewState: ?*TOKEN_PRIVILEGES, BufferLength: u32, // TODO: what to do with BytesParamIndex 3? PreviousState: ?*TOKEN_PRIVILEGES, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AllocateAndInitializeSid( pIdentifierAuthority: ?*SID_IDENTIFIER_AUTHORITY, nSubAuthorityCount: u8, nSubAuthority0: u32, nSubAuthority1: u32, nSubAuthority2: u32, nSubAuthority3: u32, nSubAuthority4: u32, nSubAuthority5: u32, nSubAuthority6: u32, nSubAuthority7: u32, pSid: ?*?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AllocateLocallyUniqueId( Luid: ?*LUID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AreAllAccessesGranted( GrantedAccess: u32, DesiredAccess: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AreAnyAccessesGranted( GrantedAccess: u32, DesiredAccess: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CheckTokenMembership( TokenHandle: ?HANDLE, SidToCheck: ?PSID, IsMember: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "KERNEL32" fn CheckTokenCapability( TokenHandle: ?HANDLE, CapabilitySidToCheck: ?PSID, HasCapability: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "KERNEL32" fn GetAppContainerAce( Acl: ?*ACL, StartingAceIndex: u32, AppContainerAce: ?*?*anyopaque, AppContainerAceIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "KERNEL32" fn CheckTokenMembershipEx( TokenHandle: ?HANDLE, SidToCheck: ?PSID, Flags: u32, IsMember: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ConvertToAutoInheritPrivateObjectSecurity( ParentDescriptor: ?*SECURITY_DESCRIPTOR, CurrentSecurityDescriptor: ?*SECURITY_DESCRIPTOR, NewSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, ObjectType: ?*Guid, IsDirectoryObject: BOOLEAN, GenericMapping: ?*GENERIC_MAPPING, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CopySid( nDestinationSidLength: u32, // TODO: what to do with BytesParamIndex 0? pDestinationSid: ?PSID, pSourceSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CreatePrivateObjectSecurity( ParentDescriptor: ?*SECURITY_DESCRIPTOR, CreatorDescriptor: ?*SECURITY_DESCRIPTOR, NewDescriptor: ?*?*SECURITY_DESCRIPTOR, IsDirectoryObject: BOOL, Token: ?HANDLE, GenericMapping: ?*GENERIC_MAPPING, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CreatePrivateObjectSecurityEx( ParentDescriptor: ?*SECURITY_DESCRIPTOR, CreatorDescriptor: ?*SECURITY_DESCRIPTOR, NewDescriptor: ?*?*SECURITY_DESCRIPTOR, ObjectType: ?*Guid, IsContainerObject: BOOL, AutoInheritFlags: SECURITY_AUTO_INHERIT_FLAGS, Token: ?HANDLE, GenericMapping: ?*GENERIC_MAPPING, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CreatePrivateObjectSecurityWithMultipleInheritance( ParentDescriptor: ?*SECURITY_DESCRIPTOR, CreatorDescriptor: ?*SECURITY_DESCRIPTOR, NewDescriptor: ?*?*SECURITY_DESCRIPTOR, ObjectTypes: ?[*]?*Guid, GuidCount: u32, IsContainerObject: BOOL, AutoInheritFlags: SECURITY_AUTO_INHERIT_FLAGS, Token: ?HANDLE, GenericMapping: ?*GENERIC_MAPPING, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CreateRestrictedToken( ExistingTokenHandle: ?HANDLE, Flags: CREATE_RESTRICTED_TOKEN_FLAGS, DisableSidCount: u32, SidsToDisable: ?[*]SID_AND_ATTRIBUTES, DeletePrivilegeCount: u32, PrivilegesToDelete: ?[*]LUID_AND_ATTRIBUTES, RestrictedSidCount: u32, SidsToRestrict: ?[*]SID_AND_ATTRIBUTES, NewTokenHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn CreateWellKnownSid( WellKnownSidType: WELL_KNOWN_SID_TYPE, DomainSid: ?PSID, // TODO: what to do with BytesParamIndex 3? pSid: ?PSID, cbSid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn EqualDomainSid( pSid1: ?PSID, pSid2: ?PSID, pfEqual: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn DeleteAce( pAcl: ?*ACL, dwAceIndex: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn DestroyPrivateObjectSecurity( ObjectDescriptor: ?*?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn DuplicateToken( ExistingTokenHandle: ?HANDLE, ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, DuplicateTokenHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn DuplicateTokenEx( hExistingToken: ?HANDLE, dwDesiredAccess: TOKEN_ACCESS_MASK, lpTokenAttributes: ?*SECURITY_ATTRIBUTES, ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, TokenType: TOKEN_TYPE, phNewToken: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn EqualPrefixSid( pSid1: ?PSID, pSid2: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn EqualSid( pSid1: ?PSID, pSid2: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn FindFirstFreeAce( pAcl: ?*ACL, pAce: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn FreeSid( pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetAce( pAcl: ?*ACL, dwAceIndex: u32, pAce: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetAclInformation( pAcl: ?*ACL, // TODO: what to do with BytesParamIndex 2? pAclInformation: ?*anyopaque, nAclInformationLength: u32, dwAclInformationClass: ACL_INFORMATION_CLASS, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn GetFileSecurityW( lpFileName: ?[*:0]const u16, RequestedInformation: u32, // TODO: what to do with BytesParamIndex 3? pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetKernelObjectSecurity( Handle: ?HANDLE, RequestedInformation: u32, // TODO: what to do with BytesParamIndex 3? pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetLengthSid( pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetPrivateObjectSecurity( ObjectDescriptor: ?*SECURITY_DESCRIPTOR, SecurityInformation: u32, // TODO: what to do with BytesParamIndex 3? ResultantDescriptor: ?*SECURITY_DESCRIPTOR, DescriptorLength: u32, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorControl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pControl: ?*u16, lpdwRevision: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorDacl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, lpbDaclPresent: ?*i32, pDacl: ?*?*ACL, lpbDaclDefaulted: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorGroup( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pGroup: ?*?PSID, lpbGroupDefaulted: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorLength( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorOwner( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pOwner: ?*?PSID, lpbOwnerDefaulted: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorRMControl( SecurityDescriptor: ?*SECURITY_DESCRIPTOR, RMControl: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSecurityDescriptorSacl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, lpbSaclPresent: ?*i32, pSacl: ?*?*ACL, lpbSaclDefaulted: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSidIdentifierAuthority( pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) ?*SID_IDENTIFIER_AUTHORITY; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSidLengthRequired( nSubAuthorityCount: u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSidSubAuthority( pSid: ?PSID, nSubAuthority: u32, ) callconv(@import("std").os.windows.WINAPI) ?*u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetSidSubAuthorityCount( pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) ?*u8; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetTokenInformation( TokenHandle: ?HANDLE, TokenInformationClass: TOKEN_INFORMATION_CLASS, // TODO: what to do with BytesParamIndex 3? TokenInformation: ?*anyopaque, TokenInformationLength: u32, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetWindowsAccountDomainSid( pSid: ?PSID, // TODO: what to do with BytesParamIndex 2? pDomainSid: ?PSID, cbDomainSid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ImpersonateAnonymousToken( ThreadHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ImpersonateLoggedOnUser( hToken: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ImpersonateSelf( ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn InitializeAcl( // TODO: what to do with BytesParamIndex 1? pAcl: ?*ACL, nAclLength: u32, dwAclRevision: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn InitializeSecurityDescriptor( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, dwRevision: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn InitializeSid( Sid: ?PSID, pIdentifierAuthority: ?*SID_IDENTIFIER_AUTHORITY, nSubAuthorityCount: u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn IsTokenRestricted( TokenHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn IsValidAcl( pAcl: ?*ACL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn IsValidSecurityDescriptor( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn IsValidSid( pSid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn IsWellKnownSid( pSid: ?PSID, WellKnownSidType: WELL_KNOWN_SID_TYPE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn MakeAbsoluteSD( pSelfRelativeSecurityDescriptor: ?*SECURITY_DESCRIPTOR, // TODO: what to do with BytesParamIndex 2? pAbsoluteSecurityDescriptor: ?*SECURITY_DESCRIPTOR, lpdwAbsoluteSecurityDescriptorSize: ?*u32, // TODO: what to do with BytesParamIndex 4? pDacl: ?*ACL, lpdwDaclSize: ?*u32, // TODO: what to do with BytesParamIndex 6? pSacl: ?*ACL, lpdwSaclSize: ?*u32, // TODO: what to do with BytesParamIndex 8? pOwner: ?PSID, lpdwOwnerSize: ?*u32, // TODO: what to do with BytesParamIndex 10? pPrimaryGroup: ?PSID, lpdwPrimaryGroupSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn MakeSelfRelativeSD( pAbsoluteSecurityDescriptor: ?*SECURITY_DESCRIPTOR, // TODO: what to do with BytesParamIndex 2? pSelfRelativeSecurityDescriptor: ?*SECURITY_DESCRIPTOR, lpdwBufferLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn MapGenericMask( AccessMask: ?*u32, GenericMapping: ?*GENERIC_MAPPING, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "ADVAPI32" fn ObjectCloseAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, GenerateOnClose: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn ObjectDeleteAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, GenerateOnClose: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn ObjectOpenAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ObjectTypeName: ?PWSTR, ObjectName: ?PWSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ClientToken: ?HANDLE, DesiredAccess: u32, GrantedAccess: u32, Privileges: ?*PRIVILEGE_SET, ObjectCreation: BOOL, AccessGranted: BOOL, GenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn ObjectPrivilegeAuditAlarmW( SubsystemName: ?[*:0]const u16, HandleId: ?*anyopaque, ClientToken: ?HANDLE, DesiredAccess: u32, Privileges: ?*PRIVILEGE_SET, AccessGranted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn PrivilegeCheck( ClientToken: ?HANDLE, RequiredPrivileges: ?*PRIVILEGE_SET, pfResult: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn PrivilegedServiceAuditAlarmW( SubsystemName: ?[*:0]const u16, ServiceName: ?[*:0]const u16, ClientToken: ?HANDLE, Privileges: ?*PRIVILEGE_SET, AccessGranted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn QuerySecurityAccessMask( SecurityInformation: u32, DesiredAccess: ?*u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn RevertToSelf( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetAclInformation( pAcl: ?*ACL, // TODO: what to do with BytesParamIndex 2? pAclInformation: ?*anyopaque, nAclInformationLength: u32, dwAclInformationClass: ACL_INFORMATION_CLASS, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ADVAPI32" fn SetFileSecurityW( lpFileName: ?[*:0]const u16, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetKernelObjectSecurity( Handle: ?HANDLE, SecurityInformation: u32, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetPrivateObjectSecurity( SecurityInformation: u32, ModificationDescriptor: ?*SECURITY_DESCRIPTOR, ObjectsSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, GenericMapping: ?*GENERIC_MAPPING, Token: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetPrivateObjectSecurityEx( SecurityInformation: u32, ModificationDescriptor: ?*SECURITY_DESCRIPTOR, ObjectsSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, AutoInheritFlags: SECURITY_AUTO_INHERIT_FLAGS, GenericMapping: ?*GENERIC_MAPPING, Token: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn SetSecurityAccessMask( SecurityInformation: u32, DesiredAccess: ?*u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorControl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ControlBitsOfInterest: u16, ControlBitsToSet: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorDacl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, bDaclPresent: BOOL, pDacl: ?*ACL, bDaclDefaulted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorGroup( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pGroup: ?PSID, bGroupDefaulted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorOwner( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pOwner: ?PSID, bOwnerDefaulted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorRMControl( SecurityDescriptor: ?*SECURITY_DESCRIPTOR, RMControl: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetSecurityDescriptorSacl( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, bSaclPresent: BOOL, pSacl: ?*ACL, bSaclDefaulted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetTokenInformation( TokenHandle: ?HANDLE, TokenInformationClass: TOKEN_INFORMATION_CLASS, // TODO: what to do with BytesParamIndex 3? TokenInformation: ?*anyopaque, TokenInformationLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "KERNEL32" fn SetCachedSigningLevel( SourceFiles: [*]?HANDLE, SourceFileCount: u32, Flags: u32, TargetFile: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "KERNEL32" fn GetCachedSigningLevel( File: ?HANDLE, Flags: ?*u32, SigningLevel: ?*u32, // TODO: what to do with BytesParamIndex 4? Thumbprint: ?*u8, ThumbprintSize: ?*u32, ThumbprintAlgorithm: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "api-ms-win-security-base-l1-2-2" fn DeriveCapabilitySidsFromName( CapName: ?[*:0]const u16, CapabilityGroupSids: ?*?*?PSID, CapabilityGroupSidCount: ?*u32, CapabilitySids: ?*?*?PSID, CapabilitySidCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ntdll" fn RtlNormalizeSecurityDescriptor( SecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, SecurityDescriptorLength: u32, NewSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, NewSecurityDescriptorLength: ?*u32, CheckOnly: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "USER32" fn SetUserObjectSecurity( hObj: ?HANDLE, pSIRequested: ?*OBJECT_SECURITY_INFORMATION, pSID: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "USER32" fn GetUserObjectSecurity( hObj: ?HANDLE, pSIRequested: ?*u32, // TODO: what to do with BytesParamIndex 3? pSID: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckAndAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ObjectTypeName: ?PSTR, ObjectName: ?PSTR, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, DesiredAccess: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: ?*u32, AccessStatus: ?*i32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckByTypeAndAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ObjectTypeName: ?[*:0]const u8, ObjectName: ?[*:0]const u8, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: ?*u32, AccessStatus: ?*i32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckByTypeResultListAndAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ObjectTypeName: ?[*:0]const u8, ObjectName: ?[*:0]const u8, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: [*]u32, AccessStatusList: [*]u32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn AccessCheckByTypeResultListAndAuditAlarmByHandleA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ClientToken: ?HANDLE, ObjectTypeName: ?[*:0]const u8, ObjectName: ?[*:0]const u8, SecurityDescriptor: ?*SECURITY_DESCRIPTOR, PrincipalSelfSid: ?PSID, DesiredAccess: u32, AuditType: AUDIT_EVENT_TYPE, Flags: u32, ObjectTypeList: ?[*]OBJECT_TYPE_LIST, ObjectTypeListLength: u32, GenericMapping: ?*GENERIC_MAPPING, ObjectCreation: BOOL, GrantedAccess: [*]u32, AccessStatusList: [*]u32, pfGenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ObjectOpenAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ObjectTypeName: ?PSTR, ObjectName: ?PSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ClientToken: ?HANDLE, DesiredAccess: u32, GrantedAccess: u32, Privileges: ?*PRIVILEGE_SET, ObjectCreation: BOOL, AccessGranted: BOOL, GenerateOnClose: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ObjectPrivilegeAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, ClientToken: ?HANDLE, DesiredAccess: u32, Privileges: ?*PRIVILEGE_SET, AccessGranted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ObjectCloseAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, GenerateOnClose: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn ObjectDeleteAuditAlarmA( SubsystemName: ?[*:0]const u8, HandleId: ?*anyopaque, GenerateOnClose: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn PrivilegedServiceAuditAlarmA( SubsystemName: ?[*:0]const u8, ServiceName: ?[*:0]const u8, ClientToken: ?HANDLE, Privileges: ?*PRIVILEGE_SET, AccessGranted: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "ADVAPI32" fn AddConditionalAce( pAcl: ?*ACL, dwAceRevision: u32, AceFlags: ACE_FLAGS, AceType: u8, AccessMask: u32, pSid: ?PSID, ConditionStr: ?[*]u16, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn SetFileSecurityA( lpFileName: ?[*:0]const u8, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn GetFileSecurityA( lpFileName: ?[*:0]const u8, RequestedInformation: u32, // TODO: what to do with BytesParamIndex 3? pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupAccountSidA( lpSystemName: ?[*:0]const u8, Sid: ?PSID, Name: ?[*:0]u8, cchName: ?*u32, ReferencedDomainName: ?[*:0]u8, cchReferencedDomainName: ?*u32, peUse: ?*SID_NAME_USE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupAccountSidW( lpSystemName: ?[*:0]const u16, Sid: ?PSID, Name: ?[*:0]u16, cchName: ?*u32, ReferencedDomainName: ?[*:0]u16, cchReferencedDomainName: ?*u32, peUse: ?*SID_NAME_USE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupAccountNameA( lpSystemName: ?[*:0]const u8, lpAccountName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 3? Sid: ?PSID, cbSid: ?*u32, ReferencedDomainName: ?[*:0]u8, cchReferencedDomainName: ?*u32, peUse: ?*SID_NAME_USE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupAccountNameW( lpSystemName: ?[*:0]const u16, lpAccountName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? Sid: ?PSID, cbSid: ?*u32, ReferencedDomainName: ?[*:0]u16, cchReferencedDomainName: ?*u32, peUse: ?*SID_NAME_USE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeValueA( lpSystemName: ?[*:0]const u8, lpName: ?[*:0]const u8, lpLuid: ?*LUID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeValueW( lpSystemName: ?[*:0]const u16, lpName: ?[*:0]const u16, lpLuid: ?*LUID, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeNameA( lpSystemName: ?[*:0]const u8, lpLuid: ?*LUID, lpName: ?[*:0]u8, cchName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeNameW( lpSystemName: ?[*:0]const u16, lpLuid: ?*LUID, lpName: ?[*:0]u16, cchName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeDisplayNameA( lpSystemName: ?[*:0]const u8, lpName: ?[*:0]const u8, lpDisplayName: ?[*:0]u8, cchDisplayName: ?*u32, lpLanguageId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LookupPrivilegeDisplayNameW( lpSystemName: ?[*:0]const u16, lpName: ?[*:0]const u16, lpDisplayName: ?[*:0]u16, cchDisplayName: ?*u32, lpLanguageId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LogonUserA( lpszUsername: ?[*:0]const u8, lpszDomain: ?[*:0]const u8, lpszPassword: ?[*:0]const u8, dwLogonType: LOGON32_LOGON, dwLogonProvider: LOGON32_PROVIDER, phToken: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LogonUserW( lpszUsername: ?[*:0]const u16, lpszDomain: ?[*:0]const u16, lpszPassword: ?[*:0]const u16, dwLogonType: LOGON32_LOGON, dwLogonProvider: LOGON32_PROVIDER, phToken: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LogonUserExA( lpszUsername: ?[*:0]const u8, lpszDomain: ?[*:0]const u8, lpszPassword: ?[*:0]const u8, dwLogonType: LOGON32_LOGON, dwLogonProvider: LOGON32_PROVIDER, phToken: ?*?HANDLE, ppLogonSid: ?*?PSID, // TODO: what to do with BytesParamIndex 8? ppProfileBuffer: ?*?*anyopaque, pdwProfileLength: ?*u32, pQuotaLimits: ?*QUOTA_LIMITS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn LogonUserExW( lpszUsername: ?[*:0]const u16, lpszDomain: ?[*:0]const u16, lpszPassword: ?[*:0]const u16, dwLogonType: LOGON32_LOGON, dwLogonProvider: LOGON32_PROVIDER, phToken: ?*?HANDLE, ppLogonSid: ?*?PSID, // TODO: what to do with BytesParamIndex 8? ppProfileBuffer: ?*?*anyopaque, pdwProfileLength: ?*u32, pQuotaLimits: ?*QUOTA_LIMITS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ntdll" fn RtlConvertSidToUnicodeString( UnicodeString: ?*UNICODE_STRING, Sid: ?PSID, AllocateDestinationString: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (18) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("zig.zig").unicode_mode) { .ansi => struct { pub const AccessCheckAndAuditAlarm = thismodule.AccessCheckAndAuditAlarmA; pub const AccessCheckByTypeAndAuditAlarm = thismodule.AccessCheckByTypeAndAuditAlarmA; pub const AccessCheckByTypeResultListAndAuditAlarm = thismodule.AccessCheckByTypeResultListAndAuditAlarmA; pub const AccessCheckByTypeResultListAndAuditAlarmByHandle = thismodule.AccessCheckByTypeResultListAndAuditAlarmByHandleA; pub const GetFileSecurity = thismodule.GetFileSecurityA; pub const ObjectCloseAuditAlarm = thismodule.ObjectCloseAuditAlarmA; pub const ObjectDeleteAuditAlarm = thismodule.ObjectDeleteAuditAlarmA; pub const ObjectOpenAuditAlarm = thismodule.ObjectOpenAuditAlarmA; pub const ObjectPrivilegeAuditAlarm = thismodule.ObjectPrivilegeAuditAlarmA; pub const PrivilegedServiceAuditAlarm = thismodule.PrivilegedServiceAuditAlarmA; pub const SetFileSecurity = thismodule.SetFileSecurityA; pub const LookupAccountSid = thismodule.LookupAccountSidA; pub const LookupAccountName = thismodule.LookupAccountNameA; pub const LookupPrivilegeValue = thismodule.LookupPrivilegeValueA; pub const LookupPrivilegeName = thismodule.LookupPrivilegeNameA; pub const LookupPrivilegeDisplayName = thismodule.LookupPrivilegeDisplayNameA; pub const LogonUser = thismodule.LogonUserA; pub const LogonUserEx = thismodule.LogonUserExA; }, .wide => struct { pub const AccessCheckAndAuditAlarm = thismodule.AccessCheckAndAuditAlarmW; pub const AccessCheckByTypeAndAuditAlarm = thismodule.AccessCheckByTypeAndAuditAlarmW; pub const AccessCheckByTypeResultListAndAuditAlarm = thismodule.AccessCheckByTypeResultListAndAuditAlarmW; pub const AccessCheckByTypeResultListAndAuditAlarmByHandle = thismodule.AccessCheckByTypeResultListAndAuditAlarmByHandleW; pub const GetFileSecurity = thismodule.GetFileSecurityW; pub const ObjectCloseAuditAlarm = thismodule.ObjectCloseAuditAlarmW; pub const ObjectDeleteAuditAlarm = thismodule.ObjectDeleteAuditAlarmW; pub const ObjectOpenAuditAlarm = thismodule.ObjectOpenAuditAlarmW; pub const ObjectPrivilegeAuditAlarm = thismodule.ObjectPrivilegeAuditAlarmW; pub const PrivilegedServiceAuditAlarm = thismodule.PrivilegedServiceAuditAlarmW; pub const SetFileSecurity = thismodule.SetFileSecurityW; pub const LookupAccountSid = thismodule.LookupAccountSidW; pub const LookupAccountName = thismodule.LookupAccountNameW; pub const LookupPrivilegeValue = thismodule.LookupPrivilegeValueW; pub const LookupPrivilegeName = thismodule.LookupPrivilegeNameW; pub const LookupPrivilegeDisplayName = thismodule.LookupPrivilegeDisplayNameW; pub const LogonUser = thismodule.LogonUserW; pub const LogonUserEx = thismodule.LogonUserExW; }, .unspecified => if (@import("builtin").is_test) struct { pub const AccessCheckAndAuditAlarm = *opaque{}; pub const AccessCheckByTypeAndAuditAlarm = *opaque{}; pub const AccessCheckByTypeResultListAndAuditAlarm = *opaque{}; pub const AccessCheckByTypeResultListAndAuditAlarmByHandle = *opaque{}; pub const GetFileSecurity = *opaque{}; pub const ObjectCloseAuditAlarm = *opaque{}; pub const ObjectDeleteAuditAlarm = *opaque{}; pub const ObjectOpenAuditAlarm = *opaque{}; pub const ObjectPrivilegeAuditAlarm = *opaque{}; pub const PrivilegedServiceAuditAlarm = *opaque{}; pub const SetFileSecurity = *opaque{}; pub const LookupAccountSid = *opaque{}; pub const LookupAccountName = *opaque{}; pub const LookupPrivilegeValue = *opaque{}; pub const LookupPrivilegeName = *opaque{}; pub const LookupPrivilegeDisplayName = *opaque{}; pub const LogonUser = *opaque{}; pub const LogonUserEx = *opaque{}; } else struct { pub const AccessCheckAndAuditAlarm = @compileError("'AccessCheckAndAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const AccessCheckByTypeAndAuditAlarm = @compileError("'AccessCheckByTypeAndAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const AccessCheckByTypeResultListAndAuditAlarm = @compileError("'AccessCheckByTypeResultListAndAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const AccessCheckByTypeResultListAndAuditAlarmByHandle = @compileError("'AccessCheckByTypeResultListAndAuditAlarmByHandle' requires that UNICODE be set to true or false in the root module"); pub const GetFileSecurity = @compileError("'GetFileSecurity' requires that UNICODE be set to true or false in the root module"); pub const ObjectCloseAuditAlarm = @compileError("'ObjectCloseAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const ObjectDeleteAuditAlarm = @compileError("'ObjectDeleteAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const ObjectOpenAuditAlarm = @compileError("'ObjectOpenAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const ObjectPrivilegeAuditAlarm = @compileError("'ObjectPrivilegeAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const PrivilegedServiceAuditAlarm = @compileError("'PrivilegedServiceAuditAlarm' requires that UNICODE be set to true or false in the root module"); pub const SetFileSecurity = @compileError("'SetFileSecurity' requires that UNICODE be set to true or false in the root module"); pub const LookupAccountSid = @compileError("'LookupAccountSid' requires that UNICODE be set to true or false in the root module"); pub const LookupAccountName = @compileError("'LookupAccountName' requires that UNICODE be set to true or false in the root module"); pub const LookupPrivilegeValue = @compileError("'LookupPrivilegeValue' requires that UNICODE be set to true or false in the root module"); pub const LookupPrivilegeName = @compileError("'LookupPrivilegeName' requires that UNICODE be set to true or false in the root module"); pub const LookupPrivilegeDisplayName = @compileError("'LookupPrivilegeDisplayName' requires that UNICODE be set to true or false in the root module"); pub const LogonUser = @compileError("'LogonUser' requires that UNICODE be set to true or false in the root module"); pub const LogonUserEx = @compileError("'LogonUserEx' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (13) //-------------------------------------------------------------------------------- const Guid = @import("zig.zig").Guid; const BOOL = @import("foundation.zig").BOOL; const BOOLEAN = @import("foundation.zig").BOOLEAN; const CHAR = @import("foundation.zig").CHAR; const FILETIME = @import("foundation.zig").FILETIME; const HANDLE = @import("foundation.zig").HANDLE; const LARGE_INTEGER = @import("foundation.zig").LARGE_INTEGER; const LUID = @import("foundation.zig").LUID; const NTSTATUS = @import("foundation.zig").NTSTATUS; const PSID = @import("foundation.zig").PSID; const PSTR = @import("foundation.zig").PSTR; const PWSTR = @import("foundation.zig").PWSTR; const UNICODE_STRING = @import("foundation.zig").UNICODE_STRING; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PLSA_AP_CALL_PACKAGE_UNTRUSTED")) { _ = PLSA_AP_CALL_PACKAGE_UNTRUSTED; } if (@hasDecl(@This(), "SEC_THREAD_START")) { _ = SEC_THREAD_START; } @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; } } } //-------------------------------------------------------------------------------- // Section: SubModules (16) //-------------------------------------------------------------------------------- pub const app_locker = @import("security/app_locker.zig"); pub const authentication = @import("security/authentication.zig"); pub const authorization = @import("security/authorization.zig"); pub const configuration_snapin = @import("security/configuration_snapin.zig"); pub const credentials = @import("security/credentials.zig"); pub const cryptography = @import("security/cryptography.zig"); pub const diagnostic_data_query = @import("security/diagnostic_data_query.zig"); pub const directory_services = @import("security/directory_services.zig"); pub const enterprise_data = @import("security/enterprise_data.zig"); pub const extensible_authentication_protocol = @import("security/extensible_authentication_protocol.zig"); pub const isolation = @import("security/isolation.zig"); pub const license_protection = @import("security/license_protection.zig"); pub const network_access_protection = @import("security/network_access_protection.zig"); pub const tpm = @import("security/tpm.zig"); pub const win_trust = @import("security/win_trust.zig"); pub const win_wlx = @import("security/win_wlx.zig");
win32/security.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Bus = @import("../bus.zig").Bus; const Cart = @import("../cart.zig").Cart; const DEBUG_INST_TABLE = @import("ops.zig").DEBUG_INST_TABLE; const INST_TABLE = @import("ops.zig").INST_TABLE; const Reg = @import("regs.zig").Reg; const Vip = @import("../hw/vip.zig").Vip; const Vsu = @import("../hw/vsu.zig").Vsu; pub const Cpu = struct { bus: Bus, regs: [32]Reg, pc: Reg, psw: Reg, // program status word eipc: Reg, // exception/interrupt pc eipsw: Reg, // exception/interrup psw fepc: Reg, // fatal duplexed exception pc fepsw: Reg, // duplexed exception psw ecr: Reg, // exception cause register adtre: Reg, // address trap register for execution chcw: Reg, // cache control word tkcw: Reg, // task control word pir: Reg, // Processor ID Register debug_mode: bool, pub fn new(allocator: *Allocator, cart: *Cart, debug_mode: bool) Cpu { var bus = Bus.new(allocator); return Cpu{ .bus = bus, .regs = [32]Reg{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }, .pc = 0xfffffff0, .psw = 0x00008000, .eipc = 0, .eipsw = 0, .fepc = 0, .fepsw = 0, .ecr = 0x0000fff0, .adtre = 0, .chcw = 0, .tkcw = 0, .pir = 0, .debug_mode = debug_mode, }; } pub fn boot(self: *Cpu, wram: []u8, cart: *Cart, vip: *Vip, vsu: *Vsu) void { self.bus.init(wram, cart, vip, vsu); } pub fn cycle(self: *Cpu) void { const halfword = self.bus.read_halfword(self.pc) catch unreachable; const opcode = (halfword & 0xfc00) >> 10; if (self.debug_mode) { std.debug.warn("0x{x:08}\t{x:04}\t", .{ self.pc, halfword }); DEBUG_INST_TABLE[opcode](self, halfword); } // call function from function pointer table INST_TABLE[opcode](self, halfword); } fn get_sysreg_ptr(self: *Cpu, imm: u5) *Reg { const reg_ptr = switch (imm) { 0 => &self.eipc, 1 => &self.eipsw, 2 => &self.fepc, 3 => &self.fepsw, 4 => &self.ecr, 5 => &self.eipc, 6 => &self.pir, 7 => &self.tkcw, 24 => &self.chcw, 25 => &self.adtre, else => unreachable, }; return reg_ptr; } fn set_interrupt_disable(self: *Cpu) void { self.psw |= 0x00001000; } fn clear_interrupt_disable(self: *Cpu) void { self.psw |= 0xffffefff; } fn cy(self: *Cpu) u1 { return @intCast(u1, ((self.psw & 0x00000008) >> 3)); } fn ov(self: *Cpu) u1 { return @intCast(u1, ((self.psw & 0x00000004) >> 2)); } fn s(self: *Cpu) u1 { return @intCast(u1, ((self.psw & 0x00000002) >> 1)); } fn z(self: *Cpu) u1 { return @intCast(u1, (self.psw & 0x00000001)); } fn set_cy(self: *Cpu) void { self.psw |= 0x00000008; } fn set_ov(self: *Cpu) void { self.psw |= 0x00000004; } fn set_s(self: *Cpu) void { self.psw |= 0x00000002; } fn set_z(self: *Cpu) void { self.psw |= 0x00000001; } fn clear_cy(self: *Cpu) void { self.psw &= 0xfffffff7; } fn clear_ov(self: *Cpu) void { self.psw &= 0xfffffffb; } fn clear_s(self: *Cpu) void { self.psw &= 0xfffffffd; } fn clear_z(self: *Cpu) void { self.psw &= 0xfffffffe; } fn set_flags(self: *Cpu, res: u32, old: u32) void { if (res < old) { self.set_cy(); } else { self.clear_cy(); } if ((res & 0x10000000) != (old & 0x10000000)) { self.set_ov(); } else { self.clear_ov(); } if (@bitCast(i32, res) < 0) { self.set_s(); } else { self.clear_s(); } if (res == 0) { self.set_z(); } else { self.clear_z(); } } fn show_reg(self: Cpu, reg: usize) void { std.debug.warn("r{}: {x:08}\n", reg, self.regs[reg]); } fn show_regs(self: Cpu) void { std.debug.warn("pc:\t{x:08}\n", self.pc); std.debug.warn("psw:\t{x:08}\n", self.psw); std.debug.warn("eipc:\t{x:08}\n", self.eipc); std.debug.warn("eipsw:\t{x:08}\n", self.eipsw); std.debug.warn("fepc:\t{x:08}\n", self.fepc); std.debug.warn("fepsw:\t{x:08}\n", self.fepsw); std.debug.warn("ecr:\t{x:08}\n", self.ecr); std.debug.warn("adtre:\t{x:08}\n", self.adtre); std.debug.warn("chcw:\t{x:08}\n", self.chcw); std.debug.warn("tkcw:\t{x:08}\n", self.tkcw); std.debug.warn("pir:\t{x:08}\n", self.pir); var reg: usize = 0; while (reg < 32) { std.debug.warn("r{}:\t{x:08}\n", reg, self.regs[reg]); reg += 1; } } fn show_flags(self: *Cpu) void { std.debug.warn("cy: {}\n", self.cy()); std.debug.warn("ov: {}\n", self.ov()); std.debug.warn("s: {}\n", self.s()); std.debug.warn("z: {}\n", self.z()); } }; pub fn sign_extend(val: u16) u32 { if (@bitCast(i16, val) < 0) { return @intCast(u32, val) | 0xffff0000; } else { return @intCast(u32, val); } } pub fn sign_extend5(val: u5) u32 { if (@bitCast(i5, val) < 0) { return @intCast(u32, val) | 0xffffffe0; } else { return @intCast(u32, val); } } pub fn sign_extend8(val: u8) u32 { if (@bitCast(i8, val) < 0) { return @intCast(u32, val) | 0xffffff00; } else { return @intCast(u32, val); } } pub fn sign_extend26(val: u26) u32 { if (@bitCast(i26, val) < 0) { return @intCast(u32, val) | 0xfc000000; } else { return @intCast(u32, val); } } pub fn illegal(cpu: *Cpu, halfword: u16) void { std.process.exit(1); } // move register pub fn mov(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); cpu.regs[r2] = cpu.regs[r1]; cpu.pc += 2; } // add register pub fn add(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const res = cpu.regs[r2] +% cpu.regs[r1]; cpu.set_flags(res, cpu.regs[r2]); cpu.regs[r2] = res; cpu.pc += 2; } // TODO // subtract pub fn sub(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn cmp(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const res = cpu.regs[r2] -% cpu.regs[r1]; cpu.set_flags(res, cpu.regs[r2]); cpu.pc += 2; } // TODO pub fn shl(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn shr(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn jmp(cpu: *Cpu, halfword: u16) void { const r1 = @intCast(usize, halfword & 0x001f); cpu.pc = cpu.regs[r1] & 0xfffffffe; } // TODO pub fn sar(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn mul(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn div(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn mulu(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn divu(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn orop(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn andop(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); cpu.regs[r2] = cpu.regs[r2] & cpu.regs[r1]; cpu.clear_ov(); cpu.pc += 2; } // TODO pub fn xor(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn not(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn mov2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u5, halfword & 0x001f); cpu.regs[r2] = sign_extend5(imm); cpu.pc += 2; } pub fn add2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @bitCast(i5, @intCast(u5, halfword & 0x001f)); const old = cpu.regs[r2]; if (imm < 0) { cpu.regs[r2] = cpu.regs[r2] -% @intCast(u32, imm * -1); } else { cpu.regs[r2] = cpu.regs[r2] +% @intCast(u32, imm); } cpu.set_flags(cpu.regs[r2], old); cpu.pc += 2; } pub fn cmp2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u32, halfword & 0x001f); const res = cpu.regs[r2] -% imm; cpu.set_flags(res, imm); cpu.pc += 2; } pub fn shl2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u5, halfword & 0x001f); const old = cpu.regs[r2]; cpu.regs[r2] = cpu.regs[r2] << imm; if ((old >> imm - 1) & 0x1 == 0x1) { cpu.set_cy(); } else { cpu.clear_cy(); } cpu.clear_ov(); if (@bitCast(i32, cpu.regs[r2]) < 0) { cpu.set_s(); } else { cpu.clear_s(); } if (cpu.regs[r2] == 0) { cpu.set_z(); } else { cpu.clear_z(); } cpu.pc += 2; } pub fn shr2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u5, halfword & 0x001f); const old = cpu.regs[r2]; cpu.regs[r2] = cpu.regs[r2] >> imm; if ((old >> imm - 1) & 0x1 == 0x1) { cpu.set_cy(); } else { cpu.clear_cy(); } cpu.clear_ov(); if (@bitCast(i32, cpu.regs[r2]) < 0) { cpu.set_s(); } else { cpu.clear_s(); } if (cpu.regs[r2] == 0) { cpu.set_z(); } else { cpu.clear_z(); } cpu.pc += 2; } // Nintendo-specific pub fn cli(cpu: *Cpu, halfword: u16) void { cpu.clear_interrupt_disable(); cpu.pc += 2; } pub fn sar2(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u5, halfword & 0x001f); const old = cpu.regs[r2]; const res = @intCast(i32, cpu.regs[r2]) >> imm; cpu.regs[r2] = @intCast(u32, res); if ((old >> imm - 1) & 0x1 == 0x1) { cpu.set_cy(); } else { cpu.clear_cy(); } cpu.clear_ov(); if (@bitCast(i32, cpu.regs[r2]) < 0) { cpu.set_s(); } else { cpu.clear_s(); } if (cpu.regs[r2] == 0) { cpu.set_z(); } else { cpu.clear_z(); } cpu.pc += 2; } // TODO pub fn setf(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn trap(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn reti(cpu: *Cpu, halfword: u16) void { cpu.pc = cpu.regs[31]; } // TODO pub fn halt(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn ldsr(cpu: *Cpu, halfword: u16) void { const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const imm = @intCast(u5, halfword & 0x001f); const reg = cpu.get_sysreg_ptr(imm); //if (imm == 5) { // cpu.regs[r2] = cpu.psw; //} reg.* = cpu.regs[r2]; cpu.pc += 2; } // TODO pub fn stsr(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // Nintendo-specific pub fn sei(cpu: *Cpu, halfword: u16) void { cpu.set_interrupt_disable(); cpu.pc += 2; } // TODO pub fn bit_string(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn bcond(cpu: *Cpu, halfword: u16) void { const cond = @intCast(u4, (halfword & 0x1e00) >> 9); const disp = halfword & 0x01ff; var cond_true = false; switch (cond) { 0x0 => { if (cpu.ov() == 1) { cond_true = true; } }, 0x1 => { if (cpu.cy() == 1) { cond_true = true; } }, 0x2 => { if (cpu.z() == 1) { cond_true = true; } }, 0x3 => { if (cpu.cy() | cpu.z() == 1) { cond_true = true; } }, 0x4 => { if (cpu.s() == 1) { cond_true = true; } }, 0x5 => { cond_true = true; }, 0x6 => { if (cpu.s() ^ cpu.ov() == 1) { cond_true = true; } }, 0x7 => { if ((cpu.s() ^ cpu.ov()) | cpu.z() == 1) { cond_true = true; } }, 0x8 => { if (cpu.ov() == 0) { cond_true = true; } }, 0x9 => { if (cpu.cy() == 0) { cond_true = true; } }, 0xa => { if (cpu.z() == 0) { cond_true = true; } }, 0xb => { if (cpu.cy() | cpu.z() == 0) { cond_true = true; } }, 0xc => { if (cpu.s() == 0) { cond_true = true; } }, 0xd => { cpu.pc += 2; return; }, 0xe => { if (cpu.s() ^ cpu.ov() == 0) { cond_true = true; } }, 0xf => { if ((cpu.s() ^ cpu.ov()) | cpu.z() == 0) { cond_true = true; } }, } if (cond_true) { if (@bitCast(i9, @intCast(u9, disp & 0x01ff)) < 0) { const offset = (@intCast(u32, disp) | 0xfffffe00) & 0xfffffffe; cpu.pc = cpu.pc +% @intCast(u32, offset); } else { const offset = @intCast(u32, disp) & 0xfffffffe; cpu.pc = cpu.pc +% @intCast(u32, offset); } } else { cpu.pc += 2; } } pub fn movea(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const imm = cpu.bus.read_halfword(cpu.pc) catch unreachable; const val = sign_extend(imm); cpu.regs[r2] = cpu.regs[r1] +% val; cpu.pc += 2; } pub fn addi(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const imm = cpu.bus.read_halfword(cpu.pc) catch unreachable; const old = cpu.regs[r2]; cpu.regs[r2] = cpu.regs[r1] +% sign_extend(imm); cpu.set_flags(cpu.regs[r2], old); cpu.pc += 2; } pub fn jr(cpu: *Cpu, halfword: u16) void { const upper = @intCast(u32, halfword & 0x03ff) << 16; const lower = @intCast(u32, cpu.bus.read_halfword(cpu.pc + 2) catch unreachable); const disp = sign_extend26(@intCast(u26, (upper | lower))); cpu.pc = cpu.pc +% disp & 0xfffffffe; } pub fn jal(cpu: *Cpu, halfword: u16) void { const upper = @intCast(u32, halfword & 0x03ff) << 16; const lower = @intCast(u32, cpu.bus.read_halfword(cpu.pc + 2) catch unreachable); const disp = sign_extend26(@intCast(u26, (upper | lower))); cpu.regs[31] = cpu.pc + 4; cpu.pc = cpu.pc +% disp & 0xfffffffe; } pub fn ori(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const imm = cpu.bus.read_halfword(cpu.pc) catch unreachable; cpu.regs[r2] = cpu.regs[r1] | @intCast(u32, imm); cpu.clear_ov(); if (@bitCast(i32, cpu.regs[r2]) < 0) { cpu.set_s(); } else { cpu.clear_s(); } if (cpu.regs[r2] == 0) { cpu.set_z(); } else { cpu.clear_z(); } cpu.pc += 2; } pub fn andi(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const imm = cpu.bus.read_halfword(cpu.pc) catch unreachable; const res = cpu.regs[r1] & @intCast(u32, imm); cpu.regs[r2] = res; cpu.clear_ov(); cpu.clear_s(); if (cpu.regs[r2] == 0) { cpu.set_z(); } else { cpu.clear_z(); } cpu.pc += 2; } // TODO pub fn xori(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn movhi(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const imm = cpu.bus.read_halfword(cpu.pc) catch unreachable; cpu.regs[r2] = cpu.regs[r1] +% (@intCast(u32, imm) << 16); cpu.pc += 2; } pub fn ldb(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; cpu.regs[r2] = sign_extend8(cpu.bus.read_byte(addr) catch unreachable); cpu.pc += 2; } pub fn ldh(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; cpu.regs[r2] = sign_extend(cpu.bus.read_halfword(addr) catch unreachable); cpu.pc += 2; } pub fn ldw(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; cpu.regs[r2] = cpu.bus.read_word(addr) catch unreachable; cpu.pc += 2; } pub fn stb(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; const byte = @intCast(u8, cpu.regs[r2] & 0x000000ff); cpu.bus.write_byte(addr, byte) catch unreachable; cpu.pc += 2; } pub fn sth(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; const whalfword = @intCast(u16, cpu.regs[r2] & 0x0000ffff); cpu.bus.write_halfword(addr, whalfword) catch unreachable; cpu.pc += 2; } pub fn stw(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; const r2 = @intCast(usize, (halfword & 0x03e0) >> 5); const r1 = @intCast(usize, halfword & 0x001f); const disp = cpu.bus.read_halfword(cpu.pc) catch unreachable; const addr = (cpu.regs[r1] +% sign_extend(disp)) & 0xfffffffe; cpu.bus.write_word(addr, cpu.regs[r2]) catch unreachable; cpu.pc += 2; } // TODO pub fn inb(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn inh(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn caxi(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } // TODO pub fn inw(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn outb(cpu: *Cpu, halfword: u16) void { stb(cpu, halfword); } pub fn outh(cpu: *Cpu, halfword: u16) void { sth(cpu, halfword); } // TODO pub fn float(cpu: *Cpu, halfword: u16) void { cpu.pc += 2; } pub fn outw(cpu: *Cpu, halfword: u16) void { stw(cpu, halfword); }
src/cpu/cpu.zig
const std = @import("std"); const testing = std.testing; const c = @import("c.zig").c; const Error = @import("errors.zig").Error; const getError = @import("errors.zig").getError; const Image = @import("Image.zig"); const Cursor = @This(); ptr: *c.GLFWcursor, // Standard system cursor shapes. const Shape = enum(isize) { /// The regular arrow cursor shape. arrow = c.GLFW_ARROW_CURSOR, /// The text input I-beam cursor shape. ibeam = c.GLFW_IBEAM_CURSOR, /// The crosshair shape. crosshair = c.GLFW_CROSSHAIR_CURSOR, /// The hand shape. hand = c.GLFW_HAND_CURSOR, /// The horizontal resize arrow shape. hresize = c.GLFW_HRESIZE_CURSOR, /// The vertical resize arrow shape. vresize = c.GLFW_VRESIZE_CURSOR, }; /// Creates a custom cursor. /// /// Creates a new custom cursor image that can be set for a window with glfw.Cursor.set. The cursor /// can be destroyed with glfwCursor.destroy. Any remaining cursors are destroyed by glfw.terminate. /// /// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with /// the red channel first. They are arranged canonically as packed sequential rows, starting from /// the top-left corner. /// /// The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor /// image. Like all other coordinate systems in GLFW, the X-axis points to the right and the Y-axis /// points down. /// /// @param[in] image The desired cursor image. /// @param[in] xhot The desired x-coordinate, in pixels, of the cursor hotspot. /// @param[in] yhot The desired y-coordinate, in pixels, of the cursor hotspot. /// @return The handle of the created cursor. /// /// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError. /// /// @pointer_lifetime The specified image data is copied before this function returns. /// /// @thread_safety This function must only be called from the main thread. /// /// see also: cursor_object, glfw.Cursor.destroy, glfw.Cursor.createStandard pub inline fn create(image: Image, xhot: isize, yhot: isize) Error!Cursor { const img = image.toC(); const cursor = c.glfwCreateCursor(&img, @intCast(c_int, xhot), @intCast(c_int, yhot)); try getError(); return Cursor{ .ptr = cursor.? }; } /// Creates a cursor with a standard shape. /// /// Returns a cursor with a standard shape (see shapes), that can be set for a window with glfw.Window.setCursor. /// /// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError. /// /// @thread_safety This function must only be called from the main thread. /// /// see also: cursor_object, glfwCreateCursor pub inline fn createStandard(shape: Shape) Error!Cursor { const cursor = c.glfwCreateStandardCursor(@intCast(c_int, @enumToInt(shape))); try getError(); return Cursor{ .ptr = cursor.? }; } /// Destroys a cursor. /// /// This function destroys a cursor previously created with glfw.Cursor.create. Any remaining /// cursors will be destroyed by glfw.terminate. /// /// If the specified cursor is current for any window, that window will be reverted to the default /// cursor. This does not affect the cursor mode. /// /// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError. /// /// @reentrancy This function must not be called from a callback. /// /// @thread_safety This function must only be called from the main thread. /// /// see also: cursor_object, glfw.createCursor pub inline fn destroy(self: Cursor) void { c.glfwDestroyCursor(self.ptr); getError() catch {}; // what would anyone do with it anyway? } test "create" { const allocator = testing.allocator; const glfw = @import("main.zig"); try glfw.init(); defer glfw.terminate(); const image = try Image.init(allocator, 32, 32, 32 * 32 * 4); defer image.deinit(allocator); const cursor = glfw.Cursor.create(image, 0, 0) catch |err| { std.debug.print("failed to create cursor, custom cursors not supported? error={}\n", .{err}); return; }; cursor.destroy(); } test "createStandard" { const glfw = @import("main.zig"); try glfw.init(); defer glfw.terminate(); const cursor = glfw.Cursor.createStandard(.ibeam) catch |err| { std.debug.print("failed to create cursor, custom cursors not supported? error={}\n", .{err}); return; }; cursor.destroy(); }
mach-glfw/src/Cursor.zig
const std = @import("std"); const io = @import("io.zig"); const fprint = @import("fprint.zig"); pub const Log = struct { const Self = @This(); const tab = " "; const marker = " - "; file: ?*io.File, indent: usize = 0, parent: ?*const Self = null, enabled: bool = true, pub fn child(self: *const Self) Self { return Self{.indent = self.indent + 1, .file = self.file, .parent = self}; } fn is_enabled(self: *const Self) bool { var logger: ?*const Self = self; while (logger) |l| { if (!l.enabled) { return false; } logger = l.parent; } return true; } fn print_indent(file: *io.File, indent: usize) void { var i: usize = 0; while (i < indent) { _ = fprint.string(file, tab) catch {}; i += 1; } _ = fprint.string(file, marker) catch {}; } pub fn log(self: *const Self, comptime fmtstr: []const u8, args: anytype) void { if (self.file) |file| { if (self.is_enabled()) { print_indent(file, self.indent); _ = fprint.format(file, fmtstr ++ "\n", args) catch {}; } } } }; test "Log" { var buffer: [1024]u8 = undefined; var buffer_file = io.BufferFile{}; buffer_file.init(buffer[0..]); const file = &buffer_file.file; { buffer_file.reset(); var log = Log{.file = file}; log.log("{}, World!", .{"Hello"}); try buffer_file.expect(" - Hello, World!\n"); } { buffer_file.reset(); var log1 = Log{.file = file}; log1.log("1", .{}); log1.enabled = false; log1.log("SHOULD NOT BE LOGGED", .{}); log1.enabled = true; log1.log("2", .{}); { var log2 = log1.child(); log2.log("3", .{}); { var log3 = log2.child(); log3.log("4", .{}); log1.enabled = false; log3.log("SHOULD NOT BE LOGGED", .{}); log1.enabled = true; log3.log("5", .{}); } log2.log("6", .{}); log2.log("7", .{}); } log1.log("8", .{}); try buffer_file.expect( \\ - 1 \\ - 2 \\ - 3 \\ - 4 \\ - 5 \\ - 6 \\ - 7 \\ - 8 \\ ); } }
kernel/log.zig
const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; const Tag = std.meta.Tag; test "enum value allocation" { const LargeEnum = enum(u32) { A0 = 0x80000000, A1, A2, }; try expect(@enumToInt(LargeEnum.A0) == 0x80000000); try expect(@enumToInt(LargeEnum.A1) == 0x80000001); try expect(@enumToInt(LargeEnum.A2) == 0x80000002); } test "enum literal casting to tagged union" { const Arch = union(enum) { x86_64, arm: Arm32, const Arm32 = enum { v8_5a, v8_4a, }; }; var t = true; var x: Arch = .x86_64; var y = if (t) x else .x86_64; switch (y) { .x86_64 => {}, else => @panic("fail"), } } const Bar = enum { A, B, C, D }; test "enum literal casting to error union with payload enum" { var bar: error{B}!Bar = undefined; bar = .B; // should never cast to the error set try expect((try bar) == Bar.B); } test "exporting enum type and value" { const S = struct { const E = enum(c_int) { one, two }; comptime { @export(E, .{ .name = "E" }); } const e: E = .two; comptime { @export(e, .{ .name = "e" }); } }; try expect(S.e == .two); } test "constant enum initialization with differing sizes" { try test3_1(test3_foo); try test3_2(test3_bar); } const Test3Foo = union(enum) { One: void, Two: f32, Three: Test3Point, }; const Test3Point = struct { x: i32, y: i32, }; const test3_foo = Test3Foo{ .Three = Test3Point{ .x = 3, .y = 4, }, }; const test3_bar = Test3Foo{ .Two = 13 }; fn test3_1(f: Test3Foo) !void { switch (f) { Test3Foo.Three => |pt| { try expect(pt.x == 3); try expect(pt.y == 4); }, else => unreachable, } } fn test3_2(f: Test3Foo) !void { switch (f) { Test3Foo.Two => |x| { try expect(x == 13); }, else => unreachable, } }
test/behavior/enum_stage1.zig
const std = @import("std"); const net = std.net; const os = std.os; const io = std.io; const Allocator = std.mem.Allocator; const resolv = @import("resolvconf.zig"); const main = @import("main.zig"); const dns = @import("dns"); const rdata = dns.rdata; const DNSPacket = dns.Packet; const DNSPacketRCode = dns.DNSPacketRCode; const DNSHeader = dns.Header; /// Returns the socket file descriptor for an UDP socket. pub fn openDNSSocket() !i32 { var flags: u32 = os.SOCK_DGRAM; if (std.event.Loop.instance) |_| { flags |= os.SOCK_NONBLOCK; } return try os.socket(os.AF_INET, flags, os.IPPROTO_UDP); } pub fn sendDNSPacket(sockfd: i32, addr: *const std.net.Address, pkt: DNSPacket, buffer: []u8) !void { const typ = io.FixedBufferStream([]u8); var stream = typ{ .buffer = buffer, .pos = 0 }; var serializer = io.Serializer(.Big, .Bit, typ.Writer).init(stream.writer()); try serializer.serialize(pkt); try serializer.flush(); _ = try std.os.sendto(sockfd, buffer, 0, &addr.any, @sizeOf(std.os.sockaddr)); } fn base64Encode(data: []u8) void { var b64_buf: [0x100000]u8 = undefined; var encoded = b64_buf[0..std.base64.Base64Encoder.calcSize(data.len)]; std.base64.standard_encoder.encode(encoded, data); std.debug.warn("b64 encoded: '{}'\n", .{encoded}); } pub fn recvDNSPacket(sockfd: os.fd_t, allocator: *Allocator) !DNSPacket { var buffer = try allocator.alloc(u8, 1024); var byte_count = try os.read(sockfd, buffer); var packet_slice = buffer[0..byte_count]; var pkt = DNSPacket.init(allocator, packet_slice); var stream = dns.FixedStream{ .buffer = packet_slice, .pos = 0 }; var deserializer = dns.DNSDeserializer.init(stream.reader()); try deserializer.deserializeInto(&pkt); return pkt; } pub const AddressArrayList = std.ArrayList(std.net.Address); pub const AddressList = struct { addrs: AddressArrayList, canon_name: ?[]u8, pub fn deinit(self: *@This()) void { self.addrs.deinit(); } }; fn toSlicePollFd(allocator: *std.mem.Allocator, fds: []os.fd_t) ![]os.pollfd { var pollfds = try allocator.alloc(os.pollfd, fds.len); for (fds) |fd, idx| { pollfds[idx] = os.pollfd{ .fd = fd, .events = os.POLLIN, .revents = 0 }; } return pollfds; } pub fn getAddressList(allocator: *std.mem.Allocator, name: []const u8, port: u16) !*AddressList { var result = try allocator.create(AddressList); result.* = AddressList{ .addrs = AddressArrayList.init(allocator), .canon_name = null, }; var fd = try openDNSSocket(); var nameservers = try resolv.readNameservers(allocator); var addrs = std.ArrayList(std.net.Address).init(allocator); defer addrs.deinit(); for (nameservers.items) |nameserver| { var ns_addr = try std.net.Address.parseIp(nameserver, 53); try addrs.append(ns_addr); } var packet_a = try main.makeDNSPacket(allocator, name, "A"); var packet_aaaa = try main.makeDNSPacket(allocator, name, "AAAA"); var buf_a = try allocator.alloc(u8, packet_a.size()); var buf_aaaa = try allocator.alloc(u8, packet_aaaa.size()); for (addrs.items) |addr| { try sendDNSPacket(fd, &addr, packet_a, buf_a); try sendDNSPacket(fd, &addr, packet_aaaa, buf_aaaa); } var fds = [_]os.fd_t{fd}; var pollfds = try toSlicePollFd(allocator, fds[0..]); const sockets = try os.poll(pollfds, 300); if (sockets == 0) return error.TimedOut; // TODO wrap this in a while true so we can retry servers who fail for (pollfds) |incoming| { if (incoming.revents == 0) continue; if (incoming.revents != os.POLLIN) return error.UnexpectedPollFd; std.debug.warn("fd {} is available\n", .{incoming.fd}); var pkt = try recvDNSPacket(incoming.fd, allocator); if (!pkt.header.qr_flag) return error.GotQuestion; // TODO remove fd from poll() and try again when no answer if (pkt.header.ancount == 0) return error.NoAnswers; // TODO check pkt.header.rcode var ans = pkt.answers.at(0); // try main.printPacket(pkt); result.canon_name = try ans.name.toStr(allocator); var pkt_rdata = try rdata.deserializeRData(pkt, ans); var addr = switch (pkt_rdata) { .A => |addr| blk: { const recast = @ptrCast(*const [4]u8, &addr.in.addr).*; var ip4array: [4]u8 = undefined; for (recast) |byte, idx| { ip4array[idx] = byte; } break :blk std.net.Address.initIp4(ip4array, port); }, .AAAA => |addr| blk: { break :blk std.net.Address.initIp6(addr.in6.addr, port, 0, 0); }, else => unreachable, }; try result.addrs.append(addr); } return result; }
src/proto.zig
const std = @import("std"); const rng = @import("../common/rng.zig"); const options = @import("../common/options.zig"); const gen1 = @import("../gen1/data.zig"); const items = @import("data/items.zig"); const moves = @import("data/moves.zig"); const species = @import("data/species.zig"); const types = @import("data/types.zig"); const assert = std.debug.assert; const expectEqual = std.testing.expectEqual; const expect = std.testing.expect; const showdown = options.showdown; pub const PRNG = rng.PRNG(2); pub fn Battle(comptime RNG: anytype) type { return extern struct { rng: RNG, sides: [2]Side, turn: u16 = 0, field: Field = .{}, pub fn p1(self: *Battle) *Side { return &self.sides[0]; } pub fn p2(self: *Battle) *Side { return &self.sides[1]; } }; } test "Battle" { try expectEqual(if (showdown) 440 else 444, @sizeOf(Battle(PRNG))); } const Field = extern struct { weather: Weather.Data = .{}, comptime { assert(@sizeOf(Field) == 1); } }; const Weather = enum(u4) { None, Rain, Sun, Sandstorm, const Data = packed struct { id: Weather = .None, duration: u4 = 0, comptime { assert(@sizeOf(Data) == 1); } }; }; const Side = extern struct { pokemon: [6]Pokemon = [_]Pokemon{.{}} ** 6, active: ActivePokemon = .{}, conditions: Conditions, // BUG: ziglang/zig#2627 const Conditions = packed struct { data: Data = .{}, Spikes: bool = false, Safeguard: bool = false, LightScreen: bool = false, Reflect: bool = false, const Data = packed struct { safeguard: u4 = 0, light_screen: u4 = 0, reflect: u4 = 0, comptime { assert(@bitSizeOf(Data) == 12); } }; comptime { assert(@sizeOf(Conditions) == 2); } }; comptime { assert(@sizeOf(Side) == 214); } pub fn get(self: *const Side, slot: u8) *Pokemon { assert(slot > 0 and slot < 7); return self.pokemon[slot - 1]; } }; // NOTE: IVs (Gender & Hidden Power) and Happiness are stored only in Pokemon const ActivePokemon = extern struct { volatiles: Volatile = .{}, stats: Stats(u16) = .{}, moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4, boosts: Boosts = .{}, species: Species = .None, item: Item = .None, last_move: Move = .None, position: u8 = 0, // FIXME move to volatiles? // trapped: bool = false, // switching: bool = false, comptime { assert(@sizeOf(ActivePokemon) == 44); } }; const Pokemon = extern struct { stats: Stats(u10) = .{}, // 4 bits trailing moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4, types: Types = .{}, ivs: IVs = .{}, hp: u16 = 0, status: u8 = 0, species: Species = .None, level: u8 = 100, item: Item = .None, happiness: u8 = 255, position: u8 = 0, comptime { assert(@sizeOf(Pokemon) == 28); } }; pub const Gender = enum(u1) { Male, Female, }; const IVs = packed struct { gender: Gender = .Male, power: u7 = 70, type: Type = .Dark, pub fn init(g: Gender, p: u7, t: Type) IVs { assert(p >= 31 and p <= 70); assert(t != .Normal and t != .@"???"); return IVs{ .gender = g, .power = p, .type = t }; } comptime { assert(@sizeOf(IVs) == 2); } }; const MoveSlot = extern struct { id: Move = .None, pp: u8 = 0, comptime { assert(@sizeOf(MoveSlot) == @sizeOf(u16)); } }; pub const Status = gen1.Status; const Volatile = packed struct { data: Data, Bide: bool = false, Thrashing: bool = false, Flinch: bool = false, Charging: bool = false, Underground: bool = false, Flying: bool = false, Confusion: bool = false, Mist: bool = false, FocusEnergy: bool = false, Substitute: bool = false, Recharging: bool = false, Rage: bool = false, LeechSeed: bool = false, Toxic: bool = false, Transform: bool = false, Nightmare: bool = false, Cure: bool = false, Protect: bool = false, Foresight: bool = false, PerishSong: bool = false, Endure: bool = false, Rollout: bool = false, Attract: bool = false, DefenseCurl: bool = false, Encore: bool = false, LockOn: bool = false, DestinyBond: bool = false, BeatUp: bool = false, _: u4 = 0, const Data = packed struct { future_sight: FutureSight = .{}, bide: u16 = 0, disabled: Disabled = .{}, rage: u8 = 0, substitute: u8 = 0, confusion: u4 = 0, encore: u4 = 0, fury_cutter: u4 = 0, perish_song: u4 = 0, protect: u4 = 0, rollout: u4 = 0, toxic: u4 = 0, wrap: u4 = 0, _: u8 = 0, const Disabled = packed struct { move: u4 = 0, duration: u4 = 0, }; const FutureSight = packed struct { damage: u12 = 0, count: u4 = 0, }; comptime { assert(@sizeOf(Data) == 12); } }; comptime { assert(@sizeOf(Volatile) == 16); } }; pub fn Stats(comptime T: type) type { return packed struct { hp: T = 0, atk: T = 0, def: T = 0, spe: T = 0, spa: T = 0, spd: T = 0, }; } test "Stats" { try expectEqual(12, @sizeOf(Stats(u16))); const stats = Stats(u4){ .spd = 2, .spe = 3 }; try expectEqual(2, stats.spd); try expectEqual(0, stats.def); } pub const Boosts = packed struct { atk: i4 = 0, def: i4 = 0, spe: i4 = 0, spa: i4 = 0, spd: i4 = 0, accuracy: i4 = 0, evasion: i4 = 0, _: i4 = 0, comptime { assert(@sizeOf(Boosts) == 4); } }; test "Boosts" { const boosts = Boosts{ .spd = -6 }; try expectEqual(0, boosts.atk); try expectEqual(-6, boosts.spd); } pub const Item = items.Item; test "Item" { try expect(Item.boost(.MasterBall) == null); try expectEqual(Type.Normal, Item.boost(.PinkBow).?); try expectEqual(Type.Normal, Item.boost(.PolkadotBow).?); try expectEqual(Type.Dark, Item.boost(.BlackGlasses).?); try expect(!Item.mail(.TM50)); try expect(Item.mail(.FlowerMail)); try expect(Item.mail(.MirageMail)); try expect(!Item.berry(.MirageMail)); try expect(Item.berry(.PSNCureBerry)); try expect(Item.berry(.GoldBerry)); } pub const Move = moves.Move; test "Moves" { try expectEqual(251, @enumToInt(Move.BeatUp)); const move = Move.get(.DynamicPunch); try expectEqual(Move.Effect.ConfusionChance, move.effect); try expectEqual(@as(u8, 50), move.accuracy()); try expectEqual(@as(u8, 5), move.pp * 5); } pub const Species = species.Species; test "Species" { try expectEqual(152, @enumToInt(Species.Chikorita)); try expectEqual(@as(u8, 100), Species.get(.Celebi).stats.spd); } pub const Type = types.Type; pub const Types = types.Types; pub const Effectiveness = gen1.Effectiveness; test "Types" { try expectEqual(13, @enumToInt(Type.Electric)); try expect(!Type.Steel.special()); try expect(Type.Dark.special()); try expectEqual(Effectiveness.Super, Type.effectiveness(.Ghost, .Psychic)); try expectEqual(Effectiveness.Super, Type.effectiveness(.Water, .Fire)); try expectEqual(Effectiveness.Resisted, Type.effectiveness(.Fire, .Water)); try expectEqual(Effectiveness.Neutral, Type.effectiveness(.Normal, .Grass)); try expectEqual(Effectiveness.Immune, Type.effectiveness(.Poison, .Steel)); } // TODO DEBUG comptime { std.testing.refAllDecls(@This()); }
src/lib/gen2/data.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 native container, which draws a frame with a title around its child. pub const Frame = opaque { pub const CLASS_NAME = "frame"; pub const NATIVE_TYPE = iup.NativeType.Control; const Self = @This(); /// /// 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; /// /// 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; /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void; pub const ZOrder = enum { Top, Bottom, }; /// /// EXPAND (non inheritable): The default value is "YES". 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.*; } pub fn setChildren(self: *Initializer, tuple: anytype) Initializer { if (self.last_error) |_| return self.*; Self.appendChildren(self.ref, tuple) catch |err| { self.last_error = err; }; 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 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 setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, 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 setExpandWeight(self: *Initializer, arg: f64) Initializer { if (self.last_error) |_| return self.*; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, 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.*; } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn setChildOffset(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, "CHILDOFFSET", .{}, value); return self.*; } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg); 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.*; } /// /// TITLE (non inheritable): Text the user will see at the top of the frame. /// If not defined during creation it can not be added lately, to be changed it /// must be at least "" during creation. pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TITLE", .{}, arg); return self.*; } /// /// FGCOLOR: Text title color. /// Not available in Windows when using Windows Visual Styles. /// Default: the global attribute DLGFGCOLOR. 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 setVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg); 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 setFontFace(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTFACE", .{}, 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.*; } 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 setPropagateFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg); return self.*; } pub fn setBackColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BACKCOLOR", .{}, 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 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.*; } /// /// BGCOLOR: ignored, transparent in all systems. /// Will use the background color of the native parent. /// Except if TITLE is not defined and BGCOLOR is defined before map (can be /// changed later), then the frame will have a color background. 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 setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg); 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 setFont(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONT", .{}, 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 setTipVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg); return self.*; } pub fn setTipDelay(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg); return self.*; } /// /// EXPAND (non inheritable): The default value is "YES". 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 setCanFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, 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 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 setTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "THEME", .{}, 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 setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPICON", .{}, arg); 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.*; } /// /// 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.*; } /// /// 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.*; } /// /// 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.*; } /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_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); } /// /// Adds a tuple of children pub fn appendChildren(self: *Self, tuple: anytype) !void { try Impl(Self).appendChildren(self, tuple); } /// /// Appends a child on this container /// child must be an Element or pub fn appendChild(self: *Self, child: anytype) !void { try Impl(Self).appendChild(self, child); } /// /// Returns a iterator for children elements. pub fn children(self: *Self) ChildrenIterator { return ChildrenIterator.init(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); } 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 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 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 getFontSize(self: *Self) i32 { return interop.getIntAttribute(self, "FONTSIZE", .{}); } pub fn setFontSize(self: *Self, arg: i32) void { interop.setIntAttribute(self, "FONTSIZE", .{}, 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 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); } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn getChildOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CHILDOFFSET", .{}); return Size.parse(str); } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn setChildOffset(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "CHILDOFFSET", .{}, value); } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn getActive(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVE", .{}); } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ACTIVE", .{}, arg); } 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); } /// /// TITLE (non inheritable): Text the user will see at the top of the frame. /// If not defined during creation it can not be added lately, to be changed it /// must be at least "" during creation. pub fn getTitle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TITLE", .{}); } /// /// TITLE (non inheritable): Text the user will see at the top of the frame. /// If not defined during creation it can not be added lately, to be changed it /// must be at least "" during creation. pub fn setTitle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TITLE", .{}, arg); } /// /// FGCOLOR: Text title color. /// Not available in Windows when using Windows Visual Styles. /// Default: the global attribute DLGFGCOLOR. pub fn getFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "FGCOLOR", .{}); } /// /// FGCOLOR: Text title color. /// Not available in Windows when using Windows Visual Styles. /// Default: the global attribute DLGFGCOLOR. pub fn setFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "FGCOLOR", .{}, rgb); } pub fn getNaturalSize(self: *Self) Size { var str = interop.getStrAttribute(self, "NATURALSIZE", .{}); return Size.parse(str); } pub fn getScreenPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "SCREENPOSITION", .{}); return iup.XYPos.parse(str, ','); } 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 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 getClientOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{}); return Size.parse(str); } 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 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 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 getPropagateFocus(self: *Self) bool { return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{}); } pub fn setPropagateFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg); } pub fn getBackColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BACKCOLOR", .{}); } pub fn setBackColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BACKCOLOR", .{}, rgb); } pub fn getCharSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CHARSIZE", .{}); return Size.parse(str); } 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 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); } /// /// BGCOLOR: ignored, transparent in all systems. /// Will use the background color of the native parent. /// Except if TITLE is not defined and BGCOLOR is defined before map (can be /// changed later), then the frame will have a color background. pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } /// /// BGCOLOR: ignored, transparent in all systems. /// Will use the background color of the native parent. /// Except if TITLE is not defined and BGCOLOR is defined before map (can be /// changed later), then the frame will have a color background. pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } 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 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 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); } 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 getTipVisible(self: *Self) bool { return interop.getBoolAttribute(self, "TIPVISIBLE", .{}); } pub fn setTipVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg); } pub fn getTipDelay(self: *Self) i32 { return interop.getIntAttribute(self, "TIPDELAY", .{}); } pub fn setTipDelay(self: *Self, arg: i32) void { interop.setIntAttribute(self, "TIPDELAY", .{}, arg); } /// /// EXPAND (non inheritable): The default value is "YES". 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; } /// /// EXPAND (non inheritable): The default value is "YES". 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 getCanFocus(self: *Self) bool { return interop.getBoolAttribute(self, "CANFOCUS", .{}); } pub fn setCanFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CANFOCUS", .{}, 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 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 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 getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } pub fn getX(self: *Self) i32 { return interop.getIntAttribute(self, "X", .{}); } pub fn getY(self: *Self) i32 { return interop.getIntAttribute(self, "Y", .{}); } 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 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 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 getClientSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTSIZE", .{}); return Size.parse(str); } /// /// 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); } /// /// 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); } /// /// 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); } /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self, callback); } }; test "Frame TipBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame UserSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame FontStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setFontStyle("Hello").unwrap()); defer item.deinit(); var ret = item.getFontStyle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame FontSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setFontSize(42).unwrap()); defer item.deinit(); var ret = item.getFontSize(); try std.testing.expect(ret == 42); } test "Frame ExpandWeight" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setExpandWeight(3.14).unwrap()); defer item.deinit(); var ret = item.getExpandWeight(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Frame MaxSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame ChildOffset" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setChildOffset(9, 10).unwrap()); defer item.deinit(); var ret = item.getChildOffset(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Frame Active" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setActive(true).unwrap()); defer item.deinit(); var ret = item.getActive(); try std.testing.expect(ret == true); } test "Frame NTheme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setNTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getNTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame Title" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTitle("Hello").unwrap()); defer item.deinit(); var ret = item.getTitle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame FgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame Visible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setVisible(true).unwrap()); defer item.deinit(); var ret = item.getVisible(); try std.testing.expect(ret == true); } test "Frame TipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame FontFace" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setFontFace("Hello").unwrap()); defer item.deinit(); var ret = item.getFontFace(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame Tip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame PropagateFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setPropagateFocus(true).unwrap()); defer item.deinit(); var ret = item.getPropagateFocus(); try std.testing.expect(ret == true); } test "Frame BackColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setBackColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBackColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Frame HandleName" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setHandleName("Hello").unwrap()); defer item.deinit(); var ret = item.getHandleName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame Size" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame BgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame NormalizerGroup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setNormalizerGroup("Hello").unwrap()); defer item.deinit(); var ret = item.getNormalizerGroup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame TipFgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame Font" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setFont("Hello").unwrap()); defer item.deinit(); var ret = item.getFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame Name" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setName("Hello").unwrap()); defer item.deinit(); var ret = item.getName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame TipVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTipVisible(true).unwrap()); defer item.deinit(); var ret = item.getTipVisible(); try std.testing.expect(ret == true); } test "Frame TipDelay" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTipDelay(42).unwrap()); defer item.deinit(); var ret = item.getTipDelay(); try std.testing.expect(ret == 42); } test "Frame Expand" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setExpand(.Yes).unwrap()); defer item.deinit(); var ret = item.getExpand(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Frame CanFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setCanFocus(true).unwrap()); defer item.deinit(); var ret = item.getCanFocus(); try std.testing.expect(ret == true); } test "Frame RasterSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame Floating" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setFloating(.Yes).unwrap()); defer item.deinit(); var ret = item.getFloating(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Frame Theme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame MinSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.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 "Frame TipIcon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setTipIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getTipIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Frame Position" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Frame.init().setPosition(9, 10).unwrap()); defer item.deinit(); var ret = item.getPosition(); try std.testing.expect(ret.x == 9 and ret.y == 10); }
src/elements/frame.zig
const std = @import("std"); const getty = @import("getty"); const assert = std.debug.assert; const expectEqual = std.testing.expectEqual; const expectEqualSlices = std.testing.expectEqualSlices; const Token = @import("common/token.zig").Token; pub const Serializer = struct { tokens: []const Token, const Self = @This(); const impl = @"impl Serializer"; pub fn init(tokens: []const Token) Self { return .{ .tokens = tokens }; } pub fn remaining(self: Self) usize { return self.tokens.len; } pub fn nextTokenOpt(self: *Self) ?Token { switch (self.remaining()) { 0 => return null, else => |len| { const first = self.tokens[0]; self.tokens = if (len == 1) &[_]Token{} else self.tokens[1..]; return first; }, } } pub usingnamespace getty.Serializer( *Self, impl.serializer.Ok, impl.serializer.Error, impl.serializer.MapSerialize, impl.serializer.SequenceSerialize, impl.serializer.StructSerialize, impl.serializer.TupleSerialize, impl.serializer.serializeBool, impl.serializer.serializeEnum, impl.serializer.serializeFloat, impl.serializer.serializeInt, impl.serializer.serializeMap, impl.serializer.serializeNull, impl.serializer.serializeSequence, impl.serializer.serializeSome, impl.serializer.serializeString, impl.serializer.serializeStruct, impl.serializer.serializeTuple, impl.serializer.serializeVoid, ); pub usingnamespace getty.ser.MapSerialize( *Self, impl.mapSerialize.Ok, impl.mapSerialize.Error, impl.mapSerialize.serializeKey, impl.mapSerialize.serializeValue, impl.mapSerialize.end, ); pub usingnamespace getty.ser.SequenceSerialize( *Self, impl.sequenceSerialize.Ok, impl.sequenceSerialize.Error, impl.sequenceSerialize.serializeElement, impl.sequenceSerialize.end, ); pub usingnamespace getty.ser.TupleSerialize( *Self, impl.tupleSerialize.Ok, impl.tupleSerialize.Error, impl.tupleSerialize.serializeElement, impl.tupleSerialize.end, ); pub usingnamespace getty.ser.StructSerialize( *Self, impl.structSerialize.Ok, impl.structSerialize.Error, impl.structSerialize.serializeField, impl.structSerialize.end, ); }; const @"impl Serializer" = struct { pub const serializer = struct { pub const Ok = void; pub const Error = getty.ser.Error || error{TestExpectedEqual}; pub const MapSerialize = *Serializer; pub const SequenceSerialize = *Serializer; pub const StructSerialize = *Serializer; pub const TupleSerialize = *Serializer; pub fn serializeBool(self: *Serializer, v: bool) Error!Ok { try assertNextToken(self, Token{ .Bool = v }); } pub fn serializeEnum(self: *Serializer, v: anytype) Error!Ok { const name = switch (@typeInfo(@TypeOf(v))) { .EnumLiteral => "", .Enum => @typeName(@TypeOf(v)), else => unreachable, }; try assertNextToken(self, Token{ .Enum = .{ .name = name, .variant = @tagName(v) } }); } pub fn serializeFloat(self: *Serializer, v: anytype) Error!Ok { var expected = switch (@typeInfo(@TypeOf(v))) { .ComptimeFloat => Token{ .ComptimeFloat = {} }, .Float => |info| switch (info.bits) { 16 => Token{ .F16 = v }, 32 => Token{ .F32 = v }, 64 => Token{ .F64 = v }, 128 => Token{ .F128 = v }, else => @panic("unexpected float size"), }, else => @panic("unexpected type"), }; try assertNextToken(self, expected); } pub fn serializeInt(self: *Serializer, v: anytype) Error!Ok { var expected = switch (@typeInfo(@TypeOf(v))) { .ComptimeInt => Token{ .ComptimeInt = {} }, .Int => |info| switch (info.signedness) { .signed => switch (info.bits) { 8 => Token{ .I8 = v }, 16 => Token{ .I16 = v }, 32 => Token{ .I32 = v }, 64 => Token{ .I64 = v }, 128 => Token{ .I128 = v }, else => @panic("unexpected integer size"), }, .unsigned => switch (info.bits) { 8 => Token{ .U8 = v }, 16 => Token{ .U16 = v }, 32 => Token{ .U32 = v }, 64 => Token{ .U64 = v }, 128 => Token{ .U128 = v }, else => @panic("unexpected integer size"), }, }, else => @panic("unexpected type"), }; try assertNextToken(self, expected); } pub fn serializeMap(self: *Serializer, length: ?usize) Error!MapSerialize { try assertNextToken(self, Token{ .Map = .{ .len = length } }); return self; } pub fn serializeNull(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .Null = {} }); } pub fn serializeSequence(self: *Serializer, length: ?usize) Error!SequenceSerialize { try assertNextToken(self, Token{ .Seq = .{ .len = length } }); return self; } pub fn serializeSome(self: *Serializer, v: anytype) Error!Ok { try assertNextToken(self, Token{ .Some = {} }); try getty.serialize(v, self.serializer()); } pub fn serializeString(self: *Serializer, v: anytype) Error!Ok { try assertNextToken(self, Token{ .String = v }); } pub fn serializeStruct(self: *Serializer, comptime name: []const u8, length: usize) Error!StructSerialize { try assertNextToken(self, Token{ .Struct = .{ .name = name, .len = length } }); return self; } pub fn serializeTuple(self: *Serializer, length: ?usize) Error!TupleSerialize { try assertNextToken(self, Token{ .Tuple = .{ .len = length.? } }); return self; } pub fn serializeVoid(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .Void = {} }); } }; pub const mapSerialize = struct { pub const Ok = serializer.Ok; pub const Error = serializer.Error; pub fn serializeKey(self: *Serializer, key: anytype) Error!void { try getty.serialize(key, self.serializer()); } pub fn serializeValue(self: *Serializer, value: anytype) Error!void { try getty.serialize(value, self.serializer()); } pub fn end(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .MapEnd = {} }); } }; pub const sequenceSerialize = struct { pub const Ok = serializer.Ok; pub const Error = serializer.Error; pub fn serializeElement(self: *Serializer, value: anytype) Error!void { try getty.serialize(value, self.serializer()); } pub fn end(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .SeqEnd = {} }); } }; pub const structSerialize = struct { pub const Ok = serializer.Ok; pub const Error = serializer.Error; pub fn serializeField(self: *Serializer, comptime key: []const u8, value: anytype) Error!Ok { try assertNextToken(self, Token{ .String = key }); try getty.serialize(value, self.serializer()); } pub fn end(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .StructEnd = {} }); } }; pub const tupleSerialize = struct { pub const Ok = serializer.Ok; pub const Error = serializer.Error; pub fn serializeElement(self: *Serializer, value: anytype) Error!void { try getty.serialize(value, self.serializer()); } pub fn end(self: *Serializer) Error!Ok { try assertNextToken(self, Token{ .TupleEnd = {} }); } }; fn assertNextToken(ser: *Serializer, expected: Token) !void { if (ser.nextTokenOpt()) |token| { const token_tag = std.meta.activeTag(token); const expected_tag = std.meta.activeTag(expected); if (token_tag == expected_tag) { switch (token) { .Bool => try expectEqual(@field(token, "Bool"), @field(expected, "Bool")), .ComptimeFloat => try expectEqual(@field(token, "ComptimeFloat"), @field(expected, "ComptimeFloat")), .ComptimeInt => try expectEqual(@field(token, "ComptimeInt"), @field(expected, "ComptimeInt")), .Enum => { const t = @field(token, "Enum"); const e = @field(expected, "Enum"); try expectEqualSlices(u8, t.name, e.name); try expectEqualSlices(u8, t.variant, e.variant); }, .F16 => try expectEqual(@field(token, "F16"), @field(expected, "F16")), .F32 => try expectEqual(@field(token, "F32"), @field(expected, "F32")), .F64 => try expectEqual(@field(token, "F64"), @field(expected, "F64")), .F128 => try expectEqual(@field(token, "F128"), @field(expected, "F128")), .I8 => try expectEqual(@field(token, "I8"), @field(expected, "I8")), .I16 => try expectEqual(@field(token, "I16"), @field(expected, "I16")), .I32 => try expectEqual(@field(token, "I32"), @field(expected, "I32")), .I64 => try expectEqual(@field(token, "I64"), @field(expected, "I64")), .I128 => try expectEqual(@field(token, "I128"), @field(expected, "I128")), .Map => try expectEqual(@field(token, "Map"), @field(expected, "Map")), .MapEnd => try expectEqual(@field(token, "MapEnd"), @field(expected, "MapEnd")), .Null => try expectEqual(@field(token, "Null"), @field(expected, "Null")), .Seq => try expectEqual(@field(token, "Seq"), @field(expected, "Seq")), .SeqEnd => try expectEqual(@field(token, "SeqEnd"), @field(expected, "SeqEnd")), .Some => try expectEqual(@field(token, "Some"), @field(expected, "Some")), .String => try expectEqualSlices(u8, @field(token, "String"), @field(expected, "String")), .Struct => { const t = @field(token, "Struct"); const e = @field(expected, "Struct"); try expectEqualSlices(u8, t.name, e.name); try expectEqual(t.len, e.len); }, .StructEnd => try expectEqual(@field(token, "StructEnd"), @field(expected, "StructEnd")), .Tuple => try expectEqual(@field(token, "Tuple"), @field(expected, "Tuple")), .TupleEnd => try expectEqual(@field(token, "TupleEnd"), @field(expected, "TupleEnd")), .U8 => try expectEqual(@field(token, "U8"), @field(expected, "U8")), .U16 => try expectEqual(@field(token, "U16"), @field(expected, "U16")), .U32 => try expectEqual(@field(token, "U32"), @field(expected, "U32")), .U64 => try expectEqual(@field(token, "U64"), @field(expected, "U64")), .U128 => try expectEqual(@field(token, "U128"), @field(expected, "U128")), .Void => try expectEqual(@field(token, "Void"), @field(expected, "Void")), } } else { @panic("expected Token::{} but serialized as {}"); } } else { @panic("expected end of tokens, but {} was serialized"); } } };
src/tests/ser/serializer.zig
const std = @import("std"); const upaya = @import("upaya"); usingnamespace @import("imgui"); pub var ui_tint: ImVec4 = upaya.colors.rgbaToVec4(135, 45, 176, 255); pub var object: ImU32 = 0; pub var object_selected: ImU32 = 0; pub var object_drag_link: ImU32 = 0; pub var object_link: ImU32 = 0; pub var white: ImU32 = 0; pub fn init() void { setDefaultImGuiStyle(); object = upaya.colors.rgbToU32(116, 252, 50); object_selected = upaya.colors.rgbToU32(282, 172, 247); object_drag_link = upaya.colors.rgbToU32(255, 0, 0); object_link = upaya.colors.rgbToU32(220, 200, 10); white = upaya.colors.rgbToU32(255, 255, 255); } fn setDefaultImGuiStyle() void { var style = igGetStyle(); style.TabRounding = 2; style.FrameRounding = 4; style.WindowBorderSize = 1; style.WindowRounding = 0; style.WindowMenuButtonPosition = ImGuiDir_None; style.Colors[ImGuiCol_WindowBg] = ogColorConvertU32ToFloat4(upaya.colors.rgbaToU32(25, 25, 25, 255)); style.Colors[ImGuiCol_TextSelectedBg] = ogColorConvertU32ToFloat4(upaya.colors.rgbaToU32(66, 150, 250, 187)); setTintColor(ui_tint); } pub fn setTintColor(color: ImVec4) void { var colors = &igGetStyle().Colors; colors[ImGuiCol_FrameBg] = hsvShiftColor(color, 0, 0, -0.2); colors[ImGuiCol_Border] = hsvShiftColor(color, 0, 0, -0.2); const header = hsvShiftColor(color, 0, -0.2, 0); colors[ImGuiCol_Header] = header; colors[ImGuiCol_HeaderHovered] = hsvShiftColor(header, 0, 0, 0.1); colors[ImGuiCol_HeaderActive] = hsvShiftColor(header, 0, 0, -0.1); const title = hsvShiftColor(color, 0, 0.1, 0); colors[ImGuiCol_TitleBg] = title; colors[ImGuiCol_TitleBgActive] = title; const tab = hsvShiftColor(color, 0, 0.1, 0); colors[ImGuiCol_Tab] = tab; colors[ImGuiCol_TabActive] = hsvShiftColor(tab, 0.05, 0.2, 0.2); colors[ImGuiCol_TabHovered] = hsvShiftColor(tab, 0.02, 0.1, 0.2); colors[ImGuiCol_TabUnfocused] = hsvShiftColor(tab, 0, -0.1, 0); colors[ImGuiCol_TabUnfocusedActive] = colors[ImGuiCol_TabActive]; const button = hsvShiftColor(color, -0.05, 0, 0); colors[ImGuiCol_Button] = button; colors[ImGuiCol_ButtonHovered] = hsvShiftColor(button, 0, 0, 0.1); colors[ImGuiCol_ButtonActive] = hsvShiftColor(button, 0, 0, -0.1); } fn hsvShiftColor(color: ImVec4, h_shift: f32, s_shift: f32, v_shift: f32) ImVec4 { var h: f32 = undefined; var s: f32 = undefined; var v: f32 = undefined; igColorConvertRGBtoHSV(color.x, color.y, color.z, &h, &s, &v); h += h_shift; s += s_shift; v += v_shift; var out_color = color; igColorConvertHSVtoRGB(h, s, v, &out_color.x, &out_color.y, &out_color.z); return out_color; } pub fn toggleObjectMode(enable: bool) void { if (enable) { setTintColor(colorRgbaVec4(5, 145, 12, 255)); } else { setTintColor(ui_tint); } }
editor/colors.zig
const X = @import("X.zig"); pub usingnamespace X; const wchar_t = c_int; pub const FreeFuncType = ?fn ([*c]Display) callconv(.C) void; pub const FreeModmapType = ?fn ([*c]XModifierKeymap) callconv(.C) c_int; pub const struct__XSQEvent = extern struct { next: [*c]struct__XSQEvent, event: XEvent, qserial_num: c_ulong, }; pub const struct__XFreeFuncs = extern struct { atoms: FreeFuncType, modifiermap: FreeModmapType, key_bindings: FreeFuncType, context_db: FreeFuncType, defaultCCCs: FreeFuncType, clientCmaps: FreeFuncType, intensityMaps: FreeFuncType, im_filters: FreeFuncType, xkb: FreeFuncType, }; pub const struct__XPrivate = opaque {}; pub const CreateGCType = ?fn ([*c]Display, GC, [*c]XExtCodes) callconv(.C) c_int; pub const CopyGCType = ?fn ([*c]Display, GC, [*c]XExtCodes) callconv(.C) c_int; pub const FlushGCType = ?fn ([*c]Display, GC, [*c]XExtCodes) callconv(.C) c_int; pub const FreeGCType = ?fn ([*c]Display, GC, [*c]XExtCodes) callconv(.C) c_int; pub const CreateFontType = ?fn ([*c]Display, [*c]XFontStruct, [*c]XExtCodes) callconv(.C) c_int; pub const FreeFontType = ?fn ([*c]Display, [*c]XFontStruct, [*c]XExtCodes) callconv(.C) c_int; pub const CloseDisplayType = ?fn ([*c]Display, [*c]XExtCodes) callconv(.C) c_int; pub const ErrorType = ?fn ([*c]Display, [*c]xError, [*c]XExtCodes, [*c]c_int) callconv(.C) c_int; pub const ErrorStringType = ?fn ([*c]Display, c_int, [*c]XExtCodes, [*c]u8, c_int) callconv(.C) [*c]u8; pub const PrintErrorType = ?fn ([*c]Display, [*c]XErrorEvent, ?*anyopaque) callconv(.C) void; pub const BeforeFlushType = ?fn ([*c]Display, [*c]XExtCodes, [*c]const u8, c_long) callconv(.C) void; pub const struct__XExten = extern struct { next: [*c]struct__XExten, codes: XExtCodes, create_GC: CreateGCType, copy_GC: CopyGCType, flush_GC: FlushGCType, free_GC: FreeGCType, create_Font: CreateFontType, free_Font: FreeFontType, close_display: CloseDisplayType, @"error": ErrorType, error_string: ErrorStringType, name: [*c]u8, error_values: PrintErrorType, before_flush: BeforeFlushType, next_flush: [*c]struct__XExten, }; pub const XSizeHints = extern struct { flags: c_long, x: c_int, y: c_int, width: c_int, height: c_int, min_width: c_int, min_height: c_int, max_width: c_int, max_height: c_int, width_inc: c_int, height_inc: c_int, min_aspect: struct_unnamed_1, max_aspect: struct_unnamed_1, base_width: c_int, base_height: c_int, win_gravity: c_int, }; pub const XWMHints = extern struct { flags: c_long, input: c_int, initial_state: c_int, icon_pixmap: X.Pixmap, icon_window: X.Window, icon_x: c_int, icon_y: c_int, icon_mask: X.Pixmap, window_group: X.XID, }; pub const XTextProperty = extern struct { value: [*c]u8, encoding: X.Atom, format: c_int, nitems: c_ulong, }; pub const XStringStyle: c_int = 0; pub const XCompoundTextStyle: c_int = 1; pub const XTextStyle: c_int = 2; pub const XStdICCTextStyle: c_int = 3; pub const XUTF8StringStyle: c_int = 4; pub const XICCEncodingStyle = c_uint; pub const XIconSize = extern struct { min_width: c_int, min_height: c_int, max_width: c_int, max_height: c_int, width_inc: c_int, height_inc: c_int, }; pub const XClassHint = extern struct { res_name: [*c]u8, res_class: [*c]u8, }; pub const struct__XComposeStatus = extern struct { compose_ptr: X.XPointer, chars_matched: c_int, }; pub const XComposeStatus = struct__XComposeStatus; pub const struct__XRegion = opaque {}; pub const Region = ?*struct__XRegion; pub const XVisualInfo = extern struct { visual: [*c]Visual, visualid: X.VisualID, screen: c_int, depth: c_int, class: c_int, red_mask: c_ulong, green_mask: c_ulong, blue_mask: c_ulong, colormap_size: c_int, bits_per_rgb: c_int, }; pub const XStandardColormap = extern struct { colormap: X.Colormap, red_max: c_ulong, red_mult: c_ulong, green_max: c_ulong, green_mult: c_ulong, blue_max: c_ulong, blue_mult: c_ulong, base_pixel: c_ulong, visualid: X.VisualID, killid: X.XID, }; pub const XContext = c_int; pub extern fn XAllocClassHint() [*c]XClassHint; pub extern fn XAllocIconSize() [*c]XIconSize; pub extern fn XAllocSizeHints() [*c]XSizeHints; pub extern fn XAllocStandardColormap() [*c]XStandardColormap; pub extern fn XAllocWMHints() [*c]XWMHints; pub extern fn XClipBox(Region, [*c]X.XRectangle) c_int; pub extern fn XCreateRegion() Region; pub extern fn XDefaultString() [*c]const u8; pub extern fn XDeleteContext(?*X.Display, X.XID, XContext) c_int; pub extern fn XDestroyRegion(Region) c_int; pub extern fn XEmptyRegion(Region) c_int; pub extern fn XEqualRegion(Region, Region) c_int; pub extern fn XFindContext(?*X.Display, X.XID, XContext, [*c]X.XPointer) c_int; pub extern fn XGetClassHint(?*X.Display, X.Window, [*c]XClassHint) c_int; pub extern fn XGetIconSizes(?*X.Display, X.Window, [*c][*c]XIconSize, [*c]c_int) c_int; pub extern fn XGetNormalHints(?*X.Display, X.Window, [*c]XSizeHints) c_int; pub extern fn XGetRGBColormaps(?*X.Display, X.Window, [*c][*c]XStandardColormap, [*c]c_int, X.Atom) c_int; pub extern fn XGetSizeHints(?*X.Display, X.Window, [*c]XSizeHints, X.Atom) c_int; pub extern fn XGetStandardColormap(?*X.Display, X.Window, [*c]XStandardColormap, X.Atom) c_int; pub extern fn XGetTextProperty(?*X.Display, X.Window, [*c]XTextProperty, X.Atom) c_int; pub extern fn XGetVisualInfo(?*X.Display, c_long, [*c]XVisualInfo, [*c]c_int) [*c]XVisualInfo; pub extern fn XGetWMClientMachine(?*X.Display, X.Window, [*c]XTextProperty) c_int; pub extern fn XGetWMHints(?*X.Display, X.Window) [*c]XWMHints; pub extern fn XGetWMIconName(?*X.Display, X.Window, [*c]XTextProperty) c_int; pub extern fn XGetWMName(?*X.Display, X.Window, [*c]XTextProperty) c_int; pub extern fn XGetWMNormalHints(?*X.Display, X.Window, [*c]XSizeHints, [*c]c_long) c_int; pub extern fn XGetWMSizeHints(?*X.Display, X.Window, [*c]XSizeHints, [*c]c_long, X.Atom) c_int; pub extern fn XGetZoomHints(?*X.Display, X.Window, [*c]XSizeHints) c_int; pub extern fn XIntersectRegion(Region, Region, Region) c_int; pub extern fn XConvertCase(X.KeySym, [*c]X.KeySym, [*c]X.KeySym) void; pub extern fn XLookupString([*c]X.XKeyEvent, [*c]u8, c_int, [*c]X.KeySym, [*c]XComposeStatus) c_int; pub extern fn XMatchVisualInfo(?*X.Display, c_int, c_int, c_int, [*c]XVisualInfo) c_int; pub extern fn XOffsetRegion(Region, c_int, c_int) c_int; pub extern fn XPointInRegion(Region, c_int, c_int) c_int; pub extern fn XPolygonRegion([*c]X.XPoint, c_int, c_int) Region; pub extern fn XRectInRegion(Region, c_int, c_int, c_uint, c_uint) c_int; pub extern fn XSaveContext(?*X.Display, X.XID, XContext, [*c]const u8) c_int; pub extern fn XSetClassHint(?*X.Display, X.Window, [*c]XClassHint) c_int; pub extern fn XSetIconSizes(?*X.Display, X.Window, [*c]XIconSize, c_int) c_int; pub extern fn XSetNormalHints(?*X.Display, X.Window, [*c]XSizeHints) c_int; pub extern fn XSetRGBColormaps(?*X.Display, X.Window, [*c]XStandardColormap, c_int, X.Atom) void; pub extern fn XSetSizeHints(?*X.Display, X.Window, [*c]XSizeHints, X.Atom) c_int; pub extern fn XSetStandardProperties(?*X.Display, X.Window, [*c]const u8, [*c]const u8, X.Pixmap, [*c][*c]u8, c_int, [*c]XSizeHints) c_int; pub extern fn XSetTextProperty(?*X.Display, X.Window, [*c]XTextProperty, X.Atom) void; pub extern fn XSetWMClientMachine(?*X.Display, X.Window, [*c]XTextProperty) void; pub extern fn XSetWMHints(?*X.Display, X.Window, [*c]XWMHints) c_int; pub extern fn XSetWMIconName(?*X.Display, X.Window, [*c]XTextProperty) void; pub extern fn XSetWMName(?*X.Display, X.Window, [*c]XTextProperty) void; pub extern fn XSetWMNormalHints(?*X.Display, X.Window, [*c]XSizeHints) void; pub extern fn XSetWMProperties(?*X.Display, X.Window, [*c]XTextProperty, [*c]XTextProperty, [*c][*c]u8, c_int, [*c]XSizeHints, [*c]XWMHints, [*c]XClassHint) void; pub extern fn XmbSetWMProperties(?*X.Display, X.Window, [*c]const u8, [*c]const u8, [*c][*c]u8, c_int, [*c]XSizeHints, [*c]XWMHints, [*c]XClassHint) void; pub extern fn Xutf8SetWMProperties(?*X.Display, X.Window, [*c]const u8, [*c]const u8, [*c][*c]u8, c_int, [*c]XSizeHints, [*c]XWMHints, [*c]XClassHint) void; pub extern fn XSetWMSizeHints(?*X.Display, X.Window, [*c]XSizeHints, X.Atom) void; pub extern fn XSetRegion(?*X.Display, GC: c_int, Region) c_int; pub extern fn XSetStandardColormap(?*X.Display, X.Window, [*c]XStandardColormap, X.Atom) void; pub extern fn XSetZoomHints(?*X.Display, X.Window, [*c]XSizeHints) c_int; pub extern fn XShrinkRegion(Region, c_int, c_int) c_int; pub extern fn XStringListToTextProperty([*c][*c]u8, c_int, [*c]XTextProperty) c_int; pub extern fn XSubtractRegion(Region, Region, Region) c_int; pub extern fn XmbTextListToTextProperty(display: ?*X.Display, list: [*c][*c]u8, count: c_int, style: XICCEncodingStyle, text_prop_return: [*c]XTextProperty) c_int; pub extern fn XwcTextListToTextProperty(display: ?*X.Display, list: [*c][*c]wchar_t, count: c_int, style: XICCEncodingStyle, text_prop_return: [*c]XTextProperty) c_int; pub extern fn Xutf8TextListToTextProperty(display: ?*X.Display, list: [*c][*c]u8, count: c_int, style: XICCEncodingStyle, text_prop_return: [*c]XTextProperty) c_int; pub extern fn XwcFreeStringList(list: [*c][*c]wchar_t) void; pub extern fn XTextPropertyToStringList([*c]XTextProperty, [*c][*c][*c]u8, [*c]c_int) c_int; pub extern fn XmbTextPropertyToTextList(display: ?*X.Display, text_prop: [*c]const XTextProperty, list_return: [*c][*c][*c]u8, count_return: [*c]c_int) c_int; pub extern fn XwcTextPropertyToTextList(display: ?*X.Display, text_prop: [*c]const XTextProperty, list_return: [*c][*c][*c]wchar_t, count_return: [*c]c_int) c_int; pub extern fn Xutf8TextPropertyToTextList(display: ?*X.Display, text_prop: [*c]const XTextProperty, list_return: [*c][*c][*c]u8, count_return: [*c]c_int) c_int; pub extern fn XUnionRectWithRegion([*c]X.XRectangle, Region, Region) c_int; pub extern fn XUnionRegion(Region, Region, Region) c_int; pub extern fn XWMGeometry(?*X.Display, c_int, [*c]const u8, [*c]const u8, c_uint, [*c]XSizeHints, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_int) c_int; pub extern fn XXorRegion(Region, Region, Region) c_int; pub inline fn XDestroyImage(ximage: anytype) @TypeOf(ximage.*.f.destroy_image.*(ximage)) { return ximage.*.f.destroy_image.*(ximage); } pub inline fn XGetPixel(ximage: anytype, x: anytype, y: anytype) @TypeOf(ximage.*.f.get_pixel.*(ximage, x, y)) { return ximage.*.f.get_pixel.*(ximage, x, y); } pub inline fn XPutPixel(ximage: anytype, x: anytype, y: anytype, pixel: anytype) @TypeOf(ximage.*.f.put_pixel.*(ximage, x, y, pixel)) { return ximage.*.f.put_pixel.*(ximage, x, y, pixel); } pub inline fn XSubImage(ximage: anytype, x: anytype, y: anytype, width: anytype, height: anytype) @TypeOf(ximage.*.f.sub_image.*(ximage, x, y, width, height)) { return ximage.*.f.sub_image.*(ximage, x, y, width, height); } pub inline fn XAddPixel(ximage: anytype, value: anytype) @TypeOf(ximage.*.f.add_pixel.*(ximage, value)) { return ximage.*.f.add_pixel.*(ximage, value); } pub inline fn IsPrivateKeypadKey(keysym: anytype) @TypeOf((@import("std").zig.c_translation.cast(X.KeySym, keysym) >= @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x11000000, .hexadecimal)) and (@import("std").zig.c_translation.cast(X.KeySym, keysym) <= @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x1100FFFF, .hexadecimal))) { return (@import("std").zig.c_translation.cast(X.KeySym, keysym) >= @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x11000000, .hexadecimal)) and (@import("std").zig.c_translation.cast(X.KeySym, keysym) <= @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x1100FFFF, .hexadecimal)); } pub const RectangleOut = @as(c_int, 0); pub const RectangleIn = @as(c_int, 1); pub const RectanglePart = @as(c_int, 2); pub const VisualNoMask = @as(c_int, 0x0); pub const VisualIDMask = @as(c_int, 0x1); pub const VisualScreenMask = @as(c_int, 0x2); pub const VisualDepthMask = @as(c_int, 0x4); pub const VisualClassMask = @as(c_int, 0x8); pub const VisualRedMaskMask = @as(c_int, 0x10); pub const VisualGreenMaskMask = @as(c_int, 0x20); pub const VisualBlueMaskMask = @as(c_int, 0x40); pub const VisualColormapSizeMask = @as(c_int, 0x80); pub const VisualBitsPerRGBMask = @as(c_int, 0x100); pub const VisualAllMask = @as(c_int, 0x1FF); pub const ReleaseByFreeingColormap = @import("std").zig.c_translation.cast(X.XID, @as(c_long, 1)); pub const BitmapSuccess = @as(c_int, 0); pub const BitmapOpenFailed = @as(c_int, 1); pub const BitmapFileInvalid = @as(c_int, 2); pub const BitmapNoMemory = @as(c_int, 3); pub const XCSUCCESS = @as(c_int, 0); pub const XCNOMEM = @as(c_int, 1); pub const XCNOENT = @as(c_int, 2); pub extern fn XLoadQueryFont(?*Display, [*c]const u8) [*c]XFontStruct; pub extern fn XQueryFont(?*Display, X.XID) [*c]XFontStruct; pub extern fn XGetMotionEvents(?*Display, X.Window, X.Time, X.Time, [*c]c_int) [*c]XTimeCoord; pub extern fn XDeleteModifiermapEntry([*c]XModifierKeymap, X.KeyCode, c_int) [*c]XModifierKeymap; pub extern fn XGetModifierMapping(?*Display) [*c]XModifierKeymap; pub extern fn XInsertModifiermapEntry([*c]XModifierKeymap, X.KeyCode, c_int) [*c]XModifierKeymap; pub extern fn XNewModifiermap(c_int) [*c]XModifierKeymap; pub extern fn XCreateImage(?*Display, [*c]Visual, c_uint, c_int, c_int, [*c]u8, c_uint, c_uint, c_int, c_int) [*c]XImage; pub extern fn XInitImage([*c]XImage) c_int; pub extern fn XGetImage(?*Display, X.Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int) [*c]XImage; pub extern fn XGetSubImage(?*Display, X.Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int, [*c]XImage, c_int, c_int) [*c]XImage; pub extern fn XOpenDisplay([*c]const u8) ?*Display; pub extern fn XrmInitialize() void; pub extern fn XFetchBytes(?*Display, [*c]c_int) [*c]u8; pub extern fn XFetchBuffer(?*Display, [*c]c_int, c_int) [*c]u8; pub extern fn XGetAtomName(?*Display, X.Atom) [*c]u8; pub extern fn XGetAtomNames(?*Display, [*c]X.Atom, c_int, [*c][*c]u8) c_int; pub extern fn XGetDefault(?*Display, [*c]const u8, [*c]const u8) [*c]u8; pub extern fn XDisplayName([*c]const u8) [*c]u8; pub extern fn XKeysymToString(X.KeySym) [*c]u8; pub extern fn XSynchronize(?*Display, c_int) ?fn (?*Display) callconv(.C) c_int; pub extern fn XSetAfterFunction(?*Display, ?fn (?*Display) callconv(.C) c_int) ?fn (?*Display) callconv(.C) c_int; pub extern fn XInternAtom(?*Display, [*c]const u8, c_int) X.Atom; pub extern fn XInternAtoms(?*Display, [*c][*c]u8, c_int, c_int, [*c]X.Atom) c_int; pub extern fn XCopyColormapAndFree(?*Display, X.Colormap) X.Colormap; pub extern fn XCreateColormap(?*Display, X.Window, [*c]Visual, c_int) X.Colormap; pub extern fn XCreatePixmapCursor(?*Display, X.Pixmap, X.Pixmap, [*c]XColor, [*c]XColor, c_uint, c_uint) X.Cursor; pub extern fn XCreateGlyphCursor(?*Display, X.Font, X.Font, c_uint, c_uint, [*c]const XColor, [*c]const XColor) X.Cursor; pub extern fn XCreateFontCursor(?*Display, c_uint) X.Cursor; pub extern fn XLoadFont(?*Display, [*c]const u8) X.Font; pub extern fn XCreateGC(?*Display, X.Drawable, c_ulong, [*c]XGCValues) GC; pub extern fn XGContextFromGC(GC) X.GContext; pub extern fn XFlushGC(?*Display, GC) void; pub extern fn XCreatePixmap(?*Display, X.Drawable, c_uint, c_uint, c_uint) X.Pixmap; pub extern fn XCreateBitmapFromData(?*Display, X.Drawable, [*c]const u8, c_uint, c_uint) X.Pixmap; pub extern fn XCreatePixmapFromBitmapData(?*Display, X.Drawable, [*c]u8, c_uint, c_uint, c_ulong, c_ulong, c_uint) X.Pixmap; pub extern fn XCreateSimpleWindow(?*Display, X.Window, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong) X.Window; pub extern fn XGetSelectionOwner(?*Display, X.Atom) X.Window; pub extern fn XCreateWindow(?*Display, X.Window, c_int, c_int, c_uint, c_uint, c_uint, c_int, c_uint, [*c]Visual, c_ulong, [*c]XSetWindowAttributes) X.Window; pub extern fn XListInstalledColormaps(?*Display, X.Window, [*c]c_int) [*c]X.Colormap; pub extern fn XListFonts(?*Display, [*c]const u8, c_int, [*c]c_int) [*c][*c]u8; pub extern fn XListFontsWithInfo(?*Display, [*c]const u8, c_int, [*c]c_int, [*c][*c]XFontStruct) [*c][*c]u8; pub extern fn XGetFontPath(?*Display, [*c]c_int) [*c][*c]u8; pub extern fn XListExtensions(?*Display, [*c]c_int) [*c][*c]u8; pub extern fn XListProperties(?*Display, X.Window, [*c]c_int) [*c]X.Atom; pub extern fn XListHosts(?*Display, [*c]c_int, [*c]c_int) [*c]XHostAddress; pub extern fn XKeycodeToKeysym(?*Display, X.KeyCode, c_int) X.KeySym; pub extern fn XLookupKeysym([*c]XKeyEvent, c_int) X.KeySym; pub extern fn XGetKeyboardMapping(?*Display, X.KeyCode, c_int, [*c]c_int) [*c]X.KeySym; pub extern fn XStringToKeysym([*c]const u8) X.KeySym; pub extern fn XMaxRequestSize(?*Display) c_long; pub extern fn XExtendedMaxRequestSize(?*Display) c_long; pub extern fn XResourceManagerString(?*Display) [*c]u8; pub extern fn XScreenResourceString([*c]Screen) [*c]u8; pub extern fn XDisplayMotionBufferSize(?*Display) c_ulong; pub extern fn XVisualIDFromVisual([*c]Visual) X.VisualID; pub extern fn XInitThreads() c_int; pub extern fn XLockDisplay(?*Display) void; pub extern fn XUnlockDisplay(?*Display) void; pub extern fn XInitExtension(?*Display, [*c]const u8) [*c]XExtCodes; pub extern fn XAddExtension(?*Display) [*c]XExtCodes; pub extern fn XFindOnExtensionList([*c][*c]XExtData, c_int) [*c]XExtData; pub extern fn XEHeadOfExtensionList(XEDataObject) [*c][*c]XExtData; pub extern fn XRootWindow(?*Display, c_int) X.Window; pub extern fn XDefaultRootWindow(?*Display) X.Window; pub extern fn XRootWindowOfScreen([*c]Screen) X.Window; pub extern fn XDefaultVisual(?*Display, c_int) [*c]Visual; pub extern fn XDefaultVisualOfScreen([*c]Screen) [*c]Visual; pub extern fn XDefaultGC(?*Display, c_int) GC; pub extern fn XDefaultGCOfScreen([*c]Screen) GC; pub extern fn XBlackPixel(?*Display, c_int) c_ulong; pub extern fn XWhitePixel(?*Display, c_int) c_ulong; pub extern fn XAllPlanes() c_ulong; pub extern fn XBlackPixelOfScreen([*c]Screen) c_ulong; pub extern fn XWhitePixelOfScreen([*c]Screen) c_ulong; pub extern fn XNextRequest(?*Display) c_ulong; pub extern fn XLastKnownRequestProcessed(?*Display) c_ulong; pub extern fn XServerVendor(?*Display) [*c]u8; pub extern fn XDisplayString(?*Display) [*c]u8; pub extern fn XDefaultColormap(?*Display, c_int) X.Colormap; pub extern fn XDefaultColormapOfScreen([*c]Screen) X.Colormap; pub extern fn XDisplayOfScreen([*c]Screen) ?*Display; pub extern fn XScreenOfDisplay(?*Display, c_int) [*c]Screen; pub extern fn XDefaultScreenOfDisplay(?*Display) [*c]Screen; pub extern fn XEventMaskOfScreen([*c]Screen) c_long; pub extern fn XScreenNumberOfScreen([*c]Screen) c_int; pub const XErrorHandler = ?fn (?*Display, [*c]XErrorEvent) callconv(.C) c_int; pub extern fn XSetErrorHandler(XErrorHandler) XErrorHandler; pub const XIOErrorHandler = ?fn (?*Display) callconv(.C) c_int; pub extern fn XSetIOErrorHandler(XIOErrorHandler) XIOErrorHandler; pub extern fn XSetIOErrorExitHandler(?*Display, XIOErrorExitHandler, ?*anyopaque) void; pub extern fn XListPixmapFormats(?*Display, [*c]c_int) [*c]XPixmapFormatValues; pub extern fn XListDepths(?*Display, c_int, [*c]c_int) [*c]c_int; pub extern fn XReconfigureWMWindow(?*Display, X.Window, c_int, c_uint, [*c]XWindowChanges) c_int; pub extern fn XGetWMProtocols(?*Display, X.Window, [*c][*c]X.Atom, [*c]c_int) c_int; pub extern fn XSetWMProtocols(?*Display, X.Window, [*c]X.Atom, c_int) c_int; pub extern fn XIconifyWindow(?*Display, X.Window, c_int) c_int; pub extern fn XWithdrawWindow(?*Display, X.Window, c_int) c_int; pub extern fn XGetCommand(?*Display, X.Window, [*c][*c][*c]u8, [*c]c_int) c_int; pub extern fn XGetWMColormapWindows(?*Display, X.Window, [*c][*c]X.Window, [*c]c_int) c_int; pub extern fn XSetWMColormapWindows(?*Display, X.Window, [*c]X.Window, c_int) c_int; pub extern fn XFreeStringList([*c][*c]u8) void; pub extern fn XSetTransientForHint(?*Display, X.Window, X.Window) c_int; pub extern fn XActivateScreenSaver(?*Display) c_int; pub extern fn XAddHost(?*Display, [*c]XHostAddress) c_int; pub extern fn XAddHosts(?*Display, [*c]XHostAddress, c_int) c_int; pub extern fn XAddToExtensionList([*c][*c]struct__XExtData, [*c]XExtData) c_int; pub extern fn XAddToSaveSet(?*Display, X.Window) c_int; pub extern fn XAllocColor(?*Display, X.Colormap, [*c]XColor) c_int; pub extern fn XAllocColorCells(?*Display, X.Colormap, c_int, [*c]c_ulong, c_uint, [*c]c_ulong, c_uint) c_int; pub extern fn XAllocColorPlanes(?*Display, X.Colormap, c_int, [*c]c_ulong, c_int, c_int, c_int, c_int, [*c]c_ulong, [*c]c_ulong, [*c]c_ulong) c_int; pub extern fn XAllocNamedColor(?*Display, X.Colormap, [*c]const u8, [*c]XColor, [*c]XColor) c_int; pub extern fn XAllowEvents(?*Display, c_int, X.Time) c_int; pub extern fn XAutoRepeatOff(?*Display) c_int; pub extern fn XAutoRepeatOn(?*Display) c_int; pub extern fn XBell(?*Display, c_int) c_int; pub extern fn XBitmapBitOrder(?*Display) c_int; pub extern fn XBitmapPad(?*Display) c_int; pub extern fn XBitmapUnit(?*Display) c_int; pub extern fn XCellsOfScreen([*c]Screen) c_int; pub extern fn XChangeActivePointerGrab(?*Display, c_uint, X.Cursor, X.Time) c_int; pub extern fn XChangeGC(?*Display, GC, c_ulong, [*c]XGCValues) c_int; pub extern fn XChangeKeyboardControl(?*Display, c_ulong, [*c]XKeyboardControl) c_int; pub extern fn XChangeKeyboardMapping(?*Display, c_int, c_int, [*c]X.KeySym, c_int) c_int; pub extern fn XChangePointerControl(?*Display, c_int, c_int, c_int, c_int, c_int) c_int; pub extern fn XChangeProperty(?*Display, X.Window, X.Atom, X.Atom, c_int, c_int, [*c]const u8, c_int) c_int; pub extern fn XChangeSaveSet(?*Display, X.Window, c_int) c_int; pub extern fn XChangeWindowAttributes(?*Display, X.Window, c_ulong, [*c]XSetWindowAttributes) c_int; pub extern fn XCheckIfEvent(?*Display, [*c]XEvent, ?fn (?*Display, [*c]XEvent, XPointer) callconv(.C) c_int, XPointer) c_int; pub extern fn XCheckMaskEvent(?*Display, c_long, [*c]XEvent) c_int; pub extern fn XCheckTypedEvent(?*Display, c_int, [*c]XEvent) c_int; pub extern fn XCheckTypedWindowEvent(?*Display, X.Window, c_int, [*c]XEvent) c_int; pub extern fn XCheckWindowEvent(?*Display, X.Window, c_long, [*c]XEvent) c_int; pub extern fn XCirculateSubwindows(?*Display, X.Window, c_int) c_int; pub extern fn XCirculateSubwindowsDown(?*Display, X.Window) c_int; pub extern fn XCirculateSubwindowsUp(?*Display, X.Window) c_int; pub extern fn XClearArea(?*Display, X.Window, c_int, c_int, c_uint, c_uint, c_int) c_int; pub extern fn XClearWindow(?*Display, X.Window) c_int; pub extern fn XCloseDisplay(?*Display) c_int; pub extern fn XConfigureWindow(?*Display, X.Window, c_uint, [*c]XWindowChanges) c_int; pub extern fn XConnectionNumber(?*Display) c_int; pub extern fn XConvertSelection(?*Display, X.Atom, X.Atom, X.Atom, X.Window, X.Time) c_int; pub extern fn XCopyArea(?*Display, X.Drawable, X.Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int) c_int; pub extern fn XCopyGC(?*Display, GC, c_ulong, GC) c_int; pub extern fn XCopyPlane(?*Display, X.Drawable, X.Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int, c_ulong) c_int; pub extern fn XDefaultDepth(?*Display, c_int) c_int; pub extern fn XDefaultDepthOfScreen([*c]Screen) c_int; pub extern fn XDefaultScreen(?*Display) c_int; pub extern fn XDefineCursor(?*Display, X.Window, X.Cursor) c_int; pub extern fn XDeleteProperty(?*Display, X.Window, X.Atom) c_int; pub extern fn XDestroyWindow(?*Display, X.Window) c_int; pub extern fn XDestroySubwindows(?*Display, X.Window) c_int; pub extern fn XDoesBackingStore([*c]Screen) c_int; pub extern fn XDoesSaveUnders([*c]Screen) c_int; pub extern fn XDisableAccessControl(?*Display) c_int; pub extern fn XDisplayCells(?*Display, c_int) c_int; pub extern fn XDisplayHeight(?*Display, c_int) c_int; pub extern fn XDisplayHeightMM(?*Display, c_int) c_int; pub extern fn XDisplayKeycodes(?*Display, [*c]c_int, [*c]c_int) c_int; pub extern fn XDisplayPlanes(?*Display, c_int) c_int; pub extern fn XDisplayWidth(?*Display, c_int) c_int; pub extern fn XDisplayWidthMM(?*Display, c_int) c_int; pub extern fn XDrawArc(?*Display, X.Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int) c_int; pub extern fn XDrawArcs(?*Display, X.Drawable, GC, [*c]XArc, c_int) c_int; pub extern fn XDrawImageString(?*Display, X.Drawable, GC, c_int, c_int, [*c]const u8, c_int) c_int; pub extern fn XDrawImageString16(?*Display, X.Drawable, GC, c_int, c_int, [*c]const XChar2b, c_int) c_int; pub extern fn XDrawLine(?*Display, X.Drawable, GC, c_int, c_int, c_int, c_int) c_int; pub extern fn XDrawLines(?*Display, X.Drawable, GC, [*c]XPoint, c_int, c_int) c_int; pub extern fn XDrawPoint(?*Display, X.Drawable, GC, c_int, c_int) c_int; pub extern fn XDrawPoints(?*Display, X.Drawable, GC, [*c]XPoint, c_int, c_int) c_int; pub extern fn XDrawRectangle(?*Display, X.Drawable, GC, c_int, c_int, c_uint, c_uint) c_int; pub extern fn XDrawRectangles(?*Display, X.Drawable, GC, [*c]XRectangle, c_int) c_int; pub extern fn XDrawSegments(?*Display, X.Drawable, GC, [*c]XSegment, c_int) c_int; pub extern fn XDrawString(?*Display, X.Drawable, GC, c_int, c_int, [*c]const u8, c_int) c_int; pub extern fn XDrawString16(?*Display, X.Drawable, GC, c_int, c_int, [*c]const XChar2b, c_int) c_int; pub extern fn XDrawText(?*Display, X.Drawable, GC, c_int, c_int, [*c]XTextItem, c_int) c_int; pub extern fn XDrawText16(?*Display, X.Drawable, GC, c_int, c_int, [*c]XTextItem16, c_int) c_int; pub extern fn XEnableAccessControl(?*Display) c_int; pub extern fn XEventsQueued(?*Display, c_int) c_int; pub extern fn XFetchName(?*Display, X.Window, [*c][*c]u8) c_int; pub extern fn XFillArc(?*Display, X.Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int) c_int; pub extern fn XFillArcs(?*Display, X.Drawable, GC, [*c]XArc, c_int) c_int; pub extern fn XFillPolygon(?*Display, X.Drawable, GC, [*c]XPoint, c_int, c_int, c_int) c_int; pub extern fn XFillRectangle(?*Display, X.Drawable, GC, c_int, c_int, c_uint, c_uint) c_int; pub extern fn XFillRectangles(?*Display, X.Drawable, GC, [*c]XRectangle, c_int) c_int; pub extern fn XFlush(?*Display) c_int; pub extern fn XForceScreenSaver(?*Display, c_int) c_int; pub extern fn XFree(?*anyopaque) c_int; pub extern fn XFreeColormap(?*Display, X.Colormap) c_int; pub extern fn XFreeColors(?*Display, X.Colormap, [*c]c_ulong, c_int, c_ulong) c_int; pub extern fn XFreeCursor(?*Display, X.Cursor) c_int; pub extern fn XFreeExtensionList([*c][*c]u8) c_int; pub extern fn XFreeFont(?*Display, [*c]XFontStruct) c_int; pub extern fn XFreeFontInfo([*c][*c]u8, [*c]XFontStruct, c_int) c_int; pub extern fn XFreeFontNames([*c][*c]u8) c_int; pub extern fn XFreeFontPath([*c][*c]u8) c_int; pub extern fn XFreeGC(?*Display, GC) c_int; pub extern fn XFreeModifiermap([*c]XModifierKeymap) c_int; pub extern fn XFreePixmap(?*Display, X.Pixmap) c_int; pub extern fn XGeometry(?*Display, c_int, [*c]const u8, [*c]const u8, c_uint, c_uint, c_uint, c_int, c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_int) c_int; pub extern fn XGetErrorDatabaseText(?*Display, [*c]const u8, [*c]const u8, [*c]const u8, [*c]u8, c_int) c_int; pub extern fn XGetErrorText(?*Display, c_int, [*c]u8, c_int) c_int; pub extern fn XGetFontProperty([*c]XFontStruct, X.Atom, [*c]c_ulong) c_int; pub extern fn XGetGCValues(?*Display, GC, c_ulong, [*c]XGCValues) c_int; pub extern fn XGetGeometry(?*Display, X.Drawable, [*c]X.Window, [*c]c_int, [*c]c_int, [*c]c_uint, [*c]c_uint, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XGetIconName(?*Display, X.Window, [*c][*c]u8) c_int; pub extern fn XGetInputFocus(?*Display, [*c]X.Window, [*c]c_int) c_int; pub extern fn XGetKeyboardControl(?*Display, [*c]XKeyboardState) c_int; pub extern fn XGetPointerControl(?*Display, [*c]c_int, [*c]c_int, [*c]c_int) c_int; pub extern fn XGetPointerMapping(?*Display, [*c]u8, c_int) c_int; pub extern fn XGetScreenSaver(?*Display, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_int) c_int; pub extern fn XGetTransientForHint(?*Display, X.Window, [*c]X.Window) c_int; pub extern fn XGetWindowProperty(?*Display, X.Window, X.Atom, c_long, c_long, c_int, X.Atom, [*c]X.Atom, [*c]c_int, [*c]c_ulong, [*c]c_ulong, [*c][*c]u8) c_int; pub extern fn XGetWindowAttributes(?*Display, X.Window, [*c]XWindowAttributes) c_int; pub extern fn XGrabButton(?*Display, c_uint, c_uint, X.Window, c_int, c_uint, c_int, c_int, X.Window, X.Cursor) c_int; pub extern fn XGrabKey(?*Display, c_int, c_uint, X.Window, c_int, c_int, c_int) c_int; pub extern fn XGrabKeyboard(?*Display, X.Window, c_int, c_int, c_int, X.Time) c_int; pub extern fn XGrabPointer(?*Display, X.Window, c_int, c_uint, c_int, c_int, .XWindow, X.Cursor, X.Time) c_int; pub extern fn XGrabServer(?*Display) c_int; pub extern fn XHeightMMOfScreen([*c]Screen) c_int; pub extern fn XHeightOfScreen([*c]Screen) c_int; pub extern fn XIfEvent(?*Display, [*c]XEvent, ?fn (?*Display, [*c]XEvent, XPointer) callconv(.C) c_int, XPointer) c_int; pub extern fn XImageByteOrder(?*Display) c_int; pub extern fn XInstallColormap(?*Display, X.Colormap) c_int; pub extern fn XKeysymToKeycode(?*Display, X.KeySym) X.KeyCode; pub extern fn XKillClient(?*Display, X.XID) c_int; pub extern fn XLookupColor(?*Display, X.Colormap, [*c]const u8, [*c]XColor, [*c]XColor) c_int; pub extern fn XLowerWindow(?*Display, X.Window) c_int; pub extern fn XMapRaised(?*Display, X.Window) c_int; pub extern fn XMapSubwindows(?*Display, X.Window) c_int; pub extern fn XMapWindow(?*Display, X.Window) c_int; pub extern fn XMaskEvent(?*Display, c_long, [*c]XEvent) c_int; pub extern fn XMaxCmapsOfScreen([*c]Screen) c_int; pub extern fn XMinCmapsOfScreen([*c]Screen) c_int; pub extern fn XMoveResizeWindow(?*Display, X.Window, c_int, c_int, c_uint, c_uint) c_int; pub extern fn XMoveWindow(?*Display, X.Window, c_int, c_int) c_int; pub extern fn XNextEvent(?*Display, [*c]XEvent) c_int; pub extern fn XNoOp(?*Display) c_int; pub extern fn XParseColor(?*Display, X.Colormap, [*c]const u8, [*c]XColor) c_int; pub extern fn XParseGeometry([*c]const u8, [*c]c_int, [*c]c_int, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XPeekEvent(?*Display, [*c]XEvent) c_int; pub extern fn XPeekIfEvent(?*Display, [*c]XEvent, ?fn (?*Display, [*c]XEvent, XPointer) callconv(.C) c_int, XPointer) c_int; pub extern fn XPending(?*Display) c_int; pub extern fn XPlanesOfScreen([*c]Screen) c_int; pub extern fn XProtocolRevision(?*Display) c_int; pub extern fn XProtocolVersion(?*Display) c_int; pub extern fn XPutBackEvent(?*Display, [*c]XEvent) c_int; pub extern fn XPutImage(?*Display, X.Drawable, GC, [*c]XImage, c_int, c_int, c_int, c_int, c_uint, c_uint) c_int; pub extern fn XQLength(?*Display) c_int; pub extern fn XQueryBestCursor(?*Display, X.Drawable, c_uint, c_uint, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XQueryBestSize(?*Display, c_int, X.Drawable, c_uint, c_uint, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XQueryBestStipple(?*Display, X.Drawable, c_uint, c_uint, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XQueryBestTile(?*Display, X.Drawable, c_uint, c_uint, [*c]c_uint, [*c]c_uint) c_int; pub extern fn XQueryColor(?*Display, X.Colormap, [*c]XColor) c_int; pub extern fn XQueryColors(?*Display, X.Colormap, [*c]XColor, c_int) c_int; pub extern fn XQueryExtension(?*Display, [*c]const u8, [*c]c_int, [*c]c_int, [*c]c_int) c_int; pub extern fn XQueryKeymap(?*Display, [*c]u8) c_int; pub extern fn XQueryPointer(?*Display, X.Window, [*c]X.Window, [*c]X.Window, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]c_uint) c_int; pub extern fn XQueryTextExtents(?*Display, X.XID, [*c]const u8, c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]XCharStruct) c_int; pub extern fn XQueryTextExtents16(?*Display, X.XID, [*c]const XChar2b, c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]XCharStruct) c_int; pub extern fn XQueryTree(?*Display, X.Window, [*c]X.Window, [*c]X.Window, [*c][*c]X.Window, [*c]c_uint) c_int; pub extern fn XRaiseWindow(?*Display, X.Window) c_int; pub extern fn XReadBitmapFile(?*Display, X.Drawable, [*c]const u8, [*c]c_uint, [*c]c_uint, [*c]X.Pixmap, [*c]c_int, [*c]c_int) c_int; pub extern fn XReadBitmapFileData([*c]const u8, [*c]c_uint, [*c]c_uint, [*c][*c]u8, [*c]c_int, [*c]c_int) c_int; pub extern fn XRebindKeysym(?*Display, X.KeySym, [*c]X.KeySym, c_int, [*c]const u8, c_int) c_int; pub extern fn XRecolorCursor(?*Display, X.Cursor, [*c]XColor, [*c]XColor) c_int; pub extern fn XRefreshKeyboardMapping([*c]XMappingEvent) c_int; pub extern fn XRemoveFromSaveSet(?*Display, X.Window) c_int; pub extern fn XRemoveHost(?*Display, [*c]XHostAddress) c_int; pub extern fn XRemoveHosts(?*Display, [*c]XHostAddress, c_int) c_int; pub extern fn XReparentWindow(?*Display, X.Window, X.Window, c_int, c_int) c_int; pub extern fn XResetScreenSaver(?*Display) c_int; pub extern fn XResizeWindow(?*Display, X.Window, c_uint, c_uint) c_int; pub extern fn XRestackWindows(?*Display, [*c]X.Window, c_int) c_int; pub extern fn XRotateBuffers(?*Display, c_int) c_int; pub extern fn XRotateWindowProperties(?*Display, X.Window, [*c]X.Atom, c_int, c_int) c_int; pub extern fn XScreenCount(?*Display) c_int; pub extern fn XSelectInput(?*Display, X.Window, c_long) c_int; pub extern fn XSendEvent(?*Display, X.Window, c_int, c_long, [*c]XEvent) c_int; pub extern fn XSetAccessControl(?*Display, c_int) c_int; pub extern fn XSetArcMode(?*Display, GC, c_int) c_int; pub extern fn XSetBackground(?*Display, GC, c_ulong) c_int; pub extern fn XSetClipMask(?*Display, GC, X.Pixmap) c_int; pub extern fn XSetClipOrigin(?*Display, GC, c_int, c_int) c_int; pub extern fn XSetClipRectangles(?*Display, GC, c_int, c_int, [*c]XRectangle, c_int, c_int) c_int; pub extern fn XSetCloseDownMode(?*Display, c_int) c_int; pub extern fn XSetCommand(?*Display, X.Window, [*c][*c]u8, c_int) c_int; pub extern fn XSetDashes(?*Display, GC, c_int, [*c]const u8, c_int) c_int; pub extern fn XSetFillRule(?*Display, GC, c_int) c_int; pub extern fn XSetFillStyle(?*Display, GC, c_int) c_int; pub extern fn XSetFont(?*Display, GC, X.Font) c_int; pub extern fn XSetFontPath(?*Display, [*c][*c]u8, c_int) c_int; pub extern fn XSetForeground(?*Display, GC, c_ulong) c_int; pub extern fn XSetFunction(?*Display, GC, c_int) c_int; pub extern fn XSetGraphicsExposures(?*Display, GC, c_int) c_int; pub extern fn XSetIconName(?*Display, X.Window, [*c]const u8) c_int; pub extern fn XSetInputFocus(?*Display, X.Window, c_int, X.Time) c_int; pub extern fn XSetLineAttributes(?*Display, GC, c_uint, c_int, c_int, c_int) c_int; pub extern fn XSetModifierMapping(?*Display, [*c]XModifierKeymap) c_int; pub extern fn XSetPlaneMask(?*Display, GC, c_ulong) c_int; pub extern fn XSetPointerMapping(?*Display, [*c]const u8, c_int) c_int; pub extern fn XSetScreenSaver(?*Display, c_int, c_int, c_int, c_int) c_int; pub extern fn XSetSelectionOwner(?*Display, X.Atom, X.Window, X.Time) c_int; pub extern fn XSetState(?*Display, GC, c_ulong, c_ulong, c_int, c_ulong) c_int; pub extern fn XSetStipple(?*Display, GC, X.Pixmap) c_int; pub extern fn XSetSubwindowMode(?*Display, GC, c_int) c_int; pub extern fn XSetTSOrigin(?*Display, GC, c_int, c_int) c_int; pub extern fn XSetTile(?*Display, GC, X.Pixmap) c_int; pub extern fn XSetWindowBackground(?*Display, X.Window, c_ulong) c_int; pub extern fn XSetWindowBackgroundPixmap(?*Display, X.Window, X.Pixmap) c_int; pub extern fn XSetWindowBorder(?*Display, X.Window, c_ulong) c_int; pub extern fn XSetWindowBorderPixmap(?*Display, X.Window, X.Pixmap) c_int; pub extern fn XSetWindowBorderWidth(?*Display, X.Window, c_uint) c_int; pub extern fn XSetWindowColormap(?*Display, X.Window, X.Colormap) c_int; pub extern fn XStoreBuffer(?*Display, [*c]const u8, c_int, c_int) c_int; pub extern fn XStoreBytes(?*Display, [*c]const u8, c_int) c_int; pub extern fn XStoreColor(?*Display, X.Colormap, [*c]XColor) c_int; pub extern fn XStoreColors(?*Display, X.Colormap, [*c]XColor, c_int) c_int; pub extern fn XStoreName(?*Display, X.Window, [*c]const u8) c_int; pub extern fn XStoreNamedColor(?*Display, X.Colormap, [*c]const u8, c_ulong, c_int) c_int; pub extern fn XSync(?*Display, c_int) c_int; pub extern fn XTextExtents([*c]XFontStruct, [*c]const u8, c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]XCharStruct) c_int; pub extern fn XTextExtents16([*c]XFontStruct, [*c]const XChar2b, c_int, [*c]c_int, [*c]c_int, [*c]c_int, [*c]XCharStruct) c_int; pub extern fn XTextWidth([*c]XFontStruct, [*c]const u8, c_int) c_int; pub extern fn XTextWidth16([*c]XFontStruct, [*c]const XChar2b, c_int) c_int; pub extern fn XTranslateCoordinates(?*Display, X.Window, X.Window, c_int, c_int, [*c]c_int, [*c]c_int, [*c]X.Window) c_int; pub extern fn XUndefineCursor(?*Display, X.Window) c_int; pub extern fn XUngrabButton(?*Display, c_uint, c_uint, X.Window) c_int; pub extern fn XUngrabKey(?*Display, c_int, c_uint, X.Window) c_int; pub extern fn XUngrabKeyboard(?*Display, X.Time) c_int; pub extern fn XUngrabPointer(?*Display, X.Time) c_int; pub extern fn XUngrabServer(?*Display) c_int; pub extern fn XUninstallColormap(?*Display, X.Colormap) c_int; pub extern fn XUnloadFont(?*Display, X.Font) c_int; pub extern fn XUnmapSubwindows(?*Display, X.Window) c_int; pub extern fn XUnmapWindow(?*Display, X.Window) c_int; pub extern fn XVendorRelease(?*Display) c_int; pub extern fn XWarpPointer(?*Display, X.Window, X.Window, c_int, c_int, c_uint, c_uint, c_int, c_int) c_int; pub extern fn XWidthMMOfScreen([*c]Screen) c_int; pub extern fn XWidthOfScreen([*c]Screen) c_int; pub extern fn XWindowEvent(?*Display, X.Window, c_long, [*c]XEvent) c_int; pub extern fn XWriteBitmapFile(?*Display, [*c]const u8, X.Pixmap, c_uint, c_uint, c_int, c_int) c_int; pub extern fn XSupportsLocale() c_int; pub extern fn XSetLocaleModifiers([*c]const u8) [*c]u8; pub extern fn XOpenOM(?*Display, ?*struct__XrmHashBucketRec, [*c]const u8, [*c]const u8) XOM; pub extern fn XCloseOM(XOM) c_int; pub extern fn XSetOMValues(XOM, ...) [*c]u8; pub extern fn XGetOMValues(XOM, ...) [*c]u8; pub extern fn XDisplayOfOM(XOM) ?*Display; pub extern fn XLocaleOfOM(XOM) [*c]u8; pub extern fn XCreateOC(XOM, ...) XOC; pub extern fn XDestroyOC(XOC) void; pub extern fn XOMOfOC(XOC) XOM; pub extern fn XSetOCValues(XOC, ...) [*c]u8; pub extern fn XGetOCValues(XOC, ...) [*c]u8; pub extern fn XCreateFontSet(?*Display, [*c]const u8, [*c][*c][*c]u8, [*c]c_int, [*c][*c]u8) XFontSet; pub extern fn XFreeFontSet(?*Display, XFontSet) void; pub extern fn XFontsOfFontSet(XFontSet, [*c][*c][*c]XFontStruct, [*c][*c][*c]u8) c_int; pub extern fn XBaseFontNameListOfFontSet(XFontSet) [*c]u8; pub extern fn XLocaleOfFontSet(XFontSet) [*c]u8; pub extern fn XContextDependentDrawing(XFontSet) c_int; pub extern fn XDirectionalDependentDrawing(XFontSet) c_int; pub extern fn XContextualDrawing(XFontSet) c_int; pub extern fn XExtentsOfFontSet(XFontSet) [*c]XFontSetExtents; pub extern fn XmbTextEscapement(XFontSet, [*c]const u8, c_int) c_int; pub extern fn XwcTextEscapement(XFontSet, [*c]const wchar_t, c_int) c_int; pub extern fn Xutf8TextEscapement(XFontSet, [*c]const u8, c_int) c_int; pub extern fn XmbTextExtents(XFontSet, [*c]const u8, c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn XwcTextExtents(XFontSet, [*c]const wchar_t, c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn Xutf8TextExtents(XFontSet, [*c]const u8, c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn XmbTextPerCharExtents(XFontSet, [*c]const u8, c_int, [*c]XRectangle, [*c]XRectangle, c_int, [*c]c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn XwcTextPerCharExtents(XFontSet, [*c]const wchar_t, c_int, [*c]XRectangle, [*c]XRectangle, c_int, [*c]c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn Xutf8TextPerCharExtents(XFontSet, [*c]const u8, c_int, [*c]XRectangle, [*c]XRectangle, c_int, [*c]c_int, [*c]XRectangle, [*c]XRectangle) c_int; pub extern fn XmbDrawText(?*Display, X.Drawable, GC, c_int, c_int, [*c]XmbTextItem, c_int) void; pub extern fn XwcDrawText(?*Display, X.Drawable, GC, c_int, c_int, [*c]XwcTextItem, c_int) void; pub extern fn Xutf8DrawText(?*Display, X.Drawable, GC, c_int, c_int, [*c]XmbTextItem, c_int) void; pub extern fn XmbDrawString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const u8, c_int) void; pub extern fn XwcDrawString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const wchar_t, c_int) void; pub extern fn Xutf8DrawString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const u8, c_int) void; pub extern fn XmbDrawImageString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const u8, c_int) void; pub extern fn XwcDrawImageString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const wchar_t, c_int) void; pub extern fn Xutf8DrawImageString(?*Display, X.Drawable, XFontSet, GC, c_int, c_int, [*c]const u8, c_int) void; pub extern fn XOpenIM(?*Display, ?*struct__XrmHashBucketRec, [*c]u8, [*c]u8) XIM; pub extern fn XCloseIM(XIM) c_int; pub extern fn XGetIMValues(XIM, ...) [*c]u8; pub extern fn XSetIMValues(XIM, ...) [*c]u8; pub extern fn XDisplayOfIM(XIM) ?*Display; pub extern fn XLocaleOfIM(XIM) [*c]u8; pub extern fn XCreateIC(XIM, ...) XIC; pub extern fn XDestroyIC(XIC) void; pub extern fn XSetICFocus(XIC) void; pub extern fn XUnsetICFocus(XIC) void; pub extern fn XwcResetIC(XIC) [*c]wchar_t; pub extern fn XmbResetIC(XIC) [*c]u8; pub extern fn Xutf8ResetIC(XIC) [*c]u8; pub extern fn XSetICValues(XIC, ...) [*c]u8; pub extern fn XGetICValues(XIC, ...) [*c]u8; pub extern fn XIMOfIC(XIC) XIM; pub extern fn XFilterEvent([*c]XEvent, X.Window) c_int; pub extern fn XmbLookupString(XIC, [*c]XKeyPressedEvent, [*c]u8, c_int, [*c]X.KeySym, [*c]c_int) c_int; pub extern fn XwcLookupString(XIC, [*c]XKeyPressedEvent, [*c]wchar_t, c_int, [*c]X.KeySym, [*c]c_int) c_int; pub extern fn Xutf8LookupString(XIC, [*c]XKeyPressedEvent, [*c]u8, c_int, [*c]X.KeySym, [*c]c_int) c_int; pub extern fn XVaCreateNestedList(c_int, ...) XVaNestedList; pub extern fn XRegisterIMInstantiateCallback(?*Display, ?*struct__XrmHashBucketRec, [*c]u8, [*c]u8, X.XIDProc, XPointer) c_int; pub extern fn XUnregisterIMInstantiateCallback(?*Display, ?*struct__XrmHashBucketRec, [*c]u8, [*c]u8, X.XIDProc, XPointer) c_int; pub extern fn XInternalConnectionNumbers(?*Display, [*c][*c]c_int, [*c]c_int) c_int; pub extern fn XProcessInternalConnection(?*Display, c_int) void; pub extern fn XAddConnectionWatch(?*Display, XConnectionWatchProc, XPointer) c_int; pub extern fn XRemoveConnectionWatch(?*Display, XConnectionWatchProc, XPointer) void; pub extern fn XSetAuthorization([*c]u8, c_int, [*c]u8, c_int) void; pub extern fn _Xmbtowc([*c]wchar_t, [*c]u8, c_int) c_int; pub extern fn _Xwctomb([*c]u8, wchar_t) c_int; pub extern fn XGetEventData(?*Display, [*c]XGenericEventCookie) c_int; pub extern fn XFreeEventData(?*Display, [*c]XGenericEventCookie) void; pub inline fn ConnectionNumber(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.fd) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.fd; } pub inline fn RootWindow(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.root) { return ScreenOfDisplay(dpy, scr).*.root; } pub inline fn DefaultScreen(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen; } pub inline fn DefaultRootWindow(dpy: anytype) @TypeOf(ScreenOfDisplay(dpy, DefaultScreen(dpy)).*.root) { return ScreenOfDisplay(dpy, DefaultScreen(dpy)).*.root; } pub inline fn DefaultVisual(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.root_visual) { return ScreenOfDisplay(dpy, scr).*.root_visual; } pub inline fn DefaultGC(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.default_gc) { return ScreenOfDisplay(dpy, scr).*.default_gc; } pub inline fn BlackPixel(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.black_pixel) { return ScreenOfDisplay(dpy, scr).*.black_pixel; } pub inline fn WhitePixel(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.white_pixel) { return ScreenOfDisplay(dpy, scr).*.white_pixel; } pub const AllPlanes = @import("std").zig.c_translation.cast(c_ulong, ~@as(c_long, 0)); pub inline fn QLength(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.qlen) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.qlen; } pub inline fn DisplayWidth(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.width) { return ScreenOfDisplay(dpy, scr).*.width; } pub inline fn DisplayHeight(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.height) { return ScreenOfDisplay(dpy, scr).*.height; } pub inline fn DisplayWidthMM(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.mwidth) { return ScreenOfDisplay(dpy, scr).*.mwidth; } pub inline fn DisplayHeightMM(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.mheight) { return ScreenOfDisplay(dpy, scr).*.mheight; } pub inline fn DisplayPlanes(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.root_depth) { return ScreenOfDisplay(dpy, scr).*.root_depth; } pub inline fn DisplayCells(dpy: anytype, scr: anytype) @TypeOf(DefaultVisual(dpy, scr).*.map_entries) { return DefaultVisual(dpy, scr).*.map_entries; } pub inline fn ScreenCount(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.nscreens) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.nscreens; } pub inline fn ServerVendor(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.vendor) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.vendor; } pub inline fn ProtocolVersion(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.proto_major_version) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.proto_major_version; } pub inline fn ProtocolRevision(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.proto_minor_version) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.proto_minor_version; } pub inline fn VendorRelease(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.release) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.release; } pub inline fn DisplayString(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.display_name) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.display_name; } pub inline fn DefaultDepth(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.root_depth) { return ScreenOfDisplay(dpy, scr).*.root_depth; } pub inline fn DefaultColormap(dpy: anytype, scr: anytype) @TypeOf(ScreenOfDisplay(dpy, scr).*.cmap) { return ScreenOfDisplay(dpy, scr).*.cmap; } pub inline fn BitmapUnit(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_unit) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_unit; } pub inline fn BitmapBitOrder(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_bit_order) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_bit_order; } pub inline fn BitmapPad(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_pad) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.bitmap_pad; } pub inline fn ImageByteOrder(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.byte_order) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.byte_order; } pub inline fn NextRequest(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.request + @as(c_int, 1)) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.request + @as(c_int, 1); } pub inline fn LastKnownRequestProcessed(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.last_request_read) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.last_request_read; } pub inline fn ScreenOfDisplay(dpy: anytype, scr: anytype) @TypeOf(&@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.screens[scr]) { return &@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.screens[scr]; } pub inline fn DefaultScreenOfDisplay(dpy: anytype) @TypeOf(ScreenOfDisplay(dpy, DefaultScreen(dpy))) { return ScreenOfDisplay(dpy, DefaultScreen(dpy)); } pub inline fn DisplayOfScreen(s: anytype) @TypeOf(s.*.display) { return s.*.display; } pub inline fn RootWindowOfScreen(s: anytype) @TypeOf(s.*.root) { return s.*.root; } pub inline fn BlackPixelOfScreen(s: anytype) @TypeOf(s.*.black_pixel) { return s.*.black_pixel; } pub inline fn WhitePixelOfScreen(s: anytype) @TypeOf(s.*.white_pixel) { return s.*.white_pixel; } pub inline fn DefaultColormapOfScreen(s: anytype) @TypeOf(s.*.cmap) { return s.*.cmap; } pub inline fn DefaultDepthOfScreen(s: anytype) @TypeOf(s.*.root_depth) { return s.*.root_depth; } pub inline fn DefaultGCOfScreen(s: anytype) @TypeOf(s.*.default_gc) { return s.*.default_gc; } pub inline fn DefaultVisualOfScreen(s: anytype) @TypeOf(s.*.root_visual) { return s.*.root_visual; } pub inline fn WidthOfScreen(s: anytype) @TypeOf(s.*.width) { return s.*.width; } pub inline fn HeightOfScreen(s: anytype) @TypeOf(s.*.height) { return s.*.height; } pub inline fn WidthMMOfScreen(s: anytype) @TypeOf(s.*.mwidth) { return s.*.mwidth; } pub inline fn HeightMMOfScreen(s: anytype) @TypeOf(s.*.mheight) { return s.*.mheight; } pub inline fn PlanesOfScreen(s: anytype) @TypeOf(s.*.root_depth) { return s.*.root_depth; } pub inline fn CellsOfScreen(s: anytype) @TypeOf(DefaultVisualOfScreen(s).*.map_entries) { return DefaultVisualOfScreen(s).*.map_entries; } pub inline fn MinCmapsOfScreen(s: anytype) @TypeOf(s.*.min_maps) { return s.*.min_maps; } pub inline fn MaxCmapsOfScreen(s: anytype) @TypeOf(s.*.max_maps) { return s.*.max_maps; } pub inline fn DoesSaveUnders(s: anytype) @TypeOf(s.*.save_unders) { return s.*.save_unders; } pub inline fn DoesBackingStore(s: anytype) @TypeOf(s.*.backing_store) { return s.*.backing_store; } pub inline fn EventMaskOfScreen(s: anytype) @TypeOf(s.*.root_input_mask) { return s.*.root_input_mask; } pub inline fn XAllocID(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.resource_alloc.*(dpy)) { return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.resource_alloc.*(dpy); } pub extern fn _Xmblen(str: [*c]u8, len: c_int) c_int; pub const XPointer = [*c]u8; pub const struct__XExtData = extern struct { number: c_int, next: [*c]struct__XExtData, free_private: ?fn ([*c]struct__XExtData) callconv(.C) c_int, private_data: XPointer, }; pub const XExtData = struct__XExtData; pub const XExtCodes = extern struct { extension: c_int, major_opcode: c_int, first_event: c_int, first_error: c_int, }; pub const XPixmapFormatValues = extern struct { depth: c_int, bits_per_pixel: c_int, scanline_pad: c_int, }; pub const XGCValues = extern struct { function: c_int, plane_mask: c_ulong, foreground: c_ulong, background: c_ulong, line_width: c_int, line_style: c_int, cap_style: c_int, join_style: c_int, fill_style: c_int, fill_rule: c_int, arc_mode: c_int, tile: X.Pixmap, stipple: X.Pixmap, ts_x_origin: c_int, ts_y_origin: c_int, font: X.Font, subwindow_mode: c_int, graphics_exposures: c_int, clip_x_origin: c_int, clip_y_origin: c_int, clip_mask: X.Pixmap, dash_offset: c_int, dashes: u8, }; pub const struct__XGC = opaque {}; pub const GC = ?*struct__XGC; pub const Visual = extern struct { ext_data: [*c]XExtData, visualid: X.VisualID, class: c_int, red_mask: c_ulong, green_mask: c_ulong, blue_mask: c_ulong, bits_per_rgb: c_int, map_entries: c_int, }; pub const Depth = extern struct { depth: c_int, nvisuals: c_int, visuals: [*c]Visual, }; pub const Screen = extern struct { ext_data: [*c]XExtData, display: ?*struct__XDisplay, root: X.Window, width: c_int, height: c_int, mwidth: c_int, mheight: c_int, ndepths: c_int, depths: [*c]Depth, root_depth: c_int, root_visual: [*c]Visual, default_gc: GC, cmap: X.Colormap, white_pixel: c_ulong, black_pixel: c_ulong, max_maps: c_int, min_maps: c_int, backing_store: c_int, save_unders: c_int, root_input_mask: c_long, }; pub const ScreenFormat = extern struct { ext_data: [*c]XExtData, depth: c_int, bits_per_pixel: c_int, scanline_pad: c_int, }; pub const XSetWindowAttributes = extern struct { background_pixmap: X.Pixmap, background_pixel: c_ulong, border_pixmap: X.Pixmap, border_pixel: c_ulong, bit_gravity: c_int, win_gravity: c_int, backing_store: c_int, backing_planes: c_ulong, backing_pixel: c_ulong, save_under: c_int, event_mask: c_long, do_not_propagate_mask: c_long, override_redirect: c_int, colormap: X.Colormap, cursor: X.Cursor, }; pub const XWindowAttributes = extern struct { x: c_int, y: c_int, width: c_int, height: c_int, border_width: c_int, depth: c_int, visual: [*c]Visual, root: X.Window, class: c_int, bit_gravity: c_int, win_gravity: c_int, backing_store: c_int, backing_planes: c_ulong, backing_pixel: c_ulong, save_under: c_int, colormap: X.Colormap, map_installed: c_int, map_state: c_int, all_event_masks: c_long, your_event_mask: c_long, do_not_propagate_mask: c_long, override_redirect: c_int, screen: [*c]Screen, }; pub const XHostAddress = extern struct { family: c_int, length: c_int, address: [*c]u8, }; pub const XServerInterpretedAddress = extern struct { typelength: c_int, valuelength: c_int, type: [*c]u8, value: [*c]u8, }; pub const struct_funcs = extern struct { create_image: ?fn (?*struct__XDisplay, [*c]Visual, c_uint, c_int, c_int, [*c]u8, c_uint, c_uint, c_int, c_int) callconv(.C) [*c]struct__XImage, destroy_image: ?fn ([*c]struct__XImage) callconv(.C) c_int, get_pixel: ?fn ([*c]struct__XImage, c_int, c_int) callconv(.C) c_ulong, put_pixel: ?fn ([*c]struct__XImage, c_int, c_int, c_ulong) callconv(.C) c_int, sub_image: ?fn ([*c]struct__XImage, c_int, c_int, c_uint, c_uint) callconv(.C) [*c]struct__XImage, add_pixel: ?fn ([*c]struct__XImage, c_long) callconv(.C) c_int, }; pub const struct__XImage = extern struct { width: c_int, height: c_int, xoffset: c_int, format: c_int, data: [*c]u8, byte_order: c_int, bitmap_unit: c_int, bitmap_bit_order: c_int, bitmap_pad: c_int, depth: c_int, bytes_per_line: c_int, bits_per_pixel: c_int, red_mask: c_ulong, green_mask: c_ulong, blue_mask: c_ulong, obdata: XPointer, f: struct_funcs, }; pub const XImage = struct__XImage; pub const XWindowChanges = extern struct { x: c_int, y: c_int, width: c_int, height: c_int, border_width: c_int, sibling: X.Window, stack_mode: c_int, }; pub const XColor = extern struct { pixel: c_ulong, red: c_ushort, green: c_ushort, blue: c_ushort, flags: u8, pad: u8, }; pub const XSegment = extern struct { x1: c_short, y1: c_short, x2: c_short, y2: c_short, }; pub const XPoint = extern struct { x: c_short, y: c_short, }; pub const XRectangle = extern struct { x: c_short, y: c_short, width: c_ushort, height: c_ushort, }; pub const XArc = extern struct { x: c_short, y: c_short, width: c_ushort, height: c_ushort, angle1: c_short, angle2: c_short, }; pub const XKeyboardControl = extern struct { key_click_percent: c_int, bell_percent: c_int, bell_pitch: c_int, bell_duration: c_int, led: c_int, led_mode: c_int, key: c_int, auto_repeat_mode: c_int, }; pub const XKeyboardState = extern struct { key_click_percent: c_int, bell_percent: c_int, bell_pitch: c_uint, bell_duration: c_uint, led_mask: c_ulong, global_auto_repeat: c_int, auto_repeats: [32]u8, }; pub const XTimeCoord = extern struct { time: X.Time, x: c_short, y: c_short, }; pub const XModifierKeymap = extern struct { max_keypermod: c_int, modifiermap: [*c]X.KeyCode, }; pub const Display = struct__XDisplay; pub const struct__XrmHashBucketRec = opaque {}; const struct_unnamed_1 = extern struct { ext_data: [*c]XExtData, private1: ?*struct__XPrivate, fd: c_int, private2: c_int, proto_major_version: c_int, proto_minor_version: c_int, vendor: [*c]u8, private3: X.XID, private4: X.XID, private5: X.XID, private6: c_int, resource_alloc: ?fn (?*struct__XDisplay) callconv(.C) X.XID, byte_order: c_int, bitmap_unit: c_int, bitmap_pad: c_int, bitmap_bit_order: c_int, nformats: c_int, pixmap_format: [*c]ScreenFormat, private8: c_int, release: c_int, private9: ?*struct__XPrivate, private10: ?*struct__XPrivate, qlen: c_int, last_request_read: c_ulong, request: c_ulong, private11: XPointer, private12: XPointer, private13: XPointer, private14: XPointer, max_request_size: c_uint, db: ?*struct__XrmHashBucketRec, private15: ?fn (?*struct__XDisplay) callconv(.C) c_int, display_name: [*c]u8, default_screen: c_int, nscreens: c_int, screens: [*c]Screen, motion_buffer: c_ulong, private16: c_ulong, min_keycode: c_int, max_keycode: c_int, private17: XPointer, private18: XPointer, private19: c_int, xdefaults: [*c]u8, }; pub const _XPrivDisplay = [*c]struct_unnamed_1; pub const XKeyEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, root: X.Window, subwindow: X.Window, time: X.Time, x: c_int, y: c_int, x_root: c_int, y_root: c_int, state: c_uint, keycode: c_uint, same_screen: c_int, }; pub const XKeyPressedEvent = XKeyEvent; pub const XKeyReleasedEvent = XKeyEvent; pub const XButtonEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, root: X.Window, subwindow: X.Window, time: X.Time, x: c_int, y: c_int, x_root: c_int, y_root: c_int, state: c_uint, button: c_uint, same_screen: c_int, }; pub const XButtonPressedEvent = XButtonEvent; pub const XButtonReleasedEvent = XButtonEvent; pub const XMotionEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, root: X.Window, subwindow: X.Window, time: X.Time, x: c_int, y: c_int, x_root: c_int, y_root: c_int, state: c_uint, is_hint: u8, same_screen: c_int, }; pub const XPointerMovedEvent = XMotionEvent; pub const XCrossingEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, root: X.Window, subwindow: X.Window, time: X.Time, x: c_int, y: c_int, x_root: c_int, y_root: c_int, mode: c_int, detail: c_int, same_screen: c_int, focus: c_int, state: c_uint, }; pub const XEnterWindowEvent = XCrossingEvent; pub const XLeaveWindowEvent = XCrossingEvent; pub const XFocusChangeEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, mode: c_int, detail: c_int, }; pub const XFocusInEvent = XFocusChangeEvent; pub const XFocusOutEvent = XFocusChangeEvent; pub const XKeymapEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, key_vector: [32]u8, }; pub const XExposeEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, x: c_int, y: c_int, width: c_int, height: c_int, count: c_int, }; pub const XGraphicsExposeEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, drawable: X.Drawable, x: c_int, y: c_int, width: c_int, height: c_int, count: c_int, major_code: c_int, minor_code: c_int, }; pub const XNoExposeEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, drawable: X.Drawable, major_code: c_int, minor_code: c_int, }; pub const XVisibilityEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, state: c_int, }; pub const XCreateWindowEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, parent: X.Window, window: X.Window, x: c_int, y: c_int, width: c_int, height: c_int, border_width: c_int, override_redirect: c_int, }; pub const XDestroyWindowEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, }; pub const XUnmapEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, from_configure: c_int, }; pub const XMapEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, override_redirect: c_int, }; pub const XMapRequestEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, parent: X.Window, window: X.Window, }; pub const XReparentEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, parent: X.Window, x: c_int, y: c_int, override_redirect: c_int, }; pub const XConfigureEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, x: c_int, y: c_int, width: c_int, height: c_int, border_width: c_int, above: X.Window, override_redirect: c_int, }; pub const XGravityEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, x: c_int, y: c_int, }; pub const XResizeRequestEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, width: c_int, height: c_int, }; pub const XConfigureRequestEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, parent: X.Window, window: X.Window, x: c_int, y: c_int, width: c_int, height: c_int, border_width: c_int, above: X.Window, detail: c_int, value_mask: c_ulong, }; pub const XCirculateEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, event: X.Window, window: X.Window, place: c_int, }; pub const XCirculateRequestEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, parent: X.Window, window: X.Window, place: c_int, }; pub const XPropertyEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, atom: X.Atom, time: X.Time, state: c_int, }; pub const XSelectionClearEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, selection: X.Atom, time: X.Time, }; pub const XSelectionRequestEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, owner: X.Window, requestor: X.Window, selection: X.Atom, target: X.Atom, property: X.Atom, time: X.Time, }; pub const XSelectionEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, requestor: X.Window, selection: X.Atom, target: X.Atom, property: X.Atom, time: X.Time, }; pub const XColormapEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, colormap: X.Colormap, new: c_int, state: c_int, }; const union_unnamed_2 = extern union { b: [20]u8, s: [10]c_short, l: [5]c_long, }; pub const XClientMessageEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, message_type: X.Atom, format: c_int, data: union_unnamed_2, }; pub const XMappingEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, request: c_int, first_keycode: c_int, count: c_int, }; pub const XErrorEvent = extern struct { type: c_int, display: ?*Display, resourceid: X.XID, serial: c_ulong, error_code: u8, request_code: u8, minor_code: u8, }; pub const XAnyEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, window: X.Window, }; pub const XGenericEvent = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, extension: c_int, evtype: c_int, }; pub const XGenericEventCookie = extern struct { type: c_int, serial: c_ulong, send_event: c_int, display: ?*Display, extension: c_int, evtype: c_int, cookie: c_uint, data: ?*anyopaque, }; pub const union__XEvent = extern union { type: c_int, xany: XAnyEvent, xkey: XKeyEvent, xbutton: XButtonEvent, xmotion: XMotionEvent, xcrossing: XCrossingEvent, xfocus: XFocusChangeEvent, xexpose: XExposeEvent, xgraphicsexpose: XGraphicsExposeEvent, xnoexpose: XNoExposeEvent, xvisibility: XVisibilityEvent, xcreatewindow: XCreateWindowEvent, xdestroywindow: XDestroyWindowEvent, xunmap: XUnmapEvent, xmap: XMapEvent, xmaprequest: XMapRequestEvent, xreparent: XReparentEvent, xconfigure: XConfigureEvent, xgravity: XGravityEvent, xresizerequest: XResizeRequestEvent, xconfigurerequest: XConfigureRequestEvent, xcirculate: XCirculateEvent, xcirculaterequest: XCirculateRequestEvent, xproperty: XPropertyEvent, xselectionclear: XSelectionClearEvent, xselectionrequest: XSelectionRequestEvent, xselection: XSelectionEvent, xcolormap: XColormapEvent, xclient: XClientMessageEvent, xmapping: XMappingEvent, xerror: XErrorEvent, xkeymap: XKeymapEvent, xgeneric: XGenericEvent, xcookie: XGenericEventCookie, pad: [24]c_long, }; pub const XEvent = union__XEvent; pub const XCharStruct = extern struct { lbearing: c_short, rbearing: c_short, width: c_short, ascent: c_short, descent: c_short, attributes: c_ushort, }; pub const XFontProp = extern struct { name: X.Atom, card32: c_ulong, }; pub const XFontStruct = extern struct { ext_data: [*c]XExtData, fid: X.Font, direction: c_uint, min_char_or_byte2: c_uint, max_char_or_byte2: c_uint, min_byte1: c_uint, max_byte1: c_uint, all_chars_exist: c_int, default_char: c_uint, n_properties: c_int, properties: [*c]XFontProp, min_bounds: XCharStruct, max_bounds: XCharStruct, per_char: [*c]XCharStruct, ascent: c_int, descent: c_int, }; pub const XTextItem = extern struct { chars: [*c]u8, nchars: c_int, delta: c_int, font: X.Font, }; pub const XChar2b = extern struct { byte1: u8, byte2: u8, }; pub const XTextItem16 = extern struct { chars: [*c]XChar2b, nchars: c_int, delta: c_int, font: X.Font, }; pub const XEDataObject = extern union { display: ?*Display, gc: GC, visual: [*c]Visual, screen: [*c]Screen, pixmap_format: [*c]ScreenFormat, font: [*c]XFontStruct, }; pub const XFontSetExtents = extern struct { max_ink_extent: XRectangle, max_logical_extent: XRectangle, }; pub const struct__XOM = opaque {}; pub const XOM = ?*struct__XOM; pub const struct__XOC = opaque {}; pub const XOC = ?*struct__XOC; pub const XFontSet = ?*struct__XOC; pub const XmbTextItem = extern struct { chars: [*c]u8, nchars: c_int, delta: c_int, font_set: XFontSet, }; pub const XwcTextItem = extern struct { chars: [*c]wchar_t, nchars: c_int, delta: c_int, font_set: XFontSet, }; pub const XOMCharSetList = extern struct { charset_count: c_int, charset_list: [*c][*c]u8, }; pub const XOMOrientation_LTR_TTB: c_int = 0; pub const XOMOrientation_RTL_TTB: c_int = 1; pub const XOMOrientation_TTB_LTR: c_int = 2; pub const XOMOrientation_TTB_RTL: c_int = 3; pub const XOMOrientation_Context: c_int = 4; pub const XOrientation = c_uint; pub const XOMOrientation = extern struct { num_orientation: c_int, orientation: [*c]XOrientation, }; pub const XOMFontInfo = extern struct { num_font: c_int, font_struct_list: [*c][*c]XFontStruct, font_name_list: [*c][*c]u8, }; pub const struct__XIM = opaque {}; pub const XIM = ?*struct__XIM; pub const struct__XIC = opaque {}; pub const XIC = ?*struct__XIC; pub const XIMProc = ?fn (XIM, XPointer, XPointer) callconv(.C) void; pub const XICProc = ?fn (XIC, XPointer, XPointer) callconv(.C) c_int; pub const XIDProc = ?fn (?*Display, XPointer, XPointer) callconv(.C) void; pub const XIMStyle = c_ulong; pub const XIMStyles = extern struct { count_styles: c_ushort, supported_styles: [*c]XIMStyle, }; pub const XVaNestedList = ?*anyopaque; pub const XIMCallback = extern struct { client_data: XPointer, callback: XIMProc, }; pub const XICCallback = extern struct { client_data: XPointer, callback: XICProc, }; pub const XIMFeedback = c_ulong; const union_unnamed_3 = extern union { multi_byte: [*c]u8, wide_char: [*c]wchar_t, }; pub const struct__XIMText = extern struct { length: c_ushort, feedback: [*c]XIMFeedback, encoding_is_wchar: c_int, string: union_unnamed_3, }; pub const XIMText = struct__XIMText; pub const XIMPreeditState = c_ulong; pub const struct__XIMPreeditStateNotifyCallbackStruct = extern struct { state: XIMPreeditState, }; pub const XIMPreeditStateNotifyCallbackStruct = struct__XIMPreeditStateNotifyCallbackStruct; pub const XIMResetState = c_ulong; pub const XIMStringConversionFeedback = c_ulong; const union_unnamed_4 = extern union { mbs: [*c]u8, wcs: [*c]wchar_t, }; pub const struct__XIMStringConversionText = extern struct { length: c_ushort, feedback: [*c]XIMStringConversionFeedback, encoding_is_wchar: c_int, string: union_unnamed_4, }; pub const XIMStringConversionText = struct__XIMStringConversionText; pub const XIMStringConversionPosition = c_ushort; pub const XIMStringConversionType = c_ushort; pub const XIMStringConversionOperation = c_ushort; pub const XIMForwardChar: c_int = 0; pub const XIMBackwardChar: c_int = 1; pub const XIMForwardWord: c_int = 2; pub const XIMBackwardWord: c_int = 3; pub const XIMCaretUp: c_int = 4; pub const XIMCaretDown: c_int = 5; pub const XIMNextLine: c_int = 6; pub const XIMPreviousLine: c_int = 7; pub const XIMLineStart: c_int = 8; pub const XIMLineEnd: c_int = 9; pub const XIMAbsolutePosition: c_int = 10; pub const XIMDontChange: c_int = 11; pub const XIMCaretDirection = c_uint; pub const struct__XIMStringConversionCallbackStruct = extern struct { position: XIMStringConversionPosition, direction: XIMCaretDirection, operation: XIMStringConversionOperation, factor: c_ushort, text: [*c]XIMStringConversionText, }; pub const XIMStringConversionCallbackStruct = struct__XIMStringConversionCallbackStruct; pub const struct__XIMPreeditDrawCallbackStruct = extern struct { caret: c_int, chg_first: c_int, chg_length: c_int, text: [*c]XIMText, }; pub const XIMPreeditDrawCallbackStruct = struct__XIMPreeditDrawCallbackStruct; pub const XIMIsInvisible: c_int = 0; pub const XIMIsPrimary: c_int = 1; pub const XIMIsSecondary: c_int = 2; pub const XIMCaretStyle = c_uint; pub const struct__XIMPreeditCaretCallbackStruct = extern struct { position: c_int, direction: XIMCaretDirection, style: XIMCaretStyle, }; pub const XIMPreeditCaretCallbackStruct = struct__XIMPreeditCaretCallbackStruct; pub const XIMTextType: c_int = 0; pub const XIMBitmapType: c_int = 1; pub const XIMStatusDataType = c_uint; const union_unnamed_5 = extern union { text: [*c]XIMText, bitmap: X.Pixmap, }; pub const struct__XIMStatusDrawCallbackStruct = extern struct { type: XIMStatusDataType, data: union_unnamed_5, }; pub const XIMStatusDrawCallbackStruct = struct__XIMStatusDrawCallbackStruct; pub const struct__XIMHotKeyTrigger = extern struct { keysym: X.KeySym, modifier: c_int, modifier_mask: c_int, }; pub const XIMHotKeyTrigger = struct__XIMHotKeyTrigger; pub const struct__XIMHotKeyTriggers = extern struct { num_hot_key: c_int, key: [*c]XIMHotKeyTrigger, }; pub const XIMHotKeyTriggers = struct__XIMHotKeyTriggers; pub const XIMHotKeyState = c_ulong; pub const XIMValuesList = extern struct { count_values: c_ushort, supported_values: [*c][*c]u8, }; pub const Bool = c_int; pub const Status = c_int; pub const True = @as(c_int, 1); pub const False = @as(c_int, 0); pub const QueuedAlready = @as(c_int, 0); pub const QueuedAfterReading = @as(c_int, 1); pub const QueuedAfterFlush = @as(c_int, 2); pub const XNRequiredCharSet = "requiredCharSet"; pub const XNQueryOrientation = "queryOrientation"; pub const XNBaseFontName = "baseFontName"; pub const XNOMAutomatic = "omAutomatic"; pub const XNMissingCharSet = "missingCharSet"; pub const XNDefaultString = "defaultString"; pub const XNOrientation = "orientation"; pub const XNDirectionalDependentDrawing = "directionalDependentDrawing"; pub const XNContextualDrawing = "contextualDrawing"; pub const XNFontInfo = "fontInfo"; pub const XIMPreeditArea = @as(c_long, 0x0001); pub const XIMPreeditCallbacks = @as(c_long, 0x0002); pub const XIMPreeditPosition = @as(c_long, 0x0004); pub const XIMPreeditNothing = @as(c_long, 0x0008); pub const XIMPreeditNone = @as(c_long, 0x0010); pub const XIMStatusArea = @as(c_long, 0x0100); pub const XIMStatusCallbacks = @as(c_long, 0x0200); pub const XIMStatusNothing = @as(c_long, 0x0400); pub const XIMStatusNone = @as(c_long, 0x0800); pub const XNVaNestedList = "XNVaNestedList"; pub const XNQueryInputStyle = "queryInputStyle"; pub const XNClientWindow = "clientWindow"; pub const XNInputStyle = "inputStyle"; pub const XNFocusWindow = "focusWindow"; pub const XNResourceName = "resourceName"; pub const XNResourceClass = "resourceClass"; pub const XNGeometryCallback = "geometryCallback"; pub const XNDestroyCallback = "destroyCallback"; pub const XNFilterEvents = "filterEvents"; pub const XNPreeditStartCallback = "preeditStartCallback"; pub const XNPreeditDoneCallback = "preeditDoneCallback"; pub const XNPreeditDrawCallback = "preeditDrawCallback"; pub const XNPreeditCaretCallback = "preeditCaretCallback"; pub const XNPreeditStateNotifyCallback = "preeditStateNotifyCallback"; pub const XNPreeditAttributes = "preeditAttributes"; pub const XNStatusStartCallback = "statusStartCallback"; pub const XNStatusDoneCallback = "statusDoneCallback"; pub const XNStatusDrawCallback = "statusDrawCallback"; pub const XNStatusAttributes = "statusAttributes"; pub const XNArea = "area"; pub const XNAreaNeeded = "areaNeeded"; pub const XNSpotLocation = "spotLocation"; pub const XNColormap = "colorMap"; pub const XNStdColormap = "stdColorMap"; pub const XNForeground = "foreground"; pub const XNBackground = "background"; pub const XNBackgroundPixmap = "backgroundPixmap"; pub const XNFontSet = "fontSet"; pub const XNLineSpace = "lineSpace"; pub const XNCursor = "cursor"; pub const XNQueryIMValuesList = "queryIMValuesList"; pub const XNQueryICValuesList = "queryICValuesList"; pub const XNVisiblePosition = "visiblePosition"; pub const XNR6PreeditCallback = "r6PreeditCallback"; pub const XNStringConversionCallback = "stringConversionCallback"; pub const XNStringConversion = "stringConversion"; pub const XNResetState = "resetState"; pub const XNHotKey = "hotKey"; pub const XNHotKeyState = "hotKeyState"; pub const XNPreeditState = "preeditState"; pub const XNSeparatorofNestedList = "separatorofNestedList"; pub const XBufferOverflow = -@as(c_int, 1); pub const XLookupNone = @as(c_int, 1); pub const XLookupChars = @as(c_int, 2); pub const XLookupKeySym = @as(c_int, 3); pub const XLookupBoth = @as(c_int, 4); pub const XIMReverse = @as(c_long, 1); pub const XIMUnderline = @as(c_long, 1) << @as(c_int, 1); pub const XIMHighlight = @as(c_long, 1) << @as(c_int, 2); pub const XIMPrimary = @as(c_long, 1) << @as(c_int, 5); pub const XIMSecondary = @as(c_long, 1) << @as(c_int, 6); pub const XIMTertiary = @as(c_long, 1) << @as(c_int, 7); pub const XIMVisibleToForward = @as(c_long, 1) << @as(c_int, 8); pub const XIMVisibleToBackword = @as(c_long, 1) << @as(c_int, 9); pub const XIMVisibleToCenter = @as(c_long, 1) << @as(c_int, 10); pub const XIMPreeditUnKnown = @as(c_long, 0); pub const XIMPreeditEnable = @as(c_long, 1); pub const XIMPreeditDisable = @as(c_long, 1) << @as(c_int, 1); pub const XIMInitialState = @as(c_long, 1); pub const XIMPreserveState = @as(c_long, 1) << @as(c_int, 1); pub const XIMStringConversionLeftEdge = @as(c_int, 0x00000001); pub const XIMStringConversionRightEdge = @as(c_int, 0x00000002); pub const XIMStringConversionTopEdge = @as(c_int, 0x00000004); pub const XIMStringConversionBottomEdge = @as(c_int, 0x00000008); pub const XIMStringConversionConcealed = @as(c_int, 0x00000010); pub const XIMStringConversionWrapped = @as(c_int, 0x00000020); pub const XIMStringConversionBuffer = @as(c_int, 0x0001); pub const XIMStringConversionLine = @as(c_int, 0x0002); pub const XIMStringConversionWord = @as(c_int, 0x0003); pub const XIMStringConversionChar = @as(c_int, 0x0004); pub const XIMStringConversionSubstitution = @as(c_int, 0x0001); pub const XIMStringConversionRetrieval = @as(c_int, 0x0002); pub const XIMHotKeyStateON = @as(c_long, 0x0001); pub const XIMHotKeyStateOFF = @as(c_long, 0x0002); pub const _XExtData = struct__XExtData; pub const _XGC = struct__XGC; pub const _XDisplay = struct__XDisplay; pub const funcs = struct_funcs; pub const _XImage = struct__XImage; pub const _XPrivate = struct__XPrivate; pub const _XrmHashBucketRec = struct__XrmHashBucketRec; pub const _XOM = struct__XOM; pub const _XOC = struct__XOC; pub const _XIM = struct__XIM; pub const _XIC = struct__XIC; pub const _XIMText = struct__XIMText; pub const _XIMPreeditStateNotifyCallbackStruct = struct__XIMPreeditStateNotifyCallbackStruct; pub const _XIMStringConversionText = struct__XIMStringConversionText; pub const _XIMStringConversionCallbackStruct = struct__XIMStringConversionCallbackStruct; pub const _XIMPreeditDrawCallbackStruct = struct__XIMPreeditDrawCallbackStruct; pub const _XIMPreeditCaretCallbackStruct = struct__XIMPreeditCaretCallbackStruct; pub const _XIMStatusDrawCallbackStruct = struct__XIMStatusDrawCallbackStruct; pub const _XIMHotKeyTrigger = struct__XIMHotKeyTrigger; pub const _XIMHotKeyTriggers = struct__XIMHotKeyTriggers; pub const INT64 = c_long; pub const CARD64 = c_ulong; pub const BITS32 = CARD32; pub const BITS16 = CARD16; pub const struct__xSegment = extern struct { x1: INT16, y1: INT16, x2: INT16, y2: INT16, }; pub const xSegment = struct__xSegment; pub const struct__xPoint = extern struct { x: INT16, y: INT16, }; pub const xPoint = struct__xPoint; pub const struct__xRectangle = extern struct { x: INT16, y: INT16, width: CARD16, height: CARD16, }; pub const xRectangle = struct__xRectangle; pub const struct__xArc = extern struct { x: INT16, y: INT16, width: CARD16, height: CARD16, angle1: INT16, angle2: INT16, }; pub const xArc = struct__xArc; pub const xConnClientPrefix = extern struct { byteOrder: CARD8, pad: BYTE, majorVersion: CARD16, minorVersion: CARD16, nbytesAuthProto: CARD16, nbytesAuthString: CARD16, pad2: CARD16, }; pub const xConnSetupPrefix = extern struct { success: CARD8, lengthReason: BYTE, majorVersion: CARD16, minorVersion: CARD16, length: CARD16, }; pub const xConnSetup = extern struct { release: CARD32, ridBase: CARD32, ridMask: CARD32, motionBufferSize: CARD32, nbytesVendor: CARD16, maxRequestSize: CARD16, numRoots: CARD8, numFormats: CARD8, imageByteOrder: CARD8, bitmapBitOrder: CARD8, bitmapScanlineUnit: CARD8, bitmapScanlinePad: CARD8, minKeyCode: CARD8, maxKeyCode: CARD8, pad2: CARD32, }; pub const xPixmapFormat = extern struct { depth: CARD8, bitsPerPixel: CARD8, scanLinePad: CARD8, pad1: CARD8, pad2: CARD32, }; pub const xDepth = extern struct { depth: CARD8, pad1: CARD8, nVisuals: CARD16, pad2: CARD32, }; pub const xVisualType = extern struct { visualID: CARD32, class: CARD8, bitsPerRGB: CARD8, colormapEntries: CARD16, redMask: CARD32, greenMask: CARD32, blueMask: CARD32, pad: CARD32, }; pub const xWindowRoot = extern struct { windowId: CARD32, defaultColormap: CARD32, whitePixel: CARD32, blackPixel: CARD32, currentInputMask: CARD32, pixWidth: CARD16, pixHeight: CARD16, mmWidth: CARD16, mmHeight: CARD16, minInstalledMaps: CARD16, maxInstalledMaps: CARD16, rootVisualID: CARD32, backingStore: CARD8, saveUnders: BOOL, rootDepth: CARD8, nDepths: CARD8, }; pub const xTimecoord = extern struct { time: CARD32, x: INT16, y: INT16, }; pub const xHostEntry = extern struct { family: CARD8, pad: BYTE, length: CARD16, }; pub const xCharInfo = extern struct { leftSideBearing: INT16, rightSideBearing: INT16, characterWidth: INT16, ascent: INT16, descent: INT16, attributes: CARD16, }; pub const xFontProp = extern struct { name: CARD32, value: CARD32, }; pub const xTextElt = extern struct { len: CARD8, delta: INT8, }; pub const xColorItem = extern struct { pixel: CARD32, red: CARD16, green: CARD16, blue: CARD16, flags: CARD8, pad: CARD8, }; pub const xrgb = extern struct { red: CARD16, green: CARD16, blue: CARD16, pad: CARD16, }; pub const KEYCODE = CARD8; pub const xGenericReply = extern struct { type: BYTE, data1: BYTE, sequenceNumber: CARD16, length: CARD32, data00: CARD32, data01: CARD32, data02: CARD32, data03: CARD32, data04: CARD32, data05: CARD32, }; pub const xGetWindowAttributesReply = extern struct { type: BYTE, backingStore: CARD8, sequenceNumber: CARD16, length: CARD32, visualID: CARD32, class: CARD16, bitGravity: CARD8, winGravity: CARD8, backingBitPlanes: CARD32, backingPixel: CARD32, saveUnder: BOOL, mapInstalled: BOOL, mapState: CARD8, override: BOOL, colormap: CARD32, allEventMasks: CARD32, yourEventMask: CARD32, doNotPropagateMask: CARD16, pad: CARD16, }; pub const xGetGeometryReply = extern struct { type: BYTE, depth: CARD8, sequenceNumber: CARD16, length: CARD32, root: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, borderWidth: CARD16, pad1: CARD16, pad2: CARD32, pad3: CARD32, }; pub const xQueryTreeReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, root: CARD32, parent: CARD32, nChildren: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, }; pub const xInternAtomReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, atom: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xGetAtomNameReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nameLength: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGetPropertyReply = extern struct { type: BYTE, format: CARD8, sequenceNumber: CARD16, length: CARD32, propertyType: CARD32, bytesAfter: CARD32, nItems: CARD32, pad1: CARD32, pad2: CARD32, pad3: CARD32, }; pub const xListPropertiesReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nProperties: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGetSelectionOwnerReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, owner: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xGrabPointerReply = extern struct { type: BYTE, status: BYTE, sequenceNumber: CARD16, length: CARD32, pad1: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xGrabKeyboardReply = xGrabPointerReply; pub const xQueryPointerReply = extern struct { type: BYTE, sameScreen: BOOL, sequenceNumber: CARD16, length: CARD32, root: CARD32, child: CARD32, rootX: INT16, rootY: INT16, winX: INT16, winY: INT16, mask: CARD16, pad1: CARD16, pad: CARD32, }; pub const xGetMotionEventsReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nEvents: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xTranslateCoordsReply = extern struct { type: BYTE, sameScreen: BOOL, sequenceNumber: CARD16, length: CARD32, child: CARD32, dstX: INT16, dstY: INT16, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, }; pub const xGetInputFocusReply = extern struct { type: BYTE, revertTo: CARD8, sequenceNumber: CARD16, length: CARD32, focus: CARD32, pad1: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, }; pub const xQueryKeymapReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, map: [32]BYTE, }; pub const struct__xQueryFontReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, minBounds: xCharInfo, walign1: CARD32, maxBounds: xCharInfo, walign2: CARD32, minCharOrByte2: CARD16, maxCharOrByte2: CARD16, defaultChar: CARD16, nFontProps: CARD16, drawDirection: CARD8, minByte1: CARD8, maxByte1: CARD8, allCharsExist: BOOL, fontAscent: INT16, fontDescent: INT16, nCharInfos: CARD32, }; pub const xQueryFontReply = struct__xQueryFontReply; pub const xQueryTextExtentsReply = extern struct { type: BYTE, drawDirection: CARD8, sequenceNumber: CARD16, length: CARD32, fontAscent: INT16, fontDescent: INT16, overallAscent: INT16, overallDescent: INT16, overallWidth: INT32, overallLeft: INT32, overallRight: INT32, pad: CARD32, }; pub const xListFontsReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nFonts: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xListFontsWithInfoReply = extern struct { type: BYTE, nameLength: CARD8, sequenceNumber: CARD16, length: CARD32, minBounds: xCharInfo, walign1: CARD32, maxBounds: xCharInfo, walign2: CARD32, minCharOrByte2: CARD16, maxCharOrByte2: CARD16, defaultChar: CARD16, nFontProps: CARD16, drawDirection: CARD8, minByte1: CARD8, maxByte1: CARD8, allCharsExist: BOOL, fontAscent: INT16, fontDescent: INT16, nReplies: CARD32, }; pub const xGetFontPathReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nPaths: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGetImageReply = extern struct { type: BYTE, depth: CARD8, sequenceNumber: CARD16, length: CARD32, visual: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xListInstalledColormapsReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nColormaps: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xAllocColorReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, red: CARD16, green: CARD16, blue: CARD16, pad2: CARD16, pixel: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, }; pub const xAllocNamedColorReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, pixel: CARD32, exactRed: CARD16, exactGreen: CARD16, exactBlue: CARD16, screenRed: CARD16, screenGreen: CARD16, screenBlue: CARD16, pad2: CARD32, pad3: CARD32, }; pub const xAllocColorCellsReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nPixels: CARD16, nMasks: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xAllocColorPlanesReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nPixels: CARD16, pad2: CARD16, redMask: CARD32, greenMask: CARD32, blueMask: CARD32, pad3: CARD32, pad4: CARD32, }; pub const xQueryColorsReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, nColors: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xLookupColorReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, exactRed: CARD16, exactGreen: CARD16, exactBlue: CARD16, screenRed: CARD16, screenGreen: CARD16, screenBlue: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, }; pub const xQueryBestSizeReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, width: CARD16, height: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xQueryExtensionReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, present: BOOL, major_opcode: CARD8, first_event: CARD8, first_error: CARD8, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xListExtensionsReply = extern struct { type: BYTE, nExtensions: CARD8, sequenceNumber: CARD16, length: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xSetMappingReply = extern struct { type: BYTE, success: CARD8, sequenceNumber: CARD16, length: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xSetPointerMappingReply = xSetMappingReply; pub const xSetModifierMappingReply = xSetMappingReply; pub const xGetPointerMappingReply = extern struct { type: BYTE, nElts: CARD8, sequenceNumber: CARD16, length: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGetKeyboardMappingReply = extern struct { type: BYTE, keySymsPerKeyCode: CARD8, sequenceNumber: CARD16, length: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGetModifierMappingReply = extern struct { type: BYTE, numKeyPerModifier: CARD8, sequenceNumber: CARD16, length: CARD32, pad1: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xGetKeyboardControlReply = extern struct { type: BYTE, globalAutoRepeat: BOOL, sequenceNumber: CARD16, length: CARD32, ledMask: CARD32, keyClickPercent: CARD8, bellPercent: CARD8, bellPitch: CARD16, bellDuration: CARD16, pad: CARD16, map: [32]BYTE, }; pub const xGetPointerControlReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, accelNumerator: CARD16, accelDenominator: CARD16, threshold: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xGetScreenSaverReply = extern struct { type: BYTE, pad1: BYTE, sequenceNumber: CARD16, length: CARD32, timeout: CARD16, interval: CARD16, preferBlanking: BOOL, allowExposures: BOOL, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, }; pub const xListHostsReply = extern struct { type: BYTE, enabled: BOOL, sequenceNumber: CARD16, length: CARD32, nHosts: CARD16, pad1: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xError = extern struct { type: BYTE, errorCode: BYTE, sequenceNumber: CARD16, resourceID: CARD32, minorCode: CARD16, majorCode: CARD8, pad1: BYTE, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xGenericEvent = extern struct { type: BYTE, extension: CARD8, sequenceNumber: CARD16, length: CARD32, evtype: CARD16, pad2: CARD16, pad3: CARD32, pad4: CARD32, pad5: CARD32, pad6: CARD32, pad7: CARD32, }; pub const xKeymapEvent = extern struct { type: BYTE, map: [31]BYTE, }; pub const xReply = extern union { generic: xGenericReply, geom: xGetGeometryReply, tree: xQueryTreeReply, atom: xInternAtomReply, atomName: xGetAtomNameReply, property: xGetPropertyReply, listProperties: xListPropertiesReply, selection: xGetSelectionOwnerReply, grabPointer: xGrabPointerReply, grabKeyboard: xGrabKeyboardReply, pointer: xQueryPointerReply, motionEvents: xGetMotionEventsReply, coords: xTranslateCoordsReply, inputFocus: xGetInputFocusReply, textExtents: xQueryTextExtentsReply, fonts: xListFontsReply, fontPath: xGetFontPathReply, image: xGetImageReply, colormaps: xListInstalledColormapsReply, allocColor: xAllocColorReply, allocNamedColor: xAllocNamedColorReply, colorCells: xAllocColorCellsReply, colorPlanes: xAllocColorPlanesReply, colors: xQueryColorsReply, lookupColor: xLookupColorReply, bestSize: xQueryBestSizeReply, extension: xQueryExtensionReply, extensions: xListExtensionsReply, setModifierMapping: xSetModifierMappingReply, getModifierMapping: xGetModifierMappingReply, setPointerMapping: xSetPointerMappingReply, getKeyboardMapping: xGetKeyboardMappingReply, getPointerMapping: xGetPointerMappingReply, pointerControl: xGetPointerControlReply, screenSaver: xGetScreenSaverReply, hosts: xListHostsReply, @"error": xError, event: xEvent, }; pub const struct__xReq = extern struct { reqType: CARD8, data: CARD8, length: CARD16, }; pub const xReq = struct__xReq; pub const xResourceReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, id: CARD32, }; pub const xCreateWindowReq = extern struct { reqType: CARD8, depth: CARD8, length: CARD16, wid: CARD32, parent: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, borderWidth: CARD16, class: CARD16, visual: CARD32, mask: CARD32, }; pub const xChangeWindowAttributesReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, valueMask: CARD32, }; pub const xChangeSaveSetReq = extern struct { reqType: CARD8, mode: BYTE, length: CARD16, window: CARD32, }; pub const xReparentWindowReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, parent: CARD32, x: INT16, y: INT16, }; pub const xConfigureWindowReq = extern struct { reqType: CARD8, pad: CARD8, length: CARD16, window: CARD32, mask: CARD16, pad2: CARD16, }; pub const xCirculateWindowReq = extern struct { reqType: CARD8, direction: CARD8, length: CARD16, window: CARD32, }; pub const xInternAtomReq = extern struct { reqType: CARD8, onlyIfExists: BOOL, length: CARD16, nbytes: CARD16, pad: CARD16, }; pub const xChangePropertyReq = extern struct { reqType: CARD8, mode: CARD8, length: CARD16, window: CARD32, property: CARD32, type: CARD32, format: CARD8, pad: [3]BYTE, nUnits: CARD32, }; pub const xDeletePropertyReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, property: CARD32, }; pub const xGetPropertyReq = extern struct { reqType: CARD8, delete: BOOL, length: CARD16, window: CARD32, property: CARD32, type: CARD32, longOffset: CARD32, longLength: CARD32, }; pub const xSetSelectionOwnerReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, selection: CARD32, time: CARD32, }; pub const xConvertSelectionReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, requestor: CARD32, selection: CARD32, target: CARD32, property: CARD32, time: CARD32, }; pub const xSendEventReq = extern struct { reqType: CARD8, propagate: BOOL, length: CARD16, destination: CARD32, eventMask: CARD32, event: xEvent, }; pub const xGrabPointerReq = extern struct { reqType: CARD8, ownerEvents: BOOL, length: CARD16, grabWindow: CARD32, eventMask: CARD16, pointerMode: BYTE, keyboardMode: BYTE, confineTo: CARD32, cursor: CARD32, time: CARD32, }; pub const xGrabButtonReq = extern struct { reqType: CARD8, ownerEvents: BOOL, length: CARD16, grabWindow: CARD32, eventMask: CARD16, pointerMode: BYTE, keyboardMode: BYTE, confineTo: CARD32, cursor: CARD32, button: CARD8, pad: BYTE, modifiers: CARD16, }; pub const xUngrabButtonReq = extern struct { reqType: CARD8, button: CARD8, length: CARD16, grabWindow: CARD32, modifiers: CARD16, pad: CARD16, }; pub const xChangeActivePointerGrabReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cursor: CARD32, time: CARD32, eventMask: CARD16, pad2: CARD16, }; pub const xGrabKeyboardReq = extern struct { reqType: CARD8, ownerEvents: BOOL, length: CARD16, grabWindow: CARD32, time: CARD32, pointerMode: BYTE, keyboardMode: BYTE, pad: CARD16, }; pub const xGrabKeyReq = extern struct { reqType: CARD8, ownerEvents: BOOL, length: CARD16, grabWindow: CARD32, modifiers: CARD16, key: CARD8, pointerMode: BYTE, keyboardMode: BYTE, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; pub const xUngrabKeyReq = extern struct { reqType: CARD8, key: CARD8, length: CARD16, grabWindow: CARD32, modifiers: CARD16, pad: CARD16, }; pub const xAllowEventsReq = extern struct { reqType: CARD8, mode: CARD8, length: CARD16, time: CARD32, }; pub const xGetMotionEventsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, start: CARD32, stop: CARD32, }; pub const xTranslateCoordsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, srcWid: CARD32, dstWid: CARD32, srcX: INT16, srcY: INT16, }; pub const xWarpPointerReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, srcWid: CARD32, dstWid: CARD32, srcX: INT16, srcY: INT16, srcWidth: CARD16, srcHeight: CARD16, dstX: INT16, dstY: INT16, }; pub const xSetInputFocusReq = extern struct { reqType: CARD8, revertTo: CARD8, length: CARD16, focus: CARD32, time: CARD32, }; pub const xOpenFontReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, fid: CARD32, nbytes: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xQueryTextExtentsReq = extern struct { reqType: CARD8, oddLength: BOOL, length: CARD16, fid: CARD32, }; pub const xListFontsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, maxNames: CARD16, nbytes: CARD16, }; pub const xListFontsWithInfoReq = xListFontsReq; pub const xSetFontPathReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, nFonts: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xCreatePixmapReq = extern struct { reqType: CARD8, depth: CARD8, length: CARD16, pid: CARD32, drawable: CARD32, width: CARD16, height: CARD16, }; pub const xCreateGCReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, gc: CARD32, drawable: CARD32, mask: CARD32, }; pub const xChangeGCReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, gc: CARD32, mask: CARD32, }; pub const xCopyGCReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, srcGC: CARD32, dstGC: CARD32, mask: CARD32, }; pub const xSetDashesReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, gc: CARD32, dashOffset: CARD16, nDashes: CARD16, }; pub const xSetClipRectanglesReq = extern struct { reqType: CARD8, ordering: BYTE, length: CARD16, gc: CARD32, xOrigin: INT16, yOrigin: INT16, }; pub const xClearAreaReq = extern struct { reqType: CARD8, exposures: BOOL, length: CARD16, window: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, }; pub const xCopyAreaReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, srcDrawable: CARD32, dstDrawable: CARD32, gc: CARD32, srcX: INT16, srcY: INT16, dstX: INT16, dstY: INT16, width: CARD16, height: CARD16, }; pub const xCopyPlaneReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, srcDrawable: CARD32, dstDrawable: CARD32, gc: CARD32, srcX: INT16, srcY: INT16, dstX: INT16, dstY: INT16, width: CARD16, height: CARD16, bitPlane: CARD32, }; pub const xPolyPointReq = extern struct { reqType: CARD8, coordMode: BYTE, length: CARD16, drawable: CARD32, gc: CARD32, }; pub const xPolyLineReq = xPolyPointReq; pub const xPolySegmentReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, drawable: CARD32, gc: CARD32, }; pub const xPolyArcReq = xPolySegmentReq; pub const xPolyRectangleReq = xPolySegmentReq; pub const xPolyFillRectangleReq = xPolySegmentReq; pub const xPolyFillArcReq = xPolySegmentReq; pub const struct__FillPolyReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, drawable: CARD32, gc: CARD32, shape: BYTE, coordMode: BYTE, pad1: CARD16, }; pub const xFillPolyReq = struct__FillPolyReq; pub const struct__PutImageReq = extern struct { reqType: CARD8, format: CARD8, length: CARD16, drawable: CARD32, gc: CARD32, width: CARD16, height: CARD16, dstX: INT16, dstY: INT16, leftPad: CARD8, depth: CARD8, pad: CARD16, }; pub const xPutImageReq = struct__PutImageReq; pub const xGetImageReq = extern struct { reqType: CARD8, format: CARD8, length: CARD16, drawable: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, planeMask: CARD32, }; pub const xPolyTextReq = extern struct { reqType: CARD8, pad: CARD8, length: CARD16, drawable: CARD32, gc: CARD32, x: INT16, y: INT16, }; pub const xPolyText8Req = xPolyTextReq; pub const xPolyText16Req = xPolyTextReq; pub const xImageTextReq = extern struct { reqType: CARD8, nChars: BYTE, length: CARD16, drawable: CARD32, gc: CARD32, x: INT16, y: INT16, }; pub const xImageText8Req = xImageTextReq; pub const xImageText16Req = xImageTextReq; pub const xCreateColormapReq = extern struct { reqType: CARD8, alloc: BYTE, length: CARD16, mid: CARD32, window: CARD32, visual: CARD32, }; pub const xCopyColormapAndFreeReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, mid: CARD32, srcCmap: CARD32, }; pub const xAllocColorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, red: CARD16, green: CARD16, blue: CARD16, pad2: CARD16, }; pub const xAllocNamedColorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, nbytes: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xAllocColorCellsReq = extern struct { reqType: CARD8, contiguous: BOOL, length: CARD16, cmap: CARD32, colors: CARD16, planes: CARD16, }; pub const xAllocColorPlanesReq = extern struct { reqType: CARD8, contiguous: BOOL, length: CARD16, cmap: CARD32, colors: CARD16, red: CARD16, green: CARD16, blue: CARD16, }; pub const xFreeColorsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, planeMask: CARD32, }; pub const xStoreColorsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, }; pub const xStoreNamedColorReq = extern struct { reqType: CARD8, flags: CARD8, length: CARD16, cmap: CARD32, pixel: CARD32, nbytes: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xQueryColorsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, }; pub const xLookupColorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cmap: CARD32, nbytes: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xCreateCursorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cid: CARD32, source: CARD32, mask: CARD32, foreRed: CARD16, foreGreen: CARD16, foreBlue: CARD16, backRed: CARD16, backGreen: CARD16, backBlue: CARD16, x: CARD16, y: CARD16, }; pub const xCreateGlyphCursorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cid: CARD32, source: CARD32, mask: CARD32, sourceChar: CARD16, maskChar: CARD16, foreRed: CARD16, foreGreen: CARD16, foreBlue: CARD16, backRed: CARD16, backGreen: CARD16, backBlue: CARD16, }; pub const xRecolorCursorReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, cursor: CARD32, foreRed: CARD16, foreGreen: CARD16, foreBlue: CARD16, backRed: CARD16, backGreen: CARD16, backBlue: CARD16, }; pub const xQueryBestSizeReq = extern struct { reqType: CARD8, class: CARD8, length: CARD16, drawable: CARD32, width: CARD16, height: CARD16, }; pub const xQueryExtensionReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, nbytes: CARD16, pad1: BYTE, pad2: BYTE, }; pub const xSetModifierMappingReq = extern struct { reqType: CARD8, numKeyPerModifier: CARD8, length: CARD16, }; pub const xSetPointerMappingReq = extern struct { reqType: CARD8, nElts: CARD8, length: CARD16, }; pub const xGetKeyboardMappingReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, firstKeyCode: CARD8, count: CARD8, pad1: CARD16, }; pub const xChangeKeyboardMappingReq = extern struct { reqType: CARD8, keyCodes: CARD8, length: CARD16, firstKeyCode: CARD8, keySymsPerKeyCode: CARD8, pad1: CARD16, }; pub const xChangeKeyboardControlReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, mask: CARD32, }; pub const xBellReq = extern struct { reqType: CARD8, percent: INT8, length: CARD16, }; pub const xChangePointerControlReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, accelNum: INT16, accelDenum: INT16, threshold: INT16, doAccel: BOOL, doThresh: BOOL, }; pub const xSetScreenSaverReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, timeout: INT16, interval: INT16, preferBlank: BYTE, allowExpose: BYTE, pad2: CARD16, }; pub const xChangeHostsReq = extern struct { reqType: CARD8, mode: BYTE, length: CARD16, hostFamily: CARD8, pad: BYTE, hostLength: CARD16, }; pub const xListHostsReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, }; pub const xChangeModeReq = extern struct { reqType: CARD8, mode: BYTE, length: CARD16, }; pub const xSetAccessControlReq = xChangeModeReq; pub const xSetCloseDownModeReq = xChangeModeReq; pub const xForceScreenSaverReq = xChangeModeReq; pub const xRotatePropertiesReq = extern struct { reqType: CARD8, pad: BYTE, length: CARD16, window: CARD32, nAtoms: CARD16, nPositions: INT16, }; pub const CARD8 = u8; pub const BYTE = CARD8; pub const CARD16 = c_ushort; const struct_unnamed_2 = extern struct { type: BYTE, detail: BYTE, sequenceNumber: CARD16, }; pub const CARD32 = c_uint; pub const INT16 = c_short; pub const KeyButMask = CARD16; pub const BOOL = CARD8; const struct_unnamed_3 = extern struct { pad00: CARD32, time: CARD32, root: CARD32, event: CARD32, child: CARD32, rootX: INT16, rootY: INT16, eventX: INT16, eventY: INT16, state: KeyButMask, sameScreen: BOOL, pad1: BYTE, }; const struct_unnamed_4 = extern struct { pad00: CARD32, time: CARD32, root: CARD32, event: CARD32, child: CARD32, rootX: INT16, rootY: INT16, eventX: INT16, eventY: INT16, state: KeyButMask, mode: BYTE, flags: BYTE, }; const struct_unnamed_5 = extern struct { pad00: CARD32, window: CARD32, mode: BYTE, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_6 = extern struct { pad00: CARD32, window: CARD32, x: CARD16, y: CARD16, width: CARD16, height: CARD16, count: CARD16, pad2: CARD16, }; const struct_unnamed_7 = extern struct { pad00: CARD32, drawable: CARD32, x: CARD16, y: CARD16, width: CARD16, height: CARD16, minorEvent: CARD16, count: CARD16, majorEvent: BYTE, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_8 = extern struct { pad00: CARD32, drawable: CARD32, minorEvent: CARD16, majorEvent: BYTE, bpad: BYTE, }; const struct_unnamed_9 = extern struct { pad00: CARD32, window: CARD32, state: CARD8, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_10 = extern struct { pad00: CARD32, parent: CARD32, window: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, borderWidth: CARD16, override: BOOL, bpad: BYTE, }; const struct_unnamed_11 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, }; const struct_unnamed_12 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, fromConfigure: BOOL, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_13 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, override: BOOL, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_14 = extern struct { pad00: CARD32, parent: CARD32, window: CARD32, }; const struct_unnamed_15 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, parent: CARD32, x: INT16, y: INT16, override: BOOL, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_16 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, aboveSibling: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, borderWidth: CARD16, override: BOOL, bpad: BYTE, }; const struct_unnamed_17 = extern struct { pad00: CARD32, parent: CARD32, window: CARD32, sibling: CARD32, x: INT16, y: INT16, width: CARD16, height: CARD16, borderWidth: CARD16, valueMask: CARD16, pad1: CARD32, }; const struct_unnamed_18 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, x: INT16, y: INT16, pad1: CARD32, pad2: CARD32, pad3: CARD32, pad4: CARD32, }; const struct_unnamed_19 = extern struct { pad00: CARD32, window: CARD32, width: CARD16, height: CARD16, }; const struct_unnamed_20 = extern struct { pad00: CARD32, event: CARD32, window: CARD32, parent: CARD32, place: BYTE, pad1: BYTE, pad2: BYTE, pad3: BYTE, }; const struct_unnamed_21 = extern struct { pad00: CARD32, window: CARD32, atom: CARD32, time: CARD32, state: BYTE, pad1: BYTE, pad2: CARD16, }; const struct_unnamed_22 = extern struct { pad00: CARD32, time: CARD32, window: CARD32, atom: CARD32, }; const struct_unnamed_23 = extern struct { pad00: CARD32, time: CARD32, owner: CARD32, requestor: CARD32, selection: CARD32, target: CARD32, property: CARD32, }; const struct_unnamed_24 = extern struct { pad00: CARD32, time: CARD32, requestor: CARD32, selection: CARD32, target: CARD32, property: CARD32, }; const struct_unnamed_25 = extern struct { pad00: CARD32, window: CARD32, colormap: CARD32, new: BOOL, state: BYTE, pad1: BYTE, pad2: BYTE, }; const struct_unnamed_26 = extern struct { pad00: CARD32, request: CARD8, firstKeyCode: CARD8, count: CARD8, pad1: BYTE, }; pub const INT32 = c_int; const struct_unnamed_29 = extern struct { type: CARD32, longs0: INT32, longs1: INT32, longs2: INT32, longs3: INT32, longs4: INT32, }; const struct_unnamed_30 = extern struct { type: CARD32, shorts0: INT16, shorts1: INT16, shorts2: INT16, shorts3: INT16, shorts4: INT16, shorts5: INT16, shorts6: INT16, shorts7: INT16, shorts8: INT16, shorts9: INT16, }; pub const INT8 = i8; const struct_unnamed_31 = extern struct { type: CARD32, bytes: [20]INT8, }; const union_unnamed_28 = extern union { l: struct_unnamed_29, s: struct_unnamed_30, b: struct_unnamed_31, }; const struct_unnamed_27 = extern struct { pad00: CARD32, window: CARD32, u: union_unnamed_28, }; const union_unnamed_1 = extern union { u: struct_unnamed_2, keyButtonPointer: struct_unnamed_3, enterLeave: struct_unnamed_4, focus: struct_unnamed_5, expose: struct_unnamed_6, graphicsExposure: struct_unnamed_7, noExposure: struct_unnamed_8, visibility: struct_unnamed_9, createNotify: struct_unnamed_10, destroyNotify: struct_unnamed_11, unmapNotify: struct_unnamed_12, mapNotify: struct_unnamed_13, mapRequest: struct_unnamed_14, reparent: struct_unnamed_15, configureNotify: struct_unnamed_16, configureRequest: struct_unnamed_17, gravity: struct_unnamed_18, resizeRequest: struct_unnamed_19, circulate: struct_unnamed_20, property: struct_unnamed_21, selectionClear: struct_unnamed_22, selectionRequest: struct_unnamed_23, selectionNotify: struct_unnamed_24, colormap: struct_unnamed_25, mappingNotify: struct_unnamed_26, clientMessage: struct_unnamed_27, }; pub const struct__xEvent = extern struct { u: union_unnamed_1, }; pub const xEvent = struct__xEvent; pub const struct__XLockInfo = opaque {}; pub const struct__XInternalAsync = extern struct { next: [*c]struct__XInternalAsync, handler: ?fn ([*c]Display, [*c]xReply, [*c]u8, c_int, XPointer) callconv(.C) c_int, data: XPointer, }; pub const struct__XLockPtrs = opaque {}; pub const struct__XKeytrans = opaque {}; pub const struct__XDisplayAtoms = opaque {}; pub const struct__XContextDB = opaque {}; const struct_unnamed_32 = extern struct { defaultCCCs: XPointer, clientCmaps: XPointer, perVisualIntensityMaps: XPointer, }; pub const struct__XIMFilter = opaque {}; pub const _XInternalConnectionProc = ?fn ([*c]Display, c_int, XPointer) callconv(.C) void; pub const struct__XConnectionInfo = extern struct { fd: c_int, read_callback: _XInternalConnectionProc, call_data: XPointer, watch_data: [*c]XPointer, next: [*c]struct__XConnectionInfo, }; pub const XConnectionWatchProc = ?fn ([*c]Display, XPointer, c_int, c_int, [*c]XPointer) callconv(.C) void; pub const struct__XConnWatchInfo = extern struct { @"fn": XConnectionWatchProc, client_data: XPointer, next: [*c]struct__XConnWatchInfo, }; pub const struct__XkbInfoRec = opaque {}; pub const struct__XtransConnInfo = opaque {}; pub const struct__X11XCBPrivate = opaque {}; pub const struct__XErrorThreadInfo = opaque {}; pub const XIOErrorExitHandler = ?fn ([*c]Display, ?*anyopaque) callconv(.C) void; pub const struct__XDisplay = extern struct { ext_data: [*c]XExtData, free_funcs: [*c]struct__XFreeFuncs, fd: c_int, conn_checker: c_int, proto_major_version: c_int, proto_minor_version: c_int, vendor: [*c]u8, resource_base: X.XID, resource_mask: X.XID, resource_id: X.XID, resource_shift: c_int, resource_alloc: ?fn ([*c]struct__XDisplay) callconv(.C) X.XID, byte_order: c_int, bitmap_unit: c_int, bitmap_pad: c_int, bitmap_bit_order: c_int, nformats: c_int, pixmap_format: [*c]ScreenFormat, vnumber: c_int, release: c_int, head: [*c]struct__XSQEvent, tail: [*c]struct__XSQEvent, qlen: c_int, last_request_read: c_ulong, request: c_ulong, last_req: [*c]u8, buffer: [*c]u8, bufptr: [*c]u8, bufmax: [*c]u8, max_request_size: c_uint, db: ?*struct__XrmHashBucketRec, synchandler: ?fn ([*c]struct__XDisplay) callconv(.C) c_int, display_name: [*c]u8, default_screen: c_int, nscreens: c_int, screens: [*c]Screen, motion_buffer: c_ulong, flags: c_ulong, min_keycode: c_int, max_keycode: c_int, keysyms: [*c]X.KeySym, modifiermap: [*c]XModifierKeymap, keysyms_per_keycode: c_int, xdefaults: [*c]u8, scratch_buffer: [*c]u8, scratch_length: c_ulong, ext_number: c_int, ext_procs: [*c]struct__XExten, event_vec: [128]?fn ([*c]Display, [*c]XEvent, [*c]xEvent) callconv(.C) c_int, wire_vec: [128]?fn ([*c]Display, [*c]XEvent, [*c]xEvent) callconv(.C) c_int, lock_meaning: X.KeySym, lock: ?*struct__XLockInfo, async_handlers: [*c]struct__XInternalAsync, bigreq_size: c_ulong, lock_fns: ?*struct__XLockPtrs, idlist_alloc: ?fn ([*c]Display, [*c]X.XID, c_int) callconv(.C) void, key_bindings: ?*struct__XKeytrans, cursor_font: X.Font, atoms: ?*struct__XDisplayAtoms, mode_switch: c_uint, num_lock: c_uint, context_db: ?*struct__XContextDB, error_vec: [*c]?fn ([*c]Display, [*c]XErrorEvent, [*c]xError) callconv(.C) c_int, cms: struct_unnamed_32, im_filters: ?*struct__XIMFilter, qfree: [*c]struct__XSQEvent, next_event_serial_num: c_ulong, flushes: [*c]struct__XExten, im_fd_info: [*c]struct__XConnectionInfo, im_fd_length: c_int, conn_watchers: [*c]struct__XConnWatchInfo, watcher_count: c_int, filedes: XPointer, savedsynchandler: ?fn ([*c]Display) callconv(.C) c_int, resource_max: X.XID, xcmisc_opcode: c_int, xkb_info: ?*struct__XkbInfoRec, trans_conn: ?*struct__XtransConnInfo, xcb: ?*struct__X11XCBPrivate, next_cookie: c_uint, generic_event_vec: [128]?fn ([*c]Display, [*c]XGenericEventCookie, [*c]xEvent) callconv(.C) c_int, generic_event_copy_vec: [128]?fn ([*c]Display, [*c]XGenericEventCookie, [*c]XGenericEventCookie) callconv(.C) c_int, cookiejar: ?*anyopaque, error_threads: ?*struct__XErrorThreadInfo, exit_handler: XIOErrorExitHandler, exit_handler_data: ?*anyopaque, };
modules/platform/src/linux/X11/Xlib.zig
const std = @import("std"); const assert = std.debug.assert; const testing = std.testing; pub const IndentationQueue = struct { const Self = @This(); pub const Null = struct { pub inline fn isEmpty(self: @This()) bool { _ = self; return true; } }; pub const Node = struct { next: ?*@This() = null, indentation: []const u8, }; list: ?struct { head: *Node, tail: *Node, } = null, has_pending: bool = false, pub fn indent(self: *Self, node: *Node) void { if (self.list) |list| { list.tail.next = node; self.list = .{ .head = list.head, .tail = node, }; } else { self.list = .{ .head = node, .tail = node, }; } } pub fn unindent(self: *Self) void { if (self.list) |list| { if (list.head == list.tail) { self.list = null; } else { var current_level: *Node = list.head; while (true) { var next_level = current_level.next orelse break; defer current_level = next_level; if (next_level == list.tail) { current_level.next = null; self.list = .{ .head = list.head, .tail = current_level, }; return; } } unreachable; } if (list.tail.next == null) { self.list = null; } else { list.tail.next = null; } } } pub fn write(self: Self, writer: anytype) !void { if (self.list) |list| { var node: ?*const Node = list.head; while (node) |level| : (node = level.next) { try writer.writeAll(level.indentation); } } } pub inline fn isEmpty(self: Self) bool { return self.list == null; } }; test "Indent/Unindent" { var queue = IndentationQueue{}; try testing.expect(queue.list == null); var node_1 = IndentationQueue.Node{ .indentation = "", }; queue.indent(&node_1); try testing.expect(queue.list != null); try testing.expect(queue.list.?.head == queue.list.?.tail); try testing.expect(queue.list.?.head == &node_1); try testing.expect(queue.list.?.tail == &node_1); var node_2 = IndentationQueue.Node{ .indentation = "", }; queue.indent(&node_2); try testing.expect(queue.list != null); try testing.expect(queue.list.?.head != queue.list.?.tail); try testing.expect(queue.list.?.head == &node_1); try testing.expect(queue.list.?.tail == &node_2); try testing.expect(node_1.next == &node_2); var node_3 = IndentationQueue.Node{ .indentation = "", }; queue.indent(&node_3); try testing.expect(queue.list != null); try testing.expect(queue.list.?.head != queue.list.?.tail); try testing.expect(queue.list.?.head == &node_1); try testing.expect(queue.list.?.tail == &node_3); try testing.expect(node_1.next == &node_2); try testing.expect(node_2.next == &node_3); queue.unindent(); try testing.expect(queue.list != null); try testing.expect(queue.list.?.head != queue.list.?.tail); try testing.expect(queue.list.?.head == &node_1); try testing.expect(queue.list.?.tail == &node_2); try testing.expect(node_2.next == null); try testing.expect(node_1.next == &node_2); queue.unindent(); try testing.expect(queue.list != null); try testing.expect(queue.list.?.head == queue.list.?.tail); try testing.expect(queue.list.?.head == &node_1); try testing.expect(queue.list.?.tail == &node_1); try testing.expect(node_1.next == null); queue.unindent(); try testing.expect(queue.list == null); }
src/rendering/indent.zig
pub const c = @cImport(@cInclude("upnp/ixml.h")); const std = @import("std"); const xml = @import("lib.zig"); const ArenaAllocator = std.heap.ArenaAllocator; const logger = std.log.scoped(.@"xml"); fn AbstractNode(comptime NodeType: type) type { return struct { /// Get all child nodes. pub fn getChildNodes(self: *const NodeType) NodeList { return NodeList.init(c.ixmlNode_getChildNodes(handleToNode(self.handle))); } /// Get the first child of this node, if any. Useful if you expect this to be an element with a single text node. pub fn getFirstChild(self: *const NodeType) !?Node { if (c.ixmlNode_getFirstChild(handleToNode(self.handle))) |child_handle| { return try Node.fromHandle(child_handle); } return null; } /// Add a child to the end of this node. pub fn appendChild(self: *const NodeType, child: anytype) !void { try check(c.ixmlNode_appendChild(handleToNode(self.handle), handleToNode(child.handle)), "Failed to append child", "err"); } /// Convert the node into a string. pub fn toString(self: *const NodeType) !DOMString { if (c.ixmlNodetoString(handleToNode(self.handle))) |string| { return DOMString.init(std.mem.sliceTo(string, 0)); } logger.err("Failed to render node to string", .{}); return xml.Error; } /// Convert to generic node. pub fn toNode(self: *const NodeType) !Node { return try Node.fromHandle(handleToNode(self.handle)); } }; } /// Generic XML node. pub const Node = union(enum) { Document: Document, Element: Element, TextNode: TextNode, fn fromHandle(handle: *c.IXML_Node) !Node { return switch (c.ixmlNode_getNodeType(handle)) { c.eDOCUMENT_NODE => Node { .Document = Document.init(@ptrCast(*c.IXML_Document, handle)) }, c.eELEMENT_NODE => Node { .Element = Element.init(@ptrCast(*c.IXML_Element, handle)) }, c.eTEXT_NODE => Node { .TextNode = TextNode.init(handle) }, else => |node_type| { logger.err("Unhandled XML node type {}", .{node_type}); return xml.Error; } }; } }; /// XML document. pub const Document = struct { usingnamespace AbstractNode(Document); handle: *c.IXML_Document, /// Create an empty document. pub fn new() !Document { var handle: [*c]c.IXML_Document = undefined; try check(c.ixmlDocument_createDocumentEx(&handle), "Failed to create document", "err"); return Document.init(handle); } /// Parse document from sentinel-terminated string. pub fn fromString(doc: [:0]const u8) !Document { var handle: [*c]c.IXML_Document = undefined; try check(c.ixmlParseBufferEx(doc, &handle), "Cannot parse document from string", "warn"); return Document.init(handle); } pub fn init(handle: *c.IXML_Document) Document { return Document { .handle = handle }; } pub fn deinit(self: *const Document) void { c.ixmlDocument_free(self.handle); } /// Create a new element with the specified tag name, belonging to this document. Use `appendChild()` to insert it into another node. pub fn createElement(self: *const Document, tag_name: [:0]const u8) !Element { var element_handle: [*c]c.IXML_Element = undefined; try check(c.ixmlDocument_createElementEx(self.handle, tag_name, &element_handle), "Failed to create element", "err"); return Element.init(element_handle); } /// Create a text node with the specified data, belonging to this document. Use `appendChild()` to insert it into another node. pub fn createTextNode(self: *const Document, data: [:0]const u8) !TextNode { var node_handle: [*c]c.IXML_Node = undefined; try check(c.ixmlDocument_createTextNodeEx(self.handle, data, &node_handle), "Failed to create text node", "err"); return TextNode.init(node_handle); } /// Get all elements by tag name in this document. pub fn getElementsByTagName(self: *const Document, tag_name: [:0]const u8) NodeList { return NodeList.init(c.ixmlDocument_getElementsByTagName(self.handle, tag_name)); } /// Convert the document into a string. Adds the XML prolog to the beginning. pub fn toStringWithProlog(self: *const Document) !DOMString { if (c.ixmlDocumenttoString(self.handle)) |string| { return DOMString.init(std.mem.sliceTo(string, 0)); } logger.err("Failed to render document to string", .{}); return xml.Error; } }; /// XML element. pub const Element = struct { usingnamespace AbstractNode(Element); handle: *c.IXML_Element, pub fn init(handle: *c.IXML_Element) Element { return Element { .handle = handle }; } /// Get the tag name of this element. pub fn getTagName(self: *const Element) [:0]const u8 { return std.mem.sliceTo(c.ixmlElement_getTagName(self.handle), 0); } /// Get single attribute of this element, if it exists. pub fn getAttribute(self: *const Element, name: [:0]const u8) ?[:0]const u8 { if (c.ixmlElement_getAttribute(self.handle, name)) |attr| { return std.mem.sliceTo(attr, 0); } return null; } /// Set or replace an attribute of this element. pub fn setAttribute(self: *const Element, name: [:0]const u8, value: [:0]const u8) !void { try check(c.ixmlElement_setAttribute(self.handle, name, value), "Failed to set attribute", "err"); } /// Remove an attributes from this element. pub fn removeAttribute(self: *const Element, name: [:0]const u8) !void { try check(c.ixmlElement_removeAttribute(self.handle, name), "Failed to remove attriute", "err"); } /// Get all attributes of this element. pub fn getAttributes(self: *const Element) AttributeMap { return AttributeMap.init(c.ixmlNode_getAttributes(handleToNode(self.handle))); } /// Get all child elements with the specified tag name. pub fn getElementsByTagName(self: *const Element, tag_name: [:0]const u8) NodeList { return NodeList.init(c.ixmlElement_getElementsByTagName(self.handle, tag_name)); } }; /// XML text node, which only contains a string value. pub const TextNode = struct { usingnamespace AbstractNode(TextNode); handle: *c.IXML_Node, pub fn init(handle: *c.IXML_Node) TextNode { return TextNode { .handle = handle }; } /// Get the string value of this node. pub fn getValue(self: *const TextNode) [:0]const u8 { return std.mem.sliceTo(c.ixmlNode_getNodeValue(self.handle), 0); } /// Set the string value of this node. pub fn setValue(self: *const TextNode, value: [:0]const u8) !void { try check(c.ixmlNode_setNodeValue(self.handle, value), "Failed to set text node value", "err"); } }; /// List of generic nodes belonging to a parent node. pub const NodeList = struct { handle: ?*c.IXML_NodeList, pub fn init(handle: ?*c.IXML_NodeList) NodeList { return NodeList { .handle = handle }; } /// Count how many nodes are in this list. pub fn getLength(self: *const NodeList) usize { return if (self.handle) |h| c.ixmlNodeList_length(h) else 0; } /// Get a node by index. Returns an error if the item doesn't exist. pub fn getItem(self: *const NodeList, index: usize) !Node { if (self.handle) |h| { if (c.ixmlNodeList_item(h, index)) |item_handle| { return try Node.fromHandle(item_handle); } logger.err("Cannot query node list item", .{}); return xml.Error; } logger.err("Cannot query empty node list", .{}); return xml.Error; } /// Asserts that this list has one item, then retrieves it. pub fn getSingleItem(self: *const NodeList) !Node { const length = self.getLength(); if (length != 1) { logger.warn("Node list expected to have 1 item, actual {d}", .{length}); return xml.Error; } return self.getItem(0); } /// Return a new iterator for this list. pub fn iterator(self: *const NodeList) Iterator { return Iterator.init(self); } /// Read-only node list iterator pub const Iterator = struct { node_list: *const NodeList, length: usize, idx: usize = 0, fn init(node_list: *const NodeList) Iterator { return Iterator { .node_list = node_list, .length = node_list.getLength(), }; } /// Get the next item in the list, if any. pub fn next(self: *Iterator) !?Node { if (self.idx < self.length) { var node = try self.node_list.getItem(self.idx); self.idx += 1; return node; } return null; } }; }; /// Attributes for some XML element. pub const AttributeMap = struct { handle: *c.IXML_NamedNodeMap, pub fn init(handle: *c.IXML_NamedNodeMap) AttributeMap { return AttributeMap { .handle = handle }; } /// Get a text node for the corresponding attribute name, if it exists. pub fn getNamedItem(self: *const AttributeMap, name: [:0]const u8) ?TextNode { if (c.ixmlNamedNodeMap_getNamedItem(self.handle, name)) |child_handle| { return TextNode.init(child_handle); } return null; } }; /// A specially allocated string. You must call `deinit()` when you're done with it. pub const DOMString = struct { /// The actual string. string: [:0]const u8, pub fn init(string: [:0]const u8) DOMString { return DOMString { .string = string }; } pub fn deinit(self: *DOMString) void { c.ixmlFreeDOMString(@intToPtr(*u8, @ptrToInt(self.string.ptr))); } }; inline fn check(err: c_int, comptime message: []const u8, comptime severity: []const u8) !void { if (err != c.IXML_SUCCESS) { @field(logger, severity)(message ++ ": {d}", .{err}); // TODO convert err to a more useful string return xml.Error; } } inline fn handleToNode(handle: anytype) *c.IXML_Node { return @ptrCast(*c.IXML_Node, handle); }
src/xml.zig
const std = @import("std"); const parse = @import("parse.zig"); const LispToken = parse.LispToken; const LispTokenizer = parse.LispTokenizer; const LispParser = parse.LispParser; const interpret = @import("interpret.zig"); const LispExpr = interpret.LispExpr; const LispInterpreter = interpret.LispInterpreter; const library = @import("library.zig"); pub fn main() !void { var main_allocator = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = main_allocator.deinit(); const allocator = &main_allocator.allocator; var core = try library.initCore(allocator); defer core.deinit(); var interpreter = LispInterpreter.init(allocator, &core); defer interpreter.deinit(); var args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); for (args[1..]) |path| try run_file(allocator, &interpreter, path); try repl(allocator, &interpreter); } fn run_file(allocator: *std.mem.Allocator, interpreter: *LispInterpreter, path: []const u8) !void { const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); var source = blk: { var file = try std.fs.cwd().openFile(path, .{ .read = true }); defer file.close(); var source = std.ArrayList(u8).init(allocator); const len = try file.getEndPos(); try file.reader().readAllArrayList(&source, len); break :blk source; }; defer source.deinit(); var tokenizer = LispTokenizer.init(source.items); var tokens = std.ArrayList(LispToken).init(allocator); defer tokens.deinit(); while (try tokenizer.next()) |token| try tokens.append(token); var parser = LispParser.init(interpreter, source.items, tokens.items); while (try parser.next()) |expr| { _ = interpreter.eval(expr) catch |err| try stderr.print("{}\n", .{err}); } } fn repl(allocator: *std.mem.Allocator, interpreter: *LispInterpreter) !void { const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); const stdin = std.io.getStdIn().reader(); repl_loop: while (true) { const PROMPT = ">> "; _ = try stdout.write(PROMPT); var source = std.ArrayList(u8).init(allocator); defer source.deinit(); var parens: usize = 0; while (true) { const c = stdin.readByte() catch |err| switch (err) { error.EndOfStream => break :repl_loop, else => return err, }; try source.append(c); switch (c) { '(' => parens += 1, ')' => { if (parens > 0) { parens -= 1; } else { try stderr.print("{}\n", .{error.REPLOverclosedParen}); continue :repl_loop; } }, '\n' => { if (parens > 0) { _ = try stdout.write(" " ** PROMPT.len); } else { break; } }, else => {}, } } var tokenizer = LispTokenizer.init(source.items); var tokens = std.ArrayList(LispToken).init(allocator); defer tokens.deinit(); while (try tokenizer.next()) |token| try tokens.append(token); var parser = LispParser.init(interpreter, source.items, tokens.items); while (try parser.next()) |expr| { if (interpreter.eval(expr)) |result| { try stdout.print("{s}\n", .{result}); } else |err| { try stderr.print("{s}\n", .{err}); } } } }
src/main.zig
//-------------------------------------------------------------------------------- // Section: Types (24) //-------------------------------------------------------------------------------- const CLSID_CEventSystem_Value = Guid.initString("4e14fba2-2e22-11d1-9964-00c04fbbb345"); pub const CLSID_CEventSystem = &CLSID_CEventSystem_Value; const CLSID_CEventPublisher_Value = Guid.initString("ab944620-79c6-11d1-88f9-0080c7d771bf"); pub const CLSID_CEventPublisher = &CLSID_CEventPublisher_Value; const CLSID_CEventClass_Value = Guid.initString("cdbec9c0-7a68-11d1-88f9-0080c7d771bf"); pub const CLSID_CEventClass = &CLSID_CEventClass_Value; const CLSID_CEventSubscription_Value = Guid.initString("7542e960-79c7-11d1-88f9-0080c7d771bf"); pub const CLSID_CEventSubscription = &CLSID_CEventSubscription_Value; const CLSID_EventObjectChange_Value = Guid.initString("d0565000-9df4-11d1-a281-00c04fca0aa7"); pub const CLSID_EventObjectChange = &CLSID_EventObjectChange_Value; const CLSID_EventObjectChange2_Value = Guid.initString("bb07bacd-cd56-4e63-a8ff-cbf0355fb9f4"); pub const CLSID_EventObjectChange2 = &CLSID_EventObjectChange2_Value; // TODO: this type is limited to platform 'windows5.0' const IID_IEventSystem_Value = Guid.initString("4e14fb9f-2e22-11d1-9964-00c04fbbb345"); pub const IID_IEventSystem = &IID_IEventSystem_Value; pub const IEventSystem = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Query: fn( self: *const IEventSystem, progID: ?BSTR, queryCriteria: ?BSTR, errorIndex: ?*i32, ppInterface: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Store: fn( self: *const IEventSystem, ProgID: ?BSTR, pInterface: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IEventSystem, progID: ?BSTR, queryCriteria: ?BSTR, errorIndex: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventObjectChangeEventClassID: fn( self: *const IEventSystem, pbstrEventClassID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryS: fn( self: *const IEventSystem, progID: ?BSTR, queryCriteria: ?BSTR, ppInterface: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveS: fn( self: *const IEventSystem, progID: ?BSTR, queryCriteria: ?BSTR, ) 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 IEventSystem_Query(self: *const T, progID: ?BSTR, queryCriteria: ?BSTR, errorIndex: ?*i32, ppInterface: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).Query(@ptrCast(*const IEventSystem, self), progID, queryCriteria, errorIndex, ppInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSystem_Store(self: *const T, ProgID: ?BSTR, pInterface: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).Store(@ptrCast(*const IEventSystem, self), ProgID, pInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSystem_Remove(self: *const T, progID: ?BSTR, queryCriteria: ?BSTR, errorIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).Remove(@ptrCast(*const IEventSystem, self), progID, queryCriteria, errorIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSystem_get_EventObjectChangeEventClassID(self: *const T, pbstrEventClassID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).get_EventObjectChangeEventClassID(@ptrCast(*const IEventSystem, self), pbstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSystem_QueryS(self: *const T, progID: ?BSTR, queryCriteria: ?BSTR, ppInterface: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).QueryS(@ptrCast(*const IEventSystem, self), progID, queryCriteria, ppInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSystem_RemoveS(self: *const T, progID: ?BSTR, queryCriteria: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSystem.VTable, self.vtable).RemoveS(@ptrCast(*const IEventSystem, self), progID, queryCriteria); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventPublisher_Value = Guid.initString("e341516b-2e32-11d1-9964-00c04fbbb345"); pub const IID_IEventPublisher = &IID_IEventPublisher_Value; pub const IEventPublisher = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PublisherID: fn( self: *const IEventPublisher, pbstrPublisherID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PublisherID: fn( self: *const IEventPublisher, bstrPublisherID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PublisherName: fn( self: *const IEventPublisher, pbstrPublisherName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PublisherName: fn( self: *const IEventPublisher, bstrPublisherName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PublisherType: fn( self: *const IEventPublisher, pbstrPublisherType: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PublisherType: fn( self: *const IEventPublisher, bstrPublisherType: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OwnerSID: fn( self: *const IEventPublisher, pbstrOwnerSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OwnerSID: fn( self: *const IEventPublisher, bstrOwnerSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IEventPublisher, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IEventPublisher, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultProperty: fn( self: *const IEventPublisher, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutDefaultProperty: fn( self: *const IEventPublisher, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveDefaultProperty: fn( self: *const IEventPublisher, bstrPropertyName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultPropertyCollection: fn( self: *const IEventPublisher, collection: ?*?*IEventObjectCollection, ) 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 IEventPublisher_get_PublisherID(self: *const T, pbstrPublisherID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).get_PublisherID(@ptrCast(*const IEventPublisher, self), pbstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_put_PublisherID(self: *const T, bstrPublisherID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).put_PublisherID(@ptrCast(*const IEventPublisher, self), bstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_get_PublisherName(self: *const T, pbstrPublisherName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).get_PublisherName(@ptrCast(*const IEventPublisher, self), pbstrPublisherName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_put_PublisherName(self: *const T, bstrPublisherName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).put_PublisherName(@ptrCast(*const IEventPublisher, self), bstrPublisherName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_get_PublisherType(self: *const T, pbstrPublisherType: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).get_PublisherType(@ptrCast(*const IEventPublisher, self), pbstrPublisherType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_put_PublisherType(self: *const T, bstrPublisherType: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).put_PublisherType(@ptrCast(*const IEventPublisher, self), bstrPublisherType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_get_OwnerSID(self: *const T, pbstrOwnerSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).get_OwnerSID(@ptrCast(*const IEventPublisher, self), pbstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_put_OwnerSID(self: *const T, bstrOwnerSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).put_OwnerSID(@ptrCast(*const IEventPublisher, self), bstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).get_Description(@ptrCast(*const IEventPublisher, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).put_Description(@ptrCast(*const IEventPublisher, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_GetDefaultProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).GetDefaultProperty(@ptrCast(*const IEventPublisher, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_PutDefaultProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).PutDefaultProperty(@ptrCast(*const IEventPublisher, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_RemoveDefaultProperty(self: *const T, bstrPropertyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).RemoveDefaultProperty(@ptrCast(*const IEventPublisher, self), bstrPropertyName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventPublisher_GetDefaultPropertyCollection(self: *const T, collection: ?*?*IEventObjectCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IEventPublisher.VTable, self.vtable).GetDefaultPropertyCollection(@ptrCast(*const IEventPublisher, self), collection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventClass_Value = Guid.initString("fb2b72a0-7a68-11d1-88f9-0080c7d771bf"); pub const IID_IEventClass = &IID_IEventClass_Value; pub const IEventClass = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventClassID: fn( self: *const IEventClass, pbstrEventClassID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventClassID: fn( self: *const IEventClass, bstrEventClassID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventClassName: fn( self: *const IEventClass, pbstrEventClassName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventClassName: fn( self: *const IEventClass, bstrEventClassName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OwnerSID: fn( self: *const IEventClass, pbstrOwnerSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OwnerSID: fn( self: *const IEventClass, bstrOwnerSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FiringInterfaceID: fn( self: *const IEventClass, pbstrFiringInterfaceID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FiringInterfaceID: fn( self: *const IEventClass, bstrFiringInterfaceID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IEventClass, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IEventClass, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CustomConfigCLSID: fn( self: *const IEventClass, pbstrCustomConfigCLSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CustomConfigCLSID: fn( self: *const IEventClass, bstrCustomConfigCLSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TypeLib: fn( self: *const IEventClass, pbstrTypeLib: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TypeLib: fn( self: *const IEventClass, bstrTypeLib: ?BSTR, ) 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 IEventClass_get_EventClassID(self: *const T, pbstrEventClassID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_EventClassID(@ptrCast(*const IEventClass, self), pbstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_EventClassID(self: *const T, bstrEventClassID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_EventClassID(@ptrCast(*const IEventClass, self), bstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_EventClassName(self: *const T, pbstrEventClassName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_EventClassName(@ptrCast(*const IEventClass, self), pbstrEventClassName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_EventClassName(self: *const T, bstrEventClassName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_EventClassName(@ptrCast(*const IEventClass, self), bstrEventClassName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_OwnerSID(self: *const T, pbstrOwnerSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_OwnerSID(@ptrCast(*const IEventClass, self), pbstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_OwnerSID(self: *const T, bstrOwnerSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_OwnerSID(@ptrCast(*const IEventClass, self), bstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_FiringInterfaceID(self: *const T, pbstrFiringInterfaceID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_FiringInterfaceID(@ptrCast(*const IEventClass, self), pbstrFiringInterfaceID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_FiringInterfaceID(self: *const T, bstrFiringInterfaceID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_FiringInterfaceID(@ptrCast(*const IEventClass, self), bstrFiringInterfaceID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_Description(@ptrCast(*const IEventClass, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_Description(@ptrCast(*const IEventClass, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_CustomConfigCLSID(self: *const T, pbstrCustomConfigCLSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_CustomConfigCLSID(@ptrCast(*const IEventClass, self), pbstrCustomConfigCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_CustomConfigCLSID(self: *const T, bstrCustomConfigCLSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_CustomConfigCLSID(@ptrCast(*const IEventClass, self), bstrCustomConfigCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_get_TypeLib(self: *const T, pbstrTypeLib: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).get_TypeLib(@ptrCast(*const IEventClass, self), pbstrTypeLib); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass_put_TypeLib(self: *const T, bstrTypeLib: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass.VTable, self.vtable).put_TypeLib(@ptrCast(*const IEventClass, self), bstrTypeLib); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventClass2_Value = Guid.initString("fb2b72a1-7a68-11d1-88f9-0080c7d771bf"); pub const IID_IEventClass2 = &IID_IEventClass2_Value; pub const IEventClass2 = extern struct { pub const VTable = extern struct { base: IEventClass.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PublisherID: fn( self: *const IEventClass2, pbstrPublisherID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PublisherID: fn( self: *const IEventClass2, bstrPublisherID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MultiInterfacePublisherFilterCLSID: fn( self: *const IEventClass2, pbstrPubFilCLSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MultiInterfacePublisherFilterCLSID: fn( self: *const IEventClass2, bstrPubFilCLSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AllowInprocActivation: fn( self: *const IEventClass2, pfAllowInprocActivation: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AllowInprocActivation: fn( self: *const IEventClass2, fAllowInprocActivation: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FireInParallel: fn( self: *const IEventClass2, pfFireInParallel: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FireInParallel: fn( self: *const IEventClass2, fFireInParallel: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IEventClass.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_get_PublisherID(self: *const T, pbstrPublisherID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).get_PublisherID(@ptrCast(*const IEventClass2, self), pbstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_put_PublisherID(self: *const T, bstrPublisherID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).put_PublisherID(@ptrCast(*const IEventClass2, self), bstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_get_MultiInterfacePublisherFilterCLSID(self: *const T, pbstrPubFilCLSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).get_MultiInterfacePublisherFilterCLSID(@ptrCast(*const IEventClass2, self), pbstrPubFilCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_put_MultiInterfacePublisherFilterCLSID(self: *const T, bstrPubFilCLSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).put_MultiInterfacePublisherFilterCLSID(@ptrCast(*const IEventClass2, self), bstrPubFilCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_get_AllowInprocActivation(self: *const T, pfAllowInprocActivation: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).get_AllowInprocActivation(@ptrCast(*const IEventClass2, self), pfAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_put_AllowInprocActivation(self: *const T, fAllowInprocActivation: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).put_AllowInprocActivation(@ptrCast(*const IEventClass2, self), fAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_get_FireInParallel(self: *const T, pfFireInParallel: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).get_FireInParallel(@ptrCast(*const IEventClass2, self), pfFireInParallel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventClass2_put_FireInParallel(self: *const T, fFireInParallel: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventClass2.VTable, self.vtable).put_FireInParallel(@ptrCast(*const IEventClass2, self), fFireInParallel); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventSubscription_Value = Guid.initString("4a6b0e15-2e38-11d1-9965-00c04fbbb345"); pub const IID_IEventSubscription = &IID_IEventSubscription_Value; pub const IEventSubscription = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubscriptionID: fn( self: *const IEventSubscription, pbstrSubscriptionID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubscriptionID: fn( self: *const IEventSubscription, bstrSubscriptionID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubscriptionName: fn( self: *const IEventSubscription, pbstrSubscriptionName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubscriptionName: fn( self: *const IEventSubscription, bstrSubscriptionName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PublisherID: fn( self: *const IEventSubscription, pbstrPublisherID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PublisherID: fn( self: *const IEventSubscription, bstrPublisherID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventClassID: fn( self: *const IEventSubscription, pbstrEventClassID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventClassID: fn( self: *const IEventSubscription, bstrEventClassID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MethodName: fn( self: *const IEventSubscription, pbstrMethodName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MethodName: fn( self: *const IEventSubscription, bstrMethodName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubscriberCLSID: fn( self: *const IEventSubscription, pbstrSubscriberCLSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubscriberCLSID: fn( self: *const IEventSubscription, bstrSubscriberCLSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubscriberInterface: fn( self: *const IEventSubscription, ppSubscriberInterface: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubscriberInterface: fn( self: *const IEventSubscription, pSubscriberInterface: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PerUser: fn( self: *const IEventSubscription, pfPerUser: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PerUser: fn( self: *const IEventSubscription, fPerUser: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OwnerSID: fn( self: *const IEventSubscription, pbstrOwnerSID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OwnerSID: fn( self: *const IEventSubscription, bstrOwnerSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const IEventSubscription, pfEnabled: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enabled: fn( self: *const IEventSubscription, fEnabled: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IEventSubscription, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Description: fn( self: *const IEventSubscription, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MachineName: fn( self: *const IEventSubscription, pbstrMachineName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MachineName: fn( self: *const IEventSubscription, bstrMachineName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPublisherProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutPublisherProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemovePublisherProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPublisherPropertyCollection: fn( self: *const IEventSubscription, collection: ?*?*IEventObjectCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSubscriberProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutSubscriberProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveSubscriberProperty: fn( self: *const IEventSubscription, bstrPropertyName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSubscriberPropertyCollection: fn( self: *const IEventSubscription, collection: ?*?*IEventObjectCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InterfaceID: fn( self: *const IEventSubscription, pbstrInterfaceID: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InterfaceID: fn( self: *const IEventSubscription, bstrInterfaceID: ?BSTR, ) 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 IEventSubscription_get_SubscriptionID(self: *const T, pbstrSubscriptionID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_SubscriptionID(@ptrCast(*const IEventSubscription, self), pbstrSubscriptionID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_SubscriptionID(self: *const T, bstrSubscriptionID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_SubscriptionID(@ptrCast(*const IEventSubscription, self), bstrSubscriptionID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_SubscriptionName(self: *const T, pbstrSubscriptionName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_SubscriptionName(@ptrCast(*const IEventSubscription, self), pbstrSubscriptionName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_SubscriptionName(self: *const T, bstrSubscriptionName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_SubscriptionName(@ptrCast(*const IEventSubscription, self), bstrSubscriptionName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_PublisherID(self: *const T, pbstrPublisherID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_PublisherID(@ptrCast(*const IEventSubscription, self), pbstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_PublisherID(self: *const T, bstrPublisherID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_PublisherID(@ptrCast(*const IEventSubscription, self), bstrPublisherID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_EventClassID(self: *const T, pbstrEventClassID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_EventClassID(@ptrCast(*const IEventSubscription, self), pbstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_EventClassID(self: *const T, bstrEventClassID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_EventClassID(@ptrCast(*const IEventSubscription, self), bstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_MethodName(self: *const T, pbstrMethodName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_MethodName(@ptrCast(*const IEventSubscription, self), pbstrMethodName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_MethodName(self: *const T, bstrMethodName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_MethodName(@ptrCast(*const IEventSubscription, self), bstrMethodName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_SubscriberCLSID(self: *const T, pbstrSubscriberCLSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_SubscriberCLSID(@ptrCast(*const IEventSubscription, self), pbstrSubscriberCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_SubscriberCLSID(self: *const T, bstrSubscriberCLSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_SubscriberCLSID(@ptrCast(*const IEventSubscription, self), bstrSubscriberCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_SubscriberInterface(self: *const T, ppSubscriberInterface: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_SubscriberInterface(@ptrCast(*const IEventSubscription, self), ppSubscriberInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_SubscriberInterface(self: *const T, pSubscriberInterface: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_SubscriberInterface(@ptrCast(*const IEventSubscription, self), pSubscriberInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_PerUser(self: *const T, pfPerUser: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_PerUser(@ptrCast(*const IEventSubscription, self), pfPerUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_PerUser(self: *const T, fPerUser: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_PerUser(@ptrCast(*const IEventSubscription, self), fPerUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_OwnerSID(self: *const T, pbstrOwnerSID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_OwnerSID(@ptrCast(*const IEventSubscription, self), pbstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_OwnerSID(self: *const T, bstrOwnerSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_OwnerSID(@ptrCast(*const IEventSubscription, self), bstrOwnerSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_Enabled(self: *const T, pfEnabled: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_Enabled(@ptrCast(*const IEventSubscription, self), pfEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_Enabled(self: *const T, fEnabled: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_Enabled(@ptrCast(*const IEventSubscription, self), fEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_Description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_Description(@ptrCast(*const IEventSubscription, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_Description(@ptrCast(*const IEventSubscription, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_MachineName(self: *const T, pbstrMachineName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_MachineName(@ptrCast(*const IEventSubscription, self), pbstrMachineName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_MachineName(self: *const T, bstrMachineName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_MachineName(@ptrCast(*const IEventSubscription, self), bstrMachineName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_GetPublisherProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).GetPublisherProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_PutPublisherProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).PutPublisherProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_RemovePublisherProperty(self: *const T, bstrPropertyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).RemovePublisherProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_GetPublisherPropertyCollection(self: *const T, collection: ?*?*IEventObjectCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).GetPublisherPropertyCollection(@ptrCast(*const IEventSubscription, self), collection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_GetSubscriberProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).GetSubscriberProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_PutSubscriberProperty(self: *const T, bstrPropertyName: ?BSTR, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).PutSubscriberProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName, propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_RemoveSubscriberProperty(self: *const T, bstrPropertyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).RemoveSubscriberProperty(@ptrCast(*const IEventSubscription, self), bstrPropertyName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_GetSubscriberPropertyCollection(self: *const T, collection: ?*?*IEventObjectCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).GetSubscriberPropertyCollection(@ptrCast(*const IEventSubscription, self), collection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_get_InterfaceID(self: *const T, pbstrInterfaceID: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).get_InterfaceID(@ptrCast(*const IEventSubscription, self), pbstrInterfaceID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventSubscription_put_InterfaceID(self: *const T, bstrInterfaceID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventSubscription.VTable, self.vtable).put_InterfaceID(@ptrCast(*const IEventSubscription, self), bstrInterfaceID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IFiringControl_Value = Guid.initString("e0498c93-4efe-11d1-9971-00c04fbbb345"); pub const IID_IFiringControl = &IID_IFiringControl_Value; pub const IFiringControl = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, FireSubscription: fn( self: *const IFiringControl, subscription: ?*IEventSubscription, ) 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 IFiringControl_FireSubscription(self: *const T, subscription: ?*IEventSubscription) callconv(.Inline) HRESULT { return @ptrCast(*const IFiringControl.VTable, self.vtable).FireSubscription(@ptrCast(*const IFiringControl, self), subscription); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IPublisherFilter_Value = Guid.initString("465e5cc0-7b26-11d1-88fb-0080c7d771bf"); pub const IID_IPublisherFilter = &IID_IPublisherFilter_Value; pub const IPublisherFilter = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IPublisherFilter, methodName: ?BSTR, dispUserDefined: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrepareToFire: fn( self: *const IPublisherFilter, methodName: ?BSTR, firingControl: ?*IFiringControl, ) 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 IPublisherFilter_Initialize(self: *const T, methodName: ?BSTR, dispUserDefined: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IPublisherFilter.VTable, self.vtable).Initialize(@ptrCast(*const IPublisherFilter, self), methodName, dispUserDefined); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPublisherFilter_PrepareToFire(self: *const T, methodName: ?BSTR, firingControl: ?*IFiringControl) callconv(.Inline) HRESULT { return @ptrCast(*const IPublisherFilter.VTable, self.vtable).PrepareToFire(@ptrCast(*const IPublisherFilter, self), methodName, firingControl); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IMultiInterfacePublisherFilter_Value = Guid.initString("465e5cc1-7b26-11d1-88fb-0080c7d771bf"); pub const IID_IMultiInterfacePublisherFilter = &IID_IMultiInterfacePublisherFilter_Value; pub const IMultiInterfacePublisherFilter = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IMultiInterfacePublisherFilter, pEIC: ?*IMultiInterfaceEventControl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrepareToFire: fn( self: *const IMultiInterfacePublisherFilter, iid: ?*const Guid, methodName: ?BSTR, firingControl: ?*IFiringControl, ) 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 IMultiInterfacePublisherFilter_Initialize(self: *const T, pEIC: ?*IMultiInterfaceEventControl) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfacePublisherFilter.VTable, self.vtable).Initialize(@ptrCast(*const IMultiInterfacePublisherFilter, self), pEIC); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfacePublisherFilter_PrepareToFire(self: *const T, iid: ?*const Guid, methodName: ?BSTR, firingControl: ?*IFiringControl) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfacePublisherFilter.VTable, self.vtable).PrepareToFire(@ptrCast(*const IMultiInterfacePublisherFilter, self), iid, methodName, firingControl); } };} pub usingnamespace MethodMixin(@This()); }; pub const EOC_ChangeType = enum(i32) { NewObject = 0, ModifiedObject = 1, DeletedObject = 2, }; pub const EOC_NewObject = EOC_ChangeType.NewObject; pub const EOC_ModifiedObject = EOC_ChangeType.ModifiedObject; pub const EOC_DeletedObject = EOC_ChangeType.DeletedObject; // TODO: this type is limited to platform 'windows5.0' const IID_IEventObjectChange_Value = Guid.initString("f4a07d70-2e25-11d1-9964-00c04fbbb345"); pub const IID_IEventObjectChange = &IID_IEventObjectChange_Value; pub const IEventObjectChange = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ChangedSubscription: fn( self: *const IEventObjectChange, changeType: EOC_ChangeType, bstrSubscriptionID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangedEventClass: fn( self: *const IEventObjectChange, changeType: EOC_ChangeType, bstrEventClassID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangedPublisher: fn( self: *const IEventObjectChange, changeType: EOC_ChangeType, bstrPublisherID: ?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 IEventObjectChange_ChangedSubscription(self: *const T, changeType: EOC_ChangeType, bstrSubscriptionID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectChange.VTable, self.vtable).ChangedSubscription(@ptrCast(*const IEventObjectChange, self), changeType, bstrSubscriptionID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectChange_ChangedEventClass(self: *const T, changeType: EOC_ChangeType, bstrEventClassID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectChange.VTable, self.vtable).ChangedEventClass(@ptrCast(*const IEventObjectChange, self), changeType, bstrEventClassID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectChange_ChangedPublisher(self: *const T, changeType: EOC_ChangeType, bstrPublisherID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectChange.VTable, self.vtable).ChangedPublisher(@ptrCast(*const IEventObjectChange, self), changeType, bstrPublisherID); } };} pub usingnamespace MethodMixin(@This()); }; pub const COMEVENTSYSCHANGEINFO = extern struct { cbSize: u32, changeType: EOC_ChangeType, objectId: ?BSTR, partitionId: ?BSTR, applicationId: ?BSTR, reserved: [10]Guid, }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventObjectChange2_Value = Guid.initString("7701a9c3-bd68-438f-83e0-67bf4f53a422"); pub const IID_IEventObjectChange2 = &IID_IEventObjectChange2_Value; pub const IEventObjectChange2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ChangedSubscription: fn( self: *const IEventObjectChange2, pInfo: ?*COMEVENTSYSCHANGEINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangedEventClass: fn( self: *const IEventObjectChange2, pInfo: ?*COMEVENTSYSCHANGEINFO, ) 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 IEventObjectChange2_ChangedSubscription(self: *const T, pInfo: ?*COMEVENTSYSCHANGEINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectChange2.VTable, self.vtable).ChangedSubscription(@ptrCast(*const IEventObjectChange2, self), pInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectChange2_ChangedEventClass(self: *const T, pInfo: ?*COMEVENTSYSCHANGEINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectChange2.VTable, self.vtable).ChangedEventClass(@ptrCast(*const IEventObjectChange2, self), pInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumEventObject_Value = Guid.initString("f4a07d63-2e25-11d1-9964-00c04fbbb345"); pub const IID_IEnumEventObject = &IID_IEnumEventObject_Value; pub const IEnumEventObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumEventObject, ppInterface: ?*?*IEnumEventObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumEventObject, cReqElem: u32, ppInterface: [*]?*IUnknown, cRetElem: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumEventObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumEventObject, cSkipElem: 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 IEnumEventObject_Clone(self: *const T, ppInterface: ?*?*IEnumEventObject) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumEventObject.VTable, self.vtable).Clone(@ptrCast(*const IEnumEventObject, self), ppInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumEventObject_Next(self: *const T, cReqElem: u32, ppInterface: [*]?*IUnknown, cRetElem: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumEventObject.VTable, self.vtable).Next(@ptrCast(*const IEnumEventObject, self), cReqElem, ppInterface, cRetElem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumEventObject_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumEventObject.VTable, self.vtable).Reset(@ptrCast(*const IEnumEventObject, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumEventObject_Skip(self: *const T, cSkipElem: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumEventObject.VTable, self.vtable).Skip(@ptrCast(*const IEnumEventObject, self), cSkipElem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventObjectCollection_Value = Guid.initString("f89ac270-d4eb-11d1-b682-00805fc79216"); pub const IID_IEventObjectCollection = &IID_IEventObjectCollection_Value; pub const IEventObjectCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IEventObjectCollection, ppUnkEnum: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Item: fn( self: *const IEventObjectCollection, objectID: ?BSTR, pItem: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NewEnum: fn( self: *const IEventObjectCollection, ppEnum: ?*?*IEnumEventObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IEventObjectCollection, pCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IEventObjectCollection, item: ?*VARIANT, objectID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IEventObjectCollection, objectID: ?BSTR, ) 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 IEventObjectCollection_get__NewEnum(self: *const T, ppUnkEnum: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IEventObjectCollection, self), ppUnkEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectCollection_get_Item(self: *const T, objectID: ?BSTR, pItem: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).get_Item(@ptrCast(*const IEventObjectCollection, self), objectID, pItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectCollection_get_NewEnum(self: *const T, ppEnum: ?*?*IEnumEventObject) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).get_NewEnum(@ptrCast(*const IEventObjectCollection, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectCollection_get_Count(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).get_Count(@ptrCast(*const IEventObjectCollection, self), pCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectCollection_Add(self: *const T, item: ?*VARIANT, objectID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).Add(@ptrCast(*const IEventObjectCollection, self), item, objectID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventObjectCollection_Remove(self: *const T, objectID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventObjectCollection.VTable, self.vtable).Remove(@ptrCast(*const IEventObjectCollection, self), objectID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventProperty_Value = Guid.initString("da538ee2-f4de-11d1-b6bb-00805fc79216"); pub const IID_IEventProperty = &IID_IEventProperty_Value; pub const IEventProperty = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IEventProperty, propertyName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const IEventProperty, propertyName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const IEventProperty, propertyValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Value: fn( self: *const IEventProperty, propertyValue: ?*VARIANT, ) 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 IEventProperty_get_Name(self: *const T, propertyName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventProperty.VTable, self.vtable).get_Name(@ptrCast(*const IEventProperty, self), propertyName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventProperty_put_Name(self: *const T, propertyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IEventProperty.VTable, self.vtable).put_Name(@ptrCast(*const IEventProperty, self), propertyName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventProperty_get_Value(self: *const T, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventProperty.VTable, self.vtable).get_Value(@ptrCast(*const IEventProperty, self), propertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventProperty_put_Value(self: *const T, propertyValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IEventProperty.VTable, self.vtable).put_Value(@ptrCast(*const IEventProperty, self), propertyValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEventControl_Value = Guid.initString("0343e2f4-86f6-11d1-b760-00c04fb926af"); pub const IID_IEventControl = &IID_IEventControl_Value; pub const IEventControl = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, SetPublisherFilter: fn( self: *const IEventControl, methodName: ?BSTR, pPublisherFilter: ?*IPublisherFilter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AllowInprocActivation: fn( self: *const IEventControl, pfAllowInprocActivation: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AllowInprocActivation: fn( self: *const IEventControl, fAllowInprocActivation: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSubscriptions: fn( self: *const IEventControl, methodName: ?BSTR, optionalCriteria: ?BSTR, optionalErrorIndex: ?*i32, ppCollection: ?*?*IEventObjectCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultQuery: fn( self: *const IEventControl, methodName: ?BSTR, criteria: ?BSTR, errorIndex: ?*i32, ) 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 IEventControl_SetPublisherFilter(self: *const T, methodName: ?BSTR, pPublisherFilter: ?*IPublisherFilter) callconv(.Inline) HRESULT { return @ptrCast(*const IEventControl.VTable, self.vtable).SetPublisherFilter(@ptrCast(*const IEventControl, self), methodName, pPublisherFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventControl_get_AllowInprocActivation(self: *const T, pfAllowInprocActivation: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventControl.VTable, self.vtable).get_AllowInprocActivation(@ptrCast(*const IEventControl, self), pfAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventControl_put_AllowInprocActivation(self: *const T, fAllowInprocActivation: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IEventControl.VTable, self.vtable).put_AllowInprocActivation(@ptrCast(*const IEventControl, self), fAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventControl_GetSubscriptions(self: *const T, methodName: ?BSTR, optionalCriteria: ?BSTR, optionalErrorIndex: ?*i32, ppCollection: ?*?*IEventObjectCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IEventControl.VTable, self.vtable).GetSubscriptions(@ptrCast(*const IEventControl, self), methodName, optionalCriteria, optionalErrorIndex, ppCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEventControl_SetDefaultQuery(self: *const T, methodName: ?BSTR, criteria: ?BSTR, errorIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IEventControl.VTable, self.vtable).SetDefaultQuery(@ptrCast(*const IEventControl, self), methodName, criteria, errorIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IMultiInterfaceEventControl_Value = Guid.initString("0343e2f5-86f6-11d1-b760-00c04fb926af"); pub const IID_IMultiInterfaceEventControl = &IID_IMultiInterfaceEventControl_Value; pub const IMultiInterfaceEventControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetMultiInterfacePublisherFilter: fn( self: *const IMultiInterfaceEventControl, classFilter: ?*IMultiInterfacePublisherFilter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSubscriptions: fn( self: *const IMultiInterfaceEventControl, eventIID: ?*const Guid, bstrMethodName: ?BSTR, optionalCriteria: ?BSTR, optionalErrorIndex: ?*i32, ppCollection: ?*?*IEventObjectCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultQuery: fn( self: *const IMultiInterfaceEventControl, eventIID: ?*const Guid, bstrMethodName: ?BSTR, bstrCriteria: ?BSTR, errorIndex: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AllowInprocActivation: fn( self: *const IMultiInterfaceEventControl, pfAllowInprocActivation: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AllowInprocActivation: fn( self: *const IMultiInterfaceEventControl, fAllowInprocActivation: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FireInParallel: fn( self: *const IMultiInterfaceEventControl, pfFireInParallel: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FireInParallel: fn( self: *const IMultiInterfaceEventControl, fFireInParallel: BOOL, ) 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 IMultiInterfaceEventControl_SetMultiInterfacePublisherFilter(self: *const T, classFilter: ?*IMultiInterfacePublisherFilter) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).SetMultiInterfacePublisherFilter(@ptrCast(*const IMultiInterfaceEventControl, self), classFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_GetSubscriptions(self: *const T, eventIID: ?*const Guid, bstrMethodName: ?BSTR, optionalCriteria: ?BSTR, optionalErrorIndex: ?*i32, ppCollection: ?*?*IEventObjectCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).GetSubscriptions(@ptrCast(*const IMultiInterfaceEventControl, self), eventIID, bstrMethodName, optionalCriteria, optionalErrorIndex, ppCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_SetDefaultQuery(self: *const T, eventIID: ?*const Guid, bstrMethodName: ?BSTR, bstrCriteria: ?BSTR, errorIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).SetDefaultQuery(@ptrCast(*const IMultiInterfaceEventControl, self), eventIID, bstrMethodName, bstrCriteria, errorIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_get_AllowInprocActivation(self: *const T, pfAllowInprocActivation: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).get_AllowInprocActivation(@ptrCast(*const IMultiInterfaceEventControl, self), pfAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_put_AllowInprocActivation(self: *const T, fAllowInprocActivation: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).put_AllowInprocActivation(@ptrCast(*const IMultiInterfaceEventControl, self), fAllowInprocActivation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_get_FireInParallel(self: *const T, pfFireInParallel: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).get_FireInParallel(@ptrCast(*const IMultiInterfaceEventControl, self), pfFireInParallel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMultiInterfaceEventControl_put_FireInParallel(self: *const T, fFireInParallel: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IMultiInterfaceEventControl.VTable, self.vtable).put_FireInParallel(@ptrCast(*const IMultiInterfaceEventControl, self), fFireInParallel); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDontSupportEventSubscription_Value = Guid.initString("784121f1-62a6-4b89-855f-d65f296de83a"); pub const IID_IDontSupportEventSubscription = &IID_IDontSupportEventSubscription_Value; pub const IDontSupportEventSubscription = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); };} 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 (7) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const BSTR = @import("../../foundation.zig").BSTR; const HRESULT = @import("../../foundation.zig").HRESULT; const IDispatch = @import("../../system/com.zig").IDispatch; const IUnknown = @import("../../system/com.zig").IUnknown; const VARIANT = @import("../../system/com.zig").VARIANT; 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/com/events.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const Rng = std.rand.DefaultPrng; fn choose(xs: anytype, rand: std.rand.Random) @TypeOf(&xs[0]) { assert(xs.len > 0); return &xs[rand.uintLessThan(usize, xs.len)]; } const WorldHash = struct { state: u64 = 0x34bbf6d13d813f47, const mul = 0xc6a4a7935bd1e995; fn update(self: *WorldHash, val: u64) void { var k = val *% mul; k ^= (k >> 47); self.state = ((k *% mul) ^ self.state) *% mul; } fn finalize(self: WorldHash) u64 { var hash = self.state; hash ^= (hash >> 47); hash *%= mul; hash ^= (hash >> 47); return hash; } }; const Vec2 = @import("geometry.zig").Vec2; const Visibility = @import("vision.zig").Visibility; pub const TileKind = enum { empty, solid }; pub const Tile = struct { kind: TileKind, is_visible: bool, is_visited: bool, }; const Player = struct { // invariant: this should be non-empty and contain no duplicates const Locs = std.ArrayList(Vec2); locs: Locs, omniscient: bool, fn deinit(self: Player) void { self.locs.deinit(); } }; const Map = struct { width: u15, height: u15, tiles: []Tile, // all positions we should consider for player positions next time we call `recomputeVisibility`. // it's fine for this list to contain duplicates. next_visible_candidates: PosBuf, // conceptually this state is only used in `recomputeVisibility`, // but we reuse the allocation marked_visible_buf: PosBuf, const PosBuf = std.ArrayListUnmanaged(Vec2); fn init(alloc: Allocator, rand: std.rand.Random, width: u15, height: u15) !Map { const tiles = try alloc.alloc(Tile, @as(usize, width) * @as(usize, height)); for (tiles) |*t| t.* = .{ .is_visible = false, .is_visited = false, .kind = if (rand.uintLessThan(u32, 5) == 0) TileKind.empty else TileKind.solid, }; var self = Map{ .width = width, .height = height, .tiles = tiles, .next_visible_candidates = PosBuf{}, .marked_visible_buf = PosBuf{}, }; self.placeRooms(rand); return self; } fn placeRooms(self: *Map, rand: std.rand.Random) void { assert(self.width == 80 and self.height == 24); // will have to be changed if this changes var group: i16 = 0; while (group < 16) : (group += 1) { // compute the widths of boundaries between rooms var boundaries = [1]u8{1} ** 6; { var i: u32 = 0; while (i < 3) : (i += 1) choose(&boundaries, rand).* += 1; } // place rooms on the map var room: usize = 0; var y: i16 = 0; const base_x = group * 5 + 1; while (room < 5) : (room += 1) { y += boundaries[room]; if (rand.uintLessThan(usize, 7) == 0) { y += 3; continue; } comptime var i = 0; inline while (i < 3) : (i += 1) { comptime var j = 0; inline while (j < 3) : (j += 1) self.tile(Vec2.new(base_x + j, y)).?.kind = TileKind.empty; y += 1; } } } } fn deinit(self: *Map, alloc: Allocator) void { alloc.free(self.tiles); self.next_visible_candidates.deinit(alloc); self.marked_visible_buf.deinit(alloc); } fn resetVisibility(self: *Map, status: bool) void { for (self.tiles) |*t| t.is_visible = status; } // collect all the tiles visible from `at` into `marked_visible_buf` in sorted order. // return the number of tiles. fn computeVisibility(self: *Map, alloc: Allocator, origin: Vec2) ?usize { self.marked_visible_buf.clearRetainingCapacity(); (Visibility(struct { alloc: Allocator, map: *Map, const Self = @This(); pub fn isOpaque(self_: Self, at: Vec2) bool { return self_.map.isSolid(at); } pub fn magnitude(at: Vec2) u32 { return Vec2.new(0, 0).dist(at); } pub fn markVisible(self_: Self, at: Vec2) !void { if (self_.map.tile(at)) |t| { if (t.is_visible) return error.Bailout; self_.map.marked_visible_buf.append(self_.alloc, at) catch {}; } } }, error{Bailout}){ .world = .{ .alloc = alloc, .map = self }, .origin = origin, .max_distance = 50, }).compute() catch |e| switch (e) { error.Bailout => { self.marked_visible_buf.clearRetainingCapacity(); return null; }, }; assert(self.marked_visible_buf.items.len > 0); // sort visible tiles (specific order is irrelevant, just needs to be consistent) std.sort.sort(Vec2, self.marked_visible_buf.items, {}, struct { fn lt(_: void, lhs: Vec2, rhs: Vec2) bool { return lhs.serialize() < rhs.serialize(); } }.lt); // deduplicate if (self.marked_visible_buf.items.len > 1) { const visible_tiles = self.marked_visible_buf.items; var read_idx: usize = 1; var write_idx: usize = 1; while (read_idx < visible_tiles.len) : (read_idx += 1) { const lhs = visible_tiles[read_idx - 1]; const rhs = visible_tiles[read_idx]; if (!lhs.eq(rhs)) { visible_tiles[write_idx] = rhs; write_idx += 1; } } self.marked_visible_buf.shrinkRetainingCapacity(write_idx); } return self.marked_visible_buf.items.len; } fn hashVisibleBuf(self: Map, at: Vec2) u64 { var hasher = WorldHash{}; for (self.marked_visible_buf.items) |pos| { const til = self.tile(pos).?; hasher.update(pos.serialize() -% at.serialize()); hasher.update(@enumToInt(til.kind)); } return hasher.finalize(); } fn contains(self: Map, at: Vec2) bool { return 0 <= at.x and at.x < self.width and 0 <= at.y and at.y < self.height; } fn tileIdx(width: u16, at: Vec2) usize { return @intCast(usize, at.y) * width + @intCast(usize, at.x); } fn tile(self: Map, at: Vec2) ?*Tile { if (self.contains(at)) { return &self.tiles[tileIdx(self.width, at)]; } else { return null; } } fn isSolid(self: Map, at: Vec2) bool { return (self.tile(at) orelse return true).kind == .solid; } fn surroundings(self: Map, at: Vec2) u64 { var result: [8]u8 = undefined; comptime var i = 0; inline for ([3]i2{ -1, 0, 1 }) |dy| { inline for ([3]i2{ -1, 0, 1 }) |dx| { if (dx != 0 or dy != 0) { const pos = Vec2.new(dx, dy).add(at); result[i] = if (self.tile(pos)) |t| 1 + @as(u8, @enumToInt(t.kind)) else 0; i += 1; } } } return @bitCast(u64, result); } }; rng: Rng, alloc: Allocator, player: Player, map: Map, const World = @This(); pub fn init(alloc: Allocator, width: u15, height: u15) !World { var rng = Rng.init(std.crypto.random.int(u64)); var map = try Map.init(alloc, rng.random(), width, height); errdefer map.deinit(alloc); var locs = try Player.Locs.initCapacity(alloc, 20); locs.appendAssumeCapacity(Vec2.new(22, 3)); return World{ .rng = rng, .alloc = alloc, .player = .{ .locs = locs, .omniscient = true }, .map = map, }; } pub fn deinit(self: *World) void { self.map.deinit(self.alloc); self.player.deinit(); } pub fn hasPlayerAt(self: World, at: Vec2) bool { for (self.player.locs.items) |loc| if (loc.eq(at)) return true; return false; } pub fn mapTile(self: World, at: Vec2) ?*Tile { return self.map.tile(at); } // randomly select one of the player's locations as the canonical one, and move the rest to candidates pub fn focusPlayer(self: *World) !void { const locs = &self.player.locs; self.rng.random().shuffle(Vec2, locs.items); // at this point, the first location is the canonical one, and we will soon truncate the rest const canonical_surroundings = self.map.surroundings(locs.items[0]); self.map.next_visible_candidates.clearRetainingCapacity(); for (locs.items[1..]) |loc| if (canonical_surroundings == self.map.surroundings(loc)) try self.map.next_visible_candidates.append(self.alloc, loc); locs.shrinkRetainingCapacity(1); // add all map positions which match the surroundings as candidates { const candidates = &self.map.next_visible_candidates; const additional_candidates_start_idx = candidates.items.len; var y: i16 = 0; while (y < self.map.height) : (y += 1) { var x: i16 = 0; while (x < self.map.width) : (x += 1) { const loc = Vec2.new(x, y); if (!self.map.isSolid(loc) and canonical_surroundings == self.map.surroundings(loc)) try candidates.append(self.alloc, loc); } } // these new candidates should be visited in random order self.rng.random().shuffle(Vec2, candidates.items[additional_candidates_start_idx..]); } } pub fn movePlayer(self: *World, dx: i2, dy: i2) !void { // move all players that can be moved const locs = &self.player.locs; { var read_idx: usize = 0; var write_idx: usize = 0; while (read_idx < locs.items.len) : (read_idx += 1) { const old_loc = locs.items[read_idx]; const new_loc = old_loc.add(Vec2.new(dx, dy)); if (!self.map.isSolid(new_loc)) { locs.items[write_idx] = new_loc; write_idx += 1; } } // can't move in that direction if (write_idx == 0) return; // no changes were made locs.shrinkRetainingCapacity(write_idx); } try self.focusPlayer(); try self.recomputeVisibility(); } pub fn toggleOmniscience(self: *World) !void { self.player.omniscient = !self.player.omniscient; try self.focusPlayer(); try self.recomputeVisibility(); } pub fn recomputeVisibility(self: *World) !void { self.map.resetVisibility(self.player.omniscient); if (self.player.omniscient) return; const timer = std.time.Timer.start() catch unreachable; defer std.debug.print("computed visibility in {}µs\n", .{timer.read() / 1000}); const map = &self.map; const player_locs = &self.player.locs; assert(player_locs.items.len == 1); const canonical_player_loc = player_locs.items[0]; const canonical_vis_length = map.computeVisibility(self.alloc, canonical_player_loc) orelse // this indicates the vision computation aborted because a tile already marked as // visible was reached, but this is impossible because we just cleared everything unreachable; const canonical_vis_hash = map.hashVisibleBuf(canonical_player_loc); for (map.marked_visible_buf.items) |pos| { const tile = map.tile(pos).?; tile.is_visible = true; tile.is_visited = true; } for (map.next_visible_candidates.items) |loc| if (map.computeVisibility(self.alloc, loc)) |vis_length| if (canonical_vis_length == vis_length and canonical_vis_hash == map.hashVisibleBuf(loc)) { try player_locs.append(loc); for (map.marked_visible_buf.items) |pos| { const tile = map.tile(pos).?; assert(!tile.is_visible); tile.is_visible = true; tile.is_visited = true; } }; } pub fn jumpPlayer(self: *World) !void { self.player.locs.clearRetainingCapacity(); while (true) { const x = self.rng.random().uintLessThan(u15, self.map.width); const y = self.rng.random().uintLessThan(u15, self.map.height); const loc = Vec2.new(x, y); if (!self.map.isSolid(loc)) { self.player.locs.appendAssumeCapacity(loc); // no need to call 'focusPlayer' because there is still only 1 player try self.recomputeVisibility(); break; } } } test "compilation" { std.testing.refAllDecls(WorldHash); std.testing.refAllDecls(Player); std.testing.refAllDecls(Map); std.testing.refAllDecls(World); }
src/World.zig
usingnamespace @import("zig-pdcurses.zig"); // Special characters that are a pain to use programatically any other way pub const lrcorner:AttrChar = c.ACS_LRCORNER; pub const urcorner:AttrChar = c.ACS_URCORNER; pub const ulcorner:AttrChar = c.ACS_ULCORNER; pub const llcorner:AttrChar = c.ACS_LLCORNER; pub const plus:AttrChar = c.ACS_PLUS; pub const ltee:AttrChar = c.ACS_LTEE; pub const rtee:AttrChar = c.ACS_RTEE; pub const btee:AttrChar = c.ACS_BTEE; pub const ttee:AttrChar = c.ACS_TTEE; pub const hline:AttrChar = c.ACS_HLINE; pub const vline:AttrChar = c.ACS_VLINE; pub const cent:AttrChar = c.ACS_CENT; pub const yen:AttrChar = c.ACS_YEN; pub const peseta:AttrChar = c.ACS_PESETA; pub const half:AttrChar = c.ACS_HALF; pub const quarter:AttrChar = c.ACS_QUARTER; pub const left_ang_qu:AttrChar = c.ACS_LEFT_ANG_QU; pub const right_ang_qu:AttrChar = c.ACS_RIGHT_ANG_QU; pub const d_hline:AttrChar = c.ACS_D_HLINE; pub const d_vline:AttrChar = c.ACS_D_VLINE; pub const club:AttrChar = c.ACS_CLUB; pub const heart:AttrChar = c.ACS_HEART; pub const spade:AttrChar = c.ACS_SPADE; pub const smile:AttrChar = c.ACS_SMILE; pub const rev_smile:AttrChar = c.ACS_REV_SMILE; pub const med_bullet:AttrChar = c.ACS_MED_BULLET; pub const white_bullet:AttrChar = c.ACS_WHITE_BULLET; pub const pilcrow:AttrChar = c.ACS_PILCROW; pub const section:AttrChar = c.ACS_SECTION; pub const sup2:AttrChar = c.ACS_SUP2; pub const alpha:AttrChar = c.ACS_ALPHA; pub const beta:AttrChar = c.ACS_BETA; pub const gamma:AttrChar = c.ACS_GAMMA; pub const up_sigma:AttrChar = c.ACS_UP_SIGMA; pub const lo_sigma:AttrChar = c.ACS_LO_SIGMA; pub const mu:AttrChar = c.ACS_MU; pub const tau:AttrChar = c.ACS_TAU; pub const up_phi:AttrChar = c.ACS_UP_PHI; pub const theta:AttrChar = c.ACS_THETA; pub const omega:AttrChar = c.ACS_OMEGA; pub const delta:AttrChar = c.ACS_DELTA; pub const infinity:AttrChar = c.ACS_INFINITY; pub const lo_phi:AttrChar = c.ACS_LO_PHI; pub const epsilon:AttrChar = c.ACS_EPSILON; pub const intersect:AttrChar = c.ACS_INTERSECT; pub const triple_bar:AttrChar = c.ACS_TRIPLE_BAR; pub const division:AttrChar = c.ACS_DIVISION; pub const approx_eq:AttrChar = c.ACS_APPROX_EQ; pub const sm_bullet:AttrChar = c.ACS_SM_BULLET; pub const square_root:AttrChar = c.ACS_SQUARE_ROOT; pub const ublock:AttrChar = c.ACS_UBLOCK; pub const bblock:AttrChar = c.ACS_BBLOCK; pub const lblock:AttrChar = c.ACS_LBLOCK; pub const rblock:AttrChar = c.ACS_RBLOCK; pub const a_ordinal:AttrChar = c.ACS_A_ORDINAL; pub const o_ordinal:AttrChar = c.ACS_O_ORDINAL; pub const inv_query:AttrChar = c.ACS_INV_QUERY; pub const rev_not:AttrChar = c.ACS_REV_NOT; pub const not:AttrChar = c.ACS_NOT; pub const inv_bang:AttrChar = c.ACS_INV_BANG; pub const up_integral:AttrChar = c.ACS_UP_INTEGRAL; pub const lo_integral:AttrChar = c.ACS_LO_INTEGRAL; pub const sup_n:AttrChar = c.ACS_SUP_N; pub const center_squ:AttrChar = c.ACS_CENTER_SQU; pub const f_with_hook:AttrChar = c.ACS_F_WITH_HOOK; pub const sd_lrcorner:AttrChar = c.ACS_SD_LRCORNER; pub const sd_urcorner:AttrChar = c.ACS_SD_URCORNER; pub const sd_ulcorner:AttrChar = c.ACS_SD_ULCORNER; pub const sd_llcorner:AttrChar = c.ACS_SD_LLCORNER; pub const sd_plus:AttrChar = c.ACS_SD_PLUS; pub const sd_ltee:AttrChar = c.ACS_SD_LTEE; pub const sd_rtee:AttrChar = c.ACS_SD_RTEE; pub const sd_btee:AttrChar = c.ACS_SD_BTEE; pub const sd_ttee:AttrChar = c.ACS_SD_TTEE; pub const d_lrcorner:AttrChar = c.ACS_D_LRCORNER; pub const d_urcorner:AttrChar = c.ACS_D_URCORNER; pub const d_ulcorner:AttrChar = c.ACS_D_ULCORNER; pub const d_llcorner:AttrChar = c.ACS_D_LLCORNER; pub const d_plus:AttrChar = c.ACS_D_PLUS; pub const d_ltee:AttrChar = c.ACS_D_LTEE; pub const d_rtee:AttrChar = c.ACS_D_RTEE; pub const d_btee:AttrChar = c.ACS_D_BTEE; pub const d_ttee:AttrChar = c.ACS_D_TTEE; pub const ds_lrcorner:AttrChar = c.ACS_DS_LRCORNER; pub const ds_urcorner:AttrChar = c.ACS_DS_URCORNER; pub const ds_ulcorner:AttrChar = c.ACS_DS_ULCORNER; pub const ds_llcorner:AttrChar = c.ACS_DS_LLCORNER; pub const ds_plus:AttrChar = c.ACS_DS_PLUS; pub const ds_ltee:AttrChar = c.ACS_DS_LTEE; pub const ds_rtee:AttrChar = c.ACS_DS_RTEE; pub const ds_btee:AttrChar = c.ACS_DS_BTEE; pub const ds_ttee:AttrChar = c.ACS_DS_TTEE; pub const s1:AttrChar = c.ACS_S1; pub const s9:AttrChar = c.ACS_S9; pub const diamond:AttrChar = c.ACS_DIAMOND; pub const ckboard:AttrChar = c.ACS_CKBOARD; pub const degree:AttrChar = c.ACS_DEGREE; pub const plminus:AttrChar = c.ACS_PLMINUS; pub const bullet:AttrChar = c.ACS_BULLET; pub const larrow:AttrChar = c.ACS_LARROW; pub const rarrow:AttrChar = c.ACS_RARROW; pub const darrow:AttrChar = c.ACS_DARROW; pub const uarrow:AttrChar = c.ACS_UARROW; pub const board:AttrChar = c.ACS_BOARD; pub const ltboard:AttrChar = c.ACS_LTBOARD; pub const lantern:AttrChar = c.ACS_LANTERN; pub const block:AttrChar = c.ACS_BLOCK; pub const s3:AttrChar = c.ACS_S3; pub const s7:AttrChar = c.ACS_S7; pub const lequal:AttrChar = c.ACS_LEQUAL; pub const gequal:AttrChar = c.ACS_GEQUAL; pub const pi:AttrChar = c.ACS_PI; pub const nequal:AttrChar = c.ACS_NEQUAL; pub const sterling:AttrChar = c.ACS_STERLING; pub const bssb:AttrChar = c.ACS_BSSB; pub const ssbb:AttrChar = c.ACS_SSBB; pub const bbss:AttrChar = c.ACS_BBSS; pub const sbbs:AttrChar = c.ACS_SBBS; pub const sbss:AttrChar = c.ACS_SBSS; pub const sssb:AttrChar = c.ACS_SSSB; pub const ssbs:AttrChar = c.ACS_SSBS; pub const bsss:AttrChar = c.ACS_BSSS; pub const bsbs:AttrChar = c.ACS_BSBS; pub const sbsb:AttrChar = c.ACS_SBSB; pub const ssss:AttrChar = c.ACS_SSSS;
src/chars.zig
const Builder = @import("std").build.Builder; const Step = @import("std").build.Step; const mem = @import("std").mem; const fs = @import("std").fs; const debug = @import("std").debug; pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const tracy = b.option([]const u8, "tracy", "Enable Tracy integration. Supply path to Tracy source"); const exe_options = b.addOptions(); if (tracy != null) debug.print("BUG: need to manually edit common/tracy.zig to enable the instrumentation\n", .{}); exe_options.addOption(bool, "enable_tracy", tracy != null); const Problem = struct { year: []const u8, day: []const u8, }; const problems = [_]Problem{ .{ .year = "2021", .day = "day01" }, .{ .year = "2021", .day = "day02" }, .{ .year = "2021", .day = "day03" }, .{ .year = "2021", .day = "day04" }, .{ .year = "2021", .day = "day05" }, .{ .year = "2021", .day = "day06" }, .{ .year = "2021", .day = "day07" }, .{ .year = "2021", .day = "day08" }, .{ .year = "2021", .day = "day09" }, .{ .year = "2021", .day = "day10" }, .{ .year = "2021", .day = "day11" }, .{ .year = "2021", .day = "day12" }, .{ .year = "2021", .day = "day13" }, .{ .year = "2021", .day = "day14" }, .{ .year = "2021", .day = "day15" }, .{ .year = "2021", .day = "day16" }, .{ .year = "2021", .day = "day17" }, .{ .year = "2021", .day = "day18" }, .{ .year = "2021", .day = "day19" }, .{ .year = "2021", .day = "day20" }, .{ .year = "2021", .day = "day21" }, .{ .year = "2021", .day = "day22" }, .{ .year = "2021", .day = "day23" }, .{ .year = "2021", .day = "day24" }, .{ .year = "2021", .day = "day25" }, .{ .year = "2021", .day = "alldays" }, // alldays in one exe .{ .year = "2020", .day = "day25" }, .{ .year = "2020", .day = "day24" }, .{ .year = "2020", .day = "day23" }, .{ .year = "2020", .day = "day22" }, .{ .year = "2020", .day = "day21" }, .{ .year = "2020", .day = "day20" }, .{ .year = "2020", .day = "day19" }, .{ .year = "2020", .day = "day18" }, .{ .year = "2020", .day = "day17" }, .{ .year = "2020", .day = "day16" }, .{ .year = "2020", .day = "day15" }, .{ .year = "2020", .day = "day14" }, .{ .year = "2020", .day = "day13" }, .{ .year = "2020", .day = "day12" }, .{ .year = "2020", .day = "day11" }, .{ .year = "2020", .day = "day10" }, .{ .year = "2020", .day = "day09" }, .{ .year = "2020", .day = "day08" }, .{ .year = "2020", .day = "day07" }, .{ .year = "2020", .day = "day06" }, .{ .year = "2020", .day = "day05" }, .{ .year = "2020", .day = "day04" }, .{ .year = "2020", .day = "day03" }, .{ .year = "2020", .day = "day02" }, .{ .year = "2020", .day = "day01" }, .{ .year = "2020", .day = "alldays" }, // alldays in one exe .{ .year = "2019", .day = "day25" }, .{ .year = "2019", .day = "day24" }, .{ .year = "2019", .day = "day23" }, .{ .year = "2019", .day = "day22" }, .{ .year = "2019", .day = "day21" }, .{ .year = "2019", .day = "day20" }, .{ .year = "2019", .day = "day19" }, .{ .year = "2019", .day = "day18" }, .{ .year = "2019", .day = "day17" }, .{ .year = "2019", .day = "day16" }, .{ .year = "2019", .day = "day15" }, .{ .year = "2019", .day = "day14" }, .{ .year = "2019", .day = "day13" }, .{ .year = "2019", .day = "day12" }, .{ .year = "2019", .day = "day11" }, .{ .year = "2019", .day = "day10" }, .{ .year = "2019", .day = "day09" }, .{ .year = "2019", .day = "day08" }, .{ .year = "2019", .day = "day07" }, .{ .year = "2019", .day = "day06" }, .{ .year = "2019", .day = "day05" }, .{ .year = "2019", .day = "day04" }, .{ .year = "2019", .day = "day03" }, .{ .year = "2019", .day = "day02" }, .{ .year = "2019", .day = "day01" }, .{ .year = "2019", .day = "alldays" }, // alldays in one exe .{ .year = "2018", .day = "day25" }, .{ .year = "2018", .day = "day24" }, .{ .year = "2018", .day = "day23" }, .{ .year = "2018", .day = "day22" }, .{ .year = "2018", .day = "day21_comptime" }, .{ .year = "2018", .day = "day20" }, .{ .year = "2018", .day = "day19" }, .{ .year = "2018", .day = "day18" }, .{ .year = "2018", .day = "day17" }, .{ .year = "2018", .day = "day16" }, .{ .year = "2018", .day = "day15" }, .{ .year = "2018", .day = "day14" }, .{ .year = "2018", .day = "day13" }, .{ .year = "2018", .day = "day12" }, .{ .year = "2018", .day = "day11" }, .{ .year = "2018", .day = "day10" }, .{ .year = "2018", .day = "day09" }, .{ .year = "2018", .day = "day08" }, .{ .year = "2018", .day = "day07" }, .{ .year = "2018", .day = "day06" }, .{ .year = "2018", .day = "day05" }, .{ .year = "2018", .day = "day04" }, .{ .year = "2018", .day = "day03" }, .{ .year = "2018", .day = "day02" }, .{ .year = "2018", .day = "day01" }, .{ .year = "synacor", .day = "main" }, }; const years = [_][]const u8{ "2018", "2019", "2020", "2021", "synacor" }; const run_step = b.step("run", "Run all the days"); var runyear_step: [years.len]*Step = undefined; inline for (years) |year, i| { runyear_step[i] = b.step("run" ++ year, "Run days from " ++ year); } for (problems) |pb| { const path = b.fmt("{s}/{s}.zig", .{ pb.year, pb.day }); const exe = b.addExecutable(pb.day, path); exe.setBuildMode(mode); exe.addOptions("build_options", exe_options); // XXX Does not apply to package tools / 'tracy'. no idea how to make it work if (mem.eql(u8, pb.year, "2021")) { exe.addPackagePath("tools", "common/tools_v2.zig"); } else { exe.addPackagePath("tools", "common/tools.zig"); } if (tracy) |tracy_path| { const client_cpp = fs.path.join( b.allocator, &[_][]const u8{ tracy_path, "TracyClient.cpp" }, ) catch unreachable; exe.addIncludeDir(tracy_path); exe.addCSourceFile(client_cpp, &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" }); exe.linkLibCpp(); } //exe.install(); const installstep = &b.addInstallArtifact(exe).step; const run_cmd = exe.run(); run_cmd.step.dependOn(installstep); if (!mem.eql(u8, pb.year, "synacor")) { run_step.dependOn(&run_cmd.step); } for (runyear_step) |s, i| { if (mem.eql(u8, years[i], pb.year)) s.dependOn(&run_cmd.step); } } const test_step = b.step("test", "Test all days of 2021"); { const test_cmd = b.addTest("2021/alldays.zig"); test_cmd.addPackagePath("tools", "common/tools_v2.zig"); test_step.dependOn(&test_cmd.step); } const info_step = b.step("info", "Additional info"); { const log = b.addLog( \\ to run a single day: \\ for 2021: `zig run 2021/day03.zig --pkg-begin "tools" "common/tools_v2.zig" --pkg-end' \\ older years: `zig run 2018/day10.zig --pkg-begin "tools" "common/tools.zig" --pkg-end' \\ \\ 2019 intcode bench: (best year by far! ) \\ `zig run 2019/intcode_bench.zig --pkg-begin "tools" "common/tools.zig" --pkg-end -OReleaseFast' \\ , .{}); info_step.dependOn(&log.step); } }
build.zig
/// montecarlo.zig /// Module to perform some Monte-Carlo simulations in Zig /// const std = @import("std"); /// result statistic for Monte-Carlo simulations const Result = struct { success: usize, failed: usize }; /// type of generator for a stimulus of type T of a Monte-Carlo run fn Generator(comptime T: type) type { return fn (*std.rand.Random) T; } /// type of Monte-Carlo simulation evaluator fn Evaluator(comptime T: type) type { return fn (T) bool; } /// runs a Monte-Carlo simulation with given number of runs fn runner(comptime T: type, gen: Generator(T), eval: Evaluator(T), rand: *std.rand.Random, n: usize) Result { var res = Result{ .success = 0, .failed = 0 }; var i: usize = 0; while (i < n) : (i += 1) { const stimulus = gen(rand); if (eval(stimulus)) { res.success += 1; } else { res.failed += 1; } } return res; } /// generate random distance for pi simulation fn piGen(rnd: *std.rand.Random) f64 { const x = 2.0 * rnd.float(f64) - 1.0; const y = 2.0 * rnd.float(f64) - 1.0; return x * x + y * y; } /// check whether distance is within unit circle fn piEval(val: f64) bool { return (val < 1.0); } /// approximate Pi by counting points inside of a unit circle and /// its surrounding square /// returns a tuple of number of points inside & outside unit circle pub fn simulatePi(count: usize) f64 { // init random generator var prng = std.rand.DefaultPrng.init(0); const rnd = &prng.random; const stat = runner(f64, piGen, piEval, rnd, count); const res = 4 * @intToFloat(f64, stat.success) / @intToFloat(f64, count); return res; } // testing const testing = std.testing; fn simpleSampler(rnd: *std.rand.Random) u8 { return rnd.intRangeAtMost(u8, 0, 1); } fn trueEval(val: u8) bool { return (val > 0); } test "no samples" { var prng = std.rand.DefaultPrng.init(0); const rnd = &prng.random; const res = runner(u8, simpleSampler, trueEval, rnd, 0); try testing.expect(res.success == 0); try testing.expect(res.failed == 0); } test "100 samples" { var prng = std.rand.DefaultPrng.init(0); const rnd = &prng.random; const res = runner(u8, simpleSampler, trueEval, rnd, 100); try testing.expect(res.success + res.failed == 100); } test "calulate Pi" { const count = 1_000_000; const res = simulatePi(count); try testing.expect(std.math.absFloat(res - std.math.pi) < 1e-4); }
Zig/benchmark/src/montecarlo.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/day01.txt"); pub fn main() !void { { // Part 1 var input = split(u8, data, "\n"); var previous: usize = (try nextInt(&input)).?; var count: usize = 0; while (try nextInt(&input)) |current| { if (current > previous) { count += 1; } previous = current; } print("Part 1: {d}\n", .{count}); } { // Part 2 var input = split(u8, data, "\n"); var buf = [_]usize{ (try nextInt(&input)).?, (try nextInt(&input)).?, (try nextInt(&input)).?, }; var next: usize = 0; var sum: usize = undefined; var prev_sum: usize = buf[0] + buf[1] + buf[2]; var count: usize = 0; while (try nextInt(&input)) |current| { buf[next] = current; next += 1; next %= buf.len; sum = buf[0] + buf[1] + buf[2]; if (sum > prev_sum) { count += 1; } prev_sum = sum; } print("Part 2: {d}\n", .{count}); } } fn nextInt(iter: *std.mem.SplitIterator(u8)) !?usize { if (iter.next()) |slice| blk: { if (slice.len == 0) break :blk; return try parseInt(usize, slice, 10); } return null; } // 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/day01.zig
const std = @import("std"); const assert = std.debug.assert; const crypto = std.crypto; const fmt = std.fmt; const mem = std.mem; const AesBlock = std.crypto.core.aes.Block; const AuthenticationError = std.crypto.errors.AuthenticationError; const State = struct { blocks: [8]AesBlock, const rounds = 20; fn init(key: [Rocca.key_length]u8, nonce: [Rocca.nonce_length]u8) State { const z0 = AesBlock.fromBytes(&[_]u8{ 205, 101, 239, 35, 145, 68, 55, 113, 34, 174, 40, 215, 152, 47, 138, 66 }); const z1 = AesBlock.fromBytes(&[_]u8{ 188, 219, 137, 129, 165, 219, 181, 233, 47, 59, 77, 236, 207, 251, 192, 181 }); const k0 = AesBlock.fromBytes(key[0..16]); const k1 = AesBlock.fromBytes(key[16..32]); const zero = AesBlock.fromBytes(&([_]u8{0} ** 16)); const nonce_block = AesBlock.fromBytes(&nonce); const blocks = [8]AesBlock{ k1, nonce_block, z0, z1, nonce_block.xorBlocks(k1), zero, k0, zero, }; var state = State{ .blocks = blocks }; var i: usize = 0; while (i < rounds) : (i += 1) { state.update(z0, z1); } return state; } inline fn update(state: *State, x0: AesBlock, x1: AesBlock) void { const blocks = &state.blocks; const next: [8]AesBlock = .{ blocks[7].xorBlocks(x0), blocks[0].encrypt(blocks[7]), blocks[1].xorBlocks(blocks[6]), blocks[2].encrypt(blocks[1]), blocks[3].xorBlocks(x1), blocks[4].encrypt(blocks[3]), blocks[5].encrypt(blocks[4]), blocks[0].xorBlocks(blocks[6]), }; state.blocks = next; } fn enc(state: *State, dst: *[32]u8, src: *const [32]u8) void { const blocks = &state.blocks; const msg0 = AesBlock.fromBytes(src[0..16]); const msg1 = AesBlock.fromBytes(src[16..32]); const tmp0 = blocks[1].encrypt(blocks[5]).xorBlocks(msg0); const tmp1 = blocks[0].xorBlocks(blocks[4]).encrypt(blocks[2]).xorBlocks(msg1); dst[0..16].* = tmp0.toBytes(); dst[16..32].* = tmp1.toBytes(); state.update(msg0, msg1); } fn dec(state: *State, dst: *[32]u8, src: *const [32]u8) void { const blocks = &state.blocks; const c0 = AesBlock.fromBytes(src[0..16]); const c1 = AesBlock.fromBytes(src[16..32]); const msg0 = blocks[1].encrypt(blocks[5]).xorBlocks(c0); const msg1 = blocks[0].xorBlocks(blocks[4]).encrypt(blocks[2]).xorBlocks(c1); dst[0..16].* = msg0.toBytes(); dst[16..32].* = msg1.toBytes(); state.update(msg0, msg1); } fn decPartial(state: *State, dst: []u8, src: *const [32]u8) void { const blocks = &state.blocks; const c0 = AesBlock.fromBytes(src[0..16]); const c1 = AesBlock.fromBytes(src[16..32]); const msg0 = blocks[1].encrypt(blocks[5]).xorBlocks(c0); const msg1 = blocks[0].xorBlocks(blocks[4]).encrypt(blocks[2]).xorBlocks(c1); var padded: [32]u8 = undefined; padded[0..16].* = msg0.toBytes(); padded[16..32].* = msg1.toBytes(); mem.set(u8, padded[dst.len..], 0); mem.copy(u8, dst, padded[0..dst.len]); state.update(AesBlock.fromBytes(padded[0..16]), AesBlock.fromBytes(padded[16..32])); } fn mac(state: *State, adlen: usize, mlen: usize) [16]u8 { const blocks = &state.blocks; var adlen_bytes: [16]u8 = undefined; var mlen_bytes: [16]u8 = undefined; mem.writeIntLittle(u128, &adlen_bytes, adlen * 8); mem.writeIntLittle(u128, &mlen_bytes, mlen * 8); const adlen_block = AesBlock.fromBytes(&adlen_bytes); const mlen_block = AesBlock.fromBytes(&mlen_bytes); var i: usize = 0; while (i < rounds) : (i += 1) { state.update(adlen_block, mlen_block); } return blocks[0].xorBlocks(blocks[1]).xorBlocks(blocks[2]).xorBlocks(blocks[3]) .xorBlocks(blocks[4]).xorBlocks(blocks[5]).xorBlocks(blocks[6]).xorBlocks(blocks[7]) .toBytes(); } }; /// ROCCA is a very fast authenticated encryption system built on top of the core AES function. /// /// It has a 256 bit key, a 128 bit nonce, and processes 256 bit message blocks. /// It was designed to fully exploit the parallelism and built-in AES support of recent Intel and ARM CPUs. /// /// https://tosc.iacr.org/index.php/ToSC/article/download/8904/8480/ pub const Rocca = struct { pub const tag_length = 16; pub const nonce_length = 16; pub const key_length = 32; /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) void { assert(c.len == m.len); var state = State.init(key, npub); var src: [32]u8 align(16) = undefined; var dst: [32]u8 align(16) = undefined; var i: usize = 0; while (i + 32 <= ad.len) : (i += 32) { state.enc(&dst, ad[i..][0..32]); } if (ad.len % 32 != 0) { mem.set(u8, src[0..], 0); mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]); state.enc(&dst, &src); } i = 0; while (i + 32 <= m.len) : (i += 32) { state.enc(c[i..][0..32], m[i..][0..32]); } if (m.len % 32 != 0) { mem.set(u8, src[0..], 0); mem.copy(u8, src[0 .. m.len % 32], m[i .. i + m.len % 32]); state.enc(&dst, &src); mem.copy(u8, c[i .. i + m.len % 32], dst[0 .. m.len % 32]); } tag.* = state.mac(ad.len, m.len); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, key: [key_length]u8) AuthenticationError!void { assert(c.len == m.len); var state = State.init(key, npub); var src: [32]u8 align(16) = undefined; var dst: [32]u8 align(16) = undefined; var i: usize = 0; while (i + 32 <= ad.len) : (i += 32) { state.enc(&dst, ad[i..][0..32]); } if (ad.len % 32 != 0) { mem.set(u8, src[0..], 0); mem.copy(u8, src[0 .. ad.len % 32], ad[i .. i + ad.len % 32]); state.enc(&dst, &src); } i = 0; while (i + 32 <= m.len) : (i += 32) { state.dec(m[i..][0..32], c[i..][0..32]); } if (m.len % 32 != 0) { mem.set(u8, src[0..], 0); mem.copy(u8, src[0 .. m.len % 32], c[i .. i + m.len % 32]); state.decPartial(m[i .. i + m.len % 32], &src); } const computed_tag = state.mac(ad.len, m.len); var acc: u8 = 0; for (computed_tag) |_, j| { acc |= (computed_tag[j] ^ tag[j]); } if (acc != 0) { mem.set(u8, m, 0xaa); return error.AuthenticationFailed; } } }; const testing = std.testing; test "empty test" { const key = [_]u8{0} ** 32; const nonce = [_]u8{0} ** 16; var c = [_]u8{}; var tag: [Rocca.tag_length]u8 = undefined; var expected_tag: [Rocca.tag_length]u8 = undefined; _ = try fmt.hexToBytes(&expected_tag, "2ee37e014157fa6a24c80f13996c77bb"); Rocca.encrypt(&c, &tag, "", "", nonce, key); try testing.expectEqualSlices(u8, &tag, &expected_tag); } test "basic test" { const key = [_]u8{0} ** 32; const nonce = [_]u8{0} ** 16; const mlen = 1000; var tag: [Rocca.tag_length]u8 = undefined; const allocator = std.testing.allocator; var m = try allocator.alloc(u8, mlen); defer allocator.free(m); mem.set(u8, m[0..], 0x41); Rocca.encrypt(m[0..], &tag, m[0..], "associated data", nonce, key); try Rocca.decrypt(m[0..], m[0..], tag, "associated data", nonce, key); for (m) |x| { try testing.expectEqual(x, 0x41); } } test "test vector 1" { const key = [_]u8{0} ** 32; const nonce = [_]u8{0} ** 16; const ad = [_]u8{0} ** 32; var m = [_]u8{0} ** 64; var tag: [Rocca.tag_length]u8 = undefined; var expected_tag: [Rocca.tag_length]u8 = undefined; _ = try fmt.hexToBytes(&expected_tag, "cc728c8baedd36f14cf8938e9e0719bf"); var expected_c: [m.len]u8 = undefined; _ = try fmt.hexToBytes(&expected_c, "15892f8555ad2db4749b90926571c4b8c28b434f277793c53833cb6e41a855291784a2c7fe374b34d875fdcbe84f5b88bf3f386f2218f046a84318565026d755"); Rocca.encrypt(&m, &tag, &m, &ad, nonce, key); try testing.expectEqualSlices(u8, &tag, &expected_tag); try testing.expectEqualSlices(u8, &m, &expected_c); } test "test vector 2" { const key = [_]u8{1} ** 32; const nonce = [_]u8{1} ** 16; const ad = [_]u8{1} ** 32; var m = [_]u8{0} ** 64; var tag: [Rocca.tag_length]u8 = undefined; var expected_tag: [Rocca.tag_length]u8 = undefined; _ = try fmt.hexToBytes(&expected_tag, "bad0a53616599bfdb553788fdaabad78"); var expected_c: [m.len]u8 = undefined; _ = try fmt.hexToBytes(&expected_c, "f931a8730b2e8a3af341c83a29c30525325c170326c29d91b24d714fecf385fd88e650ef2e2c02b37b19e70bb93ff82aa96d50c9fdf05343f6e36b66ee7bda69"); Rocca.encrypt(&m, &tag, &m, &ad, nonce, key); try testing.expectEqualSlices(u8, &tag, &expected_tag); try testing.expectEqualSlices(u8, &m, &expected_c); } test "test vector 3" { var key: [32]u8 = undefined; _ = try fmt.hexToBytes(&key, "<KEY>"); var nonce: [16]u8 = undefined; _ = try fmt.hexToBytes(&nonce, "0123456789abcdef0123456789abcdef"); var ad: [32]u8 = undefined; _ = try fmt.hexToBytes(&ad, "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); var m = [_]u8{0} ** 64; var tag: [Rocca.tag_length]u8 = undefined; var expected_tag: [Rocca.tag_length]u8 = undefined; _ = try fmt.hexToBytes(&expected_tag, "6672534a8b57c287bcf56823cd1cdb5a"); var expected_c: [m.len]u8 = undefined; _ = try fmt.hexToBytes(&expected_c, "265b7e314141fd148235a5305b217ab291a2a7aeff91efd3ac603b28e0576109723422ef3f553b0b07ce7263f63502a00591de648f3ee3b05441d8313b138b5a"); Rocca.encrypt(&m, &tag, &m, &ad, nonce, key); try testing.expectEqualSlices(u8, &tag, &expected_tag); try testing.expectEqualSlices(u8, &m, &expected_c); } test "test vector 4" { const key = [_]u8{0x11} ** 16 ++ [_]u8{0x22} ** 16; const nonce = [_]u8{0x44} ** 16; var ad: [18]u8 = undefined; _ = try fmt.hexToBytes(&ad, "808182838485868788898a8b8c8d8e8f9091"); var m: [64]u8 = undefined; _ = try fmt.hexToBytes(&m, "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"); var tag: [Rocca.tag_length]u8 = undefined; var expected_tag: [Rocca.tag_length]u8 = undefined; _ = try fmt.hexToBytes(&expected_tag, "a9f2069456559de3e69d233e154ba05e"); var expected_c: [m.len]u8 = undefined; _ = try fmt.hexToBytes(&expected_c, "d9b3361abb733958fa2830b8ec374e2835c5d29aae867efbd4f6a874cc24c6c66acab1020ac2344b3eb78efe54b5a0b6f19d1bea7dbf47f1d6c966a04a3e7692"); Rocca.encrypt(&m, &tag, &m, &ad, nonce, key); try testing.expectEqualSlices(u8, &tag, &expected_tag); try testing.expectEqualSlices(u8, &m, &expected_c); }
src/main.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); /// A refspec specifies the mapping between remote and local reference names when fetch or pushing. pub const Refspec = opaque { /// Free a refspec object which has been created by Refspec.parse. pub fn deinit(self: *Refspec) void { log.debug("Refspec.deinit called", .{}); c.git_refspec_free(@ptrCast(*c.git_refspec, self)); log.debug("refspec freed successfully", .{}); } /// Get the source specifier. pub fn source(self: *const Refspec) [:0]const u8 { log.debug("Refspec.source called", .{}); const slice = std.mem.sliceTo( c.git_refspec_src(@ptrCast( *const c.git_refspec, self, )), 0, ); log.debug("source specifier: {s}", .{slice}); return slice; } /// Get the destination specifier. pub fn destination(self: *const Refspec) [:0]const u8 { log.debug("Refspec.destination called", .{}); const slice = std.mem.sliceTo( c.git_refspec_dst(@ptrCast( *const c.git_refspec, self, )), 0, ); log.debug("destination specifier: {s}", .{slice}); return slice; } /// Get the refspec's string. pub fn string(self: *const Refspec) [:0]const u8 { log.debug("Refspec.string called", .{}); const slice = std.mem.sliceTo( c.git_refspec_string(@ptrCast( *const c.git_refspec, self, )), 0, ); log.debug("refspec string: {s}", .{slice}); return slice; } /// Get the force update setting. pub fn isForceUpdate(self: *const Refspec) bool { log.debug("Refspec.isForceUpdate called", .{}); const ret = c.git_refspec_force(@ptrCast(*const c.git_refspec, self)) != 0; log.debug("is force update: {}", .{ret}); return ret; } /// Get the refspec's direction. pub fn direction(self: *const Refspec) git.Direction { log.debug("Refspec.direction called", .{}); const ret = @intToEnum( git.Direction, c.git_refspec_direction(@ptrCast( *const c.git_refspec, self, )), ); log.debug("refspec direction: {}", .{ret}); return ret; } /// Check if a refspec's source descriptor matches a reference pub fn srcMatches(self: *const Refspec, refname: [:0]const u8) bool { log.debug("Refspec.srcMatches called, refname: {s}", .{refname}); const ret = c.git_refspec_src_matches( @ptrCast(*const c.git_refspec, self), refname.ptr, ) != 0; log.debug("match: {}", .{ret}); return ret; } /// Check if a refspec's destination descriptor matches a reference pub fn destMatches(self: *const Refspec, refname: [:0]const u8) bool { log.debug("Refspec.destMatches called, refname: {s}", .{refname}); const ret = c.git_refspec_dst_matches( @ptrCast(*const c.git_refspec, self), refname.ptr, ) != 0; log.debug("match: {}", .{ret}); return ret; } /// Transform a reference to its target following the refspec's rules /// /// # Parameters /// * `name` - The name of the reference to transform. pub fn transform(self: *const Refspec, name: [:0]const u8) !git.Buf { log.debug("Refspec.transform called, name: {s}", .{name}); var ret: git.Buf = .{}; try internal.wrapCall("git_refspec_transform", .{ @ptrCast(*c.git_buf, &ret), @ptrCast(*const c.git_refspec, self), name.ptr, }); log.debug("refspec transform completed, out: {s}", .{ret.toSlice()}); return ret; } /// Transform a target reference to its source reference following the refspec's rules /// /// # Parameters /// * `name` - The name of the reference to transform. pub fn rtransform(self: *const Refspec, name: [:0]const u8) !git.Buf { log.debug("Refspec.rtransform called, name: {s}", .{name}); var ret: git.Buf = .{}; try internal.wrapCall("git_refspec_rtransform", .{ @ptrCast(*c.git_buf, &ret), @ptrCast(*const c.git_refspec, self), name.ptr, }); log.debug("refspec rtransform completed, out: {s}", .{ret.toSlice()}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/refspec.zig
const std = @import("std"); const pc_keyboard = @import("../../pc_keyboard.zig"); pub const EXTENDED_KEY_CODE: u8 = 0xE0; pub const KEY_RELEASE_CODE: u8 = 0xF0; /// Implements state logic for scancode set 1 /// /// Start: /// E0 => Extended /// >= 0x80 => Key Up /// <= 0x7F => Key Down /// /// Extended: /// >= 0x80 => Extended Key Up /// <= 0x7F => Extended Key Down pub fn advanceState(state: *pc_keyboard.DecodeState, code: u8) pc_keyboard.KeyboardError!?pc_keyboard.KeyEvent { switch (state.*) { .Start => { if (code == EXTENDED_KEY_CODE) state.* = .Extended else if (code >= 0x80 and code <= 0xFF) return pc_keyboard.KeyEvent{ .code = try mapScancode(code - 0x80), .state = .Up } else return pc_keyboard.KeyEvent{ .code = try mapScancode(code), .state = .Down }; }, .Extended => { state.* = .Start; switch (code) { 0x80...0xFF => return pc_keyboard.KeyEvent{ .code = try mapExtendedScancode(code - 0x80), .state = .Up }, else => return pc_keyboard.KeyEvent{ .code = try mapExtendedScancode(code), .state = .Down }, } }, else => unreachable, } return null; } /// Implements the single byte codes for Set 1. fn mapScancode(code: u8) pc_keyboard.KeyboardError!pc_keyboard.KeyCode { return switch (code) { 0x01 => .Escape, 0x02 => .Key1, 0x03 => .Key2, 0x04 => .Key3, 0x05 => .Key4, 0x06 => .Key5, 0x07 => .Key6, 0x08 => .Key7, 0x09 => .Key8, 0x0A => .Key9, 0x0B => .Key0, 0x0C => .Minus, 0x0D => .Equals, 0x0E => .Backspace, 0x0F => .Tab, 0x10 => .Q, 0x11 => .W, 0x12 => .E, 0x13 => .R, 0x14 => .T, 0x15 => .Y, 0x16 => .U, 0x17 => .I, 0x18 => .O, 0x19 => .P, 0x1A => .BracketSquareLeft, 0x1B => .BracketSquareRight, 0x1C => .Enter, 0x1D => .ControlLeft, 0x1E => .A, 0x1F => .S, 0x20 => .D, 0x21 => .F, 0x22 => .G, 0x23 => .H, 0x24 => .J, 0x25 => .K, 0x26 => .L, 0x27 => .SemiColon, 0x28 => .Quote, 0x29 => .BackTick, 0x2A => .ShiftLeft, 0x2B => .BackSlash, 0x2C => .Z, 0x2D => .X, 0x2E => .C, 0x2F => .V, 0x30 => .B, 0x31 => .N, 0x32 => .M, 0x33 => .Comma, 0x34 => .Fullstop, 0x35 => .Slash, 0x36 => .ShiftRight, 0x37 => .NumpadStar, 0x38 => .AltLeft, 0x39 => .Spacebar, 0x3A => .CapsLock, 0x3B => .F1, 0x3C => .F2, 0x3D => .F3, 0x3E => .F4, 0x3F => .F5, 0x40 => .F6, 0x41 => .F7, 0x42 => .F8, 0x43 => .F9, 0x44 => .F10, 0x45 => .NumpadLock, 0x46 => .ScrollLock, 0x47 => .Numpad7, 0x48 => .Numpad8, 0x49 => .Numpad9, 0x4A => .NumpadMinus, 0x4B => .Numpad4, 0x4C => .Numpad5, 0x4D => .Numpad6, 0x4E => .NumpadPlus, 0x4F => .Numpad1, 0x50 => .Numpad2, 0x51 => .Numpad3, 0x52 => .Numpad0, 0x53 => .NumpadPeriod, //0x54 //0x55 //0x56 0x57 => .F11, 0x58 => .F12, 0x81...0xD8 => mapScancode(code - 0x80), else => pc_keyboard.KeyboardError.UnknownKeyCode, }; } /// Implements the extended byte codes for set 1 (prefixed with E0) fn mapExtendedScancode(code: u8) pc_keyboard.KeyboardError!pc_keyboard.KeyCode { return switch (code) { 0x10 => .PrevTrack, 0x19 => .NextTrack, 0x1C => .NumpadEnter, 0x1D => .ControlRight, 0x20 => .Mute, 0x21 => .Calculator, 0x22 => .Play, 0x24 => .Stop, 0x2E => .VolumeDown, 0x30 => .VolumeUp, 0x32 => .WWWHome, 0x35 => .NumpadSlash, 0x38 => .AltRight, 0x47 => .Home, 0x48 => .ArrowUp, 0x49 => .PageUp, 0x4B => .ArrowLeft, 0x4D => .ArrowRight, 0x4F => .End, 0x50 => .ArrowDown, 0x51 => .PageDown, 0x52 => .Insert, 0x53 => .Delete, 0x90...0xED => mapExtendedScancode(code - 0x80), else => pc_keyboard.KeyboardError.UnknownKeyCode, }; } comptime { @import("std").testing.refAllDecls(@This()); }
src/keycode/scancodes/scancode_set1.zig
const AstGen = @This(); const std = @import("std"); const ast = std.zig.ast; const mem = std.mem; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const ArrayListUnmanaged = std.ArrayListUnmanaged; const Zir = @import("Zir.zig"); const trace = @import("tracy.zig").trace; const BuiltinFn = @import("BuiltinFn.zig"); gpa: *Allocator, tree: *const ast.Tree, instructions: std.MultiArrayList(Zir.Inst) = .{}, extra: ArrayListUnmanaged(u32) = .{}, string_bytes: ArrayListUnmanaged(u8) = .{}, /// Tracks the current byte offset within the source file. /// Used to populate line deltas in the ZIR. AstGen maintains /// this "cursor" throughout the entire AST lowering process in order /// to avoid starting over the line/column scan for every declaration, which /// would be O(N^2). source_offset: u32 = 0, /// Tracks the current line of `source_offset`. source_line: u32 = 0, /// Tracks the current column of `source_offset`. source_column: u32 = 0, /// Used for temporary allocations; freed after AstGen is complete. /// The resulting ZIR code has no references to anything in this arena. arena: *Allocator, string_table: std.StringHashMapUnmanaged(u32) = .{}, compile_errors: ArrayListUnmanaged(Zir.Inst.CompileErrors.Item) = .{}, /// The topmost block of the current function. fn_block: ?*GenZir = null, /// Maps string table indexes to the first `@import` ZIR instruction /// that uses this string as the operand. imports: std.AutoArrayHashMapUnmanaged(u32, ast.TokenIndex) = .{}, const InnerError = error{ OutOfMemory, AnalysisFail }; fn addExtra(astgen: *AstGen, extra: anytype) Allocator.Error!u32 { const fields = std.meta.fields(@TypeOf(extra)); try astgen.extra.ensureUnusedCapacity(astgen.gpa, fields.len); return addExtraAssumeCapacity(astgen, extra); } fn addExtraAssumeCapacity(astgen: *AstGen, extra: anytype) u32 { const fields = std.meta.fields(@TypeOf(extra)); const result = @intCast(u32, astgen.extra.items.len); inline for (fields) |field| { astgen.extra.appendAssumeCapacity(switch (field.field_type) { u32 => @field(extra, field.name), Zir.Inst.Ref => @enumToInt(@field(extra, field.name)), i32 => @bitCast(u32, @field(extra, field.name)), else => @compileError("bad field type"), }); } return result; } fn appendRefs(astgen: *AstGen, refs: []const Zir.Inst.Ref) !void { const coerced = @bitCast([]const u32, refs); return astgen.extra.appendSlice(astgen.gpa, coerced); } fn appendRefsAssumeCapacity(astgen: *AstGen, refs: []const Zir.Inst.Ref) void { const coerced = @bitCast([]const u32, refs); astgen.extra.appendSliceAssumeCapacity(coerced); } pub fn generate(gpa: *Allocator, tree: ast.Tree) Allocator.Error!Zir { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); var astgen: AstGen = .{ .gpa = gpa, .arena = &arena.allocator, .tree = &tree, }; defer astgen.deinit(gpa); // String table indexes 0 and 1 are reserved for special meaning. try astgen.string_bytes.appendSlice(gpa, &[_]u8{ 0, 0 }); // We expect at least as many ZIR instructions and extra data items // as AST nodes. try astgen.instructions.ensureTotalCapacity(gpa, tree.nodes.len); // First few indexes of extra are reserved and set at the end. const reserved_count = @typeInfo(Zir.ExtraIndex).Enum.fields.len; try astgen.extra.ensureTotalCapacity(gpa, tree.nodes.len + reserved_count); astgen.extra.items.len += reserved_count; var top_scope: Scope.Top = .{}; var gen_scope: GenZir = .{ .force_comptime = true, .in_defer = false, .parent = &top_scope.base, .anon_name_strategy = .parent, .decl_node_index = 0, .decl_line = 0, .astgen = &astgen, }; defer gen_scope.instructions.deinit(gpa); const container_decl: ast.full.ContainerDecl = .{ .layout_token = null, .ast = .{ .main_token = undefined, .enum_token = null, .members = tree.rootDecls(), .arg = 0, }, }; if (AstGen.structDeclInner( &gen_scope, &gen_scope.base, 0, container_decl, .Auto, )) |struct_decl_ref| { astgen.extra.items[@enumToInt(Zir.ExtraIndex.main_struct)] = @enumToInt(struct_decl_ref); } else |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, // Handled via compile_errors below. } const err_index = @enumToInt(Zir.ExtraIndex.compile_errors); if (astgen.compile_errors.items.len == 0) { astgen.extra.items[err_index] = 0; } else { try astgen.extra.ensureUnusedCapacity(gpa, 1 + astgen.compile_errors.items.len * @typeInfo(Zir.Inst.CompileErrors.Item).Struct.fields.len); astgen.extra.items[err_index] = astgen.addExtraAssumeCapacity(Zir.Inst.CompileErrors{ .items_len = @intCast(u32, astgen.compile_errors.items.len), }); for (astgen.compile_errors.items) |item| { _ = astgen.addExtraAssumeCapacity(item); } } const imports_index = @enumToInt(Zir.ExtraIndex.imports); if (astgen.imports.count() == 0) { astgen.extra.items[imports_index] = 0; } else { try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Imports).Struct.fields.len + astgen.imports.count() * @typeInfo(Zir.Inst.Imports.Item).Struct.fields.len); astgen.extra.items[imports_index] = astgen.addExtraAssumeCapacity(Zir.Inst.Imports{ .imports_len = @intCast(u32, astgen.imports.count()), }); var it = astgen.imports.iterator(); while (it.next()) |entry| { _ = astgen.addExtraAssumeCapacity(Zir.Inst.Imports.Item{ .name = entry.key_ptr.*, .token = entry.value_ptr.*, }); } } return Zir{ .instructions = astgen.instructions.toOwnedSlice(), .string_bytes = astgen.string_bytes.toOwnedSlice(gpa), .extra = astgen.extra.toOwnedSlice(gpa), }; } pub fn deinit(astgen: *AstGen, gpa: *Allocator) void { astgen.instructions.deinit(gpa); astgen.extra.deinit(gpa); astgen.string_table.deinit(gpa); astgen.string_bytes.deinit(gpa); astgen.compile_errors.deinit(gpa); astgen.imports.deinit(gpa); } pub const ResultLoc = union(enum) { /// The expression is the right-hand side of assignment to `_`. Only the side-effects of the /// expression should be generated. The result instruction from the expression must /// be ignored. discard, /// The expression has an inferred type, and it will be evaluated as an rvalue. none, /// The expression must generate a pointer rather than a value. For example, the left hand side /// of an assignment uses this kind of result location. ref, /// The callee will accept a ref, but it is not necessary, and the `ResultLoc` /// may be treated as `none` instead. none_or_ref, /// The expression will be coerced into this type, but it will be evaluated as an rvalue. ty: Zir.Inst.Ref, /// Same as `ty` but it is guaranteed that Sema will additionall perform the coercion, /// so no `as` instruction needs to be emitted. coerced_ty: Zir.Inst.Ref, /// The expression must store its result into this typed pointer. The result instruction /// from the expression must be ignored. ptr: Zir.Inst.Ref, /// The expression must store its result into this allocation, which has an inferred type. /// The result instruction from the expression must be ignored. /// Always an instruction with tag `alloc_inferred`. inferred_ptr: Zir.Inst.Ref, /// There is a pointer for the expression to store its result into, however, its type /// is inferred based on peer type resolution for a `Zir.Inst.Block`. /// The result instruction from the expression must be ignored. block_ptr: *GenZir, pub const Strategy = struct { elide_store_to_block_ptr_instructions: bool, tag: Tag, pub const Tag = enum { /// Both branches will use break_void; result location is used to communicate the /// result instruction. break_void, /// Use break statements to pass the block result value, and call rvalue() at /// the end depending on rl. Also elide the store_to_block_ptr instructions /// depending on rl. break_operand, }; }; fn strategy(rl: ResultLoc, block_scope: *GenZir) Strategy { switch (rl) { // In this branch there will not be any store_to_block_ptr instructions. .discard, .none, .none_or_ref, .ty, .coerced_ty, .ref => return .{ .tag = .break_operand, .elide_store_to_block_ptr_instructions = false, }, // The pointer got passed through to the sub-expressions, so we will use // break_void here. // In this branch there will not be any store_to_block_ptr instructions. .ptr => return .{ .tag = .break_void, .elide_store_to_block_ptr_instructions = false, }, .inferred_ptr, .block_ptr => { if (block_scope.rvalue_rl_count == block_scope.break_count) { // Neither prong of the if consumed the result location, so we can // use break instructions to create an rvalue. return .{ .tag = .break_operand, .elide_store_to_block_ptr_instructions = true, }; } else { // Allow the store_to_block_ptr instructions to remain so that // semantic analysis can turn them into bitcasts. return .{ .tag = .break_void, .elide_store_to_block_ptr_instructions = false, }; } }, } } }; pub const align_rl: ResultLoc = .{ .ty = .u16_type }; pub const bool_rl: ResultLoc = .{ .ty = .bool_type }; pub const type_rl: ResultLoc = .{ .ty = .type_type }; pub const coerced_type_rl: ResultLoc = .{ .coerced_ty = .type_type }; fn typeExpr(gz: *GenZir, scope: *Scope, type_node: ast.Node.Index) InnerError!Zir.Inst.Ref { const prev_force_comptime = gz.force_comptime; gz.force_comptime = true; defer gz.force_comptime = prev_force_comptime; return expr(gz, scope, coerced_type_rl, type_node); } /// Same as `expr` but fails with a compile error if the result type is `noreturn`. fn reachableExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, src_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const result_inst = try expr(gz, scope, rl, node); if (gz.refIsNoReturn(result_inst)) { return gz.astgen.failNodeNotes(src_node, "unreachable code", .{}, &[_]u32{ try gz.astgen.errNoteNode(node, "control flow is diverted here", .{}), }); } return result_inst; } fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); switch (node_tags[node]) { .root => unreachable, .@"usingnamespace" => unreachable, .test_decl => unreachable, .global_var_decl => unreachable, .local_var_decl => unreachable, .simple_var_decl => unreachable, .aligned_var_decl => unreachable, .switch_case => unreachable, .switch_case_one => unreachable, .container_field_init => unreachable, .container_field_align => unreachable, .container_field => unreachable, .asm_output => unreachable, .asm_input => unreachable, .assign, .assign_bit_and, .assign_bit_or, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_xor, .assign_div, .assign_sub, .assign_sub_wrap, .assign_mod, .assign_add, .assign_add_wrap, .assign_mul, .assign_mul_wrap, .add, .add_wrap, .sub, .sub_wrap, .mul, .mul_wrap, .div, .mod, .bit_and, .bit_or, .bit_shift_left, .bit_shift_right, .bit_xor, .bang_equal, .equal_equal, .greater_than, .greater_or_equal, .less_than, .less_or_equal, .array_cat, .array_mult, .bool_and, .bool_or, .@"asm", .asm_simple, .string_literal, .integer_literal, .call, .call_comma, .async_call, .async_call_comma, .call_one, .call_one_comma, .async_call_one, .async_call_one_comma, .unreachable_literal, .@"return", .@"if", .if_simple, .@"while", .while_simple, .while_cont, .bool_not, .address_of, .float_literal, .optional_type, .block, .block_semicolon, .block_two, .block_two_semicolon, .@"break", .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .array_type, .array_type_sentinel, .enum_literal, .multiline_string_literal, .char_literal, .@"defer", .@"errdefer", .@"catch", .error_union, .merge_error_sets, .switch_range, .@"await", .bit_not, .negation, .negation_wrap, .@"resume", .@"try", .slice, .slice_open, .slice_sentinel, .array_init_one, .array_init_one_comma, .array_init_dot_two, .array_init_dot_two_comma, .array_init_dot, .array_init_dot_comma, .array_init, .array_init_comma, .struct_init_one, .struct_init_one_comma, .struct_init_dot_two, .struct_init_dot_two_comma, .struct_init_dot, .struct_init_dot_comma, .struct_init, .struct_init_comma, .@"switch", .switch_comma, .@"for", .for_simple, .@"suspend", .@"continue", .@"anytype", .fn_proto_simple, .fn_proto_multi, .fn_proto_one, .fn_proto, .fn_decl, .anyframe_type, .anyframe_literal, .error_set_decl, .container_decl, .container_decl_trailing, .container_decl_two, .container_decl_two_trailing, .container_decl_arg, .container_decl_arg_trailing, .tagged_union, .tagged_union_trailing, .tagged_union_two, .tagged_union_two_trailing, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, .@"comptime", .@"nosuspend", .error_value, => return astgen.failNode(node, "invalid left-hand side to assignment", .{}), .builtin_call, .builtin_call_comma, .builtin_call_two, .builtin_call_two_comma, => { const builtin_token = main_tokens[node]; const builtin_name = tree.tokenSlice(builtin_token); // If the builtin is an invalid name, we don't cause an error here; instead // let it pass, and the error will be "invalid builtin function" later. if (BuiltinFn.list.get(builtin_name)) |info| { if (!info.allows_lvalue) { return astgen.failNode(node, "invalid left-hand side to assignment", .{}); } } }, // These can be assigned to. .unwrap_optional, .deref, .field_access, .array_access, .identifier, .grouped_expression, .@"orelse", => {}, } return expr(gz, scope, .ref, node); } /// Turn Zig AST into untyped ZIR istructions. /// When `rl` is discard, ptr, inferred_ptr, or inferred_ptr, the /// result instruction can be used to inspect whether it is isNoReturn() but that is it, /// it must otherwise not be used. fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); switch (node_tags[node]) { .root => unreachable, // Top-level declaration. .@"usingnamespace" => unreachable, // Top-level declaration. .test_decl => unreachable, // Top-level declaration. .container_field_init => unreachable, // Top-level declaration. .container_field_align => unreachable, // Top-level declaration. .container_field => unreachable, // Top-level declaration. .fn_decl => unreachable, // Top-level declaration. .global_var_decl => unreachable, // Handled in `blockExpr`. .local_var_decl => unreachable, // Handled in `blockExpr`. .simple_var_decl => unreachable, // Handled in `blockExpr`. .aligned_var_decl => unreachable, // Handled in `blockExpr`. .@"defer" => unreachable, // Handled in `blockExpr`. .@"errdefer" => unreachable, // Handled in `blockExpr`. .switch_case => unreachable, // Handled in `switchExpr`. .switch_case_one => unreachable, // Handled in `switchExpr`. .switch_range => unreachable, // Handled in `switchExpr`. .asm_output => unreachable, // Handled in `asmExpr`. .asm_input => unreachable, // Handled in `asmExpr`. .@"anytype" => unreachable, // Handled in `containerDecl`. .assign => { try assign(gz, scope, node); return rvalue(gz, rl, .void_value, node); }, .assign_bit_shift_left => { try assignShift(gz, scope, node, .shl); return rvalue(gz, rl, .void_value, node); }, .assign_bit_shift_right => { try assignShift(gz, scope, node, .shr); return rvalue(gz, rl, .void_value, node); }, .assign_bit_and => { try assignOp(gz, scope, node, .bit_and); return rvalue(gz, rl, .void_value, node); }, .assign_bit_or => { try assignOp(gz, scope, node, .bit_or); return rvalue(gz, rl, .void_value, node); }, .assign_bit_xor => { try assignOp(gz, scope, node, .xor); return rvalue(gz, rl, .void_value, node); }, .assign_div => { try assignOp(gz, scope, node, .div); return rvalue(gz, rl, .void_value, node); }, .assign_sub => { try assignOp(gz, scope, node, .sub); return rvalue(gz, rl, .void_value, node); }, .assign_sub_wrap => { try assignOp(gz, scope, node, .subwrap); return rvalue(gz, rl, .void_value, node); }, .assign_mod => { try assignOp(gz, scope, node, .mod_rem); return rvalue(gz, rl, .void_value, node); }, .assign_add => { try assignOp(gz, scope, node, .add); return rvalue(gz, rl, .void_value, node); }, .assign_add_wrap => { try assignOp(gz, scope, node, .addwrap); return rvalue(gz, rl, .void_value, node); }, .assign_mul => { try assignOp(gz, scope, node, .mul); return rvalue(gz, rl, .void_value, node); }, .assign_mul_wrap => { try assignOp(gz, scope, node, .mulwrap); return rvalue(gz, rl, .void_value, node); }, // zig fmt: off .bit_shift_left => return shiftOp(gz, scope, rl, node, node_datas[node].lhs, node_datas[node].rhs, .shl), .bit_shift_right => return shiftOp(gz, scope, rl, node, node_datas[node].lhs, node_datas[node].rhs, .shr), .add => return simpleBinOp(gz, scope, rl, node, .add), .add_wrap => return simpleBinOp(gz, scope, rl, node, .addwrap), .sub => return simpleBinOp(gz, scope, rl, node, .sub), .sub_wrap => return simpleBinOp(gz, scope, rl, node, .subwrap), .mul => return simpleBinOp(gz, scope, rl, node, .mul), .mul_wrap => return simpleBinOp(gz, scope, rl, node, .mulwrap), .div => return simpleBinOp(gz, scope, rl, node, .div), .mod => return simpleBinOp(gz, scope, rl, node, .mod_rem), .bit_and => { const current_ampersand_token = main_tokens[node]; if (token_tags[current_ampersand_token + 1] == .ampersand) { const token_starts = tree.tokens.items(.start); const current_token_offset = token_starts[current_ampersand_token]; const next_token_offset = token_starts[current_ampersand_token + 1]; if (current_token_offset + 1 == next_token_offset) { return astgen.failTok( current_ampersand_token, "`&&` is invalid; note that `and` is boolean AND", .{}, ); } } return simpleBinOp(gz, scope, rl, node, .bit_and); }, .bit_or => return simpleBinOp(gz, scope, rl, node, .bit_or), .bit_xor => return simpleBinOp(gz, scope, rl, node, .xor), .bang_equal => return simpleBinOp(gz, scope, rl, node, .cmp_neq), .equal_equal => return simpleBinOp(gz, scope, rl, node, .cmp_eq), .greater_than => return simpleBinOp(gz, scope, rl, node, .cmp_gt), .greater_or_equal => return simpleBinOp(gz, scope, rl, node, .cmp_gte), .less_than => return simpleBinOp(gz, scope, rl, node, .cmp_lt), .less_or_equal => return simpleBinOp(gz, scope, rl, node, .cmp_lte), .array_cat => return simpleBinOp(gz, scope, rl, node, .array_cat), .array_mult => return simpleBinOp(gz, scope, rl, node, .array_mul), .error_union => return simpleBinOp(gz, scope, rl, node, .error_union_type), .merge_error_sets => return simpleBinOp(gz, scope, rl, node, .merge_error_sets), .bool_and => return boolBinOp(gz, scope, rl, node, .bool_br_and), .bool_or => return boolBinOp(gz, scope, rl, node, .bool_br_or), .bool_not => return boolNot(gz, scope, rl, node), .bit_not => return bitNot(gz, scope, rl, node), .negation => return negation(gz, scope, rl, node, .negate), .negation_wrap => return negation(gz, scope, rl, node, .negate_wrap), .identifier => return identifier(gz, scope, rl, node), .asm_simple => return asmExpr(gz, scope, rl, node, tree.asmSimple(node)), .@"asm" => return asmExpr(gz, scope, rl, node, tree.asmFull(node)), .string_literal => return stringLiteral(gz, rl, node), .multiline_string_literal => return multilineStringLiteral(gz, rl, node), .integer_literal => return integerLiteral(gz, rl, node), // zig fmt: on .builtin_call_two, .builtin_call_two_comma => { if (node_datas[node].lhs == 0) { const params = [_]ast.Node.Index{}; return builtinCall(gz, scope, rl, node, &params); } else if (node_datas[node].rhs == 0) { const params = [_]ast.Node.Index{node_datas[node].lhs}; return builtinCall(gz, scope, rl, node, &params); } else { const params = [_]ast.Node.Index{ node_datas[node].lhs, node_datas[node].rhs }; return builtinCall(gz, scope, rl, node, &params); } }, .builtin_call, .builtin_call_comma => { const params = tree.extra_data[node_datas[node].lhs..node_datas[node].rhs]; return builtinCall(gz, scope, rl, node, params); }, .call_one, .call_one_comma, .async_call_one, .async_call_one_comma => { var params: [1]ast.Node.Index = undefined; return callExpr(gz, scope, rl, node, tree.callOne(&params, node)); }, .call, .call_comma, .async_call, .async_call_comma => { return callExpr(gz, scope, rl, node, tree.callFull(node)); }, .unreachable_literal => { _ = try gz.addAsIndex(.{ .tag = .@"unreachable", .data = .{ .@"unreachable" = .{ .safety = true, .src_node = gz.nodeIndexToRelative(node), } }, }); return Zir.Inst.Ref.unreachable_value; }, .@"return" => return ret(gz, scope, node), .field_access => return fieldAccess(gz, scope, rl, node), .float_literal => return floatLiteral(gz, rl, node), .if_simple => return ifExpr(gz, scope, rl, node, tree.ifSimple(node)), .@"if" => return ifExpr(gz, scope, rl, node, tree.ifFull(node)), .while_simple => return whileExpr(gz, scope, rl, node, tree.whileSimple(node)), .while_cont => return whileExpr(gz, scope, rl, node, tree.whileCont(node)), .@"while" => return whileExpr(gz, scope, rl, node, tree.whileFull(node)), .for_simple => return forExpr(gz, scope, rl, node, tree.forSimple(node)), .@"for" => return forExpr(gz, scope, rl, node, tree.forFull(node)), .slice_open => { const lhs = try expr(gz, scope, .ref, node_datas[node].lhs); const start = try expr(gz, scope, .{ .ty = .usize_type }, node_datas[node].rhs); const result = try gz.addPlNode(.slice_start, node, Zir.Inst.SliceStart{ .lhs = lhs, .start = start, }); switch (rl) { .ref, .none_or_ref => return result, else => { const dereffed = try gz.addUnNode(.load, result, node); return rvalue(gz, rl, dereffed, node); }, } }, .slice => { const lhs = try expr(gz, scope, .ref, node_datas[node].lhs); const extra = tree.extraData(node_datas[node].rhs, ast.Node.Slice); const start = try expr(gz, scope, .{ .ty = .usize_type }, extra.start); const end = try expr(gz, scope, .{ .ty = .usize_type }, extra.end); const result = try gz.addPlNode(.slice_end, node, Zir.Inst.SliceEnd{ .lhs = lhs, .start = start, .end = end, }); switch (rl) { .ref, .none_or_ref => return result, else => { const dereffed = try gz.addUnNode(.load, result, node); return rvalue(gz, rl, dereffed, node); }, } }, .slice_sentinel => { const lhs = try expr(gz, scope, .ref, node_datas[node].lhs); const extra = tree.extraData(node_datas[node].rhs, ast.Node.SliceSentinel); const start = try expr(gz, scope, .{ .ty = .usize_type }, extra.start); const end = if (extra.end != 0) try expr(gz, scope, .{ .ty = .usize_type }, extra.end) else .none; const sentinel = try expr(gz, scope, .{ .ty = .usize_type }, extra.sentinel); const result = try gz.addPlNode(.slice_sentinel, node, Zir.Inst.SliceSentinel{ .lhs = lhs, .start = start, .end = end, .sentinel = sentinel, }); switch (rl) { .ref, .none_or_ref => return result, else => { const dereffed = try gz.addUnNode(.load, result, node); return rvalue(gz, rl, dereffed, node); }, } }, .deref => { const lhs = try expr(gz, scope, .none, node_datas[node].lhs); switch (rl) { .ref, .none_or_ref => return lhs, else => { const result = try gz.addUnNode(.load, lhs, node); return rvalue(gz, rl, result, node); }, } }, .address_of => { const result = try expr(gz, scope, .ref, node_datas[node].lhs); return rvalue(gz, rl, result, node); }, .optional_type => { const operand = try typeExpr(gz, scope, node_datas[node].lhs); const result = try gz.addUnNode(.optional_type, operand, node); return rvalue(gz, rl, result, node); }, .unwrap_optional => switch (rl) { .ref => return gz.addUnNode( .optional_payload_safe_ptr, try expr(gz, scope, .ref, node_datas[node].lhs), node, ), else => return rvalue(gz, rl, try gz.addUnNode( .optional_payload_safe, try expr(gz, scope, .none, node_datas[node].lhs), node, ), node), }, .block_two, .block_two_semicolon => { const statements = [2]ast.Node.Index{ node_datas[node].lhs, node_datas[node].rhs }; if (node_datas[node].lhs == 0) { return blockExpr(gz, scope, rl, node, statements[0..0]); } else if (node_datas[node].rhs == 0) { return blockExpr(gz, scope, rl, node, statements[0..1]); } else { return blockExpr(gz, scope, rl, node, statements[0..2]); } }, .block, .block_semicolon => { const statements = tree.extra_data[node_datas[node].lhs..node_datas[node].rhs]; return blockExpr(gz, scope, rl, node, statements); }, .enum_literal => return simpleStrTok(gz, rl, main_tokens[node], node, .enum_literal), .error_value => return simpleStrTok(gz, rl, node_datas[node].rhs, node, .error_value), .anyframe_literal => return rvalue(gz, rl, .anyframe_type, node), .anyframe_type => { const return_type = try typeExpr(gz, scope, node_datas[node].rhs); const result = try gz.addUnNode(.anyframe_type, return_type, node); return rvalue(gz, rl, result, node); }, .@"catch" => { const catch_token = main_tokens[node]; const payload_token: ?ast.TokenIndex = if (token_tags[catch_token + 1] == .pipe) catch_token + 2 else null; switch (rl) { .ref => return orelseCatchExpr( gz, scope, rl, node, node_datas[node].lhs, .is_non_err_ptr, .err_union_payload_unsafe_ptr, .err_union_code_ptr, node_datas[node].rhs, payload_token, ), else => return orelseCatchExpr( gz, scope, rl, node, node_datas[node].lhs, .is_non_err, .err_union_payload_unsafe, .err_union_code, node_datas[node].rhs, payload_token, ), } }, .@"orelse" => switch (rl) { .ref => return orelseCatchExpr( gz, scope, rl, node, node_datas[node].lhs, .is_non_null_ptr, .optional_payload_unsafe_ptr, undefined, node_datas[node].rhs, null, ), else => return orelseCatchExpr( gz, scope, rl, node, node_datas[node].lhs, .is_non_null, .optional_payload_unsafe, undefined, node_datas[node].rhs, null, ), }, .ptr_type_aligned => return ptrType(gz, scope, rl, node, tree.ptrTypeAligned(node)), .ptr_type_sentinel => return ptrType(gz, scope, rl, node, tree.ptrTypeSentinel(node)), .ptr_type => return ptrType(gz, scope, rl, node, tree.ptrType(node)), .ptr_type_bit_range => return ptrType(gz, scope, rl, node, tree.ptrTypeBitRange(node)), .container_decl, .container_decl_trailing, => return containerDecl(gz, scope, rl, node, tree.containerDecl(node)), .container_decl_two, .container_decl_two_trailing => { var buffer: [2]ast.Node.Index = undefined; return containerDecl(gz, scope, rl, node, tree.containerDeclTwo(&buffer, node)); }, .container_decl_arg, .container_decl_arg_trailing, => return containerDecl(gz, scope, rl, node, tree.containerDeclArg(node)), .tagged_union, .tagged_union_trailing, => return containerDecl(gz, scope, rl, node, tree.taggedUnion(node)), .tagged_union_two, .tagged_union_two_trailing => { var buffer: [2]ast.Node.Index = undefined; return containerDecl(gz, scope, rl, node, tree.taggedUnionTwo(&buffer, node)); }, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, => return containerDecl(gz, scope, rl, node, tree.taggedUnionEnumTag(node)), .@"break" => return breakExpr(gz, scope, node), .@"continue" => return continueExpr(gz, scope, node), .grouped_expression => return expr(gz, scope, rl, node_datas[node].lhs), .array_type => return arrayType(gz, scope, rl, node), .array_type_sentinel => return arrayTypeSentinel(gz, scope, rl, node), .char_literal => return charLiteral(gz, rl, node), .error_set_decl => return errorSetDecl(gz, rl, node), .array_access => return arrayAccess(gz, scope, rl, node), .@"comptime" => return comptimeExprAst(gz, scope, rl, node), .@"switch", .switch_comma => return switchExpr(gz, scope, rl, node), .@"nosuspend" => return nosuspendExpr(gz, scope, rl, node), .@"suspend" => return suspendExpr(gz, scope, node), .@"await" => return awaitExpr(gz, scope, rl, node), .@"resume" => return resumeExpr(gz, scope, rl, node), .@"try" => return tryExpr(gz, scope, rl, node, node_datas[node].lhs), .array_init_one, .array_init_one_comma => { var elements: [1]ast.Node.Index = undefined; return arrayInitExpr(gz, scope, rl, node, tree.arrayInitOne(&elements, node)); }, .array_init_dot_two, .array_init_dot_two_comma => { var elements: [2]ast.Node.Index = undefined; return arrayInitExpr(gz, scope, rl, node, tree.arrayInitDotTwo(&elements, node)); }, .array_init_dot, .array_init_dot_comma, => return arrayInitExpr(gz, scope, rl, node, tree.arrayInitDot(node)), .array_init, .array_init_comma, => return arrayInitExpr(gz, scope, rl, node, tree.arrayInit(node)), .struct_init_one, .struct_init_one_comma => { var fields: [1]ast.Node.Index = undefined; return structInitExpr(gz, scope, rl, node, tree.structInitOne(&fields, node)); }, .struct_init_dot_two, .struct_init_dot_two_comma => { var fields: [2]ast.Node.Index = undefined; return structInitExpr(gz, scope, rl, node, tree.structInitDotTwo(&fields, node)); }, .struct_init_dot, .struct_init_dot_comma, => return structInitExpr(gz, scope, rl, node, tree.structInitDot(node)), .struct_init, .struct_init_comma, => return structInitExpr(gz, scope, rl, node, tree.structInit(node)), .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; return fnProtoExpr(gz, scope, rl, tree.fnProtoSimple(&params, node)); }, .fn_proto_multi => { return fnProtoExpr(gz, scope, rl, tree.fnProtoMulti(node)); }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; return fnProtoExpr(gz, scope, rl, tree.fnProtoOne(&params, node)); }, .fn_proto => { return fnProtoExpr(gz, scope, rl, tree.fnProto(node)); }, } } fn nosuspendExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].lhs; assert(body_node != 0); if (gz.nosuspend_node != 0) { return astgen.failNodeNotes(node, "redundant nosuspend block", .{}, &[_]u32{ try astgen.errNoteNode(gz.nosuspend_node, "other nosuspend block here", .{}), }); } gz.nosuspend_node = node; const result = try expr(gz, scope, rl, body_node); gz.nosuspend_node = 0; return rvalue(gz, rl, result, node); } fn suspendExpr( gz: *GenZir, scope: *Scope, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].lhs; if (gz.nosuspend_node != 0) { return astgen.failNodeNotes(node, "suspend inside nosuspend block", .{}, &[_]u32{ try astgen.errNoteNode(gz.nosuspend_node, "nosuspend block here", .{}), }); } if (gz.suspend_node != 0) { return astgen.failNodeNotes(node, "cannot suspend inside suspend block", .{}, &[_]u32{ try astgen.errNoteNode(gz.suspend_node, "other suspend block here", .{}), }); } assert(body_node != 0); const suspend_inst = try gz.addBlock(.suspend_block, node); try gz.instructions.append(gpa, suspend_inst); var suspend_scope = gz.makeSubBlock(scope); suspend_scope.suspend_node = node; defer suspend_scope.instructions.deinit(gpa); const body_result = try expr(&suspend_scope, &suspend_scope.base, .none, body_node); if (!gz.refIsNoReturn(body_result)) { _ = try suspend_scope.addBreak(.break_inline, suspend_inst, .void_value); } try suspend_scope.setBlockBody(suspend_inst); return indexToRef(suspend_inst); } fn awaitExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const rhs_node = node_datas[node].lhs; if (gz.suspend_node != 0) { return astgen.failNodeNotes(node, "cannot await inside suspend block", .{}, &[_]u32{ try astgen.errNoteNode(gz.suspend_node, "suspend block here", .{}), }); } const operand = try expr(gz, scope, .none, rhs_node); const tag: Zir.Inst.Tag = if (gz.nosuspend_node != 0) .await_nosuspend else .@"await"; const result = try gz.addUnNode(tag, operand, node); return rvalue(gz, rl, result, node); } fn resumeExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const rhs_node = node_datas[node].lhs; const operand = try expr(gz, scope, .none, rhs_node); const result = try gz.addUnNode(.@"resume", operand, node); return rvalue(gz, rl, result, node); } fn fnProtoExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, fn_proto: ast.full.FnProto, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const is_extern = blk: { const maybe_extern_token = fn_proto.extern_export_inline_token orelse break :blk false; break :blk token_tags[maybe_extern_token] == .keyword_extern; }; assert(!is_extern); const is_var_args = is_var_args: { var param_type_i: usize = 0; var it = fn_proto.iterate(tree.*); while (it.next()) |param| : (param_type_i += 1) { const is_comptime = if (param.comptime_noalias) |token| token_tags[token] == .keyword_comptime else false; const is_anytype = if (param.anytype_ellipsis3) |token| blk: { switch (token_tags[token]) { .keyword_anytype => break :blk true, .ellipsis3 => break :is_var_args true, else => unreachable, } } else false; const param_name: u32 = if (param.name_token) |name_token| blk: { if (mem.eql(u8, "_", tree.tokenSlice(name_token))) break :blk 0; break :blk try astgen.identAsString(name_token); } else 0; if (is_anytype) { const name_token = param.name_token orelse param.anytype_ellipsis3.?; const tag: Zir.Inst.Tag = if (is_comptime) .param_anytype_comptime else .param_anytype; _ = try gz.addStrTok(tag, param_name, name_token); } else { const param_type_node = param.type_expr; assert(param_type_node != 0); var param_gz = gz.makeSubBlock(scope); defer param_gz.instructions.deinit(gpa); const param_type = try expr(&param_gz, scope, coerced_type_rl, param_type_node); const param_inst_expected = @intCast(u32, astgen.instructions.len + 1); _ = try param_gz.addBreak(.break_inline, param_inst_expected, param_type); const main_tokens = tree.nodes.items(.main_token); const name_token = param.name_token orelse main_tokens[param_type_node]; const tag: Zir.Inst.Tag = if (is_comptime) .param_comptime else .param; const param_inst = try gz.addParam(tag, name_token, param_name, param_gz.instructions.items); assert(param_inst_expected == param_inst); } } break :is_var_args false; }; const align_inst: Zir.Inst.Ref = if (fn_proto.ast.align_expr == 0) .none else inst: { break :inst try expr(gz, scope, align_rl, fn_proto.ast.align_expr); }; if (fn_proto.ast.section_expr != 0) { return astgen.failNode(fn_proto.ast.section_expr, "linksection not allowed on function prototypes", .{}); } const maybe_bang = tree.firstToken(fn_proto.ast.return_type) - 1; const is_inferred_error = token_tags[maybe_bang] == .bang; if (is_inferred_error) { return astgen.failTok(maybe_bang, "function prototype may not have inferred error set", .{}); } var ret_gz = gz.makeSubBlock(scope); defer ret_gz.instructions.deinit(gpa); const ret_ty = try expr(&ret_gz, scope, coerced_type_rl, fn_proto.ast.return_type); const ret_br = try ret_gz.addBreak(.break_inline, 0, ret_ty); const cc: Zir.Inst.Ref = if (fn_proto.ast.callconv_expr != 0) try expr( gz, scope, .{ .ty = .calling_convention_type }, fn_proto.ast.callconv_expr, ) else Zir.Inst.Ref.none; const result = try gz.addFunc(.{ .src_node = fn_proto.ast.proto_node, .param_block = 0, .ret_ty = ret_gz.instructions.items, .ret_br = ret_br, .body = &[0]Zir.Inst.Index{}, .cc = cc, .align_inst = align_inst, .lib_name = 0, .is_var_args = is_var_args, .is_inferred_error = false, .is_test = false, .is_extern = false, }); return rvalue(gz, rl, result, fn_proto.ast.proto_node); } fn arrayInitExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, array_init: ast.full.ArrayInit, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); assert(array_init.ast.elements.len != 0); // Otherwise it would be struct init. const types: struct { array: Zir.Inst.Ref, elem: Zir.Inst.Ref, } = inst: { if (array_init.ast.type_expr == 0) break :inst .{ .array = .none, .elem = .none, }; infer: { const array_type: ast.full.ArrayType = switch (node_tags[array_init.ast.type_expr]) { .array_type => tree.arrayType(array_init.ast.type_expr), .array_type_sentinel => tree.arrayTypeSentinel(array_init.ast.type_expr), else => break :infer, }; // This intentionally does not support `@"_"` syntax. if (node_tags[array_type.ast.elem_count] == .identifier and mem.eql(u8, tree.tokenSlice(main_tokens[array_type.ast.elem_count]), "_")) { const len_inst = try gz.addInt(array_init.ast.elements.len); const elem_type = try typeExpr(gz, scope, array_type.ast.elem_type); if (array_type.ast.sentinel == 0) { const array_type_inst = try gz.addBin(.array_type, len_inst, elem_type); break :inst .{ .array = array_type_inst, .elem = elem_type, }; } else { const sentinel = try comptimeExpr(gz, scope, .{ .ty = elem_type }, array_type.ast.sentinel); const array_type_inst = try gz.addArrayTypeSentinel(len_inst, elem_type, sentinel); break :inst .{ .array = array_type_inst, .elem = elem_type, }; } } } const array_type_inst = try typeExpr(gz, scope, array_init.ast.type_expr); const elem_type = try gz.addUnNode(.elem_type, array_type_inst, array_init.ast.type_expr); break :inst .{ .array = array_type_inst, .elem = elem_type, }; }; switch (rl) { .discard => { for (array_init.ast.elements) |elem_init| { _ = try expr(gz, scope, .discard, elem_init); } return Zir.Inst.Ref.void_value; }, .ref => { if (types.array != .none) { return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init_ref); } else { return arrayInitExprRlNone(gz, scope, node, array_init.ast.elements, .array_init_anon_ref); } }, .none, .none_or_ref => { if (types.array != .none) { return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init); } else { return arrayInitExprRlNone(gz, scope, node, array_init.ast.elements, .array_init_anon); } }, .ty, .coerced_ty => |ty_inst| { if (types.array != .none) { const result = try arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init); return rvalue(gz, rl, result, node); } else { const elem_type = try gz.addUnNode(.elem_type, ty_inst, node); return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, elem_type, .array_init); } }, .ptr, .inferred_ptr => |ptr_inst| { return arrayInitExprRlPtr(gz, scope, node, array_init.ast.elements, ptr_inst); }, .block_ptr => |block_gz| { return arrayInitExprRlPtr(gz, scope, node, array_init.ast.elements, block_gz.rl_ptr); }, } } fn arrayInitExprRlNone( gz: *GenZir, scope: *Scope, node: ast.Node.Index, elements: []const ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const elem_list = try gpa.alloc(Zir.Inst.Ref, elements.len); defer gpa.free(elem_list); for (elements) |elem_init, i| { elem_list[i] = try expr(gz, scope, .none, elem_init); } const init_inst = try gz.addPlNode(tag, node, Zir.Inst.MultiOp{ .operands_len = @intCast(u32, elem_list.len), }); try astgen.appendRefs(elem_list); return init_inst; } fn arrayInitExprRlTy( gz: *GenZir, scope: *Scope, node: ast.Node.Index, elements: []const ast.Node.Index, elem_ty_inst: Zir.Inst.Ref, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const elem_list = try gpa.alloc(Zir.Inst.Ref, elements.len); defer gpa.free(elem_list); const elem_rl: ResultLoc = .{ .ty = elem_ty_inst }; for (elements) |elem_init, i| { elem_list[i] = try expr(gz, scope, elem_rl, elem_init); } const init_inst = try gz.addPlNode(tag, node, Zir.Inst.MultiOp{ .operands_len = @intCast(u32, elem_list.len), }); try astgen.appendRefs(elem_list); return init_inst; } fn arrayInitExprRlPtr( gz: *GenZir, scope: *Scope, node: ast.Node.Index, elements: []const ast.Node.Index, result_ptr: Zir.Inst.Ref, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const elem_ptr_list = try gpa.alloc(Zir.Inst.Index, elements.len); defer gpa.free(elem_ptr_list); for (elements) |elem_init, i| { const index_inst = try gz.addInt(i); const elem_ptr = try gz.addPlNode(.elem_ptr_node, elem_init, Zir.Inst.Bin{ .lhs = result_ptr, .rhs = index_inst, }); elem_ptr_list[i] = refToIndex(elem_ptr).?; _ = try expr(gz, scope, .{ .ptr = elem_ptr }, elem_init); } _ = try gz.addPlNode(.validate_array_init_ptr, node, Zir.Inst.Block{ .body_len = @intCast(u32, elem_ptr_list.len), }); try astgen.extra.appendSlice(gpa, elem_ptr_list); return .void_value; } fn structInitExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, struct_init: ast.full.StructInit, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; if (struct_init.ast.type_expr == 0) { if (struct_init.ast.fields.len == 0) { return rvalue(gz, rl, .empty_struct, node); } } else array: { const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); const array_type: ast.full.ArrayType = switch (node_tags[struct_init.ast.type_expr]) { .array_type => tree.arrayType(struct_init.ast.type_expr), .array_type_sentinel => tree.arrayTypeSentinel(struct_init.ast.type_expr), else => break :array, }; const is_inferred_array_len = node_tags[array_type.ast.elem_count] == .identifier and // This intentionally does not support `@"_"` syntax. mem.eql(u8, tree.tokenSlice(main_tokens[array_type.ast.elem_count]), "_"); if (struct_init.ast.fields.len == 0) { if (is_inferred_array_len) { const elem_type = try typeExpr(gz, scope, array_type.ast.elem_type); const array_type_inst = if (array_type.ast.sentinel == 0) blk: { break :blk try gz.addBin(.array_type, .zero_usize, elem_type); } else blk: { const sentinel = try comptimeExpr(gz, scope, .{ .ty = elem_type }, array_type.ast.sentinel); break :blk try gz.addArrayTypeSentinel(.zero_usize, elem_type, sentinel); }; const result = try gz.addUnNode(.struct_init_empty, array_type_inst, node); return rvalue(gz, rl, result, node); } const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); const result = try gz.addUnNode(.struct_init_empty, ty_inst, node); return rvalue(gz, rl, result, node); } else { return astgen.failNode( struct_init.ast.type_expr, "initializing array with struct syntax", .{}, ); } } switch (rl) { .discard => { if (struct_init.ast.type_expr != 0) _ = try typeExpr(gz, scope, struct_init.ast.type_expr); for (struct_init.ast.fields) |field_init| { _ = try expr(gz, scope, .discard, field_init); } return Zir.Inst.Ref.void_value; }, .ref => { if (struct_init.ast.type_expr != 0) { const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init_ref); } else { return structInitExprRlNone(gz, scope, node, struct_init, .struct_init_anon_ref); } }, .none, .none_or_ref => { if (struct_init.ast.type_expr != 0) { const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init); } else { return structInitExprRlNone(gz, scope, node, struct_init, .struct_init_anon); } }, .ty, .coerced_ty => |ty_inst| { if (struct_init.ast.type_expr == 0) { return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init); } const inner_ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); const result = try structInitExprRlTy(gz, scope, node, struct_init, inner_ty_inst, .struct_init); return rvalue(gz, rl, result, node); }, .ptr, .inferred_ptr => |ptr_inst| return structInitExprRlPtr(gz, scope, node, struct_init, ptr_inst), .block_ptr => |block_gz| return structInitExprRlPtr(gz, scope, node, struct_init, block_gz.rl_ptr), } } fn structInitExprRlNone( gz: *GenZir, scope: *Scope, node: ast.Node.Index, struct_init: ast.full.StructInit, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const fields_list = try gpa.alloc(Zir.Inst.StructInitAnon.Item, struct_init.ast.fields.len); defer gpa.free(fields_list); for (struct_init.ast.fields) |field_init, i| { const name_token = tree.firstToken(field_init) - 2; const str_index = try astgen.identAsString(name_token); fields_list[i] = .{ .field_name = str_index, .init = try expr(gz, scope, .none, field_init), }; } const init_inst = try gz.addPlNode(tag, node, Zir.Inst.StructInitAnon{ .fields_len = @intCast(u32, fields_list.len), }); try astgen.extra.ensureUnusedCapacity(gpa, fields_list.len * @typeInfo(Zir.Inst.StructInitAnon.Item).Struct.fields.len); for (fields_list) |field| { _ = gz.astgen.addExtraAssumeCapacity(field); } return init_inst; } fn structInitExprRlPtr( gz: *GenZir, scope: *Scope, node: ast.Node.Index, struct_init: ast.full.StructInit, result_ptr: Zir.Inst.Ref, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const field_ptr_list = try gpa.alloc(Zir.Inst.Index, struct_init.ast.fields.len); defer gpa.free(field_ptr_list); if (struct_init.ast.type_expr != 0) _ = try typeExpr(gz, scope, struct_init.ast.type_expr); for (struct_init.ast.fields) |field_init, i| { const name_token = tree.firstToken(field_init) - 2; const str_index = try astgen.identAsString(name_token); const field_ptr = try gz.addPlNode(.field_ptr, field_init, Zir.Inst.Field{ .lhs = result_ptr, .field_name_start = str_index, }); field_ptr_list[i] = refToIndex(field_ptr).?; _ = try expr(gz, scope, .{ .ptr = field_ptr }, field_init); } _ = try gz.addPlNode(.validate_struct_init_ptr, node, Zir.Inst.Block{ .body_len = @intCast(u32, field_ptr_list.len), }); try astgen.extra.appendSlice(gpa, field_ptr_list); return .void_value; } fn structInitExprRlTy( gz: *GenZir, scope: *Scope, node: ast.Node.Index, struct_init: ast.full.StructInit, ty_inst: Zir.Inst.Ref, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const fields_list = try gpa.alloc(Zir.Inst.StructInit.Item, struct_init.ast.fields.len); defer gpa.free(fields_list); for (struct_init.ast.fields) |field_init, i| { const name_token = tree.firstToken(field_init) - 2; const str_index = try astgen.identAsString(name_token); const field_ty_inst = try gz.addPlNode(.field_type, field_init, Zir.Inst.FieldType{ .container_type = ty_inst, .name_start = str_index, }); fields_list[i] = .{ .field_type = refToIndex(field_ty_inst).?, .init = try expr(gz, scope, .{ .ty = field_ty_inst }, field_init), }; } const init_inst = try gz.addPlNode(tag, node, Zir.Inst.StructInit{ .fields_len = @intCast(u32, fields_list.len), }); try astgen.extra.ensureUnusedCapacity(gpa, fields_list.len * @typeInfo(Zir.Inst.StructInit.Item).Struct.fields.len); for (fields_list) |field| { _ = gz.astgen.addExtraAssumeCapacity(field); } return init_inst; } /// This calls expr in a comptime scope, and is intended to be called as a helper function. /// The one that corresponds to `comptime` expression syntax is `comptimeExprAst`. fn comptimeExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const prev_force_comptime = gz.force_comptime; gz.force_comptime = true; defer gz.force_comptime = prev_force_comptime; return expr(gz, scope, rl, node); } /// This one is for an actual `comptime` syntax, and will emit a compile error if /// the scope already has `force_comptime=true`. /// See `comptimeExpr` for the helper function for calling expr in a comptime scope. fn comptimeExprAst( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; if (gz.force_comptime) { return astgen.failNode(node, "redundant comptime keyword in already comptime scope", .{}); } const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].lhs; gz.force_comptime = true; const result = try expr(gz, scope, rl, body_node); gz.force_comptime = false; return result; } fn breakExpr(parent_gz: *GenZir, parent_scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const break_label = node_datas[node].lhs; const rhs = node_datas[node].rhs; // Look for the label in the scope. var scope = parent_scope; while (true) { switch (scope.tag) { .gen_zir => { const block_gz = scope.cast(GenZir).?; const block_inst = blk: { if (break_label != 0) { if (block_gz.label) |*label| { if (try astgen.tokenIdentEql(label.token, break_label)) { label.used = true; break :blk label.block_inst; } } } else if (block_gz.break_block != 0) { break :blk block_gz.break_block; } scope = block_gz.parent; continue; }; if (rhs == 0) { _ = try parent_gz.addBreak(.@"break", block_inst, .void_value); return Zir.Inst.Ref.unreachable_value; } block_gz.break_count += 1; const prev_rvalue_rl_count = block_gz.rvalue_rl_count; const operand = try expr(parent_gz, parent_scope, block_gz.break_result_loc, rhs); const have_store_to_block = block_gz.rvalue_rl_count != prev_rvalue_rl_count; const br = try parent_gz.addBreak(.@"break", block_inst, operand); if (block_gz.break_result_loc == .block_ptr) { try block_gz.labeled_breaks.append(astgen.gpa, br); if (have_store_to_block) { const zir_tags = parent_gz.astgen.instructions.items(.tag); const zir_datas = parent_gz.astgen.instructions.items(.data); const store_inst = @intCast(u32, zir_tags.len - 2); assert(zir_tags[store_inst] == .store_to_block_ptr); assert(zir_datas[store_inst].bin.lhs == block_gz.rl_ptr); try block_gz.labeled_store_to_block_ptr_list.append(astgen.gpa, store_inst); } } return Zir.Inst.Ref.unreachable_value; }, .local_val => scope = scope.cast(Scope.LocalVal).?.parent, .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, .namespace => break, .defer_normal => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; const expr_node = node_datas[defer_scope.defer_node].rhs; _ = try unusedResultExpr(parent_gz, defer_scope.parent, expr_node); }, .defer_error => scope = scope.cast(Scope.Defer).?.parent, .top => unreachable, } } if (break_label != 0) { const label_name = try astgen.identifierTokenString(break_label); return astgen.failTok(break_label, "label not found: '{s}'", .{label_name}); } else { return astgen.failNode(node, "break expression outside loop", .{}); } } fn continueExpr(parent_gz: *GenZir, parent_scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const break_label = node_datas[node].lhs; // Look for the label in the scope. var scope = parent_scope; while (true) { switch (scope.tag) { .gen_zir => { const gen_zir = scope.cast(GenZir).?; const continue_block = gen_zir.continue_block; if (continue_block == 0) { scope = gen_zir.parent; continue; } if (break_label != 0) blk: { if (gen_zir.label) |*label| { if (try astgen.tokenIdentEql(label.token, break_label)) { label.used = true; break :blk; } } // found continue but either it has a different label, or no label scope = gen_zir.parent; continue; } // TODO emit a break_inline if the loop being continued is inline _ = try parent_gz.addBreak(.@"break", continue_block, .void_value); return Zir.Inst.Ref.unreachable_value; }, .local_val => scope = scope.cast(Scope.LocalVal).?.parent, .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, .defer_normal => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; const expr_node = node_datas[defer_scope.defer_node].rhs; _ = try unusedResultExpr(parent_gz, defer_scope.parent, expr_node); }, .defer_error => scope = scope.cast(Scope.Defer).?.parent, .namespace => break, .top => unreachable, } } if (break_label != 0) { const label_name = try astgen.identifierTokenString(break_label); return astgen.failTok(break_label, "label not found: '{s}'", .{label_name}); } else { return astgen.failNode(node, "continue expression outside loop", .{}); } } fn blockExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, block_node: ast.Node.Index, statements: []const ast.Node.Index, ) InnerError!Zir.Inst.Ref { const tracy = trace(@src()); defer tracy.end(); const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const lbrace = main_tokens[block_node]; if (token_tags[lbrace - 1] == .colon and token_tags[lbrace - 2] == .identifier) { return labeledBlockExpr(gz, scope, rl, block_node, statements, .block); } try blockExprStmts(gz, scope, statements); return rvalue(gz, rl, .void_value, block_node); } fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: ast.TokenIndex) !void { // Look for the label in the scope. var scope = parent_scope; while (true) { switch (scope.tag) { .gen_zir => { const gen_zir = scope.cast(GenZir).?; if (gen_zir.label) |prev_label| { if (try astgen.tokenIdentEql(label, prev_label.token)) { const label_name = try astgen.identifierTokenString(label); return astgen.failTokNotes(label, "redefinition of label '{s}'", .{ label_name, }, &[_]u32{ try astgen.errNoteTok( prev_label.token, "previous definition here", .{}, ), }); } } scope = gen_zir.parent; }, .local_val => scope = scope.cast(Scope.LocalVal).?.parent, .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent, .namespace => break, .top => unreachable, } } } fn labeledBlockExpr( gz: *GenZir, parent_scope: *Scope, rl: ResultLoc, block_node: ast.Node.Index, statements: []const ast.Node.Index, zir_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const tracy = trace(@src()); defer tracy.end(); assert(zir_tag == .block); const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const lbrace = main_tokens[block_node]; const label_token = lbrace - 2; assert(token_tags[label_token] == .identifier); try astgen.checkLabelRedefinition(parent_scope, label_token); // Reserve the Block ZIR instruction index so that we can put it into the GenZir struct // so that break statements can reference it. const block_inst = try gz.addBlock(zir_tag, block_node); try gz.instructions.append(astgen.gpa, block_inst); var block_scope = gz.makeSubBlock(parent_scope); block_scope.label = GenZir.Label{ .token = label_token, .block_inst = block_inst, }; block_scope.setBreakResultLoc(rl); defer block_scope.instructions.deinit(astgen.gpa); defer block_scope.labeled_breaks.deinit(astgen.gpa); defer block_scope.labeled_store_to_block_ptr_list.deinit(astgen.gpa); try blockExprStmts(&block_scope, &block_scope.base, statements); if (!block_scope.label.?.used) { return astgen.failTok(label_token, "unused block label", .{}); } const zir_tags = gz.astgen.instructions.items(.tag); const zir_datas = gz.astgen.instructions.items(.data); const strat = rl.strategy(&block_scope); switch (strat.tag) { .break_void => { // The code took advantage of the result location as a pointer. // Turn the break instruction operands into void. for (block_scope.labeled_breaks.items) |br| { zir_datas[br].@"break".operand = .void_value; } try block_scope.setBlockBody(block_inst); return indexToRef(block_inst); }, .break_operand => { // All break operands are values that did not use the result location pointer. if (strat.elide_store_to_block_ptr_instructions) { for (block_scope.labeled_store_to_block_ptr_list.items) |inst| { // Mark as elided for removal below. assert(zir_tags[inst] == .store_to_block_ptr); zir_datas[inst].bin.lhs = .none; } try block_scope.setBlockBodyEliding(block_inst); } else { try block_scope.setBlockBody(block_inst); } const block_ref = indexToRef(block_inst); switch (rl) { .ref => return block_ref, else => return rvalue(gz, rl, block_ref, block_node), } }, } } fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const ast.Node.Index) !void { const astgen = gz.astgen; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); var block_arena = std.heap.ArenaAllocator.init(gz.astgen.gpa); defer block_arena.deinit(); var noreturn_src_node: ast.Node.Index = 0; var scope = parent_scope; for (statements) |statement| { if (noreturn_src_node != 0) { return astgen.failNodeNotes( statement, "unreachable code", .{}, &[_]u32{ try astgen.errNoteNode( noreturn_src_node, "control flow is diverted here", .{}, ), }, ); } switch (node_tags[statement]) { // zig fmt: off .global_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.globalVarDecl(statement)), .local_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.localVarDecl(statement)), .simple_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.simpleVarDecl(statement)), .aligned_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.alignedVarDecl(statement)), .@"defer" => scope = try makeDeferScope(scope, statement, &block_arena.allocator, .defer_normal), .@"errdefer" => scope = try makeDeferScope(scope, statement, &block_arena.allocator, .defer_error), .assign => try assign(gz, scope, statement), .assign_bit_shift_left => try assignShift(gz, scope, statement, .shl), .assign_bit_shift_right => try assignShift(gz, scope, statement, .shr), .assign_bit_and => try assignOp(gz, scope, statement, .bit_and), .assign_bit_or => try assignOp(gz, scope, statement, .bit_or), .assign_bit_xor => try assignOp(gz, scope, statement, .xor), .assign_div => try assignOp(gz, scope, statement, .div), .assign_sub => try assignOp(gz, scope, statement, .sub), .assign_sub_wrap => try assignOp(gz, scope, statement, .subwrap), .assign_mod => try assignOp(gz, scope, statement, .mod_rem), .assign_add => try assignOp(gz, scope, statement, .add), .assign_add_wrap => try assignOp(gz, scope, statement, .addwrap), .assign_mul => try assignOp(gz, scope, statement, .mul), .assign_mul_wrap => try assignOp(gz, scope, statement, .mulwrap), else => noreturn_src_node = try unusedResultExpr(gz, scope, statement), // zig fmt: on } } try genDefers(gz, parent_scope, scope, .normal_only); try checkUsed(gz, parent_scope, scope); } /// Returns AST source node of the thing that is noreturn if the statement is definitely `noreturn`. /// Otherwise returns 0. fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) InnerError!ast.Node.Index { try emitDbgNode(gz, statement); // We need to emit an error if the result is not `noreturn` or `void`, but // we want to avoid adding the ZIR instruction if possible for performance. const maybe_unused_result = try expr(gz, scope, .none, statement); var noreturn_src_node: ast.Node.Index = 0; const elide_check = if (refToIndex(maybe_unused_result)) |inst| b: { // Note that this array becomes invalid after appending more items to it // in the above while loop. const zir_tags = gz.astgen.instructions.items(.tag); switch (zir_tags[inst]) { // For some instructions, swap in a slightly different ZIR tag // so we can avoid a separate ensure_result_used instruction. .call_chkused => unreachable, .call => { zir_tags[inst] = .call_chkused; break :b true; }, // ZIR instructions that might be a type other than `noreturn` or `void`. .add, .addwrap, .param, .param_comptime, .param_anytype, .param_anytype_comptime, .alloc, .alloc_mut, .alloc_comptime, .alloc_inferred, .alloc_inferred_mut, .alloc_inferred_comptime, .array_cat, .array_mul, .array_type, .array_type_sentinel, .vector_type, .elem_type, .indexable_ptr_len, .anyframe_type, .as, .as_node, .bit_and, .bitcast, .bitcast_result_ptr, .bit_or, .block, .block_inline, .suspend_block, .loop, .bool_br_and, .bool_br_or, .bool_not, .call_compile_time, .call_nosuspend, .call_async, .cmp_lt, .cmp_lte, .cmp_eq, .cmp_gte, .cmp_gt, .cmp_neq, .coerce_result_ptr, .decl_ref, .decl_val, .load, .div, .elem_ptr, .elem_val, .elem_ptr_node, .elem_val_node, .field_ptr, .field_val, .field_ptr_named, .field_val_named, .func, .func_inferred, .int, .int_big, .float, .float128, .int_type, .is_non_null, .is_non_null_ptr, .is_non_err, .is_non_err_ptr, .mod_rem, .mul, .mulwrap, .param_type, .ref, .shl, .shr, .str, .sub, .subwrap, .negate, .negate_wrap, .typeof, .typeof_elem, .xor, .optional_type, .optional_payload_safe, .optional_payload_unsafe, .optional_payload_safe_ptr, .optional_payload_unsafe_ptr, .err_union_payload_safe, .err_union_payload_unsafe, .err_union_payload_safe_ptr, .err_union_payload_unsafe_ptr, .err_union_code, .err_union_code_ptr, .ptr_type, .ptr_type_simple, .enum_literal, .merge_error_sets, .error_union_type, .bit_not, .error_value, .error_to_int, .int_to_error, .slice_start, .slice_end, .slice_sentinel, .import, .switch_block, .switch_block_multi, .switch_block_else, .switch_block_else_multi, .switch_block_under, .switch_block_under_multi, .switch_block_ref, .switch_block_ref_multi, .switch_block_ref_else, .switch_block_ref_else_multi, .switch_block_ref_under, .switch_block_ref_under_multi, .switch_capture, .switch_capture_ref, .switch_capture_multi, .switch_capture_multi_ref, .switch_capture_else, .switch_capture_else_ref, .struct_init_empty, .struct_init, .struct_init_ref, .struct_init_anon, .struct_init_anon_ref, .array_init, .array_init_anon, .array_init_ref, .array_init_anon_ref, .union_init_ptr, .field_type, .field_type_ref, .opaque_decl, .opaque_decl_anon, .opaque_decl_func, .error_set_decl, .error_set_decl_anon, .error_set_decl_func, .int_to_enum, .enum_to_int, .type_info, .size_of, .bit_size_of, .log2_int_type, .typeof_log2_int_type, .ptr_to_int, .align_of, .bool_to_int, .embed_file, .error_name, .sqrt, .sin, .cos, .exp, .exp2, .log, .log2, .log10, .fabs, .floor, .ceil, .trunc, .round, .tag_name, .reify, .type_name, .frame_type, .frame_size, .float_to_int, .int_to_float, .int_to_ptr, .float_cast, .int_cast, .err_set_cast, .ptr_cast, .truncate, .align_cast, .has_decl, .has_field, .clz, .ctz, .pop_count, .byte_swap, .bit_reverse, .div_exact, .div_floor, .div_trunc, .mod, .rem, .shl_exact, .shr_exact, .bit_offset_of, .offset_of, .cmpxchg_strong, .cmpxchg_weak, .splat, .reduce, .shuffle, .select, .atomic_load, .atomic_rmw, .atomic_store, .mul_add, .builtin_call, .field_ptr_type, .field_parent_ptr, .maximum, .memcpy, .memset, .minimum, .builtin_async_call, .c_import, .@"resume", .@"await", .await_nosuspend, .ret_err_value_code, .extended, => break :b false, // ZIR instructions that are always `noreturn`. .@"break", .break_inline, .condbr, .condbr_inline, .compile_error, .ret_node, .ret_load, .ret_coerce, .ret_err_value, .@"unreachable", .repeat, .repeat_inline, .panic, => { noreturn_src_node = statement; break :b true; }, // ZIR instructions that are always `void`. .breakpoint, .fence, .dbg_stmt, .ensure_result_used, .ensure_result_non_error, .@"export", .set_eval_branch_quota, .ensure_err_payload_void, .store, .store_node, .store_to_block_ptr, .store_to_inferred_ptr, .resolve_inferred_alloc, .validate_struct_init_ptr, .validate_array_init_ptr, .set_align_stack, .set_cold, .set_float_mode, .set_runtime_safety, => break :b true, } } else switch (maybe_unused_result) { .none => unreachable, .unreachable_value => b: { noreturn_src_node = statement; break :b true; }, .void_value => true, else => false, }; if (!elide_check) { _ = try gz.addUnNode(.ensure_result_used, maybe_unused_result, statement); } return noreturn_src_node; } fn countDefers(astgen: *AstGen, outer_scope: *Scope, inner_scope: *Scope) struct { have_any: bool, have_normal: bool, have_err: bool, need_err_code: bool, } { const tree = astgen.tree; const node_datas = tree.nodes.items(.data); var have_normal = false; var have_err = false; var need_err_code = false; var scope = inner_scope; while (scope != outer_scope) { switch (scope.tag) { .gen_zir => scope = scope.cast(GenZir).?.parent, .local_val => scope = scope.cast(Scope.LocalVal).?.parent, .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, .defer_normal => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; have_normal = true; }, .defer_error => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; have_err = true; const have_err_payload = node_datas[defer_scope.defer_node].lhs != 0; need_err_code = need_err_code or have_err_payload; }, .namespace => unreachable, .top => unreachable, } } return .{ .have_any = have_normal or have_err, .have_normal = have_normal, .have_err = have_err, .need_err_code = need_err_code, }; } const DefersToEmit = union(enum) { both: Zir.Inst.Ref, // err code both_sans_err, normal_only, }; fn genDefers( gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope, which_ones: DefersToEmit, ) InnerError!void { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); var scope = inner_scope; while (scope != outer_scope) { switch (scope.tag) { .gen_zir => scope = scope.cast(GenZir).?.parent, .local_val => scope = scope.cast(Scope.LocalVal).?.parent, .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent, .defer_normal => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; const expr_node = node_datas[defer_scope.defer_node].rhs; const prev_in_defer = gz.in_defer; gz.in_defer = true; defer gz.in_defer = prev_in_defer; _ = try unusedResultExpr(gz, defer_scope.parent, expr_node); }, .defer_error => { const defer_scope = scope.cast(Scope.Defer).?; scope = defer_scope.parent; switch (which_ones) { .both_sans_err => { const expr_node = node_datas[defer_scope.defer_node].rhs; const prev_in_defer = gz.in_defer; gz.in_defer = true; defer gz.in_defer = prev_in_defer; _ = try unusedResultExpr(gz, defer_scope.parent, expr_node); }, .both => |err_code| { const expr_node = node_datas[defer_scope.defer_node].rhs; const payload_token = node_datas[defer_scope.defer_node].lhs; const prev_in_defer = gz.in_defer; gz.in_defer = true; defer gz.in_defer = prev_in_defer; var local_val_scope: Scope.LocalVal = undefined; const sub_scope = if (payload_token == 0) defer_scope.parent else blk: { const ident_name = try astgen.identAsString(payload_token); local_val_scope = .{ .parent = defer_scope.parent, .gen_zir = gz, .name = ident_name, .inst = err_code, .token_src = payload_token, .id_cat = .@"capture", }; break :blk &local_val_scope.base; }; _ = try unusedResultExpr(gz, sub_scope, expr_node); }, .normal_only => continue, } }, .namespace => unreachable, .top => unreachable, } } } fn checkUsed( gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope, ) InnerError!void { const astgen = gz.astgen; var scope = inner_scope; while (scope != outer_scope) { switch (scope.tag) { .gen_zir => scope = scope.cast(GenZir).?.parent, .local_val => { const s = scope.cast(Scope.LocalVal).?; if (!s.used) { return astgen.failTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)}); } scope = s.parent; }, .local_ptr => { const s = scope.cast(Scope.LocalPtr).?; if (!s.used) { return astgen.failTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)}); } scope = s.parent; }, .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent, .namespace => unreachable, .top => unreachable, } } } fn makeDeferScope( scope: *Scope, node: ast.Node.Index, block_arena: *Allocator, scope_tag: Scope.Tag, ) InnerError!*Scope { const defer_scope = try block_arena.create(Scope.Defer); defer_scope.* = .{ .base = .{ .tag = scope_tag }, .parent = scope, .defer_node = node, }; return &defer_scope.base; } fn varDecl( gz: *GenZir, scope: *Scope, node: ast.Node.Index, block_arena: *Allocator, var_decl: ast.full.VarDecl, ) InnerError!*Scope { try emitDbgNode(gz, node); const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const name_token = var_decl.ast.mut_token + 1; const ident_name_raw = tree.tokenSlice(name_token); if (mem.eql(u8, ident_name_raw, "_")) { return astgen.failTok(name_token, "'_' used as an identifier without @\"_\" syntax", .{}); } const ident_name = try astgen.identAsString(name_token); try astgen.detectLocalShadowing(scope, ident_name, name_token, ident_name_raw); if (var_decl.ast.init_node == 0) { return astgen.failNode(node, "variables must be initialized", .{}); } const align_inst: Zir.Inst.Ref = if (var_decl.ast.align_node != 0) try expr(gz, scope, align_rl, var_decl.ast.align_node) else .none; switch (token_tags[var_decl.ast.mut_token]) { .keyword_const => { if (var_decl.comptime_token) |comptime_token| { return astgen.failTok(comptime_token, "'comptime const' is redundant; instead wrap the initialization expression with 'comptime'", .{}); } // Depending on the type of AST the initialization expression is, we may need an lvalue // or an rvalue as a result location. If it is an rvalue, we can use the instruction as // the variable, no memory location needed. if (align_inst == .none and !nodeMayNeedMemoryLocation(tree, var_decl.ast.init_node)) { const result_loc: ResultLoc = if (var_decl.ast.type_node != 0) .{ .ty = try typeExpr(gz, scope, var_decl.ast.type_node), } else .none; const init_inst = try reachableExpr(gz, scope, result_loc, var_decl.ast.init_node, node); const sub_scope = try block_arena.create(Scope.LocalVal); sub_scope.* = .{ .parent = scope, .gen_zir = gz, .name = ident_name, .inst = init_inst, .token_src = name_token, .id_cat = .@"local constant", }; return &sub_scope.base; } // Detect whether the initialization expression actually uses the // result location pointer. var init_scope = gz.makeSubBlock(scope); defer init_scope.instructions.deinit(gpa); var resolve_inferred_alloc: Zir.Inst.Ref = .none; var opt_type_inst: Zir.Inst.Ref = .none; if (var_decl.ast.type_node != 0) { const type_inst = try typeExpr(gz, &init_scope.base, var_decl.ast.type_node); opt_type_inst = type_inst; if (align_inst == .none) { init_scope.rl_ptr = try init_scope.addUnNode(.alloc, type_inst, node); } else { init_scope.rl_ptr = try gz.addAllocExtended(.{ .node = node, .type_inst = type_inst, .align_inst = align_inst, .is_const = true, .is_comptime = false, }); } init_scope.rl_ty_inst = type_inst; } else { const alloc = if (align_inst == .none) try init_scope.addNode(.alloc_inferred, node) else try gz.addAllocExtended(.{ .node = node, .type_inst = .none, .align_inst = align_inst, .is_const = true, .is_comptime = false, }); resolve_inferred_alloc = alloc; init_scope.rl_ptr = alloc; } const init_result_loc: ResultLoc = .{ .block_ptr = &init_scope }; const init_inst = try reachableExpr(&init_scope, &init_scope.base, init_result_loc, var_decl.ast.init_node, node); const zir_tags = astgen.instructions.items(.tag); const zir_datas = astgen.instructions.items(.data); const parent_zir = &gz.instructions; if (align_inst == .none and init_scope.rvalue_rl_count == 1) { // Result location pointer not used. We don't need an alloc for this // const local, and type inference becomes trivial. // Move the init_scope instructions into the parent scope, eliding // the alloc instruction and the store_to_block_ptr instruction. try parent_zir.ensureUnusedCapacity(gpa, init_scope.instructions.items.len); for (init_scope.instructions.items) |src_inst| { if (indexToRef(src_inst) == init_scope.rl_ptr) continue; if (zir_tags[src_inst] == .store_to_block_ptr) { if (zir_datas[src_inst].bin.lhs == init_scope.rl_ptr) continue; } parent_zir.appendAssumeCapacity(src_inst); } const sub_scope = try block_arena.create(Scope.LocalVal); sub_scope.* = .{ .parent = scope, .gen_zir = gz, .name = ident_name, .inst = init_inst, .token_src = name_token, .id_cat = .@"local constant", }; return &sub_scope.base; } // The initialization expression took advantage of the result location // of the const local. In this case we will create an alloc and a LocalPtr for it. // Move the init_scope instructions into the parent scope, swapping // store_to_block_ptr for store_to_inferred_ptr. const expected_len = parent_zir.items.len + init_scope.instructions.items.len; try parent_zir.ensureTotalCapacity(gpa, expected_len); for (init_scope.instructions.items) |src_inst| { if (zir_tags[src_inst] == .store_to_block_ptr) { if (zir_datas[src_inst].bin.lhs == init_scope.rl_ptr) { zir_tags[src_inst] = .store_to_inferred_ptr; } } parent_zir.appendAssumeCapacity(src_inst); } assert(parent_zir.items.len == expected_len); if (resolve_inferred_alloc != .none) { _ = try gz.addUnNode(.resolve_inferred_alloc, resolve_inferred_alloc, node); } const sub_scope = try block_arena.create(Scope.LocalPtr); sub_scope.* = .{ .parent = scope, .gen_zir = gz, .name = ident_name, .ptr = init_scope.rl_ptr, .token_src = name_token, .maybe_comptime = true, .id_cat = .@"local constant", }; return &sub_scope.base; }, .keyword_var => { const is_comptime = var_decl.comptime_token != null or gz.force_comptime; var resolve_inferred_alloc: Zir.Inst.Ref = .none; const var_data: struct { result_loc: ResultLoc, alloc: Zir.Inst.Ref, } = if (var_decl.ast.type_node != 0) a: { const type_inst = try typeExpr(gz, scope, var_decl.ast.type_node); const alloc = alloc: { if (align_inst == .none) { const tag: Zir.Inst.Tag = if (is_comptime) .alloc_comptime else .alloc_mut; break :alloc try gz.addUnNode(tag, type_inst, node); } else { break :alloc try gz.addAllocExtended(.{ .node = node, .type_inst = type_inst, .align_inst = align_inst, .is_const = false, .is_comptime = is_comptime, }); } }; break :a .{ .alloc = alloc, .result_loc = .{ .ptr = alloc } }; } else a: { const alloc = alloc: { if (align_inst == .none) { const tag: Zir.Inst.Tag = if (is_comptime) .alloc_inferred_comptime else .alloc_inferred_mut; break :alloc try gz.addNode(tag, node); } else { break :alloc try gz.addAllocExtended(.{ .node = node, .type_inst = .none, .align_inst = align_inst, .is_const = false, .is_comptime = is_comptime, }); } }; resolve_inferred_alloc = alloc; break :a .{ .alloc = alloc, .result_loc = .{ .inferred_ptr = alloc } }; }; _ = try reachableExpr(gz, scope, var_data.result_loc, var_decl.ast.init_node, node); if (resolve_inferred_alloc != .none) { _ = try gz.addUnNode(.resolve_inferred_alloc, resolve_inferred_alloc, node); } const sub_scope = try block_arena.create(Scope.LocalPtr); sub_scope.* = .{ .parent = scope, .gen_zir = gz, .name = ident_name, .ptr = var_data.alloc, .token_src = name_token, .maybe_comptime = is_comptime, .id_cat = .@"local variable", }; return &sub_scope.base; }, else => unreachable, } } fn emitDbgNode(gz: *GenZir, node: ast.Node.Index) !void { // The instruction emitted here is for debugging runtime code. // If the current block will be evaluated only during semantic analysis // then no dbg_stmt ZIR instruction is needed. if (gz.force_comptime) return; const astgen = gz.astgen; const tree = astgen.tree; const source = tree.source; const token_starts = tree.tokens.items(.start); const node_start = token_starts[tree.firstToken(node)]; astgen.advanceSourceCursor(source, node_start); const line = @intCast(u32, astgen.source_line); const column = @intCast(u32, astgen.source_column); _ = try gz.add(.{ .tag = .dbg_stmt, .data = .{ .dbg_stmt = .{ .line = line, .column = column, }, } }); } fn assign(gz: *GenZir, scope: *Scope, infix_node: ast.Node.Index) InnerError!void { try emitDbgNode(gz, infix_node); const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const node_tags = tree.nodes.items(.tag); const lhs = node_datas[infix_node].lhs; const rhs = node_datas[infix_node].rhs; if (node_tags[lhs] == .identifier) { // This intentionally does not support `@"_"` syntax. const ident_name = tree.tokenSlice(main_tokens[lhs]); if (mem.eql(u8, ident_name, "_")) { _ = try expr(gz, scope, .discard, rhs); return; } } const lvalue = try lvalExpr(gz, scope, lhs); _ = try expr(gz, scope, .{ .ptr = lvalue }, rhs); } fn assignOp( gz: *GenZir, scope: *Scope, infix_node: ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!void { try emitDbgNode(gz, infix_node); const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const lhs_ptr = try lvalExpr(gz, scope, node_datas[infix_node].lhs); const lhs = try gz.addUnNode(.load, lhs_ptr, infix_node); const lhs_type = try gz.addUnNode(.typeof, lhs, infix_node); const rhs = try expr(gz, scope, .{ .coerced_ty = lhs_type }, node_datas[infix_node].rhs); const result = try gz.addPlNode(op_inst_tag, infix_node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs, }); _ = try gz.addBin(.store, lhs_ptr, result); } fn assignShift( gz: *GenZir, scope: *Scope, infix_node: ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!void { try emitDbgNode(gz, infix_node); const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const lhs_ptr = try lvalExpr(gz, scope, node_datas[infix_node].lhs); const lhs = try gz.addUnNode(.load, lhs_ptr, infix_node); const rhs_type = try gz.addUnNode(.typeof_log2_int_type, lhs, infix_node); const rhs = try expr(gz, scope, .{ .ty = rhs_type }, node_datas[infix_node].rhs); const result = try gz.addPlNode(op_inst_tag, infix_node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs, }); _ = try gz.addBin(.store, lhs_ptr, result); } fn boolNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const operand = try expr(gz, scope, bool_rl, node_datas[node].lhs); const result = try gz.addUnNode(.bool_not, operand, node); return rvalue(gz, rl, result, node); } fn bitNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const operand = try expr(gz, scope, .none, node_datas[node].lhs); const result = try gz.addUnNode(.bit_not, operand, node); return rvalue(gz, rl, result, node); } fn negation( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const operand = try expr(gz, scope, .none, node_datas[node].lhs); const result = try gz.addUnNode(tag, operand, node); return rvalue(gz, rl, result, node); } fn ptrType( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ptr_info: ast.full.PtrType, ) InnerError!Zir.Inst.Ref { const elem_type = try typeExpr(gz, scope, ptr_info.ast.child_type); const simple = ptr_info.ast.align_node == 0 and ptr_info.ast.sentinel == 0 and ptr_info.ast.bit_range_start == 0; if (simple) { const result = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = ptr_info.allowzero_token != null, .is_mutable = ptr_info.const_token == null, .is_volatile = ptr_info.volatile_token != null, .size = ptr_info.size, .elem_type = elem_type, }, } }); return rvalue(gz, rl, result, node); } var sentinel_ref: Zir.Inst.Ref = .none; var align_ref: Zir.Inst.Ref = .none; var bit_start_ref: Zir.Inst.Ref = .none; var bit_end_ref: Zir.Inst.Ref = .none; var trailing_count: u32 = 0; if (ptr_info.ast.sentinel != 0) { sentinel_ref = try expr(gz, scope, .{ .ty = elem_type }, ptr_info.ast.sentinel); trailing_count += 1; } if (ptr_info.ast.align_node != 0) { align_ref = try expr(gz, scope, align_rl, ptr_info.ast.align_node); trailing_count += 1; } if (ptr_info.ast.bit_range_start != 0) { assert(ptr_info.ast.bit_range_end != 0); bit_start_ref = try expr(gz, scope, .none, ptr_info.ast.bit_range_start); bit_end_ref = try expr(gz, scope, .none, ptr_info.ast.bit_range_end); trailing_count += 2; } const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.PtrType).Struct.fields.len + trailing_count); const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.PtrType{ .elem_type = elem_type }); if (sentinel_ref != .none) { gz.astgen.extra.appendAssumeCapacity(@enumToInt(sentinel_ref)); } if (align_ref != .none) { gz.astgen.extra.appendAssumeCapacity(@enumToInt(align_ref)); } if (bit_start_ref != .none) { gz.astgen.extra.appendAssumeCapacity(@enumToInt(bit_start_ref)); gz.astgen.extra.appendAssumeCapacity(@enumToInt(bit_end_ref)); } const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); const result = indexToRef(new_index); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = .ptr_type, .data = .{ .ptr_type = .{ .flags = .{ .is_allowzero = ptr_info.allowzero_token != null, .is_mutable = ptr_info.const_token == null, .is_volatile = ptr_info.volatile_token != null, .has_sentinel = sentinel_ref != .none, .has_align = align_ref != .none, .has_bit_range = bit_start_ref != .none, }, .size = ptr_info.size, .payload_index = payload_index, }, } }); gz.instructions.appendAssumeCapacity(new_index); return rvalue(gz, rl, result, node); } fn arrayType(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); const len_node = node_datas[node].lhs; if (node_tags[len_node] == .identifier and mem.eql(u8, tree.tokenSlice(main_tokens[len_node]), "_")) { return astgen.failNode(len_node, "unable to infer array size", .{}); } const len = try expr(gz, scope, .{ .coerced_ty = .usize_type }, len_node); const elem_type = try typeExpr(gz, scope, node_datas[node].rhs); const result = try gz.addBin(.array_type, len, elem_type); return rvalue(gz, rl, result, node); } fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); const extra = tree.extraData(node_datas[node].rhs, ast.Node.ArrayTypeSentinel); const len_node = node_datas[node].lhs; if (node_tags[len_node] == .identifier and mem.eql(u8, tree.tokenSlice(main_tokens[len_node]), "_")) { return astgen.failNode(len_node, "unable to infer array size", .{}); } const len = try expr(gz, scope, .{ .coerced_ty = .usize_type }, len_node); const elem_type = try typeExpr(gz, scope, extra.elem_type); const sentinel = try expr(gz, scope, .{ .coerced_ty = elem_type }, extra.sentinel); const result = try gz.addArrayTypeSentinel(len, elem_type, sentinel); return rvalue(gz, rl, result, node); } const WipDecls = struct { decl_index: usize = 0, cur_bit_bag: u32 = 0, bit_bag: ArrayListUnmanaged(u32) = .{}, payload: ArrayListUnmanaged(u32) = .{}, const bits_per_field = 4; const fields_per_u32 = 32 / bits_per_field; fn next( wip_decls: *WipDecls, gpa: *Allocator, is_pub: bool, is_export: bool, has_align: bool, has_section: bool, ) Allocator.Error!void { if (wip_decls.decl_index % fields_per_u32 == 0 and wip_decls.decl_index != 0) { try wip_decls.bit_bag.append(gpa, wip_decls.cur_bit_bag); wip_decls.cur_bit_bag = 0; } wip_decls.cur_bit_bag = (wip_decls.cur_bit_bag >> bits_per_field) | (@as(u32, @boolToInt(is_pub)) << 28) | (@as(u32, @boolToInt(is_export)) << 29) | (@as(u32, @boolToInt(has_align)) << 30) | (@as(u32, @boolToInt(has_section)) << 31); wip_decls.decl_index += 1; } fn deinit(wip_decls: *WipDecls, gpa: *Allocator) void { wip_decls.bit_bag.deinit(gpa); wip_decls.payload.deinit(gpa); } }; fn fnDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, decl_node: ast.Node.Index, body_node: ast.Node.Index, fn_proto: ast.full.FnProto, ) InnerError!void { const gpa = astgen.gpa; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const fn_name_token = fn_proto.name_token orelse { return astgen.failTok(fn_proto.ast.fn_token, "missing function name", .{}); }; const fn_name_str_index = try astgen.identAsString(fn_name_token); // We insert this at the beginning so that its instruction index marks the // start of the top level declaration. const block_inst = try gz.addBlock(.block_inline, fn_proto.ast.proto_node); var decl_gz: GenZir = .{ .force_comptime = true, .in_defer = false, .decl_node_index = fn_proto.ast.proto_node, .decl_line = gz.calcLine(decl_node), .parent = scope, .astgen = astgen, }; defer decl_gz.instructions.deinit(gpa); var fn_gz: GenZir = .{ .force_comptime = false, .in_defer = false, .decl_node_index = fn_proto.ast.proto_node, .decl_line = decl_gz.decl_line, .parent = &decl_gz.base, .astgen = astgen, }; defer fn_gz.instructions.deinit(gpa); // TODO: support noinline const is_pub = fn_proto.visib_token != null; const is_export = blk: { const maybe_export_token = fn_proto.extern_export_inline_token orelse break :blk false; break :blk token_tags[maybe_export_token] == .keyword_export; }; const is_extern = blk: { const maybe_extern_token = fn_proto.extern_export_inline_token orelse break :blk false; break :blk token_tags[maybe_extern_token] == .keyword_extern; }; const has_inline_keyword = blk: { const maybe_inline_token = fn_proto.extern_export_inline_token orelse break :blk false; break :blk token_tags[maybe_inline_token] == .keyword_inline; }; try wip_decls.next(gpa, is_pub, is_export, fn_proto.ast.align_expr != 0, fn_proto.ast.section_expr != 0); var params_scope = &fn_gz.base; const is_var_args = is_var_args: { var param_type_i: usize = 0; var it = fn_proto.iterate(tree.*); while (it.next()) |param| : (param_type_i += 1) { const is_comptime = if (param.comptime_noalias) |token| token_tags[token] == .keyword_comptime else false; const is_anytype = if (param.anytype_ellipsis3) |token| blk: { switch (token_tags[token]) { .keyword_anytype => break :blk true, .ellipsis3 => break :is_var_args true, else => unreachable, } } else false; const param_name: u32 = if (param.name_token) |name_token| blk: { const name_bytes = tree.tokenSlice(name_token); if (mem.eql(u8, "_", name_bytes)) break :blk 0; const param_name = try astgen.identAsString(name_token); if (!is_extern) { try astgen.detectLocalShadowing(params_scope, param_name, name_token, name_bytes); } break :blk param_name; } else if (!is_extern) { if (param.anytype_ellipsis3) |tok| { return astgen.failTok(tok, "missing parameter name", .{}); } else { return astgen.failNode(param.type_expr, "missing parameter name", .{}); } } else 0; const param_inst = if (is_anytype) param: { const name_token = param.name_token orelse param.anytype_ellipsis3.?; const tag: Zir.Inst.Tag = if (is_comptime) .param_anytype_comptime else .param_anytype; break :param try decl_gz.addStrTok(tag, param_name, name_token); } else param: { const param_type_node = param.type_expr; assert(param_type_node != 0); var param_gz = decl_gz.makeSubBlock(scope); defer param_gz.instructions.deinit(gpa); const param_type = try expr(&param_gz, params_scope, coerced_type_rl, param_type_node); const param_inst_expected = @intCast(u32, astgen.instructions.len + 1); _ = try param_gz.addBreak(.break_inline, param_inst_expected, param_type); const main_tokens = tree.nodes.items(.main_token); const name_token = param.name_token orelse main_tokens[param_type_node]; const tag: Zir.Inst.Tag = if (is_comptime) .param_comptime else .param; const param_inst = try decl_gz.addParam(tag, name_token, param_name, param_gz.instructions.items); assert(param_inst_expected == param_inst); break :param indexToRef(param_inst); }; if (param_name == 0) continue; const sub_scope = try astgen.arena.create(Scope.LocalVal); sub_scope.* = .{ .parent = params_scope, .gen_zir = &decl_gz, .name = param_name, .inst = param_inst, .token_src = param.name_token.?, .id_cat = .@"function parameter", }; params_scope = &sub_scope.base; } break :is_var_args false; }; const lib_name: u32 = if (fn_proto.lib_name) |lib_name_token| blk: { const lib_name_str = try astgen.strLitAsString(lib_name_token); break :blk lib_name_str.index; } else 0; const maybe_bang = tree.firstToken(fn_proto.ast.return_type) - 1; const is_inferred_error = token_tags[maybe_bang] == .bang; const align_inst: Zir.Inst.Ref = if (fn_proto.ast.align_expr == 0) .none else inst: { break :inst try expr(&decl_gz, params_scope, align_rl, fn_proto.ast.align_expr); }; const section_inst: Zir.Inst.Ref = if (fn_proto.ast.section_expr == 0) .none else inst: { break :inst try comptimeExpr(&decl_gz, params_scope, .{ .ty = .const_slice_u8_type }, fn_proto.ast.section_expr); }; var ret_gz = decl_gz.makeSubBlock(params_scope); defer ret_gz.instructions.deinit(gpa); const ret_ty = try expr(&ret_gz, params_scope, coerced_type_rl, fn_proto.ast.return_type); const ret_br = try ret_gz.addBreak(.break_inline, 0, ret_ty); const cc: Zir.Inst.Ref = blk: { if (fn_proto.ast.callconv_expr != 0) { if (has_inline_keyword) { return astgen.failNode( fn_proto.ast.callconv_expr, "explicit callconv incompatible with inline keyword", .{}, ); } break :blk try expr( &decl_gz, params_scope, .{ .ty = .calling_convention_type }, fn_proto.ast.callconv_expr, ); } else if (is_extern) { // note: https://github.com/ziglang/zig/issues/5269 break :blk .calling_convention_c; } else if (has_inline_keyword) { break :blk .calling_convention_inline; } else { break :blk .none; } }; const func_inst: Zir.Inst.Ref = if (body_node == 0) func: { if (!is_extern) { return astgen.failTok(fn_proto.ast.fn_token, "non-extern function has no body", .{}); } if (is_inferred_error) { return astgen.failTok(maybe_bang, "function prototype may not have inferred error set", .{}); } break :func try decl_gz.addFunc(.{ .src_node = decl_node, .ret_ty = ret_gz.instructions.items, .ret_br = ret_br, .param_block = block_inst, .body = &[0]Zir.Inst.Index{}, .cc = cc, .align_inst = .none, // passed in the per-decl data .lib_name = lib_name, .is_var_args = is_var_args, .is_inferred_error = false, .is_test = false, .is_extern = true, }); } else func: { if (is_var_args) { return astgen.failTok(fn_proto.ast.fn_token, "non-extern function is variadic", .{}); } const prev_fn_block = astgen.fn_block; astgen.fn_block = &fn_gz; defer astgen.fn_block = prev_fn_block; _ = try expr(&fn_gz, params_scope, .none, body_node); try checkUsed(gz, &fn_gz.base, params_scope); const need_implicit_ret = blk: { if (fn_gz.instructions.items.len == 0) break :blk true; const last = fn_gz.instructions.items[fn_gz.instructions.items.len - 1]; const zir_tags = astgen.instructions.items(.tag); break :blk !zir_tags[last].isNoReturn(); }; if (need_implicit_ret) { // Since we are adding the return instruction here, we must handle the coercion. // We do this by using the `ret_coerce` instruction. _ = try fn_gz.addUnTok(.ret_coerce, .void_value, tree.lastToken(body_node)); } break :func try decl_gz.addFunc(.{ .src_node = decl_node, .param_block = block_inst, .ret_ty = ret_gz.instructions.items, .ret_br = ret_br, .body = fn_gz.instructions.items, .cc = cc, .align_inst = .none, // passed in the per-decl data .lib_name = lib_name, .is_var_args = is_var_args, .is_inferred_error = is_inferred_error, .is_test = false, .is_extern = false, }); }; // We add this at the end so that its instruction index marks the end range // of the top level declaration. _ = try decl_gz.addBreak(.break_inline, block_inst, func_inst); try decl_gz.setBlockBody(block_inst); try wip_decls.payload.ensureUnusedCapacity(gpa, 9); { const contents_hash = std.zig.hashSrc(tree.getNodeSource(decl_node)); const casted = @bitCast([4]u32, contents_hash); wip_decls.payload.appendSliceAssumeCapacity(&casted); } { const line_delta = decl_gz.decl_line - gz.decl_line; wip_decls.payload.appendAssumeCapacity(line_delta); } wip_decls.payload.appendAssumeCapacity(fn_name_str_index); wip_decls.payload.appendAssumeCapacity(block_inst); if (align_inst != .none) { wip_decls.payload.appendAssumeCapacity(@enumToInt(align_inst)); } if (section_inst != .none) { wip_decls.payload.appendAssumeCapacity(@enumToInt(section_inst)); } } fn globalVarDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: ast.Node.Index, var_decl: ast.full.VarDecl, ) InnerError!void { const gpa = astgen.gpa; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const is_mutable = token_tags[var_decl.ast.mut_token] == .keyword_var; // We do this at the beginning so that the instruction index marks the range start // of the top level declaration. const block_inst = try gz.addBlock(.block_inline, node); const name_token = var_decl.ast.mut_token + 1; const name_str_index = try astgen.identAsString(name_token); var block_scope: GenZir = .{ .parent = scope, .decl_node_index = node, .decl_line = gz.calcLine(node), .astgen = astgen, .force_comptime = true, .in_defer = false, .anon_name_strategy = .parent, }; defer block_scope.instructions.deinit(gpa); const is_pub = var_decl.visib_token != null; const is_export = blk: { const maybe_export_token = var_decl.extern_export_token orelse break :blk false; break :blk token_tags[maybe_export_token] == .keyword_export; }; const is_extern = blk: { const maybe_extern_token = var_decl.extern_export_token orelse break :blk false; break :blk token_tags[maybe_extern_token] == .keyword_extern; }; const align_inst: Zir.Inst.Ref = if (var_decl.ast.align_node == 0) .none else inst: { break :inst try expr(&block_scope, &block_scope.base, align_rl, var_decl.ast.align_node); }; const section_inst: Zir.Inst.Ref = if (var_decl.ast.section_node == 0) .none else inst: { break :inst try comptimeExpr(&block_scope, &block_scope.base, .{ .ty = .const_slice_u8_type }, var_decl.ast.section_node); }; try wip_decls.next(gpa, is_pub, is_export, align_inst != .none, section_inst != .none); const is_threadlocal = if (var_decl.threadlocal_token) |tok| blk: { if (!is_mutable) { return astgen.failTok(tok, "threadlocal variable cannot be constant", .{}); } break :blk true; } else false; const lib_name: u32 = if (var_decl.lib_name) |lib_name_token| blk: { const lib_name_str = try astgen.strLitAsString(lib_name_token); break :blk lib_name_str.index; } else 0; assert(var_decl.comptime_token == null); // handled by parser const var_inst: Zir.Inst.Ref = if (var_decl.ast.init_node != 0) vi: { if (is_extern) { return astgen.failNode( var_decl.ast.init_node, "extern variables have no initializers", .{}, ); } const type_inst: Zir.Inst.Ref = if (var_decl.ast.type_node != 0) try expr( &block_scope, &block_scope.base, .{ .ty = .type_type }, var_decl.ast.type_node, ) else .none; const init_inst = try expr( &block_scope, &block_scope.base, if (type_inst != .none) .{ .ty = type_inst } else .none, var_decl.ast.init_node, ); if (is_mutable) { const var_inst = try block_scope.addVar(.{ .var_type = type_inst, .lib_name = 0, .align_inst = .none, // passed via the decls data .init = init_inst, .is_extern = false, .is_threadlocal = is_threadlocal, }); break :vi var_inst; } else { break :vi init_inst; } } else if (!is_extern) { return astgen.failNode(node, "variables must be initialized", .{}); } else if (var_decl.ast.type_node != 0) vi: { // Extern variable which has an explicit type. const type_inst = try typeExpr(&block_scope, &block_scope.base, var_decl.ast.type_node); const var_inst = try block_scope.addVar(.{ .var_type = type_inst, .lib_name = lib_name, .align_inst = .none, // passed via the decls data .init = .none, .is_extern = true, .is_threadlocal = is_threadlocal, }); break :vi var_inst; } else { return astgen.failNode(node, "unable to infer variable type", .{}); }; // We do this at the end so that the instruction index marks the end // range of a top level declaration. _ = try block_scope.addBreak(.break_inline, block_inst, var_inst); try block_scope.setBlockBody(block_inst); try wip_decls.payload.ensureUnusedCapacity(gpa, 9); { const contents_hash = std.zig.hashSrc(tree.getNodeSource(node)); const casted = @bitCast([4]u32, contents_hash); wip_decls.payload.appendSliceAssumeCapacity(&casted); } { const line_delta = block_scope.decl_line - gz.decl_line; wip_decls.payload.appendAssumeCapacity(line_delta); } wip_decls.payload.appendAssumeCapacity(name_str_index); wip_decls.payload.appendAssumeCapacity(block_inst); if (align_inst != .none) { wip_decls.payload.appendAssumeCapacity(@enumToInt(align_inst)); } if (section_inst != .none) { wip_decls.payload.appendAssumeCapacity(@enumToInt(section_inst)); } } fn comptimeDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: ast.Node.Index, ) InnerError!void { const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].lhs; // Up top so the ZIR instruction index marks the start range of this // top-level declaration. const block_inst = try gz.addBlock(.block_inline, node); try wip_decls.next(gpa, false, false, false, false); var decl_block: GenZir = .{ .force_comptime = true, .in_defer = false, .decl_node_index = node, .decl_line = gz.calcLine(node), .parent = scope, .astgen = astgen, }; defer decl_block.instructions.deinit(gpa); const block_result = try expr(&decl_block, &decl_block.base, .none, body_node); if (decl_block.instructions.items.len == 0 or !decl_block.refIsNoReturn(block_result)) { _ = try decl_block.addBreak(.break_inline, block_inst, .void_value); } try decl_block.setBlockBody(block_inst); try wip_decls.payload.ensureUnusedCapacity(gpa, 7); { const contents_hash = std.zig.hashSrc(tree.getNodeSource(node)); const casted = @bitCast([4]u32, contents_hash); wip_decls.payload.appendSliceAssumeCapacity(&casted); } { const line_delta = decl_block.decl_line - gz.decl_line; wip_decls.payload.appendAssumeCapacity(line_delta); } wip_decls.payload.appendAssumeCapacity(0); wip_decls.payload.appendAssumeCapacity(block_inst); } fn usingnamespaceDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: ast.Node.Index, ) InnerError!void { const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const type_expr = node_datas[node].lhs; const is_pub = blk: { const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const main_token = main_tokens[node]; break :blk (main_token > 0 and token_tags[main_token - 1] == .keyword_pub); }; // Up top so the ZIR instruction index marks the start range of this // top-level declaration. const block_inst = try gz.addBlock(.block_inline, node); try wip_decls.next(gpa, is_pub, true, false, false); var decl_block: GenZir = .{ .force_comptime = true, .in_defer = false, .decl_node_index = node, .decl_line = gz.calcLine(node), .parent = scope, .astgen = astgen, }; defer decl_block.instructions.deinit(gpa); const namespace_inst = try typeExpr(&decl_block, &decl_block.base, type_expr); _ = try decl_block.addBreak(.break_inline, block_inst, namespace_inst); try decl_block.setBlockBody(block_inst); try wip_decls.payload.ensureUnusedCapacity(gpa, 7); { const contents_hash = std.zig.hashSrc(tree.getNodeSource(node)); const casted = @bitCast([4]u32, contents_hash); wip_decls.payload.appendSliceAssumeCapacity(&casted); } { const line_delta = decl_block.decl_line - gz.decl_line; wip_decls.payload.appendAssumeCapacity(line_delta); } wip_decls.payload.appendAssumeCapacity(0); wip_decls.payload.appendAssumeCapacity(block_inst); } fn testDecl( astgen: *AstGen, gz: *GenZir, scope: *Scope, wip_decls: *WipDecls, node: ast.Node.Index, ) InnerError!void { const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].rhs; // Up top so the ZIR instruction index marks the start range of this // top-level declaration. const block_inst = try gz.addBlock(.block_inline, node); try wip_decls.next(gpa, false, false, false, false); var decl_block: GenZir = .{ .force_comptime = true, .in_defer = false, .decl_node_index = node, .decl_line = gz.calcLine(node), .parent = scope, .astgen = astgen, }; defer decl_block.instructions.deinit(gpa); const test_name: u32 = blk: { const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const test_token = main_tokens[node]; const str_lit_token = test_token + 1; if (token_tags[str_lit_token] == .string_literal) { break :blk try astgen.testNameString(str_lit_token); } // String table index 1 has a special meaning here of test decl with no name. break :blk 1; }; var fn_block: GenZir = .{ .force_comptime = false, .in_defer = false, .decl_node_index = node, .decl_line = decl_block.decl_line, .parent = &decl_block.base, .astgen = astgen, }; defer fn_block.instructions.deinit(gpa); const prev_fn_block = astgen.fn_block; astgen.fn_block = &fn_block; defer astgen.fn_block = prev_fn_block; const block_result = try expr(&fn_block, &fn_block.base, .none, body_node); if (fn_block.instructions.items.len == 0 or !fn_block.refIsNoReturn(block_result)) { // Since we are adding the return instruction here, we must handle the coercion. // We do this by using the `ret_coerce` instruction. _ = try fn_block.addUnTok(.ret_coerce, .void_value, tree.lastToken(body_node)); } const func_inst = try decl_block.addFunc(.{ .src_node = node, .param_block = block_inst, .ret_ty = &.{}, .ret_br = 0, .body = fn_block.instructions.items, .cc = .none, .align_inst = .none, .lib_name = 0, .is_var_args = false, .is_inferred_error = true, .is_test = true, .is_extern = false, }); _ = try decl_block.addBreak(.break_inline, block_inst, func_inst); try decl_block.setBlockBody(block_inst); try wip_decls.payload.ensureUnusedCapacity(gpa, 7); { const contents_hash = std.zig.hashSrc(tree.getNodeSource(node)); const casted = @bitCast([4]u32, contents_hash); wip_decls.payload.appendSliceAssumeCapacity(&casted); } { const line_delta = decl_block.decl_line - gz.decl_line; wip_decls.payload.appendAssumeCapacity(line_delta); } wip_decls.payload.appendAssumeCapacity(test_name); wip_decls.payload.appendAssumeCapacity(block_inst); } fn structDeclInner( gz: *GenZir, scope: *Scope, node: ast.Node.Index, container_decl: ast.full.ContainerDecl, layout: std.builtin.TypeInfo.ContainerLayout, ) InnerError!Zir.Inst.Ref { if (container_decl.ast.members.len == 0) { const decl_inst = try gz.reserveInstructionIndex(); try gz.setStruct(decl_inst, .{ .src_node = node, .layout = layout, .fields_len = 0, .body_len = 0, .decls_len = 0, .known_has_bits = false, }); return indexToRef(decl_inst); } const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); // The struct_decl instruction introduces a scope in which the decls of the struct // are in scope, so that field types, alignments, and default value expressions // can refer to decls within the struct itself. var block_scope: GenZir = .{ .parent = scope, .decl_node_index = node, .decl_line = gz.calcLine(node), .astgen = astgen, .force_comptime = true, .in_defer = false, }; defer block_scope.instructions.deinit(gpa); var namespace: Scope.Namespace = .{ .parent = scope, .node = node }; defer namespace.decls.deinit(gpa); try astgen.scanDecls(&namespace, container_decl.ast.members); var wip_decls: WipDecls = .{}; defer wip_decls.deinit(gpa); // We don't know which members are fields until we iterate, so cannot do // an accurate ensureCapacity yet. var fields_data = ArrayListUnmanaged(u32){}; defer fields_data.deinit(gpa); const bits_per_field = 4; const fields_per_u32 = 32 / bits_per_field; // We only need this if there are greater than fields_per_u32 fields. var bit_bag = ArrayListUnmanaged(u32){}; defer bit_bag.deinit(gpa); var known_has_bits = false; var cur_bit_bag: u32 = 0; var field_index: usize = 0; for (container_decl.ast.members) |member_node| { const member = switch (node_tags[member_node]) { .container_field_init => tree.containerFieldInit(member_node), .container_field_align => tree.containerFieldAlign(member_node), .container_field => tree.containerField(member_node), .fn_decl => { const fn_proto = node_datas[member_node].lhs; const body = node_datas[member_node].rhs; switch (node_tags[fn_proto]) { .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoSimple(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoMulti(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoOne(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProto(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, } }, .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoSimple(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoMulti(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoOne(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProto(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .global_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.globalVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .local_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.localVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .simple_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.simpleVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .aligned_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.alignedVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"comptime" => { astgen.comptimeDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"usingnamespace" => { astgen.usingnamespaceDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .test_decl => { astgen.testDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, }; if (field_index % fields_per_u32 == 0 and field_index != 0) { try bit_bag.append(gpa, cur_bit_bag); cur_bit_bag = 0; } try fields_data.ensureUnusedCapacity(gpa, 4); const field_name = try astgen.identAsString(member.ast.name_token); fields_data.appendAssumeCapacity(field_name); if (member.ast.type_expr == 0) { return astgen.failTok(member.ast.name_token, "struct field missing type", .{}); } const field_type: Zir.Inst.Ref = if (node_tags[member.ast.type_expr] == .@"anytype") .none else try typeExpr(&block_scope, &namespace.base, member.ast.type_expr); fields_data.appendAssumeCapacity(@enumToInt(field_type)); known_has_bits = known_has_bits or nodeImpliesRuntimeBits(tree, member.ast.type_expr); const have_align = member.ast.align_expr != 0; const have_value = member.ast.value_expr != 0; const is_comptime = member.comptime_token != null; const unused = false; cur_bit_bag = (cur_bit_bag >> bits_per_field) | (@as(u32, @boolToInt(have_align)) << 28) | (@as(u32, @boolToInt(have_value)) << 29) | (@as(u32, @boolToInt(is_comptime)) << 30) | (@as(u32, @boolToInt(unused)) << 31); if (have_align) { const align_inst = try expr(&block_scope, &namespace.base, align_rl, member.ast.align_expr); fields_data.appendAssumeCapacity(@enumToInt(align_inst)); } if (have_value) { const rl: ResultLoc = if (field_type == .none) .none else .{ .ty = field_type }; const default_inst = try expr(&block_scope, &namespace.base, rl, member.ast.value_expr); fields_data.appendAssumeCapacity(@enumToInt(default_inst)); } else if (member.comptime_token) |comptime_token| { return astgen.failTok(comptime_token, "comptime field without default initialization value", .{}); } field_index += 1; } { const empty_slot_count = fields_per_u32 - (field_index % fields_per_u32); if (empty_slot_count < fields_per_u32) { cur_bit_bag >>= @intCast(u5, empty_slot_count * bits_per_field); } } { const empty_slot_count = WipDecls.fields_per_u32 - (wip_decls.decl_index % WipDecls.fields_per_u32); if (empty_slot_count < WipDecls.fields_per_u32) { wip_decls.cur_bit_bag >>= @intCast(u5, empty_slot_count * WipDecls.bits_per_field); } } const decl_inst = try gz.reserveInstructionIndex(); if (block_scope.instructions.items.len != 0) { _ = try block_scope.addBreak(.break_inline, decl_inst, .void_value); } try gz.setStruct(decl_inst, .{ .src_node = node, .layout = layout, .body_len = @intCast(u32, block_scope.instructions.items.len), .fields_len = @intCast(u32, field_index), .decls_len = @intCast(u32, wip_decls.decl_index), .known_has_bits = known_has_bits, }); try astgen.extra.ensureUnusedCapacity(gpa, bit_bag.items.len + @boolToInt(field_index != 0) + fields_data.items.len + block_scope.instructions.items.len + wip_decls.bit_bag.items.len + @boolToInt(wip_decls.decl_index != 0) + wip_decls.payload.items.len); astgen.extra.appendSliceAssumeCapacity(wip_decls.bit_bag.items); // Likely empty. if (wip_decls.decl_index != 0) { astgen.extra.appendAssumeCapacity(wip_decls.cur_bit_bag); } astgen.extra.appendSliceAssumeCapacity(wip_decls.payload.items); astgen.extra.appendSliceAssumeCapacity(block_scope.instructions.items); astgen.extra.appendSliceAssumeCapacity(bit_bag.items); // Likely empty. if (field_index != 0) { astgen.extra.appendAssumeCapacity(cur_bit_bag); } astgen.extra.appendSliceAssumeCapacity(fields_data.items); return indexToRef(decl_inst); } fn unionDeclInner( gz: *GenZir, scope: *Scope, node: ast.Node.Index, members: []const ast.Node.Index, layout: std.builtin.TypeInfo.ContainerLayout, arg_node: ast.Node.Index, have_auto_enum: bool, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); // The union_decl instruction introduces a scope in which the decls of the union // are in scope, so that field types, alignments, and default value expressions // can refer to decls within the union itself. var block_scope: GenZir = .{ .parent = scope, .decl_node_index = node, .decl_line = gz.calcLine(node), .astgen = astgen, .force_comptime = true, .in_defer = false, }; defer block_scope.instructions.deinit(gpa); var namespace: Scope.Namespace = .{ .parent = scope, .node = node }; defer namespace.decls.deinit(gpa); try astgen.scanDecls(&namespace, members); const arg_inst: Zir.Inst.Ref = if (arg_node != 0) try typeExpr(gz, &namespace.base, arg_node) else .none; var wip_decls: WipDecls = .{}; defer wip_decls.deinit(gpa); // We don't know which members are fields until we iterate, so cannot do // an accurate ensureCapacity yet. var fields_data = ArrayListUnmanaged(u32){}; defer fields_data.deinit(gpa); const bits_per_field = 4; const fields_per_u32 = 32 / bits_per_field; // We only need this if there are greater than fields_per_u32 fields. var bit_bag = ArrayListUnmanaged(u32){}; defer bit_bag.deinit(gpa); var cur_bit_bag: u32 = 0; var field_index: usize = 0; for (members) |member_node| { const member = switch (node_tags[member_node]) { .container_field_init => tree.containerFieldInit(member_node), .container_field_align => tree.containerFieldAlign(member_node), .container_field => tree.containerField(member_node), .fn_decl => { const fn_proto = node_datas[member_node].lhs; const body = node_datas[member_node].rhs; switch (node_tags[fn_proto]) { .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoSimple(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoMulti(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoOne(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProto(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, } }, .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoSimple(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoMulti(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoOne(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProto(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .global_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.globalVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .local_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.localVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .simple_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.simpleVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .aligned_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.alignedVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"comptime" => { astgen.comptimeDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"usingnamespace" => { astgen.usingnamespaceDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .test_decl => { astgen.testDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, }; if (field_index % fields_per_u32 == 0 and field_index != 0) { try bit_bag.append(gpa, cur_bit_bag); cur_bit_bag = 0; } if (member.comptime_token) |comptime_token| { return astgen.failTok(comptime_token, "union fields cannot be marked comptime", .{}); } try fields_data.ensureUnusedCapacity(gpa, if (node_tags[member.ast.type_expr] != .@"anytype") 4 else 3); const field_name = try astgen.identAsString(member.ast.name_token); fields_data.appendAssumeCapacity(field_name); const have_type = member.ast.type_expr != 0; const have_align = member.ast.align_expr != 0; const have_value = member.ast.value_expr != 0; const unused = false; cur_bit_bag = (cur_bit_bag >> bits_per_field) | (@as(u32, @boolToInt(have_type)) << 28) | (@as(u32, @boolToInt(have_align)) << 29) | (@as(u32, @boolToInt(have_value)) << 30) | (@as(u32, @boolToInt(unused)) << 31); if (have_type and node_tags[member.ast.type_expr] != .@"anytype") { const field_type = try typeExpr(&block_scope, &namespace.base, member.ast.type_expr); fields_data.appendAssumeCapacity(@enumToInt(field_type)); } if (have_align) { const align_inst = try expr(&block_scope, &block_scope.base, .{ .ty = .u32_type }, member.ast.align_expr); fields_data.appendAssumeCapacity(@enumToInt(align_inst)); } if (have_value) { if (arg_inst == .none) { return astgen.failNodeNotes( node, "explicitly valued tagged union missing integer tag type", .{}, &[_]u32{ try astgen.errNoteNode( member.ast.value_expr, "tag value specified here", .{}, ), }, ); } const tag_value = try expr(&block_scope, &block_scope.base, .{ .ty = arg_inst }, member.ast.value_expr); fields_data.appendAssumeCapacity(@enumToInt(tag_value)); } field_index += 1; } if (field_index == 0) { return astgen.failNode(node, "union declarations must have at least one tag", .{}); } { const empty_slot_count = fields_per_u32 - (field_index % fields_per_u32); if (empty_slot_count < fields_per_u32) { cur_bit_bag >>= @intCast(u5, empty_slot_count * bits_per_field); } } { const empty_slot_count = WipDecls.fields_per_u32 - (wip_decls.decl_index % WipDecls.fields_per_u32); if (empty_slot_count < WipDecls.fields_per_u32) { wip_decls.cur_bit_bag >>= @intCast(u5, empty_slot_count * WipDecls.bits_per_field); } } const decl_inst = try gz.reserveInstructionIndex(); if (block_scope.instructions.items.len != 0) { _ = try block_scope.addBreak(.break_inline, decl_inst, .void_value); } try gz.setUnion(decl_inst, .{ .src_node = node, .layout = layout, .tag_type = arg_inst, .body_len = @intCast(u32, block_scope.instructions.items.len), .fields_len = @intCast(u32, field_index), .decls_len = @intCast(u32, wip_decls.decl_index), .auto_enum_tag = have_auto_enum, }); try astgen.extra.ensureUnusedCapacity(gpa, bit_bag.items.len + 1 + fields_data.items.len + block_scope.instructions.items.len + wip_decls.bit_bag.items.len + @boolToInt(wip_decls.decl_index != 0) + wip_decls.payload.items.len); astgen.extra.appendSliceAssumeCapacity(wip_decls.bit_bag.items); // Likely empty. if (wip_decls.decl_index != 0) { astgen.extra.appendAssumeCapacity(wip_decls.cur_bit_bag); } astgen.extra.appendSliceAssumeCapacity(wip_decls.payload.items); astgen.extra.appendSliceAssumeCapacity(block_scope.instructions.items); astgen.extra.appendSliceAssumeCapacity(bit_bag.items); // Likely empty. astgen.extra.appendAssumeCapacity(cur_bit_bag); astgen.extra.appendSliceAssumeCapacity(fields_data.items); return indexToRef(decl_inst); } fn containerDecl( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, container_decl: ast.full.ContainerDecl, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const prev_fn_block = astgen.fn_block; astgen.fn_block = null; defer astgen.fn_block = prev_fn_block; // We must not create any types until Sema. Here the goal is only to generate // ZIR for all the field types, alignments, and default value expressions. switch (token_tags[container_decl.ast.main_token]) { .keyword_struct => { const layout = if (container_decl.layout_token) |t| switch (token_tags[t]) { .keyword_packed => std.builtin.TypeInfo.ContainerLayout.Packed, .keyword_extern => std.builtin.TypeInfo.ContainerLayout.Extern, else => unreachable, } else std.builtin.TypeInfo.ContainerLayout.Auto; assert(container_decl.ast.arg == 0); const result = try structDeclInner(gz, scope, node, container_decl, layout); return rvalue(gz, rl, result, node); }, .keyword_union => { const layout = if (container_decl.layout_token) |t| switch (token_tags[t]) { .keyword_packed => std.builtin.TypeInfo.ContainerLayout.Packed, .keyword_extern => std.builtin.TypeInfo.ContainerLayout.Extern, else => unreachable, } else std.builtin.TypeInfo.ContainerLayout.Auto; const have_auto_enum = container_decl.ast.enum_token != null; const result = try unionDeclInner(gz, scope, node, container_decl.ast.members, layout, container_decl.ast.arg, have_auto_enum); return rvalue(gz, rl, result, node); }, .keyword_enum => { if (container_decl.layout_token) |t| { return astgen.failTok(t, "enums do not support 'packed' or 'extern'; instead provide an explicit integer tag type", .{}); } // Count total fields as well as how many have explicitly provided tag values. const counts = blk: { var values: usize = 0; var total_fields: usize = 0; var decls: usize = 0; var nonexhaustive_node: ast.Node.Index = 0; for (container_decl.ast.members) |member_node| { const member = switch (node_tags[member_node]) { .container_field_init => tree.containerFieldInit(member_node), .container_field_align => tree.containerFieldAlign(member_node), .container_field => tree.containerField(member_node), else => { decls += 1; continue; }, }; if (member.comptime_token) |comptime_token| { return astgen.failTok(comptime_token, "enum fields cannot be marked comptime", .{}); } if (member.ast.type_expr != 0) { return astgen.failNodeNotes( member.ast.type_expr, "enum fields do not have types", .{}, &[_]u32{ try astgen.errNoteNode( node, "consider 'union(enum)' here to make it a tagged union", .{}, ), }, ); } // Alignment expressions in enums are caught by the parser. assert(member.ast.align_expr == 0); const name_token = member.ast.name_token; if (mem.eql(u8, tree.tokenSlice(name_token), "_")) { if (nonexhaustive_node != 0) { return astgen.failNodeNotes( member_node, "redundant non-exhaustive enum mark", .{}, &[_]u32{ try astgen.errNoteNode( nonexhaustive_node, "other mark here", .{}, ), }, ); } nonexhaustive_node = member_node; if (member.ast.value_expr != 0) { return astgen.failNode(member.ast.value_expr, "'_' is used to mark an enum as non-exhaustive and cannot be assigned a value", .{}); } continue; } total_fields += 1; if (member.ast.value_expr != 0) { if (container_decl.ast.arg == 0) { return astgen.failNode(member.ast.value_expr, "value assigned to enum tag with inferred tag type", .{}); } values += 1; } } break :blk .{ .total_fields = total_fields, .values = values, .decls = decls, .nonexhaustive_node = nonexhaustive_node, }; }; if (counts.total_fields == 0 and counts.nonexhaustive_node == 0) { // One can construct an enum with no tags, and it functions the same as `noreturn`. But // this is only useful for generic code; when explicitly using `enum {}` syntax, there // must be at least one tag. return astgen.failNode(node, "enum declarations must have at least one tag", .{}); } if (counts.nonexhaustive_node != 0 and container_decl.ast.arg == 0) { return astgen.failNodeNotes( node, "non-exhaustive enum missing integer tag type", .{}, &[_]u32{ try astgen.errNoteNode( counts.nonexhaustive_node, "marked non-exhaustive here", .{}, ), }, ); } // In this case we must generate ZIR code for the tag values, similar to // how structs are handled above. const nonexhaustive = counts.nonexhaustive_node != 0; // The enum_decl instruction introduces a scope in which the decls of the enum // are in scope, so that tag values can refer to decls within the enum itself. var block_scope: GenZir = .{ .parent = scope, .decl_node_index = node, .decl_line = gz.calcLine(node), .astgen = astgen, .force_comptime = true, .in_defer = false, }; defer block_scope.instructions.deinit(gpa); var namespace: Scope.Namespace = .{ .parent = scope, .node = node }; defer namespace.decls.deinit(gpa); try astgen.scanDecls(&namespace, container_decl.ast.members); const arg_inst: Zir.Inst.Ref = if (container_decl.ast.arg != 0) try comptimeExpr(gz, &namespace.base, .{ .ty = .type_type }, container_decl.ast.arg) else .none; var wip_decls: WipDecls = .{}; defer wip_decls.deinit(gpa); var fields_data = ArrayListUnmanaged(u32){}; defer fields_data.deinit(gpa); try fields_data.ensureTotalCapacity(gpa, counts.total_fields + counts.values); // We only need this if there are greater than 32 fields. var bit_bag = ArrayListUnmanaged(u32){}; defer bit_bag.deinit(gpa); var cur_bit_bag: u32 = 0; var field_index: usize = 0; for (container_decl.ast.members) |member_node| { if (member_node == counts.nonexhaustive_node) continue; const member = switch (node_tags[member_node]) { .container_field_init => tree.containerFieldInit(member_node), .container_field_align => tree.containerFieldAlign(member_node), .container_field => tree.containerField(member_node), .fn_decl => { const fn_proto = node_datas[member_node].lhs; const body = node_datas[member_node].rhs; switch (node_tags[fn_proto]) { .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoSimple(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoMulti(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoOne(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProto(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, } }, .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoSimple(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoMulti(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoOne(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProto(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .global_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.globalVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .local_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.localVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .simple_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.simpleVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .aligned_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.alignedVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"comptime" => { astgen.comptimeDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"usingnamespace" => { astgen.usingnamespaceDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .test_decl => { astgen.testDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, }; if (field_index % 32 == 0 and field_index != 0) { try bit_bag.append(gpa, cur_bit_bag); cur_bit_bag = 0; } assert(member.comptime_token == null); assert(member.ast.type_expr == 0); assert(member.ast.align_expr == 0); const field_name = try astgen.identAsString(member.ast.name_token); fields_data.appendAssumeCapacity(field_name); const have_value = member.ast.value_expr != 0; cur_bit_bag = (cur_bit_bag >> 1) | (@as(u32, @boolToInt(have_value)) << 31); if (have_value) { if (arg_inst == .none) { return astgen.failNodeNotes( node, "explicitly valued enum missing integer tag type", .{}, &[_]u32{ try astgen.errNoteNode( member.ast.value_expr, "tag value specified here", .{}, ), }, ); } const tag_value_inst = try expr(&block_scope, &namespace.base, .{ .ty = arg_inst }, member.ast.value_expr); fields_data.appendAssumeCapacity(@enumToInt(tag_value_inst)); } field_index += 1; } { const empty_slot_count = 32 - (field_index % 32); if (empty_slot_count < 32) { cur_bit_bag >>= @intCast(u5, empty_slot_count); } } { const empty_slot_count = WipDecls.fields_per_u32 - (wip_decls.decl_index % WipDecls.fields_per_u32); if (empty_slot_count < WipDecls.fields_per_u32) { wip_decls.cur_bit_bag >>= @intCast(u5, empty_slot_count * WipDecls.bits_per_field); } } const decl_inst = try gz.reserveInstructionIndex(); if (block_scope.instructions.items.len != 0) { _ = try block_scope.addBreak(.break_inline, decl_inst, .void_value); } try gz.setEnum(decl_inst, .{ .src_node = node, .nonexhaustive = nonexhaustive, .tag_type = arg_inst, .body_len = @intCast(u32, block_scope.instructions.items.len), .fields_len = @intCast(u32, field_index), .decls_len = @intCast(u32, wip_decls.decl_index), }); try astgen.extra.ensureUnusedCapacity(gpa, bit_bag.items.len + 1 + fields_data.items.len + block_scope.instructions.items.len + wip_decls.bit_bag.items.len + @boolToInt(wip_decls.decl_index != 0) + wip_decls.payload.items.len); astgen.extra.appendSliceAssumeCapacity(wip_decls.bit_bag.items); // Likely empty. if (wip_decls.decl_index != 0) { astgen.extra.appendAssumeCapacity(wip_decls.cur_bit_bag); } astgen.extra.appendSliceAssumeCapacity(wip_decls.payload.items); astgen.extra.appendSliceAssumeCapacity(block_scope.instructions.items); astgen.extra.appendSliceAssumeCapacity(bit_bag.items); // Likely empty. astgen.extra.appendAssumeCapacity(cur_bit_bag); astgen.extra.appendSliceAssumeCapacity(fields_data.items); return rvalue(gz, rl, indexToRef(decl_inst), node); }, .keyword_opaque => { assert(container_decl.ast.arg == 0); var namespace: Scope.Namespace = .{ .parent = scope, .node = node }; defer namespace.decls.deinit(gpa); try astgen.scanDecls(&namespace, container_decl.ast.members); var wip_decls: WipDecls = .{}; defer wip_decls.deinit(gpa); for (container_decl.ast.members) |member_node| { switch (node_tags[member_node]) { .container_field_init, .container_field_align, .container_field => {}, .fn_decl => { const fn_proto = node_datas[member_node].lhs; const body = node_datas[member_node].rhs; switch (node_tags[fn_proto]) { .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoSimple(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoMulti(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProtoOne(&params, fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, body, tree.fnProto(fn_proto)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, } }, .fn_proto_simple => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoSimple(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_multi => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoMulti(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto_one => { var params: [1]ast.Node.Index = undefined; astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProtoOne(&params, member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .fn_proto => { astgen.fnDecl(gz, &namespace.base, &wip_decls, member_node, 0, tree.fnProto(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .global_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.globalVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .local_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.localVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .simple_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.simpleVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .aligned_var_decl => { astgen.globalVarDecl(gz, &namespace.base, &wip_decls, member_node, tree.alignedVarDecl(member_node)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"comptime" => { astgen.comptimeDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .@"usingnamespace" => { astgen.usingnamespaceDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, .test_decl => { astgen.testDecl(gz, &namespace.base, &wip_decls, member_node) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => {}, }; continue; }, else => unreachable, } } { const empty_slot_count = WipDecls.fields_per_u32 - (wip_decls.decl_index % WipDecls.fields_per_u32); if (empty_slot_count < WipDecls.fields_per_u32) { wip_decls.cur_bit_bag >>= @intCast(u5, empty_slot_count * WipDecls.bits_per_field); } } const tag: Zir.Inst.Tag = switch (gz.anon_name_strategy) { .parent => .opaque_decl, .anon => .opaque_decl_anon, .func => .opaque_decl_func, }; const decl_inst = try gz.addBlock(tag, node); try gz.instructions.append(gpa, decl_inst); try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.OpaqueDecl).Struct.fields.len + wip_decls.bit_bag.items.len + @boolToInt(wip_decls.decl_index != 0) + wip_decls.payload.items.len); const zir_datas = astgen.instructions.items(.data); zir_datas[decl_inst].pl_node.payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.OpaqueDecl{ .decls_len = @intCast(u32, wip_decls.decl_index), }); astgen.extra.appendSliceAssumeCapacity(wip_decls.bit_bag.items); // Likely empty. if (wip_decls.decl_index != 0) { astgen.extra.appendAssumeCapacity(wip_decls.cur_bit_bag); } astgen.extra.appendSliceAssumeCapacity(wip_decls.payload.items); return rvalue(gz, rl, indexToRef(decl_inst), node); }, else => unreachable, } } fn errorSetDecl(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); var field_names: std.ArrayListUnmanaged(u32) = .{}; defer field_names.deinit(gpa); { const error_token = main_tokens[node]; var tok_i = error_token + 2; var field_i: usize = 0; while (true) : (tok_i += 1) { switch (token_tags[tok_i]) { .doc_comment, .comma => {}, .identifier => { const str_index = try astgen.identAsString(tok_i); try field_names.append(gpa, str_index); field_i += 1; }, .r_brace => break, else => unreachable, } } } const result = try gz.addPlNode(.error_set_decl, node, Zir.Inst.ErrorSetDecl{ .fields_len = @intCast(u32, field_names.items.len), }); try astgen.extra.appendSlice(gpa, field_names.items); return rvalue(gz, rl, result, node); } fn tryExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, operand_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const fn_block = astgen.fn_block orelse { return astgen.failNode(node, "'try' outside function scope", .{}); }; if (parent_gz.in_defer) return astgen.failNode(node, "'try' not allowed inside defer expression", .{}); var block_scope = parent_gz.makeSubBlock(scope); block_scope.setBreakResultLoc(rl); defer block_scope.instructions.deinit(astgen.gpa); const operand_rl: ResultLoc = switch (block_scope.break_result_loc) { .ref => .ref, else => .none, }; const err_ops = switch (rl) { // zig fmt: off .ref => [3]Zir.Inst.Tag{ .is_non_err_ptr, .err_union_code_ptr, .err_union_payload_unsafe_ptr }, else => [3]Zir.Inst.Tag{ .is_non_err, .err_union_code, .err_union_payload_unsafe }, // zig fmt: on }; // This could be a pointer or value depending on the `operand_rl` parameter. // We cannot use `block_scope.break_result_loc` because that has the bare // type, whereas this expression has the optional type. Later we make // up for this fact by calling rvalue on the else branch. const operand = try expr(&block_scope, &block_scope.base, operand_rl, operand_node); const cond = try block_scope.addUnNode(err_ops[0], operand, node); const condbr = try block_scope.addCondBr(.condbr, node); const block = try parent_gz.addBlock(.block, node); try parent_gz.instructions.append(astgen.gpa, block); try block_scope.setBlockBody(block); var then_scope = parent_gz.makeSubBlock(scope); defer then_scope.instructions.deinit(astgen.gpa); block_scope.break_count += 1; // This could be a pointer or value depending on `err_ops[2]`. const unwrapped_payload = try then_scope.addUnNode(err_ops[2], operand, node); const then_result = switch (rl) { .ref => unwrapped_payload, else => try rvalue(&then_scope, block_scope.break_result_loc, unwrapped_payload, node), }; var else_scope = parent_gz.makeSubBlock(scope); defer else_scope.instructions.deinit(astgen.gpa); const err_code = try else_scope.addUnNode(err_ops[1], operand, node); try genDefers(&else_scope, &fn_block.base, scope, .{ .both = err_code }); const else_result = try else_scope.addUnNode(.ret_node, err_code, node); return finishThenElseBlock( parent_gz, rl, node, &block_scope, &then_scope, &else_scope, condbr, cond, then_result, else_result, block, block, .@"break", ); } fn orelseCatchExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs: ast.Node.Index, cond_op: Zir.Inst.Tag, unwrap_op: Zir.Inst.Tag, unwrap_code_op: Zir.Inst.Tag, rhs: ast.Node.Index, payload_token: ?ast.TokenIndex, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const tree = astgen.tree; var block_scope = parent_gz.makeSubBlock(scope); block_scope.setBreakResultLoc(rl); defer block_scope.instructions.deinit(astgen.gpa); const operand_rl: ResultLoc = switch (block_scope.break_result_loc) { .ref => .ref, else => .none, }; block_scope.break_count += 1; // This could be a pointer or value depending on the `operand_rl` parameter. // We cannot use `block_scope.break_result_loc` because that has the bare // type, whereas this expression has the optional type. Later we make // up for this fact by calling rvalue on the else branch. const operand = try expr(&block_scope, &block_scope.base, operand_rl, lhs); const cond = try block_scope.addUnNode(cond_op, operand, node); const condbr = try block_scope.addCondBr(.condbr, node); const block = try parent_gz.addBlock(.block, node); try parent_gz.instructions.append(astgen.gpa, block); try block_scope.setBlockBody(block); var then_scope = parent_gz.makeSubBlock(scope); defer then_scope.instructions.deinit(astgen.gpa); // This could be a pointer or value depending on `unwrap_op`. const unwrapped_payload = try then_scope.addUnNode(unwrap_op, operand, node); const then_result = switch (rl) { .ref => unwrapped_payload, else => try rvalue(&then_scope, block_scope.break_result_loc, unwrapped_payload, node), }; var else_scope = parent_gz.makeSubBlock(scope); defer else_scope.instructions.deinit(astgen.gpa); var err_val_scope: Scope.LocalVal = undefined; const else_sub_scope = blk: { const payload = payload_token orelse break :blk &else_scope.base; if (mem.eql(u8, tree.tokenSlice(payload), "_")) { return astgen.failTok(payload, "discard of error capture; omit it instead", .{}); } const err_name = try astgen.identAsString(payload); err_val_scope = .{ .parent = &else_scope.base, .gen_zir = &else_scope, .name = err_name, .inst = try else_scope.addUnNode(unwrap_code_op, operand, node), .token_src = payload, .id_cat = .@"capture", }; break :blk &err_val_scope.base; }; block_scope.break_count += 1; const else_result = try expr(&else_scope, else_sub_scope, block_scope.break_result_loc, rhs); try checkUsed(parent_gz, &else_scope.base, else_sub_scope); // We hold off on the break instructions as well as copying the then/else // instructions into place until we know whether to keep store_to_block_ptr // instructions or not. return finishThenElseBlock( parent_gz, rl, node, &block_scope, &then_scope, &else_scope, condbr, cond, then_result, else_result, block, block, .@"break", ); } fn finishThenElseBlock( parent_gz: *GenZir, rl: ResultLoc, node: ast.Node.Index, block_scope: *GenZir, then_scope: *GenZir, else_scope: *GenZir, condbr: Zir.Inst.Index, cond: Zir.Inst.Ref, then_result: Zir.Inst.Ref, else_result: Zir.Inst.Ref, main_block: Zir.Inst.Index, then_break_block: Zir.Inst.Index, break_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { // We now have enough information to decide whether the result instruction should // be communicated via result location pointer or break instructions. const strat = rl.strategy(block_scope); switch (strat.tag) { .break_void => { if (!then_scope.endsWithNoReturn()) { _ = try then_scope.addBreak(break_tag, then_break_block, .void_value); } if (!else_scope.endsWithNoReturn()) { _ = try else_scope.addBreak(break_tag, main_block, .void_value); } assert(!strat.elide_store_to_block_ptr_instructions); try setCondBrPayload(condbr, cond, then_scope, else_scope); return indexToRef(main_block); }, .break_operand => { if (!then_scope.endsWithNoReturn()) { _ = try then_scope.addBreak(break_tag, then_break_block, then_result); } if (else_result != .none) { if (!else_scope.endsWithNoReturn()) { _ = try else_scope.addBreak(break_tag, main_block, else_result); } } else { _ = try else_scope.addBreak(break_tag, main_block, .void_value); } if (strat.elide_store_to_block_ptr_instructions) { try setCondBrPayloadElideBlockStorePtr(condbr, cond, then_scope, else_scope, block_scope.rl_ptr); } else { try setCondBrPayload(condbr, cond, then_scope, else_scope); } const block_ref = indexToRef(main_block); switch (rl) { .ref => return block_ref, else => return rvalue(parent_gz, rl, block_ref, node), } }, } } /// Return whether the identifier names of two tokens are equal. Resolves @"" /// tokens without allocating. /// OK in theory it could do it without allocating. This implementation /// allocates when the @"" form is used. fn tokenIdentEql(astgen: *AstGen, token1: ast.TokenIndex, token2: ast.TokenIndex) !bool { const ident_name_1 = try astgen.identifierTokenString(token1); const ident_name_2 = try astgen.identifierTokenString(token2); return mem.eql(u8, ident_name_1, ident_name_2); } fn fieldAccess( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const node_datas = tree.nodes.items(.data); const object_node = node_datas[node].lhs; const dot_token = main_tokens[node]; const field_ident = dot_token + 1; const str_index = try astgen.identAsString(field_ident); switch (rl) { .ref => return gz.addPlNode(.field_ptr, node, Zir.Inst.Field{ .lhs = try expr(gz, scope, .ref, object_node), .field_name_start = str_index, }), else => return rvalue(gz, rl, try gz.addPlNode(.field_val, node, Zir.Inst.Field{ .lhs = try expr(gz, scope, .none_or_ref, object_node), .field_name_start = str_index, }), node), } } fn arrayAccess( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); switch (rl) { .ref => return gz.addBin( .elem_ptr, try expr(gz, scope, .ref, node_datas[node].lhs), try expr(gz, scope, .{ .ty = .usize_type }, node_datas[node].rhs), ), else => return rvalue(gz, rl, try gz.addBin( .elem_val, try expr(gz, scope, .none_or_ref, node_datas[node].lhs), try expr(gz, scope, .{ .ty = .usize_type }, node_datas[node].rhs), ), node), } } fn simpleBinOp( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const result = try gz.addPlNode(op_inst_tag, node, Zir.Inst.Bin{ .lhs = try expr(gz, scope, .none, node_datas[node].lhs), .rhs = try expr(gz, scope, .none, node_datas[node].rhs), }); return rvalue(gz, rl, result, node); } fn simpleStrTok( gz: *GenZir, rl: ResultLoc, ident_token: ast.TokenIndex, node: ast.Node.Index, op_inst_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const str_index = try astgen.identAsString(ident_token); const result = try gz.addStrTok(op_inst_tag, str_index, ident_token); return rvalue(gz, rl, result, node); } fn boolBinOp( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, zir_tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const lhs = try expr(gz, scope, bool_rl, node_datas[node].lhs); const bool_br = try gz.addBoolBr(zir_tag, lhs); var rhs_scope = gz.makeSubBlock(scope); defer rhs_scope.instructions.deinit(gz.astgen.gpa); const rhs = try expr(&rhs_scope, &rhs_scope.base, bool_rl, node_datas[node].rhs); if (!gz.refIsNoReturn(rhs)) { _ = try rhs_scope.addBreak(.break_inline, bool_br, rhs); } try rhs_scope.setBoolBrBody(bool_br); const block_ref = indexToRef(bool_br); return rvalue(gz, rl, block_ref, node); } fn ifExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, if_full: ast.full.If, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); var block_scope = parent_gz.makeSubBlock(scope); block_scope.setBreakResultLoc(rl); defer block_scope.instructions.deinit(astgen.gpa); const payload_is_ref = if (if_full.payload_token) |payload_token| token_tags[payload_token] == .asterisk else false; const cond: struct { inst: Zir.Inst.Ref, bool_bit: Zir.Inst.Ref, } = c: { if (if_full.error_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const err_union = try expr(&block_scope, &block_scope.base, cond_rl, if_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_err_ptr else .is_non_err; break :c .{ .inst = err_union, .bool_bit = try block_scope.addUnNode(tag, err_union, node), }; } else if (if_full.payload_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const optional = try expr(&block_scope, &block_scope.base, cond_rl, if_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null; break :c .{ .inst = optional, .bool_bit = try block_scope.addUnNode(tag, optional, node), }; } else { const cond = try expr(&block_scope, &block_scope.base, bool_rl, if_full.ast.cond_expr); break :c .{ .inst = cond, .bool_bit = cond, }; } }; const condbr = try block_scope.addCondBr(.condbr, node); const block = try parent_gz.addBlock(.block, node); try parent_gz.instructions.append(astgen.gpa, block); try block_scope.setBlockBody(block); var then_scope = parent_gz.makeSubBlock(scope); defer then_scope.instructions.deinit(astgen.gpa); var payload_val_scope: Scope.LocalVal = undefined; const then_sub_scope = s: { if (if_full.error_token != null) { if (if_full.payload_token) |payload_token| { const tag: Zir.Inst.Tag = if (payload_is_ref) .err_union_payload_unsafe_ptr else .err_union_payload_unsafe; const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); const token_name_index = payload_token + @boolToInt(payload_is_ref); const ident_name = try astgen.identAsString(token_name_index); const token_name_str = tree.tokenSlice(token_name_index); if (mem.eql(u8, "_", token_name_str)) break :s &then_scope.base; try astgen.detectLocalShadowing(&then_scope.base, ident_name, token_name_index, token_name_str); payload_val_scope = .{ .parent = &then_scope.base, .gen_zir = &then_scope, .name = ident_name, .inst = payload_inst, .token_src = payload_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &then_scope.base; } } else if (if_full.payload_token) |payload_token| { const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; const tag: Zir.Inst.Tag = if (payload_is_ref) .optional_payload_unsafe_ptr else .optional_payload_unsafe; const ident_bytes = tree.tokenSlice(ident_token); if (mem.eql(u8, "_", ident_bytes)) break :s &then_scope.base; const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(ident_token); try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes); payload_val_scope = .{ .parent = &then_scope.base, .gen_zir = &then_scope, .name = ident_name, .inst = payload_inst, .token_src = ident_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &then_scope.base; } }; block_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, block_scope.break_result_loc, if_full.ast.then_expr); try checkUsed(parent_gz, &then_scope.base, then_sub_scope); // We hold off on the break instructions as well as copying the then/else // instructions into place until we know whether to keep store_to_block_ptr // instructions or not. var else_scope = parent_gz.makeSubBlock(scope); defer else_scope.instructions.deinit(astgen.gpa); const else_node = if_full.ast.else_expr; const else_info: struct { src: ast.Node.Index, result: Zir.Inst.Ref, } = if (else_node != 0) blk: { block_scope.break_count += 1; const sub_scope = s: { if (if_full.error_token) |error_token| { const tag: Zir.Inst.Tag = if (payload_is_ref) .err_union_code_ptr else .err_union_code; const payload_inst = try else_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(error_token); const error_token_str = tree.tokenSlice(error_token); if (mem.eql(u8, "_", error_token_str)) break :s &else_scope.base; try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, error_token_str); payload_val_scope = .{ .parent = &else_scope.base, .gen_zir = &else_scope, .name = ident_name, .inst = payload_inst, .token_src = error_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &else_scope.base; } }; const e = try expr(&else_scope, sub_scope, block_scope.break_result_loc, else_node); try checkUsed(parent_gz, &else_scope.base, sub_scope); break :blk .{ .src = else_node, .result = e, }; } else .{ .src = if_full.ast.then_expr, .result = .none, }; return finishThenElseBlock( parent_gz, rl, node, &block_scope, &then_scope, &else_scope, condbr, cond.bool_bit, then_result, else_info.result, block, block, .@"break", ); } fn setCondBrPayload( condbr: Zir.Inst.Index, cond: Zir.Inst.Ref, then_scope: *GenZir, else_scope: *GenZir, ) !void { const astgen = then_scope.astgen; try astgen.extra.ensureUnusedCapacity(astgen.gpa, @typeInfo(Zir.Inst.CondBr).Struct.fields.len + then_scope.instructions.items.len + else_scope.instructions.items.len); const zir_datas = astgen.instructions.items(.data); zir_datas[condbr].pl_node.payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.CondBr{ .condition = cond, .then_body_len = @intCast(u32, then_scope.instructions.items.len), .else_body_len = @intCast(u32, else_scope.instructions.items.len), }); astgen.extra.appendSliceAssumeCapacity(then_scope.instructions.items); astgen.extra.appendSliceAssumeCapacity(else_scope.instructions.items); } fn setCondBrPayloadElideBlockStorePtr( condbr: Zir.Inst.Index, cond: Zir.Inst.Ref, then_scope: *GenZir, else_scope: *GenZir, block_ptr: Zir.Inst.Ref, ) !void { const astgen = then_scope.astgen; try astgen.extra.ensureUnusedCapacity(astgen.gpa, @typeInfo(Zir.Inst.CondBr).Struct.fields.len + then_scope.instructions.items.len + else_scope.instructions.items.len); const zir_tags = astgen.instructions.items(.tag); const zir_datas = astgen.instructions.items(.data); const condbr_pl = astgen.addExtraAssumeCapacity(Zir.Inst.CondBr{ .condition = cond, .then_body_len = @intCast(u32, then_scope.instructions.items.len), .else_body_len = @intCast(u32, else_scope.instructions.items.len), }); zir_datas[condbr].pl_node.payload_index = condbr_pl; const then_body_len_index = condbr_pl + 1; const else_body_len_index = condbr_pl + 2; for (then_scope.instructions.items) |src_inst| { if (zir_tags[src_inst] == .store_to_block_ptr) { if (zir_datas[src_inst].bin.lhs == block_ptr) { astgen.extra.items[then_body_len_index] -= 1; continue; } } astgen.extra.appendAssumeCapacity(src_inst); } for (else_scope.instructions.items) |src_inst| { if (zir_tags[src_inst] == .store_to_block_ptr) { if (zir_datas[src_inst].bin.lhs == block_ptr) { astgen.extra.items[else_body_len_index] -= 1; continue; } } astgen.extra.appendAssumeCapacity(src_inst); } } fn whileExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, while_full: ast.full.While, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); if (while_full.label_token) |label_token| { try astgen.checkLabelRedefinition(scope, label_token); } const is_inline = parent_gz.force_comptime or while_full.inline_token != null; const loop_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .loop; const loop_block = try parent_gz.addBlock(loop_tag, node); try parent_gz.instructions.append(astgen.gpa, loop_block); var loop_scope = parent_gz.makeSubBlock(scope); loop_scope.setBreakResultLoc(rl); defer loop_scope.instructions.deinit(astgen.gpa); defer loop_scope.labeled_breaks.deinit(astgen.gpa); defer loop_scope.labeled_store_to_block_ptr_list.deinit(astgen.gpa); var continue_scope = parent_gz.makeSubBlock(&loop_scope.base); defer continue_scope.instructions.deinit(astgen.gpa); const payload_is_ref = if (while_full.payload_token) |payload_token| token_tags[payload_token] == .asterisk else false; const cond: struct { inst: Zir.Inst.Ref, bool_bit: Zir.Inst.Ref, } = c: { if (while_full.error_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const err_union = try expr(&continue_scope, &continue_scope.base, cond_rl, while_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_err_ptr else .is_non_err; break :c .{ .inst = err_union, .bool_bit = try continue_scope.addUnNode(tag, err_union, node), }; } else if (while_full.payload_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const optional = try expr(&continue_scope, &continue_scope.base, cond_rl, while_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null; break :c .{ .inst = optional, .bool_bit = try continue_scope.addUnNode(tag, optional, node), }; } else { const cond = try expr(&continue_scope, &continue_scope.base, bool_rl, while_full.ast.cond_expr); break :c .{ .inst = cond, .bool_bit = cond, }; } }; const condbr_tag: Zir.Inst.Tag = if (is_inline) .condbr_inline else .condbr; const condbr = try continue_scope.addCondBr(condbr_tag, node); const block_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .block; const cond_block = try loop_scope.addBlock(block_tag, node); try loop_scope.instructions.append(astgen.gpa, cond_block); try continue_scope.setBlockBody(cond_block); var then_scope = parent_gz.makeSubBlock(&continue_scope.base); defer then_scope.instructions.deinit(astgen.gpa); var payload_val_scope: Scope.LocalVal = undefined; const then_sub_scope = s: { if (while_full.error_token != null) { if (while_full.payload_token) |payload_token| { const tag: Zir.Inst.Tag = if (payload_is_ref) .err_union_payload_unsafe_ptr else .err_union_payload_unsafe; const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; const ident_bytes = tree.tokenSlice(ident_token); if (mem.eql(u8, "_", ident_bytes)) break :s &then_scope.base; const payload_name_loc = payload_token + @boolToInt(payload_is_ref); const ident_name = try astgen.identAsString(payload_name_loc); try astgen.detectLocalShadowing(&then_scope.base, ident_name, payload_name_loc, ident_bytes); payload_val_scope = .{ .parent = &then_scope.base, .gen_zir = &then_scope, .name = ident_name, .inst = payload_inst, .token_src = payload_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &then_scope.base; } } else if (while_full.payload_token) |payload_token| { const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; const tag: Zir.Inst.Tag = if (payload_is_ref) .optional_payload_unsafe_ptr else .optional_payload_unsafe; const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(ident_token); const ident_bytes = tree.tokenSlice(ident_token); if (mem.eql(u8, "_", ident_bytes)) break :s &then_scope.base; try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes); payload_val_scope = .{ .parent = &then_scope.base, .gen_zir = &then_scope, .name = ident_name, .inst = payload_inst, .token_src = ident_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &then_scope.base; } }; // This code could be improved to avoid emitting the continue expr when there // are no jumps to it. This happens when the last statement of a while body is noreturn // and there are no `continue` statements. // Tracking issue: https://github.com/ziglang/zig/issues/9185 if (while_full.ast.cont_expr != 0) { _ = try expr(&loop_scope, then_sub_scope, .{ .ty = .void_type }, while_full.ast.cont_expr); } const repeat_tag: Zir.Inst.Tag = if (is_inline) .repeat_inline else .repeat; _ = try loop_scope.addNode(repeat_tag, node); try loop_scope.setBlockBody(loop_block); loop_scope.break_block = loop_block; loop_scope.continue_block = cond_block; if (while_full.label_token) |label_token| { loop_scope.label = @as(?GenZir.Label, GenZir.Label{ .token = label_token, .block_inst = loop_block, }); } loop_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, loop_scope.break_result_loc, while_full.ast.then_expr); try checkUsed(parent_gz, &then_scope.base, then_sub_scope); var else_scope = parent_gz.makeSubBlock(&continue_scope.base); defer else_scope.instructions.deinit(astgen.gpa); const else_node = while_full.ast.else_expr; const else_info: struct { src: ast.Node.Index, result: Zir.Inst.Ref, } = if (else_node != 0) blk: { loop_scope.break_count += 1; const sub_scope = s: { if (while_full.error_token) |error_token| { const tag: Zir.Inst.Tag = if (payload_is_ref) .err_union_code_ptr else .err_union_code; const payload_inst = try else_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(error_token); const ident_bytes = tree.tokenSlice(error_token); if (mem.eql(u8, ident_bytes, "_")) break :s &else_scope.base; try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, ident_bytes); payload_val_scope = .{ .parent = &else_scope.base, .gen_zir = &else_scope, .name = ident_name, .inst = payload_inst, .token_src = error_token, .id_cat = .@"capture", }; break :s &payload_val_scope.base; } else { break :s &else_scope.base; } }; const e = try expr(&else_scope, sub_scope, loop_scope.break_result_loc, else_node); try checkUsed(parent_gz, &else_scope.base, sub_scope); break :blk .{ .src = else_node, .result = e, }; } else .{ .src = while_full.ast.then_expr, .result = .none, }; if (loop_scope.label) |some| { if (!some.used) { return astgen.failTok(some.token, "unused while loop label", .{}); } } const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break"; return finishThenElseBlock( parent_gz, rl, node, &loop_scope, &then_scope, &else_scope, condbr, cond.bool_bit, then_result, else_info.result, loop_block, cond_block, break_tag, ); } fn forExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, for_full: ast.full.While, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; if (for_full.label_token) |label_token| { try astgen.checkLabelRedefinition(scope, label_token); } // Set up variables and constants. const is_inline = parent_gz.force_comptime or for_full.inline_token != null; const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); const payload_is_ref = if (for_full.payload_token) |payload_token| token_tags[payload_token] == .asterisk else false; const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const array_ptr = try expr(parent_gz, scope, cond_rl, for_full.ast.cond_expr); const len = try parent_gz.addUnNode(.indexable_ptr_len, array_ptr, for_full.ast.cond_expr); const index_ptr = blk: { const index_ptr = try parent_gz.addUnNode(.alloc, .usize_type, node); // initialize to zero _ = try parent_gz.addBin(.store, index_ptr, .zero_usize); break :blk index_ptr; }; const loop_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .loop; const loop_block = try parent_gz.addBlock(loop_tag, node); try parent_gz.instructions.append(astgen.gpa, loop_block); var loop_scope = parent_gz.makeSubBlock(scope); loop_scope.setBreakResultLoc(rl); defer loop_scope.instructions.deinit(astgen.gpa); defer loop_scope.labeled_breaks.deinit(astgen.gpa); defer loop_scope.labeled_store_to_block_ptr_list.deinit(astgen.gpa); var cond_scope = parent_gz.makeSubBlock(&loop_scope.base); defer cond_scope.instructions.deinit(astgen.gpa); // check condition i < array_expr.len const index = try cond_scope.addUnNode(.load, index_ptr, for_full.ast.cond_expr); const cond = try cond_scope.addPlNode(.cmp_lt, for_full.ast.cond_expr, Zir.Inst.Bin{ .lhs = index, .rhs = len, }); const condbr_tag: Zir.Inst.Tag = if (is_inline) .condbr_inline else .condbr; const condbr = try cond_scope.addCondBr(condbr_tag, node); const block_tag: Zir.Inst.Tag = if (is_inline) .block_inline else .block; const cond_block = try loop_scope.addBlock(block_tag, node); try loop_scope.instructions.append(astgen.gpa, cond_block); try cond_scope.setBlockBody(cond_block); // Increment the index variable. const index_2 = try loop_scope.addUnNode(.load, index_ptr, for_full.ast.cond_expr); const index_plus_one = try loop_scope.addPlNode(.add, node, Zir.Inst.Bin{ .lhs = index_2, .rhs = .one_usize, }); _ = try loop_scope.addBin(.store, index_ptr, index_plus_one); const repeat_tag: Zir.Inst.Tag = if (is_inline) .repeat_inline else .repeat; _ = try loop_scope.addNode(repeat_tag, node); try loop_scope.setBlockBody(loop_block); loop_scope.break_block = loop_block; loop_scope.continue_block = cond_block; if (for_full.label_token) |label_token| { loop_scope.label = @as(?GenZir.Label, GenZir.Label{ .token = label_token, .block_inst = loop_block, }); } var then_scope = parent_gz.makeSubBlock(&cond_scope.base); defer then_scope.instructions.deinit(astgen.gpa); var payload_val_scope: Scope.LocalVal = undefined; var index_scope: Scope.LocalPtr = undefined; const then_sub_scope = blk: { const payload_token = for_full.payload_token.?; const ident = if (token_tags[payload_token] == .asterisk) payload_token + 1 else payload_token; const is_ptr = ident != payload_token; const value_name = tree.tokenSlice(ident); var payload_sub_scope: *Scope = undefined; if (!mem.eql(u8, value_name, "_")) { const name_str_index = try astgen.identAsString(ident); const tag: Zir.Inst.Tag = if (is_ptr) .elem_ptr else .elem_val; const payload_inst = try then_scope.addBin(tag, array_ptr, index); try astgen.detectLocalShadowing(&then_scope.base, name_str_index, ident, value_name); payload_val_scope = .{ .parent = &then_scope.base, .gen_zir = &then_scope, .name = name_str_index, .inst = payload_inst, .token_src = ident, .id_cat = .@"capture", }; payload_sub_scope = &payload_val_scope.base; } else if (is_ptr) { return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{}); } else { payload_sub_scope = &then_scope.base; } const index_token = if (token_tags[ident + 1] == .comma) ident + 2 else break :blk payload_sub_scope; const token_bytes = tree.tokenSlice(index_token); if (mem.eql(u8, token_bytes, "_")) { return astgen.failTok(index_token, "discard of index capture; omit it instead", .{}); } const index_name = try astgen.identAsString(index_token); try astgen.detectLocalShadowing(payload_sub_scope, index_name, index_token, token_bytes); index_scope = .{ .parent = payload_sub_scope, .gen_zir = &then_scope, .name = index_name, .ptr = index_ptr, .token_src = index_token, .maybe_comptime = is_inline, .id_cat = .@"loop index capture", }; break :blk &index_scope.base; }; loop_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, loop_scope.break_result_loc, for_full.ast.then_expr); try checkUsed(parent_gz, &then_scope.base, then_sub_scope); var else_scope = parent_gz.makeSubBlock(&cond_scope.base); defer else_scope.instructions.deinit(astgen.gpa); const else_node = for_full.ast.else_expr; const else_info: struct { src: ast.Node.Index, result: Zir.Inst.Ref, } = if (else_node != 0) blk: { loop_scope.break_count += 1; const sub_scope = &else_scope.base; break :blk .{ .src = else_node, .result = try expr(&else_scope, sub_scope, loop_scope.break_result_loc, else_node), }; } else .{ .src = for_full.ast.then_expr, .result = .none, }; if (loop_scope.label) |some| { if (!some.used) { return astgen.failTok(some.token, "unused for loop label", .{}); } } const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break"; return finishThenElseBlock( parent_gz, rl, node, &loop_scope, &then_scope, &else_scope, condbr, cond, then_result, else_info.result, loop_block, cond_block, break_tag, ); } fn switchExpr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, switch_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); const operand_node = node_datas[switch_node].lhs; const extra = tree.extraData(node_datas[switch_node].rhs, ast.Node.SubRange); const case_nodes = tree.extra_data[extra.start..extra.end]; // We perform two passes over the AST. This first pass is to collect information // for the following variables, make note of the special prong AST node index, // and bail out with a compile error if there are multiple special prongs present. var any_payload_is_ref = false; var scalar_cases_len: u32 = 0; var multi_cases_len: u32 = 0; var special_prong: Zir.SpecialProng = .none; var special_node: ast.Node.Index = 0; var else_src: ?ast.TokenIndex = null; var underscore_src: ?ast.TokenIndex = null; for (case_nodes) |case_node| { const case = switch (node_tags[case_node]) { .switch_case_one => tree.switchCaseOne(case_node), .switch_case => tree.switchCase(case_node), else => unreachable, }; if (case.payload_token) |payload_token| { if (token_tags[payload_token] == .asterisk) { any_payload_is_ref = true; } } // Check for else/`_` prong. if (case.ast.values.len == 0) { const case_src = case.ast.arrow_token - 1; if (else_src) |src| { return astgen.failTokNotes( case_src, "multiple else prongs in switch expression", .{}, &[_]u32{ try astgen.errNoteTok( src, "previous else prong here", .{}, ), }, ); } else if (underscore_src) |some_underscore| { return astgen.failNodeNotes( switch_node, "else and '_' prong in switch expression", .{}, &[_]u32{ try astgen.errNoteTok( case_src, "else prong here", .{}, ), try astgen.errNoteTok( some_underscore, "'_' prong here", .{}, ), }, ); } special_node = case_node; special_prong = .@"else"; else_src = case_src; continue; } else if (case.ast.values.len == 1 and node_tags[case.ast.values[0]] == .identifier and mem.eql(u8, tree.tokenSlice(main_tokens[case.ast.values[0]]), "_")) { const case_src = case.ast.arrow_token - 1; if (underscore_src) |src| { return astgen.failTokNotes( case_src, "multiple '_' prongs in switch expression", .{}, &[_]u32{ try astgen.errNoteTok( src, "previous '_' prong here", .{}, ), }, ); } else if (else_src) |some_else| { return astgen.failNodeNotes( switch_node, "else and '_' prong in switch expression", .{}, &[_]u32{ try astgen.errNoteTok( some_else, "else prong here", .{}, ), try astgen.errNoteTok( case_src, "'_' prong here", .{}, ), }, ); } special_node = case_node; special_prong = .under; underscore_src = case_src; continue; } if (case.ast.values.len == 1 and node_tags[case.ast.values[0]] != .switch_range) { scalar_cases_len += 1; } else { multi_cases_len += 1; } } const operand_rl: ResultLoc = if (any_payload_is_ref) .ref else .none; const operand = try expr(parent_gz, scope, operand_rl, operand_node); // We need the type of the operand to use as the result location for all the prong items. const typeof_tag: Zir.Inst.Tag = if (any_payload_is_ref) .typeof_elem else .typeof; const operand_ty_inst = try parent_gz.addUnNode(typeof_tag, operand, operand_node); const item_rl: ResultLoc = .{ .ty = operand_ty_inst }; // Contains the data that goes into the `extra` array for the SwitchBlock/SwitchBlockMulti. // This is the header as well as the optional else prong body, as well as all the // scalar cases. // At the end we will memcpy this into place. var scalar_cases_payload = ArrayListUnmanaged(u32){}; defer scalar_cases_payload.deinit(gpa); // Same deal, but this is only the `extra` data for the multi cases. var multi_cases_payload = ArrayListUnmanaged(u32){}; defer multi_cases_payload.deinit(gpa); var block_scope = parent_gz.makeSubBlock(scope); block_scope.setBreakResultLoc(rl); defer block_scope.instructions.deinit(gpa); // This gets added to the parent block later, after the item expressions. const switch_block = try parent_gz.addBlock(undefined, switch_node); // We re-use this same scope for all cases, including the special prong, if any. var case_scope = parent_gz.makeSubBlock(&block_scope.base); defer case_scope.instructions.deinit(gpa); // Do the else/`_` first because it goes first in the payload. var capture_val_scope: Scope.LocalVal = undefined; if (special_node != 0) { const case = switch (node_tags[special_node]) { .switch_case_one => tree.switchCaseOne(special_node), .switch_case => tree.switchCase(special_node), else => unreachable, }; const sub_scope = blk: { const payload_token = case.payload_token orelse break :blk &case_scope.base; const ident = if (token_tags[payload_token] == .asterisk) payload_token + 1 else payload_token; const is_ptr = ident != payload_token; if (mem.eql(u8, tree.tokenSlice(ident), "_")) { if (is_ptr) { return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{}); } break :blk &case_scope.base; } const capture_tag: Zir.Inst.Tag = if (is_ptr) .switch_capture_else_ref else .switch_capture_else; const capture = try case_scope.add(.{ .tag = capture_tag, .data = .{ .switch_capture = .{ .switch_inst = switch_block, .prong_index = undefined, } }, }); const capture_name = try astgen.identAsString(payload_token); capture_val_scope = .{ .parent = &case_scope.base, .gen_zir = &case_scope, .name = capture_name, .inst = capture, .token_src = payload_token, .id_cat = .@"capture", }; break :blk &capture_val_scope.base; }; const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); } // Documentation for this: `Zir.Inst.SwitchBlock` and `Zir.Inst.SwitchBlockMulti`. try scalar_cases_payload.ensureUnusedCapacity(gpa, case_scope.instructions.items.len + 3 + // operand, scalar_cases_len, else body len @boolToInt(multi_cases_len != 0)); scalar_cases_payload.appendAssumeCapacity(@enumToInt(operand)); scalar_cases_payload.appendAssumeCapacity(scalar_cases_len); if (multi_cases_len != 0) { scalar_cases_payload.appendAssumeCapacity(multi_cases_len); } scalar_cases_payload.appendAssumeCapacity(@intCast(u32, case_scope.instructions.items.len)); scalar_cases_payload.appendSliceAssumeCapacity(case_scope.instructions.items); } else { // Documentation for this: `Zir.Inst.SwitchBlock` and `Zir.Inst.SwitchBlockMulti`. try scalar_cases_payload.ensureUnusedCapacity( gpa, @as(usize, 2) + // operand, scalar_cases_len @boolToInt(multi_cases_len != 0), ); scalar_cases_payload.appendAssumeCapacity(@enumToInt(operand)); scalar_cases_payload.appendAssumeCapacity(scalar_cases_len); if (multi_cases_len != 0) { scalar_cases_payload.appendAssumeCapacity(multi_cases_len); } } // In this pass we generate all the item and prong expressions except the special case. var multi_case_index: u32 = 0; var scalar_case_index: u32 = 0; for (case_nodes) |case_node| { if (case_node == special_node) continue; const case = switch (node_tags[case_node]) { .switch_case_one => tree.switchCaseOne(case_node), .switch_case => tree.switchCase(case_node), else => unreachable, }; // Reset the scope. case_scope.instructions.shrinkRetainingCapacity(0); const is_multi_case = case.ast.values.len != 1 or node_tags[case.ast.values[0]] == .switch_range; const sub_scope = blk: { const payload_token = case.payload_token orelse break :blk &case_scope.base; const ident = if (token_tags[payload_token] == .asterisk) payload_token + 1 else payload_token; const is_ptr = ident != payload_token; if (mem.eql(u8, tree.tokenSlice(ident), "_")) { if (is_ptr) { return astgen.failTok(payload_token, "pointer modifier invalid on discard", .{}); } break :blk &case_scope.base; } const is_multi_case_bits: u2 = @boolToInt(is_multi_case); const is_ptr_bits: u2 = @boolToInt(is_ptr); const capture_tag: Zir.Inst.Tag = switch ((is_multi_case_bits << 1) | is_ptr_bits) { 0b00 => .switch_capture, 0b01 => .switch_capture_ref, 0b10 => .switch_capture_multi, 0b11 => .switch_capture_multi_ref, }; const capture_index = if (is_multi_case) ci: { multi_case_index += 1; break :ci multi_case_index - 1; } else ci: { scalar_case_index += 1; break :ci scalar_case_index - 1; }; const capture = try case_scope.add(.{ .tag = capture_tag, .data = .{ .switch_capture = .{ .switch_inst = switch_block, .prong_index = capture_index, } }, }); const capture_name = try astgen.identAsString(ident); capture_val_scope = .{ .parent = &case_scope.base, .gen_zir = &case_scope, .name = capture_name, .inst = capture, .token_src = payload_token, .id_cat = .@"capture", }; break :blk &capture_val_scope.base; }; if (is_multi_case) { // items_len, ranges_len, body_len const header_index = multi_cases_payload.items.len; try multi_cases_payload.resize(gpa, multi_cases_payload.items.len + 3); // items var items_len: u32 = 0; for (case.ast.values) |item_node| { if (node_tags[item_node] == .switch_range) continue; items_len += 1; const item_inst = try comptimeExpr(parent_gz, scope, item_rl, item_node); try multi_cases_payload.append(gpa, @enumToInt(item_inst)); } // ranges var ranges_len: u32 = 0; for (case.ast.values) |range| { if (node_tags[range] != .switch_range) continue; ranges_len += 1; const first = try comptimeExpr(parent_gz, scope, item_rl, node_datas[range].lhs); const last = try comptimeExpr(parent_gz, scope, item_rl, node_datas[range].rhs); try multi_cases_payload.appendSlice(gpa, &[_]u32{ @enumToInt(first), @enumToInt(last), }); } const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); } multi_cases_payload.items[header_index + 0] = items_len; multi_cases_payload.items[header_index + 1] = ranges_len; multi_cases_payload.items[header_index + 2] = @intCast(u32, case_scope.instructions.items.len); try multi_cases_payload.appendSlice(gpa, case_scope.instructions.items); } else { const item_node = case.ast.values[0]; const item_inst = try comptimeExpr(parent_gz, scope, item_rl, item_node); const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); } try scalar_cases_payload.ensureUnusedCapacity(gpa, 2 + case_scope.instructions.items.len); scalar_cases_payload.appendAssumeCapacity(@enumToInt(item_inst)); scalar_cases_payload.appendAssumeCapacity(@intCast(u32, case_scope.instructions.items.len)); scalar_cases_payload.appendSliceAssumeCapacity(case_scope.instructions.items); } } // Now that the item expressions are generated we can add this. try parent_gz.instructions.append(gpa, switch_block); const ref_bit: u4 = @boolToInt(any_payload_is_ref); const multi_bit: u4 = @boolToInt(multi_cases_len != 0); const special_prong_bits: u4 = @enumToInt(special_prong); comptime { assert(@enumToInt(Zir.SpecialProng.none) == 0b00); assert(@enumToInt(Zir.SpecialProng.@"else") == 0b01); assert(@enumToInt(Zir.SpecialProng.under) == 0b10); } const zir_tags = astgen.instructions.items(.tag); zir_tags[switch_block] = switch ((ref_bit << 3) | (special_prong_bits << 1) | multi_bit) { 0b0_00_0 => .switch_block, 0b0_00_1 => .switch_block_multi, 0b0_01_0 => .switch_block_else, 0b0_01_1 => .switch_block_else_multi, 0b0_10_0 => .switch_block_under, 0b0_10_1 => .switch_block_under_multi, 0b1_00_0 => .switch_block_ref, 0b1_00_1 => .switch_block_ref_multi, 0b1_01_0 => .switch_block_ref_else, 0b1_01_1 => .switch_block_ref_else_multi, 0b1_10_0 => .switch_block_ref_under, 0b1_10_1 => .switch_block_ref_under_multi, else => unreachable, }; const payload_index = astgen.extra.items.len; const zir_datas = astgen.instructions.items(.data); zir_datas[switch_block].pl_node.payload_index = @intCast(u32, payload_index); try astgen.extra.ensureUnusedCapacity(gpa, scalar_cases_payload.items.len + multi_cases_payload.items.len); const strat = rl.strategy(&block_scope); switch (strat.tag) { .break_operand => { // Switch expressions return `true` for `nodeMayNeedMemoryLocation` thus // `elide_store_to_block_ptr_instructions` will either be true, // or all prongs are noreturn. if (!strat.elide_store_to_block_ptr_instructions) { astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items); astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items); return indexToRef(switch_block); } // There will necessarily be a store_to_block_ptr for // all prongs, except for prongs that ended with a noreturn instruction. // Elide all the `store_to_block_ptr` instructions. // The break instructions need to have their operands coerced if the // switch's result location is a `ty`. In this case we overwrite the // `store_to_block_ptr` instruction with an `as` instruction and repurpose // it as the break operand. var extra_index: usize = 0; extra_index += 2; extra_index += @boolToInt(multi_cases_len != 0); if (special_prong != .none) special_prong: { const body_len_index = extra_index; const body_len = scalar_cases_payload.items[extra_index]; extra_index += 1; if (body_len < 2) { extra_index += body_len; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[0..extra_index]); break :special_prong; } extra_index += body_len - 2; const store_inst = scalar_cases_payload.items[extra_index]; if (zir_tags[store_inst] != .store_to_block_ptr or zir_datas[store_inst].bin.lhs != block_scope.rl_ptr) { extra_index += 2; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[0..extra_index]); break :special_prong; } assert(zir_datas[store_inst].bin.lhs == block_scope.rl_ptr); if (block_scope.rl_ty_inst != .none) { extra_index += 1; const break_inst = scalar_cases_payload.items[extra_index]; extra_index += 1; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[0..extra_index]); zir_tags[store_inst] = .as; zir_datas[store_inst].bin = .{ .lhs = block_scope.rl_ty_inst, .rhs = zir_datas[break_inst].@"break".operand, }; zir_datas[break_inst].@"break".operand = indexToRef(store_inst); } else { scalar_cases_payload.items[body_len_index] -= 1; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[0..extra_index]); extra_index += 1; astgen.extra.appendAssumeCapacity(scalar_cases_payload.items[extra_index]); extra_index += 1; } } else { astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[0..extra_index]); } var scalar_i: u32 = 0; while (scalar_i < scalar_cases_len) : (scalar_i += 1) { const start_index = extra_index; extra_index += 1; const body_len_index = extra_index; const body_len = scalar_cases_payload.items[extra_index]; extra_index += 1; if (body_len < 2) { extra_index += body_len; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[start_index..extra_index]); continue; } extra_index += body_len - 2; const store_inst = scalar_cases_payload.items[extra_index]; if (zir_tags[store_inst] != .store_to_block_ptr or zir_datas[store_inst].bin.lhs != block_scope.rl_ptr) { extra_index += 2; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[start_index..extra_index]); continue; } if (block_scope.rl_ty_inst != .none) { extra_index += 1; const break_inst = scalar_cases_payload.items[extra_index]; extra_index += 1; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[start_index..extra_index]); zir_tags[store_inst] = .as; zir_datas[store_inst].bin = .{ .lhs = block_scope.rl_ty_inst, .rhs = zir_datas[break_inst].@"break".operand, }; zir_datas[break_inst].@"break".operand = indexToRef(store_inst); } else { scalar_cases_payload.items[body_len_index] -= 1; astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items[start_index..extra_index]); extra_index += 1; astgen.extra.appendAssumeCapacity(scalar_cases_payload.items[extra_index]); extra_index += 1; } } extra_index = 0; var multi_i: u32 = 0; while (multi_i < multi_cases_len) : (multi_i += 1) { const start_index = extra_index; const items_len = multi_cases_payload.items[extra_index]; extra_index += 1; const ranges_len = multi_cases_payload.items[extra_index]; extra_index += 1; const body_len_index = extra_index; const body_len = multi_cases_payload.items[extra_index]; extra_index += 1; extra_index += items_len; extra_index += 2 * ranges_len; if (body_len < 2) { extra_index += body_len; astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items[start_index..extra_index]); continue; } extra_index += body_len - 2; const store_inst = multi_cases_payload.items[extra_index]; if (zir_tags[store_inst] != .store_to_block_ptr or zir_datas[store_inst].bin.lhs != block_scope.rl_ptr) { extra_index += 2; astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items[start_index..extra_index]); continue; } if (block_scope.rl_ty_inst != .none) { extra_index += 1; const break_inst = multi_cases_payload.items[extra_index]; extra_index += 1; astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items[start_index..extra_index]); zir_tags[store_inst] = .as; zir_datas[store_inst].bin = .{ .lhs = block_scope.rl_ty_inst, .rhs = zir_datas[break_inst].@"break".operand, }; zir_datas[break_inst].@"break".operand = indexToRef(store_inst); } else { assert(zir_datas[store_inst].bin.lhs == block_scope.rl_ptr); multi_cases_payload.items[body_len_index] -= 1; astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items[start_index..extra_index]); extra_index += 1; astgen.extra.appendAssumeCapacity(multi_cases_payload.items[extra_index]); extra_index += 1; } } const block_ref = indexToRef(switch_block); switch (rl) { .ref => return block_ref, else => return rvalue(parent_gz, rl, block_ref, switch_node), } }, .break_void => { assert(!strat.elide_store_to_block_ptr_instructions); astgen.extra.appendSliceAssumeCapacity(scalar_cases_payload.items); astgen.extra.appendSliceAssumeCapacity(multi_cases_payload.items); // Modify all the terminating instruction tags to become `break` variants. var extra_index: usize = payload_index; extra_index += 2; extra_index += @boolToInt(multi_cases_len != 0); if (special_prong != .none) { const body_len = astgen.extra.items[extra_index]; extra_index += 1; const body = astgen.extra.items[extra_index..][0..body_len]; extra_index += body_len; const last = body[body.len - 1]; if (zir_tags[last] == .@"break" and zir_datas[last].@"break".block_inst == switch_block) { zir_datas[last].@"break".operand = .void_value; } } var scalar_i: u32 = 0; while (scalar_i < scalar_cases_len) : (scalar_i += 1) { extra_index += 1; const body_len = astgen.extra.items[extra_index]; extra_index += 1; const body = astgen.extra.items[extra_index..][0..body_len]; extra_index += body_len; const last = body[body.len - 1]; if (zir_tags[last] == .@"break" and zir_datas[last].@"break".block_inst == switch_block) { zir_datas[last].@"break".operand = .void_value; } } var multi_i: u32 = 0; while (multi_i < multi_cases_len) : (multi_i += 1) { const items_len = astgen.extra.items[extra_index]; extra_index += 1; const ranges_len = astgen.extra.items[extra_index]; extra_index += 1; const body_len = astgen.extra.items[extra_index]; extra_index += 1; extra_index += items_len; extra_index += 2 * ranges_len; const body = astgen.extra.items[extra_index..][0..body_len]; extra_index += body_len; const last = body[body.len - 1]; if (zir_tags[last] == .@"break" and zir_datas[last].@"break".block_inst == switch_block) { zir_datas[last].@"break".operand = .void_value; } } return indexToRef(switch_block); }, } } fn ret(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); if (astgen.fn_block == null) { return astgen.failNode(node, "'return' outside function scope", .{}); } if (gz.in_defer) return astgen.failNode(node, "cannot return from defer expression", .{}); const defer_outer = &astgen.fn_block.?.base; const operand_node = node_datas[node].lhs; if (operand_node == 0) { // Returning a void value; skip error defers. try genDefers(gz, defer_outer, scope, .normal_only); _ = try gz.addUnNode(.ret_node, .void_value, node); return Zir.Inst.Ref.unreachable_value; } if (node_tags[operand_node] == .error_value) { // Hot path for `return error.Foo`. This bypasses result location logic as well as logic // for detecting whether to add something to the function's inferred error set. const ident_token = node_datas[operand_node].rhs; const err_name_str_index = try astgen.identAsString(ident_token); const defer_counts = countDefers(astgen, defer_outer, scope); if (!defer_counts.need_err_code) { try genDefers(gz, defer_outer, scope, .both_sans_err); _ = try gz.addStrTok(.ret_err_value, err_name_str_index, ident_token); return Zir.Inst.Ref.unreachable_value; } const err_code = try gz.addStrTok(.ret_err_value_code, err_name_str_index, ident_token); try genDefers(gz, defer_outer, scope, .{ .both = err_code }); _ = try gz.addUnNode(.ret_node, err_code, node); return Zir.Inst.Ref.unreachable_value; } const rl: ResultLoc = if (nodeMayNeedMemoryLocation(tree, operand_node)) .{ .ptr = try gz.addNodeExtended(.ret_ptr, node), } else .{ .ty = try gz.addNodeExtended(.ret_type, node), }; const operand = try expr(gz, scope, rl, operand_node); switch (nodeMayEvalToError(tree, operand_node)) { .never => { // Returning a value that cannot be an error; skip error defers. try genDefers(gz, defer_outer, scope, .normal_only); _ = try gz.addUnNode(.ret_node, operand, node); return Zir.Inst.Ref.unreachable_value; }, .always => { // Value is always an error. Emit both error defers and regular defers. const err_code = try gz.addUnNode(.err_union_code, operand, node); try genDefers(gz, defer_outer, scope, .{ .both = err_code }); try gz.addRet(rl, operand, node); return Zir.Inst.Ref.unreachable_value; }, .maybe => { const defer_counts = countDefers(astgen, defer_outer, scope); if (!defer_counts.have_err) { // Only regular defers; no branch needed. try genDefers(gz, defer_outer, scope, .normal_only); try gz.addRet(rl, operand, node); return Zir.Inst.Ref.unreachable_value; } // Emit conditional branch for generating errdefers. const is_non_err = try gz.addUnNode(.is_non_err, operand, node); const condbr = try gz.addCondBr(.condbr, node); var then_scope = gz.makeSubBlock(scope); defer then_scope.instructions.deinit(astgen.gpa); try genDefers(&then_scope, defer_outer, scope, .normal_only); try then_scope.addRet(rl, operand, node); var else_scope = gz.makeSubBlock(scope); defer else_scope.instructions.deinit(astgen.gpa); const which_ones: DefersToEmit = if (!defer_counts.need_err_code) .both_sans_err else .{ .both = try else_scope.addUnNode(.err_union_code, operand, node), }; try genDefers(&else_scope, defer_outer, scope, which_ones); try else_scope.addRet(rl, operand, node); try setCondBrPayload(condbr, is_non_err, &then_scope, &else_scope); return Zir.Inst.Ref.unreachable_value; }, } } fn identifier( gz: *GenZir, scope: *Scope, rl: ResultLoc, ident: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const tracy = trace(@src()); defer tracy.end(); const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const ident_token = main_tokens[ident]; const ident_name_raw = tree.tokenSlice(ident_token); if (mem.eql(u8, ident_name_raw, "_")) { return astgen.failNode(ident, "'_' used as an identifier without @\"_\" syntax", .{}); } const ident_name = try astgen.identifierTokenString(ident_token); if (ident_name_raw[0] != '@') { if (simple_types.get(ident_name)) |zir_const_ref| { return rvalue(gz, rl, zir_const_ref, ident); } if (ident_name.len >= 2) integer: { const first_c = ident_name[0]; if (first_c == 'i' or first_c == 'u') { const signedness: std.builtin.Signedness = switch (first_c == 'i') { true => .signed, false => .unsigned, }; const bit_count = std.fmt.parseInt(u16, ident_name[1..], 10) catch |err| switch (err) { error.Overflow => return astgen.failNode( ident, "primitive integer type '{s}' exceeds maximum bit width of 65535", .{ident_name}, ), error.InvalidCharacter => break :integer, }; const result = try gz.add(.{ .tag = .int_type, .data = .{ .int_type = .{ .src_node = gz.nodeIndexToRelative(ident), .signedness = signedness, .bit_count = bit_count, } }, }); return rvalue(gz, rl, result, ident); } } } // Local variables, including function parameters. const name_str_index = try astgen.identAsString(ident_token); var s = scope; var found_already: ?ast.Node.Index = null; // we have found a decl with the same name already var hit_namespace: ast.Node.Index = 0; while (true) switch (s.tag) { .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (local_val.name == name_str_index) { local_val.used = true; // Locals cannot shadow anything, so we do not need to look for ambiguous // references in this case. return rvalue(gz, rl, local_val.inst, ident); } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == name_str_index) { local_ptr.used = true; if (hit_namespace != 0 and !local_ptr.maybe_comptime) { return astgen.failNodeNotes(ident, "mutable '{s}' not accessible from here", .{ident_name}, &.{ try astgen.errNoteTok(local_ptr.token_src, "declared mutable here", .{}), try astgen.errNoteNode(hit_namespace, "crosses namespace boundary here", .{}), }); } switch (rl) { .ref, .none_or_ref => return local_ptr.ptr, else => { const loaded = try gz.addUnNode(.load, local_ptr.ptr, ident); return rvalue(gz, rl, loaded, ident); }, } } s = local_ptr.parent; }, .gen_zir => s = s.cast(GenZir).?.parent, .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, .namespace => { const ns = s.cast(Scope.Namespace).?; if (ns.decls.get(name_str_index)) |i| { if (found_already) |f| { return astgen.failNodeNotes(ident, "ambiguous reference", .{}, &.{ try astgen.errNoteNode(f, "declared here", .{}), try astgen.errNoteNode(i, "also declared here", .{}), }); } // We found a match but must continue looking for ambiguous references to decls. found_already = i; } hit_namespace = ns.node; s = ns.parent; }, .top => break, }; // Decl references happen by name rather than ZIR index so that when unrelated // decls are modified, ZIR code containing references to them can be unmodified. switch (rl) { .ref, .none_or_ref => return gz.addStrTok(.decl_ref, name_str_index, ident_token), else => { const result = try gz.addStrTok(.decl_val, name_str_index, ident_token); return rvalue(gz, rl, result, ident); }, } } fn stringLiteral( gz: *GenZir, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const str_lit_token = main_tokens[node]; const str = try astgen.strLitAsString(str_lit_token); const result = try gz.add(.{ .tag = .str, .data = .{ .str = .{ .start = str.index, .len = str.len, } }, }); return rvalue(gz, rl, result, node); } fn multilineStringLiteral( gz: *GenZir, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const str = try astgen.strLitNodeAsString(node); const result = try gz.add(.{ .tag = .str, .data = .{ .str = .{ .start = str.index, .len = str.len, } }, }); return rvalue(gz, rl, result, node); } fn charLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const main_token = main_tokens[node]; const slice = tree.tokenSlice(main_token); switch (std.zig.parseCharLiteral(slice)) { .success => |codepoint| { const result = try gz.addInt(codepoint); return rvalue(gz, rl, result, node); }, .invalid_escape_character => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "invalid escape character: '{c}'", .{slice[bad_index]}, ); }, .expected_hex_digit => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "expected hex digit, found '{c}'", .{slice[bad_index]}, ); }, .empty_unicode_escape_sequence => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "empty unicode escape sequence", .{}, ); }, .expected_hex_digit_or_rbrace => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "expected hex digit or '}}', found '{c}'", .{slice[bad_index]}, ); }, .unicode_escape_overflow => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "unicode escape too large to be a valid codepoint", .{}, ); }, .expected_lbrace => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "expected '{{', found '{c}", .{slice[bad_index]}, ); }, .expected_end => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "expected ending single quote ('), found '{c}", .{slice[bad_index]}, ); }, .invalid_character => |bad_index| { return astgen.failOff( main_token, @intCast(u32, bad_index), "invalid byte in character literal: '{c}'", .{slice[bad_index]}, ); }, } } fn integerLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const int_token = main_tokens[node]; const prefixed_bytes = tree.tokenSlice(int_token); if (std.fmt.parseInt(u64, prefixed_bytes, 0)) |small_int| { const result: Zir.Inst.Ref = switch (small_int) { 0 => .zero, 1 => .one, else => try gz.addInt(small_int), }; return rvalue(gz, rl, result, node); } else |err| switch (err) { error.InvalidCharacter => unreachable, // Caught by the parser. error.Overflow => {}, } var base: u8 = 10; var non_prefixed: []const u8 = prefixed_bytes; if (mem.startsWith(u8, prefixed_bytes, "0x")) { base = 16; non_prefixed = prefixed_bytes[2..]; } else if (mem.startsWith(u8, prefixed_bytes, "0o")) { base = 8; non_prefixed = prefixed_bytes[2..]; } else if (mem.startsWith(u8, prefixed_bytes, "0b")) { base = 2; non_prefixed = prefixed_bytes[2..]; } const gpa = astgen.gpa; var big_int = try std.math.big.int.Managed.init(gpa); defer big_int.deinit(); big_int.setString(base, non_prefixed) catch |err| switch (err) { error.InvalidCharacter => unreachable, // caught by parser error.InvalidBase => unreachable, // we only pass 16, 8, 2, see above error.OutOfMemory => return error.OutOfMemory, }; const limbs = big_int.limbs[0..big_int.len()]; assert(big_int.isPositive()); const result = try gz.addIntBig(limbs); return rvalue(gz, rl, result, node); } fn floatLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const main_token = main_tokens[node]; const bytes = tree.tokenSlice(main_token); const float_number: f128 = if (bytes.len > 2 and bytes[1] == 'x') hex: { assert(bytes[0] == '0'); // validated by tokenizer break :hex std.fmt.parseHexFloat(f128, bytes) catch |err| switch (err) { error.InvalidCharacter => unreachable, // validated by tokenizer error.Overflow => return astgen.failNode(node, "number literal cannot be represented in a 128-bit floating point", .{}), }; } else std.fmt.parseFloat(f128, bytes) catch |err| switch (err) { error.InvalidCharacter => unreachable, // validated by tokenizer }; // If the value fits into a f64 without losing any precision, store it that way. @setFloatMode(.Strict); const smaller_float = @floatCast(f64, float_number); const bigger_again: f128 = smaller_float; if (bigger_again == float_number) { const result = try gz.addFloat(smaller_float); return rvalue(gz, rl, result, node); } // We need to use 128 bits. Break the float into 4 u32 values so we can // put it into the `extra` array. const int_bits = @bitCast(u128, float_number); const result = try gz.addPlNode(.float128, node, Zir.Inst.Float128{ .piece0 = @truncate(u32, int_bits), .piece1 = @truncate(u32, int_bits >> 32), .piece2 = @truncate(u32, int_bits >> 64), .piece3 = @truncate(u32, int_bits >> 96), }); return rvalue(gz, rl, result, node); } fn asmExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, full: ast.full.Asm, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const token_tags = tree.tokens.items(.tag); const asm_source = switch (node_tags[full.ast.template]) { .string_literal => try astgen.strLitAsString(main_tokens[full.ast.template]), .multiline_string_literal => try astgen.strLitNodeAsString(full.ast.template), else => return astgen.failNode(full.ast.template, "assembly code must use string literal syntax", .{}), }; // See https://github.com/ziglang/zig/issues/215 and related issues discussing // possible inline assembly improvements. Until then here is status quo AstGen // for assembly syntax. It's used by std lib crypto aesni.zig. const is_container_asm = astgen.fn_block == null; if (is_container_asm) { if (full.volatile_token) |t| return astgen.failTok(t, "volatile is meaningless on global assembly", .{}); if (full.outputs.len != 0 or full.inputs.len != 0 or full.first_clobber != null) return astgen.failNode(node, "global assembly cannot have inputs, outputs, or clobbers", .{}); } else { if (full.outputs.len == 0 and full.volatile_token == null) { return astgen.failNode(node, "assembly expression with no output must be marked volatile", .{}); } } if (full.outputs.len > 32) { return astgen.failNode(full.outputs[32], "too many asm outputs", .{}); } var outputs_buffer: [32]Zir.Inst.Asm.Output = undefined; const outputs = outputs_buffer[0..full.outputs.len]; var output_type_bits: u32 = 0; for (full.outputs) |output_node, i| { const symbolic_name = main_tokens[output_node]; const name = try astgen.identAsString(symbolic_name); const constraint_token = symbolic_name + 2; const constraint = (try astgen.strLitAsString(constraint_token)).index; const has_arrow = token_tags[symbolic_name + 4] == .arrow; if (has_arrow) { output_type_bits |= @as(u32, 1) << @intCast(u5, i); const out_type_node = node_datas[output_node].lhs; const out_type_inst = try typeExpr(gz, scope, out_type_node); outputs[i] = .{ .name = name, .constraint = constraint, .operand = out_type_inst, }; } else { const ident_token = symbolic_name + 4; const str_index = try astgen.identAsString(ident_token); // TODO this needs extra code for local variables. Have a look at #215 and related // issues and decide how to handle outputs. Do we want this to be identifiers? // Or maybe we want to force this to be expressions with a pointer type. // Until that is figured out this is only hooked up for referencing Decls. // TODO we have put this as an identifier lookup just so that we don't get // unused vars for outputs. We need to check if this is correct in the future ^^ // so we just put in this simple lookup. This is a workaround. { var s = scope; while (true) switch (s.tag) { .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (local_val.name == str_index) { local_val.used = true; break; } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == str_index) { local_ptr.used = true; break; } s = local_ptr.parent; }, .gen_zir => s = s.cast(GenZir).?.parent, .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, .namespace, .top => break, }; } const operand = try gz.addStrTok(.decl_ref, str_index, ident_token); outputs[i] = .{ .name = name, .constraint = constraint, .operand = operand, }; } } if (full.inputs.len > 32) { return astgen.failNode(full.inputs[32], "too many asm inputs", .{}); } var inputs_buffer: [32]Zir.Inst.Asm.Input = undefined; const inputs = inputs_buffer[0..full.inputs.len]; for (full.inputs) |input_node, i| { const symbolic_name = main_tokens[input_node]; const name = try astgen.identAsString(symbolic_name); const constraint_token = symbolic_name + 2; const constraint = (try astgen.strLitAsString(constraint_token)).index; const operand = try expr(gz, scope, .{ .ty = .usize_type }, node_datas[input_node].lhs); inputs[i] = .{ .name = name, .constraint = constraint, .operand = operand, }; } var clobbers_buffer: [32]u32 = undefined; var clobber_i: usize = 0; if (full.first_clobber) |first_clobber| clobbers: { // asm ("foo" ::: "a", "b") // asm ("foo" ::: "a", "b",) var tok_i = first_clobber; while (true) : (tok_i += 1) { if (clobber_i >= clobbers_buffer.len) { return astgen.failTok(tok_i, "too many asm clobbers", .{}); } clobbers_buffer[clobber_i] = (try astgen.strLitAsString(tok_i)).index; clobber_i += 1; tok_i += 1; switch (token_tags[tok_i]) { .r_paren => break :clobbers, .comma => { if (token_tags[tok_i + 1] == .r_paren) { break :clobbers; } else { continue; } }, else => unreachable, } } } const result = try gz.addAsm(.{ .node = node, .asm_source = asm_source.index, .is_volatile = full.volatile_token != null, .output_type_bits = output_type_bits, .outputs = outputs, .inputs = inputs, .clobbers = clobbers_buffer[0..clobber_i], }); return rvalue(gz, rl, result, node); } fn as( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs: ast.Node.Index, rhs: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const dest_type = try typeExpr(gz, scope, lhs); switch (rl) { .none, .none_or_ref, .discard, .ref, .ty, .coerced_ty => { const result = try reachableExpr(gz, scope, .{ .ty = dest_type }, rhs, node); return rvalue(gz, rl, result, node); }, .ptr, .inferred_ptr => |result_ptr| { return asRlPtr(gz, scope, rl, node, result_ptr, rhs, dest_type); }, .block_ptr => |block_scope| { return asRlPtr(gz, scope, rl, node, block_scope.rl_ptr, rhs, dest_type); }, } } fn unionInit( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, params: []const ast.Node.Index, ) InnerError!Zir.Inst.Ref { const union_type = try typeExpr(gz, scope, params[0]); const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[1]); switch (rl) { .none, .none_or_ref, .discard, .ref, .ty, .coerced_ty, .inferred_ptr => { _ = try gz.addPlNode(.field_type_ref, params[1], Zir.Inst.FieldTypeRef{ .container_type = union_type, .field_name = field_name, }); const result = try expr(gz, scope, .{ .ty = union_type }, params[2]); return rvalue(gz, rl, result, node); }, .ptr => |result_ptr| { return unionInitRlPtr(gz, scope, node, result_ptr, params[2], union_type, field_name); }, .block_ptr => |block_scope| { return unionInitRlPtr(gz, scope, node, block_scope.rl_ptr, params[2], union_type, field_name); }, } } fn unionInitRlPtr( parent_gz: *GenZir, scope: *Scope, node: ast.Node.Index, result_ptr: Zir.Inst.Ref, expr_node: ast.Node.Index, union_type: Zir.Inst.Ref, field_name: Zir.Inst.Ref, ) InnerError!Zir.Inst.Ref { const union_init_ptr = try parent_gz.addPlNode(.union_init_ptr, node, Zir.Inst.UnionInitPtr{ .result_ptr = result_ptr, .union_type = union_type, .field_name = field_name, }); // TODO check if we need to do the elision like below in asRlPtr return expr(parent_gz, scope, .{ .ptr = union_init_ptr }, expr_node); } fn asRlPtr( parent_gz: *GenZir, scope: *Scope, rl: ResultLoc, src_node: ast.Node.Index, result_ptr: Zir.Inst.Ref, operand_node: ast.Node.Index, dest_type: Zir.Inst.Ref, ) InnerError!Zir.Inst.Ref { // Detect whether this expr() call goes into rvalue() to store the result into the // result location. If it does, elide the coerce_result_ptr instruction // as well as the store instruction, instead passing the result as an rvalue. const astgen = parent_gz.astgen; var as_scope = parent_gz.makeSubBlock(scope); defer as_scope.instructions.deinit(astgen.gpa); as_scope.rl_ptr = try as_scope.addBin(.coerce_result_ptr, dest_type, result_ptr); const result = try reachableExpr(&as_scope, &as_scope.base, .{ .block_ptr = &as_scope }, operand_node, src_node); const parent_zir = &parent_gz.instructions; if (as_scope.rvalue_rl_count == 1) { // Busted! This expression didn't actually need a pointer. const zir_tags = astgen.instructions.items(.tag); const zir_datas = astgen.instructions.items(.data); try parent_zir.ensureUnusedCapacity(astgen.gpa, as_scope.instructions.items.len); for (as_scope.instructions.items) |src_inst| { if (indexToRef(src_inst) == as_scope.rl_ptr) continue; if (zir_tags[src_inst] == .store_to_block_ptr) { if (zir_datas[src_inst].bin.lhs == as_scope.rl_ptr) continue; } parent_zir.appendAssumeCapacity(src_inst); } const casted_result = try parent_gz.addBin(.as, dest_type, result); return rvalue(parent_gz, rl, casted_result, operand_node); } else { try parent_zir.appendSlice(astgen.gpa, as_scope.instructions.items); return result; } } fn bitCast( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs: ast.Node.Index, rhs: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const dest_type = try typeExpr(gz, scope, lhs); switch (rl) { .none, .none_or_ref, .discard, .ty, .coerced_ty => { const operand = try expr(gz, scope, .none, rhs); const result = try gz.addPlNode(.bitcast, node, Zir.Inst.Bin{ .lhs = dest_type, .rhs = operand, }); return rvalue(gz, rl, result, node); }, .ref => { return astgen.failNode(node, "cannot take address of `@bitCast` result", .{}); }, .ptr, .inferred_ptr => |result_ptr| { return bitCastRlPtr(gz, scope, node, dest_type, result_ptr, rhs); }, .block_ptr => |block| { return bitCastRlPtr(gz, scope, node, dest_type, block.rl_ptr, rhs); }, } } fn bitCastRlPtr( gz: *GenZir, scope: *Scope, node: ast.Node.Index, dest_type: Zir.Inst.Ref, result_ptr: Zir.Inst.Ref, rhs: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const casted_result_ptr = try gz.addPlNode(.bitcast_result_ptr, node, Zir.Inst.Bin{ .lhs = dest_type, .rhs = result_ptr, }); return expr(gz, scope, .{ .ptr = casted_result_ptr }, rhs); } fn typeOf( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, params: []const ast.Node.Index, ) InnerError!Zir.Inst.Ref { if (params.len < 1) { return gz.astgen.failNode(node, "expected at least 1 argument, found 0", .{}); } if (params.len == 1) { const expr_result = try reachableExpr(gz, scope, .none, params[0], node); const result = try gz.addUnNode(.typeof, expr_result, node); return rvalue(gz, rl, result, node); } const arena = gz.astgen.arena; var items = try arena.alloc(Zir.Inst.Ref, params.len); for (params) |param, param_i| { items[param_i] = try reachableExpr(gz, scope, .none, param, node); } const result = try gz.addExtendedMultiOp(.typeof_peer, node, items); return rvalue(gz, rl, result, node); } fn builtinCall( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, params: []const ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const builtin_token = main_tokens[node]; const builtin_name = tree.tokenSlice(builtin_token); // We handle the different builtins manually because they have different semantics depending // on the function. For example, `@as` and others participate in result location semantics, // and `@cImport` creates a special scope that collects a .c source code text buffer. // Also, some builtins have a variable number of parameters. const info = BuiltinFn.list.get(builtin_name) orelse { return astgen.failNode(node, "invalid builtin function: '{s}'", .{ builtin_name, }); }; if (info.param_count) |expected| { if (expected != params.len) { const s = if (expected == 1) "" else "s"; return astgen.failNode(node, "expected {d} argument{s}, found {d}", .{ expected, s, params.len, }); } } // zig fmt: off switch (info.tag) { .import => { const node_tags = tree.nodes.items(.tag); const operand_node = params[0]; if (node_tags[operand_node] != .string_literal) { // Spec reference: https://github.com/ziglang/zig/issues/2206 return astgen.failNode(operand_node, "@import operand must be a string literal", .{}); } const str_lit_token = main_tokens[operand_node]; const str = try astgen.strLitAsString(str_lit_token); const result = try gz.addStrTok(.import, str.index, str_lit_token); const gop = try astgen.imports.getOrPut(astgen.gpa, str.index); if (!gop.found_existing) { gop.value_ptr.* = str_lit_token; } return rvalue(gz, rl, result, node); }, .compile_log => { const arg_refs = try astgen.gpa.alloc(Zir.Inst.Ref, params.len); defer astgen.gpa.free(arg_refs); for (params) |param, i| arg_refs[i] = try expr(gz, scope, .none, param); const result = try gz.addExtendedMultiOp(.compile_log, node, arg_refs); return rvalue(gz, rl, result, node); }, .field => { const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[1]); if (rl == .ref) { return gz.addPlNode(.field_ptr_named, node, Zir.Inst.FieldNamed{ .lhs = try expr(gz, scope, .ref, params[0]), .field_name = field_name, }); } const result = try gz.addPlNode(.field_val_named, node, Zir.Inst.FieldNamed{ .lhs = try expr(gz, scope, .none, params[0]), .field_name = field_name, }); return rvalue(gz, rl, result, node); }, .as => return as( gz, scope, rl, node, params[0], params[1]), .bit_cast => return bitCast( gz, scope, rl, node, params[0], params[1]), .TypeOf => return typeOf( gz, scope, rl, node, params), .union_init => return unionInit(gz, scope, rl, node, params), .c_import => return cImport( gz, scope, rl, node, params[0]), .@"export" => { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); // This function causes a Decl to be exported. The first parameter is not an expression, // but an identifier of the Decl to be exported. var namespace: Zir.Inst.Ref = .none; var decl_name: u32 = 0; switch (node_tags[params[0]]) { .identifier => { const ident_token = main_tokens[params[0]]; decl_name = try astgen.identAsString(ident_token); { var s = scope; while (true) switch (s.tag) { .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (local_val.name == decl_name) { local_val.used = true; break; } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == decl_name) { if (!local_ptr.maybe_comptime) return astgen.failNode(params[0], "unable to export runtime-known value", .{}); local_ptr.used = true; break; } s = local_ptr.parent; }, .gen_zir => s = s.cast(GenZir).?.parent, .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, .namespace, .top => break, }; } }, .field_access => { const namespace_node = node_datas[params[0]].lhs; namespace = try typeExpr(gz, scope, namespace_node); const dot_token = main_tokens[params[0]]; const field_ident = dot_token + 1; decl_name = try astgen.identAsString(field_ident); }, else => return astgen.failNode( params[0], "symbol to export must identify a declaration", .{}, ), } const options = try comptimeExpr(gz, scope, .{ .ty = .export_options_type }, params[1]); _ = try gz.addPlNode(.@"export", node, Zir.Inst.Export{ .namespace = namespace, .decl_name = decl_name, .options = options, }); return rvalue(gz, rl, .void_value, node); }, .@"extern" => { const type_inst = try typeExpr(gz, scope, params[0]); const options = try comptimeExpr(gz, scope, .{ .ty = .extern_options_type }, params[1]); const result = try gz.addExtendedPayload(.builtin_extern, Zir.Inst.BinNode{ .node = gz.nodeIndexToRelative(node), .lhs = type_inst, .rhs = options, }); return rvalue(gz, rl, result, node); }, .breakpoint => return simpleNoOpVoid(gz, rl, node, .breakpoint), .fence => return simpleNoOpVoid(gz, rl, node, .fence), .This => return rvalue(gz, rl, try gz.addNodeExtended(.this, node), node), .return_address => return rvalue(gz, rl, try gz.addNodeExtended(.ret_addr, node), node), .src => return rvalue(gz, rl, try gz.addNodeExtended(.builtin_src, node), node), .error_return_trace => return rvalue(gz, rl, try gz.addNodeExtended(.error_return_trace, node), node), .frame => return rvalue(gz, rl, try gz.addNodeExtended(.frame, node), node), .frame_address => return rvalue(gz, rl, try gz.addNodeExtended(.frame_address, node), node), .type_info => return simpleUnOpType(gz, scope, rl, node, params[0], .type_info), .size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .size_of), .bit_size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .bit_size_of), .align_of => return simpleUnOpType(gz, scope, rl, node, params[0], .align_of), .ptr_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ptr_to_int), .error_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .error_to_int), .int_to_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u16_type }, params[0], .int_to_error), .compile_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .compile_error), .set_eval_branch_quota => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u32_type }, params[0], .set_eval_branch_quota), .enum_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .enum_to_int), .bool_to_int => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .bool_to_int), .embed_file => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .embed_file), .error_name => return simpleUnOp(gz, scope, rl, node, .{ .ty = .anyerror_type }, params[0], .error_name), .panic => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .panic), .set_align_stack => return simpleUnOp(gz, scope, rl, node, align_rl, params[0], .set_align_stack), .set_cold => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_cold), .set_float_mode => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .float_mode_type }, params[0], .set_float_mode), .set_runtime_safety => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_runtime_safety), .sqrt => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sqrt), .sin => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sin), .cos => return simpleUnOp(gz, scope, rl, node, .none, params[0], .cos), .exp => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp), .exp2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp2), .log => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log), .log2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log2), .log10 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log10), .fabs => return simpleUnOp(gz, scope, rl, node, .none, params[0], .fabs), .floor => return simpleUnOp(gz, scope, rl, node, .none, params[0], .floor), .ceil => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ceil), .trunc => return simpleUnOp(gz, scope, rl, node, .none, params[0], .trunc), .round => return simpleUnOp(gz, scope, rl, node, .none, params[0], .round), .tag_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .tag_name), .Type => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .type_info_type }, params[0], .reify), .type_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .type_name), .Frame => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_type), .frame_size => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_size), .float_to_int => return typeCast(gz, scope, rl, node, params[0], params[1], .float_to_int), .int_to_float => return typeCast(gz, scope, rl, node, params[0], params[1], .int_to_float), .int_to_ptr => return typeCast(gz, scope, rl, node, params[0], params[1], .int_to_ptr), .int_to_enum => return typeCast(gz, scope, rl, node, params[0], params[1], .int_to_enum), .float_cast => return typeCast(gz, scope, rl, node, params[0], params[1], .float_cast), .int_cast => return typeCast(gz, scope, rl, node, params[0], params[1], .int_cast), .err_set_cast => return typeCast(gz, scope, rl, node, params[0], params[1], .err_set_cast), .ptr_cast => return typeCast(gz, scope, rl, node, params[0], params[1], .ptr_cast), .truncate => return typeCast(gz, scope, rl, node, params[0], params[1], .truncate), .align_cast => { const dest_align = try comptimeExpr(gz, scope, align_rl, params[0]); const rhs = try expr(gz, scope, .none, params[1]); const result = try gz.addPlNode(.align_cast, node, Zir.Inst.Bin{ .lhs = dest_align, .rhs = rhs, }); return rvalue(gz, rl, result, node); }, .has_decl => return hasDeclOrField(gz, scope, rl, node, params[0], params[1], .has_decl), .has_field => return hasDeclOrField(gz, scope, rl, node, params[0], params[1], .has_field), .clz => return bitBuiltin(gz, scope, rl, node, params[0], params[1], .clz), .ctz => return bitBuiltin(gz, scope, rl, node, params[0], params[1], .ctz), .pop_count => return bitBuiltin(gz, scope, rl, node, params[0], params[1], .pop_count), .byte_swap => return bitBuiltin(gz, scope, rl, node, params[0], params[1], .byte_swap), .bit_reverse => return bitBuiltin(gz, scope, rl, node, params[0], params[1], .bit_reverse), .div_exact => return divBuiltin(gz, scope, rl, node, params[0], params[1], .div_exact), .div_floor => return divBuiltin(gz, scope, rl, node, params[0], params[1], .div_floor), .div_trunc => return divBuiltin(gz, scope, rl, node, params[0], params[1], .div_trunc), .mod => return divBuiltin(gz, scope, rl, node, params[0], params[1], .mod), .rem => return divBuiltin(gz, scope, rl, node, params[0], params[1], .rem), .shl_exact => return shiftOp(gz, scope, rl, node, params[0], params[1], .shl_exact), .shr_exact => return shiftOp(gz, scope, rl, node, params[0], params[1], .shr_exact), .bit_offset_of => return offsetOf(gz, scope, rl, node, params[0], params[1], .bit_offset_of), .offset_of => return offsetOf(gz, scope, rl, node, params[0], params[1], .offset_of), .c_undef => return simpleCBuiltin(gz, scope, rl, node, params[0], .c_undef), .c_include => return simpleCBuiltin(gz, scope, rl, node, params[0], .c_include), .cmpxchg_strong => return cmpxchg(gz, scope, rl, node, params, .cmpxchg_strong), .cmpxchg_weak => return cmpxchg(gz, scope, rl, node, params, .cmpxchg_weak), .wasm_memory_size => { const operand = try expr(gz, scope, .{ .ty = .u32_type }, params[0]); const result = try gz.addExtendedPayload(.wasm_memory_size, Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(node), .operand = operand, }); return rvalue(gz, rl, result, node); }, .wasm_memory_grow => { const index_arg = try expr(gz, scope, .{ .ty = .u32_type }, params[0]); const delta_arg = try expr(gz, scope, .{ .ty = .u32_type }, params[1]); const result = try gz.addExtendedPayload(.wasm_memory_grow, Zir.Inst.BinNode{ .node = gz.nodeIndexToRelative(node), .lhs = index_arg, .rhs = delta_arg, }); return rvalue(gz, rl, result, node); }, .c_define => { const name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[0]); const value = try comptimeExpr(gz, scope, .none, params[1]); const result = try gz.addExtendedPayload(.c_define, Zir.Inst.BinNode{ .node = gz.nodeIndexToRelative(node), .lhs = name, .rhs = value, }); return rvalue(gz, rl, result, node); }, .splat => { const len = try expr(gz, scope, .{ .ty = .u32_type }, params[0]); const scalar = try expr(gz, scope, .none, params[1]); const result = try gz.addPlNode(.splat, node, Zir.Inst.Bin{ .lhs = len, .rhs = scalar, }); return rvalue(gz, rl, result, node); }, .reduce => { const op = try expr(gz, scope, .{ .ty = .reduce_op_type }, params[0]); const scalar = try expr(gz, scope, .none, params[1]); const result = try gz.addPlNode(.reduce, node, Zir.Inst.Bin{ .lhs = op, .rhs = scalar, }); return rvalue(gz, rl, result, node); }, .maximum => { const a = try expr(gz, scope, .none, params[0]); const b = try expr(gz, scope, .none, params[1]); const result = try gz.addPlNode(.maximum, node, Zir.Inst.Bin{ .lhs = a, .rhs = b, }); return rvalue(gz, rl, result, node); }, .minimum => { const a = try expr(gz, scope, .none, params[0]); const b = try expr(gz, scope, .none, params[1]); const result = try gz.addPlNode(.minimum, node, Zir.Inst.Bin{ .lhs = a, .rhs = b, }); return rvalue(gz, rl, result, node); }, .add_with_overflow => return overflowArithmetic(gz, scope, rl, node, params, .add_with_overflow), .sub_with_overflow => return overflowArithmetic(gz, scope, rl, node, params, .sub_with_overflow), .mul_with_overflow => return overflowArithmetic(gz, scope, rl, node, params, .mul_with_overflow), .shl_with_overflow => { const int_type = try typeExpr(gz, scope, params[0]); const log2_int_type = try gz.addUnNode(.log2_int_type, int_type, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = true, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const lhs = try expr(gz, scope, .{ .ty = int_type }, params[1]); const rhs = try expr(gz, scope, .{ .ty = log2_int_type }, params[2]); const ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[3]); const result = try gz.addExtendedPayload(.shl_with_overflow, Zir.Inst.OverflowArithmetic{ .node = gz.nodeIndexToRelative(node), .lhs = lhs, .rhs = rhs, .ptr = ptr, }); return rvalue(gz, rl, result, node); }, .atomic_load => { const int_type = try typeExpr(gz, scope, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = false, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[1]); const ordering = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[2]); const result = try gz.addPlNode(.atomic_load, node, Zir.Inst.Bin{ .lhs = ptr, .rhs = ordering, }); return rvalue(gz, rl, result, node); }, .atomic_rmw => { const int_type = try typeExpr(gz, scope, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = true, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[1]); const operation = try expr(gz, scope, .{ .ty = .atomic_rmw_op_type }, params[2]); const operand = try expr(gz, scope, .{ .ty = int_type }, params[3]); const ordering = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[4]); const result = try gz.addPlNode(.atomic_rmw, node, Zir.Inst.AtomicRmw{ .ptr = ptr, .operation = operation, .operand = operand, .ordering = ordering, }); return rvalue(gz, rl, result, node); }, .atomic_store => { const int_type = try typeExpr(gz, scope, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = true, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[1]); const operand = try expr(gz, scope, .{ .ty = int_type }, params[2]); const ordering = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[3]); const result = try gz.addPlNode(.atomic_store, node, Zir.Inst.AtomicStore{ .ptr = ptr, .operand = operand, .ordering = ordering, }); return rvalue(gz, rl, result, node); }, .mul_add => { const float_type = try typeExpr(gz, scope, params[0]); const mulend1 = try expr(gz, scope, .{ .ty = float_type }, params[1]); const mulend2 = try expr(gz, scope, .{ .ty = float_type }, params[2]); const addend = try expr(gz, scope, .{ .ty = float_type }, params[3]); const result = try gz.addPlNode(.mul_add, node, Zir.Inst.MulAdd{ .mulend1 = mulend1, .mulend2 = mulend2, .addend = addend, }); return rvalue(gz, rl, result, node); }, .call => { const options = try comptimeExpr(gz, scope, .{ .ty = .call_options_type }, params[0]); const callee = try expr(gz, scope, .none, params[1]); const args = try expr(gz, scope, .none, params[2]); const result = try gz.addPlNode(.builtin_call, node, Zir.Inst.BuiltinCall{ .options = options, .callee = callee, .args = args, }); return rvalue(gz, rl, result, node); }, .field_parent_ptr => { const parent_type = try typeExpr(gz, scope, params[0]); const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[1]); const field_ptr_type = try gz.addBin(.field_ptr_type, parent_type, field_name); const result = try gz.addPlNode(.field_parent_ptr, node, Zir.Inst.FieldParentPtr{ .parent_type = parent_type, .field_name = field_name, .field_ptr = try expr(gz, scope, .{ .ty = field_ptr_type }, params[2]), }); return rvalue(gz, rl, result, node); }, .memcpy => { const result = try gz.addPlNode(.memcpy, node, Zir.Inst.Memcpy{ .dest = try expr(gz, scope, .{ .ty = .manyptr_u8_type }, params[0]), .source = try expr(gz, scope, .{ .ty = .manyptr_const_u8_type }, params[1]), .byte_count = try expr(gz, scope, .{ .ty = .usize_type }, params[2]), }); return rvalue(gz, rl, result, node); }, .memset => { const result = try gz.addPlNode(.memset, node, Zir.Inst.Memset{ .dest = try expr(gz, scope, .{ .ty = .manyptr_u8_type }, params[0]), .byte = try expr(gz, scope, .{ .ty = .u8_type }, params[1]), .byte_count = try expr(gz, scope, .{ .ty = .usize_type }, params[2]), }); return rvalue(gz, rl, result, node); }, .shuffle => { const result = try gz.addPlNode(.shuffle, node, Zir.Inst.Shuffle{ .elem_type = try typeExpr(gz, scope, params[0]), .a = try expr(gz, scope, .none, params[1]), .b = try expr(gz, scope, .none, params[2]), .mask = try comptimeExpr(gz, scope, .none, params[3]), }); return rvalue(gz, rl, result, node); }, .select => { const result = try gz.addPlNode(.select, node, Zir.Inst.Select{ .elem_type = try typeExpr(gz, scope, params[0]), .pred = try expr(gz, scope, .none, params[1]), .a = try expr(gz, scope, .none, params[2]), .b = try expr(gz, scope, .none, params[3]), }); return rvalue(gz, rl, result, node); }, .async_call => { const result = try gz.addPlNode(.builtin_async_call, node, Zir.Inst.AsyncCall{ .frame_buffer = try expr(gz, scope, .none, params[0]), .result_ptr = try expr(gz, scope, .none, params[1]), .fn_ptr = try expr(gz, scope, .none, params[2]), .args = try expr(gz, scope, .none, params[3]), }); return rvalue(gz, rl, result, node); }, .Vector => { const result = try gz.addPlNode(.vector_type, node, Zir.Inst.Bin{ .lhs = try comptimeExpr(gz, scope, .{.ty = .u32_type}, params[0]), .rhs = try typeExpr(gz, scope, params[1]), }); return rvalue(gz, rl, result, node); }, } // zig fmt: on } fn simpleNoOpVoid( gz: *GenZir, rl: ResultLoc, node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { _ = try gz.addNode(tag, node); return rvalue(gz, rl, .void_value, node); } fn hasDeclOrField( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs_node: ast.Node.Index, rhs_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const container_type = try typeExpr(gz, scope, lhs_node); const name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, rhs_node); const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = container_type, .rhs = name, }); return rvalue(gz, rl, result, node); } fn typeCast( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs_node: ast.Node.Index, rhs_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = try typeExpr(gz, scope, lhs_node), .rhs = try expr(gz, scope, .none, rhs_node), }); return rvalue(gz, rl, result, node); } fn simpleUnOpType( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, operand_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const operand = try typeExpr(gz, scope, operand_node); const result = try gz.addUnNode(tag, operand, node); return rvalue(gz, rl, result, node); } fn simpleUnOp( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, operand_rl: ResultLoc, operand_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const operand = try expr(gz, scope, operand_rl, operand_node); const result = try gz.addUnNode(tag, operand, node); return rvalue(gz, rl, result, node); } fn cmpxchg( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, params: []const ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const int_type = try typeExpr(gz, scope, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = true, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const result = try gz.addPlNode(tag, node, Zir.Inst.Cmpxchg{ // zig fmt: off .ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[1]), .expected_value = try expr(gz, scope, .{ .ty = int_type }, params[2]), .new_value = try expr(gz, scope, .{ .ty = int_type }, params[3]), .success_order = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[4]), .fail_order = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[5]), // zig fmt: on }); return rvalue(gz, rl, result, node); } fn bitBuiltin( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, int_type_node: ast.Node.Index, operand_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const int_type = try typeExpr(gz, scope, int_type_node); const operand = try expr(gz, scope, .{ .ty = int_type }, operand_node); const result = try gz.addUnNode(tag, operand, node); return rvalue(gz, rl, result, node); } fn divBuiltin( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs_node: ast.Node.Index, rhs_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = try expr(gz, scope, .none, lhs_node), .rhs = try expr(gz, scope, .none, rhs_node), }); return rvalue(gz, rl, result, node); } fn simpleCBuiltin( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, operand_node: ast.Node.Index, tag: Zir.Inst.Extended, ) InnerError!Zir.Inst.Ref { const operand = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, operand_node); _ = try gz.addExtendedPayload(tag, Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(node), .operand = operand, }); return rvalue(gz, rl, .void_value, node); } fn offsetOf( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs_node: ast.Node.Index, rhs_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const type_inst = try typeExpr(gz, scope, lhs_node); const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, rhs_node); const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = type_inst, .rhs = field_name, }); return rvalue(gz, rl, result, node); } fn shiftOp( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, lhs_node: ast.Node.Index, rhs_node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { const lhs = try expr(gz, scope, .none, lhs_node); const log2_int_type = try gz.addUnNode(.typeof_log2_int_type, lhs, lhs_node); const rhs = try expr(gz, scope, .{ .ty = log2_int_type }, rhs_node); const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs, }); return rvalue(gz, rl, result, node); } fn cImport( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, body_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; var block_scope = gz.makeSubBlock(scope); block_scope.force_comptime = true; defer block_scope.instructions.deinit(gpa); const block_inst = try gz.addBlock(.c_import, node); const block_result = try expr(&block_scope, &block_scope.base, .none, body_node); if (!gz.refIsNoReturn(block_result)) { _ = try block_scope.addBreak(.break_inline, block_inst, .void_value); } try block_scope.setBlockBody(block_inst); try gz.instructions.append(gpa, block_inst); return rvalue(gz, rl, .void_value, node); } fn overflowArithmetic( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, params: []const ast.Node.Index, tag: Zir.Inst.Extended, ) InnerError!Zir.Inst.Ref { const int_type = try typeExpr(gz, scope, params[0]); const ptr_type = try gz.add(.{ .tag = .ptr_type_simple, .data = .{ .ptr_type_simple = .{ .is_allowzero = false, .is_mutable = true, .is_volatile = false, .size = .One, .elem_type = int_type, }, } }); const lhs = try expr(gz, scope, .{ .ty = int_type }, params[1]); const rhs = try expr(gz, scope, .{ .ty = int_type }, params[2]); const ptr = try expr(gz, scope, .{ .ty = ptr_type }, params[3]); const result = try gz.addExtendedPayload(tag, Zir.Inst.OverflowArithmetic{ .node = gz.nodeIndexToRelative(node), .lhs = lhs, .rhs = rhs, .ptr = ptr, }); return rvalue(gz, rl, result, node); } fn callExpr( gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index, call: ast.full.Call, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const lhs = try expr(gz, scope, .none, call.ast.fn_expr); const args = try astgen.gpa.alloc(Zir.Inst.Ref, call.ast.params.len); defer astgen.gpa.free(args); for (call.ast.params) |param_node, i| { const param_type = try gz.add(.{ .tag = .param_type, .data = .{ .param_type = .{ .callee = lhs, .param_index = @intCast(u32, i), } }, }); args[i] = try expr(gz, scope, .{ .coerced_ty = param_type }, param_node); } const modifier: std.builtin.CallOptions.Modifier = blk: { if (gz.force_comptime) { break :blk .compile_time; } if (call.async_token != null) { break :blk .async_kw; } if (gz.nosuspend_node != 0) { break :blk .no_async; } break :blk .auto; }; const result: Zir.Inst.Ref = res: { const tag: Zir.Inst.Tag = switch (modifier) { .auto => .call, .async_kw => .call_async, .never_tail => unreachable, .never_inline => unreachable, .no_async => .call_nosuspend, .always_tail => unreachable, .always_inline => unreachable, .compile_time => .call_compile_time, }; break :res try gz.addCall(tag, lhs, args, node); }; return rvalue(gz, rl, result, node); // TODO function call with result location } pub const simple_types = std.ComptimeStringMap(Zir.Inst.Ref, .{ .{ "anyerror", .anyerror_type }, .{ "anyframe", .anyframe_type }, .{ "bool", .bool_type }, .{ "c_int", .c_int_type }, .{ "c_long", .c_long_type }, .{ "c_longdouble", .c_longdouble_type }, .{ "c_longlong", .c_longlong_type }, .{ "c_short", .c_short_type }, .{ "c_uint", .c_uint_type }, .{ "c_ulong", .c_ulong_type }, .{ "c_ulonglong", .c_ulonglong_type }, .{ "c_ushort", .c_ushort_type }, .{ "c_void", .c_void_type }, .{ "comptime_float", .comptime_float_type }, .{ "comptime_int", .comptime_int_type }, .{ "f128", .f128_type }, .{ "f16", .f16_type }, .{ "f32", .f32_type }, .{ "f64", .f64_type }, .{ "false", .bool_false }, .{ "i16", .i16_type }, .{ "i32", .i32_type }, .{ "i64", .i64_type }, .{ "i128", .i128_type }, .{ "i8", .i8_type }, .{ "isize", .isize_type }, .{ "noreturn", .noreturn_type }, .{ "null", .null_value }, .{ "true", .bool_true }, .{ "type", .type_type }, .{ "u16", .u16_type }, .{ "u32", .u32_type }, .{ "u64", .u64_type }, .{ "u128", .u128_type }, .{ "u1", .u1_type }, .{ "u8", .u8_type }, .{ "undefined", .undef }, .{ "usize", .usize_type }, .{ "void", .void_type }, }); fn nodeMayNeedMemoryLocation(tree: *const ast.Tree, start_node: ast.Node.Index) bool { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); var node = start_node; while (true) { switch (node_tags[node]) { .root, .@"usingnamespace", .test_decl, .switch_case, .switch_case_one, .container_field_init, .container_field_align, .container_field, .asm_output, .asm_input, => unreachable, .@"return", .@"break", .@"continue", .bit_not, .bool_not, .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl, .@"defer", .@"errdefer", .address_of, .optional_type, .negation, .negation_wrap, .@"resume", .array_type, .array_type_sentinel, .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .@"suspend", .@"anytype", .fn_proto_simple, .fn_proto_multi, .fn_proto_one, .fn_proto, .fn_decl, .anyframe_type, .anyframe_literal, .integer_literal, .float_literal, .enum_literal, .string_literal, .multiline_string_literal, .char_literal, .unreachable_literal, .identifier, .error_set_decl, .container_decl, .container_decl_trailing, .container_decl_two, .container_decl_two_trailing, .container_decl_arg, .container_decl_arg_trailing, .tagged_union, .tagged_union_trailing, .tagged_union_two, .tagged_union_two_trailing, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, .@"asm", .asm_simple, .add, .add_wrap, .array_cat, .array_mult, .assign, .assign_bit_and, .assign_bit_or, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_xor, .assign_div, .assign_sub, .assign_sub_wrap, .assign_mod, .assign_add, .assign_add_wrap, .assign_mul, .assign_mul_wrap, .bang_equal, .bit_and, .bit_or, .bit_shift_left, .bit_shift_right, .bit_xor, .bool_and, .bool_or, .div, .equal_equal, .error_union, .greater_or_equal, .greater_than, .less_or_equal, .less_than, .merge_error_sets, .mod, .mul, .mul_wrap, .switch_range, .field_access, .sub, .sub_wrap, .slice, .slice_open, .slice_sentinel, .deref, .array_access, .error_value, .while_simple, // This variant cannot have an else expression. .while_cont, // This variant cannot have an else expression. .for_simple, // This variant cannot have an else expression. .if_simple, // This variant cannot have an else expression. => return false, // Forward the question to the LHS sub-expression. .grouped_expression, .@"try", .@"await", .@"comptime", .@"nosuspend", .unwrap_optional, => node = node_datas[node].lhs, // Forward the question to the RHS sub-expression. .@"catch", .@"orelse", => node = node_datas[node].rhs, // True because these are exactly the expressions we need memory locations for. .array_init_one, .array_init_one_comma, .array_init_dot_two, .array_init_dot_two_comma, .array_init_dot, .array_init_dot_comma, .array_init, .array_init_comma, .struct_init_one, .struct_init_one_comma, .struct_init_dot_two, .struct_init_dot_two_comma, .struct_init_dot, .struct_init_dot_comma, .struct_init, .struct_init_comma, => return true, // True because depending on comptime conditions, sub-expressions // may be the kind that need memory locations. .@"while", // This variant always has an else expression. .@"if", // This variant always has an else expression. .@"for", // This variant always has an else expression. .@"switch", .switch_comma, .call_one, .call_one_comma, .async_call_one, .async_call_one_comma, .call, .call_comma, .async_call, .async_call_comma, => return true, .block_two, .block_two_semicolon, .block, .block_semicolon, => { const lbrace = main_tokens[node]; if (token_tags[lbrace - 1] == .colon) { // Labeled blocks may need a memory location to forward // to their break statements. return true; } else { return false; } }, .builtin_call, .builtin_call_comma, .builtin_call_two, .builtin_call_two_comma, => { const builtin_token = main_tokens[node]; const builtin_name = tree.tokenSlice(builtin_token); // If the builtin is an invalid name, we don't cause an error here; instead // let it pass, and the error will be "invalid builtin function" later. const builtin_info = BuiltinFn.list.get(builtin_name) orelse return false; return builtin_info.needs_mem_loc; }, } } } fn nodeMayEvalToError(tree: *const ast.Tree, start_node: ast.Node.Index) enum { never, always, maybe } { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); var node = start_node; while (true) { switch (node_tags[node]) { .root, .@"usingnamespace", .test_decl, .switch_case, .switch_case_one, .container_field_init, .container_field_align, .container_field, .asm_output, .asm_input, => unreachable, .error_value => return .always, .@"asm", .asm_simple, .identifier, .field_access, .deref, .array_access, .while_simple, .while_cont, .for_simple, .if_simple, .@"while", .@"if", .@"for", .@"switch", .switch_comma, .call_one, .call_one_comma, .async_call_one, .async_call_one_comma, .call, .call_comma, .async_call, .async_call_comma, => return .maybe, .@"return", .@"break", .@"continue", .bit_not, .bool_not, .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl, .@"defer", .@"errdefer", .address_of, .optional_type, .negation, .negation_wrap, .@"resume", .array_type, .array_type_sentinel, .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .@"suspend", .@"anytype", .fn_proto_simple, .fn_proto_multi, .fn_proto_one, .fn_proto, .fn_decl, .anyframe_type, .anyframe_literal, .integer_literal, .float_literal, .enum_literal, .string_literal, .multiline_string_literal, .char_literal, .unreachable_literal, .error_set_decl, .container_decl, .container_decl_trailing, .container_decl_two, .container_decl_two_trailing, .container_decl_arg, .container_decl_arg_trailing, .tagged_union, .tagged_union_trailing, .tagged_union_two, .tagged_union_two_trailing, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, .add, .add_wrap, .array_cat, .array_mult, .assign, .assign_bit_and, .assign_bit_or, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_xor, .assign_div, .assign_sub, .assign_sub_wrap, .assign_mod, .assign_add, .assign_add_wrap, .assign_mul, .assign_mul_wrap, .bang_equal, .bit_and, .bit_or, .bit_shift_left, .bit_shift_right, .bit_xor, .bool_and, .bool_or, .div, .equal_equal, .error_union, .greater_or_equal, .greater_than, .less_or_equal, .less_than, .merge_error_sets, .mod, .mul, .mul_wrap, .switch_range, .sub, .sub_wrap, .slice, .slice_open, .slice_sentinel, .array_init_one, .array_init_one_comma, .array_init_dot_two, .array_init_dot_two_comma, .array_init_dot, .array_init_dot_comma, .array_init, .array_init_comma, .struct_init_one, .struct_init_one_comma, .struct_init_dot_two, .struct_init_dot_two_comma, .struct_init_dot, .struct_init_dot_comma, .struct_init, .struct_init_comma, => return .never, // Forward the question to the LHS sub-expression. .grouped_expression, .@"try", .@"await", .@"comptime", .@"nosuspend", .unwrap_optional, => node = node_datas[node].lhs, // Forward the question to the RHS sub-expression. .@"catch", .@"orelse", => node = node_datas[node].rhs, .block_two, .block_two_semicolon, .block, .block_semicolon, => { const lbrace = main_tokens[node]; if (token_tags[lbrace - 1] == .colon) { // Labeled blocks may need a memory location to forward // to their break statements. return .maybe; } else { return .never; } }, .builtin_call, .builtin_call_comma, .builtin_call_two, .builtin_call_two_comma, => { const builtin_token = main_tokens[node]; const builtin_name = tree.tokenSlice(builtin_token); // If the builtin is an invalid name, we don't cause an error here; instead // let it pass, and the error will be "invalid builtin function" later. const builtin_info = BuiltinFn.list.get(builtin_name) orelse return .maybe; if (builtin_info.tag == .err_set_cast) { return .always; } else { return .never; } }, } } } fn nodeImpliesRuntimeBits(tree: *const ast.Tree, start_node: ast.Node.Index) bool { const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); var node = start_node; while (true) { switch (node_tags[node]) { .root, .@"usingnamespace", .test_decl, .switch_case, .switch_case_one, .container_field_init, .container_field_align, .container_field, .asm_output, .asm_input, .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl, => unreachable, .@"return", .@"break", .@"continue", .bit_not, .bool_not, .@"defer", .@"errdefer", .address_of, .negation, .negation_wrap, .@"resume", .array_type, .@"suspend", .@"anytype", .fn_decl, .anyframe_literal, .integer_literal, .float_literal, .enum_literal, .string_literal, .multiline_string_literal, .char_literal, .unreachable_literal, .identifier, .error_set_decl, .container_decl, .container_decl_trailing, .container_decl_two, .container_decl_two_trailing, .container_decl_arg, .container_decl_arg_trailing, .tagged_union, .tagged_union_trailing, .tagged_union_two, .tagged_union_two_trailing, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, .@"asm", .asm_simple, .add, .add_wrap, .array_cat, .array_mult, .assign, .assign_bit_and, .assign_bit_or, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_xor, .assign_div, .assign_sub, .assign_sub_wrap, .assign_mod, .assign_add, .assign_add_wrap, .assign_mul, .assign_mul_wrap, .bang_equal, .bit_and, .bit_or, .bit_shift_left, .bit_shift_right, .bit_xor, .bool_and, .bool_or, .div, .equal_equal, .error_union, .greater_or_equal, .greater_than, .less_or_equal, .less_than, .merge_error_sets, .mod, .mul, .mul_wrap, .switch_range, .field_access, .sub, .sub_wrap, .slice, .slice_open, .slice_sentinel, .deref, .array_access, .error_value, .while_simple, .while_cont, .for_simple, .if_simple, .@"catch", .@"orelse", .array_init_one, .array_init_one_comma, .array_init_dot_two, .array_init_dot_two_comma, .array_init_dot, .array_init_dot_comma, .array_init, .array_init_comma, .struct_init_one, .struct_init_one_comma, .struct_init_dot_two, .struct_init_dot_two_comma, .struct_init_dot, .struct_init_dot_comma, .struct_init, .struct_init_comma, .@"while", .@"if", .@"for", .@"switch", .switch_comma, .call_one, .call_one_comma, .async_call_one, .async_call_one_comma, .call, .call_comma, .async_call, .async_call_comma, .block_two, .block_two_semicolon, .block, .block_semicolon, .builtin_call, .builtin_call_comma, .builtin_call_two, .builtin_call_two_comma, => return false, // Forward the question to the LHS sub-expression. .grouped_expression, .@"try", .@"await", .@"comptime", .@"nosuspend", .unwrap_optional, => node = node_datas[node].lhs, .fn_proto_simple, .fn_proto_multi, .fn_proto_one, .fn_proto, .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .optional_type, .anyframe_type, .array_type_sentinel, => return true, } } } /// Applies `rl` semantics to `result`. Expressions which do not do their own handling of /// result locations must call this function on their result. /// As an example, if the `ResultLoc` is `ptr`, it will write the result to the pointer. /// If the `ResultLoc` is `ty`, it will coerce the result to the type. fn rvalue( gz: *GenZir, rl: ResultLoc, result: Zir.Inst.Ref, src_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { if (gz.endsWithNoReturn()) return result; switch (rl) { .none, .none_or_ref, .coerced_ty => return result, .discard => { // Emit a compile error for discarding error values. _ = try gz.addUnNode(.ensure_result_non_error, result, src_node); return result; }, .ref => { // We need a pointer but we have a value. const tree = gz.astgen.tree; const src_token = tree.firstToken(src_node); return gz.addUnTok(.ref, result, src_token); }, .ty => |ty_inst| { // Quickly eliminate some common, unnecessary type coercion. const as_ty = @as(u64, @enumToInt(Zir.Inst.Ref.type_type)) << 32; const as_comptime_int = @as(u64, @enumToInt(Zir.Inst.Ref.comptime_int_type)) << 32; const as_bool = @as(u64, @enumToInt(Zir.Inst.Ref.bool_type)) << 32; const as_usize = @as(u64, @enumToInt(Zir.Inst.Ref.usize_type)) << 32; const as_void = @as(u64, @enumToInt(Zir.Inst.Ref.void_type)) << 32; switch ((@as(u64, @enumToInt(ty_inst)) << 32) | @as(u64, @enumToInt(result))) { as_ty | @enumToInt(Zir.Inst.Ref.u1_type), as_ty | @enumToInt(Zir.Inst.Ref.u8_type), as_ty | @enumToInt(Zir.Inst.Ref.i8_type), as_ty | @enumToInt(Zir.Inst.Ref.u16_type), as_ty | @enumToInt(Zir.Inst.Ref.i16_type), as_ty | @enumToInt(Zir.Inst.Ref.u32_type), as_ty | @enumToInt(Zir.Inst.Ref.i32_type), as_ty | @enumToInt(Zir.Inst.Ref.u64_type), as_ty | @enumToInt(Zir.Inst.Ref.i64_type), as_ty | @enumToInt(Zir.Inst.Ref.usize_type), as_ty | @enumToInt(Zir.Inst.Ref.isize_type), as_ty | @enumToInt(Zir.Inst.Ref.c_short_type), as_ty | @enumToInt(Zir.Inst.Ref.c_ushort_type), as_ty | @enumToInt(Zir.Inst.Ref.c_int_type), as_ty | @enumToInt(Zir.Inst.Ref.c_uint_type), as_ty | @enumToInt(Zir.Inst.Ref.c_long_type), as_ty | @enumToInt(Zir.Inst.Ref.c_ulong_type), as_ty | @enumToInt(Zir.Inst.Ref.c_longlong_type), as_ty | @enumToInt(Zir.Inst.Ref.c_ulonglong_type), as_ty | @enumToInt(Zir.Inst.Ref.c_longdouble_type), as_ty | @enumToInt(Zir.Inst.Ref.f16_type), as_ty | @enumToInt(Zir.Inst.Ref.f32_type), as_ty | @enumToInt(Zir.Inst.Ref.f64_type), as_ty | @enumToInt(Zir.Inst.Ref.f128_type), as_ty | @enumToInt(Zir.Inst.Ref.c_void_type), as_ty | @enumToInt(Zir.Inst.Ref.bool_type), as_ty | @enumToInt(Zir.Inst.Ref.void_type), as_ty | @enumToInt(Zir.Inst.Ref.type_type), as_ty | @enumToInt(Zir.Inst.Ref.anyerror_type), as_ty | @enumToInt(Zir.Inst.Ref.comptime_int_type), as_ty | @enumToInt(Zir.Inst.Ref.comptime_float_type), as_ty | @enumToInt(Zir.Inst.Ref.noreturn_type), as_ty | @enumToInt(Zir.Inst.Ref.null_type), as_ty | @enumToInt(Zir.Inst.Ref.undefined_type), as_ty | @enumToInt(Zir.Inst.Ref.fn_noreturn_no_args_type), as_ty | @enumToInt(Zir.Inst.Ref.fn_void_no_args_type), as_ty | @enumToInt(Zir.Inst.Ref.fn_naked_noreturn_no_args_type), as_ty | @enumToInt(Zir.Inst.Ref.fn_ccc_void_no_args_type), as_ty | @enumToInt(Zir.Inst.Ref.single_const_pointer_to_comptime_int_type), as_ty | @enumToInt(Zir.Inst.Ref.const_slice_u8_type), as_ty | @enumToInt(Zir.Inst.Ref.enum_literal_type), as_comptime_int | @enumToInt(Zir.Inst.Ref.zero), as_comptime_int | @enumToInt(Zir.Inst.Ref.one), as_bool | @enumToInt(Zir.Inst.Ref.bool_true), as_bool | @enumToInt(Zir.Inst.Ref.bool_false), as_usize | @enumToInt(Zir.Inst.Ref.zero_usize), as_usize | @enumToInt(Zir.Inst.Ref.one_usize), as_void | @enumToInt(Zir.Inst.Ref.void_value), => return result, // type of result is already correct // Need an explicit type coercion instruction. else => return gz.addPlNode(.as_node, src_node, Zir.Inst.As{ .dest_type = ty_inst, .operand = result, }), } }, .ptr => |ptr_inst| { _ = try gz.addPlNode(.store_node, src_node, Zir.Inst.Bin{ .lhs = ptr_inst, .rhs = result, }); return result; }, .inferred_ptr => |alloc| { _ = try gz.addBin(.store_to_inferred_ptr, alloc, result); return result; }, .block_ptr => |block_scope| { block_scope.rvalue_rl_count += 1; _ = try gz.addBin(.store_to_block_ptr, block_scope.rl_ptr, result); return result; }, } } /// Given an identifier token, obtain the string for it. /// If the token uses @"" syntax, parses as a string, reports errors if applicable, /// and allocates the result within `astgen.arena`. /// Otherwise, returns a reference to the source code bytes directly. /// See also `appendIdentStr` and `parseStrLit`. fn identifierTokenString(astgen: *AstGen, token: ast.TokenIndex) InnerError![]const u8 { const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); assert(token_tags[token] == .identifier); const ident_name = tree.tokenSlice(token); if (!mem.startsWith(u8, ident_name, "@")) { return ident_name; } var buf: ArrayListUnmanaged(u8) = .{}; defer buf.deinit(astgen.gpa); try astgen.parseStrLit(token, &buf, ident_name, 1); const duped = try astgen.arena.dupe(u8, buf.items); return duped; } /// Given an identifier token, obtain the string for it (possibly parsing as a string /// literal if it is @"" syntax), and append the string to `buf`. /// See also `identifierTokenString` and `parseStrLit`. fn appendIdentStr( astgen: *AstGen, token: ast.TokenIndex, buf: *ArrayListUnmanaged(u8), ) InnerError!void { const tree = astgen.tree; const token_tags = tree.tokens.items(.tag); assert(token_tags[token] == .identifier); const ident_name = tree.tokenSlice(token); if (!mem.startsWith(u8, ident_name, "@")) { return buf.appendSlice(astgen.gpa, ident_name); } else { return astgen.parseStrLit(token, buf, ident_name, 1); } } /// Appends the result to `buf`. fn parseStrLit( astgen: *AstGen, token: ast.TokenIndex, buf: *ArrayListUnmanaged(u8), bytes: []const u8, offset: u32, ) InnerError!void { const raw_string = bytes[offset..]; var buf_managed = buf.toManaged(astgen.gpa); const result = std.zig.string_literal.parseAppend(&buf_managed, raw_string); buf.* = buf_managed.toUnmanaged(); switch (try result) { .success => return, .invalid_character => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "invalid string literal character: '{c}'", .{raw_string[bad_index]}, ); }, .expected_hex_digits => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "expected hex digits after '\\x'", .{}, ); }, .invalid_hex_escape => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "invalid hex digit: '{c}'", .{raw_string[bad_index]}, ); }, .invalid_unicode_escape => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "invalid unicode digit: '{c}'", .{raw_string[bad_index]}, ); }, .missing_matching_rbrace => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "missing matching '}}' character", .{}, ); }, .expected_unicode_digits => |bad_index| { return astgen.failOff( token, offset + @intCast(u32, bad_index), "expected unicode digits after '\\u'", .{}, ); }, } } fn failNode( astgen: *AstGen, node: ast.Node.Index, comptime format: []const u8, args: anytype, ) InnerError { return astgen.failNodeNotes(node, format, args, &[0]u32{}); } fn failNodeNotes( astgen: *AstGen, node: ast.Node.Index, comptime format: []const u8, args: anytype, notes: []const u32, ) InnerError { @setCold(true); const string_bytes = &astgen.string_bytes; const msg = @intCast(u32, string_bytes.items.len); { var managed = string_bytes.toManaged(astgen.gpa); defer string_bytes.* = managed.toUnmanaged(); try managed.writer().print(format ++ "\x00", args); } const notes_index: u32 = if (notes.len != 0) blk: { const notes_start = astgen.extra.items.len; try astgen.extra.ensureTotalCapacity(astgen.gpa, notes_start + 1 + notes.len); astgen.extra.appendAssumeCapacity(@intCast(u32, notes.len)); astgen.extra.appendSliceAssumeCapacity(notes); break :blk @intCast(u32, notes_start); } else 0; try astgen.compile_errors.append(astgen.gpa, .{ .msg = msg, .node = node, .token = 0, .byte_offset = 0, .notes = notes_index, }); return error.AnalysisFail; } fn failTok( astgen: *AstGen, token: ast.TokenIndex, comptime format: []const u8, args: anytype, ) InnerError { return astgen.failTokNotes(token, format, args, &[0]u32{}); } fn failTokNotes( astgen: *AstGen, token: ast.TokenIndex, comptime format: []const u8, args: anytype, notes: []const u32, ) InnerError { @setCold(true); const string_bytes = &astgen.string_bytes; const msg = @intCast(u32, string_bytes.items.len); { var managed = string_bytes.toManaged(astgen.gpa); defer string_bytes.* = managed.toUnmanaged(); try managed.writer().print(format ++ "\x00", args); } const notes_index: u32 = if (notes.len != 0) blk: { const notes_start = astgen.extra.items.len; try astgen.extra.ensureTotalCapacity(astgen.gpa, notes_start + 1 + notes.len); astgen.extra.appendAssumeCapacity(@intCast(u32, notes.len)); astgen.extra.appendSliceAssumeCapacity(notes); break :blk @intCast(u32, notes_start); } else 0; try astgen.compile_errors.append(astgen.gpa, .{ .msg = msg, .node = 0, .token = token, .byte_offset = 0, .notes = notes_index, }); return error.AnalysisFail; } /// Same as `fail`, except given an absolute byte offset. fn failOff( astgen: *AstGen, token: ast.TokenIndex, byte_offset: u32, comptime format: []const u8, args: anytype, ) InnerError { @setCold(true); const string_bytes = &astgen.string_bytes; const msg = @intCast(u32, string_bytes.items.len); { var managed = string_bytes.toManaged(astgen.gpa); defer string_bytes.* = managed.toUnmanaged(); try managed.writer().print(format ++ "\x00", args); } try astgen.compile_errors.append(astgen.gpa, .{ .msg = msg, .node = 0, .token = token, .byte_offset = byte_offset, .notes = 0, }); return error.AnalysisFail; } fn errNoteTok( astgen: *AstGen, token: ast.TokenIndex, comptime format: []const u8, args: anytype, ) Allocator.Error!u32 { @setCold(true); const string_bytes = &astgen.string_bytes; const msg = @intCast(u32, string_bytes.items.len); { var managed = string_bytes.toManaged(astgen.gpa); defer string_bytes.* = managed.toUnmanaged(); try managed.writer().print(format ++ "\x00", args); } return astgen.addExtra(Zir.Inst.CompileErrors.Item{ .msg = msg, .node = 0, .token = token, .byte_offset = 0, .notes = 0, }); } fn errNoteNode( astgen: *AstGen, node: ast.Node.Index, comptime format: []const u8, args: anytype, ) Allocator.Error!u32 { @setCold(true); const string_bytes = &astgen.string_bytes; const msg = @intCast(u32, string_bytes.items.len); { var managed = string_bytes.toManaged(astgen.gpa); defer string_bytes.* = managed.toUnmanaged(); try managed.writer().print(format ++ "\x00", args); } return astgen.addExtra(Zir.Inst.CompileErrors.Item{ .msg = msg, .node = node, .token = 0, .byte_offset = 0, .notes = 0, }); } fn identAsString(astgen: *AstGen, ident_token: ast.TokenIndex) !u32 { const gpa = astgen.gpa; const string_bytes = &astgen.string_bytes; const str_index = @intCast(u32, string_bytes.items.len); try astgen.appendIdentStr(ident_token, string_bytes); const key = string_bytes.items[str_index..]; const gop = try astgen.string_table.getOrPut(gpa, key); if (gop.found_existing) { string_bytes.shrinkRetainingCapacity(str_index); return gop.value_ptr.*; } else { // We have to dupe the key into the arena, otherwise the memory // becomes invalidated when string_bytes gets data appended. // TODO https://github.com/ziglang/zig/issues/8528 gop.key_ptr.* = try astgen.arena.dupe(u8, key); gop.value_ptr.* = str_index; try string_bytes.append(gpa, 0); return str_index; } } const IndexSlice = struct { index: u32, len: u32 }; fn strLitAsString(astgen: *AstGen, str_lit_token: ast.TokenIndex) !IndexSlice { const gpa = astgen.gpa; const string_bytes = &astgen.string_bytes; const str_index = @intCast(u32, string_bytes.items.len); const token_bytes = astgen.tree.tokenSlice(str_lit_token); try astgen.parseStrLit(str_lit_token, string_bytes, token_bytes, 0); const key = string_bytes.items[str_index..]; const gop = try astgen.string_table.getOrPut(gpa, key); if (gop.found_existing) { string_bytes.shrinkRetainingCapacity(str_index); return IndexSlice{ .index = gop.value_ptr.*, .len = @intCast(u32, key.len), }; } else { // We have to dupe the key into the arena, otherwise the memory // becomes invalidated when string_bytes gets data appended. // TODO https://github.com/ziglang/zig/issues/8528 gop.key_ptr.* = try astgen.arena.dupe(u8, key); gop.value_ptr.* = str_index; // Still need a null byte because we are using the same table // to lookup null terminated strings, so if we get a match, it has to // be null terminated for that to work. try string_bytes.append(gpa, 0); return IndexSlice{ .index = str_index, .len = @intCast(u32, key.len), }; } } fn strLitNodeAsString(astgen: *AstGen, node: ast.Node.Index) !IndexSlice { const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const start = node_datas[node].lhs; const end = node_datas[node].rhs; const gpa = astgen.gpa; const string_bytes = &astgen.string_bytes; const str_index = string_bytes.items.len; // First line: do not append a newline. var tok_i = start; { const slice = tree.tokenSlice(tok_i); const line_bytes = slice[2 .. slice.len - 1]; try string_bytes.appendSlice(gpa, line_bytes); tok_i += 1; } // Following lines: each line prepends a newline. while (tok_i <= end) : (tok_i += 1) { const slice = tree.tokenSlice(tok_i); const line_bytes = slice[2 .. slice.len - 1]; try string_bytes.ensureUnusedCapacity(gpa, line_bytes.len + 1); string_bytes.appendAssumeCapacity('\n'); string_bytes.appendSliceAssumeCapacity(line_bytes); } const len = string_bytes.items.len - str_index; try string_bytes.append(gpa, 0); return IndexSlice{ .index = @intCast(u32, str_index), .len = @intCast(u32, len), }; } fn testNameString(astgen: *AstGen, str_lit_token: ast.TokenIndex) !u32 { const gpa = astgen.gpa; const string_bytes = &astgen.string_bytes; const str_index = @intCast(u32, string_bytes.items.len); const token_bytes = astgen.tree.tokenSlice(str_lit_token); try string_bytes.append(gpa, 0); // Indicates this is a test. try astgen.parseStrLit(str_lit_token, string_bytes, token_bytes, 0); try string_bytes.append(gpa, 0); return str_index; } const Scope = struct { tag: Tag, fn cast(base: *Scope, comptime T: type) ?*T { if (T == Defer) { switch (base.tag) { .defer_normal, .defer_error => return @fieldParentPtr(T, "base", base), else => return null, } } if (base.tag != T.base_tag) return null; return @fieldParentPtr(T, "base", base); } const Tag = enum { gen_zir, local_val, local_ptr, defer_normal, defer_error, namespace, top, }; /// The category of identifier. These tag names are user-visible in compile errors. const IdCat = enum { @"function parameter", @"local constant", @"local variable", @"loop index capture", @"capture", }; /// This is always a `const` local and importantly the `inst` is a value type, not a pointer. /// This structure lives as long as the AST generation of the Block /// node that contains the variable. const LocalVal = struct { const base_tag: Tag = .local_val; base: Scope = Scope{ .tag = base_tag }, /// Parents can be: `LocalVal`, `LocalPtr`, `GenZir`, `Defer`. parent: *Scope, gen_zir: *GenZir, inst: Zir.Inst.Ref, /// Source location of the corresponding variable declaration. token_src: ast.TokenIndex, /// String table index. name: u32, id_cat: IdCat, /// Track whether the name has been referenced. used: bool = false, }; /// This could be a `const` or `var` local. It has a pointer instead of a value. /// This structure lives as long as the AST generation of the Block /// node that contains the variable. const LocalPtr = struct { const base_tag: Tag = .local_ptr; base: Scope = Scope{ .tag = base_tag }, /// Parents can be: `LocalVal`, `LocalPtr`, `GenZir`, `Defer`. parent: *Scope, gen_zir: *GenZir, ptr: Zir.Inst.Ref, /// Source location of the corresponding variable declaration. token_src: ast.TokenIndex, /// String table index. name: u32, id_cat: IdCat, /// true means we find out during Sema whether the value is comptime. /// false means it is already known at AstGen the value is runtime-known. maybe_comptime: bool, /// Track whether the name has been referenced. used: bool = false, }; const Defer = struct { base: Scope, /// Parents can be: `LocalVal`, `LocalPtr`, `GenZir`, `Defer`. parent: *Scope, defer_node: ast.Node.Index, }; /// Represents a global scope that has any number of declarations in it. /// Each declaration has this as the parent scope. const Namespace = struct { const base_tag: Tag = .namespace; base: Scope = Scope{ .tag = base_tag }, parent: *Scope, /// Maps string table index to the source location of declaration, /// for the purposes of reporting name shadowing compile errors. decls: std.AutoHashMapUnmanaged(u32, ast.Node.Index) = .{}, node: ast.Node.Index, }; const Top = struct { const base_tag: Scope.Tag = .top; base: Scope = Scope{ .tag = base_tag }, }; }; /// This is a temporary structure; references to it are valid only /// while constructing a `Zir`. const GenZir = struct { const base_tag: Scope.Tag = .gen_zir; base: Scope = Scope{ .tag = base_tag }, force_comptime: bool, in_defer: bool, /// How decls created in this scope should be named. anon_name_strategy: Zir.Inst.NameStrategy = .anon, /// The containing decl AST node. decl_node_index: ast.Node.Index, /// The containing decl line index, absolute. decl_line: u32, parent: *Scope, /// All `GenZir` scopes for the same ZIR share this. astgen: *AstGen, /// Keeps track of the list of instructions in this scope only. Indexes /// to instructions in `astgen`. instructions: ArrayListUnmanaged(Zir.Inst.Index) = .{}, label: ?Label = null, break_block: Zir.Inst.Index = 0, continue_block: Zir.Inst.Index = 0, /// Only valid when setBreakResultLoc is called. break_result_loc: AstGen.ResultLoc = undefined, /// When a block has a pointer result location, here it is. rl_ptr: Zir.Inst.Ref = .none, /// When a block has a type result location, here it is. rl_ty_inst: Zir.Inst.Ref = .none, /// Keeps track of how many branches of a block did not actually /// consume the result location. astgen uses this to figure out /// whether to rely on break instructions or writing to the result /// pointer for the result instruction. rvalue_rl_count: usize = 0, /// Keeps track of how many break instructions there are. When astgen is finished /// with a block, it can check this against rvalue_rl_count to find out whether /// the break instructions should be downgraded to break_void. break_count: usize = 0, /// Tracks `break :foo bar` instructions so they can possibly be elided later if /// the labeled block ends up not needing a result location pointer. labeled_breaks: ArrayListUnmanaged(Zir.Inst.Index) = .{}, /// Tracks `store_to_block_ptr` instructions that correspond to break instructions /// so they can possibly be elided later if the labeled block ends up not needing /// a result location pointer. labeled_store_to_block_ptr_list: ArrayListUnmanaged(Zir.Inst.Index) = .{}, suspend_node: ast.Node.Index = 0, nosuspend_node: ast.Node.Index = 0, fn makeSubBlock(gz: *GenZir, scope: *Scope) GenZir { return .{ .force_comptime = gz.force_comptime, .in_defer = gz.in_defer, .decl_node_index = gz.decl_node_index, .decl_line = gz.decl_line, .parent = scope, .astgen = gz.astgen, .suspend_node = gz.suspend_node, .nosuspend_node = gz.nosuspend_node, }; } const Label = struct { token: ast.TokenIndex, block_inst: Zir.Inst.Index, used: bool = false, }; fn endsWithNoReturn(gz: GenZir) bool { const tags = gz.astgen.instructions.items(.tag); if (gz.instructions.items.len == 0) return false; const last_inst = gz.instructions.items[gz.instructions.items.len - 1]; return tags[last_inst].isNoReturn(); } /// TODO all uses of this should be replaced with uses of `endsWithNoReturn`. fn refIsNoReturn(gz: GenZir, inst_ref: Zir.Inst.Ref) bool { if (inst_ref == .unreachable_value) return true; if (refToIndex(inst_ref)) |inst_index| { return gz.astgen.instructions.items(.tag)[inst_index].isNoReturn(); } return false; } fn calcLine(gz: GenZir, node: ast.Node.Index) u32 { const astgen = gz.astgen; const tree = astgen.tree; const source = tree.source; const token_starts = tree.tokens.items(.start); const node_start = token_starts[tree.firstToken(node)]; astgen.advanceSourceCursor(source, node_start); return @intCast(u32, gz.decl_line + astgen.source_line); } fn tokSrcLoc(gz: GenZir, token_index: ast.TokenIndex) LazySrcLoc { return .{ .token_offset = token_index - gz.srcToken() }; } fn nodeSrcLoc(gz: GenZir, node_index: ast.Node.Index) LazySrcLoc { return .{ .node_offset = gz.nodeIndexToRelative(node_index) }; } fn nodeIndexToRelative(gz: GenZir, node_index: ast.Node.Index) i32 { return @bitCast(i32, node_index) - @bitCast(i32, gz.decl_node_index); } fn tokenIndexToRelative(gz: GenZir, token: ast.TokenIndex) u32 { return token - gz.srcToken(); } fn srcToken(gz: GenZir) ast.TokenIndex { return gz.astgen.tree.firstToken(gz.decl_node_index); } fn setBreakResultLoc(gz: *GenZir, parent_rl: AstGen.ResultLoc) void { // Depending on whether the result location is a pointer or value, different // ZIR needs to be generated. In the former case we rely on storing to the // pointer to communicate the result, and use breakvoid; in the latter case // the block break instructions will have the result values. // One more complication: when the result location is a pointer, we detect // the scenario where the result location is not consumed. In this case // we emit ZIR for the block break instructions to have the result values, // and then rvalue() on that to pass the value to the result location. switch (parent_rl) { .ty, .coerced_ty => |ty_inst| { gz.rl_ty_inst = ty_inst; gz.break_result_loc = parent_rl; }, .none_or_ref => { gz.break_result_loc = .ref; }, .discard, .none, .ptr, .ref => { gz.break_result_loc = parent_rl; }, .inferred_ptr => |ptr| { gz.rl_ptr = ptr; gz.break_result_loc = .{ .block_ptr = gz }; }, .block_ptr => |parent_block_scope| { gz.rl_ty_inst = parent_block_scope.rl_ty_inst; gz.rl_ptr = parent_block_scope.rl_ptr; gz.break_result_loc = .{ .block_ptr = gz }; }, } } fn setBoolBrBody(gz: GenZir, inst: Zir.Inst.Index) !void { const gpa = gz.astgen.gpa; try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Block).Struct.fields.len + gz.instructions.items.len); const zir_datas = gz.astgen.instructions.items(.data); zir_datas[inst].bool_br.payload_index = gz.astgen.addExtraAssumeCapacity( Zir.Inst.Block{ .body_len = @intCast(u32, gz.instructions.items.len) }, ); gz.astgen.extra.appendSliceAssumeCapacity(gz.instructions.items); } fn setBlockBody(gz: GenZir, inst: Zir.Inst.Index) !void { const gpa = gz.astgen.gpa; try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Block).Struct.fields.len + gz.instructions.items.len); const zir_datas = gz.astgen.instructions.items(.data); zir_datas[inst].pl_node.payload_index = gz.astgen.addExtraAssumeCapacity( Zir.Inst.Block{ .body_len = @intCast(u32, gz.instructions.items.len) }, ); gz.astgen.extra.appendSliceAssumeCapacity(gz.instructions.items); } /// Same as `setBlockBody` except we don't copy instructions which are /// `store_to_block_ptr` instructions with lhs set to .none. fn setBlockBodyEliding(gz: GenZir, inst: Zir.Inst.Index) !void { const gpa = gz.astgen.gpa; try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Block).Struct.fields.len + gz.instructions.items.len); const zir_datas = gz.astgen.instructions.items(.data); const zir_tags = gz.astgen.instructions.items(.tag); const block_pl_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Block{ .body_len = @intCast(u32, gz.instructions.items.len), }); zir_datas[inst].pl_node.payload_index = block_pl_index; for (gz.instructions.items) |sub_inst| { if (zir_tags[sub_inst] == .store_to_block_ptr and zir_datas[sub_inst].bin.lhs == .none) { // Decrement `body_len`. gz.astgen.extra.items[block_pl_index] -= 1; continue; } gz.astgen.extra.appendAssumeCapacity(sub_inst); } } fn addFunc(gz: *GenZir, args: struct { src_node: ast.Node.Index, body: []const Zir.Inst.Index, param_block: Zir.Inst.Index, ret_ty: []const Zir.Inst.Index, ret_br: Zir.Inst.Index, cc: Zir.Inst.Ref, align_inst: Zir.Inst.Ref, lib_name: u32, is_var_args: bool, is_inferred_error: bool, is_test: bool, is_extern: bool, }) !Zir.Inst.Ref { assert(args.src_node != 0); const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); var src_locs_buffer: [3]u32 = undefined; var src_locs: []u32 = src_locs_buffer[0..0]; if (args.body.len != 0) { const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const node_datas = tree.nodes.items(.data); const token_starts = tree.tokens.items(.start); const fn_decl = args.src_node; assert(node_tags[fn_decl] == .fn_decl or node_tags[fn_decl] == .test_decl); const block = node_datas[fn_decl].rhs; const lbrace_start = token_starts[tree.firstToken(block)]; const rbrace_start = token_starts[tree.lastToken(block)]; astgen.advanceSourceCursor(tree.source, lbrace_start); const lbrace_line = @intCast(u32, astgen.source_line); const lbrace_column = @intCast(u32, astgen.source_column); astgen.advanceSourceCursor(tree.source, rbrace_start); const rbrace_line = @intCast(u32, astgen.source_line); const rbrace_column = @intCast(u32, astgen.source_column); const columns = lbrace_column | (rbrace_column << 16); src_locs_buffer[0] = lbrace_line; src_locs_buffer[1] = rbrace_line; src_locs_buffer[2] = columns; src_locs = &src_locs_buffer; } if (args.cc != .none or args.lib_name != 0 or args.is_var_args or args.is_test or args.align_inst != .none or args.is_extern) { try astgen.extra.ensureUnusedCapacity( gpa, @typeInfo(Zir.Inst.ExtendedFunc).Struct.fields.len + args.ret_ty.len + args.body.len + src_locs.len + @boolToInt(args.lib_name != 0) + @boolToInt(args.align_inst != .none) + @boolToInt(args.cc != .none), ); const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.ExtendedFunc{ .src_node = gz.nodeIndexToRelative(args.src_node), .param_block = args.param_block, .ret_body_len = @intCast(u32, args.ret_ty.len), .body_len = @intCast(u32, args.body.len), }); if (args.lib_name != 0) { astgen.extra.appendAssumeCapacity(args.lib_name); } if (args.cc != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.cc)); } if (args.align_inst != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.align_inst)); } astgen.extra.appendSliceAssumeCapacity(args.ret_ty); astgen.extra.appendSliceAssumeCapacity(args.body); astgen.extra.appendSliceAssumeCapacity(src_locs); const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); if (args.ret_br != 0) { astgen.instructions.items(.data)[args.ret_br].@"break".block_inst = new_index; } astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = .func, .small = @bitCast(u16, Zir.Inst.ExtendedFunc.Small{ .is_var_args = args.is_var_args, .is_inferred_error = args.is_inferred_error, .has_lib_name = args.lib_name != 0, .has_cc = args.cc != .none, .has_align = args.align_inst != .none, .is_test = args.is_test, .is_extern = args.is_extern, }), .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } else { try astgen.extra.ensureUnusedCapacity( gpa, @typeInfo(Zir.Inst.Func).Struct.fields.len + args.ret_ty.len + args.body.len + src_locs.len, ); const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.Func{ .param_block = args.param_block, .ret_body_len = @intCast(u32, args.ret_ty.len), .body_len = @intCast(u32, args.body.len), }); astgen.extra.appendSliceAssumeCapacity(args.ret_ty); astgen.extra.appendSliceAssumeCapacity(args.body); astgen.extra.appendSliceAssumeCapacity(src_locs); const tag: Zir.Inst.Tag = if (args.is_inferred_error) .func_inferred else .func; const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); if (args.ret_br != 0) { astgen.instructions.items(.data)[args.ret_br].@"break".block_inst = new_index; } astgen.instructions.appendAssumeCapacity(.{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(args.src_node), .payload_index = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } } fn addVar(gz: *GenZir, args: struct { align_inst: Zir.Inst.Ref, lib_name: u32, var_type: Zir.Inst.Ref, init: Zir.Inst.Ref, is_extern: bool, is_threadlocal: bool, }) !Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); try astgen.extra.ensureUnusedCapacity( gpa, @typeInfo(Zir.Inst.ExtendedVar).Struct.fields.len + @boolToInt(args.lib_name != 0) + @boolToInt(args.align_inst != .none) + @boolToInt(args.init != .none), ); const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.ExtendedVar{ .var_type = args.var_type, }); if (args.lib_name != 0) { astgen.extra.appendAssumeCapacity(args.lib_name); } if (args.align_inst != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.align_inst)); } if (args.init != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.init)); } const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = .variable, .small = @bitCast(u16, Zir.Inst.ExtendedVar.Small{ .has_lib_name = args.lib_name != 0, .has_align = args.align_inst != .none, .has_init = args.init != .none, .is_extern = args.is_extern, .is_threadlocal = args.is_threadlocal, }), .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } fn addCall( gz: *GenZir, tag: Zir.Inst.Tag, callee: Zir.Inst.Ref, args: []const Zir.Inst.Ref, /// Absolute node index. This function does the conversion to offset from Decl. src_node: ast.Node.Index, ) !Zir.Inst.Ref { assert(callee != .none); assert(src_node != 0); const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Call).Struct.fields.len + args.len); const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Call{ .callee = callee, .args_len = @intCast(u32, args.len), }); gz.astgen.appendRefsAssumeCapacity(args); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(src_node), .payload_index = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } /// Note that this returns a `Zir.Inst.Index` not a ref. /// Leaves the `payload_index` field undefined. fn addBoolBr( gz: *GenZir, tag: Zir.Inst.Tag, lhs: Zir.Inst.Ref, ) !Zir.Inst.Index { assert(lhs != .none); const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = tag, .data = .{ .bool_br = .{ .lhs = lhs, .payload_index = undefined, } }, }); gz.instructions.appendAssumeCapacity(new_index); return new_index; } fn addInt(gz: *GenZir, integer: u64) !Zir.Inst.Ref { return gz.add(.{ .tag = .int, .data = .{ .int = integer }, }); } fn addIntBig(gz: *GenZir, limbs: []const std.math.big.Limb) !Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); try astgen.string_bytes.ensureUnusedCapacity(gpa, @sizeOf(std.math.big.Limb) * limbs.len); const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); astgen.instructions.appendAssumeCapacity(.{ .tag = .int_big, .data = .{ .str = .{ .start = @intCast(u32, astgen.string_bytes.items.len), .len = @intCast(u32, limbs.len), } }, }); gz.instructions.appendAssumeCapacity(new_index); astgen.string_bytes.appendSliceAssumeCapacity(mem.sliceAsBytes(limbs)); return indexToRef(new_index); } fn addFloat(gz: *GenZir, number: f64) !Zir.Inst.Ref { return gz.add(.{ .tag = .float, .data = .{ .float = number }, }); } fn addUnNode( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, /// Absolute node index. This function does the conversion to offset from Decl. src_node: ast.Node.Index, ) !Zir.Inst.Ref { assert(operand != .none); return gz.add(.{ .tag = tag, .data = .{ .un_node = .{ .operand = operand, .src_node = gz.nodeIndexToRelative(src_node), } }, }); } fn addPlNode( gz: *GenZir, tag: Zir.Inst.Tag, /// Absolute node index. This function does the conversion to offset from Decl. src_node: ast.Node.Index, extra: anytype, ) !Zir.Inst.Ref { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const payload_index = try gz.astgen.addExtra(extra); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(src_node), .payload_index = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } fn addParam( gz: *GenZir, tag: Zir.Inst.Tag, /// Absolute token index. This function does the conversion to Decl offset. abs_tok_index: ast.TokenIndex, name: u32, body: []const u32, ) !Zir.Inst.Index { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Param).Struct.fields.len + body.len); const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Param{ .name = name, .body_len = @intCast(u32, body.len), }); gz.astgen.extra.appendSliceAssumeCapacity(body); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = tag, .data = .{ .pl_tok = .{ .src_tok = gz.tokenIndexToRelative(abs_tok_index), .payload_index = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return new_index; } fn addExtendedPayload( gz: *GenZir, opcode: Zir.Inst.Extended, extra: anytype, ) !Zir.Inst.Ref { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const payload_index = try gz.astgen.addExtra(extra); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = opcode, .small = undefined, .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } fn addExtendedMultiOp( gz: *GenZir, opcode: Zir.Inst.Extended, node: ast.Node.Index, operands: []const Zir.Inst.Ref, ) !Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); try astgen.extra.ensureUnusedCapacity( gpa, @typeInfo(Zir.Inst.NodeMultiOp).Struct.fields.len + operands.len, ); const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.NodeMultiOp{ .src_node = gz.nodeIndexToRelative(node), }); const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = opcode, .small = @intCast(u16, operands.len), .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); astgen.appendRefsAssumeCapacity(operands); return indexToRef(new_index); } fn addArrayTypeSentinel( gz: *GenZir, len: Zir.Inst.Ref, sentinel: Zir.Inst.Ref, elem_type: Zir.Inst.Ref, ) !Zir.Inst.Ref { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const payload_index = try gz.astgen.addExtra(Zir.Inst.ArrayTypeSentinel{ .sentinel = sentinel, .elem_type = elem_type, }); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(.{ .tag = .array_type_sentinel, .data = .{ .array_type_sentinel = .{ .len = len, .payload_index = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } fn addUnTok( gz: *GenZir, tag: Zir.Inst.Tag, operand: Zir.Inst.Ref, /// Absolute token index. This function does the conversion to Decl offset. abs_tok_index: ast.TokenIndex, ) !Zir.Inst.Ref { assert(operand != .none); return gz.add(.{ .tag = tag, .data = .{ .un_tok = .{ .operand = operand, .src_tok = gz.tokenIndexToRelative(abs_tok_index), } }, }); } fn addStrTok( gz: *GenZir, tag: Zir.Inst.Tag, str_index: u32, /// Absolute token index. This function does the conversion to Decl offset. abs_tok_index: ast.TokenIndex, ) !Zir.Inst.Ref { return gz.add(.{ .tag = tag, .data = .{ .str_tok = .{ .start = str_index, .src_tok = gz.tokenIndexToRelative(abs_tok_index), } }, }); } fn addBreak( gz: *GenZir, tag: Zir.Inst.Tag, break_block: Zir.Inst.Index, operand: Zir.Inst.Ref, ) !Zir.Inst.Index { return gz.addAsIndex(.{ .tag = tag, .data = .{ .@"break" = .{ .block_inst = break_block, .operand = operand, } }, }); } fn addBin( gz: *GenZir, tag: Zir.Inst.Tag, lhs: Zir.Inst.Ref, rhs: Zir.Inst.Ref, ) !Zir.Inst.Ref { assert(lhs != .none); assert(rhs != .none); return gz.add(.{ .tag = tag, .data = .{ .bin = .{ .lhs = lhs, .rhs = rhs, } }, }); } fn addDecl( gz: *GenZir, tag: Zir.Inst.Tag, decl_index: u32, src_node: ast.Node.Index, ) !Zir.Inst.Ref { return gz.add(.{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(src_node), .payload_index = decl_index, } }, }); } fn addNode( gz: *GenZir, tag: Zir.Inst.Tag, /// Absolute node index. This function does the conversion to offset from Decl. src_node: ast.Node.Index, ) !Zir.Inst.Ref { return gz.add(.{ .tag = tag, .data = .{ .node = gz.nodeIndexToRelative(src_node) }, }); } fn addNodeExtended( gz: *GenZir, opcode: Zir.Inst.Extended, /// Absolute node index. This function does the conversion to offset from Decl. src_node: ast.Node.Index, ) !Zir.Inst.Ref { return gz.add(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = opcode, .small = undefined, .operand = @bitCast(u32, gz.nodeIndexToRelative(src_node)), } }, }); } fn addAllocExtended( gz: *GenZir, args: struct { /// Absolute node index. This function does the conversion to offset from Decl. node: ast.Node.Index, type_inst: Zir.Inst.Ref, align_inst: Zir.Inst.Ref, is_const: bool, is_comptime: bool, }, ) !Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); try astgen.extra.ensureUnusedCapacity( gpa, @typeInfo(Zir.Inst.AllocExtended).Struct.fields.len + @as(usize, @boolToInt(args.type_inst != .none)) + @as(usize, @boolToInt(args.align_inst != .none)), ); const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.AllocExtended{ .src_node = gz.nodeIndexToRelative(args.node), }); if (args.type_inst != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.type_inst)); } if (args.align_inst != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.align_inst)); } const has_type: u4 = @boolToInt(args.type_inst != .none); const has_align: u4 = @boolToInt(args.align_inst != .none); const is_const: u4 = @boolToInt(args.is_const); const is_comptime: u4 = @boolToInt(args.is_comptime); const small: u16 = has_type | (has_align << 1) | (is_const << 2) | (is_comptime << 3); const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = .alloc, .small = small, .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } fn addAsm( gz: *GenZir, args: struct { /// Absolute node index. This function does the conversion to offset from Decl. node: ast.Node.Index, asm_source: u32, output_type_bits: u32, is_volatile: bool, outputs: []const Zir.Inst.Asm.Output, inputs: []const Zir.Inst.Asm.Input, clobbers: []const u32, }, ) !Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try astgen.instructions.ensureUnusedCapacity(gpa, 1); try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.Asm).Struct.fields.len + args.outputs.len * @typeInfo(Zir.Inst.Asm.Output).Struct.fields.len + args.inputs.len * @typeInfo(Zir.Inst.Asm.Input).Struct.fields.len + args.clobbers.len); const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Asm{ .src_node = gz.nodeIndexToRelative(args.node), .asm_source = args.asm_source, .output_type_bits = args.output_type_bits, }); for (args.outputs) |output| { _ = gz.astgen.addExtraAssumeCapacity(output); } for (args.inputs) |input| { _ = gz.astgen.addExtraAssumeCapacity(input); } gz.astgen.extra.appendSliceAssumeCapacity(args.clobbers); // * 0b00000000_000XXXXX - `outputs_len`. // * 0b000000XX_XXX00000 - `inputs_len`. // * 0b0XXXXX00_00000000 - `clobbers_len`. // * 0bX0000000_00000000 - is volatile const small: u16 = @intCast(u16, args.outputs.len) | @intCast(u16, args.inputs.len << 5) | @intCast(u16, args.clobbers.len << 10) | (@as(u16, @boolToInt(args.is_volatile)) << 15); const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len); astgen.instructions.appendAssumeCapacity(.{ .tag = .extended, .data = .{ .extended = .{ .opcode = .@"asm", .small = small, .operand = payload_index, } }, }); gz.instructions.appendAssumeCapacity(new_index); return indexToRef(new_index); } /// Note that this returns a `Zir.Inst.Index` not a ref. /// Does *not* append the block instruction to the scope. /// Leaves the `payload_index` field undefined. fn addBlock(gz: *GenZir, tag: Zir.Inst.Tag, node: ast.Node.Index) !Zir.Inst.Index { const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); const gpa = gz.astgen.gpa; try gz.astgen.instructions.append(gpa, .{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(node), .payload_index = undefined, } }, }); return new_index; } /// Note that this returns a `Zir.Inst.Index` not a ref. /// Leaves the `payload_index` field undefined. fn addCondBr(gz: *GenZir, tag: Zir.Inst.Tag, node: ast.Node.Index) !Zir.Inst.Index { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); try gz.astgen.instructions.append(gpa, .{ .tag = tag, .data = .{ .pl_node = .{ .src_node = gz.nodeIndexToRelative(node), .payload_index = undefined, } }, }); gz.instructions.appendAssumeCapacity(new_index); return new_index; } fn setStruct(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_node: ast.Node.Index, body_len: u32, fields_len: u32, decls_len: u32, layout: std.builtin.TypeInfo.ContainerLayout, known_has_bits: bool, }) !void { const astgen = gz.astgen; const gpa = astgen.gpa; try astgen.extra.ensureUnusedCapacity(gpa, 4); const payload_index = @intCast(u32, astgen.extra.items.len); if (args.src_node != 0) { const node_offset = gz.nodeIndexToRelative(args.src_node); astgen.extra.appendAssumeCapacity(@bitCast(u32, node_offset)); } if (args.body_len != 0) { astgen.extra.appendAssumeCapacity(args.body_len); } if (args.fields_len != 0) { astgen.extra.appendAssumeCapacity(args.fields_len); } if (args.decls_len != 0) { astgen.extra.appendAssumeCapacity(args.decls_len); } astgen.instructions.set(inst, .{ .tag = .extended, .data = .{ .extended = .{ .opcode = .struct_decl, .small = @bitCast(u16, Zir.Inst.StructDecl.Small{ .has_src_node = args.src_node != 0, .has_body_len = args.body_len != 0, .has_fields_len = args.fields_len != 0, .has_decls_len = args.decls_len != 0, .known_has_bits = args.known_has_bits, .name_strategy = gz.anon_name_strategy, .layout = args.layout, }), .operand = payload_index, } }, }); } fn setUnion(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_node: ast.Node.Index, tag_type: Zir.Inst.Ref, body_len: u32, fields_len: u32, decls_len: u32, layout: std.builtin.TypeInfo.ContainerLayout, auto_enum_tag: bool, }) !void { const astgen = gz.astgen; const gpa = astgen.gpa; try astgen.extra.ensureUnusedCapacity(gpa, 5); const payload_index = @intCast(u32, astgen.extra.items.len); if (args.src_node != 0) { const node_offset = gz.nodeIndexToRelative(args.src_node); astgen.extra.appendAssumeCapacity(@bitCast(u32, node_offset)); } if (args.tag_type != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.tag_type)); } if (args.body_len != 0) { astgen.extra.appendAssumeCapacity(args.body_len); } if (args.fields_len != 0) { astgen.extra.appendAssumeCapacity(args.fields_len); } if (args.decls_len != 0) { astgen.extra.appendAssumeCapacity(args.decls_len); } astgen.instructions.set(inst, .{ .tag = .extended, .data = .{ .extended = .{ .opcode = .union_decl, .small = @bitCast(u16, Zir.Inst.UnionDecl.Small{ .has_src_node = args.src_node != 0, .has_tag_type = args.tag_type != .none, .has_body_len = args.body_len != 0, .has_fields_len = args.fields_len != 0, .has_decls_len = args.decls_len != 0, .name_strategy = gz.anon_name_strategy, .layout = args.layout, .auto_enum_tag = args.auto_enum_tag, }), .operand = payload_index, } }, }); } fn setEnum(gz: *GenZir, inst: Zir.Inst.Index, args: struct { src_node: ast.Node.Index, tag_type: Zir.Inst.Ref, body_len: u32, fields_len: u32, decls_len: u32, nonexhaustive: bool, }) !void { const astgen = gz.astgen; const gpa = astgen.gpa; try astgen.extra.ensureUnusedCapacity(gpa, 5); const payload_index = @intCast(u32, astgen.extra.items.len); if (args.src_node != 0) { const node_offset = gz.nodeIndexToRelative(args.src_node); astgen.extra.appendAssumeCapacity(@bitCast(u32, node_offset)); } if (args.tag_type != .none) { astgen.extra.appendAssumeCapacity(@enumToInt(args.tag_type)); } if (args.body_len != 0) { astgen.extra.appendAssumeCapacity(args.body_len); } if (args.fields_len != 0) { astgen.extra.appendAssumeCapacity(args.fields_len); } if (args.decls_len != 0) { astgen.extra.appendAssumeCapacity(args.decls_len); } astgen.instructions.set(inst, .{ .tag = .extended, .data = .{ .extended = .{ .opcode = .enum_decl, .small = @bitCast(u16, Zir.Inst.EnumDecl.Small{ .has_src_node = args.src_node != 0, .has_tag_type = args.tag_type != .none, .has_body_len = args.body_len != 0, .has_fields_len = args.fields_len != 0, .has_decls_len = args.decls_len != 0, .name_strategy = gz.anon_name_strategy, .nonexhaustive = args.nonexhaustive, }), .operand = payload_index, } }, }); } fn add(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Ref { return indexToRef(try gz.addAsIndex(inst)); } fn addAsIndex(gz: *GenZir, inst: Zir.Inst) !Zir.Inst.Index { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.appendAssumeCapacity(inst); gz.instructions.appendAssumeCapacity(new_index); return new_index; } fn reserveInstructionIndex(gz: *GenZir) !Zir.Inst.Index { const gpa = gz.astgen.gpa; try gz.instructions.ensureUnusedCapacity(gpa, 1); try gz.astgen.instructions.ensureUnusedCapacity(gpa, 1); const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len); gz.astgen.instructions.len += 1; gz.instructions.appendAssumeCapacity(new_index); return new_index; } fn addRet(gz: *GenZir, rl: ResultLoc, operand: Zir.Inst.Ref, node: ast.Node.Index) !void { switch (rl) { .ptr => |ret_ptr| _ = try gz.addUnNode(.ret_load, ret_ptr, node), .ty => _ = try gz.addUnNode(.ret_node, operand, node), else => unreachable, } } }; /// This can only be for short-lived references; the memory becomes invalidated /// when another string is added. fn nullTerminatedString(astgen: AstGen, index: usize) [*:0]const u8 { return @ptrCast([*:0]const u8, astgen.string_bytes.items.ptr) + index; } fn isPrimitive(name: []const u8) bool { if (simple_types.get(name) != null) return true; if (name.len < 2) return false; const first_c = name[0]; if (first_c != 'i' and first_c != 'u') return false; if (std.fmt.parseInt(u16, name[1..], 10)) |_| { return true; } else |err| switch (err) { error.Overflow => return true, error.InvalidCharacter => return false, } } /// Local variables shadowing detection, including function parameters and primitives. fn detectLocalShadowing( astgen: *AstGen, scope: *Scope, ident_name: u32, name_token: ast.TokenIndex, token_bytes: []const u8, ) !void { const gpa = astgen.gpa; if (token_bytes[0] != '@' and isPrimitive(token_bytes)) { return astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{ token_bytes, }, &[_]u32{ try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{ token_bytes, }), }); } var s = scope; while (true) switch (s.tag) { .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (local_val.name == ident_name) { const name_slice = mem.span(astgen.nullTerminatedString(ident_name)); const name = try gpa.dupe(u8, name_slice); defer gpa.free(name); return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{ @tagName(local_val.id_cat), name, }, &[_]u32{ try astgen.errNoteTok( local_val.token_src, "previous declaration here", .{}, ), }); } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == ident_name) { const name_slice = mem.span(astgen.nullTerminatedString(ident_name)); const name = try gpa.dupe(u8, name_slice); defer gpa.free(name); return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{ @tagName(local_ptr.id_cat), name, }, &[_]u32{ try astgen.errNoteTok( local_ptr.token_src, "previous declaration here", .{}, ), }); } s = local_ptr.parent; }, .namespace => { const ns = s.cast(Scope.Namespace).?; const decl_node = ns.decls.get(ident_name) orelse { s = ns.parent; continue; }; const name_slice = mem.span(astgen.nullTerminatedString(ident_name)); const name = try gpa.dupe(u8, name_slice); defer gpa.free(name); return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{ name, }, &[_]u32{ try astgen.errNoteNode(decl_node, "declared here", .{}), }); }, .gen_zir => s = s.cast(GenZir).?.parent, .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, .top => break, }; } fn advanceSourceCursor(astgen: *AstGen, source: []const u8, end: usize) void { var i = astgen.source_offset; var line = astgen.source_line; var column = astgen.source_column; while (i < end) : (i += 1) { if (source[i] == '\n') { line += 1; column = 0; } else { column += 1; } } astgen.source_offset = i; astgen.source_line = line; astgen.source_column = column; } const ref_start_index: u32 = Zir.Inst.Ref.typed_value_map.len; fn indexToRef(inst: Zir.Inst.Index) Zir.Inst.Ref { return @intToEnum(Zir.Inst.Ref, ref_start_index + inst); } fn refToIndex(inst: Zir.Inst.Ref) ?Zir.Inst.Index { const ref_int = @enumToInt(inst); if (ref_int >= ref_start_index) { return ref_int - ref_start_index; } else { return null; } } fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const ast.Node.Index) !void { const gpa = astgen.gpa; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); for (members) |member_node| { const name_token = switch (node_tags[member_node]) { .fn_decl, .fn_proto_simple, .fn_proto_multi, .fn_proto_one, .fn_proto, .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl, => main_tokens[member_node] + 1, else => continue, }; const token_bytes = astgen.tree.tokenSlice(name_token); if (token_bytes[0] != '@' and isPrimitive(token_bytes)) { switch (astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{ token_bytes, }, &[_]u32{ try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{ token_bytes, }), })) { error.AnalysisFail => continue, error.OutOfMemory => return error.OutOfMemory, } } const name_str_index = try astgen.identAsString(name_token); const gop = try namespace.decls.getOrPut(gpa, name_str_index); if (gop.found_existing) { const name = try gpa.dupe(u8, mem.span(astgen.nullTerminatedString(name_str_index))); defer gpa.free(name); switch (astgen.failNodeNotes(member_node, "redeclaration of '{s}'", .{ name, }, &[_]u32{ try astgen.errNoteNode(gop.value_ptr.*, "other declaration here", .{}), })) { error.AnalysisFail => continue, error.OutOfMemory => return error.OutOfMemory, } } gop.value_ptr.* = member_node; } }
src/AstGen.zig
const std = @import("../std.zig"); const testing = std.testing; const builtin = std.builtin; const fs = std.fs; const mem = std.mem; const wasi = std.os.wasi; const ArenaAllocator = std.heap.ArenaAllocator; const Dir = std.fs.Dir; const File = std.fs.File; const tmpDir = testing.tmpDir; test "Dir.readLink" { var tmp = tmpDir(.{}); defer tmp.cleanup(); // Create some targets try tmp.dir.writeFile("file.txt", "nonsense"); try tmp.dir.makeDir("subdir"); { // Create symbolic link by path tmp.dir.symLink("file.txt", "symlink1", .{}) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLink(tmp.dir, "file.txt", "symlink1"); } { // Create symbolic link by path tmp.dir.symLink("subdir", "symlink2", .{ .is_directory = true }) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLink(tmp.dir, "subdir", "symlink2"); } } fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void { var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; const given = try dir.readLink(symlink_path, buffer[0..]); testing.expect(mem.eql(u8, target_path, given)); } test "accessAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; try fs.accessAbsolute(base_path, .{}); } test "openDirAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makeDir("subdir"); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..], "subdir" }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; var dir = try fs.openDirAbsolute(base_path, .{}); defer dir.close(); } test "readLinkAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); // Create some targets try tmp.dir.writeFile("file.txt", "nonsense"); try tmp.dir.makeDir("subdir"); // Get base abs path var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; const allocator = &arena.allocator; { const target_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "file.txt" }); const symlink_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "symlink1" }); // Create symbolic link by path fs.symLinkAbsolute(target_path, symlink_path, .{}) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLinkAbsolute(target_path, symlink_path); } { const target_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "subdir" }); const symlink_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "symlink2" }); // Create symbolic link by path fs.symLinkAbsolute(target_path, symlink_path, .{ .is_directory = true }) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLinkAbsolute(target_path, symlink_path); } } fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void { var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]); testing.expect(mem.eql(u8, target_path, given)); } test "Dir.Iterator" { var tmp_dir = tmpDir(.{ .iterate = true }); defer tmp_dir.cleanup(); // First, create a couple of entries to iterate over. const file = try tmp_dir.dir.createFile("some_file", .{}); file.close(); try tmp_dir.dir.makeDir("some_dir"); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); var entries = std.ArrayList(Dir.Entry).init(&arena.allocator); // Create iterator. var iter = tmp_dir.dir.iterate(); while (try iter.next()) |entry| { // We cannot just store `entry` as on Windows, we're re-using the name buffer // which means we'll actually share the `name` pointer between entries! const name = try arena.allocator.dupe(u8, entry.name); try entries.append(Dir.Entry{ .name = name, .kind = entry.kind }); } testing.expect(entries.items.len == 2); // note that the Iterator skips '.' and '..' testing.expect(contains(&entries, Dir.Entry{ .name = "some_file", .kind = Dir.Entry.Kind.File })); testing.expect(contains(&entries, Dir.Entry{ .name = "some_dir", .kind = Dir.Entry.Kind.Directory })); } fn entryEql(lhs: Dir.Entry, rhs: Dir.Entry) bool { return mem.eql(u8, lhs.name, rhs.name) and lhs.kind == rhs.kind; } fn contains(entries: *const std.ArrayList(Dir.Entry), el: Dir.Entry) bool { for (entries.items) |entry| { if (entryEql(entry, el)) return true; } return false; } test "Dir.realpath smoke test" { switch (builtin.os.tag) { .linux, .windows, .macos, .ios, .watchos, .tvos => {}, else => return error.SkipZigTest, } var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .lock = File.Lock.Shared }); // We need to close the file immediately as otherwise on Windows we'll end up // with a sharing violation. file.close(); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; // First, test non-alloc version { var buf1: [fs.MAX_PATH_BYTES]u8 = undefined; const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]); const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" }); testing.expect(mem.eql(u8, file_path, expected_path)); } // Next, test alloc version { const file_path = try tmp_dir.dir.realpathAlloc(&arena.allocator, "test_file"); const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" }); testing.expect(mem.eql(u8, file_path, expected_path)); } } test "readAllAlloc" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .read = true }); defer file.close(); const buf1 = try file.readToEndAlloc(testing.allocator, 1024); defer testing.allocator.free(buf1); testing.expect(buf1.len == 0); const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n"; try file.writeAll(write_buf); try file.seekTo(0); // max_bytes > file_size const buf2 = try file.readToEndAlloc(testing.allocator, 1024); defer testing.allocator.free(buf2); testing.expectEqual(write_buf.len, buf2.len); testing.expect(std.mem.eql(u8, write_buf, buf2)); try file.seekTo(0); // max_bytes == file_size const buf3 = try file.readToEndAlloc(testing.allocator, write_buf.len); defer testing.allocator.free(buf3); testing.expectEqual(write_buf.len, buf3.len); testing.expect(std.mem.eql(u8, write_buf, buf3)); try file.seekTo(0); // max_bytes < file_size testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1)); } test "directory operations on files" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_file_name = "test_file"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); testing.expectError(error.PathAlreadyExists, tmp_dir.dir.makeDir(test_file_name)); testing.expectError(error.NotDir, tmp_dir.dir.openDir(test_file_name, .{})); testing.expectError(error.NotDir, tmp_dir.dir.deleteDir(test_file_name)); if (builtin.os.tag != .wasi and builtin.os.tag != .freebsd and builtin.os.tag != .openbsd) { const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_file_name); defer testing.allocator.free(absolute_path); testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(absolute_path)); testing.expectError(error.NotDir, fs.deleteDirAbsolute(absolute_path)); } // ensure the file still exists and is a file as a sanity check file = try tmp_dir.dir.openFile(test_file_name, .{}); const stat = try file.stat(); testing.expect(stat.kind == .File); file.close(); } test "file operations on directories" { // TODO: fix this test on FreeBSD. https://github.com/ziglang/zig/issues/1759 if (builtin.os.tag == .freebsd) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_dir_name = "test_dir"; try tmp_dir.dir.makeDir(test_dir_name); testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{})); testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name)); // Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle. // TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved. if (builtin.os.tag != .wasi) { testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize))); } // Note: The `.write = true` is necessary to ensure the error occurs on all platforms. // TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732 testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true })); if (builtin.os.tag != .wasi and builtin.os.tag != .freebsd and builtin.os.tag != .openbsd) { const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_dir_name); defer testing.allocator.free(absolute_path); testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{})); testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path)); } // ensure the directory still exists as a sanity check var dir = try tmp_dir.dir.openDir(test_dir_name, .{}); dir.close(); } test "deleteDir" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // deleting a non-existent directory testing.expectError(error.FileNotFound, tmp_dir.dir.deleteDir("test_dir")); var dir = try tmp_dir.dir.makeOpenPath("test_dir", .{}); var file = try dir.createFile("test_file", .{}); file.close(); dir.close(); // deleting a non-empty directory // TODO: Re-enable this check on Windows, see https://github.com/ziglang/zig/issues/5537 if (builtin.os.tag != .windows) { testing.expectError(error.DirNotEmpty, tmp_dir.dir.deleteDir("test_dir")); } dir = try tmp_dir.dir.openDir("test_dir", .{}); try dir.deleteFile("test_file"); dir.close(); // deleting an empty directory try tmp_dir.dir.deleteDir("test_dir"); } test "Dir.rename files" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); testing.expectError(error.FileNotFound, tmp_dir.dir.rename("missing_file_name", "something_else")); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); try tmp_dir.dir.rename(test_file_name, renamed_test_file_name); // Ensure the file was renamed testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{})); file = try tmp_dir.dir.openFile(renamed_test_file_name, .{}); file.close(); // Rename to self succeeds try tmp_dir.dir.rename(renamed_test_file_name, renamed_test_file_name); // Rename to existing file succeeds var existing_file = try tmp_dir.dir.createFile("existing_file", .{ .read = true }); existing_file.close(); try tmp_dir.dir.rename(renamed_test_file_name, "existing_file"); testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(renamed_test_file_name, .{})); file = try tmp_dir.dir.openFile("existing_file", .{}); file.close(); } test "Dir.rename directories" { // TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364 if (builtin.os.tag == .windows) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // Renaming directories try tmp_dir.dir.makeDir("test_dir"); try tmp_dir.dir.rename("test_dir", "test_dir_renamed"); // Ensure the directory was renamed testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir", .{})); var dir = try tmp_dir.dir.openDir("test_dir_renamed", .{}); // Put a file in the directory var file = try dir.createFile("test_file", .{ .read = true }); file.close(); dir.close(); try tmp_dir.dir.rename("test_dir_renamed", "test_dir_renamed_again"); // Ensure the directory was renamed and the file still exists in it testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir_renamed", .{})); dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{}); file = try dir.openFile("test_file", .{}); file.close(); dir.close(); // Try to rename to a non-empty directory now var target_dir = try tmp_dir.dir.makeOpenPath("non_empty_target_dir", .{}); file = try target_dir.createFile("filler", .{ .read = true }); file.close(); testing.expectError(error.PathAlreadyExists, tmp_dir.dir.rename("test_dir_renamed_again", "non_empty_target_dir")); // Ensure the directory was not renamed dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{}); file = try dir.openFile("test_file", .{}); file.close(); dir.close(); } test "Dir.rename file <-> dir" { // TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364 if (builtin.os.tag == .windows) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .read = true }); file.close(); try tmp_dir.dir.makeDir("test_dir"); testing.expectError(error.IsDir, tmp_dir.dir.rename("test_file", "test_dir")); testing.expectError(error.NotDir, tmp_dir.dir.rename("test_dir", "test_file")); } test "rename" { var tmp_dir1 = tmpDir(.{}); defer tmp_dir1.cleanup(); var tmp_dir2 = tmpDir(.{}); defer tmp_dir2.cleanup(); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir1.dir.createFile(test_file_name, .{ .read = true }); file.close(); try fs.rename(tmp_dir1.dir, test_file_name, tmp_dir2.dir, renamed_test_file_name); // ensure the file was renamed testing.expectError(error.FileNotFound, tmp_dir1.dir.openFile(test_file_name, .{})); file = try tmp_dir2.dir.openFile(renamed_test_file_name, .{}); file.close(); } test "renameAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // Get base abs path var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = &arena.allocator; const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; testing.expectError(error.FileNotFound, fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, "missing_file_name" }), try fs.path.join(allocator, &[_][]const u8{ base_path, "something_else" }), )); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); try fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, test_file_name }), try fs.path.join(allocator, &[_][]const u8{ base_path, renamed_test_file_name }), ); // ensure the file was renamed testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{})); file = try tmp_dir.dir.openFile(renamed_test_file_name, .{}); const stat = try file.stat(); testing.expect(stat.kind == .File); file.close(); // Renaming directories const test_dir_name = "test_dir"; const renamed_test_dir_name = "test_dir_renamed"; try tmp_dir.dir.makeDir(test_dir_name); try fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, test_dir_name }), try fs.path.join(allocator, &[_][]const u8{ base_path, renamed_test_dir_name }), ); // ensure the directory was renamed testing.expectError(error.FileNotFound, tmp_dir.dir.openDir(test_dir_name, .{})); var dir = try tmp_dir.dir.openDir(renamed_test_dir_name, .{}); dir.close(); } test "openSelfExe" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const self_exe_file = try std.fs.openSelfExe(.{}); self_exe_file.close(); } test "makePath, put some files in it, deleteTree" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); try tmp.dir.deleteTree("os_test_tmp"); if (tmp.dir.openDir("os_test_tmp", .{})) |dir| { @panic("expected error"); } else |err| { testing.expect(err == error.FileNotFound); } } test "access file" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); if (tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{})) |ok| { @panic("expected error"); } else |err| { testing.expect(err == error.FileNotFound); } try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", ""); try tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{}); try tmp.dir.deleteTree("os_test_tmp"); } test "sendfile" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); defer tmp.dir.deleteTree("os_test_tmp") catch {}; var dir = try tmp.dir.openDir("os_test_tmp", .{}); defer dir.close(); const line1 = "line1\n"; const line2 = "second line\n"; var vecs = [_]std.os.iovec_const{ .{ .iov_base = line1, .iov_len = line1.len, }, .{ .iov_base = line2, .iov_len = line2.len, }, }; var src_file = try dir.createFile("sendfile1.txt", .{ .read = true }); defer src_file.close(); try src_file.writevAll(&vecs); var dest_file = try dir.createFile("sendfile2.txt", .{ .read = true }); defer dest_file.close(); const header1 = "header1\n"; const header2 = "second header\n"; const trailer1 = "trailer1\n"; const trailer2 = "second trailer\n"; var hdtr = [_]std.os.iovec_const{ .{ .iov_base = header1, .iov_len = header1.len, }, .{ .iov_base = header2, .iov_len = header2.len, }, .{ .iov_base = trailer1, .iov_len = trailer1.len, }, .{ .iov_base = trailer2, .iov_len = trailer2.len, }, }; var written_buf: [100]u8 = undefined; try dest_file.writeFileAll(src_file, .{ .in_offset = 1, .in_len = 10, .headers_and_trailers = &hdtr, .header_count = 2, }); const amt = try dest_file.preadAll(&written_buf, 0); testing.expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n")); } test "copyRangeAll" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); defer tmp.dir.deleteTree("os_test_tmp") catch {}; var dir = try tmp.dir.openDir("os_test_tmp", .{}); defer dir.close(); var src_file = try dir.createFile("file1.txt", .{ .read = true }); defer src_file.close(); const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP"; try src_file.writeAll(data); var dest_file = try dir.createFile("file2.txt", .{ .read = true }); defer dest_file.close(); var written_buf: [100]u8 = undefined; _ = try src_file.copyRangeAll(0, dest_file, 0, data.len); const amt = try dest_file.preadAll(&written_buf, 0); testing.expect(mem.eql(u8, written_buf[0..amt], data)); } test "fs.copyFile" { const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP"; const src_file = "tmp_test_copy_file.txt"; const dest_file = "tmp_test_copy_file2.txt"; const dest_file2 = "tmp_test_copy_file3.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(src_file, data); defer tmp.dir.deleteFile(src_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file, .{}); defer tmp.dir.deleteFile(dest_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file2, .{ .override_mode = File.default_mode }); defer tmp.dir.deleteFile(dest_file2) catch {}; try expectFileContents(tmp.dir, dest_file, data); try expectFileContents(tmp.dir, dest_file2, data); } fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void { const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000); defer testing.allocator.free(contents); testing.expectEqualSlices(u8, data, contents); } test "AtomicFile" { const test_out_file = "tmp_atomic_file_test_dest.txt"; const test_content = \\ hello! \\ this is a test file ; var tmp = tmpDir(.{}); defer tmp.cleanup(); { var af = try tmp.dir.atomicFile(test_out_file, .{}); defer af.deinit(); try af.file.writeAll(test_content); try af.finish(); } const content = try tmp.dir.readFileAlloc(testing.allocator, test_out_file, 9999); defer testing.allocator.free(content); testing.expect(mem.eql(u8, content, test_content)); try tmp.dir.deleteFile(test_out_file); } test "realpath" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf)); } test "open file with exclusive nonblocking lock twice" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); testing.expectError(error.WouldBlock, file2); } test "open file with shared and exclusive nonblocking lock" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Shared, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); testing.expectError(error.WouldBlock, file2); } test "open file with exclusive and shared nonblocking lock" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Shared, .lock_nonblocking = true }); testing.expectError(error.WouldBlock, file2); } test "open file with exclusive lock twice, make sure it waits" { if (builtin.single_threaded) return error.SkipZigTest; if (std.io.is_async) { // This test starts its own threads and is not compatible with async I/O. return error.SkipZigTest; } if (std.Target.current.os.tag == .windows) { // https://github.com/ziglang/zig/issues/7010 return error.SkipZigTest; } const filename = "file_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file = try tmp.dir.createFile(filename, .{ .lock = .Exclusive }); errdefer file.close(); const S = struct { const C = struct { dir: *fs.Dir, evt: *std.ResetEvent }; fn checkFn(ctx: C) !void { const file1 = try ctx.dir.createFile(filename, .{ .lock = .Exclusive }); defer file1.close(); ctx.evt.set(); } }; var evt = std.ResetEvent.init(); defer evt.deinit(); const t = try std.Thread.spawn(S.C{ .dir = &tmp.dir, .evt = &evt }, S.checkFn); defer t.wait(); const SLEEP_TIMEOUT_NS = 10 * std.time.ns_per_ms; std.time.sleep(SLEEP_TIMEOUT_NS); // Check that createFile is still waiting for the lock to be released. testing.expect(!evt.isSet()); file.close(); // Generous timeout to avoid failures on heavily loaded systems. try evt.timedWait(SLEEP_TIMEOUT_NS); } test "open file with exclusive nonblocking lock twice (absolute paths)" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const allocator = testing.allocator; const file_paths: [1][]const u8 = .{"zig-test-absolute-paths.txt"}; const filename = try fs.path.resolve(allocator, &file_paths); defer allocator.free(filename); const file1 = try fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); const file2 = fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); file1.close(); testing.expectError(error.WouldBlock, file2); try fs.deleteFileAbsolute(filename); }
lib/std/fs/test.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const maxInt = std.math.maxInt; const State = enum { Complete, Value, ArrayStart, Array, ObjectStart, Object, }; /// Writes JSON ([RFC8259](https://tools.ietf.org/html/rfc8259)) formatted data /// to a stream. `max_depth` is a comptime-known upper bound on the nesting depth. /// TODO A future iteration of this API will allow passing `null` for this value, /// and disable safety checks in release builds. pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { return struct { const Self = @This(); pub const Stream = OutStream; /// The string used for indenting. one_indent: []const u8 = " ", /// The string used as a newline character. newline: []const u8 = "\n", stream: *OutStream, state_index: usize, state: [max_depth]State, pub fn init(stream: *OutStream) Self { var self = Self{ .stream = stream, .state_index = 1, .state = undefined, }; self.state[0] = .Complete; self.state[1] = .Value; return self; } pub fn beginArray(self: *Self) !void { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('['); self.state[self.state_index] = State.ArrayStart; } pub fn beginObject(self: *Self) !void { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('{'); self.state[self.state_index] = State.ObjectStart; } pub fn arrayElem(self: *Self) !void { const state = self.state[self.state_index]; switch (state) { .Complete => unreachable, .Value => unreachable, .ObjectStart => unreachable, .Object => unreachable, .Array, .ArrayStart => { if (state == .Array) { try self.stream.writeByte(','); } self.state[self.state_index] = .Array; self.pushState(.Value); try self.indent(); }, } } pub fn objectField(self: *Self, name: []const u8) !void { const state = self.state[self.state_index]; switch (state) { .Complete => unreachable, .Value => unreachable, .ArrayStart => unreachable, .Array => unreachable, .Object, .ObjectStart => { if (state == .Object) { try self.stream.writeByte(','); } self.state[self.state_index] = .Object; self.pushState(.Value); try self.indent(); try self.writeEscapedString(name); try self.stream.write(": "); }, } } pub fn endArray(self: *Self) !void { switch (self.state[self.state_index]) { .Complete => unreachable, .Value => unreachable, .ObjectStart => unreachable, .Object => unreachable, .ArrayStart => { try self.stream.writeByte(']'); self.popState(); }, .Array => { try self.indent(); self.popState(); try self.stream.writeByte(']'); }, } } pub fn endObject(self: *Self) !void { switch (self.state[self.state_index]) { .Complete => unreachable, .Value => unreachable, .ArrayStart => unreachable, .Array => unreachable, .ObjectStart => { try self.stream.writeByte('}'); self.popState(); }, .Object => { try self.indent(); self.popState(); try self.stream.writeByte('}'); }, } } pub fn emitNull(self: *Self) !void { assert(self.state[self.state_index] == State.Value); try self.stream.write("null"); self.popState(); } pub fn emitBool(self: *Self, value: bool) !void { assert(self.state[self.state_index] == State.Value); if (value) { try self.stream.write("true"); } else { try self.stream.write("false"); } self.popState(); } pub fn emitNumber( self: *Self, /// An integer, float, or `std.math.BigInt`. Emitted as a bare number if it fits losslessly /// in a IEEE 754 double float, otherwise emitted as a string to the full precision. value: var, ) !void { assert(self.state[self.state_index] == State.Value); switch (@typeInfo(@typeOf(value))) { .Int => |info| if (info.bits < 53 or (value < 4503599627370496 and value > -4503599627370496)) { try self.stream.print("{}", value); self.popState(); return; }, .Float => if (@floatCast(f64, value) == value) { try self.stream.print("{}", value); self.popState(); return; }, else => {}, } try self.stream.print("\"{}\"", value); self.popState(); } pub fn emitString(self: *Self, string: []const u8) !void { try self.writeEscapedString(string); self.popState(); } fn writeEscapedString(self: *Self, string: []const u8) !void { try self.stream.writeByte('"'); for (string) |s| { switch (s) { '"' => try self.stream.write("\\\""), '\t' => try self.stream.write("\\t"), '\r' => try self.stream.write("\\r"), '\n' => try self.stream.write("\\n"), 8 => try self.stream.write("\\b"), 12 => try self.stream.write("\\f"), '\\' => try self.stream.write("\\\\"), else => try self.stream.writeByte(s), } } try self.stream.writeByte('"'); } fn indent(self: *Self) !void { assert(self.state_index >= 1); try self.stream.write(self.newline); var i: usize = 0; while (i < self.state_index - 1) : (i += 1) { try self.stream.write(self.one_indent); } } fn pushState(self: *Self, state: State) void { self.state_index += 1; self.state[self.state_index] = state; } fn popState(self: *Self) void { self.state_index -= 1; } }; }
lib/std/json/write_stream.zig
const std = @import("std"); const builtin = @import("builtin"); /// Discord utilizes Twitter's snowflake format for uniquely identifiable /// descriptors (IDs). These IDs are guaranteed to be unique across all of /// Discord, except in some unique scenarios in which child objects share their /// parent's ID. Because Snowflake IDs are up to 64 bits in size (e.g. a uint64), /// they are always returned as strings in the HTTP API to prevent integer /// overflows in some languages. See Gateway ETF/JSON for more information /// regarding Gateway encoding. pub fn Snowflake(comptime scope: @Type(.EnumLiteral)) type { _ = scope; return enum(u64) { _, const Self = @This(); pub fn init(num: u64) Self { return @intToEnum(Self, num); } pub fn parse(str: []const u8) !Self { return init( std.fmt.parseInt(u64, str, 10) catch return error.SnowflakeTooSpecial, ); } pub fn consumeJsonElement(elem: anytype) !Self { var buf: [64]u8 = undefined; const str = elem.stringBuffer(&buf) catch |err| switch (err) { error.StreamTooLong => return error.SnowflakeTooSpecial, else => |e| return e, }; return try parse(str); } /// Milliseconds since Discord Epoch, the first second of 2015 or 1420070400000. pub fn getTimestamp(self: Self) u64 { return (@enumToInt(self) >> 22) + 1420070400000; } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; try writer.print("{}", .{@enumToInt(self)}); } pub fn jsonStringify(self: Self, options: std.json.StringifyOptions, writer: anytype) !void { _ = options; try writer.print("\"{}\"", .{@enumToInt(self)}); } }; } pub const Gateway = struct { pub const Opcode = enum(u4) { /// An event was dispatched. dispatch = 0, /// Fired periodically by the client to keep the connection alive. heartbeat = 1, /// Starts a new session during the initial handshake. identify = 2, /// Update the client's presence. presence_update = 3, /// Used to join/leave or move between voice channels. voice_state_update = 4, /// Resume a previous session that was disconnected. @"resume" = 6, /// You should attempt to reconnect and resume immediately. reconnect = 7, /// Request information about offline guild members in a large guild. request_guild_members = 8, /// The session has been invalidated. You should reconnect and identify/resume accordingly. invalid_session = 9, /// Sent immediately after connecting, contains the heartbeat_interval to use. hello = 10, /// Sent in response to receiving a heartbeat to acknowledge that it has been received. heartbeat_ack = 11, }; pub const CloseEventCode = enum(u16) { NormalClosure = 1000, GoingAway = 1001, ProtocolError = 1002, UnsupportedData = 1003, NoStatusReceived = 1005, AbnormalClosure = 1006, InvalidFramePayloadData = 1007, PolicyViolation = 1008, MessageTooBig = 1009, MissingExtension = 1010, InternalError = 1011, ServiceRestart = 1012, TryAgainLater = 1013, BadGateway = 1014, TlsHandshake = 1015, UnknownError = 4000, UnknownOpcode = 4001, DecodeError = 4002, NotAuthenticated = 4003, AuthenticationFailed = 4004, AlreadyAuthenticated = 4005, InvalidSeq = 4007, RateLimited = 4008, SessionTimedOut = 4009, InvalidShard = 4010, ShardingRequired = 4011, InvalidApiVersion = 4012, InvalidIntents = 4013, DisallowedIntents = 4014, _, }; pub const Command = union(Opcode) { dispatch: void, reconnect: void, invalid_session: void, hello: void, heartbeat_ack: void, identify: struct { token: []const u8, properties: struct { @"$os": []const u8 = @tagName(builtin.target.os.tag), @"$browser": []const u8, @"$device": []const u8, }, compress: bool = false, presence: ?Presence = null, intents: Intents, }, @"resume": struct { token: []const u8, session_id: []const u8, seq: u32, }, heartbeat: u32, request_guild_members: struct { guild_id: Snowflake(.guild), query: []const u8 = "", limit: u32, presences: bool = false, user_ids: ?[]Snowflake(.user) = null, }, voice_state_update: struct { guild_id: Snowflake(.guild), channel_id: ?Snowflake(.channel) = null, self_mute: bool, self_deaf: bool, }, presence_update: struct { since: ?u32 = null, activities: ?[]Activity = null, status: Status, afk: bool, }, pub fn jsonStringify(self: Command, options: std.json.StringifyOptions, writer: anytype) @TypeOf(writer).Error!void { inline for (std.meta.fields(Opcode)) |field| { const tag = @field(Opcode, field.name); if (std.meta.activeTag(self) == tag) { return std.json.stringify(.{ .op = @enumToInt(tag), .d = @field(self, @tagName(tag)), }, options, writer); } } unreachable; } }; pub const Intents = packed struct { guilds: bool = false, guild_members: bool = false, guild_bans: bool = false, guild_emojis: bool = false, guild_integrations: bool = false, guild_webhooks: bool = false, guild_invites: bool = false, guild_voice_states: bool = false, guild_presences: bool = false, guild_messages: bool = false, guild_message_reactions: bool = false, guild_message_typing: bool = false, direct_messages: bool = false, direct_message_reactions: bool = false, direct_message_typing: bool = false, _pad: u1 = 0, pub fn toRaw(self: Intents) u16 { return @bitCast(u16, self); } pub fn fromRaw(raw: u16) Intents { return @bitCast(Intents, raw); } pub fn jsonStringify(self: Intents, options: std.json.StringifyOptions, writer: anytype) !void { _ = options; try writer.print("{}", .{self.toRaw()}); } }; pub const Status = enum { online, dnd, idle, invisible, offline, pub fn jsonStringify(self: @This(), options: std.json.StringifyOptions, writer: anytype) !void { _ = options; try writer.writeAll("\""); try writer.writeAll(@tagName(self)); try writer.writeAll("\""); } }; pub const Presence = struct { status: Status = .online, activities: []const Activity = &.{}, since: ?u32 = null, afk: bool = false, }; pub const Activity = struct { type: enum(u3) { Game = 0, Streaming = 1, Listening = 2, Watching = 3, Custom = 4, Competing = 5, pub fn jsonStringify(self: @This(), options: std.json.StringifyOptions, writer: anytype) !void { _ = options; try writer.print("{d}", .{@enumToInt(self)}); } }, name: []const u8, }; }; pub const Resource = struct { pub const Message = struct { content: []const u8 = "", embed: ?Embed = null, pub const Embed = struct { title: ?[]const u8 = null, description: ?[]const u8 = null, url: ?[]const u8 = null, timestamp: ?[]const u8 = null, color: ?u32 = null, }; }; }; test { _ = std.testing.refAllDecls(Gateway); _ = std.testing.refAllDecls(Resource); }
src/discord.zig
pub const limine_uuid = extern struct { a: u32, b: u16, c: u16, d: [8]u8, }; pub const limine_file = extern struct { revision: u64, address: ?*anyopaque, size: u64, path: [*c]u8, cmdline: [*c]u8, media_type: u32, unused: u32, tftp_ip: u32, tftp_port: u32, partition_index: u32, mbr_disk_id: u32, gpt_disk_uuid: limine_uuid, gpt_part_uuid: limine_uuid, part_uuid: limine_uuid, }; pub const limine_bootloader_info_response = extern struct { revision: u64, name: [*c]u8, version: [*c]u8, }; pub const limine_bootloader_info_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_bootloader_info_response, }; pub const limine_stack_size_response = extern struct { revision: u64, }; pub const limine_stack_size_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_stack_size_response, stack_size: u64, }; pub const limine_hhdm_response = extern struct { revision: u64, offset: u64, }; pub const limine_hhdm_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_hhdm_response, }; pub const limine_framebuffer = extern struct { address: ?*anyopaque, width: u64, height: u64, pitch: u64, 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: [7]u8, edid_size: u64, edid: ?*anyopaque, }; pub const limine_framebuffer_response = extern struct { revision: u64, framebuffer_count: u64, framebuffers: [*c][*c]limine_framebuffer, }; pub const limine_framebuffer_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_framebuffer_response, }; pub const limine_framebuffer_legacy = extern struct { address: ?*anyopaque, 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: ?*anyopaque, }; pub const limine_framebuffer_legacy_response = extern struct { revision: u64, framebuffer_count: u64, framebuffers: [*c][*c]limine_framebuffer_legacy, }; pub const limine_framebuffer_legacy_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_framebuffer_legacy_response, }; pub const limine_terminal = extern struct { columns: u64, rows: u64, framebuffer: [*c]limine_framebuffer, }; pub const limine_terminal_write = ?fn ([*c]limine_terminal, [*c]const u8, u64) callconv(.C) void; pub const limine_terminal_callback = ?fn ([*c]limine_terminal, u64, u64, u64, u64) callconv(.C) void; pub const limine_terminal_response = extern struct { revision: u64, terminal_count: u64, terminals: [*c][*c]limine_terminal, write: limine_terminal_write, }; pub const limine_terminal_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_terminal_response, callback: limine_terminal_callback, }; pub const limine_terminal_legacy = extern struct { columns: u32, rows: u32, framebuffer: [*c]limine_framebuffer_legacy, }; pub const limine_terminal_legacy_write = ?fn ([*c]limine_terminal_legacy, [*c]const u8, u64) callconv(.C) void; pub const limine_terminal_legacy_callback = ?fn ([*c]limine_terminal_legacy, u64, u64, u64, u64) callconv(.C) void; pub const limine_terminal_legacy_response = extern struct { revision: u64, terminal_count: u64, terminals: [*c][*c]limine_terminal_legacy, write: limine_terminal_legacy_write, }; pub const limine_terminal_legacy_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_terminal_legacy_response, callback: limine_terminal_legacy_callback, }; pub const limine_5_level_paging_response = extern struct { revision: u64, }; pub const limine_5_level_paging_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_5_level_paging_response, }; pub const limine_goto_address = ?fn ([*c]limine_smp_info) callconv(.C) void; pub const limine_smp_info = extern struct { processor_id: u32, lapic_id: u32, reserved: u64, goto_address: limine_goto_address, extra_argument: u64, }; pub const limine_smp_response = extern struct { revision: u64, flags: u32, bsp_lapic_id: u32, cpu_count: u64, cpus: [*c][*c]limine_smp_info, }; pub const limine_smp_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_smp_response, flags: u64, }; pub const limine_memmap_entry = extern struct { base: u64, length: u64, type: u64, }; pub const limine_memmap_response = extern struct { revision: u64, entry_count: u64, entries: [*c][*c]limine_memmap_entry, }; pub const limine_memmap_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_memmap_response, }; pub const limine_entry_point = ?fn () callconv(.C) void; pub const limine_entry_point_response = extern struct { revision: u64, }; pub const limine_entry_point_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_entry_point_response, entry: limine_entry_point, }; pub const limine_kernel_file_response = extern struct { revision: u64, kernel_file: [*c]limine_file, }; pub const limine_kernel_file_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_kernel_file_response, }; pub const limine_module_response = extern struct { revision: u64, module_count: u64, modules: [*c][*c]limine_file, }; pub const limine_module_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_module_response, }; pub const limine_rsdp_response = extern struct { revision: u64, address: ?*anyopaque, }; pub const limine_rsdp_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_rsdp_response, }; pub const limine_smbios_response = extern struct { revision: u64, entry_32: ?*anyopaque, entry_64: ?*anyopaque, }; pub const limine_smbios_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_smbios_response, }; pub const limine_efi_system_table_response = extern struct { revision: u64, address: ?*anyopaque, }; pub const limine_efi_system_table_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_efi_system_table_response, }; pub const limine_boot_time_response = extern struct { revision: u64, boot_time: i64, }; pub const limine_boot_time_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_boot_time_response, }; pub const limine_kernel_address_response = extern struct { revision: u64, physical_base: u64, virtual_base: u64, }; pub const limine_kernel_address_request = extern struct { id: [4]u64, revision: u64, response: [*c]limine_kernel_address_response, }; pub inline fn LIMINE_PTR(TYPE: anytype) @TypeOf(TYPE) { return TYPE; } pub const limine_terminal_request_id = [_]u64{ 0xc7b1dd30df4c8b88, 0x0a82e883a194f07b, 0xc8ac59310c2b0844, 0xa68d0c7265d38878 }; pub const LIMINE_MEDIA_TYPE_GENERIC = @as(c_int, 0); pub const LIMINE_MEDIA_TYPE_OPTICAL = @as(c_int, 1); pub const LIMINE_MEDIA_TYPE_TFTP = @as(c_int, 2); pub const LIMINE_FRAMEBUFFER_RGB = @as(c_int, 1); pub const LIMINE_TERMINAL_CB_DEC = @as(c_int, 10); pub const LIMINE_TERMINAL_CB_BELL = @as(c_int, 20); pub const LIMINE_TERMINAL_CB_PRIVATE_ID = @as(c_int, 30); pub const LIMINE_TERMINAL_CB_STATUS_REPORT = @as(c_int, 40); pub const LIMINE_TERMINAL_CB_POS_REPORT = @as(c_int, 50); pub const LIMINE_TERMINAL_CB_KBD_LEDS = @as(c_int, 60); pub const LIMINE_TERMINAL_CB_MODE = @as(c_int, 70); pub const LIMINE_TERMINAL_CB_LINUX = @as(c_int, 80); pub const LIMINE_TERMINAL_CTX_SIZE = @import("std").zig.c_translation.cast(u64, -@as(c_int, 1)); pub const LIMINE_TERMINAL_CTX_SAVE = @import("std").zig.c_translation.cast(u64, -@as(c_int, 2)); pub const LIMINE_TERMINAL_CTX_RESTORE = @import("std").zig.c_translation.cast(u64, -@as(c_int, 3)); pub const LIMINE_TERMINAL_FULL_REFRESH = @import("std").zig.c_translation.cast(u64, -@as(c_int, 4)); pub const LIMINE_SMP_X2APIC = @as(c_int, 1) << @as(c_int, 0); pub const LIMINE_MEMMAP_USABLE = @as(c_int, 0); pub const LIMINE_MEMMAP_RESERVED = @as(c_int, 1); pub const LIMINE_MEMMAP_ACPI_RECLAIMABLE = @as(c_int, 2); pub const LIMINE_MEMMAP_ACPI_NVS = @as(c_int, 3); pub const LIMINE_MEMMAP_BAD_MEMORY = @as(c_int, 4); pub const LIMINE_MEMMAP_BOOTLOADER_RECLAIMABLE = @as(c_int, 5); pub const LIMINE_MEMMAP_KERNEL_AND_MODULES = @as(c_int, 6); pub const LIMINE_MEMMAP_FRAMEBUFFER = @as(c_int, 7);
src/kernel/arch/x86_64/limine/limine.zig
const std = @import("std"); const debug = std.debug; const testing = std.testing; /// A tuple implementation structured as a tree of `first+second` pairs. pub fn Tuple(comptime types: []const type) type { const Functions = struct { fn At(comptime T: type, comptime i: usize) type { var info = @typeInfo(T); if (info.Pointer.is_const) return *const types[i]; return *types[i]; } pub fn init(comptime Self: type) type { return struct { fn func(t: var) Self { comptime debug.assert(t.len == types.len); var res: Self = undefined; comptime var i = 0; inline while (i < t.len) : (i += 1) { res.at(i).* = t[i]; } return res; } }; } pub fn at(t: var, comptime i: usize) At(@TypeOf(t), i) { comptime debug.assert(i < t.len); if (t.len <= 2 and i == 0) return &t.first; if (t.len <= 2 and i == 1) return &t.second; if (i < t.first.len) return t.first.at(i); return t.second.at(i - t.first.len); } }; if (types.len <= 2) { return struct { comptime len: usize = types.len, first: if (types.len >= 1) types[0] else void, second: if (types.len == 2) types[1] else void, pub const init = Functions.init(@This()).func; pub const at = Functions.at; }; } else { return struct { comptime len: usize = types.len, first: Tuple(types[0 .. types.len / 2]), second: Tuple(types[types.len / 2 ..]), pub const init = Functions.init(@This()).func; pub const at = Functions.at; }; } } test "tuple" { const unit = Tuple(&[_]type{u8}).init(.{0}); const pair = Tuple(&[_]type{ u8, u16 }).init(.{ 0, 1 }); const trip = Tuple(&[_]type{ u8, u16, u32 }).init(.{ 0, 1, 2 }); const quad = Tuple(&[_]type{ u8, u16, u32, u64 }).init(.{ 0, 1, 2, 3 }); const all = Tuple(&[_]type{ @TypeOf(unit), @TypeOf(pair), @TypeOf(trip), @TypeOf(quad), }).init(.{ unit, pair, trip, quad }); comptime var i = 0; inline while (i < all.len) : (i += 1) { const t = all.at(i).*; comptime var j = 0; inline while (j < t.len) : (j += 1) testing.expectEqual(@as(u64, j), t.at(j).*); } }
tuple.zig