code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const network = @import("network"); pub const io_mode = .evented; pub fn main() !void { // Make sure async is on if (!std.io.is_async) return error.NO_ASYNC; const allocator = std.heap.page_allocator; // Start the network (only executes code under Windows) try network.init(); defer network.deinit(); // Start the server and bind it to a port var server = try network.Socket.create(.ipv4, .tcp); defer server.close(); try server.bindToPort(2505); // start to listen on the port try server.listen(); std.debug.warn("listening at {}\n", .{try server.getLocalEndPoint()}); // Setup clients to accept incoming connections const N_CLIENTS = 4; var clients = std.ArrayList(*Client).init(allocator); try clients.resize(N_CLIENTS); for (clients.items) |*it| { it.* = try Client.createAndStart(allocator, &server); } // Main event loop while (true) { for (clients.items) |client| { if (!client.done) { resume client.handle_frame; } else { //restart a closed client await client.handle_frame catch |e| { std.debug.warn("client ended with error: {}, restarting client\n", .{e}); }; client.start(&server); } } // take some breath std.os.nanosleep(0, 30000000); } } const Client = struct { conn: network.Socket = undefined, handle_frame: @Frame(Client.handle) = undefined, done: bool = false, fn createAndStart(allocator: *std.mem.Allocator, server: *network.Socket) !*Client { const client = try allocator.create(Client); client.start(server); return client; } fn start(self: *Client, server: *network.Socket) void { self.* = Client{}; self.handle_frame = async self.handle(server); } fn handle(self: *Client, server: *network.Socket) !void { std.debug.warn("accepting\n", .{}); while (true) { self.conn = server.accept() catch |e| { switch (e) { error.WouldBlock => { suspend; continue; }, else => { std.debug.warn("error: {}\n", .{e}); self.done = true; return e; }, } }; break; } try self.conn.writer().writeAll("server: welcome to the chat server\n"); std.debug.warn("remote ip:{}\n", .{self.conn.getRemoteEndPoint()}); while (true) { var buf: [100]u8 = undefined; const amt = self.conn.receive(&buf) catch |e| { switch (e) { error.WouldBlock => { suspend; continue; }, else => { std.debug.warn("error: {}\n", .{e}); self.done = true; return e; }, } }; if (amt == 0) { self.done = true; break; // We're done, end of connection } const msg = buf[0..amt]; std.debug.print("Client wrote: {s}", .{msg}); } } };
examples/async.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } //const Grid = @Vector(25, u1); // marche pas vraiment vu les operations qu'on veut faire.. //const Grid = u25; // marche pas vraiment, pénible pour accéder aux bits.. const Grid = std.StaticBitSet(25); const null_grid = Grid{ .mask = 0 }; fn trace_grid(header: []const u8, g: Grid) void { trace("{s}", .{header}); var i: u32 = 0; while (i < 25) : (i += 1) { const c: u8 = if (g.isSet(i)) '#' else '.'; if (i % 5 == 4) { trace("{c}\n", .{c}); } else { trace("{c}", .{c}); } } } const neibourgh_masks_part1: [25]Grid = blk: { @setEvalBranchQuota(4000); var neib = [1]Grid{null_grid} ** 25; for (neib) |*grid, i| { var j: u32 = 0; while (j < 25) : (j += 1) { grid.setValue(j, // (@boolToInt((i / 5) == (j / 5)) & (@boolToInt(i == j + 1) | @boolToInt(j == i + 1))) // same line | (@boolToInt(i == j + 5) | @boolToInt(j == i + 5)) != 0); // same column } } break :blk neib; }; const neibourgh_masks_part2: [25][3]Grid = blk: { const NeighbourSquare = struct { l: i8, // relative grid layer i: u8, // sq index in the grid }; const table = [5 * 5][8]?NeighbourSquare{ [8]?NeighbourSquare{ .{ .l = 0, .i = 1 }, .{ .l = 0, .i = 5 }, .{ .l = -1, .i = 7 }, .{ .l = -1, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 0 }, .{ .l = 0, .i = 2 }, .{ .l = 0, .i = 6 }, .{ .l = -1, .i = 7 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 1 }, .{ .l = 0, .i = 3 }, .{ .l = 0, .i = 7 }, .{ .l = -1, .i = 7 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 2 }, .{ .l = 0, .i = 4 }, .{ .l = 0, .i = 8 }, .{ .l = -1, .i = 7 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 3 }, .{ .l = 0, .i = 9 }, .{ .l = -1, .i = 7 }, .{ .l = -1, .i = 13 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 0 }, .{ .l = 0, .i = 6 }, .{ .l = 0, .i = 10 }, .{ .l = -1, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 1 }, .{ .l = 0, .i = 5 }, .{ .l = 0, .i = 7 }, .{ .l = 0, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 2 }, .{ .l = 0, .i = 6 }, .{ .l = 0, .i = 8 }, .{ .l = 1, .i = 0 }, .{ .l = 1, .i = 1 }, .{ .l = 1, .i = 2 }, .{ .l = 1, .i = 3 }, .{ .l = 1, .i = 4 } }, [8]?NeighbourSquare{ .{ .l = 0, .i = 3 }, .{ .l = 0, .i = 7 }, .{ .l = 0, .i = 9 }, .{ .l = 0, .i = 13 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 4 }, .{ .l = 0, .i = 8 }, .{ .l = 0, .i = 14 }, .{ .l = -1, .i = 13 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 5 }, .{ .l = 0, .i = 11 }, .{ .l = 0, .i = 15 }, .{ .l = -1, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 6 }, .{ .l = 0, .i = 10 }, .{ .l = 0, .i = 16 }, .{ .l = 1, .i = 0 }, .{ .l = 1, .i = 5 }, .{ .l = 1, .i = 10 }, .{ .l = 1, .i = 15 }, .{ .l = 1, .i = 20 } }, [8]?NeighbourSquare{ null, null, null, null, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 8 }, .{ .l = 0, .i = 14 }, .{ .l = 0, .i = 18 }, .{ .l = 1, .i = 4 }, .{ .l = 1, .i = 9 }, .{ .l = 1, .i = 14 }, .{ .l = 1, .i = 19 }, .{ .l = 1, .i = 24 } }, [8]?NeighbourSquare{ .{ .l = 0, .i = 9 }, .{ .l = 0, .i = 13 }, .{ .l = 0, .i = 19 }, .{ .l = -1, .i = 13 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 10 }, .{ .l = 0, .i = 16 }, .{ .l = 0, .i = 20 }, .{ .l = -1, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 11 }, .{ .l = 0, .i = 15 }, .{ .l = 0, .i = 17 }, .{ .l = 0, .i = 21 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 22 }, .{ .l = 0, .i = 16 }, .{ .l = 0, .i = 18 }, .{ .l = 1, .i = 20 }, .{ .l = 1, .i = 21 }, .{ .l = 1, .i = 22 }, .{ .l = 1, .i = 23 }, .{ .l = 1, .i = 24 } }, [8]?NeighbourSquare{ .{ .l = 0, .i = 13 }, .{ .l = 0, .i = 17 }, .{ .l = 0, .i = 19 }, .{ .l = 0, .i = 23 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 14 }, .{ .l = 0, .i = 18 }, .{ .l = 0, .i = 24 }, .{ .l = -1, .i = 13 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 21 }, .{ .l = 0, .i = 15 }, .{ .l = -1, .i = 17 }, .{ .l = -1, .i = 11 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 20 }, .{ .l = 0, .i = 22 }, .{ .l = 0, .i = 16 }, .{ .l = -1, .i = 17 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 21 }, .{ .l = 0, .i = 23 }, .{ .l = 0, .i = 17 }, .{ .l = -1, .i = 17 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 22 }, .{ .l = 0, .i = 24 }, .{ .l = 0, .i = 18 }, .{ .l = -1, .i = 17 }, null, null, null, null }, [8]?NeighbourSquare{ .{ .l = 0, .i = 23 }, .{ .l = 0, .i = 19 }, .{ .l = -1, .i = 17 }, .{ .l = -1, .i = 13 }, null, null, null, null }, }; //@setEvalBranchQuota(4000); var neib = [1][3]Grid{[3]Grid{ null_grid, null_grid, null_grid }} ** 25; for (neib) |*layers, i| { for (table[i]) |maybe_square| { if (maybe_square) |sq| layers[1 + sq.l].set(sq.i); } } break :blk neib; }; pub fn run(_: []const u8, allocator: std.mem.Allocator) tools.RunError![2][]const u8 { const text = \\ ..### \\ .#### \\ ...#. \\ .#..# \\ #.### ; //const text = // \\ ....# // \\ #..#. // \\ #..## // \\ ..#.. // \\ #.... //; const start_grid = comptime blk: { var g = null_grid; var i: u32 = 0; for (text) |c| { if (c == '.' or c == '#') { if (c == '#') g.set(i); i += 1; } } assert(i == 5 * 5); break :blk g; }; const ans1 = ans: { const Visited = std.StaticBitSet(1 << 25); // 4Mo var visited = Visited.initEmpty(); const neibourgh_masks = neibourgh_masks_part1; for (neibourgh_masks) |g| trace_grid("neibourgh_mask:\n", g); trace_grid("start_grid:\n", start_grid); var cur = start_grid; while (true) { const biodiversity = @intCast(usize, cur.mask) & 0b11111_11111_11111_11111_11111; // zig bug u25->usize garbage bits if (visited.isSet(biodiversity)) { break :ans biodiversity; } visited.set(biodiversity); const next = step: { var new: Grid = undefined; var i: u32 = 0; while (i < 25) : (i += 1) { //const count = @reduce(.Add, @as(@Vector(25, u4), cur & neibourgh_masks[i])); // pfff. TODO u25 + popcount... const count = @popCount(u25, cur.mask & neibourgh_masks[i].mask); if (cur.isSet(i)) { new.setValue(i, (count == 1)); } else { new.setValue(i, (count == 2 or count == 1)); } } break :step new; }; cur = next; } unreachable; }; const ans2 = ans: { const masks = neibourgh_masks_part2; var world = [1]Grid{null_grid} ** 300; world[world.len / 2] = start_grid; // ultime layer: zero padding // penultième layer: canari assert(world[0].mask == 0 and world[1].mask == 0 and world[world.len - 1].mask == 0 and world[world.len - 2].mask == 0); var minutes: u32 = 0; while (minutes < 200) : (minutes += 1) { const next = step: { var new: [world.len]Grid = undefined; new[0] = null_grid; new[world.len - 1] = null_grid; std.mem.set(Grid, &new, null_grid); // zig bug work-around (u25 vs padding bits for u32) for (new[1 .. world.len - 1]) |*layer, idx| { var i: u32 = 0; while (i < 25) : (i += 1) { const count = 0 // + @popCount(u25, world[(idx + 1) - 1].mask & masks[i][0].mask) // + @popCount(u25, world[(idx + 1) + 0].mask & masks[i][1].mask) // + @popCount(u25, world[(idx + 1) + 1].mask & masks[i][2].mask); if (world[(idx + 1) + 0].isSet(i)) { layer.setValue(i, (count == 1)); } else { layer.setValue(i, (count == 2 or count == 1)); } } } break :step new; }; // assert((next[0].mask | next[1].mask | next[world.len - 1].mask | next[world.len - 2].mask) == 0); // zig bug assert(@as(usize, (next[0].mask | next[1].mask | next[world.len - 1].mask | next[world.len - 2].mask)) & 0b11111_11111_11111_11111_11111 == 0); world = next; } var total: usize = 0; for (world) |layer| { // if (layer.mask != 0) trace_grid("layer :\n", layer); total += @popCount(u25, layer.mask); } break :ans total; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("", run);
2019/day24.zig
const sf = @import("../sfml.zig"); pub const RenderWindow = struct { const Self = @This(); // Constructor/destructor // TODO : choose style of window /// Inits a render window with a size, a bits per pixel (most put 32) and a title /// The window will have the default style pub fn init(size: sf.Vector2u, bpp: usize, title: [:0]const u8) !Self { var ret: Self = undefined; var mode: sf.c.sfVideoMode = .{ .width = @intCast(c_uint, size.x), .height = @intCast(c_uint, size.y), .bitsPerPixel = @intCast(c_uint, bpp), }; var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), sf.c.sfDefaultStyle, 0); if (window) |w| { ret.ptr = w; } else { return sf.Error.windowCreationFailed; } return ret; } /// Destroys this window object pub fn deinit(self: Self) void { sf.c.sfRenderWindow_destroy(self.ptr); } // Event related /// Returns true if this window is still open pub fn isOpen(self: Self) bool { return sf.c.sfRenderWindow_isOpen(self.ptr) != 0; } /// Closes this window pub fn close(self: Self) void { sf.c.sfRenderWindow_close(self.ptr); } /// Gets an event from the queue, returns null is theres none /// Use while on this to get all the events in your game loop pub fn pollEvent(self: Self) ?sf.Event { var event: sf.c.sfEvent = undefined; if (sf.c.sfRenderWindow_pollEvent(self.ptr, &event) == 0) return null; return sf.Event.fromCSFML(event); } // Drawing functions /// Clears the drawing screen with a color pub fn clear(self: Self, color: sf.Color) void { sf.c.sfRenderWindow_clear(self.ptr, color.toCSFML()); } /// Displays what has been drawn on the render area pub fn display(self: Self) void { sf.c.sfRenderWindow_display(self.ptr); } /// Draw something on the screen (won't be visible until display is called) /// Object must be a SFML object from the wrapper /// You can pass a render state or null for default pub fn draw(self: Self, to_draw: anytype, states: ?*sf.c.sfRenderStates) void { switch (@TypeOf(to_draw)) { sf.Sprite => sf.c.sfRenderWindow_drawSprite(self.ptr, to_draw.ptr, states), sf.CircleShape => sf.c.sfRenderWindow_drawCircleShape(self.ptr, to_draw.ptr, states), sf.RectangleShape => sf.c.sfRenderWindow_drawRectangleShape(self.ptr, to_draw.ptr, states), sf.Text => sf.c.sfRenderWindow_drawText(self.ptr, to_draw.ptr, states), else => @compileError("You must provide a drawable object"), } } // Getters/setters /// Gets the current view of the window /// Unlike in SFML, you don't get a const pointer but a copy pub fn getView(self: Self) sf.View { return sf.View.fromCSFML(sf.c.sfRenderWindow_getView(self.ptr).?); } /// Gets the default view of this window /// Unlike in SFML, you don't get a const pointer but a copy pub fn getDefaultView(self: Self) sf.View { return sf.View.fromCSFML(sf.c.sfRenderWindow_getDefaultView(self.ptr).?); } /// Sets the view of this window pub fn setView(self: Self, view: sf.View) void { var cview = view.toCSFML(); defer sf.c.sfView_destroy(cview); sf.c.sfRenderWindow_setView(self.ptr, cview); } /// Gets the size of this window pub fn getSize(self: Self) sf.Vector2u { return sf.Vector2u.fromCSFML(sf.c.sfRenderWindow_getSize(self.ptr)); } /// Sets the size of this window pub fn setSize(self: Self, size: sf.Vector2u) void { sf.c.sfRenderWindow_setSize(self.ptr, size.toCSFML()); } /// Gets the position of this window pub fn getPosition(self: Self) sf.Vector2i { return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_getPosition(self.ptr)); } /// Sets the position of this window pub fn setPosition(self: Self, pos: sf.Vector2i) void { sf.c.sfRenderWindow_setPosition(self.ptr, pos.toCSFML()); } // TODO : unicode title? /// Sets the title of this window pub fn setTitle(self: Self, title: [:0]const u8) void { sf.c.sfRenderWindow_setTitle(self.ptr, title); } /// Sets the windows's framerate limit pub fn setFramerateLimit(self: Self, fps: c_uint) void { sf.c.sfRenderWindow_setFramerateLimit(self.ptr, fps); } /// Enables or disables vertical sync pub fn setVerticalSyncEnabled(self: Self, enabled: bool) void { sf.c.sfRenderWindow_setFramerateLimit(self.ptr, if (enabled) 1 else 0); } /// Convert a point from target coordinates to world coordinates, using the current view (or the specified view) pub fn mapPixelToCoords(self: Self, pixel: sf.Vector2i, view: ?sf.View) sf.Vector2f { if (view) |v| { var cview = v.toCSFML(); defer sf.c.sfView_destroy(cview); return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), cview)); } else return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), null)); } /// Convert a point from world coordinates to target coordinates, using the current view (or the specified view) pub fn mapCoordsToPixel(self: Self, coords: sf.Vector2f, view: ?sf.View) sf.Vector2i { if (view) |v| { var cview = v.toCSFML(); defer sf.c.sfView_destroy(cview); return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), cview)); } else return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), null)); } /// Pointer to the csfml structure ptr: *sf.c.sfRenderWindow };
src/sfml/graphics/render_window.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/day02.txt"); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; const actionList = try util.parseDay02FileString(allocator, util.ReadType.ArrayList, data); const part1Answer = doPart1(actionList); std.debug.print("Part 1 answer = {any}\n", .{part1Answer}); const part2Answer = doPart2(actionList); std.debug.print("Part 2 answer = {any}\n", .{part2Answer}); } fn doPart1(actions : []util.MoveAction) u64 { var depth : u64 = 0; var distance : u64 = 0; var i : usize = 0; while (i < actions.len) : (i += 1) { const currentAction = actions[i]; switch (currentAction.direction) { util.Direction.Forward => distance += currentAction.length, util.Direction.Down => depth += currentAction.length, util.Direction.Up => depth -= currentAction.length, } } std.debug.print("Function Depth = {any}\n", .{depth}); std.debug.print("Function Distance = {any}\n", .{distance}); return depth * distance; } fn doPart2(actions : []util.MoveAction) u64 { var depth : u64 = 0; var distance : u64 = 0; var aim : u64 = 0; var i : usize = 0; while (i < actions.len) : (i += 1) { const currentAction = actions[i]; switch (currentAction.direction) { util.Direction.Forward => { distance += currentAction.length; depth += aim * currentAction.length; }, util.Direction.Down => aim += currentAction.length, util.Direction.Up => aim -= currentAction.length, } } std.debug.print("Function Depth = {any}\n", .{depth}); std.debug.print("Function Distance = {any}\n", .{distance}); return depth * distance; } // 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/day02.zig
const std = @import("std"); const lua = @import("lua.zig").lua; const sqlite = @import("sqlite.zig").sqlite; const base16 = @import("base16.zig").standard_base16; const c = @import("card.zig"); const Card = c.Card; const CardSchema = c.CardSchema; const e = @import("engine.zig"); const Engine = e.Engine; const EngineError = e.EngineError; const ByteCodeError = e.ByteCodeError; const DatabaseError = e.DatabaseError; const i = @import("image.zig"); const Image = i.Image; pub fn init(L: ?*lua.lua_State, db: ?*sqlite.sqlite3) void { lua.luaL_openlibs(L); lua.lua_register(L, "loadImg", loadImg); lua.lua_pushlightuserdata(L, db); lua.lua_setglobal(L, "__db__"); } pub fn getString(engine: *const Engine, field: CardSchema) EngineError![]const u8 { _ = lua.lua_getfield(engine.L, 1, @tagName(field)); if (lua.lua_isstring(engine.L, -1) != 1) { lua.lua_pop(engine.L, 1); const string = "invalid field expected string"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } var field_length: usize = 0; const field_value = lua.lua_tolstring(engine.L, -1, &field_length); lua.lua_pop(engine.L, 1); const result = try engine.allocator.dupe(u8, field_value[0..@intCast(usize, field_length)]); errdefer engine.allocator.free(result); return result; } pub fn checkVersionMajor(engine: *const Engine) EngineError!f64 { const field_type = lua.lua_getfield(engine.L, 1, @tagName(CardSchema.VersionMajor)); if (field_type != lua.LUA_INT_TYPE) { lua.lua_pop(engine.L, 1); const string = "Card.VersionMajor is required to be an integer"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } const majorVersion = lua.lua_tonumberx(engine.L, -1, null); lua.lua_pop(engine.L, 1); if (majorVersion > e.EngineMajor) { const string = "Card.VersionMajor is greater this engine supports"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } return majorVersion; } pub fn checkversionMinor(engine: *const Engine) EngineError!f64 { const field_type = lua.lua_getfield(engine.L, 1, @tagName(CardSchema.VersionMinor)); if (field_type != lua.LUA_INT_TYPE) { lua.lua_pop(engine.L, 1); const string = "Card.VersionMinor is required to be an integer"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } const versionMinor = lua.lua_tonumberx(engine.L, -1, null); lua.lua_pop(engine.L, 1); if (versionMinor > e.EngineMinor) { const string = "Card.VersionMinor is greater than engine supports"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } return versionMinor; } pub fn checkReturn(engine: *const Engine) EngineError!void { // checks that the return was a table if (!lua.lua_istable(engine.L, 1)) { lua.lua_pop(engine.L, 1); const string = "return value must be a Card table"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } } pub fn validateHash(engine: *const Engine, card_id: anytype, provided_hash: anytype) EngineError!void { var res: ?*sqlite.sqlite3_stmt = undefined; defer _ = sqlite.sqlite3_finalize(res); var rc = sqlite.sqlite3_prepare_v2(engine.db, "SELECT data FROM 'card_blocks' WHERE card_id=$1", -1, &res, 0); if (rc != sqlite.SQLITE_OK) return DatabaseError.Prepare; rc = sqlite.sqlite3_bind_text(res, 1, card_id.ptr, @intCast(c_int, card_id.len), null); if (rc != sqlite.SQLITE_OK) return DatabaseError.Bind; var binary_hash: [32]u8 = undefined; var encoded_hash: [64]u8 = undefined; var hash = std.crypto.hash.sha2.Sha256.init(.{}); while (sqlite.sqlite3_step(res) == sqlite.SQLITE_ROW) { const block_length = sqlite.sqlite3_column_bytes(res, 0); const block_data = sqlite.sqlite3_column_text(res, 0); hash.update(block_data[0..@intCast(usize, block_length)]); } hash.final(&binary_hash); base16.encode(&encoded_hash, &binary_hash); if (!std.mem.eql(u8, encoded_hash[0..encoded_hash.len], provided_hash)) return DatabaseError.HashCheck; } pub fn getImage(engine: *const Engine, field: CardSchema) EngineError!Image { _ = lua.lua_getfield(engine.L, 1, @tagName(field)); if (lua.lua_isstring(engine.L, -1) != 1) { lua.lua_pop(engine.L, 1); const string = "invalid field expected binary blob"; _ = lua.lua_pushlstring(engine.L, string, string.len); return ByteCodeError.InvalidReturn; } var img_size: usize = 0; const img_value = lua.lua_tolstring(engine.L, -1, &img_size); const result = try engine.allocator.dupe(u8, img_value[0..@intCast(usize, img_size)]); errdefer engine.allocator.free(result); lua.lua_pop(engine.L, 1); return Image.init(engine.allocator, result) catch { _ = lua.lua_pushfstring(engine.L, "could not load image"); return ByteCodeError.InvalidReturn; }; } export fn loadImg(L: ?*lua.lua_State) c_int { var name_length: usize = 0; const name = lua.luaL_checklstring(L, 1, &name_length); _ = lua.lua_pop(L, 1); const db = getDB(L); var res: ?*sqlite.sqlite3_stmt = undefined; defer _ = sqlite.sqlite3_finalize(res); var rc = sqlite.sqlite3_prepare_v2(db, "SELECT id,data FROM 'card_blocks' WHERE name=$1;", -1, &res, 0); if (rc != sqlite.SQLITE_OK) return lua.luaL_error(L, "could not prepare statement %s %s", sqlite.sqlite3_errstr(rc), sqlite.sqlite3_errmsg(db)); rc = sqlite.sqlite3_bind_text(res, 1, name, @intCast(c_int, name_length), null); if (rc != sqlite.SQLITE_OK) return lua.luaL_error(L, "could not bind statement %s", sqlite.sqlite3_errstr(rc)); rc = sqlite.sqlite3_step(res); if (rc == sqlite.SQLITE_ROW) { // const id = sqlite.sqlite3_column_text(res, 0); const block = sqlite.sqlite3_column_text(res, 1); const block_length = sqlite.sqlite3_column_bytes(res, 1); _ = lua.lua_pushlstring(L, block, @intCast(usize, block_length)); return 1; } else { return lua.luaL_error(L, "Could not load image: %s %s", name, sqlite.sqlite3_errstr(rc)); } } fn getDB(L: ?*lua.lua_State) ?*sqlite.sqlite3 { _ = lua.lua_getglobal(L, "__db__"); if (lua.lua_isuserdata(L, 1) != 1) { _ = lua.lua_pop(L, 1); // this never returns _ = lua.luaL_error(L, "could not read database"); unreachable; } var voidp = lua.lua_touserdata(L, 1); _ = lua.lua_pop(L, 1); return @ptrCast(?*sqlite.sqlite3, @alignCast(@alignOf(?*sqlite.sqlite3), voidp)); }
engine/src/util.zig
const std = @import("std"); const assert = std.debug.assert; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var input_file = try std.fs.cwd().openFile("input/12.txt", .{}); defer input_file.close(); var buffered_reader = std.io.bufferedReader(input_file.reader()); const count = try countPaths(allocator, buffered_reader.reader()); std.debug.print("number of paths: {}\n", .{count}); } fn countPaths(gpa: std.mem.Allocator, reader: anytype) !u64 { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const allocator = arena.allocator(); var buf: [4096]u8 = undefined; var nodes = std.StringHashMap(u32).init(allocator); try nodes.put("start", 0); try nodes.put("end", 1); var edges = std.ArrayList(std.ArrayList(u32)).init(allocator); try edges.appendNTimes(std.ArrayList(u32).init(allocator), 2); var big_caves = std.ArrayList(u32).init(allocator); while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { var iter = std.mem.split(u8, line, "-"); const origin = iter.next() orelse return error.WrongFormat; const dest = iter.next() orelse return error.WrongFormat; if (iter.next() != null) return error.WrongFormat; if (!nodes.contains(origin)) { const id = nodes.count(); try nodes.put(try allocator.dupe(u8, origin), id); try edges.append(std.ArrayList(u32).init(allocator)); if ('A' <= origin[0] and origin[0] <= 'Z') try big_caves.append(id); } if (!nodes.contains(dest)) { const id = nodes.count(); try nodes.put(try allocator.dupe(u8, dest), id); try edges.append(std.ArrayList(u32).init(allocator)); if ('A' <= dest[0] and dest[0] <= 'Z') try big_caves.append(id); } const origin_id = nodes.get(origin).?; const dest_id = nodes.get(dest).?; try edges.items[origin_id].append(dest_id); try edges.items[dest_id].append(origin_id); } // { // std.debug.print("--- Nodes ---\n", .{}); // var iter = nodes.iterator(); // while (iter.next()) |entry| { // std.debug.print("{s}: {}\n", .{ entry.key_ptr.*, entry.value_ptr.* }); // } // } // { // std.debug.print("--- Edges ---\n", .{}); // for (edges.items) |x, i| { // std.debug.print("{}: {any}\n", .{ i, x.items }); // } // } // { // std.debug.print("--- Big caves ---\n", .{}); // for (big_caves.items) |x| { // std.debug.print("{}\n", .{x}); // } // } return countFurtherPaths( allocator, edges.items, big_caves.items, &[_]u32{0}, ); } fn countFurtherPaths( allocator: std.mem.Allocator, edges: []const std.ArrayList(u32), big_caves: []const u32, current_path: []const u32, ) std.mem.Allocator.Error!u64 { const current_node = current_path[current_path.len - 1]; if (current_node == 1) return 1; const neighbors = edges[current_node].items; var path_array_list = std.ArrayList(u32).fromOwnedSlice(allocator, try allocator.dupe(u32, current_path)); defer path_array_list.deinit(); var sum: u64 = 0; // std.debug.print("at {}\n", .{current_node}); for (neighbors) |neighbor| { // never visit start again if (neighbor == 0) continue; // check if we visited this node before and this node is not a // big cave const visited_before = std.mem.indexOfScalar(u32, current_path, neighbor) != null; const big_cave = std.mem.indexOfScalar(u32, big_caves, neighbor) != null; const visited_small_cave_twice_before = for (current_path) |x, i| { // skip if big cave if (std.mem.indexOfScalar(u32, big_caves, x) != null) continue; // skip if start if (x == 0) continue; if (std.mem.indexOfScalarPos(u32, current_path, i + 1, x) != null) break true; } else false; if (visited_small_cave_twice_before and visited_before and !big_cave) continue; try path_array_list.append(neighbor); defer _ = path_array_list.pop(); sum += try countFurtherPaths( allocator, edges, big_caves, path_array_list.items, ); } return sum; } test "example 1" { const text = \\start-A \\start-b \\A-c \\A-b \\b-d \\A-end \\b-end ; var fbs = std.io.fixedBufferStream(text); const count = try countPaths(std.testing.allocator, fbs.reader()); try std.testing.expectEqual(@as(u64, 36), count); } test "example 2" { const text = \\dc-end \\HN-start \\start-kj \\dc-start \\dc-HN \\LN-dc \\HN-end \\kj-sa \\kj-HN \\kj-dc ; var fbs = std.io.fixedBufferStream(text); const count = try countPaths(std.testing.allocator, fbs.reader()); try std.testing.expectEqual(@as(u64, 103), count); } test "example 1" { const text = \\fs-end \\he-DX \\fs-he \\start-DX \\pj-DX \\end-zg \\zg-sl \\zg-pj \\pj-he \\RW-he \\fs-DX \\pj-RW \\zg-RW \\start-pj \\he-WI \\zg-he \\pj-fs \\start-RW ; var fbs = std.io.fixedBufferStream(text); const count = try countPaths(std.testing.allocator, fbs.reader()); try std.testing.expectEqual(@as(u64, 3509), count); }
src/12_2.zig
const std = @import("std"); const pokemon = @import("pokemon"); const utils = @import("utils"); const constants = @import("gen2-constants.zig"); const search = @import("search.zig"); const fun = @import("../../lib/fun-with-zig/index.zig"); const debug = std.debug; const mem = std.mem; const math = std.math; const common = pokemon.common; const gen2 = pokemon.gen2; const lu16 = fun.platform.lu16; const Offset = struct { start: usize, len: usize, fn fromSlice(start: usize, comptime T: type, slice: []const T) Offset { return Offset{ .start = @ptrToInt(slice.ptr) - start, .len = slice.len, }; } }; const Info = struct { base_stats: Offset, trainer_group_pointers: Offset, trainer_group_lenghts: []u8, }; pub fn findInfoInFile(data: []const u8, version: pokemon.Version, allocator: *mem.Allocator) !Info { // In gen2, trainers are split into groups. Each group have attributes for their items, reward ai and so on. // The game does not store the size of each group anywere oviuse, so we have to figure out the size of each // group. var trainer_group_pointers: []const lu16 = undefined; var trainer_group_lenghts: []u8 = undefined; switch (version) { pokemon.Version.Crystal => { // First, we find the first and last group pointers const first_group_pointer = indexOfTrainer(data, 0, constants.first_trainers) orelse return error.TrainerGroupsNotFound; const last_group_pointer = indexOfTrainer(data, first_group_pointer, constants.last_trainers) orelse return error.TrainerGroupsNotFound; // Then, we can find the group pointer table const first_group_pointers = []lu16{lu16.init(@intCast(u16, first_group_pointer))}; const last_group_pointers = []lu16{lu16.init(@intCast(u16, last_group_pointer))}; trainer_group_pointers = search.findStructs( lu16, [][]const u8{}, data, first_group_pointers, last_group_pointers, ) orelse return error.UnableToFindBaseStatsOffset; // Ensure that the pointers are in ascending order. for (trainer_group_pointers[1..]) |item, i| { const prev = trainer_group_pointers[i - 1]; if (prev.value() > item.value()) return error.TrainerGroupsNotFound; } trainer_group_lenghts = try allocator.alloc(u8, trainer_group_pointers.len); // If the pointers are in ascending order, then we will assume that pointers[i] // is terminated by pointers[i + 1], so we can just check for all parties between // this range to find the group count for each group. // For poiners[pointers.len - 1], we will look until we hit an invalid party. for (trainer_group_pointers) |_, i| { const is_last = i + 1 == trainer_group_pointers.len; var curr = trainer_group_pointers[i].value(); const next = if (!is_last) trainer_group_pointers[i + 1].value() else math.maxInt(u16); group_loop: while (curr < next) : (trainer_group_lenghts[i] += 1) { // Skip, until we find the string terminator for the trainer name while (data[curr] != '\x50') curr += 1; curr += 1; // Skip terminator const trainer_type = data[curr]; const valid_type_bits: u8 = gen2.Party.has_moves | gen2.Party.has_item; if (trainer_type & ~(valid_type_bits) != 0) break :group_loop; curr += 1; // Validate trainers party while (data[curr] != 0xFF) { const level = data[curr]; const species = data[curr + 1]; if (level > 100) break :group_loop; curr += 2; if (trainer_type & gen2.Party.has_item != 0) curr += 1; if (trainer_type & gen2.Party.has_moves != 0) curr += 4; } } } for (trainer_group_lenghts) |b| { debug.warn("{}, ", b); } }, else => unreachable, } const ignored_base_stat_fields = [][]const u8{ "dimension_of_front_sprite", "blank", "machine_learnset", "gender_ratio", "egg_group1_pad", "egg_group2_pad" }; const base_stats = search.findStructs( gen2.BasePokemon, ignored_base_stat_fields, data, constants.first_base_stats, constants.last_base_stats, ) orelse { return error.UnableToFindBaseStatsOffset; }; const start = @ptrToInt(data.ptr); return Info{ .base_stats = Offset.fromSlice(start, gen2.BasePokemon, base_stats), .trainer_group_pointers = Offset.fromSlice(start, lu16, trainer_group_pointers), .trainer_group_lenghts = trainer_group_lenghts, }; } fn indexOfTrainer(data: []const u8, start_index: usize, trainers: []const constants.Trainer) ?usize { const bytes = blk: { var res: usize = 0; for (trainers) |trainer| { res += trainer.name.len; res += 2 * trainer.party.len; // level, species if (trainer.kind & gen2.Party.has_item != 0) res += 1 * trainer.party.len; if (trainer.kind & gen2.Party.has_moves != 0) res += 4 * trainer.party.len; res += 1; // trainer terminator } break :blk res; }; if (data.len < bytes) return null; var i = start_index; var end = data.len - bytes; search_loop: while (i <= end) : (i += 1) { var off = i; for (trainers) |trainer, j| { off += trainer.name.len; if (!mem.eql(u8, trainer.name, data[i..off])) continue :search_loop; if (data[off] != trainer.kind) continue :search_loop; off += 1; for (trainer.party) |member| { if (data[off] != member.base.level) continue :search_loop; if (data[off + 1] != member.base.species) continue :search_loop; off += 2; if (trainer.kind & gen2.Party.has_item != 0) { if (data[off] != member.item) continue :search_loop; off += 1; } if (trainer.kind & gen2.Party.has_moves != 0) { if (!mem.eql(u8, data[off..][0..4], member.moves)) continue :search_loop; off += 4; } } if (data[off] != 0xFF) continue :search_loop; off += 1; } return i; } return null; }
tools/offset-finder/gen2.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const HashMap = std.AutoHashMap(u36, u36); const eql = std.mem.eql; const tokenize = std.mem.tokenize; const parseUnsigned = std.fmt.parseUnsigned; const Mask = struct { on: u36, off: u36, float: u36 }; const u36_max = ~@as(u36, 0); fn parseMask(str: []const u8, mask: *Mask) void { mask.on = 0; mask.off = u36_max; mask.float = 0; for (str) |c, i| { if (c == '0') { mask.off ^= @as(u36, 1) << @intCast(u6, 35 - i); } else if (c == '1') { mask.on ^= @as(u36, 1) << @intCast(u6, 35 - i); } else if (c == 'X') { mask.float ^= @as(u36, 1) << @intCast(u6, 35 - i); } } } fn parseAssignA(lhs: []const u8, rhs: []const u8, mem: *HashMap, mask: Mask) !void { var l = tokenize(lhs, "[]"); _ = l.next(); const addr = try parseUnsigned(u36, l.next().?, 10); var val = try parseUnsigned(u36, rhs, 10); val |= mask.on; // overwrite 1s in mask val &= mask.off; // overwrite 0s in mask try mem.put(addr, val); } fn parseAssignB(lhs: []const u8, rhs: []const u8, mem: *HashMap, mask: Mask) !void { const val = try parseUnsigned(u36, rhs, 10); var l = tokenize(lhs, "[]"); _ = l.next(); var addr = try parseUnsigned(u36, l.next().?, 10); addr |= mask.on; // overwrite 1s in mask // Loop over combinations of floating bits var i: u36 = 0; while (i < (@as(u36, 1) << @popCount(u36, mask.float))) : (i += 1) { var j: u6 = 0; var n: u6 = 0; while (j < 36) : (j += 1) { if ((mask.float >> j) & 1 == 1) { if ((i >> n) & 1 == 1) { addr |= @as(u36, 1) << j; } else { addr &= ~(@as(u36, 1) << j); } n += 1; } } try mem.put(addr, val); } } fn sum(memory: *HashMap) usize { var n: usize = 0; var iter = memory.iterator(); while (iter.next()) |entry| { n += entry.value_ptr.*; } return n; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Since memory is a sparse array use a hash map instead var memA = HashMap.init(allocator); var memB = HashMap.init(allocator); var mask: Mask = undefined; var stdin = std.io.getStdIn().reader(); var in = std.io.bufferedReader(stdin).reader(); var buf: [256]u8 = undefined; while (try in.readUntilDelimiterOrEof(&buf, '\n')) |line| { var iter = tokenize(line, " "); const lhs = iter.next().?; // mask or mem[] _ = iter.next().?; // = const rhs = iter.next().?; // value if (eql(u8, lhs, "mask")) { parseMask(rhs, &mask); } else { try parseAssignA(lhs, rhs, &memA, mask); try parseAssignB(lhs, rhs, &memB, mask); } } const na = sum(&memA); std.debug.print("A) Sum of all values in memory is {d}\n", .{na}); const nb = sum(&memB); std.debug.print("B) Sum of all values in memory is {d}\n", .{nb}); }
2020/zig/src/14.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "compile time recursion" { try expect(some_data.len == 21); } var some_data: [@intCast(usize, fibonacci(7))]u8 = undefined; fn fibonacci(x: i32) i32 { if (x <= 1) return 1; return fibonacci(x - 1) + fibonacci(x - 2); } fn unwrapAndAddOne(blah: ?i32) i32 { return blah.? + 1; } const should_be_1235 = unwrapAndAddOne(1234); test "static add one" { try expect(should_be_1235 == 1235); } test "inlined loop" { comptime var i = 0; comptime var sum = 0; inline while (i <= 5) : (i += 1) sum += i; try expect(sum == 15); } fn gimme1or2(comptime a: bool) i32 { const x: i32 = 1; const y: i32 = 2; comptime var z: i32 = if (a) x else y; return z; } test "inline variable gets result of const if" { try expect(gimme1or2(true) == 1); try expect(gimme1or2(false) == 2); } test "static function evaluation" { try expect(statically_added_number == 3); } const statically_added_number = staticAdd(1, 2); fn staticAdd(a: i32, b: i32) i32 { return a + b; } test "const expr eval on single expr blocks" { try expect(constExprEvalOnSingleExprBlocksFn(1, true) == 3); comptime try expect(constExprEvalOnSingleExprBlocksFn(1, true) == 3); } fn constExprEvalOnSingleExprBlocksFn(x: i32, b: bool) i32 { const literal = 3; const result = if (b) b: { break :b literal; } else b: { break :b x; }; return result; } test "constant expressions" { var array: [array_size]u8 = undefined; try expect(@sizeOf(@TypeOf(array)) == 20); } const array_size: u8 = 20; fn max(comptime T: type, a: T, b: T) T { if (T == bool) { return a or b; } else if (a > b) { return a; } else { return b; } } fn letsTryToCompareBools(a: bool, b: bool) bool { return max(bool, a, b); } test "inlined block and runtime block phi" { try expect(letsTryToCompareBools(true, true)); try expect(letsTryToCompareBools(true, false)); try expect(letsTryToCompareBools(false, true)); try expect(!letsTryToCompareBools(false, false)); comptime { try expect(letsTryToCompareBools(true, true)); try expect(letsTryToCompareBools(true, false)); try expect(letsTryToCompareBools(false, true)); try expect(!letsTryToCompareBools(false, false)); } } test "eval @setRuntimeSafety at compile-time" { const result = comptime fnWithSetRuntimeSafety(); try expect(result == 1234); } fn fnWithSetRuntimeSafety() i32 { @setRuntimeSafety(true); return 1234; } test "compile-time downcast when the bits fit" { comptime { const spartan_count: u16 = 255; const byte = @intCast(u8, spartan_count); try expect(byte == 255); } } test "pointer to type" { comptime { var T: type = i32; try expect(T == i32); var ptr = &T; try expect(@TypeOf(ptr) == *type); ptr.* = f32; try expect(T == f32); try expect(*T == *f32); } } test "a type constructed in a global expression" { var l: List = undefined; l.array[0] = 10; l.array[1] = 11; l.array[2] = 12; const ptr = @ptrCast([*]u8, &l.array); try expect(ptr[0] == 10); try expect(ptr[1] == 11); try expect(ptr[2] == 12); } const List = blk: { const T = [10]u8; break :blk struct { array: T, }; }; test "comptime function with the same args is memoized" { comptime { try expect(MakeType(i32) == MakeType(i32)); try expect(MakeType(i32) != MakeType(f64)); } } fn MakeType(comptime T: type) type { return struct { field: T, }; } test "try to trick eval with runtime if" { try expect(testTryToTrickEvalWithRuntimeIf(true) == 10); } fn testTryToTrickEvalWithRuntimeIf(b: bool) usize { comptime var i: usize = 0; inline while (i < 10) : (i += 1) { const result = if (b) false else true; _ = result; } comptime { return i; } } test "@setEvalBranchQuota" { comptime { // 1001 for the loop and then 1 more for the expect fn call @setEvalBranchQuota(1002); var i = 0; var sum = 0; while (i < 1001) : (i += 1) { sum += i; } try expect(sum == 500500); } } test "constant struct with negation" { try expect(vertices[0].x == @as(f32, -0.6)); } const Vertex = struct { x: f32, y: f32, r: f32, g: f32, b: f32, }; const vertices = [_]Vertex{ Vertex{ .x = -0.6, .y = -0.4, .r = 1.0, .g = 0.0, .b = 0.0, }, Vertex{ .x = 0.6, .y = -0.4, .r = 0.0, .g = 1.0, .b = 0.0, }, Vertex{ .x = 0.0, .y = 0.6, .r = 0.0, .g = 0.0, .b = 1.0, }, }; test "statically initialized list" { try expect(static_point_list[0].x == 1); try expect(static_point_list[0].y == 2); try expect(static_point_list[1].x == 3); try expect(static_point_list[1].y == 4); } const Point = struct { x: i32, y: i32, }; const static_point_list = [_]Point{ makePoint(1, 2), makePoint(3, 4), }; fn makePoint(x: i32, y: i32) Point { return Point{ .x = x, .y = y, }; } test "statically initialized array literal" { const y: [4]u8 = st_init_arr_lit_x; try expect(y[3] == 4); } const st_init_arr_lit_x = [_]u8{ 1, 2, 3, 4 }; const CmdFn = struct { name: []const u8, func: fn (i32) i32, }; const cmd_fns = [_]CmdFn{ CmdFn{ .name = "one", .func = one, }, CmdFn{ .name = "two", .func = two, }, CmdFn{ .name = "three", .func = three, }, }; fn one(value: i32) i32 { return value + 1; } fn two(value: i32) i32 { return value + 2; } fn three(value: i32) i32 { return value + 3; } fn performFn(comptime prefix_char: u8, start_value: i32) i32 { var result: i32 = start_value; comptime var i = 0; inline while (i < cmd_fns.len) : (i += 1) { if (cmd_fns[i].name[0] == prefix_char) { result = cmd_fns[i].func(result); } } return result; } test "comptime iterate over fn ptr list" { try expect(performFn('t', 1) == 6); try expect(performFn('o', 0) == 1); try expect(performFn('w', 99) == 99); } test "create global array with for loop" { try expect(global_array[5] == 5 * 5); try expect(global_array[9] == 9 * 9); } const global_array = x: { var result: [10]usize = undefined; for (result) |*item, index| { item.* = index * index; } break :x result; }; fn generateTable(comptime T: type) [1010]T { var res: [1010]T = undefined; var i: usize = 0; while (i < 1010) : (i += 1) { res[i] = @intCast(T, i); } return res; } fn doesAlotT(comptime T: type, value: usize) T { @setEvalBranchQuota(5000); const table = comptime blk: { break :blk generateTable(T); }; return table[value]; } test "@setEvalBranchQuota at same scope as generic function call" { try expect(doesAlotT(u32, 2) == 2); } pub const Info = struct { version: u8, }; pub const diamond_info = Info{ .version = 0 }; test "comptime modification of const struct field" { comptime { var res = diamond_info; res.version = 1; try expect(diamond_info.version == 0); try expect(res.version == 1); } } test "refer to the type of a generic function" { const Func = fn (type) void; const f: Func = doNothingWithType; f(i32); } fn doNothingWithType(comptime T: type) void { _ = T; } test "zero extend from u0 to u1" { var zero_u0: u0 = 0; var zero_u1: u1 = zero_u0; try expect(zero_u1 == 0); } test "return 0 from function that has u0 return type" { const S = struct { fn foo_zero() u0 { return 0; } }; comptime { if (S.foo_zero() != 0) { @compileError("test failed"); } } } test "statically initialized struct" { st_init_str_foo.x += 1; try expect(st_init_str_foo.x == 14); } const StInitStrFoo = struct { x: i32, y: bool, }; var st_init_str_foo = StInitStrFoo{ .x = 13, .y = true, }; test "inline for with same type but different values" { var res: usize = 0; inline for ([_]type{ [2]u8, [1]u8, [2]u8 }) |T| { var a: T = undefined; res += a.len; } try expect(res == 5); } test "f32 at compile time is lossy" { try expect(@as(f32, 1 << 24) + 1 == 1 << 24); } test "f64 at compile time is lossy" { try expect(@as(f64, 1 << 53) + 1 == 1 << 53); } test { comptime try expect(@as(f128, 1 << 113) == 10384593717069655257060992658440192); } fn copyWithPartialInline(s: []u32, b: []u8) void { comptime var i: usize = 0; inline while (i < 4) : (i += 1) { s[i] = 0; s[i] |= @as(u32, b[i * 4 + 0]) << 24; s[i] |= @as(u32, b[i * 4 + 1]) << 16; s[i] |= @as(u32, b[i * 4 + 2]) << 8; s[i] |= @as(u32, b[i * 4 + 3]) << 0; } } test "binary math operator in partially inlined function" { var s: [4]u32 = undefined; var b: [16]u8 = undefined; for (b) |*r, i| r.* = @intCast(u8, i + 1); copyWithPartialInline(s[0..], b[0..]); try expect(s[0] == 0x1020304); try expect(s[1] == 0x5060708); try expect(s[2] == 0x90a0b0c); try expect(s[3] == 0xd0e0f10); } test "comptime shl" { var a: u128 = 3; var b: u7 = 63; var c: u128 = 3 << 63; try expect((a << b) == c); } test "comptime bitwise operators" { comptime { try expect(3 & 1 == 1); try expect(3 & -1 == 3); try expect(-3 & -1 == -3); try expect(3 | -1 == -1); try expect(-3 | -1 == -1); try expect(3 ^ -1 == -4); try expect(-3 ^ -1 == 2); try expect(~@as(i8, -1) == 0); try expect(~@as(i128, -1) == 0); try expect(18446744073709551615 & 18446744073709551611 == 18446744073709551611); try expect(-18446744073709551615 & -18446744073709551611 == -18446744073709551615); try expect(~@as(u128, 0) == 0xffffffffffffffffffffffffffffffff); } } test "comptime shlWithOverflow" { const ct_shifted: u64 = comptime amt: { var amt = @as(u64, 0); _ = @shlWithOverflow(u64, ~@as(u64, 0), 16, &amt); break :amt amt; }; const rt_shifted: u64 = amt: { var amt = @as(u64, 0); _ = @shlWithOverflow(u64, ~@as(u64, 0), 16, &amt); break :amt amt; }; try expect(ct_shifted == rt_shifted); }
test/behavior/eval.zig
const builtin = @import("builtin"); const build_options = @import("build_options"); const std = @import("std"); const json = std.json; const log = std.log; const fs = std.fs; const Sha1 = std.crypto.hash.Sha1; const Base64 = std.base64.url_safe_no_pad.Encoder; // Foilz Archive Util const foilz = @import("archiver.zig"); // Maint utils const logger = @import("logger.zig"); const maint = @import("maintenance.zig"); const shutil = @import("shutil.zig"); const win_asni = @cImport(@cInclude("win_ansi_fix.h")); // Install dir suffix const install_suffix = ".tinfoil"; const plugin = @import("burrito_plugin"); const metadata = @import("metadata.zig"); const MetaStruct = metadata.MetaStruct; // Payload pub const FOILZ_PAYLOAD = @embedFile("../payload.foilz.gz"); pub const RELEASE_METADATA_JSON = @embedFile("../_metadata.json"); // Memory allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var allocator = arena.allocator(); // Windows cmd argument parser const windows = std.os.windows; const LPCWSTR = windows.LPCWSTR; const LPWSTR = windows.LPWSTR; pub extern "kernel32" fn GetCommandLineW() LPWSTR; pub extern "shell32" fn CommandLineToArgvW(lpCmdLine: LPCWSTR, out_pNumArgs: *c_int) ?[*]LPWSTR; pub fn main() anyerror!void { log.debug("Size of embedded payload is: {}", .{FOILZ_PAYLOAD.len}); // If this is not a production build, we always want a clean install const wants_clean_install = !build_options.IS_PROD; const meta = metadata.parse(allocator, RELEASE_METADATA_JSON).?; const install_dir = (try get_install_dir(&meta))[0..]; const metadata_path = try fs.path.join(allocator, &[_][]const u8{ install_dir, "_metadata.json" }); log.debug("Install Directory: {s}", .{install_dir}); log.debug("Metadata path: {s}", .{metadata_path}); // Ensure the destination directory is created try std.fs.cwd().makePath(install_dir); // If the metadata file exists, don't install again var needs_install: bool = false; std.fs.accessAbsolute(metadata_path, .{}) catch |err| { if (err == error.FileNotFound) { needs_install = true; } else { log.err("We failed to open the destination directory with an unexpected error: {s}", .{err}); return; } }; var args: ?[][]u8 = null; // Get argvs -- on Windows we need to call CommandLineToArgvW() with GetCommandLineW() if (builtin.os.tag == .windows) { // Windows arguments var arg_count: c_int = undefined; var raw_args = CommandLineToArgvW(GetCommandLineW(), &arg_count); var windows_arg_list = std.ArrayList([]u8).init(allocator); var i: c_int = 0; while (i < arg_count) : (i += 1) { var index = @intCast(usize, i); var length = std.mem.len(raw_args.?[index]); const argument = try std.unicode.utf16leToUtf8Alloc(allocator, raw_args.?[index][0..length]); try windows_arg_list.append(argument); } args = windows_arg_list.items; } else { // POSIX arguments args = try std.process.argsAlloc(allocator); } const args_trimmed = args.?[1..]; const args_string = try std.mem.join(allocator, " ", args_trimmed); log.debug("Passing args string: {s}", .{args_string}); // Execute plugin code plugin.burrito_plugin_entry(install_dir, RELEASE_METADATA_JSON); // If we need an install, install the payload onto the target machine if (needs_install or wants_clean_install) { try do_payload_install(install_dir, metadata_path); } else { log.debug("Skipping archive unpacking, this machine already has the app installed!", .{}); } // Check for maintenance commands if (args_trimmed.len > 0 and std.mem.eql(u8, args_trimmed[0], "maintenance")) { logger.info("Entering {s} maintenance mode...", .{build_options.RELEASE_NAME}); logger.info("Build metadata: {s}", .{RELEASE_METADATA_JSON}); try maint.do_maint(args_trimmed[1..], install_dir); return; } // Clean up older versions const base_install_path = try get_base_install_dir(); try maint.do_clean_old_versions(base_install_path, install_dir); // Get Env var env_map = try std.process.getEnvMap(allocator); // Add _IS_TTY env variable if (shutil.is_tty()) { try env_map.put("_IS_TTY", "1"); } else { try env_map.put("_IS_TTY", "0"); } // Get name of the exe (useful to pass into argv for the child erlang process) const exe_path = try fs.selfExePathAlloc(allocator); const exe_name = fs.path.basename(exe_path); // Compute the full base bin path const base_bin_path = try fs.path.join(allocator, &[_][]const u8{ install_dir, "bin", build_options.RELEASE_NAME }); log.debug("Base Executable Path: {s}", .{base_bin_path}); // Windows does not have a REAL execve, so instead the wrapper will hang around while the Erlang process runs // We'll use a ChildProcess with stdin and out being inherited if (builtin.os.tag == .windows) { // Fix up Windows 10+ consoles having ANSI escape support, but only if we set some flags win_asni.enable_virtual_term(); const bat_path = try std.mem.concat(allocator, u8, &[_][]const u8{ base_bin_path, ".bat" }); // HACK: To get aroung the many issues with escape characters (like ", ', =, !, and %) in Windows // we will encode each argument as a base64 string, these will be then be decoded using `Burrito.Util.Args.get_arguments/0`. try env_map.put("_ARGUMENTS_ENCODED", "1"); var encoded_list = std.ArrayList([]u8).init(allocator); defer encoded_list.deinit(); for (args_trimmed) |argument| { const encoded_len = std.base64.standard_no_pad.Encoder.calcSize(argument.len); const argument_encoded = try allocator.alloc(u8, encoded_len); _ = std.base64.standard_no_pad.Encoder.encode(argument_encoded, argument); try encoded_list.append(argument_encoded); } const win_args = &[_][]const u8{ bat_path, "start", exe_name }; const final_args = try std.mem.concat(allocator, []const u8, &.{ win_args, encoded_list.items }); const win_child_proc = try std.ChildProcess.init(final_args, allocator); win_child_proc.env_map = &env_map; win_child_proc.stdout_behavior = .Inherit; win_child_proc.stdin_behavior = .Inherit; log.debug("CLI List: {s}", .{final_args}); _ = try win_child_proc.spawnAndWait(); } else { const cli = &[_][]const u8{ base_bin_path, "start", exe_name, args_string }; log.debug("CLI List: {s}", .{cli}); return std.process.execve(allocator, cli, &env_map); } } fn do_payload_install(install_dir: []const u8, metadata_path: []const u8) !void { // Unpack the files try foilz.unpack_files(FOILZ_PAYLOAD, install_dir); // Write metadata file const file = try fs.createFileAbsolute(metadata_path, .{ .truncate = true }); try file.writeAll(RELEASE_METADATA_JSON); } fn get_base_install_dir() ![]const u8 { // If we have a override for the install path, use that, otherwise, continue to return // the standard install path const upper_name = try std.ascii.allocUpperString(allocator, build_options.RELEASE_NAME); const env_install_dir_name = try std.fmt.allocPrint(allocator, "{s}_INSTALL_DIR", .{upper_name}); if (std.process.getEnvVarOwned(allocator, env_install_dir_name)) |new_path| { logger.info("Install path is being overriden using `{s}`", .{env_install_dir_name}); logger.info("New install path is: {s}", .{new_path}); return try fs.path.join(allocator, &[_][]const u8{ new_path, install_suffix }); } else |err| switch (err) { error.InvalidUtf8 => {}, error.EnvironmentVariableNotFound => {}, error.OutOfMemory => {}, } const app_dir = fs.getAppDataDir(allocator, install_suffix) catch { install_dir_error(); return ""; }; return app_dir; } fn get_install_dir(meta: *const MetaStruct) ![]u8 { // Combine the hash of the payload and a base dir to get a safe install directory const base_install_path = try get_base_install_dir(); // Parse the ERTS version and app version from the metadata JSON string const dir_name = try std.fmt.allocPrint(allocator, "{s}_erts-{s}_{s}", .{ build_options.RELEASE_NAME, meta.erts_version, meta.app_version }); // Ensure that base directory is created std.os.mkdir(base_install_path, 0o755) catch |err| { if (err != error.PathAlreadyExists) { install_dir_error(); return ""; } }; // Construct the full app install path const name = fs.path.join(allocator, &[_][]const u8{ base_install_path, dir_name }) catch { install_dir_error(); return ""; }; return name; } fn install_dir_error() void { const upper_name = std.ascii.allocUpperString(allocator, build_options.RELEASE_NAME) catch { return; }; const env_install_dir_name = std.fmt.allocPrint(allocator, "{s}_INSTALL_DIR", .{upper_name}) catch { return; }; logger.err("We could not install this application to the default directory.", .{}); logger.err("This may be due to a permission error.", .{}); logger.err("Please override the default {s} install directory using the `{s}` environment variable.", .{ build_options.RELEASE_NAME, env_install_dir_name }); logger.err("On Linux or MacOS you can run the command: `export {s}=/some/other/path`", .{env_install_dir_name}); logger.err("On Windows you can use: `SET {s}=D:\\some\\other\\path`", .{env_install_dir_name}); std.process.exit(1); }
src/wrapper.zig
const std = @import("std"); const os = std.os; const warn = std.debug.warn; const syspect = @import("syspect"); /// Syscall only points to memory address, instead of directly containing values. /// To edit the ip/port, we need to edit the other process' memory. const sockaddr_rw = @import("memory_rw_netaddress.zig"); pub fn main() !void { const allocator = std.heap.c_allocator; const syscalls = &[_]os.SYS{ .connect, }; var inspector = syspect.Inspector.init(allocator, syscalls, .{}); try init(allocator, &inspector); defer inspector.deinit(); while (try inspector.next_syscall()) |*syscall| { switch (syscall.*) { .pre_call => |context| { try redirectConnectCall(context); try inspector.resume_tracee(context.pid); }, .post_call => |context| { try inspector.resume_tracee(context.pid); }, } } } fn usage(our_name: [*:0]u8) void { warn("{} requires an argument\n", .{our_name}); } fn init(allocator: *std.mem.Allocator, inspector: *syspect.Inspector) !void { if (os.argv.len <= 1) { usage(os.argv[0]); os.exit(1); } var target_argv = try allocator.alloc([]u8, os.argv.len - 1); defer allocator.free(target_argv); for (os.argv[1..os.argv.len]) |arg, index| { target_argv[index] = std.mem.span(arg); } _ = try inspector.spawn_process(allocator, target_argv); } fn redirectConnectCall(context: syspect.Context) !void { const sockaddr_register_ptr = @intCast(usize, context.registers.arg2); const sockaddr = try sockaddr_rw.readSockaddr_PVReadv(context.pid, sockaddr_register_ptr); if (sockaddr.family != os.AF_INET and sockaddr.family != os.AF_INET6) { return; } var address = std.net.Address.initPosix(@alignCast(4, &sockaddr)); warn("[{}] connect( {} )\n", .{ context.pid, address }); var buffer = [_]u8{0} ** 20; const stdin = std.io.getStdIn(); while (true) { warn("Please enter a port number (leave blank for unchanged):\n", .{}); var read_bytes = try stdin.read(buffer[0..]); if (buffer[read_bytes - 1] == '\n') read_bytes -= 1; if (read_bytes == 0) break; const user_input = buffer[0..read_bytes]; const new_port = std.fmt.parseInt(u16, user_input, 10) catch |err| { warn("\"{}\" is an invalid port number\n", .{user_input}); continue; }; address.setPort(new_port); break; } while (true) { warn("Please enter an ip address (leave blank for unchanged):\n", .{}); var read_bytes = try stdin.read(buffer[0..]); if (buffer[read_bytes - 1] == '\n') read_bytes -= 1; if (read_bytes == 0) break; const user_input = buffer[0..read_bytes]; const new_addr = std.net.Address.parseIp(user_input, address.getPort()) catch |err| { warn("\"{}\" is an invalid ip\n", .{user_input}); continue; }; address = new_addr; break; } warn("New address: {}\n", .{address}); _ = try sockaddr_rw.writeSockaddr_PVWritev(context.pid, sockaddr_register_ptr, address.any); }
examples/connect_redirector/main.zig
const std = @import("std"); const ini = @import("ini.zig"); const c = @cImport({ @cInclude("ini.h"); }); const Record = extern struct { type: Type, value: Data, const Type = extern enum { nul = 0, section = 1, property = 2, enumeration = 3, }; const Data = extern union { section: [*:0]const u8, property: KeyValuePair, enumeration: [*:0]const u8, }; const KeyValuePair = extern struct { key: [*:0]const u8, value: [*:0]const u8, }; }; const BufferParser = struct { stream: std.io.FixedBufferStream([]const u8), parser: ini.Parser(std.io.FixedBufferStream([]const u8).Reader), }; const IniParser = union(enum) { buffer: BufferParser, file: ini.Parser(CReader), }; const IniError = extern enum { success = 0, out_of_memory = 1, io = 2, invalid_data = 3, }; comptime { if (@sizeOf(c.ini_Parser) < @sizeOf(IniParser)) @compileError(std.fmt.comptimePrint("ini_Parser struct in header is too small. Please set the char array to at least {d} chars!", .{@sizeOf(IniParser)})); if (@alignOf(c.ini_Parser) < @alignOf(IniParser)) @compileError("align mismatch: ini_Parser struct does not match IniParser"); if (@sizeOf(c.ini_Record) != @sizeOf(Record)) @compileError("size mismatch: ini_Record struct does not match Record!"); if (@alignOf(c.ini_Record) != @alignOf(Record)) @compileError("align mismatch: ini_Record struct does not match Record!"); if (@sizeOf(c.ini_KeyValuePair) != @sizeOf(Record.KeyValuePair)) @compileError("size mismatch: ini_KeyValuePair struct does not match Record.KeyValuePair!"); if (@alignOf(c.ini_KeyValuePair) != @alignOf(Record.KeyValuePair)) @compileError("align mismatch: ini_KeyValuePair struct does not match Record.KeyValuePair!"); } export fn ini_create_buffer(parser: *IniParser, data: [*]const u8, length: usize) void { parser.* = IniParser{ .buffer = .{ .stream = std.io.fixedBufferStream(data[0..length]), .parser = undefined, }, }; // this is required to have the parser store a pointer to the stream. parser.buffer.parser = ini.parse(std.heap.c_allocator, parser.buffer.stream.reader()); } export fn ini_create_file(parser: *IniParser, file: *std.c.FILE) void { parser.* = IniParser{ .file = ini.parse(std.heap.c_allocator, cReader(file)), }; } export fn ini_destroy(parser: *IniParser) void { switch (parser.*) { .buffer => |*p| p.parser.deinit(), .file => |*p| p.deinit(), } parser.* = undefined; } const ParseError = error{ OutOfMemory, StreamTooLong } || CReader.Error; fn mapError(err: ParseError) IniError { return switch (err) { error.OutOfMemory => IniError.out_of_memory, error.StreamTooLong => IniError.invalid_data, else => IniError.io, }; } export fn ini_next(parser: *IniParser, record: *Record) IniError { const src_record_or_null: ?ini.Record = switch (parser.*) { .buffer => |*p| p.parser.next() catch |e| return mapError(e), .file => |*p| p.next() catch |e| return mapError(e), }; if (src_record_or_null) |src_record| { record.* = switch (src_record) { .section => |heading| Record{ .type = .section, .value = .{ .section = heading.ptr }, }, .enumeration => |enumeration| Record{ .type = .enumeration, .value = .{ .enumeration = enumeration.ptr }, }, .property => |property| Record{ .type = .property, .value = .{ .property = .{ .key = property.key.ptr, .value = property.value.ptr, } }, }, }; } else { record.* = Record{ .type = .nul, .value = undefined, }; } return .success; } const CReader = std.io.Reader(*std.c.FILE, std.fs.File.ReadError, cReaderRead); fn cReader(c_file: *std.c.FILE) CReader { return .{ .context = c_file }; } fn cReaderRead(c_file: *std.c.FILE, bytes: []u8) std.fs.File.ReadError!usize { const amt_written = std.c.fread(bytes.ptr, 1, bytes.len, c_file); if (amt_written >= 0) return amt_written; switch (std.c._errno().*) { 0 => unreachable, os.EINVAL => unreachable, os.EFAULT => unreachable, os.EAGAIN => unreachable, // this is a blocking API os.EBADF => unreachable, // always a race condition os.EDESTADDRREQ => unreachable, // connect was never called os.EDQUOT => return error.DiskQuota, os.EFBIG => return error.FileTooBig, os.EIO => return error.InputOutput, os.ENOSPC => return error.NoSpaceLeft, os.EPERM => return error.AccessDenied, os.EPIPE => return error.BrokenPipe, else => |err| return std.os.unexpectedErrno(err), } }
src/lib.zig
const std = @import("std"); const c = @cImport(@cInclude("ed25519.h")); const crypto = std.crypto; const testing = std.testing; export fn @"ed25519_randombytes_unsafe"(ptr: *c_void, len: usize) callconv(.C) void { crypto.random.bytes(@ptrCast([*]u8, ptr)[0..len]); } export fn @"ed25519_hash_init"(ctx: *crypto.hash.sha3.Sha3_512) callconv(.C) void { ctx.* = crypto.hash.sha3.Sha3_512.init(.{}); } export fn @"ed25519_hash_update"(ctx: *crypto.hash.sha3.Sha3_512, ptr: [*]const u8, len: usize) callconv(.C) void { ctx.update(ptr[0..len]); } export fn @"ed25519_hash_final"(ctx: *crypto.hash.sha3.Sha3_512, hash: [*]u8) callconv(.C) void { ctx.final(@ptrCast(*[64]u8, hash)); } export fn @"ed25519_hash"(hash: [*]u8, ptr: [*]const u8, len: usize) callconv(.C) void { crypto.hash.sha3.Sha3_512.hash(ptr[0..len], @ptrCast(*[64]u8, hash), .{}); } pub fn addTo(step: *std.build.LibExeObjStep, comptime dir: []const u8) void { step.linkLibC(); step.addIncludeDir(dir ++ "/lib"); var defines: std.ArrayListUnmanaged([]const u8) = .{}; defer defines.deinit(step.builder.allocator); defines.append(step.builder.allocator, "-DED25519_CUSTOMRANDOM") catch unreachable; defines.append(step.builder.allocator, "-DED25519_CUSTOMHASH") catch unreachable; if (std.Target.x86.featureSetHas(step.target.getCpuFeatures(), .sse2)) { defines.append(step.builder.allocator, "-DED25519_SSE2") catch unreachable; } step.addCSourceFile(dir ++ "/ed25519.c", defines.items); } pub fn derivePublicKey(secret_key: [32]u8) [32]u8 { var public_key: [32]u8 = undefined; c.ed25519_publickey(&secret_key, &public_key); return public_key; } pub fn sign(msg: []const u8, secret_key: [32]u8, public_key: [32]u8) [64]u8 { var signature: [64]u8 = undefined; c.ed25519_sign(msg.ptr, msg.len, &secret_key, &public_key, &signature); return signature; } pub fn open(msg: []const u8, public_key: [32]u8, signature: [64]u8) bool { return c.ed25519_sign_open(msg.ptr, msg.len, &public_key, &signature) == 0; } test "ed25519_donna" { var secret_key: [32]u8 = undefined; crypto.random.bytes(&secret_key); var public_key: [32]u8 = derivePublicKey(secret_key); var buf: [1024]u8 = undefined; var i: usize = 0; while (i < 100) : (i += 1) { testing.expect(open(&buf, public_key, sign(&buf, secret_key, public_key))); } }
ed25519_donna/ed25519.zig
const std = @import("std"); const builtin = @import("builtin"); const win32 = @import("win32"); const foundation = win32.foundation; const windows = win32.ui.windows_and_messaging; const mem = std.mem; const Allocator = mem.Allocator; const c = @import("c.zig"); const nvg = @import("nanovg"); const gui = @import("gui"); const Rect = @import("gui/geometry.zig").Rect; const Clipboard = @import("Clipboard.zig"); const EditorWidget = @import("EditorWidget.zig"); const MessageBoxWidget = @import("MessageBoxWidget.zig"); const info = @import("info.zig"); extern fn gladLoadGL() callconv(.C) c_int; // init OpenGL function pointers on Windows and Linux extern fn SetProcessDPIAware() callconv(.C) c_int; extern fn enableAppleMomentumScroll() callconv(.C) void; // export fn WinMain() callconv(.C) c_int { // main() catch return 1; // TODO report error // return 0; // } var vg: nvg = undefined; var window_config_file_path: ?[]u8 = null; var has_touch_mouse: bool = false; var touch_window_id: c_uint = 0; var is_touch_panning: bool = false; var is_touch_zooming: bool = false; const SdlWindow = struct { handle: *c.SDL_Window, context: c.SDL_GLContext, // TODO: shared gl context window: *gui.Window, dirty: bool = true, windowed_width: f32, // size when not maximized windowed_height: f32, video_width: f32, video_height: f32, video_scale: f32 = 1, fn create(title: [:0]const u8, width: u32, height: u32, options: gui.Window.CreateOptions, window: *gui.Window) !SdlWindow { var self: SdlWindow = SdlWindow{ .windowed_width = @intToFloat(f32, width), .windowed_height = @intToFloat(f32, height), .video_width = @intToFloat(f32, width), .video_height = @intToFloat(f32, height), .handle = undefined, .context = undefined, .window = window, }; var display_index: c_uint = 0; if (options.parent_id) |parent_id| { const parent_window = c.SDL_GetWindowFromID(parent_id); const result = c.SDL_GetWindowDisplayIndex(parent_window); if (result >= 0) { display_index = @intCast(c_uint, result); } } var window_flags: c_uint = c.SDL_WINDOW_OPENGL | c.SDL_WINDOW_ALLOW_HIGHDPI | c.SDL_WINDOW_HIDDEN; if (options.resizable) window_flags |= c.SDL_WINDOW_RESIZABLE; var window_width: c_int = undefined; var window_height: c_int = undefined; if (builtin.os.tag == .macos) { window_width = @floatToInt(c_int, self.video_width); window_height = @floatToInt(c_int, self.video_height); } else { window_width = @floatToInt(c_int, self.video_scale * self.video_width); window_height = @floatToInt(c_int, self.video_scale * self.video_height); } const maybe_window = c.SDL_CreateWindow( title, @bitCast(c_int, c.SDL_WINDOWPOS_UNDEFINED_DISPLAY(display_index)), @bitCast(c_int, c.SDL_WINDOWPOS_UNDEFINED_DISPLAY(display_index)), window_width, window_height, window_flags, ); if (maybe_window) |sdl_window| { self.handle = sdl_window; } else { c.SDL_Log("Unable to create window: %s", c.SDL_GetError()); return error.SDLCreateWindowFailed; } errdefer c.SDL_DestroyWindow(self.handle); self.context = c.SDL_GL_CreateContext(self.handle); if (self.context == null) { c.SDL_Log("Unable to create gl context: %s", c.SDL_GetError()); return error.SDLCreateGLContextFailed; } if (!options.resizable) { var sys_info: c.SDL_SysWMinfo = undefined; c.SDL_GetVersion(&sys_info.version); _ = c.SDL_GetWindowWMInfo(self.handle, &sys_info); if (builtin.os.tag == .windows) { if (sys_info.subsystem == c.SDL_SYSWM_WINDOWS) { const hwnd = @ptrCast(foundation.HWND, sys_info.info.win.window); const style = windows.GetWindowLong(hwnd, windows.GWL_STYLE); const no_minimizebox = ~@bitCast(i32, @enumToInt(windows.WS_MINIMIZEBOX)); _ = windows.SetWindowLong(hwnd, windows.GWL_STYLE, style & no_minimizebox); } } } return self; } fn destroy(self: SdlWindow) void { c.SDL_GL_DeleteContext(self.context); c.SDL_DestroyWindow(self.handle); } fn getId(self: SdlWindow) u32 { return c.SDL_GetWindowID(self.handle); } fn getDisplayIndex(self: SdlWindow) i32 { return c.SDL_GetWindowDisplayIndex(self.handle); } fn isMaximized(self: SdlWindow) bool { return c.SDL_GetWindowFlags(self.handle) & c.SDL_WINDOW_MAXIMIZED != 0; } fn maximize(self: *SdlWindow) void { c.SDL_MaximizeWindow(self.handle); } fn setSize(self: *SdlWindow, width: i32, height: i32) void { self.video_width = @intToFloat(f32, width); self.video_height = @intToFloat(f32, height); self.window.setSize(self.video_width, self.video_height); switch (builtin.os.tag) { .windows, .linux => { self.updateVideoScale(); const scaled_width = self.video_scale * self.video_width; const scaled_height = self.video_scale * self.video_height; c.SDL_SetWindowSize(self.handle, @floatToInt(c_int, scaled_width), @floatToInt(c_int, scaled_height)); }, .macos => c.SDL_SetWindowSize(self.handle, width, height), else => unreachable, // unsupported } } fn setDisplay(self: SdlWindow, display_index: i32) void { const pos = @bitCast(i32, c.SDL_WINDOWPOS_CENTERED_DISPLAY(@bitCast(u32, display_index))); c.SDL_SetWindowPosition(self.handle, pos, pos); } fn beginDraw(self: SdlWindow) void { _ = c.SDL_GL_MakeCurrent(self.handle, self.context); } fn updateVideoScale(self: *SdlWindow) void { switch (builtin.os.tag) { .windows, .linux => { const default_dpi: f32 = 96; const dpi = self.getLogicalDpi(); self.video_scale = dpi / default_dpi; }, .macos => { var drawable_width: i32 = undefined; var drawable_height: i32 = undefined; c.SDL_GL_GetDrawableSize(self.handle, &drawable_width, &drawable_height); var window_width: i32 = undefined; var window_height: i32 = undefined; c.SDL_GetWindowSize(self.handle, &window_width, &window_height); self.video_scale = @intToFloat(f32, drawable_width) / @intToFloat(f32, window_width); }, else => unreachable, } } fn getLogicalDpi(self: SdlWindow) f32 { if (builtin.os.tag == .linux) { // SDL_GetDisplayDPI returns physical DPI on Linux/X11 var sys_info: c.SDL_SysWMinfo = undefined; c.SDL_GetVersion(&sys_info.version); _ = c.SDL_GetWindowWMInfo(self.handle, &sys_info); if (sys_info.subsystem == c.SDL_SYSWM_X11) { const str = c.XGetDefault(sys_info.info.x11.display, "Xft", "dpi"); const dpi_or_error = std.fmt.parseFloat(f32, std.mem.sliceTo(str, 0)); if (dpi_or_error) |dpi| { return dpi; } else |_| {} // fall through to SDL2 default implementation } } const display = self.getDisplayIndex(); var dpi: f32 = undefined; _ = c.SDL_GetDisplayDPI(display, &dpi, null, null); return dpi; } fn setupFrame(self: *SdlWindow) void { var drawable_width: i32 = undefined; var drawable_height: i32 = undefined; c.SDL_GL_GetDrawableSize(self.handle, &drawable_width, &drawable_height); switch (builtin.os.tag) { .windows, .linux => { const default_dpi: f32 = 96; const dpi = self.getLogicalDpi(); const new_video_scale = dpi / default_dpi; if (new_video_scale != self.video_scale) { // detect DPI change //std.debug.print("new_video_scale {} {}\n", .{ new_video_scale, dpi }); self.video_scale = new_video_scale; const window_width = @floatToInt(i32, self.video_scale * self.video_width); const window_height = @floatToInt(i32, self.video_scale * self.video_height); c.SDL_SetWindowSize(self.handle, window_width, window_height); c.SDL_GL_GetDrawableSize(self.handle, &drawable_width, &drawable_height); } }, .macos => { var window_width: i32 = undefined; var window_height: i32 = undefined; c.SDL_GetWindowSize(self.handle, &window_width, &window_height); self.video_scale = @intToFloat(f32, drawable_width) / @intToFloat(f32, window_width); }, else => unreachable, // unsupported } c.glViewport(0, 0, drawable_width, drawable_height); // only when window is resizable self.video_width = @intToFloat(f32, drawable_width) / self.video_scale; self.video_height = @intToFloat(f32, drawable_height) / self.video_scale; self.window.setSize(self.video_width, self.video_height); } pub fn draw(self: *SdlWindow) void { self.beginDraw(); self.setupFrame(); c.glClearColor(0.5, 0.5, 0.5, 1); c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_STENCIL_BUFFER_BIT); vg.beginFrame(self.video_width, self.video_height, self.video_scale); self.window.draw(vg); vg.endFrame(); c.glFlush(); if (c.SDL_GetWindowFlags(self.handle) & c.SDL_WINDOW_HIDDEN != 0) { c.SDL_ShowWindow(self.handle); } c.SDL_GL_SwapWindow(self.handle); self.dirty = false; } }; var sdl_windows: std.ArrayList(SdlWindow) = undefined; var app: *gui.Application = undefined; var editor_widget: *EditorWidget = undefined; fn findSdlWindow(id: u32) ?*SdlWindow { for (sdl_windows.items) |*sdl_window| { if (sdl_window.getId() == id) return sdl_window; } return null; } fn markAllWindowsAsDirty() void { for (sdl_windows.items) |*sdl_window| { sdl_window.dirty = true; } } fn sdlProcessWindowEvent(window_event: c.SDL_WindowEvent) void { if (findSdlWindow(window_event.windowID)) |sdl_window| { sdl_window.dirty = true; switch (window_event.event) { c.SDL_WINDOWEVENT_EXPOSED => { if (sdl_window.window.isBlockedByModal()) { // TODO: find all modal windows for (sdl_window.window.children.items) |child| { if (child.is_modal) { if (findSdlWindow(child.id)) |child_sdl_window| { c.SDL_RaiseWindow(child_sdl_window.handle); } } } } }, c.SDL_WINDOWEVENT_ENTER => { var enter_event = gui.Event{ .type = .Enter }; sdl_window.window.handleEvent(&enter_event); }, c.SDL_WINDOWEVENT_LEAVE => { var leave_event = gui.Event{ .type = .Leave }; sdl_window.window.handleEvent(&leave_event); }, c.SDL_WINDOWEVENT_FOCUS_GAINED => { sdl_window.window.is_active = true; }, c.SDL_WINDOWEVENT_FOCUS_LOST => { sdl_window.window.is_active = false; var leave_event = gui.Event{ .type = .Leave }; sdl_window.window.handleEvent(&leave_event); }, c.SDL_WINDOWEVENT_MINIMIZED => { if (sdl_window.window.isBlockedByModal()) { c.SDL_RestoreWindow(sdl_window.handle); } }, c.SDL_WINDOWEVENT_SIZE_CHANGED => { if (!sdl_window.isMaximized()) { sdl_window.windowed_width = sdl_window.video_width; sdl_window.windowed_height = sdl_window.video_height; } }, c.SDL_WINDOWEVENT_CLOSE => app.requestWindowClose(sdl_window.window), else => {}, } } } fn sdlQueryModState() u4 { var modifiers: u4 = 0; const sdl_mod_state = c.SDL_GetModState(); if ((sdl_mod_state & c.KMOD_ALT) != 0) modifiers |= @as(u4, 1) << @enumToInt(gui.Modifier.alt); if ((sdl_mod_state & c.KMOD_CTRL) != 0) modifiers |= @as(u4, 1) << @enumToInt(gui.Modifier.ctrl); if ((sdl_mod_state & c.KMOD_SHIFT) != 0) modifiers |= @as(u4, 1) << @enumToInt(gui.Modifier.shift); if ((sdl_mod_state & c.KMOD_GUI) != 0) modifiers |= @as(u4, 1) << @enumToInt(gui.Modifier.super); return modifiers; } fn sdlProcessMouseMotion(motion_event: c.SDL_MouseMotionEvent) void { if (findSdlWindow(motion_event.windowID)) |sdl_window| { sdl_window.dirty = true; if (motion_event.which == c.SDL_TOUCH_MOUSEID) {} else { var mx: f32 = @intToFloat(f32, motion_event.x); var my: f32 = @intToFloat(f32, motion_event.y); if (builtin.os.tag == .windows or builtin.os.tag == .linux) { mx /= sdl_window.video_scale; my /= sdl_window.video_scale; } var me = gui.MouseEvent{ .event = gui.Event{ .type = .MouseMove }, .button = .none, .click_count = 0, .state = motion_event.state, .modifiers = sdlQueryModState(), .x = mx, .y = my, .wheel_x = 0, .wheel_y = 0, }; sdl_window.window.handleEvent(&me.event); } } } fn sdlProcessMouseButton(button_event: c.SDL_MouseButtonEvent) void { if (is_touch_panning) return; // reject accidental button presses if (findSdlWindow(button_event.windowID)) |sdl_window| { sdl_window.dirty = true; var mx: f32 = @intToFloat(f32, button_event.x); var my: f32 = @intToFloat(f32, button_event.y); if (builtin.os.tag == .windows or builtin.os.tag == .linux) { mx /= sdl_window.video_scale; my /= sdl_window.video_scale; } var me = gui.MouseEvent{ .event = gui.Event{ .type = if (button_event.state == c.SDL_PRESSED) .MouseDown else .MouseUp, }, .button = switch (button_event.button) { c.SDL_BUTTON_LEFT => .left, c.SDL_BUTTON_MIDDLE => .middle, c.SDL_BUTTON_RIGHT => .right, c.SDL_BUTTON_X1 => .back, c.SDL_BUTTON_X2 => .forward, else => .none, }, .click_count = button_event.clicks, .state = c.SDL_GetMouseState(null, null), .modifiers = sdlQueryModState(), .x = mx, .y = my, .wheel_x = 0, .wheel_y = 0, }; sdl_window.window.handleEvent(&me.event); // TODO maybe if app gains focus? _ = c.SDL_CaptureMouse(if (button_event.state == c.SDL_PRESSED) c.SDL_TRUE else c.SDL_FALSE); } } fn sdlProcessMouseWheel(wheel_event: c.SDL_MouseWheelEvent) void { if (findSdlWindow(wheel_event.windowID)) |sdl_window| { sdl_window.dirty = true; var x: i32 = undefined; var y: i32 = undefined; const state = c.SDL_GetMouseState(&x, &y); var mx: f32 = @intToFloat(f32, x); var my: f32 = @intToFloat(f32, y); if (builtin.os.tag == .windows or builtin.os.tag == .linux) { mx /= sdl_window.video_scale; my /= sdl_window.video_scale; } if (wheel_event.which == @bitCast(c_int, c.SDL_TOUCH_MOUSEID) or has_touch_mouse) { is_touch_panning = true; const magic_factor = 4; // TODO: we need floating point resolution var se = gui.TouchEvent{ .event = gui.Event{ .type = .TouchPan }, .x = mx, .y = my, .dx = magic_factor * @intToFloat(f32, wheel_event.x), .dy = magic_factor * @intToFloat(f32, wheel_event.y), .zoom = 0, }; if (wheel_event.direction == c.SDL_MOUSEWHEEL_FLIPPED) { se.dx *= -1; } sdl_window.window.handleEvent(&se.event); } else { var me = gui.MouseEvent{ .event = gui.Event{ .type = .MouseWheel }, .button = .none, .click_count = 0, .state = state, .modifiers = sdlQueryModState(), .x = mx, .y = my, .wheel_x = wheel_event.x, .wheel_y = wheel_event.y, // TODO: swap if direction is inverse? }; sdl_window.window.handleEvent(&me.event); } } } fn sdlProcessTouchFinger(finger_event: c.SDL_TouchFingerEvent) void { if (finger_event.touchId == @bitCast(c_int, c.SDL_TOUCH_MOUSEID)) { // has_touch_mouse = true; // doesn't work on windows } touch_window_id = finger_event.windowID; if (finger_event.type == c.SDL_FINGERUP) { // reset touch gestures is_touch_panning = false; is_touch_zooming = false; } // std.debug.print("touchId: {}\n", .{finger_event.touchId}); } fn translateSdlKey(sym: c.SDL_Keycode) gui.KeyCode { return switch (sym) { c.SDLK_RETURN, c.SDLK_KP_ENTER => .Return, c.SDLK_0, c.SDLK_KP_0 => .D0, c.SDLK_1, c.SDLK_KP_1 => .D1, c.SDLK_2, c.SDLK_KP_2 => .D2, c.SDLK_3, c.SDLK_KP_3 => .D3, c.SDLK_4, c.SDLK_KP_4 => .D4, c.SDLK_5, c.SDLK_KP_5 => .D5, c.SDLK_6, c.SDLK_KP_6 => .D6, c.SDLK_7, c.SDLK_KP_7 => .D7, c.SDLK_8, c.SDLK_KP_8 => .D8, c.SDLK_9, c.SDLK_KP_9 => .D9, c.SDLK_PERIOD, c.SDLK_KP_DECIMAL => .Period, c.SDLK_COMMA => .Comma, c.SDLK_ESCAPE => .Escape, c.SDLK_BACKSPACE => .Backspace, c.SDLK_SPACE => .Space, c.SDLK_PLUS, c.SDLK_KP_PLUS => .Plus, c.SDLK_MINUS, c.SDLK_KP_MINUS => .Minus, c.SDLK_ASTERISK, c.SDLK_KP_MULTIPLY => .Asterisk, c.SDLK_SLASH, c.SDLK_KP_DIVIDE => .Slash, c.SDLK_PERCENT => .Percent, c.SDLK_DELETE => .Delete, c.SDLK_HOME => .Home, c.SDLK_END => .End, c.SDLK_TAB => .Tab, c.SDLK_LSHIFT => .LShift, c.SDLK_RSHIFT => .RShift, c.SDLK_LCTRL => .LCtrl, c.SDLK_RCTRL => .RCtrl, c.SDLK_LALT => .LAlt, c.SDLK_RALT => .RAlt, c.SDLK_LEFT => .Left, c.SDLK_RIGHT => .Right, c.SDLK_UP => .Up, c.SDLK_DOWN => .Down, c.SDLK_a...c.SDLK_z => @intToEnum(gui.KeyCode, @enumToInt(gui.KeyCode.A) + @intCast(u8, sym - c.SDLK_a)), c.SDLK_HASH => .Hash, else => .Unknown, }; } fn sdlProcessKey(key_event: c.SDL_KeyboardEvent) void { if (findSdlWindow(key_event.windowID)) |sdl_window| { sdl_window.dirty = true; var ke = gui.KeyEvent{ .event = gui.Event{ .type = if (key_event.type == c.SDL_KEYDOWN) .KeyDown else .KeyUp }, .key = translateSdlKey(key_event.keysym.sym), .down = key_event.state == c.SDL_PRESSED, .repeat = key_event.repeat > 0, .modifiers = sdlQueryModState(), }; sdl_window.window.handleEvent(&ke.event); } } var first_surrogate_half: ?u16 = null; fn sdlProcessTextInput(text_event: c.SDL_TextInputEvent) void { if (findSdlWindow(text_event.windowID)) |sdl_window| { sdl_window.dirty = true; const text = mem.sliceTo(std.meta.assumeSentinel(&text_event.text, 0), 0); if (std.unicode.utf8ValidateSlice(text)) { var te = gui.TextInputEvent{ .text = text, }; sdl_window.window.handleEvent(&te.event); } else if (text.len == 3) { _ = std.unicode.utf8Decode(text) catch |err| switch (err) { error.Utf8EncodesSurrogateHalf => { var codepoint: u21 = text[0] & 0b00001111; codepoint <<= 6; codepoint |= text[1] & 0b00111111; codepoint <<= 6; codepoint |= text[2] & 0b00111111; const surrogate = @intCast(u16, codepoint); if (first_surrogate_half) |first_surrogate0| { const utf16 = [_]u16{ first_surrogate0, surrogate }; var utf8 = [_]u8{0} ** 4; _ = std.unicode.utf16leToUtf8(&utf8, &utf16) catch unreachable; first_surrogate_half = null; var te = gui.TextInputEvent{ .text = &utf8, }; sdl_window.window.handleEvent(&te.event); } else { first_surrogate_half = surrogate; } }, else => {}, }; } } } fn sdlEventWatch(userdata: ?*anyopaque, sdl_event_ptr: [*c]c.SDL_Event) callconv(.C) c_int { _ = userdata; // unused const sdl_event = sdl_event_ptr[0]; if (sdl_event.type == c.SDL_WINDOWEVENT) { if (sdl_event.window.event == c.SDL_WINDOWEVENT_RESIZED) { if (findSdlWindow(sdl_event.window.windowID)) |sdl_window| { sdl_window.draw(); } return 0; } } return 1; // unhandled } // fn sdlShowMessageBox(icon: gui.MessageBoxIcon, title: [:0]const u8, message: [:0]const u8) void { // const sdl_icon = @intCast(u32, switch (icon) { // .err => c.SDL_MESSAGEBOX_ERROR, // .warn => c.SDL_MESSAGEBOX_WARNING, // .info => c.SDL_MESSAGEBOX_INFORMATION, // }); // _ = c.SDL_ShowSimpleMessageBox(sdl_icon, title, message, main_window.handle); // } fn sdlAddTimer(timer: *gui.Timer, interval: u32) u32 { const res = c.SDL_AddTimer(interval, sdlTimerCallback, timer); if (res == 0) { std.debug.print("SDL_AddTimer failed: {s}", .{c.SDL_GetError()}); } return @intCast(u32, res); } fn sdlCancelTimer(timer_id: u32) void { _ = c.SDL_RemoveTimer(@intCast(c_int, timer_id)); //if (!res) std.debug.print("SDL_RemoveTimer failed: {}", .{c.SDL_GetError()}); } const SDL_USEREVENT_TIMER = 1; fn sdlTimerCallback(interval: u32, param: ?*anyopaque) callconv(.C) u32 { var userevent: c.SDL_UserEvent = undefined; userevent.type = c.SDL_USEREVENT; userevent.code = SDL_USEREVENT_TIMER; userevent.data1 = param; var event: c.SDL_Event = undefined; event.type = c.SDL_USEREVENT; event.user = userevent; _ = c.SDL_PushEvent(&event); return interval; } fn sdlProcessUserEvent(user_event: c.SDL_UserEvent) void { markAllWindowsAsDirty(); switch (user_event.code) { SDL_USEREVENT_TIMER => { var timer = @ptrCast(*gui.Timer, @alignCast(@sizeOf(usize), user_event.data1)); timer.onElapsed(); }, else => {}, } } fn sdlProcessDropFile(drop_event: c.SDL_DropEvent) void { markAllWindowsAsDirty(); const file_path = std.mem.sliceTo(drop_event.file, 0); editor_widget.tryLoadDocument(file_path); c.SDL_free(drop_event.file); } fn sdlProcessClipboardUpdate() void { markAllWindowsAsDirty(); var event = gui.Event{ .type = .ClipboardUpdate }; app.broadcastEvent(&event); } fn sdlProcessMultiGesture(gesture_event: c.SDL_MultiGestureEvent) void { if (gesture_event.numFingers != 2 or is_touch_panning) return; if (@fabs(gesture_event.dDist) > 0.004) { is_touch_zooming = true; } if (!is_touch_zooming) return; // there's no window id :( -> broadcast to all windows for (sdl_windows.items) |*sdl_window| { sdl_window.dirty = true; var x: i32 = undefined; var y: i32 = undefined; _ = c.SDL_GetMouseState(&x, &y); var mx: f32 = @intToFloat(f32, x); var my: f32 = @intToFloat(f32, y); if (builtin.os.tag == .windows or builtin.os.tag == .linux) { mx /= sdl_window.video_scale; my /= sdl_window.video_scale; } const magic_factor = 4; var se = gui.TouchEvent{ .event = gui.Event{ .type = .TouchZoom }, .x = mx, .y = my, .dx = 0, .dy = 0, .zoom = magic_factor * gesture_event.dDist, }; sdl_window.window.handleEvent(&se.event); } } fn sdlShowCursor(enable: bool) void { _ = c.SDL_ShowCursor(if (enable) c.SDL_ENABLE else c.SDL_DISABLE); } fn sdlCreateWindow(title: [:0]const u8, width: u32, height: u32, options: gui.Window.CreateOptions, window: *gui.Window) !u32 { const sdl_window = try SdlWindow.create(title, width, height, options, window); try sdl_windows.append(sdl_window); return sdl_window.getId(); } fn sdlDestroyWindow(id: u32) void { var i: usize = 0; while (i < sdl_windows.items.len) { if (sdl_windows.items[i].getId() == id) { sdl_windows.items[i].destroy(); _ = sdl_windows.swapRemove(i); } else i += 1; } } fn sdlSetWindowTitle(window_id: u32, title: [:0]const u8) void { if (findSdlWindow(window_id)) |window| { c.SDL_SetWindowTitle(window.handle, title); } } pub fn sdlHasClipboardText() bool { return c.SDL_HasClipboardText() == c.SDL_TRUE; } pub fn sdlGetClipboardText(allocator: std.mem.Allocator) !?[]const u8 { const sdl_text = c.SDL_GetClipboardText(); if (sdl_text == null) return null; var text = try allocator.dupe(u8, std.mem.sliceTo(sdl_text, 0)); c.SDL_free(sdl_text); return text; } pub fn sdlSetClipboardText(allocator: std.mem.Allocator, text: []const u8) !void { const sdl_text = try allocator.dupeZ(u8, text); defer allocator.free(sdl_text); if (c.SDL_SetClipboardText(sdl_text) != 0) { return error.SdlSetClipboardTextFailed; } sdlProcessClipboardUpdate(); // broadcasts a gui.ClipboardUpdate event to all windows } fn sdlHandleEvent(sdl_event: c.SDL_Event) void { switch (sdl_event.type) { c.SDL_WINDOWEVENT => sdlProcessWindowEvent(sdl_event.window), c.SDL_MOUSEMOTION => sdlProcessMouseMotion(sdl_event.motion), c.SDL_MOUSEBUTTONDOWN, c.SDL_MOUSEBUTTONUP => sdlProcessMouseButton(sdl_event.button), c.SDL_MOUSEWHEEL => sdlProcessMouseWheel(sdl_event.wheel), c.SDL_FINGERMOTION, c.SDL_FINGERDOWN, c.SDL_FINGERUP => sdlProcessTouchFinger(sdl_event.tfinger), c.SDL_KEYDOWN, c.SDL_KEYUP => sdlProcessKey(sdl_event.key), c.SDL_TEXTINPUT => sdlProcessTextInput(sdl_event.text), c.SDL_USEREVENT => sdlProcessUserEvent(sdl_event.user), c.SDL_DROPFILE => sdlProcessDropFile(sdl_event.drop), c.SDL_CLIPBOARDUPDATE => sdlProcessClipboardUpdate(), c.SDL_MULTIGESTURE => sdlProcessMultiGesture(sdl_event.mgesture), else => {}, } } const MainloopType = enum { waitEvent, // updates only when an event occurs regularInterval, // runs at monitor refresh rate }; var mainloop_type: MainloopType = .waitEvent; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{ .enable_memory_limit = true, }){}; defer { const leaked = gpa.deinit(); if (leaked) @panic("Memory leak :("); } const allocator = gpa.allocator(); defer Clipboard.deinit(); if (builtin.os.tag == .windows) { _ = SetProcessDPIAware(); } if (c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_TIMER | c.SDL_INIT_EVENTS) != 0) { c.SDL_Log("Unable to initialize SDL: %s", c.SDL_GetError()); return error.SDLInitializationFailed; } defer c.SDL_Quit(); if (builtin.os.tag == .macos) { enableAppleMomentumScroll(); } if (c.SDL_GetPrefPath(info.org_name, info.app_name)) |sdl_pref_path| { defer c.SDL_free(sdl_pref_path); const user_pref_path = std.mem.sliceTo(sdl_pref_path, 0); window_config_file_path = try std.fs.path.join(allocator, &.{ user_pref_path, "window.json" }); } defer { if (window_config_file_path) |path| allocator.free(path); } // enable multitouch gestures from touchpads _ = c.SDL_SetHint(c.SDL_HINT_MOUSE_TOUCH_EVENTS, "1"); _ = c.SDL_GL_SetAttribute(c.SDL_GL_STENCIL_SIZE, 1); _ = c.SDL_GL_SetAttribute(c.SDL_GL_MULTISAMPLEBUFFERS, 1); _ = c.SDL_GL_SetAttribute(c.SDL_GL_MULTISAMPLESAMPLES, 4); _ = c.SDL_GL_SetAttribute(c.SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); sdl_windows = std.ArrayList(SdlWindow).init(allocator); defer { // TODO: destroy all windows sdl_windows.deinit(); } app = try gui.Application.init(allocator, .{ .createWindow = sdlCreateWindow, .destroyWindow = sdlDestroyWindow, .setWindowTitle = sdlSetWindowTitle, .startTimer = sdlAddTimer, .cancelTimer = sdlCancelTimer, .showCursor = sdlShowCursor, .hasClipboardText = sdlHasClipboardText, .getClipboardText = sdlGetClipboardText, .setClipboardText = sdlSetClipboardText, }); defer app.deinit(); var main_window = try app.createWindow("Untitled - Mini Pixel", 800, 600, .{}); // if (findSdlWindow(main_window.id)) |main_sdl_window| { // c.SDL_SetWindowMinimumSize(main_sdl_window.handle, 400, 200); // } if (builtin.os.tag == .linux or builtin.os.tag == .macos or true) { mainloop_type = .regularInterval; _ = c.SDL_GL_SetSwapInterval(0); // disable VSync } _ = gladLoadGL(); c.SDL_AddEventWatch(sdlEventWatch, null); _ = c.SDL_EventState(c.SDL_DROPFILE, c.SDL_ENABLE); // allow drop events vg = try nvg.gl.init(allocator, .{}); defer vg.deinit(); gui.init(vg); defer gui.deinit(vg); const roboto_regular = @embedFile("../data/fonts/Roboto-Regular.ttf"); const roboto_bold = @embedFile("../data/fonts/Roboto-Bold.ttf"); _ = vg.createFontMem("guifont", roboto_regular); _ = vg.createFontMem("guifontbold", roboto_bold); const rect = Rect(f32).make(0, 0, main_window.width, main_window.height); editor_widget = try EditorWidget.init(allocator, rect, vg); defer editor_widget.deinit(vg); main_window.setMainWidget(&editor_widget.widget); main_window.close_request_context = @ptrToInt(main_window); main_window.onCloseRequestFn = onMainWindowCloseRequest; if (window_config_file_path) |file_path| { loadAndApplyWindowConfig(allocator, main_window, file_path) catch {}; // don't care editor_widget.canvas.centerDocument(); // Window size might have changed recenter document } // parse command line arguments const args = try std.process.argsAlloc(allocator); if (args.len > 1) { editor_widget.tryLoadDocument(args[1]); } std.process.argsFree(allocator, args); // quit app when there are no more windows open while (app.windows.items.len > 0) { var sdl_event: c.SDL_Event = undefined; switch (mainloop_type) { .waitEvent => if (c.SDL_WaitEvent(&sdl_event) == 0) { c.SDL_Log("SDL_WaitEvent failed: %s", c.SDL_GetError()); } else { sdlHandleEvent(sdl_event); }, .regularInterval => while (c.SDL_PollEvent(&sdl_event) != 0) { sdlHandleEvent(sdl_event); }, } editor_widget.setMemoryUsageInfo(gpa.total_requested_bytes); for (sdl_windows.items) |*sdl_window| { if (sdl_window.dirty) sdl_window.draw(); } } } fn onMainWindowCloseRequest(context: usize) bool { if (editor_widget.has_unsaved_changes) { editor_widget.showUnsavedChangesDialog(onUnsavedChangesDialogResult, context); return false; } const window = @intToPtr(*gui.Window, context); if (window_config_file_path) |file_path| { writeWindowConfig(window, file_path) catch {}; // don't care } return true; } fn onUnsavedChangesDialogResult(result_context: usize, result: MessageBoxWidget.Result) void { if (result == .no) { editor_widget.has_unsaved_changes = false; // HACK: close will succeed when there are no unsaved changes const main_window = @intToPtr(*gui.Window, result_context); main_window.close(); } else if (result == .yes) { editor_widget.trySaveAsDocument(); // TODO: if success, continue closing app } } const WindowConfig = struct { display_index: i32, windowed_width: i32, windowed_height: i32, is_maximized: bool, }; fn writeWindowConfig(window: *gui.Window, file_path: []const u8) !void { const sdl_window = findSdlWindow(window.id) orelse return; const config = WindowConfig{ .display_index = sdl_window.getDisplayIndex(), .windowed_width = @floatToInt(i32, sdl_window.windowed_width), .windowed_height = @floatToInt(i32, sdl_window.windowed_height), .is_maximized = sdl_window.isMaximized(), }; var file = try std.fs.cwd().createFile(file_path, .{}); defer file.close(); try std.json.stringify(config, .{}, file.writer()); } fn loadAndApplyWindowConfig(allocator: std.mem.Allocator, window: *gui.Window, file_path: []const u8) !void { const sdl_window = findSdlWindow(window.id) orelse return; var file = try std.fs.cwd().openFile(file_path, .{}); defer file.close(); const json = try file.readToEndAlloc(allocator, 1_000_000); defer allocator.free(json); var stream = std.json.TokenStream.init(json); const config = try std.json.parse(WindowConfig, &stream, .{}); sdl_window.setSize(config.windowed_width, config.windowed_height); sdl_window.setDisplay(config.display_index); if (config.is_maximized) { sdl_window.maximize(); } }
src/main.zig
pub const WNV_API_MAJOR_VERSION_1 = @as(u32, 1); pub const WNV_API_MINOR_VERSION_0 = @as(u32, 0); //-------------------------------------------------------------------------------- // Section: Types (11) //-------------------------------------------------------------------------------- pub const WNV_NOTIFICATION_TYPE = enum(i32) { PolicyMismatchType = 0, RedirectType = 1, ObjectChangeType = 2, NotificationTypeMax = 3, }; pub const WnvPolicyMismatchType = WNV_NOTIFICATION_TYPE.PolicyMismatchType; pub const WnvRedirectType = WNV_NOTIFICATION_TYPE.RedirectType; pub const WnvObjectChangeType = WNV_NOTIFICATION_TYPE.ObjectChangeType; pub const WnvNotificationTypeMax = WNV_NOTIFICATION_TYPE.NotificationTypeMax; pub const WNV_OBJECT_TYPE = enum(i32) { ProviderAddressType = 0, CustomerAddressType = 1, ObjectTypeMax = 2, }; pub const WnvProviderAddressType = WNV_OBJECT_TYPE.ProviderAddressType; pub const WnvCustomerAddressType = WNV_OBJECT_TYPE.CustomerAddressType; pub const WnvObjectTypeMax = WNV_OBJECT_TYPE.ObjectTypeMax; pub const WNV_CA_NOTIFICATION_TYPE = enum(i32) { Added = 0, Deleted = 1, Moved = 2, Max = 3, }; pub const WnvCustomerAddressAdded = WNV_CA_NOTIFICATION_TYPE.Added; pub const WnvCustomerAddressDeleted = WNV_CA_NOTIFICATION_TYPE.Deleted; pub const WnvCustomerAddressMoved = WNV_CA_NOTIFICATION_TYPE.Moved; pub const WnvCustomerAddressMax = WNV_CA_NOTIFICATION_TYPE.Max; pub const WNV_OBJECT_HEADER = extern struct { MajorVersion: u8, MinorVersion: u8, Size: u32, }; pub const WNV_NOTIFICATION_PARAM = extern struct { Header: WNV_OBJECT_HEADER, NotificationType: WNV_NOTIFICATION_TYPE, PendingNotifications: u32, Buffer: ?*u8, }; pub const WNV_IP_ADDRESS = extern struct { IP: extern union { v4: IN_ADDR, v6: IN6_ADDR, Addr: [16]u8, }, }; pub const WNV_POLICY_MISMATCH_PARAM = extern struct { CAFamily: u16, PAFamily: u16, VirtualSubnetId: u32, CA: WNV_IP_ADDRESS, PA: WNV_IP_ADDRESS, }; pub const WNV_PROVIDER_ADDRESS_CHANGE_PARAM = extern struct { PAFamily: u16, PA: WNV_IP_ADDRESS, AddressState: NL_DAD_STATE, }; pub const WNV_CUSTOMER_ADDRESS_CHANGE_PARAM = extern struct { MACAddress: DL_EUI48, CAFamily: u16, CA: WNV_IP_ADDRESS, VirtualSubnetId: u32, PAFamily: u16, PA: WNV_IP_ADDRESS, NotificationReason: WNV_CA_NOTIFICATION_TYPE, }; pub const WNV_OBJECT_CHANGE_PARAM = extern struct { ObjectType: WNV_OBJECT_TYPE, ObjectParam: extern union { ProviderAddressChange: WNV_PROVIDER_ADDRESS_CHANGE_PARAM, CustomerAddressChange: WNV_CUSTOMER_ADDRESS_CHANGE_PARAM, }, }; pub const WNV_REDIRECT_PARAM = extern struct { CAFamily: u16, PAFamily: u16, NewPAFamily: u16, VirtualSubnetId: u32, CA: WNV_IP_ADDRESS, PA: WNV_IP_ADDRESS, NewPA: WNV_IP_ADDRESS, }; //-------------------------------------------------------------------------------- // Section: Functions (2) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windowsServer2012' pub extern "wnvapi" fn WnvOpen( ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windowsServer2012' pub extern "wnvapi" fn WnvRequestNotification( WnvHandle: ?HANDLE, NotificationParam: ?*WNV_NOTIFICATION_PARAM, Overlapped: ?*OVERLAPPED, BytesTransferred: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // 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 DL_EUI48 = @import("../network_management/windows_filtering_platform.zig").DL_EUI48; const HANDLE = @import("../foundation.zig").HANDLE; const IN6_ADDR = @import("../networking/win_sock.zig").IN6_ADDR; const IN_ADDR = @import("../networking/win_sock.zig").IN_ADDR; const NL_DAD_STATE = @import("../networking/win_sock.zig").NL_DAD_STATE; const OVERLAPPED = @import("../system/system_services.zig").OVERLAPPED; 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; } } }
deps/zigwin32/win32/network_management/windows_network_virtualization.zig
const std = @import("std"); const io = std.io; const os = std.os; const Buffer = std.Buffer; const allocator = std.heap.c_allocator; const util = @import("stringUtil.zig"); const TokenizerErrors = error { EndOfStream, StreamTooLong, }; pub const Tokenizer = struct { const Self = this; const delimiters = []const u8 { '{', '}', '[', ']', ':', ',' }; var prevDeliminator : ?u8 = null; fileStream: &io.FileInStream, pub fn atEOF(self: &Self) !bool { var curPos = try self.fileStream.file.getPos(); var endPos = try self.fileStream.file.getEndPos(); return curPos == endPos; } pub fn init(stream: &io.FileInStream) Tokenizer { return Tokenizer { .fileStream = stream, }; } fn isInt(byte: u8) bool { return util.isNumber(byte) or byte == '+' or byte == '-'; } fn isFloat(byte: u8) bool { return isInt(byte) or byte == 'e' or byte == 'E' or byte == '.'; } pub fn readTillDeliminators(self: &Self, buffer: &Buffer, maxSize: usize) !void { try buffer.resize(0); var metNonWhiteSpace = false; var quoteMode = false; var escaped = false; var newline = false; // 0 is int, 1 is float, 2 is letter, later on will add octals/hex/bin // -1 is nothing var readType : i32 = -1; if (prevDeliminator) |byte| { try buffer.appendByte(byte); prevDeliminator = null; if (byte == '"') { quoteMode = true; } else if (byte == '.') { readType = 1; } else if (isInt(byte)) { readType = 0; } else if (util.isLetter(byte)) { readType = 2; } else { return; } } while (true) { var byte: u8 = self.fileStream.stream.readByte() catch |err| { if (err == error.EndOfStream) { if (quoteMode) { return error.MissingEndQuote; } else { return err; } } else { return err; } }; if (quoteMode or byte == '"') { if (buffer.len() != 0 and !quoteMode) { prevDeliminator = '"'; return; } if (escaped and (byte == '"' or byte == '\\')) { escaped = false; try buffer.appendByte(byte); } else if (!escaped and byte == '\\') { escaped = true; } else if (!escaped) { try buffer.appendByte(byte); if (!quoteMode) { quoteMode = true; } else if (byte == '"') { return; } } else { return error.UnknownEscapeCode; } continue; } if (byte == '/') { byte = self.fileStream.stream.readByte() catch |err| { return error.InvalidCharacter; }; if (byte == '/') { // Comment while (byte != '\n') { byte = try self.fileStream.stream.readByte(); } } else { return error.InvalidCharacter; } } if (!metNonWhiteSpace and util.isWhitespace(byte)) { continue; } else { metNonWhiteSpace = true; } for (delimiters) |delimiter| { if (byte == delimiter) { if (buffer.len() == 0) { try buffer.appendByte(byte); } else { prevDeliminator = byte; } return; } } switch (readType) { 0 => { // Int if (byte == '.' or byte == 'e') { readType = 1; } else if (!isInt(byte)) { if (!util.isWhitespace(byte)) { prevDeliminator = byte; } return; } }, 1 => { // Float if (!isFloat(byte)) { if (!util.isWhitespace(byte)) { prevDeliminator = byte; } return; } }, 2 => { // Null/True/False if (!util.isLetter(byte)) { if (!util.isWhitespace(byte)) { prevDeliminator = byte; } return; } }, -1 => { if (isInt(byte)) { readType = 0; } else if (byte == '.') { readType = 1; } else if (util.isLetter(byte)) { readType = 2; } }, else => { return error.InvalidReadType; } } try buffer.appendByte(byte); if (buffer.len() == maxSize) { return error.StreamTooLong; } } } };
src/tokenizer.zig
const std = @import("std"); const os = std.os; const fs = std.fs; const io = std.io; const Allocator = std.mem.Allocator; const XAuth = @This(); family: Family, address: []const u8, number: []const u8, name: []const u8, data: []const u8, pub const Family = enum(u16) { ip_address = 0, localhost = 252, krb5 = 253, netname = 254, local = 256, wild = 65535, _, }; fn pad(n: usize) usize { return @bitCast(usize, (-%@bitCast(isize, n)) & 3); } pub fn size(self: XAuth) usize { const header_size = 14; return header_size + self.name.len + self.data.len + pad(self.data.len); } const Header = extern struct { order: u8 = 'l', unused: u8 = '0', major: u16 = 11, minor: u16 = 0, name_len: u16, data_len: u16, pad: u16 = 0, }; pub fn request(self: XAuth, buffer: []u8) ![]const u8 { var fbs = io.fixedBufferStream(buffer); const writer = fbs.writer(); try writer.writeStruct(Header{ .name_len = @intCast(u16, self.name.len), .data_len = @intCast(u16, self.data.len), }); try writer.writeAll(self.name); try writer.writeIntLittle(u16, 0); try writer.writeAll(self.data); try writer.writeByteNTimes(0, pad(self.data.len)); return fbs.getWritten(); } pub fn init(gpa: *Allocator) !Iterator { const file = if (os.getenv("XAUTHORITY")) |name| try fs.openFileAbsolute(name, .{}) else blk: { const home = os.getenv("HOME") orelse return error.HomeNotFound; var dir = try fs.cwd().openDir(home, .{}); defer dir.close(); break :blk try dir.openFile(".Xauthority", .{}); }; defer file.close(); const stat = try file.stat(); const buffer = try gpa.alloc(u8, stat.size); errdefer gpa.free(buffer); if ((try file.read(buffer)) != buffer.len) return error.Failed; return Iterator{ .bytes = buffer }; } pub const Iterator = struct { bytes: []const u8, index: usize = 0, pub fn next(self: *Iterator) !?XAuth { var fbs = io.fixedBufferStream(self.bytes); fbs.pos = self.index; const reader = fbs.reader(); const family = reader.readIntBig(u16) catch return null; var len = try reader.readIntBig(u16); const address = self.bytes[fbs.pos .. fbs.pos + len]; try reader.skipBytes(address.len, .{}); len = try reader.readIntBig(u16); const number = self.bytes[fbs.pos .. fbs.pos + len]; try reader.skipBytes(number.len, .{}); len = try reader.readIntBig(u16); const name = self.bytes[fbs.pos .. fbs.pos + len]; try reader.skipBytes(name.len, .{}); len = try reader.readIntBig(u16); const data = self.bytes[fbs.pos .. fbs.pos + len]; try reader.skipBytes(data.len, .{}); self.index = fbs.pos; return XAuth{ .family = @intToEnum(XAuth.Family, family), .address = address, .number = number, .name = name, .data = data, }; } pub fn deinit(self: *Iterator, gpa: *Allocator) void { gpa.free(self.bytes); self.* = undefined; } };
src/XAuth.zig
const build_options = @import("build_options"); const std = @import("std"); const fs = std.fs; const io = std.io; const os = std.os; const wlr = @import("wlroots"); const flags = @import("flags"); const c = @import("c.zig"); const util = @import("util.zig"); const Server = @import("Server.zig"); const usage: []const u8 = \\usage: river [options] \\ \\ -h Print this help message and exit. \\ -version Print the version number and exit. \\ -c <command> Run `sh -c <command>` on startup. \\ -log-level <level> Set the log level to error, warning, info, or debug. \\ ; pub var server: Server = undefined; pub fn main() anyerror!void { // This line is here because of 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 = "-c", .kind = .arg }, .{ .name = "-log-level", .kind = .arg }, }) catch { try io.getStdErr().writeAll(usage); os.exit(1); }; if (result.boolFlag("-h")) { try io.getStdOut().writeAll(usage); os.exit(0); } if (result.args.len != 0) { std.log.err("unknown option '{s}'", .{result.args[0]}); try io.getStdErr().writeAll(usage); os.exit(1); } if (result.boolFlag("-version")) { try io.getStdOut().writeAll(build_options.version ++ "\n"); os.exit(0); } if (result.argFlag("-log-level")) |level_str| { const level = std.meta.stringToEnum(LogLevel, std.mem.span(level_str)) orelse { std.log.err("invalid log level '{s}'", .{level_str}); try io.getStdErr().writeAll(usage); os.exit(1); }; runtime_log_level = switch (level) { .@"error" => .err, .warning => .warn, .info => .info, .debug => .debug, }; } const startup_command = blk: { if (result.argFlag("-c")) |command| { break :blk try util.gpa.dupeZ(u8, std.mem.span(command)); } else { break :blk try defaultInitPath(); } }; river_init_wlroots_log(switch (runtime_log_level) { .debug => .debug, .notice, .info => .info, .warn, .err, .crit, .alert, .emerg => .err, }); std.log.info("initializing server", .{}); try server.init(); defer server.deinit(); try server.start(); // Run the child in a new process group so that we can send SIGTERM to all // descendants on exit. const child_pgid = if (startup_command) |cmd| blk: { std.log.info("running init executable '{s}'", .{cmd}); const child_args = [_:null]?[*:0]const u8{ "/bin/sh", "-c", cmd, null }; const pid = try os.fork(); if (pid == 0) { if (c.setsid() < 0) unreachable; if (os.system.sigprocmask(os.SIG_SETMASK, &os.empty_sigset, null) < 0) unreachable; os.execveZ("/bin/sh", &child_args, std.c.environ) catch c._exit(1); } util.gpa.free(cmd); // Since the child has called setsid, the pid is the pgid break :blk pid; } else null; defer if (child_pgid) |pgid| os.kill(-pgid, os.SIGTERM) catch |err| { std.log.err("failed to kill init process group: {s}", .{@errorName(err)}); }; std.log.info("running server", .{}); server.wl_server.run(); std.log.info("shutting down", .{}); } fn defaultInitPath() !?[:0]const u8 { const path = blk: { if (os.getenv("XDG_CONFIG_HOME")) |xdg_config_home| { break :blk try fs.path.joinZ(util.gpa, &[_][]const u8{ xdg_config_home, "river/init" }); } else if (os.getenv("HOME")) |home| { break :blk try fs.path.joinZ(util.gpa, &[_][]const u8{ home, ".config/river/init" }); } else { return null; } }; os.accessZ(path, os.X_OK) catch |err| { std.log.err("failed to run init executable {s}: {s}", .{ path, @errorName(err) }); util.gpa.free(path); return null; }; return path; } /// Tell std.log to leave all log level filtering to us. pub const log_level: std.log.Level = .debug; /// Set the default log level based on the build mode. var runtime_log_level: std.log.Level = switch (std.builtin.mode) { .Debug => .debug, .ReleaseSafe, .ReleaseFast, .ReleaseSmall => .info, }; /// River only exposes these 4 log levels to the user for simplicity const LogLevel = enum { @"error", warning, info, debug, }; pub fn log( comptime message_level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (@enumToInt(message_level) > @enumToInt(runtime_log_level)) return; const river_level: LogLevel = switch (message_level) { .emerg, .alert, .crit, .err => .@"error", .warn => .warning, .notice, .info => .info, .debug => .debug, }; const scope_prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const stderr = std.io.getStdErr().writer(); stderr.print(@tagName(river_level) ++ scope_prefix ++ format ++ "\n", args) catch {}; } /// See wlroots_log_wrapper.c extern fn river_init_wlroots_log(importance: wlr.log.Importance) void; export fn river_wlroots_log_callback(importance: wlr.log.Importance, ptr: [*:0]const u8, len: usize) void { switch (importance) { .err => log(.err, .wlroots, "{s}", .{ptr[0..len]}), .info => log(.info, .wlroots, "{s}", .{ptr[0..len]}), .debug => log(.debug, .wlroots, "{s}", .{ptr[0..len]}), .silent, .last => unreachable, } }
source/river-0.1.0/river/main.zig
const std = @import("std"); const fmt = std.fmt; const testing = std.testing; const P384 = @import("../p384.zig").P384; test "p384 ECDH key exchange" { const dha = P384.scalar.random(.Little); const dhb = P384.scalar.random(.Little); const dhA = try P384.basePoint.mul(dha, .Little); const dhB = try P384.basePoint.mul(dhb, .Little); const shareda = try dhA.mul(dhb, .Little); const sharedb = try dhB.mul(dha, .Little); try testing.expect(shareda.equivalent(sharedb)); } test "p384 point from affine coordinates" { const xh = "aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"; const yh = "3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"; var xs: [48]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); var ys: [48]u8 = undefined; _ = try fmt.hexToBytes(&ys, yh); var p = try P384.fromSerializedAffineCoordinates(xs, ys, .Big); try testing.expect(p.equivalent(P384.basePoint)); } test "p384 test vectors" { const expected = [_][]const u8{ "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", "08D999057BA3D2D969260045C55B97F089025959A6F434D651D207D19FB96E9E4FE0E86EBE0E64F85B96A9C75295DF61", "077A41D4606FFA1464793C7E5FDC7D98CB9D3910202DCD06BEA4F240D3566DA6B408BBAE5026580D02D7E5C70500C831", "138251CD52AC9298C1C8AAD977321DEB97E709BD0B4CA0ACA55DC8AD51DCFC9D1589A1597E3A5120E1EFD631C63E1835", "<KEY>", "<KEY>", "<KEY>", "1692778EA596E0BE75114297A6FA383445BF227FBE58190A900C3C73256F11FB5A3258D6F403D5ECE6E9B269D822C87D", "<KEY>", "A669C5563BD67EEC678D29D6EF4FDE864F372D90B79B9E88931D5C29291238CCED8E85AB507BF91AA9CB2D13186658FB", }; var p = P384.identityElement; for (expected) |xh| { const x = p.affineCoordinates().x; p = p.add(P384.basePoint); var xs: [48]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs); } } test "p384 test vectors - doubling" { const expected = [_][]const u8{ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", "08D999057BA3D2D969260045C55B97F089025959A6F434D651D207D19FB96E9E4FE0E86EBE0E64F85B96A9C75295DF61", "138251CD52AC9298C1C8AAD977321DEB97E709BD0B4CA0ACA55DC8AD51DCFC9D1589A1597E3A5120E1EFD631C63E1835", "1692778EA596E0BE75114297A6FA383445BF227FBE58190A900C3C73256F11FB5A3258D6F403D5ECE6E9B269D822C87D", }; var p = P384.basePoint; for (expected) |xh| { const x = p.affineCoordinates().x; p = p.dbl(); var xs: [48]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs); } } test "p384 compressed sec1 encoding/decoding" { const p = P384.random(); const s0 = p.toUncompressedSec1(); const s = p.toCompressedSec1(); try testing.expectEqualSlices(u8, s0[1..49], s[1..49]); const q = try P384.fromSec1(&s); try testing.expect(p.equivalent(q)); } test "p384 uncompressed sec1 encoding/decoding" { const p = P384.random(); const s = p.toUncompressedSec1(); const q = try P384.fromSec1(&s); try testing.expect(p.equivalent(q)); } test "p384 public key is the neutral element" { const n = P384.scalar.Scalar.zero.toBytes(.Little); const p = P384.random(); try testing.expectError(error.IdentityElement, p.mul(n, .Little)); } test "p384 public key is the neutral element (public verification)" { const n = P384.scalar.Scalar.zero.toBytes(.Little); const p = P384.random(); try testing.expectError(error.IdentityElement, p.mulPublic(n, .Little)); } test "p384 field element non-canonical encoding" { const s = [_]u8{0xff} ** 48; try testing.expectError(error.NonCanonical, P384.Fe.fromBytes(s, .Little)); } test "p384 neutral element decoding" { try testing.expectError(error.InvalidEncoding, P384.fromAffineCoordinates(.{ .x = P384.Fe.zero, .y = P384.Fe.zero })); const p = try P384.fromAffineCoordinates(.{ .x = P384.Fe.zero, .y = P384.Fe.one }); try testing.expectError(error.IdentityElement, p.rejectIdentity()); } test "p384 double base multiplication" { const p1 = P384.basePoint; const p2 = P384.basePoint.dbl(); const s1 = [_]u8{0x01} ** 48; const s2 = [_]u8{0x02} ** 48; const pr1 = try P384.mulDoubleBasePublic(p1, s1, p2, s2, .Little); const pr2 = (try p1.mul(s1, .Little)).add(try p2.mul(s2, .Little)); try testing.expect(pr1.equivalent(pr2)); } test "p384 scalar inverse" { const expected = "a3cc705f33b5679a66e76ce66e68055c927c5dba531b2837b18fe86119511091b54d733f26b2e7a0f6fa2e7ea21ca806"; var out: [48]u8 = undefined; _ = try std.fmt.hexToBytes(&out, expected); const scalar = try P384.scalar.Scalar.fromBytes(.{ 0x94, 0xa1, 0xbb, 0xb1, 0x4b, 0x90, 0x6a, 0x61, 0xa2, 0x80, 0xf2, 0x45, 0xf9, 0xe9, 0x3c, 0x7f, 0x3b, 0x4a, 0x62, 0x47, 0x82, 0x4f, 0x5d, 0x33, 0xb9, 0x67, 0x07, 0x87, 0x64, 0x2a, 0x68, 0xde, 0x38, 0x36, 0xe8, 0x0f, 0xa2, 0x84, 0x6b, 0x4e, 0xf3, 0x9a, 0x02, 0x31, 0x24, 0x41, 0x22, 0xca, }, .Big); const inverse = scalar.invert(); const inverse2 = inverse.invert(); try testing.expectEqualSlices(u8, &out, &inverse.toBytes(.Big)); try testing.expect(inverse2.equivalent(scalar)); const sq = scalar.sq(); const sqr = try sq.sqrt(); try testing.expect(sqr.equivalent(scalar)); }
lib/std/crypto/pcurves/tests/p384.zig
const std = @import("std"); const Barr = std.BoundedArray; const fmt = std.fmt; const log = std.log; const mem = std.mem; const os = std.os; const process = std.process; const stdout = std.io.getStdOut(); // 1. ensure test_folders existence // 2. control_sequences 0x00..0x31 and 0x7F // 3. bad_patterns like ' filename', 'filename ', '~filename', '-filename', 'f1 -f2' // * test code __can not__ ensure traversal order const usage: []const u8 = \\ path ; fn fatal(comptime format: []const u8, args: anytype) noreturn { log.err(format, args); std.process.exit(2); } fn ensureDir(path: []const u8) !void { //std.debug.print("path: {s}\n", .{path}); std.fs.cwd().makeDir(path) catch |err| switch (err) { error.PathAlreadyExists => {}, else => { fatal("unable to create test directory '{s}': {s}", .{ path, @errorName(err), }); }, }; } // -------------- move above parts into testhelper.zig -------------- fn ensureFile(path: []const u8) !void { var file = std.fs.cwd().createFile(path, .{ .read = true, }) catch |err| switch (err) { error.PathAlreadyExists => { return; }, else => { fatal("unable to create test file '{s}': {s}", .{ path, @errorName(err), }); }, }; defer file.close(); const stat = try file.stat(); if (stat.kind != .File) fatal("stat on test file '{s}' failed", .{path}); } pub fn main() !void { var path_buffer: [1000]u8 = undefined; var n_pbuf: u64 = 0; // next free position var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_instance.deinit(); const arena = arena_instance.allocator(); const args: [][:0]u8 = try process.argsAlloc(arena); defer process.argsFree(arena, args); for (args) |arg| { std.debug.print("{s}\n", .{arg}); } if (args.len != 2) { try stdout.writer().print("To create test at path, run in shell: {s} {s}\n", .{ args[0], usage }); std.process.exit(1); } // 1. folders for tests try ensureDir(args[1]); var test_dir = try std.fs.cwd().openDir(args[1], .{ .no_follow = true, }); defer test_dir.close(); mem.copy(u8, path_buffer[n_pbuf..], args[1]); n_pbuf += args[1].len; // 2. control_sequences (0x00..0x31 and 0x7F) // to keep things simple, we create direcories with d_controlsequence // and files with f_controlsequences inside folder control_sequences { const path2: []const u8 = "/control_sequences"; mem.copy(u8, path_buffer[n_pbuf..], path2); n_pbuf += path2.len; try ensureDir(path_buffer[0..n_pbuf]); defer n_pbuf -= path2.len; { // 1. directories var tmpbuf = "/d_2".*; //tmpbuf[2] = 0x00; // cannot access memory at addres 0x0/null tmpbuf[3] = 0x01; var i: u8 = 1; while (i < 32) : (i += 1) { mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureDir(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; tmpbuf[3] = i; } tmpbuf[3] = 0x7F; mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureDir(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; // 2. files tmpbuf[1] = 'f'; // f_symbol //tmpbuf[2] = 0x00; // cannot access memory at addres 0x0/null tmpbuf[3] = 0x01; i = 1; while (i < 32) : (i += 1) { mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureFile(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; tmpbuf[3] = i; } tmpbuf[3] = 0x7F; mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureFile(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; } } // 3. control_sequences (0x00..0x31 and 0x7F without newline \n 0x0a) // to keep things simple, we create direcories with d_controlsequence // and files with f_controlsequences inside folder control_sequences { const path3: []const u8 = "/ctrl_seq_nonewline"; mem.copy(u8, path_buffer[n_pbuf..], path3); n_pbuf += path3.len; try ensureDir(path_buffer[0..n_pbuf]); defer n_pbuf -= path3.len; { // 1. directories var tmpbuf = "/d_3".*; //tmpbuf[2] = 0x00; // cannot access memory at addres 0x0/null tmpbuf[3] = 0x01; var i: u8 = 1; while (i < 32) : (i += 1) { if (tmpbuf[3] != 10) { // if nr not '\n' mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureDir(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; } tmpbuf[3] = i; // deferred update to exclude 32 } tmpbuf[3] = 0x7F; mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureDir(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; // 2. files tmpbuf[1] = 'f'; // f_symbol //tmpbuf[2] = 0x00; // cannot access memory at addres 0x0/null tmpbuf[3] = 0x01; i = 1; while (i < 32) : (i += 1) { if (tmpbuf[3] != 10) { // if nr not '\n' mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureFile(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; } tmpbuf[3] = i; // deferred update to exclude 32 } tmpbuf[3] = 0x7F; mem.copy(u8, path_buffer[n_pbuf..], tmpbuf[0..]); n_pbuf += tmpbuf.len; try ensureFile(path_buffer[0..n_pbuf]); n_pbuf -= tmpbuf.len; } } // 4. bad_patterns like ' filename', 'filename ', '~filename', '-filename', 'f1 -f2' const bad_patterns = [_][]const u8{ "/ fname", "/fname ", "/~fname", "/-fname", "/--fname", "/fname1 ~fname2", "/fname1 -fname2", "/fname1 --fname2", // TODO test cases with escaped path delimiter, ie blabla\/blabla // TODO extend this list // TODO think of bad patterns in utf8 }; { const path3: []const u8 = "/bad_patterns"; mem.copy(u8, path_buffer[n_pbuf..], path3); n_pbuf += path3.len; try ensureDir(path_buffer[0..n_pbuf]); defer n_pbuf -= path3.len; { for (bad_patterns) |pattern| { mem.copy(u8, path_buffer[n_pbuf..], pattern[0..]); n_pbuf += pattern.len; try ensureDir(path_buffer[0..n_pbuf]); n_pbuf -= pattern.len; } } } try stdout.writer().print("test creation finished\n", .{}); } test "use of realpath instead of realpathAlloc" { // to be called after running `zig test tfgen` // realpath utilizes the cwd() of the current process (undocumented in libstd) const path_name: []const u8 = "test_folders/bad_patterns/ fname/.."; // adding \x00 breaks things var out_buf: [4096]u8 = undefined; const real_path = try os.realpath(path_name, &out_buf); // works std.debug.print("real_path: {s}\n", .{real_path}); }
src/testfolder_gen.zig
const __floatdidf = @import("floatdidf.zig").__floatdidf; const testing = @import("std").testing; fn test__floatdidf(a: i64, expected: f64) !void { const r = __floatdidf(a); try testing.expect(r == expected); } test "floatdidf" { try test__floatdidf(0, 0.0); try test__floatdidf(1, 1.0); try test__floatdidf(2, 2.0); try test__floatdidf(20, 20.0); try test__floatdidf(-1, -1.0); try test__floatdidf(-2, -2.0); try test__floatdidf(-20, -20.0); try test__floatdidf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); try test__floatdidf(0x7FFFFFFFFFFFF800, 0x1.FFFFFFFFFFFFEp+62); try test__floatdidf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); try test__floatdidf(0x7FFFFFFFFFFFF000, 0x1.FFFFFFFFFFFFCp+62); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000008000000000)), -0x1.FFFFFEp+62); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000000000000800)), -0x1.FFFFFFFFFFFFEp+62); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000010000000000)), -0x1.FFFFFCp+62); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000000000001000)), -0x1.FFFFFFFFFFFFCp+62); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000000000000000)), -0x1.000000p+63); try test__floatdidf(@bitCast(i64, @intCast(u64, 0x8000000000000001)), -0x1.000000p+63); try test__floatdidf(0x0007FB72E8000000, 0x1.FEDCBAp+50); try test__floatdidf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); try test__floatdidf(0x0007FB72EB000000, 0x1.FEDCBACp+50); try test__floatdidf(0x0007FB72EBFFFFFF, 0x1.FEDCBAFFFFFFCp+50); try test__floatdidf(0x0007FB72EC000000, 0x1.FEDCBBp+50); try test__floatdidf(0x0007FB72E8000001, 0x1.FEDCBA0000004p+50); try test__floatdidf(0x0007FB72E6000000, 0x1.FEDCB98p+50); try test__floatdidf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); try test__floatdidf(0x0007FB72E7FFFFFF, 0x1.FEDCB9FFFFFFCp+50); try test__floatdidf(0x0007FB72E4000001, 0x1.FEDCB90000004p+50); try test__floatdidf(0x0007FB72E4000000, 0x1.FEDCB9p+50); try test__floatdidf(0x023479FD0E092DC0, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DA1, 0x1.1A3CFE870496Dp+57); try test__floatdidf(0x023479FD0E092DB0, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DB8, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DB6, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DBF, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DC1, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DC7, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DC8, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DCF, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DD0, 0x1.1A3CFE870496Ep+57); try test__floatdidf(0x023479FD0E092DD1, 0x1.1A3CFE870496Fp+57); try test__floatdidf(0x023479FD0E092DD8, 0x1.1A3CFE870496Fp+57); try test__floatdidf(0x023479FD0E092DDF, 0x1.1A3CFE870496Fp+57); try test__floatdidf(0x023479FD0E092DE0, 0x1.1A3CFE870496Fp+57); }
lib/std/special/compiler_rt/floatdidf_test.zig
const ResultStream = @import("result_stream.zig").ResultStream; const Iterator = @import("result_stream.zig").Iterator; const ParserPath = @import("parser_path.zig").ParserPath; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const Error = error{OutOfMemory}; pub const ResultTag = enum { value, err, }; /// deinitOptional invokes value.deinit(allocator), taking into account it being an optional /// `?Value`, `??Value`, etc. pub inline fn deinitOptional(value: anytype, allocator: *mem.Allocator) void { switch (@typeInfo(@TypeOf(value))) { .Optional => if (value) |v| return deinitOptional(v, allocator), else => value.deinit(allocator), } } /// A parser result, one of: /// /// 1. A `value` and new `offset` into the input `src`. /// 2. An `err` and new `offset` ito the input `src` ((i.e. position of error). /// /// A Result always knows how to `deinit` itself. pub fn Result(comptime Value: type) type { return struct { offset: usize, result: union(ResultTag) { value: Value, err: []const u8, }, owned: bool, pub fn init(offset: usize, value: Value) @This() { return .{ .offset = offset, .result = .{ .value = value }, .owned = true, }; } pub fn deinit(self: @This(), allocator: *mem.Allocator) void { if (!self.owned) return; switch (self.result) { .value => |value| { deinitOptional(value, allocator); }, else => {}, } } pub fn toUnowned(self: @This()) @This() { var tmp = self; tmp.owned = false; return tmp; } pub fn initError(offset: usize, err: []const u8) @This() { return .{ .offset = offset, .result = .{ .err = err }, .owned = false, }; } }; } const MemoizeValue = struct { results: usize, // untyped pointer *ResultStream(Result(Value)) deinit: fn (results: usize, allocator: *mem.Allocator) void, }; fn MemoizedResult(comptime Value: type) type { return struct { results: *ResultStream(Result(Value)), was_cached: bool, }; } /// A key describing a parser node at a specific position in an input string, as well as the number /// of times it reentrantly called itself at that exact position. const ParserPosDepthKey = struct { pos_key: ParserPosKey, reentrant_depth: usize, }; /// Describes the exact string and offset into it that a parser node is parsing. pub const ParserPosKey = struct { node_name: ParserNodeName, src_ptr: usize, offset: usize, }; /// The name of a parser node. This includes hashes of: /// /// * The parser's type name (e.g. "MapTo", "Sequence", etc.) /// * The actual parser inputs (e.g. the list of parsers to match in a Sequence parser, or for a /// MapTo parser the input parser to match and the actual function that does mapping.) /// /// It is enough to distinctly represent a _single node in the parser graph._ Note that it is NOT /// the same as: /// /// * Identifying a singular parser instance (two parser instances with the same inputs will be /// "deduplicated" and have the same parser node name.) /// * Identifying a parser node at a particular position: the parser `offset` position and `src` /// string to parse are NOT parse of a parser node name, for that see `ParserPosKey`. /// pub const ParserNodeName = u64; /// Records a single recursion retry for a parser. const RecursionRetry = struct { /// The current reentrant depth of the parser. depth: usize, /// The maximum reentrant depth before this retry attempt will be stopped. max_depth: usize, }; const Memoizer = struct { /// Parser position & reentrant depth key -> memoized results memoized: std.AutoHashMap(ParserPosDepthKey, MemoizeValue), /// *Parser(T, P) -> computed parser node name. node_name_cache: std.AutoHashMap(usize, ParserNodeName), /// Maps position key -> the currently active recursion retry attempt, if any. recursion: std.AutoHashMap(ParserPosKey, RecursionRetry), /// Memoized values to cleanup later, because freeing them inside a reentrant parser /// invocation is not possible as the parent still intends to use it. /// /// TODO(slimsag): consider something like reference counting here to reduce memory /// footprint. deferred_cleanups: std.ArrayList(MemoizeValue), /// Tells if the given parser node is currently being retried at different maximum reentrant /// depths as part of a Reentrant combinator. pub fn isRetrying(self: *@This(), key: ParserPosKey) bool { const recursion = self.recursion.get(key); if (recursion == null) return false; return true; } fn clearPastRecursions(self: *@This(), parser: ParserPosKey, new_max_depth: usize) !void { var i: usize = 0; while (i <= new_max_depth) : (i += 1) { const k = ParserPosDepthKey{ .pos_key = parser, .reentrant_depth = i, }; if (self.memoized.get(k)) |memoized| try self.deferred_cleanups.append(memoized); _ = self.memoized.remove(k); } } pub fn get(self: *@This(), comptime Value: type, allocator: *mem.Allocator, parser_path: ParserPath, parser: ParserPosKey, new_max_depth: ?usize) !MemoizedResult(Value) { // We memoize results for each unique ParserPosDepthKey, meaning that a parser node can be // invoked to parse a specific input string at a specific offset recursively in a reentrant // way up to a maximum depth (new_max_depth). This enables our GLL parser to handle grammars // that are left-recursive, such as: // // ```ebnf // Expr = Expr?, "abc" ; // Grammar = Expr ; // ``` // // Where an input string "abcabcabc" would require `Expr` be parsed at offset=0 in the // input string multiple times. How many times? We start out with a maximum reentry depth // of zero, and if we determine that the parsing is cyclic (a ResultStream subscriber is in // fact itself the source) we consider that parse path as failed (it matches only the empty // language) and retry with a new_max_depth of N+1 and retry the whole parse path, // repeating this process until eventually we find the parsing is not cyclic. // // It is important to note that this is for handling reentrant parsing _at the same exact // offset position in the input string_, the GLL parsing algorithm itself handles left // recursive and right recursive parsing fine on its own, as long as the parse position is // changing, but many implementations cannot handle reentrant parsing at the same exact // offset position in the input string (I am unsure if this is by design, or a limitation // of the implementations themselves). Packrattle[1] which uses an "optimized" GLL parsing // algorithm (memoization is localized to parse nodes) is the closest to our algorithm, and // can handle this type of same-position left recursion in some instances such as with: // // ```ebnf // Expr = Expr?, "abc" ; // Grammar = Expr, EOF ; // ``` // // However, it does so using a _globalized_ retry mechanism[2] which in this event resets // the entire parser back to an earlier point in time, only if the overall parse failed. // This also coincidently means that if the `EOF` matcher is removed (`Grammar = Expr ;`) // then `Expr` matching becomes "non-greedy" matching just one "abc" value instead of all // three as when the EOF matcher is in place. // // Our implementation here uses node-localized retries, which makes us not subject to the // same bug as packrattle and more optimized (the entire parse need not fail for us to // detect and retry in this case, we do so exactly at the reentrant parser node itself.) // // [1] https://github.com/robey/packrattle // [2] https://github.com/robey/packrattle/blob/3db99f2d87abdddb9d29a0d0cf86e272c59d4ddb/src/packrattle/engine.js#L137-L177 // var reentrant_depth: usize = 0; const recursionEntry = self.recursion.get(parser); if (recursionEntry) |entry| { if (new_max_depth != null) { // Existing entry, but we want to retry with a new_max_depth; reentrant_depth = new_max_depth.?; try self.recursion.put(parser, .{ .depth = new_max_depth.?, .max_depth = new_max_depth.? }); try self.clearPastRecursions(parser, new_max_depth.?); } else { // Existing entry, so increment the depth and continue. var depth = entry.depth; if (depth > 0) { depth -= 1; } try self.recursion.put(parser, .{ .depth = depth, .max_depth = entry.max_depth }); reentrant_depth = depth; } } else if (new_max_depth != null) { // No existing entry, want to retry with new_max_depth. reentrant_depth = new_max_depth.?; try self.recursion.put(parser, .{ .depth = new_max_depth.?, .max_depth = new_max_depth.? }); try self.clearPastRecursions(parser, new_max_depth.?); } else { // No existing entry, but a distant parent parser may be retrying with a max depth that // we should respect. var next_node = parser_path.stack.root; while (next_node) |next| { const parentRecursionEntry = self.recursion.get(next.data); if (parentRecursionEntry) |parent_entry| { reentrant_depth = parent_entry.depth; try self.clearPastRecursions(parser, parent_entry.max_depth); break; } next_node = next.next; } } // Do we have an existing result stream for this key? const m = try self.memoized.getOrPut(ParserPosDepthKey{ .pos_key = parser, .reentrant_depth = reentrant_depth, }); if (!m.found_existing) { // Create a new result stream for this key. var results = try allocator.create(ResultStream(Result(Value))); results.* = try ResultStream(Result(Value)).init(allocator, parser); m.value_ptr.* = MemoizeValue{ .results = @ptrToInt(results), .deinit = struct { fn deinit(_resultsPtr: usize, _allocator: *mem.Allocator) void { var _results = @intToPtr(*ResultStream(Result(Value)), _resultsPtr); _results.deinit(); _allocator.destroy(_results); } }.deinit, }; } return MemoizedResult(Value){ .results = @intToPtr(*ResultStream(Result(Value)), m.value_ptr.results), .was_cached = m.found_existing, }; } pub fn init(allocator: *mem.Allocator) !*@This() { var self = try allocator.create(@This()); self.* = .{ .memoized = std.AutoHashMap(ParserPosDepthKey, MemoizeValue).init(allocator), .node_name_cache = std.AutoHashMap(usize, ParserNodeName).init(allocator), .recursion = std.AutoHashMap(ParserPosKey, RecursionRetry).init(allocator), .deferred_cleanups = std.ArrayList(MemoizeValue).init(allocator), }; return self; } pub fn deinit(self: *@This(), allocator: *mem.Allocator) void { var iter = self.memoized.iterator(); while (iter.next()) |memoized| { memoized.value_ptr.deinit(memoized.value_ptr.results, allocator); } self.memoized.deinit(); self.node_name_cache.deinit(); self.recursion.deinit(); for (self.deferred_cleanups.items) |item| { item.deinit(item.results, allocator); } self.deferred_cleanups.deinit(); allocator.destroy(self); } }; /// Describes context to be given to a `Parser`, such as `input` parameters, an `allocator`, and /// the actual `src` to parse. pub fn Context(comptime Input: type, comptime Value: type) type { return struct { input: Input, allocator: *mem.Allocator, src: []const u8, offset: usize, results: *ResultStream(Result(Value)), existing_results: bool, memoizer: *Memoizer, key: ParserPosKey, path: ParserPath, pub fn init(allocator: *mem.Allocator, src: []const u8, input: Input) !@This() { var src_ptr: usize = 0; if (src.len > 0) { src_ptr = @ptrToInt(&src[0]); } const key = .{ .node_name = 0, .src_ptr = src_ptr, .offset = 0, }; var results = try allocator.create(ResultStream(Result(Value))); results.* = try ResultStream(Result(Value)).init(allocator, key); return @This(){ .input = input, .allocator = allocator, .src = src, .offset = 0, .results = results, .existing_results = false, .memoizer = try Memoizer.init(allocator), .key = key, .path = ParserPath.init(), }; } pub fn initChild(self: @This(), comptime NewValue: type, node_name: ParserNodeName, offset: usize) !Context(Input, NewValue) { return self.initChildRetry(NewValue, node_name, offset, null); } /// initChildRetry initializes a child context to be used as a single retry attempt with a /// new maximum depth of reentrant parser invocations for the child and all of its /// children. pub fn initChildRetry(self: @This(), comptime NewValue: type, node_name: ParserNodeName, offset: usize, max_depth: ?usize) !Context(Input, NewValue) { var src_ptr: usize = 0; if (self.src.len > 0) { src_ptr = @ptrToInt(&self.src[0]); } const key = ParserPosKey{ .node_name = node_name, .src_ptr = src_ptr, .offset = offset, }; var child_ctx = Context(Input, NewValue){ .input = self.input, .allocator = self.allocator, .src = self.src, .offset = offset, .results = undefined, .existing_results = false, .memoizer = self.memoizer, .key = key, .path = try self.path.clone(self.allocator), }; try child_ctx.path.push(child_ctx.key, self.allocator); var memoized = try self.memoizer.get(NewValue, self.allocator, child_ctx.path, key, max_depth); child_ctx.results = memoized.results; if (memoized.was_cached) { child_ctx.existing_results = true; } return child_ctx; } /// isRetrying tells if this context represents a retry initiated previously via /// initChildRetry, potentially by a distant parent recursive call, indicating that a new /// reentrant retry should not be attempted. pub fn isRetrying(self: @This(), node_name: ParserNodeName, offset: usize) bool { var src_ptr: usize = 0; if (self.src.len > 0) { src_ptr = @ptrToInt(&self.src[0]); } return self.memoizer.isRetrying(ParserPosKey{ .node_name = node_name, .src_ptr = src_ptr, .offset = offset, }); } /// Subscribe to the results from this context. The caller owns the values and is /// responsible for calling `deinit` on each. pub fn subscribe(self: @This()) Iterator(Result(Value)) { return self.results.subscribe( self.key, self.path, Result(Value).initError(self.offset, "matches only the empty language"), ); } pub fn with(self: @This(), new_input: anytype) Context(@TypeOf(new_input), Value) { return Context(@TypeOf(new_input), Value){ .input = new_input, .allocator = self.allocator, .src = self.src, .offset = self.offset, .results = self.results, .existing_results = self.existing_results, .memoizer = self.memoizer, .key = self.key, .path = self.path, }; } pub fn deinit(self: *const @This()) void { self.results.deinit(); self.allocator.destroy(self.results); self.memoizer.deinit(self.allocator); self.path.deinit(self.allocator); return; } pub fn deinitChild(self: @This()) void { self.path.deinit(self.allocator); return; } }; } /// An interface whose implementation can be swapped out at runtime. It carries an arbitrary /// `Context` to make the type signature generic, and produces a `Value` of the given type which /// may vary from parser to parser. /// /// The `Payload` type is used to denote a payload of a single type which is typically passed /// through all parsers in a grammar. Parser and parser combinator implementations should always /// allow the user to specify this type, and should generally avoid changing the type or using it /// for their own purposes unless they are e.g. deferring parsing to another language grammar /// entirely. pub fn Parser(comptime Payload: type, comptime Value: type) type { return struct { const Self = @This(); _parse: fn (self: *const Self, ctx: *const Context(Payload, Value)) callconv(.Async) Error!void, _nodeName: fn (self: *const Self, node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64, _deinit: ?fn (self: *Self, allocator: *mem.Allocator) void, _heap_storage: ?[]u8, _refs: usize, pub fn init( parseImpl: fn (self: *const Self, ctx: *const Context(Payload, Value)) callconv(.Async) Error!void, nodeNameImpl: fn (self: *const Self, node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64, deinitImpl: ?fn (self: *Self, allocator: *mem.Allocator) void, ) @This() { return .{ ._parse = parseImpl, ._nodeName = nodeNameImpl, ._deinit = deinitImpl, ._heap_storage = null, ._refs = 0, }; } /// Allocates and stores the `parent` value (e.g. `Literal(...).init(...)` on the heap, /// turning this `Parser` into a heap-allocated one. Returned is a poiner to the /// heap-allocated `&parent.parser`. pub fn heapAlloc(self: *const @This(), allocator: *mem.Allocator, parent: anytype) !*@This() { const Parent = @TypeOf(parent); var memory = try allocator.allocAdvanced(u8, @alignOf(Parent), @sizeOf(Parent), mem.Allocator.Exact.at_least); var parent_ptr = @ptrCast(*Parent, &memory[0]); parent_ptr.* = parent; parent_ptr.parser._heap_storage = memory; parent_ptr.parser._refs += 1; return &parent_ptr.parser; } pub fn ref(self: *@This()) *@This() { self._refs += 1; return self; } pub fn deinit(self: *@This(), allocator: *mem.Allocator) void { self._refs -= 1; if (self._refs == 0) { if (self._deinit) |dfn| { dfn(self, allocator); } if (self._heap_storage) |s| { allocator.free(s); } } if (self._refs < 0) unreachable; } pub fn parse(self: *const Self, ctx: *const Context(Payload, Value)) callconv(.Async) Error!void { var frame = try std.heap.page_allocator.allocAdvanced(u8, 16, @frameSize(self._parse), std.mem.Allocator.Exact.at_least); defer std.heap.page_allocator.free(frame); return try await @asyncCall(frame, {}, self._parse, .{ self, ctx }); } pub fn nodeName(self: *const Self, node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 { var v = try node_name_cache.getOrPut(@ptrToInt(self)); if (!v.found_existing) { v.value_ptr.* = 1337; // "currently calculating" code const calculated = try self._nodeName(self, node_name_cache); // If self._nodeName added more entries to node_name_cache, ours is now potentially invalid. var vv = node_name_cache.getEntry(@ptrToInt(self)); vv.?.value_ptr.* = calculated; return calculated; } if (v.value_ptr.* == 1337) { return 0; // reentrant, don't bother trying to calculate any more recursively } return v.value_ptr.*; } }; } test "syntax" { const p = Parser(void, []u8); } test "heap_parser" { nosuspend { const Literal = @import("../parser/literal.zig").Literal; const LiteralValue = @import("../parser/literal.zig").LiteralValue; const LiteralContext = @import("../parser/literal.zig").LiteralContext; const allocator = testing.allocator; const Payload = void; var ctx = try Context(Payload, LiteralValue).init(allocator, "hello world", {}); defer ctx.deinit(); // The parser we'll store on the heap. var want = "hello"; var literal_parser = Literal(Payload).init(want); // Move to heap. var heap_parser = try literal_parser.parser.heapAlloc(allocator, literal_parser); defer heap_parser.deinit(allocator); // Use it. try heap_parser.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; defer first.deinit(ctx.allocator); try testing.expectEqual(Result(LiteralValue).init(want.len, .{ .value = "hello" }), first); try testing.expect(sub.next() == null); } }
src/combn/engine/parser.zig
const kernel = @import("../kernel/kernel.zig"); const log = kernel.log.scoped(.PCI); const TODO = kernel.TODO; const Controller = @This(); const PrivilegeLevel = kernel.PrivilegeLevel; const x86_64 = @import("../kernel/arch/x86_64.zig"); devices: []Device, bus_scan_states: [256]BusScanState, pub var controller: Controller = undefined; pub fn init() void { controller.enumerate(); } const BusScanState = enum(u8) { do_not_scan = 0, scan_next = 1, scanned = 2, }; const pci_read_config = kernel.arch.pci_read_config; const pci_write_config = kernel.arch.pci_read_config; fn enumerate(pci: *Controller) void { const base_header_type = pci_read_config(u32, 0, 0, 0, 0x0c); log.debug("Base header type: 0x{x}", .{base_header_type}); const base_bus_count: u8 = if (base_header_type & 0x80 != 0) 8 else 1; var base_bus: u8 = 0; var buses_to_scan: u8 = 0; while (base_bus < base_bus_count) : (base_bus += 1) { // TODO: ERROR maybe? shouldn't base bus be another parameter? const device_id = pci_read_config(u32, 0, 0, base_bus, 0x00); if (@truncate(u16, device_id) == 0xffff) continue; pci.bus_scan_states[base_bus] = .scan_next; buses_to_scan += 1; } const original_bus_to_scan_count = buses_to_scan; if (buses_to_scan == 0) kernel.panic("unable to find any PCI bus", .{}); var device_count: u64 = 0; // First scan the buses to find out how many PCI devices the computer has while (buses_to_scan > 0) { var bus_i: u9 = 0; while (bus_i < 256) : (bus_i += 1) { const bus = @intCast(u8, bus_i); if (pci.bus_scan_states[bus] != .scan_next) continue; log.debug("Scanning bus {}...", .{bus}); pci.bus_scan_states[bus] = .scanned; buses_to_scan -= 1; var device: u8 = 0; while (device < 32) : (device += 1) { const outer_device_id = pci_read_config(u32, bus, device, 0, 0); if (@truncate(u16, outer_device_id) == 0xffff) continue; log.debug("Outer device id: 0x{x}", .{outer_device_id}); const header_type = @truncate(u8, pci_read_config(u32, bus, device, 0, 0x0c) >> 16); const function_count: u8 = if (header_type & 0x80 != 0) 8 else 1; var function: u8 = 0; log.debug("Function count: {}", .{function_count}); while (function < function_count) : (function += 1) { const inner_device_id = pci_read_config(u32, bus, device, function, 0x00); if (@truncate(u16, inner_device_id) == 0xffff) continue; device_count += 1; const device_class = pci_read_config(u32, bus, device, function, 0x08); const class_code = @truncate(u8, device_class >> 24); const subclass_code = @truncate(u8, device_class >> 16); if (class_code == 0x06 and subclass_code == 0x04) { const secondary_bus = @truncate(u8, pci_read_config(u32, bus, device, function, 0x18) >> 8); buses_to_scan += 1; pci.bus_scan_states[secondary_bus] = .scan_next; } } } } } base_bus = 0; while (base_bus < base_bus_count) : (base_bus += 1) { // TODO: ERROR maybe? shouldn't base bus be another parameter? const device_id = pci_read_config(u32, 0, 0, base_bus, 0x00); if (@truncate(u16, device_id) == 0xffff) continue; pci.bus_scan_states[base_bus] = .scan_next; } log.debug("Device count: {}", .{device_count}); buses_to_scan = original_bus_to_scan_count; pci.devices = kernel.core_heap.allocate_many(Device, device_count) orelse @panic("unable to allocate pci devices"); var registered_device_count: u64 = 0; log.debug("Buses to scan: {}", .{buses_to_scan}); while (buses_to_scan > 0) { var bus_i: u9 = 0; while (bus_i < 256) : (bus_i += 1) { const bus = @intCast(u8, bus_i); if (pci.bus_scan_states[bus] != .scan_next) continue; log.debug("Scanning bus {}...", .{bus}); pci.bus_scan_states[bus] = .scanned; buses_to_scan -= 1; var device: u8 = 0; while (device < 32) : (device += 1) { const outer_device_id = pci_read_config(u32, bus, device, 0, 0); if (@truncate(u16, outer_device_id) == 0xffff) continue; log.debug("Outer device id: 0x{x}", .{outer_device_id}); const header_type = @truncate(u8, pci_read_config(u32, bus, device, 0, 0x0c) >> 16); const function_count: u8 = if (header_type & 0x80 != 0) 8 else 1; var function: u8 = 0; log.debug("Function count: {}", .{function_count}); while (function < function_count) : (function += 1) { const inner_device_id = pci_read_config(u32, bus, device, function, 0x00); if (@truncate(u16, inner_device_id) == 0xffff) continue; log.debug("Inner Device id: 0x{x}", .{inner_device_id}); const device_class = pci_read_config(u32, bus, device, function, 0x08); log.debug("Device class: 0x{x}", .{device_class}); const interrupt_information = pci_read_config(u32, bus, device, function, 0x3c); log.debug("Interrupt information: 0x{x}", .{interrupt_information}); const pci_device = &pci.devices[registered_device_count]; registered_device_count += 1; pci_device.class_code = @truncate(u8, device_class >> 24); pci_device.subclass_code = @truncate(u8, device_class >> 16); pci_device.prog_if = @truncate(u8, device_class >> 8); pci_device.bus = bus; pci_device.slot = device; pci_device.function = function; pci_device.interrupt_pin = @truncate(u8, interrupt_information >> 8); pci_device.interrupt_line = @truncate(u8, interrupt_information); log.debug("Interrupt line: 0x{x}", .{pci_device.interrupt_line}); const new_device_id = pci_read_config(u32, bus, device, function, 0x00); kernel.assert(@src(), new_device_id == inner_device_id); pci_device.device_id = new_device_id; pci_device.subsystem_id = pci_read_config(u32, bus, device, function, 0x2c); for (pci_device.base_addresses) |*base_address, i| { base_address.* = pci_device.read_config(u32, 0x10 + 4 * @intCast(u8, i), .kernel); } const class_code_name = if (pci_device.class_code < class_code_names.len) class_code_names[pci_device.class_code] else "Unknown"; const subclass_code_name = switch (pci_device.class_code) { 1 => if (pci_device.subclass_code < subclass1_code_names.len) subclass1_code_names[pci_device.subclass_code] else "", 12 => if (pci_device.subclass_code < subclass12_code_names.len) subclass12_code_names[pci_device.subclass_code] else "", else => "", }; const prog_if_name = if (pci_device.class_code == 12 and pci_device.subclass_code == 3 and pci_device.prog_if / 0x10 < prog_if_12_3_names.len) prog_if_12_3_names[pci_device.prog_if / 0x10] else ""; log.debug("PCI device. Class 0x{x} ({s}). Subclass: 0x{x} ({s}). Prog IF: {s}", .{ pci_device.class_code, class_code_name, pci_device.subclass_code, subclass_code_name, prog_if_name }); } } } } } pub fn find_device(pci: *Controller, class_code: u8, subclass_code: u8) ?*Device { for (pci.devices) |*device| { if (device.class_code == class_code and device.subclass_code == subclass_code) { return device; } } return null; } const class_code_names = [_][]const u8{ "Unknown", "Mass storage controller", "Network controller", "Display controller", "Multimedia controller", "Memory controller", "Bridge controller", "Simple communication controller", "Base system peripheral", "Input device controller", "Docking station", "Processor", "Serial bus controller", "Wireless controller", "Intelligent controller", "Satellite communication controller", "Encryption controller", "Signal processing controller", }; const subclass1_code_names = [_][]const u8{ "SCSI bus controller", "IDE controller", "Floppy disk controller", "IPI bus controller", "RAID controller", "ATA controller", "Serial ATA", "Serial attached SCSI", "Non-volatile memory controller (NVMe)", }; const subclass12_code_names = [_][]const u8{ "FireWire (IEEE 1394) controller", "ACCESS bus", "SSA", "USB controller", "Fibre channel", "SMBus", "InfiniBand", "IPMI interface", "SERCOS interface (IEC 61491)", "CANbus", }; const prog_if_12_3_names = [_][]const u8{ "UHCI", "OHCI", "EHCI", "XHCI", }; pub const Device = struct { device_id: u32, subsystem_id: u32, domain: u32, class_code: u8, subclass_code: u8, prog_if: u8, bus: u8, slot: u8, function: u8, interrupt_pin: u8, interrupt_line: u8, base_virtual_addresses: [6]kernel.Virtual.Address, base_physical_addresses: [6]kernel.Physical.Address, base_addresses_size: [6]u64, base_addresses: [6]u32, //uint8_t *baseAddressesVirtual[6]; //uintptr_t baseAddressesPhysical[6]; //size_t baseAddressesSizes[6]; //uint32_t baseAddresses[6]; pub inline fn read_config(device: *Device, comptime T: type, offset: u8, comptime privilege_level: PrivilegeLevel) T { kernel.assert(@src(), privilege_level == .kernel); return kernel.arch.pci_read_config(T, device.bus, device.slot, device.function, offset); } pub inline fn write_config(device: *Device, comptime T: type, value: T, offset: u8, comptime privilege_level: PrivilegeLevel) void { kernel.assert(@src(), privilege_level == .kernel); return kernel.arch.pci_write_config(T, value, device.bus, device.slot, device.function, offset); } pub inline fn read_bar(device: *Device, comptime T: type, index: u64, offset: u64) T { const base_address = device.base_addresses[index]; log.debug("Base address: 0x{x}", .{base_address}); if (T != u64) { if (base_address & 1 != 0) { log.debug("Using base address for read", .{}); const port = @intCast(u16, (base_address & ~@as(u32, 3)) + offset); return kernel.arch.io_read(T, port); } else { log.debug("Using base virtual address for read", .{}); return device.base_virtual_addresses[index].offset(offset).access(*volatile T).*; } } else { if (base_address & 1 != 0) { log.debug("Using base address for read", .{}); return device.read_bar(u32, index, offset) | (@intCast(u64, device.read_bar(u64, index, offset + @sizeOf(u32))) << 32); } else { log.debug("Using base virtual address for read", .{}); return device.base_virtual_addresses[index].offset(offset).access(*volatile T).*; } } } pub inline fn write_bar(device: *Device, comptime T: type, index: u64, offset: u64, value: T) void { const base_address = device.base_addresses[index]; log.debug("Base address 0x{x}", .{base_address}); if (T != u64) { if (base_address & 1 != 0) { const port = @intCast(u16, (base_address & ~@as(@TypeOf(base_address), 3)) + offset); log.debug("Writing to port 0x{x}", .{port}); kernel.arch.io_write(T, port, value); } else { log.debug("index: {}", .{index}); const virtual_address = device.base_virtual_addresses[index].offset(offset); log.debug("Virtual address: 0x{x}", .{virtual_address.value}); virtual_address.access(*volatile T).* = value; } } else { if (base_address & 1 != 0) { log.debug("here?", .{}); device.write_bar(u32, index, offset, @truncate(u32, value)); device.write_bar(u32, index, offset + @sizeOf(u32), @truncate(u32, value >> 32)); } else { log.debug("here?", .{}); device.base_virtual_addresses[index].offset(offset).access(*volatile T).* = value; } } } pub const Features = kernel.Bitflag(false, enum(u64) { bar0 = 0, bar1 = 1, bar2 = 2, bar3 = 3, bar4 = 4, bar5 = 5, interrupts = 8, busmastering_dma = 9, memory_space_access = 10, io_port_access = 11, }); pub fn enable_features(device: *Device, features: Features) bool { log.debug("Enabling features for device {}", .{device}); var config = device.read_config(u32, 4, .kernel); if (features.contains(.interrupts)) config &= ~@as(u32, 1 << 10); if (features.contains(.busmastering_dma)) config |= 1 << 2; if (features.contains(.memory_space_access)) config |= 1 << 1; if (features.contains(.io_port_access)) config |= 1 << 0; log.debug("Writing config: 0x{x}", .{config}); device.write_config(u32, config, 4, .kernel); if (device.read_config(u32, 4, .kernel) != config) { return false; } for (device.base_addresses) |*base_address_ptr, i| { if (~features.bits & (@as(u64, 1) << @intCast(u3, i)) != 0) continue; const base_address = base_address_ptr.*; if (base_address & 1 != 0) continue; // BAR is an IO port log.debug("Actually setting up base address #{}", .{i}); if (base_address & 0b1000 == 0) { // TODO: not prefetchable } const is_size_64 = base_address & 0b100 != 0; log.debug("is size 64: {}", .{is_size_64}); var address: u64 = 0; var size: u64 = 0; if (is_size_64) { device.write_config(u32, kernel.max_int(u32), 0x10 + 4 * @intCast(u8, i), .kernel); device.write_config(u32, kernel.max_int(u32), 0x10 + 4 * @intCast(u8, i + 1), .kernel); size = device.read_config(u32, 0x10 + 4 * @intCast(u8, i), .kernel); size |= @intCast(u64, device.read_config(u32, 0x10 + 4 * @intCast(u8, i + 1), .kernel)) << 32; device.write_config(u32, base_address, 0x10 + 4 * @intCast(u8, i), .kernel); device.write_config(u32, device.base_addresses[i + 1], 0x10 + 4 * @intCast(u8, i + 1), .kernel); address = base_address; address |= @intCast(u64, device.base_addresses[i + 1]) << 32; } else { device.write_config(u32, kernel.max_int(u32), 0x10 + 4 * @intCast(u8, i), .kernel); size = device.read_config(u32, 0x10 + 4 * @intCast(u8, i), .kernel); size |= @as(u64, kernel.max_int(u32)) << 32; device.write_config(u32, base_address, 0x10 + 4 * @intCast(u8, i), .kernel); address = base_address; } if (size == 0 or address == 0) return false; log.debug("Address: 0x{x}. Size: {}", .{ address, size }); size &= ~@as(u64, 0xf); size = ~size + 1; address &= ~@as(u64, 0xf); log.debug("Address: 0x{x}. Size: {}", .{ address, size }); device.base_physical_addresses[i] = kernel.Physical.Address.new(address); device.base_virtual_addresses[i] = device.base_physical_addresses[i].to_higher_half_virtual_address(); const physical_region = kernel.Physical.Memory.Region.new(device.base_physical_addresses[i], size); physical_region.map(&kernel.address_space, device.base_virtual_addresses[i], kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .cache_disable, .read_write })); log.debug("Virtual 0x{x}. Physical 0x{x}", .{ device.base_virtual_addresses[i].value, device.base_physical_addresses[i].value }); device.base_addresses_size[i] = size; } return true; } pub fn enable_single_interrupt(device: *Device, handler: x86_64.interrupts.HandlerInfo) bool { if (device.enable_MSI(handler)) return true; if (device.interrupt_pin == 0) return false; if (device.interrupt_pin > 4) return false; const result = device.enable_features(Features.from_flag(.interrupts)); kernel.assert(@src(), result); // TODO: consider some stuff Essence does? const interrupt_line: ?u64 = null; if (handler.register_IRQ(interrupt_line, device)) { return true; } TODO(@src()); } pub fn enable_MSI(device: *Device, handler: x86_64.interrupts.HandlerInfo) bool { _ = handler; const status = device.read_config(u32, 0x04, .kernel) >> 16; if (~status & (1 << 4) != 0) return false; var pointer = device.read_config(u8, 0x34, .kernel); var index: u64 = 0; while (true) { if (pointer == 0) break; if (index >= 0xff) break; index += 1; const dw = device.read_config(u32, pointer, .kernel); const next_pointer = @truncate(u8, dw >> 8); const id = @truncate(u8, dw); if (id != 5) { pointer = next_pointer; continue; } // TODO: maybe this is a bug.NVMe should support MSI TODO(@src()); //const msi = } return false; } };
src/drivers/pci.zig
const std = @import("std"); const glfw = @import("../mach-glfw/build.zig"); const gpu_dawn = @import("../mach-gpu-dawn/build.zig"); pub const Options = struct { glfw_options: glfw.Options = .{}, gpu_dawn_options: gpu_dawn.Options = .{}, }; fn buildLibrary( exe: *std.build.LibExeObjStep, options: Options, ) *std.build.LibExeObjStep { const lib = exe.builder.addStaticLibrary("zgpu", thisDir() ++ "/src/zgpu.zig"); lib.setBuildMode(exe.build_mode); lib.setTarget(exe.target); glfw.link(exe.builder, lib, options.glfw_options); gpu_dawn.link(exe.builder, lib, options.gpu_dawn_options); // If you don't want to use 'dear imgui' library just comment out below lines and do not use `zgpu.gui` // namespace in your code. lib.addIncludeDir(thisDir() ++ "/libs"); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_widgets.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_tables.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_draw.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_demo.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/cimgui.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_impl_glfw.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/libs/imgui/imgui_impl_wgpu.cpp", &.{""}); // If you don't want to use 'stb_image' library just comment out below line and do not use `zgpu.stbi` // namespace in your code. lib.addCSourceFile(thisDir() ++ "/libs/stb/stb_image.c", &.{"-std=c99"}); return lib; } pub fn link(exe: *std.build.LibExeObjStep, options: Options) void { glfw.link(exe.builder, exe, options.glfw_options); gpu_dawn.link(exe.builder, exe, options.gpu_dawn_options); const lib = buildLibrary(exe, options); exe.linkLibrary(lib); // imgui exe.addIncludeDir(thisDir() ++ "/libs"); } pub const pkg = std.build.Pkg{ .name = "zgpu", .path = .{ .path = thisDir() ++ "/src/zgpu.zig" }, .dependencies = &.{glfw.pkg}, }; fn thisDir() []const u8 { comptime { return std.fs.path.dirname(@src().file) orelse "."; } }
libs/zgpu/build.zig
const c = @import("c.zig"); const std = @import("std"); const panic = std.debug.panic; const ArrayList = std.ArrayList; const GeneralPurposeAllocator: type = std.heap.GeneralPurposeAllocator(.{}); fn glfwErrorCallback(err: c_int, description: [*c]const u8) callconv(.C) void { panic("Error: {}\n", .{@as([*:0]const u8, description)}); } fn glfwMouseCallback(window: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) callconv(.C) void { if (action == c.GLFW_PRESS) { input.setMouseState(@intCast(usize, button), true); } else if (action == c.GLFW_RELEASE) { input.setMouseState(@intCast(usize, button), false); } } fn glfwKeyCallback(window: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void { if (action == c.GLFW_PRESS) { input.setKeyState(@intCast(usize, key), true); } else if (action == c.GLFW_RELEASE) { input.setKeyState(@intCast(usize, key), false); } } fn glfwMouseMoveCallback(window: ?*c.GLFWwindow, xpos: f64, ypos: f64) callconv(.C) void { if (window == capturedWindow) { input.mouse_axes[0] = @floatCast(f32, xpos); input.mouse_axes[1] = @floatCast(f32, ypos); } else { // Set mouse pos } } fn glfwMouseEnteredCallback(window: ?*c.GLFWwindow, entered: c_int) callconv(.C) void { //If mouse has left current capture area var focused = c.glfwGetWindowAttrib(window, c.GLFW_FOCUSED); if (capturedWindow == window and entered == 0 and focused == 0) { c.glfwSetInputMode(window, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL); capturedWindow = null; } } //Global Variables/Functions var globalAllocator: GeneralPurposeAllocator = undefined; pub fn init() void { globalAllocator = GeneralPurposeAllocator{}; windowMap = WindowHashMap.init(&globalAllocator.allocator); _ = c.glfwSetErrorCallback(glfwErrorCallback); if (c.glfwInit() == c.GL_FALSE) { panic("Failed to initialise glfw\n", .{}); } c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 4); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 6); c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); c.glfwWindowHint(c.GLFW_DEPTH_BITS, 24); c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8); //c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on); c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_TRUE); } pub fn deinit() void { c.glfwTerminate(); windowMap.deinit(); const leaked = globalAllocator.deinit(); if (leaked) panic("Error: memory leaked", .{}); } pub fn update() void { if (capturedWindow) |windowHandle| { c.glfwSetCursorPos(windowHandle, 0.0, 0.0); } input.update(); c.glfwPollEvents(); } pub fn getTime() f64 { return c.glfwGetTime(); } //Window Variables/Functions pub const WindowId = usize; const WindowHashMap = std.AutoHashMap(WindowId, *c.GLFWwindow); var nextWindowId: WindowId = 0; var windowMap: WindowHashMap = undefined; pub fn createWindow(width: i32, height: i32, title: [:0]const u8) WindowId { var handle = c.glfwCreateWindow(width, height, title, null, null) orelse { panic("Failed to create window", .{}); }; c.glfwMakeContextCurrent(handle); _ = c.glfwSetMouseButtonCallback(handle, glfwMouseCallback); _ = c.glfwSetKeyCallback(handle, glfwKeyCallback); _ = c.glfwSetCursorPosCallback(handle, glfwMouseMoveCallback); _ = c.glfwSetCursorEnterCallback(handle, glfwMouseEnteredCallback); if (nextWindowId == 0) { //Load Glad if this is the first window if (c.gladLoadGLLoader(@ptrCast(c.GLADloadproc, c.glfwGetProcAddress)) == 0) { panic("Failed to initialise GLAD", .{}); } //Enable Vsync c.glfwSwapInterval(1); var major_ver: c.GLint = undefined; var minor_ver: c.GLint = undefined; c.glGetIntegerv(c.GL_MAJOR_VERSION, &major_ver); c.glGetIntegerv(c.GL_MINOR_VERSION, &minor_ver); var vendor_name = c.glGetString(c.GL_VENDOR); var device_name = c.glGetString(c.GL_RENDERER); const stdout = std.io.getStdOut().writer(); stdout.print("Opengl Initialized\n", .{}) catch {}; stdout.print("Opengl Version: {}.{}\n", .{major_ver, minor_ver}) catch {}; stdout.print("Devcie Vendor: {s}\n", .{vendor_name}) catch {}; stdout.print("Device Name: {s}\n", .{device_name}) catch {}; stdout.print("\n", .{}) catch {}; } windowMap.put(nextWindowId, handle) catch panic("Failed to add window Id", .{}); var windowId = nextWindowId; nextWindowId += 1; return windowId; } pub fn destoryWindow(windowId: WindowId) void { if (windowMap.contains(windowId)) { var handle = windowMap.remove(windowId).?.value; c.glfwDestroyWindow(handle); } } pub fn refreshWindow(windowId: WindowId) void { if (windowMap.contains(windowId)) { c.glfwSwapBuffers(windowMap.get(windowId).?); } } pub fn shouldCloseWindow(windowId: WindowId) bool { if (windowMap.contains(windowId)) { return c.glfwWindowShouldClose(windowMap.get(windowId).?) == 0; } return false; } pub fn getWindowSize(windowId: WindowId) [2]i32 { var size: [2]i32 = undefined; if (windowMap.contains(windowId)) { var cSize: [2]c_int = undefined; c.glfwGetFramebufferSize(windowMap.get(windowId).?, &cSize[0], &cSize[1]); size[0] = @intCast(i32, cSize[0]); size[1] = @intCast(i32, cSize[1]); } return size; } pub fn maximizeWindow(windowId: WindowId) void { if (windowMap.contains(windowId)) { c.glfwMaximizeWindow(getWindowHandle(windowId)); } } pub fn getWindowHandle(windowId: WindowId) *c.GLFWwindow { if (windowMap.contains(windowId)) { return windowMap.get(windowId).?; } panic("Tried to get handle for invalid window", .{}); } pub fn isWindowHovered(windowId: WindowId) bool { if (windowMap.contains(windowId)) { return c.glfwGetWindowAttrib(getWindowHandle(windowId), c.GLFW_HOVERED) != 0; } return false; } pub fn isWindowFocused(windowId: WindowId) bool { if (windowMap.contains(windowId)) { return c.glfwGetWindowAttrib(getWindowHandle(windowId), c.GLFW_FOCUSED) != 0; } return false; } pub fn setMouseCaptured(windowId: WindowId, capture: bool) void { if (windowMap.contains(windowId)) { var handle = getWindowHandle(windowId); if (capture) { c.glfwSetInputMode(handle, c.GLFW_CURSOR, c.GLFW_CURSOR_DISABLED); c.glfwSetCursorPos(handle, 0.0, 0.0); capturedWindow = handle; } else { var size = getWindowSize(windowId); c.glfwSetInputMode(handle, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL); c.glfwSetCursorPos(handle, @intToFloat(f64, size[0]) / 2.0, @intToFloat(f64, size[1]) / 2.0); capturedWindow = null; } } } pub fn getMouseCaptured(windowId: WindowId) bool { if (capturedWindow) |windowHandle| { return true; } else { return false; } } var capturedWindow: ?*c.GLFWwindow = null; //Input Variables/Functions const MouseButtonCount: usize = c.GLFW_MOUSE_BUTTON_LAST; const KeyboardButtonCount: usize = c.GLFW_KEY_LAST; const ButtonInput = struct { current_state: bool = false, prev_state: bool = false, }; pub var input = struct { const Self = @This(); mouse_buttons: [MouseButtonCount]ButtonInput, keyboard_buttons: [KeyboardButtonCount]ButtonInput, mouse_axes: [2]f32, pub fn init() Self { return Self { .mouse_buttons = [_]ButtonInput{.{}} ** MouseButtonCount, .keyboard_buttons = [_]ButtonInput{.{}} ** KeyboardButtonCount, .mouse_axes = [_]f32{ 0.0, 0.0 }, }; } pub fn update(self: *Self) void { for (self.mouse_buttons) |*button| { button.prev_state = button.current_state; } for (self.keyboard_buttons) |*button| { button.prev_state = button.current_state; } self.mouse_axes = [_]f32{ 0.0, 0.0 }; } pub fn setMouseState(self: *Self, mouse_button: usize, state: bool) void { self.mouse_buttons[mouse_button].current_state = state; } pub fn getMouseDown(self: *Self, mouse_button: usize) bool { return self.mouse_buttons[mouse_button].current_state == true; } pub fn getMousePressed(self: *Self, mouse_button: usize) bool { var button = self.mouse_buttons[mouse_button]; return button.current_state == true and button.prev_state == false; } pub fn getMouseAxes(self: *Self) [2]f32 { return self.mouse_axes; } pub fn setKeyState(self: *Self, key: usize, state: bool) void { self.keyboard_buttons[key].current_state = state; } pub fn getKeyDown(self: *Self, key: usize) bool { return self.keyboard_buttons[key].current_state == true; } pub fn getKeyPressed(self: *Self, key: usize) bool { var button = self.keyboard_buttons[key]; return button.current_state == true and button.prev_state == false; } }.init();
src/glfw_platform.zig
const utils = @import("utils"); const georgios = @import("georgios"); const kernel = @import("kernel.zig"); const print = @import("print.zig"); const Allocator = @import("memory.zig").Allocator; const MemoryError = @import("memory.zig").MemoryError; const io = @import("io.zig"); const fs = @import("fs.zig"); pub const Error = fs.Error || io.BlockError || MemoryError || utils.Error; const Superblock = packed struct { const expected_magic: u16 = 0xef53; // Rev0 Superblock inode_count: u32 = 0, block_count: u32 = 0, superuser_block_count: u32 = 0, free_block_count: u32 = 0, free_inode_count: u32 = 0, first_data_block: u32 = 0, log_block_size: u32 = 0, log_frag_size: u32 = 0, blocks_per_group: u32 = 0, frags_per_group: u32 = 0, inodes_per_group: u32 = 0, last_mount_time: u32 = 0, last_write_time: u32 = 0, unchecked_mount_count: u16 = 0, max_unchecked_mount_count: u16 = 0, magic: u16 = 0, state: u16 = 0, error_repsponse: u16 = 0, minor_revision: u16 = 0, last_check_time: u32 = 0, check_interval: u32 = 0, creator_os: u32 = 0, major_revision: u32 = 0, superuser_uid: u16 = 0, superuser_gid: u16 = 0, // Start of Rev1 Superblock Extention first_nonreserved_inode: u32 = 0, inode_size: u32 = 0, // Rest has been left out for now pub fn verify(self: *const Superblock) Error!void { if (self.magic != expected_magic) { print.string("Invalid Ext2 Magic\n"); return Error.InvalidFilesystem; } if (self.major_revision != 1) { print.string("Invalid Ext2 Revision"); return Error.InvalidFilesystem; } if ((utils.align_up(self.inode_count, self.inodes_per_group) / self.inodes_per_group) != self.block_group_count()) { print.string("Inconsistent Ext2 Block Group Count"); return Error.InvalidFilesystem; } // TODO: Verify things related to inode_size } pub fn block_size(self: *const Superblock) usize { // TODO: Zig Bug? Can't inline utils.Ki(1) return @as(usize, 1024) << @truncate(utils.UsizeLog2Type, self.log_block_size); } pub fn block_group_count(self: *const Superblock) usize { return utils.align_up(self.block_count, self.blocks_per_group) / self.blocks_per_group; } }; const BlockGroupDescriptor = packed struct { block_bitmap: u32, inode_bitmap: u32, inode_table: u32, free_block_count: u16, free_inode_count: u16, used_dir_count: u16, pad: u16, reserved: [12]u8, }; const Inode = packed struct { mode: u16, uid: u16, size: u32, last_access_time: u32, creation_time: u32, last_modification_time: u32, deletion_time: u32, gid: u16, link_count: u16, block_count: u32, flags: u32, os_dependant_field_1: u32, blocks: [15]u32, generation: u32, file_acl: u32, dir_acl: u32, fragment_address: u32, os_dependant_field_2: [12]u8, pub fn is_file(self: *const Inode) bool { return self.mode & 0x8000 > 0; } pub fn is_directory(self: *const Inode) bool { return self.mode & 0x4000 > 0; } }; pub const DataBlockIterator = struct { const max_first_level_index: u8 = 11; const second_level_index = max_first_level_index + 1; const third_level_index = second_level_index + 1; const fourth_level_index = third_level_index + 1; const DataBlockInfoState = enum { Index, FillInZeros, EndOfFile, }; const DataBlockInfo = union(DataBlockInfoState) { Index: u32, FillInZeros: void, EndOfFile: void, }; ext2: *Ext2, inode: *Inode, got: usize = 0, first_level_pos: usize = 0, second_level: ?[]u32 = null, second_level_pos: usize = 0, third_level: ?[]u32 = null, third_level_pos: usize = 0, fourth_level: ?[]u32 = null, fourth_level_pos: usize = 0, new_pos: bool = false, pub fn set_position(self: *DataBlockIterator, block: usize) Error!void { if (block <= max_first_level_index) { self.first_level_pos = block; self.second_level_pos = 0; self.third_level_pos = 0; self.fourth_level_pos = 0; } else if (block >= Ext2.second_level_start and block < self.ext2.third_level_start) { self.first_level_pos = second_level_index; self.second_level_pos = block - Ext2.second_level_start; self.third_level_pos = 0; self.fourth_level_pos = 0; } else if (block >= self.ext2.third_level_start and block < self.ext2.fourth_level_start) { self.first_level_pos = third_level_index; const level_offset = block - self.ext2.third_level_start; self.second_level_pos = level_offset / self.ext2.max_entries_per_block; self.third_level_pos = level_offset % self.ext2.max_entries_per_block; self.fourth_level_pos = 0; } else if (block >= self.ext2.fourth_level_start and block < self.ext2.max_fourth_level_entries) { self.first_level_pos = fourth_level_index; const level_offset = block - self.ext2.fourth_level_start; self.second_level_pos = level_offset / self.ext2.max_third_level_entries; const sub_level_offset = level_offset % self.ext2.max_third_level_entries; self.third_level_pos = sub_level_offset / self.ext2.max_entries_per_block; self.fourth_level_pos = sub_level_offset % self.ext2.max_entries_per_block; } else return Error.OutOfBounds; self.got = block * self.ext2.block_size; self.new_pos = true; } fn get_level(self: *DataBlockIterator, level: *?[]u32, index: u32) Error!void { if (level.* == null) { level.* = try self.ext2.alloc.alloc_array( u32, self.ext2.block_size / @sizeOf(u32)); } try self.ext2.get_entry_block(level.*.?, index); } fn prepare_level(self: *DataBlockIterator, index: usize, level_pos: *usize, level: *?[]u32, parent_level_pos: *usize) bool { if (self.first_level_pos < index) return false; if (level_pos.* >= self.ext2.max_entries_per_block) { parent_level_pos.* += 1; level_pos.* = 0; return true; } return level.* == null or self.new_pos; } fn get_next_block_info(self: *DataBlockIterator) Error!DataBlockInfo { // print.format("get_next_block_index_i: {}\n", self.first_level_pos); // First Level if (self.first_level_pos <= max_first_level_index) { const index = self.inode.blocks[self.first_level_pos]; self.first_level_pos += 1; if (index == 0) { return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; } // Figure Out Our Position var get_fourth_level = self.prepare_level( fourth_level_index, &self.fourth_level_pos, &self.fourth_level, &self.third_level_pos); var get_third_level = self.prepare_level( third_level_index, &self.third_level_pos, &self.third_level, &self.second_level_pos); var get_second_level = self.prepare_level( second_level_index, &self.second_level_pos, &self.second_level, &self.first_level_pos); if (self.new_pos) self.new_pos = false; // Check for end of blocks if (self.first_level_pos > fourth_level_index) return DataBlockInfo.EndOfFile; // Get New Levels if Needed if (get_second_level) { const index = self.inode.blocks[self.first_level_pos]; if (index == 0) { self.second_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.second_level, index); } if (get_third_level) { const index = self.second_level.?[self.second_level_pos]; if (index == 0) { self.third_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.third_level, index); } if (get_fourth_level) { const index = self.third_level.?[self.third_level_pos]; if (index == 0) { self.fourth_level_pos += 1; return DataBlockInfo.FillInZeros; } try self.get_level(&self.fourth_level, index); } // Return The Result switch (self.first_level_pos) { second_level_index => { const index = self.second_level.?[self.second_level_pos]; if (index == 0) { self.second_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, third_level_index => { const index = self.third_level.?[self.third_level_pos]; if (index == 0) { self.third_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, fourth_level_index => { const index = self.fourth_level.?[self.fourth_level_pos]; if (index == 0) { self.fourth_level_pos += 1; return DataBlockInfo.FillInZeros; } return DataBlockInfo{.Index = index}; }, else => unreachable, } } pub fn next(self: *DataBlockIterator, dest: []u8) Error!?[]u8 { if (dest.len < self.ext2.block_size) { return Error.NotEnoughDestination; } const dest_use = dest[0..self.ext2.block_size]; switch (try self.get_next_block_info()) { .Index => |index| { try self.ext2.get_data_block(dest_use, index); }, .FillInZeros => utils.memory_set(dest_use, 0), .EndOfFile => return null, } const got = utils.min(u32, self.inode.size - self.got, self.ext2.block_size); // print.format("DataBlockIterator.next: got: {} {}\n", self.inode.size, self.got); self.got += got; return dest_use[0..got]; } pub fn done(self: *DataBlockIterator) Error!void { if (self.second_level != null) try self.ext2.alloc.free_array(self.second_level.?); if (self.third_level != null) try self.ext2.alloc.free_array(self.third_level.?); if (self.fourth_level != null) try self.ext2.alloc.free_array(self.fourth_level.?); } }; const DirectoryEntry = packed struct { inode: u32, next_entry_offset: u16, name_size: u8, file_type: u8, // NOTE: This field seems to always be 0 for the disk I am creating at the // time of writing, so this field can't be relied on. }; const DirectoryIterator = struct { pub const Value = struct { inode_number: u32, name: []const u8, inode: Inode, }; ext2: *Ext2, inode: *Inode, data_block_iter: DataBlockIterator, buffer: []u8, block_count: usize, buffer_pos: usize = 0, initial: bool = true, value: Value = undefined, pub fn new(ext2: *Ext2, inode: *Inode) fs.Error!DirectoryIterator { if (!inode.is_directory()) { return fs.Error.NotADirectory; } return DirectoryIterator{ .ext2 = ext2, .inode = inode, .data_block_iter = DataBlockIterator{.ext2 = ext2, .inode = inode}, .buffer = try ext2.alloc.alloc_array(u8, ext2.block_size), .block_count = inode.size / ext2.block_size, }; } pub fn next(self: *DirectoryIterator) fs.Error!bool { const get_next_block = self.buffer_pos >= self.ext2.block_size; if (get_next_block) { self.buffer_pos = 0; self.block_count -= 1; if (self.block_count == 0) { return false; } } if (get_next_block or self.initial) { self.initial = false; const result = self.data_block_iter.next(self.buffer) catch return fs.Error.Internal; if (result == null) { return false; } } const entry = @ptrCast(*DirectoryEntry, &self.buffer[self.buffer_pos]); const name_pos = self.buffer_pos + @sizeOf(DirectoryEntry); self.buffer_pos += entry.next_entry_offset; self.value.inode_number = entry.inode; self.value.name = self.buffer[name_pos..name_pos + entry.name_size]; self.ext2.get_inode(entry.inode, &self.value.inode) catch return fs.Error.Internal; return true; } pub fn done(self: *DirectoryIterator) Error!void { try self.data_block_iter.done(); try self.ext2.alloc.free_array(self.buffer); } }; pub const File = struct { const Self = @This(); ext2: *Ext2 = undefined, inode: Inode = undefined, io_file: io.File = undefined, data_block_iter: DataBlockIterator = undefined, buffer: ?[]u8 = null, position: usize = 0, pub fn init(self: *File, ext2: *Ext2, inode: u32) Error!void { self.* = File{}; self.ext2 = ext2; try ext2.get_inode(inode, &self.inode); self.data_block_iter = DataBlockIterator{.ext2 = ext2, .inode = &self.inode}; self.io_file = io.File{ .read_impl = Self.read, .write_impl = io.File.unsupported.write_impl, .seek_impl = Self.seek, .close_impl = io.File.nop.close_impl, }; } pub fn close(self: *File) MemoryError!void { if (self.buffer) |buffer| { try self.ext2.alloc.free_array(buffer); } } pub fn read(file: *io.File, to: []u8) io.FileError!usize { const self = @fieldParentPtr(Self, "io_file", file); if (self.buffer == null) { self.buffer = try self.ext2.alloc.alloc_array(u8, self.ext2.block_size); } var got: usize = 0; while (got < to.len) { // TODO: See if buffer already has the data we need!!! self.data_block_iter.set_position(self.position / self.ext2.block_size) catch |e| { print.format("ERROR: ext2.File.read: set_position: {}\n", .{@errorName(e)}); return io.FileError.Internal; }; const block = self.data_block_iter.next(self.buffer.?) catch |e| { print.format("ERROR: ext2.File.read: next: {}\n", .{@errorName(e)}); return io.FileError.Internal; }; if (block == null) break; const read_size = utils.memory_copy_truncate( to[got..], block.?[self.position % self.ext2.block_size..]); if (read_size == 0) break; self.position += read_size; got += read_size; } return got; } pub fn seek(file: *io.File, offset: isize, seek_type: io.File.SeekType) io.FileError!usize { const self = @fieldParentPtr(Self, "io_file", file); self.position = try io.File.generic_seek( self.position, self.inode.size, null, offset, seek_type); return self.position; } }; pub const Ext2 = struct { const root_inode_number = @as(usize, 2); const second_level_start = 12; initialized: bool = false, alloc: *Allocator = undefined, block_store: *io.BlockStore = undefined, offset: io.AddressType = 0, superblock: Superblock = Superblock{}, block_size: usize = 0, block_group_descriptor_table: io.AddressType = 0, max_entries_per_block: usize = 0, max_third_level_entries: usize = 0, max_fourth_level_entries: usize = 0, third_level_start: usize = 0, fourth_level_start: usize = 0, fn get_block_address(self: *const Ext2, index: usize) io.AddressType { return self.offset + @as(u64, index) * @as(u64, self.block_size); } pub fn get_block_group_descriptor(self: *Ext2, index: usize, dest: *BlockGroupDescriptor) Error!void { try self.block_store.read( self.block_group_descriptor_table + @sizeOf(BlockGroupDescriptor) * index, utils.to_bytes(dest)); } pub fn get_inode(self: *Ext2, n: usize, inode: *Inode) Error!void { var block_group: BlockGroupDescriptor = undefined; const nm1 = n - 1; try self.get_block_group_descriptor( nm1 / self.superblock.inodes_per_group, &block_group); const address = @as(u64, block_group.inode_table) * self.block_size + (nm1 % self.superblock.inodes_per_group) * self.superblock.inode_size; try self.block_store.read(self.offset + address, utils.to_bytes(inode)); // print.format("inode {}\n{}\n", n, inode.*); } pub fn get_data_block(self: *Ext2, block: []u8, index: usize) Error!void { try self.block_store.read(self.get_block_address(index), block); } pub fn get_entry_block(self: *Ext2, block: []u32, index: usize) Error!void { try self.get_data_block( @ptrCast([*]u8, block.ptr)[0..block.len * @sizeOf(u32)], index); } pub fn init(self: *Ext2, alloc: *Allocator, block_store: *io.BlockStore) Error!void { self.alloc = alloc; self.block_store = block_store; try block_store.read(self.offset + utils.Ki(1), utils.to_bytes(&self.superblock)); // print.format("{}\n", self.superblock); try self.superblock.verify(); self.block_size = self.superblock.block_size(); self.max_entries_per_block = self.block_size / @sizeOf(u32); self.block_group_descriptor_table = self.get_block_address( if (self.block_size >= utils.Ki(2)) 1 else 2); self.third_level_start = second_level_start + self.max_entries_per_block; self.max_third_level_entries = self.max_entries_per_block * self.max_entries_per_block; self.fourth_level_start = self.third_level_start + self.max_third_level_entries; self.max_fourth_level_entries = self.max_third_level_entries * self.max_entries_per_block; self.initialized = true; } fn find_in_directory( self: *Ext2, dir_inode: *Inode, name: []const u8, inode: *Inode) Error!u32 { if (!dir_inode.is_directory()) { return fs.Error.NotADirectory; } var dir_iter = try DirectoryIterator.new(self, dir_inode); defer dir_iter.done() catch |e| @panic(@typeName(@TypeOf(e))); while (try dir_iter.next()) { if (utils.memory_compare(name, dir_iter.value.name)) { inode.* = dir_iter.value.inode; return dir_iter.value.inode_number; } } return fs.Error.FileNotFound; } const Resolved = struct { inode_number: u32 = undefined, path: ?*[]u8 = null, inode: ?*Inode = null, }; fn resolve_path(self: *Ext2, path_str: []const u8, resolved: *Resolved) Error!void { // See man page path_resolution(7) for reference // TODO: Assert path with trailing slash is a directory // Get unresolved full path var path = fs.Path{.alloc = self.alloc}; try path.init(path_str); defer (path.done() catch @panic("path.done()")); if (!path.absolute) { var cwd = kernel.threading_mgr.get_cwd_heap() catch return fs.Error.Internal; try path.prepend(cwd); try kernel.alloc.free_array(cwd); } // Get root node var inode: *Inode = resolved.inode orelse try self.alloc.alloc(Inode); defer { if (resolved.inode == null) { self.alloc.free(inode) catch @panic("self.alloc.free(inode)"); } } resolved.inode_number = Ext2.root_inode_number; self.get_inode(resolved.inode_number, inode) catch return fs.Error.Internal; // Find inode and build resolved path var resolved_path = fs.Path{.alloc = self.alloc, .absolute = true}; try resolved_path.init(null); defer (resolved_path.done() catch @panic("resolved_path.done()")); var it = path.list.const_iterator(); while (it.next()) |component| { resolved.inode_number = try self.find_in_directory(inode, component, inode); if (utils.memory_compare(component, "..")) { try resolved_path.pop_component(); } else { try resolved_path.push_component(component); } } if (resolved.path) |rp| { rp.* = try resolved_path.get(); } } fn resolve_kind(self: *Ext2, path_str: []const u8, resolved: *Resolved, valid_fn: fn(inode: *const Inode) bool, invalid_error: Error) Error!void { const alloc_inode = resolved.inode == null; if (alloc_inode) { resolved.inode = try self.alloc.alloc(Inode); } defer { if (alloc_inode) { self.alloc.free(resolved.inode.?) catch @panic("self.alloc.free(inode)"); resolved.inode = null; } } try self.resolve_path(path_str, resolved); if (!valid_fn(resolved.inode.?)) { return invalid_error; } } fn resolve_directory(self: *Ext2, path_str: []const u8, resolved: *Resolved) Error!void { try self.resolve_kind(path_str, resolved, Inode.is_directory, fs.Error.NotADirectory); } pub fn resolve_directory_path(self: *Ext2, path: []const u8) Error![]const u8 { var resolved_path: []u8 = undefined; var resolved = Resolved{.path = &resolved_path}; try self.resolve_directory(path, &resolved); return resolved_path; } fn resolve_file(self: *Ext2, path_str: []const u8, resolved: *Resolved) Error!void { try self.resolve_kind(path_str, resolved, Inode.is_file, fs.Error.NotAFile); } pub fn open(self: *Ext2, path: []const u8) fs.Error!*File { if (!self.initialized) return fs.Error.InvalidFilesystem; // print.format("open({})\n", .{path}); var resolved = Resolved{}; try self.resolve_file(path, &resolved); const file = try self.alloc.alloc(File); file.init(self, resolved.inode_number) catch return fs.Error.Internal; return file; } pub fn close(self: *Ext2, file: *File) io.FileError!void { if (!self.initialized) return io.FileError.InvalidFileId; try file.close(); try self.alloc.free(file); } fn open_dir(self: *Ext2, path: []const u8) fs.Error!DirectoryIterator.Value { var inode = try self.alloc.alloc(Inode); defer self.alloc.free(inode) catch @panic("self.alloc.free(inode)"); var resolved = Resolved{.inode = inode}; try self.resolve_directory(path, &resolved); return DirectoryIterator.Value{ .inode_number = resolved.inode_number, .name = "", .inode = resolved.inode.?.*, }; } pub fn next_dir_entry(self: *Ext2, dir_entry: *georgios.DirEntry) Error!void { if (!self.initialized) return fs.Error.InvalidFilesystem; var in_dir: DirectoryIterator.Value = undefined; if (dir_entry.dir_inode) |dir_inode| { try self.get_inode(dir_inode, &in_dir.inode); // Note: Leaving in_dir.inode_number undefined } else { in_dir = try self.open_dir(dir_entry.dir); dir_entry.dir_inode = in_dir.inode_number; } var dir_iter = try DirectoryIterator.new(self, &in_dir.inode); defer dir_iter.done() catch |e| @panic(@typeName(@TypeOf(e))); var get_next = false; while (try dir_iter.next()) { // print.format("dir_item: {} {}\n", .{dir_iter.value.inode_number, dir_iter.value.name}); var return_this = false; if (get_next) { if (dir_entry.current_entry_inode) |current| { // Case of listing / where . == .. // TODO: Also maybe if there are two or more hard links to // the same file in a row. This might be have be rethought // out though because it will get in a loop if identical // hard links are interspersed in the directory listing. if (current == dir_iter.value.inode_number) { continue; } } // print.format("get_next return this\n", .{}); return_this = true; } else if (dir_entry.current_entry_inode) |current| { // print.format("current: {}\n", .{current}); if (current == dir_iter.value.inode_number) { get_next = true; continue; } } else { // print.format("return this\n", .{}); return_this = true; } if (return_this) { dir_entry.current_entry_inode = dir_iter.value.inode_number; const len = utils.memory_copy_truncate( dir_entry.current_entry_buffer[0..], dir_iter.value.name); dir_entry.current_entry = dir_entry.current_entry_buffer[0..len]; return; } } // print.format("done\n", .{}); dir_entry.current_entry.len = 0; dir_entry.current_entry_inode = null; dir_entry.done = true; } };
kernel/ext2.zig
const std = @import("std"); const tenet = @import("tenet.zig"); const Array = tenet.Array; const Tensor = tenet.Tensor; fn readIdx(comptime T: type, alc: *std.mem.Allocator, dirpath: []const u8, filename: []const u8, magic_number: i32, comptime num_dims: comptime_int) !Tensor { // check for the already extracted file, if it is missing, extract it from the provided compressed file path if (!std.mem.eql(u8, filename[filename.len-3..], ".gz")) { std.debug.panic("Filename should end in .gz: {}", .{filename}); } const extracted_filename = filename[0..filename.len - 3]; var f : std.fs.File = undefined; var dir = try std.fs.cwd().openDir(dirpath, .{}); defer dir.close(); if (dir.openFile(extracted_filename, std.fs.File.OpenFlags{ .read = true })) |ok| { f = ok; } else |err| switch (err) { error.FileNotFound => { // extract the file { var fw = try dir.createFile(extracted_filename, std.fs.File.CreateFlags{}); defer fw.close(); var fr = try dir.openFile(filename, std.fs.File.OpenFlags{ .read = true }); defer fr.close(); var s = try std.compress.gzip.gzipStream(alc, fr.reader()); defer s.deinit(); var buf : [4096]u8 = undefined; var total_nbytes : u64 = 0; while (true) { var nbytes = try s.read(&buf); if (nbytes == 0) { break; } try fw.writeAll(buf[0..nbytes]); total_nbytes += nbytes; } } // open the extracted file f = try dir.openFile(extracted_filename, std.fs.File.OpenFlags{ .read = true }); }, else => { std.debug.panic("Failed to open file {}", .{err}); }, } defer f.close(); var r = f.reader(); var num = try r.readIntBig(i32); if (num != magic_number) { return error.InvalidFile; } var shape = [_]u64{0} ** num_dims; for (shape) |_, i| { shape[i] = @intCast(u64, try r.readIntBig(i32)); } // create array, read into it var result = try Tensor.allocWithValue(T, alc, &shape, 0, tenet.tensor.NO_FLAGS); errdefer result.release(); var data_buf = result.data.getBuffer(T); var nbytes = try r.read(data_buf); if (nbytes != data_buf.len) { return error.InvalidFile; } return result; } fn loadImageData(alc: *std.mem.Allocator, dirpath: []const u8, filename: []const u8) !Tensor { std.debug.print("reading {}/{}\n", .{dirpath, filename}); return readIdx(u8, alc, dirpath, filename, 2051, 3); } fn loadLabelData(alc: *std.mem.Allocator, dirpath: []const u8, filename: []const u8) !Tensor { std.debug.print("reading {}/{}\n", .{dirpath, filename}); return readIdx(u8, alc, dirpath, filename, 2049, 1); } fn preprocessImages(alc: *std.mem.Allocator, images: Tensor) !Tensor { return try tenet.tensor.expr(alc, "f32(images) ./ 255.0", .{.images=images}); } const Model = struct { mlp: tenet.module.MLP, const Self = @This(); fn init(alc: *std.mem.Allocator, rng: *std.rand.Random, input_size: u64, hidden_size: u64, output_size: u64) !Self { return Self{.mlp=try tenet.module.MLP.init(alc, rng, input_size, hidden_size, output_size)}; } fn collectParameters(self: Self, pc: tenet.module.ParameterCollector) !void { try pc.collectParameters(self, "mlp"); } fn forward(self: *Self, alc: *std.mem.Allocator, x: Tensor) !Tensor { var logits = try self.mlp.forward(alc, x); defer logits.release(); return try tenet.funcs.logSoftmax(alc, logits, &[_]u64{1}); } fn deinit(self: *Self) void { self.mlp.deinit(); } }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var alc = &gpa.allocator; var args = try std.process.argsAlloc(alc); defer std.process.argsFree(alc, args); if (args.len != 2) { @panic("Incorrect number of args, must provide path to MNIST data"); } var dataset_path = args[1]; const batch_size : u64 = 100; const in_features : u64 = 28*28; const hidden_features : u64 = 500; const out_features : u64 = 10; const num_epochs : u64 = 5; const learning_rate : f32 = 0.001; var gen = std.rand.Xoroshiro128.init(0); var model = try Model.init(alc, &gen.random, in_features, hidden_features, out_features); defer model.deinit(); var train_images_raw = try loadImageData(alc, dataset_path, "train-images-idx3-ubyte.gz"); defer train_images_raw.release(); var train_images = try preprocessImages(alc, train_images_raw); defer train_images.release(); var train_labels = try loadLabelData(alc, dataset_path, "train-labels-idx1-ubyte.gz"); defer train_labels.release(); var test_images_raw = try loadImageData(alc, dataset_path, "t10k-images-idx3-ubyte.gz"); defer test_images_raw.release(); var test_images = try preprocessImages(alc, test_images_raw); defer test_images.release(); var test_labels = try loadLabelData(alc, dataset_path, "t10k-labels-idx1-ubyte.gz"); defer test_labels.release(); var pc = try tenet.module.ParameterCollector.init(alc); defer pc.deinit(); try model.collectParameters(pc); var opt = try tenet.optim.SGD.init(alc, pc.getParameters(), 0.9); // var opt = try tenet.optim.Adam.init(alc, pc.getParameters(), 0.9, 0.999, 1e-8); defer opt.deinit(); var epoch : u64 = 0; const num_train_batches = @divTrunc(train_images.data.getShape()[0], batch_size); const num_test_batches = @divTrunc(test_images.data.getShape()[0], batch_size); while (epoch < num_epochs) : (epoch += 1) { std.debug.print("epoch {}\n", .{epoch}); var batch_index : u64 = 0; var start = std.time.milliTimestamp(); var image_count : u64 = 0; while (batch_index < num_train_batches) : (batch_index += 1) { var input = train_images.narrowView(&[_]u64{batch_size * batch_index, 0, 0}, &[_]u64{batch_size, 28, 28}); var input_flat = input.reshapeView(&[_]u64{batch_size, in_features}); var labels = train_labels.narrowView(&[_]u64{batch_size * batch_index}, &[_]u64{batch_size}); var logprobs = try model.forward(alc, input_flat); defer logprobs.release(); var loss = try tenet.funcs.nllLoss(alc, logprobs, labels); defer loss.release(); try opt.zeroGrad(); try tenet.tensor.backwardScalarAlloc(alc, loss); try opt.step(learning_rate); var end = std.time.milliTimestamp(); image_count += batch_size; if (batch_index % 100 == 0) { var rate = @intToFloat(f32, image_count) / ((@intToFloat(f32, end - start) / 1000)); std.debug.print("train step batch_index {} num_train_batches {} loss {} rate {}\n", .{batch_index, num_train_batches, loss.data.getItem(f32), @floatToInt(u64, rate)}); } } batch_index = 0; var total : u64 = 0; var correct : u64 = 0; while (batch_index < num_test_batches) : (batch_index += 1) { var input = test_images.narrowView(&[_]u64{batch_size * batch_index, 0, 0}, &[_]u64{batch_size, 28, 28}); var input_flat = input.reshapeView(&[_]u64{batch_size, in_features}); var logprobs = try model.forward(alc, input_flat); defer logprobs.release(); var labels = test_labels.narrowView(&[_]u64{batch_size * batch_index}, &[_]u64{batch_size}); var dims = [_]u64{0}; var correct_count = try tenet.array.expr(alc, "reduce_sum(reduce_arg_max(logprobs, 1) == labels, dims)", .{.logprobs=logprobs.data, .labels=labels.data, .dims=Array.flatFromBuffer(u64, &dims)}); defer correct_count.release(); total += input.data.getShape()[0]; correct += correct_count.getItem(u64); } var accuracy : f32 = @intToFloat(f32, correct) / @intToFloat(f32, total); std.debug.print("test step correct {} total {} accuracy {}%\n", .{correct, total, @floatToInt(u64, accuracy * 100)}); } }
src/main.zig
const std = @import("std"); const encoder = @import("encoder.zig"); const decoder = @import("decoder.zig"); var globalAllocator: std.mem.Allocator = undefined; var exception: std.ArrayList([]const u8) = undefined; const scoped = std.log.scoped(.WasmBottomProgram); const buffer_size = 128 * 1024; const RestartState = enum(u32) { bottomify_failed = 1, regress_failed = 2, generic_error = 3, panic = 4, }; var current_state: RestartState = .generic_error; export fn _start() void { globalAllocator = std.heap.page_allocator; exception = std.ArrayList([]const u8).init(globalAllocator); } export fn decode() void { var temp: []u8 = &@as([1]u8, undefined); current_state = .regress_failed; var len = getTextLen(); if (len > std.math.maxInt(usize)) { scoped.err("Input Too Long", .{}); return; } var text = getText()[0..len]; var buffer: []u8 = globalAllocator.alloc(u8, encoder.BottomEncoder.max_expansion_per_byte * buffer_size) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }; defer globalAllocator.free(buffer); var bufferRegress: []u8 = globalAllocator.alloc(u8, buffer_size) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }; defer globalAllocator.free(bufferRegress); var bufferInput = std.io.fixedBufferStream(text); setResult("", 0); while (temp.len != 0) { temp = (bufferInput.reader().readUntilDelimiterOrEof(buffer, "👈"[4]) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }) orelse &@as([0]u8, undefined); if (temp.len > 0) { var outbuffer: []u8 = decoder.BottomDecoder.decode(temp, bufferRegress) catch |err| { scoped.err("Failed with err: {any}", .{err}); return; }; appendResult(outbuffer.ptr, @truncate(u32, outbuffer.len)); } } hideException(); } export fn encode() void { current_state = .bottomify_failed; var len = getTextLen(); if (len > std.math.maxInt(usize)) { var err = error.input_too_long; var message = std.fmt.allocPrint(globalAllocator, "Failed with err: {any}", .{err}) catch |err2| { scoped.err("Failed with err: {any}", .{err}); scoped.err("Failed with err: {any}", .{err2}); restart(@enumToInt(current_state)); return; }; appendException(message.ptr, @truncate(u32, message.len)); return; } var text = getText()[0..len]; var buffer: []u8 = globalAllocator.alloc(u8, buffer_size) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }; defer globalAllocator.free(buffer); var bufferBottom: []u8 = globalAllocator.alloc(u8, encoder.BottomEncoder.max_expansion_per_byte * buffer_size) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }; defer globalAllocator.free(bufferBottom); setResult("", 0); var bufferInput = std.io.fixedBufferStream(text); var size: usize = 1; while (size != 0) { size = bufferInput.read(buffer) catch |err| { scoped.err("Failed with err: {any}", .{err}); restart(@enumToInt(current_state)); return; }; if (size > 0) { var outbuffer: []u8 = encoder.BottomEncoder.encode(buffer[0..size], bufferBottom); appendResult(outbuffer.ptr, @truncate(u32, outbuffer.len)); } } hideException(); } extern fn setResult(ptr: [*]const u8, len: u32) void; extern fn appendResult(ptr: [*]const u8, len: u32) void; extern fn appendException(ptr: [*]const u8, len: u32) void; extern fn hideException() void; extern fn getText() [*]const u8; extern fn getTextLen() u32; extern fn restart(status: u32) void; pub extern fn logus(ptr: [*]const u8, len: u32) void; pub fn log( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { current_state = .generic_error; var message = std.fmt.allocPrint(globalAllocator, format, args) catch |err| { logus("failed on error:", "failed on error:".len); logus(@errorName(err).ptr, @errorName(err).len); restart(@enumToInt(current_state)); return; }; var to_print = std.fmt.allocPrint(globalAllocator, "{s}-{s}: {s}", .{ @tagName(scope), message_level.asText(), message }) catch |err| { logus("failed on error:", "failed on error:".len); logus(@errorName(err).ptr, @errorName(err).len); restart(@enumToInt(current_state)); return; }; appendException(to_print.ptr, @truncate(u32, to_print.len)); logus(to_print.ptr, @truncate(u32, to_print.len)); globalAllocator.free(message); globalAllocator.free(to_print); } pub fn panic(msg: []const u8, stackTrace: ?*std.builtin.StackTrace) noreturn { current_state = .panic; restart(@enumToInt(current_state)); var stack_trace_print: ?[]u8 = null; if (stackTrace != null) { stack_trace_print = std.fmt.allocPrint(globalAllocator, "{s}", .{stackTrace}) catch |err| { logus("failed on error:", "failed on error:".len); logus(@errorName(err).ptr, @errorName(err).len); restart(@enumToInt(current_state)); trap(); }; } var message = std.fmt.allocPrint(globalAllocator, "{s}", .{msg}) catch |err| { logus("failed on error:", "failed on error:".len); logus(@errorName(err).ptr, @errorName(err).len); restart(@enumToInt(current_state)); trap(); }; var to_print = std.fmt.allocPrint(globalAllocator, "{s}", .{message}) catch |err| { logus("failed on error:", "failed on error:".len); logus(@errorName(err).ptr, @errorName(err).len); restart(@enumToInt(current_state)); trap(); }; logus(to_print.ptr, @truncate(u32, to_print.len)); globalAllocator.free(message); globalAllocator.free(to_print); if (stack_trace_print != null) { globalAllocator.free(stack_trace_print.?); } trap(); } inline fn trap() noreturn { while (true) { @breakpoint(); } }
src/wasm-example.zig
const std = @import("std"); const pipe = struct { usingnamespace @import("pipes"); usingnamespace @import("filters"); }; // two context structs (must be pub for cross file access) pub const x = struct { pub var xxx: u16 = 5; pub var aaa: u16 = 50; pub var ar = [_]u64{ 11, 22, 33, 44 }; pub var sss: []u64 = &ar; }; pub var testme: u64 = 38; pub var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub var arena2 = std.heap.ArenaAllocator.init(std.heap.page_allocator); pub fn main() !void { defer arena.deinit(); defer arena2.deinit(); const allocator = &arena.allocator; // pipe allocator const allocator2= &arena2.allocator; // misc storage allocator // stage instances are always 'owned' by a pipe instance, but the PipeType and instance comptime var Make = pipe.Z{}; // are defined after the Stages. This structure is used to save PipeTypes as they are // created and is used by Stage to reconstruct the PipeType and instance pointer. // create a Stage type with U64, []u64 and ArrayList(u64) as a TypeUnion const F = pipe.Filters(Make.Stage(.{ u64, []u64, std.ArrayList(u64), []const u8 }), u64); const S = pipe.Filters(F.S, []const u8); // create a varient Stage type with ArrayList(u64) as its primary type, sharing the TypeUnion defined by F const A = pipe.Filters(F.S, std.ArrayList(u64)); const y = struct { pub var xxx: u16 = 17; // must be pub pub var aaa: u16 = 80; pub var alist = std.ArrayList(u64).init(allocator2); pub var blist = std.ArrayList(u64).init(allocator2); pub var prime = [_]u64{1, 2, 3, 5, 7, 11, 13}; pub var fib = [_]u64{1, 1, 2, 3, 5, 8, 13, 22, 35}; pub var init: []u64 = prime[1..]; pub var list: []F.S.TU = undefined; }; try y.alist.appendSlice(&y.prime); y.list = F.S.TU.list(allocator2, .{u64, []u64, @TypeOf(y.alist), []const u8}, .{51, y.fib[0..], y.alist, "test"}); try Make.run(@This(), .{ .{ F.gen, .{35} }, .{ .not3, F.exactdiv, .{3} }, .{ .by3not5, F.exactdiv, .{5} }, .{ S.replace, .{ @as([]const u8, "\'FizzBuzz")} }, // Divisible by 3 and 5 .{ .all, F.faninany }, .{ F.console, ._ }, .{ .by3not5 }, .{ S.replace, .{ @as([]const u8, "\'Fizz")} }, // Divisible by 3 but not 5 .{ .all, ._ }, .{ .not3 }, .{ .not3not5, F.exactdiv, .{5} }, // not divisible by 3, check 5 .{ S.replace, .{ @as([]const u8, "\'Buzz")} }, .{ .all, ._ }, .{ .not3not5 }, // route numbers back to faninany .{ .all, ._ }, }); std.debug.print("\n", .{}); try Make.run(y, .{ .{ F.typeUnion, .{ "list" } }, // put the elements of the array of TypeUnions onto the pipe .{ .a, F.collateTypes }, // split by types in typeunion (u64 is stream 0) .{ .b, F.faninany }, .{ F.console, ._ }, // display the number .{ .a }, .{ F.slice, .{null} }, // read the slice and output elements .{ .b, ._ }, .{ .a }, // trinary output of collateTypes (std.ArrayList(u64)) .{ F.arrayList, .{null, .pipe} }, // elements of the arraylist are put onto the pipe .{ .b, ._ }, // and sent to secondary input of faninany .{ .a }, // just pass a string to faninany // .{ F.copy}, .{ .b, ._ }, }); std.debug.print("\n", .{}); // a sample pipe using uP stages, note that ._ indicates stage or connector's output is not connected const aPipe = .{ .{ F.gen, .{"aaa"} }, // generate a steam of numbers and pass each to the next stage .{ .a, F.exactdiv, .{"xxx"} }, // exact goes to fanin, otherwise to exactdiv(7) via .a .{ .b, F.faninany }, // take input from any stream and pass it to console .{ F.console, ._ }, // output to console .{.a }, .{ .c, F.exactdiv, .{7} }, // exact goes via label .b to fanin, otherwise to exactdiv(11) via .c .{ .b, ._ }, .{.c }, .{ F.exactdiv, .{11} }, // exact goes via label b to fanint, otherwise ignore number .{ .b, ._ }, }; // create a new PipeType and create an instance using allocator var myPipe = Make.Mint(aPipe).init(allocator); // run the pipe with the above args, the values from x are assigned to the pipe stages in .run(x) // x.aaa=50, x.xxx=5 try myPipe.run(x); std.debug.print("\n", .{}); // play with vars in pipe context structures x.xxx += 1; x.aaa += 50; // call using helper function // x.aaa=110, x.xxx=6 try Make.run(x,aPipe); std.debug.print("\n", .{}); // and using a different context structure // y.aaa=80, y.xxx=17 try myPipe.run(y); std.debug.print("\n", .{}); const pSlicew = .{ .{ F.gen, .{"sss.len"} }, .{ F.slice, .{"sss"} }, // update slice with generated values .{ F.console, ._ } }; var sPipew = Make.Mint(pSlicew).init(allocator); // update the slice try sPipew.run(x); std.debug.print("\n", .{}); const pSlicer = .{ .{ F.slice, .{"sss"} }, // extract elements of slice sss and pass to console .{ F.console, ._ }, }; var sPiper = Make.Mint(pSlicer).init(allocator); try sPiper.run(x); std.debug.print("\n", .{}); _ = testme; const pNoContect = .{ .{ F.gen, .{"testme"} }, .{ F.console, ._ }, // update slice with generated values }; try Make.Mint(pNoContect).init(allocator).run(@This()); std.debug.print("\n", .{}); //try y.alist.appendSlice(&y.prime); const pReadAL = .{ .{ F.arrayList, .{"alist", .read} }, .{ F.slice, .{"init"} }, // output elements of alist into pipe .{ F.arrayList, .{"blist", .write} }, // assemble blist from pipe .{ F.arrayList, .{null, .pipe} }, // read copy of blist from pipe and output elements .{ F.console, ._ }, }; try Make.run(y, pReadAL); std.debug.print("\n", .{}); try Make.run(y, .{ .{ A.variable, .{"blist"} }, // put arraylist blist into pipe .{ F.arrayList, .{null, .pipe} }, // output elements of blist .{ F.console, ._ }, }); std.debug.print("\n", .{}); try Make.run(y, .{ .{ F.typeUnion, .{ "list" } }, // put the elements of the array of TypeUnions onto the pipe .{ .a, F.collateTypes }, // split by types in typeunion (u64 is stream 0) .{ .b, F.faninany }, .{ F.console, ._ }, // display the number .{ .a, ._}, // seconday output of collateTypes is ignored ([]u64) .{ .a }, // trinary output of collateTypes (std.ArrayList(u64)) .{ F.arrayList, .{null, .pipe} }, // elements of the arraylist are put onto the pipe .{ .b, ._}, // and sent to secondary input of faninany }); std.debug.print("\n", .{}); }
main.zig
const std = @import("std"); const testing = std.testing; const mem = std.mem; const TapeType = dom.TapeType; const simdjzon = @import("simdjzon.zig"); const dom = simdjzon.dom; const ondemand = simdjzon.ondemand; const cmn = @import("common.zig"); const allr = testing.allocator; test "tape build" { const input = @embedFile("../test/test.json"); const expecteds = [_]u64{ TapeType.ROOT.encode_value(37), // pointing to 37 (rightafter last node) :0 TapeType.START_OBJECT.encode_value(37 | (8 << 32)), // pointing to 37, length 8 :1 TapeType.STRING.encode_value(6), // "Width" :2 TapeType.INT64.as_u64(), 800, // :3 TapeType.STRING.encode_value(6), // "Height" :5 TapeType.INT64.as_u64(), 600, // :6 TapeType.STRING.encode_value(5), // "Title" :8 TapeType.STRING.encode_value(4), // "View from my room" :9 TapeType.STRING.encode_value(3), // "Url" :10 TapeType.STRING.encode_value(21), // "http://ex.com/img.png" :11 TapeType.STRING.encode_value(7), // "Private" :12 TapeType.FALSE.as_u64(), // :13 TapeType.STRING.encode_value(9), // "Thumbnail" :14 TapeType.START_OBJECT.encode_value(25 | (3 << 32)), // 25, length 3 :15 TapeType.STRING.encode_value(3), // "Url" :16 TapeType.STRING.encode_value(21), // "http://ex.com/th.png". :17 TapeType.STRING.encode_value(6), // "Height" :18 TapeType.INT64.as_u64(), 125, // :19 TapeType.STRING.encode_value(6), // "Width" :21 TapeType.INT64.as_u64(), 100, // :22 TapeType.END_OBJECT.encode_value(15), // pointing to 15 :24 TapeType.STRING.encode_value(5), // "array" :25 TapeType.START_ARRAY.encode_value(34 | (3 << 32)), // pointing to 34 :26 TapeType.INT64.as_u64(), 116, // :27 TapeType.INT64.as_u64(), 943, // :29 TapeType.INT64.as_u64(), 234, // :31 TapeType.END_ARRAY.encode_value(26), // pointing to 26 :33 TapeType.STRING.encode_value(5), // "Owner" :34 TapeType.NULL.as_u64(), // :35 TapeType.END_OBJECT.encode_value(1), // pointing to 1 :36 TapeType.ROOT.encode_value(0), // pointing to 0 :37 }; var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); defer parser.deinit(); try parser.parse(); // verify doc.string_buf var p = @ptrCast([*:0]u8, parser.doc.string_buf.ptr); var j: u8 = 0; const expected_strings: []const []const u8 = &.{ "Width", "Height", "Title", "View from my room", "Url", "http://ex.com/img.png", "Private", "Thumbnail", "Url", "http://ex.com/th.png", "Height", "Width", "array", "Owner", }; while (@ptrToInt(p) < @ptrToInt(parser.doc.string_buf.ptr + parser.doc.string_buf.len)) : (j += 1) { const len = mem.bytesAsValue(u32, p[0..4]).*; p += 4; const str = std.mem.span(p); cmn.println("{}:{}-'{s}' '{s}'", .{ j, len, str, p[0..10] }); try testing.expectEqual(@intCast(u32, str.len), len); try testing.expectEqualStrings(expected_strings[j], str); p += str.len + 1; } var i: usize = 0; while (i < expecteds.len) : (i += 1) { const expected = expecteds[i]; const expected_type = TapeType.from_u64(expected); const expected_val = TapeType.extract_value(expected); // cmn.println("{} : expected {s}:{}-{x}", .{ i, @tagName(expected_type), expected_val, expected }); const tape_item = parser.doc.tape.items[i]; const tape_type = TapeType.from_u64(tape_item); const tape_val = TapeType.extract_value(tape_item); // cmn.println("{} : actual {s}:{}-{x}", .{ i, @tagName(tape_type), tape_val, tape_item }); // cmn.println("actual {}:{}", .{expected_type, expected_val}); // cmn.println("expected 0x{x} tape_item 0x{x}", .{ expected, tape_item }); try testing.expectEqual(expected_type, tape_type); // cmn.println("expected_val {} tape_val {}", .{ expected_val, tape_val }); if (expected_type != .STRING) try testing.expectEqual(expected_val, tape_val); if (expected_type == .INT64) { i += 1; cmn.println("{s} {}", .{ @tagName(expected_type), parser.doc.tape.items[i] }); try testing.expectEqual(expecteds[i], parser.doc.tape.items[i]); } } } test "float" { { var parser = try dom.Parser.initFixedBuffer(allr, "123.456", .{}); defer parser.deinit(); try parser.parse(); try testing.expectEqual( TapeType.DOUBLE.encode_value(0), parser.doc.tape.items[1], ); try testing.expectApproxEqAbs( @as(f64, 123.456), @bitCast(f64, parser.doc.tape.items[2]), 0.000000001, ); const ele = parser.element(); const d = try ele.get_double(); try testing.expectApproxEqAbs(@as(f64, 123.456), d, 0.000000001); } { var parser = try dom.Parser.initFixedBuffer(allr, "[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]", .{}); defer parser.deinit(); try parser.parse(); // for (parser.doc.tape.items) |tape_item, i| // cmn.println("{}:{s} {}", .{ i, @tagName(TapeType.from_u64(tape_item)), TapeType.extract_value(tape_item) }); try testing.expectEqual( TapeType.DOUBLE.encode_value(0), parser.doc.tape.items[2], ); try testing.expectApproxEqAbs( @as(f64, 0.000000000000000000000000000000000000000000000000000000000000000000000000000001), @bitCast(f64, parser.doc.tape.items[3]), std.math.f64_epsilon, ); } } test "search tape" { var parser = try dom.Parser.initFile(allr, "test/test.json", .{}); defer parser.deinit(); try parser.parse(); const ele = parser.element(); const thumb = ele.at_key("Thumbnail") orelse return testing.expect(false); try testing.expectEqual(thumb.tape.scope_count(), 3); try testing.expect(thumb.is(.OBJECT)); try testing.expectEqual(thumb.tape.idx, 15); const url = thumb.at_key("Url") orelse return testing.expect(false); try testing.expectEqual(url.tape.idx, 17); try testing.expectEqualStrings("http://ex.com/th.png", try url.get_string()); const ht = thumb.at_key("Height") orelse return testing.expect(false); try testing.expectEqual(@as(i64, 125), try ht.get_int64()); const priv = ele.at_key("Private") orelse return testing.expect(false); try testing.expectEqual(false, try priv.get_bool()); const owner = ele.at_key("Owner") orelse return testing.expect(false); try testing.expectEqual(true, owner.is(.NULL)); const array = ele.at_key("array") orelse return testing.expect(false); try testing.expectEqual(array.tape.idx, 26); try testing.expectEqual(true, array.is(.ARRAY)); const array1 = array.at(0) orelse return testing.expect(false); try testing.expectEqual(true, array1.is(.INT64)); try testing.expectEqual(@as(i64, 116), try array1.get_int64()); } test "json pointer" { const input = \\{"a": {"b": [1,2,3], "c": 3.1415, "d": true, "e": "e-string", "f": null}} ; var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); defer parser.deinit(); try parser.parse(); const b0 = try parser.element().at_pointer("/a/b/0"); try testing.expectEqual(@as(i64, 1), try b0.get_int64()); const b2 = try parser.element().at_pointer("/a/b/2"); try testing.expectEqual(@as(i64, 3), try b2.get_int64()); try testing.expectError(error.INVALID_JSON_POINTER, parser.element().at_pointer("/a/b/3")); try testing.expectError(error.INVALID_JSON_POINTER, parser.element().at_pointer("/c/b")); var i: i64 = undefined; try (try parser.element().at_pointer("/a/b/1")).get(&i); try testing.expectEqual(@as(i64, 2), i); var f: f32 = undefined; try (try parser.element().at_pointer("/a/c")).get(&f); try testing.expectApproxEqAbs(@as(f32, 3.1415), f, 0.00000001); var b = false; try (try parser.element().at_pointer("/a/d")).get(&b); try testing.expectEqual(true, b); var u: u64 = undefined; try (try parser.element().at_pointer("/a/b/2")).get(&u); try testing.expectEqual(@as(u64, 3), u); { var s = [1]u8{'x'} ** 8; try (try parser.element().at_pointer("/a/e")).get(&s); try testing.expectEqualStrings("e-string", &s); } const expected: [8]u8 = "e-stxxxx".*; { var s = [1]u8{'x'} ** 8; try (try parser.element().at_pointer("/a/e")).get(s[0..4]); try testing.expectEqualStrings(&expected, &s); } { // this contrived example shows you can read string data into slice types other than u8 var s = [1]u16{mem.readIntLittle(u16, "xx")} ** 4; try (try parser.element().at_pointer("/a/e")).get(s[0..2]); const expected_u16s = @bitCast([4]u16, expected); try testing.expectEqualSlices(u16, &expected_u16s, &s); } var opt: ?u8 = undefined; try (try parser.element().at_pointer("/a/f")).get(&opt); try testing.expectEqual(@as(?u8, null), opt); try (try parser.element().at_pointer("/a/b/2")).get(&opt); try testing.expectEqual(@as(?u8, 3), opt); } test "get with slice/array" { const input = \\[1,2,3,4] ; var s: [4]u8 = undefined; var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); defer parser.deinit(); try parser.parse(); try parser.element().get(&s); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, &s); } // ------------ // README tests // ------------ // const dom = @import("dom.zig"); test "get with struct" { const S = struct { a: u8, b: []const u8, c: struct { d: u8 } }; const input = \\{"a": 42, "b": "b-string", "c": {"d": 126}} ; var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); defer parser.deinit(); try parser.parse(); var s: S = undefined; try parser.element().get(&s); try testing.expectEqual(@as(u8, 42), s.a); try testing.expectEqualStrings("b-string", s.b); try testing.expectEqual(@as(u8, 126), s.c.d); } test "at_pointer" { const input = \\{"a": {"b": [1,2,3]}} ; var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); defer parser.deinit(); try parser.parse(); const b0 = try parser.element().at_pointer("/a/b/0"); try testing.expectEqual(@as(i64, 1), try b0.get_int64()); } // const ondemand = @import("ondemand.zig"); test "ondemand get with struct" { const S = struct { a: struct { b: []const u8 } }; const input = \\{"a": {"b": "b-string"}} ; var src = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(input) }; var parser = try ondemand.Parser.init(&src, allr, "<fba>", .{}); defer parser.deinit(); var doc = try parser.iterate(); var s: S = undefined; try doc.get(&s, .{ .allocator = allr }); defer allr.free(s.a.b); try testing.expectEqualStrings("b-string", s.a.b); } test "ondemand at_pointer" { const input = \\{"a": {"b": [1,2,3]}} ; var src = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(input) }; var parser = try ondemand.Parser.init(&src, allr, "<fba>", .{}); defer parser.deinit(); var doc = try parser.iterate(); var b0 = try doc.at_pointer("/a/b/0"); try testing.expectEqual(@as(u8, 1), try b0.get_int(u8)); } // ------------ // end README tests // ------------ const E = cmn.Error || error{ TestExpectedEqual, TestUnexpectedResult, TestExpectedApproxEqAbs, TestUnexpectedError, TestExpectedError }; fn test_ondemand_doc(input: []const u8, expected: fn (doc: *ondemand.Document) E!void) !void { // std.debug.print("\n0123456789012345678901234567890123456789\n{s}\n", .{input}); var src = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(input) }; var parser = try ondemand.Parser.init(&src, allr, "<fba>", .{}); defer parser.deinit(); var doc = try parser.iterate(); try expected(&doc); } test "ondemand struct find_field" { try test_ondemand_doc( \\ {"x": 1, "y": 2, "z": {"a": 33}} , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectEqual(@as(u64, 2), try (try doc.find_field("y")).get_int(u64)); try testing.expectEqual(@as(u64, 1), try (try doc.find_field("x")).get_int(u64)); try testing.expectEqual(@as(u8, 33), try (try (try doc.find_field("z")).find_field("a")).get_int(u8)); } }.func); } test "ondemand struct iteration" { try test_ondemand_doc( \\ {"x": 1, "y": 2} , struct { fn func(doc: *ondemand.Document) E!void { var obj = try doc.get_object(); var objit = obj.iterator(); var buf: [10]u8 = undefined; { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("x", buf[0..1]); try testing.expectEqual(@as(u64, 1), try f.value.get_int(u64)); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("y", buf[0..1]); try testing.expectEqual(@as(u64, 2), try f.value.get_int(u64)); } try testing.expect((try objit.next(&buf)) == null); } }.func); } test "ondemand struct iteration types" { try test_ondemand_doc( \\ {"str": "strval", "f": 1.23, "t": true, "not": false, "n": null, "neg": -42 } , struct { fn func(doc: *ondemand.Document) E!void { var obj = try doc.get_object(); var objit = obj.iterator(); var buf: [10]u8 = undefined; { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("str", buf[0..3]); try testing.expectEqualStrings("strval", try f.value.get_string([]u8, &buf)); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("f", buf[0..1]); try testing.expectApproxEqAbs(@as(f64, 1.23), try f.value.get_double(), std.math.f64_epsilon); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("t", buf[0..1]); try testing.expectEqual(true, try f.value.get_bool()); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("not", buf[0..3]); try testing.expectEqual(false, try f.value.get_bool()); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("n", buf[0..1]); try testing.expectEqual(true, try f.value.is_null()); } { var f = (try objit.next(&buf)) orelse return testing.expect(false); try testing.expectEqualStrings("neg", buf[0..3]); try testing.expectEqual(@as(i8, -42), try f.value.get_int(i8)); } try testing.expect((try objit.next(&buf)) == null); } }.func); } test "ondemand array iteration" { try test_ondemand_doc( \\ [1,2] , struct { fn func(doc: *ondemand.Document) E!void { var arr = try doc.get_array(); var arrit = arr.iterator(); { var e = (try arrit.next()) orelse return testing.expect(false); try testing.expectEqual(@as(u64, 1), try e.get_int(u64)); } { var e = (try arrit.next()) orelse return testing.expect(false); try testing.expectEqual(@as(u64, 2), try e.get_int(u64)); } try testing.expect((try arrit.next()) == null); } }.func); } test "ondemand array iteration nested" { try test_ondemand_doc( \\[ \\ { "xs": [ 1.0, 2.0, 3.0, 4.0 ] }, \\ { "xs": [ 1.0, 2.0, 3.0, 4.0 ] }, \\ { "xs": [ 1.0, 2.0, 3.0, 4.0 ] } \\] , struct { fn func(doc: *ondemand.Document) E!void { var arr = try doc.get_array(); var arrit = arr.iterator(); while (try arrit.next()) |*e| { var obj = try e.get_object(); var xs = try obj.find_field("xs"); var arr2 = try xs.get_array(); var it = arr2.iterator(); var i: u8 = 0; while (try it.next()) |*e2| { try testing.expectApproxEqAbs( @intToFloat(f64, i + 1), try e2.get_double(), std.math.f64_epsilon, ); i += 1; } try testing.expectEqual(@as(u8, 4), i); } try testing.expect((try arrit.next()) == null); } }.func); } test "ondemand root types" { try test_ondemand_doc( \\1 , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectEqual(@as(u8, 1), try doc.get_int(u8)); } }.func); try test_ondemand_doc( \\1.0 , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectApproxEqAbs(@as(f64, 1.0), try doc.get_double(), std.math.f64_epsilon); } }.func); try test_ondemand_doc( \\"string" , struct { fn func(doc: *ondemand.Document) E!void { var buf: [6]u8 = undefined; try testing.expectEqualStrings("string", try doc.get_string([]u8, &buf)); } }.func); try test_ondemand_doc( \\true , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectEqual(true, try doc.get_bool()); } }.func); try test_ondemand_doc( \\false , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectEqual(false, try doc.get_bool()); } }.func); try test_ondemand_doc( \\null , struct { fn func(doc: *ondemand.Document) E!void { try testing.expect(try doc.is_null()); } }.func); } test "ondemand atpointer" { try test_ondemand_doc( \\{"a": {"b": 1, "c": [1,2]}} , struct { fn func(doc: *ondemand.Document) E!void { try testing.expectEqual(@as(u8, 1), try (try doc.at_pointer("/a/b")).get_int(u8)); try testing.expectEqual(@as(u8, 2), try (try doc.at_pointer("/a/c/1")).get_int(u8)); try testing.expectError(error.NO_SUCH_FIELD, doc.at_pointer("/b")); } }.func); } test "ondemand at, array at_pointer" { try test_ondemand_doc( \\[1,2] , struct { fn func(doc: *ondemand.Document) E!void { var arr = try doc.get_array(); try testing.expectEqual(@as(u8, 1), try (try arr.at(0)).?.get_int(u8)); try testing.expectEqual(@as(u8, 2), try (try arr.at(1)).?.get_int(u8)); try testing.expectEqual(@as(?ondemand.Value, null), try arr.at(2)); try testing.expectEqual(@as(u8, 1), try (try arr.at_pointer("/0")).get_int(u8)); try testing.expectEqual(@as(u8, 2), try (try arr.at_pointer("/1")).get_int(u8)); try testing.expectError(error.INVALID_JSON_POINTER, arr.at_pointer("/2")); } }.func); } test "ondemand get struct" { try test_ondemand_doc( \\{"a": 1, "b": 2, "c": {"d": 3}} , struct { fn func(doc: *ondemand.Document) E!void { const S = struct { a: u8, b: u8, c: struct { d: u8 } }; var s: S = undefined; try doc.get(&s, .{}); try testing.expectEqual(@as(u8, 1), s.a); try testing.expectEqual(@as(u8, 2), s.b); try testing.expectEqual(@as(u8, 3), s.c.d); } }.func); try test_ondemand_doc( \\{"a": {"b": [1,2,3], "c": 3.1415, "d": true, "e": "e-string", "f": null, "g": [4,5,6]}} , struct { fn func(doc: *ondemand.Document) E!void { { const S = struct { a: struct { b: [3]u8, c: f32, d: bool, f: ?u8 } }; var s: S = undefined; try doc.get(&s, .{}); try testing.expectApproxEqAbs(@as(f32, 3.1416), s.a.c, std.math.f16_epsilon); try testing.expectEqual(true, s.a.d); try testing.expectEqual(@as(?u8, null), s.a.f); try testing.expectEqualSlices(u8, &.{ 1, 2, 3 }, &s.a.b); } { // parse strings or arrays in slices using an allocator const S = struct { a: struct { g: []u8, e: []const u8 } }; var s: S = undefined; defer allr.free(s.a.g); defer allr.free(s.a.e); try doc.get(&s, .{ .allocator = allr }); try testing.expectEqualSlices(u8, &.{ 4, 5, 6 }, s.a.g); try testing.expectEqualStrings("e-string", s.a.e); } } }.func); } test "get_string_alloc" { try test_ondemand_doc( \\"asdf" , struct { fn func(doc: *ondemand.Document) E!void { { const str = try doc.get_string_alloc([]u8, allr); defer allr.free(str); try testing.expectEqualStrings("asdf", str); } { const str = try doc.get_string_alloc([]const u8, allr); defer allr.free(str); try testing.expectEqualStrings("asdf", str); } } }.func); const s = "asdf"; const reps = ondemand.READ_BUF_CAP / s.len + 100; const overlong_str = "\"" ++ s ** reps ++ "\""; try test_ondemand_doc(overlong_str, struct { fn func(doc: *ondemand.Document) E!void { const str = doc.get_string_alloc([]const u8, allr); try testing.expectError(error.CAPACITY, str); } }.func); } test "ondemand array iteration nested" { try test_ondemand_doc( \\{"a": [{}, {}] } , struct { fn func(doc: *ondemand.Document) E!void { var buf: [0x10]u8 = undefined; const obj1 = try doc.get_object(); var field1 = (try obj1.iterator().next(&buf)) orelse return testing.expect(false); var arr1 = try field1.value.get_array(); var it = arr1.iterator(); var i: u8 = 0; while (try it.next()) |_| : (i += 1) {} try testing.expectEqual(@as(u8, 2), i); } }.func); } test "ondemand edge cases" { // This is a sneaky case where TokenIterator.buf could have 'null' when read only moves ahead by 1 try test_ondemand_doc( \\[nul] , struct { fn func(doc: *ondemand.Document) E!void { const arr = try doc.get_array(); var it = arr.iterator(); var val = (try it.next()) orelse return testing.expect(false); try testing.expectEqual(false, try val.is_null()); } }.func); } test "ondemand raw_json_token" { try test_ondemand_doc( \\12321323213213213213213213213211223 , struct { fn func(doc: *ondemand.Document) E!void { var tok = try doc.raw_json_token(); try testing.expectEqualStrings("12321323213213213213213213213211223", tok); } }.func); try test_ondemand_doc( \\{"value":12321323213213213213213213213211223} , struct { fn func(doc: *ondemand.Document) E!void { var obj = try doc.get_object(); var val = try obj.find_field("value"); const tok = try val.raw_json_token(); try testing.expectEqualStrings("12321323213213213213213213213211223", tok); } }.func); } test "twitter" { const builtin = @import("builtin"); const output_filename: []const u8 = if (builtin.os.tag == .windows) "test\\twitter.json" else "test/twitter.json"; const json_url = "https://raw.githubusercontent.com/simdjson/simdjson/master/jsonexamples/twitter.json"; const argv: []const []const u8 = &.{ "curl", "-fsS", "-o", output_filename, json_url }; const res = try std.ChildProcess.exec(.{ .allocator = allr, .argv = argv, }); if (res.stderr.len > 0) { allr.free(res.stderr); if (res.term == .Exited) if (res.term.Exited != 0) return error.UnexpectedExitCode; } if (res.stdout.len > 0) { allr.free(res.stdout); if (res.term == .Exited) if (res.term.Exited != 0) return error.UnexpectedExitCode; } { var parser = try dom.Parser.initFile(allr, output_filename, .{}); try parser.parse(); defer parser.deinit(); var tweets = parser.element(); const count = try (try tweets.at_pointer("/search_metadata/count")).get_uint64(); try testing.expectEqual(@as(u64, 100), count); } { var file = try std.fs.cwd().openFile(output_filename, .{ .read = true }); defer file.close(); var src = std.io.StreamSource{ .file = file }; var parser = try ondemand.Parser.init(&src, allr, output_filename, .{}); defer parser.deinit(); var tweets = try parser.iterate(); const count = try (try tweets.at_pointer("/search_metadata/count")).get_int(u8); try testing.expectEqual(@as(u8, 100), count); } }
src/tests.zig
const std = @import("std"); const deps = @import("./deps.zig"); 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_tests = b.addTest("src/main.zig"); exe_tests.setTarget(target); exe_tests.setBuildMode(mode); deps.addAllTo(exe_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); const manage_exe = b.addExecutable("awtfdb-manage", "src/main.zig"); manage_exe.setTarget(target); manage_exe.setBuildMode(mode); manage_exe.install(); deps.addAllTo(manage_exe); const watcher_exe = b.addExecutable("awtfdb-watcher", "src/rename_watcher_main.zig"); watcher_exe.setTarget(target); watcher_exe.setBuildMode(mode); watcher_exe.install(); deps.addAllTo(watcher_exe); const include_exe = b.addExecutable("ainclude", "src/include_main.zig"); include_exe.setTarget(target); include_exe.setBuildMode(mode); include_exe.install(); deps.addAllTo(include_exe); const find_exe = b.addExecutable("afind", "src/find_main.zig"); find_exe.setTarget(target); find_exe.setBuildMode(mode); find_exe.install(); deps.addAllTo(find_exe); const ls_exe = b.addExecutable("als", "src/ls_main.zig"); ls_exe.setTarget(target); ls_exe.setBuildMode(mode); ls_exe.install(); deps.addAllTo(ls_exe); const tags_exe = b.addExecutable("atags", "src/tags_main.zig"); tags_exe.setTarget(target); tags_exe.setBuildMode(mode); tags_exe.install(); deps.addAllTo(tags_exe); const rm_exe = b.addExecutable("arm", "src/rm_main.zig"); rm_exe.setTarget(target); rm_exe.setBuildMode(mode); rm_exe.install(); deps.addAllTo(rm_exe); const hydrus_api_exe = b.addExecutable("ahydrus-api", "src/hydrus_api_main.zig"); hydrus_api_exe.setTarget(target); hydrus_api_exe.setBuildMode(mode); hydrus_api_exe.install(); hydrus_api_exe.addIncludeDir("/usr/include"); hydrus_api_exe.addLibPath("/usr/lib"); deps.addAllTo(hydrus_api_exe); const janitor_exe = b.addExecutable("awtfdb-janitor", "src/janitor_main.zig"); janitor_exe.setTarget(target); janitor_exe.setBuildMode(mode); janitor_exe.install(); deps.addAllTo(janitor_exe); }
build.zig
const std = @import("std"); const debug = std.debug; const testing = std.testing; const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const StringHashMap = std.StringHashMap; fn trimStart(slice: []const u8, ch: u8) []const u8 { var i: usize = 0; for (slice) |b| { if (b != '-') break; i += 1; } return slice[i..]; } fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool { if (maybe_set) |set| { for (set) |possible| { if (mem.eql(u8, arg, possible)) { return true; } } return false; } else { return true; } } // Modifies the current argument index during iteration fn readFlagArguments(allocator: *Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: *usize) !FlagArg { switch (required) { 0 => return FlagArg{ .None = undefined }, // TODO: Required to force non-tag but value? 1 => { if (index.* + 1 >= args.len) { return error.MissingFlagArguments; } index.* += 1; const arg = args[index.*]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } return FlagArg{ .Single = arg }; }, else => |needed| { var extra = ArrayList([]const u8).init(allocator); errdefer extra.deinit(); var j: usize = 0; while (j < needed) : (j += 1) { if (index.* + 1 >= args.len) { return error.MissingFlagArguments; } index.* += 1; const arg = args[index.*]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } try extra.append(arg); } return FlagArg{ .Many = extra }; }, } } const HashMapFlags = StringHashMap(FlagArg); // A store for querying found flags and positional arguments. pub const Args = struct { flags: HashMapFlags, positionals: ArrayList([]const u8), pub fn parse(allocator: *Allocator, comptime spec: []const Flag, args: []const []const u8) !Args { var parsed = Args{ .flags = HashMapFlags.init(allocator), .positionals = ArrayList([]const u8).init(allocator), }; var i: usize = 0; next: while (i < args.len) : (i += 1) { const arg = args[i]; if (arg.len != 0 and arg[0] == '-') { // TODO: hashmap, although the linear scan is okay for small argument sets as is for (spec) |flag| { if (mem.eql(u8, arg, flag.name)) { const flag_name_trimmed = trimStart(flag.name, '-'); const flag_args = readFlagArguments(allocator, args, flag.required, flag.allowed_set, &i) catch |err| { switch (err) { error.ArgumentNotInAllowedSet => { std.debug.warn("argument '{}' is invalid for flag '{}'\n", .{ args[i], arg }); std.debug.warn("allowed options are ", .{}); for (flag.allowed_set.?) |possible| { std.debug.warn("'{}' ", .{possible}); } std.debug.warn("\n", .{}); }, error.MissingFlagArguments => { std.debug.warn("missing argument for flag: {}\n", .{arg}); }, else => {}, } return err; }; if (flag.mergable) { var prev = if (parsed.flags.get(flag_name_trimmed)) |entry| entry.value.Many else ArrayList([]const u8).init(allocator); // MergeN creation disallows 0 length flag entry (doesn't make sense) switch (flag_args) { .None => unreachable, .Single => |inner| try prev.append(inner), .Many => |inner| try prev.appendSlice(inner.toSliceConst()), } _ = try parsed.flags.put(flag_name_trimmed, FlagArg{ .Many = prev }); } else { _ = try parsed.flags.put(flag_name_trimmed, flag_args); } continue :next; } } // TODO: Better errors with context, global error state and return is sufficient. std.debug.warn("could not match flag: {}\n", .{arg}); return error.UnknownFlag; } else { try parsed.positionals.append(arg); } } return parsed; } pub fn deinit(self: *Args) void { self.flags.deinit(); self.positionals.deinit(); } // e.g. --help pub fn present(self: *const Args, name: []const u8) bool { return self.flags.contains(name); } // e.g. --name value pub fn single(self: *Args, name: []const u8) ?[]const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { .Single => |inner| { return inner; }, else => @panic("attempted to retrieve flag with wrong type"), } } else { return null; } } // e.g. --names value1 value2 value3 pub fn many(self: *Args, name: []const u8) []const []const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { .Many => |inner| { return inner.toSliceConst(); }, else => @panic("attempted to retrieve flag with wrong type"), } } else { return &[_][]const u8{}; } } }; // Arguments for a flag. e.g. arg1, arg2 in `--command arg1 arg2`. const FlagArg = union(enum) { None, Single: []const u8, Many: ArrayList([]const u8), }; // Specification for how a flag should be parsed. pub const Flag = struct { name: []const u8, required: usize, mergable: bool, allowed_set: ?[]const []const u8, pub fn Bool(comptime name: []const u8) Flag { return ArgN(name, 0); } pub fn Arg1(comptime name: []const u8) Flag { return ArgN(name, 1); } pub fn ArgN(comptime name: []const u8, comptime n: usize) Flag { return Flag{ .name = name, .required = n, .mergable = false, .allowed_set = null, }; } pub fn ArgMergeN(comptime name: []const u8, comptime n: usize) Flag { if (n == 0) { @compileError("n must be greater than 0"); } return Flag{ .name = name, .required = n, .mergable = true, .allowed_set = null, }; } pub fn Option(comptime name: []const u8, comptime set: []const []const u8) Flag { return Flag{ .name = name, .required = 1, .mergable = false, .allowed_set = set, }; } }; test "parse arguments" { const spec1 = comptime [_]Flag{ Flag.Bool("--help"), Flag.Bool("--init"), Flag.Arg1("--build-file"), Flag.Option("--color", [_][]const u8{ "on", "off", "auto", }), Flag.ArgN("--pkg-begin", 2), Flag.ArgMergeN("--object", 1), Flag.ArgN("--library", 1), }; const cliargs = [_][]const u8{ "build", "--help", "pos1", "--build-file", "build.zig", "--object", "obj1", "--object", "obj2", "--library", "lib1", "--library", "lib2", "--color", "on", "pos2", }; var args = try Args.parse(std.debug.global_allocator, spec1, cliargs); testing.expect(args.present("help")); testing.expect(!args.present("help2")); testing.expect(!args.present("init")); testing.expect(mem.eql(u8, args.single("build-file").?, "build.zig")); testing.expect(mem.eql(u8, args.single("color").?, "on")); const objects = args.many("object").?; testing.expect(mem.eql(u8, objects[0], "obj1")); testing.expect(mem.eql(u8, objects[1], "obj2")); testing.expect(mem.eql(u8, args.single("library").?, "lib2")); const pos = args.positionals.toSliceConst(); testing.expect(mem.eql(u8, pos[0], "build")); testing.expect(mem.eql(u8, pos[1], "pos1")); testing.expect(mem.eql(u8, pos[2], "pos2")); }
src-self-hosted/arg.zig
const builtin = @import("builtin"); const std = @import("std"); const maxInt = std.math.maxInt; fn floatsiXf(comptime T: type, a: i32) T { @setRuntimeSafety(builtin.is_test); const bits = @typeInfo(T).Float.bits; const Z = std.meta.Int(.unsigned, bits); const S = std.meta.Int(.unsigned, bits - @clz(Z, @as(Z, bits) - 1)); if (a == 0) { return @as(T, 0.0); } const significandBits = std.math.floatMantissaBits(T); const exponentBits = std.math.floatExponentBits(T); const exponentBias = ((1 << exponentBits - 1) - 1); const implicitBit = @as(Z, 1) << significandBits; const signBit = @as(Z, 1 << bits - 1); const sign = a >> 31; // Take absolute value of a via abs(x) = (x^(x >> 31)) - (x >> 31). const abs_a = (a ^ sign) -% sign; // The exponent is the width of abs(a) const exp = @as(Z, 31 - @clz(i32, abs_a)); const sign_bit = if (sign < 0) signBit else 0; var mantissa: Z = undefined; // Shift a into the significand field and clear the implicit bit. if (exp <= significandBits) { // No rounding needed const shift = @intCast(S, significandBits - exp); mantissa = @intCast(Z, @bitCast(u32, abs_a)) << shift ^ implicitBit; } else { const shift = @intCast(S, exp - significandBits); // Round to the nearest number after truncation mantissa = @intCast(Z, @bitCast(u32, abs_a)) >> shift ^ implicitBit; // Align to the left and check if the truncated part is halfway over const round = @bitCast(u32, abs_a) << @intCast(u5, 31 - shift); mantissa += @boolToInt(round > 0x80000000); // Tie to even mantissa += mantissa & 1; } // Use the addition instead of a or since we may have a carry from the // mantissa to the exponent var result = mantissa; result += (exp + exponentBias) << significandBits; result += sign_bit; return @bitCast(T, result); } pub fn __floatsisf(arg: i32) callconv(.C) f32 { @setRuntimeSafety(builtin.is_test); return @call(.{ .modifier = .always_inline }, floatsiXf, .{ f32, arg }); } pub fn __floatsidf(arg: i32) callconv(.C) f64 { @setRuntimeSafety(builtin.is_test); return @call(.{ .modifier = .always_inline }, floatsiXf, .{ f64, arg }); } pub fn __floatsitf(arg: i32) callconv(.C) f128 { @setRuntimeSafety(builtin.is_test); return @call(.{ .modifier = .always_inline }, floatsiXf, .{ f128, arg }); } pub fn __aeabi_i2d(arg: i32) callconv(.AAPCS) f64 { @setRuntimeSafety(false); return @call(.{ .modifier = .always_inline }, __floatsidf, .{arg}); } pub fn __aeabi_i2f(arg: i32) callconv(.AAPCS) f32 { @setRuntimeSafety(false); return @call(.{ .modifier = .always_inline }, __floatsisf, .{arg}); } fn test_one_floatsitf(a: i32, expected: u128) void { const r = __floatsitf(a); std.testing.expect(@bitCast(u128, r) == expected); } fn test_one_floatsidf(a: i32, expected: u64) void { const r = __floatsidf(a); std.testing.expect(@bitCast(u64, r) == expected); } fn test_one_floatsisf(a: i32, expected: u32) void { const r = __floatsisf(a); std.testing.expect(@bitCast(u32, r) == expected); } test "floatsidf" { test_one_floatsidf(0, 0x0000000000000000); test_one_floatsidf(1, 0x3ff0000000000000); test_one_floatsidf(-1, 0xbff0000000000000); test_one_floatsidf(0x7FFFFFFF, 0x41dfffffffc00000); test_one_floatsidf(@bitCast(i32, @intCast(u32, 0x80000000)), 0xc1e0000000000000); } test "floatsisf" { test_one_floatsisf(0, 0x00000000); test_one_floatsisf(1, 0x3f800000); test_one_floatsisf(-1, 0xbf800000); test_one_floatsisf(0x7FFFFFFF, 0x4f000000); test_one_floatsisf(@bitCast(i32, @intCast(u32, 0x80000000)), 0xcf000000); } test "floatsitf" { test_one_floatsitf(0, 0); test_one_floatsitf(0x7FFFFFFF, 0x401dfffffffc00000000000000000000); test_one_floatsitf(0x12345678, 0x401b2345678000000000000000000000); test_one_floatsitf(-0x12345678, 0xc01b2345678000000000000000000000); test_one_floatsitf(@bitCast(i32, @intCast(u32, 0xffffffff)), 0xbfff0000000000000000000000000000); test_one_floatsitf(@bitCast(i32, @intCast(u32, 0x80000000)), 0xc01e0000000000000000000000000000); }
lib/std/special/compiler_rt/floatsiXf.zig
const std = @import("std"); const builtin = @import("builtin"); const clap = @import("clap"); const zfetch = @import("zfetch"); const build_options = @import("build_options"); const Dependency = @import("Dependency.zig"); usingnamespace @import("commands.zig"); //pub const io_mode = .evented; pub const zfetch_use_buffered_io = false; pub const log_level: std.log.Level = if (builtin.mode == .Debug) .debug else .info; const Command = enum { init, add, remove, build, fetch, update, publish, package, // redirect, }; fn printUsage() noreturn { const stderr = std.io.getStdErr().writer(); _ = stderr.write(std.fmt.comptimePrint( \\gyro <cmd> [cmd specific options] \\ \\cmds: \\ init Initialize a gyro.zzz with a link to a github repo \\ add Add dependencies to the project \\ remove Remove dependency from project \\ build Use exactly like 'zig build', automatically downloads dependencies \\ fetch Manually download dependencies and generate deps.zig file \\ update Update dependencies to latest \\ publish Publish package to {s}, requires github account \\ package Generate tar file that gets published \\ \\for more information: gyro <cmd> --help \\ \\ , .{build_options.default_repo})) catch {}; std.os.exit(1); } fn showHelp(comptime summary: []const u8, comptime params: anytype) void { const stderr = std.io.getStdErr().writer(); _ = stderr.write(summary ++ "\n\n") catch {}; clap.help(stderr, params) catch {}; _ = stderr.write("\n") catch {}; } fn parseHandlingHelpAndErrors( allocator: *std.mem.Allocator, comptime summary: []const u8, comptime params: anytype, iter: anytype, ) clap.ComptimeClap(clap.Help, params) { var diag: clap.Diagnostic = undefined; var args = clap.ComptimeClap(clap.Help, params).parse(allocator, iter, &diag) catch |err| { // Report useful error and exit const stderr = std.io.getStdErr().writer(); diag.report(stderr, err) catch {}; showHelp(summary, params); std.os.exit(1); }; // formerly checkHelp(summary, params, args); if (args.flag("--help")) { showHelp(summary, params); std.os.exit(0); } return args; } pub fn main() !void { try zfetch.init(); defer zfetch.deinit(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; runCommands(allocator) catch |err| { switch (err) { error.Explained => std.process.exit(1), else => return err, } }; } fn runCommands(allocator: *std.mem.Allocator) !void { var iter = try clap.args.OsIterator.init(allocator); defer iter.deinit(); const stderr = std.io.getStdErr().writer(); const cmd_str = (try iter.next()) orelse { try stderr.print("no command given\n", .{}); printUsage(); }; const cmd = inline for (std.meta.fields(Command)) |field| { if (std.mem.eql(u8, cmd_str, field.name)) { break @field(Command, field.name); } } else { try stderr.print("{s} is not a valid command\n", .{cmd_str}); printUsage(); }; @setEvalBranchQuota(3000); switch (cmd) { .init => { const summary = "Initialize a gyro.zzz with a link to a github repo"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.Param(clap.Help){ .takes_value = .One, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); const num = args.positionals().len; if (num > 1) { std.log.err("that's too many args, please just give me one in the form of a link to your github repo or just '<user>/<repo>'", .{}); return error.Explained; } try init(allocator, if (num == 1) args.positionals()[0] else null); }, .add => { const summary = "Add dependencies to the project"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-s, --src <SRC> Set type of dependency, default is 'pkg', others are 'github', 'url', or 'local'") catch unreachable, clap.parseParam("-a, --alias <ALIAS> Override what string the package is imported with") catch unreachable, clap.parseParam("-b, --build-dep Add this as a build dependency") catch unreachable, clap.parseParam("-r, --root <PATH> Set root path with respect to the project root, default is 'src/main.zig'") catch unreachable, clap.parseParam("-t, --to <PKG> Add this as a scoped dependency to a specific exported package") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); const src_str = args.option("--src") orelse "pkg"; const src_tag = inline for (std.meta.fields(Dependency.SourceType)) |field| { if (std.mem.eql(u8, src_str, field.name)) break @field(Dependency.SourceType, field.name); } else { std.log.err("{s} is not a valid source type", .{src_str}); return error.Explained; }; try add( allocator, src_tag, args.option("--alias"), args.flag("--build-dep"), args.option("--root"), args.option("--to"), args.positionals(), ); }, .remove => { const summary = "Remove dependency from project"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-b, --build-dep Remove a scoped dependency") catch unreachable, clap.parseParam("-f, --from <PKG> Remove a scoped dependency") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try remove(allocator, args.flag("--build-dep"), args.option("--from"), args.positionals()); }, .build => try build(allocator, &iter), .fetch => try fetch(allocator), .update => { const summary = "Update dependencies to latest"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-i, --in <PKG> Update a scoped dependency") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try update(allocator, args.option("--in"), args.positionals()); }, .publish => { const summary = "Generate tar file that gets published"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.Param(clap.Help){ .takes_value = .One, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try publish(allocator, if (args.positionals().len > 0) args.positionals()[0] else null); }, .package => { const summary = "Manage local development"; const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display help") catch unreachable, clap.parseParam("-o, --output-dir <DIR> output directory") catch unreachable, clap.Param(clap.Help){ .takes_value = .Many, }, }; var args = parseHandlingHelpAndErrors(allocator, summary, &params, &iter); defer args.deinit(); try package(allocator, args.option("--output-dir"), args.positionals()); }, //.redirect => { // const summary = "Manage local development"; // const params = comptime [_]clap.Param(clap.Help){ // clap.parseParam("-h, --help Display help") catch unreachable, // clap.parseParam("-c, --clean undo all local redirects") catch unreachable, // clap.Param(clap.Help){ // .takes_value = .Many, // }, // }; // return error.Todo; //}, } } test "all" { std.testing.refAllDecls(@import("Dependency.zig")); }
src/main.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); test "validate year" { try aoc.assert(validYear("2002", 1920, 2002)); try aoc.assert(!validYear("2003", 1920, 2002)); } test "validate height" { try aoc.assert(validHeight("60in")); try aoc.assert(validHeight("190cm")); try aoc.assert(!validHeight("190in")); try aoc.assert(!validHeight("190")); } test "validate hair color" { try aoc.assert(validHairColor("#123abc")); try aoc.assert(!validHairColor("#123abz")); try aoc.assert(!validHairColor("123abc")); } test "validate eye color" { try aoc.assert(validEyeColor("brn")); try aoc.assert(!validEyeColor("wat")); } test "examples" { var test1 = aoc.readChunkyObjects(aoc.talloc, aoc.test1file, "\n\n", "\n ", ":"); defer { for (test1) |*e| { e.deinit(); } aoc.talloc.free(test1); } try aoc.assertEq(@as(usize, 2), part1(test1)); try aoc.assertEq(@as(usize, 2), part2(test1)); var test2 = aoc.readChunkyObjects(aoc.talloc, aoc.test2file, "\n\n", "\n ", ":"); defer { for (test2) |*e| { e.deinit(); } aoc.talloc.free(test2); } try aoc.assertEq(@as(usize, 4), part1(test2)); try aoc.assertEq(@as(usize, 0), part2(test2)); var test3 = aoc.readChunkyObjects(aoc.talloc, aoc.test3file, "\n\n", "\n ", ":"); defer { for (test3) |*e| { e.deinit(); } aoc.talloc.free(test3); } try aoc.assertEq(@as(usize, 4), part1(test3)); try aoc.assertEq(@as(usize, 4), part2(test3)); var inp = aoc.readChunkyObjects(aoc.talloc, aoc.inputfile, "\n\n", "\n ", ":"); defer { for (inp) |*e| { e.deinit(); } aoc.talloc.free(inp); } try aoc.assertEq(@as(usize, 213), part1(inp)); try aoc.assertEq(@as(usize, 147), part2(inp)); } const fields = [_][]const u8{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", }; fn part1(inp: anytype) usize { var c: usize = 0; for (inp) |pp| { var fc: usize = 0; for (fields) |f| { if (pp.get(f)) |_| { fc += 1; } } if (fc == fields.len) { c += 1; } } return c; } fn validYear(ys: []const u8, min: i16, max: i16) bool { const y = std.fmt.parseInt(i16, ys, 10) catch return false; return y >= min and y <= max; } fn validHeight(hs: []const u8) bool { const l = hs.len; if (l < 3) { return false; } const units = hs[l - 2 ..]; const n = std.fmt.parseInt(i16, hs[0 .. l - 2], 10) catch return false; if (units[0] == 'c' and units[1] == 'm') { if (n < 150 or n > 193) { return false; } } else if (units[0] == 'i' and units[1] == 'n') { if (n < 59 or n > 76) { return false; } } else { return false; } return true; } fn validHairColor(hs: []const u8) bool { if (hs.len != 7) { return false; } for (hs[1..]) |ch| { if (!(ch >= 'a' and ch <= 'f') and !(ch >= '0' and ch <= '9')) { return false; } } return true; } fn eyeColorEq(ec: []const u8, str: []const u8) bool { if (ec.len != str.len) { return false; } var i: usize = 0; while (i < ec.len) : (i += 1) { if (ec[i] != str[i]) { return false; } } return true; } fn validEyeColor(ec: []const u8) bool { return eyeColorEq(ec, "amb") or eyeColorEq(ec, "blu") or eyeColorEq(ec, "brn") or eyeColorEq(ec, "gry") or eyeColorEq(ec, "grn") or eyeColorEq(ec, "hzl") or eyeColorEq(ec, "oth"); } fn validPID(pid: []const u8) bool { if (pid.len != 9) { return false; } _ = std.fmt.parseInt(i64, pid, 10) catch return false; return true; } fn part2(inp: anytype) usize { var c: usize = 0; for (inp) |pp| { if (!validYear(pp.get("byr") orelse "", 1920, 2002)) { continue; } if (!validYear(pp.get("iyr") orelse "", 2010, 2020)) { continue; } if (!validYear(pp.get("eyr") orelse "", 2020, 2030)) { continue; } if (!validHeight(pp.get("hgt") orelse "")) { continue; } if (!validHairColor(pp.get("hcl") orelse "")) { continue; } if (!validEyeColor(pp.get("ecl") orelse "")) { continue; } if (!validPID(pp.get("pid") orelse "")) { continue; } c += 1; } return c; } fn day04(inp: []const u8, bench: bool) anyerror!void { var scan = aoc.readChunkyObjects(aoc.halloc, inp, "\n\n", "\n ", ":"); defer { for (scan) |*e| { e.deinit(); } aoc.halloc.free(scan); } var p1 = part1(scan); var p2 = part2(scan); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day04); }
2020/04/aoc.zig
const std = @import("std"); const svd = @import("svd.zig"); const xml = @import("xml.zig"); const assert = std.debug.assert; const ArenaAllocator = std.heap.ArenaAllocator; const Allocator = std.mem.Allocator; const Self = @This(); const Range = struct { begin: u32, end: u32, }; const PeripheralUsesInterrupt = struct { peripheral_idx: u32, interrupt_value: u32, }; const FieldsInRegister = struct { register_idx: u32, field_range: Range, }; const ClusterInPeripheral = struct { peripheral_idx: u32, cluster_idx: u32, }; const ClusterInCluster = struct { parent_idx: u32, child_idx: u32, }; const Nesting = enum { namespaced, contained, }; arena: std.heap.ArenaAllocator, device: svd.Device, cpu: ?svd.Cpu, interrupts: std.ArrayList(svd.Interrupt), peripherals: std.ArrayList(svd.Peripheral), clusters: std.ArrayList(svd.Cluster), registers: std.ArrayList(svd.Register), fields: std.ArrayList(svd.Field), peripherals_use_interrupts: std.ArrayList(PeripheralUsesInterrupt), clusters_in_peripherals: std.ArrayList(ClusterInPeripheral), clusters_in_clusters: std.ArrayList(ClusterInCluster), registers_in_peripherals: std.AutoHashMap(u32, Range), registers_in_clusters: std.AutoHashMap(u32, Range), fields_in_registers: std.MultiArrayList(FieldsInRegister), dimensions: Dimensions, /// takes ownership of arena allocator fn init(arena: std.heap.ArenaAllocator, device: svd.Device) Self { const allocator = arena.child_allocator; return Self{ .arena = arena, .device = device, .cpu = null, .interrupts = std.ArrayList(svd.Interrupt).init(allocator), .peripherals = std.ArrayList(svd.Peripheral).init(allocator), .clusters = std.ArrayList(svd.Cluster).init(allocator), .registers = std.ArrayList(svd.Register).init(allocator), .fields = std.ArrayList(svd.Field).init(allocator), .peripherals_use_interrupts = std.ArrayList(PeripheralUsesInterrupt).init(allocator), .clusters_in_peripherals = std.ArrayList(ClusterInPeripheral).init(allocator), .clusters_in_clusters = std.ArrayList(ClusterInCluster).init(allocator), .registers_in_peripherals = std.AutoHashMap(u32, Range).init(allocator), .registers_in_clusters = std.AutoHashMap(u32, Range).init(allocator), .fields_in_registers = std.MultiArrayList(FieldsInRegister){}, .dimensions = Dimensions.init(allocator), }; } pub fn initFromSvd(allocator: std.mem.Allocator, doc: *xml.Doc) !Self { const root_element: *xml.Node = xml.docGetRootElement(doc) orelse return error.NoRoot; const device_node = xml.findNode(root_element, "device") orelse return error.NoDevice; const device_nodes: *xml.Node = device_node.children orelse return error.NoDeviceNodes; var arena = std.heap.ArenaAllocator.init(allocator); const device = blk: { errdefer arena.deinit(); break :blk try svd.Device.parse(&arena, device_nodes); }; var db = Self.init(arena, device); errdefer db.deinit(); db.cpu = if (xml.findNode(device_nodes, "cpu")) |cpu_node| try svd.Cpu.parse(&db.arena, @ptrCast(*xml.Node, cpu_node.children orelse return error.NoCpu)) else null; var named_derivations = Derivations([]const u8).init(allocator); defer named_derivations.deinit(); if (xml.findNode(device_nodes, "peripherals")) |peripherals_node| { var peripheral_it: ?*xml.Node = xml.findNode(peripherals_node.children, "peripheral"); //peripherals_node.children; while (peripheral_it != null) : (peripheral_it = xml.findNode(peripheral_it.?.next, "peripheral")) { const peripheral_nodes: *xml.Node = peripheral_it.?.children orelse continue; const peripheral = try svd.Peripheral.parse(&db.arena, peripheral_nodes); try db.peripherals.append(peripheral); const peripheral_idx = @intCast(u32, db.peripherals.items.len - 1); if (xml.getAttribute(peripheral_it, "derivedFrom")) |derived_from| try named_derivations.peripherals.put(peripheral_idx, try db.arena.allocator().dupe(u8, derived_from)); if (try svd.Dimension.parse(&db.arena, peripheral_nodes)) |dimension| try db.dimensions.peripherals.put(peripheral_idx, dimension); var interrupt_it: ?*xml.Node = xml.findNode(peripheral_nodes, "interrupt"); while (interrupt_it != null) : (interrupt_it = xml.findNode(interrupt_it.?.next, "interrupt")) { const interrupt_nodes: *xml.Node = interrupt_it.?.children orelse continue; const interrupt = try svd.Interrupt.parse(&db.arena, interrupt_nodes); try db.peripherals_use_interrupts.append(.{ .peripheral_idx = peripheral_idx, .interrupt_value = @intCast(u32, interrupt.value), }); // if the interrupt doesn't exist then do a sorted insert if (std.sort.binarySearch(svd.Interrupt, interrupt, db.interrupts.items, {}, svd.Interrupt.compare) == null) { try db.interrupts.append(interrupt); std.sort.sort(svd.Interrupt, db.interrupts.items, {}, svd.Interrupt.lessThan); } } if (xml.findNode(peripheral_nodes, "registers")) |registers_node| { const reg_begin_idx = db.registers.items.len; try db.loadRegisters(registers_node.children, &named_derivations); try db.registers_in_peripherals.put(peripheral_idx, .{ .begin = @intCast(u32, reg_begin_idx), .end = @intCast(u32, db.registers.items.len), }); // process clusters, this might need to be recursive var cluster_it: ?*xml.Node = xml.findNode(registers_node.children, "cluster"); while (cluster_it != null) : (cluster_it = xml.findNode(cluster_it.?.next, "cluster")) { const cluster_nodes: *xml.Node = cluster_it.?.children orelse continue; const cluster = try svd.Cluster.parse(&db.arena, cluster_nodes); try db.clusters.append(cluster); const cluster_idx = @intCast(u32, db.clusters.items.len - 1); if (xml.getAttribute(cluster_it, "derivedFrom")) |derived_from| try named_derivations.clusters.put(cluster_idx, try db.arena.allocator().dupe(u8, derived_from)); if (try svd.Dimension.parse(&db.arena, cluster_nodes)) |dimension| try db.dimensions.clusters.put(cluster_idx, dimension); try db.clusters_in_peripherals.append(.{ .cluster_idx = cluster_idx, .peripheral_idx = peripheral_idx, }); const first_reg_idx = db.registers.items.len; try db.loadRegisters(cluster_nodes, &named_derivations); try db.registers_in_clusters.put(cluster_idx, .{ .begin = @intCast(u32, first_reg_idx), .end = @intCast(u32, db.registers.items.len), }); try db.loadNestedClusters(cluster_nodes, &named_derivations); } } } } if (named_derivations.enumerations.count() != 0) return error.Todo; if (named_derivations.fields.count() != 0) return error.Todo; if (named_derivations.clusters.count() != 0) return error.Todo; // transform derivatives from strings to indexes, makes searching at bit // cleaner, and much easier to detect circular dependencies var derivations = Derivations(u32).init(allocator); defer derivations.deinit(); { var it = named_derivations.peripherals.iterator(); while (it.next()) |entry| { const base_name = entry.value_ptr.*; const idx = @intCast(u32, for (db.peripherals.items) |peripheral, i| { if (std.mem.eql(u8, base_name, peripheral.name)) break i; } else return error.DerivationNotFound); try derivations.peripherals.put(entry.key_ptr.*, idx); } it = named_derivations.registers.iterator(); while (it.next()) |entry| { const base_name = entry.value_ptr.*; const idx = @intCast(u32, for (db.registers.items) |register, i| { if (std.mem.eql(u8, base_name, register.name)) break i; } else return error.DerivationNotFound); try derivations.registers.put(entry.key_ptr.*, idx); } } // TODO: circular dependency checks // expand derivations { // TODO: look into needing more than pointing at registers var it = derivations.peripherals.iterator(); while (it.next()) |entry| { const parent_idx = entry.value_ptr.*; const child_idx = entry.key_ptr.*; if (db.registers_in_peripherals.contains(child_idx)) return error.Todo; if (db.registers_in_peripherals.get(parent_idx)) |parent_range| try db.registers_in_peripherals.put(child_idx, parent_range) else return error.FailedToDerive; } } { // TODO: look into needing more than pointing at registers var it = derivations.registers.iterator(); while (it.next()) |entry| { const parent_idx = entry.value_ptr.*; const child_idx = entry.key_ptr.*; if (db.fields_in_registers.items(.field_range)[child_idx].begin != db.fields_in_registers.items(.field_range)[child_idx].end) return error.Todo; db.fields_in_registers.items(.field_range)[child_idx] = db.fields_in_registers.items(.field_range)[parent_idx]; } } return db; } fn loadRegisters( db: *Self, nodes: ?*xml.Node, named_derivations: *Derivations([]const u8), ) !void { var register_it: ?*xml.Node = xml.findNode(nodes, "register"); while (register_it != null) : (register_it = xml.findNode(register_it.?.next, "register")) { const register_nodes: *xml.Node = register_it.?.children orelse continue; const register = try svd.Register.parse(&db.arena, register_nodes, db.device.register_properties.size orelse db.device.width); try db.registers.append(register); const register_idx = @intCast(u32, db.registers.items.len - 1); if (xml.getAttribute(register_it, "derivedFrom")) |derived_from| try named_derivations.registers.put(register_idx, try db.arena.allocator().dupe(u8, derived_from)); if (try svd.Dimension.parse(&db.arena, register_nodes)) |dimension| try db.dimensions.registers.put(register_idx, dimension); const field_begin_idx = db.fields.items.len; if (xml.findNode(register_nodes, "fields")) |fields_node| { var field_it: ?*xml.Node = xml.findNode(fields_node.children, "field"); while (field_it != null) : (field_it = xml.findNode(field_it.?.next, "field")) { const field_nodes: *xml.Node = field_it.?.children orelse continue; const field = try svd.Field.parse(&db.arena, field_nodes); try db.fields.append(field); const field_idx = @intCast(u32, db.fields.items.len - 1); if (xml.getAttribute(field_it, "derivedFrom")) |derived_from| try named_derivations.fields.put(field_idx, try db.arena.allocator().dupe(u8, derived_from)); if (try svd.Dimension.parse(&db.arena, field_nodes)) |dimension| try db.dimensions.fields.put(field_idx, dimension); // TODO: enumerations at some point when there's a solid plan //if (xml.findNode(field_nodes, "enumeratedValues")) |enum_values_node| { // // TODO: usage // // TODO: named_derivations // const name = xml.findValueForKey(enum_values_node, "name"); // _ = name; // var enum_values_it: ?*xml.Node = xml.findNode(enum_values_node.children, "enumeratedValue"); // while (enum_values_it != null) : (enum_values_it = xml.findNode(enum_values_it.?.next, "enumeratedValue")) { // const enum_nodes: *xml.Node = enum_values_it.?.children orelse continue; // const enum_value = try svd.EnumeratedValue.parse(&arena, enum_nodes); // _ = enum_value; // } //} } } // sort fields by offset std.sort.sort(svd.Field, db.fields.items[field_begin_idx..], {}, svd.Field.lessThan); // TODO: can we use unions for overlapping fields? // remove overlapping fields var i = field_begin_idx; var current_bit: usize = 0; while (i < db.fields.items.len) { if (current_bit > db.fields.items[i].offset) { const ignored = db.fields.orderedRemove(i); std.log.warn("ignoring field '{s}' ({}-{}) because it overlaps with '{s}' ({}-{}) in register '{s}'", .{ ignored.name, ignored.offset, ignored.offset + ignored.width, db.fields.items[i - 1].name, db.fields.items[i - 1].offset, db.fields.items[i - 1].offset + db.fields.items[i - 1].width, register.name, }); } else if (db.fields.items[i].offset + db.fields.items[i].width > db.device.width) { const ignored = db.fields.orderedRemove(i); std.log.warn("ignoring field '{s}' ({}-{}) in register '{s}' because it's outside it's size: {}", .{ ignored.name, ignored.offset, ignored.offset + ignored.width, register.name, db.device.width, }); } else { current_bit = db.fields.items[i].offset + db.fields.items[i].width; i += 1; } } try db.fields_in_registers.append(db.arena.child_allocator, .{ .register_idx = @intCast(u32, db.registers.items.len - 1), .field_range = .{ .begin = @intCast(u32, field_begin_idx), .end = @intCast(u32, db.fields.items.len), }, }); } } // TODO: record order somehow (clusters vs. register) fn loadNestedClusters( db: *Self, nodes: ?*xml.Node, named_derivations: *Derivations([]const u8), ) anyerror!void { const parent_idx = @intCast(u32, db.clusters.items.len - 1); var cluster_it: ?*xml.Node = xml.findNode(nodes, "cluster"); while (cluster_it != null) : (cluster_it = xml.findNode(cluster_it.?.next, "cluster")) { const cluster_nodes: *xml.Node = cluster_it.?.children orelse continue; const cluster = try svd.Cluster.parse(&db.arena, cluster_nodes); try db.clusters.append(cluster); const cluster_idx = @intCast(u32, db.clusters.items.len - 1); if (xml.getAttribute(cluster_it, "derivedFrom")) |derived_from| try named_derivations.clusters.put(cluster_idx, try db.arena.allocator().dupe(u8, derived_from)); if (try svd.Dimension.parse(&db.arena, cluster_nodes)) |dimension| try db.dimensions.clusters.put(cluster_idx, dimension); try db.clusters_in_clusters.append(.{ .parent_idx = parent_idx, .child_idx = cluster_idx, }); const first_reg_idx = db.registers.items.len; try db.loadRegisters(cluster_nodes, named_derivations); try db.registers_in_clusters.put(cluster_idx, .{ .begin = @intCast(u32, first_reg_idx), .end = @intCast(u32, db.registers.items.len), }); try db.loadNestedClusters(cluster_nodes, named_derivations); } } pub fn initFromAtdf(allocator: std.mem.Allocator, doc: *xml.Doc) !Self { _ = doc; _ = allocator; return error.Todo; } pub fn deinit(self: *Self) void { const allocator = self.arena.child_allocator; self.peripherals.deinit(); self.interrupts.deinit(); self.registers.deinit(); self.fields.deinit(); self.clusters.deinit(); self.peripherals_use_interrupts.deinit(); self.registers_in_peripherals.deinit(); self.fields_in_registers.deinit(allocator); self.clusters_in_peripherals.deinit(); self.clusters_in_clusters.deinit(); self.registers_in_clusters.deinit(); self.dimensions.deinit(); self.arena.deinit(); } fn writeDescription( allocator: Allocator, writer: anytype, description: []const u8, indent: usize, ) !void { const max_line_width = 80; // keep explicit lines from svd var line_it = std.mem.tokenize(u8, description, "\n\r"); while (line_it.next()) |input_line| { var it = std.mem.tokenize(u8, input_line, " \t"); var line = std.ArrayList(u8).init(allocator); defer line.deinit(); while (it.next()) |token| { if (line.items.len + token.len > max_line_width) { if (line.items.len > 0) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("///{s}\n", .{line.items}); line.clearRetainingCapacity(); try line.append(' '); try line.appendSlice(token); } else { try writer.writeByteNTimes(' ', indent * 4); try writer.print("/// {s}\n", .{token}); } } else { try line.append(' '); try line.appendSlice(token); } } if (line.items.len > 0) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("///{s}\n", .{line.items}); } } } pub fn toZig(self: *Self, writer: anytype) !void { try writer.writeAll("// this file is generated by regz\n//\n"); if (self.device.vendor) |vendor_name| try writer.print("// vendor: {s}\n", .{vendor_name}); if (self.device.name) |device_name| try writer.print("// device: {s}\n", .{device_name}); if (self.cpu) |cpu| if (cpu.name) |cpu_name| try writer.print("// cpu: {s}\n", .{cpu_name}); if (self.interrupts.items.len > 0 and self.cpu != null) { if (svd.CpuName.parse(self.cpu.?.name.?)) |cpu_type| { try writer.writeAll("\npub const VectorTable = struct {\n"); // this is an arm machine try writer.writeAll( \\ initial_stack_pointer: u32, \\ Reset: InterruptVector = unhandled, \\ NMI: InterruptVector = unhandled, \\ HardFault: InterruptVector = unhandled, \\ ); switch (cpu_type) { // Cortex M23 has a security extension and when implemented // there are two vector tables (same layout though) .cortex_m0, .cortex_m0plus, .cortex_m23 => try writer.writeAll( \\ reserved0: [7]u32 = undefined, \\ ), .sc300, .cortex_m3, .cortex_m4, .cortex_m7, .cortex_m33 => try writer.writeAll( \\ MemManage: InterruptVector = unhandled, \\ BusFault: InterruptVector = unhandled, \\ UsageFault: InterruptVector = unhandled, \\ reserved0: [4]u32 = undefined, \\ ), else => { std.log.err("unhandled cpu type: {}", .{cpu_type}); return error.Todo; }, } try writer.writeAll( \\ SVCall: InterruptVector = unhandled, \\ reserved1: [2]u32 = undefined, \\ PendSV: InterruptVector = unhandled, \\ SysTick: InterruptVector = unhandled, \\ ); var reserved_count: usize = 2; var expected: usize = 0; for (self.interrupts.items) |interrupt| { if (expected > interrupt.value) { assert(false); return error.InterruptOrder; } while (expected < interrupt.value) : ({ expected += 1; reserved_count += 1; }) { try writer.print(" reserved{}: u32 = undefined,\n", .{reserved_count}); } if (interrupt.description) |description| if (!isUselessDescription(description)) try writeDescription(self.arena.child_allocator, writer, description, 1); try writer.print(" {s}: InterruptVector = unhandled,\n", .{std.zig.fmtId(interrupt.name)}); expected += 1; } try writer.writeAll("};\n"); } } if (self.registers.items.len > 0) { try writer.writeAll("\npub const registers = struct {\n"); for (self.peripherals.items) |peripheral, i| { const peripheral_idx = @intCast(u32, i); const has_registers = self.registers_in_peripherals.contains(peripheral_idx); const has_clusters = for (self.clusters_in_peripherals.items) |cip| { if (cip.peripheral_idx == peripheral_idx) break true; } else false; if (!has_registers and !has_clusters) continue; if (self.dimensions.peripherals.get(peripheral_idx)) |_| { std.log.warn("dimensioned peripherals not supported yet: {s}", .{peripheral.name}); continue; } const reg_range = self.registers_in_peripherals.get(peripheral_idx).?; const registers = self.registers.items[reg_range.begin..reg_range.end]; if (registers.len != 0 or has_clusters) { if (peripheral.description) |description| if (!isUselessDescription(description)) try writeDescription(self.arena.child_allocator, writer, description, 1); try writer.print( \\ pub const {s} = struct {{ \\ pub const base_address = 0x{x}; \\ , .{ std.zig.fmtId(peripheral.name), peripheral.base_addr }); if (peripheral.version) |version| try writer.print(" pub const version = \"{s}\";\n", .{version}); for (registers) |_, range_offset| { const reg_idx = @intCast(u32, reg_range.begin + range_offset); try self.genZigRegister(writer, peripheral.base_addr, reg_idx, 2, .namespaced); } if (has_clusters) { for (self.clusters_in_peripherals.items) |cip| { if (cip.peripheral_idx == peripheral_idx) { try self.genZigCluster(writer, peripheral.base_addr, cip.cluster_idx, 2, .namespaced); } } for (self.clusters_in_clusters.items) |cic| { const nested = self.clusters.items[cic.child_idx]; std.log.warn("nested clusters not supported yet: {s}", .{nested.name}); } } try writer.writeAll(" };\n"); } } try writer.writeAll("};\n"); } try writer.writeAll("\n" ++ @embedFile("mmio.zig")); } fn genZigCluster( db: *Self, writer: anytype, base_addr: usize, cluster_idx: u32, indent: usize, nesting: Nesting, ) !void { const cluster = db.clusters.items[cluster_idx]; const dimension_opt = db.dimensions.clusters.get(cluster_idx); if (dimension_opt == null and std.mem.indexOf(u8, cluster.name, "%s") != null) return error.MissingDimension; if (dimension_opt) |dimension| if (dimension.index != null) { std.log.warn("clusters with dimIndex set are not implemented yet: {s}", .{cluster.name}); return; }; switch (nesting) { .namespaced => if (db.registers_in_clusters.get(cluster_idx)) |range| { const registers = db.registers.items[range.begin..range.end]; try writer.writeByte('\n'); if (cluster.description) |description| if (!isUselessDescription(description)) try writeDescription(db.arena.child_allocator, writer, description, indent); if (dimension_opt) |dimension| { const name = try std.mem.replaceOwned(u8, db.arena.allocator(), cluster.name, "[%s]", ""); try writer.writeByteNTimes(' ', indent * 4); try writer.print("pub const {s} = @ptrCast(*volatile [{}]packed struct {{", .{ name, dimension.dim }); // TODO: check address offset of register wrt the cluster var bits: usize = 0; for (registers) |register, offset| { const reg_idx = @intCast(u32, range.begin + offset); try db.genZigRegister(writer, base_addr, reg_idx, indent + 1, .contained); bits += register.size; } if (bits % 8 != 0 or db.device.width % 8 != 0) return error.InvalidWordSize; const bytes = bits / 8; const bytes_per_word = db.device.width / 8; if (bytes > dimension.increment) return error.InvalidClusterSize; const num_padding_words = (dimension.increment - bytes) / bytes_per_word; var i: usize = 0; while (i < num_padding_words) : (i += 1) { try writer.writeByteNTimes(' ', (indent + 1) * 4); try writer.print("padding{}: u{},\n", .{ i, db.device.width }); } try writer.writeByteNTimes(' ', indent * 4); try writer.print("}}, base_address + 0x{x});\n", .{cluster.addr_offset}); } else { try writer.writeByteNTimes(' ', indent * 4); try writer.print("pub const {s} = struct {{\n", .{std.zig.fmtId(cluster.name)}); for (registers) |_, offset| { const reg_idx = @intCast(u32, range.begin + offset); try db.genZigRegister(writer, base_addr, reg_idx, indent + 1, .namespaced); } try writer.writeByteNTimes(' ', indent * 4); try writer.writeAll("};\n"); } }, .contained => {}, } } fn genZigSingleRegister( self: *Self, writer: anytype, name: []const u8, width: usize, addr_offset: usize, fields: []svd.Field, first_field_idx: u32, array_prefix: []const u8, indent: usize, nesting: Nesting, ) !void { const single_line_declaration = fields.len == 0 or (fields.len == 1 and std.mem.eql(u8, fields[0].name, name)); if (single_line_declaration) { if (fields.len == 1 and fields[0].width < width) { try writer.writeByteNTimes(' ', indent * 4); switch (nesting) { .namespaced => try writer.print("pub const {s} = @intToPtr(*volatile {s}MmioInt({}, u{}), base_address + 0x{x});\n", .{ std.zig.fmtId(name), array_prefix, width, fields[0].width, addr_offset, }), .contained => try writer.print("{s}: {s}MmioInt({}, u{}),\n", .{ std.zig.fmtId(name), array_prefix, width, fields[0].width, }), } } else if (fields.len == 1 and fields[0].width > width) { return error.BadWidth; } else { try writer.writeByteNTimes(' ', indent * 4); switch (nesting) { .namespaced => try writer.print("pub const {s} = @intToPtr(*volatile {s}u{}, base_address + 0x{x});\n", .{ std.zig.fmtId(name), array_prefix, width, addr_offset, }), .contained => try writer.print("{s}: {s}u{},\n", .{ std.zig.fmtId(name), array_prefix, width, }), } } } else { try writer.writeByteNTimes(' ', indent * 4); switch (nesting) { .namespaced => try writer.print("pub const {s} = @intToPtr(*volatile {s}Mmio({}, packed struct{{\n", .{ std.zig.fmtId(name), array_prefix, width, }), .contained => try writer.print("{s}: {s}Mmio({}, packed struct{{\n", .{ std.zig.fmtId(name), array_prefix, width, }), } try self.genZigFields( writer, width, fields, first_field_idx, indent + 1, ); try writer.writeByteNTimes(' ', indent * 4); switch (nesting) { .namespaced => try writer.print("}}), base_address + 0x{x});\n", .{addr_offset}), .contained => try writer.writeAll("}),\n"), } } } fn genZigFields( self: *Self, writer: anytype, reg_width: usize, fields: []svd.Field, first_field_idx: u32, indent: usize, ) !void { var expected_bit: usize = 0; var reserved_num: usize = 0; for (fields) |field, offset| { const field_idx = @intCast(u32, first_field_idx + offset); const dimension_opt = self.dimensions.fields.get(field_idx); if (dimension_opt) |dimension| { assert(std.mem.indexOf(u8, field.name, "[%s]") == null); if (dimension.index) |dim_index| switch (dim_index) { .list => |list| for (list.items) |entry| { const name = try std.mem.replaceOwned(u8, self.arena.allocator(), field.name, "%s", entry); try writer.writeByteNTimes(' ', indent * 4); try writer.print("{s}: u{},\n", .{ std.zig.fmtId(name), field.width }); expected_bit += field.width; }, .num => { std.log.warn("dimensioned register fields not supported yet: {s}", .{field.name}); assert(false); }, } else { var i: usize = 0; while (i < dimension.dim) : (i += 1) { const num_str = try std.fmt.allocPrint(self.arena.allocator(), "{}", .{i}); const name = try std.mem.replaceOwned(u8, self.arena.allocator(), field.name, "%s", num_str); try writer.writeByteNTimes(' ', indent * 4); try writer.print("{s}: u{},\n", .{ std.zig.fmtId(name), field.width }); expected_bit += field.width; } } continue; } if (std.mem.indexOf(u8, field.name, "%s") != null) return error.MissingDimension; if (expected_bit > field.offset) { std.log.err("found overlapping fields in register:", .{}); for (fields) |f| { std.log.err(" {s}: {}+{}", .{ f.name, f.offset, f.width }); } return error.Explained; } while (expected_bit < field.offset) : ({ expected_bit += 1; reserved_num += 1; }) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("reserved{}: u1,\n", .{reserved_num}); } if (expected_bit + field.width > reg_width) { for (fields[offset..]) |ignored| { std.log.warn("field '{s}' ({}-{}) in register is outside word size: {}", .{ ignored.name, ignored.offset, ignored.offset + ignored.width, reg_width, }); } break; } // TODO: default values? if (field.description) |description| if (!isUselessDescription(description)) try writeDescription(self.arena.child_allocator, writer, description, indent); try writer.writeByteNTimes(' ', indent * 4); try writer.print("{s}: u{},\n", .{ std.zig.fmtId(field.name), field.width }); expected_bit += field.width; } var padding_num: usize = 0; while (expected_bit < reg_width) : ({ expected_bit += 1; padding_num += 1; }) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("padding{}: u1,\n", .{padding_num}); } } fn genZigRegister( self: *Self, writer: anytype, base_addr: usize, reg_idx: u32, indent: usize, nesting: Nesting, ) !void { const register = self.registers.items[reg_idx]; const fields = blk: { const range = self.fields_in_registers.items(.field_range)[reg_idx]; break :blk self.fields.items[range.begin..range.end]; }; const dimension_opt = self.dimensions.registers.get(reg_idx); if (dimension_opt == null and std.mem.indexOf(u8, register.name, "%s") != null) return error.MissingDimension; const wants_list = dimension_opt != null and std.mem.indexOf(u8, register.name, "%s") != null and std.mem.indexOf(u8, register.name, "[%s]") == null; const is_list = if (dimension_opt) |dimension| if (dimension.index) |dim_index| dim_index == .list and std.mem.indexOf(u8, register.name, "[%s]") == null else false else false; if (is_list) { if (std.mem.indexOf(u8, register.name, "[%s]") != null) { std.log.info("register name: {s}", .{register.name}); std.log.info("dimension: {s}", .{dimension_opt}); return error.InvalidRegisterName; } const dimension = dimension_opt.?; for (dimension.index.?.list.items) |elem, i| { const name = try std.mem.replaceOwned(u8, self.arena.allocator(), register.name, "%s", elem); const addr_offset = register.addr_offset + (i * dimension.increment); try writer.writeByte('\n'); if (nesting == .namespaced) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("/// address: 0x{x}\n", .{base_addr + addr_offset}); } if (register.description) |description| try writeDescription(self.arena.child_allocator, writer, description, indent); try self.genZigSingleRegister( writer, name, register.size, addr_offset, fields, self.fields_in_registers.items(.field_range)[reg_idx].begin, "", indent, nesting, ); } return; } else if (wants_list) { if (std.mem.indexOf(u8, register.name, "[%s]") != null) { return error.InvalidRegisterName; } const dimension = dimension_opt.?; var i: usize = 0; while (i < dimension.dim) : (i += 1) { const num_str = try std.fmt.allocPrint(self.arena.allocator(), "{}", .{i}); const name = try std.mem.replaceOwned(u8, self.arena.allocator(), register.name, "%s", num_str); const addr_offset = register.addr_offset + (i * dimension.increment); try writer.writeByte('\n'); if (nesting == .namespaced) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("/// address: 0x{x}\n", .{base_addr + addr_offset}); } if (register.description) |description| try writeDescription(self.arena.child_allocator, writer, description, indent); try self.genZigSingleRegister( writer, name, register.size, addr_offset, fields, self.fields_in_registers.items(.field_range)[reg_idx].begin, "", indent, nesting, ); } return; } else { if (std.mem.indexOf(u8, register.name, "[%s]") == null and std.mem.indexOf(u8, register.name, "%s") != null) { std.log.err("register: {s}", .{register.name}); return error.InvalidRegisterName; } const array_prefix: []const u8 = if (dimension_opt) |dimension| blk: { if (dimension.increment != register.size / 8) { std.log.err("register: {s}", .{register.name}); std.log.err("size: {}", .{register.size}); std.log.err("dimension: {}", .{dimension}); return error.InvalidArrayIncrement; } // if index is set, then it must be a comma separated list of numbers 0 to dim - 1 if (dimension.index) |dim_index| switch (dim_index) { .list => |list| { var expected_num: usize = 0; while (expected_num < dimension.dim) : (expected_num += 1) { const num = try std.fmt.parseInt(usize, list.items[expected_num], 0); if (num != expected_num) return error.InvalidDimIndex; } }, .num => |num| if (num != dimension.dim) { return error.InvalidDimIndex; }, }; break :blk try std.fmt.allocPrint(self.arena.allocator(), "[{}]", .{dimension.dim}); } else ""; const name = try std.mem.replaceOwned(u8, self.arena.allocator(), register.name, "[%s]", ""); try writer.writeByte('\n'); if (nesting == .namespaced) { try writer.writeByteNTimes(' ', indent * 4); try writer.print("/// address: 0x{x}\n", .{base_addr + register.addr_offset}); } if (register.description) |description| try writeDescription(self.arena.child_allocator, writer, description, indent); try self.genZigSingleRegister( writer, name, register.size, register.addr_offset, fields, self.fields_in_registers.items(.field_range)[reg_idx].begin, array_prefix, indent, nesting, ); return; } std.log.info("register {}: {s}", .{ reg_idx, register.name }); std.log.info(" nesting: {}", .{nesting}); if (dimension_opt) |dimension| { std.log.info(" dim: {}", .{dimension.dim}); std.log.info(" dim_index: {}", .{dimension.index}); } std.log.info(" fields: {}", .{fields.len}); assert(false); // haven't figured out this configuration yet } pub fn toJson(writer: anytype) !void { _ = writer; return error.Todo; } fn Derivations(comptime T: type) type { return struct { enumerations: std.AutoHashMap(u32, T), fields: std.AutoHashMap(u32, T), registers: std.AutoHashMap(u32, T), clusters: std.AutoHashMap(u32, T), peripherals: std.AutoHashMap(u32, T), fn init(allocator: Allocator) @This() { return @This(){ .enumerations = std.AutoHashMap(u32, T).init(allocator), .fields = std.AutoHashMap(u32, T).init(allocator), .registers = std.AutoHashMap(u32, T).init(allocator), .clusters = std.AutoHashMap(u32, T).init(allocator), .peripherals = std.AutoHashMap(u32, T).init(allocator), }; } fn deinit(self: *@This()) void { self.enumerations.deinit(); self.fields.deinit(); self.registers.deinit(); self.clusters.deinit(); self.peripherals.deinit(); } }; } const Dimensions = struct { fields: std.AutoHashMap(u32, svd.Dimension), registers: std.AutoHashMap(u32, svd.Dimension), clusters: std.AutoHashMap(u32, svd.Dimension), peripherals: std.AutoHashMap(u32, svd.Dimension), fn init(allocator: Allocator) @This() { return @This(){ .fields = std.AutoHashMap(u32, svd.Dimension).init(allocator), .registers = std.AutoHashMap(u32, svd.Dimension).init(allocator), .clusters = std.AutoHashMap(u32, svd.Dimension).init(allocator), .peripherals = std.AutoHashMap(u32, svd.Dimension).init(allocator), }; } fn deinit(self: *@This()) void { self.fields.deinit(); self.registers.deinit(); self.clusters.deinit(); self.peripherals.deinit(); } }; const useless_descriptions: []const []const u8 = &.{ "Unspecified", }; fn isUselessDescription(description: []const u8) bool { return for (useless_descriptions) |useless_description| { if (std.mem.eql(u8, description, useless_description)) break true; } else false; }
src/Database.zig
const builtin = @import("builtin"); const std = @import("std"); const Os = builtin.Os; const darwin = std.os.darwin; const linux = std.os.linux; const mem = std.mem; const warn = std.debug.warn; const assert = std.debug.assert; const windows = std.os.windows; pub const Location = struct { name: []const u8, zone: ?[]zone, tx: ?[]ZoneTrans, // Most lookups will be for the current time. // To avoid the binary search through tx, keep a // static one-element cache that gives the correct // zone for the time when the Location was created. // if cacheStart <= t < cacheEnd, // lookup can return cacheZone. // The units for cacheStart and cacheEnd are seconds // since January 1, 1970 UTC, to match the argument // to lookup. cache_start: ?i64, cache_end: ?i64, cached_zone: ?*zone, arena: std.heap.ArenaAllocator, const alpha: i64 = -1 << 63; const omega: i64 = 1 << 63 - 1; const max_file_size: usize = 10 << 20; const initLocation = switch (builtin.os.tag) { .linux => initLinux, .macos, .ios => initDarwin, else => @compileError("Unsupported OS"), }; pub var utc_local = Location.init(std.heap.page_allocator, "UTC"); var unix_sources = [_][]const u8{ "/usr/share/zoneinfo/", "/usr/share/lib/zoneinfo/", "/usr/lib/locale/TZ/", }; // readFile reads contents of a file with path and writes the read bytes to buf. const zone = struct { name: []const u8, offset: isize, is_dst: bool, }; const ZoneTrans = struct { when: i64, index: usize, is_std: bool, is_utc: bool, }; pub const zoneDetails = struct { name: []const u8, offset: isize, start: i64, end: i64, }; // alpha and omega are the beginning and end of time for zone // transitions. const dataIO = struct { p: []u8, n: usize, fn init(p: []u8) dataIO { return dataIO{ .p = p, .n = 0, }; } fn read(d: *dataIO, p: []u8) usize { if (d.n >= d.p.len) { // end of stream return 0; } const pos = d.n; const offset = pos + p.len; while ((d.n < offset) and (d.n < d.p.len)) : (d.n += 1) { p[d.n - pos] = d.p[d.n]; } return d.n - pos; } fn big4(d: *dataIO) !i32 { var p: [4]u8 = undefined; const size = d.read(p[0..]); if (size < 4) { return error.BadData; } const o = @intCast(i32, p[3]) | (@intCast(i32, p[2]) << 8) | (@intCast(i32, p[1]) << 16) | (@intCast(i32, p[0]) << 24); return o; } // advances the cursor by n. next read will start after skipping the n bytes. fn skip(d: *dataIO, n: usize) void { d.n += n; } fn byte(d: *dataIO) !u8 { if (d.n < d.p.len) { const u = d.p[d.n]; d.n += 1; return u; } return error.EOF; } }; fn init(a: *mem.Allocator, name: []const u8) Location { var arena = std.heap.ArenaAllocator.init(a); return Location{ .name = name, .zone = null, .tx = null, .arena = arena, .cache_start = null, .cache_end = null, .cached_zone = null, }; } pub fn deinit(self: *Location) void { self.arena.deinit(); } /// getLocal returns local timezone. pub fn getLocal() Location { return initLocation(); } /// firstZoneUsed returns whether the first zone is used by some /// transition. pub fn firstZoneUsed(self: *const Location) bool { if (self.tx) |tx| { for (tx) |value| { if (value.index == 0) { return true; } } } return false; } // lookupFirstZone returns the index of the time zone to use for times // before the first transition time, or when there are no transition // times. // // The reference implementation in localtime.c from // https://www.iana.org/time-zones/repository/releases/tzcode2013g.tar.gz // implements the following algorithm for these cases: // 1) If the first zone is unused by the transitions, use it. // 2) Otherwise, if there are transition times, and the first // transition is to a zone in daylight time, find the first // non-daylight-time zone before and closest to the first transition // zone. // 3) Otherwise, use the first zone that is not daylight time, if // there is one. // 4) Otherwise, use the first zone. pub fn lookupFirstZone(self: *const Location) usize { // Case 1. if (!self.firstZoneUsed()) { return 0; } // Case 2. if (self.tx) |tx| { if (tx.len > 0 and self.zone.?[tx[0].index].is_dst) { var zi = @intCast(isize, tx[0].index); while (zi >= 0) : (zi -= 1) { if (!self.zone.?[@intCast(usize, zi)].is_dst) { return @intCast(usize, zi); } } } } // Case 3. if (self.zone) |tzone| { for (tzone) |z, idx| { if (!z.is_dst) { return idx; } } } // Case 4. return 0; } /// lookup returns information about the time zone in use at an /// instant in time expressed as seconds since January 1, 1970 00:00:00 UTC. /// /// The returned information gives the name of the zone (such as "CET"), /// the start and end times bracketing sec when that zone is in effect, /// the offset in seconds east of UTC (such as -5*60*60), and whether /// the daylight savings is being observed at that time. pub fn lookup(self: *const Location, sec: i64) zoneDetails { if (self.zone == null) { return zoneDetails{ .name = "UTC", .offset = 0, .start = alpha, .end = omega, }; } if (self.tx) |tx| { if (tx.len == 0 or sec < tx[0].when) { const tzone = &self.zone.?[self.lookupFirstZone()]; var end: i64 = undefined; if (tx.len > 0) { end = tx[0].when; } else { end = omega; } return zoneDetails{ .name = tzone.name, .offset = tzone.offset, .start = alpha, .end = end, }; } } // Binary search for entry with largest time <= sec. // Not using sort.Search to avoid dependencies. var lo: usize = 0; var hi = self.tx.?.len; var end = omega; while ((hi - lo) > 1) { const m = lo + ((hi - lo) / 2); const lim = self.tx.?[m].when; if (sec < lim) { end = lim; hi = m; } else { lo = m; } } const tzone = &self.zone.?[self.tx.?[lo].index]; return zoneDetails{ .name = tzone.name, .offset = tzone.offset, .start = self.tx.?[lo].when, .end = end, }; } /// lookupName returns information about the time zone with /// the given name (such as "EST") at the given pseudo-Unix time /// (what the given time of day would be in UTC). pub fn lookupName(self: *Location, name: []const u8, unix: i64) !isize { // First try for a zone with the right name that was actually // in effect at the given time. (In Sydney, Australia, both standard // and daylight-savings time are abbreviated "EST". Using the // offset helps us pick the right one for the given time. // It's not perfect: during the backward transition we might pick // either one.) if (self.zone) |zone| { for (zone) |*z| { if (mem.eql(u8, z.name, name)) { const d = self.lookup(unix - @intCast(i64, z.offset)); if (mem.eql(d.name, z.name)) { return d.offset; } } } } // Otherwise fall back to an ordinary name match. if (self.zone) |zone| { for (zone) |*z| { if (mem.eql(u8, z.name, name)) { return z.offset; } } } return error.ZoneNotFound; } pub fn loadLocationFromTZData(a: *mem.Allocator, name: []const u8, data: []u8) !Location { var arena = std.heap.ArenaAllocator.init(a); var arena_allocator = &arena.allocator; defer arena.deinit(); errdefer arena.deinit(); var d = &dataIO.init(data); var magic: [4]u8 = undefined; var size = d.read(magic[0..]); if (size != 4) { return error.BadData; } if (!mem.eql(u8, &magic, "TZif")) { return error.BadData; } // 1-byte version, then 15 bytes of padding var p: [16]u8 = undefined; size = d.read(p[0..]); if (size != 16 or p[0] != 0 and p[0] != '2' and p[0] != '3') { return error.BadData; } // six big-endian 32-bit integers: // number of UTC/local indicators // number of standard/wall indicators // number of leap seconds // number of transition times // number of local time zones // number of characters of time zone abbrev strings const n_value = enum(usize) { UTCLocal, STDWall, Leap, Time, Zone, Char, }; var n: [6]usize = undefined; var i: usize = 0; while (i < 6) : (i += 1) { const nn = try d.big4(); n[i] = @intCast(usize, nn); } // Transition times. var tx_times = try arena_allocator.alloc(u8, n[@enumToInt(n_value.Time)] * 4); _ = d.read(tx_times); var tx_times_data = dataIO.init(tx_times); // Time zone indices for transition times. var tx_zone = try arena_allocator.alloc(u8, n[@enumToInt(n_value.Time)]); _ = d.read(tx_zone); var tx_zone_data = dataIO.init(tx_zone); // Zone info structures var zone_data_value = try arena_allocator.alloc(u8, n[@enumToInt(n_value.Zone)] * 6); _ = d.read(zone_data_value); var zone_data = dataIO.init(zone_data_value); // Time zone abbreviations. var abbrev = try arena_allocator.alloc(u8, n[@enumToInt(n_value.Char)]); _ = d.read(abbrev); // Leap-second time pairs d.skip(n[@enumToInt(n_value.Leap)] * 8); // Whether tx times associated with local time types // are specified as standard time or wall time. var isstd = try arena_allocator.alloc(u8, n[@enumToInt(n_value.STDWall)]); _ = d.read(isstd); var isutc = try arena_allocator.alloc(u8, n[@enumToInt(n_value.UTCLocal)]); size = d.read(isutc); if (size == 0) { return error.BadData; } // If version == 2 or 3, the entire file repeats, this time using // 8-byte ints for txtimes and leap seconds. // We won't need those until 2106. var loc = Location.init(a, name); errdefer loc.deinit(); var zalloc = &loc.arena.allocator; // Now we can build up a useful data structure. // First the zone information. //utcoff[4] isdst[1] nameindex[1] i = 0; var zones = try zalloc.alloc(zone, n[@enumToInt(n_value.Zone)]); while (i < n[@enumToInt(n_value.Zone)]) : (i += 1) { const zn = try zone_data.big4(); const b = try zone_data.byte(); var z: zone = undefined; z.offset = @intCast(isize, zn); z.is_dst = b != 0; const b2 = try zone_data.byte(); if (@intCast(usize, b2) >= abbrev.len) { return error.BadData; } const cn = byteString(abbrev[b2..]); // we copy the name and ensure it stay valid throughout location // lifetime. var znb = try zalloc.alloc(u8, cn.len); mem.copy(u8, znb, cn); z.name = znb; zones[i] = z; } loc.zone = zones; // Now the transition time info. i = 0; const tx_n = n[@enumToInt(n_value.Time)]; var tx_list = try zalloc.alloc(ZoneTrans, tx_n); if (tx_n != 0) { while (i < n[@enumToInt(n_value.Time)]) : (i += 1) { var tx: ZoneTrans = undefined; const w = try tx_times_data.big4(); tx.when = @intCast(i64, w); if (@intCast(usize, tx_zone[i]) >= zones.len) { return error.BadData; } tx.index = @intCast(usize, tx_zone[i]); if (i < isstd.len) { tx.is_std = isstd[i] != 0; } if (i < isutc.len) { tx.is_utc = isutc[i] != 0; } tx_list[i] = tx; } loc.tx = tx_list; } else { var ls = [_]ZoneTrans{ZoneTrans{ .when = alpha, .index = 0, .is_std = false, .is_utc = false, }}; loc.tx = ls[0..]; } return loc; } // darwin_sources directory to search for timezone files. fn readFile(path: []const u8) !void { var file = try std.fs.File.openRead(path); defer file.close(); var stream = &file.inStream().stream; try stream.readAllBuffer(buf, max_file_size); } fn loadLocationFile(a: *mem.Allocator, fileName: []const u8, sources: [][]const u8) ![]u8 { var buf = std.ArrayList(u8).init(a); defer buf.deinit(); for (sources) |source| { try buf.resize(0); try buf.appendSlice(source); if (buf.items[buf.items.len - 1] != '/') { try buf.append('/'); } try buf.appendSlice(fileName); if (std.fs.cwd().readFileAlloc(a, buf.items, 20 * 1024 * 1024)) |contents| { return contents; } else |err| { continue; } } return error.MissingZoneFile; } fn loadLocationFromTZFile(a: *mem.Allocator, name: []const u8, sources: [][]const u8) !Location { var buf: []u8 = undefined; var t = try loadLocationFile(a, name, sources); return loadLocationFromTZData(a, name, t); } pub fn load(name: []const u8) !Location { return loadLocationFromTZFile(std.heap.page_allocator, name, unix_sources[0..]); } fn initDarwin() Location { return initLinux(); } fn initLinux() Location { var tz: ?[]const u8 = null; if (std.process.getEnvMap(std.heap.page_allocator)) |value| { var env = value; defer env.deinit(); tz = env.get("TZ"); } else |err| {} if (tz) |name| { if (name.len != 0 and !mem.eql(u8, name, "UTC")) { if (loadLocationFromTZFile(std.heap.page_allocator, name, unix_sources[0..])) |tzone| { return tzone; } else |err| {} } } else { var etc = [_][]const u8{"/etc/"}; if (loadLocationFromTZFile(std.heap.page_allocator, "localtime", etc[0..])) |tzone| { var zz = tzone; zz.name = "local"; return zz; } else |err| {} } return utc_local; } fn byteString(x: []u8) []u8 { for (x) |v, idx| { if (v == 0) { return x[0..idx]; } } return x; } }; const seconds_per_minute = 60; const seconds_per_hour = 60 * seconds_per_minute; const seconds_per_day = 24 * seconds_per_hour; const seconds_per_week = 7 * seconds_per_day; const days_per_400_years = 365 * 400 + 97; const days_per_100_years = 365 * 100 + 24; const days_per_4_years = 365 * 4 + 1; // The unsigned zero year for internal calculations. // Must be 1 mod 400, and times before it will not compute correctly, // but otherwise can be changed at will. const absolute_zero_year: i64 = -292277022399; // The year of the zero Time. // Assumed by the unix_to_internal computation below. const internal_year: i64 = 1; // Offsets to convert between internal and absolute or Unix times. const absolute_to_internal: i64 = (absolute_zero_year - internal_year) * @floatToInt(i64, 365.2425 * @intToFloat(f64, seconds_per_day)); const internal_to_absolute = -absolute_to_internal; const unix_to_internal: i64 = (1969 * 365 + 1969 / 4 - 1969 / 100 + 1969 / 400) * seconds_per_day; const internal_to_unix: i64 = -unix_to_internal; const wall_to_internal: i64 = (1884 * 365 + 1884 / 4 - 1884 / 100 + 1884 / 400) * seconds_per_day; const internal_to_wall: i64 = -wall_to_internal; const has_monotonic = 1 << 63; const max_wall = wall_to_internal + ((1 << 33) - 1); // year 2157 const min_wall = wall_to_internal; // year 1885 const nsec_mask: u64 = (1 << 30) - 1; const nsec_shift = 30; const context = @This(); pub const Time = struct { const Self = @This(); wall: u64, ext: i64, loc: *Location, const short_days = [_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", }; const divResult = struct { qmod: isize, r: Duration, }; // div divides self by d and returns the quotient parity and remainder. // We don't use the quotient parity anymore (round half up instead of round to even) // but it's still here in case we change our minds. fn nsec(self: Self) i32 { if (self.wall == 0) { return 0; } return @intCast(i32, self.wall & nsec_mask); } fn sec(self: Self) i64 { if ((self.wall & has_monotonic) != 0) { return wall_to_internal + @intCast(i64, self.wall << 1 >> (nsec_shift + 1)); } return self.ext; } // unixSec returns the time's seconds since Jan 1 1970 (Unix time). fn unixSec(self: Self) i64 { return self.sec() + internal_to_unix; } pub fn unix(self: Self) i64 { return self.unixSec(); } fn addSec(self: *Self, d: i64) void { if ((self.wall & has_monotonic) != 0) { const s = @intCast(i64, self.wall << 1 >> (nsec_shift + 1)); const dsec = s + d; if (0 <= dsec and dsec <= (1 << 33) - 1) { self.wall = self.wall & nsec_mask | @intCast(u64, dsec) << nsec_shift | has_monotonic; return; } // Wall second now out of range for packed field. // Move to ext self.stripMono(); } self.ext += d; } /// returns the time corresponding to adding the /// given number of years, months, and days to self. /// For example, addDate(-1, 2, 3) applied to January 1, 2011 /// returns March 4, 2010. /// /// addDate normalizes its result in the same way that Date does, /// so, for example, adding one month to October 31 yields /// December 1, the normalized form for November 31. pub fn addDate(self: Self, years: isize, number_of_months: isize, number_of_days: isize) Self { const d = self.date(); const c = self.clock(); const m = @intCast(isize, @enumToInt(d.month)) + number_of_months; return context.date( d.year + years, m, d.day + number_of_days, c.hour, c.min, c.sec, @intCast(isize, self.nsec()), self.loc, ); } fn stripMono(self: *Self) void { if ((self.wall & has_monotonic) != 0) { self.ext = self.sec(); self.wall &= nsec_mask; } } pub fn setLoc(self: Self, l: *Location) void { self.stripMono(); self.loc = l; } fn setMono(self: Self, m: i64) void { if ((self.wall & has_monotonic) == 0) { const s = self.ext; if (s < min_wall or max_wall < s) { return; } self.wall |= has_monotonic | @intCast(u64, s - min_wall) << nsec_shift; } self.ext = m; } // mono returns t's monotonic clock reading. // It returns 0 for a missing reading. // This function is used only for testing, // so it's OK that technically 0 is a valid // monotonic clock reading as well. fn mono(self: Self) i64 { if ((self.wall & has_monotonic) == 0) { return 0; } return self.ext; } /// reports whether self represents the zero time instant, /// January 1, year 1, 00:00:00 UTC. pub fn isZero(self: Self) bool { return self.sec() == 0 and self.nsec() == 0; } /// returns true if time self is after time u. pub fn after(self: Self, u: Self) bool { const ts = self.sec(); const us = u.sec(); return ts > us or (ts == us and self.nsec() > u.nsec()); } /// returns true if time self is before u. pub fn before(self: Self, u: Self) bool { return (self.sec() < u.sec()) or (self.sec() == u.sec() and self.nsec() < u.nsec()); } /// reports whether self and u represent the same time instant. /// Two times can be equal even if they are in different locations. /// For example, 6:00 +0200 CEST and 4:00 UTC are Equal. /// See the documentation on the Time type for the pitfalls of using == with /// Time values; most code should use Equal instead. pub fn equal(self: Self, u: Self) bool { return self.sec() == u.sec() and self.nsec() == u.nsec(); } /// abs returns the time self as an absolute time, adjusted by the zone offset. /// It is called when computing a presentation property like Month or Hour. fn abs(self: Self) u64 { var usec = self.unixSec(); const d = self.loc.lookup(usec); usec += @intCast(i64, d.offset); var result: i64 = undefined; _ = @addWithOverflow(i64, usec, (unix_to_internal + internal_to_absolute), &result); return @bitCast(u64, result); } pub fn date(self: Self) DateDetail { return absDate(self.abs(), true); } pub fn year(self: Self) isize { const d = self.date(); return d.year; } pub fn month(self: Self) Month { const d = self.date(); return d.month; } pub fn day(self: Self) isize { const d = self.date(); return d.day; } /// returns the day of the week specified by self. pub fn weekday(self: Self) Weekday { return absWeekday(self.abs()); } /// isoWeek returns the ISO 8601 year and week number in which self occurs. /// Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to /// week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 /// of year n+1. pub fn isoWeek(self: Self) ISOWeek { var d = self.date(); const wday = @mod(@intCast(isize, @enumToInt(self.weekday()) + 8), 7); const Mon: isize = 0; const Tue = Mon + 1; const Wed = Tue + 1; const Thu = Wed + 1; const Fri = Thu + 1; const Sat = Fri + 1; const Sun = Sat + 1; // Calculate week as number of Mondays in year up to // and including today, plus 1 because the first week is week 0. // Putting the + 1 inside the numerator as a + 7 keeps the // numerator from being negative, which would cause it to // round incorrectly. var week = @divTrunc(d.yday - wday + 7, 7); // The week number is now correct under the assumption // that the first Monday of the year is in week 1. // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday // is actually in week 2. const jan1wday = @mod((wday - d.yday + 7 * 53), 7); if (Tue <= jan1wday and jan1wday <= Thu) { week += 1; } if (week == 0) { d.year -= 1; week = 52; } // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday, // meaning Jan 1 of the next year is a Friday // or it was a leap year and Jan 1 of the next year is a Saturday. if (jan1wday == Fri or (jan1wday == Sat) and isLeap(d.year)) { week += 1; } // December 29 to 31 are in week 1 of next year if // they are after the last Thursday of the year and // December 31 is a Monday, Tuesday, or Wednesday. if (@enumToInt(d.month) == @enumToInt(Month.December) and d.day >= 29 and wday < Thu) { const dec31wday = @mod((wday + 31 - d.day), 7); if (Mon <= dec31wday and dec31wday <= Wed) { d.year += 1; week = 1; } } return ISOWeek{ .year = d.year, .week = week }; } /// clock returns the hour, minute, and second within the day specified by t. pub fn clock(self: Self) Clock { return Clock.absClock(self.abs()); } /// returns the hour within the day specified by self, in the range [0, 23]. pub fn hour(self: Self) isize { return @divTrunc(@intCast(isize, self.abs() % seconds_per_day), seconds_per_hour); } /// returns the minute offset within the hour specified by self, in the /// range [0, 59]. pub fn minute(self: Self) isize { return @divTrunc(@intCast(isize, self.abs() % seconds_per_hour), seconds_per_minute); } /// returns the second offset within the minute specified by self, in the /// range [0, 59]. pub fn second(self: Self) isize { return @intCast(isize, self.abs() % seconds_per_minute); } /// returns the nanosecond offset within the second specified by self, /// in the range [0, 999999999]. pub fn nanosecond(self: Self) isize { return @intCast(isize, self.nsec()); } /// returns the day of the year specified by self, in the range [1,365] for non-leap years, /// and [1,366] in leap years. pub fn yearDay(self: Self) isize { const d = absDate(self.abs(), false); return d.yday + 1; } /// computes the time zone in effect at time t, returning the abbreviated /// name of the zone (such as "CET") and its offset in seconds east of UTC. pub fn zone(self: Self) ZoneDetail { const zn = self.loc.lookup(self.unixSec()); return ZoneDetail{ .name = zn.name, .offset = zn.offset, }; } /// utc returns time with the location set to UTC. fn utc(self: Self) Self { return Time{ .wall = self.wall, .ext = self.ext, .loc = &Location.utc_local, }; } fn string(self: Self, out: anytype) !void { try self.formatBuffer(out, DefaultFormat); // Format monotonic clock reading as m=±ddd.nnnnnnnnn. if ((self.wall & has_monotonic) != 0) { var m2 = @intCast(u64, self.ext); var sign: u8 = '+'; if (self.ext < 0) { sign = '-'; m2 = @intCast(u64, -self.ext); } var m1 = @divTrunc(m2, @as(u64, 1e9)); m2 = @mod(m2, @as(u64, 1e9)); var m0 = @divTrunc(m1, @as(u64, 1e9)); m1 = @mod(m1, @as(u64, 1e9)); try out.writeAll("m="); try out.writeByte(sign); var wid: usize = 0; if (m0 != 0) { try appendInt(out, @intCast(isize, m0), 0); wid = 9; } try appendInt(out, @intCast(isize, m1), wid); try out.writeByte('.'); try appendInt(out, @intCast(isize, m2), 9); } } pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { try self.string(out_stream); } /// writes into out a textual representation of the time value formatted /// according to layout, which defines the format by showing how the reference /// time, defined to be /// Mon Jan 2 15:04:05 -0700 MST 2006 /// would be displayed if it were the value; it serves as an example of the /// desired output. The same display rules will then be applied to the time /// value. /// /// A fractional second is represented by adding a period and zeros /// to the end of the seconds section of layout string, as in "15:04:05.000" /// to format a time stamp with millisecond precision. /// /// Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard /// and convenient representations of the reference time. For more information /// about the formats and the definition of the reference time, see the /// documentation for ANSIC and the other constants defined by this package. pub fn formatBuffer(self: Self, out: anytype, layout: []const u8) !void { return self.appendFormat(out, layout); } fn appendInt(stream: anytype, x: isize, width: usize) !void { var u = std.math.absCast(x); if (x < 0) { _ = try stream.write("-"); } var buf: [20]u8 = undefined; var i = buf.len; while (u >= 10) { i -= 1; const q = @divTrunc(u, 10); buf[i] = @intCast(u8, '0' + u - q * 10); u = q; } i -= 1; buf[i] = '0' + @intCast(u8, u); var w = buf.len - i; while (w < width) : (w += 1) { _ = try stream.write("0"); } const v = buf[i..]; _ = try stream.write(v); } fn formatNano(stream: anytype, nanosec: usize, n: usize, trim: bool) !void { var u = nanosec; var buf = [_]u8{0} ** 9; var start = buf.len; while (start > 0) { start -= 1; buf[start] = @intCast(u8, @mod(u, 10) + '0'); u /= 10; } var x = n; if (x > 9) { x = 9; } if (trim) { while (x > 0 and buf[x - 1] == '0') : (x -= 1) {} if (x == 0) { return; } } _ = try stream.write("."); _ = try stream.write(buf[0..x]); } /// appendFormat is like Format but appends the textual /// representation to b pub fn appendFormat(self: Self, stream: anytype, layout: []const u8) !void { const abs_value = self.abs(); const tz = self.zone(); const clock_value = self.clock(); const ddate = self.date(); var lay = layout; while (lay.len != 0) { const ctx = nextStdChunk(lay); if (ctx.prefix.len != 0) { try stream.writeAll(ctx.prefix); } lay = ctx.suffix; switch (ctx.chunk) { .none => return, .stdYear => { var y = ddate.year; if (y < 0) { y = -y; } try appendInt(stream, @mod(y, 100), 2); }, .stdLongYear => { try appendInt(stream, ddate.year, 4); }, .stdMonth => { _ = try stream.write(ddate.month.string()[0..3]); }, .stdLongMonth => { _ = try stream.write(ddate.month.string()); }, .stdNumMonth => { try appendInt(stream, @intCast(isize, @enumToInt(ddate.month)), 0); }, .stdZeroMonth => { try appendInt(stream, @intCast(isize, @enumToInt(ddate.month)), 2); }, .stdWeekDay => { const wk = self.weekday(); _ = try stream.write(wk.string()[0..3]); }, .stdLongWeekDay => { const wk = self.weekday(); _ = try stream.write(wk.string()); }, .stdDay => { try appendInt(stream, ddate.day, 0); }, .stdUnderDay => { if (ddate.day < 10) { _ = try stream.write(" "); } try appendInt(stream, ddate.day, 0); }, .stdZeroDay => { try appendInt(stream, ddate.day, 2); }, .stdHour => { try appendInt(stream, clock_value.hour, 2); }, .stdHour12 => { // Noon is 12PM, midnight is 12AM. var hr = @mod(clock_value.hour, 12); if (hr == 0) { hr = 12; } try appendInt(stream, hr, 0); }, .stdZeroHour12 => { // Noon is 12PM, midnight is 12AM. var hr = @mod(clock_value.hour, 12); if (hr == 0) { hr = 12; } try appendInt(stream, hr, 2); }, .stdMinute => { try appendInt(stream, clock_value.min, 0); }, .stdZeroMinute => { try appendInt(stream, clock_value.min, 2); }, .stdSecond => { try appendInt(stream, clock_value.sec, 0); }, .stdZeroSecond => { try appendInt(stream, clock_value.sec, 2); }, .stdPM => { if (clock_value.hour >= 12) { _ = try stream.write("PM"); } else { _ = try stream.write("AM"); } }, .stdpm => { if (clock_value.hour >= 12) { _ = try stream.write("pm"); } else { _ = try stream.write("am"); } }, .stdISO8601TZ, .stdISO8601ColonTZ, .stdISO8601SecondsTZ, .stdISO8601ShortTZ, .stdISO8601ColonSecondsTZ, .stdNumTZ, .stdNumColonTZ, .stdNumSecondsTz, .stdNumShortTZ, .stdNumColonSecondsTZ => { // Ugly special case. We cheat and take the "Z" variants // to mean "the time zone as formatted for ISO 8601". const cond = tz.offset == 0 and (ctx.chunk.eql(chunk.stdISO8601TZ) or ctx.chunk.eql(chunk.stdISO8601ColonTZ) or ctx.chunk.eql(chunk.stdISO8601SecondsTZ) or ctx.chunk.eql(chunk.stdISO8601ShortTZ) or ctx.chunk.eql(chunk.stdISO8601ColonSecondsTZ)); if (cond) { _ = try stream.write("Z"); } var z = @divTrunc(tz.offset, 60); var abs_offset = tz.offset; if (z < 0) { _ = try stream.write("-"); z = -z; abs_offset = -abs_offset; } else { _ = try stream.write("+"); } try appendInt(stream, @divTrunc(z, 60), 2); if (ctx.chunk.eql(chunk.stdISO8601ColonTZ) or ctx.chunk.eql(chunk.stdNumColonTZ) or ctx.chunk.eql(chunk.stdISO8601ColonSecondsTZ) or ctx.chunk.eql(chunk.stdISO8601ColonSecondsTZ) or ctx.chunk.eql(chunk.stdNumColonSecondsTZ)) { _ = try stream.write(":"); } if (!ctx.chunk.eql(chunk.stdNumShortTZ) and !ctx.chunk.eql(chunk.stdISO8601ShortTZ)) { try appendInt(stream, @mod(z, 60), 2); } if (ctx.chunk.eql(chunk.stdISO8601SecondsTZ) or ctx.chunk.eql(chunk.stdNumSecondsTz) or ctx.chunk.eql(chunk.stdNumColonSecondsTZ) or ctx.chunk.eql(chunk.stdISO8601ColonSecondsTZ)) { if (ctx.chunk.eql(chunk.stdNumColonSecondsTZ) or ctx.chunk.eql(chunk.stdISO8601ColonSecondsTZ)) { _ = try stream.write(":"); } try appendInt(stream, @mod(abs_offset, 60), 2); } }, .stdTZ => { if (tz.name.len != 0) { _ = try stream.write(tz.name); continue; } var z = @divTrunc(tz.offset, 60); if (z < 0) { _ = try stream.write("-"); z = -z; } else { _ = try stream.write("+"); } try appendInt(stream, @divTrunc(z, 60), 2); try appendInt(stream, @mod(z, 60), 2); }, .stdFracSecond0, .stdFracSecond9 => { try formatNano(stream, @intCast(usize, self.nanosecond()), ctx.args_shift.?, ctx.chunk.eql(chunk.stdFracSecond9)); }, else => unreachable, } } } fn parseInternal(layout: []const u8, value: []const u8, default_location: *Location, local: *Location) !Self { var alayout = layout; var avalue = value; var am_set = false; var pm_set = false; var parsed_year: isize = 0; var parsed_month: isize = -1; var parsed_day: isize = -1; var parsed_yday: isize = -1; var parsed_hour: isize = 0; var parsed_min: isize = 0; var parsed_sec: isize = 0; var parsed_nsec: isize = 0; var z: ?*Location = null; var zone_offset: isize = -1; var zone_name = ""; var lay = layout; var val = value; while (true) { const ctx = nextStdChunk(lay); const std_str = lay[ctx.prefix.len..(lay.len - ctx.suffix.len)]; val = try skip(val, ctx.prefix); if (ctx.chunk == .none) { if (val.len != 0) { return error.ExtraText; } } lay = ctx.suffix; switch (ctx.chunk) { .stdYear => { if (val.len < 2) { return error.BadValue; } const p = val[0..2]; val = val[2..]; var has_err = false; parsed_year = try std.fmt.parseInt(isize, p, 10); if (parsed_year >= 69) { // Unix time starts Dec 31 1969 in some time zones parsed_year += 1900; } else { parsed_year += 2000; } }, .stdLongYear => { if (val.len < 4 or !isDigit(val, 0)) { return error.BadValue; } const p = val[0..4]; val = val[4..]; parsed_year = try std.fmt.parseInt(isize, p, 10); }, .stdMonth => { const idx = try lookup(short_month_names, val); parsed_month = @intCast(isize, idx); val = val[short_month_names[idx].len..]; parsed_month += 1; }, .stdLongMonth => { const idx = try lookup(long_month_names, val); parsed_month = @intCast(isize, idx); val = val[long_month_names[idx].len..]; parsed_month += 1; }, .stdNumMonth, .stdZeroMonth => { const n = try getNum(val, ctx.chunk == .stdZeroMonth); parsed_month = n.value; val = n.string; }, .stdWeekDay => { const idx = try lookup(short_day_names, val); val = val[short_day_names[idx].len..]; }, .stdLongWeekDay => { const idx = try lookup(long_day_names, val); val = val[long_day_names[idx].len..]; }, .stdDay, .stdUnderDay, .stdZeroDay => { if (ctx.chunk == .stdUnderDay and val.len > 0 and val[0] == ' ') { val = val[1..]; } const n = try getNum(val, ctx.chunk == .stdZeroDay); parsed_day = n.value; val = n.string; // Note that we allow any one- or two-digit day here. // The month, day, year combination is validated after we've completed parsing }, .stdUnderYearDay, .stdZeroYearDay => { var i: usize = 0; while (i < 2) : (i += 1) { if (ctx.chunk == .stdUnderYearDay and val.len > 0 and val[0] == ' ') { val = val[1..]; } } const n = try getNum3(val, ctx.chunk == .stdZeroYearDay); parsed_yday = n.value; val = n.string; // Note that we allow any one-, two-, or three-digit year-day here. // The year-day, year combination is validated after we've completed parsing. }, .stdHour => { const n = try getNum(val, false); parsed_hour = n.value; val = n.string; if (parsed_hour < 0 or 24 <= parsed_hour) { return error.BadHourRange; } }, .stdHour12, .stdZeroHour12 => { const n = try getNum(val, ctx.chunk == .stdZeroHour12); parsed_hour = n.value; val = n.string; if (parsed_hour < 0 or 12 <= parsed_hour) { return error.BadHourRange; } }, .stdMinute, .stdZeroMinute => { const n = try getNum(val, ctx.chunk == .stdZeroMinute); parsed_min = n.value; val = n.string; if (parsed_min < 0 or 60 <= parsed_min) { return error.BadMinuteRange; } }, .stdSecond, .stdZeroSecond => { const n = try getNum(val, ctx.chunk == .stdZeroSecond); parsed_sec = n.value; val = n.string; if (parsed_sec < 0 or 60 <= parsed_sec) { return error.BadSecondRange; } if (val.len > 2 and val[0] == '.' and isDigit(val, 1)) { const ch = nextStdChunk(lay); if (ch.chunk == .stdFracSecond0 or ch.chunk == .stdFracSecond9) { // Fractional second in the layout; proceed normally break; } var f: usize = 0; while (f < val.len and isDigit(val, f)) : (f += 1) {} parsed_nsec = try parseNanoseconds(val, f); val = val[f..]; } }, .stdPM => { if (val.len < 2) { return error.BadValue; } const p = val[0..2]; val = val[2..]; if (mem.eql(u8, p, "PM")) { pm_set = true; } else if (mem.eql(u8, p, "AM")) { am_set = true; } else { return error.BadValue; } }, .stdpm => { if (val.len < 2) { return error.BadValue; } const p = val[0..2]; val = val[2..]; if (mem.eql(u8, p, "pm")) { pm_set = true; } else if (mem.eql(u8, p, "am")) { am_set = true; } else { return error.BadValue; } }, else => {}, } } return error.TODO; } /// skip removes the given prefix from value, /// treating runs of space characters as equivalent. fn skip(value: []const u8, prefix: []const u8) ![]const u8 { var v = value; var p = prefix; while (p.len > 0) { if (p[0] == ' ') { if (v.len > 0 and v[0] != ' ') { return error.BadValue; } p = cutSpace(p); v = cutSpace(v); continue; } if (v.len == 0 or v[0] != p[0]) { return error.BadValue; } p = p[1..]; v = v[1..]; } return v; } fn cutSpace(str: []const u8) []const u8 { var s = str; while (s.len > 0 and s[0] == ' ') : (s = s[1..]) {} return s; } /// add adds returns a new Time with duration added to self. pub fn add(self: Self, d: Duration) Self { var dsec = @divTrunc(d.value, @as(i64, 1e9)); var nsec_value = self.nsec() + @intCast(i32, @mod(d.value, @as(i64, 1e9))); if (nsec_value >= @as(i32, 1e9)) { dsec += 1; nsec_value -= @as(i32, 1e9); } else if (nsec_value < 0) { dsec -= 1; nsec_value += @as(i32, 1e9); } var cp = self; var t = &cp; t.wall = (t.wall & ~nsec_mask) | @intCast(u64, nsec_value); // update nsec t.addSec(dsec); if (t.wall & has_monotonic != 0) { const te = t.ext + @intCast(i64, d.value); if (d.value < 0 and te > t.ext or d.value > 0 and te < t.ext) { t.stripMono(); } else { t.ext = te; } } return cp; } /// sub returns the duration t-u. If the result exceeds the maximum (or minimum) /// value that can be stored in a Duration, the maximum (or minimum) duration /// will be returned. /// To compute t-d for a duration d, use self.add(-d). pub fn sub(self: Self, u: Self) Duration { if ((self.wall & u.wall & has_monotonic) != 0) { const te = self.ext; const ue = u.ext; var d = Duration.init(te - ue); if (d.value < 0 and te > ue) { return Duration.maxDuration; } if (d.value > 0 and te < ue) { return Duration.minDuration; } return d; } const ts = self.sec(); const us = u.sec(); const ssub = ts - us; if ((ssub < ts) != (us > 0)) { if (self.before(u)) { return Duration.minDuration; } return Duration.maxDuration; } if ((ssub < @divFloor(Duration.minDuration.value, Duration.Second.value)) or (ssub > @divFloor(Duration.maxDuration.value, Duration.Second.value))) { if (self.before(u)) { return Duration.minDuration; } return Duration.maxDuration; } var ssec: i64 = 0; var nnsec: i64 = 0; var d: i64 = 0; ssec = ssub * Duration.Second.value; nnsec = @intCast(i64, self.nsec() - u.nsec()); if ((d > ssec) != (nnsec > 0)) { if (self.before(u)) { return Duration.minDuration; } return Duration.maxDuration; } return Duration.init(d); } fn div(self: Self, d: Duration) divResult { var neg = false; var nsec_value = self.nsec(); var sec_value = self.sec(); if (sec_value < 0) { // Operate on absolute value. neg = true; sec_value = -sec_value; if (nsec_value < 0) { nsec_value += @as(i32, 1e9); sec_value -= 1; } } var res = divResult{ .qmod = 0, .r = Duration.init(0) }; if (d.value < @mod(Duration.Second.value, d.value * 2)) { res.qmod = @intCast(isize, @divTrunc(nsec_value, @intCast(i32, d.value))) & 1; res.r = Duration.init(@intCast(i64, @mod(nsec_value, @intCast(i32, d.value)))); } else if (@mod(d.value, Duration.Second.value) == 0) { const d1 = @divTrunc(d.value, Duration.Second.value); res.qmod = @intCast(isize, @divTrunc(sec_value, d1)) & 1; res.r = Duration.init(@mod(sec_value, d1) * Duration.Second.value + @intCast(i64, nsec_value)); } else { var s = @intCast(u64, sec_value); var tmp = (s >> 32) * u64(1e9); var u_1 = tmp >> 32; var u_0 = tmp << 32; tmp = (s & 0xFFFFFFFF) * u64(1e9); var u_0x = u_0; u_0 = u_0 + tmp; if (u_0 < u_0x) { u_1 += 1; } u_0x = u_0; u_0 = u_0 + @intCast(u64, nsec_value); if (u_0 < u_0x) { u_1 += 1; } // Compute remainder by subtracting r<<k for decreasing k. // Quotient parity is whether we subtract on last round. var d1 = @intCast(u64, d.value); while ((d1 >> 63) != 1) { d1 <<= 1; } var d0 = u64(0); while (true) { res.qmod = 0; if (u_1 > d1 or u_1 == d1 and u_0 >= d0) { res.qmod = 1; u_0x = u_0; u_0 = u_0 - d0; if (u_0 > u_0x) { u_1 -= 1; } u_1 -= d1; if (d1 == 0 and d0 == @intCast(u64, d.value)) { break; } d0 >>= 1; d0 |= (d1 & 1) << 63; d1 >>= 1; } res.r = Duration.init(@intCast(i64, u_0)); } if (neg and res.r.value != 0) { // If input was negative and not an exact multiple of d, we computed q, r such that // q*d + r = -t // But the right answers are given by -(q-1), d-r: // q*d + r = -t // -q*d - r = t // -(q-1)*d + (d - r) = t res.qmod ^= 1; res.r = Duration.init(d.value - res.r.value); } return res; } return res; } // these are utility functions that I ported from // github.com/jinzhu/now pub fn beginningOfMinute(self: Self) Self { //TODO: this needs truncate to be implemented. return self; } pub fn beginningOfHour(self: Self) Self { const d = self.date(); const c = self.clock(); return context.date( d.year, @intCast(isize, @enumToInt(d.month)), d.day, c.hour, 0, 0, 0, self.loc, ); } pub fn beginningOfDay(self: Self) Self { const d = self.date(); return context.date( d.year, @intCast(isize, @enumToInt(d.month)), d.day, 0, 0, 0, 0, self.loc, ); } pub fn beginningOfWeek(self: Self) Self { var t = self.beginningOfDay(); const week_day = @intCast(isize, @enumToInt(self.weekday())); return self.addDate(0, 0, -week_day); } pub fn beginningOfMonth(self: Self) Self { var d = self.date(); return context.date( d.year, @intCast(isize, @enumToInt(d.month)), 1, 0, 0, 0, 0, self.loc, ); } pub fn endOfMonth(self: Self) Self { return self.beginningOfMonth().addDate(0, 1, 0) .add(Duration.init(-Duration.Hour.value)); } fn current_month() [4][7]usize { return [4][7]usize{ [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, }; } pub fn calendar() void { var ma = [_][7]usize{ [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, [_]usize{0} ** 7, }; var m = ma[0..]; var local = Location.getLocal(); var current_time = now(&local); const today = current_time.day(); var begin = current_time.beginningOfMonth(); var end = current_time.endOfMonth(); const x = begin.date(); const y = end.date(); var i: usize = 1; var at = @enumToInt(begin.weekday()); var mx: usize = 0; var d: usize = 1; while (mx < m.len) : (mx += 1) { var a = m[mx][0..]; while (at < a.len and d <= @intCast(usize, y.day)) : (at += 1) { a[at] = d; d += 1; } at = 0; } warn("\n", .{}); for (short_days) |ds| { warn("{s} |", .{ds}); } warn("\n", .{}); for (m) |mv, idx| { for (mv) |dv, vx| { if (idx != 0 and vx == 0 and dv == 0) { // The pre allocated month buffer is lage enough to span 7 // weeks. // // we know for a fact at the first week must have at least 1 // date,any other week that start with 0 date means we are // past the end of the calendar so no need to keep printing. return; } if (dv == 0) { warn(" |", .{}); continue; } if (dv == @intCast(usize, today)) { if (dv < 10) { warn(" *{} |", .{dv}); } else { warn("*{} |", .{dv}); } } else { if (dv < 10) { warn(" {} |", .{dv}); } else { warn(" {} |", .{dv}); } } } warn("\n", .{}); } warn("\n", .{}); } }; const ZoneDetail = struct { name: []const u8, offset: isize, }; pub const Duration = struct { value: i64, pub const Nanosecond = init(1); pub const Microsecond = init(1000 * Nanosecond.value); pub const Millisecond = init(1000 * Microsecond.value); pub const Second = init(1000 * Millisecond.value); pub const Minute = init(60 * Second.value); pub const Hour = init(60 * Minute.value); const minDuration = init(-1 << 63); const maxDuration = init((1 << 63) - 1); const fracRes = struct { nw: usize, nv: u64, }; // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the // tail of buf, omitting trailing zeros. It omits the decimal // point too when the fraction is 0. It returns the index where the // output bytes begin and the value v/10**prec. pub fn init(v: i64) Duration { return Duration{ .value = v }; } fn fmtFrac(buf: []u8, value: u64, prec: usize) fracRes { // Omit trailing zeros up to and including decimal point. var w = buf.len; var v = value; var i: usize = 0; var print: bool = false; while (i < prec) : (i += 1) { const digit = @mod(v, 10); print = print or digit != 0; if (print) { w -= 1; buf[w] = @intCast(u8, digit) + '0'; } v /= 10; } if (print) { w -= 1; buf[w] = '.'; } return fracRes{ .nw = w, .nv = v }; } fn fmtInt(buf: []u8, value: u64) usize { var w = buf.len; var v = value; if (v == 0) { w -= 1; buf[w] = '0'; } else { while (v > 0) { w -= 1; buf[w] = @intCast(u8, @mod(v, 10)) + '0'; v /= 10; } } return w; } pub fn string(self: Duration) []const u8 { var buf: [32]u8 = undefined; var w = buf.len; var u = @intCast(u64, self.value); const neg = self.value < 0; if (neg) { u = @intCast(u64, -self.value); } if (u < @intCast(u64, Second.value)) { // Special case: if duration is smaller than a second, // use smaller units, like 1.2ms var prec: usize = 0; w -= 1; buf[w] = 's'; w -= 1; if (u == 0) { const s = "0s"; return s[0..]; } else if (u < @intCast(u64, Microsecond.value)) { // print nanoseconds prec = 0; buf[w] = 'n'; } else if (u < @intCast(u64, Millisecond.value)) { // print microseconds prec = 3; // U+00B5 'µ' micro sign == 0xC2 0xB5 w -= 1; mem.copy(u8, buf[w..], "µ"); } else { prec = 6; buf[w] = 'm'; } const r = fmtFrac(buf[0..w], u, prec); w = r.nw; u = r.nv; w = fmtInt(buf[0..w], u); } else { w -= 1; buf[w] = 's'; const r = fmtFrac(buf[0..w], u, 9); w = r.nw; u = r.nv; w = fmtInt(buf[0..w], @mod(u, 60)); u /= 60; // u is now integer minutes if (u > 0) { w -= 1; buf[w] = 'm'; w = fmtInt(buf[0..w], @mod(u, 60)); u /= 60; // u is now integer hours // Stop at hours because days can be different lengths. if (u > 0) { w -= 1; buf[w] = 'h'; w = fmtInt(buf[0..w], u); } } } if (neg) { w -= 1; buf[w] = '-'; } return buf[w..]; } pub fn format( self: Duration, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { try out_stream(context, self.string()); } /// nanoseconds returns the duration as an integer nanosecond count. pub fn nanoseconds(self: Duration) i64 { return self.value; } // These methods return float64 because the dominant // use case is for printing a floating point number like 1.5s, and // a truncation to integer would make them not useful in those cases. // Splitting the integer and fraction ourselves guarantees that // converting the returned float64 to an integer rounds the same // way that a pure integer conversion would have, even in cases // where, say, float64(d.Nanoseconds())/1e9 would have rounded // differently. /// Seconds returns the duration as a floating point number of seconds. pub fn seconds(self: Duration) f64 { const sec = @divTrunc(self.value, Second.value); const nsec = @mod(self.value, Second.value); return @intToFloat(f64, sec) + @intToFloat(f64, nsec) / 1e9; } /// Minutes returns the duration as a floating point number of minutes. pub fn minutes(self: Duration) f64 { const min = @divTrunc(self.value, Minute.value); const nsec = @mod(self.value, Minute.value); return @intToFloat(f64, min) + @intToFloat(f64, nsec) / (60 * 1e9); } // Hours returns the duration as a floating point number of hours. pub fn hours(self: Duration) f64 { const hour = @divTrunc(self.value, Hour.value); const nsec = @mod(self.value, Hour.value); return @intToFloat(f64, hour) + @intToFloat(f64, nsec) / (60 * 60 * 1e9); } /// Truncate returns the result of rounding d toward zero to a multiple of m. /// If m <= 0, Truncate returns d unchanged. pub fn truncate(self: Duration, m: Duration) Duration { if (m.value <= 0) { return self; } return init(self.value - @mod(d.value, m.value)); } // lessThanHalf reports whether x+x < y but avoids overflow, // assuming x and y are both positive (Duration is signed). fn lessThanHalf(self: Duration, m: Duration) bool { const x = @intCast(u64, self.value); return x + x < @intCast(u64, m.value); } // Round returns the result of rounding d to the nearest multiple of m. // The rounding behavior for halfway values is to round away from zero. // If the result exceeds the maximum (or minimum) // value that can be stored in a Duration, // Round returns the maximum (or minimum) duration. // If m <= 0, Round returns d unchanged. pub fn round(self: Duration, m: Duration) Duration { if (v.value <= 0) { return d; } var r = init(@mod(self.value, m.value)); if (self.value < 0) { r.value = -r.value; if (r.lessThanHalf(m)) { return init(self.value + r.value); } const d = self.value - m.value + r.value; if (d < self.value) { return init(d); } return init(minDuration); } if (r.lessThanHalf(m)) { return init(self.value - r.value); } const d = self.value + m.value - r.value; if (d > self.value) { return init(d); } return init(maxDuration); } }; const normRes = struct { hi: isize, lo: isize, }; // norm returns nhi, nlo such that // hi * base + lo == nhi * base + nlo // 0 <= nlo < base fn norm(i: isize, o: isize, base: isize) normRes { var hi = i; var lo = o; if (lo < 0) { const n = @divTrunc(-lo - 1, base) + 1; hi -= n; lo += (n * base); } if (lo >= base) { const n = @divTrunc(lo, base); hi += n; lo -= (n * base); } return normRes{ .hi = hi, .lo = lo }; } /// date returns the Time corresponding to /// yyyy-mm-dd hh:mm:ss + nsec nanoseconds /// in the appropriate zone for that time in the given location. /// /// The month, day, hour, min, sec, and nsec values may be outside /// their usual ranges and will be normalized during the conversion. /// For example, October 32 converts to November 1. /// /// A daylight savings time transition skips or repeats times. /// For example, in the United States, March 13, 2011 2:15am never occurred, /// while November 6, 2011 1:15am occurred twice. In such cases, the /// choice of time zone, and therefore the time, is not well-defined. /// Date returns a time that is correct in one of the two zones involved /// in the transition, but it does not guarantee which. /// /// Date panics if loc is nil. pub fn date( year: isize, month: isize, day: isize, hour: isize, min: isize, sec: isize, nsec: isize, loc: *Location, ) Time { var v_year = year; var v_day = day; var v_hour = hour; var v_min = min; var v_sec = sec; var v_nsec = nsec; var v_loc = loc; // Normalize month, overflowing into year var m = month - 1; var r = norm(v_year, m, 12); v_year = r.hi; m = r.lo; var v_month = @intToEnum(Month, @intCast(usize, m) + 1); // Normalize nsec, sec, min, hour, overflowing into day. r = norm(sec, v_nsec, 1e9); v_sec = r.hi; v_nsec = r.lo; r = norm(min, v_sec, 60); v_min = r.hi; v_sec = r.lo; r = norm(v_hour, v_min, 60); v_hour = r.hi; v_min = r.lo; r = norm(v_day, v_hour, 24); v_day = r.hi; v_hour = r.lo; var y = @intCast(u64, @intCast(i64, v_year) - absolute_zero_year); // Compute days since the absolute epoch. // Add in days from 400-year cycles. var n = @divTrunc(y, 400); y -= (400 * n); var d = days_per_400_years * n; // Add in 100-year cycles. n = @divTrunc(y, 100); y -= 100 * n; d += days_per_100_years * n; // Add in 4-year cycles. n = @divTrunc(y, 4); y -= 4 * n; d += days_per_4_years * n; // Add in non-leap years. n = y; d += 365 * n; // Add in days before this month. d += @intCast(u64, daysBefore[@enumToInt(v_month) - 1]); if (isLeap(v_year) and @enumToInt(v_month) >= @enumToInt(Month.March)) { d += 1; // February 29 } // Add in days before today. d += @intCast(u64, v_day - 1); // Add in time elapsed today. var abs = d * seconds_per_day; abs += @intCast(u64, hour * seconds_per_hour + min * seconds_per_minute + sec); var unix_value: i64 = undefined; _ = @addWithOverflow(i64, @bitCast(i64, abs), (absolute_to_internal + internal_to_unix), &unix_value); // Look for zone offset for t, so we can adjust to UTC. // The lookup function expects UTC, so we pass t in the // hope that it will not be too close to a zone transition, // and then adjust if it is. var zn = loc.lookup(unix_value); if (zn.offset != 0) { const utc_value = unix_value - @intCast(i64, zn.offset); if (utc_value < zn.start) { zn = loc.lookup(zn.start - 1); } else if (utc_value >= zn.end) { zn = loc.lookup(zn.end); } unix_value -= @intCast(i64, zn.offset); } return unixTimeWithLoc(unix_value, @intCast(i32, v_nsec), loc); } /// ISO 8601 year and week number pub const ISOWeek = struct { year: isize, week: isize, }; pub const Clock = struct { hour: isize, min: isize, sec: isize, fn absClock(abs: u64) Clock { var sec = @intCast(isize, abs % seconds_per_day); var hour = @divTrunc(sec, seconds_per_hour); sec -= (hour * seconds_per_hour); var min = @divTrunc(sec, seconds_per_minute); sec -= (min * seconds_per_minute); return Clock{ .hour = hour, .min = min, .sec = sec }; } }; fn absWeekday(abs: u64) Weekday { const s = @mod(abs + @intCast(u64, @enumToInt(Weekday.Monday)) * seconds_per_day, seconds_per_week); const w = s / seconds_per_day; return @intToEnum(Weekday, @intCast(usize, w)); } pub const Month = enum(usize) { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12, pub fn string(self: Month) []const u8 { const m = @enumToInt(self); if (@enumToInt(Month.January) <= m and m <= @enumToInt(Month.December)) { return months[m - 1]; } unreachable; } pub fn format( self: Month, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { try out_stream.writeAll(self.string()); } }; pub const DateDetail = struct { year: isize, month: Month, day: isize, yday: isize, }; fn absDate(abs: u64, full: bool) DateDetail { var details: DateDetail = undefined; // Split into time and day. var d = abs / seconds_per_day; // Account for 400 year cycles. var n = d / days_per_400_years; var y = 400 * n; d -= days_per_400_years * n; // Cut off 100-year cycles. // The last cycle has one extra leap year, so on the last day // of that year, day / days_per_100_years will be 4 instead of 3. // Cut it back down to 3 by subtracting n>>2. n = d / days_per_100_years; n -= n >> 2; y += 100 * n; d -= days_per_100_years * n; // Cut off 4-year cycles. // The last cycle has a missing leap year, which does not // affect the computation. n = d / days_per_4_years; y += 4 * n; d -= days_per_4_years * n; // Cut off years within a 4-year cycle. // The last year is a leap year, so on the last day of that year, // day / 365 will be 4 instead of 3. Cut it back down to 3 // by subtracting n>>2. n = d / 365; n -= n >> 2; y += n; d -= 365 * n; details.year = @intCast(isize, @intCast(i64, y) + absolute_zero_year); details.yday = @intCast(isize, d); if (!full) { return details; } details.day = details.yday; if (isLeap(details.year)) { if (details.day > (31 + 29 - 1)) { // After leap day; pretend it wasn't there. details.day -= 1; } else if (details.day == (31 + 29 - 1)) { // Leap day. details.month = Month.February; details.day = 29; return details; } } // Estimate month on assumption that every month has 31 days. // The estimate may be too low by at most one month, so adjust. var month = @intCast(usize, details.day) / @as(usize, 31); const end = daysBefore[month + 1]; var begin: isize = 0; if (details.day >= end) { month += 1; begin = end; } else { begin = daysBefore[month]; } month += 1; details.day = details.day - begin + 1; details.month = @intToEnum(Month, month); return details; } // daysBefore[m] counts the number of days in a non-leap year // before month m begins. There is an entry for m=12, counting // the number of days before January of next year (365). const daysBefore = [_]isize{ 0, 31, 31 + 28, 31 + 28 + 31, 31 + 28 + 31 + 30, 31 + 28 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31, }; fn isLeap(year: isize) bool { return @mod(year, 4) == 0 and (@mod(year, 100) != 0 or @mod(year, 100) == 0); } const months = [_][]const u8{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", }; pub const Weekday = enum(usize) { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, pub fn string(self: Weekday) []const u8 { const d = @enumToInt(self); if (@enumToInt(Weekday.Sunday) <= d and d <= @enumToInt(Weekday.Saturday)) { return days[d]; } unreachable; } pub fn format( self: Weekday, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { try out_stream(context, self.string()); } }; const days = [_][]const u8{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; /// now returns the current local time and assigns the retuned time to use /// local as location data. pub fn now(local: *Location) Time { const bt = timeNow(); const sec = (bt.sec + unix_to_internal) - min_wall; if ((@intCast(u64, sec) >> 33) != 0) { return Time{ .wall = @intCast(u64, bt.nsec), .ext = sec + min_wall, .loc = local, }; } return Time{ .wall = has_monotonic | (@intCast(u64, sec) << nsec_shift) | @intCast(u64, bt.nsec), .ext = @intCast(i64, bt.mono), .loc = local, }; } fn unixTime(sec: i64, nsec: i32) Time { var local = getLocal(); return unixTimeWithLoc(sec, nsec, local); } fn unixTimeWithLoc(sec: i64, nsec: i32, loc: *Location) Time { return Time{ .wall = @intCast(u64, nsec), .ext = sec + unix_to_internal, .loc = loc, }; } pub fn unix(sec: i64, nsec: i64, local: *Location) Time { var x = sec; var y = nsec; if (nsec < 0 or nsec >= @as(i64, 1e9)) { const n = @divTrunc(nsec, @as(i64, 1e9)); x += n; y -= (n * @as(i64, 1e9)); if (y < 0) { y += @as(i64, 1e9); x -= 1; } } return unixTimeWithLoc(x, @intCast(i32, y), local); } const bintime = struct { sec: isize, nsec: isize, mono: u64, }; fn timeNow() bintime { switch (builtin.os.tag) { .linux => { var ts: std.os.timespec = undefined; const err = std.os.clock_gettime(std.os.CLOCK_REALTIME, &ts) catch unreachable; return bintime{ .sec = ts.tv_sec, .nsec = ts.tv_nsec, .mono = clockNative() }; }, .macos, .ios => { var tv: darwin.timeval = undefined; var err = darwin.gettimeofday(&tv, null); assert(err == 0); return bintime{ .sec = tv.tv_sec, .nsec = tv.tv_usec, .mono = clockNative() }; }, else => @compileError("Unsupported OS"), } } const clockNative = switch (builtin.os.tag) { .windows => clockWindows, .linux => clockLinux, .macos, .ios => clockDarwin, else => @compileError("Unsupported OS"), }; fn clockWindows() u64 { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); assert(err != windows.FALSE); return @intCast(u64, result); } fn clockDarwin() u64 { return darwin.mach_absolute_time(); } fn clockLinux() u64 { var ts: std.os.timespec = undefined; var result = std.os.linux.clock_gettime(std.os.CLOCK_MONOTONIC, &ts); assert(std.os.linux.getErrno(result) == 0); return @intCast(u64, ts.tv_sec) * @as(u64, 1000000000) + @intCast(u64, ts.tv_nsec); } // These are predefined layouts for use in Time.Format and time.Parse. // The reference time used in the layouts is the specific time: // Mon Jan 2 15:04:05 MST 2006 // which is Unix time 1136239445. Since MST is GMT-0700, // the reference time can be thought of as // 01/02 03:04:05PM '06 -0700 // To define your own format, write down what the reference time would look // like formatted your way; see the values of constants like ANSIC, // StampMicro or Kitchen for examples. The model is to demonstrate what the // reference time looks like so that the Format and Parse methods can apply // the same transformation to a general time value. // // Some valid layouts are invalid time values for time.Parse, due to formats // such as _ for space padding and Z for zone information. // // Within the format string, an underscore _ represents a space that may be // replaced by a digit if the following number (a day) has two digits; for // compatibility with fixed-width Unix time formats. // // A decimal point followed by one or more zeros represents a fractional // second, printed to the given number of decimal places. A decimal point // followed by one or more nines represents a fractional second, printed to // the given number of decimal places, with trailing zeros removed. // When parsing (only), the input may contain a fractional second // field immediately after the seconds field, even if the layout does not // signify its presence. In that case a decimal point followed by a maximal // series of digits is parsed as a fractional second. // // Numeric time zone offsets format as follows: // -0700 ±hhmm // -07:00 ±hh:mm // -07 ±hh // Replacing the sign in the format with a Z triggers // the ISO 8601 behavior of printing Z instead of an // offset for the UTC zone. Thus: // Z0700 Z or ±hhmm // Z07:00 Z or ±hh:mm // Z07 Z or ±hh // // The recognized day of week formats are "Mon" and "Monday". // The recognized month formats are "Jan" and "January". // // Text in the format string that is not recognized as part of the reference // time is echoed verbatim during Format and expected to appear verbatim // in the input to Parse. // // The executable example for Time.Format demonstrates the working // of the layout string in detail and is a good reference. // // Note that the RFC822, RFC850, and RFC1123 formats should be applied // only to local times. Applying them to UTC times will use "UTC" as the // time zone abbreviation, while strictly speaking those RFCs require the // use of "GMT" in that case. // In general RFC1123Z should be used instead of RFC1123 for servers // that insist on that format, and RFC3339 should be preferred for new protocols. // RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; // when used with time.Parse they do not accept all the time formats // permitted by the RFCs. // The RFC3339Nano format removes trailing zeros from the seconds field // and thus may not sort correctly once formatted. pub const ANSIC = "Mon Jan _2 15:04:05 2006"; pub const UnixDate = "Mon Jan _2 15:04:05 MST 2006"; pub const RubyDate = "Mon Jan 02 15:04:05 -0700 2006"; pub const RFC822 = "02 Jan 06 15:04 MST"; pub const RFC822Z = "02 Jan 06 15:04 -0700"; // RFC822 with numeric zone pub const RFC850 = "Monday, 02-Jan-06 15:04:05 MST"; pub const RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"; pub const RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700"; // RFC1123 with numeric zone pub const RFC3339 = "2006-01-02T15:04:05Z07:00"; pub const RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"; pub const Kitchen = "3:04PM"; // Handy time stamps. pub const Stamp = "Jan _2 15:04:05"; pub const StampMilli = "Jan _2 15:04:05.000"; pub const StampMicro = "Jan _2 15:04:05.000000"; pub const StampNano = "Jan _2 15:04:05.000000000"; pub const DefaultFormat = "2006-01-02 15:04:05.999999999 -0700 MST"; pub const chunk = enum { none, stdLongMonth, // "January" stdMonth, // "Jan" stdNumMonth, // "1" stdZeroMonth, // "01" stdLongWeekDay, // "Monday" stdWeekDay, // "Mon" stdDay, // "2" stdUnderDay, // "_2" stdZeroDay, // "02" stdUnderYearDay, // "__2" stdZeroYearDay, // "002" stdHour, // "15" stdHour12, // "3" stdZeroHour12, // "03" stdMinute, // "4" stdZeroMinute, // "04" stdSecond, // "5" stdZeroSecond, // "05" stdLongYear, // "2006" stdYear, // "06" stdPM, // "PM" stdpm, // "pm" stdTZ, // "MST" stdISO8601TZ, // "Z0700" // prints Z for UTC stdISO8601SecondsTZ, // "Z070000" stdISO8601ShortTZ, // "Z07" stdISO8601ColonTZ, // "Z07:00" // prints Z for UTC stdISO8601ColonSecondsTZ, // "Z07:00:00" stdNumTZ, // "-0700" // always numeric stdNumSecondsTz, // "-070000" stdNumShortTZ, // "-07" // always numeric stdNumColonTZ, // "-07:00" // always numeric stdNumColonSecondsTZ, // "-07:00:00" stdFracSecond0, // ".0", ".00", ... , trailing zeros included stdFracSecond9, // ".9", ".99", ..., trailing zeros omitted stdNeedDate, // need month, day, year stdNeedClock, // need hour, minute, second stdArgShift, // extra argument in high bits, above low stdArgShift fn eql(self: chunk, other: chunk) bool { return @enumToInt(self) == @enumToInt(other); } }; // startsWithLowerCase reports whether the string has a lower-case letter at the beginning. // Its purpose is to prevent matching strings like "Month" when looking for "Mon". fn startsWithLowerCase(str: []const u8) bool { if (str.len == 0) { return false; } const c = str[0]; return 'a' <= c and c <= 'z'; } pub const chunkResult = struct { prefix: []const u8, suffix: []const u8, chunk: chunk, args_shift: ?usize, }; const std0x = [_]chunk{ chunk.stdZeroMonth, chunk.stdZeroDay, chunk.stdZeroHour12, chunk.stdZeroMinute, chunk.stdZeroSecond, chunk.stdYear, }; pub fn nextStdChunk(layout: []const u8) chunkResult { var i: usize = 0; while (i < layout.len) : (i += 1) { switch (layout[i]) { 'J' => { // January, Jan if ((layout.len >= i + 3) and mem.eql(u8, layout[i .. i + 3], "Jan")) { if ((layout.len >= i + 7) and mem.eql(u8, layout[i .. i + 7], "January")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdLongMonth, .suffix = layout[i + 7 ..], .args_shift = null, }; } if (!startsWithLowerCase(layout[i + 3 ..])) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdMonth, .suffix = layout[i + 3 ..], .args_shift = null, }; } } }, 'M' => { // Monday, Mon, MST if (layout.len >= 1 + 3) { if (mem.eql(u8, layout[i .. i + 3], "Mon")) { if ((layout.len >= i + 6) and mem.eql(u8, layout[i .. i + 6], "Monday")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdLongWeekDay, .suffix = layout[i + 6 ..], .args_shift = null, }; } if (!startsWithLowerCase(layout[i + 3 ..])) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdWeekDay, .suffix = layout[i + 3 ..], .args_shift = null, }; } } if (mem.eql(u8, layout[i .. i + 3], "MST")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdTZ, .suffix = layout[i + 3 ..], .args_shift = null, }; } } }, '0' => { // 01, 02, 03, 04, 05, 06, 002 if (layout.len >= i + 2 and '1' <= layout[i + 1] and layout[i + 1] <= '6') { const x = layout[i + 1] - '1'; return chunkResult{ .prefix = layout[0..i], .chunk = std0x[x], .suffix = layout[i + 2 ..], .args_shift = null, }; } if (layout.len >= i + 3 and layout[i + 1] == '0' and layout[i + 2] == '2') { return chunkResult{ .prefix = layout[0..i], .chunk = .stdZeroYearDay, .suffix = layout[i + 3 ..], .args_shift = null, }; } }, '1' => { // 15, 1 if (layout.len >= i + 2 and layout[i + 1] == '5') { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdHour, .suffix = layout[i + 2 ..], .args_shift = null, }; } return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumMonth, .suffix = layout[i + 1 ..], .args_shift = null, }; }, '2' => { // 2006, 2 if (layout.len >= i + 4 and mem.eql(u8, layout[i .. i + 4], "2006")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdLongYear, .suffix = layout[i + 4 ..], .args_shift = null, }; } return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdDay, .suffix = layout[i + 1 ..], .args_shift = null, }; }, '_' => { // _2, _2006, __2 if (layout.len >= i + 4 and layout[i + 1] == '2') { //_2006 is really a literal _, followed by stdLongYear if (layout.len >= i + 5 and mem.eql(u8, layout[i + 1 .. i + 5], "2006")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdLongYear, .suffix = layout[i + 5 ..], .args_shift = null, }; } return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdUnderDay, .suffix = layout[i + 2 ..], .args_shift = null, }; } if (layout.len >= i + 3 and layout[i + 1] == '_' and layout[i + 2] == '2') { return chunkResult{ .prefix = layout[0..i], .chunk = .stdUnderYearDay, .suffix = layout[i + 3 ..], .args_shift = null, }; } }, '3' => { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdHour12, .suffix = layout[i + 1 ..], .args_shift = null, }; }, '4' => { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdMinute, .suffix = layout[i + 1 ..], .args_shift = null, }; }, '5' => { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdSecond, .suffix = layout[i + 1 ..], .args_shift = null, }; }, 'P' => { // PM if (layout.len >= i + 2 and layout[i + 1] == 'M') { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdPM, .suffix = layout[i + 2 ..], .args_shift = null, }; } }, 'p' => { // pm if (layout.len >= i + 2 and layout[i + 1] == 'm') { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdpm, .suffix = layout[i + 2 ..], .args_shift = null, }; } }, '-' => { if (layout.len >= i + 7 and mem.eql(u8, layout[i .. i + 7], "-070000")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumSecondsTz, .suffix = layout[i + 7 ..], .args_shift = null, }; } if (layout.len >= i + 9 and mem.eql(u8, layout[i .. i + 9], "-07:00:00")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumColonSecondsTZ, .suffix = layout[i + 9 ..], .args_shift = null, }; } if (layout.len >= i + 5 and mem.eql(u8, layout[i .. i + 5], "-0700")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumTZ, .suffix = layout[i + 5 ..], .args_shift = null, }; } if (layout.len >= i + 6 and mem.eql(u8, layout[i .. i + 6], "-07:00")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumColonTZ, .suffix = layout[i + 6 ..], .args_shift = null, }; } if (layout.len >= i + 3 and mem.eql(u8, layout[i .. i + 3], "-07")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdNumShortTZ, .suffix = layout[i + 3 ..], .args_shift = null, }; } }, 'Z' => { // Z070000, Z07:00:00, Z0700, Z07:00, if (layout.len >= i + 7 and mem.eql(u8, layout[i .. i + 7], "Z070000")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdISO8601SecondsTZ, .suffix = layout[i + 7 ..], .args_shift = null, }; } if (layout.len >= i + 9 and mem.eql(u8, layout[i .. i + 9], "Z07:00:00")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdISO8601ColonSecondsTZ, .suffix = layout[i + 9 ..], .args_shift = null, }; } if (layout.len >= i + 5 and mem.eql(u8, layout[i .. i + 5], "Z0700")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdISO8601TZ, .suffix = layout[i + 5 ..], .args_shift = null, }; } if (layout.len >= i + 6 and mem.eql(u8, layout[i .. i + 6], "Z07:00")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdISO8601ColonTZ, .suffix = layout[i + 6 ..], .args_shift = null, }; } if (layout.len >= i + 3 and mem.eql(u8, layout[i .. i + 3], "Z07")) { return chunkResult{ .prefix = layout[0..i], .chunk = chunk.stdISO8601ShortTZ, .suffix = layout[i + 6 ..], .args_shift = null, }; } }, '.' => { // .000 or .999 - repeated digits for fractional seconds. if (i + 1 < layout.len and (layout[i + 1] == '0' or layout[i + 1] == '9')) { const ch = layout[i + 1]; var j = i + 1; while (j < layout.len and layout[j] == ch) : (j += 1) {} if (!isDigit(layout, j)) { var st = chunk.stdFracSecond0; if (layout[i + 1] == '9') { st = chunk.stdFracSecond9; } return chunkResult{ .prefix = layout[0..i], .chunk = st, .suffix = layout[j..], .args_shift = j - (i + 1), }; } } }, else => {}, } } return chunkResult{ .prefix = layout, .chunk = chunk.none, .suffix = "", .args_shift = null, }; } fn isDigit(s: []const u8, i: usize) bool { if (s.len <= i) { return false; } const c = s[i]; return '0' <= c and c <= '9'; } const long_day_names = [_][]const u8{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; const short_day_names = [_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", }; const short_month_names = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; const long_month_names = [_][]const u8{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", }; // match reports whether s1 and s2 match ignoring case. // It is assumed s1 and s2 are the same length. fn match(s1: []const u8, s2: []const u8) bool { if (s1.len != s2.len) { return false; } var i: usize = 0; while (i < s1.len) : (i += 1) { var c1 = s1[i]; var c2 = s2[i]; if (c1 != c2) { c1 |= ('a' - 'A'); c2 |= ('a' - 'A'); if (c1 != c2 or c1 < 'a' or c1 > 'z') { return false; } } } return true; } fn lookup(tab: []const []const u8, val: []const u8) !usize { for (tab) |v, i| { if (val.len >= v.len and match(val[0..v.len], v)) { return i; } } return error.BadValue; } const Number = struct { value: isize, string: []const u8, }; // getnum parses s[0:1] or s[0:2] (fixed forces s[0:2]) // as a decimal integer and returns the integer and the // remainder of the string. fn getNum(s: []const u8, fixed: bool) !Number { if (!isDigit(s, 0)) { return error.BadData; } if (!isDigit(s, 1)) { if (fixed) { return error.BadData; } return Number{ .value = @intCast(isize, s[0]) - '0', .string = s[1..], }; } const n = (@intCast(isize, s[0]) - '0') * 10 + (@intCast(isize, s[1]) - '0'); return Number{ .value = n, .string = s[1..], }; } // getnum3 parses s[0:1], s[0:2], or s[0:3] (fixed forces s[0:3]) // as a decimal integer and returns the integer and the remainder // of the string. fn getNum3(s: []const u8, fixed: bool) !Number { var n: isize = 0; var i: usize = 0; while (i < 3 and isDigit(s, i)) : (i += 1) { n = n * 10 + @intCast(isize, s[i] - '0'); } if (i == 0 or fixed and i != 3) { return error.BadData; } return Number{ .value = n, .string = s[i..], }; } fn parseNanoseconds(value: []const u8, nbytes: usize) !isize { if (value[0] != '.') { return error.BadData; } var ns = try std.fmt.parseInt(isize, value[1..nbytes], 10); const nf = @intToFloat(f64, ns); if (nf < 0 or 1e9 <= nf) { return error.BadFractionalRange; } const scale_digits = 10 - nbytes; var i: usize = 0; while (i < scale_digits) : (i += 1) { ns *= 10; } return ns; } const Fraction = struct { x: 164, scale: f64, rem: []const u8, }; fn leadingFraction(s: []const u8) !Fraction { var i: usize = 0; var scale: f64 = 1; var overflow = false; while (i < s.len) : (i += 1) { //TODO(gernest): finish leadingFraction } }
src/time.zig
const std = @import("std"); const c = @cImport(@cInclude("vulkan/vulkan.h")); const Result = enum(i32) { Success = @enumToInt(c.VkResult.VK_SUCCESS), NotReady = @enumToInt(c.VkResult.VK_NOT_READY), Timeout = @enumToInt(c.VkResult.VK_TIMEOUT), EventSet = @enumToInt(c.VkResult.VK_EVENT_SET), EventReset = @enumToInt(c.VkResult.VK_EVENT_RESET), Incomplete = @enumToInt(c.VkResult.VK_INCOMPLETE), Suboptimal = 1000001003, ThreadIdle = 1000268000, ThreadDone = 1000268001, }; const Error = error { InvalidArguments, OutOfHostMemory, OutOfDeviceMemory, InitializationFailed, DeviceLost, MemoryMapFailed, LayerNotPresent, ExtensionNotPresent, FeatureNotPresent, IncompatibleDriver, TooManyObjects, FormatNotSupported, FragmentedPool, Unknown, OutOfPoolMemory, InvalidExternalHandle, Fragmentation, InvalidOpaqueCaptureAddress, SurfaceLost, NativeWindowInUse, OutOfDate, IncompatibleDisplay, ValidationFailed, InvalidShader, InvalidDRMFormatModifierPlaneLayout, NotPermitted, FullScreenExclusiveModeLost, InvalidDeviceAddress, PipelineCompileRequired, }; const ExtensionProperties = c.VkExtensionProperties; pub fn enumerateInstanceExtensionProperties(layerName: ?[]const u8, propertyCount: *u32, properties: ?[]ExtensionProperties) !Result { if(propertyCount.* != 0 and properties != null) if(properties.?.len != @as(usize, propertyCount.*)) return Error.InvalidArguments; const layerNamePtr: ?[*]const u8 = if(layerName) |m_layerName| m_layerName.ptr else null; const propertiesPtr: ?[*]ExtensionProperties = if(properties) |m_properties| m_properties.ptr else null; const result = c.vkEnumerateInstanceExtensionProperties(layerNamePtr, propertyCount, propertiesPtr); return switch(result) { .VK_ERROR_OUT_OF_HOST_MEMORY => Error.OutOfHostMemory, .VK_ERROR_OUT_OF_DEVICE_MEMORY => Error.OutOfDeviceMemory, .VK_ERROR_LAYER_NOT_PRESENT => Error.LayerNotPresent, else => @intToEnum(Result, @enumToInt(result)), }; }
src/main.zig
const std = @import("std"); const hw = @import("hw/hw.zig"); const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const Cart = @import("cart.zig").Cart; const Reg = @import("cpu/regs.zig").Reg; const Vip = @import("hw/vip.zig").Vip; const Vsu = @import("hw/vsu.zig").Vsu; const MIRROR_MASK = 0x07ffffff; pub const MemError = error{ Bounds, RegionNotFound, }; pub const MemRegion = struct { lower_bound: u32, upper_bound: u32, slice: []u8, fn new(lower_bound: u32, upper_bound: u32, slice: []u8) MemRegion { return MemRegion{ .lower_bound = lower_bound, .upper_bound = upper_bound, .slice = slice, }; } }; pub const Bus = struct { // let's do this as a list we have to traverse for every memory read for // now to get things working, but we'll almost definitely need to replace // this with a more speed-efficient data structure once we're trying // to run things ~at speed~ regions: ArrayList(MemRegion), com: hw.Com, game_pad: hw.GamePad, timer: hw.Timer, pub fn new(allocator: *Allocator) Bus { var regions = ArrayList(MemRegion).init(allocator); defer regions.deinit(); return Bus{ .regions = regions, .com = hw.Com.new(), .game_pad = hw.GamePad.new(), .timer = hw.Timer.new(), }; } pub fn init(self: *Bus, wram: []u8, cart: *Cart, vip: *Vip, vsu: *Vsu) void { // a lot of this isn't *quite* correct atm, because we're not routing to // registers and dealing with io shit, but let's get things up and // running before fiddling with all that self.map_region(0x00000000, 0x00ffffff, vip.vram) catch unreachable; self.map_region(0x01000000, 0x01ffffff, vsu.dummy_ram) catch unreachable; self.map_region(0x04000000, 0x04ffffff, cart.exp_ram) catch unreachable; self.map_region(0x05000000, 0x05ffffff, wram) catch unreachable; self.map_region(0x06000000, 0x06ffffff, cart.sram) catch unreachable; self.map_region(0x07000000, 0x07ffffff, cart.rom) catch unreachable; } fn map_region(self: *Bus, lower_bound: u32, upper_bound: u32, mem_region: []u8) !void { const region = MemRegion.new(lower_bound, upper_bound, mem_region); try self.regions.append(region); } fn get_slice(self: *Bus, offset: usize) ![]u8 { const moffset = offset & MIRROR_MASK; for (self.regions.items) |region| { if (moffset >= region.lower_bound and moffset < region.upper_bound) { return region.slice; } } return MemError.RegionNotFound; } fn get_hw_ctrl_reg(self: *Bus, offset: usize) !*Reg { return switch (offset) { 0x02000000 => &self.com.link_control, 0x02000004 => &self.com.auxiliary_link, 0x02000008 => &self.com.link_transmit, 0x0200000C => &self.com.link_receive, 0x02000010 => &self.game_pad.input_high, 0x02000014 => &self.game_pad.input_low, 0x02000018 => &self.timer.tcr, 0x0200001C => &self.timer.tcr_reload_low, 0x02000020 => &self.timer.tcr_reload_high, 0x02000024 => &self.timer.wcr, 0x02000028 => &self.game_pad.input_control, else => MemError.RegionNotFound, }; } pub fn read_word(self: *Bus, offset: usize) !u32 { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const res = try self.get_hw_ctrl_reg(offset); return res.*; } else { const s = try self.get_slice(offset); // use a mask to get the relative offset within the memory region const mask = s.len - 1; const moffset = offset & mask; const val = std.mem.readIntSliceLittle(u32, s[moffset .. moffset + 4]); return val; } } pub fn read_halfword(self: *Bus, offset: usize) !u16 { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const reg = try self.get_hw_ctrl_reg(offset); return @intCast(u16, reg.* & 0x00ff); } else { const s = try self.get_slice(offset); const mask = s.len - 1; const moffset = offset & mask; if (offset < 0x01000000) { std.debug.warn("vip/vram read at offset: 0x{x}\n", .{moffset}); } return std.mem.readIntSliceLittle(u16, s[moffset .. moffset + 2]); } } pub fn read_byte(self: *Bus, offset: usize) !u8 { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const reg = try self.get_hw_ctrl_reg(offset); return @intCast(u8, reg.* & 0x000f); } else { const s = try self.get_slice(offset); const mask = s.len - 1; const moffset = offset & mask; return s[moffset]; } } pub fn write_word(self: *Bus, offset: usize, val: u32) !void { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const reg = try self.get_hw_ctrl_reg(offset); reg.* = val; } else { const s = try self.get_slice(offset); const mask = s.len - 1; const moffset = offset & mask; for (mem.asBytes(&val)) |byte, i| { s[moffset + i] = byte; } } } pub fn write_halfword(self: *Bus, offset: usize, val: u16) !void { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const reg = try self.get_hw_ctrl_reg(offset); reg.* = @intCast(u32, val); } else { const s = try self.get_slice(offset); const mask = s.len - 1; const moffset = offset & mask; if (offset < 0x01000000) { std.debug.warn("vip/vram write 0x{x} at offset: 0x{x}\n", .{ val, moffset }); } for (mem.asBytes(&val)) |byte, i| { s[moffset + i] = byte; } } } pub fn write_byte(self: *Bus, offset: usize, val: u8) !void { if (offset >= 0x02000000 and offset <= 0x02ffffff) { const reg = try self.get_hw_ctrl_reg(offset); reg.* = @intCast(u32, val); } else { const s = try self.get_slice(offset); const mask = s.len - 1; const moffset = offset & mask; s[moffset] = val; } } };
src/bus.zig
const std = @import("std"); usingnamespace @import("../module.zig").prelude; const SampleBuffer = @import("../sample_buffer.zig").SampleBuffer; //; // note: // anti-click is a needless expense if used for a game, // so anti-click defaults to be off // just, dont stop or play sounds from a point that will click // precalculate fadeins and outs in the sampledata itself, // or if a change in fading is ever needed, do it deliberately with some other module // state == .PrePause isnt the same as pause_timer > 0 // because pause_timer could be positive, then play is pressed afterwards // pausing is annoying because // maybe you want it to happen instantaneously from when its called from the main thread // message passing will delay that timing // maybe just have an atomicPause/Play that atomically pauses it and is thread safe // TODO note: currently playrate changes click length // "okay" for down pitch, not okay for up pitch, might be skipping frames // instead of using frame_at, use some raw frame_ct that just counts up // an 'actual frame_ct' thats adusted for the playback rate? or something pub const SamplePlayer = struct { const Self = @This(); pub const Message = union(enum) { play, pause, stop, setLoop: bool, setSample: *const SampleBuffer, setPlayRate: f32, setPlayPosition: usize, setAntiClick: bool, }; pub const State = enum { Playing, PrePause, Paused, }; // TODO use this pub const Loop = struct { start: usize, end: usize, }; // TODO use this pub const Interpolation = enum { None, Linear, }; curr_sample: ?*const SampleBuffer, frame_at: usize, remainder: f32, // TODO probably use f64 // fraction of sample rate to ctx rate sample_rate_mult: f32, do_anti_click: bool, // TODO makes sense to have this as a constant // not going to be changing it ever anti_click_len: u32, fade_in_timer: u32, fade_out_timer: u32, pause_frame_at: usize, pause_remainder: f32, state: State, play_rate: f32, do_loop: bool, pub fn init() Self { return .{ .curr_sample = null, .frame_at = 0, .remainder = 0., .sample_rate_mult = 1., .do_anti_click = false, .anti_click_len = 200, .fade_in_timer = 0, .fade_out_timer = 0, .pause_frame_at = 0, .pause_remainder = 0., .state = .Paused, .play_rate = 1., .do_loop = false, }; } pub fn compute( self: *Self, ctx: CallbackContext, _inputs: []const InBuffer, output: []f32, ) void { if (self.curr_sample) |sample| { if (self.state != .Paused) { var ct: usize = 0; var float_ct: f32 = 0; while (ct < ctx.frame_len) : (ct += 2) { if (self.do_anti_click) { if (self.frame_at == 0) { self.play(); } else if (self.frame_at == sample.frame_ct - self.anti_click_len) { self.stop(); } } const atten = if (!self.do_anti_click) blk: { break :blk 1.; } else if (self.fade_in_timer > 0 and self.fade_out_timer > 0) blk: { const f_tm = if (self.state == .PrePause) blk_: { break :blk_ @intToFloat(f32, std.math.min( self.anti_click_len - self.fade_in_timer, self.fade_out_timer, )); } else blk_: { break :blk_ @intToFloat(f32, std.math.max( self.anti_click_len - self.fade_in_timer, self.fade_out_timer, )); }; const f_ac = @intToFloat(f32, self.anti_click_len); self.fade_in_timer -= 1; self.fade_out_timer -= 1; break :blk f_tm / f_ac; } else if (self.fade_in_timer > 0) blk: { const f_it = @intToFloat(f32, self.anti_click_len - self.fade_in_timer); const f_ac = @intToFloat(f32, self.anti_click_len); self.fade_in_timer -= 1; break :blk f_it / f_ac; } else if (self.fade_out_timer > 0) blk: { const f_ot = @intToFloat(f32, self.fade_out_timer); const f_ac = @intToFloat(f32, self.anti_click_len); self.fade_out_timer -= 1; break :blk f_ot / f_ac; } else 1.; switch (sample.channel_ct) { 1 => { output[ct] = sample.data.items[self.frame_at] * atten; output[ct + 1] = sample.data.items[self.frame_at] * atten; }, 2 => { output[ct] = sample.data.items[self.frame_at] * atten; output[ct + 1] = sample.data.items[self.frame_at + 1] * atten; self.frame_at += 1; }, else => unreachable, } // TODO simplify and combine these two things below if (self.state == .PrePause and self.fade_out_timer == 0) { // for most cases you dont need to check if youre looping here // we just want to stop // but if this is a stop inititated above by reaching the end window, // we need to check if (self.do_loop) { self.frame_at = 0; continue; } else { self.state = .Paused; self.frame_at = self.pause_frame_at; self.remainder = self.pause_remainder; ct += 2; while (ct < ctx.frame_len) : (ct += 2) { output[ct] = 0.; output[ct + 1] = 0.; } return; } } float_ct += self.sample_rate_mult * self.play_rate; if (float_ct > 1) { float_ct -= 1; self.frame_at += 1; if (self.frame_at >= sample.frame_ct) { if (self.do_loop) { self.frame_at = 0; } else { self.state = .Paused; self.fade_out_timer = 0; ct += 2; while (ct < ctx.frame_len) : (ct += 2) { output[ct] = 0.; output[ct + 1] = 0.; } return; } } } } self.remainder = float_ct; } else { std.mem.set(f32, output, 0.); } } else { std.mem.set(f32, output, 0.); } } pub fn takeMessage(self: *Self, ctx: CallbackContext, msg: Message) void { switch (msg) { .play => self.play(), .pause => self.pause(), .stop => self.stop(), .setLoop => |to| self.do_loop = to, .setSample => |to| self.setSample(ctx, to), .setPlayRate => |to| self.play_rate = to, // TODO make into a function and error check .setPlayPosition => |to| self.frame_at = to, .setAntiClick => |to| self.do_anti_click = to, } } //; pub fn play(self: *Self) void { if (self.state != .Playing) { self.state = .Playing; self.fade_in_timer = self.anti_click_len; } } pub fn pause(self: *Self) void { if (self.state == .Playing) { if (self.do_anti_click) { self.state = .PrePause; self.fade_out_timer = self.anti_click_len; self.pause_frame_at = self.frame_at; self.pause_remainder = self.remainder; } else { self.state = .Paused; } } } pub fn stop(self: *Self) void { if (self.state == .Playing) { if (self.do_anti_click) { self.state = .PrePause; self.fade_out_timer = self.anti_click_len; } else { self.state = .Paused; } } // do this out here so if you pause then stop you restart the sample self.pause_frame_at = 0; self.pause_remainder = 0; } pub fn setSample(self: *Self, ctx: CallbackContext, sample: *const SampleBuffer) void { self.curr_sample = sample; self.frame_at = 0; self.remainder = 0.; self.sample_rate_mult = @intToFloat(f32, sample.sample_rate) / @intToFloat(f32, ctx.sample_rate); self.state = .Paused; } };
src/modules/sample_player.zig
const std = @import("std"); const Handle = windows.HANDLE; const windows = std.os.windows; pub const Layer = enum(c_int) { network = 0, network_forward = 1, flow = 2, socket = 3, reflect = 4, _, }; pub const Flags = enum(u64) { sniff = 0x0001, drop = 0x0002, /// aka read_only recv_only = 0x0004, /// aka write_only send_only = 0x0008, no_install = 0x0010, fragments = 0x0020, _, }; pub const NetworkLayerData = extern struct { interface_index: u32, sub_interface_index: u32, }; pub const FlowLayerData = extern struct { endpoint_id: u64, parent_endpoint_id: u64, process_id: u32, local_addr: [4]u32, remote_addr: [4]u32, local_port: u16, remote_port: u16, protocol: u8, }; pub const SocketLayerData = extern struct { endpoint_id: u64, parent_endpoint_id: u64, process_id: u32, local_addr: [4]u32, remote_addr: [4]u32, local_port: u16, remote_port: u16, protocol: u8, }; pub const ReflectLayerData = extern struct { timestamp: i64, process_id: u32, layer: Layer, flags: Flags, priority: i16, }; pub const LayerData = extern union { network: NetworkLayerData, flow: FlowLayerData, socket: SocketLayerData, reflect: ReflectLayerData, reserved: [64]u8, }; pub const Address = packed struct { timestamp: i64, layer: u8, event: u8, is_sniffed: bool, is_outbound: bool, is_loopback: bool, is_impostor: bool, is_ipv6: bool, has_ip_checksum: bool, has_tcp_checksum: bool, has_udp_checksum: bool, reserved: u8, reserved2: u32, data: LayerData, pub fn getLayer(self: Address) Layer { return @intToEnum(Layer, self.layer); } }; pub extern fn WinDivertOpen(filter: [*c]const u8, layer: Layer, priority: i16, flags: Flags) Handle; pub extern fn WinDivertClose(handle: Handle) windows.BOOL; pub extern fn WinDivertRecv(handle: Handle, pPacket: ?*c_void, packetLen: c_uint, pRecvLen: [*c]c_uint, pAddr: ?*Address) windows.BOOL; pub extern fn WinDivertSend(handle: Handle, pPacket: ?*const c_void, packetLen: c_uint, pSendLen: [*c]c_uint, pAddr: ?*const Address) windows.BOOL; pub const OpenError = error{ DriverNotFound, LackOfPrivilege, InvalidParameter, InvalidDigitalSignature, IncompatibleDriver, DriverNotInstalled, DriverBlocked, BaseFilteringEngineDisabled, Unexpected, }; pub fn open(filter: []const u8, layer: Layer, priority: i16, flags: Flags) OpenError!Handle { var handle = WinDivertOpen(filter.ptr, layer, priority, flags); if (handle == windows.INVALID_HANDLE_VALUE) switch (windows.kernel32.GetLastError()) { .FILE_NOT_FOUND => return error.DriverNotFound, // The driver files WinDivert32.sys or WinDivert64.sys were not found .ACCESS_DENIED => return error.LackOfPrivilege, // The calling application does not have Administrator privileges .INVALID_PARAMETER => return error.InvalidParameter, // This indicates an invalid packet filter string, layer, priority, or flags .INVALID_IMAGE_HASH => return error.InvalidDigitalSignature, // The WinDivert32.sys or WinDivert64.sys driver does not have a valid digital signature (https://reqrypt.org/windivert-doc.html#driver_signing) .DRIVER_FAILED_PRIOR_UNLOAD => return error.IncompatibleDriver, // An incompatible version of the WinDivert driver is currently loaded .SERVICE_DOES_NOT_EXIST => return error.DriverNotInstalled, // The handle was opened with the WINDIVERT_FLAG_NO_INSTALL flag and the WinDivert driver is not already installed .DRIVER_BLOCKED => return error.DriverBlocked, // Security software / driver incompatible VM .EPT_S_NOT_REGISTERED => return error.BaseFilteringEngineDisabled, // This error occurs when the Base Filtering Engine service has been disabled. else => |err| return windows.unexpectedError(err), }; return handle; } pub fn close(handle: Handle) error{Unexpected}!void { if (WinDivertClose(handle) == 0) return windows.unexpectedError(windows.kernel32.GetLastError()); } pub const ReceiveError = error{ InsufficientBuffer, NoData, Unexpected, }; pub const ReceiveResult = struct { len: c_uint, buffer: []u8, address: Address, }; pub fn receive(handle: Handle, buffer: []u8) ReceiveError!ReceiveResult { var result: ReceiveResult = undefined; if (WinDivertRecv(handle, buffer.ptr, @intCast(c_uint, buffer.len), &result.len, &result.address) == 0) switch (windows.kernel32.GetLastError()) { .INSUFFICIENT_BUFFER => return error.InsufficientBuffer, // The captured packet is larger than the pPacket buffer .NO_DATA => return error.NoData, // The handle has been shutdown using WinDivertShutdown() and the packet queue is empty else => |err| return windows.unexpectedError(err), }; result.buffer = buffer[0..result.len]; return result; } pub const SendError = error{ Unexpected, }; pub fn send(handle: Handle, buffer: []u8, address: Address) SendError!c_uint { var bytes_sent: c_uint = 0; if (WinDivertSend(handle, buffer.ptr, @intCast(c_uint, buffer.len), &bytes_sent, &address) == 0) return windows.unexpectedError(windows.kernel32.GetLastError()); return bytes_sent; }
src/bindings.zig
const Self = @This(); const std = @import("std"); const assert = std.debug.assert; const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const Box = @import("Box.zig"); const Output = @import("Output.zig"); const Subsurface = @import("Subsurface.zig"); const XdgPopup = @import("XdgPopup.zig"); const log = std.log.scoped(.layer_shell); output: *Output, wlr_layer_surface: *wlr.LayerSurfaceV1, box: Box = undefined, state: wlr.LayerSurfaceV1.State, destroy: wl.Listener(*wlr.LayerSurfaceV1) = wl.Listener(*wlr.LayerSurfaceV1).init(handleDestroy), map: wl.Listener(*wlr.LayerSurfaceV1) = wl.Listener(*wlr.LayerSurfaceV1).init(handleMap), unmap: wl.Listener(*wlr.LayerSurfaceV1) = wl.Listener(*wlr.LayerSurfaceV1).init(handleUnmap), new_popup: wl.Listener(*wlr.XdgPopup) = wl.Listener(*wlr.XdgPopup).init(handleNewPopup), new_subsurface: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleNewSubsurface), commit: wl.Listener(*wlr.Surface) = wl.Listener(*wlr.Surface).init(handleCommit), pub fn init(self: *Self, output: *Output, wlr_layer_surface: *wlr.LayerSurfaceV1) void { self.* = .{ .output = output, .wlr_layer_surface = wlr_layer_surface, .state = wlr_layer_surface.current, }; wlr_layer_surface.data = @ptrToInt(self); // Set up listeners that are active for the entire lifetime of the layer surface wlr_layer_surface.events.destroy.add(&self.destroy); wlr_layer_surface.events.map.add(&self.map); wlr_layer_surface.events.unmap.add(&self.unmap); wlr_layer_surface.events.new_popup.add(&self.new_popup); wlr_layer_surface.surface.events.commit.add(&self.commit); wlr_layer_surface.surface.events.new_subsurface.add(&self.new_subsurface); // wlroots only informs us of the new surface after the first commit, // so our listener does not get called for this first commit. However, // we do want our listener called in order to send the initial configure. handleCommit(&self.commit, wlr_layer_surface.surface); Subsurface.handleExisting(wlr_layer_surface.surface, .{ .layer_surface = self }); } fn handleDestroy(listener: *wl.Listener(*wlr.LayerSurfaceV1), wlr_layer_surface: *wlr.LayerSurfaceV1) void { const self = @fieldParentPtr(Self, "destroy", listener); log.debug("layer surface '{s}' destroyed", .{self.wlr_layer_surface.namespace}); // Remove listeners active the entire lifetime of the layer surface self.destroy.link.remove(); self.map.link.remove(); self.unmap.link.remove(); self.new_popup.link.remove(); self.commit.link.remove(); self.new_subsurface.link.remove(); Subsurface.destroySubsurfaces(self.wlr_layer_surface.surface); var it = wlr_layer_surface.popups.iterator(.forward); while (it.next()) |wlr_xdg_popup| { if (@intToPtr(?*XdgPopup, wlr_xdg_popup.base.data)) |xdg_popup| xdg_popup.destroy(); } const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); util.gpa.destroy(node); } fn handleMap(listener: *wl.Listener(*wlr.LayerSurfaceV1), wlr_layer_surface: *wlr.LayerSurfaceV1) void { const self = @fieldParentPtr(Self, "map", listener); log.debug("layer surface '{s}' mapped", .{wlr_layer_surface.namespace}); wlr_layer_surface.surface.sendEnter(wlr_layer_surface.output.?); const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); self.output.getLayer(self.state.layer).append(node); self.output.arrangeLayers(.mapped); } fn handleUnmap(listener: *wl.Listener(*wlr.LayerSurfaceV1), wlr_layer_surface: *wlr.LayerSurfaceV1) void { const self = @fieldParentPtr(Self, "unmap", listener); log.debug("layer surface '{s}' unmapped", .{self.wlr_layer_surface.namespace}); // Remove from the output's list of layer surfaces const self_node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); self.output.layers[@intCast(usize, @enumToInt(self.state.layer))].remove(self_node); // If the unmapped surface is focused, clear focus var it = server.input_manager.seats.first; while (it) |node| : (it = node.next) { const seat = &node.data; if (seat.focused == .layer and seat.focused.layer == self) seat.setFocusRaw(.{ .none = {} }); } // This gives exclusive focus to a keyboard interactive top or overlay layer // surface if there is one. self.output.arrangeLayers(.mapped); // Ensure that focus is given to the appropriate view if there is no // other top/overlay layer surface to grab focus. it = server.input_manager.seats.first; while (it) |node| : (it = node.next) { const seat = &node.data; seat.focus(null); } server.root.startTransaction(); } fn handleCommit(listener: *wl.Listener(*wlr.Surface), wlr_surface: *wlr.Surface) void { const self = @fieldParentPtr(Self, "commit", listener); // Ignore commits if the surface has been closed. if (self.wlr_layer_surface.closed) return; assert(self.wlr_layer_surface.output != null); // If a surface is committed while it is not mapped, we may need to send a configure. if (!self.wlr_layer_surface.mapped) { const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); self.output.getLayer(self.state.layer).append(node); self.output.arrangeLayers(.unmapped); self.output.getLayer(self.state.layer).remove(node); return; } const new_state = &self.wlr_layer_surface.current; if (!std.meta.eql(self.state, new_state.*)) { // If the layer changed, move the LayerSurface to the proper list if (self.state.layer != new_state.layer) { const node = @fieldParentPtr(std.TailQueue(Self).Node, "data", self); self.output.getLayer(self.state.layer).remove(node); self.output.getLayer(new_state.layer).append(node); } self.state = new_state.*; self.output.arrangeLayers(.mapped); server.root.startTransaction(); } self.output.damage.addWhole(); } fn handleNewPopup(listener: *wl.Listener(*wlr.XdgPopup), wlr_xdg_popup: *wlr.XdgPopup) void { const self = @fieldParentPtr(Self, "new_popup", listener); XdgPopup.create(wlr_xdg_popup, .{ .layer_surface = self }); } fn handleNewSubsurface(listener: *wl.Listener(*wlr.Subsurface), new_wlr_subsurface: *wlr.Subsurface) void { const self = @fieldParentPtr(Self, "new_subsurface", listener); Subsurface.create(new_wlr_subsurface, .{ .layer_surface = self }); }
source/river-0.1.0/river/LayerSurface.zig
const Self = @This(); const build_options = @import("build_options"); const std = @import("std"); const mem = std.mem; const ascii = std.ascii; const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const InputConfig = @import("InputConfig.zig"); const Seat = @import("Seat.zig"); const Server = @import("Server.zig"); const View = @import("View.zig"); const PointerConstraint = @import("PointerConstraint.zig"); const default_seat_name = "default"; const log = std.log.scoped(.input_manager); pub const InputDevice = struct { device: *wlr.InputDevice, destroy: wl.Listener(*wlr.InputDevice) = wl.Listener(*wlr.InputDevice).init(handleDestroy), /// Careful: The identifier is not unique! A physical input device may have /// multiple logical input devices with the exact same vendor id, product id /// and name. However identifiers of InputConfigs are unique. identifier: []const u8, pub fn init(self: *InputDevice, device: *wlr.InputDevice) !void { // The identifier is formatted exactly as in Sway const identifier = try std.fmt.allocPrint( util.gpa, "{}:{}:{s}", .{ device.vendor, device.product, mem.trim( u8, mem.sliceTo(device.name, 0), &ascii.spaces, ) }, ); for (identifier) |*char| { if (char.* == ' ' or !std.ascii.isPrint(char.*)) { char.* = '_'; } } self.* = .{ .device = device, .identifier = identifier, }; log.debug("new input device: {s}", .{self.identifier}); device.events.destroy.add(&self.destroy); } pub fn deinit(self: *InputDevice) void { util.gpa.free(self.identifier); self.destroy.link.remove(); } fn handleDestroy(listener: *wl.Listener(*wlr.InputDevice), device: *wlr.InputDevice) void { const self = @fieldParentPtr(InputDevice, "destroy", listener); log.debug("removed input device: {s}", .{self.identifier}); self.deinit(); const node = @fieldParentPtr(std.TailQueue(InputDevice).Node, "data", self); server.input_manager.input_devices.remove(node); util.gpa.destroy(node); } }; new_input: wl.Listener(*wlr.InputDevice) = wl.Listener(*wlr.InputDevice).init(handleNewInput), idle: *wlr.Idle, input_inhibit_manager: *wlr.InputInhibitManager, pointer_constraints: *wlr.PointerConstraintsV1, relative_pointer_manager: *wlr.RelativePointerManagerV1, virtual_pointer_manager: *wlr.VirtualPointerManagerV1, virtual_keyboard_manager: *wlr.VirtualKeyboardManagerV1, input_configs: std.ArrayList(InputConfig), input_devices: std.TailQueue(InputDevice) = .{}, seats: std.TailQueue(Seat) = .{}, exclusive_client: ?*wl.Client = null, inhibit_activate: wl.Listener(*wlr.InputInhibitManager) = wl.Listener(*wlr.InputInhibitManager).init(handleInhibitActivate), inhibit_deactivate: wl.Listener(*wlr.InputInhibitManager) = wl.Listener(*wlr.InputInhibitManager).init(handleInhibitDeactivate), new_pointer_constraint: wl.Listener(*wlr.PointerConstraintV1) = wl.Listener(*wlr.PointerConstraintV1).init(handleNewPointerConstraint), new_virtual_pointer: wl.Listener(*wlr.VirtualPointerManagerV1.event.NewPointer) = wl.Listener(*wlr.VirtualPointerManagerV1.event.NewPointer).init(handleNewVirtualPointer), new_virtual_keyboard: wl.Listener(*wlr.VirtualKeyboardV1) = wl.Listener(*wlr.VirtualKeyboardV1).init(handleNewVirtualKeyboard), pub fn init(self: *Self) !void { const seat_node = try util.gpa.create(std.TailQueue(Seat).Node); errdefer util.gpa.destroy(seat_node); self.* = .{ // These are automatically freed when the display is destroyed .idle = try wlr.Idle.create(server.wl_server), .input_inhibit_manager = try wlr.InputInhibitManager.create(server.wl_server), .pointer_constraints = try wlr.PointerConstraintsV1.create(server.wl_server), .relative_pointer_manager = try wlr.RelativePointerManagerV1.create(server.wl_server), .virtual_pointer_manager = try wlr.VirtualPointerManagerV1.create(server.wl_server), .virtual_keyboard_manager = try wlr.VirtualKeyboardManagerV1.create(server.wl_server), .input_configs = std.ArrayList(InputConfig).init(util.gpa), }; self.seats.prepend(seat_node); try seat_node.data.init(default_seat_name); if (build_options.xwayland) server.xwayland.setSeat(self.defaultSeat().wlr_seat); server.backend.events.new_input.add(&self.new_input); self.input_inhibit_manager.events.activate.add(&self.inhibit_activate); self.input_inhibit_manager.events.deactivate.add(&self.inhibit_deactivate); self.pointer_constraints.events.new_constraint.add(&self.new_pointer_constraint); self.virtual_pointer_manager.events.new_virtual_pointer.add(&self.new_virtual_pointer); self.virtual_keyboard_manager.events.new_virtual_keyboard.add(&self.new_virtual_keyboard); } pub fn deinit(self: *Self) void { while (self.seats.pop()) |seat_node| { seat_node.data.deinit(); util.gpa.destroy(seat_node); } while (self.input_devices.pop()) |input_device_node| { input_device_node.data.deinit(); util.gpa.destroy(input_device_node); } for (self.input_configs.items) |*input_config| { input_config.deinit(); } self.input_configs.deinit(); } pub fn defaultSeat(self: Self) *Seat { return &self.seats.first.?.data; } /// Returns true if input is currently allowed on the passed surface. pub fn inputAllowed(self: Self, wlr_surface: *wlr.Surface) bool { return if (self.exclusive_client) |exclusive_client| exclusive_client == wlr_surface.resource.getClient() else true; } pub fn updateCursorState(self: Self) void { var it = self.seats.first; while (it) |node| : (it = node.next) node.data.cursor.updateState(); } fn handleInhibitActivate( listener: *wl.Listener(*wlr.InputInhibitManager), input_inhibit_manager: *wlr.InputInhibitManager, ) void { const self = @fieldParentPtr(Self, "inhibit_activate", listener); log.debug("input inhibitor activated", .{}); var seat_it = self.seats.first; while (seat_it) |seat_node| : (seat_it = seat_node.next) { // Clear focus of all seats seat_node.data.setFocusRaw(.{ .none = {} }); // Enter locked mode seat_node.data.prev_mode_id = seat_node.data.mode_id; seat_node.data.mode_id = 1; } self.exclusive_client = self.input_inhibit_manager.active_client; } fn handleInhibitDeactivate( listener: *wl.Listener(*wlr.InputInhibitManager), input_inhibit_manager: *wlr.InputInhibitManager, ) void { const self = @fieldParentPtr(Self, "inhibit_deactivate", listener); log.debug("input inhibitor deactivated", .{}); self.exclusive_client = null; // Calling arrangeLayers() like this ensures that any top or overlay, // keyboard-interactive surfaces will re-grab focus. var output_it = server.root.outputs.first; while (output_it) |output_node| : (output_it = output_node.next) { output_node.data.arrangeLayers(.mapped); } // After ensuring that any possible layer surface focus grab has occured, // have each Seat handle focus and enter their previous mode. var seat_it = self.seats.first; while (seat_it) |seat_node| : (seat_it = seat_node.next) { seat_node.data.focus(null); seat_node.data.mode_id = seat_node.data.prev_mode_id; } server.root.startTransaction(); } /// This event is raised by the backend when a new input device becomes available. fn handleNewInput(listener: *wl.Listener(*wlr.InputDevice), device: *wlr.InputDevice) void { const self = @fieldParentPtr(Self, "new_input", listener); // TODO: support multiple seats const input_device_node = util.gpa.create(std.TailQueue(InputDevice).Node) catch return; input_device_node.data.init(device) catch { util.gpa.destroy(input_device_node); return; }; self.input_devices.append(input_device_node); self.defaultSeat().addDevice(device); // Apply matching input device configuration, if exists. for (self.input_configs.items) |*input_config| { if (mem.eql(u8, input_config.identifier, mem.sliceTo(input_device_node.data.identifier, 0))) { input_config.apply(&input_device_node.data); break; // There will only ever be one InputConfig for any unique identifier; } } } fn handleNewPointerConstraint(listener: *wl.Listener(*wlr.PointerConstraintV1), constraint: *wlr.PointerConstraintV1) void { const pointer_constraint = util.gpa.create(PointerConstraint) catch { log.crit("out of memory", .{}); return; }; pointer_constraint.init(constraint); } fn handleNewVirtualPointer( listener: *wl.Listener(*wlr.VirtualPointerManagerV1.event.NewPointer), event: *wlr.VirtualPointerManagerV1.event.NewPointer, ) void { const self = @fieldParentPtr(Self, "new_virtual_pointer", listener); // TODO Support multiple seats and don't ignore if (event.suggested_seat != null) { log.debug("Ignoring seat suggestion from virtual pointer", .{}); } // TODO dont ignore output suggestion if (event.suggested_output != null) { log.debug("Ignoring output suggestion from virtual pointer", .{}); } self.defaultSeat().addDevice(&event.new_pointer.input_device); } fn handleNewVirtualKeyboard( listener: *wl.Listener(*wlr.VirtualKeyboardV1), virtual_keyboard: *wlr.VirtualKeyboardV1, ) void { const self = @fieldParentPtr(Self, "new_virtual_keyboard", listener); const seat = @intToPtr(*Seat, virtual_keyboard.seat.data); seat.addDevice(&virtual_keyboard.input_device); }
source/river-0.1.0/river/InputManager.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day13.txt"); const Coord2 = struct { x: usize, y: usize, }; const Fold = struct { axis: u8, value: usize, }; const Input = struct { dots: std.ArrayList(Coord2), folds: std.ArrayList(Fold), max_x: usize, max_y: usize, pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() { var input = Input{ .dots = try std.ArrayList(Coord2).initCapacity(allocator, 800), .folds = try std.ArrayList(Fold).initCapacity(allocator, 16), .max_x = 0, .max_y = 0, }; errdefer input.deinit(); var lines = std.mem.tokenize(u8, input_text, "\r\n"); while (lines.next()) |line| { if (line[0] != 'f') { var nums = std.mem.tokenize(u8, line, ","); const x = try parseInt(usize, nums.next().?, 10); const y = try parseInt(usize, nums.next().?, 10); input.max_x = std.math.max(input.max_x, x); input.max_y = std.math.max(input.max_y, y); //print("{d},{d}\n", .{x,y}); try input.dots.append(Coord2{ .x = x, .y = y }); } else { const axis = line[11]; assert(axis == 'x' or axis == 'y'); const value = try parseInt(usize, line[13..], 10); //print("fold at {c}={d}\n", .{axis,value}); try input.folds.append(Fold{ .axis = axis, .value = value }); } } return input; } pub fn deinit(self: @This()) void { self.dots.deinit(); self.folds.deinit(); } }; fn processFold(cells: std.ArrayList(u8), fold: Fold, w: *usize, h: *usize, pitch: usize) void { if (fold.axis == 'y') { assert(fold.value < h.*); var tx: usize = 0; while (tx < w.*) : (tx += 1) { assert(cells.items[fold.value * w.* + tx] == '.'); } var y: usize = fold.value + 1; while (y < h.*) : (y += 1) { var x: usize = 0; while (x < w.*) : (x += 1) { if (cells.items[y * pitch + x] == '#') { const dy = y - fold.value; const y2 = fold.value - dy; cells.items[y2 * pitch + x] = '#'; cells.items[y * pitch + x] = '.'; } } } h.* = fold.value; } else if (fold.axis == 'x') { assert(fold.value < w.*); var ty: usize = 0; while (ty < h.*) : (ty += 1) { assert(cells.items[ty * pitch + fold.value] == '.'); } var y: usize = 0; while (y < h.*) : (y += 1) { var x: usize = fold.value + 1; while (x < w.*) : (x += 1) { if (cells.items[y * pitch + x] == '#') { const dx = x - fold.value; const x2 = fold.value - dx; cells.items[y * pitch + x2] = '#'; cells.items[y * pitch + x] = '.'; } } } w.* = fold.value; } } fn part1(input: Input) i64 { var w = input.max_x + 1; var h = input.max_y + 1; const pitch = w; var cells = std.ArrayList(u8).initCapacity(std.testing.allocator, pitch * h) catch unreachable; defer cells.deinit(); cells.appendNTimesAssumeCapacity('.', cells.capacity); for (input.dots.items) |dot| { cells.items[dot.y * pitch + dot.x] = '#'; } processFold(cells, input.folds.items[0], &w, &h, pitch); var dot_count: i64 = 0; var y: usize = 0; while (y < h) : (y += 1) { var x: usize = 0; while (x < w) : (x += 1) { if (cells.items[y * pitch + x] == '#') { dot_count += 1; } } } return dot_count; } fn part2(input: Input) i64 { var w = input.max_x + 1; var h = input.max_y + 1; const pitch = w; var cells = std.ArrayList(u8).initCapacity(std.testing.allocator, pitch * h) catch unreachable; defer cells.deinit(); cells.appendNTimesAssumeCapacity('.', cells.capacity); for (input.dots.items) |dot| { cells.items[dot.y * pitch + dot.x] = '#'; } for (input.folds.items) |fold| { processFold(cells, fold, &w, &h, pitch); } // This puzzle's output is a bitmap containing 8 characters of text. // Print the bitmap and then return a dummy value. var y: usize = 0; print("\n", .{}); while (y < h) : (y += 1) { var x: usize = 0; while (x < w) : (x += 1) { print("{c}", .{cells.items[y * pitch + x]}); } print("\n", .{}); } return 23; } const test_data = \\6,10 \\0,14 \\9,10 \\0,3 \\10,4 \\4,11 \\6,0 \\6,12 \\4,1 \\0,13 \\10,12 \\3,4 \\3,0 \\8,4 \\1,10 \\2,14 \\8,10 \\9,0 \\ \\fold along y=7 \\fold along x=5 ; const part1_test_solution: ?i64 = 17; const part1_solution: ?i64 = 664; const part2_test_solution: ?i64 = null; const part2_solution: ?i64 = 23; // Just boilerplate below here, nothing to see fn testPart1() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part1_test_solution) |solution| { try std.testing.expectEqual(solution, part1(test_input)); } var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } fn testPart2() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part2_test_solution) |solution| { try std.testing.expectEqual(solution, part2(test_input)); } var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part2_solution) |solution| { try std.testing.expectEqual(solution, part2(input)); print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } pub fn main() !void { try testPart1(); try testPart2(); } test "part1" { try testPart1(); } test "part2" { try testPart2(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day13.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day24.txt"); const Reg = enum(u2) { W = 0, X = 1, Y = 2, Z = 3, }; const Arg = enum(i64) { RW = 100, RX = 101, RY = 102, RZ = 103, _, }; const Opcode = enum(u3) { inp = 0, add = 1, mul = 2, div = 3, mod = 4, eql = 5, }; const Instruction = struct { op: Opcode, reg: Reg, arg: Arg, }; const Input = struct { instructions: std.BoundedArray(Instruction, 256), pub fn init(input_text: []const u8) !@This() { var self = Input{ .instructions = try std.BoundedArray(Instruction, 256).init(0), }; var lines = std.mem.tokenize(u8, input_text, "\r\n"); while (lines.next()) |line| { var tokens = std.mem.tokenize(u8, line, " "); const op = tokens.next().?; const reg = tokens.next().?; const a = tokens.next(); self.instructions.appendAssumeCapacity(Instruction{ .op = switch (op[1]) { 'n' => .inp, 'd' => .add, 'u' => .mul, 'i' => .div, 'o' => .mod, 'q' => .eql, else => unreachable, }, .reg = switch (reg[0]) { 'w' => .W, 'x' => .X, 'y' => .Y, 'z' => .Z, else => unreachable, // arg1 must be a register }, .arg = if (op[1] == 'n') @intToEnum(Arg, 0) else switch (a.?[0]) { 'w' => .RW, 'x' => .RX, 'y' => .RY, 'z' => .RZ, else => @intToEnum(Arg, try parseInt(i64, a.?, 10)), }, }); } return self; } }; fn argValue(regs: [4]i64, arg: Arg) i64 { return switch (arg) { .RW => regs[@enumToInt(Reg.W)], .RX => regs[@enumToInt(Reg.X)], .RY => regs[@enumToInt(Reg.Y)], .RZ => regs[@enumToInt(Reg.Z)], else => @enumToInt(arg), }; } fn run(instructions: std.BoundedArray(Instruction, 256), input: []const u8) [4]i64 { var regs: [4]i64 = .{0} ** 4; var next_input: usize = 0; for (instructions.constSlice()) |inst| { const r = &regs[@enumToInt(inst.reg)]; const b = argValue(regs, inst.arg); switch (inst.op) { .inp => { assert(next_input < input.len); const in = @intCast(i64, input[next_input] - '0'); assert(in >= 1 and in <= 9); next_input += 1; r.* = in; }, .add => { r.* += b; }, .mul => { r.* *= b; }, .div => { assert(b != 0); r.* = @divTrunc(r.*, b); }, .mod => { assert(r.* >= 0); assert(b > 0); r.* = @rem(r.*, b); }, .eql => { r.* = if (r.* == b) 1 else 0; }, } } return regs; } fn part1(input: Input) i64 { // z /= 26, maybe? // if (z%26)+K != in[i] // z *= 26 // z += in[i] + N // 0: D= 1 K= 10 N=13 // 1: D= 1 K= 13 N=10 // 2: D= 1 K= 13 N= 3 // 3: D=26 K=-11 N= 1 // 4: D= 1 K= 11 N= 9 // 5: D=26 K= -4 N= 3 // 6: D= 1 K= 12 N= 5 // 7: D= 1 K= 12 N= 1 // 8: D= 1 K= 15 N= 0 // 9: D=26 K= -2 N=13 // 10: D=26 K= -5 N= 7 // 11: D=26 K=-11 N=15 // 12: D=26 K=-13 N=12 // 13: D=26 K=-10 N= 8 // 89 // 7 A // 6 B // 4 5 // 23 // 1 C // 0 D // 01 234 567 89A BCD var m: i64 = 69_914_999_975_369; var s: [15]u8 = undefined; const len = std.fmt.formatIntBuf(s[0..], m, 10, .lower, std.fmt.FormatOptions{}); assert(len == 14); for (s) |digit| { assert(digit != '0'); } const regs = run(input.instructions, s[0..]); return regs[@enumToInt(Reg.Z)]; } fn part2(input: Input) i64 { // 01 234 567 89A BCD var m: i64 = 14_911_675_311_114; var s: [15]u8 = undefined; const len = std.fmt.formatIntBuf(s[0..], m, 10, .lower, std.fmt.FormatOptions{}); assert(len == 14); for (s) |digit| { assert(digit != '0'); } const regs = run(input.instructions, s[0..]); return regs[@enumToInt(Reg.Z)]; } const part1_solution: ?i64 = 0; const part2_test_solution: ?i64 = null; const part2_solution: ?i64 = 0; // Just boilerplate below here, nothing to see fn testPart1() !void { var regs: [4]i64 = undefined; const test_data1 = \\inp x \\mul x -1 ; var test_input1 = try Input.init(test_data1); regs = run(test_input1.instructions, "7"); try std.testing.expectEqual(@as(i64, -7), regs[@enumToInt(Reg.X)]); const test_data2 = \\inp z \\inp x \\mul z 3 \\eql z x ; var test_input2 = try Input.init(test_data2); regs = run(test_input2.instructions, "26"); try std.testing.expectEqual(@as(i64, 1), regs[@enumToInt(Reg.Z)]); regs = run(test_input2.instructions, "27"); try std.testing.expectEqual(@as(i64, 0), regs[@enumToInt(Reg.Z)]); const test_data3 = \\inp w \\add z w \\mod z 2 \\div w 2 \\add y w \\mod y 2 \\div w 2 \\add x w \\mod x 2 \\div w 2 \\mod w 2 ; var test_input3 = try Input.init(test_data3); regs = run(test_input3.instructions, "9"); try std.testing.expectEqual(@as(i64, 1), regs[@enumToInt(Reg.W)]); try std.testing.expectEqual(@as(i64, 0), regs[@enumToInt(Reg.X)]); try std.testing.expectEqual(@as(i64, 0), regs[@enumToInt(Reg.Y)]); try std.testing.expectEqual(@as(i64, 1), regs[@enumToInt(Reg.Z)]); var timer = try std.time.Timer.start(); var input = try Input.init(data); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } fn testPart2() !void { var timer = try std.time.Timer.start(); var input = try Input.init(data); if (part2_solution) |solution| { try std.testing.expectEqual(solution, part2(input)); print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } pub fn main() !void { try testPart1(); try testPart2(); } test "part1" { try testPart1(); } test "part2" { try testPart2(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day24.zig
const std = @import("std"); usingnamespace (@import("../machine.zig")); usingnamespace (@import("../util.zig")); const reg = Operand.register; const pred = Operand.registerPredicate; const predRm = Operand.rmPredicate; const sae = Operand.registerSae; const regRm = Operand.registerRm; const imm = Operand.immediate; test "XOP" { const m16 = Machine.init(.x86_32); const m32 = Machine.init(.x86_32); const m64 = Machine.init(.x64); const rm8 = Operand.memoryRm(.DefaultSeg, .BYTE, .EAX, 0); const rm16 = Operand.memoryRm(.DefaultSeg, .WORD, .EAX, 0); const rm32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0); const rm64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0); const mem_64 = rm64; const rm_mem8 = Operand.memoryRm(.DefaultSeg, .BYTE, .EAX, 0); const rm_mem16 = Operand.memoryRm(.DefaultSeg, .WORD, .EAX, 0); const rm_mem32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0); const rm_mem64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0); const rm_mem128 = Operand.memoryRm(.DefaultSeg, .XMM_WORD, .EAX, 0); const rm_mem256 = Operand.memoryRm(.DefaultSeg, .YMM_WORD, .EAX, 0); { // BEXTR testOp3(m64, .BEXTR, reg(.EAX), rm32, imm(0x44332211), "67 8f ea 78 10 00 11 22 33 44"); testOp3(m64, .BEXTR, reg(.RAX), rm64, imm(0x44332211), "67 8f ea f8 10 00 11 22 33 44"); // BLCFILL testOp2(m64, .BLCFILL, reg(.EAX), rm32, "67 8f e9 78 01 08"); testOp2(m64, .BLCFILL, reg(.RAX), rm64, "67 8f e9 f8 01 08"); // BLCI testOp2(m64, .BLCI, reg(.EAX), rm32, "67 8f e9 78 02 30"); testOp2(m64, .BLCI, reg(.RAX), rm64, "67 8f e9 f8 02 30"); // BLCIC testOp2(m64, .BLCIC, reg(.EAX), rm32, "67 8f e9 78 01 28"); testOp2(m64, .BLCIC, reg(.RAX), rm64, "67 8f e9 f8 01 28"); // BLCMSK testOp2(m64, .BLCMSK, reg(.EAX), rm32, "67 8f e9 78 02 08"); testOp2(m64, .BLCMSK, reg(.RAX), rm64, "67 8f e9 f8 02 08"); // BLCS testOp2(m64, .BLCS, reg(.EAX), rm32, "67 8f e9 78 01 18"); testOp2(m64, .BLCS, reg(.RAX), rm64, "67 8f e9 f8 01 18"); // BLSFILL testOp2(m64, .BLSFILL, reg(.EAX), rm32, "67 8f e9 78 01 10"); testOp2(m64, .BLSFILL, reg(.RAX), rm64, "67 8f e9 f8 01 10"); // BLSIC testOp2(m64, .BLSIC, reg(.EAX), rm32, "67 8f e9 78 01 30"); testOp2(m64, .BLSIC, reg(.RAX), rm64, "67 8f e9 f8 01 30"); // T1MSKC testOp2(m64, .T1MSKC, reg(.EAX), rm32, "67 8f e9 78 01 38"); testOp2(m64, .T1MSKC, reg(.RAX), rm64, "67 8f e9 f8 01 38"); // TZMSK testOp2(m64, .TZMSK, reg(.EAX), rm32, "67 8f e9 78 01 20"); testOp2(m64, .TZMSK, reg(.RAX), rm64, "67 8f e9 f8 01 20"); } // // LWP // { // LLWPCB testOp1(m64, .LLWPCB, reg(.ECX), "8f e9 78 12 c1"); testOp1(m64, .LLWPCB, reg(.RCX), "8f e9 f8 12 c1"); // LWPINS testOp3(m64, .LWPINS, reg(.ECX), rm32, imm(0x44332211), "67 8f ea 70 12 00 11 22 33 44"); testOp3(m64, .LWPINS, reg(.RCX), rm32, imm(0x44332211), "67 8f ea f0 12 00 11 22 33 44"); // LWPVAL testOp3(m64, .LWPVAL, reg(.ECX), rm32, imm(0x44332211), "67 8f ea 70 12 08 11 22 33 44"); testOp3(m64, .LWPVAL, reg(.RCX), rm32, imm(0x44332211), "67 8f ea f0 12 08 11 22 33 44"); // SLWPCB testOp1(m64, .SLWPCB, reg(.ECX), "8f e9 78 12 c9"); testOp1(m64, .SLWPCB, reg(.RCX), "8f e9 f8 12 c9"); } { // VFRCZPD testOp2(m64, .VFRCZPD, reg(.XMM1), regRm(.XMM0), "8f e9 78 81 c8"); testOp2(m64, .VFRCZPD, reg(.YMM1), regRm(.YMM0), "8f e9 7c 81 c8"); // VFRCZPS testOp2(m64, .VFRCZPS, reg(.XMM1), regRm(.XMM0), "8f e9 78 80 c8"); testOp2(m64, .VFRCZPS, reg(.YMM1), regRm(.YMM0), "8f e9 7c 80 c8"); // VFRCZSD testOp2(m64, .VFRCZSD, reg(.XMM1), regRm(.XMM0), "8f e9 78 83 c8"); // VFRCZSS testOp2(m64, .VFRCZSS, reg(.XMM1), regRm(.XMM0), "8f e9 78 82 c8"); } { // VPCMOV testOp4(m64, .VPCMOV, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 a2 c8 30"); testOp4(m64, .VPCMOV, reg(.YMM1),reg(.YMM2),regRm(.YMM0),reg(.YMM3), "8f e8 6c a2 c8 30"); testOp4(m64, .VPCMOV, reg(.XMM1),reg(.XMM2),reg(.XMM3),regRm(.XMM0), "8f e8 e8 a2 c8 30"); testOp4(m64, .VPCMOV, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0), "8f e8 ec a2 c8 30"); } { // VPCOMB / VPCOMW / VPCOMD / VPCOMQ testOp4(m64, .VPCOMB, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 cc c8 00"); testOp4(m64, .VPCOMW, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 cd c8 00"); testOp4(m64, .VPCOMD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 ce c8 00"); testOp4(m64, .VPCOMQ, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 cf c8 00"); // VPCOMUB / VPCOMUW / VPCOMUD / VPCOMUQ testOp4(m64, .VPCOMUB, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 ec c8 00"); testOp4(m64, .VPCOMUW, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 ed c8 00"); testOp4(m64, .VPCOMUD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 ee c8 00"); testOp4(m64, .VPCOMUQ, reg(.XMM1),reg(.XMM2),regRm(.XMM0),imm(0), "8f e8 68 ef c8 00"); } { // VPERMIL2PD testOp5(m64, .VPERMIL2PD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3),imm(0), "c4 e3 69 49 c8 30"); testOp5(m64, .VPERMIL2PD, reg(.XMM1),reg(.XMM2),reg(.XMM3),regRm(.XMM0),imm(0), "c4 e3 e9 49 c8 30"); testOp5(m64, .VPERMIL2PD, reg(.YMM1),reg(.YMM2),regRm(.YMM0),reg(.YMM3),imm(0), "c4 e3 6d 49 c8 30"); testOp5(m64, .VPERMIL2PD, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0), "c4 e3 ed 49 c8 30"); // VPERMIL2PS testOp5(m64, .VPERMIL2PS, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3),imm(0), "c4 e3 69 48 c8 30"); testOp5(m64, .VPERMIL2PS, reg(.XMM1),reg(.XMM2),reg(.XMM3),regRm(.XMM0),imm(0), "c4 e3 e9 48 c8 30"); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),regRm(.YMM0),reg(.YMM3),imm(0), "c4 e3 6d 48 c8 30"); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0), "c4 e3 ed 48 c8 30"); // imm testOp5(m64, .VPERMIL2PS, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3),imm(0x04), "c4 e3 69 48 c8 34"); testOp5(m64, .VPERMIL2PS, reg(.XMM1),reg(.XMM2),reg(.XMM3),regRm(.XMM0),imm(0x07), "c4 e3 e9 48 c8 37"); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),regRm(.YMM0),reg(.YMM3),imm(0x08), "c4 e3 6d 48 c8 38"); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0x0F), "c4 e3 ed 48 c8 3F"); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0x10), AsmError.InvalidImmediate); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0x11), AsmError.InvalidImmediate); testOp5(m64, .VPERMIL2PS, reg(.YMM1),reg(.YMM2),reg(.YMM3),regRm(.YMM0),imm(0xFF), AsmError.InvalidImmediate); } { // VPHADDBD / VPHADDBW / VPHADDBQ testOp2(m64, .VPHADDBW, reg(.XMM1), regRm(.XMM0), "8f e9 78 c1 c8"); testOp2(m64, .VPHADDBD, reg(.XMM1), regRm(.XMM0), "8f e9 78 c2 c8"); testOp2(m64, .VPHADDBQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 c3 c8"); // VPHADDWD / VPHADDWQ testOp2(m64, .VPHADDWD, reg(.XMM1), regRm(.XMM0), "8f e9 78 c6 c8"); testOp2(m64, .VPHADDWQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 c7 c8"); // VPHADDDQ testOp2(m64, .VPHADDDQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 cb c8"); // VPHADDUBD / VPHADDUBW / VPHADDUBQ testOp2(m64, .VPHADDUBW, reg(.XMM1), regRm(.XMM0), "8f e9 78 d1 c8"); testOp2(m64, .VPHADDUBD, reg(.XMM1), regRm(.XMM0), "8f e9 78 d2 c8"); testOp2(m64, .VPHADDUBQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 d3 c8"); // VPHADDUWD / VPHADDUWQ testOp2(m64, .VPHADDUWD, reg(.XMM1), regRm(.XMM0), "8f e9 78 d6 c8"); testOp2(m64, .VPHADDUWQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 d7 c8"); // VPHADDUDQ testOp2(m64, .VPHADDUDQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 db c8"); } { // VPHSUBBW testOp2(m64, .VPHSUBBW, reg(.XMM1), regRm(.XMM0), "8f e9 78 e1 c8"); // VPHSUBDQ testOp2(m64, .VPHSUBDQ, reg(.XMM1), regRm(.XMM0), "8f e9 78 e3 c8"); // VPHSUBWD testOp2(m64, .VPHSUBWD, reg(.XMM1), regRm(.XMM0), "8f e9 78 e2 c8"); } { // VPMACSDD testOp4(m64, .VPMACSDD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 9e c8 30"); // VPMACSDQH testOp4(m64, .VPMACSDQH, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 9f c8 30"); // VPMACSDQL testOp4(m64, .VPMACSDQL, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 97 c8 30"); // VPMACSSDD testOp4(m64, .VPMACSSDD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 8e c8 30"); // VPMACSSDQH testOp4(m64, .VPMACSSDQH, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 8f c8 30"); // VPMACSSDQL testOp4(m64, .VPMACSSDQL, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 87 c8 30"); // VPMACSSWD testOp4(m64, .VPMACSSWD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 86 c8 30"); // VPMACSSWW testOp4(m64, .VPMACSSWW, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 85 c8 30"); // VPMACSWD testOp4(m64, .VPMACSWD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 96 c8 30"); // VPMACSWW testOp4(m64, .VPMACSWW, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 95 c8 30"); } { // VPMADCSSWD testOp4(m64, .VPMADCSSWD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 a6 c8 30"); // VPMADCSWD testOp4(m64, .VPMADCSWD, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8f e8 68 b6 c8 30"); } { // VPPERM testOp4(m64, .VPPERM, reg(.XMM1),reg(.XMM2),regRm(.XMM0),reg(.XMM3), "8fe868a3c830"); testOp4(m64, .VPPERM, reg(.XMM1),reg(.XMM2),reg(.XMM3),regRm(.XMM0), "8fe8e8a3c830"); } { // VPROTB / VPROTW / VPROTD / VPROTQ // VPROTB testOp3(m64, .VPROTB, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 90 c8"); testOp3(m64, .VPROTB, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 90 c8"); testOp3(m64, .VPROTB, reg(.XMM1), regRm(.XMM0), imm(0), "8f e8 78 c0 c8 00"); // VPROTW testOp3(m64, .VPROTW, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 91 c8"); testOp3(m64, .VPROTW, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 91 c8"); testOp3(m64, .VPROTW, reg(.XMM1), regRm(.XMM0), imm(0), "8f e8 78 c1 c8 00"); // VPROTD testOp3(m64, .VPROTD, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 92 c8"); testOp3(m64, .VPROTD, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 92 c8"); testOp3(m64, .VPROTD, reg(.XMM1), regRm(.XMM0), imm(0), "8f e8 78 c2 c8 00"); // VPROTQ testOp3(m64, .VPROTQ, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 93 c8"); testOp3(m64, .VPROTQ, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 93 c8"); testOp3(m64, .VPROTQ, reg(.XMM1), regRm(.XMM0), imm(0), "8f e8 78 c3 c8 00"); } { // VPSHAB / VPSHAW / VPSHAD / VPSHAQ // VPSHAB testOp3(m64, .VPSHAB, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 98 c8"); testOp3(m64, .VPSHAB, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 98 c8"); // VPSHAW testOp3(m64, .VPSHAW, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 99 c8"); testOp3(m64, .VPSHAW, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 99 c8"); // VPSHAD testOp3(m64, .VPSHAD, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 9a c8"); testOp3(m64, .VPSHAD, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 9a c8"); // VPSHAQ testOp3(m64, .VPSHAQ, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 9b c8"); testOp3(m64, .VPSHAQ, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 9b c8"); } { // VPSHLB / VPSHLW / VPSHLD / VPSHLQ // VPSHLB testOp3(m64, .VPSHLB, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 94 c8"); testOp3(m64, .VPSHLB, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 94 c8"); // VPSHLW testOp3(m64, .VPSHLW, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 95 c8"); testOp3(m64, .VPSHLW, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 95 c8"); // VPSHLD testOp3(m64, .VPSHLD, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 96 c8"); testOp3(m64, .VPSHLD, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 96 c8"); // VPSHLQ testOp3(m64, .VPSHLQ, reg(.XMM1), regRm(.XMM0), reg(.XMM2), "8f e9 68 97 c8"); testOp3(m64, .VPSHLQ, reg(.XMM1), reg(.XMM2), regRm(.XMM0), "8f e9 e8 97 c8"); } }
src/x86/tests/xop.zig
const math = @import("std").math; const fmt = @import("std").fmt; const gmath = @import("gmath.zig").gmath(f64); const invSqrt2 = 0.7071067811865475244008443621; const almostOne = 1.0 - math.f64_epsilon; pub var srgbHighlightClipping = true; pub var srgbDesaturateBlacksAndWhites = true; pub fn Jazbz(comptime T_: type) type { return struct { const Self = @This(); pub const AzBz = AzBzType(T_); pub const Ch = ChType(T_); j: T_ = 0, azbz: AzBz = AzBz{}, pub const black = Self{ .j = 0, .azbz = AzBz.grey }; pub const white = Self{ .j = almostOne, .azbz = AzBz.grey }; pub fn init(j: T_, az: T_, bz: T_) Self { return Self{ .j = j, .azbz = AzBz{ .az = az, .bz = bz, }, }; } pub fn initJch(j: T_, c: T_, h: T_) Self { return Self{ .j = j, .azbz = AzBz.initCh(c, h), }; } pub fn grey(j: T_) Self { return .{ .j = j }; } pub fn scalar(x: T_) Self { return Self{ .j = x, .azbz = AzBz.scalar(x) }; } pub fn initSrgb(r: T_, g: T_, b: T_) Self { return srgb255ToJzazbz(T_, r * 0xff, g * 0xff, b * 0xff); } pub fn toSrgb(self: *const Self, comptime Depth: type) Srgb(Depth) { if (comptime srgbHighlightClipping) { if (self.j < 0) { return Srgb(Depth).initFloat(1, 1, 1); } else if (self.j > 1) { return Srgb(Depth).initFloat(0, 0, 0); } } const ab = if (comptime srgbDesaturateBlacksAndWhites) blk: { const x = 4.0 * self.j * (1 - self.j); const s = gmath.mix(x, math.sqrt(x), x); const ab = self.azbz.scale(s); break :blk ab; } else self.azbz; return jzazbzToSrgb(Depth, jTojz(self.j), ab.az, ab.bz); } pub fn scale(self: *const Self, x: T_) Self { return Self{ .j = self.j * x, .azbz = self.azbz.scale(x), }; } pub fn scaleJ(self: *const Self, x: T_) Self { return Self{ .j = self.j * x, .azbz = self.azbz, }; } pub fn desaturate(self: *const Self, x: T_) Self { return Self{ .j = self.j, .azbz = self.azbz.scale(x), }; } pub fn mixPow(self: *const Self, j0: T_, j1: T_, jp: T_, c0: T_, c1: T_, cp: T_) Self { return Self{ .j = gmath.mixPow(j0, j1, jp, self.j), .azbz = self.azbz.mixPow(c0, c1, cp), }; } pub fn mix(self: Self, other: Self, alpha: T_) Self { return Self{ .j = gmath.mix(self.j, other.j, alpha), .azbz = AzBz.mix(self.azbz, other.azbz, alpha), }; } pub fn add(self: *const Self, other: Self) Self { return JazbzField.add(self.*, other); } pub fn mul(self: *const Self, other: Self) Self { return JazbzField.mul(self.*, other); } pub fn complement(self: *const Self) Self { return Self{ .j = 1 - self.j, .azbz = self.azbz.rotate180(), }; } pub const JazbzField = struct { pub const T: type = Self; pub const zero: Self = Self{ .j = 0, .azbz = AzBz.AzBzField.zero }; pub const one: Self = Self{ .j = 1, .azbz = AzBz.AzBzField.one }; pub fn mul(a: Self, b: Self) Self { return Self{ .j = a.j * b.j, .azbz = AzBz.AzBzField.mul(a.azbz, b.azbz), }; } pub fn add(a: Self, b: Self) Self { return Self{ .j = a.j + b.j, .azbz = AzBz.AzBzField.add(a.azbz, b.azbz), }; } pub fn neg(a: Self) Self { return Self{ .j = -a.j, .azbz = AzBz.AzBzField.neg(a.azbz), }; } pub fn inv(a: Self) Self { return Self{ .j = 1 / a.j, .azbz = AzBz.AzBzField.inv(a.azbz), }; } }; pub fn addMean(self: *const Self, c: Self) JazbzMean { return JazbzMean.fromJazbz(self.*).addMean(c); } pub const JazbzMean = struct { const T = @This(); n: usize = 0, jab: Self = .{}, pub fn fromJazbz(c: Self) T { return .{ .n = 1, .jab = c, }; } pub fn addMean(self: *T, c: Self) T { return self.combine(fromJazbz(c)); } pub fn combine(self: *const T, other: T) T { return .{ .n = self.n + other.n, .jab = self.jab.add(other.jab), }; } pub fn toJazbz(self: *T) Self { return self.jab.scale(1 / @intToFloat(f64, math.max(self.n, 1))); } }; pub fn addLight(self: *const Self, c: Self) JazbzLight { return JazbzLight.fromJazbz(self.*).addLight(c); } pub fn addWhite(self: *const Self, j: f64) JazbzLight { return JazbzLight.fromJazbz(self.*).addWhite(j); } pub const JazbzLight = struct { const T = @This(); j: T_ = 0, az: T_ = 0, bz: T_ = 0, pub fn fromJazbz(c: Self) T { return .{ .j = c.j, .az = c.azbz.az * c.j, .bz = c.azbz.bz * c.j, }; } pub fn addLight(self: *const T, c: Self) T { return self.combine(fromJazbz(c)); } pub fn addWhite(self: *const T, j: f64) T { return .{ .j = self.j + j, .az = self.az, .bz = self.bz, }; } pub fn scaleJ(self: *const T, x: f64) T { return .{ .j = self.j * x, .az = self.az, .bz = self.bz, }; } pub fn combine(self: *const T, jc: T) T { return .{ .j = self.j + jc.j, .az = self.az + jc.az, .bz = self.bz + jc.bz, }; } pub fn toJazbz(self: *const T) Self { if (self.j == 0) { return Self.black; } else { return .{ .j = self.j, .azbz = .{ .az = self.az / self.j, .bz = self.bz / self.j, }, }; } } }; }; } fn AzBzType(comptime T_: type) type { return struct { const Self = @This(); pub const Ch = ChType(T_); az: T_ = 0, bz: T_ = 0, pub const cm = 0.15934590589262138; pub const cmn = cm * invSqrt2; pub const grey = Self{ .az = 0, .bz = 0 }; pub const violet = Self{ .az = 0, .bz = -cm }; // Payne's gray - ink - twilight pub const blue = Self{ .az = -cmn, .bz = -cmn }; // cerulean - sky pub const teal = Self{ .az = -cm, .bz = 0 }; // viridian - sea pub const green = Self{ .az = -cmn, .bz = cmn }; // cadmium green - forest pub const yellow = Self{ .az = 0, .bz = cm }; // raw sienna - earth - olive pub const red = Self{ .az = cmn, .bz = cmn }; // vermillion - blood pub const pink = Self{ .az = cm, .bz = 0 }; // alizarian crimson - rose pub const purple = Self{ .az = cmn, .bz = -cmn }; // quinacridone violet pub const orange = Self.initCh(1.0, 0.7); pub fn initCh(chroma: anytype, hue: anytype) Self { const cz = chroma * cm; const hz: f64 = hue * 6.28318530717958647 + -3.14159265358979323; const az = cz * math.cos(hz); const bz = cz * math.sin(hz); return Self{ .az = @floatCast(T_, az), .bz = @floatCast(T_, bz) }; } pub fn toCh(self: *const Self) Ch { const cz = math.hypot(T_, self.az, self.bz); const hz = math.atan2(T_, self.bz, self.az); const c = cz * 6.2756554327405890; const h = hz * 0.15915494309189535 + 0.5; return Ch{ .c = c, .h = h, }; } pub fn scalar(x: T_) Self { return Self{ .az = x, .bz = x }; } pub fn scale(self: *const Self, x: T_) Self { return Self{ .az = self.az * x, .bz = self.bz * x, }; } pub fn mixPow(self: *const Self, c0: T_, c1: T_, cp: T_) Self { if ((c0 == 0 and c1 == 1 and cp == 1) or (self.az == 0 and self.bz == 0)) { return self.*; } const cz = math.hypot(T_, self.az, self.bz); const cz_ = gmath.mixPow(c0, c1, cp, cz); return self.scale(cz_ / cz); } pub fn rotate90(self: *const Self) Self { return .{ .az = -self.bz, .bz = self.az, }; } pub fn rotate180(self: *const Self) Self { return .{ .az = -self.az, .bz = -self.bz, }; } pub fn rotate270(self: *const Self) Self { return .{ .az = self.bz, .bz = -self.az, }; } pub fn rotate(self: *const Self, rx: T_, ry: T_) Self { return Self{ .az = rx * self.az + ry * self.bz, .bz = -ry * self.az + rx * self.bz, }; } pub fn rotateA(self: *const Self, t: T_) Self { return self.rotate(math.cos(t), -math.sin(t)); } pub fn mix(self: Self, other: Self, alpha: T_) Self { return Self{ .az = gmath.mix(self.az, other.az, alpha), .bz = gmath.mix(self.bz, other.bz, alpha), }; } pub fn add(self: *const Self, other: Self) Self { return AzBzField.add(self.*, other); } pub const AzBzField = struct { pub const T: type = Self; pub const zero: Self = Self{ .az = 0, .bz = 0 }; pub const one: Self = Self{ .az = 1, .bz = 1 }; pub fn mul(x: Self, y: Self) Self { return Self{ //.az = x.az * y.az + x.bz * y.bz, //.bz = x.az * y.bz + y.bz * x.az, .az = x.az * y.az, .bz = x.bz * y.bz, }; } pub fn add(x: Self, y: Self) Self { return Self{ .az = x.az + y.az, .bz = x.bz + y.bz, }; } pub fn neg(x: Self) Self { return Self{ .az = -x.az, .bz = -x.bz, }; } pub fn inv(x: Self) Self { const h = 1 / (x.az * x.az + x.bz); return Self{ //.az = x.az * h, //.bz = -x.bz * h, .az = 1 / x.az, .bz = 1 / x.bz, }; } }; }; } fn ChType(comptime T: type) type { return struct { const Self = @This(); pub const AzBz = AzBzType(T); c: T, h: T, pub fn initCh(chroma: anytype, hue: anytype) Self { return Self{ .c = @floatCast(T, chroma), .h = @floatCast(T, hue) }; } pub fn toAzBz(self: *const Self) AzBz { return AzBz.initCh(self.c, self.h); } }; } pub fn jTojz(j: anytype) @TypeOf(j) { return j * 0.16717463120366200 + 1.6295499532821566e-11; } pub fn jzToj(j: anytype) @TypeOf(j) { return (j - 1.6295499532821566e-11) / 0.16717463120366200; } pub fn jzazbzToSrgb(comptime T: type, jz: anytype, az: anytype, bz: anytype) Srgb(T) { const iz0 = jz + 1.6295499532821566e-11; const iz1 = jz * 0.56 + 0.4400000000091254797; const iz = iz0 / iz1; const l0 = iz + az * 0.1386050432715393022 + bz * 0.05804731615611882778; const m0 = iz + az * -0.1386050432715392744 + bz * -0.05804731615611890411; const s0 = iz + az * -0.09601924202631895167 + bz * -0.8118918960560389531; const l1 = pow(math.max(l0, 0), 0.007460772656268214777); const m1 = pow(math.max(m0, 0), 0.007460772656268214777); const s1 = pow(math.max(s0, 0), 0.007460772656268214777); const l2 = 0.8359375 - l1; const m2 = 0.8359375 - m1; const s2 = 0.8359375 - s1; const l3 = l1 * 18.6875000 - 18.8515625; const m3 = m1 * 18.6875000 - 18.8515625; const s3 = s1 * 18.6875000 - 18.8515625; const l4 = l2 / l3; const m4 = m2 / m3; const s4 = s2 / s3; const l5 = pow(math.max(l4, 0), 6.277394636015325670); const m5 = pow(math.max(m4, 0), 6.277394636015325670); const s5 = pow(math.max(s4, 0), 6.277394636015325670); const sr0 = l5 * 592.8963755404249891 + m5 * -522.3947425797513470 + s5 * 32.59644233339026778; const sg0 = l5 * -222.3295790445721752 + m5 * 382.1527473694614592 + s5 * -57.03433147128811548; const sb0 = l5 * 6.270913830078805615 + m5 * -70.21906556220011906 + s5 * 166.6975603243740906; const sr1 = sr0 * 12.92; const sg1 = sg0 * 12.92; const sb1 = sb0 * 12.92; const sr2 = pow(math.max(sr0, 0), 0.4166666666666666666); const sg2 = pow(math.max(sg0, 0), 0.4166666666666666666); const sb2 = pow(math.max(sb0, 0), 0.4166666666666666666); const sr3 = sr2 * 1.055 + -0.055; const sg3 = sg2 * 1.055 + -0.055; const sb3 = sb2 * 1.055 + -0.055; const sr = if (sr0 <= 0.003130804953560371341) sr1 else sr3; const sg = if (sg0 <= 0.003130804953560371341) sg1 else sg3; const sb = if (sb0 <= 0.003130804953560371341) sb1 else sb3; return Srgb(T).initFloat(sr, sg, sb); } pub fn srgb255ToJzazbz(comptime T: type, sr: anytype, sg: anytype, sb: anytype) Jazbz(T) { if (@floatToInt(usize, sr) == 255 and @floatToInt(usize, sg) == 255 and @floatToInt(usize, sb) == 255) { return Jazbz(T).white; } else if (@floatToInt(usize, sr) == 0 and @floatToInt(usize, sg) == 0 and @floatToInt(usize, sb) == 0) { return Jazbz(T).black; } const r = if (sr <= 10.31475) (sr * 0.0003035269835488375) else pow(sr * 0.003717126661090977 + 0.052132701421800948, 2.4); const g = if (sg <= 10.31475) (sg * 0.0003035269835488375) else pow(sg * 0.003717126661090977 + 0.052132701421800948, 2.4); const b = if (sb <= 10.31475) (sb * 0.0003035269835488375) else pow(sb * 0.003717126661090977 + 0.052132701421800948, 2.4); const l1 = r * 0.003585083359727932572 + g * 0.005092044060011000719 + b * 0.001041169201586239260; const m1 = r * 0.002204179837045521148 + g * 0.005922988107728221186 + b * 0.001595495732321790141; const s1 = r * 0.0007936150919572405067 + g * 0.002303422557560143382 + b * 0.006631801538878254703; const l2 = pow(l1, 0.1593017578125); const m2 = pow(m1, 0.1593017578125); const s2 = pow(s1, 0.1593017578125); const l3 = l2 * 18.8515625 + 0.8359375; const m3 = m2 * 18.8515625 + 0.8359375; const s3 = s2 * 18.8515625 + 0.8359375; const l4 = l2 * 18.6875 + 1; const m4 = m2 * 18.6875 + 1; const s4 = s2 * 18.6875 + 1; const l = pow(l3 / l4, 134.034375); const m = pow(m3 / m4, 134.034375); const s = pow(s3 / s4, 134.034375); const jz0 = l * 0.5 + m * 0.5; const jz1 = jz0 * 0.44; const jz2 = jz0 * -0.56 + 1; const jz3 = jz1 / jz2; const jz = jz3 + -1.6295499532821566e-11; const az = l * 3.524 + m * -4.066708 + s * 0.542708; const bz = l * 0.199076 + m * 1.096799 + s * -1.295875; return Jazbz(T){ .j = math.min(math.max(jzToj(jz), 0.0), 1.0), .azbz = Jazbz(T).AzBz{ .az = az, .bz = bz }, }; } fn pow(x: anytype, a: anytype) @TypeOf(x + a) { const T = @TypeOf(x + a); return math.pow(T, x, a); } pub fn Srgb(comptime T: type) type { return struct { const Self = @This(); r: T, g: T, b: T, pub fn initFloat(r: anytype, g: anytype, b: anytype) Srgb(T) { return Srgb(T){ .r = floatTo(T, r), .g = floatTo(T, g), .b = floatTo(T, b), }; } pub fn toHtmlColor(self: *const Self) ![]u8 { var result: [15]u8 = undefined; return try fmt.bufPrint(result[0..], "#{x:0<2}{x:0<2}{x:0<2}", @floatToInt(u8, self.r * 0xff), @floatToInt(u8, self.g * 0xff), @floatToInt(u8, self.b * 0xff)); } }; } pub fn floatTo(comptime T: type, x: anytype) T { const y = clamp(0, 1, x); if (T == f32 or T == f64) { return y; } else { return @floatToInt(T, y * math.maxInt(T)); } } pub fn clamp(e0: anytype, e1: anytype, x: anytype) @TypeOf(x + e0 + e1) { if (x < e0) { return e0; } else if (x > e1) { return e1; } else { return x; } }
lib/jabz.zig
const std = @import("std"); const subcommands = @import("subcommands.zig"); const shared = @import("shared.zig"); const options = @import("options"); const builtin = @import("builtin"); const zsw = @import("zsw"); pub const enable_tracy = options.trace; pub const tracy_enable_callstack = true; const log = std.log.scoped(.main); var allocator_backing = if (!shared.is_debug_or_test) std.heap.ArenaAllocator.init(std.heap.page_allocator) else {}; var gpa = if (shared.is_debug_or_test) std.heap.GeneralPurposeAllocator(.{}){} else std.heap.stackFallback(std.mem.page_size, allocator_backing.allocator()); pub fn main() if (shared.is_debug_or_test) subcommands.ExecuteError!u8 else u8 { const main_z = shared.tracy.traceNamed(@src(), "main"); // this causes the frame to start with our main instead of `std.start` shared.tracy.frameMark(); defer { if (shared.is_debug_or_test) { _ = gpa.deinit(); } main_z.end(); } const gpa_allocator: std.mem.Allocator = if (shared.is_debug_or_test) gpa.allocator() else gpa.get(); var tracy_allocator = if (enable_tracy) shared.tracy.TracyAllocator(null).init(gpa_allocator) else {}; const allocator = if (enable_tracy) tracy_allocator.allocator() else gpa_allocator; var argument_info = ArgumentInfo.fetch(); const io_buffers_z = shared.tracy.traceNamed(@src(), "io buffers"); var std_in_buffered = std.io.bufferedReader(std.io.getStdIn().reader()); var std_out_buffered = std.io.bufferedWriter(std.io.getStdOut().writer()); io_buffers_z.end(); const stderr_writer = std.io.getStdErr().writer(); const io = .{ .stderr = stderr_writer, .stdin = std_in_buffered.reader(), .stdout = std_out_buffered.writer(), }; const result = subcommands.execute( allocator, &argument_info.arg_iter, io, argument_info.basename, zsw.host_system, argument_info.exe_path, ) catch |err| { switch (err) { error.NoSubcommand => blk: { stderr_writer.writeByte('\'') catch break :blk; stderr_writer.writeAll(argument_info.basename) catch break :blk; stderr_writer.writeAll("' subcommand not found\n") catch break :blk; }, error.OutOfMemory => stderr_writer.writeAll("out of memory\n") catch {}, error.UnableToParseArguments => stderr_writer.writeAll("unable to parse arguments\n") catch {}, } if (shared.is_debug_or_test) return err; return 1; }; // Only flush stdout if the command completed successfully // If we flush stdout after printing an error then the error message will not be the last thing printed if (result == 0) { const flush_z = shared.tracy.traceNamed(@src(), "stdout flush"); defer flush_z.end(); log.debug("flushing stdout buffer on successful execution", .{}); std_out_buffered.flush() catch |err| { shared.unableToWriteTo("stdout", io, err); return 1; }; } return result; } const ArgumentInfo = struct { basename: []const u8, exe_path: [:0]const u8, arg_iter: std.process.ArgIterator, pub fn fetch() ArgumentInfo { const z = shared.tracy.traceNamed(@src(), "fetch argument info"); defer z.end(); var arg_iter = std.process.args(); const exe_path = arg_iter.next() orelse unreachable; const basename = std.fs.path.basename(exe_path); log.debug("got exe_path: \"{s}\" with basename: \"{s}\"", .{ exe_path, basename }); return ArgumentInfo{ .basename = basename, .exe_path = exe_path, .arg_iter = arg_iter, }; } }; comptime { std.testing.refAllDecls(@This()); }
src/main.zig
const std = @import("std"); const testing = std.testing; const Regex = @import("libpcre").Regex; const Error = error{OutOfMemory}; const MemoizedRegexes = struct { atxHeadingStart: ?Regex = null, thematicBreak: ?Regex = null, setextHeadingLine: ?Regex = null, autolinkUri: ?Regex = null, autolinkEmail: ?Regex = null, openCodeFence: ?Regex = null, closeCodeFence: ?Regex = null, htmlBlockStart1: ?Regex = null, htmlBlockStart4: ?Regex = null, htmlBlockStart6: ?Regex = null, htmlBlockStart7: ?Regex = null, htmlTag: ?Regex = null, spacechars: ?Regex = null, linkTitle: ?Regex = null, dangerousUrl: ?Regex = null, tableStart: ?Regex = null, tableCell: ?Regex = null, tableCellEnd: ?Regex = null, tableRowEnd: ?Regex = null, removeAnchorizeRejectedChars: ?Regex = null, }; var memoized = MemoizedRegexes{}; // pub fn deinitRegexes() void { // inline for (@typeInfo(MemoizedRegexes).Struct.fields) |field| { // if (@field(memoized, field.name)) |re| { // re.deinit(); // @field(memoized, field.name) = null; // } // } // } fn acquire(comptime name: []const u8, regex: [:0]const u8) Error!Regex { const field_name = comptime if (std.mem.lastIndexOf(u8, name, ".")) |i| name[i + 1 ..] else name; if (@field(memoized, field_name)) |re| { return re; } @field(memoized, field_name) = Regex.compile(regex, .{ .Utf8 = true }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => unreachable, }; return @field(memoized, field_name).?; } fn search(re: Regex, line: []const u8) ?usize { if (re.matches(line, .{ .Anchored = true }) catch null) |cap| { return cap.end; } return null; } pub fn unwrap(value: Error!?usize, out: *usize) Error!bool { if (value) |maybe_val| { if (maybe_val) |val| { out.* = val; return true; } return false; } else |err| { return err; } } var searchFirstCaptureBuffer: [1024]u8 = [_]u8{undefined} ** 1024; var searchFirstCaptureBufferAllocator = std.heap.FixedBufferAllocator.init(&searchFirstCaptureBuffer); fn searchFirstCapture(re: Regex, line: []const u8) Error!?usize { searchFirstCaptureBufferAllocator.reset(); var result = re.captures(searchFirstCaptureBufferAllocator.allocator(), line, .{ .Anchored = true }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => null, }; if (result) |caps| { var i: usize = 1; while (i < caps.len) : (i += 1) { if (caps[i]) |cap| { return cap.end; } } @panic("no matching capture group"); } return null; } pub fn atxHeadingStart(line: []const u8) Error!?usize { if (line[0] != '#') { return null; } const re = try acquire(@src().fn_name, "#{1,6}[ \t\r\n]"); return search(re, line); } pub fn thematicBreak(line: []const u8) Error!?usize { if (line[0] != '*' and line[0] != '-' and line[0] != '_') { return null; } const re = try acquire(@src().fn_name, "(?:(?:\\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})[ \t]*[\r\n]"); return search(re, line); } test "thematicBreak" { try testing.expectEqual(@as(?usize, null), try thematicBreak("hello")); try testing.expectEqual(@as(?usize, 4), try thematicBreak("***\n")); try testing.expectEqual(@as(?usize, 21), try thematicBreak("- - - \r")); try testing.expectEqual(@as(?usize, 21), try thematicBreak("- - - \r\nxyz")); } pub const SetextChar = enum { Equals, Hyphen, }; pub fn setextHeadingLine(line: []const u8, sc: *SetextChar) Error!bool { const re = try acquire(@src().fn_name, "(?:=+|-+)[ \t]*[\r\n]"); if ((line[0] == '=' or line[0] == '-') and search(re, line) != null) { sc.* = if (line[0] == '=') .Equals else .Hyphen; return true; } return false; } const scheme = "[A-Za-z][A-Za-z0-9.+-]{1,31}"; pub fn autolinkUri(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, scheme ++ ":[^\\x00-\\x20<>]*>"); return search(re, line); } test "autolinkUri" { try testing.expectEqual(@as(?usize, null), try autolinkUri("www.google.com>")); try testing.expectEqual(@as(?usize, 23), try autolinkUri("https://www.google.com>")); try testing.expectEqual(@as(?usize, 7), try autolinkUri("a+b-c:>")); try testing.expectEqual(@as(?usize, null), try autolinkUri("a+b-c:")); } pub fn autolinkEmail(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, \\[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*> ); return search(re, line); } test "autolinkEmail" { try testing.expectEqual(@as(?usize, null), try autolinkEmail("abc>")); try testing.expectEqual(@as(?usize, null), try autolinkEmail("abc.def>")); try testing.expectEqual(@as(?usize, null), try autolinkEmail("abc@def")); try testing.expectEqual(@as(?usize, 8), try autolinkEmail("abc@def>")); try testing.expectEqual(@as(?usize, 16), try autolinkEmail("abc+123!?@96--1>")); } pub fn openCodeFence(line: []const u8) Error!?usize { if (line[0] != '`' and line[0] != '~') return null; const re = try acquire(@src().fn_name, "(?:(`{3,})[^`\r\n\\x00]*|(~{3,})[^\r\n\\x00]*)[\r\n]"); return searchFirstCapture(re, line); } test "openCodeFence" { try testing.expectEqual(@as(?usize, null), try openCodeFence("```m")); try testing.expectEqual(@as(?usize, 3), try openCodeFence("```m\n")); try testing.expectEqual(@as(?usize, 6), try openCodeFence("~~~~~~m\n")); } pub fn closeCodeFence(line: []const u8) Error!?usize { if (line[0] != '`' and line[0] != '~') return null; const re = try acquire(@src().fn_name, "(`{3,}|~{3,})[\t ]*[\r\n]"); return searchFirstCapture(re, line); } test "closeCodeFence" { try testing.expectEqual(@as(?usize, null), try closeCodeFence("```m")); try testing.expectEqual(@as(?usize, 3), try closeCodeFence("```\n")); try testing.expectEqual(@as(?usize, 6), try closeCodeFence("~~~~~~\r\n")); } pub fn htmlBlockEnd1(line: []const u8) bool { return std.ascii.indexOfIgnoreCase(line, "</script>") != null or std.ascii.indexOfIgnoreCase(line, "</pre>") != null or std.ascii.indexOfIgnoreCase(line, "</style>") != null; } test "htmlBlockEnd1" { try testing.expect(htmlBlockEnd1(" xyz </script> ")); try testing.expect(htmlBlockEnd1(" xyz </SCRIPT> ")); try testing.expect(!htmlBlockEnd1(" xyz </ script> ")); } pub fn htmlBlockEnd2(line: []const u8) bool { return std.mem.indexOf(u8, line, "-->") != null; } pub fn htmlBlockEnd3(line: []const u8) bool { return std.mem.indexOf(u8, line, "?>") != null; } pub fn htmlBlockEnd4(line: []const u8) bool { return std.mem.indexOfScalar(u8, line, '>') != null; } pub fn htmlBlockEnd5(line: []const u8) bool { return std.mem.indexOf(u8, line, "]]>") != null; } pub fn htmlBlockStart(line: []const u8, sc: *usize) Error!bool { if (line[0] != '<') return false; const re1 = try acquire("htmlBlockStart1", "<(?i:script|pre|style)[ \t\\x0b\\x0c\r\n>]"); const re4 = try acquire("htmlBlockStart4", "<![A-Z]"); const re6 = try acquire("htmlBlockStart6", "</?(?i:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|title|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:[ \t\\x0b\\x0c\r\n>]|/>)"); if (search(re1, line) != null) { sc.* = 1; } else if (std.mem.startsWith(u8, line, "<!--")) { sc.* = 2; } else if (std.mem.startsWith(u8, line, "<?")) { sc.* = 3; } else if (search(re4, line) != null) { sc.* = 4; } else if (std.mem.startsWith(u8, line, "<![CDATA[")) { sc.* = 5; } else if (search(re6, line) != null) { sc.* = 6; } else { return false; } return true; } test "htmlBlockStart" { var sc: usize = undefined; try testing.expect(!try htmlBlockStart("<xyz", &sc)); try testing.expect(try htmlBlockStart("<Script\r", &sc)); try testing.expectEqual(@as(usize, 1), sc); try testing.expect(try htmlBlockStart("<pre>", &sc)); try testing.expectEqual(@as(usize, 1), sc); try testing.expect(try htmlBlockStart("<!-- h", &sc)); try testing.expectEqual(@as(usize, 2), sc); try testing.expect(try htmlBlockStart("<?m", &sc)); try testing.expectEqual(@as(usize, 3), sc); try testing.expect(try htmlBlockStart("<!Q", &sc)); try testing.expectEqual(@as(usize, 4), sc); try testing.expect(try htmlBlockStart("<![CDATA[\n", &sc)); try testing.expectEqual(@as(usize, 5), sc); try testing.expect(try htmlBlockStart("</ul>", &sc)); try testing.expectEqual(@as(usize, 6), sc); try testing.expect(try htmlBlockStart("<figcaption/>", &sc)); try testing.expectEqual(@as(usize, 6), sc); try testing.expect(!try htmlBlockStart("<xhtml>", &sc)); } const space_char = "[ \t\\x0b\\x0c\r\n]"; const tag_name = "(?:[A-Za-z][A-Za-z0-9-]*)"; const close_tag = "(?:/" ++ tag_name ++ space_char ++ "*>)"; const attribute_name = "(?:[a-zA_Z_:][a-zA-Z0-9:._-]*)"; const attribute_value = "(?:(?:[^ \t\r\n\\x0b\\x0c\"'=<>`\\x00]+)|(?:'[^\\x00']*')|(?:\"[^\\x00\"]*\"))"; const attribute_value_spec = "(?:" ++ space_char ++ "*=" ++ space_char ++ "*" ++ attribute_value ++ ")"; const attribute = "(?:" ++ space_char ++ "+" ++ attribute_name ++ attribute_value_spec ++ "?)"; const open_tag = "(?:" ++ tag_name ++ attribute ++ "*" ++ space_char ++ "*/?>)"; pub fn htmlBlockStart7(line: []const u8, sc: *usize) Error!bool { const re = try acquire(@src().fn_name, "<(?:" ++ open_tag ++ "|" ++ close_tag ++ ")[\t\\x0c ]*[\r\n]"); if (search(re, line) != null) { sc.* = 7; return true; } return false; } test "htmlBlockStart7" { var sc: usize = 1; try testing.expect(!try htmlBlockStart7("<a", &sc)); try testing.expect(try htmlBlockStart7("<a> \n", &sc)); try testing.expectEqual(@as(usize, 7), sc); try testing.expect(try htmlBlockStart7("<b2/>\r", &sc)); try testing.expect(try htmlBlockStart7("<b2\ndata=\"foo\" >\t\x0c\n", &sc)); try testing.expect(try htmlBlockStart7("<a foo=\"bar\" bam = 'baz <em>\"</em>'\n_boolean zoop:33=zoop:33 />\n", &sc)); try testing.expect(!try htmlBlockStart7("<a h*#ref=\"hi\">\n", &sc)); } const html_comment = "(?:!---->|(?:!---?[^\\x00>-](?:-?[^\\x00-])*-->))"; const processing_instruction = "(?:\\?(?:[^?>\\x00]+|\\?[^>\\x00]|>)*\\?>)"; const declaration = "(?:![A-Z]+" ++ space_char ++ "+[^>\\x00]*>)"; const cdata = "(?:!\\[CDATA\\[(?:[^\\]\\x00]+|\\][^\\]\\x00]|\\]\\][^>\\x00])*]]>)"; pub fn htmlTag(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, "(?:" ++ open_tag ++ "|" ++ close_tag ++ "|" ++ html_comment ++ "|" ++ processing_instruction ++ "|" ++ declaration ++ "|" ++ cdata ++ ")"); return search(re, line); } test "htmlTag" { try testing.expectEqual(@as(?usize, 6), try htmlTag("!---->")); try testing.expectEqual(@as(?usize, 9), try htmlTag("!--x-y-->")); try testing.expectEqual(@as(?usize, 5), try htmlTag("?zy?>")); try testing.expectEqual(@as(?usize, 6), try htmlTag("?z?y?>")); try testing.expectEqual(@as(?usize, 14), try htmlTag("!ABCD aoea@#&>")); try testing.expectEqual(@as(?usize, 11), try htmlTag("![CDATA[]]>")); try testing.expectEqual(@as(?usize, 20), try htmlTag("![CDATA[a b\n c d ]]>")); try testing.expectEqual(@as(?usize, 23), try htmlTag("![CDATA[\r]abc]].>\n]>]]>")); } pub fn spacechars(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, space_char ++ "+"); return search(re, line); } const link_title = "(?:\"(?:\\\\.|[^\"\\x00])*\"|'(?:\\\\.|[^'\\x00])*'|\\((?:\\\\.|[^()\\x00])*\\))"; pub fn linkTitle(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, link_title); return search(re, line); } test "linkTitle" { try testing.expectEqual(@as(?usize, null), try linkTitle("\"xyz")); try testing.expectEqual(@as(?usize, 5), try linkTitle("\"xyz\"")); try testing.expectEqual(@as(?usize, 7), try linkTitle("\"x\\\"yz\"")); try testing.expectEqual(@as(?usize, null), try linkTitle("'xyz")); try testing.expectEqual(@as(?usize, 5), try linkTitle("'xyz'")); try testing.expectEqual(@as(?usize, null), try linkTitle("(xyz")); try testing.expectEqual(@as(?usize, 5), try linkTitle("(xyz)")); } const dangerous_url = "(?:data:(?!png|gif|jpeg|webp)|javascript:|vbscript:|file:)"; pub fn dangerousUrl(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, dangerous_url); return search(re, line); } test "dangerousUrl" { try testing.expectEqual(@as(?usize, null), try dangerousUrl("http://thing")); try testing.expectEqual(@as(?usize, 5), try dangerousUrl("data:xyz")); try testing.expectEqual(@as(?usize, null), try dangerousUrl("data:png")); try testing.expectEqual(@as(?usize, null), try dangerousUrl("data:webp")); try testing.expectEqual(@as(?usize, 5), try dangerousUrl("data:a")); try testing.expectEqual(@as(?usize, 11), try dangerousUrl("javascript:")); } const table_spacechar = "[ \t\\x0b\\x0c]"; const table_newline = "(?:\r?\n)"; const table_marker = "(?:" ++ table_spacechar ++ "*:?-+:?" ++ table_spacechar ++ "*)"; const table_cell = "(?:(\\\\.|[^|\r\n])*)"; pub fn tableStart(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, "\\|?" ++ table_marker ++ "(?:\\|" ++ table_marker ++ ")*\\|?" ++ table_spacechar ++ "*" ++ table_newline); return search(re, line); } test "tableStart" { try testing.expectEqual(@as(?usize, null), try tableStart(" \r\n")); try testing.expectEqual(@as(?usize, 7), try tableStart(" -- |\r\n")); try testing.expectEqual(@as(?usize, 14), try tableStart("| :-- | -- |\r\n")); try testing.expectEqual(@as(?usize, null), try tableStart("| -:- | -- |\r\n")); } pub fn tableCell(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, table_cell); return search(re, line); } test "tableCell" { try testing.expectEqual(@as(?usize, 3), try tableCell("abc|def")); try testing.expectEqual(@as(?usize, 8), try tableCell("abc\\|def")); try testing.expectEqual(@as(?usize, 5), try tableCell("abc\\\\|def")); } pub fn tableCellEnd(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, "\\|" ++ table_spacechar ++ "*" ++ table_newline ++ "?"); return search(re, line); } test "tableCellEnd" { try testing.expectEqual(@as(?usize, 1), try tableCellEnd("|")); try testing.expectEqual(@as(?usize, null), try tableCellEnd(" |")); try testing.expectEqual(@as(?usize, 1), try tableCellEnd("|a")); try testing.expectEqual(@as(?usize, 3), try tableCellEnd("| \r")); try testing.expectEqual(@as(?usize, 4), try tableCellEnd("| \n")); try testing.expectEqual(@as(?usize, 5), try tableCellEnd("| \r\n")); } pub fn tableRowEnd(line: []const u8) Error!?usize { const re = try acquire(@src().fn_name, table_spacechar ++ "*" ++ table_newline); return search(re, line); } test "tableRowEnd" { try testing.expectEqual(@as(?usize, null), try tableRowEnd("a")); try testing.expectEqual(@as(?usize, 1), try tableRowEnd("\na")); try testing.expectEqual(@as(?usize, null), try tableRowEnd(" a")); try testing.expectEqual(@as(?usize, 4), try tableRowEnd(" \na")); try testing.expectEqual(@as(?usize, 5), try tableRowEnd(" \r\na")); } pub fn removeAnchorizeRejectedChars(allocator: std.mem.Allocator, src: []const u8) Error![]u8 { const re = try acquire(@src().fn_name, "[^\\p{L}\\p{M}\\p{N}\\p{Pc} -]"); var output = std.ArrayList(u8).init(allocator); errdefer output.deinit(); var org: usize = 0; while (re.matches(src[org..], .{}) catch null) |cap| { try output.appendSlice(src[org .. org + cap.start]); org += cap.end; if (org >= src.len) break; } try output.appendSlice(src[org..]); return output.toOwnedSlice(); } test "removeAnchorizeRejectedChars" { for ([_][]const u8{ "abc", "'abc", "''abc", "a'bc", "'a'''b'c'" }) |abc| { var result = try removeAnchorizeRejectedChars(std.testing.allocator, abc); try testing.expectEqualStrings("abc", result); std.testing.allocator.free(result); } }
src/scanners.zig
usingnamespace @import("root").preamble; pub var bsp_task: os.thread.Task = .{ .name = "BSP task", }; const TPIDR_EL1 = os.platform.msr(*os.platform.smp.CoreData, "TPIDR_EL1"); pub const CoreData = struct { pub fn start_monitoring(self: *@This()) void {} pub fn wait(self: *@This()) void { os.platform.spin_hint(); } pub fn ring(self: *@This()) void {} }; pub const sched_stack_size = 0x10000; pub const int_stack_size = 0x10000; pub const task_stack_size = 0x10000; pub const stack_guard_size = 0x1000; pub const ap_init_stack_size = 0x4000; pub fn get_current_cpu() *os.platform.smp.CoreData { return TPIDR_EL1.read(); } pub fn set_current_cpu(ptr: *os.platform.smp.CoreData) void { TPIDR_EL1.write(ptr); } pub const TaskData = struct { pub fn loadState(self: *@This()) void { const cpu = os.platform.thread.get_current_cpu(); } }; pub fn sched_call_impl(fun: usize, ctx: usize) void { asm volatile ( \\SVC #'S' : : [_] "{X2}" (fun), [_] "{X1}" (ctx) : "memory" ); } pub fn enter_userspace(entry: u64, arg: u64, stack: u64) noreturn { asm volatile ( \\ MOV SP, %[stack] \\ MSR ELR_EL1, %[entry] \\ MOV X1, #0 \\ MSR SPSR_EL1, X1 \\ \\ MOV X2, #0 \\ MOV X3, #0 \\ MOV X4, #0 \\ MOV X5, #0 \\ MOV X6, #0 \\ MOV X7, #0 \\ MOV X8, #0 \\ MOV X9, #0 \\ MOV X10, #0 \\ MOV X11, #0 \\ MOV X12, #0 \\ MOV X13, #0 \\ MOV X14, #0 \\ MOV X15, #0 \\ MOV X16, #0 \\ MOV X17, #0 \\ MOV X18, #0 \\ MOV X19, #0 \\ MOV X20, #0 \\ MOV X21, #0 \\ MOV X22, #0 \\ MOV X23, #0 \\ MOV X24, #0 \\ MOV X25, #0 \\ MOV X26, #0 \\ MOV X27, #0 \\ MOV X28, #0 \\ MOV X29, #0 \\ MOV X30, #0 \\ \\ ERET \\ : : [arg] "{X0}" (arg), [stack] "r" (stack), [entry] "r" (entry) ); unreachable; } pub fn init_task_call(new_task: *os.thread.Task, entry: *os.thread.NewTaskEntry) !void { const cpu = os.platform.thread.get_current_cpu(); new_task.registers.pc = @ptrToInt(entry.function); new_task.registers.x0 = @ptrToInt(entry); new_task.registers.sp = lib.util.libalign.alignDown(usize, 16, @ptrToInt(entry)); new_task.registers.spsr = 0b0100; // EL1t / EL1 with SP0 } pub fn self_exited() ?*os.thread.Task { const curr = os.platform.get_current_task(); if (curr == &bsp_task) return null; return curr; }
subprojects/flork/src/platform/aarch64/thread.zig
const Garmin = @This(); const std = @import("std"); const mem = std.mem; const testing = std.testing; const Allocator = std.mem.Allocator; const FlightPlan = @import("../FlightPlan.zig"); const Waypoint = @import("../Waypoint.zig"); const format = @import("../format.zig"); const testutil = @import("../test.zig"); const xml = @import("../xml.zig"); const c = xml.c; const Error = @import("../Error.zig"); const ErrorSet = Error.Set; const Route = @import("../Route.zig"); test { _ = Binding; _ = Reader; _ = Writer; } /// The Format type that can be used with the generic functions on FlightPlan. /// You can also call the direct functions in this file. pub const Format = format.Format(Garmin); /// Initialize a flightplan from a file. pub fn initFromFile(alloc: Allocator, path: [:0]const u8) !FlightPlan { return Reader.initFromFile(alloc, path); } /// Encode a flightplan to this format to the given writer. writer should /// be a std.io.Writer-like implementation. pub fn writeTo(writer: anytype, fpl: *const FlightPlan) !void { return Writer.writeTo(writer, fpl); } /// Binding are the C bindings for this format. pub const Binding = struct { const binding = @import("../binding.zig"); const c_allocator = std.heap.c_allocator; export fn fpl_garmin_parse_file(path: [*:0]const u8) ?*FlightPlan { var fpl = Reader.initFromFile(c_allocator, mem.sliceTo(path, 0)) catch return null; return binding.cflightplan(fpl); } export fn fpl_garmin_write_to_file(raw: ?*FlightPlan, path: [*:0]const u8) c_int { const fpl = raw orelse return -1; Format.writeToFile(mem.sliceTo(path, 0), fpl) catch return -1; return 0; } }; /// Reader implementation (see format.zig) pub const Reader = struct { pub fn initFromFile(alloc: Allocator, path: [:0]const u8) !FlightPlan { // Create a parser context. We use the context form rather than the global // xmlReadFile form so that we can be a little more thread safe. const ctx = c.xmlNewParserCtxt(); if (ctx == null) { Error.setLastError(null); return ErrorSet.ReadFailed; } // NOTE: we do not defer freeing the context cause we want to preserve // the context if there are any errors. // Read the file const doc = c.xmlCtxtReadFile(ctx, path.ptr, null, 0); if (doc == null) { return Error.setLastErrorXML(ErrorSet.ReadFailed, .{ .parser = ctx }); } defer c.xmlFreeParserCtxt(ctx); defer c.xmlFreeDoc(doc); // Get the root elem const root = c.xmlDocGetRootElement(doc); return initFromXMLNode(alloc, root); } pub fn initFromReader(alloc: Allocator, reader: anytype) !FlightPlan { // Read the full contents. var buf = try reader.readAllAlloc( alloc, 1024 * 1024 * 50, // 50 MB for now ); defer alloc.free(buf); const ctx = c.xmlNewParserCtxt(); if (ctx == null) { Error.setLastError(null); return ErrorSet.ReadFailed; } // NOTE: we do not defer freeing the context cause we want to preserve // the context if there are any errors. // Read the const doc = c.xmlCtxtReadMemory( ctx, buf.ptr, @intCast(c_int, buf.len), null, null, 0, ); if (doc == null) { return Error.setLastErrorXML(ErrorSet.ReadFailed, .{ .parser = ctx }); } defer c.xmlFreeParserCtxt(ctx); defer c.xmlFreeDoc(doc); // Get the root elem const root = c.xmlDocGetRootElement(doc); return initFromXMLNode(alloc, root); } fn initFromXMLNode(alloc: Allocator, node: *c.xmlNode) !FlightPlan { // Should be an opening node if (node.type != c.XML_ELEMENT_NODE) { return ErrorSet.NodeExpected; } // Should be a "flight-plan" node. if (c.xmlStrcmp(node.name, "flight-plan") != 0) { Error.setLastError(try Error.initMessage( alloc, ErrorSet.InvalidElement, "flight-plan element not found", .{}, )); return ErrorSet.InvalidElement; } const WPType = comptime std.meta.fieldInfo(FlightPlan, .waypoints).field_type; var self = FlightPlan{ .alloc = alloc, .created = undefined, .waypoints = WPType{}, .route = undefined, }; try parseFlightPlan(&self, node); return self; } fn parseFlightPlan(self: *FlightPlan, node: *c.xmlNode) !void { var cur: ?*c.xmlNode = node.children; while (cur) |n| : (cur = n.next) { if (n.type != c.XML_ELEMENT_NODE) { continue; } if (c.xmlStrcmp(n.name, "created") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.created = try Allocator.dupeZ(self.alloc, u8, mem.sliceTo(copy, 0)); } else if (c.xmlStrcmp(n.name, "waypoint-table") == 0) { try parseWaypointTable(self, n); } else if (c.xmlStrcmp(n.name, "route") == 0) { self.route = try parseRoute(self.alloc, n); } } } fn parseWaypointTable(self: *FlightPlan, node: *c.xmlNode) !void { var cur: ?*c.xmlNode = node.children; while (cur) |n| : (cur = n.next) { if (n.type != c.XML_ELEMENT_NODE) { continue; } if (c.xmlStrcmp(n.name, "waypoint") == 0) { const wp = try parseWaypoint(self.alloc, n); try self.waypoints.put(self.alloc, wp.identifier, wp); } } } fn parseRoute(alloc: Allocator, node: *c.xmlNode) !Route { var self = Route{ .name = undefined, .points = .{}, }; var cur: ?*c.xmlNode = node.children; while (cur) |n| : (cur = n.next) { if (n.type != c.XML_ELEMENT_NODE) { continue; } if (c.xmlStrcmp(n.name, "route-name") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.name = try Allocator.dupeZ(alloc, u8, mem.sliceTo(copy, 0)); } else if (c.xmlStrcmp(n.name, "route-point") == 0) { try parseRoutePoint(&self, alloc, n); } } return self; } fn parseRoutePoint(self: *Route, alloc: Allocator, node: *c.xmlNode) !void { var cur: ?*c.xmlNode = node.children; while (cur) |n| : (cur = n.next) { if (n.type != c.XML_ELEMENT_NODE) { continue; } if (c.xmlStrcmp(n.name, "waypoint-identifier") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); const zcopy = try Allocator.dupeZ(alloc, u8, mem.sliceTo(copy, 0)); try self.points.append(alloc, Route.Point{ .identifier = zcopy, }); } } } fn parseWaypoint(alloc: Allocator, node: *c.xmlNode) !Waypoint { var self = Waypoint{ .identifier = undefined, .type = undefined, }; var cur: ?*c.xmlNode = node.children; while (cur) |n| : (cur = n.next) { if (n.type != c.XML_ELEMENT_NODE) { continue; } if (c.xmlStrcmp(n.name, "identifier") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.identifier = try Allocator.dupeZ(alloc, u8, mem.sliceTo(copy, 0)); } else if (c.xmlStrcmp(n.name, "lat") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.lat = try std.fmt.parseFloat(f32, mem.sliceTo(copy, 0)); } else if (c.xmlStrcmp(n.name, "lon") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.lon = try std.fmt.parseFloat(f32, mem.sliceTo(copy, 0)); } else if (c.xmlStrcmp(n.name, "type") == 0) { const copy = c.xmlNodeListGetString(node.doc, n.children, 1); defer xml.free(copy); self.type = Waypoint.Type.fromString(mem.sliceTo(copy, 0)); } } return self; } test "basic reading" { const testPath = try testutil.testFile("basic.fpl"); var plan = try Format.initFromFile(testing.allocator, testPath); defer plan.deinit(); try testing.expectEqualStrings(plan.created.?, "20211230T22:07:20Z"); try testing.expectEqual(plan.waypoints.count(), 20); // Test route try testing.expectEqualStrings(plan.route.name.?, "KHHR TO KHTH"); try testing.expectEqual(plan.route.points.items.len, 20); // Test a waypoint { const wp = plan.waypoints.get("KHHR").?; try testing.expectEqualStrings(wp.identifier, "KHHR"); try testing.expect(wp.lat > 33.91 and wp.lat < 33.93); try testing.expect(wp.lon > -118.336 and wp.lon < -118.334); try testing.expectEqual(wp.type, .airport); try testing.expectEqualStrings(wp.type.toString(), "AIRPORT"); } } test "parse error" { const testPath = try testutil.testFile("error_syntax.fpl"); try testing.expectError(ErrorSet.ReadFailed, Format.initFromFile(testing.allocator, testPath)); var lastErr = Error.lastError().?; defer Error.setLastError(null); try testing.expectEqual(lastErr.code, ErrorSet.ReadFailed); const xmlErr = lastErr.detail.?.xml.err(); const message = mem.span(xmlErr.?.message); try testing.expect(message.len > 0); } test "error: no flight-plan" { const testPath = try testutil.testFile("error_no_flightplan.fpl"); try testing.expectError(ErrorSet.InvalidElement, Format.initFromFile(testing.allocator, testPath)); var lastErr = Error.lastError().?; defer Error.setLastError(null); try testing.expectEqual(lastErr.code, ErrorSet.InvalidElement); } }; /// Writer implementation (see format.zig) pub const Writer = struct { pub fn writeTo(writer: anytype, fpl: *const FlightPlan) !void { // Initialize an in-memory buffer. We have to do all writes to a buffer // first. We know that our flight plans can't be _that_ big (for a // reasonable user) so this is fine. var buf = c.xmlBufferCreate(); if (buf == null) { return Error.setLastErrorXML(ErrorSet.OutOfMemory, .{ .global = {} }); } defer c.xmlBufferFree(buf); var xmlwriter = c.xmlNewTextWriterMemory(buf, 0); if (xmlwriter == null) { return Error.setLastErrorXML(ErrorSet.OutOfMemory, .{ .global = {} }); } // Make the output human-friendly var rc = c.xmlTextWriterSetIndent(xmlwriter, 1); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterSetIndentString(xmlwriter, "\t"); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterStartDocument(xmlwriter, "1.0", "utf-8", null); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // Start <flight-plan> const ns = "http://www8.garmin.com/xmlschemas/FlightPlan/v1"; rc = c.xmlTextWriterStartElementNS(xmlwriter, null, "flight-plan", ns); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // <created> if (fpl.created) |created| { rc = c.xmlTextWriterWriteElement(xmlwriter, "created", created); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } // Encode our waypoints try writeWaypoints(xmlwriter, fpl); // Encode our route try writeRoute(xmlwriter, fpl); // End <flight-plan> rc = c.xmlTextWriterEndElement(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // End doc rc = c.xmlTextWriterEndDocument(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // Free our text writer. We defer this now because errors below no longer // need this reference. defer c.xmlFreeTextWriter(xmlwriter); // Success, lets copy our buffer to the writer. try writer.writeAll(mem.span(buf.*.content)); } fn writeWaypoints(xmlwriter: c.xmlTextWriterPtr, fpl: *const FlightPlan) !void { // Do nothing if we have no waypoints if (fpl.waypoints.count() == 0) { return; } // Buffer for writing var buf: [128]u8 = undefined; // Start <waypoint-table> var rc = c.xmlTextWriterStartElement(xmlwriter, "waypoint-table"); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // Iterate over each waypoint and write it var iter = fpl.waypoints.valueIterator(); while (iter.next()) |wp| { // Start <waypoint> rc = c.xmlTextWriterStartElement(xmlwriter, "waypoint"); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement(xmlwriter, "identifier", wp.identifier); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement(xmlwriter, "type", wp.type.toString()); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement( xmlwriter, "lat", try std.fmt.bufPrintZ(&buf, "{d}", .{wp.lat}), ); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement( xmlwriter, "lon", try std.fmt.bufPrintZ(&buf, "{d}", .{wp.lon}), ); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // End <waypoint> rc = c.xmlTextWriterEndElement(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } // End <waypoint-table> rc = c.xmlTextWriterEndElement(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } fn writeRoute(xmlwriter: c.xmlTextWriterPtr, fpl: *const FlightPlan) !void { // Start <route> var rc = c.xmlTextWriterStartElement(xmlwriter, "route"); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } if (fpl.route.name) |name| { rc = c.xmlTextWriterWriteElement(xmlwriter, "route-name", name); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } for (fpl.route.points.items) |point| { // Find the waypoint for this point const wp = fpl.waypoints.get(point.identifier) orelse return ErrorSet.RouteMissingWaypoint; // Start <route-point> rc = c.xmlTextWriterStartElement(xmlwriter, "route-point"); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement(xmlwriter, "waypoint-identifier", point.identifier); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } rc = c.xmlTextWriterWriteElement(xmlwriter, "waypoint-type", wp.type.toString()); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } // End <route-point> rc = c.xmlTextWriterEndElement(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } // End <route> rc = c.xmlTextWriterEndElement(xmlwriter); if (rc < 0) { return Error.setLastErrorXML(ErrorSet.WriteFailed, .{ .writer = xmlwriter }); } } test "basic writing" { const testPath = try testutil.testFile("basic.fpl"); var plan = try Format.initFromFile(testing.allocator, testPath); defer plan.deinit(); // Write the plan and compare var output = std.ArrayList(u8).init(testing.allocator); defer output.deinit(); // Write try Writer.writeTo(output.writer(), &plan); // Debug, write output to compare //std.debug.print("write:\n\n{s}\n", .{output.items}); // re-read to verify it parses const reader = std.io.fixedBufferStream(output.items).reader(); var plan2 = try Reader.initFromReader(testing.allocator, reader); defer plan2.deinit(); } };
src/format/garmin.zig
const std = @import("std"); const io = std.io; const mem = std.mem; const Range = @import("record.zig").Range; const Record = @import("record.zig").Record; const Collection = @This(); const comp_path = "components/autogen"; allocator: *mem.Allocator, kind: []const u8, lo: u21, hi: u21, records: []Record, pub fn init(allocator: *mem.Allocator, kind: []const u8, lo: u21, hi: u21, records: []Record) !Collection { return Collection{ .allocator = allocator, .kind = blk: { var b = try allocator.alloc(u8, kind.len); mem.copy(u8, b, kind); break :blk b; }, .lo = lo, .hi = hi, .records = records, }; } pub fn deinit(self: *Collection) void { self.allocator.free(self.kind); self.allocator.free(self.records); } pub fn writeFile(self: *Collection, dir: []const u8) !void { const header_tpl = @embedFile("parts/collection_header_tpl.txt"); const trailer_tpl = @embedFile("parts/collection_trailer_tpl.txt"); // Prepare output files. const name = try self.clean_name(); defer self.allocator.free(name); var dir_name = try mem.concat(self.allocator, u8, &[_][]const u8{ comp_path, "/", dir, }); defer self.allocator.free(dir_name); var cwd = std.fs.cwd(); cwd.makeDir(dir_name) catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var file_name = try mem.concat(self.allocator, u8, &[_][]const u8{ dir_name, "/", name, ".zig" }); defer self.allocator.free(file_name); var file = try cwd.createFile(file_name, .{}); defer file.close(); var buf_writer = io.bufferedWriter(file.writer()); const writer = buf_writer.writer(); // Write data. const array_len = self.hi - self.lo + 1; _ = try writer.print(header_tpl, .{ self.kind, name, array_len, self.lo, self.hi }); _ = try writer.write(" var index: u21 = 0;\n"); for (self.records) |record| { switch (record) { .single => |cp| { _ = try writer.print(" instance.array[{d}] = true;\n", .{cp - self.lo}); }, .range => |range| { _ = try writer.print(" index = {d};\n", .{range.lo - self.lo}); _ = try writer.print(" while (index <= {d}) : (index += 1) {{\n", .{range.hi - self.lo}); _ = try writer.write(" instance.array[index] = true;\n"); _ = try writer.write(" }\n"); }, } } _ = try writer.print(trailer_tpl, .{ name, self.kind }); try buf_writer.flush(); } fn clean_name(self: *Collection) ![]u8 { var name1 = try self.allocator.alloc(u8, mem.replacementSize(u8, self.kind, "_", "")); defer self.allocator.free(name1); _ = mem.replace(u8, self.kind, "_", "", name1); var name2 = try self.allocator.alloc(u8, mem.replacementSize(u8, name1, "-", "")); defer self.allocator.free(name2); _ = mem.replace(u8, name1, "-", "", name2); var name = try self.allocator.alloc(u8, mem.replacementSize(u8, name1, " ", "")); _ = mem.replace(u8, name2, " ", "", name); return name; }
src/Collection.zig
const c = @import("c.zig"); const std = @import("std"); pub const Frame = struct { name: [*c]const u8, pub fn mark(name: ?[*c]const u8) void { c.___tracy_emit_frame_mark(name); } pub fn image(image_ptr: ?*const anyopaque, width: u16, height: u16, offset: u8, flip: c_int) void { c.___tracy_emit_frame_image(image_ptr, width, height, offset, flip); } pub fn start(name: ?[*c]const u8) Frame { const frame: Frame = .{ .name = if (name) |n| n else null }; c.___tracy_emit_frame_mark_start(frame.name); return frame; } pub fn end(self: *Frame) void { c.___tracy_emit_frame_mark_end(self.name); } }; pub const Zone = struct { ctx: c.TracyCZoneCtx, pub fn hashColor(comptime str: []const u8) u32 { return @truncate(u32, std.hash.Wyhash.hash(0, str)); } pub fn start(comptime src: std.builtin.SourceLocation, name: ?[]const u8, color: u32) Zone { var srcloc: u64 = undefined; if (name) |n| { srcloc = c.___tracy_alloc_srcloc_name(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len, n.ptr, n.len); } else { srcloc = c.___tracy_alloc_srcloc(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len); } var zone: Zone = .{ .ctx = c.___tracy_emit_zone_begin_alloc(srcloc, 1) }; c.___tracy_emit_zone_color(zone.ctx, color); return zone; } pub fn start_no_color(comptime src: std.builtin.SourceLocation, name: ?[]const u8) Zone { return start(src, name, 0); } pub fn start_color_from_fnc(comptime src: std.builtin.SourceLocation, name: ?[]const u8) Zone { return start(src, name, hashColor(src.fn_name)); } pub fn start_color_from_file(comptime src: std.builtin.SourceLocation, name: ?[]const u8) Zone { return start(src, name, hashColor(src.file)); } pub fn end(self: *Zone) void { _ = self; c.___tracy_emit_zone_end(self.ctx); } };
src/tracy.zig
const std = @import("std"); /// Counts the amount of `{` tokens insi fn countCaptures(buffer: []const u8) usize { var result: usize = 0; for (buffer) |c| { if (c == '{') result += 1; } return result; } /// Creates a new Template engine based on the given input pub fn Template(comptime fmt: []const u8) type { comptime const num_captures = countCaptures(fmt); comptime var captures: [num_captures][]const u8 = undefined; comptime var level = 0; comptime var start = 0; comptime var index = 0; for (fmt) |c, i| { switch (c) { '{' => { level += 1; start = i + 1; }, '}' => { if (start > i) continue; level -= 1; captures[index] = fmt[start..i]; index += 1; }, else => {}, } } if (level != 0) @compileError("Incorrect capture level"); return struct { const Self = @This(); /// Parses the template with the input and writes it to the stream pub fn write(comptime T: type, value: T, writer: anytype) @TypeOf(writer).Error!void { comptime var write_index = 0; comptime var capture_index = 0; inline for (fmt) |c, i| { switch (c) { '{' => try writer.writeAll(fmt[write_index..i]), '}' => { write_index = i + 1; switch (@typeInfo(T)) { .Struct => |info| { if (@hasField(T, captures[capture_index])) { try writeTyped(writer, @field(value, captures[capture_index])); } }, else => { @compileError("Implement for type: " ++ @typeName(T)); }, } capture_index += 1; }, else => {}, } } // Write the remaining try writer.writeAll(fmt[write_index..]); } /// Writes the value to the stream based on the type of the given value fn writeTyped(writer: anytype, arg: anytype) @TypeOf(writer).Error!void { switch (@TypeOf(arg)) { []u8, []const u8 => try writer.writeAll(arg), else => switch (@typeInfo(@TypeOf(arg))) { .ComptimeInt, .Int => try std.fmt.formatIntValue(arg, "d", .{}, writer), .ComptimeFloat, .Float => try std.fmt.formatFloatDecimal(arg, .{ .precision = 2 }, writer), .Bool => try writer.writeAll(if (arg) "true" else "false"), else => @compileError("TODO: Implement for type: " ++ @typeName(@TypeOf(arg))), }, } } }; } test "Basic parse" { const input = "<html>{name} 371178 + 371178 = {number} {float} {boolean}</html>"; const expected = "<html>apple_pie 371178 + 371178 = 742356 1.24 true</html>"; var buffer: [1024]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); const template = Template(input); try template.write(struct { name: []const u8, number: u32, float: f32, boolean: bool, }, .{ .name = "apple_pie", .number = 742356, .float = 1.235235, .boolean = true, }, stream.writer()); std.testing.expectEqualStrings(expected, stream.getWritten()); }
src/template.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Bingo = struct { const Board = struct { const SIZE = 5; const Pos = struct { row: usize, col: usize, hit: bool, pub fn init(row: usize, col: usize) Pos { var self = Pos{ .row = row, .col = col, .hit = false, }; return self; } }; won: bool, data: std.AutoHashMap(usize, Pos), row_hits: [SIZE]usize, col_hits: [SIZE]usize, pub fn init() Board { var self = Board{ .won = false, .data = std.AutoHashMap(usize, Pos).init(allocator), .row_hits = [_]usize{0} ** SIZE, .col_hits = [_]usize{0} ** SIZE, }; return self; } pub fn deinit(self: *Board) void { self.data.deinit(); } fn get_score(self: *Board, draw: usize) usize { var sum: usize = 0; var it = self.data.iterator(); while (it.next()) |entry| { const p = entry.value_ptr; if (p.*.hit) continue; const n = entry.key_ptr.*; // std.debug.warn("POS {} {} = {}\n", .{ p.*.row, p.*.col, n }); sum += n; } const score = draw * sum; // std.debug.warn("SCORE {} * {} = {}\n", .{ draw, sum, score }); return score; } }; boards: std.ArrayList(Board), draws: std.ArrayList(usize), row: usize, col: usize, pub fn init() Bingo { var self = Bingo{ .boards = std.ArrayList(Board).init(allocator), .draws = std.ArrayList(usize).init(allocator), .row = 0, .col = 0, }; return self; } pub fn deinit(self: *Bingo) void { self.draws.deinit(); for (self.boards.items) |*board| { board.deinit(); } self.boards.deinit(); } pub fn process_line(self: *Bingo, data: []const u8) void { if (self.draws.items.len == 0) { var it = std.mem.split(u8, data, ","); while (it.next()) |num| { const n = std.fmt.parseInt(usize, num, 10) catch unreachable; // std.debug.warn("DRAW {}\n", .{n}); self.draws.append(n) catch unreachable; } return; } if (data.len == 0) { // std.debug.warn("BLANK\n", .{}); self.row = 0; self.col = 0; return; } if (self.row == 0 and self.col == 0) { const b = Board.init(); self.boards.append(b) catch unreachable; } const b = self.boards.items.len - 1; var it = std.mem.tokenize(u8, data, " "); while (it.next()) |num| { const n = std.fmt.parseInt(usize, num, 10) catch unreachable; // std.debug.warn("POS {} => {} {}\n", .{ n, self.row, self.col }); const p = Board.Pos.init(self.row, self.col); self.boards.items[b].data.put(n, p) catch unreachable; self.col += 1; } self.col = 0; self.row += 1; } pub fn play_until_first_win(self: *Bingo) usize { for (self.draws.items) |draw| { // std.debug.warn("FIRST DRAW {}\n", .{draw}); for (self.boards.items) |*board| { if (!board.data.contains(draw)) continue; const entry = board.data.getEntry(draw).?; var p = entry.value_ptr; p.*.hit = true; board.row_hits[p.*.row] += 1; board.col_hits[p.*.col] += 1; if (board.row_hits[p.*.row] == Board.SIZE or board.col_hits[p.*.col] == Board.SIZE) { // std.debug.warn("FIRST WINNER\n", .{}); return board.get_score(draw); } } } return 0; } pub fn play_until_last_win(self: *Bingo) usize { for (self.draws.items) |draw| { // std.debug.warn("LAST DRAW {}\n", .{draw}); var count_left: usize = 0; var count_won: usize = 0; var score: usize = 0; for (self.boards.items) |*board| { if (board.won) continue; count_left += 1; if (!board.data.contains(draw)) continue; const entry = board.data.getEntry(draw).?; var p = entry.value_ptr; p.*.hit = true; board.row_hits[p.*.row] += 1; board.col_hits[p.*.col] += 1; if (board.row_hits[p.*.row] == Board.SIZE or board.col_hits[p.*.col] == Board.SIZE) { // std.debug.warn("LAST WINNER\n", .{}); board.won = true; score = board.get_score(draw); count_won += 1; } } if (count_left == 1 and count_won == 1) { return score; } } return 0; } }; test "sample part a" { const data: []const u8 = \\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 \\ \\22 13 17 11 0 \\ 8 2 23 4 24 \\21 9 14 16 7 \\ 6 10 3 18 5 \\ 1 12 20 15 19 \\ \\ 3 15 0 2 22 \\ 9 18 13 17 5 \\19 8 7 25 23 \\20 11 10 24 4 \\14 21 16 12 6 \\ \\14 21 17 24 4 \\10 16 15 9 19 \\18 8 23 26 20 \\22 11 13 6 5 \\ 2 0 12 3 7 ; var bingo = Bingo.init(); defer bingo.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { bingo.process_line(line); } const score = bingo.play_until_first_win(); try testing.expect(score == 4512); } test "sample part b" { const data: []const u8 = \\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 \\ \\22 13 17 11 0 \\ 8 2 23 4 24 \\21 9 14 16 7 \\ 6 10 3 18 5 \\ 1 12 20 15 19 \\ \\ 3 15 0 2 22 \\ 9 18 13 17 5 \\19 8 7 25 23 \\20 11 10 24 4 \\14 21 16 12 6 \\ \\14 21 17 24 4 \\10 16 15 9 19 \\18 8 23 26 20 \\22 11 13 6 5 \\ 2 0 12 3 7 ; var bingo = Bingo.init(); defer bingo.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { bingo.process_line(line); } const score = bingo.play_until_last_win(); try testing.expect(score == 1924); }
2021/p04/bingo.zig
const std = @import("std"); /// A First In/First Out ring buffer holding at most `size` elements. pub fn RingBuffer(comptime T: type, comptime size: usize) type { return struct { const Self = @This(); buffer: [size]T = undefined, /// The index of the slot with the first item, if any. index: usize = 0, /// The number of items in the buffer. count: usize = 0, /// Add an element to the RingBuffer. Returns an error if the buffer /// is already full and the element could not be added. pub fn push(self: *Self, item: T) error{NoSpaceLeft}!void { if (self.full()) return error.NoSpaceLeft; self.buffer[(self.index + self.count) % self.buffer.len] = item; self.count += 1; } /// Return but do not remove the next item, if any. pub fn peek(self: *Self) ?T { if (self.empty()) return null; return self.buffer[self.index]; } /// Remove and return the next item, if any. pub fn pop(self: *Self) ?T { if (self.empty()) return null; const ret = self.buffer[self.index]; self.index = (self.index + 1) % self.buffer.len; self.count -= 1; return ret; } pub fn full(self: Self) bool { return self.count == self.buffer.len; } pub fn empty(self: Self) bool { return self.count == 0; } }; } test "push/peek/pop/full/empty" { const testing = std.testing; var fifo = RingBuffer(u32, 3){}; testing.expect(!fifo.full()); testing.expect(fifo.empty()); try fifo.push(1); testing.expectEqual(@as(?u32, 1), fifo.peek()); testing.expect(!fifo.full()); testing.expect(!fifo.empty()); try fifo.push(2); testing.expectEqual(@as(?u32, 1), fifo.peek()); try fifo.push(3); testing.expectError(error.NoSpaceLeft, fifo.push(4)); testing.expect(fifo.full()); testing.expect(!fifo.empty()); testing.expectEqual(@as(?u32, 1), fifo.peek()); testing.expectEqual(@as(?u32, 1), fifo.pop()); testing.expect(!fifo.full()); testing.expect(!fifo.empty()); testing.expectEqual(@as(?u32, 2), fifo.pop()); testing.expectEqual(@as(?u32, 3), fifo.pop()); testing.expectEqual(@as(?u32, null), fifo.pop()); testing.expect(!fifo.full()); testing.expect(fifo.empty()); }
src/ring_buffer.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const MarbleCircle = tools.CircularBuffer(u32); pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { //const input = "9 players; last marble is worth 25 points"; //const input = "10 players; last marble is worth 1618 points"; //const input = "21 players; last marble is worth 6111 points"; const params: struct { nb_players: u32, nb_marbles: u32 } = blk: { var it = std.mem.tokenize(u8, input, "\n\r"); const fields = tools.match_pattern("{} players; last marble is worth {} points", it.next().?) orelse unreachable; break :blk .{ .nb_players = @intCast(u32, fields[0].imm), .nb_marbles = @intCast(u32, fields[1].imm) + 1, }; }; // part1 const ans1 = ans: { const scores = try allocator.alloc(u32, params.nb_players); defer allocator.free(scores); std.mem.set(u32, scores, 0); var highscore_player: u32 = 0; var circle2 = MarbleCircle.init(allocator); defer circle2.deinit(); try circle2.pushHead(0); var circle = std.ArrayList(u32).init(allocator); defer circle.deinit(); try circle.ensureTotalCapacity(params.nb_marbles); try circle.append(0); var current: usize = 0; var marble: u32 = 1; while (marble < params.nb_marbles) : (marble += 1) { const player = (marble - 1) % params.nb_players; if (marble % 23 == 0) { circle2.rotate(-7); const bonus2 = circle2.pop(); const bonus_marble_index = (current + circle.items.len - 7) % circle.items.len; const bonus = circle.orderedRemove(bonus_marble_index); std.debug.assert(bonus2 == bonus); scores[player] += marble + bonus; if (scores[player] > scores[highscore_player]) highscore_player = player; current = bonus_marble_index % circle.items.len; } else { circle2.rotate(2); try circle2.pushHead(marble); const index = 1 + (current + 1) % (circle.items.len); try circle.insert(index, marble); current = index; } if (false) { std.debug.print("[{}]: ", .{player + 1}); var iter = circle2.iter(); while (iter.next()) |it| { std.debug.print("{} ", .{it}); } std.debug.print("\n", .{}); std.debug.print("[{}]: ", .{player + 1}); for (circle.items) |it, i| { if (i == current) { std.debug.print("({}) ", .{it}); } else { std.debug.print("{} ", .{it}); } } std.debug.print("\n", .{}); } } if (false) { std.debug.print("Scores: ", .{}); for (scores) |it, i| { if (i == highscore_player) { std.debug.print(">{}< ", .{it}); } else { std.debug.print("{} ", .{it}); } } std.debug.print("\n", .{}); std.debug.print("xinner {} : {}\n", .{ highscore_player + 1, scores[highscore_player] }); } break :ans scores[highscore_player]; }; // part2 const ans2 = ans: { const scores = try allocator.alloc(u32, params.nb_players); defer allocator.free(scores); std.mem.set(u32, scores, 0); var highscore_player: u32 = 0; var circle = MarbleCircle.init(allocator); defer circle.deinit(); try circle.pushHead(0); var marble: u32 = 1; while (marble < params.nb_marbles * 100) : (marble += 1) { const player = (marble - 1) % params.nb_players; if (marble % 23 == 0) { circle.rotate(-7); const bonus = circle.pop().?; scores[player] += marble + bonus; if (scores[player] > scores[highscore_player]) highscore_player = player; } else { circle.rotate(2); try circle.pushHead(marble); } } break :ans scores[highscore_player]; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); //const limit = 1 * 1024 * 1024 * 1024; //const text = try std.fs.cwd().readFileAlloc(allocator, "2018/input_day08.txt", limit); //defer allocator.free(text); const text = "473 players; last marble is worth 70904 points"; const ans = try run(text, allocator); defer allocator.free(ans[0]); defer allocator.free(ans[1]); try stdout.print("PART 1: {s}\nPART 2: {s}\n", .{ ans[0], ans[1] }); }
2018/day09.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } fn add(p: usize, d: isize) usize { return @intCast(usize, @intCast(isize, p) + d); } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day19.txt", limit); defer allocator.free(text); var stride: usize = 0; var height: usize = 0; var width: usize = 0; { var it = std.mem.split(u8, text, "\n"); while (it.next()) |line| { if (width == 0) { width = line.len; } assert(width == line.len); if (stride == 0) { stride = @ptrToInt(line.ptr) - @ptrToInt(text.ptr); } assert(line.ptr == text.ptr + height * stride); height += 1; assert(line[0] == ' ' and line[line.len - 1] == ' '); // guardband } trace("Map size= {}x{}.\n", .{ width, height }); } const map = text[0 .. stride * height - 1]; const up: u2 = 0; const left: u2 = 1; const down: u2 = 2; const right: u2 = 3; const moves = [_]isize{ -@intCast(isize, stride), -1, @intCast(isize, stride), 1 }; const start_dir = down; var start_pos: usize = 0; { start_pos = std.mem.indexOfScalar(u8, map, '|') orelse unreachable; trace("Start={}\n", .{start_pos}); } var letters: [64]u8 = undefined; var len: usize = 0; var steps: usize = 0; var pos = start_pos; var dir = start_dir; while (true) { pos = add(pos, moves[dir]); steps += 1; const m = map[pos]; switch (m) { ' ' => break, // reachead the end '-', '|' => continue, 'A'...'Z' => { letters[len] = m; len += 1; continue; }, '+' => { const dir_l = dir +% 1; const dir_r = dir +% 3; if (map[add(pos, moves[dir_l])] != ' ') { dir = dir_l; } else if (map[add(pos, moves[dir_r])] != ' ') { dir = dir_r; } else { unreachable; } continue; }, else => unreachable, } } try stdout.print("letters={}, steps={}\n", .{ letters[0..len], steps }); }
2017/day19.zig
const ImageReader = zigimg.ImageReader; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const png = zigimg.png; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); usingnamespace @import("../helpers.zig"); test "Read basn0g01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale1); expectEq(pixels.Grayscale1[0].value, 1); expectEq(pixels.Grayscale1[31].value, 0); expectEq(pixels.Grayscale1[4 * 32 + 3].value, 1); expectEq(pixels.Grayscale1[4 * 32 + 4].value, 0); expectEq(pixels.Grayscale1[18 * 32 + 19].value, 0); expectEq(pixels.Grayscale1[18 * 32 + 20].value, 1); expectEq(pixels.Grayscale1[31 * 32 + 31].value, 0); } } test "Read basn0g02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale2); expectEq(pixels.Grayscale2[0].value, 0); expectEq(pixels.Grayscale2[4].value, 1); expectEq(pixels.Grayscale2[8].value, 2); expectEq(pixels.Grayscale2[12].value, 3); expectEq(pixels.Grayscale2[16 * 32 + 16].value, 0); expectEq(pixels.Grayscale2[31 * 32 + 31].value, 2); } } test "Read basn0g04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale4); expectEq(pixels.Grayscale4[0].value, 0); expectEq(pixels.Grayscale4[4].value, 1); expectEq(pixels.Grayscale4[8].value, 2); expectEq(pixels.Grayscale4[12].value, 3); expectEq(pixels.Grayscale4[16].value, 4); expectEq(pixels.Grayscale4[20].value, 5); expectEq(pixels.Grayscale4[24].value, 6); expectEq(pixels.Grayscale4[28].value, 7); expectEq(pixels.Grayscale4[31 * 32 + 31].value, 14); } } test "Read basn0g08 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8); var i: usize = 0; while (i < 256) : (i += 1) { expectEq(pixels.Grayscale8[i].value, @intCast(u8, i)); } while (i < 510) : (i += 1) { expectEq(pixels.Grayscale8[i].value, @intCast(u8, 510 - i)); } } } test "Read basn0g16 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn0g16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale16); expectEq(pixels.Grayscale16[0].value, 0); expectEq(pixels.Grayscale16[31].value, 47871); } } test "Read basn2c08 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn2c08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgb24); expectEq(pixels.Rgb24[0].R, 0xFF); expectEq(pixels.Rgb24[0].G, 0xFF); expectEq(pixels.Rgb24[0].B, 0xFF); expectEq(pixels.Rgb24[7 * 32 + 31].R, 0xFF); expectEq(pixels.Rgb24[7 * 32 + 31].G, 0xFF); expectEq(pixels.Rgb24[7 * 32 + 31].B, 0); expectEq(pixels.Rgb24[15 * 32 + 31].R, 0xFF); expectEq(pixels.Rgb24[15 * 32 + 31].G, 0); expectEq(pixels.Rgb24[15 * 32 + 31].B, 0xFF); expectEq(pixels.Rgb24[23 * 32 + 31].R, 0x0); expectEq(pixels.Rgb24[23 * 32 + 31].G, 0xFF); expectEq(pixels.Rgb24[23 * 32 + 31].B, 0xFF); expectEq(pixels.Rgb24[31 * 32 + 31].R, 0x0); expectEq(pixels.Rgb24[31 * 32 + 31].G, 0x0); expectEq(pixels.Rgb24[31 * 32 + 31].B, 0x0); } } test "Read basn2c16 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn2c16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgb48); expectEq(pixels.Rgb48[0].R, 0xFFFF); expectEq(pixels.Rgb48[0].G, 0xFFFF); expectEq(pixels.Rgb48[0].B, 0); expectEq(pixels.Rgb48[16 * 32 + 16].R, 0x7bde); expectEq(pixels.Rgb48[16 * 32 + 16].G, 0x7bde); expectEq(pixels.Rgb48[16 * 32 + 16].B, 0x842); expectEq(pixels.Rgb48[31 * 32 + 31].R, 0); expectEq(pixels.Rgb48[31 * 32 + 31].G, 0); expectEq(pixels.Rgb48[31 * 32 + 31].B, 0xFFFF); } } test "Read basn3p01 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn3p01.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); var palette_chunk_opt = pngFile.getPalette(); testing.expect(palette_chunk_opt != null); if (palette_chunk_opt) |palette_chunk| { const first_color = palette_chunk.palette[0].toIntegerColor8(); const second_color = palette_chunk.palette[1].toIntegerColor8(); expectEq(first_color.R, 0xee); expectEq(first_color.G, 0xff); expectEq(first_color.B, 0x22); expectEq(second_color.R, 0x22); expectEq(second_color.G, 0x66); expectEq(second_color.B, 0xff); } if (pixelsOpt) |pixels| { testing.expect(pixels == .Bpp1); expectEq(pixels.Bpp1.palette.len, 2); const first_color = pixels.Bpp1.palette[0].toIntegerColor8(); const second_color = pixels.Bpp1.palette[1].toIntegerColor8(); expectEq(first_color.R, 0xee); expectEq(first_color.G, 0xff); expectEq(first_color.B, 0x22); expectEq(second_color.R, 0x22); expectEq(second_color.G, 0x66); expectEq(second_color.B, 0xff); var i: usize = 0; while (i < pixels.Bpp1.indices.len) : (i += 1) { const x = i % 32; const y = i / 32; const temp1 = (x / 4); const temp2 = (y / 4); const final_pixel: u1 = @intCast(u1, (temp1 + temp2) & 1); expectEq(pixels.Bpp1.indices[i], final_pixel); } } } test "Read basn3p02 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn3p02.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); var palette_chunk_opt = pngFile.getPalette(); testing.expect(palette_chunk_opt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Bpp2); expectEq(pixels.Bpp2.palette.len, 4); const color0 = pixels.Bpp2.palette[0].toIntegerColor8(); const color1 = pixels.Bpp2.palette[1].toIntegerColor8(); const color2 = pixels.Bpp2.palette[2].toIntegerColor8(); const color3 = pixels.Bpp2.palette[3].toIntegerColor8(); expectEq(color0.R, 0x00); expectEq(color0.G, 0xff); expectEq(color0.B, 0x00); expectEq(color1.R, 0xff); expectEq(color1.G, 0x00); expectEq(color1.B, 0x00); expectEq(color2.R, 0xff); expectEq(color2.G, 0xff); expectEq(color2.B, 0x00); expectEq(color3.R, 0x00); expectEq(color3.G, 0x00); expectEq(color3.B, 0xff); expectEq(pixels.Bpp2.indices[0], 3); expectEq(pixels.Bpp2.indices[4], 1); expectEq(pixels.Bpp2.indices[8], 2); expectEq(pixels.Bpp2.indices[12], 0); expectEq(pixels.Bpp2.indices[31 * 32 + 31], 3); } } test "Read basn3p04 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn3p04.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); var palette_chunk_opt = pngFile.getPalette(); testing.expect(palette_chunk_opt != null); if (palette_chunk_opt) |palette_chunk| { expectEq(palette_chunk.palette.len, 15); } if (pixelsOpt) |pixels| { testing.expect(pixels == .Bpp4); const color0 = pixels.Bpp4.palette[0].toIntegerColor8(); const color1 = pixels.Bpp4.palette[1].toIntegerColor8(); const color2 = pixels.Bpp4.palette[2].toIntegerColor8(); const color3 = pixels.Bpp4.palette[3].toIntegerColor8(); const color4 = pixels.Bpp4.palette[4].toIntegerColor8(); const color5 = pixels.Bpp4.palette[5].toIntegerColor8(); const color6 = pixels.Bpp4.palette[6].toIntegerColor8(); const color7 = pixels.Bpp4.palette[7].toIntegerColor8(); const color8 = pixels.Bpp4.palette[8].toIntegerColor8(); const color9 = pixels.Bpp4.palette[9].toIntegerColor8(); const color10 = pixels.Bpp4.palette[10].toIntegerColor8(); const color11 = pixels.Bpp4.palette[11].toIntegerColor8(); const color12 = pixels.Bpp4.palette[12].toIntegerColor8(); const color13 = pixels.Bpp4.palette[13].toIntegerColor8(); const color14 = pixels.Bpp4.palette[14].toIntegerColor8(); expectEq(color0.R, 0x22); expectEq(color0.G, 0x00); expectEq(color0.B, 0xff); expectEq(color1.R, 0x00); expectEq(color1.G, 0xff); expectEq(color1.B, 0xff); expectEq(color2.R, 0x88); expectEq(color2.G, 0x00); expectEq(color2.B, 0xff); expectEq(color3.R, 0x22); expectEq(color3.G, 0xff); expectEq(color3.B, 0x00); expectEq(color4.R, 0x00); expectEq(color4.G, 0x99); expectEq(color4.B, 0xff); expectEq(color5.R, 0xff); expectEq(color5.G, 0x66); expectEq(color5.B, 0x00); expectEq(color6.R, 0xdd); expectEq(color6.G, 0x00); expectEq(color6.B, 0xff); expectEq(color7.R, 0x77); expectEq(color7.G, 0xff); expectEq(color7.B, 0x00); expectEq(color8.R, 0xff); expectEq(color8.G, 0x00); expectEq(color8.B, 0x00); expectEq(color9.R, 0x00); expectEq(color9.G, 0xff); expectEq(color9.B, 0x99); expectEq(color10.R, 0xdd); expectEq(color10.G, 0xff); expectEq(color10.B, 0x00); expectEq(color11.R, 0xff); expectEq(color11.G, 0x00); expectEq(color11.B, 0xbb); expectEq(color12.R, 0xff); expectEq(color12.G, 0xbb); expectEq(color12.B, 0x00); expectEq(color13.R, 0x00); expectEq(color13.G, 0x44); expectEq(color13.B, 0xff); expectEq(color14.R, 0x00); expectEq(color14.G, 0xff); expectEq(color14.B, 0x44); expectEq(pixels.Bpp4.indices[0], 8); expectEq(pixels.Bpp4.indices[4], 5); expectEq(pixels.Bpp4.indices[8], 12); expectEq(pixels.Bpp4.indices[12], 10); expectEq(pixels.Bpp4.indices[16], 7); expectEq(pixels.Bpp4.indices[20], 3); expectEq(pixels.Bpp4.indices[24], 14); expectEq(pixels.Bpp4.indices[28], 9); expectEq(pixels.Bpp4.indices[31 * 32 + 31], 11); } } test "Read basn3p08 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn3p08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); var palette_chunk_opt = pngFile.getPalette(); testing.expect(palette_chunk_opt != null); if (palette_chunk_opt) |palette_chunk| { expectEq(palette_chunk.palette.len, 256); } if (pixelsOpt) |pixels| { testing.expect(pixels == .Bpp8); const color0 = pixels.Bpp8.palette[0].toIntegerColor8(); const color64 = pixels.Bpp8.palette[64].toIntegerColor8(); const color128 = pixels.Bpp8.palette[128].toIntegerColor8(); const color192 = pixels.Bpp8.palette[192].toIntegerColor8(); const color255 = pixels.Bpp8.palette[255].toIntegerColor8(); expectEq(color0.R, 0x22); expectEq(color0.G, 0x44); expectEq(color0.B, 0x00); expectEq(color64.R, 0x66); expectEq(color64.G, 0x00); expectEq(color64.B, 0x00); expectEq(color128.R, 0xff); expectEq(color128.G, 0xff); expectEq(color128.B, 0x44); expectEq(color192.R, 0xba); expectEq(color192.G, 0x00); expectEq(color192.B, 0x00); expectEq(color255.R, 0xff); expectEq(color255.G, 0x33); expectEq(color255.B, 0xff); expectEq(pixels.Bpp8.indices[0], 165); expectEq(pixels.Bpp8.indices[16 * 32], 107); expectEq(pixels.Bpp8.indices[16 * 32 + 16], 65); expectEq(pixels.Bpp8.indices[31 * 32 + 31], 80); } } test "Read basn4a08 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn4a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8Alpha); expectEq(pixels.Grayscale8Alpha[0].value, 255); expectEq(pixels.Grayscale8Alpha[0].alpha, 0); expectEq(pixels.Grayscale8Alpha[8].value, 255); expectEq(pixels.Grayscale8Alpha[8].alpha, 65); expectEq(pixels.Grayscale8Alpha[31].value, 255); expectEq(pixels.Grayscale8Alpha[31].alpha, 255); expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].value, 0); expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].alpha, 255); } } test "Read basn4a16 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn4a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale16Alpha); expectEq(pixels.Grayscale16Alpha[0].value, 0); expectEq(pixels.Grayscale16Alpha[0].alpha, 0); expectEq(pixels.Grayscale16Alpha[8].value, 33824); expectEq(pixels.Grayscale16Alpha[8].alpha, 0); expectEq(pixels.Grayscale16Alpha[9 * 32 + 8].value, 8737); expectEq(pixels.Grayscale16Alpha[9 * 32 + 8].alpha, 33825); expectEq(pixels.Grayscale16Alpha[31].value, 0); expectEq(pixels.Grayscale16Alpha[31].alpha, 0); expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].value, 0); expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].alpha, 0); } } test "Read basn6a08 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn6a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgba32); const color0 = pixels.Rgba32[0]; const color16 = pixels.Rgba32[16]; const color31 = pixels.Rgba32[31]; const color16_16 = pixels.Rgba32[16 * 32 + 16]; expectEq(color0.R, 0xFF); expectEq(color0.G, 0x00); expectEq(color0.B, 0x08); expectEq(color0.A, 0x00); expectEq(color16.R, 0xFF); expectEq(color16.G, 0x00); expectEq(color16.B, 0x08); expectEq(color16.A, 131); expectEq(color31.R, 0xFF); expectEq(color31.G, 0x00); expectEq(color31.B, 0x08); expectEq(color31.A, 0xFF); expectEq(color16_16.R, 0x04); expectEq(color16_16.G, 0xFF); expectEq(color16_16.B, 0x00); expectEq(color16_16.A, 131); } } test "Read basn6a16 data properly" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/png/basn6a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgba64); const color0 = pixels.Rgba64[0]; const color16 = pixels.Rgba64[16]; const color31 = pixels.Rgba64[31]; const color16_16 = pixels.Rgba64[16 * 32 + 16]; const color25_17 = pixels.Rgba64[17 * 32 + 25]; expectEq(color0.R, 0xFFFF); expectEq(color0.G, 0xFFFF); expectEq(color0.B, 0x0000); expectEq(color0.A, 0x0000); expectEq(color16.R, 0x7BDE); expectEq(color16.G, 0xFFFF); expectEq(color16.B, 0x0000); expectEq(color16.A, 0x0000); expectEq(color31.R, 0x0000); expectEq(color31.G, 0xFFFF); expectEq(color31.B, 0x0000); expectEq(color31.A, 0x0000); expectEq(color16_16.R, 0x0000); expectEq(color16_16.G, 0x0000); expectEq(color16_16.B, 0xFFFF); expectEq(color16_16.A, 0xF7BD); expectEq(color25_17.R, 0x0000); expectEq(color25_17.G, 0x6BC9); expectEq(color25_17.B, 0x9435); expectEq(color25_17.A, 0x6319); } }
tests/formats/png_basn_test.zig
const std = @import("std"); const assert = std.debug.assert; const image = @import("image.zig"); var alloctr: *std.mem.Allocator = undefined; pub var stdout: std.fs.File.Writer = undefined; pub const ArgError = error{ OpInvalid, NotEnoughArgs, BytesInvalid, FormatInvalid, }; const Op = enum(u8) { Help = 0, HelpLong = 1, File = 2, FileLong = 3, Text = 4, TextLong = 5, fn parse(op_str_user: []const u8) ArgError!Op { const ops = [_][]const u8{ "-h", "--help", "-f", "--file", "-t", "--text" }; var op_idx: u8 = 0; for (ops) |op_str| { if (std.mem.eql(u8, op_str, op_str_user)) { return @intToEnum(Op, op_idx); } op_idx += 1; } return ArgError.OpInvalid; } }; /// Ignores errors fn usage() void { stdout.writeByte('\n') catch {}; stdout.print( \\Usage: bytes2img <[-h | -f | -t] width height img_format byte_src> \\ \\-h,--help: Displays a help message. \\-f,--file: Reads bytes from a file. \\-t,--text: Reads bytes from the string that has been passed in. \\ \\Note: The output will be saved inside the current working directory as 'out.[img_format]'. \\Note: The 'img_format' is the extension name like 'pbm'. \\Note: The byte string is assumed to be a lowercase string of hex digits like '1badb002'. Placing any symbol that is not in the hex alphabet will lead to immediate exit. , .{}) catch {}; stdout.writeByte('\n') catch {}; } fn fileReadAll(path: []const u8) ![]u8 { var path_absolute: []const u8 = undefined; if (std.fs.path.isAbsolute(path) == true) { path_absolute = path; } else { path_absolute = try std.fs.path.resolve(alloctr, &[_][]const u8{path}); } try stdout.print("Parsed path to absolute path: '{s}'\n", .{path_absolute}); const file: std.fs.File = try std.fs.openFileAbsolute(path_absolute, std.fs.File.OpenFlags{ .read = true, .write = false }); const buf: []u8 = try file.readToEndAllocOptions(alloctr, std.math.maxInt(u64), null, @alignOf(u32), null); try stdout.print("Read {d} bytes from file\n", .{buf.len}); return buf; } /// Check if all characters in a buffer are a hex digits (0-9,a-f) fn validateHexChars(buffer: []const u8) bool { for (buffer) |char| { switch (char) { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' => continue, else => return false, } } return true; } pub fn main() !void { errdefer usage(); var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); alloctr = &arena.allocator; var argv = std.process.args(); stdout = std.io.getStdOut().writer(); // Skip exe name assert(argv.skip() == true); // Read byte source type const src_op_str = try argv.next(alloctr) orelse return ArgError.NotEnoughArgs; const src_op = Op.parse(src_op_str) catch |err| { try stdout.print("Failed to parse operation string, got: {s}\n", .{err}); return err; }; // Early exit since help was requested if (src_op == Op.Help or src_op == Op.HelpLong) { usage(); return; } // Read width and height const width_str = try argv.next(alloctr) orelse return ArgError.NotEnoughArgs; const height_str = try argv.next(alloctr) orelse return ArgError.NotEnoughArgs; const width: u16 = try std.fmt.parseUnsigned(u16, width_str, 10); const height: u16 = try std.fmt.parseUnsigned(u16, height_str, 10); // Read image format const format_str = try argv.next(alloctr) orelse return ArgError.NotEnoughArgs; const format: image.ImageFormat = image.ImageFormat.parse(format_str) catch |err| { switch (err) { ArgError.FormatInvalid => try stdout.print("The provided file format is not supported\n", .{}), else => unreachable, } return err; }; const file_name_base = "out"; var file_name: [16]u8 = undefined; _ = try std.fmt.bufPrint(&file_name, file_name_base ++ ".{s}", .{format_str}); // The output file is created and opened here const file_save = try std.fs.cwd().createFile(file_name[0..(4 + format_str.len)], std.fs.File.CreateFlags{}); defer file_save.close(); // Get a buffer hex digit characters var hex_digits: []u8 = undefined; switch (src_op) { Op.Help, Op.HelpLong => { usage(); return; }, Op.File, Op.FileLong => { const file_path = try (argv.next(alloctr) orelse { try stdout.print("Expected third argument to be a path to file with bytes\n", .{}); return error.InvalidArgs; }); const hex_digits_raw: []u8 = try fileReadAll(file_path); if (validateHexChars(hex_digits_raw) == true) { hex_digits = hex_digits_raw; } else { return ArgError.BytesInvalid; } }, Op.Text, Op.TextLong => { const hex_digits_raw = try (argv.next(alloctr) orelse { try stdout.print("Expected third argument to be a string of bytes\n", .{}); return error.InvalidArgs; }); if (validateHexChars(hex_digits_raw) == true) { hex_digits = hex_digits_raw; } else { return ArgError.BytesInvalid; } }, } // Combine 2 characters together into a pixel/color value var hex_digit_idx: u32 = 0; while (hex_digit_idx < (hex_digits.len / 2)) : (hex_digit_idx += 1) { var byte_a = hex_digits[(hex_digit_idx) * 2]; if (byte_a >= '0' and byte_a <= '9') { byte_a = byte_a - '0'; } else { byte_a = 10 + (byte_a - 'a'); } var byte_b = hex_digits[(hex_digit_idx * 2) + 1]; if (byte_b >= '0' and byte_b <= '9') { byte_b = byte_b - '0'; } else { byte_b = 10 + (byte_b - 'a'); } hex_digits[hex_digit_idx] = (byte_a * 16) + byte_b; } // This slice contains a byte per pixel/color channel const bytes = hex_digits[0..(hex_digits.len / 2)]; try stdout.print("Writing output to '{s}'\n", .{file_name[0..(file_name_base.len + 1 + format_str.len)]}); try image.saveFile(&file_save, bytes, format, width, height); }
src/main.zig
const std = @import("std"); const glfw = @import("glfw.zig"); const vk = @import("vulkan.zig"); const builtin = std.builtin; const fs = std.fs; const math = std.math; const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const BufSet = std.BufSet; const max_frames_in_flight = 2; const device_extensions = [_][]const u8{vk.swapchain_extension_name}; const validation_layers = [_][]const u8{vk.layer_khronos_validation}; const QueueFamilyIndices = struct { graphics_family: ?u32, present_family: ?u32, fn isComplete(self: QueueFamilyIndices) bool { return self.graphics_family != null and self.present_family != null; } }; const SwapChainSupportDetails = struct { capabilities: vk.SurfaceCapabilities, formats: ArrayList(vk.SurfaceFormat), present_modes: ArrayList(vk.PresentMode), fn init(allocator: *Allocator) SwapChainSupportDetails { return SwapChainSupportDetails{ .capabilities = undefined, .formats = ArrayList(vk.SurfaceFormat).init(allocator), .present_modes = ArrayList(vk.PresentMode).init(allocator), }; } fn deinit(self: *SwapChainSupportDetails) void { self.formats.deinit(); self.present_modes.deinit(); } }; var window: *glfw.Window = undefined; var instance: vk.Instance = undefined; var debug_messenger: vk.DebugUtilsMessenger = undefined; var surface: vk.Surface = undefined; var physical_device: vk.PhysicalDevice = undefined; var device: vk.Device = undefined; var graphics_queue: vk.Queue = undefined; var present_queue: vk.Queue = undefined; var swap_chain: vk.Swapchain = undefined; var swap_chain_images: []vk.Image = undefined; var swap_chain_image_format: vk.Format = undefined; var swap_chain_extent: vk.Extent2D = undefined; var swap_chain_image_views: []vk.ImageView = undefined; var swap_chain_framebuffers: []vk.Framebuffer = undefined; var render_pass: vk.RenderPass = undefined; var pipeline_layout: vk.PipelineLayout = undefined; var graphics_pipeline: vk.Pipeline = undefined; var command_pool: vk.CommandPool = undefined; var command_buffers: []vk.CommandBuffer = undefined; var image_available_semaphores: [max_frames_in_flight]vk.Semaphore = undefined; var render_finished_semaphores: [max_frames_in_flight]vk.Semaphore = undefined; var in_flight_fences: [max_frames_in_flight]vk.Fence = undefined; var images_in_flight: []vk.Fence = undefined; var current_frame: usize = 0; var framebuffer_resized = false; fn resizeCallback(win: ?*glfw.Window, width: c_int, height: c_int) callconv(.C) void { framebuffer_resized = true; } fn errorCallback(error_code: c_int, description: [*c]const u8) callconv(.C) void { std.debug.warn("GLFW: {s}\n", .{description}); } fn debugCallback( message_severity: vk.DebugUtilsMessageSeverityFlagBits, message_types: vk.DebugUtilsMessageTypeFlags, callback_data: [*c]const vk.DebugUtilsMessengerCallbackData, user_data: ?*c_void, ) callconv(.C) vk.Bool32 { std.debug.warn("Vulkan: {s}\n", .{callback_data.*.pMessage}); return @boolToInt(false); } pub fn main() !void { if (builtin.mode == .Debug) { _ = glfw.setErrorCallback(errorCallback); } if (!glfw.init()) return error.GlfwInitFailed; defer glfw.terminate(); if (!glfw.vulkanSupported()) return error.VulkanNotSupported; glfw.windowHint(glfw.client_api, glfw.no_api); window = glfw.createWindow(1920, 1080, "Triangle", null, null) orelse return error.GlfwCreateWindowFailed; defer glfw.destroyWindow(window); _ = glfw.setFramebufferSizeCallback(window, resizeCallback); try init(); defer deinit(); while (!glfw.windowShouldClose(window)) { glfw.pollEvents(); try drawFrame(); } try vk.deviceWaitIdle(device); } fn init() !void { const allocator = std.heap.c_allocator; try createInstance(allocator); try setupDebugMessenger(); try createSurface(); try pickPhysicalDevice(allocator); try createLogicalDevice(allocator); try createSwapChain(allocator); try createImageViews(allocator); try createRenderPass(); try createGraphicsPipeline(allocator); try createFramebuffers(allocator); try createCommandPool(allocator); try createCommandBuffers(allocator); try createSyncObjects(allocator); } fn deinit() void { cleanupSwapChain(); comptime var i = 0; inline while (i < max_frames_in_flight) : (i += 1) { vk.destroySemaphore(device, render_finished_semaphores[i], null); vk.destroySemaphore(device, image_available_semaphores[i], null); vk.destroyFence(device, in_flight_fences[i], null); } vk.destroyCommandPool(device, command_pool, null); vk.destroyDevice(device, null); vk.destroySurface(instance, surface, null); if (builtin.mode == .Debug) { vk.destroyDebugUtilsMessenger(instance, debug_messenger, null); } vk.destroyInstance(instance, null); } fn cleanupSwapChain() void { for (swap_chain_framebuffers) |framebuffer| { vk.destroyFramebuffer(device, framebuffer, null); } vk.freeCommandBuffers(device, command_pool, command_buffers); vk.destroyPipeline(device, graphics_pipeline, null); vk.destroyPipelineLayout(device, pipeline_layout, null); vk.destroyRenderPass(device, render_pass, null); for (swap_chain_image_views) |image_view| { vk.destroyImageView(device, image_view, null); } vk.destroySwapchain(device, swap_chain, null); } fn recreateSwapChain() !void { var width: i32 = 0; var height: i32 = 0; glfw.getFramebufferSize(window, &width, &height); while (width == 0 or height == 0) { glfw.getFramebufferSize(window, &width, &height); glfw.waitEvents(); } try vk.deviceWaitIdle(device); cleanupSwapChain(); const allocator = std.heap.c_allocator; try createSwapChain(allocator); try createImageViews(allocator); try createRenderPass(); try createGraphicsPipeline(allocator); try createFramebuffers(allocator); try createCommandBuffers(allocator); } fn setupDebugMessenger() !void { if (builtin.mode != .Debug) return; const create_info = vk.DebugUtilsMessengerCreateInfo{ .sType = .VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .pNext = null, .flags = 0, .messageSeverity = vk.debug_utils_message_severity_warning_bit | vk.debug_utils_message_severity_error_bit, .messageType = vk.debug_utils_message_type_general_bit | vk.debug_utils_message_type_validation_bit | vk.debug_utils_message_type_performance_bit, .pfnUserCallback = debugCallback, .pUserData = null, }; try vk.createDebugUtilsMessenger(instance, &create_info, null, &debug_messenger); } fn createSurface() !void { try glfw.createWindowSurface(instance, window, null, &surface); } fn findQueueFamilies(allocator: *Allocator, phys_dev: vk.PhysicalDevice) !QueueFamilyIndices { var indices = QueueFamilyIndices{ .graphics_family = null, .present_family = null, }; var queue_family_count: u32 = 0; vk.getPhysicalDeviceQueueFamilyProperties(phys_dev, &queue_family_count, null); const queue_families = try allocator.alloc(vk.QueueFamilyProperties, queue_family_count); defer allocator.free(queue_families); vk.getPhysicalDeviceQueueFamilyProperties(phys_dev, &queue_family_count, queue_families); for (queue_families) |queue_family, i| { if (queue_family.queueFlags & @intCast(u32, vk.queue_graphics_bit) != 0) { indices.graphics_family = @intCast(u32, i); } var present_support align(@alignOf(vk.Bool32)) = false; try vk.getPhysicalDeviceSurfaceSupport(phys_dev, i, surface, &present_support); if (present_support) { indices.present_family = @intCast(u32, i); } if (indices.isComplete()) { break; } } return indices; } fn checkDeviceExtensionSupport(allocator: *Allocator, phys_dev: vk.PhysicalDevice) !bool { var extension_count: u32 = 0; _ = try vk.enumerateDeviceExtensionProperties(phys_dev, null, &extension_count, null); const available_extensions = try allocator.alloc(vk.ExtensionProperties, extension_count); defer allocator.free(available_extensions); _ = try vk.enumerateDeviceExtensionProperties(phys_dev, null, &extension_count, available_extensions); var required_extensions = BufSet.init(allocator); defer required_extensions.deinit(); for (device_extensions) |extension| { try required_extensions.put(extension); } for (available_extensions) |extension| { required_extensions.delete(mem.spanZ(@ptrCast([*:0]const u8, &extension.extensionName))); } return required_extensions.count() == 0; } fn querySwapChainSupport(allocator: *Allocator, phys_dev: vk.PhysicalDevice) !SwapChainSupportDetails { var details = SwapChainSupportDetails.init(allocator); errdefer details.deinit(); try vk.getPhysicalDeviceSurfaceCapabilities(phys_dev, surface, &details.capabilities); var format_count: u32 = 0; _ = try vk.getPhysicalDeviceSurfaceFormats(phys_dev, surface, &format_count, null); if (format_count > 0) { try details.formats.resize(format_count); _ = try vk.getPhysicalDeviceSurfaceFormats(phys_dev, surface, &format_count, details.formats.items); } var present_mode_count: u32 = 0; _ = try vk.getPhysicalDeviceSurfacePresentModes(phys_dev, surface, &present_mode_count, null); if (present_mode_count > 0) { try details.present_modes.resize(present_mode_count); _ = try vk.getPhysicalDeviceSurfacePresentModes(phys_dev, surface, &present_mode_count, details.present_modes.items); } return details; } fn isDeviceSuitable(allocator: *Allocator, phys_dev: vk.PhysicalDevice) !bool { const indices = try findQueueFamilies(allocator, phys_dev); if (!indices.isComplete()) return false; var swap_chain_adequate = false; if (try checkDeviceExtensionSupport(allocator, phys_dev)) { var swap_chain_support = try querySwapChainSupport(allocator, phys_dev); defer swap_chain_support.deinit(); swap_chain_adequate = swap_chain_support.formats.items.len > 0 and swap_chain_support.present_modes.items.len > 0; } return swap_chain_adequate; } fn pickPhysicalDevice(allocator: *Allocator) !void { var device_count: u32 = 0; _ = try vk.enumeratePhysicalDevices(instance, &device_count, null); if (device_count == 0) return error.FailedToFindGPUsWithVulkanSupport; const devices = try allocator.alloc(vk.PhysicalDevice, device_count); defer allocator.free(devices); _ = try vk.enumeratePhysicalDevices(instance, &device_count, devices); physical_device = for (devices) |dev| { if (try isDeviceSuitable(allocator, dev)) { break dev; } } else return error.FailedToFindSuitableGPU; } fn createLogicalDevice(allocator: *Allocator) !void { const indices = try findQueueFamilies(allocator, physical_device); const all_queue_families = [_]u32{ indices.graphics_family.?, indices.present_family.? }; const unique_queue_families = if (indices.graphics_family.? == indices.present_family.?) all_queue_families[0..1] else all_queue_families[0..2]; const queue_create_infos = try allocator.alloc(vk.DeviceQueueCreateInfo, unique_queue_families.len); defer allocator.free(queue_create_infos); const queue_priority: f32 = 1.0; for (unique_queue_families) |queue_family, i| { queue_create_infos[i] = vk.DeviceQueueCreateInfo{ .sType = .VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = null, .flags = 0, .queueFamilyIndex = queue_family, .queueCount = 1, .pQueuePriorities = &queue_priority, }; } const device_features = mem.zeroes(vk.PhysicalDeviceFeatures); var create_info = vk.DeviceCreateInfo{ .sType = .VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = null, .flags = 0, .queueCreateInfoCount = @intCast(u32, queue_create_infos.len), .pQueueCreateInfos = queue_create_infos.ptr, .enabledLayerCount = 0, .ppEnabledLayerNames = null, .enabledExtensionCount = @intCast(u32, device_extensions.len), .ppEnabledExtensionNames = @ptrCast([*]const [*]const u8, &device_extensions), .pEnabledFeatures = &device_features, }; if (builtin.mode == .Debug) { create_info.enabledLayerCount = @intCast(u32, validation_layers.len); create_info.ppEnabledLayerNames = @ptrCast([*]const [*]const u8, &validation_layers); } try vk.createDevice(physical_device, &create_info, null, &device); vk.getDeviceQueue(device, indices.graphics_family.?, 0, &graphics_queue); vk.getDeviceQueue(device, indices.present_family.?, 0, &present_queue); } fn chooseSwapSurfaceFormat(formats: []vk.SurfaceFormat) vk.SurfaceFormat { return for (formats) |format| { if (format.format == .VK_FORMAT_B8G8R8A8_SRGB and format.colorSpace == .VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { break format; } } else formats[0]; } fn chooseSwapPresentMode(present_modes: []vk.PresentMode) vk.PresentMode { return for (present_modes) |mode| { if (mode == .VK_PRESENT_MODE_MAILBOX_KHR) { break mode; } } else .VK_PRESENT_MODE_FIFO_KHR; } fn chooseSwapExtent(capabilities: *vk.SurfaceCapabilities) vk.Extent2D { if (capabilities.currentExtent.width < math.maxInt(u32)) return capabilities.currentExtent; var width: i32 = 0; var height: i32 = 0; glfw.getFramebufferSize(window, &width, &height); return vk.Extent2D{ .width = math.max( capabilities.minImageExtent.width, math.min(capabilities.maxImageExtent.width, @intCast(u32, width)), ), .height = math.max( capabilities.minImageExtent.height, math.min(capabilities.maxImageExtent.height, @intCast(u32, height)), ), }; } fn createSwapChain(allocator: *Allocator) !void { var swap_chain_support = try querySwapChainSupport(allocator, physical_device); defer swap_chain_support.deinit(); const surface_format = chooseSwapSurfaceFormat(swap_chain_support.formats.items); const present_mode = chooseSwapPresentMode(swap_chain_support.present_modes.items); const extent = chooseSwapExtent(&swap_chain_support.capabilities); var image_count = swap_chain_support.capabilities.minImageCount + 1; if (swap_chain_support.capabilities.maxImageCount > 0 and swap_chain_support.capabilities.maxImageCount < image_count) { image_count = swap_chain_support.capabilities.maxImageCount; } var create_info = vk.SwapchainCreateInfo{ .sType = .VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .pNext = null, .flags = 0, .surface = surface, .minImageCount = image_count, .imageFormat = surface_format.format, .imageColorSpace = surface_format.colorSpace, .imageExtent = extent, .imageArrayLayers = 1, .imageUsage = vk.image_usage_color_attachment_bit, .imageSharingMode = .VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = null, .preTransform = swap_chain_support.capabilities.currentTransform, .compositeAlpha = .VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, .presentMode = present_mode, .clipped = @boolToInt(true), .oldSwapchain = null, }; const indices = try findQueueFamilies(allocator, physical_device); if (indices.graphics_family.? != indices.present_family.?) { const queue_families = [_]u32{ indices.graphics_family.?, indices.present_family.? }; create_info.imageSharingMode = .VK_SHARING_MODE_CONCURRENT; create_info.queueFamilyIndexCount = queue_families.len; create_info.pQueueFamilyIndices = &queue_families; } try vk.createSwapchain(device, &create_info, null, &swap_chain); _ = try vk.getSwapchainImages(device, swap_chain, &image_count, null); swap_chain_images = try allocator.alloc(vk.Image, image_count); errdefer allocator.free(swap_chain_images); _ = try vk.getSwapchainImages(device, swap_chain, &image_count, swap_chain_images); swap_chain_image_format = surface_format.format; swap_chain_extent = extent; } fn createImageViews(allocator: *Allocator) !void { swap_chain_image_views = try allocator.alloc(vk.ImageView, swap_chain_images.len); errdefer allocator.free(swap_chain_image_views); for (swap_chain_images) |image, i| { const create_info = vk.ImageViewCreateInfo{ .sType = .VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .pNext = null, .flags = 0, .image = image, .viewType = .VK_IMAGE_VIEW_TYPE_2D, .format = swap_chain_image_format, .components = vk.ComponentMapping{ .r = .VK_COMPONENT_SWIZZLE_IDENTITY, .g = .VK_COMPONENT_SWIZZLE_IDENTITY, .b = .VK_COMPONENT_SWIZZLE_IDENTITY, .a = .VK_COMPONENT_SWIZZLE_IDENTITY, }, .subresourceRange = vk.ImageSubresourceRange{ .aspectMask = vk.image_aspect_color_bit, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }, }; try vk.createImageView(device, &create_info, null, &swap_chain_image_views[i]); } } fn createRenderPass() !void { const color_attachment = vk.AttachmentDescription{ .flags = 0, .format = swap_chain_image_format, .samples = .VK_SAMPLE_COUNT_1_BIT, .loadOp = .VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = .VK_ATTACHMENT_STORE_OP_STORE, .stencilLoadOp = .VK_ATTACHMENT_LOAD_OP_DONT_CARE, .stencilStoreOp = .VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = .VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = .VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, }; const color_attachment_ref = vk.AttachmentReference{ .attachment = 0, .layout = .VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; const subpass = vk.SubpassDescription{ .flags = 0, .pipelineBindPoint = .VK_PIPELINE_BIND_POINT_GRAPHICS, .inputAttachmentCount = 0, .pInputAttachments = null, .colorAttachmentCount = 1, .pColorAttachments = &color_attachment_ref, .pResolveAttachments = null, .pDepthStencilAttachment = null, .preserveAttachmentCount = 0, .pPreserveAttachments = null, }; const dependency = vk.SubpassDependency{ .srcSubpass = vk.subpass_external, .dstSubpass = 0, .srcStageMask = vk.pipeline_stage_color_attachment_output_bit, .dstStageMask = vk.pipeline_stage_color_attachment_output_bit, .srcAccessMask = 0, .dstAccessMask = vk.access_color_attachment_write_bit, .dependencyFlags = 0, }; const render_pass_info = vk.RenderPassCreateInfo{ .sType = .VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .pNext = null, .flags = 0, .attachmentCount = 1, .pAttachments = &color_attachment, .subpassCount = 1, .pSubpasses = &subpass, .dependencyCount = 1, .pDependencies = &dependency, }; try vk.createRenderPass(device, &render_pass_info, null, &render_pass); } fn createFramebuffers(allocator: *Allocator) !void { swap_chain_framebuffers = try allocator.alloc(vk.Framebuffer, swap_chain_image_views.len); errdefer allocator.free(swap_chain_framebuffers); for (swap_chain_image_views) |*image_view, i| { const framebuffer_info = vk.FramebufferCreateInfo{ .sType = .VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .pNext = null, .flags = 0, .renderPass = render_pass, .attachmentCount = 1, .pAttachments = @ptrCast([*]const vk.ImageView, image_view), .width = swap_chain_extent.width, .height = swap_chain_extent.height, .layers = 1, }; try vk.createFramebuffer(device, &framebuffer_info, null, &swap_chain_framebuffers[i]); } } fn createCommandPool(allocator: *Allocator) !void { const indices = try findQueueFamilies(allocator, physical_device); const pool_info = vk.CommandPoolCreateInfo{ .sType = .VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .pNext = null, .flags = 0, .queueFamilyIndex = indices.graphics_family.?, }; try vk.createCommandPool(device, &pool_info, null, &command_pool); } fn createSyncObjects(allocator: *Allocator) !void { images_in_flight = try allocator.alloc(vk.Fence, swap_chain_images.len); errdefer allocator.free(images_in_flight); mem.set(vk.Fence, images_in_flight, null); const semaphore_info = vk.SemaphoreCreateInfo{ .sType = .VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = null, .flags = 0, }; const fence_info = vk.FenceCreateInfo{ .sType = .VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = null, .flags = vk.fence_create_signaled_bit, }; comptime var i = 0; inline while (i < max_frames_in_flight) : (i += 1) { try vk.createSemaphore(device, &semaphore_info, null, &image_available_semaphores[i]); try vk.createSemaphore(device, &semaphore_info, null, &render_finished_semaphores[i]); try vk.createFence(device, &fence_info, null, &in_flight_fences[i]); } } fn createShaderModule(code: []const u8) !vk.ShaderModule { const create_info = vk.ShaderModuleCreateInfo{ .sType = .VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .pNext = null, .flags = 0, .codeSize = code.len, .pCode = mem.bytesAsSlice(u32, @alignCast(@alignOf(u32), code)).ptr, // XXX }; var shader_module: vk.ShaderModule = undefined; try vk.createShaderModule(device, &create_info, null, &shader_module); return shader_module; } fn createGraphicsPipeline(allocator: *Allocator) !void { const vert_shader_code = try fs.cwd().readFileAlloc(allocator, "shaders/triangle.vert.spv", 2048); defer allocator.free(vert_shader_code); const frag_shader_code = try fs.cwd().readFileAlloc(allocator, "shaders/triangle.frag.spv", 2048); defer allocator.free(frag_shader_code); const vert_shader_module = try createShaderModule(vert_shader_code); defer vk.destroyShaderModule(device, vert_shader_module, null); const frag_shader_module = try createShaderModule(frag_shader_code); defer vk.destroyShaderModule(device, frag_shader_module, null); const shader_stages = [_]vk.PipelineShaderStageCreateInfo{ vk.PipelineShaderStageCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .pNext = null, .flags = 0, .stage = .VK_SHADER_STAGE_VERTEX_BIT, .module = vert_shader_module, .pName = "main", .pSpecializationInfo = null, }, vk.PipelineShaderStageCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .pNext = null, .flags = 0, .stage = .VK_SHADER_STAGE_FRAGMENT_BIT, .module = frag_shader_module, .pName = "main", .pSpecializationInfo = null, }, }; const vertex_input_info = vk.PipelineVertexInputStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .pNext = null, .flags = 0, .vertexBindingDescriptionCount = 0, .pVertexBindingDescriptions = null, .vertexAttributeDescriptionCount = 0, .pVertexAttributeDescriptions = null, }; const input_assembly = vk.PipelineInputAssemblyStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .pNext = null, .flags = 0, .topology = .VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, .primitiveRestartEnable = @boolToInt(false), }; const viewport = vk.Viewport{ .x = 0.0, .y = 0.0, .width = @intToFloat(f32, swap_chain_extent.width), .height = @intToFloat(f32, swap_chain_extent.height), .minDepth = 0.0, .maxDepth = 1.0, }; const scissor = vk.Rect2D{ .offset = vk.Offset2D{ .x = 0, .y = 0 }, .extent = swap_chain_extent, }; const viewport_state = vk.PipelineViewportStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .pNext = null, .flags = 0, .viewportCount = 1, .pViewports = &viewport, .scissorCount = 1, .pScissors = &scissor, }; const rasterizer = vk.PipelineRasterizationStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .pNext = null, .flags = 0, .depthClampEnable = @boolToInt(false), .rasterizerDiscardEnable = @boolToInt(false), .polygonMode = .VK_POLYGON_MODE_FILL, .cullMode = vk.cull_mode_back_bit, .frontFace = .VK_FRONT_FACE_CLOCKWISE, .depthBiasEnable = @boolToInt(false), .depthBiasConstantFactor = 0, .depthBiasClamp = 0, .depthBiasSlopeFactor = 0, .lineWidth = 1.0, }; const multisampling = vk.PipelineMultisampleStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .pNext = null, .flags = 0, .rasterizationSamples = .VK_SAMPLE_COUNT_1_BIT, .sampleShadingEnable = @boolToInt(false), .minSampleShading = 0, .pSampleMask = null, .alphaToCoverageEnable = @boolToInt(false), .alphaToOneEnable = @boolToInt(false), }; const color_blend_attachment = vk.PipelineColorBlendAttachmentState{ .colorWriteMask = vk.color_component_r_bit | vk.color_component_g_bit | vk.color_component_b_bit | vk.color_component_a_bit, .blendEnable = @boolToInt(false), .srcColorBlendFactor = .VK_BLEND_FACTOR_ZERO, .dstColorBlendFactor = .VK_BLEND_FACTOR_ZERO, .colorBlendOp = .VK_BLEND_OP_ADD, .srcAlphaBlendFactor = .VK_BLEND_FACTOR_ZERO, .dstAlphaBlendFactor = .VK_BLEND_FACTOR_ZERO, .alphaBlendOp = .VK_BLEND_OP_ADD, }; const color_blending = vk.PipelineColorBlendStateCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .pNext = null, .flags = 0, .logicOpEnable = @boolToInt(false), .logicOp = .VK_LOGIC_OP_COPY, .attachmentCount = 1, .pAttachments = &color_blend_attachment, .blendConstants = [_]f32{ 0, 0, 0, 0 }, }; const pipeline_layout_info = vk.PipelineLayoutCreateInfo{ .sType = .VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .pNext = null, .flags = 0, .setLayoutCount = 0, .pSetLayouts = null, .pushConstantRangeCount = 0, .pPushConstantRanges = null, }; try vk.createPipelineLayout(device, &pipeline_layout_info, null, &pipeline_layout); const pipeline_info = [_]vk.GraphicsPipelineCreateInfo{vk.GraphicsPipelineCreateInfo{ .sType = .VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = null, .flags = 0, .stageCount = shader_stages.len, .pStages = &shader_stages, .pVertexInputState = &vertex_input_info, .pInputAssemblyState = &input_assembly, .pTessellationState = null, .pViewportState = &viewport_state, .pRasterizationState = &rasterizer, .pMultisampleState = &multisampling, .pDepthStencilState = null, .pColorBlendState = &color_blending, .pDynamicState = null, .layout = pipeline_layout, .renderPass = render_pass, .subpass = 0, .basePipelineHandle = null, .basePipelineIndex = 0, }}; _ = try vk.createGraphicsPipelines(device, null, &pipeline_info, null, @as(*[1]vk.Pipeline, &graphics_pipeline)); } fn drawFrame() !void { _ = try vk.waitForFences(device, @as(*[1]vk.Fence, &in_flight_fences[current_frame]), true, math.maxInt(u64)); var image_index: u32 = 0; if (vk.acquireNextImage(device, swap_chain, math.maxInt(u64), image_available_semaphores[current_frame], null, &image_index)) |result| { if (result != .Success and result != .Suboptimal) return error.FailedToAcquireImage; } else |err| switch (err) { error.OutOfDate => { try recreateSwapChain(); return; }, else => return err, } if (images_in_flight[image_index] != null) { _ = try vk.waitForFences(device, @as(*[1]vk.Fence, &images_in_flight[image_index]), true, math.maxInt(u64)); } images_in_flight[image_index] = in_flight_fences[current_frame]; const signal_semaphores = [_]vk.Semaphore{render_finished_semaphores[current_frame]}; // XXX const submit_info = [_]vk.SubmitInfo{vk.SubmitInfo{ // XXX .sType = .VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = null, .waitSemaphoreCount = 1, .pWaitSemaphores = &[_]vk.Semaphore{image_available_semaphores[current_frame]}, .pWaitDstStageMask = &[_]vk.PipelineStageFlags{vk.pipeline_stage_color_attachment_output_bit}, .commandBufferCount = 1, .pCommandBuffers = &command_buffers[image_index], .signalSemaphoreCount = 1, .pSignalSemaphores = &signal_semaphores, }}; try vk.resetFences(device, @as(*[1]vk.Fence, &in_flight_fences[current_frame])); try vk.queueSubmit(graphics_queue, &submit_info, in_flight_fences[current_frame]); const present_info = vk.PresentInfo{ // XXX .sType = .VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = null, .waitSemaphoreCount = 1, .pWaitSemaphores = &signal_semaphores, .swapchainCount = 1, .pSwapchains = &[_]vk.Swapchain{swap_chain}, .pImageIndices = &image_index, .pResults = null, }; if (vk.queuePresent(present_queue, &present_info)) |result| { if (result == .Suboptimal or framebuffer_resized) { framebuffer_resized = false; try recreateSwapChain(); } } else |err| switch (err) { error.OutOfDate => { framebuffer_resized = false; try recreateSwapChain(); }, else => return err, } current_frame = (current_frame + 1) % max_frames_in_flight; } fn getRequiredExtensions(allocator: *Allocator) ![]const [*c]const u8 { var glfw_extension_count: u32 = 0; const glfw_extensions = glfw.getRequiredInstanceExtensions(&glfw_extension_count) orelse return error.GlfwGetRequiredInstanceExtensionsFailed; // TODO Use unknown length pointer over C pointer var extensions = try ArrayList([*c]const u8).initCapacity(allocator, glfw_extension_count + 1); errdefer extensions.deinit(); extensions.appendSliceAssumeCapacity(glfw_extensions[0..glfw_extension_count]); if (builtin.mode == .Debug) { extensions.appendAssumeCapacity(vk.debug_utils_extension_name); } return extensions.toOwnedSlice(); } fn checkValidationLayerSupport(allocator: *Allocator) !bool { var layer_count: u32 = 0; _ = try vk.enumerateInstanceLayerProperties(&layer_count, null); const available_layers = try allocator.alloc(vk.LayerProperties, layer_count); defer allocator.free(available_layers); _ = try vk.enumerateInstanceLayerProperties(&layer_count, available_layers); for (validation_layers) |validation_layer| { var layer_found = false; for (available_layers) |available_layer| { const layer = mem.spanZ(@ptrCast([*:0]const u8, &available_layer.layerName)); if (mem.eql(u8, layer, validation_layer)) { layer_found = true; break; } } if (!layer_found) return false; } return true; } fn createInstance(allocator: *Allocator) !void { const app_info = vk.ApplicationInfo{ .sType = .VK_STRUCTURE_TYPE_APPLICATION_INFO, .pNext = null, .pApplicationName = "Triangle", .applicationVersion = vk.makeVersion(1, 0, 0), .pEngineName = null, .engineVersion = 0, .apiVersion = 0, }; const extensions = try getRequiredExtensions(allocator); defer allocator.free(extensions); var create_info = vk.InstanceCreateInfo{ .sType = .VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = null, .flags = 0, .pApplicationInfo = &app_info, .enabledLayerCount = 0, .ppEnabledLayerNames = null, .enabledExtensionCount = @intCast(u32, extensions.len), .ppEnabledExtensionNames = extensions.ptr, }; if (builtin.mode == .Debug) { if (!try checkValidationLayerSupport(allocator)) return error.ValidationLayersNotAvailable; const debug_create_info = vk.DebugUtilsMessengerCreateInfo{ .sType = .VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .pNext = null, .flags = 0, .messageSeverity = vk.debug_utils_message_severity_warning_bit | vk.debug_utils_message_severity_error_bit, .messageType = vk.debug_utils_message_type_general_bit | vk.debug_utils_message_type_validation_bit | vk.debug_utils_message_type_performance_bit, .pfnUserCallback = debugCallback, .pUserData = null, }; create_info.pNext = &debug_create_info; create_info.enabledLayerCount = validation_layers.len; create_info.ppEnabledLayerNames = @ptrCast([*]const [*]const u8, &validation_layers); } try vk.createInstance(&create_info, null, &instance); } fn createCommandBuffers(allocator: *Allocator) !void { command_buffers = try allocator.alloc(vk.CommandBuffer, swap_chain_framebuffers.len); errdefer allocator.free(command_buffers); const alloc_info = vk.CommandBufferAllocateInfo{ .sType = .VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = null, .commandPool = command_pool, .level = .VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = @intCast(u32, command_buffers.len), }; try vk.allocateCommandBuffers(device, &alloc_info, command_buffers); for (command_buffers) |command_buffer, i| { const begin_info = vk.CommandBufferBeginInfo{ .sType = .VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = null, .flags = 0, .pInheritanceInfo = null, }; const clear_color = vk.ClearValue{ .color = vk.ClearColorValue{ .float32 = [_]f32{ 0.0, 0.0, 0.0, 1.0 }, }, }; const render_pass_info = vk.RenderPassBeginInfo{ .sType = .VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .pNext = null, .renderPass = render_pass, .framebuffer = swap_chain_framebuffers[i], .renderArea = vk.Rect2D{ .offset = vk.Offset2D{ .x = 0, .y = 0 }, .extent = swap_chain_extent, }, .clearValueCount = 1, .pClearValues = &clear_color, }; try vk.beginCommandBuffer(command_buffer, &begin_info); vk.cmdBeginRenderPass(command_buffer, &render_pass_info, .VK_SUBPASS_CONTENTS_INLINE); { vk.cmdBindPipeline(command_buffer, .VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline); vk.cmdDraw(command_buffer, 3, 1, 0, 0); } vk.cmdEndRenderPass(command_buffer); try vk.endCommandBuffer(command_buffer); } }
src/main.zig
const std = @import("std"); const mecha = @import("mecha"); const Parser = mecha.Parser; const oneOf = mecha.oneOf; const discard = mecha.discard; const combine = mecha.combine; const many = mecha.many; const map = mecha.map; const utf8 = mecha.utf8; const ascii = mecha.ascii; const opt = mecha.opt; const ref = mecha.ref; const Allocator = std.mem.Allocator; var alloc: *Allocator = undefined; fn discardUntil(comptime endChar: u8) Parser(void) { return struct { fn func(_: *Allocator, s: []const u8) mecha.Error!mecha.Void { const end = std.mem.indexOfScalar(u8, s, endChar) orelse s.len; return mecha.Void { .value = {}, .rest = s[end..] }; } }.func; } const ws = discard(many(oneOf(.{ utf8.char(0x20), // space utf8.char(0x0A), // line feed utf8.char(0x0D), // carriage return utf8.char(0x09), // horizontal tab combine(.{ ascii.char('-'), ascii.char('-'), discardUntil('\n') }) }), .{ .collect = false })); const literalString = oneOf(.{ combine(.{ discard(utf8.char('\'')), many(stringChar, .{ .collect = false }), discard(utf8.char('\'')) }), combine(.{ discard(utf8.char('"')), many(stringChar, .{ .collect = false }), discard(utf8.char('"')) }) }); const stringChar = oneOf(.{ utf8.range(0x0020, '"' - 1), utf8.range('"' + 1, '\\' - 1), utf8.range('\\' + 1, 0x10FFFF), combine(.{ ascii.char('\\'), oneOf(.{ utf8.range('n', 'n'), utf8.range('r', 'r'), utf8.range('\\', '\\') }) }) }); const name = many(oneOf(.{ ascii.alphanum, ascii.range('_', '_') }), .{ .collect = false, .min = 1 }); const number = many(oneOf(.{ ascii.digit(10), ascii.range('.', '.') }), .{ .collect = false, .min = 1 }); const namelist = many(name, .{ .min = 1, .separator = combine(.{ ascii.char(','), discard(opt(ws)) })}); const lvar = oneOf(.{ map(Expr, varPreExpConv, combine(.{ name, discard(opt(ws)), many( combine(.{ ascii.char('.'), discard(opt(ws)), ref(lvar_ref) }), .{ .min = 1 }) })), map(Expr, varNameConv, name), }); fn lvar_ref() Parser(Expr) { return lvar; } fn varNameConv(arg: anytype) Expr { return Expr { .Var = .{ .Name = arg } }; } fn varPreExpConv(arg: anytype) Expr { var lhs = Expr { .Var = .{ .Name = arg[0] } }; for (arg[1]) |rhs| { var lhsDupe = alloc.create(Expr) catch unreachable; lhsDupe.* = lhs; var rhsDupe = alloc.create(Expr) catch unreachable; rhsDupe.* = rhs; // what's detected as var is actually a string if (rhsDupe.* == .Var) { const new = .{ .LiteralString = rhsDupe.Var.Name }; rhsDupe.* = new; } lhs = Expr { .Index = .{ .lhs = lhsDupe, .rhs = rhsDupe, } }; } return lhs; } const varlist = many(lvar, .{ .min = 1, .separator = combine(.{ ascii.char(','), discard(opt(ws)) })}); pub const FunctionCall = struct { callee: Var, args: []const Expr }; pub const Var = union(enum) { Name: []const u8, pub fn format(value: Var, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; switch (value) { .Name => |varName| { try writer.writeAll(varName); } } } }; const TableConstructor = struct { pub const TableEntry = struct { key: Expr, value: Expr }; entries: []const TableEntry }; pub const Expr = union(enum) { Nil: void, Var: Var, LiteralString: []const u8, Number: f64, Boolean: bool, BinaryOperation: struct { lhs: *const Expr, op: []const u8, rhs: *const Expr }, FunctionCall: FunctionCall, FunctionDefinition: struct { stats: []Stat, argNames: [][]const u8 }, TableConstructor: TableConstructor, Index: struct { lhs: *const Expr, rhs: *const Expr } }; pub const Stat = union(enum) { NoOp: void, // ; Definition: struct { vars: []const Var, exprs: []const Expr }, LocalDefinition: struct { names: [][]const u8, exprs: []const Expr }, If: struct { /// The condition expression expr: Expr, statements: []const Stat }, Return: struct { expressions: []const Expr }, FunctionCall: FunctionCall }; const boolean = mecha.asStr(oneOf(.{ mecha.string("true"), mecha.string("false") })); const functiondef = combine(.{ discard(opt(ws)), mecha.string("function"), discard(opt(ws)), ascii.char('('), opt(namelist), ascii.char(')'), discard(opt(ws)), ref(block_ref), discard(opt(ws)), mecha.string("end"), discard(opt(ws)) }); const field = combine(.{ ascii.char('['), ws, ref(exp_ref), ws, ascii.char(']'), ws, ascii.char('='), ws, ref(exp_ref) }); const fieldsep = oneOf(.{ ascii.char(','), ascii.char(';') }); const fieldlist = combine(.{ field, many(combine(.{ ws, fieldsep, ws, field }), .{}), opt(fieldsep) }); const tableconstructor = combine(.{ ascii.char('{'), discard(opt(ws)), opt(fieldlist), discard(opt(ws)), ascii.char('}') }); const constexpr = oneOf(.{ map(Expr, functionDefExprConv, functiondef), map(Expr, numberConv, number), map(Expr, booleanConv, boolean), map(Expr, stringConv, literalString), map(Expr, functionCallExprConv, functioncall), map(Expr, tableConstructorConv, tableconstructor), map(Expr, parenthesisConv, combine(.{ discard(opt(ws)), ascii.char('('), discard(opt(ws)), ref(exp_ref), discard(opt(ws)), ascii.char(')'), discard(opt(ws)) })), lvar }); const exp = oneOf(.{ compOp, concatOp, binop2, binop1, constexpr }); const compOp = map(Expr, binopConv, combine(.{ many(combine(.{ concatOp, discard(opt(ws)), mecha.asStr(oneOf(.{ mecha.string("=="), mecha.string("~=") })) }), .{ .min = 1 }), discard(opt(ws)), ref(exp_ref) })); const concatOp = oneOf(.{ map(Expr, binopConv, combine(.{ many(combine(.{ binop2, discard(opt(ws)), mecha.asStr(mecha.string("..")), discard(opt(ws)) }), .{ .min = 1 }), ref(exp_ref) })), binop2 }); const binop2 = oneOf(.{ map(Expr, binopConv, combine(.{ many(combine(.{ binop1, discard(opt(ws)), mecha.asStr(oneOf(.{ mecha.string("*"), mecha.string("/"), mecha.string("//"), mecha.string("%") })), discard(opt(ws)) }), .{ .min = 1 }), ref(binop2_ref) })), binop1 }); const binop1 = oneOf(.{ map(Expr, binopConv, combine(.{ many(combine(.{ constexpr, discard(opt(ws)), mecha.asStr(oneOf(.{ mecha.string("+"), mecha.string("-") })), discard(opt(ws)) }), .{ .min = 1 }), ref(binop1_ref) })), constexpr }); fn binop2_ref() Parser(Expr) { return binop2; } fn binop1_ref() Parser(Expr) { return binop1; } fn exp_ref() Parser(Expr) { return exp; } fn parenthesisConv(arg: Expr) Expr { return arg; } fn booleanConv(arg: []const u8) Expr { return Expr { .Boolean = std.mem.eql(u8, arg, "true") }; } fn stringConv(arg: []const u8) Expr { return Expr { .LiteralString = arg }; } fn numberConv(arg: []const u8) Expr { return Expr { .Number = std.fmt.parseFloat(f64, arg) catch unreachable }; } fn nameConv(arg: []const u8) Expr { if (std.mem.eql(u8, arg, "nil")) { return Expr { .Nil = .{} }; } return Expr { .Var = .{ .Name = arg } }; } fn functionCallExprConv(arg: anytype) Expr { return Expr { .FunctionCall = .{ .callee = arg[0].Var, .args = arg[1] orelse &[0]Expr {} } }; } fn functionDefExprConv(arg: anytype) Expr { return Expr { .FunctionDefinition = .{ .stats = arg[1], .argNames = arg[0] orelse &[0][]const u8 {} } }; } fn tableConstructorConv(arg: anytype) Expr { var entries = std.ArrayList(TableConstructor.TableEntry).init(alloc); if (arg) |flist| { // first entry entries.append(.{ .key = flist[0][0], .value = flist[0][1] }) catch unreachable; // other entries for (flist[1]) |entry| { entries.append(.{ .key = entry[0], .value = entry[1] }) catch unreachable; } } return Expr { .TableConstructor = .{ .entries = entries.toOwnedSlice() } }; } fn binopConv(arg: anytype) Expr { const lhs = alloc.create(Expr) catch unreachable; // This handles operator precedence and left associativity //std.log.debug("arg = {d}, op = {s}", .{arg[0].len, arg[0][arg[0].len-1][1]}); if (arg[0].len == 1) { //std.log.debug("lhs: {any}", .{arg[0][0][0]}); lhs.* = arg[0][0][0]; } else { const newArgs: @TypeOf(arg) = .{ arg[0][0..arg.len-1], arg[0][1][0] }; lhs.* = binopConv(newArgs); } const rhs = alloc.create(Expr) catch unreachable; //std.log.debug("rhs: {any}", .{arg[1]}); rhs.* = arg[1]; return Expr { .BinaryOperation = .{ .lhs = lhs, .op = arg[0][arg[0].len-1][1], .rhs = rhs }}; } const explist = combine(.{ many(exp, .{ .min = 1, .separator = combine(.{ ascii.char(','), discard(opt(ws)) })}) }); fn explist_ref() Parser([]Expr) { return explist; } fn noOpConv(arg: void) Stat { _ = arg; return Stat { .NoOp = .{} }; } fn definitionConv(arg: anytype) Stat { var vars = alloc.alloc(Var, arg[0].len) catch unreachable; // TODO: handle Expr.Index and convert into Var.PrefixExpression for (arg[0]) |expr, i| vars[i] = expr.Var; return Stat { .Definition = .{ .vars = vars, .exprs = arg[1] } }; } fn localDefinitionConv(arg: anytype) Stat { return Stat { .LocalDefinition = .{ .names = arg[0], .exprs = arg[1] } }; } fn functionCallStatConv(arg: anytype) Stat { return Stat { .FunctionCall = .{ .callee = arg[0].Var, .args = arg[1] orelse &[0]Expr {} } }; } fn localFunctionDefConv(arg: anytype) Stat { var names = alloc.alloc([]const u8, 1) catch unreachable; var exprs = alloc.alloc(Expr, 1) catch unreachable; names[0] = arg[0]; exprs[0] = Expr { .FunctionDefinition = .{ .stats = arg[2], .argNames = arg[1] orelse &[0][]const u8 {} } }; return Stat { .LocalDefinition = .{ .names = names, .exprs = exprs } }; } fn functionDefConv(arg: anytype) Stat { var vars = alloc.alloc(Var, 1) catch unreachable; var exprs = alloc.alloc(Expr, 1) catch unreachable; vars[0] = arg[0].Var; exprs[0] = Expr { .FunctionDefinition = .{ .stats = arg[2], .argNames = arg[1] orelse &[0][]const u8 {} } }; return Stat { .Definition = .{ .vars = vars, .exprs = exprs } }; } fn ifStatConv(arg: anytype) Stat { return Stat { .If = .{ .expr = arg[0], .statements = arg[1] } }; } fn doBlockStatConv(arg: anytype) Stat { return Stat { .If = .{ .expr = .{ .Boolean = true }, .statements = arg } }; } fn retStatConv(arg: anytype) Stat { return Stat { .Return = .{ .expressions = arg orelse &[0]Expr {} } }; } const args = oneOf(.{ combine(.{ ascii.char('('), discard(opt(ws)), opt(ref(explist_ref)), discard(opt(ws)), ascii.char(')') }) }); const functioncall = oneOf(.{ combine(.{ discard(opt(ws)), lvar, discard(opt(ws)), args, discard(opt(ws)) }) }); const funcname = name; const shortlocalfunctiondef = combine(.{ discard(opt(ws)), mecha.string("local"), discard(ws), mecha.string("function"), discard(ws), name, discard(opt(ws)), ascii.char('('), opt(namelist), ascii.char(')'), discard(opt(ws)), ref(block_ref), discard(opt(ws)), mecha.string("end"), discard(opt(ws)) }); const shortfunctiondef = combine(.{ discard(opt(ws)), mecha.string("function"), discard(ws), lvar, discard(opt(ws)), ascii.char('('), opt(namelist), ascii.char(')'), discard(opt(ws)), ref(block_ref), discard(opt(ws)), mecha.string("end"), discard(opt(ws)) }); const stat = oneOf(.{ map(Stat, noOpConv, combine(.{ ascii.char(';'), discard(opt(ws)) })), map(Stat, definitionConv, combine(.{ varlist, discard(opt(ws)), ascii.char('='), discard(opt(ws)), explist, discard(opt(ws)) })), map(Stat, functionCallStatConv, functioncall), map(Stat, localDefinitionConv, combine(.{ discard(opt(ws)), mecha.string("local"), discard(opt(ws)), namelist, discard(opt(ws)), ascii.char('='), discard(opt(ws)), explist, discard(opt(ws)) })), map(Stat, functionDefConv, shortfunctiondef), map(Stat, localFunctionDefConv, shortlocalfunctiondef), map(Stat, ifStatConv, combine(.{ discard(opt(ws)), mecha.string("if"), discard(ws), exp, discard(ws), mecha.string("then"), discard(opt(ws)), ref(block_ref), discard(opt(ws)), mecha.string("end"), discard(opt(ws)) })), map(Stat, doBlockStatConv, combine(.{ discard(opt(ws)), mecha.string("do"), discard(ws), ref(block_ref), mecha.string("end"), discard(opt(ws)) })) }); const retstat = map(Stat, retStatConv, combine(.{ mecha.string("return"), discard(ws), opt(explist), discard(opt(ascii.char(';'))) }) ); fn blockConv(arg: anytype) []Stat { const slice: []const Stat = blk: { if (arg[1]) |ret| { break :blk &[1]Stat { ret }; } else { break :blk &[0]Stat {}; } }; return std.mem.concat(alloc, Stat, &[_][]const Stat { arg[0], slice }) catch unreachable; } const block = map([]Stat, blockConv, combine(.{ many(stat, .{ }), opt(retstat) })); fn block_ref() Parser([]Stat) { return block; } pub const chunk = combine(.{ block, mecha.eos }); pub fn parse(allocator: *Allocator, source: []const u8) !mecha.ParserResult(@TypeOf(chunk)) { alloc = allocator; return (try chunk(allocator, source)).value; }
src/parser.zig
const std = @import("std"); pub const Color = std.debug.TTY.Color; /// Basic output-wrapper with console-escape-codes for supported platforms. /// Convenience-oriented with regards to enabling different levels of output /// API: <stream>Print(), <stream>Colored(), with <stream> being std, debug, error or verbose. pub const Console = struct { const Self = @This(); pub const ColorConfig = enum { on, off, auto }; // Writers debug_writer: ?std.fs.File.Writer = null, std_writer: ?std.fs.File.Writer = null, error_writer: ?std.fs.File.Writer = null, verbose_writer: ?std.fs.File.Writer = null, ttyconf: std.debug.TTY.Config, /// Returns a Console which suppresses all output pub fn initNull() Self { return Self { .ttyconf = Console.colorConfig(.off), }; } /// Main constructor. Takes optional writers. null == suppress. pub fn init(args: struct { std_writer: ?std.fs.File.Writer, error_writer: ?std.fs.File.Writer, verbose_writer: ?std.fs.File.Writer, debug_writer: ?std.fs.File.Writer, colors: ColorConfig}) Self { return Self { .debug_writer = args.debug_writer, .std_writer = args.std_writer, .error_writer = args.error_writer, .verbose_writer = args.verbose_writer, .ttyconf = Console.colorConfig(args.colors), }; } /// Basic constructor providing same writer for all output-types pub fn initSimple(writer: ?std.fs.File.Writer) Self { return Self { .debug_writer = writer, .std_writer = writer, .error_writer = writer, .verbose_writer = writer, .ttyconf = std.debug.detectTTYConfig(), }; } fn colorConfig(value: ColorConfig) std.debug.TTY.Config { return switch(value) { .on => .escape_codes, .off => .no_color, .auto => std.debug.detectTTYConfig() }; } /// Core output-function, utilized by all others. fn out(self: *const Self, maybe_writer: ?std.fs.File.Writer, maybe_color: ?Color, comptime fmt:[]const u8, args: anytype) void { if(maybe_writer == null) return; const writer = maybe_writer.?; if(maybe_color) |color| { self.ttyconf.setColor(writer, color); } writer.print(fmt, args) catch {}; if(maybe_color != null) { self.ttyconf.setColor(writer, .Reset); } } ////////////////////////////////////////////////////// // Print-functions ////////////////////////////////////////////////////// pub fn stdPrint(self: *const Self, comptime fmt:[]const u8, args: anytype) void { self.out(self.std_writer, null, fmt, args); } pub fn stdColored(self: *const Self, color: Color, comptime fmt:[]const u8, args: anytype) void { self.out(self.std_writer, color, fmt, args); } pub fn errorPrint(self: *const Self, comptime fmt:[]const u8, args: anytype) void { self.errorColored(.Red, "ERROR: ", .{}); self.out(self.error_writer, null, fmt, args); } pub fn errorPrintNoPrefix(self: *const Self, comptime fmt:[]const u8, args: anytype) void { self.out(self.error_writer, null, fmt, args); } pub fn errorColored(self: *const Self, color: Color, comptime fmt:[]const u8, args: anytype) void { self.out(self.error_writer, color, fmt, args); } // TBD: What's the use case for "debug"? pub fn debugPrint(self: *const Self, comptime fmt:[]const u8, args: anytype) void { self.out(self.debug_writer, null, fmt, args); } pub fn debugColored(self: *const Self, color: Color, comptime fmt:[]const u8, args: anytype) void { self.out(self.debug_writer, color, fmt, args); } pub fn verbosePrint(self: *const Self, comptime fmt:[]const u8, args: anytype) void { self.out(self.verbose_writer, null, fmt, args); } pub fn verboseColored(self: *const Self, color: Color, comptime fmt:[]const u8, args: anytype) void { self.out(self.verbose_writer, color, fmt, args); } }; test "Console" { const stdout = std.io.getStdOut().writer(); const c = Console.initSimple(stdout); c.stdPrint("\n", .{}); c.errorPrint("Something very wrong\n", .{}); c.stdPrint("Regular output\n", .{}); c.debugPrint("Debug output\n", .{}); c.verbosePrint("Verbose output\n", .{}); }
src/console.zig
const macro = @import("pspmacros.zig"); comptime { asm (macro.import_module_start("IoFileMgrForUser", "0x40010000", "36")); asm (macro.import_function("IoFileMgrForUser", "0x3251EA56", "sceIoPollAsync")); asm (macro.import_function("IoFileMgrForUser", "0xE23EEC33", "sceIoWaitAsync")); asm (macro.import_function("IoFileMgrForUser", "0x35DBD746", "sceIoWaitAsyncCB")); asm (macro.import_function("IoFileMgrForUser", "0xCB05F8D6", "sceIoGetAsyncStat")); asm (macro.import_function("IoFileMgrForUser", "0xB293727F", "sceIoChangeAsyncPriority")); asm (macro.import_function("IoFileMgrForUser", "0xA12A0514", "sceIoSetAsyncCallback")); asm (macro.import_function("IoFileMgrForUser", "0x810C4BC3", "sceIoClose")); asm (macro.import_function("IoFileMgrForUser", "0xFF5940B6", "sceIoCloseAsync")); asm (macro.import_function("IoFileMgrForUser", "0x109F50BC", "sceIoOpen")); asm (macro.import_function("IoFileMgrForUser", "0x89AA9906", "sceIoOpenAsync")); asm (macro.import_function("IoFileMgrForUser", "0x6A638D83", "sceIoRead")); asm (macro.import_function("IoFileMgrForUser", "0xA0B5A7C2", "sceIoReadAsync")); asm (macro.import_function("IoFileMgrForUser", "0x42EC03AC", "sceIoWrite")); asm (macro.import_function("IoFileMgrForUser", "0x0FACAB19", "sceIoWriteAsync")); asm (macro.import_function("IoFileMgrForUser", "0x27EB27B8", "sceIoLseek")); asm (macro.import_function("IoFileMgrForUser", "0x71B19E77", "sceIoLseekAsync")); asm (macro.import_function("IoFileMgrForUser", "0x68963324", "sceIoLseek32")); asm (macro.import_function("IoFileMgrForUser", "0x1B385D8F", "sceIoLseek32Async")); asm (macro.import_function("IoFileMgrForUser", "0x63632449", "sceIoIoctl_stub")); asm (macro.import_function("IoFileMgrForUser", "0xE95A012B", "sceIoIoctlAsync_stub")); asm (macro.import_function("IoFileMgrForUser", "0xB29DDF9C", "sceIoDopen")); asm (macro.import_function("IoFileMgrForUser", "0xE3EB004C", "sceIoDread")); asm (macro.import_function("IoFileMgrForUser", "0xEB092469", "sceIoDclose")); asm (macro.import_function("IoFileMgrForUser", "0xF27A9C51", "sceIoRemove")); asm (macro.import_function("IoFileMgrForUser", "0x06A70004", "sceIoMkdir")); asm (macro.import_function("IoFileMgrForUser", "0x1117C65F", "sceIoRmdir")); asm (macro.import_function("IoFileMgrForUser", "0x55F4717D", "sceIoChdir")); asm (macro.import_function("IoFileMgrForUser", "0xAB96437F", "sceIoSync")); asm (macro.import_function("IoFileMgrForUser", "0xACE946E8", "sceIoGetstat")); asm (macro.import_function("IoFileMgrForUser", "0xB8A740F4", "sceIoChstat")); asm (macro.import_function("IoFileMgrForUser", "0x779103A0", "sceIoRename")); asm (macro.import_function("IoFileMgrForUser", "0x54F5FB11", "sceIoDevctl_stub")); asm (macro.import_function("IoFileMgrForUser", "0x08BD7374", "sceIoGetDevType")); asm (macro.import_function("IoFileMgrForUser", "0xB2A628C1", "sceIoAssign_stub")); asm (macro.import_function("IoFileMgrForUser", "0x6D08A871", "sceIoUnassign")); asm (macro.import_function("IoFileMgrForUser", "0xE8BC6571", "sceIoCancel")); asm (macro.generic_abi_wrapper("sceIoDevctl", 6)); asm (macro.generic_abi_wrapper("sceIoAssign", 6)); asm (macro.generic_abi_wrapper("sceIoIoctl", 6)); asm (macro.generic_abi_wrapper("sceIoIoctlAsync", 6)); }
src/psp/nids/pspiofilemgr.zig
const gpio = @import("gpio.zig"); const mmio = @import("mmio.zig"); const mbox = @import("mbox.zig"); const Registers = struct { data_reg: u32, rsrecr: u32, reserved0: [14]u8, flag_reg: u32, reserved1: [8]u8, integer_bound_rate_divisor: u32, fractal_bound_rate_divisor: u32, line_control_reg: u32, control_reg: u32, interupt_fifo_level_reg: u32, interupt_mask_clear_reg: u32, raw_interupt_status_reg: u32, mask_interupt_status_reg: u32, interupt_clear_reg: u32, dma_control_reg: u32, test_control_reg: u32, integrateion_test_intput: u32, integration_test_output: u32, test_data_reg: u32, }; pub const Uart = struct { registers: *volatile Registers = @intToPtr(*volatile Registers, mmio.UART_REGISTERS), const Self = @This(); pub fn new() Self { var self = Self{}; self.init(); return self; } pub fn init(self: Self) void { self.registers.control_reg = 0; // set up clock for consistent divisor values mbox.data[0] = 9 * 4; mbox.data[1] = mbox.MBOX_REQUEST; mbox.data[2] = mbox.Tag.set_clk_rate.to_int(); // set clock rate mbox.data[3] = 12; mbox.data[4] = 8; mbox.data[5] = 2; // UART clock mbox.data[6] = 4000000; // 4Mhz mbox.data[7] = 0; // clear turbo mbox.data[8] = mbox.Tag.last.to_int(); var success = mbox.call(mbox.Channel.prop); var pins = [_]u8{ 14, 15 }; gpio.set_pins_mode(&pins, gpio.Mode.alt0); self.registers.interupt_clear_reg = 0x7FF; self.registers.integer_bound_rate_divisor = 2; self.registers.fractal_bound_rate_divisor = 0xB; self.registers.interupt_mask_clear_reg = 0b11 << 5; self.registers.control_reg = 0x301; } pub fn send(self: Self, c: u8) void { while ((self.registers.flag_reg & 0x20) != 0) { asm volatile ("nop"); } self.registers.data_reg = c; } pub fn puts(self: Self, string: []const u8) usize { for (string) |value| { if (value == '\n') self.send('\r'); self.send(value); } return string.len; } pub fn gets(self: Self, buffer: []u8) usize { for (buffer) |value, index| { buffer[index] = self.getc(); } return buffer.len; } pub fn getc(self: Self) u8 { while ((self.registers.flag_reg & 0x10) != 0) { asm volatile ("nop"); } var c: u8 = @intCast(u8, self.registers.data_reg); if (c == '\r') { return '\n'; } return c; } }; pub fn qsend(c: u8) void { mmio.write(0x3F201000, c); } pub fn qputs(string: []const u8) void { for (string) |value| { if (value == '\n') qsend('\r'); qsend(value); } } pub fn uart_hex(d: u32) void { var n: u32 = 0; var c: i32 = 28; while (c >= 0) : (c -= 4) { // get highest tetrad n = (d >> @intCast(u5, c)) & 0xF; // 0-9 => '0'-'9', 10-15 => 'A'-'F' var v: u32 = if (n > 9) 0x37 else 0x30; n += v; qsend(@intCast(u8, n)); } } test "uart registers" { const expectEqual = @import("std").testing.expectEqual; var addr = @intToPtr(*Registers, 0x10000000); expectEqual(@as(usize, 0x10000000), @ptrToInt(&addr.data_reg)); expectEqual(@as(usize, 0x10000018), @ptrToInt(&addr.flag_reg)); expectEqual(@as(usize, 0x10000024), @ptrToInt(&addr.integer_bound_rate_divisor)); expectEqual(@as(usize, 0x10000028), @ptrToInt(&addr.fractal_bound_rate_divisor)); expectEqual(@as(usize, 0x1000002C), @ptrToInt(&addr.line_control_reg)); expectEqual(@as(usize, 0x10000030), @ptrToInt(&addr.control_reg)); expectEqual(@as(usize, 0x10000038), @ptrToInt(&addr.interupt_mask_clear_reg)); expectEqual(@as(usize, 0x10000044), @ptrToInt(&addr.interupt_clear_reg)); }
src/arm/io/uart.zig
const std = @import("std"); const build_options = @import("build_options"); pub const c = @cImport({ @cInclude("SDL2/SDL.h"); @cInclude("SDL2/SDL_audio.h"); @cInclude("SDL2/SDL_opengl.h"); if (build_options.imgui) { @cDefine("CIMGUI_DEFINE_ENUMS_AND_STRUCTS", ""); @cInclude("cimgui.h"); @cInclude("cimgui_impl.h"); } }); pub const Sdl = struct { const empty_options = .{ .sdl = .{} }; pub const Window = c.SDL_Window; pub const GLContext = c.SDL_GLContext; pub const init = wrap(c.SDL_Init, empty_options); pub const quit = wrap(c.SDL_Quit, empty_options); pub const glCreateContext = wrap(c.SDL_GL_CreateContext, empty_options); pub const glDeleteContext = wrap(c.SDL_GL_DeleteContext, empty_options); pub const glSetAttribute = wrap(c.SDL_GL_SetAttribute, empty_options); pub const glMakeCurrent = wrap(c.SDL_GL_MakeCurrent, empty_options); pub const glSetSwapInterval = wrap(c.SDL_GL_SetSwapInterval, empty_options); pub const glSwapWindow = wrap(c.SDL_GL_SwapWindow, empty_options); pub const createWindow = wrap(c.SDL_CreateWindow, empty_options); pub const destroyWindow = wrap(c.SDL_DestroyWindow, empty_options); pub const getWindowSize = wrap(c.SDL_GetWindowSize, empty_options); pub const setWindowSize = wrap(c.SDL_SetWindowSize, empty_options); pub const setWindowPosition = wrap(c.SDL_SetWindowPosition, empty_options); pub const pollEvent = wrap(c.SDL_PollEvent, .{ .sdl = .{ .int = .int_to_zig } }); pub const getKeyboardState = wrap(c.SDL_GetKeyboardState, .{ .sdl = .{ .many_ptr_to_single = false, } }); pub const openAudioDevice = wrap(c.SDL_OpenAudioDevice, .{ .sdl = .{ .int = null } }); pub const closeAudioDevice = wrap(c.SDL_CloseAudioDevice, empty_options); pub const pauseAudioDevice = wrap(c.SDL_PauseAudioDevice, empty_options); }; pub const Gl = struct { const empty_options = .{ .opengl = .{} }; pub const viewport = wrap(c.glViewport, empty_options); pub const enable = wrap(c.glEnable, empty_options); pub const clearColor = wrap(c.glClearColor, .{ .opengl = .{ .check_error = false } }); pub const clear = wrap(c.glClear, empty_options); pub const pushClientAttrib = wrap(c.glPushClientAttrib, empty_options); pub const popClientAttrib = wrap(c.glPopClientAttrib, empty_options); pub const enableClientState = wrap(c.glEnableClientState, empty_options); pub const disableClientState = wrap(c.glDisableClientState, empty_options); pub const pushMatrix = wrap(c.glPushMatrix, empty_options); pub const popMatrix = wrap(c.glPopMatrix, empty_options); pub const loadIdentity = wrap(c.glLoadIdentity, empty_options); pub const ortho = wrap(c.glOrtho, empty_options); pub const matrixMode = wrap(c.glMatrixMode, empty_options); pub const genTextures = wrap(c.glGenTextures, empty_options); pub const deleteTextures = wrap(c.glDeleteTextures, empty_options); pub const bindTexture = wrap(c.glBindTexture, empty_options); pub const texImage2D = wrap(c.glTexImage2D, empty_options); pub const texParameteri = wrap(c.glTexParameteri, empty_options); pub const vertexPointer = wrap(c.glVertexPointer, empty_options); pub const texCoordPointer = wrap(c.glTexCoordPointer, empty_options); pub const drawArrays = wrap(c.glDrawArrays, empty_options); }; pub const Imgui = struct { const empty_options = .{ .imgui = .{} }; const bool_err = .{ .imgui = .{ .bool_to_error = true } }; pub const createContext = wrap(c.igCreateContext, empty_options); pub const sdl2InitForOpengl = wrap(c.ImGui_ImplSDL2_InitForOpenGL, bool_err); pub const opengl3Init = wrap(c.ImGui_ImplOpenGL3_Init, bool_err); pub const sdl2Shutdown = wrap(c.ImGui_ImplSDL2_Shutdown, empty_options); pub const opengl3Shutdown = wrap(c.ImGui_ImplOpenGL3_Shutdown, empty_options); pub const styleColorsDark = wrap(c.igStyleColorsDark, empty_options); pub const sdl2ProcessEvent = wrap(c.ImGui_ImplSDL2_ProcessEvent, empty_options); pub const opengl3NewFrame = wrap(c.ImGui_ImplOpenGL3_NewFrame, empty_options); pub const sdl2NewFrame = wrap(c.ImGui_ImplSDL2_NewFrame, empty_options); pub const newFrame = wrap(c.igNewFrame, empty_options); pub const render = wrap(c.igRender, empty_options); pub const opengl3RenderDrawData = wrap(c.ImGui_ImplOpenGL3_RenderDrawData, empty_options); pub const getDrawData = wrap(c.igGetDrawData, empty_options); pub const begin = wrap(c.igBegin, empty_options); pub const end = wrap(c.igEnd, empty_options); pub const findWindowByName = wrap(c.igFindWindowByName, .{ .imgui = .{ .optional_to_error = false } }); pub const setNextWindowSize = wrap(c.igSetNextWindowSize, empty_options); pub const setNextWindowContentSize = wrap(c.igSetNextWindowContentSize, empty_options); pub const beginPopup = wrap(c.igBeginPopup, empty_options); pub const beginPopupModal = wrap(c.igBeginPopupModal, empty_options); pub const endPopup = wrap(c.igEndPopup, empty_options); pub const beginMenu = wrap(c.igBeginMenu, empty_options); pub const endMenu = wrap(c.igEndMenu, empty_options); pub const beginMainMenuBar = wrap(c.igBeginMainMenuBar, empty_options); pub const endMainMenuBar = wrap(c.igEndMainMenuBar, empty_options); pub const menuItem = wrap(c.igMenuItem_Bool, empty_options); pub const menuItemPtr = wrap(c.igMenuItem_BoolPtr, empty_options); pub const button = wrap(c.igButton, empty_options); pub const image = wrap(c.igImage, empty_options); pub const windowFlagsNone = c.ImGuiWindowFlags_None; pub const windowFlagsNoTitleBar = c.ImGuiWindowFlags_NoTitleBar; pub const windowFlagsNoResize = c.ImGuiWindowFlags_NoResize; pub const windowFlagsNoMove = c.ImGuiWindowFlags_NoMove; pub const windowFlagsNoScrollbar = c.ImGuiWindowFlags_NoScrollbar; pub const windowFlagsNoScrollWithMouse = c.ImGuiWindowFlags_NoScrollWithMouse; pub const windowFlagsNoCollapse = c.ImGuiWindowFlags_NoCollapse; pub const windowFlagsAlwaysAutoResize = c.ImGuiWindowFlags_AlwaysAutoResize; pub const windowFlagsNoBackground = c.ImGuiWindowFlags_NoBackground; pub const windowFlagsNoSavedSettings = c.ImGuiWindowFlags_NoSavedSettings; pub const windowFlagsNoMouseInputs = c.ImGuiWindowFlags_NoMouseInputs; pub const windowFlagsMenuBar = c.ImGuiWindowFlags_MenuBar; pub const windowFlagsHorizontalScrollbar = c.ImGuiWindowFlags_HorizontalScrollbar; pub const windowFlagsNoFocusOnAppearing = c.ImGuiWindowFlags_NoFocusOnAppearing; pub const windowFlagsNoBringToFrontOnFocus = c.ImGuiWindowFlags_NoBringToFrontOnFocus; pub const windowFlagsAlwaysVerticalScrollbar = c.ImGuiWindowFlags_AlwaysVerticalScrollbar; pub const windowFlagsAlwaysHorizontalScrollbar = c.ImGuiWindowFlags_AlwaysHorizontalScrollbar; pub const windowFlagsAlwaysUseWindowPadding = c.ImGuiWindowFlags_AlwaysUseWindowPadding; pub const windowFlagsNoNavInputs = c.ImGuiWindowFlags_NoNavInputs; pub const windowFlagsNoNavFocus = c.ImGuiWindowFlags_NoNavFocus; pub const windowFlagsUnsavedDocument = c.ImGuiWindowFlags_UnsavedDocument; pub const windowFlagsNoNav = c.ImGuiWindowFlags_NoNavInputs | c.ImGuiWindowFlags_NoNavFocus; pub const windowFlagsNoDecoration = c.ImGuiWindowFlags_NoTitleBar | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoScrollbar | c.ImGuiWindowFlags_NoCollapse; pub const windowFlagsNoInputs = c.ImGuiWindowFlags_NoMouseInputs | c.ImGuiWindowFlags_NoNavInputs | c.ImGuiWindowFlags_NoNavFocus; }; pub const CError = error{ SdlError, GlError, ImguiError, }; fn errorFromOptions(comptime options: WrapOptions) CError { return switch (options) { .sdl => CError.SdlError, .opengl => CError.GlError, .imgui => CError.ImguiError, }; } const WrapOptions = union(enum) { sdl: struct { int: ?IntConversion = .int_to_error, optional_to_error: bool = true, many_ptr_to_single: bool = true, }, // whether to check glGetError opengl: struct { check_error: bool = true, }, imgui: struct { bool_to_error: bool = false, optional_to_error: bool = true, }, const IntConversion = enum { int_to_error, int_to_zig, }; fn intConversion(comptime self: WrapOptions) ?IntConversion { return switch (self) { .sdl => |x| x.int, .opengl, .imgui => null, }; } fn boolToError(comptime self: WrapOptions) bool { return switch (self) { .sdl => false, .opengl => false, .imgui => |x| x.bool_to_error, }; } fn optionalToError(comptime self: WrapOptions) bool { return switch (self) { .sdl => |x| x.optional_to_error, .opengl => false, .imgui => |x| x.optional_to_error, }; } fn manyPtrToSingle(comptime self: WrapOptions) bool { return switch (self) { .sdl => |x| x.many_ptr_to_single, .opengl => false, .imgui => true, }; } }; fn WrappedCallReturn(comptime T: type, comptime options: WrapOptions) type { const type_info = @typeInfo(T); switch (type_info) { .Int => if (comptime options.intConversion()) |int| { switch (int) { .int_to_error => return CError!void, .int_to_zig => if (T == c_int) { const c_int_info = @typeInfo(c_int).Int; return @Type(.{ .Int = .{ .signedness = c_int_info.signedness, .bits = c_int_info.bits }, }); } else { return T; }, } } else { return T; }, .Bool => if (comptime options.boolToError()) { return CError!void; } else { return bool; }, .Optional => |optional| if (comptime options.optionalToError()) { return CError!optional.child; } else { return T; }, .Pointer => |pointer| switch (pointer.size) { .C => if (comptime options.manyPtrToSingle()) { return CError!*pointer.child; } else { return T; }, else => return T, }, else => return T, } } fn WrappedCheckedReturn(comptime T: type, comptime options: WrapOptions) type { switch (options) { .sdl, .imgui => return T, .opengl => |x| { std.debug.assert(T == void); if (x.check_error) { return CError!void; } else { return void; } }, } } fn WrappedFinalReturn(comptime T: type, comptime options: WrapOptions) type { return WrappedCheckedReturn(WrappedCallReturn(T, options), options); } fn ReturnType(comptime T: type) type { switch (@typeInfo(T)) { .Fn => |func_info| { if (func_info.return_type) |t| { return t; } else { @compileError("Function has no return type"); } }, else => @compileError("Can't wrap a non-function"), } } fn WrappedSignature(comptime T: type, comptime options: WrapOptions) type { const RetType = WrappedFinalReturn(ReturnType(T), options); switch (@typeInfo(T)) { .Fn => |func_info| { if (func_info.args.len == 0) { return (fn () RetType); } else { return (fn (anytype) RetType); } }, else => @compileError("Can't wrap a non-function"), } } fn wrapReturn(ret_val: anytype, comptime options: WrapOptions) WrappedCallReturn(@TypeOf(ret_val), options) { const T = @TypeOf(ret_val); const RetType = WrappedCallReturn(T, options); const type_info = @typeInfo(@TypeOf(ret_val)); switch (type_info) { .Int => if (comptime options.intConversion()) |int| { switch (int) { .int_to_error => if (ret_val == 0) { return; } else { return errorFromOptions(options); }, .int_to_zig => { return @as(RetType, ret_val); }, } } else { return ret_val; }, .Bool => if (comptime options.boolToError()) { if (ret_val) { return; } else { return errorFromOptions(options); } } else { return ret_val; }, .Optional => if (comptime options.optionalToError()) { if (ret_val) |val| { return val; } else { return errorFromOptions(options); } } else { return ret_val; }, .Pointer => |pointer| switch (pointer.size) { .C => if (comptime options.manyPtrToSingle()) { if (ret_val != 0) { return @ptrCast(*pointer.child, ret_val); } else { return errorFromOptions(options); } } else { return ret_val; }, else => return ret_val, }, else => return ret_val, } } fn wrapPrintError( comptime options: WrapOptions, ret_val: anytype, ) WrappedCheckedReturn(@TypeOf(ret_val), options) { const is_error = switch (@typeInfo(@TypeOf(ret_val))) { .ErrorUnion => std.meta.isError(ret_val), else => false, }; switch (options) { .sdl => if (is_error) { std.log.err("{s}", .{c.SDL_GetError()}); }, .opengl => |gl_options| { if (gl_options.check_error) { var err = c.glGetError(); const has_error = err != c.GL_NO_ERROR; while (err != c.GL_NO_ERROR) : (err = c.glGetError()) { std.log.err("{}", .{err}); } if (has_error) { return CError.GlError; } } }, .imgui => if (is_error) { std.log.err("Imgui error", .{}); }, } return ret_val; } fn wrap( comptime func: anytype, comptime options: WrapOptions, ) WrappedSignature(@TypeOf(func), options) { const T = @TypeOf(func); const RetType = WrappedFinalReturn(ReturnType(T), options); switch (@typeInfo(@TypeOf(func))) { .Fn => |func_info| { if (func_info.args.len == 0) { return (struct { fn f() RetType { return wrapPrintError(options, wrapReturn(func(), options)); } }).f; } else { return (struct { fn f(args: anytype) RetType { return wrapPrintError(options, wrapReturn(@call(.{}, func, args), options)); } }).f; } }, else => @compileError("Can't wrap a non-function"), } }
src/sdl/bindings.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const utils = @import("utils.zig"); const InputState = enum { rules, my_ticket, other_tickets }; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const Rules = struct { allo: *std.mem.Allocator, rules: [][2][2]usize, pub fn init(allo: *std.mem.Allocator) Rules { return Rules{ .allo = allo, .rules = allo.alloc([2][2]usize, 0) catch unreachable, }; } pub fn count(self: *Rules) usize { return self.rules.len; } pub fn ingest(self: *Rules, line: []const u8) void { // mostly ugly text parsing code var colon_iter = std.mem.tokenize(line, ":"); _ = colon_iter.next(); const rule_part = colon_iter.next() orelse unreachable; var rules_iter = std.mem.tokenize(rule_part, " or "); const a = rules_iter.next() orelse unreachable; const b = rules_iter.next() orelse unreachable; var a_iter = std.mem.tokenize(a, "-"); var b_iter = std.mem.tokenize(b, "-"); var a_from = std.fmt.parseInt(usize, a_iter.next() orelse unreachable, 10) catch unreachable; var a_to = std.fmt.parseInt(usize, a_iter.next() orelse unreachable, 10) catch unreachable; var b_from = std.fmt.parseInt(usize, b_iter.next() orelse unreachable, 10) catch unreachable; var b_to = std.fmt.parseInt(usize, b_iter.next() orelse unreachable, 10) catch unreachable; self.rules = self.allo.realloc(self.rules, self.rules.len + 1) catch unreachable; self.rules[self.rules.len - 1] = .{ .{ a_from, a_to }, .{ b_from, b_to }, }; } pub fn isValidRuleValue(self: *Rules, val: usize, rule_idx: usize) bool { const rule = self.rules[rule_idx]; const a = rule[0]; const b = rule[1]; const in_a = a[0] <= val and val <= a[1]; const in_b = b[0] <= val and val <= b[1]; if (in_a or in_b) { return true; } return false; } pub fn isValidValue(self: *Rules, val: usize) bool { for (self.rules) |_, i| { const valid = self.isValidRuleValue(val, i); if (valid) { return true; } } return false; } pub fn sumInvalid(self: *Rules, nums: []usize) ?usize { var invalid: ?usize = null; for (nums) |num| { if (!self.isValidValue(num)) { if (invalid) |*x| { x.* += @intCast(usize, 0); } else { invalid = num; } } } return invalid; } pub fn deinit(self: *Rules) void { self.allo.free(self.rules); } }; fn lineToNums(allo: *std.mem.Allocator, line: []const u8) []usize { var tokens = std.mem.tokenize(line, ","); var output = allo.alloc(usize, 0) catch unreachable; while (tokens.next()) |token| { output = allo.realloc(output, output.len + 1) catch unreachable; output[output.len - 1] = std.fmt.parseInt(usize, token, 10) catch unreachable; } return output; } pub fn main() !void { const begin = @divTrunc(std.time.nanoTimestamp(), 1000); // setup // defer _ = gpa.deinit(); var allo = &gpa.allocator; var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1"); defer allo.free(lines.buffer); var rules = Rules.init(allo); defer rules.deinit(); var input_state: InputState = .rules; var invalid_total: usize = 0; var my_ticket: []usize = allo.alloc(usize, 0) catch unreachable; defer allo.free(my_ticket); var valid_tickets: [][]usize = allo.alloc([]usize, 0) catch unreachable; defer allo.free(valid_tickets); // elements need separate freeing // p1 while (lines.next()) |line| { if (std.mem.startsWith(u8, line, "your ticket")) { input_state = .my_ticket; continue; } if (std.mem.startsWith(u8, line, "nearby tickets")) { input_state = .other_tickets; continue; } switch (input_state) { .rules => { rules.ingest(line); }, .my_ticket => { // NOTE: needs_free my_ticket = lineToNums(allo, line); }, .other_tickets => { // NOTE: needs_free const line_nums = lineToNums(allo, line); const invalid_val = rules.sumInvalid(line_nums); if (invalid_val) |new| { // free invalid ticket allo.free(line_nums); invalid_total += new; } else { // don't free valid ticket valid_tickets = allo.realloc(valid_tickets, valid_tickets.len + 1) catch unreachable; valid_tickets[valid_tickets.len - 1] = line_nums; } }, } } print("p1: {}\n", .{invalid_total}); // p2 const rules_cnt = rules.count(); // track possible field matches var rule_fields = allo.alloc(std.AutoHashMap(usize, void), rules_cnt) catch unreachable; defer allo.free(rule_fields); for (rule_fields) |*rf| { rf.* = std.AutoHashMap(usize, void).init(allo); var i: usize = 0; while (i < rules_cnt) : (i += 1) { rf.*.put(i, undefined) catch unreachable; } } // remove invalid fields from rules for (valid_tickets) |ticket| { defer allo.free(ticket); for (ticket) |field_val, field_idx| { var i: usize = 0; while (i < rules_cnt) : (i += 1) { const valid_for_rule = rules.isValidRuleValue(field_val, i); if (!valid_for_rule) { // remove this field from this rule _ = rule_fields[i].remove(field_idx); } } } } // reduce constraints while (true) { var removed = false; for (rule_fields) |rule_caps, i| { if (rule_caps.count() == 1) { var iter = rule_caps.iterator(); while (iter.next()) |entry| { for (rule_fields) |*rule_caps_2| { if (rule_caps_2.count() > 1) { _ = rule_caps_2.remove(entry.key); removed = true; } } } } } if (!removed) { break; } } // see which fields are left var p2: usize = 1; for (rule_fields) |rf, i| { // NOTE: our task requires first 5 rules if (i > 5) { break; } var iter = rf.iterator(); while (iter.next()) |vals| { const ticket_field = vals.key; p2 *= my_ticket[ticket_field]; } } print("p2: {}\n", .{p2}); // free for (rule_fields) |*rf| { rf.deinit(); } // end const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin; print("all done in {} microseconds\n", .{delta}); }
day_16/src/main.zig
pub const ComponentTypeEnforcementClientSoH = @as(u32, 1); pub const ComponentTypeEnforcementClientRp = @as(u32, 2); //-------------------------------------------------------------------------------- // Section: Types (22) //-------------------------------------------------------------------------------- pub const IsolationState = enum(i32) { NotRestricted = 1, InProbation = 2, RestrictedAccess = 3, }; pub const isolationStateNotRestricted = IsolationState.NotRestricted; pub const isolationStateInProbation = IsolationState.InProbation; pub const isolationStateRestrictedAccess = IsolationState.RestrictedAccess; pub const ExtendedIsolationState = enum(i32) { NoData = 0, Transition = 1, Infected = 2, Unknown = 3, }; pub const extendedIsolationStateNoData = ExtendedIsolationState.NoData; pub const extendedIsolationStateTransition = ExtendedIsolationState.Transition; pub const extendedIsolationStateInfected = ExtendedIsolationState.Infected; pub const extendedIsolationStateUnknown = ExtendedIsolationState.Unknown; pub const NapTracingLevel = enum(i32) { Undefined = 0, Basic = 1, Advanced = 2, Debug = 3, }; pub const tracingLevelUndefined = NapTracingLevel.Undefined; pub const tracingLevelBasic = NapTracingLevel.Basic; pub const tracingLevelAdvanced = NapTracingLevel.Advanced; pub const tracingLevelDebug = NapTracingLevel.Debug; pub const CountedString = extern struct { length: u16, string: ?PWSTR, }; pub const IsolationInfo = extern struct { isolationState: IsolationState, probEndTime: FILETIME, failureUrl: CountedString, }; pub const IsolationInfoEx = extern struct { isolationState: IsolationState, extendedIsolationState: ExtendedIsolationState, probEndTime: FILETIME, failureUrl: CountedString, }; pub const FailureCategory = enum(i32) { None = 0, Other = 1, ClientComponent = 2, ClientCommunication = 3, ServerComponent = 4, ServerCommunication = 5, }; pub const failureCategoryNone = FailureCategory.None; pub const failureCategoryOther = FailureCategory.Other; pub const failureCategoryClientComponent = FailureCategory.ClientComponent; pub const failureCategoryClientCommunication = FailureCategory.ClientCommunication; pub const failureCategoryServerComponent = FailureCategory.ServerComponent; pub const failureCategoryServerCommunication = FailureCategory.ServerCommunication; pub const FailureCategoryMapping = extern struct { mappingCompliance: [5]BOOL, }; pub const CorrelationId = extern struct { connId: Guid, timeStamp: FILETIME, }; pub const ResultCodes = extern struct { count: u16, results: ?*HRESULT, }; pub const Ipv4Address = extern struct { addr: [4]u8, }; pub const Ipv6Address = extern struct { addr: [16]u8, }; pub const FixupState = enum(i32) { Success = 0, InProgress = 1, CouldNotUpdate = 2, }; pub const fixupStateSuccess = FixupState.Success; pub const fixupStateInProgress = FixupState.InProgress; pub const fixupStateCouldNotUpdate = FixupState.CouldNotUpdate; pub const FixupInfo = extern struct { state: FixupState, percentage: u8, resultCodes: ResultCodes, fixupMsgId: u32, }; pub const NapNotifyType = enum(i32) { Unknown = 0, ServiceState = 1, QuarState = 2, }; pub const napNotifyTypeUnknown = NapNotifyType.Unknown; pub const napNotifyTypeServiceState = NapNotifyType.ServiceState; pub const napNotifyTypeQuarState = NapNotifyType.QuarState; pub const SystemHealthAgentState = extern struct { id: u32, shaResultCodes: ResultCodes, failureCategory: FailureCategory, fixupInfo: FixupInfo, }; pub const SoHAttribute = extern struct { type: u16, size: u16, value: ?*u8, }; pub const SoH = extern struct { count: u16, attributes: ?*SoHAttribute, }; pub const NetworkSoH = extern struct { size: u16, data: ?*u8, }; pub const PrivateData = extern struct { size: u16, data: ?*u8, }; pub const NapComponentRegistrationInfo = extern struct { id: u32, friendlyName: CountedString, description: CountedString, version: CountedString, vendorName: CountedString, infoClsid: Guid, configClsid: Guid, registrationDate: FILETIME, componentType: u32, }; pub const RemoteConfigurationType = enum(i32) { Machine = 1, ConfigBlob = 2, }; pub const remoteConfigTypeMachine = RemoteConfigurationType.Machine; pub const remoteConfigTypeConfigBlob = RemoteConfigurationType.ConfigBlob; //-------------------------------------------------------------------------------- // 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 (5) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const FILETIME = @import("../foundation.zig").FILETIME; const HRESULT = @import("../foundation.zig").HRESULT; 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/security/network_access_protection.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Map = struct { pub const Mode = enum { TEST, RUN }; // what a cheat const State = enum { ALGO, DATA }; const Pos = struct { x: isize, y: isize, pub fn init(x: isize, y: isize) Pos { var self = Pos{ .x = x, .y = y }; return self; } }; const Grid = struct { min: Pos, max: Pos, data: std.AutoHashMap(Pos, u8), default: u8, pub fn init() Grid { var self = Grid{ .min = Pos.init(std.math.maxInt(isize), std.math.maxInt(isize)), .max = Pos.init(std.math.minInt(isize), std.math.minInt(isize)), .data = std.AutoHashMap(Pos, u8).init(allocator), .default = 0, }; return self; } pub fn deinit(self: *Grid) void { self.data.deinit(); } pub fn reset(self: *Grid) void { self.data.clearRetainingCapacity(); self.min = Pos.init(std.math.maxInt(isize), std.math.maxInt(isize)); self.max = Pos.init(std.math.minInt(isize), std.math.minInt(isize)); } pub fn get_pos(self: Grid, x: isize, y: isize) u8 { const pos = Pos.init(x, y); const entry = self.data.getEntry(pos); if (entry) |e| { return e.value_ptr.*; } return self.default; } pub fn put_pos(self: *Grid, x: isize, y: isize, c: u8) !void { const pos = Pos.init(x, y); try self.data.put(pos, c); if (self.min.x > x) self.min.x = x; if (self.min.y > y) self.min.y = y; if (self.max.x < x) self.max.x = x; if (self.max.y < y) self.max.y = y; } }; mode: Mode, state: State, width: usize, height: usize, pos: usize, pixel: [512]u1, cur: usize, grid: [2]Grid, pub fn init(mode: Mode) Map { var self = Map{ .mode = mode, .state = State.ALGO, .width = 0, .height = 0, .pos = 0, .pixel = [_]u1{0} ** 512, .cur = 0, .grid = undefined, }; for (self.grid) |*g| { g.* = Grid.init(); } return self; } pub fn deinit(self: *Map) void { for (self.grid) |*g| { g.*.deinit(); } } pub fn process_line(self: *Map, data: []const u8) !void { if (data.len == 0) { self.state = State.DATA; self.cur = 0; self.grid[self.cur].reset(); return; } switch (self.state) { State.ALGO => { // although it is said the algo comes in a single line, it is more readable to support multiple lines for (data) |c, p| { if (c != '#') continue; self.pixel[self.pos + p] = 1; } self.pos += data.len; // I know, I'm a fucking cheat switch (self.mode) { Mode.TEST => { self.grid[0].default = '.'; self.grid[1].default = '.'; }, Mode.RUN => { self.grid[0].default = data[511]; self.grid[1].default = data[0]; }, } }, State.DATA => { if (self.width == 0) self.width = data.len; if (self.width != data.len) unreachable; const y = self.height; for (data) |c, x| { const sx = @intCast(isize, x); const sy = @intCast(isize, y); try self.grid[self.cur].put_pos(sx, sy, c); } self.height += 1; }, } } pub fn process(self: *Map, steps: usize) !void { var n: usize = 0; // self.show(n); while (n < steps) { try self.iterate(); n += 1; // self.show(n); } } pub fn count_pixels_on(self: Map) usize { var count: usize = 0; var sy: isize = self.grid[self.cur].min.y; while (sy <= self.grid[self.cur].max.y) : (sy += 1) { var sx: isize = self.grid[self.cur].min.x; while (sx <= self.grid[self.cur].max.x) : (sx += 1) { const b = self.grid[self.cur].get_pos(sx, sy); if (b != '#') continue; count += 1; } } return count; } fn iterate(self: *Map) !void { var nxt = 1 - self.cur; self.grid[nxt].reset(); // std.debug.warn("PROCESS {} -> {}, {} to {}\n", .{ self.cur, nxt, self.grid[self.cur].min, self.grid[self.cur].max }); var sy: isize = self.grid[self.cur].min.y - 1; while (sy <= self.grid[self.cur].max.y + 1) : (sy += 1) { var sx: isize = self.grid[self.cur].min.x - 1; while (sx <= self.grid[self.cur].max.x + 1) : (sx += 1) { var pos: usize = 0; var dy: isize = -1; while (dy <= 1) : (dy += 1) { var py = sy + dy; var dx: isize = -1; while (dx <= 1) : (dx += 1) { var px = sx + dx; const b = self.grid[self.cur].get_pos(px, py); pos <<= 1; if (b != '#') continue; pos |= 1; } } var c = self.pixel[pos]; try self.grid[nxt].put_pos(sx, sy, if (c == 1) '#' else '.'); } } self.cur = nxt; } fn show(self: *Map, step: usize) void { std.debug.warn("SHOW STEP {}, POS {}\n", .{ step, self.cur }); var sy: isize = self.grid[self.cur].min.y; while (sy <= self.grid[self.cur].max.y) : (sy += 1) { var sx: isize = self.grid[self.cur].min.x; while (sx <= self.grid[self.cur].max.x) : (sx += 1) { const b = self.grid[self.cur].get_pos(sx, sy); std.debug.warn("{c}", .{b}); } std.debug.warn("\n", .{}); } } }; test "sample part a" { const data: []const u8 = \\..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..## \\#..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.### \\.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#. \\.#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#..... \\.#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.. \\...####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#..... \\..##..####..#...#.#.#...##..#.#..###..#####........#..####......#..# \\ \\#..#. \\#.... \\##..# \\..#.. \\..### ; var map = Map.init(Map.Mode.TEST); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } try map.process(2); const count = map.count_pixels_on(); try testing.expect(count == 35); } test "sample part b" { const data: []const u8 = \\..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..## \\#..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.### \\.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#. \\.#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#..... \\.#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.. \\...####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#..... \\..##..####..#...#.#.#...##..#.#..###..#####........#..####......#..# \\ \\#..#. \\#.... \\##..# \\..#.. \\..### ; var map = Map.init(Map.Mode.TEST); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } try map.process(50); const count = map.count_pixels_on(); try testing.expect(count == 3351); }
2021/p20/map.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Fish = struct { pub const AGE_CYCLE = 7; pub const EXTRA_CYCLE = 2; pub const TOTAL_CYCLE = AGE_CYCLE + EXTRA_CYCLE; count_at_age: [TOTAL_CYCLE]usize, pub fn init() Fish { var self = Fish{ .count_at_age = [_]usize{0} ** (TOTAL_CYCLE) }; return self; } pub fn deinit(_: *Fish) void {} pub fn process_line(self: *Fish, data: []const u8) void { var it = std.mem.split(u8, data, ","); while (it.next()) |num| { const n = std.fmt.parseInt(usize, num, 10) catch unreachable; self.count_at_age[n] += 1; // std.debug.warn("AGE {} => {}\n", .{ n, self.count_at_age[n] }); } } fn simulate_n_days(self: *Fish, n: usize) void { var day: usize = 0; while (day < n) : (day += 1) { // age 0 is special because, when we process it, we need to change // totals that we have not yet processed; therefore, we remember // its current value and process it after all other ages are done var age_zero: usize = self.count_at_age[0]; var age: usize = 1; // note: start at 1 while (age < TOTAL_CYCLE) : (age += 1) { self.count_at_age[age - 1] += self.count_at_age[age]; self.count_at_age[age] -= self.count_at_age[age]; } // every fish with age 0 spawns one new fish at age 6, and its own // age becomes 8 self.count_at_age[AGE_CYCLE - 1] += age_zero; self.count_at_age[AGE_CYCLE + 1] += age_zero; self.count_at_age[0] -= age_zero; } } pub fn count_fish_after_n_days(self: *Fish, n: usize) usize { self.simulate_n_days(n); var count: usize = 0; var age: usize = 0; while (age < TOTAL_CYCLE) : (age += 1) { count += self.count_at_age[age]; } return count; } }; test "sample part a" { const data: []const u8 = \\3,4,3,1,2 ; var fish = Fish.init(); defer fish.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { fish.process_line(line); } const DAYS1 = 18; const DAYS2 = 80; const count1 = fish.count_fish_after_n_days(DAYS1); try testing.expect(count1 == 26); const count2 = fish.count_fish_after_n_days(DAYS2 - DAYS1); try testing.expect(count2 == 5934); } test "sample part b" { const data: []const u8 = \\3,4,3,1,2 ; var fish = Fish.init(); defer fish.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { fish.process_line(line); } const count = fish.count_fish_after_n_days(256); try testing.expect(count == 26984457539); }
2021/p06/fish.zig
const MessageDB = @import("message-db"); const std = @import("std"); test "Connect, Raw, Default Values" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb(null); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_OK); } test "Connect, Raw, URL" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb("postgresql://localhost:5432/postgres"); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_OK); } test "Connect, Raw, Keyword/Value" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb("host=localhost port=5432 dbname=postgres"); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_OK); } test "Connect, Then Disconnect" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb(null); MessageDB.Connect.Raw.PQfinish(pg_connection); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_STARTED); } test "Connect, Then Reset Connection" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb(null); MessageDB.Connect.Raw.PQreset(pg_connection); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_OK); } test "Connect, No Server" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb("port=11111"); var status = MessageDB.Connect.Raw.PQstatus(pg_connection); try std.testing.expect(status == MessageDB.Connect.Raw.ConnStatusType.CONNECTION_STARTED); } test "Connect, Perform Query" { var pg_connection = try MessageDB.Connect.Raw.PQconnectdb(null); var result = MessageDB.Connect.Raw.PQexec(pg_connection, "SELECT 1;"); try std.testing.expect(result == 1); }
test/automated/connect/raw.zig
const std = @import("std"); const config = @import("config.zig"); const MessageBus = @import("test_message_bus.zig").MessageBus; const vr = @import("vr.zig"); const Replica = vr.Replica; const Journal = vr.Journal; const Storage = vr.Storage; const StateMachine = @import("state_machine.zig").StateMachine; const log = std.log.default; const Account = @import("tigerbeetle.zig").Account; pub fn run() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = &arena.allocator; const f = 1; const cluster = 123456789; var configuration: [3]*Replica = undefined; var message_bus = try MessageBus.init(allocator, &configuration); var storage: [2 * f + 1]Storage = undefined; var journals: [2 * f + 1]Journal = undefined; for (journals) |*journal, index| { storage[index] = try Storage.init(allocator, config.journal_size_max); journal.* = try Journal.init( allocator, &storage[index], @intCast(u16, index), config.journal_size_max, config.journal_headers_max, ); } var state_machines: [2 * f + 1]StateMachine = undefined; for (state_machines) |*state_machine| { state_machine.* = try StateMachine.init( allocator, config.accounts_max, config.transfers_max, config.commits_max, ); } var replicas: [2 * f + 1]Replica = undefined; for (replicas) |*replica, index| { replica.* = try Replica.init( allocator, cluster, &configuration, @intCast(u16, index), f, &journals[index], &message_bus, &state_machines[index], ); configuration[index] = replica; } var ticks: usize = 0; while (true) : (ticks += 1) { var leader: ?*Replica = null; for (replicas) |*replica| { if (replica.status == .normal and replica.leader()) leader = replica; replica.tick(); } if (leader) |replica| { if (ticks == 1 or ticks == 5) { const request = message_bus.get_message() orelse unreachable; defer message_bus.unref(request); request.header.* = .{ .cluster = cluster, .client = 1, .view = 0, .request = @intCast(u32, ticks), .command = .request, .operation = .create_accounts, .size = @sizeOf(vr.Header) + @sizeOf(Account), }; var body = request.buffer[@sizeOf(vr.Header)..][0..@sizeOf(Account)]; std.mem.bytesAsValue(Account, body).* = .{ .id = 1, .custom = 0, .flags = .{}, .unit = 710, .debit_reserved = 0, .debit_accepted = 0, .credit_reserved = 0, .credit_accepted = 0, .debit_reserved_limit = 100_000, .debit_accepted_limit = 1_000_000, .credit_reserved_limit = 0, .credit_accepted_limit = 0, }; request.header.set_checksum_body(body); request.header.set_checksum(); message_bus.send_message_to_replica(replica.replica, request); } } std.time.sleep(std.time.ns_per_ms * 50); } } pub fn main() !void { var frame = async run(); nosuspend try await frame; }
src/test_main.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const ans1 = ans: { var p = Vec2{ .x = 0, .y = 0 }; var d = Vec2{ .x = 1, .y = 0 }; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { const action = line[0]; const amount = try std.fmt.parseInt(i32, line[1..], 10); //std.debug.print("{c}{} p={}, d={} .....", .{ action, amount, p, d }); switch (action) { 'N' => { // means to move north by the given value. p = p.add(Vec2{ .x = 0, .y = -amount }); }, 'S' => { // means to move south by the given value. p = p.add(Vec2{ .x = 0, .y = amount }); }, 'E' => { // means to move east by the given value. p = p.add(Vec2{ .x = amount, .y = 0 }); }, 'W' => { // means to move west by the given value. p = p.add(Vec2{ .x = -amount, .y = 0 }); }, 'L' => { // means to turn left the given number of degrees. var rots = @divExact(amount, 90); while (rots > 0) { const new = Vec2{ .x = d.y, .y = -d.x }; d = new; rots -= 1; } }, 'R' => { // means to turn right the given number of degrees. var rots = @divExact(amount, 90); while (rots > 0) { const new = Vec2{ .x = -d.y, .y = d.x }; d = new; rots -= 1; } }, 'F' => { // means to move forward by the given value in the direction the ship is currently facing. p = p.add(Vec2{ .x = d.x * amount, .y = d.y * amount }); }, else => unreachable, } //std.debug.print("p={}, d={}\n", .{ p, d }); } break :ans (try std.math.absInt(p.x)) + (try std.math.absInt(p.y)); }; const ans2 = ans: { var p = Vec2{ .x = 0, .y = 0 }; var d = Vec2{ .x = 10, .y = -1 }; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { const action = line[0]; const amount = try std.fmt.parseInt(i32, line[1..], 10); //std.debug.print("{c}{} p={}, d={} .....", .{ action, amount, p, d }); switch (action) { 'N' => { // move the waypoint north by the given value. d = d.add(Vec2{ .x = 0, .y = -amount }); }, 'S' => { // move the waypoint south by the given value. d = d.add(Vec2{ .x = 0, .y = amount }); }, 'E' => { // move the waypoint east by the given value. d = d.add(Vec2{ .x = amount, .y = 0 }); }, 'W' => { // move the waypoint west by the given value. d = d.add(Vec2{ .x = -amount, .y = 0 }); }, 'L' => { // rotate the waypoint around the ship left (counter-clockwise) the given number of degrees. var rots = @divExact(amount, 90); while (rots > 0) { const new = Vec2{ .x = d.y, .y = -d.x }; d = new; rots -= 1; } }, 'R' => { // rotate the waypoint around the ship right (clockwise) the given number of degrees. var rots = @divExact(amount, 90); while (rots > 0) { const new = Vec2{ .x = -d.y, .y = d.x }; d = new; rots -= 1; } }, 'F' => { // mmove forward to the waypoint a number of times equal to the given value. p = p.add(Vec2{ .x = d.x * amount, .y = d.y * amount }); }, else => unreachable, } //std.debug.print("p={}, d={}\n", .{ p, d }); } break :ans (try std.math.absInt(p.x)) + (try std.math.absInt(p.y)); }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day12.txt", run);
2020/day12.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const nitori = @import("nitori"); const communication = nitori.communication; const Channel = communication.Channel; const EventChannel = communication.EventChannel; const ng = nitori.graph; const Graph = ng.Graph; const NodeIndex = ng.NodeIndex; const EdgeIndex = ng.EdgeIndex; //; const module = @import("module.zig"); const Module = module.Module; const system = @import("system.zig"); const CallbackContext = system.CallbackContext; //; pub const max_callback_len: usize = 2048; pub const GraphModule = struct { module: Module, // TODO change this to a ptr / allocate and own it buffer: [max_callback_len]f32, }; //; fn cloneArrayList( comptime T: type, allocator: *Allocator, alist: ArrayList(T), ) Allocator.Error!ArrayList(T) { var ret = try ArrayList(T).initCapacity(allocator, alist.capacity); ret.items.len = alist.items.len; for (alist.items) |item, i| ret.items[i] = item; return ret; } //; // ptrs can be shared between audio thread and main thread, // audio thread is the only one modifying and accessing the ptrs // after theyve been allocated on main thread, then swapped atomically // freed by main thread pub const AudioGraphBase = struct { const Self = @This(); allocator: *Allocator, modules: ArrayList(GraphModule), graph: Graph(usize, usize), sorted: []NodeIndex, output: ?NodeIndex, temp_in_bufs: ArrayList(Module.InBuffer), removals: ArrayList(usize), fn init(allocator: *Allocator) Self { const graph = Graph(usize, usize).init(allocator); return .{ .allocator = allocator, .modules = ArrayList(GraphModule).init(allocator), .graph = graph, // no errors here, everything is empty // only error is if allocator.alloc(0) can return an error .sorted = graph.toposort(allocator, allocator) catch unreachable, .output = null, .temp_in_bufs = ArrayList(Module.InBuffer).init(allocator), .removals = ArrayList(usize).init(allocator), }; } fn deinit(self: *Self) void { self.removals.deinit(); self.temp_in_bufs.deinit(); self.allocator.free(self.sorted); self.modules.deinit(); self.graph.deinit(); } //; fn sort(self: *Self, workspace_allocator: *Allocator) Graph(usize, usize).SortError!void { self.sorted = try self.graph.toposort(self.allocator, workspace_allocator); } // clones using allocator sent on init fn clone(self: Self) Allocator.Error!Self { var ret: Self = undefined; ret.allocator = self.allocator; ret.modules = try cloneArrayList(GraphModule, self.allocator, self.modules); errdefer ret.modules.deinit(); ret.graph = try self.graph.clone(self.allocator); errdefer ret.graph.deinit(); ret.sorted = try self.allocator.dupe(NodeIndex, self.sorted); errdefer self.allocator.free(ret.sorted); ret.output = self.output; ret.temp_in_bufs = try cloneArrayList(Module.InBuffer, self.allocator, self.temp_in_bufs); errdefer ret.temp_in_bufs.deinit(); ret.removals = try cloneArrayList(usize, self.allocator, self.removals); return ret; } }; // Audio-thread side audio graph // nothing should or needs to support reallocation pub const AudioGraph = struct { const Self = @This(); base: AudioGraphBase, tx: Channel(AudioGraphBase).Sender, rx: EventChannel(AudioGraphBase).Receiver, // allocator must be the same as used for the controller pub fn init( allocator: *Allocator, channel: *Channel(AudioGraphBase), event_channel: *EventChannel(AudioGraphBase), ) Self { return .{ .base = AudioGraphBase.init(allocator), .tx = channel.makeSender(), .rx = event_channel.makeReceiver(), }; } // deinit is called after audio thread is killed pub fn deinit(self: *Self) void { self.base.deinit(); } //; // TODO move to base fn moduleIdxFromNodeIdx(self: Self, idx: NodeIndex) usize { return self.base.graph.nodes.items[idx].weight; } pub fn frame(self: *Self, ctx: Module.FrameContext) Channel(AudioGraphBase).Error!void { if (self.rx.tryRecv(ctx.now)) |*swap_ev| { std.mem.swap(AudioGraphBase, &self.base, &swap_ev.data); std.mem.swap(ArrayList(usize), &self.base.removals, &swap_ev.data.removals); try self.tx.send(swap_ev.data); } for (self.base.sorted) |idx| { const module_idx = self.moduleIdxFromNodeIdx(idx); const m = self.base.modules.items[module_idx].module; m.vtable.frame(m, ctx); } } // TODO handle buffer max len more robustly // as is, out[]f32 param can be any len pub fn compute(self: *Self, ctx: Module.ComputeContext, out: []f32) void { var ctx_copy = ctx; if (self.base.output) |output_node_idx| { for (self.base.sorted) |idx| { const module_idx = self.moduleIdxFromNodeIdx(idx); var gm = &self.base.modules.items[module_idx]; // TODO could probably memoize this somehow var in_bufs_at: usize = 0; var edge_iter = self.base.graph.edgesDirected(idx, .Incoming); while (edge_iter.next()) |ref| { const in_buf_idx = self.moduleIdxFromNodeIdx(ref.edge.start_node); self.base.temp_in_bufs.items[in_bufs_at] = .{ .id = ref.edge.weight, .buf = &self.base.modules.items[in_buf_idx].buffer, }; in_bufs_at += 1; } ctx_copy.inputs = self.base.temp_in_bufs.items[0..in_bufs_at]; ctx_copy.output = &gm.buffer; gm.module.vtable.compute(gm.module, ctx_copy); } const output_idx = self.moduleIdxFromNodeIdx(output_node_idx); std.mem.copy(f32, out, self.base.modules.items[output_idx].buffer[0..ctx.frame_len]); } else { std.mem.set(f32, out, 0.); } } }; // this needs to keep track of removals, // so it can deinit removed modules after theve been swapped out // module interface needs deinit (rust does this with Box<> but secretly) pub const Controller = struct { const Self = @This(); const Error = Graph(usize, usize).SortError || EventChannel(AudioGraphBase).Error || Allocator.Error; allocator: *Allocator, base: AudioGraphBase, max_inputs: usize, tx: EventChannel(AudioGraphBase).Sender, rx: Channel(AudioGraphBase).Receiver, pub fn init( allocator: *Allocator, channel: *Channel(AudioGraphBase), event_channel: *EventChannel(AudioGraphBase), ) Self { return .{ .allocator = allocator, .base = AudioGraphBase.init(allocator), .max_inputs = 0, .tx = event_channel.makeSender(), .rx = channel.makeReceiver(), }; } pub fn deinit(self: *Self) void { // TODO // for (self.base.graph.nodes.items) |*node| { // if (node.in_use) { // self.base.modules.items[node.weight].module.deinit(); // } // } self.base.deinit(); } //; fn updateMaxInputs(self: *Self) void { self.max_inputs = 0; for (self.base.graph.nodes) |node, idx| { if (node.in_use) { var input_ct = 0; var edge_iter = self.base.graph.edgesDirected(idx, .Incoming); while (edge_iter.next()) |_| : (input_ct += 1) {} if (input_ct > self.max_inputs) { self.max_inputs = input_ct; } } } } // takes ownership of module // TODO handle not found errors? maybe not pub fn addModule(self: *Self, mod: Module) Allocator.Error!NodeIndex { const id = self.base.modules.items.len; try self.base.modules.append(.{ .module = mod, .buffer = [_]f32{0.} ** max_callback_len, }); return try self.base.graph.addNode(id); } pub fn addEdge( self: *Self, source: NodeIndex, target: NodeIndex, input_number: usize, ) Allocator.Error!EdgeIndex { const edge_idx = try self.base.graph.addEdge(source, target, input_number); var input_ct: usize = 0; var edge_iter = self.base.graph.edgesDirected(target, .Incoming); while (edge_iter.next()) |_| : (input_ct += 1) {} if (input_ct > self.max_inputs) { self.max_inputs = input_ct; } return edge_idx; } // TODO test removals // remove by node id // module id is just uzsed internally pub fn removeModule(self: *Self, node_idx: NodeIndex) void { const module_idx = self.base.graph.nodes.items[node_idx].weight; try self.base.graph.removeNode(node_idx); try self.removals.append(module_idx); self.updateMaxInputs(); } pub fn removeEdge(self: *Self, edge_idx: EdgeIndex) void { self.base.graph.removeEdge(edge_idx); self.updateMaxInputs(); } pub fn setOutput(self: *Self, node_idx: NodeIndex) void { // TODO maybe set base.output to be the module_idx not the node_idx self.base.output = node_idx; } pub fn pushChanges( self: *Self, workspace_allocator: *Allocator, now: u64, ) Error!void { // TODO you have to clone here // this send here takes ownership // actual AudioGraphBase the controller started with is never sent to the other thread // can be deinited normally when controller is deinited var to_send = try self.base.clone(); try to_send.sort(workspace_allocator); try to_send.temp_in_bufs.ensureCapacity(self.max_inputs); // TODO do i really wana do this to_send.temp_in_bufs.items.len = self.max_inputs; try self.tx.send(now, to_send); } pub fn frame(self: *Self) void { if (self.rx.tryRecv()) |*swap| { for (swap.removals.items) |module_idx| { var gm = swap.modules.orderedRemove(module_idx); gm.module.deinit(); } // ?? // TODO deinit and free and stuff // swap.deinit(); } } };
src/audio_graph.zig
const __floattidf = @import("floattidf.zig").__floattidf; const testing = @import("std").testing; fn test__floattidf(a: i128, expected: f64) !void { const x = __floattidf(a); try testing.expect(x == expected); } test "floattidf" { try test__floattidf(0, 0.0); try test__floattidf(1, 1.0); try test__floattidf(2, 2.0); try test__floattidf(20, 20.0); try test__floattidf(-1, -1.0); try test__floattidf(-2, -2.0); try test__floattidf(-20, -20.0); try test__floattidf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); try test__floattidf(0x7FFFFFFFFFFFF800, 0x1.FFFFFFFFFFFFEp+62); try test__floattidf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); try test__floattidf(0x7FFFFFFFFFFFF000, 0x1.FFFFFFFFFFFFCp+62); try test__floattidf(make_ti(0x8000008000000000, 0), -0x1.FFFFFEp+126); try test__floattidf(make_ti(0x8000000000000800, 0), -0x1.FFFFFFFFFFFFEp+126); try test__floattidf(make_ti(0x8000010000000000, 0), -0x1.FFFFFCp+126); try test__floattidf(make_ti(0x8000000000001000, 0), -0x1.FFFFFFFFFFFFCp+126); try test__floattidf(make_ti(0x8000000000000000, 0), -0x1.000000p+127); try test__floattidf(make_ti(0x8000000000000001, 0), -0x1.000000p+127); try test__floattidf(0x0007FB72E8000000, 0x1.FEDCBAp+50); try test__floattidf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); try test__floattidf(0x0007FB72EB000000, 0x1.FEDCBACp+50); try test__floattidf(0x0007FB72EBFFFFFF, 0x1.FEDCBAFFFFFFCp+50); try test__floattidf(0x0007FB72EC000000, 0x1.FEDCBBp+50); try test__floattidf(0x0007FB72E8000001, 0x1.FEDCBA0000004p+50); try test__floattidf(0x0007FB72E6000000, 0x1.FEDCB98p+50); try test__floattidf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); try test__floattidf(0x0007FB72E7FFFFFF, 0x1.FEDCB9FFFFFFCp+50); try test__floattidf(0x0007FB72E4000001, 0x1.FEDCB90000004p+50); try test__floattidf(0x0007FB72E4000000, 0x1.FEDCB9p+50); try test__floattidf(0x023479FD0E092DC0, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DA1, 0x1.1A3CFE870496Dp+57); try test__floattidf(0x023479FD0E092DB0, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DB8, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DB6, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DBF, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DC1, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DC7, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DC8, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DCF, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DD0, 0x1.1A3CFE870496Ep+57); try test__floattidf(0x023479FD0E092DD1, 0x1.1A3CFE870496Fp+57); try test__floattidf(0x023479FD0E092DD8, 0x1.1A3CFE870496Fp+57); try test__floattidf(0x023479FD0E092DDF, 0x1.1A3CFE870496Fp+57); try test__floattidf(0x023479FD0E092DE0, 0x1.1A3CFE870496Fp+57); try test__floattidf(make_ti(0x023479FD0E092DC0, 0), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DA1, 1), 0x1.1A3CFE870496Dp+121); try test__floattidf(make_ti(0x023479FD0E092DB0, 2), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DB8, 3), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DB6, 4), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DBF, 5), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DC1, 6), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DC7, 7), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DC8, 8), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DCF, 9), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DD0, 0), 0x1.1A3CFE870496Ep+121); try test__floattidf(make_ti(0x023479FD0E092DD1, 11), 0x1.1A3CFE870496Fp+121); try test__floattidf(make_ti(0x023479FD0E092DD8, 12), 0x1.1A3CFE870496Fp+121); try test__floattidf(make_ti(0x023479FD0E092DDF, 13), 0x1.1A3CFE870496Fp+121); try test__floattidf(make_ti(0x023479FD0E092DE0, 14), 0x1.1A3CFE870496Fp+121); } fn make_ti(high: u64, low: u64) i128 { var result: u128 = high; result <<= 64; result |= low; return @bitCast(i128, result); }
lib/std/special/compiler_rt/floattidf_test.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day19.txt"); const Point3 = struct { x: i64, y: i64, z: i64, }; const Input = struct { scanners: std.BoundedArray(std.BoundedArray(Point3, 27), 39) = undefined, pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() { _ = allocator; var input = Input{ .scanners = try std.BoundedArray(std.BoundedArray(Point3, 27), 39).init(0), }; errdefer input.deinit(); var lines = std.mem.tokenize(u8, input_text, "\r\n"); var scanner_index: usize = 0; while (lines.next()) |line| { if (line[3] == ' ') { // new scanner scanner_index = input.scanners.len; try input.scanners.append(try std.BoundedArray(Point3, 27).init(0)); } else { // beacon within current scanner var coords = std.mem.tokenize(u8, line, ","); const x: i64 = try parseInt(i64, coords.next().?, 10); const y: i64 = try parseInt(i64, coords.next().?, 10); const z: i64 = try parseInt(i64, coords.next().?, 10); try input.scanners.buffer[scanner_index].append(Point3{ .x = x, .y = y, .z = z }); } } return input; } pub fn deinit(self: @This()) void { _ = self; } }; const transforms = [24][9]i32{ [9]i32{ 1, 0, 0, 0, 1, 0, 0, 0, 1 }, [9]i32{ 0, 0, 1, 0, 1, 0, -1, 0, 0 }, [9]i32{ 0, 0, 1, 0, -1, 0, 1, 0, 0 }, [9]i32{ 0, 0, 1, 1, 0, 0, 0, 1, 0 }, [9]i32{ 0, 0, 1, -1, 0, 0, 0, -1, 0 }, [9]i32{ 0, 0, -1, 0, 1, 0, 1, 0, 0 }, [9]i32{ 0, 0, -1, 0, -1, 0, -1, 0, 0 }, [9]i32{ 0, 0, -1, 1, 0, 0, 0, -1, 0 }, [9]i32{ 0, 0, -1, -1, 0, 0, 0, 1, 0 }, [9]i32{ 0, 1, 0, 0, 0, 1, 1, 0, 0 }, [9]i32{ 0, 1, 0, 0, 0, -1, -1, 0, 0 }, [9]i32{ 0, 1, 0, 1, 0, 0, 0, 0, -1 }, [9]i32{ 0, 1, 0, -1, 0, 0, 0, 0, 1 }, [9]i32{ 0, -1, 0, 0, 0, 1, -1, 0, 0 }, [9]i32{ 0, -1, 0, 0, 0, -1, 1, 0, 0 }, [9]i32{ 0, -1, 0, 1, 0, 0, 0, 0, 1 }, [9]i32{ 0, -1, 0, -1, 0, 0, 0, 0, -1 }, [9]i32{ 1, 0, 0, 0, 0, 1, 0, -1, 0 }, [9]i32{ 1, 0, 0, 0, 0, -1, 0, 1, 0 }, [9]i32{ 1, 0, 0, 0, -1, 0, 0, 0, -1 }, [9]i32{ -1, 0, 0, 0, 0, 1, 0, 1, 0 }, [9]i32{ -1, 0, 0, 0, 0, -1, 0, -1, 0 }, [9]i32{ -1, 0, 0, 0, 1, 0, 0, 0, -1 }, [9]i32{ -1, 0, 0, 0, -1, 0, 0, 0, 1 }, }; const IDENTITY_TRANSFORM: usize = 0; fn transformPoints(points: []const Point3, out_points: []Point3, xform_index: usize) void { const mat = transforms[xform_index]; for (points) |point, i| { out_points[i] = Point3{ .x = mat[0] * point.x + mat[1] * point.y + mat[2] * point.z, .y = mat[3] * point.x + mat[4] * point.y + mat[5] * point.z, .z = mat[6] * point.x + mat[7] * point.y + mat[8] * point.z, }; } } test "transformPoints" { const transform_test_data = \\--- scanner 0 --- \\-1,-1,1 \\-2,-2,2 \\-3,-3,3 \\-2,-3,1 \\5,6,-4 \\8,0,7 \\ \\--- scanner 0 --- \\1,-1,1 \\2,-2,2 \\3,-3,3 \\2,-1,3 \\-5,4,-6 \\-8,-7,0 \\ \\--- scanner 0 --- \\-1,-1,-1 \\-2,-2,-2 \\-3,-3,-3 \\-1,-3,-2 \\4,6,5 \\-7,0,8 \\ \\--- scanner 0 --- \\1,1,-1 \\2,2,-2 \\3,3,-3 \\1,3,-2 \\-4,-6,5 \\7,0,8 \\ \\--- scanner 0 --- \\1,1,1 \\2,2,2 \\3,3,3 \\3,1,2 \\-6,-4,-5 \\0,7,-8 ; var test_input = try Input.init(transform_test_data, std.testing.allocator); defer test_input.deinit(); // populate set with beacons from scanner 0 var all_beacons = std.AutoHashMap(Point3, bool).init(std.testing.allocator); defer all_beacons.deinit(); try all_beacons.ensureTotalCapacity(6); for (test_input.scanners.buffer[0].constSlice()) |beacon_pos| { all_beacons.putAssumeCapacityNoClobber(beacon_pos, true); } // make sure remaining scanners all rotate to the existing beacons var transformed_points: [6]Point3 = .{undefined} ** 6; for (test_input.scanners.constSlice()) |scanner| { var found_xform_for_match = false; for (transforms) |_, xform_index| { transformPoints(scanner.constSlice(), transformed_points[0..], xform_index); //print("with transform {d:2}, beacon 5 transforms to {d:2},{d:2},{d:2}\n", .{ xform_index, transformed_points[5].x, transformed_points[5].y, transformed_points[5].z }); var found_all_beacons = true; for (transformed_points) |pt| { if (!all_beacons.contains(pt)) { found_all_beacons = false; break; } } if (found_all_beacons) { found_xform_for_match = true; break; } } try expect(found_xform_for_match); } } const TransformedScannerData = struct { beacons: std.BoundedArray(Point3, 27), offsets: std.AutoHashMap(Point3, Point3), allocator: std.mem.Allocator, pub fn init(points: std.BoundedArray(Point3, 27), xform_index: usize, allocator: std.mem.Allocator) !@This() { var self = TransformedScannerData{ .beacons = try std.BoundedArray(Point3, 27).init(points.len), .offsets = std.AutoHashMap(Point3, Point3).init(allocator), .allocator = allocator, }; transformPoints(points.constSlice(), self.beacons.slice(), xform_index); const offset_count = @truncate(u32, (self.beacons.len * (self.beacons.len - 1)) / 2); try self.offsets.ensureTotalCapacity(offset_count); for (self.beacons.constSlice()) |p1, i| { var j: usize = i + 1; while (j < self.beacons.len) : (j += 1) { const p2 = self.beacons.buffer[j]; const offset = Point3{ .x = p2.x - p1.x, .y = p2.y - p1.y, .z = p2.z - p1.z }; self.offsets.putAssumeCapacity(offset, p1); } } return self; } pub fn deinit(self: *@This()) void { self.offsets.deinit(); } }; const Scanner = struct { transformed: std.BoundedArray(TransformedScannerData, 24), id: usize, pub fn init(id: usize, points: std.BoundedArray(Point3, 27), allocator: std.mem.Allocator) !@This() { var self = Scanner{ .transformed = try std.BoundedArray(TransformedScannerData, 24).init(0), .id = id, }; for (transforms) |_, xform_index| { self.transformed.appendAssumeCapacity(try TransformedScannerData.init(points, xform_index, allocator)); } return self; } pub fn deinit(self: *@This()) void { for (self.transformed.slice()) |*t| { t.deinit(); } } }; const KnownSpace = struct { beacons: std.ArrayList(Point3), beacon_map: std.AutoHashMap(Point3, bool), offsets_map: std.AutoHashMap(Point3, Point3), scanner_positions: std.ArrayList(Point3), pub fn init(allocator: std.mem.Allocator) !@This() { var self = KnownSpace{ .beacons = try std.ArrayList(Point3).initCapacity(allocator, 40 * 30), .beacon_map = std.AutoHashMap(Point3, bool).init(allocator), .offsets_map = std.AutoHashMap(Point3, Point3).init(allocator), .scanner_positions = try std.ArrayList(Point3).initCapacity(allocator, 40), }; try self.beacon_map.ensureTotalCapacity(@truncate(u32, self.beacons.capacity)); return self; } pub fn deinit(self: *@This()) void { self.beacons.deinit(); self.beacon_map.deinit(); self.offsets_map.deinit(); self.scanner_positions.deinit(); } pub fn pointWithOffset(self: @This(), offset: Point3) ?Point3 { return self.offsets_map.get(offset); } pub fn numMatches(self: @This(), scanner_points: std.BoundedArray(Point3, 27), relative_scanner_offset: Point3) usize { var count: usize = 0; for (scanner_points.constSlice()) |p| { const shifted = Point3{ .x = p.x + relative_scanner_offset.x, .y = p.y + relative_scanner_offset.y, .z = p.z + relative_scanner_offset.z }; if (self.beacon_map.contains(shifted)) { count += 1; } } return count; } pub fn addScanner(self: *@This(), scanners: *std.BoundedArray(Scanner, 39), scanner_index: usize, xform_index: usize, relative_scanner_offset: Point3) !void { // Add beacons for (scanners.buffer[scanner_index].transformed.buffer[xform_index].beacons.constSlice()) |beacon| { const b = Point3{ .x = beacon.x + relative_scanner_offset.x, .y = beacon.y + relative_scanner_offset.y, .z = beacon.z + relative_scanner_offset.z }; if (!self.beacon_map.contains(b)) { //print("Adding {d:4},{d:4},{d:4} to known space from scanner {d}\n", .{ b.x, b.y, b.z, scanners.buffer[scanner_index].id }); self.beacons.appendAssumeCapacity(b); self.beacon_map.putAssumeCapacity(b, true); } else { //print("Skipping {d:4},{d:4},{d:4} to known space from scanner {d} (already known)\n", .{ b.x, b.y, b.z, scanners.buffer[scanner_index].id }); } } //print("Known space now contains {d} beacons\n", .{self.beacons.items.len}); // Recalculate offsets between known beacons self.offsets_map.clearRetainingCapacity(); const offset_count = @truncate(u32, (self.beacons.items.len * (self.beacons.items.len - 1)) / 2); try self.offsets_map.ensureTotalCapacity(offset_count); for (self.beacons.items) |p1, i| { var j: usize = i + 1; while (j < self.beacons.items.len) : (j += 1) { const p2 = self.beacons.items[j]; const offset = Point3{ .x = p2.x - p1.x, .y = p2.y - p1.y, .z = p2.z - p1.z }; self.offsets_map.putAssumeCapacity(offset, p1); } } // Add scanner position self.scanner_positions.appendAssumeCapacity(relative_scanner_offset); // remove scanner var s = scanners.swapRemove(scanner_index); s.deinit(); } }; fn mapKnownSpace(input: Input) !KnownSpace { var scanners = try std.BoundedArray(Scanner, 39).init(0); for (input.scanners.constSlice()) |beacons, id| { scanners.appendAssumeCapacity(try Scanner.init(id, beacons, std.testing.allocator)); } var known_space = try KnownSpace.init(std.testing.allocator); errdefer known_space.deinit(); // Add scanner 0 to known space try known_space.addScanner(&scanners, 0, IDENTITY_TRANSFORM, Point3{ .x = 0, .y = 0, .z = 0 }); while (scanners.len > 0) { scanner_loop: for (scanners.constSlice()) |scanner, scanner_index| { for (scanner.transformed.constSlice()) |transformed, xform_index| { var offset_itor = transformed.offsets.keyIterator(); while (offset_itor.next()) |offset| { if (known_space.pointWithOffset(offset.*)) |kp| { const sp = transformed.offsets.get(offset.*).?; const relative_scanner_pos = Point3{ .x = kp.x - sp.x, .y = kp.y - sp.y, .z = kp.z - sp.z }; // possible match; shift transformed.beacons to overlap at this // point and check for matches const matches = known_space.numMatches(transformed.beacons, relative_scanner_pos); if (matches >= 12) { //print("found overlap: scanner {d} transform {d} matches {d} beacons at {d:5},{d:5},{d:5}\n", // .{ scanner.id, xform_index, matches, relative_scanner_pos.x, relative_scanner_pos.y, relative_scanner_pos.z}); known_space.addScanner(&scanners, scanner_index, xform_index, relative_scanner_pos) catch unreachable; break :scanner_loop; } } } } } } // clean up remaining scanners (though there shouldn't be any!) for (scanners.slice()) |*scanner| { scanner.deinit(); } return known_space; } fn part1(input: Input) i64 { var known_space = mapKnownSpace(input) catch unreachable; defer known_space.deinit(); return @intCast(i64, known_space.beacons.items.len); } fn part2(input: Input) i64 { var known_space = mapKnownSpace(input) catch unreachable; defer known_space.deinit(); var max_distance: i64 = 0; for (known_space.scanner_positions.items) |p1, i| { var j = i + 1; while (j < known_space.scanner_positions.items.len) : (j += 1) { const p2 = known_space.scanner_positions.items[j]; var d = std.math.absInt(p2.x - p1.x) catch unreachable; d += std.math.absInt(p2.y - p1.y) catch unreachable; d += std.math.absInt(p2.z - p1.z) catch unreachable; max_distance = std.math.max(max_distance, d); } } return @intCast(i64, max_distance); } const test_data = \\--- scanner 0 --- \\404,-588,-901 \\528,-643,409 \\-838,591,734 \\390,-675,-793 \\-537,-823,-458 \\-485,-357,347 \\-345,-311,381 \\-661,-816,-575 \\-876,649,763 \\-618,-824,-621 \\553,345,-567 \\474,580,667 \\-447,-329,318 \\-584,868,-557 \\544,-627,-890 \\564,392,-477 \\455,729,728 \\-892,524,684 \\-689,845,-530 \\423,-701,434 \\7,-33,-71 \\630,319,-379 \\443,580,662 \\-789,900,-551 \\459,-707,401 \\ \\--- scanner 1 --- \\686,422,578 \\605,423,415 \\515,917,-361 \\-336,658,858 \\95,138,22 \\-476,619,847 \\-340,-569,-846 \\567,-361,727 \\-460,603,-452 \\669,-402,600 \\729,430,532 \\-500,-761,534 \\-322,571,750 \\-466,-666,-811 \\-429,-592,574 \\-355,545,-477 \\703,-491,-529 \\-328,-685,520 \\413,935,-424 \\-391,539,-444 \\586,-435,557 \\-364,-763,-893 \\807,-499,-711 \\755,-354,-619 \\553,889,-390 \\ \\--- scanner 2 --- \\649,640,665 \\682,-795,504 \\-784,533,-524 \\-644,584,-595 \\-588,-843,648 \\-30,6,44 \\-674,560,763 \\500,723,-460 \\609,671,-379 \\-555,-800,653 \\-675,-892,-343 \\697,-426,-610 \\578,704,681 \\493,664,-388 \\-671,-858,530 \\-667,343,800 \\571,-461,-707 \\-138,-166,112 \\-889,563,-600 \\646,-828,498 \\640,759,510 \\-630,509,768 \\-681,-892,-333 \\673,-379,-804 \\-742,-814,-386 \\577,-820,562 \\ \\--- scanner 3 --- \\-589,542,597 \\605,-692,669 \\-500,565,-823 \\-660,373,557 \\-458,-679,-417 \\-488,449,543 \\-626,468,-788 \\338,-750,-386 \\528,-832,-391 \\562,-778,733 \\-938,-730,414 \\543,643,-506 \\-524,371,-870 \\407,773,750 \\-104,29,83 \\378,-903,-323 \\-778,-728,485 \\426,699,580 \\-438,-605,-362 \\-469,-447,-387 \\509,732,623 \\647,635,-688 \\-868,-804,481 \\614,-800,639 \\595,780,-596 \\ \\--- scanner 4 --- \\727,592,562 \\-293,-554,779 \\441,611,-461 \\-714,465,-776 \\-743,427,-804 \\-660,-479,-426 \\832,-632,460 \\927,-485,-438 \\408,393,-506 \\466,436,-512 \\110,16,151 \\-258,-428,682 \\-393,719,612 \\-211,-452,876 \\808,-476,-593 \\-575,615,604 \\-485,667,467 \\-680,325,-822 \\-627,-443,-432 \\872,-547,-609 \\833,512,582 \\807,604,487 \\839,-516,451 \\891,-625,532 \\-652,-548,-490 \\30,-46,-14 ; const part1_test_solution: ?i64 = 79; const part1_solution: ?i64 = 467; const part2_test_solution: ?i64 = 3621; const part2_solution: ?i64 = 12226; // Just boilerplate below here, nothing to see fn testPart1() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part1_test_solution) |solution| { try std.testing.expectEqual(solution, part1(test_input)); } var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } fn testPart2() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part2_test_solution) |solution| { try std.testing.expectEqual(solution, part2(test_input)); } var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part2_solution) |solution| { try std.testing.expectEqual(solution, part2(input)); print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } pub fn main() !void { try testPart1(); try testPart2(); } test "part1" { try testPart1(); } test "part2" { try testPart2(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day19.zig
const std = @import("std"); usingnamespace (@import("../machine.zig")); usingnamespace (@import("../util.zig")); const imm = Operand.immediate; const imm8 = Operand.immediate8; const imm16 = Operand.immediate16; const imm32 = Operand.immediate32; const imm64 = Operand.immediate64; const immSign = Operand.immediateSigned; const immSign8 = Operand.immediateSigned8; const immSign16 = Operand.immediateSigned16; const immSign32 = Operand.immediateSigned32; const immSign64 = Operand.immediateSigned64; const reg = Operand.register; const regRm = Operand.registerRm; const memSib = Operand.memorySibDef; const far16 = Operand.far16; const far32 = Operand.far32; test "call" { const m32 = Machine.init(.x86_32); const m64 = Machine.init(.x64); debugPrint(false); { testOp1(m32, .CALL, immSign16(-1), "66 E8 ff ff"); testOp1(m64, .CALL, immSign16(-1), AsmError.InvalidOperand); // testOp1(m32, .CALL, immSign32(-1), "E8 ff ff ff ff"); testOp1(m64, .CALL, immSign32(-1), "E8 ff ff ff ff"); } { testOp1(m32, .CALL, reg(.AX), "66 ff d0"); testOp1(m64, .CALL, reg(.AX), AsmError.InvalidOperand); // testOp1(m32, .CALL, regRm(.AX), "66 ff d0"); testOp1(m64, .CALL, regRm(.AX), AsmError.InvalidOperand); // testOp1(m32, .CALL, regRm(.EAX), "ff d0"); testOp1(m64, .CALL, regRm(.EAX), AsmError.InvalidOperand); // testOp1(m32, .CALL, regRm(.RAX), AsmError.InvalidOperand); testOp1(m64, .CALL, regRm(.RAX), "ff d0"); } { testOp1(m32, .CALL, far16(0x1100, 0x3322), "66 9A 22 33 00 11"); testOp1(m64, .CALL, far16(0x1100, 0x3322), AsmError.InvalidOperand); // testOp1(m32, .CALL, far32(0x1100, 0x55443322), "9A 22 33 44 55 00 11"); testOp1(m64, .CALL, far32(0x1100, 0x55443322), AsmError.InvalidOperand); } { testOp1(m32, .CALL, memSib(.FAR_WORD, 1, .EAX, .EAX, 0), "66 FF 1C 00"); testOp1(m64, .CALL, memSib(.FAR_WORD, 1, .EAX, .EAX, 0), "66 67 FF 1C 00"); // testOp1(m32, .CALL, memSib(.FAR_DWORD, 1, .EAX, .EAX, 0), "FF 1C 00"); testOp1(m64, .CALL, memSib(.FAR_DWORD, 1, .EAX, .EAX, 0), "67 FF 1C 00"); // testOp1(m32, .CALL, memSib(.FAR_QWORD, 1, .EAX, .EAX, 0), AsmError.InvalidOperand); testOp1(m64, .CALL, memSib(.FAR_QWORD, 1, .EAX, .EAX, 0), "67 48 FF 1C 00"); } }
src/x86/tests/call.zig
const std = @import("std"); const Atomic = std.atomic.Atomic; const utils = @import("../utils.zig"); pub const Lock = extern struct { pub const name = "NtKeyedEvent"; state: Atomic(u32) = Atomic(u32).init(UNLOCKED), const UNLOCKED = 0; const LOCKED = 1 << 0; const WAKING = 1 << 8; const WAITING = 1 << 9; pub fn init(self: *Lock) void { self.* = Lock{}; } pub fn deinit(self: *Lock) void { self.* = undefined; } pub fn acquire(self: *Lock) void { if (self.state.bitSet(@ctz(u32, LOCKED), .Acquire) != UNLOCKED) { self.acquireSlow(); } } fn acquireSlow(self: *Lock) void { @setCold(true); var spin: usize = 100; var state = self.state.load(.Monotonic); while (true) { if (state & LOCKED == 0) { if (@ptrCast(*Atomic(u8), &self.state).swap(LOCKED, .Acquire) == UNLOCKED) return; //if (self.state.bitSet(@ctz(u32, LOCKED), .Acquire) == UNLOCKED) return; std.atomic.spinLoopHint(); state = self.state.load(.Monotonic); // state = self.state.tryCompareAndSwap( // state, // state | LOCKED, // .Acquire, // .Monotonic, // ) orelse return; continue; } if (state < WAITING and spin > 0) { spin -= 1; std.atomic.spinLoopHint(); state = self.state.load(.Monotonic); continue; } state = self.state.tryCompareAndSwap( state, state + WAITING, .Monotonic, .Monotonic, ) orelse blk: { NtKeyedEvent.call(&self.state, "NtWaitForKeyedEvent"); state = self.state.fetchSub(WAKING, .Monotonic); break :blk state - WAKING; }; } } pub fn release(self: *Lock) void { //@ptrCast(*Atomic(u8), &self.state).store(UNLOCKED, .SeqCst); //const state = self.state.load(.Monotonic); const state = asm volatile( \\ movb $0, %[ptr] \\ lock addl $0, %%gs:0 \\ movl %[ptr], %[state] : [state] "=r" (-> u32) : [ptr] "*m" (@ptrCast(*Atomic(u8), &self.state)) : "cc", "memory" ); if ((state >= WAITING) and (state & (LOCKED | WAKING) == 0)) { self.releaseSlow(); } } fn releaseSlow(self: *Lock) void { @setCold(true); var state = self.state.load(.Monotonic); while ((state >= WAITING) and (state & (LOCKED | WAKING) == 0)) { state = self.state.tryCompareAndSwap( state, (state - WAITING) + WAKING, .Monotonic, .Monotonic, ) orelse { NtKeyedEvent.call(&self.state, "NtReleaseKeyedEvent"); return; }; } } }; pub const NtKeyedEvent = struct { var event_handle = Atomic(?std.os.windows.HANDLE).init(null); pub fn call(ptr: *const Atomic(u32), comptime event_fn: []const u8) void { @setCold(true); const handle = event_handle.load(.Unordered) orelse blk: { var handle: std.os.windows.HANDLE = undefined; const access_mask = std.os.windows.GENERIC_READ | std.os.windows.GENERIC_WRITE; const status = std.os.windows.ntdll.NtCreateKeyedEvent(&handle, access_mask, null, 0); if (status != .SUCCESS) handle = std.os.windows.INVALID_HANDLE_VALUE; if (event_handle.compareAndSwap(null, handle, .Monotonic, .Monotonic)) |current| { if (status != .SUCCESS) std.os.windows.CloseHandle(handle); handle = current orelse unreachable; } if (handle == std.os.windows.INVALID_HANDLE_VALUE) break :blk null; break :blk handle; }; switch (@field(std.os.windows.ntdll, event_fn)( handle, @ptrCast(*const c_void, ptr), std.os.windows.FALSE, // alertable null, // timeout )) { .SUCCESS => {}, else => unreachable, } } };
locks/keyed_event_lock.zig
const std = @import("std"); const lib = @import("lib"); const io = std.io; const fs = std.fs; const assert = std.debug.assert; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayListUnmanaged; const HashMap = std.AutoHashMapUnmanaged; const Interpreter = lib.Interpreter; const GraphContext = @This(); stream: Stream, stack: Stack = .{}, omit: Omit = .{}, gpa: Allocator, colour: u8 = 0, target: Target = .{}, text_colour: u24 = 0, inherit: bool = false, colours: []const u24 = &.{}, gradient: u8 = 5, pub const Error = error{OutOfMemory} || std.os.WriteError; pub const Stack = ArrayList(Layer); pub const Layer = struct { list: ArrayList([]const u8) = .{}, }; pub const Target = HashMap([*]const u8, u8); pub const Omit = HashMap(Pair, void); pub const Pair = struct { from: [*]const u8, to: [*]const u8, }; pub const Stream = io.BufferedWriter(1024, std.fs.File.Writer); pub fn init(gpa: Allocator, writer: fs.File.Writer) GraphContext { return .{ .stream = .{ .unbuffered_writer = writer }, .gpa = gpa, }; } pub const GraphOptions = struct { border: u24 = 0, background: u24 = 0, text: u24 = 0, colours: []const u24 = &.{}, inherit: bool = false, gradient: u8 = 0, }; pub fn begin(self: *GraphContext, options: GraphOptions) !void { try self.stream.writer().print( \\graph G {{ \\ bgcolor = "#{[background]x:0>6}"; \\ overlap = false; \\ rankdir = LR; \\ concentrate = true; \\ node[shape = rectangle, color = "#{[border]x:0>6}"]; \\ , .{ .background = options.background, .border = options.border, }); try self.stack.append(self.gpa, .{}); self.colours = options.colours; self.text_colour = options.text; self.inherit = options.inherit; self.gradient = options.gradient; } pub fn end(self: *GraphContext) !void { try self.stream.writer().writeAll("}\n"); try self.stream.flush(); } pub fn call(self: *GraphContext, vm: *Interpreter) !void { _ = vm; try self.stack.append(self.gpa, .{}); } pub fn ret(self: *GraphContext, vm: *Interpreter, name: []const u8) !void { _ = vm; try self.render(name); var old = self.stack.pop(); old.list.deinit(self.gpa); try self.stack.items[self.stack.items.len - 1].list.append(self.gpa, name); } pub fn terminate(self: *GraphContext, vm: *Interpreter, name: []const u8) !void { _ = vm; try self.render(name); self.stack.items[0].list.clearRetainingCapacity(); assert(self.stack.items.len == 1); } fn render(self: *GraphContext, name: []const u8) !void { const writer = self.stream.writer(); const sub_nodes = self.stack.items[self.stack.items.len - 1].list.items; var valid: usize = 0; for (sub_nodes) |sub| { if (!self.omit.contains(.{ .from = name.ptr, .to = sub.ptr })) { valid += 1; } } const theme = try self.target.getOrPut(self.gpa, name.ptr); if (!theme.found_existing) { theme.value_ptr.* = self.colour; defer self.colour +%= 1; const selected = if (self.colours.len == 0) self.colour else self.colours[self.colour % self.colours.len]; if (self.inherit) { try writer.print( \\ "{[name]s}"[fontcolor = "#{[colour]x:0>6}", color = "#{[inherit]x:0>6}"]; \\ , .{ .name = name, .colour = self.text_colour, .inherit = selected, }); } else { try writer.print( \\ "{[name]s}"[fontcolor = "#{[colour]x:0>6}"]; \\ , .{ .name = name, .colour = self.text_colour, }); } } for (sub_nodes) |sub| { const entry = try self.omit.getOrPut(self.gpa, .{ .from = name.ptr, .to = sub.ptr, }); if (!entry.found_existing) { const to = self.target.get(sub.ptr).?; const from = self.target.get(name.ptr).?; const selected: struct { from: u24, to: u24 } = if (self.colours.len == 0) .{ .from = 0, .to = 0, } else .{ .from = self.colours[from % self.colours.len], .to = self.colours[to % self.colours.len], }; try writer.print( \\ "{s}" -- "{s}" [color = " , .{ name, sub }); if (self.gradient != 0) { var i: i24 = 0; const r: i32 = @truncate(u8, selected.from >> 16); const g: i32 = @truncate(u8, selected.from >> 8); const b: i32 = @truncate(u8, selected.from); const x: i32 = @truncate(u8, selected.to >> 16); const y: i32 = @truncate(u8, selected.to >> 8); const z: i32 = @truncate(u8, selected.to); const dx = @divTrunc(x - r, self.gradient); const gy = @divTrunc(y - g, self.gradient); const bz = @divTrunc(z - b, self.gradient); while (i < self.gradient) : (i += 1) { const red = r + dx * i; const green = g + gy * i; const blue = b + bz * i; const rgb = @bitCast(u24, @truncate(i24, red << 16 | (green << 8) | (blue & 0xff))); try writer.print("#{x:0>6};{d}:", .{ rgb, 1.0 / @intToFloat(f64, self.gradient) }); } } try writer.print( \\#{x:0>6}"]; \\ , .{selected.to}); } } }
src/GraphContext.zig
const std = @import("../../std.zig"); const maxInt = std.math.maxInt; // See https://svnweb.freebsd.org/base/head/sys/sys/_types.h?view=co // TODO: audit pid_t/mode_t. They should likely be i32 and u16, respectively pub const fd_t = c_int; pub const pid_t = c_int; pub const uid_t = u32; pub const gid_t = u32; pub const mode_t = c_uint; pub const socklen_t = u32; /// Renamed from `kevent` to `Kevent` to avoid conflict with function name. pub const Kevent = extern struct { ident: usize, filter: i16, flags: u16, fflags: u32, data: i64, udata: usize, // TODO ext }; // Modes and flags for dlopen() // include/dlfcn.h /// Bind function calls lazily. pub const RTLD_LAZY = 1; /// Bind function calls immediately. pub const RTLD_NOW = 2; pub const RTLD_MODEMASK = 0x3; /// Make symbols globally available. pub const RTLD_GLOBAL = 0x100; /// Opposite of RTLD_GLOBAL, and the default. pub const RTLD_LOCAL = 0; /// Trace loaded objects and exit. pub const RTLD_TRACE = 0x200; /// Do not remove members. pub const RTLD_NODELETE = 0x01000; /// Do not load if not already loaded. pub const RTLD_NOLOAD = 0x02000; pub const dl_phdr_info = extern struct { dlpi_addr: usize, dlpi_name: ?[*:0]const u8, dlpi_phdr: [*]std.elf.Phdr, dlpi_phnum: u16, }; pub const Flock = extern struct { l_start: off_t, l_len: off_t, l_pid: pid_t, l_type: i16, l_whence: i16, l_sysid: i32, __unused: [4]u8, }; pub const msghdr = extern struct { /// optional address msg_name: ?*sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]iovec, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*c_void, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; pub const msghdr_const = extern struct { /// optional address msg_name: ?*const sockaddr, /// size of address msg_namelen: socklen_t, /// scatter/gather array msg_iov: [*]iovec_const, /// # elements in msg_iov msg_iovlen: i32, /// ancillary data msg_control: ?*c_void, /// ancillary data buffer len msg_controllen: socklen_t, /// flags on received message msg_flags: i32, }; pub const off_t = i64; pub const ino_t = u64; pub const libc_stat = extern struct { dev: u64, ino: ino_t, nlink: usize, mode: u16, __pad0: u16, uid: uid_t, gid: gid_t, __pad1: u32, rdev: u64, atim: timespec, mtim: timespec, ctim: timespec, birthtim: timespec, size: off_t, blocks: i64, blksize: isize, flags: u32, gen: u64, __spare: [10]u64, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const timespec = extern struct { tv_sec: isize, tv_nsec: isize, }; pub const dirent = extern struct { d_fileno: usize, d_off: i64, d_reclen: u16, d_type: u8, d_pad0: u8, d_namlen: u16, d_pad1: u16, d_name: [256]u8, pub fn reclen(self: dirent) u16 { return self.d_reclen; } }; pub const in_port_t = u16; pub const sa_family_t = u8; pub const sockaddr = extern struct { /// total length len: u8, /// address family family: sa_family_t, /// actually longer; address value data: [14]u8, }; pub const sockaddr_in = extern struct { len: u8 = @sizeOf(sockaddr_in), family: sa_family_t = AF_INET, port: in_port_t, addr: u32, zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }, }; pub const sockaddr_in6 = extern struct { len: u8 = @sizeOf(sockaddr_in6), family: sa_family_t = AF_INET6, port: in_port_t, flowinfo: u32, addr: [16]u8, scope_id: u32, }; pub const sockaddr_un = extern struct { len: u8 = @sizeOf(sockaddr_un), family: sa_family_t = AF_UNIX, path: [104]u8, }; pub const CTL_KERN = 1; pub const CTL_DEBUG = 5; pub const KERN_PROC = 14; // struct: process entries pub const KERN_PROC_PATHNAME = 12; // path to executable pub const PATH_MAX = 1024; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const PROT_NONE = 0; pub const PROT_READ = 1; pub const PROT_WRITE = 2; pub const PROT_EXEC = 4; pub const CLOCK_REALTIME = 0; pub const CLOCK_VIRTUAL = 1; pub const CLOCK_PROF = 2; pub const CLOCK_MONOTONIC = 4; pub const CLOCK_UPTIME = 5; pub const CLOCK_UPTIME_PRECISE = 7; pub const CLOCK_UPTIME_FAST = 8; pub const CLOCK_REALTIME_PRECISE = 9; pub const CLOCK_REALTIME_FAST = 10; pub const CLOCK_MONOTONIC_PRECISE = 11; pub const CLOCK_MONOTONIC_FAST = 12; pub const CLOCK_SECOND = 13; pub const CLOCK_THREAD_CPUTIME_ID = 14; pub const CLOCK_PROCESS_CPUTIME_ID = 15; pub const MAP_FAILED = @intToPtr(*c_void, maxInt(usize)); pub const MAP_SHARED = 0x0001; pub const MAP_PRIVATE = 0x0002; pub const MAP_FIXED = 0x0010; pub const MAP_STACK = 0x0400; pub const MAP_NOSYNC = 0x0800; pub const MAP_ANON = 0x1000; pub const MAP_ANONYMOUS = MAP_ANON; pub const MAP_FILE = 0; pub const MAP_GUARD = 0x00002000; pub const MAP_EXCL = 0x00004000; pub const MAP_NOCORE = 0x00020000; pub const MAP_PREFAULT_READ = 0x00040000; pub const MAP_32BIT = 0x00080000; pub const WNOHANG = 1; pub const WUNTRACED = 2; pub const WSTOPPED = WUNTRACED; pub const WCONTINUED = 4; pub const WNOWAIT = 8; pub const WEXITED = 16; pub const WTRAPPED = 32; pub const SA_ONSTACK = 0x0001; pub const SA_RESTART = 0x0002; pub const SA_RESETHAND = 0x0004; pub const SA_NOCLDSTOP = 0x0008; pub const SA_NODEFER = 0x0010; pub const SA_NOCLDWAIT = 0x0020; pub const SA_SIGINFO = 0x0040; pub const SIGHUP = 1; pub const SIGINT = 2; pub const SIGQUIT = 3; pub const SIGILL = 4; pub const SIGTRAP = 5; pub const SIGABRT = 6; pub const SIGIOT = SIGABRT; pub const SIGEMT = 7; pub const SIGFPE = 8; pub const SIGKILL = 9; pub const SIGBUS = 10; pub const SIGSEGV = 11; pub const SIGSYS = 12; pub const SIGPIPE = 13; pub const SIGALRM = 14; pub const SIGTERM = 15; pub const SIGURG = 16; pub const SIGSTOP = 17; pub const SIGTSTP = 18; pub const SIGCONT = 19; pub const SIGCHLD = 20; pub const SIGTTIN = 21; pub const SIGTTOU = 22; pub const SIGIO = 23; pub const SIGXCPU = 24; pub const SIGXFSZ = 25; pub const SIGVTALRM = 26; pub const SIGPROF = 27; pub const SIGWINCH = 28; pub const SIGINFO = 29; pub const SIGUSR1 = 30; pub const SIGUSR2 = 31; pub const SIGTHR = 32; pub const SIGLWP = SIGTHR; pub const SIGLIBRT = 33; pub const SIGRTMIN = 65; pub const SIGRTMAX = 126; // access function pub const F_OK = 0; // test for existence of file pub const X_OK = 1; // test for execute or search permission pub const W_OK = 2; // test for write permission pub const R_OK = 4; // test for read permission pub const O_RDONLY = 0x0000; pub const O_WRONLY = 0x0001; pub const O_RDWR = 0x0002; pub const O_ACCMODE = 0x0003; pub const O_SHLOCK = 0x0010; pub const O_EXLOCK = 0x0020; pub const O_CREAT = 0x0200; pub const O_EXCL = 0x0800; pub const O_NOCTTY = 0x8000; pub const O_TRUNC = 0x0400; pub const O_APPEND = 0x0008; pub const O_NONBLOCK = 0x0004; pub const O_DSYNC = 0o10000; pub const O_SYNC = 0x0080; pub const O_RSYNC = 0o4010000; pub const O_DIRECTORY = 0x20000; pub const O_NOFOLLOW = 0x0100; pub const O_CLOEXEC = 0x00100000; pub const O_ASYNC = 0x0040; pub const O_DIRECT = 0x00010000; pub const O_NOATIME = 0o1000000; pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20200000; pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; pub const F_SETFD = 2; pub const F_GETFL = 3; pub const F_SETFL = 4; pub const F_GETOWN = 5; pub const F_SETOWN = 6; pub const F_GETLK = 11; pub const F_SETLK = 12; pub const F_SETLKW = 13; pub const F_RDLCK = 1; pub const F_WRLCK = 3; pub const F_UNLCK = 2; pub const LOCK_SH = 1; pub const LOCK_EX = 2; pub const LOCK_UN = 8; pub const LOCK_NB = 4; pub const F_SETOWN_EX = 15; pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; pub const FD_CLOEXEC = 1; pub const SEEK_SET = 0; pub const SEEK_CUR = 1; pub const SEEK_END = 2; pub const SIG_BLOCK = 1; pub const SIG_UNBLOCK = 2; pub const SIG_SETMASK = 3; pub const SOCK_STREAM = 1; pub const SOCK_DGRAM = 2; pub const SOCK_RAW = 3; pub const SOCK_RDM = 4; pub const SOCK_SEQPACKET = 5; pub const SOCK_CLOEXEC = 0x10000000; pub const SOCK_NONBLOCK = 0x20000000; pub const SO_DEBUG = 0x00000001; pub const SO_ACCEPTCONN = 0x00000002; pub const SO_REUSEADDR = 0x00000004; pub const SO_KEEPALIVE = 0x00000008; pub const SO_DONTROUTE = 0x00000010; pub const SO_BROADCAST = 0x00000020; pub const SO_USELOOPBACK = 0x00000040; pub const SO_LINGER = 0x00000080; pub const SO_OOBINLINE = 0x00000100; pub const SO_REUSEPORT = 0x00000200; pub const SO_TIMESTAMP = 0x00000400; pub const SO_NOSIGPIPE = 0x00000800; pub const SO_ACCEPTFILTER = 0x00001000; pub const SO_BINTIME = 0x00002000; pub const SO_NO_OFFLOAD = 0x00004000; pub const SO_NO_DDP = 0x00008000; pub const SO_REUSEPORT_LB = 0x00010000; pub const SO_SNDBUF = 0x1001; pub const SO_RCVBUF = 0x1002; pub const SO_SNDLOWAT = 0x1003; pub const SO_RCVLOWAT = 0x1004; pub const SO_SNDTIMEO = 0x1005; pub const SO_RCVTIMEO = 0x1006; pub const SO_ERROR = 0x1007; pub const SO_TYPE = 0x1008; pub const SO_LABEL = 0x1009; pub const SO_PEERLABEL = 0x1010; pub const SO_LISTENQLIMIT = 0x1011; pub const SO_LISTENQLEN = 0x1012; pub const SO_LISTENINCQLEN = 0x1013; pub const SO_SETFIB = 0x1014; pub const SO_USER_COOKIE = 0x1015; pub const SO_PROTOCOL = 0x1016; pub const SO_PROTOTYPE = SO_PROTOCOL; pub const SO_TS_CLOCK = 0x1017; pub const SO_MAX_PACING_RATE = 0x1018; pub const SO_DOMAIN = 0x1019; pub const SOL_SOCKET = 0xffff; pub const PF_UNSPEC = AF_UNSPEC; pub const PF_LOCAL = AF_LOCAL; pub const PF_UNIX = PF_LOCAL; pub const PF_INET = AF_INET; pub const PF_IMPLINK = AF_IMPLINK; pub const PF_PUP = AF_PUP; pub const PF_CHAOS = AF_CHAOS; pub const PF_NETBIOS = AF_NETBIOS; pub const PF_ISO = AF_ISO; pub const PF_OSI = AF_ISO; pub const PF_ECMA = AF_ECMA; pub const PF_DATAKIT = AF_DATAKIT; pub const PF_CCITT = AF_CCITT; pub const PF_DECnet = AF_DECnet; pub const PF_DLI = AF_DLI; pub const PF_LAT = AF_LAT; pub const PF_HYLINK = AF_HYLINK; pub const PF_APPLETALK = AF_APPLETALK; pub const PF_ROUTE = AF_ROUTE; pub const PF_LINK = AF_LINK; pub const PF_XTP = pseudo_AF_XTP; pub const PF_COIP = AF_COIP; pub const PF_CNT = AF_CNT; pub const PF_SIP = AF_SIP; pub const PF_IPX = AF_IPX; pub const PF_RTIP = pseudo_AF_RTIP; pub const PF_PIP = psuedo_AF_PIP; pub const PF_ISDN = AF_ISDN; pub const PF_KEY = pseudo_AF_KEY; pub const PF_INET6 = pseudo_AF_INET6; pub const PF_NATM = AF_NATM; pub const PF_ATM = AF_ATM; pub const PF_NETGRAPH = AF_NETGRAPH; pub const PF_SLOW = AF_SLOW; pub const PF_SCLUSTER = AF_SCLUSTER; pub const PF_ARP = AF_ARP; pub const PF_BLUETOOTH = AF_BLUETOOTH; pub const PF_IEEE80211 = AF_IEEE80211; pub const PF_INET_SDP = AF_INET_SDP; pub const PF_INET6_SDP = AF_INET6_SDP; pub const PF_MAX = AF_MAX; pub const AF_UNSPEC = 0; pub const AF_UNIX = 1; pub const AF_LOCAL = AF_UNIX; pub const AF_FILE = AF_LOCAL; pub const AF_INET = 2; pub const AF_IMPLINK = 3; pub const AF_PUP = 4; pub const AF_CHAOS = 5; pub const AF_NETBIOS = 6; pub const AF_ISO = 7; pub const AF_OSI = AF_ISO; pub const AF_ECMA = 8; pub const AF_DATAKIT = 9; pub const AF_CCITT = 10; pub const AF_SNA = 11; pub const AF_DECnet = 12; pub const AF_DLI = 13; pub const AF_LAT = 14; pub const AF_HYLINK = 15; pub const AF_APPLETALK = 16; pub const AF_ROUTE = 17; pub const AF_LINK = 18; pub const pseudo_AF_XTP = 19; pub const AF_COIP = 20; pub const AF_CNT = 21; pub const pseudo_AF_RTIP = 22; pub const AF_IPX = 23; pub const AF_SIP = 24; pub const pseudo_AF_PIP = 25; pub const AF_ISDN = 26; pub const AF_E164 = AF_ISDN; pub const pseudo_AF_KEY = 27; pub const AF_INET6 = 28; pub const AF_NATM = 29; pub const AF_ATM = 30; pub const pseudo_AF_HDRCMPLT = 31; pub const AF_NETGRAPH = 32; pub const AF_SLOW = 33; pub const AF_SCLUSTER = 34; pub const AF_ARP = 35; pub const AF_BLUETOOTH = 36; pub const AF_IEEE80211 = 37; pub const AF_INET_SDP = 40; pub const AF_INET6_SDP = 42; pub const AF_MAX = 42; pub const DT_UNKNOWN = 0; pub const DT_FIFO = 1; pub const DT_CHR = 2; pub const DT_DIR = 4; pub const DT_BLK = 6; pub const DT_REG = 8; pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; /// add event to kq (implies enable) pub const EV_ADD = 0x0001; /// delete event from kq pub const EV_DELETE = 0x0002; /// enable event pub const EV_ENABLE = 0x0004; /// disable event (not reported) pub const EV_DISABLE = 0x0008; /// only report one occurrence pub const EV_ONESHOT = 0x0010; /// clear event state after reporting pub const EV_CLEAR = 0x0020; /// force immediate event output /// ... with or without EV_ERROR /// ... use KEVENT_FLAG_ERROR_EVENTS /// on syscalls supporting flags pub const EV_RECEIPT = 0x0040; /// disable event after reporting pub const EV_DISPATCH = 0x0080; pub const EVFILT_READ = -1; pub const EVFILT_WRITE = -2; /// attached to aio requests pub const EVFILT_AIO = -3; /// attached to vnodes pub const EVFILT_VNODE = -4; /// attached to struct proc pub const EVFILT_PROC = -5; /// attached to struct proc pub const EVFILT_SIGNAL = -6; /// timers pub const EVFILT_TIMER = -7; /// Process descriptors pub const EVFILT_PROCDESC = -8; /// Filesystem events pub const EVFILT_FS = -9; pub const EVFILT_LIO = -10; /// User events pub const EVFILT_USER = -11; /// Sendfile events pub const EVFILT_SENDFILE = -12; pub const EVFILT_EMPTY = -13; /// On input, NOTE_TRIGGER causes the event to be triggered for output. pub const NOTE_TRIGGER = 0x01000000; /// ignore input fflags pub const NOTE_FFNOP = 0x00000000; /// and fflags pub const NOTE_FFAND = 0x40000000; /// or fflags pub const NOTE_FFOR = 0x80000000; /// copy fflags pub const NOTE_FFCOPY = 0xc0000000; /// mask for operations pub const NOTE_FFCTRLMASK = 0xc0000000; pub const NOTE_FFLAGSMASK = 0x00ffffff; /// low water mark pub const NOTE_LOWAT = 0x00000001; /// behave like poll() pub const NOTE_FILE_POLL = 0x00000002; /// vnode was removed pub const NOTE_DELETE = 0x00000001; /// data contents changed pub const NOTE_WRITE = 0x00000002; /// size increased pub const NOTE_EXTEND = 0x00000004; /// attributes changed pub const NOTE_ATTRIB = 0x00000008; /// link count changed pub const NOTE_LINK = 0x00000010; /// vnode was renamed pub const NOTE_RENAME = 0x00000020; /// vnode access was revoked pub const NOTE_REVOKE = 0x00000040; /// vnode was opened pub const NOTE_OPEN = 0x00000080; /// file closed, fd did not allow write pub const NOTE_CLOSE = 0x00000100; /// file closed, fd did allow write pub const NOTE_CLOSE_WRITE = 0x00000200; /// file was read pub const NOTE_READ = 0x00000400; /// process exited pub const NOTE_EXIT = 0x80000000; /// process forked pub const NOTE_FORK = 0x40000000; /// process exec'd pub const NOTE_EXEC = 0x20000000; /// mask for signal & exit status pub const NOTE_PDATAMASK = 0x000fffff; pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK); /// data is seconds pub const NOTE_SECONDS = 0x00000001; /// data is milliseconds pub const NOTE_MSECONDS = 0x00000002; /// data is microseconds pub const NOTE_USECONDS = 0x00000004; /// data is nanoseconds pub const NOTE_NSECONDS = 0x00000008; /// timeout is absolute pub const NOTE_ABSTIME = 0x00000010; pub const TIOCEXCL = 0x2000740d; pub const TIOCNXCL = 0x2000740e; pub const TIOCSCTTY = 0x20007461; pub const TIOCGPGRP = 0x40047477; pub const TIOCSPGRP = 0x80047476; pub const TIOCOUTQ = 0x40047473; pub const TIOCSTI = 0x80017472; pub const TIOCGWINSZ = 0x40087468; pub const TIOCSWINSZ = 0x80087467; pub const TIOCMGET = 0x4004746a; pub const TIOCMBIS = 0x8004746c; pub const TIOCMBIC = 0x8004746b; pub const TIOCMSET = 0x8004746d; pub const FIONREAD = 0x4004667f; pub const TIOCCONS = 0x80047462; pub const TIOCPKT = 0x80047470; pub const FIONBIO = 0x8004667e; pub const TIOCNOTTY = 0x20007471; pub const TIOCSETD = 0x8004741b; pub const TIOCGETD = 0x4004741a; pub const TIOCSBRK = 0x2000747b; pub const TIOCCBRK = 0x2000747a; pub const TIOCGSID = 0x40047463; pub const TIOCGPTN = 0x4004740f; pub const TIOCSIG = 0x2004745f; pub fn WEXITSTATUS(s: u32) u32 { return (s & 0xff00) >> 8; } pub fn WTERMSIG(s: u32) u32 { return s & 0x7f; } pub fn WSTOPSIG(s: u32) u32 { return WEXITSTATUS(s); } pub fn WIFEXITED(s: u32) bool { return WTERMSIG(s) == 0; } pub fn WIFSTOPPED(s: u32) bool { return @intCast(u16, (((s & 0xffff) *% 0x10001) >> 8)) > 0x7f00; } pub fn WIFSIGNALED(s: u32) bool { return (s & 0xffff) -% 1 < 0xff; } pub const winsize = extern struct { ws_row: u16, ws_col: u16, ws_xpixel: u16, ws_ypixel: u16, }; const NSIG = 32; pub const SIG_ERR = @intToPtr(fn (i32) callconv(.C) void, maxInt(usize)); pub const SIG_DFL = @intToPtr(fn (i32) callconv(.C) void, 0); pub const SIG_IGN = @intToPtr(fn (i32) callconv(.C) void, 1); /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { /// signal handler __sigaction_u: extern union { __sa_handler: fn (i32) callconv(.C) void, __sa_sigaction: fn (i32, *__siginfo, usize) callconv(.C) void, }, /// see signal options sa_flags: u32, /// signal mask to apply sa_mask: sigset_t, }; pub const _SIG_WORDS = 4; pub const _SIG_MAXSIG = 128; pub inline fn _SIG_IDX(sig: usize) usize { return sig - 1; } pub inline fn _SIG_WORD(sig: usize) usize { return_SIG_IDX(sig) >> 5; } pub inline fn _SIG_BIT(sig: usize) usize { return 1 << (_SIG_IDX(sig) & 31); } pub inline fn _SIG_VALID(sig: usize) usize { return sig <= _SIG_MAXSIG and sig > 0; } pub const sigset_t = extern struct { __bits: [_SIG_WORDS]u32, }; pub const EPERM = 1; // Operation not permitted pub const ENOENT = 2; // No such file or directory pub const ESRCH = 3; // No such process pub const EINTR = 4; // Interrupted system call pub const EIO = 5; // Input/output error pub const ENXIO = 6; // Device not configured pub const E2BIG = 7; // Argument list too long pub const ENOEXEC = 8; // Exec format error pub const EBADF = 9; // Bad file descriptor pub const ECHILD = 10; // No child processes pub const EDEADLK = 11; // Resource deadlock avoided // 11 was EAGAIN pub const ENOMEM = 12; // Cannot allocate memory pub const EACCES = 13; // Permission denied pub const EFAULT = 14; // Bad address pub const ENOTBLK = 15; // Block device required pub const EBUSY = 16; // Device busy pub const EEXIST = 17; // File exists pub const EXDEV = 18; // Cross-device link pub const ENODEV = 19; // Operation not supported by device pub const ENOTDIR = 20; // Not a directory pub const EISDIR = 21; // Is a directory pub const EINVAL = 22; // Invalid argument pub const ENFILE = 23; // Too many open files in system pub const EMFILE = 24; // Too many open files pub const ENOTTY = 25; // Inappropriate ioctl for device pub const ETXTBSY = 26; // Text file busy pub const EFBIG = 27; // File too large pub const ENOSPC = 28; // No space left on device pub const ESPIPE = 29; // Illegal seek pub const EROFS = 30; // Read-only filesystem pub const EMLINK = 31; // Too many links pub const EPIPE = 32; // Broken pipe // math software pub const EDOM = 33; // Numerical argument out of domain pub const ERANGE = 34; // Result too large // non-blocking and interrupt i/o pub const EAGAIN = 35; // Resource temporarily unavailable pub const EWOULDBLOCK = EAGAIN; // Operation would block pub const EINPROGRESS = 36; // Operation now in progress pub const EALREADY = 37; // Operation already in progress // ipc/network software -- argument errors pub const ENOTSOCK = 38; // Socket operation on non-socket pub const EDESTADDRREQ = 39; // Destination address required pub const EMSGSIZE = 40; // Message too long pub const EPROTOTYPE = 41; // Protocol wrong type for socket pub const ENOPROTOOPT = 42; // Protocol not available pub const EPROTONOSUPPORT = 43; // Protocol not supported pub const ESOCKTNOSUPPORT = 44; // Socket type not supported pub const EOPNOTSUPP = 45; // Operation not supported pub const ENOTSUP = EOPNOTSUPP; // Operation not supported pub const EPFNOSUPPORT = 46; // Protocol family not supported pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family pub const EADDRINUSE = 48; // Address already in use pub const EADDRNOTAVAIL = 49; // Can't assign requested address // ipc/network software -- operational errors pub const ENETDOWN = 50; // Network is down pub const ENETUNREACH = 51; // Network is unreachable pub const ENETRESET = 52; // Network dropped connection on reset pub const ECONNABORTED = 53; // Software caused connection abort pub const ECONNRESET = 54; // Connection reset by peer pub const ENOBUFS = 55; // No buffer space available pub const EISCONN = 56; // Socket is already connected pub const ENOTCONN = 57; // Socket is not connected pub const ESHUTDOWN = 58; // Can't send after socket shutdown pub const ETOOMANYREFS = 59; // Too many references: can't splice pub const ETIMEDOUT = 60; // Operation timed out pub const ECONNREFUSED = 61; // Connection refused pub const ELOOP = 62; // Too many levels of symbolic links pub const ENAMETOOLONG = 63; // File name too long // should be rearranged pub const EHOSTDOWN = 64; // Host is down pub const EHOSTUNREACH = 65; // No route to host pub const ENOTEMPTY = 66; // Directory not empty // quotas & mush pub const EPROCLIM = 67; // Too many processes pub const EUSERS = 68; // Too many users pub const EDQUOT = 69; // Disc quota exceeded // Network File System pub const ESTALE = 70; // Stale NFS file handle pub const EREMOTE = 71; // Too many levels of remote in path pub const EBADRPC = 72; // RPC struct is bad pub const ERPCMISMATCH = 73; // RPC version wrong pub const EPROGUNAVAIL = 74; // RPC prog. not avail pub const EPROGMISMATCH = 75; // Program version wrong pub const EPROCUNAVAIL = 76; // Bad procedure for program pub const ENOLCK = 77; // No locks available pub const ENOSYS = 78; // Function not implemented pub const EFTYPE = 79; // Inappropriate file type or format pub const EAUTH = 80; // Authentication error pub const ENEEDAUTH = 81; // Need authenticator pub const EIDRM = 82; // Identifier removed pub const ENOMSG = 83; // No message of desired type pub const EOVERFLOW = 84; // Value too large to be stored in data type pub const ECANCELED = 85; // Operation canceled pub const EILSEQ = 86; // Illegal byte sequence pub const ENOATTR = 87; // Attribute not found pub const EDOOFUS = 88; // Programming error pub const EBADMSG = 89; // Bad message pub const EMULTIHOP = 90; // Multihop attempted pub const ENOLINK = 91; // Link has been severed pub const EPROTO = 92; // Protocol error pub const ENOTCAPABLE = 93; // Capabilities insufficient pub const ECAPMODE = 94; // Not permitted in capability mode pub const ENOTRECOVERABLE = 95; // State not recoverable pub const EOWNERDEAD = 96; // Previous owner died pub const ELAST = 96; // Must be equal largest errno pub const MINSIGSTKSZ = switch (builtin.arch) { .i386, .x86_64 => 2048, .arm, .aarch64 => 4096, else => @compileError("MINSIGSTKSZ not defined for this architecture"), }; pub const SIGSTKSZ = MINSIGSTKSZ + 32768; pub const SS_ONSTACK = 1; pub const SS_DISABLE = 4; pub const stack_t = extern struct { ss_sp: [*]u8, ss_size: isize, ss_flags: i32, }; pub const S_IFMT = 0o170000; pub const S_IFIFO = 0o010000; pub const S_IFCHR = 0o020000; pub const S_IFDIR = 0o040000; pub const S_IFBLK = 0o060000; pub const S_IFREG = 0o100000; pub const S_IFLNK = 0o120000; pub const S_IFSOCK = 0o140000; pub const S_IFWHT = 0o160000; pub const S_ISUID = 0o4000; pub const S_ISGID = 0o2000; pub const S_ISVTX = 0o1000; pub const S_IRWXU = 0o700; pub const S_IRUSR = 0o400; pub const S_IWUSR = 0o200; pub const S_IXUSR = 0o100; pub const S_IRWXG = 0o070; pub const S_IRGRP = 0o040; pub const S_IWGRP = 0o020; pub const S_IXGRP = 0o010; pub const S_IRWXO = 0o007; pub const S_IROTH = 0o004; pub const S_IWOTH = 0o002; pub const S_IXOTH = 0o001; pub fn S_ISFIFO(m: u32) bool { return m & S_IFMT == S_IFIFO; } pub fn S_ISCHR(m: u32) bool { return m & S_IFMT == S_IFCHR; } pub fn S_ISDIR(m: u32) bool { return m & S_IFMT == S_IFDIR; } pub fn S_ISBLK(m: u32) bool { return m & S_IFMT == S_IFBLK; } pub fn S_ISREG(m: u32) bool { return m & S_IFMT == S_IFREG; } pub fn S_ISLNK(m: u32) bool { return m & S_IFMT == S_IFLNK; } pub fn S_ISSOCK(m: u32) bool { return m & S_IFMT == S_IFSOCK; } pub fn S_IWHT(m: u32) bool { return m & S_IFMT == S_IFWHT; } pub const HOST_NAME_MAX = 255; /// Magic value that specify the use of the current working directory /// to determine the target of relative file paths in the openat() and /// similar syscalls. pub const AT_FDCWD = -100; /// Check access using effective user and group ID pub const AT_EACCESS = 0x0100; /// Do not follow symbolic links pub const AT_SYMLINK_NOFOLLOW = 0x0200; /// Follow symbolic link pub const AT_SYMLINK_FOLLOW = 0x0400; /// Remove directory instead of file pub const AT_REMOVEDIR = 0x0800; pub const addrinfo = extern struct { flags: i32, family: i32, socktype: i32, protocol: i32, addrlen: socklen_t, canonname: ?[*:0]u8, addr: ?*sockaddr, next: ?*addrinfo, }; /// Fail if not under dirfd pub const AT_BENEATH = 0x1000; /// dummy for IP pub const IPPROTO_IP = 0; /// control message protocol pub const IPPROTO_ICMP = 1; /// tcp pub const IPPROTO_TCP = 6; /// user datagram protocol pub const IPPROTO_UDP = 17; /// IP6 header pub const IPPROTO_IPV6 = 41; /// raw IP packet pub const IPPROTO_RAW = 255; /// IP6 hop-by-hop options pub const IPPROTO_HOPOPTS = 0; /// group mgmt protocol pub const IPPROTO_IGMP = 2; /// gateway^2 (deprecated) pub const IPPROTO_GGP = 3; /// IPv4 encapsulation pub const IPPROTO_IPV4 = 4; /// for compatibility pub const IPPROTO_IPIP = IPPROTO_IPV4; /// Stream protocol II pub const IPPROTO_ST = 7; /// exterior gateway protocol pub const IPPROTO_EGP = 8; /// private interior gateway pub const IPPROTO_PIGP = 9; /// BBN RCC Monitoring pub const IPPROTO_RCCMON = 10; /// network voice protocol pub const IPPROTO_NVPII = 11; /// pup pub const IPPROTO_PUP = 12; /// Argus pub const IPPROTO_ARGUS = 13; /// EMCON pub const IPPROTO_EMCON = 14; /// Cross Net Debugger pub const IPPROTO_XNET = 15; /// Chaos pub const IPPROTO_CHAOS = 16; /// Multiplexing pub const IPPROTO_MUX = 18; /// DCN Measurement Subsystems pub const IPPROTO_MEAS = 19; /// Host Monitoring pub const IPPROTO_HMP = 20; /// Packet Radio Measurement pub const IPPROTO_PRM = 21; /// xns idp pub const IPPROTO_IDP = 22; /// Trunk-1 pub const IPPROTO_TRUNK1 = 23; /// Trunk-2 pub const IPPROTO_TRUNK2 = 24; /// Leaf-1 pub const IPPROTO_LEAF1 = 25; /// Leaf-2 pub const IPPROTO_LEAF2 = 26; /// Reliable Data pub const IPPROTO_RDP = 27; /// Reliable Transaction pub const IPPROTO_IRTP = 28; /// tp-4 w/ class negotiation pub const IPPROTO_TP = 29; /// Bulk Data Transfer pub const IPPROTO_BLT = 30; /// Network Services pub const IPPROTO_NSP = 31; /// Merit Internodal pub const IPPROTO_INP = 32; /// Datagram Congestion Control Protocol pub const IPPROTO_DCCP = 33; /// Third Party Connect pub const IPPROTO_3PC = 34; /// InterDomain Policy Routing pub const IPPROTO_IDPR = 35; /// XTP pub const IPPROTO_XTP = 36; /// Datagram Delivery pub const IPPROTO_DDP = 37; /// Control Message Transport pub const IPPROTO_CMTP = 38; /// TP++ Transport pub const IPPROTO_TPXX = 39; /// IL transport protocol pub const IPPROTO_IL = 40; /// Source Demand Routing pub const IPPROTO_SDRP = 42; /// IP6 routing header pub const IPPROTO_ROUTING = 43; /// IP6 fragmentation header pub const IPPROTO_FRAGMENT = 44; /// InterDomain Routing pub const IPPROTO_IDRP = 45; /// resource reservation pub const IPPROTO_RSVP = 46; /// General Routing Encap. pub const IPPROTO_GRE = 47; /// Mobile Host Routing pub const IPPROTO_MHRP = 48; /// BHA pub const IPPROTO_BHA = 49; /// IP6 Encap Sec. Payload pub const IPPROTO_ESP = 50; /// IP6 Auth Header pub const IPPROTO_AH = 51; /// Integ. Net Layer Security pub const IPPROTO_INLSP = 52; /// IP with encryption pub const IPPROTO_SWIPE = 53; /// Next Hop Resolution pub const IPPROTO_NHRP = 54; /// IP Mobility pub const IPPROTO_MOBILE = 55; /// Transport Layer Security pub const IPPROTO_TLSP = 56; /// SKIP pub const IPPROTO_SKIP = 57; /// ICMP6 pub const IPPROTO_ICMPV6 = 58; /// IP6 no next header pub const IPPROTO_NONE = 59; /// IP6 destination option pub const IPPROTO_DSTOPTS = 60; /// any host internal protocol pub const IPPROTO_AHIP = 61; /// CFTP pub const IPPROTO_CFTP = 62; /// "hello" routing protocol pub const IPPROTO_HELLO = 63; /// SATNET/Backroom EXPAK pub const IPPROTO_SATEXPAK = 64; /// Kryptolan pub const IPPROTO_KRYPTOLAN = 65; /// Remote Virtual Disk pub const IPPROTO_RVD = 66; /// Pluribus Packet Core pub const IPPROTO_IPPC = 67; /// Any distributed FS pub const IPPROTO_ADFS = 68; /// Satnet Monitoring pub const IPPROTO_SATMON = 69; /// VISA Protocol pub const IPPROTO_VISA = 70; /// Packet Core Utility pub const IPPROTO_IPCV = 71; /// Comp. Prot. Net. Executive pub const IPPROTO_CPNX = 72; /// Comp. Prot. HeartBeat pub const IPPROTO_CPHB = 73; /// Wang Span Network pub const IPPROTO_WSN = 74; /// Packet Video Protocol pub const IPPROTO_PVP = 75; /// BackRoom SATNET Monitoring pub const IPPROTO_BRSATMON = 76; /// Sun net disk proto (temp.) pub const IPPROTO_ND = 77; /// WIDEBAND Monitoring pub const IPPROTO_WBMON = 78; /// WIDEBAND EXPAK pub const IPPROTO_WBEXPAK = 79; /// ISO cnlp pub const IPPROTO_EON = 80; /// VMTP pub const IPPROTO_VMTP = 81; /// Secure VMTP pub const IPPROTO_SVMTP = 82; /// Banyon VINES pub const IPPROTO_VINES = 83; /// TTP pub const IPPROTO_TTP = 84; /// NSFNET-IGP pub const IPPROTO_IGP = 85; /// dissimilar gateway prot. pub const IPPROTO_DGP = 86; /// TCF pub const IPPROTO_TCF = 87; /// Cisco/GXS IGRP pub const IPPROTO_IGRP = 88; /// OSPFIGP pub const IPPROTO_OSPFIGP = 89; /// Strite RPC protocol pub const IPPROTO_SRPC = 90; /// Locus Address Resoloution pub const IPPROTO_LARP = 91; /// Multicast Transport pub const IPPROTO_MTP = 92; /// AX.25 Frames pub const IPPROTO_AX25 = 93; /// IP encapsulated in IP pub const IPPROTO_IPEIP = 94; /// Mobile Int.ing control pub const IPPROTO_MICP = 95; /// Semaphore Comm. security pub const IPPROTO_SCCSP = 96; /// Ethernet IP encapsulation pub const IPPROTO_ETHERIP = 97; /// encapsulation header pub const IPPROTO_ENCAP = 98; /// any private encr. scheme pub const IPPROTO_APES = 99; /// GMTP pub const IPPROTO_GMTP = 100; /// payload compression (IPComp) pub const IPPROTO_IPCOMP = 108; /// SCTP pub const IPPROTO_SCTP = 132; /// IPv6 Mobility Header pub const IPPROTO_MH = 135; /// UDP-Lite pub const IPPROTO_UDPLITE = 136; /// IP6 Host Identity Protocol pub const IPPROTO_HIP = 139; /// IP6 Shim6 Protocol pub const IPPROTO_SHIM6 = 140; /// Protocol Independent Mcast pub const IPPROTO_PIM = 103; /// CARP pub const IPPROTO_CARP = 112; /// PGM pub const IPPROTO_PGM = 113; /// MPLS-in-IP pub const IPPROTO_MPLS = 137; /// PFSYNC pub const IPPROTO_PFSYNC = 240; /// Reserved pub const IPPROTO_RESERVED_253 = 253; /// Reserved pub const IPPROTO_RESERVED_254 = 254; pub const rlimit_resource = extern enum(c_int) { CPU = 0, FSIZE = 1, DATA = 2, STACK = 3, CORE = 4, RSS = 5, MEMLOCK = 6, NPROC = 7, NOFILE = 8, SBSIZE = 9, VMEM = 10, AS = 10, NPTS = 11, SWAP = 12, KQUEUES = 13, UMTXP = 14, _, }; pub const rlim_t = i64; /// No limit pub const RLIM_INFINITY: rlim_t = (1 << 63) - 1; pub const RLIM_SAVED_MAX = RLIM_INFINITY; pub const RLIM_SAVED_CUR = RLIM_INFINITY; pub const rlimit = extern struct { /// Soft limit cur: rlim_t, /// Hard limit max: rlim_t, }; pub const SHUT_RD = 0; pub const SHUT_WR = 1; pub const SHUT_RDWR = 2;
lib/std/os/bits/freebsd.zig
const std = @import("std"); const fmt = std.fmt; /// Group operations over Edwards25519. pub const Ristretto255 = struct { /// The underlying elliptic curve. pub const Curve = @import("edwards25519.zig").Edwards25519; /// The underlying prime field. pub const Fe = Curve.Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = Curve.scalar; /// Length in byte of an encoded element. pub const encoded_length: usize = 32; p: Curve, fn sqrtRatioM1(u: Fe, v: Fe) struct { ratio_is_square: u32, root: Fe } { const v3 = v.sq().mul(v); // v^3 var x = v3.sq().mul(u).mul(v).pow2523().mul(v3).mul(u); // uv^3(uv^7)^((q-5)/8) const vxx = x.sq().mul(v); // vx^2 const m_root_check = vxx.sub(u); // vx^2-u const p_root_check = vxx.add(u); // vx^2+u const f_root_check = u.mul(Fe.sqrtm1).add(vxx); // vx^2+u*sqrt(-1) const has_m_root = m_root_check.isZero(); const has_p_root = p_root_check.isZero(); const has_f_root = f_root_check.isZero(); const x_sqrtm1 = x.mul(Fe.sqrtm1); // x*sqrt(-1) x.cMov(x_sqrtm1, @boolToInt(has_p_root) | @boolToInt(has_f_root)); return .{ .ratio_is_square = @boolToInt(has_m_root) | @boolToInt(has_p_root), .root = x.abs() }; } fn rejectNonCanonical(s: [encoded_length]u8) !void { if ((s[0] & 1) != 0) { return error.NonCanonical; } try Fe.rejectNonCanonical(s, false); } /// Reject the neutral element. pub inline fn rejectIdentity(p: Ristretto255) !void { return p.p.rejectIdentity(); } /// The base point (Ristretto is a curve in desguise). pub const basePoint = Ristretto255{ .p = Curve.basePoint }; /// Decode a Ristretto255 representative. pub fn fromBytes(s: [encoded_length]u8) !Ristretto255 { try rejectNonCanonical(s); const s_ = Fe.fromBytes(s); const ss = s_.sq(); // s^2 const u1_ = Fe.one.sub(ss); // (1-s^2) const u1u1 = u1_.sq(); // (1-s^2)^2 const u2_ = Fe.one.add(ss); // (1+s^2) const u2u2 = u2_.sq(); // (1+s^2)^2 const v = Fe.edwards25519d.mul(u1u1).neg().sub(u2u2); // -(d*u1^2)-u2^2 const v_u2u2 = v.mul(u2u2); // v*u2^2 const inv_sqrt = sqrtRatioM1(Fe.one, v_u2u2); var x = inv_sqrt.root.mul(u2_); const y = inv_sqrt.root.mul(x).mul(v).mul(u1_); x = x.mul(s_); x = x.add(x).abs(); const t = x.mul(y); if ((1 - inv_sqrt.ratio_is_square) | @boolToInt(t.isNegative()) | @boolToInt(y.isZero()) != 0) { return error.InvalidEncoding; } const p: Curve = .{ .x = x, .y = y, .z = Fe.one, .t = t, }; return Ristretto255{ .p = p }; } /// Encode to a Ristretto255 representative. pub fn toBytes(e: Ristretto255) [encoded_length]u8 { const p = &e.p; var u1_ = p.z.add(p.y); // Z+Y const zmy = p.z.sub(p.y); // Z-Y u1_ = u1_.mul(zmy); // (Z+Y)*(Z-Y) const u2_ = p.x.mul(p.y); // X*Y const u1_u2u2 = u2_.sq().mul(u1_); // u1*u2^2 const inv_sqrt = sqrtRatioM1(Fe.one, u1_u2u2); const den1 = inv_sqrt.root.mul(u1_); const den2 = inv_sqrt.root.mul(u2_); const z_inv = den1.mul(den2).mul(p.t); // den1*den2*T const ix = p.x.mul(Fe.sqrtm1); // X*sqrt(-1) const iy = p.y.mul(Fe.sqrtm1); // Y*sqrt(-1) const eden = den1.mul(Fe.edwards25519sqrtamd); // den1/sqrt(a-d) const t_z_inv = p.t.mul(z_inv); // T*z_inv const rotate = @boolToInt(t_z_inv.isNegative()); var x = p.x; var y = p.y; var den_inv = den2; x.cMov(iy, rotate); y.cMov(ix, rotate); den_inv.cMov(eden, rotate); const x_z_inv = x.mul(z_inv); const yneg = y.neg(); y.cMov(yneg, @boolToInt(x_z_inv.isNegative())); return p.z.sub(y).mul(den_inv).abs().toBytes(); } fn elligator(t: Fe) Curve { const r = t.sq().mul(Fe.sqrtm1); // sqrt(-1)*t^2 const u = r.add(Fe.one).mul(Fe.edwards25519eonemsqd); // (r+1)*(1-d^2) var c = comptime Fe.one.neg(); // -1 const v = c.sub(r.mul(Fe.edwards25519d)).mul(r.add(Fe.edwards25519d)); // (c-r*d)*(r+d) const ratio_sqrt = sqrtRatioM1(u, v); const wasnt_square = 1 - ratio_sqrt.ratio_is_square; var s = ratio_sqrt.root; const s_prime = s.mul(t).abs().neg(); // -|s*t| s.cMov(s_prime, wasnt_square); c.cMov(r, wasnt_square); const n = r.sub(Fe.one).mul(c).mul(Fe.edwards25519sqdmone).sub(v); // c*(r-1)*(d-1)^2-v const w0 = s.add(s).mul(v); // 2s*v const w1 = n.mul(Fe.edwards25519sqrtadm1); // n*sqrt(ad-1) const ss = s.sq(); // s^2 const w2 = Fe.one.sub(ss); // 1-s^2 const w3 = Fe.one.add(ss); // 1+s^2 return .{ .x = w0.mul(w3), .y = w2.mul(w1), .z = w1.mul(w3), .t = w0.mul(w2) }; } /// Map a 64-bit string into a Ristretto255 group element pub fn fromUniform(h: [64]u8) Ristretto255 { const p0 = elligator(Fe.fromBytes(h[0..32].*)); const p1 = elligator(Fe.fromBytes(h[32..64].*)); return Ristretto255{ .p = p0.add(p1) }; } /// Double a Ristretto255 element. pub inline fn dbl(p: Ristretto255) Ristretto255 { return .{ .p = p.p.dbl() }; } /// Add two Ristretto255 elements. pub inline fn add(p: Ristretto255, q: Ristretto255) Ristretto255 { return .{ .p = p.p.add(q.p) }; } /// Multiply a Ristretto255 element with a scalar. /// Return error.WeakPublicKey if the resulting element is /// the identity element. pub inline fn mul(p: Ristretto255, s: [encoded_length]u8) !Ristretto255 { return Ristretto255{ .p = try p.p.mul(s) }; } /// Return true if two Ristretto255 elements are equivalent pub fn equivalent(p: Ristretto255, q: Ristretto255) bool { const p_ = &p.p; const q_ = &q.p; const a = p_.x.mul(q_.y).equivalent(p_.y.mul(q_.x)); const b = p_.y.mul(q_.y).equivalent(p_.x.mul(q_.x)); return (@boolToInt(a) | @boolToInt(b)) != 0; } }; test "ristretto255" { const p = Ristretto255.basePoint; var buf: [256]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{p.toBytes()}), "E2F2AE0A6ABC4E71A884A961C500515F58E30B6AA582DD8DB6A65945E08D2D76"); var r: [Ristretto255.encoded_length]u8 = undefined; try fmt.hexToBytes(r[0..], "6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919"); var q = try Ristretto255.fromBytes(r); q = q.dbl().add(p); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{q.toBytes()}), "E882B131016B52C1D3337080187CF768423EFCCBB517BB495AB812C4160FF44E"); const s = [_]u8{15} ++ [_]u8{0} ** 31; const w = try p.mul(s); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{w.toBytes()}), "E0C418F7C8D9C4CDD7395B93EA124F3AD99021BB681DFC3302A9D99A2E53E64E"); std.testing.expect(p.dbl().dbl().dbl().dbl().equivalent(w.add(p))); const h = [_]u8{69} ** 32 ++ [_]u8{42} ** 32; const ph = Ristretto255.fromUniform(h); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{ph.toBytes()}), "DCCA54E037A4311EFBEEF413ACD21D35276518970B7A61DC88F8587B493D5E19"); }
lib/std/crypto/25519/ristretto255.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; const testing = std.testing; const leb = std.leb; const mem = std.mem; const wasm = std.wasm; const log = std.log.scoped(.codegen); const Module = @import("../../Module.zig"); const Decl = Module.Decl; const Type = @import("../../type.zig").Type; const Value = @import("../../value.zig").Value; const Compilation = @import("../../Compilation.zig"); const LazySrcLoc = Module.LazySrcLoc; const link = @import("../../link.zig"); const TypedValue = @import("../../TypedValue.zig"); const Air = @import("../../Air.zig"); const Liveness = @import("../../Liveness.zig"); const Mir = @import("Mir.zig"); const Emit = @import("Emit.zig"); /// Wasm Value, created when generating an instruction const WValue = union(enum) { /// May be referenced but is unused none: void, /// Index of the local variable local: u32, /// An immediate 32bit value imm32: u32, /// An immediate 64bit value imm64: u64, /// A constant 32bit float value float32: f32, /// A constant 64bit float value float64: f64, /// A value that represents a pointer to the data section /// Note: The value contains the symbol index, rather than the actual address /// as we use this to perform the relocation. memory: u32, /// Represents a function pointer /// In wasm function pointers are indexes into a function table, /// rather than an address in the data section. function_index: u32, }; /// Wasm ops, but without input/output/signedness information /// Used for `buildOpcode` const Op = enum { @"unreachable", nop, block, loop, @"if", @"else", end, br, br_if, br_table, @"return", call, call_indirect, drop, select, local_get, local_set, local_tee, global_get, global_set, load, store, memory_size, memory_grow, @"const", eqz, eq, ne, lt, gt, le, ge, clz, ctz, popcnt, add, sub, mul, div, rem, @"and", @"or", xor, shl, shr, rotl, rotr, abs, neg, ceil, floor, trunc, nearest, sqrt, min, max, copysign, wrap, convert, demote, promote, reinterpret, extend, }; /// Contains the settings needed to create an `Opcode` using `buildOpcode`. /// /// The fields correspond to the opcode name. Here is an example /// i32_trunc_f32_s /// ^ ^ ^ ^ /// | | | | /// valtype1 | | | /// = .i32 | | | /// | | | /// op | | /// = .trunc | | /// | | /// valtype2 | /// = .f32 | /// | /// width | /// = null | /// | /// signed /// = true /// /// There can be missing fields, here are some more examples: /// i64_load8_u /// --> .{ .valtype1 = .i64, .op = .load, .width = 8, signed = false } /// i32_mul /// --> .{ .valtype1 = .i32, .op = .trunc } /// nop /// --> .{ .op = .nop } const OpcodeBuildArguments = struct { /// First valtype in the opcode (usually represents the type of the output) valtype1: ?wasm.Valtype = null, /// The operation (e.g. call, unreachable, div, min, sqrt, etc.) op: Op, /// Width of the operation (e.g. 8 for i32_load8_s, 16 for i64_extend16_i32_s) width: ?u8 = null, /// Second valtype in the opcode name (usually represents the type of the input) valtype2: ?wasm.Valtype = null, /// Signedness of the op signedness: ?std.builtin.Signedness = null, }; /// Helper function that builds an Opcode given the arguments needed fn buildOpcode(args: OpcodeBuildArguments) wasm.Opcode { switch (args.op) { .@"unreachable" => return .@"unreachable", .nop => return .nop, .block => return .block, .loop => return .loop, .@"if" => return .@"if", .@"else" => return .@"else", .end => return .end, .br => return .br, .br_if => return .br_if, .br_table => return .br_table, .@"return" => return .@"return", .call => return .call, .call_indirect => return .call_indirect, .drop => return .drop, .select => return .select, .local_get => return .local_get, .local_set => return .local_set, .local_tee => return .local_tee, .global_get => return .global_get, .global_set => return .global_set, .load => if (args.width) |width| switch (width) { 8 => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_load8_s else return .i32_load8_u, .i64 => if (args.signedness.? == .signed) return .i64_load8_s else return .i64_load8_u, .f32, .f64 => unreachable, }, 16 => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_load16_s else return .i32_load16_u, .i64 => if (args.signedness.? == .signed) return .i64_load16_s else return .i64_load16_u, .f32, .f64 => unreachable, }, 32 => switch (args.valtype1.?) { .i64 => if (args.signedness.? == .signed) return .i64_load32_s else return .i64_load32_u, .i32 => return .i32_load, .f32 => return .f32_load, .f64 => unreachable, }, 64 => switch (args.valtype1.?) { .i64 => return .i64_load, .f64 => return .f64_load, else => unreachable, }, else => unreachable, } else switch (args.valtype1.?) { .i32 => return .i32_load, .i64 => return .i64_load, .f32 => return .f32_load, .f64 => return .f64_load, }, .store => if (args.width) |width| { switch (width) { 8 => switch (args.valtype1.?) { .i32 => return .i32_store8, .i64 => return .i64_store8, .f32, .f64 => unreachable, }, 16 => switch (args.valtype1.?) { .i32 => return .i32_store16, .i64 => return .i64_store16, .f32, .f64 => unreachable, }, 32 => switch (args.valtype1.?) { .i64 => return .i64_store32, .i32 => return .i32_store, .f32 => return .f32_store, .f64 => unreachable, }, 64 => switch (args.valtype1.?) { .i64 => return .i64_store, .f64 => return .f64_store, else => unreachable, }, else => unreachable, } } else { switch (args.valtype1.?) { .i32 => return .i32_store, .i64 => return .i64_store, .f32 => return .f32_store, .f64 => return .f64_store, } }, .memory_size => return .memory_size, .memory_grow => return .memory_grow, .@"const" => switch (args.valtype1.?) { .i32 => return .i32_const, .i64 => return .i64_const, .f32 => return .f32_const, .f64 => return .f64_const, }, .eqz => switch (args.valtype1.?) { .i32 => return .i32_eqz, .i64 => return .i64_eqz, .f32, .f64 => unreachable, }, .eq => switch (args.valtype1.?) { .i32 => return .i32_eq, .i64 => return .i64_eq, .f32 => return .f32_eq, .f64 => return .f64_eq, }, .ne => switch (args.valtype1.?) { .i32 => return .i32_ne, .i64 => return .i64_ne, .f32 => return .f32_ne, .f64 => return .f64_ne, }, .lt => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_lt_s else return .i32_lt_u, .i64 => if (args.signedness.? == .signed) return .i64_lt_s else return .i64_lt_u, .f32 => return .f32_lt, .f64 => return .f64_lt, }, .gt => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_gt_s else return .i32_gt_u, .i64 => if (args.signedness.? == .signed) return .i64_gt_s else return .i64_gt_u, .f32 => return .f32_gt, .f64 => return .f64_gt, }, .le => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_le_s else return .i32_le_u, .i64 => if (args.signedness.? == .signed) return .i64_le_s else return .i64_le_u, .f32 => return .f32_le, .f64 => return .f64_le, }, .ge => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_ge_s else return .i32_ge_u, .i64 => if (args.signedness.? == .signed) return .i64_ge_s else return .i64_ge_u, .f32 => return .f32_ge, .f64 => return .f64_ge, }, .clz => switch (args.valtype1.?) { .i32 => return .i32_clz, .i64 => return .i64_clz, .f32, .f64 => unreachable, }, .ctz => switch (args.valtype1.?) { .i32 => return .i32_ctz, .i64 => return .i64_ctz, .f32, .f64 => unreachable, }, .popcnt => switch (args.valtype1.?) { .i32 => return .i32_popcnt, .i64 => return .i64_popcnt, .f32, .f64 => unreachable, }, .add => switch (args.valtype1.?) { .i32 => return .i32_add, .i64 => return .i64_add, .f32 => return .f32_add, .f64 => return .f64_add, }, .sub => switch (args.valtype1.?) { .i32 => return .i32_sub, .i64 => return .i64_sub, .f32 => return .f32_sub, .f64 => return .f64_sub, }, .mul => switch (args.valtype1.?) { .i32 => return .i32_mul, .i64 => return .i64_mul, .f32 => return .f32_mul, .f64 => return .f64_mul, }, .div => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_div_s else return .i32_div_u, .i64 => if (args.signedness.? == .signed) return .i64_div_s else return .i64_div_u, .f32 => return .f32_div, .f64 => return .f64_div, }, .rem => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_rem_s else return .i32_rem_u, .i64 => if (args.signedness.? == .signed) return .i64_rem_s else return .i64_rem_u, .f32, .f64 => unreachable, }, .@"and" => switch (args.valtype1.?) { .i32 => return .i32_and, .i64 => return .i64_and, .f32, .f64 => unreachable, }, .@"or" => switch (args.valtype1.?) { .i32 => return .i32_or, .i64 => return .i64_or, .f32, .f64 => unreachable, }, .xor => switch (args.valtype1.?) { .i32 => return .i32_xor, .i64 => return .i64_xor, .f32, .f64 => unreachable, }, .shl => switch (args.valtype1.?) { .i32 => return .i32_shl, .i64 => return .i64_shl, .f32, .f64 => unreachable, }, .shr => switch (args.valtype1.?) { .i32 => if (args.signedness.? == .signed) return .i32_shr_s else return .i32_shr_u, .i64 => if (args.signedness.? == .signed) return .i64_shr_s else return .i64_shr_u, .f32, .f64 => unreachable, }, .rotl => switch (args.valtype1.?) { .i32 => return .i32_rotl, .i64 => return .i64_rotl, .f32, .f64 => unreachable, }, .rotr => switch (args.valtype1.?) { .i32 => return .i32_rotr, .i64 => return .i64_rotr, .f32, .f64 => unreachable, }, .abs => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_abs, .f64 => return .f64_abs, }, .neg => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_neg, .f64 => return .f64_neg, }, .ceil => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_ceil, .f64 => return .f64_ceil, }, .floor => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_floor, .f64 => return .f64_floor, }, .trunc => switch (args.valtype1.?) { .i32 => switch (args.valtype2.?) { .i32 => unreachable, .i64 => unreachable, .f32 => if (args.signedness.? == .signed) return .i32_trunc_f32_s else return .i32_trunc_f32_u, .f64 => if (args.signedness.? == .signed) return .i32_trunc_f64_s else return .i32_trunc_f64_u, }, .i64 => unreachable, .f32 => return .f32_trunc, .f64 => return .f64_trunc, }, .nearest => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_nearest, .f64 => return .f64_nearest, }, .sqrt => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_sqrt, .f64 => return .f64_sqrt, }, .min => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_min, .f64 => return .f64_min, }, .max => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_max, .f64 => return .f64_max, }, .copysign => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => return .f32_copysign, .f64 => return .f64_copysign, }, .wrap => switch (args.valtype1.?) { .i32 => switch (args.valtype2.?) { .i32 => unreachable, .i64 => return .i32_wrap_i64, .f32, .f64 => unreachable, }, .i64, .f32, .f64 => unreachable, }, .convert => switch (args.valtype1.?) { .i32, .i64 => unreachable, .f32 => switch (args.valtype2.?) { .i32 => if (args.signedness.? == .signed) return .f32_convert_i32_s else return .f32_convert_i32_u, .i64 => if (args.signedness.? == .signed) return .f32_convert_i64_s else return .f32_convert_i64_u, .f32, .f64 => unreachable, }, .f64 => switch (args.valtype2.?) { .i32 => if (args.signedness.? == .signed) return .f64_convert_i32_s else return .f64_convert_i32_u, .i64 => if (args.signedness.? == .signed) return .f64_convert_i64_s else return .f64_convert_i64_u, .f32, .f64 => unreachable, }, }, .demote => if (args.valtype1.? == .f32 and args.valtype2.? == .f64) return .f32_demote_f64 else unreachable, .promote => if (args.valtype1.? == .f64 and args.valtype2.? == .f32) return .f64_promote_f32 else unreachable, .reinterpret => switch (args.valtype1.?) { .i32 => if (args.valtype2.? == .f32) return .i32_reinterpret_f32 else unreachable, .i64 => if (args.valtype2.? == .f64) return .i64_reinterpret_f64 else unreachable, .f32 => if (args.valtype2.? == .i32) return .f32_reinterpret_i32 else unreachable, .f64 => if (args.valtype2.? == .i64) return .f64_reinterpret_i64 else unreachable, }, .extend => switch (args.valtype1.?) { .i32 => switch (args.width.?) { 8 => if (args.signedness.? == .signed) return .i32_extend8_s else unreachable, 16 => if (args.signedness.? == .signed) return .i32_extend16_s else unreachable, else => unreachable, }, .i64 => switch (args.width.?) { 8 => if (args.signedness.? == .signed) return .i64_extend8_s else unreachable, 16 => if (args.signedness.? == .signed) return .i64_extend16_s else unreachable, 32 => if (args.signedness.? == .signed) return .i64_extend32_s else unreachable, else => unreachable, }, .f32, .f64 => unreachable, }, } } test "Wasm - buildOpcode" { // Make sure buildOpcode is referenced, and test some examples const i32_const = buildOpcode(.{ .op = .@"const", .valtype1 = .i32 }); const end = buildOpcode(.{ .op = .end }); const local_get = buildOpcode(.{ .op = .local_get }); const i64_extend32_s = buildOpcode(.{ .op = .extend, .valtype1 = .i64, .width = 32, .signedness = .signed }); const f64_reinterpret_i64 = buildOpcode(.{ .op = .reinterpret, .valtype1 = .f64, .valtype2 = .i64 }); try testing.expectEqual(@as(wasm.Opcode, .i32_const), i32_const); try testing.expectEqual(@as(wasm.Opcode, .end), end); try testing.expectEqual(@as(wasm.Opcode, .local_get), local_get); try testing.expectEqual(@as(wasm.Opcode, .i64_extend32_s), i64_extend32_s); try testing.expectEqual(@as(wasm.Opcode, .f64_reinterpret_i64), f64_reinterpret_i64); } pub const Result = union(enum) { /// The codegen bytes have been appended to `Context.code` appended: void, /// The data is managed externally and are part of the `Result` externally_managed: []const u8, }; /// Hashmap to store generated `WValue` for each `Air.Inst.Ref` pub const ValueTable = std.AutoHashMapUnmanaged(Air.Inst.Ref, WValue); const Self = @This(); /// Reference to the function declaration the code /// section belongs to decl: *Decl, air: Air, liveness: Liveness, gpa: mem.Allocator, /// Table to save `WValue`'s generated by an `Air.Inst` values: ValueTable, /// Mapping from Air.Inst.Index to block ids blocks: std.AutoArrayHashMapUnmanaged(Air.Inst.Index, struct { label: u32, value: WValue, }) = .{}, /// `bytes` contains the wasm bytecode belonging to the 'code' section. code: ArrayList(u8), /// The index the next local generated will have /// NOTE: arguments share the index with locals therefore the first variable /// will have the index that comes after the last argument's index local_index: u32 = 0, /// The index of the current argument. /// Used to track which argument is being referenced in `airArg`. arg_index: u32 = 0, /// If codegen fails, an error messages will be allocated and saved in `err_msg` err_msg: *Module.ErrorMsg, /// Current block depth. Used to calculate the relative difference between a break /// and block block_depth: u32 = 0, /// List of all locals' types generated throughout this declaration /// used to emit locals count at start of 'code' section. locals: std.ArrayListUnmanaged(u8), /// The Target we're emitting (used to call intInfo) target: std.Target, /// Represents the wasm binary file that is being linked. bin_file: *link.File.Wasm, /// Reference to the Module that this decl is part of. /// Used to find the error value. module: *Module, /// List of MIR Instructions mir_instructions: std.MultiArrayList(Mir.Inst) = .{}, /// Contains extra data for MIR mir_extra: std.ArrayListUnmanaged(u32) = .{}, /// When a function is executing, we store the the current stack pointer's value within this local. /// This value is then used to restore the stack pointer to the original value at the return of the function. initial_stack_value: WValue = .none, /// Arguments of this function declaration /// This will be set after `resolveCallingConventionValues` args: []WValue = &.{}, /// This will only be `.none` if the function returns void, or returns an immediate. /// When it returns a pointer to the stack, the `.local` tag will be active and must be populated /// before this function returns its execution to the caller. return_value: WValue = .none, const InnerError = error{ OutOfMemory, /// An error occured when trying to lower AIR to MIR. CodegenFail, /// Can occur when dereferencing a pointer that points to a `Decl` of which the analysis has failed AnalysisFail, /// Compiler implementation could not handle a large integer. Overflow, }; pub fn deinit(self: *Self) void { self.values.deinit(self.gpa); self.blocks.deinit(self.gpa); self.locals.deinit(self.gpa); self.mir_instructions.deinit(self.gpa); self.mir_extra.deinit(self.gpa); self.code.deinit(); self.* = undefined; } /// Sets `err_msg` on `CodeGen` and returns `error.CodegenFail` which is caught in link/Wasm.zig fn fail(self: *Self, comptime fmt: []const u8, args: anytype) InnerError { const src: LazySrcLoc = .{ .node_offset = 0 }; const src_loc = src.toSrcLoc(self.decl); self.err_msg = try Module.ErrorMsg.create(self.gpa, src_loc, fmt, args); return error.CodegenFail; } /// Resolves the `WValue` for the given instruction `inst` /// When the given instruction has a `Value`, it returns a constant instead fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!WValue { const gop = try self.values.getOrPut(self.gpa, ref); if (gop.found_existing) return gop.value_ptr.*; // when we did not find an existing instruction, it // means we must generate it from a constant. const val = self.air.value(ref).?; const ty = self.air.typeOf(ref); if (!ty.hasRuntimeBits() and !ty.isInt()) return WValue{ .none = {} }; // When we need to pass the value by reference (such as a struct), we will // leverage `genTypedValue` to lower the constant to bytes and emit it // to the 'rodata' section. We then return the index into the section as `WValue`. // // In the other cases, we will simply lower the constant to a value that fits // into a single local (such as a pointer, integer, bool, etc). const result = if (isByRef(ty, self.target)) blk: { var value_bytes = std.ArrayList(u8).init(self.gpa); defer value_bytes.deinit(); var decl_gen: DeclGen = .{ .bin_file = self.bin_file, .decl = self.decl, .err_msg = undefined, .gpa = self.gpa, .module = self.module, .code = &value_bytes, .symbol_index = try self.bin_file.createLocalSymbol(self.decl, ty), }; const result = decl_gen.genTypedValue(ty, val) catch |err| { // When a codegen error occured, take ownership of the error message if (err == error.CodegenFail) { self.err_msg = decl_gen.err_msg; } return err; }; const code = switch (result) { .appended => value_bytes.items, .externally_managed => |data| data, }; try self.bin_file.updateLocalSymbolCode(self.decl, decl_gen.symbol_index, code); break :blk WValue{ .memory = decl_gen.symbol_index }; } else try self.lowerConstant(val, ty); gop.value_ptr.* = result; return result; } /// Appends a MIR instruction and returns its index within the list of instructions fn addInst(self: *Self, inst: Mir.Inst) error{OutOfMemory}!void { try self.mir_instructions.append(self.gpa, inst); } /// Inserts a Mir instruction at the given `offset`. /// Asserts offset is within bound. fn addInstAt(self: *Self, offset: usize, inst: Mir.Inst) error{OutOfMemory}!void { try self.mir_instructions.ensureUnusedCapacity(self.gpa, 1); self.mir_instructions.insertAssumeCapacity(offset, inst); } fn addTag(self: *Self, tag: Mir.Inst.Tag) error{OutOfMemory}!void { try self.addInst(.{ .tag = tag, .data = .{ .tag = {} } }); } fn addExtended(self: *Self, opcode: wasm.PrefixedOpcode) error{OutOfMemory}!void { try self.addInst(.{ .tag = .extended, .secondary = @enumToInt(opcode), .data = .{ .tag = {} } }); } fn addLabel(self: *Self, tag: Mir.Inst.Tag, label: u32) error{OutOfMemory}!void { try self.addInst(.{ .tag = tag, .data = .{ .label = label } }); } fn addImm32(self: *Self, imm: i32) error{OutOfMemory}!void { try self.addInst(.{ .tag = .i32_const, .data = .{ .imm32 = imm } }); } /// Accepts an unsigned 64bit integer rather than a signed integer to /// prevent us from having to bitcast multiple times as most values /// within codegen are represented as unsigned rather than signed. fn addImm64(self: *Self, imm: u64) error{OutOfMemory}!void { const extra_index = try self.addExtra(Mir.Imm64.fromU64(imm)); try self.addInst(.{ .tag = .i64_const, .data = .{ .payload = extra_index } }); } fn addFloat64(self: *Self, float: f64) error{OutOfMemory}!void { const extra_index = try self.addExtra(Mir.Float64.fromFloat64(float)); try self.addInst(.{ .tag = .f64_const, .data = .{ .payload = extra_index } }); } /// Inserts an instruction to load/store from/to wasm's linear memory dependent on the given `tag`. fn addMemArg(self: *Self, tag: Mir.Inst.Tag, mem_arg: Mir.MemArg) error{OutOfMemory}!void { const extra_index = try self.addExtra(mem_arg); try self.addInst(.{ .tag = tag, .data = .{ .payload = extra_index } }); } /// Appends entries to `mir_extra` based on the type of `extra`. /// Returns the index into `mir_extra` fn addExtra(self: *Self, extra: anytype) error{OutOfMemory}!u32 { const fields = std.meta.fields(@TypeOf(extra)); try self.mir_extra.ensureUnusedCapacity(self.gpa, fields.len); return self.addExtraAssumeCapacity(extra); } /// Appends entries to `mir_extra` based on the type of `extra`. /// Returns the index into `mir_extra` fn addExtraAssumeCapacity(self: *Self, extra: anytype) error{OutOfMemory}!u32 { const fields = std.meta.fields(@TypeOf(extra)); const result = @intCast(u32, self.mir_extra.items.len); inline for (fields) |field| { self.mir_extra.appendAssumeCapacity(switch (field.field_type) { u32 => @field(extra, field.name), else => |field_type| @compileError("Unsupported field type " ++ @typeName(field_type)), }); } return result; } /// Using a given `Type`, returns the corresponding type fn typeToValtype(ty: Type, target: std.Target) wasm.Valtype { return switch (ty.zigTypeTag()) { .Float => blk: { const bits = ty.floatBits(target); if (bits == 16 or bits == 32) break :blk wasm.Valtype.f32; if (bits == 64) break :blk wasm.Valtype.f64; return wasm.Valtype.i32; // represented as pointer to stack }, .Int => blk: { const info = ty.intInfo(target); if (info.bits <= 32) break :blk wasm.Valtype.i32; if (info.bits > 32 and info.bits <= 64) break :blk wasm.Valtype.i64; break :blk wasm.Valtype.i32; // represented as pointer to stack }, .Enum => { var buf: Type.Payload.Bits = undefined; return typeToValtype(ty.intTagType(&buf), target); }, else => wasm.Valtype.i32, // all represented as reference/immediate }; } /// Using a given `Type`, returns the byte representation of its wasm value type fn genValtype(ty: Type, target: std.Target) u8 { return wasm.valtype(typeToValtype(ty, target)); } /// Using a given `Type`, returns the corresponding wasm value type /// Differently from `genValtype` this also allows `void` to create a block /// with no return type fn genBlockType(ty: Type, target: std.Target) u8 { return switch (ty.tag()) { .void, .noreturn => wasm.block_empty, else => genValtype(ty, target), }; } /// Writes the bytecode depending on the given `WValue` in `val` fn emitWValue(self: *Self, value: WValue) InnerError!void { switch (value) { .none => {}, // no-op .local => |idx| try self.addLabel(.local_get, idx), .imm32 => |val| try self.addImm32(@bitCast(i32, val)), .imm64 => |val| try self.addImm64(val), .float32 => |val| try self.addInst(.{ .tag = .f32_const, .data = .{ .float32 = val } }), .float64 => |val| try self.addFloat64(val), .memory => |ptr| try self.addLabel(.memory_address, ptr), // write sybol address and generate relocation .function_index => |index| try self.addLabel(.function_index, index), // write function index and generate relocation } } /// Creates one locals for a given `Type`. /// Returns a corresponding `Wvalue` with `local` as active tag fn allocLocal(self: *Self, ty: Type) InnerError!WValue { const initial_index = self.local_index; const valtype = genValtype(ty, self.target); try self.locals.append(self.gpa, valtype); self.local_index += 1; return WValue{ .local = initial_index }; } /// Generates a `wasm.Type` from a given function type. /// Memory is owned by the caller. fn genFunctype(gpa: Allocator, fn_ty: Type, target: std.Target) !wasm.Type { var params = std.ArrayList(wasm.Valtype).init(gpa); defer params.deinit(); var returns = std.ArrayList(wasm.Valtype).init(gpa); defer returns.deinit(); const return_type = fn_ty.fnReturnType(); const want_sret = isByRef(return_type, target); if (want_sret) { try params.append(typeToValtype(return_type, target)); } // param types if (fn_ty.fnParamLen() != 0) { const fn_params = try gpa.alloc(Type, fn_ty.fnParamLen()); defer gpa.free(fn_params); fn_ty.fnParamTypes(fn_params); for (fn_params) |param_type| { if (!param_type.hasRuntimeBits()) continue; try params.append(typeToValtype(param_type, target)); } } // return type if (!want_sret and return_type.hasRuntimeBits()) { try returns.append(typeToValtype(return_type, target)); } return wasm.Type{ .params = params.toOwnedSlice(), .returns = returns.toOwnedSlice(), }; } pub fn genFunc(self: *Self) InnerError!void { var func_type = try genFunctype(self.gpa, self.decl.ty, self.target); defer func_type.deinit(self.gpa); self.decl.fn_link.wasm.type_index = try self.bin_file.putOrGetFuncType(func_type); var cc_result = try self.resolveCallingConventionValues(self.decl.ty); defer cc_result.deinit(self.gpa); self.args = cc_result.args; self.return_value = cc_result.return_value; // Generate MIR for function body try self.genBody(self.air.getMainBody()); // In case we have a return value, but the last instruction is a noreturn (such as a while loop) // we emit an unreachable instruction to tell the stack validator that part will never be reached. if (func_type.returns.len != 0 and self.air.instructions.len > 0) { const inst = @intCast(u32, self.air.instructions.len - 1); if (self.air.typeOfIndex(inst).isNoReturn()) { try self.addTag(.@"unreachable"); } } // End of function body try self.addTag(.end); var mir: Mir = .{ .instructions = self.mir_instructions.toOwnedSlice(), .extra = self.mir_extra.toOwnedSlice(self.gpa), }; defer mir.deinit(self.gpa); var emit: Emit = .{ .mir = mir, .bin_file = &self.bin_file.base, .code = &self.code, .locals = self.locals.items, .decl = self.decl, }; emit.emitMir() catch |err| switch (err) { error.EmitFail => { self.err_msg = emit.error_msg.?; return error.CodegenFail; }, else => |e| return e, }; } pub const DeclGen = struct { /// The decl we are generating code for. decl: *Decl, /// The symbol we're generating code for. /// This can either be the symbol of the Decl itself, /// or one of its locals. symbol_index: u32, gpa: Allocator, /// A reference to the linker, that will process the decl's /// code and create any relocations it deems neccesary. bin_file: *link.File.Wasm, /// This will be set when `InnerError` has been returned. /// In any other case, this will be 'undefined'. err_msg: *Module.ErrorMsg, /// Reference to the Module that is being compiled. /// Used to find the error value of an error. module: *Module, /// The list of bytes that have been generated so far, /// can be used to calculate the offset into a section. code: *std.ArrayList(u8), /// Sets `err_msg` on `DeclGen` and returns `error.CodegenFail` which is caught in link/Wasm.zig fn fail(self: *DeclGen, comptime fmt: []const u8, args: anytype) InnerError { const src: LazySrcLoc = .{ .node_offset = 0 }; const src_loc = src.toSrcLoc(self.decl); self.err_msg = try Module.ErrorMsg.create(self.gpa, src_loc, fmt, args); return error.CodegenFail; } fn target(self: *const DeclGen) std.Target { return self.bin_file.base.options.target; } pub fn genDecl(self: *DeclGen) InnerError!Result { const decl = self.decl; assert(decl.has_tv); log.debug("gen: {s} type: {}, value: {}", .{ decl.name, decl.ty, decl.val }); if (decl.val.castTag(.function)) |func_payload| { _ = func_payload; return self.fail("TODO wasm backend genDecl function pointer", .{}); } else if (decl.val.castTag(.extern_fn)) |extern_fn| { const ext_decl = extern_fn.data; var func_type = try genFunctype(self.gpa, ext_decl.ty, self.target()); func_type.deinit(self.gpa); ext_decl.fn_link.wasm.type_index = try self.bin_file.putOrGetFuncType(func_type); return Result{ .appended = {} }; } else { const init_val = if (decl.val.castTag(.variable)) |payload| init_val: { break :init_val payload.data.init; } else decl.val; if (init_val.tag() != .unreachable_value) { return self.genTypedValue(decl.ty, init_val); } return Result{ .appended = {} }; } } /// Generates the wasm bytecode for the declaration belonging to `Context` fn genTypedValue(self: *DeclGen, ty: Type, val: Value) InnerError!Result { const writer = self.code.writer(); if (val.isUndef()) { try writer.writeByteNTimes(0xaa, @intCast(usize, ty.abiSize(self.target()))); return Result{ .appended = {} }; } switch (ty.zigTypeTag()) { .Fn => { const fn_decl = switch (val.tag()) { .extern_fn => val.castTag(.extern_fn).?.data, .function => val.castTag(.function).?.data.owner_decl, else => unreachable, }; return try self.lowerDeclRef(ty, val, fn_decl); }, .Optional => { var opt_buf: Type.Payload.ElemType = undefined; const payload_type = ty.optionalChild(&opt_buf); const is_pl = !val.isNull(); const abi_size = @intCast(usize, ty.abiSize(self.target())); const offset = abi_size - @intCast(usize, payload_type.abiSize(self.target())); if (!payload_type.hasRuntimeBits()) { try writer.writeByteNTimes(@boolToInt(is_pl), abi_size); return Result{ .appended = {} }; } if (ty.isPtrLikeOptional()) { if (val.castTag(.opt_payload)) |payload| { return self.genTypedValue(payload_type, payload.data); } else if (!val.isNull()) { return self.genTypedValue(payload_type, val); } else { try writer.writeByteNTimes(0, abi_size); return Result{ .appended = {} }; } } // `null-tag` bytes try writer.writeByteNTimes(@boolToInt(is_pl), offset); switch (try self.genTypedValue( payload_type, if (val.castTag(.opt_payload)) |pl| pl.data else Value.initTag(.undef), )) { .appended => {}, .externally_managed => |payload| try writer.writeAll(payload), } return Result{ .appended = {} }; }, .Array => switch (val.tag()) { .bytes => { const payload = val.castTag(.bytes).?; return Result{ .externally_managed = payload.data }; }, .array => { const elem_vals = val.castTag(.array).?.data; const elem_ty = ty.childType(); for (elem_vals) |elem_val| { switch (try self.genTypedValue(elem_ty, elem_val)) { .appended => {}, .externally_managed => |data| try writer.writeAll(data), } } return Result{ .appended = {} }; }, .repeated => { const array = val.castTag(.repeated).?.data; const elem_ty = ty.childType(); const sentinel = ty.sentinel(); const len = ty.arrayLen(); var index: u32 = 0; while (index < len) : (index += 1) { switch (try self.genTypedValue(elem_ty, array)) { .externally_managed => |data| try writer.writeAll(data), .appended => {}, } } if (sentinel) |sentinel_value| { return self.genTypedValue(elem_ty, sentinel_value); } return Result{ .appended = {} }; }, .empty_array_sentinel => { const elem_ty = ty.childType(); const sent_val = ty.sentinel().?; return self.genTypedValue(elem_ty, sent_val); }, else => unreachable, }, .Int => { const info = ty.intInfo(self.target()); const abi_size = @intCast(usize, ty.abiSize(self.target())); if (info.bits <= 64) { var buf: [8]u8 = undefined; if (info.signedness == .unsigned) { std.mem.writeIntLittle(u64, &buf, val.toUnsignedInt()); } else std.mem.writeIntLittle(i64, &buf, val.toSignedInt()); try writer.writeAll(buf[0..abi_size]); return Result{ .appended = {} }; } var space: Value.BigIntSpace = undefined; const bigint = val.toBigInt(&space); const iterations = @divExact(abi_size, @sizeOf(usize)); for (bigint.limbs) |_, index| { const limb = bigint.limbs[bigint.limbs.len - index - 1]; try writer.writeIntLittle(usize, limb); } else if (bigint.limbs.len < iterations) { // When the value is saved in less limbs than the required // abi size, we fill the remaining parts with 0's. var it_left = iterations - bigint.limbs.len; while (it_left > 0) { it_left -= 1; try writer.writeIntLittle(usize, 0); } } return Result{ .appended = {} }; }, .Enum => { var int_buffer: Value.Payload.U64 = undefined; const int_val = val.enumToInt(ty, &int_buffer); var buf: Type.Payload.Bits = undefined; const int_ty = ty.intTagType(&buf); return self.genTypedValue(int_ty, int_val); }, .Bool => { try writer.writeByte(@boolToInt(val.toBool())); return Result{ .appended = {} }; }, .Struct => { const struct_obj = ty.castTag(.@"struct").?.data; if (struct_obj.layout == .Packed) { return self.fail("TODO: Packed structs for wasm", .{}); } const struct_begin = self.code.items.len; const field_vals = val.castTag(.@"struct").?.data; for (field_vals) |field_val, index| { const field_ty = ty.structFieldType(index); if (!field_ty.hasRuntimeBits()) continue; switch (try self.genTypedValue(field_ty, field_val)) { .appended => {}, .externally_managed => |payload| try writer.writeAll(payload), } const unpadded_field_len = self.code.items.len - struct_begin; // Pad struct members if required const padded_field_end = ty.structFieldOffset(index + 1, self.target()); const padding = try std.math.cast(usize, padded_field_end - unpadded_field_len); if (padding > 0) { try writer.writeByteNTimes(0, padding); } } return Result{ .appended = {} }; }, .Union => { const union_val = val.castTag(.@"union").?.data; const layout = ty.unionGetLayout(self.target()); if (layout.payload_size == 0) { return self.genTypedValue(ty.unionTagType().?, union_val.tag); } // Check if we should store the tag first, in which case, do so now: if (layout.tag_align >= layout.payload_align) { switch (try self.genTypedValue(ty.unionTagType().?, union_val.tag)) { .appended => {}, .externally_managed => |payload| try writer.writeAll(payload), } } const union_ty = ty.cast(Type.Payload.Union).?.data; const field_index = union_ty.tag_ty.enumTagFieldIndex(union_val.tag).?; assert(union_ty.haveFieldTypes()); const field_ty = union_ty.fields.values()[field_index].ty; if (!field_ty.hasRuntimeBits()) { try writer.writeByteNTimes(0xaa, @intCast(usize, layout.payload_size)); } else { switch (try self.genTypedValue(field_ty, union_val.val)) { .appended => {}, .externally_managed => |payload| try writer.writeAll(payload), } // Unions have the size of the largest field, so we must pad // whenever the active field has a smaller size. const diff = layout.payload_size - field_ty.abiSize(self.target()); if (diff > 0) { try writer.writeByteNTimes(0xaa, @intCast(usize, diff)); } } if (layout.tag_size == 0) { return Result{ .appended = {} }; } return self.genTypedValue(union_ty.tag_ty, union_val.tag); }, .Pointer => switch (val.tag()) { .variable => { const decl = val.castTag(.variable).?.data.owner_decl; return self.lowerDeclRef(ty, val, decl); }, .decl_ref => { const decl = val.castTag(.decl_ref).?.data; return self.lowerDeclRef(ty, val, decl); }, .slice => { const slice = val.castTag(.slice).?.data; var buf: Type.SlicePtrFieldTypeBuffer = undefined; const ptr_ty = ty.slicePtrFieldType(&buf); switch (try self.genTypedValue(ptr_ty, slice.ptr)) { .externally_managed => |data| try writer.writeAll(data), .appended => {}, } switch (try self.genTypedValue(Type.usize, slice.len)) { .externally_managed => |data| try writer.writeAll(data), .appended => {}, } return Result{ .appended = {} }; }, .zero => { try writer.writeByteNTimes(0, @divExact(self.target().cpu.arch.ptrBitWidth(), 8)); return Result{ .appended = {} }; }, else => return self.fail("TODO: Implement zig decl gen for pointer type value: '{s}'", .{@tagName(val.tag())}), }, .ErrorUnion => { const error_ty = ty.errorUnionSet(); const payload_ty = ty.errorUnionPayload(); const is_pl = val.errorUnionIsPayload(); const err_val = if (!is_pl) val else Value.initTag(.zero); switch (try self.genTypedValue(error_ty, err_val)) { .externally_managed => |data| try writer.writeAll(data), .appended => {}, } if (payload_ty.hasRuntimeBits()) { const pl_val = if (val.castTag(.eu_payload)) |pl| pl.data else Value.initTag(.undef); switch (try self.genTypedValue(payload_ty, pl_val)) { .externally_managed => |data| try writer.writeAll(data), .appended => {}, } } return Result{ .appended = {} }; }, .ErrorSet => { switch (val.tag()) { .@"error" => { const name = val.castTag(.@"error").?.data.name; const kv = try self.module.getErrorValue(name); try writer.writeIntLittle(u32, kv.value); }, else => { try writer.writeByteNTimes(0, @intCast(usize, ty.abiSize(self.target()))); }, } return Result{ .appended = {} }; }, else => |tag| return self.fail("TODO: Implement zig type codegen for type: '{s}'", .{tag}), } } fn lowerDeclRef(self: *DeclGen, ty: Type, val: Value, decl: *Module.Decl) InnerError!Result { const writer = self.code.writer(); if (ty.isSlice()) { var buf: Type.SlicePtrFieldTypeBuffer = undefined; const slice_ty = ty.slicePtrFieldType(&buf); switch (try self.genTypedValue(slice_ty, val)) { .appended => {}, .externally_managed => |payload| try writer.writeAll(payload), } var slice_len: Value.Payload.U64 = .{ .base = .{ .tag = .int_u64 }, .data = val.sliceLen(), }; return self.genTypedValue(Type.usize, Value.initPayload(&slice_len.base)); } decl.markAlive(); try writer.writeIntLittle(u32, try self.bin_file.getDeclVAddr( self.decl, // The decl containing the source symbol index decl.ty, // type we generate the address of self.symbol_index, // source symbol index decl.link.wasm.sym_index, // target symbol index @intCast(u32, self.code.items.len), // offset )); return Result{ .appended = {} }; } }; const CallWValues = struct { args: []WValue, return_value: WValue, fn deinit(self: *CallWValues, gpa: Allocator) void { gpa.free(self.args); self.* = undefined; } }; fn resolveCallingConventionValues(self: *Self, fn_ty: Type) InnerError!CallWValues { const cc = fn_ty.fnCallingConvention(); const param_types = try self.gpa.alloc(Type, fn_ty.fnParamLen()); defer self.gpa.free(param_types); fn_ty.fnParamTypes(param_types); var result: CallWValues = .{ .args = try self.gpa.alloc(WValue, param_types.len), .return_value = .none, }; errdefer self.gpa.free(result.args); const ret_ty = fn_ty.fnReturnType(); // Check if we store the result as a pointer to the stack rather than // by value if (isByRef(ret_ty, self.target)) { // the sret arg will be passed as first argument, therefore we // set the `return_value` before allocating locals for regular args. result.return_value = .{ .local = self.local_index }; self.local_index += 1; } switch (cc) { .Naked => return result, .Unspecified, .C => { for (param_types) |ty, ty_index| { if (!ty.hasRuntimeBits()) { result.args[ty_index] = .{ .none = {} }; continue; } result.args[ty_index] = .{ .local = self.local_index }; self.local_index += 1; } }, else => return self.fail("TODO implement function parameters for cc '{}' on wasm", .{cc}), } return result; } /// Retrieves the stack pointer's value from the global variable and stores /// it in a local /// Asserts `initial_stack_value` is `.none` fn initializeStack(self: *Self) !void { assert(self.initial_stack_value == .none); // reserve space for immediate value // get stack pointer global try self.addLabel(.global_get, 0); // Reserve a local to store the current stack pointer // We can later use this local to set the stack pointer back to the value // we have stored here. self.initial_stack_value = try self.allocLocal(Type.initTag(.i32)); // save the value to the local try self.addLabel(.local_set, self.initial_stack_value.local); } /// Reads the stack pointer from `Context.initial_stack_value` and writes it /// to the global stack pointer variable fn restoreStackPointer(self: *Self) !void { // only restore the pointer if it was initialized if (self.initial_stack_value == .none) return; // Get the original stack pointer's value try self.emitWValue(self.initial_stack_value); // save its value in the global stack pointer try self.addLabel(.global_set, 0); } /// Moves the stack pointer by given `offset` /// It does this by retrieving the stack pointer, subtracting `offset` and storing /// the result back into the stack pointer. fn moveStack(self: *Self, offset: u32, local: u32) !void { if (offset == 0) return; try self.addLabel(.global_get, 0); try self.addImm32(@bitCast(i32, offset)); try self.addTag(.i32_sub); try self.addLabel(.local_tee, local); try self.addLabel(.global_set, 0); } /// From a given type, will create space on the virtual stack to store the value of such type. /// This returns a `WValue` with its active tag set to `local`, containing the index to the local /// that points to the position on the virtual stack. This function should be used instead of /// moveStack unless a local was already created to store the point. /// /// Asserts Type has codegenbits fn allocStack(self: *Self, ty: Type) !WValue { assert(ty.hasRuntimeBits()); // calculate needed stack space const abi_size = std.math.cast(u32, ty.abiSize(self.target)) catch { return self.fail("Given type '{}' too big to fit into stack frame", .{ty}); }; // allocate a local using wasm's pointer size const local = try self.allocLocal(Type.@"usize"); try self.moveStack(abi_size, local.local); return local; } /// From given zig bitsize, returns the wasm bitsize fn toWasmIntBits(bits: u16) ?u16 { return for ([_]u16{ 32, 64 }) |wasm_bits| { if (bits <= wasm_bits) return wasm_bits; } else null; } /// Performs a copy of bytes for a given type. Copying all bytes /// from rhs to lhs. /// /// TODO: Perform feature detection and when bulk_memory is available, /// use wasm's mem.copy instruction. fn memCopy(self: *Self, ty: Type, lhs: WValue, rhs: WValue) !void { const abi_size = ty.abiSize(self.target); var offset: u32 = 0; while (offset < abi_size) : (offset += 1) { // get lhs' address to store the result try self.emitWValue(lhs); // load byte from rhs' adress try self.emitWValue(rhs); try self.addMemArg(.i32_load8_u, .{ .offset = offset, .alignment = 1 }); // store the result in lhs (we already have its address on the stack) try self.addMemArg(.i32_store8, .{ .offset = offset, .alignment = 1 }); } } fn ptrSize(self: *const Self) u16 { return @divExact(self.target.cpu.arch.ptrBitWidth(), 8); } fn arch(self: *const Self) std.Target.Cpu.Arch { return self.target.cpu.arch; } /// For a given `Type`, will return true when the type will be passed /// by reference, rather than by value fn isByRef(ty: Type, target: std.Target) bool { switch (ty.zigTypeTag()) { .Type, .ComptimeInt, .ComptimeFloat, .EnumLiteral, .Undefined, .Null, .BoundFn, .Opaque, => unreachable, .NoReturn, .Void, .Bool, .Float, .ErrorSet, .Fn, .Enum, .Vector, .AnyFrame, => return false, .Array, .Struct, .Frame, .Union, => return ty.hasRuntimeBits(), .Int => return if (ty.intInfo(target).bits > 64) true else false, .ErrorUnion => { const has_tag = ty.errorUnionSet().hasRuntimeBits(); const has_pl = ty.errorUnionPayload().hasRuntimeBits(); if (!has_tag or !has_pl) return false; return ty.hasRuntimeBits(); }, .Optional => { if (ty.isPtrLikeOptional()) return false; var buf: Type.Payload.ElemType = undefined; return ty.optionalChild(&buf).hasRuntimeBits(); }, .Pointer => { // Slices act like struct and will be passed by reference if (ty.isSlice()) return true; return false; }, } } /// Creates a new local for a pointer that points to memory with given offset. /// This can be used to get a pointer to a struct field, error payload, etc. /// By providing `modify` as action, it will modify the given `ptr_value` instead of making a new /// local value to store the pointer. This allows for local re-use and improves binary size. fn buildPointerOffset(self: *Self, ptr_value: WValue, offset: u64, action: enum { modify, new }) InnerError!WValue { // do not perform arithmetic when offset is 0. if (offset == 0) return ptr_value; const result_ptr: WValue = switch (action) { .new => try self.allocLocal(Type.usize), .modify => ptr_value, }; try self.emitWValue(ptr_value); switch (self.target.cpu.arch.ptrBitWidth()) { 32 => { try self.addImm32(@bitCast(i32, @intCast(u32, offset))); try self.addTag(.i32_add); }, 64 => { try self.addImm64(offset); try self.addTag(.i64_add); }, else => unreachable, } try self.addLabel(.local_set, result_ptr.local); return result_ptr; } /// Creates a new local and sets its value to the given `value` local. /// User must ensure `ty` matches that of given `value`. /// Asserts `value` is a `local`. fn copyLocal(self: *Self, value: WValue, ty: Type) InnerError!WValue { const copy = try self.allocLocal(ty); try self.addLabel(.local_get, value.local); try self.addLabel(.local_set, copy.local); return copy; } fn genInst(self: *Self, inst: Air.Inst.Index) !WValue { const air_tags = self.air.instructions.items(.tag); return switch (air_tags[inst]) { .constant => unreachable, .const_ty => unreachable, .add => self.airBinOp(inst, .add), .addwrap => self.airWrapBinOp(inst, .add), .sub => self.airBinOp(inst, .sub), .subwrap => self.airWrapBinOp(inst, .sub), .mul => self.airBinOp(inst, .mul), .mulwrap => self.airWrapBinOp(inst, .mul), .div_trunc => self.airBinOp(inst, .div), .bit_and => self.airBinOp(inst, .@"and"), .bit_or => self.airBinOp(inst, .@"or"), .bool_and => self.airBinOp(inst, .@"and"), .bool_or => self.airBinOp(inst, .@"or"), .rem => self.airBinOp(inst, .rem), .shl, .shl_exact => self.airBinOp(inst, .shl), .shr, .shr_exact => self.airBinOp(inst, .shr), .xor => self.airBinOp(inst, .xor), .cmp_eq => self.airCmp(inst, .eq), .cmp_gte => self.airCmp(inst, .gte), .cmp_gt => self.airCmp(inst, .gt), .cmp_lte => self.airCmp(inst, .lte), .cmp_lt => self.airCmp(inst, .lt), .cmp_neq => self.airCmp(inst, .neq), .array_elem_val => self.airArrayElemVal(inst), .array_to_slice => self.airArrayToSlice(inst), .alloc => self.airAlloc(inst), .arg => self.airArg(inst), .bitcast => self.airBitcast(inst), .block => self.airBlock(inst), .breakpoint => self.airBreakpoint(inst), .br => self.airBr(inst), .bool_to_int => self.airBoolToInt(inst), .call => self.airCall(inst), .cond_br => self.airCondBr(inst), .dbg_stmt => WValue.none, .intcast => self.airIntcast(inst), .float_to_int => self.airFloatToInt(inst), .get_union_tag => self.airGetUnionTag(inst), .is_err => self.airIsErr(inst, .i32_ne), .is_non_err => self.airIsErr(inst, .i32_eq), .is_null => self.airIsNull(inst, .i32_eq, .value), .is_non_null => self.airIsNull(inst, .i32_ne, .value), .is_null_ptr => self.airIsNull(inst, .i32_eq, .ptr), .is_non_null_ptr => self.airIsNull(inst, .i32_ne, .ptr), .load => self.airLoad(inst), .loop => self.airLoop(inst), .memset => self.airMemset(inst), .not => self.airNot(inst), .optional_payload => self.airOptionalPayload(inst), .optional_payload_ptr => self.airOptionalPayloadPtr(inst), .optional_payload_ptr_set => self.airOptionalPayloadPtrSet(inst), .ptr_add => self.airPtrBinOp(inst, .add), .ptr_sub => self.airPtrBinOp(inst, .sub), .ptr_elem_ptr => self.airPtrElemPtr(inst), .ptr_elem_val => self.airPtrElemVal(inst), .ptrtoint => self.airPtrToInt(inst), .ret => self.airRet(inst), .ret_ptr => self.airRetPtr(inst), .ret_load => self.airRetLoad(inst), .splat => self.airSplat(inst), .vector_init => self.airVectorInit(inst), .prefetch => self.airPrefetch(inst), .slice => self.airSlice(inst), .slice_len => self.airSliceLen(inst), .slice_elem_val => self.airSliceElemVal(inst), .slice_elem_ptr => self.airSliceElemPtr(inst), .slice_ptr => self.airSlicePtr(inst), .store => self.airStore(inst), .set_union_tag => self.airSetUnionTag(inst), .struct_field_ptr => self.airStructFieldPtr(inst), .struct_field_ptr_index_0 => self.airStructFieldPtrIndex(inst, 0), .struct_field_ptr_index_1 => self.airStructFieldPtrIndex(inst, 1), .struct_field_ptr_index_2 => self.airStructFieldPtrIndex(inst, 2), .struct_field_ptr_index_3 => self.airStructFieldPtrIndex(inst, 3), .struct_field_val => self.airStructFieldVal(inst), .switch_br => self.airSwitchBr(inst), .trunc => self.airTrunc(inst), .unreach => self.airUnreachable(inst), .wrap_optional => self.airWrapOptional(inst), .unwrap_errunion_payload => self.airUnwrapErrUnionPayload(inst), .unwrap_errunion_err => self.airUnwrapErrUnionError(inst), .wrap_errunion_payload => self.airWrapErrUnionPayload(inst), .wrap_errunion_err => self.airWrapErrUnionErr(inst), .add_sat, .sub_sat, .mul_sat, .div_float, .div_floor, .div_exact, .mod, .max, .min, .assembly, .shl_sat, .ret_addr, .clz, .ctz, .popcount, .is_err_ptr, .is_non_err_ptr, .fptrunc, .fpext, .unwrap_errunion_payload_ptr, .unwrap_errunion_err_ptr, .ptr_slice_len_ptr, .ptr_slice_ptr_ptr, .int_to_float, .memcpy, .cmpxchg_weak, .cmpxchg_strong, .fence, .atomic_load, .atomic_store_unordered, .atomic_store_monotonic, .atomic_store_release, .atomic_store_seq_cst, .atomic_rmw, .tag_name, .error_name, // For these 4, probably best to wait until https://github.com/ziglang/zig/issues/10248 // is implemented in the frontend before implementing them here in the wasm backend. .add_with_overflow, .sub_with_overflow, .mul_with_overflow, .shl_with_overflow, => |tag| return self.fail("TODO: Implement wasm inst: {s}", .{@tagName(tag)}), }; } fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void { for (body) |inst| { const result = try self.genInst(inst); try self.values.putNoClobber(self.gpa, Air.indexToRef(inst), result); } } fn airRet(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const un_op = self.air.instructions.items(.data)[inst].un_op; const operand = try self.resolveInst(un_op); // result must be stored in the stack and we return a pointer // to the stack instead if (self.return_value != .none) { try self.store(self.return_value, operand, self.decl.ty.fnReturnType(), 0); } else { try self.emitWValue(operand); } try self.restoreStackPointer(); try self.addTag(.@"return"); return .none; } fn airRetPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const child_type = self.air.typeOfIndex(inst).childType(); if (child_type.abiSize(self.target) == 0) return WValue{ .none = {} }; if (isByRef(child_type, self.target)) { return self.return_value; } // Initialize the stack if (self.initial_stack_value == .none) { try self.initializeStack(); } return self.allocStack(child_type); } fn airRetLoad(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const un_op = self.air.instructions.items(.data)[inst].un_op; const operand = try self.resolveInst(un_op); const ret_ty = self.air.typeOf(un_op).childType(); if (!ret_ty.hasRuntimeBits()) return WValue.none; if (!isByRef(ret_ty, self.target)) { const result = try self.load(operand, ret_ty, 0); try self.emitWValue(result); } try self.restoreStackPointer(); try self.addTag(.@"return"); return .none; } fn airCall(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const pl_op = self.air.instructions.items(.data)[inst].pl_op; const extra = self.air.extraData(Air.Call, pl_op.payload); const args = self.air.extra[extra.end..][0..extra.data.args_len]; const ty = self.air.typeOf(pl_op.operand); const fn_ty = switch (ty.zigTypeTag()) { .Fn => ty, .Pointer => ty.childType(), else => unreachable, }; const ret_ty = fn_ty.fnReturnType(); const first_param_sret = isByRef(ret_ty, self.target); const target: ?*Decl = blk: { const func_val = self.air.value(pl_op.operand) orelse break :blk null; if (func_val.castTag(.function)) |func| { break :blk func.data.owner_decl; } else if (func_val.castTag(.extern_fn)) |ext_fn| { break :blk ext_fn.data; } else if (func_val.castTag(.decl_ref)) |decl_ref| { break :blk decl_ref.data; } return self.fail("Expected a function, but instead found type '{s}'", .{func_val.tag()}); }; const sret = if (first_param_sret) blk: { const sret_local = try self.allocStack(ret_ty); try self.emitWValue(sret_local); break :blk sret_local; } else WValue{ .none = {} }; for (args) |arg| { const arg_ref = @intToEnum(Air.Inst.Ref, arg); const arg_val = try self.resolveInst(arg_ref); const arg_ty = self.air.typeOf(arg_ref); if (!arg_ty.hasRuntimeBits()) continue; try self.emitWValue(arg_val); } if (target) |direct| { try self.addLabel(.call, direct.link.wasm.sym_index); } else { // in this case we call a function pointer // so load its value onto the stack std.debug.assert(ty.zigTypeTag() == .Pointer); const operand = try self.resolveInst(pl_op.operand); try self.emitWValue(operand); var fn_type = try genFunctype(self.gpa, fn_ty, self.target); defer fn_type.deinit(self.gpa); const fn_type_index = try self.bin_file.putOrGetFuncType(fn_type); try self.addLabel(.call_indirect, fn_type_index); } if (self.liveness.isUnused(inst) or !ret_ty.hasRuntimeBits()) { return WValue.none; } else if (ret_ty.isNoReturn()) { try self.addTag(.@"unreachable"); return WValue.none; } else if (first_param_sret) { return sret; } else { const result_local = try self.allocLocal(ret_ty); try self.addLabel(.local_set, result_local.local); return result_local; } } fn airAlloc(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const pointee_type = self.air.typeOfIndex(inst).childType(); // Initialize the stack if (self.initial_stack_value == .none) { try self.initializeStack(); } if (!pointee_type.hasRuntimeBits()) { // when the pointee is zero-sized, we still want to create a pointer. // but instead use a default pointer type as storage. const zero_ptr = try self.allocStack(Type.usize); return zero_ptr; } return self.allocStack(pointee_type); } fn airStore(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const bin_op = self.air.instructions.items(.data)[inst].bin_op; const lhs = try self.resolveInst(bin_op.lhs); const rhs = try self.resolveInst(bin_op.rhs); const ty = self.air.typeOf(bin_op.lhs).childType(); try self.store(lhs, rhs, ty, 0); return .none; } fn store(self: *Self, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerError!void { switch (ty.zigTypeTag()) { .ErrorUnion => { const err_ty = ty.errorUnionSet(); const pl_ty = ty.errorUnionPayload(); if (!pl_ty.hasRuntimeBits()) { const err_val = try self.load(rhs, err_ty, 0); return self.store(lhs, err_val, err_ty, 0); } return try self.memCopy(ty, lhs, rhs); }, .Optional => { if (ty.isPtrLikeOptional()) { return self.store(lhs, rhs, Type.usize, 0); } var buf: Type.Payload.ElemType = undefined; const pl_ty = ty.optionalChild(&buf); if (!pl_ty.hasRuntimeBits()) { return self.store(lhs, rhs, Type.initTag(.u8), 0); } return self.memCopy(ty, lhs, rhs); }, .Struct, .Array, .Union => { return try self.memCopy(ty, lhs, rhs); }, .Pointer => { if (ty.isSlice()) { // store pointer first const ptr_local = try self.load(rhs, Type.usize, 0); try self.store(lhs, ptr_local, Type.usize, 0); // retrieve length from rhs, and store that alongside lhs as well const len_local = try self.load(rhs, Type.usize, self.ptrSize()); try self.store(lhs, len_local, Type.usize, self.ptrSize()); return; } }, .Int => if (ty.intInfo(self.target).bits > 64) { return try self.memCopy(ty, lhs, rhs); }, else => {}, } try self.emitWValue(lhs); try self.emitWValue(rhs); const valtype = typeToValtype(ty, self.target); const abi_size = @intCast(u8, ty.abiSize(self.target)); const opcode = buildOpcode(.{ .valtype1 = valtype, .width = abi_size * 8, // use bitsize instead of byte size .op = .store, }); // store rhs value at stack pointer's location in memory try self.addMemArg( Mir.Inst.Tag.fromOpcode(opcode), .{ .offset = offset, .alignment = ty.abiAlignment(self.target) }, ); } fn airLoad(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const ty = self.air.getRefType(ty_op.ty); if (!ty.hasRuntimeBits()) return WValue{ .none = {} }; if (isByRef(ty, self.target)) { const new_local = try self.allocStack(ty); try self.store(new_local, operand, ty, 0); return new_local; } return self.load(operand, ty, 0); } fn load(self: *Self, operand: WValue, ty: Type, offset: u32) InnerError!WValue { // load local's value from memory by its stack position try self.emitWValue(operand); // Build the opcode with the right bitsize const signedness: std.builtin.Signedness = if (ty.isUnsignedInt() or ty.zigTypeTag() == .ErrorSet or ty.zigTypeTag() == .Bool) .unsigned else .signed; // TODO: Revisit below to determine if optional zero-sized pointers should still have abi-size 4. const abi_size = if (ty.isPtrLikeOptional()) @as(u8, 4) else @intCast(u8, ty.abiSize(self.target)); const opcode = buildOpcode(.{ .valtype1 = typeToValtype(ty, self.target), .width = abi_size * 8, // use bitsize instead of byte size .op = .load, .signedness = signedness, }); try self.addMemArg( Mir.Inst.Tag.fromOpcode(opcode), .{ .offset = offset, .alignment = ty.abiAlignment(self.target) }, ); // store the result in a local const result = try self.allocLocal(ty); try self.addLabel(.local_set, result.local); return result; } fn airArg(self: *Self, inst: Air.Inst.Index) InnerError!WValue { _ = inst; defer self.arg_index += 1; return self.args[self.arg_index]; } fn airBinOp(self: *Self, inst: Air.Inst.Index, op: Op) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const bin_op = self.air.instructions.items(.data)[inst].bin_op; const lhs = try self.resolveInst(bin_op.lhs); const rhs = try self.resolveInst(bin_op.rhs); const operand_ty = self.air.typeOfIndex(inst); if (isByRef(operand_ty, self.target)) { return self.fail("TODO: Implement binary operation for type: {}", .{operand_ty}); } try self.emitWValue(lhs); try self.emitWValue(rhs); const bin_ty = self.air.typeOf(bin_op.lhs); const opcode: wasm.Opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(bin_ty, self.target), .signedness = if (bin_ty.isSignedInt()) .signed else .unsigned, }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); // save the result in a temporary const bin_local = try self.allocLocal(bin_ty); try self.addLabel(.local_set, bin_local.local); return bin_local; } fn airWrapBinOp(self: *Self, inst: Air.Inst.Index, op: Op) InnerError!WValue { const bin_op = self.air.instructions.items(.data)[inst].bin_op; const lhs = try self.resolveInst(bin_op.lhs); const rhs = try self.resolveInst(bin_op.rhs); try self.emitWValue(lhs); try self.emitWValue(rhs); const bin_ty = self.air.typeOf(bin_op.lhs); const opcode: wasm.Opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(bin_ty, self.target), .signedness = if (bin_ty.isSignedInt()) .signed else .unsigned, }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); const int_info = bin_ty.intInfo(self.target); const bitsize = int_info.bits; const is_signed = int_info.signedness == .signed; // if target type bitsize is x < 32 and 32 > x < 64, we perform // result & ((1<<N)-1) where N = bitsize or bitsize -1 incase of signed. if (bitsize != 32 and bitsize < 64) { // first check if we can use a single instruction, // wasm provides those if the integers are signed and 8/16-bit. // For arbitrary integer sizes, we use the algorithm mentioned above. if (is_signed and bitsize == 8) { try self.addTag(.i32_extend8_s); } else if (is_signed and bitsize == 16) { try self.addTag(.i32_extend16_s); } else { const result = (@as(u64, 1) << @intCast(u6, bitsize - @boolToInt(is_signed))) - 1; if (bitsize < 32) { try self.addImm32(@bitCast(i32, @intCast(u32, result))); try self.addTag(.i32_and); } else { try self.addImm64(result); try self.addTag(.i64_and); } } } else if (int_info.bits > 64) { return self.fail("TODO wasm: Integer wrapping for bitsizes larger than 64", .{}); } // save the result in a temporary const bin_local = try self.allocLocal(bin_ty); try self.addLabel(.local_set, bin_local.local); return bin_local; } fn lowerConstant(self: *Self, val: Value, ty: Type) InnerError!WValue { if (val.isUndefDeep()) return self.emitUndefined(ty); switch (ty.zigTypeTag()) { .Int => { const int_info = ty.intInfo(self.target); // write constant switch (int_info.signedness) { .signed => switch (int_info.bits) { 0...32 => return WValue{ .imm32 = @bitCast(u32, @intCast(i32, val.toSignedInt())) }, 33...64 => return WValue{ .imm64 = @bitCast(u64, val.toSignedInt()) }, else => unreachable, }, .unsigned => switch (int_info.bits) { 0...32 => return WValue{ .imm32 = @intCast(u32, val.toUnsignedInt()) }, 33...64 => return WValue{ .imm64 = val.toUnsignedInt() }, else => unreachable, }, } }, .Bool => return WValue{ .imm32 = @intCast(u32, val.toUnsignedInt()) }, .Float => switch (ty.floatBits(self.target)) { 0...32 => return WValue{ .float32 = val.toFloat(f32) }, 33...64 => return WValue{ .float64 = val.toFloat(f64) }, else => unreachable, }, .Pointer => switch (val.tag()) { .decl_ref => { const decl = val.castTag(.decl_ref).?.data; decl.markAlive(); const target_sym_index = decl.link.wasm.sym_index; if (ty.isSlice()) { var slice_len: Value.Payload.U64 = .{ .base = .{ .tag = .int_u64 }, .data = val.sliceLen(), }; var slice_val: Value.Payload.Slice = .{ .base = .{ .tag = .slice }, .data = .{ .ptr = val.slicePtr(), .len = Value.initPayload(&slice_len.base) }, }; return self.lowerConstant(Value.initPayload(&slice_val.base), ty); } else if (decl.ty.zigTypeTag() == .Fn) { try self.bin_file.addTableFunction(target_sym_index); return WValue{ .function_index = target_sym_index }; } else return WValue{ .memory = target_sym_index }; }, .int_u64, .one => return WValue{ .imm32 = @intCast(u32, val.toUnsignedInt()) }, .zero, .null_value => return WValue{ .imm32 = 0 }, else => return self.fail("Wasm TODO: lowerConstant for other const pointer tag {s}", .{val.tag()}), }, .Enum => { if (val.castTag(.enum_field_index)) |field_index| { switch (ty.tag()) { .enum_simple => return WValue{ .imm32 = field_index.data }, .enum_full, .enum_nonexhaustive => { const enum_full = ty.cast(Type.Payload.EnumFull).?.data; if (enum_full.values.count() != 0) { const tag_val = enum_full.values.keys()[field_index.data]; return self.lowerConstant(tag_val, enum_full.tag_ty); } else { return WValue{ .imm32 = field_index.data }; } }, .enum_numbered => { const index = field_index.data; const enum_data = ty.castTag(.enum_numbered).?.data; const enum_val = enum_data.values.keys()[index]; return self.lowerConstant(enum_val, enum_data.tag_ty); }, else => return self.fail("TODO: lowerConstant for enum tag: {}", .{ty.tag()}), } } else { var int_tag_buffer: Type.Payload.Bits = undefined; const int_tag_ty = ty.intTagType(&int_tag_buffer); return self.lowerConstant(val, int_tag_ty); } }, .ErrorSet => switch (val.tag()) { .@"error" => { const kv = try self.module.getErrorValue(val.getError().?); return WValue{ .imm32 = kv.value }; }, else => return WValue{ .imm32 = 0 }, }, .ErrorUnion => { const error_type = ty.errorUnionSet(); const is_pl = val.errorUnionIsPayload(); const err_val = if (!is_pl) val else Value.initTag(.zero); return self.lowerConstant(err_val, error_type); }, .Optional => if (ty.isPtrLikeOptional()) { var buf: Type.Payload.ElemType = undefined; return self.lowerConstant(val, ty.optionalChild(&buf)); } else { const is_pl = val.tag() == .opt_payload; return WValue{ .imm32 = if (is_pl) @as(u32, 1) else 0 }; }, else => |zig_type| return self.fail("Wasm TODO: LowerConstant for zigTypeTag {s}", .{zig_type}), } } fn emitUndefined(self: *Self, ty: Type) InnerError!WValue { switch (ty.zigTypeTag()) { .Bool, .ErrorSet => return WValue{ .imm32 = 0xaaaaaaaa }, .Int => switch (ty.intInfo(self.target).bits) { 0...32 => return WValue{ .imm32 = 0xaaaaaaaa }, 33...64 => return WValue{ .imm64 = 0xaaaaaaaaaaaaaaaa }, else => unreachable, }, .Float => switch (ty.floatBits(self.target)) { 0...32 => return WValue{ .float32 = @bitCast(f32, @as(u32, 0xaaaaaaaa)) }, 33...64 => return WValue{ .float64 = @bitCast(f64, @as(u64, 0xaaaaaaaaaaaaaaaa)) }, else => unreachable, }, .Pointer => switch (self.arch()) { .wasm32 => return WValue{ .imm32 = 0xaaaaaaaa }, .wasm64 => return WValue{ .imm64 = 0xaaaaaaaaaaaaaaaa }, else => unreachable, }, .Optional => { var buf: Type.Payload.ElemType = undefined; const pl_ty = ty.optionalChild(&buf); if (ty.isPtrLikeOptional()) { return self.emitUndefined(pl_ty); } return WValue{ .imm32 = 0xaaaaaaaa }; }, .ErrorUnion => { return WValue{ .imm32 = 0xaaaaaaaa }; }, else => return self.fail("Wasm TODO: emitUndefined for type: {}\n", .{ty.zigTypeTag()}), } } /// Returns a `Value` as a signed 32 bit value. /// It's illegal to provide a value with a type that cannot be represented /// as an integer value. fn valueAsI32(self: Self, val: Value, ty: Type) i32 { switch (ty.zigTypeTag()) { .Enum => { if (val.castTag(.enum_field_index)) |field_index| { switch (ty.tag()) { .enum_simple => return @bitCast(i32, field_index.data), .enum_full, .enum_nonexhaustive => { const enum_full = ty.cast(Type.Payload.EnumFull).?.data; if (enum_full.values.count() != 0) { const tag_val = enum_full.values.keys()[field_index.data]; return self.valueAsI32(tag_val, enum_full.tag_ty); } else return @bitCast(i32, field_index.data); }, else => unreachable, } } else { var int_tag_buffer: Type.Payload.Bits = undefined; const int_tag_ty = ty.intTagType(&int_tag_buffer); return self.valueAsI32(val, int_tag_ty); } }, .Int => switch (ty.intInfo(self.target).signedness) { .signed => return @truncate(i32, val.toSignedInt()), .unsigned => return @bitCast(i32, @truncate(u32, val.toUnsignedInt())), }, .ErrorSet => { const kv = self.module.getErrorValue(val.getError().?) catch unreachable; // passed invalid `Value` to function return @bitCast(i32, kv.value); }, else => unreachable, // Programmer called this function for an illegal type } } fn airBlock(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const block_ty = genBlockType(self.air.getRefType(ty_pl.ty), self.target); const extra = self.air.extraData(Air.Block, ty_pl.payload); const body = self.air.extra[extra.end..][0..extra.data.body_len]; // if block_ty is non-empty, we create a register to store the temporary value const block_result: WValue = if (block_ty != wasm.block_empty) try self.allocLocal(self.air.getRefType(ty_pl.ty)) else WValue.none; try self.startBlock(.block, wasm.block_empty); // Here we set the current block idx, so breaks know the depth to jump // to when breaking out. try self.blocks.putNoClobber(self.gpa, inst, .{ .label = self.block_depth, .value = block_result, }); try self.genBody(body); try self.endBlock(); return block_result; } /// appends a new wasm block to the code section and increases the `block_depth` by 1 fn startBlock(self: *Self, block_tag: wasm.Opcode, valtype: u8) !void { self.block_depth += 1; try self.addInst(.{ .tag = Mir.Inst.Tag.fromOpcode(block_tag), .data = .{ .block_type = valtype }, }); } /// Ends the current wasm block and decreases the `block_depth` by 1 fn endBlock(self: *Self) !void { try self.addTag(.end); self.block_depth -= 1; } fn airLoop(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const loop = self.air.extraData(Air.Block, ty_pl.payload); const body = self.air.extra[loop.end..][0..loop.data.body_len]; // result type of loop is always 'noreturn', meaning we can always // emit the wasm type 'block_empty'. try self.startBlock(.loop, wasm.block_empty); try self.genBody(body); // breaking to the index of a loop block will continue the loop instead try self.addLabel(.br, 0); try self.endBlock(); return .none; } fn airCondBr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const pl_op = self.air.instructions.items(.data)[inst].pl_op; const condition = try self.resolveInst(pl_op.operand); const extra = self.air.extraData(Air.CondBr, pl_op.payload); const then_body = self.air.extra[extra.end..][0..extra.data.then_body_len]; const else_body = self.air.extra[extra.end + then_body.len ..][0..extra.data.else_body_len]; // TODO: Handle death instructions for then and else body // result type is always noreturn, so use `block_empty` as type. try self.startBlock(.block, wasm.block_empty); // emit the conditional value try self.emitWValue(condition); // we inserted the block in front of the condition // so now check if condition matches. If not, break outside this block // and continue with the then codepath try self.addLabel(.br_if, 0); try self.genBody(else_body); try self.endBlock(); // Outer block that matches the condition try self.genBody(then_body); return .none; } fn airCmp(self: *Self, inst: Air.Inst.Index, op: std.math.CompareOperator) InnerError!WValue { const bin_op = self.air.instructions.items(.data)[inst].bin_op; const lhs = try self.resolveInst(bin_op.lhs); const rhs = try self.resolveInst(bin_op.rhs); const operand_ty = self.air.typeOf(bin_op.lhs); if (operand_ty.zigTypeTag() == .Optional and !operand_ty.isPtrLikeOptional()) { var buf: Type.Payload.ElemType = undefined; const payload_ty = operand_ty.optionalChild(&buf); if (payload_ty.hasRuntimeBits()) { // When we hit this case, we must check the value of optionals // that are not pointers. This means first checking against non-null for // both lhs and rhs, as well as checking the payload are matching of lhs and rhs return self.cmpOptionals(lhs, rhs, operand_ty, op); } } else if (isByRef(operand_ty, self.target)) { return self.cmpBigInt(lhs, rhs, operand_ty, op); } try self.emitWValue(lhs); try self.emitWValue(rhs); const signedness: std.builtin.Signedness = blk: { // by default we tell the operand type is unsigned (i.e. bools and enum values) if (operand_ty.zigTypeTag() != .Int) break :blk .unsigned; // incase of an actual integer, we emit the correct signedness break :blk operand_ty.intInfo(self.target).signedness; }; const opcode: wasm.Opcode = buildOpcode(.{ .valtype1 = typeToValtype(operand_ty, self.target), .op = switch (op) { .lt => .lt, .lte => .le, .eq => .eq, .neq => .ne, .gte => .ge, .gt => .gt, }, .signedness = signedness, }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); const cmp_tmp = try self.allocLocal(Type.initTag(.i32)); // bool is always i32 try self.addLabel(.local_set, cmp_tmp.local); return cmp_tmp; } fn airBr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const br = self.air.instructions.items(.data)[inst].br; const block = self.blocks.get(br.block_inst).?; // if operand has codegen bits we should break with a value if (self.air.typeOf(br.operand).hasRuntimeBits()) { try self.emitWValue(try self.resolveInst(br.operand)); if (block.value != .none) { try self.addLabel(.local_set, block.value.local); } } // We map every block to its block index. // We then determine how far we have to jump to it by subtracting it from current block depth const idx: u32 = self.block_depth - block.label; try self.addLabel(.br, idx); return .none; } fn airNot(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); try self.emitWValue(operand); // wasm does not have booleans nor the `not` instruction, therefore compare with 0 // to create the same logic try self.addImm32(0); try self.addTag(.i32_eq); // save the result in the local const not_tmp = try self.allocLocal(Type.initTag(.i32)); try self.addLabel(.local_set, not_tmp.local); return not_tmp; } fn airBreakpoint(self: *Self, inst: Air.Inst.Index) InnerError!WValue { _ = self; _ = inst; // unsupported by wasm itself. Can be implemented once we support DWARF // for wasm return .none; } fn airUnreachable(self: *Self, inst: Air.Inst.Index) InnerError!WValue { _ = inst; try self.addTag(.@"unreachable"); return .none; } fn airBitcast(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); return operand; } fn airStructFieldPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const extra = self.air.extraData(Air.StructField, ty_pl.payload); const struct_ptr = try self.resolveInst(extra.data.struct_operand); const struct_ty = self.air.typeOf(extra.data.struct_operand).childType(); const offset = std.math.cast(u32, struct_ty.structFieldOffset(extra.data.field_index, self.target)) catch { return self.fail("Field type '{}' too big to fit into stack frame", .{ struct_ty.structFieldType(extra.data.field_index), }); }; return self.structFieldPtr(struct_ptr, offset); } fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u32) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const struct_ptr = try self.resolveInst(ty_op.operand); const struct_ty = self.air.typeOf(ty_op.operand).childType(); const field_ty = struct_ty.structFieldType(index); const offset = std.math.cast(u32, struct_ty.structFieldOffset(index, self.target)) catch { return self.fail("Field type '{}' too big to fit into stack frame", .{ field_ty, }); }; return self.structFieldPtr(struct_ptr, offset); } fn structFieldPtr(self: *Self, struct_ptr: WValue, offset: u32) InnerError!WValue { return self.buildPointerOffset(struct_ptr, offset, .new); } fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const struct_field = self.air.extraData(Air.StructField, ty_pl.payload).data; const struct_ty = self.air.typeOf(struct_field.struct_operand); const operand = try self.resolveInst(struct_field.struct_operand); const field_index = struct_field.field_index; const field_ty = struct_ty.structFieldType(field_index); if (!field_ty.hasRuntimeBits()) return WValue{ .none = {} }; const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, self.target)) catch { return self.fail("Field type '{}' too big to fit into stack frame", .{field_ty}); }; if (isByRef(field_ty, self.target)) { return self.buildPointerOffset(operand, offset, .new); } return self.load(operand, field_ty, offset); } fn airSwitchBr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { // result type is always 'noreturn' const blocktype = wasm.block_empty; const pl_op = self.air.instructions.items(.data)[inst].pl_op; const target = try self.resolveInst(pl_op.operand); const target_ty = self.air.typeOf(pl_op.operand); const switch_br = self.air.extraData(Air.SwitchBr, pl_op.payload); var extra_index: usize = switch_br.end; var case_i: u32 = 0; // a list that maps each value with its value and body based on the order inside the list. const CaseValue = struct { integer: i32, value: Value }; var case_list = try std.ArrayList(struct { values: []const CaseValue, body: []const Air.Inst.Index, }).initCapacity(self.gpa, switch_br.data.cases_len); defer for (case_list.items) |case| { self.gpa.free(case.values); } else case_list.deinit(); var lowest: i32 = 0; var highest: i32 = 0; while (case_i < switch_br.data.cases_len) : (case_i += 1) { const case = self.air.extraData(Air.SwitchBr.Case, extra_index); const items = @bitCast([]const Air.Inst.Ref, self.air.extra[case.end..][0..case.data.items_len]); const case_body = self.air.extra[case.end + items.len ..][0..case.data.body_len]; extra_index = case.end + items.len + case_body.len; const values = try self.gpa.alloc(CaseValue, items.len); errdefer self.gpa.free(values); for (items) |ref, i| { const item_val = self.air.value(ref).?; const int_val = self.valueAsI32(item_val, target_ty); if (int_val < lowest) { lowest = int_val; } if (int_val > highest) { highest = int_val; } values[i] = .{ .integer = int_val, .value = item_val }; } case_list.appendAssumeCapacity(.{ .values = values, .body = case_body }); try self.startBlock(.block, blocktype); } // When the highest and lowest values are seperated by '50', // we define it as sparse and use an if/else-chain, rather than a jump table. // When the target is an integer size larger than u32, we have no way to use the value // as an index, therefore we also use an if/else-chain for those cases. // TODO: Benchmark this to find a proper value, LLVM seems to draw the line at '40~45'. const is_sparse = highest - lowest > 50 or target_ty.bitSize(self.target) > 32; const else_body = self.air.extra[extra_index..][0..switch_br.data.else_body_len]; const has_else_body = else_body.len != 0; if (has_else_body) { try self.startBlock(.block, blocktype); } if (!is_sparse) { // Generate the jump table 'br_table' when the prongs are not sparse. // The value 'target' represents the index into the table. // Each index in the table represents a label to the branch // to jump to. try self.startBlock(.block, blocktype); try self.emitWValue(target); if (lowest < 0) { // since br_table works using indexes, starting from '0', we must ensure all values // we put inside, are atleast 0. try self.addImm32(lowest * -1); try self.addTag(.i32_add); } // Account for default branch so always add '1' const depth = @intCast(u32, highest - lowest + @boolToInt(has_else_body)) + 1; const jump_table: Mir.JumpTable = .{ .length = depth }; const table_extra_index = try self.addExtra(jump_table); try self.addInst(.{ .tag = .br_table, .data = .{ .payload = table_extra_index } }); try self.mir_extra.ensureUnusedCapacity(self.gpa, depth); while (lowest <= highest) : (lowest += 1) { // idx represents the branch we jump to const idx = blk: { for (case_list.items) |case, idx| { for (case.values) |case_value| { if (case_value.integer == lowest) break :blk @intCast(u32, idx); } } break :blk if (has_else_body) case_i else unreachable; }; self.mir_extra.appendAssumeCapacity(idx); } else if (has_else_body) { self.mir_extra.appendAssumeCapacity(case_i); // default branch } try self.endBlock(); } const signedness: std.builtin.Signedness = blk: { // by default we tell the operand type is unsigned (i.e. bools and enum values) if (target_ty.zigTypeTag() != .Int) break :blk .unsigned; // incase of an actual integer, we emit the correct signedness break :blk target_ty.intInfo(self.target).signedness; }; for (case_list.items) |case| { // when sparse, we use if/else-chain, so emit conditional checks if (is_sparse) { // for single value prong we can emit a simple if if (case.values.len == 1) { try self.emitWValue(target); const val = try self.lowerConstant(case.values[0].value, target_ty); try self.emitWValue(val); const opcode = buildOpcode(.{ .valtype1 = typeToValtype(target_ty, self.target), .op = .ne, // not equal, because we want to jump out of this block if it does not match the condition. .signedness = signedness, }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); try self.addLabel(.br_if, 0); } else { // in multi-value prongs we must check if any prongs match the target value. try self.startBlock(.block, blocktype); for (case.values) |value| { try self.emitWValue(target); const val = try self.lowerConstant(value.value, target_ty); try self.emitWValue(val); const opcode = buildOpcode(.{ .valtype1 = typeToValtype(target_ty, self.target), .op = .eq, .signedness = signedness, }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); try self.addLabel(.br_if, 0); } // value did not match any of the prong values try self.addLabel(.br, 1); try self.endBlock(); } } try self.genBody(case.body); try self.endBlock(); } if (has_else_body) { try self.genBody(else_body); try self.endBlock(); } return .none; } fn airIsErr(self: *Self, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerError!WValue { const un_op = self.air.instructions.items(.data)[inst].un_op; const operand = try self.resolveInst(un_op); const err_ty = self.air.typeOf(un_op); const pl_ty = err_ty.errorUnionPayload(); // load the error tag value try self.emitWValue(operand); if (pl_ty.hasRuntimeBits()) { try self.addMemArg(.i32_load16_u, .{ .offset = 0, .alignment = err_ty.errorUnionSet().abiAlignment(self.target), }); } // Compare the error value with '0' try self.addImm32(0); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); const is_err_tmp = try self.allocLocal(Type.initTag(.i32)); // result is always an i32 try self.addLabel(.local_set, is_err_tmp.local); return is_err_tmp; } fn airUnwrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const err_ty = self.air.typeOf(ty_op.operand); const payload_ty = err_ty.errorUnionPayload(); if (!payload_ty.hasRuntimeBits()) return WValue{ .none = {} }; const offset = @intCast(u32, err_ty.errorUnionSet().abiSize(self.target)); if (isByRef(payload_ty, self.target)) { return self.buildPointerOffset(operand, offset, .new); } return try self.load(operand, payload_ty, offset); } fn airUnwrapErrUnionError(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const err_ty = self.air.typeOf(ty_op.operand); const payload_ty = err_ty.errorUnionPayload(); if (!payload_ty.hasRuntimeBits()) { return operand; } return try self.load(operand, err_ty.errorUnionSet(), 0); } fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const op_ty = self.air.typeOf(ty_op.operand); if (!op_ty.hasRuntimeBits()) return operand; const err_ty = self.air.getRefType(ty_op.ty); const offset = err_ty.errorUnionSet().abiSize(self.target); const err_union = try self.allocStack(err_ty); const payload_ptr = try self.buildPointerOffset(err_union, offset, .new); try self.store(payload_ptr, operand, op_ty, 0); // ensure we also write '0' to the error part, so any present stack value gets overwritten by it. try self.addLabel(.local_get, err_union.local); try self.addImm32(0); try self.addMemArg(.i32_store16, .{ .offset = 0, .alignment = 2 }); return err_union; } fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const err_ty = self.air.getRefType(ty_op.ty); const err_union = try self.allocStack(err_ty); // TODO: Also write 'undefined' to the payload try self.store(err_union, operand, err_ty.errorUnionSet(), 0); return err_union; } fn airIntcast(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const ty = self.air.getRefType(ty_op.ty); const operand = try self.resolveInst(ty_op.operand); const ref_ty = self.air.typeOf(ty_op.operand); const ref_info = ref_ty.intInfo(self.target); const wanted_info = ty.intInfo(self.target); const op_bits = toWasmIntBits(ref_info.bits) orelse return self.fail("TODO: Wasm intcast integer types of bitsize: {d}", .{ref_info.bits}); const wanted_bits = toWasmIntBits(wanted_info.bits) orelse return self.fail("TODO: Wasm intcast integer types of bitsize: {d}", .{wanted_info.bits}); // hot path if (op_bits == wanted_bits) return operand; if (op_bits > 32 and wanted_bits == 32) { try self.emitWValue(operand); try self.addTag(.i32_wrap_i64); } else if (op_bits == 32 and wanted_bits > 32) { try self.emitWValue(operand); try self.addTag(switch (ref_info.signedness) { .signed => .i64_extend_i32_s, .unsigned => .i64_extend_i32_u, }); } else unreachable; const result = try self.allocLocal(ty); try self.addLabel(.local_set, result.local); return result; } fn airIsNull(self: *Self, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind: enum { value, ptr }) InnerError!WValue { const un_op = self.air.instructions.items(.data)[inst].un_op; const operand = try self.resolveInst(un_op); const op_ty = self.air.typeOf(un_op); const optional_ty = if (op_kind == .ptr) op_ty.childType() else op_ty; return self.isNull(operand, optional_ty, opcode); } fn isNull(self: *Self, operand: WValue, optional_ty: Type, opcode: wasm.Opcode) InnerError!WValue { try self.emitWValue(operand); if (!optional_ty.isPtrLikeOptional()) { var buf: Type.Payload.ElemType = undefined; const payload_ty = optional_ty.optionalChild(&buf); // When payload is zero-bits, we can treat operand as a value, rather than // a pointer to the stack value if (payload_ty.hasRuntimeBits()) { try self.addMemArg(.i32_load8_u, .{ .offset = 0, .alignment = 1 }); } } // Compare the null value with '0' try self.addImm32(0); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); const is_null_tmp = try self.allocLocal(Type.initTag(.i32)); try self.addLabel(.local_set, is_null_tmp.local); return is_null_tmp; } fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const opt_ty = self.air.typeOf(ty_op.operand); const payload_ty = self.air.typeOfIndex(inst); if (!payload_ty.hasRuntimeBits()) return WValue{ .none = {} }; if (opt_ty.isPtrLikeOptional()) return operand; const offset = opt_ty.abiSize(self.target) - payload_ty.abiSize(self.target); if (isByRef(payload_ty, self.target)) { return self.buildPointerOffset(operand, offset, .new); } return self.load(operand, payload_ty, @intCast(u32, offset)); } fn airOptionalPayloadPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const opt_ty = self.air.typeOf(ty_op.operand).childType(); var buf: Type.Payload.ElemType = undefined; const payload_ty = opt_ty.optionalChild(&buf); if (!payload_ty.hasRuntimeBits() or opt_ty.isPtrLikeOptional()) { return operand; } const offset = opt_ty.abiSize(self.target) - payload_ty.abiSize(self.target); return self.buildPointerOffset(operand, offset, .new); } fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const opt_ty = self.air.typeOf(ty_op.operand).childType(); var buf: Type.Payload.ElemType = undefined; const payload_ty = opt_ty.optionalChild(&buf); if (!payload_ty.hasRuntimeBits()) { return self.fail("TODO: Implement OptionalPayloadPtrSet for optional with zero-sized type {}", .{payload_ty}); } if (opt_ty.isPtrLikeOptional()) { return operand; } const offset = std.math.cast(u32, opt_ty.abiSize(self.target) - payload_ty.abiSize(self.target)) catch { return self.fail("Optional type {} too big to fit into stack frame", .{opt_ty}); }; try self.emitWValue(operand); try self.addImm32(1); try self.addMemArg(.i32_store8, .{ .offset = 0, .alignment = 1 }); return self.buildPointerOffset(operand, offset, .new); } fn airWrapOptional(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const payload_ty = self.air.typeOf(ty_op.operand); if (!payload_ty.hasRuntimeBits()) { const non_null_bit = try self.allocStack(Type.initTag(.u1)); try self.addLabel(.local_get, non_null_bit.local); try self.addImm32(1); try self.addMemArg(.i32_store8, .{ .offset = 0, .alignment = 1 }); return non_null_bit; } const operand = try self.resolveInst(ty_op.operand); const op_ty = self.air.typeOfIndex(inst); if (op_ty.isPtrLikeOptional()) { return operand; } const offset = std.math.cast(u32, op_ty.abiSize(self.target) - payload_ty.abiSize(self.target)) catch { return self.fail("Optional type {} too big to fit into stack frame", .{op_ty}); }; // Create optional type, set the non-null bit, and store the operand inside the optional type const result = try self.allocStack(op_ty); try self.addLabel(.local_get, result.local); try self.addImm32(1); try self.addMemArg(.i32_store8, .{ .offset = 0, .alignment = 1 }); const payload_ptr = try self.buildPointerOffset(result, offset, .new); try self.store(payload_ptr, operand, payload_ty, 0); return result; } fn airSlice(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data; const lhs = try self.resolveInst(bin_op.lhs); const rhs = try self.resolveInst(bin_op.rhs); const slice_ty = self.air.typeOfIndex(inst); const slice = try self.allocStack(slice_ty); try self.store(slice, lhs, Type.usize, 0); try self.store(slice, rhs, Type.usize, self.ptrSize()); return slice; } fn airSliceLen(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); return try self.load(operand, Type.usize, self.ptrSize()); } fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const bin_op = self.air.instructions.items(.data)[inst].bin_op; const slice_ty = self.air.typeOf(bin_op.lhs); const slice = try self.resolveInst(bin_op.lhs); const index = try self.resolveInst(bin_op.rhs); const elem_ty = slice_ty.childType(); const elem_size = elem_ty.abiSize(self.target); // load pointer onto stack const slice_ptr = try self.load(slice, Type.usize, 0); try self.addLabel(.local_get, slice_ptr.local); // calculate index into slice try self.emitWValue(index); try self.addImm32(@bitCast(i32, @intCast(u32, elem_size))); try self.addTag(.i32_mul); try self.addTag(.i32_add); const result = try self.allocLocal(elem_ty); try self.addLabel(.local_set, result.local); if (isByRef(elem_ty, self.target)) { return result; } return try self.load(result, elem_ty, 0); } fn airSliceElemPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data; const elem_ty = self.air.getRefType(ty_pl.ty).childType(); const elem_size = elem_ty.abiSize(self.target); const slice = try self.resolveInst(bin_op.lhs); const index = try self.resolveInst(bin_op.rhs); const slice_ptr = try self.load(slice, Type.usize, 0); try self.addLabel(.local_get, slice_ptr.local); // calculate index into slice try self.emitWValue(index); try self.addImm32(@bitCast(i32, @intCast(u32, elem_size))); try self.addTag(.i32_mul); try self.addTag(.i32_add); const result = try self.allocLocal(Type.initTag(.i32)); try self.addLabel(.local_set, result.local); return result; } fn airSlicePtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); return try self.load(operand, Type.usize, 0); } fn airTrunc(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue.none; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const op_ty = self.air.typeOf(ty_op.operand); const int_info = self.air.getRefType(ty_op.ty).intInfo(self.target); const wanted_bits = int_info.bits; const result = try self.allocLocal(self.air.getRefType(ty_op.ty)); const op_bits = op_ty.intInfo(self.target).bits; const wasm_bits = toWasmIntBits(wanted_bits) orelse return self.fail("TODO: Implement wasm integer truncation for integer bitsize: {d}", .{wanted_bits}); // Use wasm's instruction to wrap from 64bit to 32bit integer when possible if (op_bits == 64 and wanted_bits == 32) { try self.emitWValue(operand); try self.addTag(.i32_wrap_i64); try self.addLabel(.local_set, result.local); return result; } // Any other truncation must be done manually if (int_info.signedness == .unsigned) { const mask = (@as(u65, 1) << @intCast(u7, wanted_bits)) - 1; try self.emitWValue(operand); switch (wasm_bits) { 32 => { try self.addImm32(@bitCast(i32, @intCast(u32, mask))); try self.addTag(.i32_and); }, 64 => { try self.addImm64(@intCast(u64, mask)); try self.addTag(.i64_and); }, else => unreachable, } } else { const shift_bits = wasm_bits - wanted_bits; try self.emitWValue(operand); switch (wasm_bits) { 32 => { try self.addImm32(@bitCast(i16, shift_bits)); try self.addTag(.i32_shl); try self.addImm32(@bitCast(i16, shift_bits)); try self.addTag(.i32_shr_s); }, 64 => { try self.addImm64(shift_bits); try self.addTag(.i64_shl); try self.addImm64(shift_bits); try self.addTag(.i64_shr_s); }, else => unreachable, } } try self.addLabel(.local_set, result.local); return result; } fn airBoolToInt(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const un_op = self.air.instructions.items(.data)[inst].un_op; return try self.resolveInst(un_op); } fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const array_ty = self.air.typeOf(ty_op.operand).childType(); const ty = Type.@"usize"; const ptr_width = @intCast(u32, ty.abiSize(self.target)); const slice_ty = self.air.getRefType(ty_op.ty); // create a slice on the stack const slice_local = try self.allocStack(slice_ty); // store the array ptr in the slice if (array_ty.hasRuntimeBits()) { try self.store(slice_local, operand, ty, 0); } // store the length of the array in the slice const len = array_ty.arrayLen(); try self.addImm32(@bitCast(i32, @intCast(u32, len))); const len_local = try self.allocLocal(ty); try self.addLabel(.local_set, len_local.local); try self.store(slice_local, len_local, ty, ptr_width); return slice_local; } fn airPtrToInt(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const un_op = self.air.instructions.items(.data)[inst].un_op; return try self.resolveInst(un_op); } fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const bin_op = self.air.instructions.items(.data)[inst].bin_op; const ptr_ty = self.air.typeOf(bin_op.lhs); const pointer = try self.resolveInst(bin_op.lhs); const index = try self.resolveInst(bin_op.rhs); const elem_ty = ptr_ty.childType(); const elem_size = elem_ty.abiSize(self.target); // load pointer onto the stack if (ptr_ty.isSlice()) { const ptr_local = try self.load(pointer, ptr_ty, 0); try self.addLabel(.local_get, ptr_local.local); } else { try self.emitWValue(pointer); } // calculate index into slice try self.emitWValue(index); try self.addImm32(@bitCast(i32, @intCast(u32, elem_size))); try self.addTag(.i32_mul); try self.addTag(.i32_add); const result = try self.allocLocal(elem_ty); try self.addLabel(.local_set, result.local); if (isByRef(elem_ty, self.target)) { return result; } return try self.load(result, elem_ty, 0); } fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data; const ptr_ty = self.air.typeOf(bin_op.lhs); const elem_ty = self.air.getRefType(ty_pl.ty).childType(); const elem_size = elem_ty.abiSize(self.target); const ptr = try self.resolveInst(bin_op.lhs); const index = try self.resolveInst(bin_op.rhs); // load pointer onto the stack if (ptr_ty.isSlice()) { const ptr_local = try self.load(ptr, ptr_ty, 0); try self.addLabel(.local_get, ptr_local.local); } else { try self.emitWValue(ptr); } // calculate index into ptr try self.emitWValue(index); try self.addImm32(@bitCast(i32, @intCast(u32, elem_size))); try self.addTag(.i32_mul); try self.addTag(.i32_add); const result = try self.allocLocal(Type.initTag(.i32)); try self.addLabel(.local_set, result.local); return result; } fn airPtrBinOp(self: *Self, inst: Air.Inst.Index, op: Op) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const bin_op = self.air.instructions.items(.data)[inst].bin_op; const ptr = try self.resolveInst(bin_op.lhs); const offset = try self.resolveInst(bin_op.rhs); const ptr_ty = self.air.typeOf(bin_op.lhs); const pointee_ty = switch (ptr_ty.ptrSize()) { .One => ptr_ty.childType().childType(), // ptr to array, so get array element type else => ptr_ty.childType(), }; const valtype = typeToValtype(Type.usize, self.target); const mul_opcode = buildOpcode(.{ .valtype1 = valtype, .op = .mul }); const bin_opcode = buildOpcode(.{ .valtype1 = valtype, .op = op }); try self.emitWValue(ptr); try self.emitWValue(offset); try self.addImm32(@bitCast(i32, @intCast(u32, pointee_ty.abiSize(self.target)))); try self.addTag(Mir.Inst.Tag.fromOpcode(mul_opcode)); try self.addTag(Mir.Inst.Tag.fromOpcode(bin_opcode)); const result = try self.allocLocal(Type.usize); try self.addLabel(.local_set, result.local); return result; } fn airMemset(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const pl_op = self.air.instructions.items(.data)[inst].pl_op; const bin_op = self.air.extraData(Air.Bin, pl_op.payload).data; const ptr = try self.resolveInst(pl_op.operand); const value = try self.resolveInst(bin_op.lhs); const len = try self.resolveInst(bin_op.rhs); try self.memSet(ptr, len, value); return WValue.none; } /// Sets a region of memory at `ptr` to the value of `value` /// When the user has enabled the bulk_memory feature, we lower /// this to wasm's memset instruction. When the feature is not present, /// we implement it manually. fn memSet(self: *Self, ptr: WValue, len: WValue, value: WValue) InnerError!void { // When bulk_memory is enabled, we lower it to wasm's memset instruction. // If not, we lower it ourselves if (std.Target.wasm.featureSetHas(self.target.cpu.features, .bulk_memory)) { try self.emitWValue(ptr); try self.emitWValue(value); try self.emitWValue(len); try self.addExtended(.memory_fill); return; } // TODO: We should probably lower this to a call to compiler_rt // But for now, we implement it manually const offset = try self.allocLocal(Type.usize); // local for counter // outer block to jump to when loop is done try self.startBlock(.block, wasm.block_empty); try self.startBlock(.loop, wasm.block_empty); try self.emitWValue(offset); try self.emitWValue(len); switch (self.ptrSize()) { 4 => try self.addTag(.i32_eq), 8 => try self.addTag(.i64_eq), else => unreachable, } try self.addLabel(.br_if, 1); // jump out of loop into outer block (finished) try self.emitWValue(ptr); try self.emitWValue(offset); switch (self.ptrSize()) { 4 => try self.addTag(.i32_add), 8 => try self.addTag(.i64_add), else => unreachable, } try self.emitWValue(value); const mem_store_op: Mir.Inst.Tag = switch (self.ptrSize()) { 4 => .i32_store8, 8 => .i64_store8, else => unreachable, }; try self.addMemArg(mem_store_op, .{ .offset = 0, .alignment = 1 }); try self.emitWValue(offset); try self.addImm32(1); switch (self.ptrSize()) { 4 => try self.addTag(.i32_add), 8 => try self.addTag(.i64_add), else => unreachable, } try self.addLabel(.local_set, offset.local); try self.addLabel(.br, 0); // jump to start of loop try self.endBlock(); try self.endBlock(); } fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const bin_op = self.air.instructions.items(.data)[inst].bin_op; const array_ty = self.air.typeOf(bin_op.lhs); const array = try self.resolveInst(bin_op.lhs); const index = try self.resolveInst(bin_op.rhs); const elem_ty = array_ty.childType(); const elem_size = elem_ty.abiSize(self.target); // calculate index into slice try self.emitWValue(array); try self.emitWValue(index); try self.addImm32(@bitCast(i32, @intCast(u32, elem_size))); try self.addTag(.i32_mul); try self.addTag(.i32_add); const result = try self.allocLocal(elem_ty); try self.addLabel(.local_set, result.local); if (isByRef(elem_ty, self.target)) { return result; } return try self.load(result, elem_ty, 0); } fn airFloatToInt(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); const dest_ty = self.air.typeOfIndex(inst); const op_ty = self.air.typeOf(ty_op.operand); try self.emitWValue(operand); const op = buildOpcode(.{ .op = .trunc, .valtype1 = typeToValtype(dest_ty, self.target), .valtype2 = typeToValtype(op_ty, self.target), .signedness = if (dest_ty.isSignedInt()) .signed else .unsigned, }); try self.addTag(Mir.Inst.Tag.fromOpcode(op)); const result = try self.allocLocal(dest_ty); try self.addLabel(.local_set, result.local); return result; } fn airSplat(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const operand = try self.resolveInst(ty_op.operand); _ = ty_op; _ = operand; return self.fail("TODO: Implement wasm airSplat", .{}); } fn airVectorInit(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const vector_ty = self.air.typeOfIndex(inst); const len = vector_ty.vectorLen(); const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; const elements = @bitCast([]const Air.Inst.Ref, self.air.extra[ty_pl.payload..][0..len]); _ = elements; return self.fail("TODO: Wasm backend: implement airVectorInit", .{}); } fn airPrefetch(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const prefetch = self.air.instructions.items(.data)[inst].prefetch; _ = prefetch; return WValue{ .none = {} }; } fn cmpOptionals(self: *Self, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue { assert(operand_ty.hasRuntimeBits()); assert(op == .eq or op == .neq); var buf: Type.Payload.ElemType = undefined; const payload_ty = operand_ty.optionalChild(&buf); const offset = @intCast(u32, operand_ty.abiSize(self.target) - payload_ty.abiSize(self.target)); const lhs_is_null = try self.isNull(lhs, operand_ty, .i32_eq); const rhs_is_null = try self.isNull(rhs, operand_ty, .i32_eq); // We store the final result in here that will be validated // if the optional is truly equal. const result = try self.allocLocal(Type.initTag(.i32)); try self.startBlock(.block, wasm.block_empty); try self.emitWValue(lhs_is_null); try self.emitWValue(rhs_is_null); try self.addTag(.i32_ne); // inverse so we can exit early try self.addLabel(.br_if, 0); const lhs_pl = try self.load(lhs, payload_ty, offset); const rhs_pl = try self.load(rhs, payload_ty, offset); try self.emitWValue(lhs_pl); try self.emitWValue(rhs_pl); const opcode = buildOpcode(.{ .op = .ne, .valtype1 = typeToValtype(payload_ty, self.target) }); try self.addTag(Mir.Inst.Tag.fromOpcode(opcode)); try self.addLabel(.br_if, 0); try self.addImm32(1); try self.addLabel(.local_set, result.local); try self.endBlock(); try self.emitWValue(result); try self.addImm32(0); try self.addTag(if (op == .eq) .i32_ne else .i32_eq); try self.addLabel(.local_set, result.local); return result; } /// Compares big integers by checking both its high bits and low bits. /// TODO: Lower this to compiler_rt call fn cmpBigInt(self: *Self, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue { if (operand_ty.intInfo(self.target).bits > 128) { return self.fail("TODO: Support cmpBigInt for integer bitsize: '{d}'", .{operand_ty.intInfo(self.target).bits}); } const result = try self.allocLocal(Type.initTag(.i32)); { try self.startBlock(.block, wasm.block_empty); const lhs_high_bit = try self.load(lhs, Type.initTag(.u64), 0); const lhs_low_bit = try self.load(lhs, Type.initTag(.u64), 8); const rhs_high_bit = try self.load(rhs, Type.initTag(.u64), 0); const rhs_low_bit = try self.load(rhs, Type.initTag(.u64), 8); try self.emitWValue(lhs_high_bit); try self.emitWValue(rhs_high_bit); try self.addTag(.i64_ne); try self.addLabel(.br_if, 0); try self.emitWValue(lhs_low_bit); try self.emitWValue(rhs_low_bit); try self.addTag(.i64_ne); try self.addLabel(.br_if, 0); try self.addImm32(1); try self.addLabel(.local_set, result.local); try self.endBlock(); } try self.emitWValue(result); try self.addImm32(0); try self.addTag(if (op == .eq) .i32_ne else .i32_eq); try self.addLabel(.local_set, result.local); return result; } fn airSetUnionTag(self: *Self, inst: Air.Inst.Index) InnerError!WValue { const bin_op = self.air.instructions.items(.data)[inst].bin_op; const un_ty = self.air.typeOf(bin_op.lhs).childType(); const tag_ty = self.air.typeOf(bin_op.rhs); const layout = un_ty.unionGetLayout(self.target); if (layout.tag_size == 0) return WValue{ .none = {} }; const union_ptr = try self.resolveInst(bin_op.lhs); const new_tag = try self.resolveInst(bin_op.rhs); if (layout.payload_size == 0) { try self.store(union_ptr, new_tag, tag_ty, 0); return WValue{ .none = {} }; } // when the tag alignment is smaller than the payload, the field will be stored // after the payload. const offset = if (layout.tag_align < layout.payload_align) blk: { break :blk @intCast(u32, layout.payload_size); } else @as(u32, 0); try self.store(union_ptr, new_tag, tag_ty, offset); return WValue{ .none = {} }; } fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) InnerError!WValue { if (self.liveness.isUnused(inst)) return WValue{ .none = {} }; const ty_op = self.air.instructions.items(.data)[inst].ty_op; const un_ty = self.air.typeOf(ty_op.operand); const tag_ty = self.air.typeOfIndex(inst); const layout = un_ty.unionGetLayout(self.target); if (layout.tag_size == 0) return WValue{ .none = {} }; const operand = try self.resolveInst(ty_op.operand); // when the tag alignment is smaller than the payload, the field will be stored // after the payload. const offset = if (layout.tag_align < layout.payload_align) blk: { break :blk @intCast(u32, layout.payload_size); } else @as(u32, 0); return self.load(operand, tag_ty, offset); }
src/arch/wasm/CodeGen.zig
const std = @import("../../std.zig"); const elf = std.elf; const linux = std.os.linux; const mem = std.mem; const maxInt = std.math.maxInt; pub fn lookup(vername: []const u8, name: []const u8) usize { const vdso_addr = std.os.system.getauxval(std.elf.AT_SYSINFO_EHDR); if (vdso_addr == 0) return 0; const eh = @intToPtr(*elf.Ehdr, vdso_addr); var ph_addr: usize = vdso_addr + eh.e_phoff; const ph = @intToPtr(*elf.Phdr, ph_addr); var maybe_dynv: ?[*]usize = null; var base: usize = maxInt(usize); { var i: usize = 0; while (i < eh.e_phnum) : ({ i += 1; ph_addr += eh.e_phentsize; }) { const this_ph = @intToPtr(*elf.Phdr, ph_addr); switch (this_ph.p_type) { elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, vdso_addr + this_ph.p_offset), else => {}, } } } const dynv = maybe_dynv orelse return 0; if (base == maxInt(usize)) return 0; var maybe_strings: ?[*]u8 = null; var maybe_syms: ?[*]elf.Sym = null; var maybe_hashtab: ?[*]linux.Elf_Symndx = null; var maybe_versym: ?[*]u16 = null; var maybe_verdef: ?*elf.Verdef = null; { var i: usize = 0; while (dynv[i] != 0) : (i += 2) { const p = base + dynv[i + 1]; switch (dynv[i]) { elf.DT_STRTAB => maybe_strings = @intToPtr([*]u8, p), elf.DT_SYMTAB => maybe_syms = @intToPtr([*]elf.Sym, p), elf.DT_HASH => maybe_hashtab = @intToPtr([*]linux.Elf_Symndx, p), elf.DT_VERSYM => maybe_versym = @intToPtr([*]u16, p), elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p), else => {}, } } } const strings = maybe_strings orelse return 0; const syms = maybe_syms orelse return 0; const hashtab = maybe_hashtab orelse return 0; if (maybe_verdef == null) maybe_versym = null; const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON); const OK_BINDS = (1 << elf.STB_GLOBAL | 1 << elf.STB_WEAK | 1 << elf.STB_GNU_UNIQUE); var i: usize = 0; while (i < hashtab[1]) : (i += 1) { if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info & 0xf) & OK_TYPES)) continue; if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, mem.toSliceConst(u8, strings + syms[i].st_name))) continue; if (maybe_versym) |versym| { if (!checkver(maybe_verdef.?, versym[i], vername, strings)) continue; } return base + syms[i].st_value; } return 0; } fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [*]u8) bool { var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) break; if (def.vd_next == 0) return false; def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next); } const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); return mem.eql(u8, vername, mem.toSliceConst(u8, strings + aux.vda_name)); }
lib/std/os/linux/vdso.zig
const std = @import("std"); const getty = @import("../../../lib.zig"); pub fn Visitor(comptime Tuple: type) type { return struct { const Self = @This(); pub usingnamespace getty.de.Visitor( Self, Value, undefined, undefined, undefined, undefined, undefined, undefined, visitSeq, undefined, undefined, undefined, ); const Value = Tuple; fn visitSeq(_: Self, allocator: ?std.mem.Allocator, comptime Deserializer: type, seq: anytype) Deserializer.Error!Value { const fields = std.meta.fields(Value); const len = fields.len; var tuple: Value = undefined; comptime var seen: usize = 0; errdefer { comptime var i: usize = 0; if (allocator) |alloc| { if (len > 0) { inline while (i < seen) : (i += 1) { getty.de.free(alloc, tuple[i]); } } } } switch (len) { 0 => tuple = .{}, else => { comptime var i: usize = 0; inline while (i < len) : (i += 1) { // NOTE: Using an if to unwrap `value` runs into a // compiler bug, so this is a workaround. const value = try seq.nextElement(allocator, fields[i].field_type); if (value == null) return error.InvalidLength; tuple[i] = value.?; seen += 1; } }, } // Expected end of sequence, but found an element. if ((try seq.nextElement(allocator, void)) != null) { return error.InvalidLength; } return tuple; } }; }
src/de/impl/visitor/tuple.zig
const std = @import("std"); const Src = std.builtin.SourceLocation; // check for a decl named tracy_enabled in root or build_options pub const enabled = blk: { var build_enable: ?bool = null; var root_enable: ?bool = null; const root = @import("root"); if (@hasDecl(root, "tracy_enabled")) { root_enable = @as(bool, root.tracy_enabled); } if (!std.builtin.is_test) { // Don't try to include build_options in tests. // Otherwise `zig test` doesn't work. const options = @import("build_options"); if (@hasDecl(options, "tracy_enabled")) { build_enable = @as(bool, options.tracy_enabled); } } if (build_enable != null and root_enable != null) { if (build_enable.? != root_enable.?) { @compileError("root.tracy_enabled disagrees with build_options.tracy_enabled! Please remove one or make them match."); } } break :blk root_enable orelse (build_enable orelse false); }; const debug_verify_stack_order = false; usingnamespace if (enabled) tracy_full else tracy_stub; const tracy_stub = struct { pub const ZoneCtx = struct { pub inline fn Text(self: ZoneCtx, text: []const u8) void { _ = self; _ = text; } pub inline fn Name(self: ZoneCtx, name: []const u8) void { _ = self; _ = name; } pub inline fn Value(self: ZoneCtx, value: u64) void { _ = self; _ = value; } pub inline fn End(self: ZoneCtx) void { _ = self; } }; pub inline fn InitThread() void {} pub inline fn SetThreadName(name: [*:0]const u8) void { _ = name; } pub inline fn Zone(comptime src: Src) ZoneCtx { _ = src; return .{}; } pub inline fn ZoneN(comptime src: Src, name: [*:0]const u8) ZoneCtx { _ = src; _ = name; return .{}; } pub inline fn ZoneC(comptime src: Src, color: u32) ZoneCtx { _ = src; _ = color; return .{}; } pub inline fn ZoneNC(comptime src: Src, name: [*:0]const u8, color: u32) ZoneCtx { _ = src; _ = name; _ = color; return .{}; } pub inline fn ZoneS(comptime src: Src, depth: i32) ZoneCtx { _ = src; _ = depth; return .{}; } pub inline fn ZoneNS(comptime src: Src, name: [*:0]const u8, depth: i32) ZoneCtx { _ = src; _ = name; _ = depth; return .{}; } pub inline fn ZoneCS(comptime src: Src, color: u32, depth: i32) ZoneCtx { _ = src; _ = color; _ = depth; return .{}; } pub inline fn ZoneNCS(comptime src: Src, name: [*:0]const u8, color: u32, depth: i32) ZoneCtx { _ = src; _ = name; _ = color; _ = depth; return .{}; } pub inline fn Alloc(ptr: ?*const c_void, size: usize) void { _ = ptr; _ = size; } pub inline fn Free(ptr: ?*const c_void) void { _ = ptr; } pub inline fn SecureAlloc(ptr: ?*const c_void, size: usize) void { _ = ptr; _ = size; } pub inline fn SecureFree(ptr: ?*const c_void) void { _ = ptr; } pub inline fn AllocS(ptr: ?*const c_void, size: usize, depth: c_int) void { _ = ptr; _ = size; _ = depth; } pub inline fn FreeS(ptr: ?*const c_void, depth: c_int) void { _ = ptr; _ = depth; } pub inline fn SecureAllocS(ptr: ?*const c_void, size: usize, depth: c_int) void { _ = ptr; _ = size; _ = depth; } pub inline fn SecureFreeS(ptr: ?*const c_void, depth: c_int) void { _ = ptr; _ = depth; } pub inline fn AllocN(ptr: ?*const c_void, size: usize, name: [*:0]const u8) void { _ = ptr; _ = size; _ = name; } pub inline fn FreeN(ptr: ?*const c_void, name: [*:0]const u8) void { _ = ptr; _ = name; } pub inline fn SecureAllocN(ptr: ?*const c_void, size: usize, name: [*:0]const u8) void { _ = ptr; _ = size; _ = name; } pub inline fn SecureFreeN(ptr: ?*const c_void, name: [*:0]const u8) void { _ = ptr; _ = name; } pub inline fn AllocNS(ptr: ?*const c_void, size: usize, depth: c_int, name: [*:0]const u8) void { _ = ptr; _ = size; _ = depth; _ = name; } pub inline fn FreeNS(ptr: ?*const c_void, depth: c_int, name: [*:0]const u8) void { _ = ptr; _ = depth; _ = name; } pub inline fn SecureAllocNS(ptr: ?*const c_void, size: usize, depth: c_int, name: [*:0]const u8) void { _ = ptr; _ = size; _ = depth; _ = name; } pub inline fn SecureFreeNS(ptr: ?*const c_void, depth: c_int, name: [*:0]const u8) void { _ = ptr; _ = depth; _ = name; } pub inline fn Message(text: []const u8) void { _ = text; } pub inline fn MessageL(text: [*:0]const u8) void { _ = text; } pub inline fn MessageC(text: []const u8, color: u32) void { _ = text; _ = color; } pub inline fn MessageLC(text: [*:0]const u8, color: u32) void { _ = text; _ = color; } pub inline fn MessageS(text: []const u8, depth: c_int) void { _ = text; _ = depth; } pub inline fn MessageLS(text: [*:0]const u8, depth: c_int) void { _ = text; _ = depth; } pub inline fn MessageCS(text: []const u8, color: u32, depth: c_int) void { _ = text; _ = color; _ = depth; } pub inline fn MessageLCS(text: [*:0]const u8, color: u32, depth: c_int) void { _ = text; _ = color; _ = depth; } pub inline fn FrameMark() void {} pub inline fn FrameMarkNamed(name: [*:0]const u8) void { _ = name; } pub inline fn FrameMarkStart(name: [*:0]const u8) void { _ = name; } pub inline fn FrameMarkEnd(name: [*:0]const u8) void { _ = name; } pub inline fn FrameImage(image: ?*const c_void, width: u16, height: u16, offset: u8, flip: c_int) void { _ = image; _ = width; _ = height; _ = offset; _ = flip; } pub inline fn PlotF(name: [*:0]const u8, val: f64) void { _ = name; _ = val; } pub inline fn PlotU(name: [*:0]const u8, val: u64) void { _ = name; _ = val; } pub inline fn PlotI(name: [*:0]const u8, val: i64) void { _ = name; _ = val; } pub inline fn AppInfo(text: []const u8) void { _ = text; } }; const tracy_full = struct { const c = @cImport({ @cDefine("TRACY_ENABLE", ""); @cInclude("TracyC.h"); }); const has_callstack_support = @hasDecl(c, "TRACY_HAS_CALLSTACK") and @hasDecl(c, "TRACY_CALLSTACK"); const callstack_enabled: c_int = if (has_callstack_support) c.TRACY_CALLSTACK else 0; threadlocal var stack_depth: if (debug_verify_stack_order) usize else u0 = 0; pub const ZoneCtx = struct { _zone: c.___tracy_c_zone_context, _token: if (debug_verify_stack_order) usize else void, pub inline fn Text(self: ZoneCtx, text: []const u8) void { if (debug_verify_stack_order) { if (stack_depth != self._token) { std.debug.panic("Error: expected Value() at stack depth {} but was {}\n", .{ self._token, stack_depth }); } } c.___tracy_emit_zone_text(self._zone, text.ptr, text.len); } pub inline fn Name(self: ZoneCtx, name: []const u8) void { if (debug_verify_stack_order) { if (stack_depth != self._token) { std.debug.panic("Error: expected Value() at stack depth {} but was {}\n", .{ self._token, stack_depth }); } } c.___tracy_emit_zone_name(self._zone, name.ptr, name.len); } pub inline fn Value(self: ZoneCtx, val: u64) void { if (debug_verify_stack_order) { if (stack_depth != self._token) { std.debug.panic("Error: expected Value() at stack depth {} but was {}\n", .{ self._token, stack_depth }); } } c.___tracy_emit_zone_value(self._zone, val); } pub inline fn End(self: ZoneCtx) void { if (debug_verify_stack_order) { if (stack_depth != self._token) { std.debug.panic("Error: expected End() at stack depth {} but was {}\n", .{ self._token, stack_depth }); } stack_depth -= 1; } c.___tracy_emit_zone_end(self._zone); } }; inline fn initZone(comptime src: Src, name: ?[*:0]const u8, color: u32, depth: c_int) ZoneCtx { // Tracy uses pointer identity to identify contexts. // The `src` parameter being comptime ensures that // each zone gets its own unique global location for this // struct. const static = struct { var loc: c.___tracy_source_location_data = undefined; }; static.loc = .{ .name = name, .function = src.fn_name.ptr, .file = src.file.ptr, .line = src.line, .color = color, }; const zone = if (has_callstack_support) c.___tracy_emit_zone_begin_callstack(&static.loc, depth, 1) else c.___tracy_emit_zone_begin(&static.loc, 1); if (debug_verify_stack_order) { stack_depth += 1; return ZoneCtx{ ._zone = zone, ._token = stack_depth }; } else { return ZoneCtx{ ._zone = zone, ._token = {} }; } } pub inline fn InitThread() void { c.___tracy_init_thread(); } pub inline fn SetThreadName(name: [*:0]const u8) void { c.___tracy_set_thread_name(name); } pub inline fn Zone(comptime src: Src) ZoneCtx { return initZone(src, null, 0, callstack_enabled); } pub inline fn ZoneN(comptime src: Src, name: [*:0]const u8) ZoneCtx { return initZone(src, name, 0, callstack_enabled); } pub inline fn ZoneC(comptime src: Src, color: u32) ZoneCtx { return initZone(src, null, color, callstack_enabled); } pub inline fn ZoneNC(comptime src: Src, name: [*:0]const u8, color: u32) ZoneCtx { return initZone(src, name, color, callstack_enabled); } pub inline fn ZoneS(comptime src: Src, depth: i32) ZoneCtx { return initZone(src, null, 0, depth); } pub inline fn ZoneNS(comptime src: Src, name: [*:0]const u8, depth: i32) ZoneCtx { return initZone(src, name, 0, depth); } pub inline fn ZoneCS(comptime src: Src, color: u32, depth: i32) ZoneCtx { return initZone(src, null, color, depth); } pub inline fn ZoneNCS(comptime src: Src, name: [*:0]const u8, color: u32, depth: i32) ZoneCtx { return initZone(src, name, color, depth); } pub inline fn Alloc(ptr: ?*const c_void, size: usize) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack(ptr, size, callstack_enabled, 0); } else { c.___tracy_emit_memory_alloc(ptr, size, 0); } } pub inline fn Free(ptr: ?*const c_void) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack(ptr, callstack_enabled, 0); } else { c.___tracy_emit_memory_free(ptr, size, 0); } } pub inline fn SecureAlloc(ptr: ?*const c_void, size: usize) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack(ptr, size, callstack_enabled, 1); } else { c.___tracy_emit_memory_alloc(ptr, size, 1); } } pub inline fn SecureFree(ptr: ?*const c_void) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack(ptr, callstack_enabled, 1); } else { c.___tracy_emit_memory_free(ptr, size, 1); } } pub inline fn AllocS(ptr: ?*const c_void, size: usize, depth: c_int) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack(ptr, size, depth, 0); } else { c.___tracy_emit_memory_alloc(ptr, size, 0); } } pub inline fn FreeS(ptr: ?*const c_void, depth: c_int) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack(ptr, depth, 0); } else { c.___tracy_emit_memory_free(ptr, 0); } } pub inline fn SecureAllocS(ptr: ?*const c_void, size: usize, depth: c_int) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack(ptr, size, depth, 1); } else { c.___tracy_emit_memory_alloc(ptr, size, 1); } } pub inline fn SecureFreeS(ptr: ?*const c_void, depth: c_int) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack(ptr, depth, 1); } else { c.___tracy_emit_memory_free(ptr, 1); } } pub inline fn AllocN(ptr: ?*const c_void, size: usize, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack_named(ptr, size, callstack_enabled, 0, name); } else { c.___tracy_emit_memory_alloc_named(ptr, size, 0, name); } } pub inline fn FreeN(ptr: ?*const c_void, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack_named(ptr, callstack_enabled, 0, name); } else { c.___tracy_emit_memory_free_named(ptr, 0, name); } } pub inline fn SecureAllocN(ptr: ?*const c_void, size: usize, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack_named(ptr, size, callstack_enabled, 1, name); } else { c.___tracy_emit_memory_alloc_named(ptr, size, 1, name); } } pub inline fn SecureFreeN(ptr: ?*const c_void, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack_named(ptr, callstack_enabled, 1, name); } else { c.___tracy_emit_memory_free_named(ptr, 1, name); } } pub inline fn AllocNS(ptr: ?*const c_void, size: usize, depth: c_int, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack_named(ptr, size, depth, 0, name); } else { c.___tracy_emit_memory_alloc_named(ptr, size, 0, name); } } pub inline fn FreeNS(ptr: ?*const c_void, depth: c_int, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack_named(ptr, depth, 0, name); } else { c.___tracy_emit_memory_free_named(ptr, 0, name); } } pub inline fn SecureAllocNS(ptr: ?*const c_void, size: usize, depth: c_int, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_alloc_callstack_named(ptr, size, depth, 1, name); } else { c.___tracy_emit_memory_alloc_named(ptr, size, 1, name); } } pub inline fn SecureFreeNS(ptr: ?*const c_void, depth: c_int, name: [*:0]const u8) void { if (has_callstack_support) { c.___tracy_emit_memory_free_callstack_named(ptr, depth, 1, name); } else { c.___tracy_emit_memory_free_named(ptr, 1, name); } } pub inline fn Message(text: []const u8) void { c.___tracy_emit_message(text.ptr, text.len, callstack_enabled); } pub inline fn MessageL(text: [*:0]const u8) void { c.___tracy_emit_messageL(text, color, callstack_enabled); } pub inline fn MessageC(text: []const u8, color: u32) void { c.___tracy_emit_messageC(text.ptr, text.len, color, callstack_enabled); } pub inline fn MessageLC(text: [*:0]const u8, color: u32) void { c.___tracy_emit_messageLC(text, color, callstack_enabled); } pub inline fn MessageS(text: []const u8, depth: c_int) void { const inner_depth: c_int = if (has_callstack_support) depth else 0; c.___tracy_emit_message(text.ptr, text.len, inner_depth); } pub inline fn MessageLS(text: [*:0]const u8, depth: c_int) void { const inner_depth: c_int = if (has_callstack_support) depth else 0; c.___tracy_emit_messageL(text, inner_depth); } pub inline fn MessageCS(text: []const u8, color: u32, depth: c_int) void { const inner_depth: c_int = if (has_callstack_support) depth else 0; c.___tracy_emit_messageC(text.ptr, text.len, color, inner_depth); } pub inline fn MessageLCS(text: [*:0]const u8, color: u32, depth: c_int) void { const inner_depth: c_int = if (has_callstack_support) depth else 0; c.___tracy_emit_messageLC(text, color, inner_depth); } pub inline fn FrameMark() void { c.___tracy_emit_frame_mark(null); } pub inline fn FrameMarkNamed(name: [*:0]const u8) void { c.___tracy_emit_frame_mark(name); } pub inline fn FrameMarkStart(name: [*:0]const u8) void { c.___tracy_emit_frame_mark_start(name); } pub inline fn FrameMarkEnd(name: [*:0]const u8) void { c.___tracy_emit_frame_mark_end(name); } pub inline fn FrameImage(image: ?*const c_void, width: u16, height: u16, offset: u8, flip: c_int) void { c.___tracy_emit_frame_image(image, width, height, offset, flip); } pub inline fn PlotF(name: [*:0]const u8, val: f64) void { c.___tracy_emit_plot(name, val); } pub inline fn PlotU(name: [*:0]const u8, val: u64) void { c.___tracy_emit_plot(name, @intToFloat(f64, val)); } pub inline fn PlotI(name: [*:0]const u8, val: i64) void { c.___tracy_emit_plot(name, @intToFloat(f64, val)); } pub inline fn AppInfo(text: []const u8) void { c.___tracy_emit_message_appinfo(text.ptr, text.len); } };
nativemap/src/tracy.zig
const std = @import("std"); const testing = std.testing; const secret_handshake = @import("secret_handshake.zig"); test "wink for 1" { const expected = &[_]secret_handshake.Signal{.wink}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 1); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "double blink for 10" { const expected = &[_]secret_handshake.Signal{.double_blink}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 2); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "close your eyes for 100" { const expected = &[_]secret_handshake.Signal{.close_your_eyes}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 4); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "jump for 1000" { const expected = &[_]secret_handshake.Signal{.jump}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 8); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "combine two actions" { const expected = &[_]secret_handshake.Signal{.wink, .double_blink}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 3); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "reverse two actions" { const expected = &[_]secret_handshake.Signal{.double_blink, .wink}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 19); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "reversing one action gives the same action" { const expected = &[_]secret_handshake.Signal{.jump}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 24); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "reversing no actions still gives no actions" { const expected = &[_]secret_handshake.Signal{}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 16); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "all possible actions" { const expected = &[_]secret_handshake.Signal{ .wink, .double_blink, .close_your_eyes, .jump}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 15); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "reverse all possible actions" { const expected = &[_]secret_handshake.Signal{ .jump, .close_your_eyes, .double_blink, .wink}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 31); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); } test "do nothing for zero" { const expected = &[_]secret_handshake.Signal{}; var actual = try secret_handshake.calculateHandshake(testing.allocator, 0); defer testing.allocator.free(actual); testing.expectEqualSlices(secret_handshake.Signal, expected, actual); }
exercises/practice/secret-handshake/test_secret_handshake.zig
const std = @import("std"); const mem = std.mem; const Cased = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 65, hi: u21 = 127369, pub fn init(allocator: *mem.Allocator) !Cased { var instance = Cased{ .allocator = allocator, .array = try allocator.alloc(bool, 127305), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 25) : (index += 1) { instance.array[index] = true; } index = 32; while (index <= 57) : (index += 1) { instance.array[index] = true; } instance.array[105] = true; instance.array[116] = true; instance.array[121] = true; index = 127; while (index <= 149) : (index += 1) { instance.array[index] = true; } index = 151; while (index <= 181) : (index += 1) { instance.array[index] = true; } index = 183; while (index <= 377) : (index += 1) { instance.array[index] = true; } index = 379; while (index <= 382) : (index += 1) { instance.array[index] = true; } index = 387; while (index <= 594) : (index += 1) { instance.array[index] = true; } index = 596; while (index <= 622) : (index += 1) { instance.array[index] = true; } index = 623; while (index <= 631) : (index += 1) { instance.array[index] = true; } index = 639; while (index <= 640) : (index += 1) { instance.array[index] = true; } index = 671; while (index <= 675) : (index += 1) { instance.array[index] = true; } instance.array[772] = true; index = 815; while (index <= 818) : (index += 1) { instance.array[index] = true; } index = 821; while (index <= 822) : (index += 1) { instance.array[index] = true; } instance.array[825] = true; index = 826; while (index <= 828) : (index += 1) { instance.array[index] = true; } instance.array[830] = true; instance.array[837] = true; index = 839; while (index <= 841) : (index += 1) { instance.array[index] = true; } instance.array[843] = true; index = 845; while (index <= 864) : (index += 1) { instance.array[index] = true; } index = 866; while (index <= 948) : (index += 1) { instance.array[index] = true; } index = 950; while (index <= 1088) : (index += 1) { instance.array[index] = true; } index = 1097; while (index <= 1262) : (index += 1) { instance.array[index] = true; } index = 1264; while (index <= 1301) : (index += 1) { instance.array[index] = true; } index = 1311; while (index <= 1351) : (index += 1) { instance.array[index] = true; } index = 4191; while (index <= 4228) : (index += 1) { instance.array[index] = true; } instance.array[4230] = true; instance.array[4236] = true; index = 4239; while (index <= 4281) : (index += 1) { instance.array[index] = true; } index = 4284; while (index <= 4286) : (index += 1) { instance.array[index] = true; } index = 4959; while (index <= 5044) : (index += 1) { instance.array[index] = true; } index = 5047; while (index <= 5052) : (index += 1) { instance.array[index] = true; } index = 7231; while (index <= 7239) : (index += 1) { instance.array[index] = true; } index = 7247; while (index <= 7289) : (index += 1) { instance.array[index] = true; } index = 7292; while (index <= 7294) : (index += 1) { instance.array[index] = true; } index = 7359; while (index <= 7402) : (index += 1) { instance.array[index] = true; } index = 7403; while (index <= 7465) : (index += 1) { instance.array[index] = true; } index = 7466; while (index <= 7478) : (index += 1) { instance.array[index] = true; } instance.array[7479] = true; index = 7480; while (index <= 7513) : (index += 1) { instance.array[index] = true; } index = 7514; while (index <= 7550) : (index += 1) { instance.array[index] = true; } index = 7615; while (index <= 7892) : (index += 1) { instance.array[index] = true; } index = 7895; while (index <= 7900) : (index += 1) { instance.array[index] = true; } index = 7903; while (index <= 7940) : (index += 1) { instance.array[index] = true; } index = 7943; while (index <= 7948) : (index += 1) { instance.array[index] = true; } index = 7951; while (index <= 7958) : (index += 1) { instance.array[index] = true; } instance.array[7960] = true; instance.array[7962] = true; instance.array[7964] = true; index = 7966; while (index <= 7996) : (index += 1) { instance.array[index] = true; } index = 7999; while (index <= 8051) : (index += 1) { instance.array[index] = true; } index = 8053; while (index <= 8059) : (index += 1) { instance.array[index] = true; } instance.array[8061] = true; index = 8065; while (index <= 8067) : (index += 1) { instance.array[index] = true; } index = 8069; while (index <= 8075) : (index += 1) { instance.array[index] = true; } index = 8079; while (index <= 8082) : (index += 1) { instance.array[index] = true; } index = 8085; while (index <= 8090) : (index += 1) { instance.array[index] = true; } index = 8095; while (index <= 8107) : (index += 1) { instance.array[index] = true; } index = 8113; while (index <= 8115) : (index += 1) { instance.array[index] = true; } index = 8117; while (index <= 8123) : (index += 1) { instance.array[index] = true; } instance.array[8240] = true; instance.array[8254] = true; index = 8271; while (index <= 8283) : (index += 1) { instance.array[index] = true; } instance.array[8385] = true; instance.array[8390] = true; index = 8393; while (index <= 8402) : (index += 1) { instance.array[index] = true; } instance.array[8404] = true; index = 8408; while (index <= 8412) : (index += 1) { instance.array[index] = true; } instance.array[8419] = true; instance.array[8421] = true; instance.array[8423] = true; index = 8425; while (index <= 8428) : (index += 1) { instance.array[index] = true; } index = 8430; while (index <= 8435) : (index += 1) { instance.array[index] = true; } instance.array[8440] = true; index = 8443; while (index <= 8446) : (index += 1) { instance.array[index] = true; } index = 8452; while (index <= 8456) : (index += 1) { instance.array[index] = true; } instance.array[8461] = true; index = 8479; while (index <= 8510) : (index += 1) { instance.array[index] = true; } index = 8514; while (index <= 8515) : (index += 1) { instance.array[index] = true; } index = 9333; while (index <= 9384) : (index += 1) { instance.array[index] = true; } index = 11199; while (index <= 11245) : (index += 1) { instance.array[index] = true; } index = 11247; while (index <= 11293) : (index += 1) { instance.array[index] = true; } index = 11295; while (index <= 11322) : (index += 1) { instance.array[index] = true; } index = 11323; while (index <= 11324) : (index += 1) { instance.array[index] = true; } index = 11325; while (index <= 11427) : (index += 1) { instance.array[index] = true; } index = 11434; while (index <= 11437) : (index += 1) { instance.array[index] = true; } index = 11441; while (index <= 11442) : (index += 1) { instance.array[index] = true; } index = 11455; while (index <= 11492) : (index += 1) { instance.array[index] = true; } instance.array[11494] = true; instance.array[11500] = true; index = 42495; while (index <= 42540) : (index += 1) { instance.array[index] = true; } index = 42559; while (index <= 42586) : (index += 1) { instance.array[index] = true; } index = 42587; while (index <= 42588) : (index += 1) { instance.array[index] = true; } index = 42721; while (index <= 42798) : (index += 1) { instance.array[index] = true; } instance.array[42799] = true; index = 42800; while (index <= 42822) : (index += 1) { instance.array[index] = true; } index = 42826; while (index <= 42829) : (index += 1) { instance.array[index] = true; } index = 42831; while (index <= 42878) : (index += 1) { instance.array[index] = true; } index = 42881; while (index <= 42889) : (index += 1) { instance.array[index] = true; } index = 42932; while (index <= 42933) : (index += 1) { instance.array[index] = true; } index = 42935; while (index <= 42936) : (index += 1) { instance.array[index] = true; } instance.array[42937] = true; index = 43759; while (index <= 43801) : (index += 1) { instance.array[index] = true; } index = 43803; while (index <= 43806) : (index += 1) { instance.array[index] = true; } index = 43807; while (index <= 43815) : (index += 1) { instance.array[index] = true; } index = 43823; while (index <= 43902) : (index += 1) { instance.array[index] = true; } index = 64191; while (index <= 64197) : (index += 1) { instance.array[index] = true; } index = 64210; while (index <= 64214) : (index += 1) { instance.array[index] = true; } index = 65248; while (index <= 65273) : (index += 1) { instance.array[index] = true; } index = 65280; while (index <= 65305) : (index += 1) { instance.array[index] = true; } index = 66495; while (index <= 66574) : (index += 1) { instance.array[index] = true; } index = 66671; while (index <= 66706) : (index += 1) { instance.array[index] = true; } index = 66711; while (index <= 66746) : (index += 1) { instance.array[index] = true; } index = 68671; while (index <= 68721) : (index += 1) { instance.array[index] = true; } index = 68735; while (index <= 68785) : (index += 1) { instance.array[index] = true; } index = 71775; while (index <= 71838) : (index += 1) { instance.array[index] = true; } index = 93695; while (index <= 93758) : (index += 1) { instance.array[index] = true; } index = 119743; while (index <= 119827) : (index += 1) { instance.array[index] = true; } index = 119829; while (index <= 119899) : (index += 1) { instance.array[index] = true; } index = 119901; while (index <= 119902) : (index += 1) { instance.array[index] = true; } instance.array[119905] = true; index = 119908; while (index <= 119909) : (index += 1) { instance.array[index] = true; } index = 119912; while (index <= 119915) : (index += 1) { instance.array[index] = true; } index = 119917; while (index <= 119928) : (index += 1) { instance.array[index] = true; } instance.array[119930] = true; index = 119932; while (index <= 119938) : (index += 1) { instance.array[index] = true; } index = 119940; while (index <= 120004) : (index += 1) { instance.array[index] = true; } index = 120006; while (index <= 120009) : (index += 1) { instance.array[index] = true; } index = 120012; while (index <= 120019) : (index += 1) { instance.array[index] = true; } index = 120021; while (index <= 120027) : (index += 1) { instance.array[index] = true; } index = 120029; while (index <= 120056) : (index += 1) { instance.array[index] = true; } index = 120058; while (index <= 120061) : (index += 1) { instance.array[index] = true; } index = 120063; while (index <= 120067) : (index += 1) { instance.array[index] = true; } instance.array[120069] = true; index = 120073; while (index <= 120079) : (index += 1) { instance.array[index] = true; } index = 120081; while (index <= 120420) : (index += 1) { instance.array[index] = true; } index = 120423; while (index <= 120447) : (index += 1) { instance.array[index] = true; } index = 120449; while (index <= 120473) : (index += 1) { instance.array[index] = true; } index = 120475; while (index <= 120505) : (index += 1) { instance.array[index] = true; } index = 120507; while (index <= 120531) : (index += 1) { instance.array[index] = true; } index = 120533; while (index <= 120563) : (index += 1) { instance.array[index] = true; } index = 120565; while (index <= 120589) : (index += 1) { instance.array[index] = true; } index = 120591; while (index <= 120621) : (index += 1) { instance.array[index] = true; } index = 120623; while (index <= 120647) : (index += 1) { instance.array[index] = true; } index = 120649; while (index <= 120679) : (index += 1) { instance.array[index] = true; } index = 120681; while (index <= 120705) : (index += 1) { instance.array[index] = true; } index = 120707; while (index <= 120714) : (index += 1) { instance.array[index] = true; } index = 125119; while (index <= 125186) : (index += 1) { instance.array[index] = true; } index = 127215; while (index <= 127240) : (index += 1) { instance.array[index] = true; } index = 127247; while (index <= 127272) : (index += 1) { instance.array[index] = true; } index = 127279; while (index <= 127304) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Cased) void { self.allocator.free(self.array); } // isCased checks if cp is of the kind Cased. pub fn isCased(self: Cased, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedCoreProperties/Cased.zig
const std = @import("std"); const builtin = @import("builtin"); const zwl = @import("zwl.zig"); usingnamespace @import("x11/types.zig"); const Allocator = std.mem.Allocator; const DisplayInfo = @import("x11/display_info.zig").DisplayInfo; const auth = @import("x11/auth.zig"); // A circular buffer for reply events that we expect const ReplyCBuffer = struct { const ReplyHandler = enum { ExtensionQueryBigRequests, BigRequestsEnable, ExtensionQueryXKB, ExtensionQueryMitShm, MitShmEnable, ExtensionQueryPresent, PresentEnable, ExtensionQueryXFixes, XFixesEnable, AtomMotifWmHints, }; const ReplyEvent = struct { seq: u32, handler: ReplyHandler, }; mem: [32]ReplyEvent = undefined, tail: u8 = 0, head: u8 = 0, seq_next: u32 = 1, pub fn len(self: *ReplyCBuffer) usize { var hp: usize = self.head; if (self.head < self.tail) hp += self.mem.len; return hp - self.tail; } pub fn push(self: *ReplyCBuffer, handler: ReplyHandler) !void { if (self.len() == self.mem.len - 1) return error.OutOfMemory; self.mem[self.head] = .{ .handler = handler, .seq = self.seq_next }; self.seq_next += 1; self.head = @intCast(u8, (self.head + 1) % self.mem.len); } pub fn ignoreEvent(self: *ReplyCBuffer) void { self.seq_next += 1; } pub fn get(self: *ReplyCBuffer, seq: u32) ?ReplyHandler { while (self.len() > 0) { const tailp = self.tail; const ev = self.mem[tailp]; if (ev.seq < seq) { unreachable; } else if (ev.seq == seq) { self.tail = @intCast(u8, (self.tail + 1) % self.mem.len); return ev.handler; } else { return null; } } return null; } }; pub fn Platform(comptime Parent: anytype) type { const file_is_always_unix = if (Parent.settings.remote == false and builtin.os.tag != .windows) true else false; return struct { const Self = @This(); parent: Parent, file: std.fs.File, file_is_unix: if (file_is_always_unix) void else bool, replies: ReplyCBuffer = .{}, rbuf: [1024]u8 align(8) = undefined, rbuf_n: usize = 0, xid_next: u32, root: WINDOW, root_depth: u8, root_color_bits: u8, max_req_len: u32 = 262140, // Atoms atom_motif_wm_hints: u32 = 0, // Extension info xfixes_major_opcode: u8 = 0, xfixes_first_event: u8 = 0, xkb_opcode_major: u8 = 0, xkb_first_event: u8 = 0, mitshm_major_opcode: u8 = 0, mitshm_first_event: u8 = 0, present_major_opcode: u8 = 0, present_first_event: u8 = 0, pub fn init(allocator: Allocator, options: zwl.PlatformOptions) !*Parent { if (builtin.os.tag == .windows) { _ = try std.os.windows.WSAStartup(2, 2); } errdefer { if (builtin.os.tag == .windows) { std.os.windows.WSACleanup() catch unreachable; } } var display_info_buf: [256]u8 = undefined; var display_info_allocator = std.heap.FixedBufferAllocator.init(display_info_buf[0..]); const display_info = try DisplayInfo.init(display_info_allocator.allocator(), options.x11.host, options.x11.display, options.x11.screen); const file = blk: { if (file_is_always_unix or display_info.unix) { break :blk try displayConnectUnix(display_info); } else { break :blk try displayConnectTCP(display_info); } }; errdefer file.close(); const auth_cookie: ?[16]u8 = if (options.x11.mit_magic_cookie != null) options.x11.mit_magic_cookie.? else try auth.getCookie(options.x11.xauthority_location); var rbuf = std.io.bufferedReader(file.reader()); var wbuf = std.io.bufferedWriter(file.writer()); var reader = rbuf.reader(); var writer = wbuf.writer(); try sendClientHandshake(auth_cookie, writer); try wbuf.flush(); const server_handshake = try readServerHandshake(reader); if (display_info.screen >= server_handshake.roots_len) { std.log.scoped(.zwl).err("X11 screen {} does not exist, max is {}", .{ display_info.screen, server_handshake.roots_len }); return error.InvalidScreen; } const screen_info = try readScreenInfo(server_handshake, display_info.screen, reader); var self = try allocator.create(Self); errdefer allocator.destroy(self); self.* = .{ .parent = .{ .allocator = allocator, .type = .X11, .window = undefined, .windows = if (!Parent.settings.single_window) &[0]*Parent.Window{} else undefined, }, .file = file, .file_is_unix = if (file_is_always_unix) undefined else display_info.unix, .xid_next = server_handshake.resource_id_base, .root = screen_info.root, .root_depth = screen_info.root_depth, .root_color_bits = screen_info.root_color_bits, }; // Init extensions try writer.writeAll(std.mem.asBytes(&QueryExtensionRequest{ .length_request = 4, .length_name = 6 })); try writer.writeAll("XFIXES"); try writer.writeByteNTimes(0, xpad("XFIXES".len)); try self.replies.push(.ExtensionQueryXFixes); try writer.writeAll(std.mem.asBytes(&QueryExtensionRequest{ .length_request = 5, .length_name = 12 })); try writer.writeAll("BIG-REQUESTS"); try self.replies.push(.ExtensionQueryBigRequests); try writer.writeAll(std.mem.asBytes(&QueryExtensionRequest{ .length_request = 5, .length_name = 9 })); try writer.writeAll("XKEYBOARD"); try writer.writeByteNTimes(0, xpad("XKEYBOARD".len)); try self.replies.push(.ExtensionQueryXKB); try writer.writeAll(std.mem.asBytes(&QueryExtensionRequest{ .length_request = 4, .length_name = 7 })); try writer.writeAll("MIT-SHM"); try writer.writeByteNTimes(0, xpad("MIT-SHM".len)); try self.replies.push(.ExtensionQueryMitShm); try writer.writeAll(std.mem.asBytes(&QueryExtensionRequest{ .length_request = 4, .length_name = 7 })); try writer.writeAll("Present"); try writer.writeByteNTimes(0, xpad("Present".len)); try self.replies.push(.ExtensionQueryPresent); // Get atoms try writer.writeAll(std.mem.asBytes(&InternAtom{ .if_exists = 0, .request_length = @intCast(u16, (8 + "_MOTIF_WM_HINTS".len + xpad("_MOTIF_WM_HINTS".len)) >> 2), .name_length = "_MOTIF_WM_HINTS".len, })); try writer.writeAll("_MOTIF_WM_HINTS"); try writer.writeByteNTimes(0, xpad("_MOTIF_WM_HINTS".len)); try self.replies.push(.AtomMotifWmHints); try wbuf.flush(); try self.handleInitEvents(); if (self.present_major_opcode == 0) return error.PresentExtensionNotPresent; std.log.scoped(.zwl).info("Platform Initialized: X11", .{}); return @ptrCast(*Parent, self); } fn handleInitEvents(self: *Self) !void { var rbuf = std.io.bufferedReader(self.file.reader()); var wbuf = std.io.bufferedWriter(self.file.writer()); var reader = rbuf.reader(); var writer = wbuf.writer(); while (self.replies.len() > 0) { var evdata: [32]u8 align(8) = undefined; _ = try reader.readAll(evdata[0..]); const evtype = evdata[0] & 0x7F; const seq = std.mem.readIntNative(u16, evdata[2..4]); const extlen = std.mem.readIntNative(u32, evdata[4..8]) * 4; if (evtype == @enumToInt(XEventCode.Error)) { unreachable; // We will never make mistakes during init } else if (evtype != @enumToInt(XEventCode.Reply)) { continue; // The only possible events here are stuff we don't care about } const handler = self.replies.get(seq) orelse unreachable; switch (handler) { .ExtensionQueryBigRequests => { const qreply = @ptrCast(*const QueryExtensionReply, &evdata); if (qreply.present != 0) { try writer.writeAll(std.mem.asBytes(&BigReqEnable{ .opcode = qreply.major_opcode })); try self.replies.push(.BigRequestsEnable); } }, .BigRequestsEnable => { const qreply = @ptrCast(*const BigReqEnableReply, &evdata); self.max_req_len = qreply.max_req_len; }, .ExtensionQueryXKB => { const qreply = @ptrCast(*const QueryExtensionReply, &evdata); if (qreply.present != 0) { self.xkb_first_event = qreply.major_opcode; self.xkb_opcode_major = qreply.first_event; // UseExtension } }, .ExtensionQueryMitShm => { const qreply = @ptrCast(*const QueryExtensionReply, &evdata); if (qreply.present != 0) { self.mitshm_major_opcode = qreply.major_opcode; self.mitshm_first_event = qreply.first_event; try writer.writeAll(std.mem.asBytes(&MitShmQueryVersion{ .opcode = qreply.major_opcode })); try self.replies.push(.MitShmEnable); } }, .MitShmEnable => { // Just need version 1, so whatever }, .ExtensionQueryPresent => { const qreply = @ptrCast(*const QueryExtensionReply, &evdata); if (qreply.present != 0) { self.present_major_opcode = qreply.major_opcode; self.present_first_event = qreply.first_event; try writer.writeAll(std.mem.asBytes(&PresentQueryVersion{ .opcode = qreply.major_opcode, .version_major = 1, .version_minor = 0 })); try self.replies.push(.PresentEnable); } }, .PresentEnable => { // Just need version 1, so whatever }, .ExtensionQueryXFixes => { const qreply = @ptrCast(*const QueryExtensionReply, &evdata); if (qreply.present != 0) { self.xfixes_major_opcode = qreply.major_opcode; self.xfixes_first_event = qreply.first_event; try writer.writeAll(std.mem.asBytes(&XFixesQueryVersion{ .opcode = qreply.major_opcode, .version_major = 5, .version_minor = 0 })); try self.replies.push(.XFixesEnable); } }, .XFixesEnable => { // Don't need to verify the version. We depend on the Present extension that depends on this, so whatever. }, .AtomMotifWmHints => { const qreply = @ptrCast(*const InternAtomReply, &evdata); self.atom_motif_wm_hints = qreply.atom; }, // else => unreachable, // The other events cannot appear during init } if (rbuf.fifo.readableLength() == 0) { try wbuf.flush(); } } } pub fn deinit(self: *Self) void { if (builtin.os.tag == .windows) { std.os.windows.WSACleanup() catch unreachable; } self.parent.allocator.destroy(self); } fn genXId(self: *Self) u32 { const id = self.xid_next; self.xid_next += 1; return id; } pub fn waitForEvent(self: *Self) !Parent.Event { var p: usize = 0; defer { std.mem.copy(u8, self.rbuf[0 .. self.rbuf_n - p], self.rbuf[p..self.rbuf_n]); self.rbuf_n -= p; } const generic_event_size = 32; while (true) { // If we've skipped so many events that we have to adjust the rbuf prematurely... if (self.rbuf.len - p < generic_event_size) { std.mem.copy(u8, self.rbuf[0 .. self.rbuf_n - p], self.rbuf[p..self.rbuf_n]); self.rbuf_n -= p; p = 0; } // Make sure we've got data for at least one event while (self.rbuf_n - p < generic_event_size) { self.rbuf_n += try self.file.read(self.rbuf[self.rbuf_n..]); } const evdata = self.rbuf[p .. p + generic_event_size]; const evtype = @intToEnum(XEventCode, evdata[0] & 0x7F); if (evtype == .GenericEvent) { const gev = @ptrCast(*const GenericEvent, @alignCast(4, evdata.ptr)); // std.log.info("Size: {}", .{generic_event_size + gev.length * 4}); // std.time.sleep(1000000); if (self.rbuf_n - p < generic_event_size + gev.length * 4) continue; defer p += generic_event_size + gev.length * 4; if (gev.extension == self.present_major_opcode) { if (gev.evtype == 1) { const present_complete = @ptrCast(*const PresentCompleteNotify, @alignCast(8, evdata.ptr)); // if we ever have an extended event with an odd number of bytes, this alignment will explode if (self.getWindowById(present_complete.window)) |window| { return Parent.Event{ .WindowVBlank = @ptrCast(*Parent.Window, window) }; } } } else { std.log.info("Unhandled generic event: {}.{}\n", .{ gev.extension, gev.evtype }); } } else { defer p += generic_event_size; switch (evtype) { .Error => { const ev = @ptrCast(*const XEventError, @alignCast(4, evdata.ptr)); std.log.err("{}: {}", .{ self.replies.seq_next, ev }); unreachable; }, .Reply => { // explicit reply for some request const extlen = std.mem.readIntNative(u32, evdata[4..8]) * 4; if (extlen > 0) unreachable; // Can't handle this yet }, .ReparentNotify, .MapNotify, .UnmapNotify, .NoExposure => { // Whatever }, .Expose => { const ev = @ptrCast(*const Expose, @alignCast(4, evdata.ptr)); if (self.getWindowById(ev.window)) |window| { // TODO: Not greater than underlying buffer...? return Parent.Event{ .WindowDamaged = .{ .window = @ptrCast(*Parent.Window, window), .x = ev.x, .y = ev.y, .w = ev.width, .h = ev.height, }, }; } }, .ConfigureNotify => { const ev = @ptrCast(*const ConfigureNotify, @alignCast(4, evdata.ptr)); if (self.getWindowById(ev.window)) |window| { if (window.width != ev.width or window.height != ev.height) { window.width = ev.width; window.height = ev.height; return Parent.Event{ .WindowResized = @ptrCast(*Parent.Window, window) }; } } }, .DestroyNotify => { const ev = @ptrCast(*const DestroyNotify, @alignCast(4, evdata.ptr)); if (self.getWindowById(ev.window)) |window| { window.handle = 0; return Parent.Event{ .WindowDestroyed = @ptrCast(*Parent.Window, window) }; } }, .KeyPress, .KeyRelease, .ButtonPress, .ButtonRelease, .MotionNotify, => { const ev = @ptrCast(*const InputDeviceEvent, @alignCast(4, evdata.ptr)); if (self.getWindowById(ev.event)) |window| { switch (evtype) { .KeyPress, .KeyRelease, => { var kev = zwl.KeyEvent{ .scancode = ev.detail - 8, }; return switch (evtype) { .KeyPress => Parent.Event{ .KeyDown = kev }, .KeyRelease => Parent.Event{ .KeyUp = kev }, else => unreachable, }; }, .ButtonPress, .ButtonRelease, => { var bev = zwl.MouseButtonEvent{ .x = ev.event_x, .y = ev.event_y, .button = @intToEnum(zwl.MouseButton, ev.detail), }; return switch (evtype) { .ButtonPress => Parent.Event{ .MouseButtonDown = bev }, .ButtonRelease => Parent.Event{ .MouseButtonUp = bev }, else => unreachable, }; }, .MotionNotify => return Parent.Event{ .MouseMotion = zwl.MouseMotionEvent{ .x = ev.event_x, .y = ev.event_y, }, }, else => unreachable, } } }, else => { std.log.info("Unhandled event: {}", .{evtype}); }, } } } } fn getWindowById(self: *Self, id: u32) ?*Window { if (Parent.settings.single_window) { const win = @ptrCast(*Window, self.parent.window); if (id == win.handle) return win; } else { for (self.parent.windows) |pwin| { const win = @ptrCast(*Window, pwin); if (win.handle == id) return win; } } return null; } pub fn createWindow(self: *Self, options: zwl.WindowOptions) !*Parent.Window { var window = try self.parent.allocator.create(Window); errdefer self.parent.allocator.destroy(window); var wbuf = std.io.bufferedWriter(self.file.writer()); var writer = wbuf.writer(); try window.init(self, options, writer); // todo: mode // todo: transparent if (options.resizeable == false) try window.disableResizeable(writer); if (options.title) |title| try window.setTitle(writer, title); if (options.decorations == false) try window.disableDecorations(writer); if (options.visible == true) try window.map(writer); try wbuf.flush(); return @ptrCast(*Parent.Window, window); } const WindowSWData = struct { gc: GCONTEXT, pixmap: PIXMAP, region: REGION, present_event: EventID, data: []u32 = &[0]u32{}, width: u16 = 0, height: u16 = 0, }; pub const Window = struct { parent: Parent.Window, handle: WINDOW, mapped: bool, width: u16, height: u16, sw: if (Parent.settings.backends_enabled.software) ?WindowSWData else void, pub fn init(self: *Window, platform: *Self, options: zwl.WindowOptions, writer: anytype) !void { self.* = .{ .parent = .{ .platform = @ptrCast(*Parent, platform), }, .width = options.width orelse 800, .height = options.height orelse 600, .handle = platform.genXId(), .mapped = if (options.visible == true) true else false, .sw = undefined, }; var values_n: u16 = 0; var value_mask: u32 = 0; var values: [2]u32 = undefined; values[values_n] = EventStructureNotify; values[values_n] |= if (options.track_damage == true) @as(u32, EventExposure) else 0; values[values_n] |= if (options.track_mouse == true) @as(u32, EventButtonPress | EventButtonRelease | EventPointerMotion) else 0; values[values_n] |= if (options.track_keyboard == true) @as(u32, EventKeyPress | EventKeyRelease) else 0; values_n += 1; value_mask |= CWEventMask; const create_window = CreateWindow{ .id = self.handle, .depth = 0, .x = 0, .y = 0, .parent = platform.root, .request_length = (@sizeOf(CreateWindow) >> 2) + values_n, .width = self.width, .height = self.height, .visual = 0, .mask = value_mask, }; try writer.writeAll(std.mem.asBytes(&create_window)); try writer.writeAll(std.mem.sliceAsBytes(values[0..values_n])); platform.replies.ignoreEvent(); if (Parent.settings.backends_enabled.software) { self.sw = .{ .gc = platform.genXId(), .pixmap = 0, .region = platform.genXId(), .present_event = platform.genXId(), }; const create_gc = CreateGC{ .request_length = 4, .cid = self.sw.?.gc, .drawable = .{ .window = self.handle }, .bitmask = 0, }; const create_region = CreateRegion{ .opcode = platform.xfixes_major_opcode, .length_request = 2, .region = self.sw.?.region, }; try writer.writeAll(std.mem.asBytes(&create_region)); platform.replies.ignoreEvent(); const select_input = PresentSelectInput{ .opcode = platform.present_major_opcode, .event_id = self.sw.?.present_event, .window = self.handle, .mask = 2, }; try writer.writeAll(std.mem.asBytes(&select_input)); platform.replies.ignoreEvent(); // TODO: SHM when it's in Zig stdlib... // TODO: disable GraphicsExpose and NoExpose? try writer.writeAll(std.mem.asBytes(&create_gc)); platform.replies.ignoreEvent(); } } pub fn deinit(self: *Window) void { var platform = @ptrCast(*Self, self.parent.platform); var wbuf = std.io.bufferedWriter(platform.file.writer()); var writer = wbuf.writer(); if (Parent.settings.backends_enabled.software) { writer.writeAll(std.mem.asBytes(&FreeGC{ .gc = self.sw.?.gc })) catch return; platform.replies.ignoreEvent(); if (self.sw.?.pixmap != 0) { writer.writeAll(std.mem.asBytes(&FreePixmap{ .pixmap = self.sw.?.pixmap })) catch return; platform.replies.ignoreEvent(); } const destroy_region = DestroyRegion{ .opcode = platform.xfixes_major_opcode, .region = self.sw.?.region }; writer.writeAll(std.mem.asBytes(&destroy_region)) catch return; platform.replies.ignoreEvent(); const select_input = PresentSelectInput{ .opcode = platform.present_major_opcode, .event_id = self.sw.?.present_event, .window = self.handle, .mask = 0, }; writer.writeAll(std.mem.asBytes(&select_input)) catch return; platform.replies.ignoreEvent(); platform.parent.allocator.free(self.sw.?.data); } if (self.handle != 0) { const destroy_window = DestroyWindow{ .id = self.handle }; writer.writeAll(std.mem.asBytes(&destroy_window)) catch return; platform.replies.ignoreEvent(); } wbuf.flush() catch return; platform.parent.allocator.destroy(self); } pub fn configure(self: *Window, options: zwl.WindowOptions) !void { var platform = @ptrCast(*Self, self.parent.platform); var wbuf = std.io.bufferedWriter(platform.file.writer()); var writer = wbuf.writer(); const needs_remap = (options.resizeable != null); if (needs_remap and self.mapped == true) { try self.unmap(writer); } // todo: width, height // todo: mode // todo: transparent if (options.resizeable == true) try self.enableResizeable(writer); if (options.resizeable == false) try self.disableResizeable(writer); if (options.decorations == true) try self.enableDecorations(writer); if (options.decorations == false) try self.disableDecorations(writer); if (options.title) |title| try self.setTitle(writer, title); if (options.visible == false) { try self.unmap(writer); } else if (options.visible == true) { try self.map(writer); } else if (needs_remap == true) { try self.map(writer); } try wbuf.flush(); } pub fn mapPixels(self: *Window) !zwl.PixelBuffer { var platform = @ptrCast(*Self, self.parent.platform); var wbuf = std.io.bufferedWriter(platform.file.writer()); var writer = wbuf.writer(); if (self.sw.?.pixmap == 0 or self.sw.?.width != self.width or self.sw.?.height != self.height) { if (self.sw.?.pixmap != 0) { try writer.writeAll(std.mem.asBytes(&FreePixmap{ .pixmap = self.sw.?.pixmap })); platform.replies.ignoreEvent(); } self.sw.?.pixmap = platform.genXId(); self.sw.?.width = self.width; self.sw.?.height = self.height; const create_pixmap = CreatePixmap{ .depth = platform.root_depth, .pid = self.sw.?.pixmap, .drawable = .{ .window = self.handle }, .width = self.sw.?.width, .height = self.sw.?.height, }; try writer.writeAll(std.mem.asBytes(&create_pixmap)); platform.replies.ignoreEvent(); // Todo: MIT-SHM self.sw.?.data = try platform.parent.allocator.realloc(self.sw.?.data, @intCast(usize, self.sw.?.width) * @intCast(usize, self.sw.?.height)); } try wbuf.flush(); return zwl.PixelBuffer{ .data = self.sw.?.data.ptr, .width = self.sw.?.width, .height = self.sw.?.height }; } pub fn submitPixels(self: *Window, updates: []const zwl.UpdateArea) !void { var platform = @ptrCast(*Self, self.parent.platform); var wbuf = std.io.bufferedWriter(platform.file.writer()); var writer = wbuf.writer(); // If no MIT-SHM, send pixels manually if (true) { for (updates) |update| { const pixels_n = @as(u32, update.w) * @as(u32, update.h); const put_image = PutImageBig{ .request_length = 7 + pixels_n, .drawable = .{ .pixmap = self.sw.?.pixmap }, .gc = self.sw.?.gc, .width = update.w, .height = update.h, .dst = [2]u16{ update.x, update.y }, .left_pad = 0, .depth = 24, }; try writer.writeAll(std.mem.asBytes(&put_image)); if (update.w == self.sw.?.width) { const offset = @as(u32, update.w) * @as(u32, update.y); try writer.writeAll(std.mem.sliceAsBytes(self.sw.?.data[offset .. offset + pixels_n])); } else { var ri: u16 = 0; while (ri < update.h) : (ri += 1) { const row_pixels_n = @as(u32, update.w); const row_pixels_offset = (@as(u32, self.sw.?.width) * @as(u32, update.y + ri)) + @as(u32, update.x); try writer.writeAll(std.mem.sliceAsBytes(self.sw.?.data[row_pixels_offset .. row_pixels_offset + row_pixels_n])); } } platform.replies.ignoreEvent(); } } // TODO: MIT-SHM // Set the change region const set_region = SetRegion{ .opcode = platform.xfixes_major_opcode, .length_request = 2 + @intCast(u16, updates.len * 2), .region = self.sw.?.region, }; try writer.writeAll(std.mem.asBytes(&set_region)); for (updates) |update| { const rect = [4]u16{ update.x, update.y, update.w, update.h }; try writer.writeAll(std.mem.asBytes(&rect)); } platform.replies.ignoreEvent(); // Present! const present_pixmap = PresentPixmap{ .length = 18, .opcode = platform.present_major_opcode, .window = self.handle, .pixmap = self.sw.?.pixmap, .serial = 0, .valid_area = self.sw.?.region, .update_area = self.sw.?.region, .crtc = 0, .wait_fence = 0, .idle_fence = 0, .options = 0, .target_msc = 0, .divisor = 0, .remainder = 0, }; try writer.writeAll(std.mem.asBytes(&present_pixmap)); const present_notify = PresentNotify{ .window = self.handle, .serial = 0, }; // Add this to segfault X11 //try writer.writeAll(std.mem.asBytes(&present_notify)); platform.replies.ignoreEvent(); try wbuf.flush(); } pub fn getSize(self: *Window) [2]u16 { return [2]u16{ self.width, self.height }; } fn map(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); try writer.writeAll(std.mem.asBytes(&MapWindow{ .id = self.handle })); platform.replies.ignoreEvent(); } fn unmap(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); try writer.writeAll(std.mem.asBytes(&UnmapWindow{ .id = self.handle })); platform.replies.ignoreEvent(); } fn disableResizeable(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); const size_hints_request = ChangeProperty{ .window = self.handle, .request_length = @intCast(u16, (@sizeOf(ChangeProperty) + @sizeOf(SizeHints)) >> 2), .property = @enumToInt(BuiltinAtom.WM_NORMAL_HINTS), .property_type = @enumToInt(BuiltinAtom.WM_SIZE_HINTS), .format = 32, .length = @sizeOf(SizeHints) >> 2, }; try writer.writeAll(std.mem.asBytes(&size_hints_request)); const size_hints: SizeHints = .{ .flags = (1 << 4) + (1 << 5) + (1 << 8), .min = [2]u32{ self.width, self.height }, .max = [2]u32{ self.width, self.height }, .base = [2]u32{ self.width, self.height }, }; try writer.writeAll(std.mem.asBytes(&size_hints)); platform.replies.ignoreEvent(); } fn enableResizeable(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); const size_hints_request = DeleteProperty{ .window = self.handle, .property = @enumToInt(BuiltinAtom.WM_NORMAL_HINTS), }; try writer.writeAll(std.mem.asBytes(&size_hints_request)); platform.replies.ignoreEvent(); } fn setTitle(self: *Window, writer: anytype, title: []const u8) !void { var platform = @ptrCast(*Self, self.parent.platform); const title_request = ChangeProperty{ .window = self.handle, .request_length = @intCast(u16, (@sizeOf(ChangeProperty) + title.len + xpad(title.len)) >> 2), .property = @enumToInt(BuiltinAtom.WM_NAME), .property_type = @enumToInt(BuiltinAtom.STRING), .format = 8, .length = @intCast(u32, title.len), }; try writer.writeAll(std.mem.asBytes(&title_request)); try writer.writeAll(title); try writer.writeByteNTimes(0, xpad(title.len)); platform.replies.ignoreEvent(); } fn disableDecorations(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); const hints = MotifHints{ .flags = 2, .functions = 0, .decorations = 0, .input_mode = 0, .status = 0 }; const hints_request = ChangeProperty{ .window = self.handle, .request_length = @intCast(u16, (@sizeOf(ChangeProperty) + @sizeOf(MotifHints)) >> 2), .property = platform.atom_motif_wm_hints, .property_type = platform.atom_motif_wm_hints, .format = 32, .length = @intCast(u32, @sizeOf(MotifHints) >> 2), }; try writer.writeAll(std.mem.asBytes(&hints_request)); try writer.writeAll(std.mem.asBytes(&hints)); platform.replies.ignoreEvent(); } fn enableDecorations(self: *Window, writer: anytype) !void { var platform = @ptrCast(*Self, self.parent.platform); const size_hints_request = DeleteProperty{ .window = self.handle, .property = platform.atom_motif_wm_hints, }; try writer.writeAll(std.mem.asBytes(&size_hints_request)); platform.replies.ignoreEvent(); } }; }; } fn xpad(n: usize) usize { return @bitCast(usize, (-%@bitCast(isize, n)) & 3); } fn displayConnectUnix(display_info: DisplayInfo) !std.fs.File { const opt_non_block = if (std.io.is_async) os.SOCK_NONBLOCK else 0; var socket = try std.os.socket(std.os.AF_UNIX, std.os.SOCK_STREAM | std.os.SOCK_CLOEXEC | opt_non_block, 0); errdefer std.os.close(socket); var addr = std.os.sockaddr_un{ .path = [_]u8{0} ** 108 }; std.mem.copy(u8, addr.path[0..], "\x00/tmp/.X11-unix/X"); _ = std.fmt.formatIntBuf(addr.path["\x00/tmp/.X11-unix/X".len..], display_info.display, 10, false, .{}); const addrlen = 1 + std.mem.lenZ(@ptrCast([*:0]u8, addr.path[1..])); try std.os.connect(socket, @ptrCast(*const std.os.sockaddr, &addr), @sizeOf(std.os.sockaddr_un) - @intCast(u32, addr.path.len - addrlen)); return std.fs.File{ .handle = socket }; } fn displayConnectTCP(display_info: DisplayInfo) !std.fs.File { const hostname = if (std.mem.eql(u8, display_info.host, "")) "127.0.0.1" else display_info.host; var tmpmem: [4096]u8 = undefined; var tmpalloc = std.heap.FixedBufferAllocator.init(tmpmem[0..]); const file = try std.net.tcpConnectToHost(tmpalloc.allocator(), hostname, 6000 + @intCast(u16, display_info.display)); errdefer file.close(); // Set TCP_NODELAY? return file; } fn sendClientHandshake(auth_cookie: ?[16]u8, writer: anytype) !void { if (auth_cookie) |cookie| { const req: extern struct { setup: SetupRequest, mit_magic_cookie_str: [20]u8, mit_magic_cookie_value: [16]u8, } = .{ .setup = .{ .auth_proto_name_len = "MIT-MAGIC-COOKIE-1".len, .auth_proto_data_len = 16, }, .mit_magic_cookie_str = "MIT-MAGIC-COOKIE-1\x00\x00".*, .mit_magic_cookie_value = cookie, }; _ = try writer.writeAll(std.mem.asBytes(&req)); } else { _ = try writer.writeAll(std.mem.asBytes(&SetupRequest{})); } } const ServerHandshake = struct { resource_id_base: u32, pixmap_formats_len: u32, roots_len: u32, }; fn readServerHandshake(reader: anytype) !ServerHandshake { const response_header = try reader.readStruct(SetupResponseHeader); switch (response_header.status) { 0 => { var reason_buf: [256]u8 = undefined; _ = try reader.readAll(reason_buf[0..response_header.reason_length]); var reason = reason_buf[0..response_header.reason_length]; if (reason.len > 0 and reason[reason.len - 1] == '\n') reason = reason[0 .. reason.len - 1]; std.log.scoped(.zwl).err("X11 handshake failed: {}", .{reason}); return error.HandshakeFailed; }, 1 => { var server_handshake: ServerHandshake = undefined; const response = try reader.readStruct(SetupAccepted); server_handshake.resource_id_base = response.resource_id_base; server_handshake.pixmap_formats_len = response.pixmap_formats_len; server_handshake.roots_len = response.roots_len; try reader.skipBytes(response.vendor_len + xpad(response.vendor_len), .{ .buf_size = 32 }); return server_handshake; }, else => return error.Protocol, } } const ScreenInfo = struct { root: u32, root_depth: u8, root_color_bits: u8, }; fn readScreenInfo(server_handshake: ServerHandshake, screen_id: usize, reader: anytype) !ScreenInfo { var screen_info: ScreenInfo = undefined; var pfi: usize = 0; while (pfi < server_handshake.pixmap_formats_len) : (pfi += 1) { const format = try reader.readStruct(PixmapFormat); } var sci: usize = 0; while (sci < server_handshake.roots_len) : (sci += 1) { const screen = try reader.readStruct(Screen); if (sci == screen_id) { screen_info.root = screen.root; } var dpi: usize = 0; while (dpi < screen.allowed_depths_len) : (dpi += 1) { const depth = try reader.readStruct(Depth); var vii: usize = 0; while (vii < depth.visual_count) : (vii += 1) { const visual = try reader.readStruct(Visual); if (sci == screen_id and screen.root_visual_id == visual.id) { screen_info.root_depth = depth.depth; screen_info.root_color_bits = visual.bits_per_rgb; } } } } return screen_info; }
didot-zwl/zwl/src/x11.zig
const std = @import("std"); const reg = @import("registry.zig"); const id_render = @import("../id_render.zig"); const cparse = @import("c_parse.zig"); const mem = std.mem; const Allocator = mem.Allocator; const CaseStyle = id_render.CaseStyle; const IdRenderer = id_render.IdRenderer; const preamble = \\// This file is generated from the Khronos Vulkan XML API registry by vulkan-zig. \\ \\const std = @import("std"); \\const builtin = @import("builtin"); \\const root = @import("root"); \\ \\pub const vulkan_call_conv: std.builtin.CallingConvention = if (builtin.os.tag == .windows and builtin.cpu.arch == .i386) \\ .Stdcall \\ else if (builtin.abi == .android and (builtin.cpu.arch.isARM() or builtin.cpu.arch.isThumb()) and std.Target.arm.featureSetHas(builtin.cpu.features, .has_v7) and builtin.cpu.arch.ptrBitWidth() == 32) \\ // On Android 32-bit ARM targets, Vulkan functions use the "hardfloat" \\ // calling convention, i.e. float parameters are passed in registers. This \\ // is true even if the rest of the application passes floats on the stack, \\ // as it does by default when compiling for the armeabi-v7a NDK ABI. \\ .AAPCSVFP \\ else \\ .C; \\pub fn FlagsMixin(comptime FlagsType: type, comptime Int: type) type { \\ return struct { \\ pub const IntType = Int; \\ pub fn toInt(self: FlagsType) IntType { \\ return @bitCast(IntType, self); \\ } \\ pub fn fromInt(flags: IntType) FlagsType { \\ return @bitCast(FlagsType, flags); \\ } \\ pub fn merge(lhs: FlagsType, rhs: FlagsType) FlagsType { \\ return fromInt(toInt(lhs) | toInt(rhs)); \\ } \\ pub fn intersect(lhs: FlagsType, rhs: FlagsType) FlagsType { \\ return fromInt(toInt(lhs) & toInt(rhs)); \\ } \\ pub fn complement(self: FlagsType) FlagsType { \\ return fromInt(~toInt(self)); \\ } \\ pub fn subtract(lhs: FlagsType, rhs: FlagsType) FlagsType { \\ return fromInt(toInt(lhs) & toInt(rhs.complement())); \\ } \\ pub fn contains(lhs: FlagsType, rhs: FlagsType) bool { \\ return toInt(intersect(lhs, rhs)) == toInt(rhs); \\ } \\ }; \\} \\pub fn makeApiVersion(variant: u3, major: u7, minor: u10, patch: u12) u32 { \\ return (@as(u32, variant) << 29) | (@as(u32, major) << 22) | (@as(u32, minor) << 12) | patch; \\} \\pub fn apiVersionVariant(version: u32) u3 { \\ return @truncate(u3, version >> 29); \\} \\pub fn apiVersionMajor(version: u32) u7 { \\ return @truncate(u7, version >> 22); \\} \\pub fn apiVersionMinor(version: u32) u10 { \\ return @truncate(u10, version >> 12); \\} \\pub fn apiVersionPatch(version: u32) u12 { \\ return @truncate(u12, version); \\} \\ ; const builtin_types = std.ComptimeStringMap([]const u8, .{ .{ "void", @typeName(void) }, .{ "char", @typeName(u8) }, .{ "float", @typeName(f32) }, .{ "double", @typeName(f64) }, .{ "uint8_t", @typeName(u8) }, .{ "uint16_t", @typeName(u16) }, .{ "uint32_t", @typeName(u32) }, .{ "uint64_t", @typeName(u64) }, .{ "int8_t", @typeName(i8) }, .{ "int16_t", @typeName(i16) }, .{ "int32_t", @typeName(i32) }, .{ "int64_t", @typeName(i64) }, .{ "size_t", @typeName(usize) }, .{ "int", @typeName(c_int) }, }); const foreign_types = std.ComptimeStringMap([]const u8, .{ .{ "Display", "opaque {}" }, .{ "VisualID", @typeName(c_uint) }, .{ "Window", @typeName(c_ulong) }, .{ "RROutput", @typeName(c_ulong) }, .{ "wl_display", "opaque {}" }, .{ "wl_surface", "opaque {}" }, .{ "HINSTANCE", "std.os.windows.HINSTANCE" }, .{ "HWND", "std.os.windows.HWND" }, .{ "HMONITOR", "*opaque {}" }, .{ "HANDLE", "std.os.windows.HANDLE" }, .{ "SECURITY_ATTRIBUTES", "std.os.SECURITY_ATTRIBUTES" }, .{ "DWORD", "std.os.windows.DWORD" }, .{ "LPCWSTR", "std.os.windows.LPCWSTR" }, .{ "xcb_connection_t", "opaque {}" }, .{ "xcb_visualid_t", @typeName(u32) }, .{ "xcb_window_t", @typeName(u32) }, .{ "zx_handle_t", @typeName(u32) }, .{ "_screen_context", "opaque {}" }, .{ "_screen_window", "opaque {}" }, }); fn eqlIgnoreCase(lhs: []const u8, rhs: []const u8) bool { if (lhs.len != rhs.len) { return false; } for (lhs) |c, i| { if (std.ascii.toLower(c) != std.ascii.toLower(rhs[i])) { return false; } } return true; } pub fn trimVkNamespace(id: []const u8) []const u8 { const prefixes = [_][]const u8{ "VK_", "vk", "Vk", "PFN_vk" }; for (prefixes) |prefix| { if (mem.startsWith(u8, id, prefix)) { return id[prefix.len..]; } } return id; } fn Renderer(comptime WriterType: type) type { return struct { const Self = @This(); const WriteError = WriterType.Error; const RenderTypeInfoError = WriteError || std.fmt.ParseIntError || error{ OutOfMemory, InvalidRegistry }; const BitflagName = struct { /// Name without FlagBits, so VkSurfaceTransformFlagBitsKHR /// becomes VkSurfaceTransform base_name: []const u8, /// Optional flag bits revision, used in places like VkAccessFlagBits2KHR revision: ?[]const u8, /// Optional tag of the flag tag: ?[]const u8, }; const ParamType = enum { in_pointer, out_pointer, in_out_pointer, bitflags, mut_buffer_len, buffer_len, other, }; const ReturnValue = struct { name: []const u8, return_value_type: reg.TypeInfo, origin: enum { parameter, inner_return_value, }, }; const CommandDispatchType = enum { base, instance, device, }; writer: WriterType, allocator: Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer, declarations_by_name: std.StringHashMap(*const reg.DeclarationType), fn init(writer: WriterType, allocator: Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !Self { var declarations_by_name = std.StringHashMap(*const reg.DeclarationType).init(allocator); errdefer declarations_by_name.deinit(); for (registry.decls) |*decl| { const result = try declarations_by_name.getOrPut(decl.name); if (result.found_existing) { return error.InvalidRegistry; } result.value_ptr.* = &decl.decl_type; } return Self{ .writer = writer, .allocator = allocator, .registry = registry, .id_renderer = id_renderer, .declarations_by_name = declarations_by_name, }; } fn deinit(self: *Self) void { self.declarations_by_name.deinit(); } fn writeIdentifier(self: Self, id: []const u8) !void { try id_render.writeIdentifier(self.writer, id); } fn writeIdentifierWithCase(self: *Self, case: CaseStyle, id: []const u8) !void { try self.id_renderer.renderWithCase(self.writer, case, id); } fn writeIdentifierFmt(self: *Self, comptime fmt: []const u8, args: anytype) !void { try self.id_renderer.renderFmt(self.writer, fmt, args); } fn extractEnumFieldName(self: Self, enum_name: []const u8, field_name: []const u8) ![]const u8 { const adjusted_enum_name = self.id_renderer.stripAuthorTag(enum_name); var enum_it = id_render.SegmentIterator.init(adjusted_enum_name); var field_it = id_render.SegmentIterator.init(field_name); while (true) { const rest = field_it.rest(); const field_segment = field_it.next() orelse return error.InvalidRegistry; const enum_segment = enum_it.next() orelse return rest; if (!eqlIgnoreCase(enum_segment, field_segment)) { return rest; } } } fn extractBitflagFieldName(bitflag_name: BitflagName, field_name: []const u8) ![]const u8 { var flag_it = id_render.SegmentIterator.init(bitflag_name.base_name); var field_it = id_render.SegmentIterator.init(field_name); while (true) { const rest = field_it.rest(); const field_segment = field_it.next() orelse return error.InvalidRegistry; const flag_segment = flag_it.next() orelse { if (bitflag_name.revision) |revision| { if (mem.eql(u8, revision, field_segment)) return field_it.rest(); } return rest; }; if (!eqlIgnoreCase(flag_segment, field_segment)) { return rest; } } } fn extractBitflagName(self: Self, name: []const u8) !?BitflagName { const tag = self.id_renderer.getAuthorTag(name); const tagless_name = if (tag) |tag_name| name[0 .. name.len - tag_name.len] else name; // Strip out the "version" number of a bitflag, like VkAccessFlagBits2KHR. const base_name = std.mem.trimRight(u8, tagless_name, "0123456789"); const maybe_flag_bits_index = mem.lastIndexOf(u8, base_name, "FlagBits"); if (maybe_flag_bits_index == null) { return null; } else if (maybe_flag_bits_index != base_name.len - "FlagBits".len) { // It is unlikely that a type that is not a flag bit would contain FlagBits, // and more likely that we have missed something if FlagBits isn't the last // part of base_name return error.InvalidRegistry; } return BitflagName{ .base_name = base_name[0 .. base_name.len - "FlagBits".len], .revision = if (base_name.len != tagless_name.len) tagless_name[base_name.len..] else null, .tag = tag, }; } fn isFlags(self: Self, name: []const u8) bool { const tag = self.id_renderer.getAuthorTag(name); const base_name = if (tag) |tag_name| name[0 .. name.len - tag_name.len] else name; return mem.endsWith(u8, base_name, "Flags"); } fn isInOutPointer(self: Self, ptr: reg.Pointer) !bool { if (ptr.child.* != .name) { return false; } var name = ptr.child.name; const decl = while (true) { const decl = self.declarations_by_name.get(name) orelse return error.InvalidRegistry; if (decl.* != .alias) { break decl; } name = decl.alias.name; } else unreachable; if (decl.* != .container) { return false; } const container = decl.container; if (container.is_union) { return false; } for (container.fields) |field| { if (mem.eql(u8, field.name, "pNext")) { return true; } } return false; } fn classifyParam(self: Self, param: reg.Command.Param) !ParamType { switch (param.param_type) { .pointer => |ptr| { if (param.is_buffer_len) { if (ptr.is_const or ptr.is_optional) { return error.InvalidRegistry; } return .mut_buffer_len; } if (ptr.child.* == .name) { const child_name = ptr.child.name; if (mem.eql(u8, child_name, "void")) { return .other; } else if (builtin_types.get(child_name) == null and trimVkNamespace(child_name).ptr == child_name.ptr) { return .other; // External type } } if (ptr.size == .one and !ptr.is_optional) { // Sometimes, a mutable pointer to a struct is taken, even though // Vulkan expects this struct to be initialized. This is particularly the case // for getting structs which include pNext chains. if (ptr.is_const) { return .in_pointer; } else if (try self.isInOutPointer(ptr)) { return .in_out_pointer; } else { return .out_pointer; } } }, .name => |name| { if ((try self.extractBitflagName(name)) != null or self.isFlags(name)) { return .bitflags; } }, else => {}, } if (param.is_buffer_len) { return .buffer_len; } return .other; } fn classifyCommandDispatch(name: []const u8, command: reg.Command) CommandDispatchType { const device_handles = std.ComptimeStringMap(void, .{ .{ "VkDevice", {} }, .{ "VkCommandBuffer", {} }, .{ "VkQueue", {} }, }); const override_functions = std.ComptimeStringMap(CommandDispatchType, .{ .{ "vkGetInstanceProcAddr", .base }, .{ "vkCreateInstance", .base }, .{ "vkEnumerateInstanceLayerProperties", .base }, .{ "vkEnumerateInstanceExtensionProperties", .base }, .{ "vkEnumerateInstanceVersion", .base }, .{ "vkGetDeviceProcAddr", .instance }, }); if (override_functions.get(name)) |dispatch_type| { return dispatch_type; } switch (command.params[0].param_type) { .name => |first_param_type_name| { if (device_handles.get(first_param_type_name)) |_| { return .device; } }, else => {}, } return .instance; } fn render(self: *Self) !void { try self.writer.writeAll(preamble); try self.renderCommandEnums(); for (self.registry.api_constants) |api_constant| { try self.renderApiConstant(api_constant); } for (self.registry.decls) |decl| { try self.renderDecl(decl); } try self.renderCommandPtrs(); try self.renderExtensionInfo(); try self.renderWrappers(); } fn renderCommandEnums(self: *Self) !void { try self.renderCommandEnumOfDispatchType(.base); try self.renderCommandEnumOfDispatchType(.instance); try self.renderCommandEnumOfDispatchType(.device); try self.writer.writeAll("\n"); } fn renderCommandEnumOfDispatchType(self: *Self, dispatch_type: CommandDispatchType) !void { const dispatch_type_name = switch (dispatch_type) { .base => "Base", .instance => "Instance", .device => "Device", }; try self.writer.print("pub const {s}Command = enum {{\n", .{dispatch_type_name}); for (self.registry.decls) |decl| { const command = switch (decl.decl_type) { .command => |cmd| cmd, else => continue, }; if (classifyCommandDispatch(decl.name, command) == dispatch_type) { try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name)); try self.writer.writeAll(",\n"); } } { try self.writer.print( \\ \\pub fn symbol(self: {s}Command) [:0]const u8 {{ \\ return switch (self) {{ \\ , .{dispatch_type_name}, ); for (self.registry.decls) |decl| { const command = switch (decl.decl_type) { .command => |cmd| cmd, else => continue, }; if (classifyCommandDispatch(decl.name, command) == dispatch_type) { try self.writer.writeAll("."); try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name)); try self.writer.print(" => \"{s}\",\n", .{decl.name}); } } try self.writer.writeAll("};\n}\n"); } { try self.writer.print( \\ \\pub fn PfnType(comptime self: {s}Command) type {{ \\ return switch (self) {{ \\ , .{dispatch_type_name}, ); for (self.registry.decls) |decl| { const command = switch (decl.decl_type) { .command => |cmd| cmd, else => continue, }; if (classifyCommandDispatch(decl.name, command) == dispatch_type) { try self.writer.writeAll("."); try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name)); try self.writer.writeAll(" => "); try self.renderCommandPtrName(decl.name); try self.writer.writeAll(",\n"); } } try self.writer.writeAll("};\n}\n"); } try self.writer.writeAll("};\n"); } fn renderApiConstant(self: *Self, api_constant: reg.ApiConstant) !void { try self.writer.writeAll("pub const "); try self.renderName(api_constant.name); try self.writer.writeAll(" = "); switch (api_constant.value) { .expr => |expr| try self.renderApiConstantExpr(expr), .version => |version| { try self.writer.writeAll("makeApiVersion("); for (version) |part, i| { if (i != 0) { try self.writer.writeAll(", "); } try self.renderApiConstantExpr(part); } try self.writer.writeAll(")"); }, } try self.writer.writeAll(";\n"); } fn renderApiConstantExpr(self: *Self, expr: []const u8) !void { const adjusted_expr = if (expr.len > 2 and expr[0] == '(' and expr[expr.len - 1] == ')') expr[1 .. expr.len - 1] else expr; var tokenizer = cparse.CTokenizer{ .source = adjusted_expr }; var peeked: ?cparse.Token = null; while (true) { const tok = peeked orelse (try tokenizer.next()) orelse break; peeked = null; switch (tok.kind) { .lparen, .rparen, .tilde, .minus => { try self.writer.writeAll(tok.text); continue; }, .id => { try self.renderName(tok.text); continue; }, .int => {}, else => return error.InvalidApiConstant, } const suffix = (try tokenizer.next()) orelse { try self.writer.writeAll(tok.text); break; }; switch (suffix.kind) { .id => { if (mem.eql(u8, suffix.text, "ULL")) { try self.writer.print("@as(u64, {s})", .{tok.text}); } else if (mem.eql(u8, suffix.text, "U")) { try self.writer.print("@as(u32, {s})", .{tok.text}); } else { return error.InvalidApiConstant; } }, .dot => { const decimal = (try tokenizer.next()) orelse return error.InvalidConstantExpr; try self.writer.print("@as(f32, {s}.{s})", .{ tok.text, decimal.text }); const f = (try tokenizer.next()) orelse return error.InvalidConstantExpr; if (f.kind != .id or f.text.len != 1 or (f.text[0] != 'f' and f.text[0] != 'F')) { return error.InvalidApiConstant; } }, else => { try self.writer.writeAll(tok.text); peeked = suffix; }, } } } fn renderTypeInfo(self: *Self, type_info: reg.TypeInfo) RenderTypeInfoError!void { switch (type_info) { .name => |name| try self.renderName(name), .command_ptr => |command_ptr| try self.renderCommandPtr(command_ptr, true), .pointer => |pointer| try self.renderPointer(pointer), .array => |array| try self.renderArray(array), } } fn renderName(self: *Self, name: []const u8) !void { if (builtin_types.get(name)) |zig_name| { try self.writer.writeAll(zig_name); return; } else if (try self.extractBitflagName(name)) |bitflag_name| { try self.writeIdentifierFmt("{s}Flags{s}{s}", .{ trimVkNamespace(bitflag_name.base_name), @as([]const u8, if (bitflag_name.revision) |revision| revision else ""), @as([]const u8, if (bitflag_name.tag) |tag| tag else ""), }); return; } else if (mem.startsWith(u8, name, "vk")) { // Function type, always render with the exact same text for linking purposes. try self.writeIdentifier(name); return; } else if (mem.startsWith(u8, name, "Vk")) { // Type, strip namespace and write, as they are alreay in title case. try self.writeIdentifier(name[2..]); return; } else if (mem.startsWith(u8, name, "PFN_vk")) { // Function pointer type, strip off the PFN_vk part and replace it with Pfn. Note that // this function is only called to render the typedeffed function pointers like vkVoidFunction try self.writeIdentifierFmt("Pfn{s}", .{name[6..]}); return; } else if (mem.startsWith(u8, name, "VK_")) { // Constants try self.writeIdentifier(name[3..]); return; } try self.writeIdentifier(name); } fn renderCommandPtr(self: *Self, command_ptr: reg.Command, optional: bool) !void { if (optional) { try self.writer.writeByte('?'); } try self.writer.writeAll("fn("); for (command_ptr.params) |param| { try self.writeIdentifierWithCase(.snake, param.name); try self.writer.writeAll(": "); blk: { if (param.param_type == .name) { if (try self.extractBitflagName(param.param_type.name)) |bitflag_name| { try self.writeIdentifierFmt("{s}Flags{s}{s}", .{ trimVkNamespace(bitflag_name.base_name), @as([]const u8, if (bitflag_name.revision) |revision| revision else ""), @as([]const u8, if (bitflag_name.tag) |tag| tag else ""), }); try self.writer.writeAll(".IntType"); break :blk; } else if (self.isFlags(param.param_type.name)) { try self.renderTypeInfo(param.param_type); try self.writer.writeAll(".IntType"); break :blk; } } try self.renderTypeInfo(param.param_type); } try self.writer.writeAll(", "); } try self.writer.writeAll(") callconv(vulkan_call_conv)"); try self.renderTypeInfo(command_ptr.return_type.*); } fn renderPointer(self: *Self, pointer: reg.Pointer) !void { const child_is_void = pointer.child.* == .name and mem.eql(u8, pointer.child.name, "void"); if (pointer.is_optional) { try self.writer.writeByte('?'); } const size = if (child_is_void) .one else pointer.size; switch (size) { .one => try self.writer.writeByte('*'), .many, .other_field => try self.writer.writeAll("[*]"), .zero_terminated => try self.writer.writeAll("[*:0]"), } if (pointer.is_const) { try self.writer.writeAll("const "); } if (child_is_void) { try self.writer.writeAll("anyopaque"); } else { try self.renderTypeInfo(pointer.child.*); } } fn renderArray(self: *Self, array: reg.Array) !void { try self.writer.writeByte('['); switch (array.size) { .int => |size| try self.writer.print("{}", .{size}), .alias => |alias| try self.renderName(alias), } try self.writer.writeByte(']'); try self.renderTypeInfo(array.child.*); } fn renderDecl(self: *Self, decl: reg.Declaration) !void { switch (decl.decl_type) { .container => |container| try self.renderContainer(decl.name, container), .enumeration => |enumeration| try self.renderEnumeration(decl.name, enumeration), .bitmask => |bitmask| try self.renderBitmask(decl.name, bitmask), .handle => |handle| try self.renderHandle(decl.name, handle), .command => {}, .alias => |alias| try self.renderAlias(decl.name, alias), .foreign => |foreign| try self.renderForeign(decl.name, foreign), .typedef => |type_info| try self.renderTypedef(decl.name, type_info), .external => try self.renderExternal(decl.name), } } fn renderContainer(self: *Self, name: []const u8, container: reg.Container) !void { try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = "); for (container.fields) |field| { if (field.bits != null) { try self.writer.writeAll("packed "); break; } } else { try self.writer.writeAll("extern "); } if (container.is_union) { try self.writer.writeAll("union {"); } else { try self.writer.writeAll("struct {"); } for (container.fields) |field| { try self.writeIdentifierWithCase(.snake, field.name); try self.writer.writeAll(": "); if (field.bits) |bits| { try self.writer.print(" u{},", .{bits}); if (field.field_type != .name or builtin_types.get(field.field_type.name) == null) { try self.writer.writeAll("// "); try self.renderTypeInfo(field.field_type); try self.writer.writeByte('\n'); } } else { try self.renderTypeInfo(field.field_type); try self.renderContainerDefaultField(name, container, field); try self.writer.writeAll(", "); } } try self.writer.writeAll("};\n"); } fn renderContainerDefaultField(self: *Self, name: []const u8, container: reg.Container, field: reg.Container.Field) !void { if (mem.eql(u8, field.name, "pNext")) { try self.writer.writeAll(" = null"); } else if (mem.eql(u8, field.name, "sType")) { if (container.stype == null) { return; } const stype = container.stype.?; if (!mem.startsWith(u8, stype, "VK_STRUCTURE_TYPE_")) { return error.InvalidRegistry; } try self.writer.writeAll(" = ."); try self.writeIdentifierWithCase(.snake, stype["VK_STRUCTURE_TYPE_".len..]); } else if (field.field_type == .name and !container.is_union and mem.eql(u8, "VkBool32", field.field_type.name) and isFeatureStruct(name, container.extends)) { try self.writer.writeAll(" = FALSE"); } } fn isFeatureStruct(name: []const u8, maybe_extends: ?[]const []const u8) bool { if (std.mem.eql(u8, name, "VkPhysicalDeviceFeatures")) return true; if (maybe_extends) |extends| { return for (extends) |extend| { if (mem.eql(u8, extend, "VkDeviceCreateInfo")) break true; } else false; } return false; } fn renderEnumFieldName(self: *Self, name: []const u8, field_name: []const u8) !void { try self.writeIdentifierWithCase(.snake, try self.extractEnumFieldName(name, field_name)); } fn renderEnumeration(self: *Self, name: []const u8, enumeration: reg.Enum) !void { if (enumeration.is_bitmask) { try self.renderBitmaskBits(name, enumeration); return; } try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = enum(i32) {"); for (enumeration.fields) |field| { if (field.value == .alias) continue; try self.renderEnumFieldName(name, field.name); switch (field.value) { .int => |int| try self.writer.print(" = {}, ", .{int}), .bitpos => |pos| try self.writer.print(" = 1 << {}, ", .{pos}), .bit_vector => |bv| try self.writer.print("= 0x{X}, ", .{bv}), .alias => unreachable, } } try self.writer.writeAll("_,"); for (enumeration.fields) |field| { if (field.value != .alias or field.value.alias.is_compat_alias) continue; try self.writer.writeAll("pub const "); try self.renderEnumFieldName(name, field.name); try self.writer.writeAll(" = "); try self.renderName(name); try self.writer.writeByte('.'); try self.renderEnumFieldName(name, field.value.alias.name); try self.writer.writeAll(";\n"); } try self.writer.writeAll("};\n"); } fn bitmaskFlagsType(bitwidth: u8) ![]const u8 { return switch (bitwidth) { 32 => "Flags", 64 => "Flags64", else => return error.InvalidRegistry, }; } fn renderUsingFlagsMixin(self: *Self, name: []const u8, bitwidth: u8) !void { const flags_type = try bitmaskFlagsType(bitwidth); try self.writer.writeAll("pub usingnamespace FlagsMixin("); try self.renderName(name); try self.writer.print(", {s});\n", .{flags_type}); } fn renderBitmaskBits(self: *Self, name: []const u8, bits: reg.Enum) !void { try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = packed struct {"); const bitflag_name = (try self.extractBitflagName(name)) orelse return error.InvalidRegistry; const flags_type = try bitmaskFlagsType(bits.bitwidth); if (bits.fields.len == 0) { try self.writer.print("_reserved_bits: {s} = 0,", .{flags_type}); } else { var flags_by_bitpos = [_]?[]const u8{null} ** 64; for (bits.fields) |field| { if (field.value == .bitpos) { flags_by_bitpos[field.value.bitpos] = field.name; } } for (flags_by_bitpos[0..bits.bitwidth]) |maybe_flag_name, bitpos| { if (maybe_flag_name) |flag_name| { const field_name = try extractBitflagFieldName(bitflag_name, flag_name); try self.writeIdentifierWithCase(.snake, field_name); } else { try self.writer.print("_reserved_bit_{}", .{bitpos}); } try self.writer.writeAll(": bool "); if (bitpos == 0) { // Force alignment to integer boundaries try self.writer.print("align(@alignOf({s})) ", .{flags_type}); } try self.writer.writeAll("= false, "); } } try self.writer.writeAll("pub usingnamespace FlagsMixin("); try self.renderName(name); try self.writer.print(", {s});\n}};\n", .{flags_type}); } fn renderBitmask(self: *Self, name: []const u8, bitmask: reg.Bitmask) !void { if (bitmask.bits_enum == null) { // The bits structure is generated by renderBitmaskBits, but that wont // output flags with no associated bits type. const flags_type = try bitmaskFlagsType(bitmask.bitwidth); try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.print( \\ = packed struct {{ \\_reserved_bits: {s} = 0, \\pub usingnamespace FlagsMixin( , .{flags_type}); try self.renderName(name); try self.writer.print( \\, {s}); \\}}; \\ , .{flags_type}); } } fn renderHandle(self: *Self, name: []const u8, handle: reg.Handle) !void { const backing_type: []const u8 = if (handle.is_dispatchable) "usize" else "u64"; try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.print(" = enum({s}) {{null_handle = 0, _}};\n", .{backing_type}); } fn renderAlias(self: *Self, name: []const u8, alias: reg.Alias) !void { if (alias.target == .other_command) { return; } else if ((try self.extractBitflagName(name)) != null) { // Don't make aliases of the bitflag names, as those are replaced by just the flags type return; } try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = "); try self.renderName(alias.name); try self.writer.writeAll(";\n"); } fn renderExternal(self: *Self, name: []const u8) !void { try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = opaque {};\n"); } fn renderForeign(self: *Self, name: []const u8, foreign: reg.Foreign) !void { if (mem.eql(u8, foreign.depends, "vk_platform")) { return; // Skip built-in types, they are handled differently } try self.writer.writeAll("pub const "); try self.writeIdentifier(name); try self.writer.print(" = if (@hasDecl(root, \"{s}\")) root.", .{name}); try self.writeIdentifier(name); try self.writer.writeAll(" else "); if (foreign_types.get(name)) |default| { try self.writer.writeAll(default); try self.writer.writeAll(";\n"); } else { try self.writer.print("@compileError(\"Missing type definition of '{s}'\");\n", .{name}); } } fn renderTypedef(self: *Self, name: []const u8, type_info: reg.TypeInfo) !void { try self.writer.writeAll("pub const "); try self.renderName(name); try self.writer.writeAll(" = "); try self.renderTypeInfo(type_info); try self.writer.writeAll(";\n"); } fn renderCommandPtrName(self: *Self, name: []const u8) !void { try self.writeIdentifierFmt("Pfn{s}", .{trimVkNamespace(name)}); } fn renderCommandPtrs(self: *Self) !void { for (self.registry.decls) |decl| { if (decl.decl_type != .command) { continue; } try self.writer.writeAll("pub const "); try self.renderCommandPtrName(decl.name); try self.writer.writeAll(" = "); try self.renderCommandPtr(decl.decl_type.command, false); try self.writer.writeAll(";\n"); } } fn renderExtensionInfo(self: *Self) !void { try self.writer.writeAll( \\pub const extension_info = struct { \\ const Info = struct { \\ name: [:0]const u8, \\ version: u32, \\ }; ); for (self.registry.extensions) |ext| { try self.writer.writeAll("pub const "); try self.writeIdentifierWithCase(.snake, trimVkNamespace(ext.name)); try self.writer.writeAll("= Info {\n"); try self.writer.print(".name = \"{s}\", .version = {},", .{ ext.name, ext.version }); try self.writer.writeAll("};\n"); } try self.writer.writeAll("};\n"); } fn renderWrappers(self: *Self) !void { try self.renderWrappersOfDispatchType(.base); try self.renderWrappersOfDispatchType(.instance); try self.renderWrappersOfDispatchType(.device); } fn renderWrappersOfDispatchType(self: *Self, dispatch_type: CommandDispatchType) !void { const name = switch (dispatch_type) { .base => "Base", .instance => "Instance", .device => "Device", }; try self.writer.print( \\pub fn {s}Wrapper(comptime cmds: []const {s}Command) type {{ \\ comptime var fields: [cmds.len]std.builtin.TypeInfo.StructField = undefined; \\ inline for (cmds) |cmd, i| {{ \\ const PfnType = cmd.PfnType(); \\ fields[i] = .{{ \\ .name = cmd.symbol(), \\ .field_type = PfnType, \\ .default_value = null, \\ .is_comptime = false, \\ .alignment = @alignOf(PfnType), \\ }}; \\ }} \\ const Dispatch = @Type(.{{ \\ .Struct = .{{ \\ .layout = .Auto, \\ .fields = &fields, \\ .decls = &[_]std.builtin.TypeInfo.Declaration{{}}, \\ .is_tuple = false, \\ }}, \\ }}); \\ return struct {{ \\ dispatch: Dispatch, \\ \\ const Self = @This(); , .{ name, name }); try self.renderWrapperLoader(dispatch_type); for (self.registry.decls) |decl| { if (decl.decl_type == .command) { const command = decl.decl_type.command; if (classifyCommandDispatch(decl.name, command) == dispatch_type) { try self.renderWrapper(decl.name, decl.decl_type.command); } } } try self.writer.writeAll("};}\n"); } fn renderWrapperLoader(self: *Self, dispatch_type: CommandDispatchType) !void { const params = switch (dispatch_type) { .base => "loader: anytype", .instance => "instance: Instance, loader: anytype", .device => "device: Device, loader: anytype", }; const loader_first_arg = switch (dispatch_type) { .base => "Instance.null_handle", .instance => "instance", .device => "device", }; @setEvalBranchQuota(2000); try self.writer.print( \\pub fn load({[params]s}) error{{CommandLoadFailure}}!Self {{ \\ var self: Self = undefined; \\ inline for (std.meta.fields(Dispatch)) |field| {{ \\ const name = @ptrCast([*:0]const u8, field.name ++ "\x00"); \\ const cmd_ptr = loader({[first_arg]s}, name) orelse return error.CommandLoadFailure; \\ @field(self.dispatch, field.name) = @ptrCast(field.field_type, cmd_ptr); \\ }} \\ return self; \\}} \\pub fn loadNoFail({[params]s}) Self {{ \\ var self: Self = undefined; \\ inline for (std.meta.fields(Dispatch)) |field| {{ \\ const name = @ptrCast([*:0]const u8, field.name ++ "\x00"); \\ const cmd_ptr = loader({[first_arg]s}, name) orelse undefined; \\ @field(self.dispatch, field.name) = @ptrCast(field.field_type, cmd_ptr); \\ }} \\ return self; \\}} , .{ .params = params, .first_arg = loader_first_arg }); } fn derefName(name: []const u8) []const u8 { var it = id_render.SegmentIterator.init(name); return if (mem.eql(u8, it.next().?, "p")) name[1..] else name; } fn renderWrapperPrototype(self: *Self, name: []const u8, command: reg.Command, returns: []const ReturnValue) !void { try self.writer.writeAll("pub fn "); try self.writeIdentifierWithCase(.camel, trimVkNamespace(name)); try self.writer.writeAll("(self: Self, "); for (command.params) |param| { // This parameter is returned instead. if ((try self.classifyParam(param)) == .out_pointer) { continue; } try self.writeIdentifierWithCase(.snake, param.name); try self.writer.writeAll(": "); try self.renderTypeInfo(param.param_type); try self.writer.writeAll(", "); } try self.writer.writeAll(") "); if (command.error_codes.len > 0) { try self.renderErrorSetName(name); try self.writer.writeByte('!'); } if (returns.len == 1) { try self.renderTypeInfo(returns[0].return_value_type); } else if (returns.len > 1) { try self.renderReturnStructName(name); } else { try self.writer.writeAll("void"); } } fn renderWrapperCall(self: *Self, name: []const u8, command: reg.Command, returns: []const ReturnValue) !void { try self.writer.writeAll("self.dispatch."); try self.writeIdentifier(name); try self.writer.writeAll("("); for (command.params) |param| { switch (try self.classifyParam(param)) { .out_pointer => { try self.writer.writeByte('&'); if (returns.len > 1) { try self.writer.writeAll("return_values."); } try self.writeIdentifierWithCase(.snake, derefName(param.name)); }, .bitflags => { try self.writeIdentifierWithCase(.snake, param.name); try self.writer.writeAll(".toInt()"); }, .in_pointer, .in_out_pointer, .buffer_len, .mut_buffer_len, .other => { try self.writeIdentifierWithCase(.snake, param.name); }, } try self.writer.writeAll(", "); } try self.writer.writeAll(")"); } fn extractReturns(self: *Self, command: reg.Command) ![]const ReturnValue { var returns = std.ArrayList(ReturnValue).init(self.allocator); if (command.return_type.* == .name) { const return_name = command.return_type.name; if (!mem.eql(u8, return_name, "void") and !mem.eql(u8, return_name, "VkResult")) { try returns.append(.{ .name = "return_value", .return_value_type = command.return_type.*, .origin = .inner_return_value, }); } } if (command.success_codes.len > 1) { if (command.return_type.* != .name or !mem.eql(u8, command.return_type.name, "VkResult")) { return error.InvalidRegistry; } try returns.append(.{ .name = "result", .return_value_type = command.return_type.*, .origin = .inner_return_value, }); } else if (command.success_codes.len == 1 and !mem.eql(u8, command.success_codes[0], "VK_SUCCESS")) { return error.InvalidRegistry; } for (command.params) |param| { if ((try self.classifyParam(param)) == .out_pointer) { try returns.append(.{ .name = derefName(param.name), .return_value_type = param.param_type.pointer.child.*, .origin = .parameter, }); } } return returns.toOwnedSlice(); } fn renderReturnStructName(self: *Self, command_name: []const u8) !void { try self.writeIdentifierFmt("{s}Result", .{trimVkNamespace(command_name)}); } fn renderErrorSetName(self: *Self, name: []const u8) !void { try self.writeIdentifierWithCase(.title, trimVkNamespace(name)); try self.writer.writeAll("Error"); } fn renderReturnStruct(self: *Self, command_name: []const u8, returns: []const ReturnValue) !void { try self.writer.writeAll("pub const "); try self.renderReturnStructName(command_name); try self.writer.writeAll(" = struct {\n"); for (returns) |ret| { try self.writeIdentifierWithCase(.snake, ret.name); try self.writer.writeAll(": "); try self.renderTypeInfo(ret.return_value_type); try self.writer.writeAll(", "); } try self.writer.writeAll("};\n"); } fn renderWrapper(self: *Self, name: []const u8, command: reg.Command) !void { const returns_vk_result = command.return_type.* == .name and mem.eql(u8, command.return_type.name, "VkResult"); const returns_void = command.return_type.* == .name and mem.eql(u8, command.return_type.name, "void"); const returns = try self.extractReturns(command); if (returns.len > 1) { try self.renderReturnStruct(name, returns); } if (command.error_codes.len > 0) { try self.writer.writeAll("pub const "); try self.renderErrorSetName(name); try self.writer.writeAll(" = "); try self.renderErrorSet(command.error_codes); try self.writer.writeAll(";\n"); } try self.renderWrapperPrototype(name, command, returns); if (returns.len == 1 and returns[0].origin == .inner_return_value) { try self.writer.writeAll("{\n\n"); if (returns_vk_result) { try self.writer.writeAll("const result = "); try self.renderWrapperCall(name, command, returns); try self.writer.writeAll(";\n"); try self.renderErrorSwitch("result", command); try self.writer.writeAll("return result;\n"); } else { try self.writer.writeAll("return "); try self.renderWrapperCall(name, command, returns); try self.writer.writeAll(";\n"); } try self.writer.writeAll("\n}\n"); return; } try self.writer.writeAll("{\n"); if (returns.len == 1) { try self.writer.writeAll("var "); try self.writeIdentifierWithCase(.snake, returns[0].name); try self.writer.writeAll(": "); try self.renderTypeInfo(returns[0].return_value_type); try self.writer.writeAll(" = undefined;\n"); } else if (returns.len > 1) { try self.writer.writeAll("var return_values: "); try self.renderReturnStructName(name); try self.writer.writeAll(" = undefined;\n"); } if (returns_vk_result) { try self.writer.writeAll("const result = "); try self.renderWrapperCall(name, command, returns); try self.writer.writeAll(";\n"); try self.renderErrorSwitch("result", command); if (command.success_codes.len > 1) { try self.writer.writeAll("return_values.result = result;\n"); } } else { if (!returns_void) { try self.writer.writeAll("return_values.return_value = "); } try self.renderWrapperCall(name, command, returns); try self.writer.writeAll(";\n"); } if (returns.len == 1) { try self.writer.writeAll("return "); try self.writeIdentifierWithCase(.snake, returns[0].name); try self.writer.writeAll(";\n"); } else if (returns.len > 1) { try self.writer.writeAll("return return_values;\n"); } try self.writer.writeAll("}\n"); } fn renderErrorSwitch(self: *Self, result_var: []const u8, command: reg.Command) !void { try self.writer.writeAll("switch ("); try self.writeIdentifier(result_var); try self.writer.writeAll(") {\n"); for (command.success_codes) |success| { try self.writer.writeAll("Result."); try self.renderEnumFieldName("VkResult", success); try self.writer.writeAll(" => {},"); } for (command.error_codes) |err| { try self.writer.writeAll("Result."); try self.renderEnumFieldName("VkResult", err); try self.writer.writeAll(" => return error."); try self.renderResultAsErrorName(err); try self.writer.writeAll(", "); } try self.writer.writeAll("else => return error.Unknown,}\n"); } fn renderErrorSet(self: *Self, errors: []const []const u8) !void { try self.writer.writeAll("error{"); for (errors) |name| { try self.renderResultAsErrorName(name); try self.writer.writeAll(", "); } try self.writer.writeAll("Unknown, }"); } fn renderResultAsErrorName(self: *Self, name: []const u8) !void { const error_prefix = "VK_ERROR_"; if (mem.startsWith(u8, name, error_prefix)) { try self.writeIdentifierWithCase(.title, name[error_prefix.len..]); } else { // Apparently some commands (VkAcquireProfilingLockInfoKHR) return // success codes as error... try self.writeIdentifierWithCase(.title, trimVkNamespace(name)); } } }; } pub fn render(writer: anytype, allocator: Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !void { var renderer = try Renderer(@TypeOf(writer)).init(writer, allocator, registry, id_renderer); defer renderer.deinit(); try renderer.render(); }
generator/vulkan/render.zig
pub const MMC_VER = @as(u32, 512); pub const MMC_PROP_CHANGEAFFECTSUI = @as(u32, 1); pub const MMC_PROP_MODIFIABLE = @as(u32, 2); pub const MMC_PROP_REMOVABLE = @as(u32, 4); pub const MMC_PROP_PERSIST = @as(u32, 8); pub const MMCLV_AUTO = @as(i32, -1); pub const MMCLV_NOPARAM = @as(i32, -2); pub const MMCLV_NOICON = @as(i32, -1); pub const MMCLV_VIEWSTYLE_ICON = @as(u32, 0); pub const MMCLV_VIEWSTYLE_SMALLICON = @as(u32, 2); pub const MMCLV_VIEWSTYLE_LIST = @as(u32, 3); pub const MMCLV_VIEWSTYLE_REPORT = @as(u32, 1); pub const MMCLV_VIEWSTYLE_FILTERED = @as(u32, 4); pub const MMCLV_NOPTR = @as(u32, 0); pub const MMCLV_UPDATE_NOINVALIDATEALL = @as(u32, 1); pub const MMCLV_UPDATE_NOSCROLL = @as(u32, 2); pub const MMC_IMAGECALLBACK = @as(i32, -1); pub const RDI_STR = @as(u32, 2); pub const RDI_IMAGE = @as(u32, 4); pub const RDI_STATE = @as(u32, 8); pub const RDI_PARAM = @as(u32, 16); pub const RDI_INDEX = @as(u32, 32); pub const RDI_INDENT = @as(u32, 64); pub const MMC_VIEW_OPTIONS_NONE = @as(u32, 0); pub const MMC_VIEW_OPTIONS_NOLISTVIEWS = @as(u32, 1); pub const MMC_VIEW_OPTIONS_MULTISELECT = @as(u32, 2); pub const MMC_VIEW_OPTIONS_OWNERDATALIST = @as(u32, 4); pub const MMC_VIEW_OPTIONS_FILTERED = @as(u32, 8); pub const MMC_VIEW_OPTIONS_CREATENEW = @as(u32, 16); pub const MMC_VIEW_OPTIONS_USEFONTLINKING = @as(u32, 32); pub const MMC_VIEW_OPTIONS_EXCLUDE_SCOPE_ITEMS_FROM_LIST = @as(u32, 64); pub const MMC_VIEW_OPTIONS_LEXICAL_SORT = @as(u32, 128); pub const MMC_PSO_NOAPPLYNOW = @as(u32, 1); pub const MMC_PSO_HASHELP = @as(u32, 2); pub const MMC_PSO_NEWWIZARDTYPE = @as(u32, 4); pub const MMC_PSO_NO_PROPTITLE = @as(u32, 8); pub const RFI_PARTIAL = @as(u32, 1); pub const RFI_WRAP = @as(u32, 2); pub const RSI_DESCENDING = @as(u32, 1); pub const RSI_NOSORTICON = @as(u32, 2); pub const SDI_STR = @as(u32, 2); pub const SDI_IMAGE = @as(u32, 4); pub const SDI_OPENIMAGE = @as(u32, 8); pub const SDI_STATE = @as(u32, 16); pub const SDI_PARAM = @as(u32, 32); pub const SDI_CHILDREN = @as(u32, 64); pub const SDI_PARENT = @as(u32, 0); pub const SDI_PREVIOUS = @as(u32, 268435456); pub const SDI_NEXT = @as(u32, 536870912); pub const SDI_FIRST = @as(u32, 134217728); pub const MMC_MULTI_SELECT_COOKIE = @as(i32, -2); pub const MMC_WINDOW_COOKIE = @as(i32, -3); pub const SPECIAL_COOKIE_MIN = @as(i32, -10); pub const SPECIAL_COOKIE_MAX = @as(i32, -1); pub const MMC_NW_OPTION_NONE = @as(u32, 0); pub const MMC_NW_OPTION_NOSCOPEPANE = @as(u32, 1); pub const MMC_NW_OPTION_NOTOOLBARS = @as(u32, 2); pub const MMC_NW_OPTION_SHORTTITLE = @as(u32, 4); pub const MMC_NW_OPTION_CUSTOMTITLE = @as(u32, 8); pub const MMC_NW_OPTION_NOPERSIST = @as(u32, 16); pub const MMC_NW_OPTION_NOACTIONPANE = @as(u32, 32); pub const MMC_NODEID_SLOW_RETRIEVAL = @as(u32, 1); pub const SPECIAL_DOBJ_MIN = @as(i32, -10); pub const SPECIAL_DOBJ_MAX = @as(u32, 0); pub const AUTO_WIDTH = @as(i32, -1); pub const HIDE_COLUMN = @as(i32, -4); pub const ILSIF_LEAVE_LARGE_ICON = @as(u32, 1073741824); pub const ILSIF_LEAVE_SMALL_ICON = @as(u32, 536870912); pub const HDI_HIDDEN = @as(u32, 1); pub const RDCI_ScopeItem = @as(u32, 2147483648); pub const RVTI_MISC_OPTIONS_NOLISTVIEWS = @as(u32, 1); pub const RVTI_LIST_OPTIONS_NONE = @as(u32, 0); pub const RVTI_LIST_OPTIONS_OWNERDATALIST = @as(u32, 2); pub const RVTI_LIST_OPTIONS_MULTISELECT = @as(u32, 4); pub const RVTI_LIST_OPTIONS_FILTERED = @as(u32, 8); pub const RVTI_LIST_OPTIONS_USEFONTLINKING = @as(u32, 32); pub const RVTI_LIST_OPTIONS_EXCLUDE_SCOPE_ITEMS_FROM_LIST = @as(u32, 64); pub const RVTI_LIST_OPTIONS_LEXICAL_SORT = @as(u32, 128); pub const RVTI_LIST_OPTIONS_ALLOWPASTE = @as(u32, 256); pub const RVTI_HTML_OPTIONS_NONE = @as(u32, 0); pub const RVTI_HTML_OPTIONS_NOLISTVIEW = @as(u32, 1); pub const RVTI_OCX_OPTIONS_NONE = @as(u32, 0); pub const RVTI_OCX_OPTIONS_NOLISTVIEW = @as(u32, 1); pub const RVTI_OCX_OPTIONS_CACHE_OCX = @as(u32, 2); pub const MMC_DEFAULT_OPERATION_COPY = @as(u32, 1); pub const MMC_ITEM_OVERLAY_STATE_MASK = @as(u32, 3840); pub const MMC_ITEM_OVERLAY_STATE_SHIFT = @as(u32, 8); pub const MMC_ITEM_STATE_MASK = @as(u32, 255); //-------------------------------------------------------------------------------- // Section: Types (127) //-------------------------------------------------------------------------------- const CLSID_Application_Value = Guid.initString("49b2791a-b1ae-4c90-9b8e-e860ba07f889"); pub const CLSID_Application = &CLSID_Application_Value; const CLSID_AppEventsDHTMLConnector_Value = Guid.initString("ade6444b-c91f-4e37-92a4-5bb430a33340"); pub const CLSID_AppEventsDHTMLConnector = &CLSID_AppEventsDHTMLConnector_Value; pub const MMC_PROPERTY_ACTION = enum(i32) { DELETING = 1, CHANGING = 2, INITIALIZED = 3, }; pub const MMC_PROPACT_DELETING = MMC_PROPERTY_ACTION.DELETING; pub const MMC_PROPACT_CHANGING = MMC_PROPERTY_ACTION.CHANGING; pub const MMC_PROPACT_INITIALIZED = MMC_PROPERTY_ACTION.INITIALIZED; pub const MMC_SNAPIN_PROPERTY = extern struct { pszPropName: ?[*:0]const u16, varValue: VARIANT, eAction: MMC_PROPERTY_ACTION, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISnapinProperties_Value = Guid.initString("f7889da9-4a02-4837-bf89-1a6f2a021010"); pub const IID_ISnapinProperties = &IID_ISnapinProperties_Value; pub const ISnapinProperties = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const ISnapinProperties, pProperties: ?*Properties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryPropertyNames: fn( self: *const ISnapinProperties, pCallback: ?*ISnapinPropertiesCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PropertiesChanged: fn( self: *const ISnapinProperties, cProperties: i32, pProperties: [*]MMC_SNAPIN_PROPERTY, ) 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 ISnapinProperties_Initialize(self: *const T, pProperties: ?*Properties) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinProperties.VTable, self.vtable).Initialize(@ptrCast(*const ISnapinProperties, self), pProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinProperties_QueryPropertyNames(self: *const T, pCallback: ?*ISnapinPropertiesCallback) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinProperties.VTable, self.vtable).QueryPropertyNames(@ptrCast(*const ISnapinProperties, self), pCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinProperties_PropertiesChanged(self: *const T, cProperties: i32, pProperties: [*]MMC_SNAPIN_PROPERTY) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinProperties.VTable, self.vtable).PropertiesChanged(@ptrCast(*const ISnapinProperties, self), cProperties, pProperties); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISnapinPropertiesCallback_Value = Guid.initString("a50fa2e5-7e61-45eb-a8d4-9a07b3e851a8"); pub const IID_ISnapinPropertiesCallback = &IID_ISnapinPropertiesCallback_Value; pub const ISnapinPropertiesCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddPropertyName: fn( self: *const ISnapinPropertiesCallback, pszPropName: ?[*:0]const u16, dwFlags: 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 ISnapinPropertiesCallback_AddPropertyName(self: *const T, pszPropName: ?[*:0]const u16, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinPropertiesCallback.VTable, self.vtable).AddPropertyName(@ptrCast(*const ISnapinPropertiesCallback, self), pszPropName, dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const _DocumentMode = enum(i32) { Author = 0, User = 1, User_MDI = 2, User_SDI = 3, }; pub const DocumentMode_Author = _DocumentMode.Author; pub const DocumentMode_User = _DocumentMode.User; pub const DocumentMode_User_MDI = _DocumentMode.User_MDI; pub const DocumentMode_User_SDI = _DocumentMode.User_SDI; pub const _ListViewMode = enum(i32) { Small_Icons = 0, Large_Icons = 1, List = 2, Detail = 3, Filtered = 4, }; pub const ListMode_Small_Icons = _ListViewMode.Small_Icons; pub const ListMode_Large_Icons = _ListViewMode.Large_Icons; pub const ListMode_List = _ListViewMode.List; pub const ListMode_Detail = _ListViewMode.Detail; pub const ListMode_Filtered = _ListViewMode.Filtered; pub const _ViewOptions = enum(i32) { Default = 0, ScopeTreeHidden = 1, NoToolBars = 2, NotPersistable = 4, ActionPaneHidden = 8, }; pub const ViewOption_Default = _ViewOptions.Default; pub const ViewOption_ScopeTreeHidden = _ViewOptions.ScopeTreeHidden; pub const ViewOption_NoToolBars = _ViewOptions.NoToolBars; pub const ViewOption_NotPersistable = _ViewOptions.NotPersistable; pub const ViewOption_ActionPaneHidden = _ViewOptions.ActionPaneHidden; pub const _ExportListOptions = enum(i32) { Default = 0, Unicode = 1, TabDelimited = 2, SelectedItemsOnly = 4, }; pub const ExportListOptions_Default = _ExportListOptions.Default; pub const ExportListOptions_Unicode = _ExportListOptions.Unicode; pub const ExportListOptions_TabDelimited = _ExportListOptions.TabDelimited; pub const ExportListOptions_SelectedItemsOnly = _ExportListOptions.SelectedItemsOnly; const IID__Application_Value = Guid.initString("a3afb9cc-b653-4741-86ab-f0470ec1384c"); pub const IID__Application = &IID__Application_Value; pub const _Application = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Help: fn( self: *const _Application, ) callconv(@import("std").os.windows.WINAPI) void, Quit: fn( self: *const _Application, ) callconv(@import("std").os.windows.WINAPI) void, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Document: fn( self: *const _Application, Document: ?*?*Document, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Load: fn( self: *const _Application, Filename: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Frame: fn( self: *const _Application, Frame: ?*?*Frame, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Visible: fn( self: *const _Application, Visible: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Show: fn( self: *const _Application, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Hide: fn( self: *const _Application, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserControl: fn( self: *const _Application, UserControl: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UserControl: fn( self: *const _Application, UserControl: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_VersionMajor: fn( self: *const _Application, VersionMajor: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_VersionMinor: fn( self: *const _Application, VersionMinor: ?*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 _Application_Help(self: *const T) callconv(.Inline) void { return @ptrCast(*const _Application.VTable, self.vtable).Help(@ptrCast(*const _Application, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_Quit(self: *const T) callconv(.Inline) void { return @ptrCast(*const _Application.VTable, self.vtable).Quit(@ptrCast(*const _Application, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_Document(self: *const T, _param_Document: ?*?*Document) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_Document(@ptrCast(*const _Application, self), _param_Document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_Load(self: *const T, Filename: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).Load(@ptrCast(*const _Application, self), Filename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_Frame(self: *const T, _param_Frame: ?*?*Frame) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_Frame(@ptrCast(*const _Application, self), _param_Frame); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_Visible(self: *const T, Visible: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_Visible(@ptrCast(*const _Application, self), Visible); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_Show(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).Show(@ptrCast(*const _Application, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_Hide(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).Hide(@ptrCast(*const _Application, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_UserControl(self: *const T, UserControl: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_UserControl(@ptrCast(*const _Application, self), UserControl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_put_UserControl(self: *const T, UserControl: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).put_UserControl(@ptrCast(*const _Application, self), UserControl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_VersionMajor(self: *const T, VersionMajor: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_VersionMajor(@ptrCast(*const _Application, self), VersionMajor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _Application_get_VersionMinor(self: *const T, VersionMinor: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const _Application.VTable, self.vtable).get_VersionMinor(@ptrCast(*const _Application, self), VersionMinor); } };} pub usingnamespace MethodMixin(@This()); }; const IID__AppEvents_Value = Guid.initString("de46cbdd-53f5-4635-af54-4fe71e923d3f"); pub const IID__AppEvents = &IID__AppEvents_Value; pub const _AppEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, OnQuit: fn( self: *const _AppEvents, Application: ?*_Application, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDocumentOpen: fn( self: *const _AppEvents, Document: ?*Document, New: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDocumentClose: fn( self: *const _AppEvents, Document: ?*Document, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSnapInAdded: fn( self: *const _AppEvents, Document: ?*Document, SnapIn: ?*SnapIn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSnapInRemoved: fn( self: *const _AppEvents, Document: ?*Document, SnapIn: ?*SnapIn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnNewView: fn( self: *const _AppEvents, View: ?*View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnViewClose: fn( self: *const _AppEvents, View: ?*View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnViewChange: fn( self: *const _AppEvents, View: ?*View, NewOwnerNode: ?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSelectionChange: fn( self: *const _AppEvents, View: ?*View, NewNodes: ?*Nodes, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnContextMenuExecuted: fn( self: *const _AppEvents, MenuItem: ?*MenuItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnToolbarButtonClicked: fn( self: *const _AppEvents, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnListUpdated: fn( self: *const _AppEvents, View: ?*View, ) 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 _AppEvents_OnQuit(self: *const T, Application: ?*_Application) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnQuit(@ptrCast(*const _AppEvents, self), Application); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnDocumentOpen(self: *const T, _param_Document: ?*Document, New: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnDocumentOpen(@ptrCast(*const _AppEvents, self), _param_Document, New); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnDocumentClose(self: *const T, _param_Document: ?*Document) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnDocumentClose(@ptrCast(*const _AppEvents, self), _param_Document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnSnapInAdded(self: *const T, _param_Document: ?*Document, _param_SnapIn: ?*SnapIn) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnSnapInAdded(@ptrCast(*const _AppEvents, self), _param_Document, _param_SnapIn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnSnapInRemoved(self: *const T, _param_Document: ?*Document, _param_SnapIn: ?*SnapIn) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnSnapInRemoved(@ptrCast(*const _AppEvents, self), _param_Document, _param_SnapIn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnNewView(self: *const T, _param_View: ?*View) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnNewView(@ptrCast(*const _AppEvents, self), _param_View); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnViewClose(self: *const T, _param_View: ?*View) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnViewClose(@ptrCast(*const _AppEvents, self), _param_View); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnViewChange(self: *const T, _param_View: ?*View, NewOwnerNode: ?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnViewChange(@ptrCast(*const _AppEvents, self), _param_View, NewOwnerNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnSelectionChange(self: *const T, _param_View: ?*View, NewNodes: ?*Nodes) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnSelectionChange(@ptrCast(*const _AppEvents, self), _param_View, NewNodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnContextMenuExecuted(self: *const T, _param_MenuItem: ?*MenuItem) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnContextMenuExecuted(@ptrCast(*const _AppEvents, self), _param_MenuItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnToolbarButtonClicked(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnToolbarButtonClicked(@ptrCast(*const _AppEvents, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _AppEvents_OnListUpdated(self: *const T, _param_View: ?*View) callconv(.Inline) HRESULT { return @ptrCast(*const _AppEvents.VTable, self.vtable).OnListUpdated(@ptrCast(*const _AppEvents, self), _param_View); } };} pub usingnamespace MethodMixin(@This()); }; const IID_AppEvents_Value = Guid.initString("fc7a4252-78ac-4532-8c5a-563cfe138863"); pub const IID_AppEvents = &IID_AppEvents_Value; pub const AppEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID__EventConnector_Value = Guid.initString("c0bccd30-de44-4528-8403-a05a6a1cc8ea"); pub const IID__EventConnector = &IID__EventConnector_Value; pub const _EventConnector = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ConnectTo: fn( self: *const _EventConnector, Application: ?*_Application, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const _EventConnector, ) 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 _EventConnector_ConnectTo(self: *const T, Application: ?*_Application) callconv(.Inline) HRESULT { return @ptrCast(*const _EventConnector.VTable, self.vtable).ConnectTo(@ptrCast(*const _EventConnector, self), Application); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _EventConnector_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const _EventConnector.VTable, self.vtable).Disconnect(@ptrCast(*const _EventConnector, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Frame_Value = Guid.initString("e5e2d970-5bb3-4306-8804-b0968a31c8e6"); pub const IID_Frame = &IID_Frame_Value; pub const Frame = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Maximize: fn( self: *const Frame, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Minimize: fn( self: *const Frame, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const Frame, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Top: fn( self: *const Frame, Top: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Top: fn( self: *const Frame, top: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Bottom: fn( self: *const Frame, Bottom: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Bottom: fn( self: *const Frame, bottom: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Left: fn( self: *const Frame, Left: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Left: fn( self: *const Frame, left: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Right: fn( self: *const Frame, Right: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Right: fn( self: *const Frame, right: 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 Frame_Maximize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).Maximize(@ptrCast(*const Frame, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_Minimize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).Minimize(@ptrCast(*const Frame, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).Restore(@ptrCast(*const Frame, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_get_Top(self: *const T, Top: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).get_Top(@ptrCast(*const Frame, self), Top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_put_Top(self: *const T, top: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).put_Top(@ptrCast(*const Frame, self), top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_get_Bottom(self: *const T, Bottom: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).get_Bottom(@ptrCast(*const Frame, self), Bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_put_Bottom(self: *const T, bottom: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).put_Bottom(@ptrCast(*const Frame, self), bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_get_Left(self: *const T, Left: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).get_Left(@ptrCast(*const Frame, self), Left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_put_Left(self: *const T, left: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).put_Left(@ptrCast(*const Frame, self), left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_get_Right(self: *const T, Right: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).get_Right(@ptrCast(*const Frame, self), Right); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Frame_put_Right(self: *const T, right: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Frame.VTable, self.vtable).put_Right(@ptrCast(*const Frame, self), right); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Node_Value = Guid.initString("f81ed800-7839-4447-945d-8e15da59ca55"); pub const IID_Node = &IID_Node_Value; pub const Node = 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 Node, Name: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Property: fn( self: *const Node, PropertyName: ?BSTR, PropertyValue: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Bookmark: fn( self: *const Node, Bookmark: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsScopeNode: fn( self: *const Node, IsScopeNode: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Nodetype: fn( self: *const Node, Nodetype: ?*?*u16, ) 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 Node_get_Name(self: *const T, Name: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Node.VTable, self.vtable).get_Name(@ptrCast(*const Node, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Node_get_Property(self: *const T, PropertyName: ?BSTR, PropertyValue: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Node.VTable, self.vtable).get_Property(@ptrCast(*const Node, self), PropertyName, PropertyValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Node_get_Bookmark(self: *const T, Bookmark: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Node.VTable, self.vtable).get_Bookmark(@ptrCast(*const Node, self), Bookmark); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Node_IsScopeNode(self: *const T, IsScopeNode: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Node.VTable, self.vtable).IsScopeNode(@ptrCast(*const Node, self), IsScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Node_get_Nodetype(self: *const T, Nodetype: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Node.VTable, self.vtable).get_Nodetype(@ptrCast(*const Node, self), Nodetype); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ScopeNamespace_Value = Guid.initString("ebbb48dc-1a3b-4d86-b786-c21b28389012"); pub const IID_ScopeNamespace = &IID_ScopeNamespace_Value; pub const ScopeNamespace = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetParent: fn( self: *const ScopeNamespace, Node: ?*Node, Parent: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChild: fn( self: *const ScopeNamespace, Node: ?*Node, Child: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNext: fn( self: *const ScopeNamespace, Node: ?*Node, Next: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRoot: fn( self: *const ScopeNamespace, Root: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Expand: fn( self: *const ScopeNamespace, Node: ?*Node, ) 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 ScopeNamespace_GetParent(self: *const T, _param_Node: ?*Node, Parent: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const ScopeNamespace.VTable, self.vtable).GetParent(@ptrCast(*const ScopeNamespace, self), _param_Node, Parent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ScopeNamespace_GetChild(self: *const T, _param_Node: ?*Node, Child: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const ScopeNamespace.VTable, self.vtable).GetChild(@ptrCast(*const ScopeNamespace, self), _param_Node, Child); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ScopeNamespace_GetNext(self: *const T, _param_Node: ?*Node, Next: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const ScopeNamespace.VTable, self.vtable).GetNext(@ptrCast(*const ScopeNamespace, self), _param_Node, Next); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ScopeNamespace_GetRoot(self: *const T, Root: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const ScopeNamespace.VTable, self.vtable).GetRoot(@ptrCast(*const ScopeNamespace, self), Root); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ScopeNamespace_Expand(self: *const T, _param_Node: ?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const ScopeNamespace.VTable, self.vtable).Expand(@ptrCast(*const ScopeNamespace, self), _param_Node); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Document_Value = Guid.initString("225120d6-1e0f-40a3-93fe-1079e6a8017b"); pub const IID_Document = &IID_Document_Value; pub const Document = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Save: fn( self: *const Document, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveAs: fn( self: *const Document, Filename: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const Document, SaveChanges: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Views: fn( self: *const Document, Views: ?*?*Views, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SnapIns: fn( self: *const Document, SnapIns: ?*?*SnapIns, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ActiveView: fn( self: *const Document, View: ?*?*View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const Document, Name: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Name: fn( self: *const Document, Name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Location: fn( self: *const Document, Location: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsSaved: fn( self: *const Document, IsSaved: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Mode: fn( self: *const Document, Mode: ?*_DocumentMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Mode: fn( self: *const Document, Mode: _DocumentMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RootNode: fn( self: *const Document, Node: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScopeNamespace: fn( self: *const Document, ScopeNamespace: ?*?*ScopeNamespace, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateProperties: fn( self: *const Document, Properties: ?*?*Properties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Application: fn( self: *const Document, Application: ?*?*_Application, ) 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 Document_Save(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).Save(@ptrCast(*const Document, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_SaveAs(self: *const T, Filename: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).SaveAs(@ptrCast(*const Document, self), Filename); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_Close(self: *const T, SaveChanges: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).Close(@ptrCast(*const Document, self), SaveChanges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_Views(self: *const T, _param_Views: ?*?*Views) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_Views(@ptrCast(*const Document, self), _param_Views); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_SnapIns(self: *const T, _param_SnapIns: ?*?*SnapIns) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_SnapIns(@ptrCast(*const Document, self), _param_SnapIns); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_ActiveView(self: *const T, _param_View: ?*?*View) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_ActiveView(@ptrCast(*const Document, self), _param_View); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_Name(self: *const T, Name: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_Name(@ptrCast(*const Document, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_put_Name(self: *const T, Name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).put_Name(@ptrCast(*const Document, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_Location(self: *const T, Location: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_Location(@ptrCast(*const Document, self), Location); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_IsSaved(self: *const T, IsSaved: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_IsSaved(@ptrCast(*const Document, self), IsSaved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_Mode(self: *const T, Mode: ?*_DocumentMode) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_Mode(@ptrCast(*const Document, self), Mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_put_Mode(self: *const T, Mode: _DocumentMode) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).put_Mode(@ptrCast(*const Document, self), Mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_RootNode(self: *const T, _param_Node: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_RootNode(@ptrCast(*const Document, self), _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_ScopeNamespace(self: *const T, _param_ScopeNamespace: ?*?*ScopeNamespace) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_ScopeNamespace(@ptrCast(*const Document, self), _param_ScopeNamespace); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_CreateProperties(self: *const T, _param_Properties: ?*?*Properties) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).CreateProperties(@ptrCast(*const Document, self), _param_Properties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Document_get_Application(self: *const T, Application: ?*?*_Application) callconv(.Inline) HRESULT { return @ptrCast(*const Document.VTable, self.vtable).get_Application(@ptrCast(*const Document, self), Application); } };} pub usingnamespace MethodMixin(@This()); }; const IID_SnapIn_Value = Guid.initString("3be910f6-3459-49c6-a1bb-41e6be9df3ea"); pub const IID_SnapIn = &IID_SnapIn_Value; pub const SnapIn = 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 SnapIn, Name: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Vendor: fn( self: *const SnapIn, Vendor: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Version: fn( self: *const SnapIn, Version: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Extensions: fn( self: *const SnapIn, Extensions: ?*?*Extensions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SnapinCLSID: fn( self: *const SnapIn, SnapinCLSID: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Properties: fn( self: *const SnapIn, Properties: ?*?*Properties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableAllExtensions: fn( self: *const SnapIn, Enable: BOOL, ) 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 SnapIn_get_Name(self: *const T, Name: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_Name(@ptrCast(*const SnapIn, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_get_Vendor(self: *const T, Vendor: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_Vendor(@ptrCast(*const SnapIn, self), Vendor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_get_Version(self: *const T, Version: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_Version(@ptrCast(*const SnapIn, self), Version); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_get_Extensions(self: *const T, _param_Extensions: ?*?*Extensions) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_Extensions(@ptrCast(*const SnapIn, self), _param_Extensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_get_SnapinCLSID(self: *const T, SnapinCLSID: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_SnapinCLSID(@ptrCast(*const SnapIn, self), SnapinCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_get_Properties(self: *const T, _param_Properties: ?*?*Properties) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).get_Properties(@ptrCast(*const SnapIn, self), _param_Properties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIn_EnableAllExtensions(self: *const T, Enable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIn.VTable, self.vtable).EnableAllExtensions(@ptrCast(*const SnapIn, self), Enable); } };} pub usingnamespace MethodMixin(@This()); }; const IID_SnapIns_Value = Guid.initString("2ef3de1d-b12a-49d1-92c5-0b00798768f1"); pub const IID_SnapIns = &IID_SnapIns_Value; pub const SnapIns = 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 SnapIns, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const SnapIns, Index: i32, SnapIn: ?*?*SnapIn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const SnapIns, Count: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const SnapIns, SnapinNameOrCLSID: ?BSTR, ParentSnapin: VARIANT, Properties: VARIANT, SnapIn: ?*?*SnapIn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const SnapIns, SnapIn: ?*SnapIn, ) 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 SnapIns_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIns.VTable, self.vtable).get__NewEnum(@ptrCast(*const SnapIns, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIns_Item(self: *const T, Index: i32, _param_SnapIn: ?*?*SnapIn) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIns.VTable, self.vtable).Item(@ptrCast(*const SnapIns, self), Index, _param_SnapIn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIns_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIns.VTable, self.vtable).get_Count(@ptrCast(*const SnapIns, self), Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIns_Add(self: *const T, SnapinNameOrCLSID: ?BSTR, ParentSnapin: VARIANT, _param_Properties: VARIANT, _param_SnapIn: ?*?*SnapIn) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIns.VTable, self.vtable).Add(@ptrCast(*const SnapIns, self), SnapinNameOrCLSID, ParentSnapin, _param_Properties, _param_SnapIn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn SnapIns_Remove(self: *const T, _param_SnapIn: ?*SnapIn) callconv(.Inline) HRESULT { return @ptrCast(*const SnapIns.VTable, self.vtable).Remove(@ptrCast(*const SnapIns, self), _param_SnapIn); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Extension_Value = Guid.initString("ad4d6ca6-912f-409b-a26e-7fd234aef542"); pub const IID_Extension = &IID_Extension_Value; pub const Extension = 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 Extension, Name: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Vendor: fn( self: *const Extension, Vendor: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Version: fn( self: *const Extension, Version: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Extensions: fn( self: *const Extension, Extensions: ?*?*Extensions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SnapinCLSID: fn( self: *const Extension, SnapinCLSID: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableAllExtensions: fn( self: *const Extension, Enable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Enable: fn( self: *const Extension, Enable: BOOL, ) 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 Extension_get_Name(self: *const T, Name: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).get_Name(@ptrCast(*const Extension, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_get_Vendor(self: *const T, Vendor: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).get_Vendor(@ptrCast(*const Extension, self), Vendor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_get_Version(self: *const T, Version: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).get_Version(@ptrCast(*const Extension, self), Version); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_get_Extensions(self: *const T, _param_Extensions: ?*?*Extensions) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).get_Extensions(@ptrCast(*const Extension, self), _param_Extensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_get_SnapinCLSID(self: *const T, SnapinCLSID: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).get_SnapinCLSID(@ptrCast(*const Extension, self), SnapinCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_EnableAllExtensions(self: *const T, Enable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).EnableAllExtensions(@ptrCast(*const Extension, self), Enable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extension_Enable(self: *const T, Enable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Extension.VTable, self.vtable).Enable(@ptrCast(*const Extension, self), Enable); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Extensions_Value = Guid.initString("82dbea43-8ca4-44bc-a2ca-d18741059ec8"); pub const IID_Extensions = &IID_Extensions_Value; pub const Extensions = 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 Extensions, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const Extensions, Index: i32, Extension: ?*?*Extension, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const Extensions, Count: ?*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 Extensions_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const Extensions.VTable, self.vtable).get__NewEnum(@ptrCast(*const Extensions, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extensions_Item(self: *const T, Index: i32, _param_Extension: ?*?*Extension) callconv(.Inline) HRESULT { return @ptrCast(*const Extensions.VTable, self.vtable).Item(@ptrCast(*const Extensions, self), Index, _param_Extension); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Extensions_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Extensions.VTable, self.vtable).get_Count(@ptrCast(*const Extensions, self), Count); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Columns_Value = Guid.initString("383d4d97-fc44-478b-b139-6323dc48611c"); pub const IID_Columns = &IID_Columns_Value; pub const Columns = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Item: fn( self: *const Columns, Index: i32, Column: ?*?*Column, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const Columns, Count: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const Columns, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Columns_Item(self: *const T, Index: i32, _param_Column: ?*?*Column) callconv(.Inline) HRESULT { return @ptrCast(*const Columns.VTable, self.vtable).Item(@ptrCast(*const Columns, self), Index, _param_Column); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Columns_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Columns.VTable, self.vtable).get_Count(@ptrCast(*const Columns, self), Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Columns_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const Columns.VTable, self.vtable).get__NewEnum(@ptrCast(*const Columns, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; pub const _ColumnSortOrder = enum(i32) { Ascending = 0, Descending = 1, }; pub const SortOrder_Ascending = _ColumnSortOrder.Ascending; pub const SortOrder_Descending = _ColumnSortOrder.Descending; const IID_Column_Value = Guid.initString("fd1c5f63-2b16-4d06-9ab3-f45350b940ab"); pub const IID_Column = &IID_Column_Value; pub const Column = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Name: fn( self: *const Column, Name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Width: fn( self: *const Column, Width: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Width: fn( self: *const Column, Width: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayPosition: fn( self: *const Column, DisplayPosition: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisplayPosition: fn( self: *const Column, Index: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Hidden: fn( self: *const Column, Hidden: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Hidden: fn( self: *const Column, Hidden: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAsSortColumn: fn( self: *const Column, SortOrder: _ColumnSortOrder, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsSortColumn: fn( self: *const Column, IsSortColumn: ?*BOOL, ) 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 Column_Name(self: *const T, Name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).Name(@ptrCast(*const Column, self), Name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_get_Width(self: *const T, Width: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).get_Width(@ptrCast(*const Column, self), Width); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_put_Width(self: *const T, Width: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).put_Width(@ptrCast(*const Column, self), Width); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_get_DisplayPosition(self: *const T, DisplayPosition: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).get_DisplayPosition(@ptrCast(*const Column, self), DisplayPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_put_DisplayPosition(self: *const T, Index: i32) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).put_DisplayPosition(@ptrCast(*const Column, self), Index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_get_Hidden(self: *const T, Hidden: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).get_Hidden(@ptrCast(*const Column, self), Hidden); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_put_Hidden(self: *const T, Hidden: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).put_Hidden(@ptrCast(*const Column, self), Hidden); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_SetAsSortColumn(self: *const T, SortOrder: _ColumnSortOrder) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).SetAsSortColumn(@ptrCast(*const Column, self), SortOrder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Column_IsSortColumn(self: *const T, IsSortColumn: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const Column.VTable, self.vtable).IsSortColumn(@ptrCast(*const Column, self), IsSortColumn); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Views_Value = Guid.initString("d6b8c29d-a1ff-4d72-aab0-e381e9b9338d"); pub const IID_Views = &IID_Views_Value; pub const Views = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Item: fn( self: *const Views, Index: i32, View: ?*?*View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const Views, Count: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const Views, Node: ?*Node, viewOptions: _ViewOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const Views, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Views_Item(self: *const T, Index: i32, _param_View: ?*?*View) callconv(.Inline) HRESULT { return @ptrCast(*const Views.VTable, self.vtable).Item(@ptrCast(*const Views, self), Index, _param_View); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Views_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Views.VTable, self.vtable).get_Count(@ptrCast(*const Views, self), Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Views_Add(self: *const T, _param_Node: ?*Node, viewOptions: _ViewOptions) callconv(.Inline) HRESULT { return @ptrCast(*const Views.VTable, self.vtable).Add(@ptrCast(*const Views, self), _param_Node, viewOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Views_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const Views.VTable, self.vtable).get__NewEnum(@ptrCast(*const Views, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; const IID_View_Value = Guid.initString("6efc2da2-b38c-457e-9abb-ed2d189b8c38"); pub const IID_View = &IID_View_Value; pub const View = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ActiveScopeNode: fn( self: *const View, Node: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ActiveScopeNode: fn( self: *const View, Node: ?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Selection: fn( self: *const View, Nodes: ?*?*Nodes, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ListItems: fn( self: *const View, Nodes: ?*?*Nodes, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SnapinScopeObject: fn( self: *const View, ScopeNode: VARIANT, ScopeNodeObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SnapinSelectionObject: fn( self: *const View, SelectionObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Is: fn( self: *const View, View: ?*View, TheSame: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Document: fn( self: *const View, Document: ?*?*Document, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SelectAll: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Select: fn( self: *const View, Node: ?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Deselect: fn( self: *const View, Node: ?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsSelected: fn( self: *const View, Node: ?*Node, IsSelected: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisplayScopeNodePropertySheet: fn( self: *const View, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisplaySelectionPropertySheet: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyScopeNode: fn( self: *const View, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopySelection: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteScopeNode: fn( self: *const View, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteSelection: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RenameScopeNode: fn( self: *const View, NewName: ?BSTR, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RenameSelectedItem: fn( self: *const View, NewName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScopeNodeContextMenu: fn( self: *const View, ScopeNode: VARIANT, ContextMenu: ?*?*ContextMenu, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SelectionContextMenu: fn( self: *const View, ContextMenu: ?*?*ContextMenu, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RefreshScopeNode: fn( self: *const View, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RefreshSelection: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExecuteSelectionMenuItem: fn( self: *const View, MenuItemPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExecuteScopeNodeMenuItem: fn( self: *const View, MenuItemPath: ?BSTR, ScopeNode: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExecuteShellCommand: fn( self: *const View, Command: ?BSTR, Directory: ?BSTR, Parameters: ?BSTR, WindowState: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Frame: fn( self: *const View, Frame: ?*?*Frame, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ScopeTreeVisible: fn( self: *const View, Visible: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ScopeTreeVisible: fn( self: *const View, Visible: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Back: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Forward: fn( self: *const View, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StatusBarText: fn( self: *const View, StatusBarText: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Memento: fn( self: *const View, Memento: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ViewMemento: fn( self: *const View, Memento: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Columns: fn( self: *const View, Columns: ?*?*Columns, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CellContents: fn( self: *const View, Node: ?*Node, Column: i32, CellContents: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExportList: fn( self: *const View, File: ?BSTR, exportoptions: _ExportListOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ListViewMode: fn( self: *const View, Mode: ?*_ListViewMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ListViewMode: fn( self: *const View, mode: _ListViewMode, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ControlObject: fn( self: *const View, Control: ?*?*IDispatch, ) 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 View_get_ActiveScopeNode(self: *const T, _param_Node: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ActiveScopeNode(@ptrCast(*const View, self), _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_put_ActiveScopeNode(self: *const T, _param_Node: ?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).put_ActiveScopeNode(@ptrCast(*const View, self), _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_Selection(self: *const T, _param_Nodes: ?*?*Nodes) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_Selection(@ptrCast(*const View, self), _param_Nodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_ListItems(self: *const T, _param_Nodes: ?*?*Nodes) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ListItems(@ptrCast(*const View, self), _param_Nodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_SnapinScopeObject(self: *const T, ScopeNode: VARIANT, ScopeNodeObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).SnapinScopeObject(@ptrCast(*const View, self), ScopeNode, ScopeNodeObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_SnapinSelectionObject(self: *const T, SelectionObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).SnapinSelectionObject(@ptrCast(*const View, self), SelectionObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Is(self: *const T, _param_View: ?*View, TheSame: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Is(@ptrCast(*const View, self), _param_View, TheSame); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_Document(self: *const T, _param_Document: ?*?*Document) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_Document(@ptrCast(*const View, self), _param_Document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_SelectAll(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).SelectAll(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Select(self: *const T, _param_Node: ?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Select(@ptrCast(*const View, self), _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Deselect(self: *const T, _param_Node: ?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Deselect(@ptrCast(*const View, self), _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_IsSelected(self: *const T, _param_Node: ?*Node, IsSelected: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).IsSelected(@ptrCast(*const View, self), _param_Node, IsSelected); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_DisplayScopeNodePropertySheet(self: *const T, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).DisplayScopeNodePropertySheet(@ptrCast(*const View, self), ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_DisplaySelectionPropertySheet(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).DisplaySelectionPropertySheet(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_CopyScopeNode(self: *const T, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).CopyScopeNode(@ptrCast(*const View, self), ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_CopySelection(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).CopySelection(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_DeleteScopeNode(self: *const T, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).DeleteScopeNode(@ptrCast(*const View, self), ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_DeleteSelection(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).DeleteSelection(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_RenameScopeNode(self: *const T, NewName: ?BSTR, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).RenameScopeNode(@ptrCast(*const View, self), NewName, ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_RenameSelectedItem(self: *const T, NewName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).RenameSelectedItem(@ptrCast(*const View, self), NewName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_ScopeNodeContextMenu(self: *const T, ScopeNode: VARIANT, _param_ContextMenu: ?*?*ContextMenu) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ScopeNodeContextMenu(@ptrCast(*const View, self), ScopeNode, _param_ContextMenu); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_SelectionContextMenu(self: *const T, _param_ContextMenu: ?*?*ContextMenu) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_SelectionContextMenu(@ptrCast(*const View, self), _param_ContextMenu); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_RefreshScopeNode(self: *const T, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).RefreshScopeNode(@ptrCast(*const View, self), ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_RefreshSelection(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).RefreshSelection(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_ExecuteSelectionMenuItem(self: *const T, MenuItemPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).ExecuteSelectionMenuItem(@ptrCast(*const View, self), MenuItemPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_ExecuteScopeNodeMenuItem(self: *const T, MenuItemPath: ?BSTR, ScopeNode: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).ExecuteScopeNodeMenuItem(@ptrCast(*const View, self), MenuItemPath, ScopeNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_ExecuteShellCommand(self: *const T, Command: ?BSTR, Directory: ?BSTR, Parameters: ?BSTR, WindowState: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).ExecuteShellCommand(@ptrCast(*const View, self), Command, Directory, Parameters, WindowState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_Frame(self: *const T, _param_Frame: ?*?*Frame) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_Frame(@ptrCast(*const View, self), _param_Frame); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Close(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_ScopeTreeVisible(self: *const T, Visible: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ScopeTreeVisible(@ptrCast(*const View, self), Visible); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_put_ScopeTreeVisible(self: *const T, Visible: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).put_ScopeTreeVisible(@ptrCast(*const View, self), Visible); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Back(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Back(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_Forward(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).Forward(@ptrCast(*const View, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_put_StatusBarText(self: *const T, StatusBarText: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).put_StatusBarText(@ptrCast(*const View, self), StatusBarText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_Memento(self: *const T, Memento: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_Memento(@ptrCast(*const View, self), Memento); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_ViewMemento(self: *const T, Memento: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).ViewMemento(@ptrCast(*const View, self), Memento); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_Columns(self: *const T, _param_Columns: ?*?*Columns) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_Columns(@ptrCast(*const View, self), _param_Columns); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_CellContents(self: *const T, _param_Node: ?*Node, _param_Column: i32, CellContents: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_CellContents(@ptrCast(*const View, self), _param_Node, _param_Column, CellContents); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_ExportList(self: *const T, File: ?BSTR, exportoptions: _ExportListOptions) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).ExportList(@ptrCast(*const View, self), File, exportoptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_ListViewMode(self: *const T, Mode: ?*_ListViewMode) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ListViewMode(@ptrCast(*const View, self), Mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_put_ListViewMode(self: *const T, mode: _ListViewMode) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).put_ListViewMode(@ptrCast(*const View, self), mode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn View_get_ControlObject(self: *const T, Control: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const View.VTable, self.vtable).get_ControlObject(@ptrCast(*const View, self), Control); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Nodes_Value = Guid.initString("313b01df-b22f-4d42-b1b8-483cdcf51d35"); pub const IID_Nodes = &IID_Nodes_Value; pub const Nodes = 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 Nodes, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const Nodes, Index: i32, Node: ?*?*Node, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const Nodes, Count: ?*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 Nodes_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const Nodes.VTable, self.vtable).get__NewEnum(@ptrCast(*const Nodes, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Nodes_Item(self: *const T, Index: i32, _param_Node: ?*?*Node) callconv(.Inline) HRESULT { return @ptrCast(*const Nodes.VTable, self.vtable).Item(@ptrCast(*const Nodes, self), Index, _param_Node); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Nodes_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Nodes.VTable, self.vtable).get_Count(@ptrCast(*const Nodes, self), Count); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ContextMenu_Value = Guid.initString("dab39ce0-25e6-4e07-8362-ba9c95706545"); pub const IID_ContextMenu = &IID_ContextMenu_Value; pub const ContextMenu = 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 ContextMenu, retval: ?*?*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 ContextMenu, IndexOrPath: VARIANT, MenuItem: ?*?*MenuItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const ContextMenu, Count: ?*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 ContextMenu_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ContextMenu.VTable, self.vtable).get__NewEnum(@ptrCast(*const ContextMenu, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ContextMenu_get_Item(self: *const T, IndexOrPath: VARIANT, _param_MenuItem: ?*?*MenuItem) callconv(.Inline) HRESULT { return @ptrCast(*const ContextMenu.VTable, self.vtable).get_Item(@ptrCast(*const ContextMenu, self), IndexOrPath, _param_MenuItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ContextMenu_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ContextMenu.VTable, self.vtable).get_Count(@ptrCast(*const ContextMenu, self), Count); } };} pub usingnamespace MethodMixin(@This()); }; const IID_MenuItem_Value = Guid.initString("0178fad1-b361-4b27-96ad-67c57ebf2e1d"); pub const IID_MenuItem = &IID_MenuItem_Value; pub const MenuItem = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const MenuItem, DisplayName: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LanguageIndependentName: fn( self: *const MenuItem, LanguageIndependentName: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const MenuItem, Path: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LanguageIndependentPath: fn( self: *const MenuItem, LanguageIndependentPath: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Execute: fn( self: *const MenuItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const MenuItem, Enabled: ?*BOOL, ) 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 MenuItem_get_DisplayName(self: *const T, DisplayName: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).get_DisplayName(@ptrCast(*const MenuItem, self), DisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn MenuItem_get_LanguageIndependentName(self: *const T, LanguageIndependentName: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).get_LanguageIndependentName(@ptrCast(*const MenuItem, self), LanguageIndependentName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn MenuItem_get_Path(self: *const T, Path: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).get_Path(@ptrCast(*const MenuItem, self), Path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn MenuItem_get_LanguageIndependentPath(self: *const T, LanguageIndependentPath: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).get_LanguageIndependentPath(@ptrCast(*const MenuItem, self), LanguageIndependentPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn MenuItem_Execute(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).Execute(@ptrCast(*const MenuItem, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn MenuItem_get_Enabled(self: *const T, Enabled: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const MenuItem.VTable, self.vtable).get_Enabled(@ptrCast(*const MenuItem, self), Enabled); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Properties_Value = Guid.initString("2886abc2-a425-42b2-91c6-e25c0e04581c"); pub const IID_Properties = &IID_Properties_Value; pub const Properties = 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 Properties, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const Properties, Name: ?BSTR, Property: ?*?*Property, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const Properties, Count: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const Properties, Name: ?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 Properties_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const Properties.VTable, self.vtable).get__NewEnum(@ptrCast(*const Properties, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Properties_Item(self: *const T, Name: ?BSTR, _param_Property: ?*?*Property) callconv(.Inline) HRESULT { return @ptrCast(*const Properties.VTable, self.vtable).Item(@ptrCast(*const Properties, self), Name, _param_Property); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Properties_get_Count(self: *const T, Count: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const Properties.VTable, self.vtable).get_Count(@ptrCast(*const Properties, self), Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Properties_Remove(self: *const T, Name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const Properties.VTable, self.vtable).Remove(@ptrCast(*const Properties, self), Name); } };} pub usingnamespace MethodMixin(@This()); }; const IID_Property_Value = Guid.initString("4600c3a5-e301-41d8-b6d0-ef2e4212e0ca"); pub const IID_Property = &IID_Property_Value; pub const Property = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const Property, Value: ?*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 Property, Value: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const Property, Name: ?*?*u16, ) 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 Property_get_Value(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const Property.VTable, self.vtable).get_Value(@ptrCast(*const Property, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Property_put_Value(self: *const T, Value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const Property.VTable, self.vtable).put_Value(@ptrCast(*const Property, self), Value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn Property_get_Name(self: *const T, Name: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const Property.VTable, self.vtable).get_Name(@ptrCast(*const Property, self), Name); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_MMCVersionInfo_Value = Guid.initString("d6fedb1d-cf21-4bd9-af3b-c5468e9c6684"); pub const CLSID_MMCVersionInfo = &CLSID_MMCVersionInfo_Value; const CLSID_ConsolePower_Value = Guid.initString("f0285374-dff1-11d3-b433-00c04f8ecd78"); pub const CLSID_ConsolePower = &CLSID_ConsolePower_Value; pub const MMC_RESULT_VIEW_STYLE = enum(i32) { SINGLESEL = 1, SHOWSELALWAYS = 2, NOSORTHEADER = 4, ENSUREFOCUSVISIBLE = 8, }; pub const MMC_SINGLESEL = MMC_RESULT_VIEW_STYLE.SINGLESEL; pub const MMC_SHOWSELALWAYS = MMC_RESULT_VIEW_STYLE.SHOWSELALWAYS; pub const MMC_NOSORTHEADER = MMC_RESULT_VIEW_STYLE.NOSORTHEADER; pub const MMC_ENSUREFOCUSVISIBLE = MMC_RESULT_VIEW_STYLE.ENSUREFOCUSVISIBLE; pub const MMC_CONTROL_TYPE = enum(i32) { TOOLBAR = 0, MENUBUTTON = 1, COMBOBOXBAR = 2, }; pub const TOOLBAR = MMC_CONTROL_TYPE.TOOLBAR; pub const MENUBUTTON = MMC_CONTROL_TYPE.MENUBUTTON; pub const COMBOBOXBAR = MMC_CONTROL_TYPE.COMBOBOXBAR; pub const MMC_CONSOLE_VERB = enum(i32) { NONE = 0, OPEN = 32768, COPY = 32769, PASTE = 32770, DELETE = 32771, PROPERTIES = 32772, RENAME = 32773, REFRESH = 32774, PRINT = 32775, CUT = 32776, MAX = 32777, // FIRST = 32768, this enum value conflicts with OPEN // LAST = 32776, this enum value conflicts with CUT }; pub const MMC_VERB_NONE = MMC_CONSOLE_VERB.NONE; pub const MMC_VERB_OPEN = MMC_CONSOLE_VERB.OPEN; pub const MMC_VERB_COPY = MMC_CONSOLE_VERB.COPY; pub const MMC_VERB_PASTE = MMC_CONSOLE_VERB.PASTE; pub const MMC_VERB_DELETE = MMC_CONSOLE_VERB.DELETE; pub const MMC_VERB_PROPERTIES = MMC_CONSOLE_VERB.PROPERTIES; pub const MMC_VERB_RENAME = MMC_CONSOLE_VERB.RENAME; pub const MMC_VERB_REFRESH = MMC_CONSOLE_VERB.REFRESH; pub const MMC_VERB_PRINT = MMC_CONSOLE_VERB.PRINT; pub const MMC_VERB_CUT = MMC_CONSOLE_VERB.CUT; pub const MMC_VERB_MAX = MMC_CONSOLE_VERB.MAX; pub const MMC_VERB_FIRST = MMC_CONSOLE_VERB.OPEN; pub const MMC_VERB_LAST = MMC_CONSOLE_VERB.CUT; pub const MMCBUTTON = extern struct { nBitmap: i32, idCommand: i32, fsState: u8, fsType: u8, lpButtonText: ?PWSTR, lpTooltipText: ?PWSTR, }; pub const MMC_BUTTON_STATE = enum(i32) { ENABLED = 1, CHECKED = 2, HIDDEN = 4, INDETERMINATE = 8, BUTTONPRESSED = 16, }; pub const ENABLED = MMC_BUTTON_STATE.ENABLED; pub const CHECKED = MMC_BUTTON_STATE.CHECKED; pub const HIDDEN = MMC_BUTTON_STATE.HIDDEN; pub const INDETERMINATE = MMC_BUTTON_STATE.INDETERMINATE; pub const BUTTONPRESSED = MMC_BUTTON_STATE.BUTTONPRESSED; pub const RESULTDATAITEM = extern struct { mask: u32, bScopeItem: BOOL, itemID: isize, nIndex: i32, nCol: i32, str: ?PWSTR, nImage: i32, nState: u32, lParam: LPARAM, iIndent: i32, }; pub const RESULTFINDINFO = extern struct { psz: ?PWSTR, nStart: i32, dwOptions: u32, }; pub const SCOPEDATAITEM = extern struct { mask: u32, displayname: ?PWSTR, nImage: i32, nOpenImage: i32, nState: u32, cChildren: i32, lParam: LPARAM, relativeID: isize, ID: isize, }; pub const MMC_SCOPE_ITEM_STATE = enum(i32) { NORMAL = 1, BOLD = 2, EXPANDEDONCE = 3, }; pub const MMC_SCOPE_ITEM_STATE_NORMAL = MMC_SCOPE_ITEM_STATE.NORMAL; pub const MMC_SCOPE_ITEM_STATE_BOLD = MMC_SCOPE_ITEM_STATE.BOLD; pub const MMC_SCOPE_ITEM_STATE_EXPANDEDONCE = MMC_SCOPE_ITEM_STATE.EXPANDEDONCE; pub const CONTEXTMENUITEM = extern struct { strName: ?PWSTR, strStatusBarText: ?PWSTR, lCommandID: i32, lInsertionPointID: i32, fFlags: i32, fSpecialFlags: i32, }; pub const MMC_MENU_COMMAND_IDS = enum(i32) { T = -1, }; pub const MMCC_STANDARD_VIEW_SELECT = MMC_MENU_COMMAND_IDS.T; pub const MENUBUTTONDATA = extern struct { idCommand: i32, x: i32, y: i32, }; pub const MMC_FILTER_TYPE = enum(i32) { STRING_FILTER = 0, INT_FILTER = 1, FILTER_NOVALUE = 32768, }; pub const MMC_STRING_FILTER = MMC_FILTER_TYPE.STRING_FILTER; pub const MMC_INT_FILTER = MMC_FILTER_TYPE.INT_FILTER; pub const MMC_FILTER_NOVALUE = MMC_FILTER_TYPE.FILTER_NOVALUE; pub const MMC_FILTERDATA = extern struct { pszText: ?PWSTR, cchTextMax: i32, lValue: i32, }; pub const MMC_FILTER_CHANGE_CODE = enum(i32) { DISABLE = 0, ENABLE = 1, VALUE_CHANGE = 2, }; pub const MFCC_DISABLE = MMC_FILTER_CHANGE_CODE.DISABLE; pub const MFCC_ENABLE = MMC_FILTER_CHANGE_CODE.ENABLE; pub const MFCC_VALUE_CHANGE = MMC_FILTER_CHANGE_CODE.VALUE_CHANGE; pub const MMC_RESTORE_VIEW = extern struct { dwSize: u32, cookie: isize, pViewType: ?PWSTR, lViewOptions: i32, }; pub const MMC_EXPANDSYNC_STRUCT = extern struct { bHandled: BOOL, bExpanding: BOOL, hItem: isize, }; pub const MMC_VISIBLE_COLUMNS = extern struct { nVisibleColumns: i32, rgVisibleCols: [1]i32, }; pub const MMC_NOTIFY_TYPE = enum(i32) { ACTIVATE = 32769, ADD_IMAGES = 32770, BTN_CLICK = 32771, CLICK = 32772, COLUMN_CLICK = 32773, CONTEXTMENU = 32774, CUTORMOVE = 32775, DBLCLICK = 32776, DELETE = 32777, DESELECT_ALL = 32778, EXPAND = 32779, HELP = 32780, MENU_BTNCLICK = 32781, MINIMIZED = 32782, PASTE = 32783, PROPERTY_CHANGE = 32784, QUERY_PASTE = 32785, REFRESH = 32786, REMOVE_CHILDREN = 32787, RENAME = 32788, SELECT = 32789, SHOW = 32790, VIEW_CHANGE = 32791, SNAPINHELP = 32792, CONTEXTHELP = 32793, INITOCX = 32794, FILTER_CHANGE = 32795, FILTERBTN_CLICK = 32796, RESTORE_VIEW = 32797, PRINT = 32798, PRELOAD = 32799, LISTPAD = 32800, EXPANDSYNC = 32801, COLUMNS_CHANGED = 32802, CANPASTE_OUTOFPROC = 32803, }; pub const MMCN_ACTIVATE = MMC_NOTIFY_TYPE.ACTIVATE; pub const MMCN_ADD_IMAGES = MMC_NOTIFY_TYPE.ADD_IMAGES; pub const MMCN_BTN_CLICK = MMC_NOTIFY_TYPE.BTN_CLICK; pub const MMCN_CLICK = MMC_NOTIFY_TYPE.CLICK; pub const MMCN_COLUMN_CLICK = MMC_NOTIFY_TYPE.COLUMN_CLICK; pub const MMCN_CONTEXTMENU = MMC_NOTIFY_TYPE.CONTEXTMENU; pub const MMCN_CUTORMOVE = MMC_NOTIFY_TYPE.CUTORMOVE; pub const MMCN_DBLCLICK = MMC_NOTIFY_TYPE.DBLCLICK; pub const MMCN_DELETE = MMC_NOTIFY_TYPE.DELETE; pub const MMCN_DESELECT_ALL = MMC_NOTIFY_TYPE.DESELECT_ALL; pub const MMCN_EXPAND = MMC_NOTIFY_TYPE.EXPAND; pub const MMCN_HELP = MMC_NOTIFY_TYPE.HELP; pub const MMCN_MENU_BTNCLICK = MMC_NOTIFY_TYPE.MENU_BTNCLICK; pub const MMCN_MINIMIZED = MMC_NOTIFY_TYPE.MINIMIZED; pub const MMCN_PASTE = MMC_NOTIFY_TYPE.PASTE; pub const MMCN_PROPERTY_CHANGE = MMC_NOTIFY_TYPE.PROPERTY_CHANGE; pub const MMCN_QUERY_PASTE = MMC_NOTIFY_TYPE.QUERY_PASTE; pub const MMCN_REFRESH = MMC_NOTIFY_TYPE.REFRESH; pub const MMCN_REMOVE_CHILDREN = MMC_NOTIFY_TYPE.REMOVE_CHILDREN; pub const MMCN_RENAME = MMC_NOTIFY_TYPE.RENAME; pub const MMCN_SELECT = MMC_NOTIFY_TYPE.SELECT; pub const MMCN_SHOW = MMC_NOTIFY_TYPE.SHOW; pub const MMCN_VIEW_CHANGE = MMC_NOTIFY_TYPE.VIEW_CHANGE; pub const MMCN_SNAPINHELP = MMC_NOTIFY_TYPE.SNAPINHELP; pub const MMCN_CONTEXTHELP = MMC_NOTIFY_TYPE.CONTEXTHELP; pub const MMCN_INITOCX = MMC_NOTIFY_TYPE.INITOCX; pub const MMCN_FILTER_CHANGE = MMC_NOTIFY_TYPE.FILTER_CHANGE; pub const MMCN_FILTERBTN_CLICK = MMC_NOTIFY_TYPE.FILTERBTN_CLICK; pub const MMCN_RESTORE_VIEW = MMC_NOTIFY_TYPE.RESTORE_VIEW; pub const MMCN_PRINT = MMC_NOTIFY_TYPE.PRINT; pub const MMCN_PRELOAD = MMC_NOTIFY_TYPE.PRELOAD; pub const MMCN_LISTPAD = MMC_NOTIFY_TYPE.LISTPAD; pub const MMCN_EXPANDSYNC = MMC_NOTIFY_TYPE.EXPANDSYNC; pub const MMCN_COLUMNS_CHANGED = MMC_NOTIFY_TYPE.COLUMNS_CHANGED; pub const MMCN_CANPASTE_OUTOFPROC = MMC_NOTIFY_TYPE.CANPASTE_OUTOFPROC; pub const DATA_OBJECT_TYPES = enum(i32) { SCOPE = 32768, RESULT = 32769, SNAPIN_MANAGER = 32770, UNINITIALIZED = 65535, }; pub const CCT_SCOPE = DATA_OBJECT_TYPES.SCOPE; pub const CCT_RESULT = DATA_OBJECT_TYPES.RESULT; pub const CCT_SNAPIN_MANAGER = DATA_OBJECT_TYPES.SNAPIN_MANAGER; pub const CCT_UNINITIALIZED = DATA_OBJECT_TYPES.UNINITIALIZED; pub const SMMCDataObjects = extern struct { count: u32, lpDataObject: [1]?*IDataObject, }; pub const SMMCObjectTypes = extern struct { count: u32, guid: [1]Guid, }; pub const SNodeID = extern struct { cBytes: u32, id: [1]u8, }; pub const SNodeID2 = extern struct { dwFlags: u32, cBytes: u32, id: [1]u8, }; pub const SColumnSetID = extern struct { dwFlags: u32, cBytes: u32, id: [1]u8, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IComponentData_Value = Guid.initString("955ab28a-5218-11d0-a985-00c04fd8d565"); pub const IID_IComponentData = &IID_IComponentData_Value; pub const IComponentData = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IComponentData, pUnknown: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateComponent: fn( self: *const IComponentData, ppComponent: ?*?*IComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Notify: fn( self: *const IComponentData, lpDataObject: ?*IDataObject, event: MMC_NOTIFY_TYPE, arg: LPARAM, param3: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Destroy: fn( self: *const IComponentData, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryDataObject: fn( self: *const IComponentData, cookie: isize, type: DATA_OBJECT_TYPES, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayInfo: fn( self: *const IComponentData, pScopeDataItem: ?*SCOPEDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareObjects: fn( self: *const IComponentData, lpDataObjectA: ?*IDataObject, lpDataObjectB: ?*IDataObject, ) 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 IComponentData_Initialize(self: *const T, pUnknown: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).Initialize(@ptrCast(*const IComponentData, self), pUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_CreateComponent(self: *const T, ppComponent: ?*?*IComponent) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).CreateComponent(@ptrCast(*const IComponentData, self), ppComponent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_Notify(self: *const T, lpDataObject: ?*IDataObject, event: MMC_NOTIFY_TYPE, arg: LPARAM, param3: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).Notify(@ptrCast(*const IComponentData, self), lpDataObject, event, arg, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_Destroy(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).Destroy(@ptrCast(*const IComponentData, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_QueryDataObject(self: *const T, cookie: isize, type_: DATA_OBJECT_TYPES, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).QueryDataObject(@ptrCast(*const IComponentData, self), cookie, type_, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_GetDisplayInfo(self: *const T, pScopeDataItem: ?*SCOPEDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).GetDisplayInfo(@ptrCast(*const IComponentData, self), pScopeDataItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData_CompareObjects(self: *const T, lpDataObjectA: ?*IDataObject, lpDataObjectB: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData.VTable, self.vtable).CompareObjects(@ptrCast(*const IComponentData, self), lpDataObjectA, lpDataObjectB); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IComponent_Value = Guid.initString("43136eb2-d36c-11cf-adbc-00aa00a80033"); pub const IID_IComponent = &IID_IComponent_Value; pub const IComponent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IComponent, lpConsole: ?*IConsole, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Notify: fn( self: *const IComponent, lpDataObject: ?*IDataObject, event: MMC_NOTIFY_TYPE, arg: LPARAM, param3: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Destroy: fn( self: *const IComponent, cookie: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryDataObject: fn( self: *const IComponent, cookie: isize, type: DATA_OBJECT_TYPES, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResultViewType: fn( self: *const IComponent, cookie: isize, ppViewType: ?*?PWSTR, pViewOptions: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayInfo: fn( self: *const IComponent, pResultDataItem: ?*RESULTDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareObjects: fn( self: *const IComponent, lpDataObjectA: ?*IDataObject, lpDataObjectB: ?*IDataObject, ) 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 IComponent_Initialize(self: *const T, lpConsole: ?*IConsole) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).Initialize(@ptrCast(*const IComponent, self), lpConsole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_Notify(self: *const T, lpDataObject: ?*IDataObject, event: MMC_NOTIFY_TYPE, arg: LPARAM, param3: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).Notify(@ptrCast(*const IComponent, self), lpDataObject, event, arg, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_Destroy(self: *const T, cookie: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).Destroy(@ptrCast(*const IComponent, self), cookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_QueryDataObject(self: *const T, cookie: isize, type_: DATA_OBJECT_TYPES, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).QueryDataObject(@ptrCast(*const IComponent, self), cookie, type_, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_GetResultViewType(self: *const T, cookie: isize, ppViewType: ?*?PWSTR, pViewOptions: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).GetResultViewType(@ptrCast(*const IComponent, self), cookie, ppViewType, pViewOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_GetDisplayInfo(self: *const T, pResultDataItem: ?*RESULTDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).GetDisplayInfo(@ptrCast(*const IComponent, self), pResultDataItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent_CompareObjects(self: *const T, lpDataObjectA: ?*IDataObject, lpDataObjectB: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent.VTable, self.vtable).CompareObjects(@ptrCast(*const IComponent, self), lpDataObjectA, lpDataObjectB); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IResultDataCompare_Value = Guid.initString("e8315a52-7a1a-11d0-a2d2-00c04fd909dd"); pub const IID_IResultDataCompare = &IID_IResultDataCompare_Value; pub const IResultDataCompare = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compare: fn( self: *const IResultDataCompare, lUserParam: LPARAM, cookieA: isize, cookieB: isize, pnResult: ?*i32, ) 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 IResultDataCompare_Compare(self: *const T, lUserParam: LPARAM, cookieA: isize, cookieB: isize, pnResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultDataCompare.VTable, self.vtable).Compare(@ptrCast(*const IResultDataCompare, self), lUserParam, cookieA, cookieB, pnResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IResultOwnerData_Value = Guid.initString("9cb396d8-ea83-11d0-aef1-00c04fb6dd2c"); pub const IID_IResultOwnerData = &IID_IResultOwnerData_Value; pub const IResultOwnerData = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, FindItem: fn( self: *const IResultOwnerData, pFindInfo: ?*RESULTFINDINFO, pnFoundIndex: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CacheHint: fn( self: *const IResultOwnerData, nStartIndex: i32, nEndIndex: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SortItems: fn( self: *const IResultOwnerData, nColumn: i32, dwSortOptions: u32, lUserParam: LPARAM, ) 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 IResultOwnerData_FindItem(self: *const T, pFindInfo: ?*RESULTFINDINFO, pnFoundIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultOwnerData.VTable, self.vtable).FindItem(@ptrCast(*const IResultOwnerData, self), pFindInfo, pnFoundIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultOwnerData_CacheHint(self: *const T, nStartIndex: i32, nEndIndex: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultOwnerData.VTable, self.vtable).CacheHint(@ptrCast(*const IResultOwnerData, self), nStartIndex, nEndIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultOwnerData_SortItems(self: *const T, nColumn: i32, dwSortOptions: u32, lUserParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultOwnerData.VTable, self.vtable).SortItems(@ptrCast(*const IResultOwnerData, self), nColumn, dwSortOptions, lUserParam); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsole_Value = Guid.initString("43136eb1-d36c-11cf-adbc-00aa00a80033"); pub const IID_IConsole = &IID_IConsole_Value; pub const IConsole = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetHeader: fn( self: *const IConsole, pHeader: ?*IHeaderCtrl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetToolbar: fn( self: *const IConsole, pToolbar: ?*IToolbar, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryResultView: fn( self: *const IConsole, pUnknown: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryScopeImageList: fn( self: *const IConsole, ppImageList: ?*?*IImageList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryResultImageList: fn( self: *const IConsole, ppImageList: ?*?*IImageList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateAllViews: fn( self: *const IConsole, lpDataObject: ?*IDataObject, data: LPARAM, hint: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MessageBox: fn( self: *const IConsole, lpszText: ?[*:0]const u16, lpszTitle: ?[*:0]const u16, fuStyle: u32, piRetval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryConsoleVerb: fn( self: *const IConsole, ppConsoleVerb: ?*?*IConsoleVerb, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SelectScopeItem: fn( self: *const IConsole, hScopeItem: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMainWindow: fn( self: *const IConsole, phwnd: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NewWindow: fn( self: *const IConsole, hScopeItem: isize, lOptions: 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 IConsole_SetHeader(self: *const T, pHeader: ?*IHeaderCtrl) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).SetHeader(@ptrCast(*const IConsole, self), pHeader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_SetToolbar(self: *const T, pToolbar: ?*IToolbar) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).SetToolbar(@ptrCast(*const IConsole, self), pToolbar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_QueryResultView(self: *const T, pUnknown: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).QueryResultView(@ptrCast(*const IConsole, self), pUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_QueryScopeImageList(self: *const T, ppImageList: ?*?*IImageList) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).QueryScopeImageList(@ptrCast(*const IConsole, self), ppImageList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_QueryResultImageList(self: *const T, ppImageList: ?*?*IImageList) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).QueryResultImageList(@ptrCast(*const IConsole, self), ppImageList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_UpdateAllViews(self: *const T, lpDataObject: ?*IDataObject, data: LPARAM, hint: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).UpdateAllViews(@ptrCast(*const IConsole, self), lpDataObject, data, hint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_MessageBox(self: *const T, lpszText: ?[*:0]const u16, lpszTitle: ?[*:0]const u16, fuStyle: u32, piRetval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).MessageBox(@ptrCast(*const IConsole, self), lpszText, lpszTitle, fuStyle, piRetval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_QueryConsoleVerb(self: *const T, ppConsoleVerb: ?*?*IConsoleVerb) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).QueryConsoleVerb(@ptrCast(*const IConsole, self), ppConsoleVerb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_SelectScopeItem(self: *const T, hScopeItem: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).SelectScopeItem(@ptrCast(*const IConsole, self), hScopeItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_GetMainWindow(self: *const T, phwnd: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).GetMainWindow(@ptrCast(*const IConsole, self), phwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole_NewWindow(self: *const T, hScopeItem: isize, lOptions: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole.VTable, self.vtable).NewWindow(@ptrCast(*const IConsole, self), hScopeItem, lOptions); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IHeaderCtrl_Value = Guid.initString("43136eb3-d36c-11cf-adbc-00aa00a80033"); pub const IID_IHeaderCtrl = &IID_IHeaderCtrl_Value; pub const IHeaderCtrl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InsertColumn: fn( self: *const IHeaderCtrl, nCol: i32, title: ?[*:0]const u16, nFormat: i32, nWidth: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteColumn: fn( self: *const IHeaderCtrl, nCol: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumnText: fn( self: *const IHeaderCtrl, nCol: i32, title: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnText: fn( self: *const IHeaderCtrl, nCol: i32, pText: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumnWidth: fn( self: *const IHeaderCtrl, nCol: i32, nWidth: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnWidth: fn( self: *const IHeaderCtrl, nCol: i32, pWidth: ?*i32, ) 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 IHeaderCtrl_InsertColumn(self: *const T, nCol: i32, title: ?[*:0]const u16, nFormat: i32, nWidth: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).InsertColumn(@ptrCast(*const IHeaderCtrl, self), nCol, title, nFormat, nWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl_DeleteColumn(self: *const T, nCol: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).DeleteColumn(@ptrCast(*const IHeaderCtrl, self), nCol); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl_SetColumnText(self: *const T, nCol: i32, title: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).SetColumnText(@ptrCast(*const IHeaderCtrl, self), nCol, title); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl_GetColumnText(self: *const T, nCol: i32, pText: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).GetColumnText(@ptrCast(*const IHeaderCtrl, self), nCol, pText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl_SetColumnWidth(self: *const T, nCol: i32, nWidth: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).SetColumnWidth(@ptrCast(*const IHeaderCtrl, self), nCol, nWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl_GetColumnWidth(self: *const T, nCol: i32, pWidth: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl.VTable, self.vtable).GetColumnWidth(@ptrCast(*const IHeaderCtrl, self), nCol, pWidth); } };} pub usingnamespace MethodMixin(@This()); }; pub const CCM_INSERTIONPOINTID = enum(i32) { MASK_SPECIAL = -65536, MASK_SHARED = -2147483648, MASK_CREATE_PRIMARY = 1073741824, MASK_ADD_PRIMARY = 536870912, MASK_ADD_3RDPARTY = 268435456, MASK_RESERVED = 268369920, MASK_FLAGINDEX = 31, PRIMARY_TOP = -1610612736, PRIMARY_NEW = -1610612735, PRIMARY_TASK = -1610612734, PRIMARY_VIEW = -1610612733, PRIMARY_HELP = -1610612732, @"3RDPARTY_NEW" = -1879048191, @"3RDPARTY_TASK" = -1879048190, // ROOT_MENU = -2147483648, this enum value conflicts with MASK_SHARED }; pub const CCM_INSERTIONPOINTID_MASK_SPECIAL = CCM_INSERTIONPOINTID.MASK_SPECIAL; pub const CCM_INSERTIONPOINTID_MASK_SHARED = CCM_INSERTIONPOINTID.MASK_SHARED; pub const CCM_INSERTIONPOINTID_MASK_CREATE_PRIMARY = CCM_INSERTIONPOINTID.MASK_CREATE_PRIMARY; pub const CCM_INSERTIONPOINTID_MASK_ADD_PRIMARY = CCM_INSERTIONPOINTID.MASK_ADD_PRIMARY; pub const CCM_INSERTIONPOINTID_MASK_ADD_3RDPARTY = CCM_INSERTIONPOINTID.MASK_ADD_3RDPARTY; pub const CCM_INSERTIONPOINTID_MASK_RESERVED = CCM_INSERTIONPOINTID.MASK_RESERVED; pub const CCM_INSERTIONPOINTID_MASK_FLAGINDEX = CCM_INSERTIONPOINTID.MASK_FLAGINDEX; pub const CCM_INSERTIONPOINTID_PRIMARY_TOP = CCM_INSERTIONPOINTID.PRIMARY_TOP; pub const CCM_INSERTIONPOINTID_PRIMARY_NEW = CCM_INSERTIONPOINTID.PRIMARY_NEW; pub const CCM_INSERTIONPOINTID_PRIMARY_TASK = CCM_INSERTIONPOINTID.PRIMARY_TASK; pub const CCM_INSERTIONPOINTID_PRIMARY_VIEW = CCM_INSERTIONPOINTID.PRIMARY_VIEW; pub const CCM_INSERTIONPOINTID_PRIMARY_HELP = CCM_INSERTIONPOINTID.PRIMARY_HELP; pub const CCM_INSERTIONPOINTID_3RDPARTY_NEW = CCM_INSERTIONPOINTID.@"3RDPARTY_NEW"; pub const CCM_INSERTIONPOINTID_3RDPARTY_TASK = CCM_INSERTIONPOINTID.@"3RDPARTY_TASK"; pub const CCM_INSERTIONPOINTID_ROOT_MENU = CCM_INSERTIONPOINTID.MASK_SHARED; pub const CCM_INSERTIONALLOWED = enum(i32) { TOP = 1, NEW = 2, TASK = 4, VIEW = 8, }; pub const CCM_INSERTIONALLOWED_TOP = CCM_INSERTIONALLOWED.TOP; pub const CCM_INSERTIONALLOWED_NEW = CCM_INSERTIONALLOWED.NEW; pub const CCM_INSERTIONALLOWED_TASK = CCM_INSERTIONALLOWED.TASK; pub const CCM_INSERTIONALLOWED_VIEW = CCM_INSERTIONALLOWED.VIEW; pub const CCM_COMMANDID_MASK_CONSTANTS = enum(u32) { D = 4294901760, }; pub const CCM_COMMANDID_MASK_RESERVED = CCM_COMMANDID_MASK_CONSTANTS.D; pub const CCM_SPECIAL = enum(i32) { SEPARATOR = 1, SUBMENU = 2, DEFAULT_ITEM = 4, INSERTION_POINT = 8, TESTONLY = 16, }; pub const CCM_SPECIAL_SEPARATOR = CCM_SPECIAL.SEPARATOR; pub const CCM_SPECIAL_SUBMENU = CCM_SPECIAL.SUBMENU; pub const CCM_SPECIAL_DEFAULT_ITEM = CCM_SPECIAL.DEFAULT_ITEM; pub const CCM_SPECIAL_INSERTION_POINT = CCM_SPECIAL.INSERTION_POINT; pub const CCM_SPECIAL_TESTONLY = CCM_SPECIAL.TESTONLY; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IContextMenuCallback_Value = Guid.initString("43136eb7-d36c-11cf-adbc-00aa00a80033"); pub const IID_IContextMenuCallback = &IID_IContextMenuCallback_Value; pub const IContextMenuCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddItem: fn( self: *const IContextMenuCallback, pItem: ?*CONTEXTMENUITEM, ) 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 IContextMenuCallback_AddItem(self: *const T, pItem: ?*CONTEXTMENUITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuCallback.VTable, self.vtable).AddItem(@ptrCast(*const IContextMenuCallback, self), pItem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IContextMenuProvider_Value = Guid.initString("43136eb6-d36c-11cf-adbc-00aa00a80033"); pub const IID_IContextMenuProvider = &IID_IContextMenuProvider_Value; pub const IContextMenuProvider = extern struct { pub const VTable = extern struct { base: IContextMenuCallback.VTable, EmptyMenuList: fn( self: *const IContextMenuProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPrimaryExtensionItems: fn( self: *const IContextMenuProvider, piExtension: ?*IUnknown, piDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddThirdPartyExtensionItems: fn( self: *const IContextMenuProvider, piDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowContextMenu: fn( self: *const IContextMenuProvider, hwndParent: ?HWND, xPos: i32, yPos: i32, plSelected: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IContextMenuCallback.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IContextMenuProvider_EmptyMenuList(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuProvider.VTable, self.vtable).EmptyMenuList(@ptrCast(*const IContextMenuProvider, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IContextMenuProvider_AddPrimaryExtensionItems(self: *const T, piExtension: ?*IUnknown, piDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuProvider.VTable, self.vtable).AddPrimaryExtensionItems(@ptrCast(*const IContextMenuProvider, self), piExtension, piDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IContextMenuProvider_AddThirdPartyExtensionItems(self: *const T, piDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuProvider.VTable, self.vtable).AddThirdPartyExtensionItems(@ptrCast(*const IContextMenuProvider, self), piDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IContextMenuProvider_ShowContextMenu(self: *const T, hwndParent: ?HWND, xPos: i32, yPos: i32, plSelected: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuProvider.VTable, self.vtable).ShowContextMenu(@ptrCast(*const IContextMenuProvider, self), hwndParent, xPos, yPos, plSelected); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendContextMenu_Value = Guid.initString("4f3b7a4f-cfac-11cf-b8e3-00c04fd8d5b0"); pub const IID_IExtendContextMenu = &IID_IExtendContextMenu_Value; pub const IExtendContextMenu = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddMenuItems: fn( self: *const IExtendContextMenu, piDataObject: ?*IDataObject, piCallback: ?*IContextMenuCallback, pInsertionAllowed: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Command: fn( self: *const IExtendContextMenu, lCommandID: i32, piDataObject: ?*IDataObject, ) 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 IExtendContextMenu_AddMenuItems(self: *const T, piDataObject: ?*IDataObject, piCallback: ?*IContextMenuCallback, pInsertionAllowed: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendContextMenu.VTable, self.vtable).AddMenuItems(@ptrCast(*const IExtendContextMenu, self), piDataObject, piCallback, pInsertionAllowed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendContextMenu_Command(self: *const T, lCommandID: i32, piDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendContextMenu.VTable, self.vtable).Command(@ptrCast(*const IExtendContextMenu, self), lCommandID, piDataObject); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IImageList_Value = Guid.initString("43136eb8-d36c-11cf-adbc-00aa00a80033"); pub const IID_IImageList = &IID_IImageList_Value; pub const IImageList = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ImageListSetIcon: fn( self: *const IImageList, pIcon: ?*isize, nLoc: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ImageListSetStrip: fn( self: *const IImageList, pBMapSm: ?*isize, pBMapLg: ?*isize, nStartLoc: i32, cMask: 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 IImageList_ImageListSetIcon(self: *const T, pIcon: ?*isize, nLoc: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IImageList.VTable, self.vtable).ImageListSetIcon(@ptrCast(*const IImageList, self), pIcon, nLoc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IImageList_ImageListSetStrip(self: *const T, pBMapSm: ?*isize, pBMapLg: ?*isize, nStartLoc: i32, cMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IImageList.VTable, self.vtable).ImageListSetStrip(@ptrCast(*const IImageList, self), pBMapSm, pBMapLg, nStartLoc, cMask); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IResultData_Value = Guid.initString("31da5fa0-e0eb-11cf-9f21-00aa003ca9f6"); pub const IID_IResultData = &IID_IResultData_Value; pub const IResultData = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InsertItem: fn( self: *const IResultData, item: ?*RESULTDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteItem: fn( self: *const IResultData, itemID: isize, nCol: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindItemByLParam: fn( self: *const IResultData, lParam: LPARAM, pItemID: ?*isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAllRsltItems: fn( self: *const IResultData, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetItem: fn( self: *const IResultData, item: ?*RESULTDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItem: fn( self: *const IResultData, item: ?*RESULTDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextItem: fn( self: *const IResultData, item: ?*RESULTDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyItemState: fn( self: *const IResultData, nIndex: i32, itemID: isize, uAdd: u32, uRemove: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyViewStyle: fn( self: *const IResultData, add: MMC_RESULT_VIEW_STYLE, remove: MMC_RESULT_VIEW_STYLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetViewMode: fn( self: *const IResultData, lViewMode: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetViewMode: fn( self: *const IResultData, lViewMode: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateItem: fn( self: *const IResultData, itemID: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Sort: fn( self: *const IResultData, nColumn: i32, dwSortOptions: u32, lUserParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDescBarText: fn( self: *const IResultData, DescText: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetItemCount: fn( self: *const IResultData, nItemCount: i32, dwOptions: 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 IResultData_InsertItem(self: *const T, item: ?*RESULTDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).InsertItem(@ptrCast(*const IResultData, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_DeleteItem(self: *const T, itemID: isize, nCol: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).DeleteItem(@ptrCast(*const IResultData, self), itemID, nCol); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_FindItemByLParam(self: *const T, lParam: LPARAM, pItemID: ?*isize) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).FindItemByLParam(@ptrCast(*const IResultData, self), lParam, pItemID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_DeleteAllRsltItems(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).DeleteAllRsltItems(@ptrCast(*const IResultData, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_SetItem(self: *const T, item: ?*RESULTDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).SetItem(@ptrCast(*const IResultData, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_GetItem(self: *const T, item: ?*RESULTDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).GetItem(@ptrCast(*const IResultData, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_GetNextItem(self: *const T, item: ?*RESULTDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).GetNextItem(@ptrCast(*const IResultData, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_ModifyItemState(self: *const T, nIndex: i32, itemID: isize, uAdd: u32, uRemove: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).ModifyItemState(@ptrCast(*const IResultData, self), nIndex, itemID, uAdd, uRemove); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_ModifyViewStyle(self: *const T, add: MMC_RESULT_VIEW_STYLE, remove: MMC_RESULT_VIEW_STYLE) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).ModifyViewStyle(@ptrCast(*const IResultData, self), add, remove); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_SetViewMode(self: *const T, lViewMode: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).SetViewMode(@ptrCast(*const IResultData, self), lViewMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_GetViewMode(self: *const T, lViewMode: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).GetViewMode(@ptrCast(*const IResultData, self), lViewMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_UpdateItem(self: *const T, itemID: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).UpdateItem(@ptrCast(*const IResultData, self), itemID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_Sort(self: *const T, nColumn: i32, dwSortOptions: u32, lUserParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).Sort(@ptrCast(*const IResultData, self), nColumn, dwSortOptions, lUserParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_SetDescBarText(self: *const T, DescText: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).SetDescBarText(@ptrCast(*const IResultData, self), DescText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData_SetItemCount(self: *const T, nItemCount: i32, dwOptions: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData.VTable, self.vtable).SetItemCount(@ptrCast(*const IResultData, self), nItemCount, dwOptions); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsoleNameSpace_Value = Guid.initString("bedeb620-f24d-11cf-8afc-00aa003ca9f6"); pub const IID_IConsoleNameSpace = &IID_IConsoleNameSpace_Value; pub const IConsoleNameSpace = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InsertItem: fn( self: *const IConsoleNameSpace, item: ?*SCOPEDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteItem: fn( self: *const IConsoleNameSpace, hItem: isize, fDeleteThis: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetItem: fn( self: *const IConsoleNameSpace, item: ?*SCOPEDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItem: fn( self: *const IConsoleNameSpace, item: ?*SCOPEDATAITEM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChildItem: fn( self: *const IConsoleNameSpace, item: isize, pItemChild: ?*isize, pCookie: ?*isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextItem: fn( self: *const IConsoleNameSpace, item: isize, pItemNext: ?*isize, pCookie: ?*isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParentItem: fn( self: *const IConsoleNameSpace, item: isize, pItemParent: ?*isize, pCookie: ?*isize, ) 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 IConsoleNameSpace_InsertItem(self: *const T, item: ?*SCOPEDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).InsertItem(@ptrCast(*const IConsoleNameSpace, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_DeleteItem(self: *const T, hItem: isize, fDeleteThis: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).DeleteItem(@ptrCast(*const IConsoleNameSpace, self), hItem, fDeleteThis); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_SetItem(self: *const T, item: ?*SCOPEDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).SetItem(@ptrCast(*const IConsoleNameSpace, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_GetItem(self: *const T, item: ?*SCOPEDATAITEM) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).GetItem(@ptrCast(*const IConsoleNameSpace, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_GetChildItem(self: *const T, item: isize, pItemChild: ?*isize, pCookie: ?*isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).GetChildItem(@ptrCast(*const IConsoleNameSpace, self), item, pItemChild, pCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_GetNextItem(self: *const T, item: isize, pItemNext: ?*isize, pCookie: ?*isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).GetNextItem(@ptrCast(*const IConsoleNameSpace, self), item, pItemNext, pCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace_GetParentItem(self: *const T, item: isize, pItemParent: ?*isize, pCookie: ?*isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace.VTable, self.vtable).GetParentItem(@ptrCast(*const IConsoleNameSpace, self), item, pItemParent, pCookie); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsoleNameSpace2_Value = Guid.initString("255f18cc-65db-11d1-a7dc-00c04fd8d565"); pub const IID_IConsoleNameSpace2 = &IID_IConsoleNameSpace2_Value; pub const IConsoleNameSpace2 = extern struct { pub const VTable = extern struct { base: IConsoleNameSpace.VTable, Expand: fn( self: *const IConsoleNameSpace2, hItem: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddExtension: fn( self: *const IConsoleNameSpace2, hItem: isize, lpClsid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IConsoleNameSpace.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace2_Expand(self: *const T, hItem: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace2.VTable, self.vtable).Expand(@ptrCast(*const IConsoleNameSpace2, self), hItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleNameSpace2_AddExtension(self: *const T, hItem: isize, lpClsid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleNameSpace2.VTable, self.vtable).AddExtension(@ptrCast(*const IConsoleNameSpace2, self), hItem, lpClsid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPropertySheetCallback_Value = Guid.initString("85de64dd-ef21-11cf-a285-00c04fd8dbe6"); pub const IID_IPropertySheetCallback = &IID_IPropertySheetCallback_Value; pub const IPropertySheetCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddPage: fn( self: *const IPropertySheetCallback, hPage: ?HPROPSHEETPAGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemovePage: fn( self: *const IPropertySheetCallback, hPage: ?HPROPSHEETPAGE, ) 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 IPropertySheetCallback_AddPage(self: *const T, hPage: ?HPROPSHEETPAGE) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetCallback.VTable, self.vtable).AddPage(@ptrCast(*const IPropertySheetCallback, self), hPage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertySheetCallback_RemovePage(self: *const T, hPage: ?HPROPSHEETPAGE) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetCallback.VTable, self.vtable).RemovePage(@ptrCast(*const IPropertySheetCallback, self), hPage); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPropertySheetProvider_Value = Guid.initString("85de64de-ef21-11cf-a285-00c04fd8dbe6"); pub const IID_IPropertySheetProvider = &IID_IPropertySheetProvider_Value; pub const IPropertySheetProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreatePropertySheet: fn( self: *const IPropertySheetProvider, title: ?[*:0]const u16, type: u8, cookie: isize, pIDataObjectm: ?*IDataObject, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindPropertySheet: fn( self: *const IPropertySheetProvider, hItem: isize, lpComponent: ?*IComponent, lpDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPrimaryPages: fn( self: *const IPropertySheetProvider, lpUnknown: ?*IUnknown, bCreateHandle: BOOL, hNotifyWindow: ?HWND, bScopePane: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddExtensionPages: fn( self: *const IPropertySheetProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Show: fn( self: *const IPropertySheetProvider, window: isize, page: i32, ) 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 IPropertySheetProvider_CreatePropertySheet(self: *const T, title: ?[*:0]const u16, type_: u8, cookie: isize, pIDataObjectm: ?*IDataObject, dwOptions: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetProvider.VTable, self.vtable).CreatePropertySheet(@ptrCast(*const IPropertySheetProvider, self), title, type_, cookie, pIDataObjectm, dwOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertySheetProvider_FindPropertySheet(self: *const T, hItem: isize, lpComponent: ?*IComponent, lpDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetProvider.VTable, self.vtable).FindPropertySheet(@ptrCast(*const IPropertySheetProvider, self), hItem, lpComponent, lpDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertySheetProvider_AddPrimaryPages(self: *const T, lpUnknown: ?*IUnknown, bCreateHandle: BOOL, hNotifyWindow: ?HWND, bScopePane: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetProvider.VTable, self.vtable).AddPrimaryPages(@ptrCast(*const IPropertySheetProvider, self), lpUnknown, bCreateHandle, hNotifyWindow, bScopePane); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertySheetProvider_AddExtensionPages(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetProvider.VTable, self.vtable).AddExtensionPages(@ptrCast(*const IPropertySheetProvider, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPropertySheetProvider_Show(self: *const T, window: isize, page: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPropertySheetProvider.VTable, self.vtable).Show(@ptrCast(*const IPropertySheetProvider, self), window, page); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendPropertySheet_Value = Guid.initString("85de64dc-ef21-11cf-a285-00c04fd8dbe6"); pub const IID_IExtendPropertySheet = &IID_IExtendPropertySheet_Value; pub const IExtendPropertySheet = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreatePropertyPages: fn( self: *const IExtendPropertySheet, lpProvider: ?*IPropertySheetCallback, handle: isize, lpIDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryPagesFor: fn( self: *const IExtendPropertySheet, lpDataObject: ?*IDataObject, ) 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 IExtendPropertySheet_CreatePropertyPages(self: *const T, lpProvider: ?*IPropertySheetCallback, handle: isize, lpIDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendPropertySheet.VTable, self.vtable).CreatePropertyPages(@ptrCast(*const IExtendPropertySheet, self), lpProvider, handle, lpIDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendPropertySheet_QueryPagesFor(self: *const T, lpDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendPropertySheet.VTable, self.vtable).QueryPagesFor(@ptrCast(*const IExtendPropertySheet, self), lpDataObject); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IControlbar_Value = Guid.initString("69fb811e-6c1c-11d0-a2cb-00c04fd909dd"); pub const IID_IControlbar = &IID_IControlbar_Value; pub const IControlbar = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Create: fn( self: *const IControlbar, nType: MMC_CONTROL_TYPE, pExtendControlbar: ?*IExtendControlbar, ppUnknown: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Attach: fn( self: *const IControlbar, nType: MMC_CONTROL_TYPE, lpUnknown: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Detach: fn( self: *const IControlbar, lpUnknown: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IControlbar_Create(self: *const T, nType: MMC_CONTROL_TYPE, pExtendControlbar: ?*IExtendControlbar, ppUnknown: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IControlbar.VTable, self.vtable).Create(@ptrCast(*const IControlbar, self), nType, pExtendControlbar, ppUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IControlbar_Attach(self: *const T, nType: MMC_CONTROL_TYPE, lpUnknown: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IControlbar.VTable, self.vtable).Attach(@ptrCast(*const IControlbar, self), nType, lpUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IControlbar_Detach(self: *const T, lpUnknown: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IControlbar.VTable, self.vtable).Detach(@ptrCast(*const IControlbar, self), lpUnknown); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendControlbar_Value = Guid.initString("49506520-6f40-11d0-a98b-00c04fd8d565"); pub const IID_IExtendControlbar = &IID_IExtendControlbar_Value; pub const IExtendControlbar = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetControlbar: fn( self: *const IExtendControlbar, pControlbar: ?*IControlbar, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ControlbarNotify: fn( self: *const IExtendControlbar, event: MMC_NOTIFY_TYPE, arg: LPARAM, param2: LPARAM, ) 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 IExtendControlbar_SetControlbar(self: *const T, pControlbar: ?*IControlbar) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendControlbar.VTable, self.vtable).SetControlbar(@ptrCast(*const IExtendControlbar, self), pControlbar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendControlbar_ControlbarNotify(self: *const T, event: MMC_NOTIFY_TYPE, arg: LPARAM, param2: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendControlbar.VTable, self.vtable).ControlbarNotify(@ptrCast(*const IExtendControlbar, self), event, arg, param2); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IToolbar_Value = Guid.initString("43136eb9-d36c-11cf-adbc-00aa00a80033"); pub const IID_IToolbar = &IID_IToolbar_Value; pub const IToolbar = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddBitmap: fn( self: *const IToolbar, nImages: i32, hbmp: ?HBITMAP, cxSize: i32, cySize: i32, crMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddButtons: fn( self: *const IToolbar, nButtons: i32, lpButtons: ?*MMCBUTTON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertButton: fn( self: *const IToolbar, nIndex: i32, lpButton: ?*MMCBUTTON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteButton: fn( self: *const IToolbar, nIndex: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetButtonState: fn( self: *const IToolbar, idCommand: i32, nState: MMC_BUTTON_STATE, pState: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetButtonState: fn( self: *const IToolbar, idCommand: i32, nState: MMC_BUTTON_STATE, bState: 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 IToolbar_AddBitmap(self: *const T, nImages: i32, hbmp: ?HBITMAP, cxSize: i32, cySize: i32, crMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).AddBitmap(@ptrCast(*const IToolbar, self), nImages, hbmp, cxSize, cySize, crMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IToolbar_AddButtons(self: *const T, nButtons: i32, lpButtons: ?*MMCBUTTON) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).AddButtons(@ptrCast(*const IToolbar, self), nButtons, lpButtons); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IToolbar_InsertButton(self: *const T, nIndex: i32, lpButton: ?*MMCBUTTON) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).InsertButton(@ptrCast(*const IToolbar, self), nIndex, lpButton); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IToolbar_DeleteButton(self: *const T, nIndex: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).DeleteButton(@ptrCast(*const IToolbar, self), nIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IToolbar_GetButtonState(self: *const T, idCommand: i32, nState: MMC_BUTTON_STATE, pState: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).GetButtonState(@ptrCast(*const IToolbar, self), idCommand, nState, pState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IToolbar_SetButtonState(self: *const T, idCommand: i32, nState: MMC_BUTTON_STATE, bState: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IToolbar.VTable, self.vtable).SetButtonState(@ptrCast(*const IToolbar, self), idCommand, nState, bState); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsoleVerb_Value = Guid.initString("e49f7a60-74af-11d0-a286-00c04fd8fe93"); pub const IID_IConsoleVerb = &IID_IConsoleVerb_Value; pub const IConsoleVerb = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetVerbState: fn( self: *const IConsoleVerb, eCmdID: MMC_CONSOLE_VERB, nState: MMC_BUTTON_STATE, pState: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVerbState: fn( self: *const IConsoleVerb, eCmdID: MMC_CONSOLE_VERB, nState: MMC_BUTTON_STATE, bState: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultVerb: fn( self: *const IConsoleVerb, eCmdID: MMC_CONSOLE_VERB, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultVerb: fn( self: *const IConsoleVerb, peCmdID: ?*MMC_CONSOLE_VERB, ) 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 IConsoleVerb_GetVerbState(self: *const T, eCmdID: MMC_CONSOLE_VERB, nState: MMC_BUTTON_STATE, pState: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleVerb.VTable, self.vtable).GetVerbState(@ptrCast(*const IConsoleVerb, self), eCmdID, nState, pState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleVerb_SetVerbState(self: *const T, eCmdID: MMC_CONSOLE_VERB, nState: MMC_BUTTON_STATE, bState: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleVerb.VTable, self.vtable).SetVerbState(@ptrCast(*const IConsoleVerb, self), eCmdID, nState, bState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleVerb_SetDefaultVerb(self: *const T, eCmdID: MMC_CONSOLE_VERB) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleVerb.VTable, self.vtable).SetDefaultVerb(@ptrCast(*const IConsoleVerb, self), eCmdID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsoleVerb_GetDefaultVerb(self: *const T, peCmdID: ?*MMC_CONSOLE_VERB) callconv(.Inline) HRESULT { return @ptrCast(*const IConsoleVerb.VTable, self.vtable).GetDefaultVerb(@ptrCast(*const IConsoleVerb, self), peCmdID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISnapinAbout_Value = Guid.initString("1245208c-a151-11d0-a7d7-00c04fd909dd"); pub const IID_ISnapinAbout = &IID_ISnapinAbout_Value; pub const ISnapinAbout = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSnapinDescription: fn( self: *const ISnapinAbout, lpDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProvider: fn( self: *const ISnapinAbout, lpName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSnapinVersion: fn( self: *const ISnapinAbout, lpVersion: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSnapinImage: fn( self: *const ISnapinAbout, hAppIcon: ?*?HICON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStaticFolderImage: fn( self: *const ISnapinAbout, hSmallImage: ?*?HBITMAP, hSmallImageOpen: ?*?HBITMAP, hLargeImage: ?*?HBITMAP, cMask: ?*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 ISnapinAbout_GetSnapinDescription(self: *const T, lpDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinAbout.VTable, self.vtable).GetSnapinDescription(@ptrCast(*const ISnapinAbout, self), lpDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinAbout_GetProvider(self: *const T, lpName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinAbout.VTable, self.vtable).GetProvider(@ptrCast(*const ISnapinAbout, self), lpName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinAbout_GetSnapinVersion(self: *const T, lpVersion: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinAbout.VTable, self.vtable).GetSnapinVersion(@ptrCast(*const ISnapinAbout, self), lpVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinAbout_GetSnapinImage(self: *const T, hAppIcon: ?*?HICON) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinAbout.VTable, self.vtable).GetSnapinImage(@ptrCast(*const ISnapinAbout, self), hAppIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinAbout_GetStaticFolderImage(self: *const T, hSmallImage: ?*?HBITMAP, hSmallImageOpen: ?*?HBITMAP, hLargeImage: ?*?HBITMAP, cMask: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinAbout.VTable, self.vtable).GetStaticFolderImage(@ptrCast(*const ISnapinAbout, self), hSmallImage, hSmallImageOpen, hLargeImage, cMask); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IMenuButton_Value = Guid.initString("951ed750-d080-11d0-b197-000000000000"); pub const IID_IMenuButton = &IID_IMenuButton_Value; pub const IMenuButton = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddButton: fn( self: *const IMenuButton, idCommand: i32, lpButtonText: ?PWSTR, lpTooltipText: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetButton: fn( self: *const IMenuButton, idCommand: i32, lpButtonText: ?PWSTR, lpTooltipText: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetButtonState: fn( self: *const IMenuButton, idCommand: i32, nState: MMC_BUTTON_STATE, bState: 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 IMenuButton_AddButton(self: *const T, idCommand: i32, lpButtonText: ?PWSTR, lpTooltipText: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IMenuButton.VTable, self.vtable).AddButton(@ptrCast(*const IMenuButton, self), idCommand, lpButtonText, lpTooltipText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMenuButton_SetButton(self: *const T, idCommand: i32, lpButtonText: ?PWSTR, lpTooltipText: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IMenuButton.VTable, self.vtable).SetButton(@ptrCast(*const IMenuButton, self), idCommand, lpButtonText, lpTooltipText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMenuButton_SetButtonState(self: *const T, idCommand: i32, nState: MMC_BUTTON_STATE, bState: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IMenuButton.VTable, self.vtable).SetButtonState(@ptrCast(*const IMenuButton, self), idCommand, nState, bState); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISnapinHelp_Value = Guid.initString("a6b15ace-df59-11d0-a7dd-00c04fd909dd"); pub const IID_ISnapinHelp = &IID_ISnapinHelp_Value; pub const ISnapinHelp = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetHelpTopic: fn( self: *const ISnapinHelp, lpCompiledHelpFile: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinHelp_GetHelpTopic(self: *const T, lpCompiledHelpFile: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinHelp.VTable, self.vtable).GetHelpTopic(@ptrCast(*const ISnapinHelp, self), lpCompiledHelpFile); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendPropertySheet2_Value = Guid.initString("b7a87232-4a51-11d1-a7ea-00c04fd909dd"); pub const IID_IExtendPropertySheet2 = &IID_IExtendPropertySheet2_Value; pub const IExtendPropertySheet2 = extern struct { pub const VTable = extern struct { base: IExtendPropertySheet.VTable, GetWatermarks: fn( self: *const IExtendPropertySheet2, lpIDataObject: ?*IDataObject, lphWatermark: ?*?HBITMAP, lphHeader: ?*?HBITMAP, lphPalette: ?*?HPALETTE, bStretch: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IExtendPropertySheet.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendPropertySheet2_GetWatermarks(self: *const T, lpIDataObject: ?*IDataObject, lphWatermark: ?*?HBITMAP, lphHeader: ?*?HBITMAP, lphPalette: ?*?HPALETTE, bStretch: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendPropertySheet2.VTable, self.vtable).GetWatermarks(@ptrCast(*const IExtendPropertySheet2, self), lpIDataObject, lphWatermark, lphHeader, lphPalette, bStretch); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IHeaderCtrl2_Value = Guid.initString("9757abb8-1b32-11d1-a7ce-00c04fd8d565"); pub const IID_IHeaderCtrl2 = &IID_IHeaderCtrl2_Value; pub const IHeaderCtrl2 = extern struct { pub const VTable = extern struct { base: IHeaderCtrl.VTable, SetChangeTimeOut: fn( self: *const IHeaderCtrl2, uTimeout: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumnFilter: fn( self: *const IHeaderCtrl2, nColumn: u32, dwType: u32, pFilterData: ?*MMC_FILTERDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnFilter: fn( self: *const IHeaderCtrl2, nColumn: u32, pdwType: ?*u32, pFilterData: ?*MMC_FILTERDATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IHeaderCtrl.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl2_SetChangeTimeOut(self: *const T, uTimeout: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl2.VTable, self.vtable).SetChangeTimeOut(@ptrCast(*const IHeaderCtrl2, self), uTimeout); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl2_SetColumnFilter(self: *const T, nColumn: u32, dwType: u32, pFilterData: ?*MMC_FILTERDATA) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl2.VTable, self.vtable).SetColumnFilter(@ptrCast(*const IHeaderCtrl2, self), nColumn, dwType, pFilterData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IHeaderCtrl2_GetColumnFilter(self: *const T, nColumn: u32, pdwType: ?*u32, pFilterData: ?*MMC_FILTERDATA) callconv(.Inline) HRESULT { return @ptrCast(*const IHeaderCtrl2.VTable, self.vtable).GetColumnFilter(@ptrCast(*const IHeaderCtrl2, self), nColumn, pdwType, pFilterData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ISnapinHelp2_Value = Guid.initString("4861a010-20f9-11d2-a510-00c04fb6dd2c"); pub const IID_ISnapinHelp2 = &IID_ISnapinHelp2_Value; pub const ISnapinHelp2 = extern struct { pub const VTable = extern struct { base: ISnapinHelp.VTable, GetLinkedTopics: fn( self: *const ISnapinHelp2, lpCompiledHelpFiles: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ISnapinHelp.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISnapinHelp2_GetLinkedTopics(self: *const T, lpCompiledHelpFiles: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ISnapinHelp2.VTable, self.vtable).GetLinkedTopics(@ptrCast(*const ISnapinHelp2, self), lpCompiledHelpFiles); } };} pub usingnamespace MethodMixin(@This()); }; pub const MMC_TASK_DISPLAY_TYPE = enum(i32) { UNINITIALIZED = 0, TYPE_SYMBOL = 1, TYPE_VANILLA_GIF = 2, TYPE_CHOCOLATE_GIF = 3, TYPE_BITMAP = 4, }; pub const MMC_TASK_DISPLAY_UNINITIALIZED = MMC_TASK_DISPLAY_TYPE.UNINITIALIZED; pub const MMC_TASK_DISPLAY_TYPE_SYMBOL = MMC_TASK_DISPLAY_TYPE.TYPE_SYMBOL; pub const MMC_TASK_DISPLAY_TYPE_VANILLA_GIF = MMC_TASK_DISPLAY_TYPE.TYPE_VANILLA_GIF; pub const MMC_TASK_DISPLAY_TYPE_CHOCOLATE_GIF = MMC_TASK_DISPLAY_TYPE.TYPE_CHOCOLATE_GIF; pub const MMC_TASK_DISPLAY_TYPE_BITMAP = MMC_TASK_DISPLAY_TYPE.TYPE_BITMAP; pub const MMC_TASK_DISPLAY_SYMBOL = extern struct { szFontFamilyName: ?PWSTR, szURLtoEOT: ?PWSTR, szSymbolString: ?PWSTR, }; pub const MMC_TASK_DISPLAY_BITMAP = extern struct { szMouseOverBitmap: ?PWSTR, szMouseOffBitmap: ?PWSTR, }; pub const MMC_TASK_DISPLAY_OBJECT = extern struct { eDisplayType: MMC_TASK_DISPLAY_TYPE, Anonymous: extern union { uBitmap: MMC_TASK_DISPLAY_BITMAP, uSymbol: MMC_TASK_DISPLAY_SYMBOL, }, }; pub const MMC_ACTION_TYPE = enum(i32) { UNINITIALIZED = -1, ID = 0, LINK = 1, SCRIPT = 2, }; pub const MMC_ACTION_UNINITIALIZED = MMC_ACTION_TYPE.UNINITIALIZED; pub const MMC_ACTION_ID = MMC_ACTION_TYPE.ID; pub const MMC_ACTION_LINK = MMC_ACTION_TYPE.LINK; pub const MMC_ACTION_SCRIPT = MMC_ACTION_TYPE.SCRIPT; pub const MMC_TASK = extern struct { sDisplayObject: MMC_TASK_DISPLAY_OBJECT, szText: ?PWSTR, szHelpString: ?PWSTR, eActionType: MMC_ACTION_TYPE, Anonymous: extern union { nCommandID: isize, szActionURL: ?PWSTR, szScript: ?PWSTR, }, }; pub const MMC_LISTPAD_INFO = extern struct { szTitle: ?PWSTR, szButtonText: ?PWSTR, nCommandID: isize, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IEnumTASK_Value = Guid.initString("338698b1-5a02-11d1-9fec-00600832db4a"); pub const IID_IEnumTASK = &IID_IEnumTASK_Value; pub const IEnumTASK = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumTASK, celt: u32, rgelt: [*]MMC_TASK, pceltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTASK, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTASK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumTASK, ppenum: ?*?*IEnumTASK, ) 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 IEnumTASK_Next(self: *const T, celt: u32, rgelt: [*]MMC_TASK, pceltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTASK.VTable, self.vtable).Next(@ptrCast(*const IEnumTASK, self), celt, rgelt, pceltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTASK_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTASK.VTable, self.vtable).Skip(@ptrCast(*const IEnumTASK, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTASK_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTASK.VTable, self.vtable).Reset(@ptrCast(*const IEnumTASK, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTASK_Clone(self: *const T, ppenum: ?*?*IEnumTASK) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTASK.VTable, self.vtable).Clone(@ptrCast(*const IEnumTASK, self), ppenum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendTaskPad_Value = Guid.initString("8dee6511-554d-11d1-9fea-00600832db4a"); pub const IID_IExtendTaskPad = &IID_IExtendTaskPad_Value; pub const IExtendTaskPad = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, TaskNotify: fn( self: *const IExtendTaskPad, pdo: ?*IDataObject, arg: ?*VARIANT, param2: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumTasks: fn( self: *const IExtendTaskPad, pdo: ?*IDataObject, szTaskGroup: ?PWSTR, ppEnumTASK: ?*?*IEnumTASK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTitle: fn( self: *const IExtendTaskPad, pszGroup: ?PWSTR, pszTitle: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescriptiveText: fn( self: *const IExtendTaskPad, pszGroup: ?PWSTR, pszDescriptiveText: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBackground: fn( self: *const IExtendTaskPad, pszGroup: ?PWSTR, pTDO: ?*MMC_TASK_DISPLAY_OBJECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetListPadInfo: fn( self: *const IExtendTaskPad, pszGroup: ?PWSTR, lpListPadInfo: ?*MMC_LISTPAD_INFO, ) 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 IExtendTaskPad_TaskNotify(self: *const T, pdo: ?*IDataObject, arg: ?*VARIANT, param2: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).TaskNotify(@ptrCast(*const IExtendTaskPad, self), pdo, arg, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendTaskPad_EnumTasks(self: *const T, pdo: ?*IDataObject, szTaskGroup: ?PWSTR, ppEnumTASK: ?*?*IEnumTASK) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).EnumTasks(@ptrCast(*const IExtendTaskPad, self), pdo, szTaskGroup, ppEnumTASK); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendTaskPad_GetTitle(self: *const T, pszGroup: ?PWSTR, pszTitle: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).GetTitle(@ptrCast(*const IExtendTaskPad, self), pszGroup, pszTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendTaskPad_GetDescriptiveText(self: *const T, pszGroup: ?PWSTR, pszDescriptiveText: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).GetDescriptiveText(@ptrCast(*const IExtendTaskPad, self), pszGroup, pszDescriptiveText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendTaskPad_GetBackground(self: *const T, pszGroup: ?PWSTR, pTDO: ?*MMC_TASK_DISPLAY_OBJECT) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).GetBackground(@ptrCast(*const IExtendTaskPad, self), pszGroup, pTDO); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IExtendTaskPad_GetListPadInfo(self: *const T, pszGroup: ?PWSTR, lpListPadInfo: ?*MMC_LISTPAD_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendTaskPad.VTable, self.vtable).GetListPadInfo(@ptrCast(*const IExtendTaskPad, self), pszGroup, lpListPadInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsole2_Value = Guid.initString("103d842a-aa63-11d1-a7e1-00c04fd8d565"); pub const IID_IConsole2 = &IID_IConsole2_Value; pub const IConsole2 = extern struct { pub const VTable = extern struct { base: IConsole.VTable, Expand: fn( self: *const IConsole2, hItem: isize, bExpand: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsTaskpadViewPreferred: fn( self: *const IConsole2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStatusText: fn( self: *const IConsole2, pszStatusText: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IConsole.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole2_Expand(self: *const T, hItem: isize, bExpand: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole2.VTable, self.vtable).Expand(@ptrCast(*const IConsole2, self), hItem, bExpand); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole2_IsTaskpadViewPreferred(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole2.VTable, self.vtable).IsTaskpadViewPreferred(@ptrCast(*const IConsole2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole2_SetStatusText(self: *const T, pszStatusText: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole2.VTable, self.vtable).SetStatusText(@ptrCast(*const IConsole2, self), pszStatusText); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDisplayHelp_Value = Guid.initString("cc593830-b926-11d1-8063-0000f875a9ce"); pub const IID_IDisplayHelp = &IID_IDisplayHelp_Value; pub const IDisplayHelp = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ShowTopic: fn( self: *const IDisplayHelp, pszHelpTopic: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDisplayHelp_ShowTopic(self: *const T, pszHelpTopic: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDisplayHelp.VTable, self.vtable).ShowTopic(@ptrCast(*const IDisplayHelp, self), pszHelpTopic); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IRequiredExtensions_Value = Guid.initString("72782d7a-a4a0-11d1-af0f-00c04fb6dd2c"); pub const IID_IRequiredExtensions = &IID_IRequiredExtensions_Value; pub const IRequiredExtensions = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnableAllExtensions: fn( self: *const IRequiredExtensions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFirstExtension: fn( self: *const IRequiredExtensions, pExtCLSID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextExtension: fn( self: *const IRequiredExtensions, pExtCLSID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRequiredExtensions_EnableAllExtensions(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IRequiredExtensions.VTable, self.vtable).EnableAllExtensions(@ptrCast(*const IRequiredExtensions, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRequiredExtensions_GetFirstExtension(self: *const T, pExtCLSID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IRequiredExtensions.VTable, self.vtable).GetFirstExtension(@ptrCast(*const IRequiredExtensions, self), pExtCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRequiredExtensions_GetNextExtension(self: *const T, pExtCLSID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IRequiredExtensions.VTable, self.vtable).GetNextExtension(@ptrCast(*const IRequiredExtensions, self), pExtCLSID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IStringTable_Value = Guid.initString("de40b7a4-0f65-11d2-8e25-00c04f8ecd78"); pub const IID_IStringTable = &IID_IStringTable_Value; pub const IStringTable = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddString: fn( self: *const IStringTable, pszAdd: ?[*:0]const u16, pStringID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const IStringTable, StringID: u32, cchBuffer: u32, lpBuffer: [*:0]u16, pcchOut: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStringLength: fn( self: *const IStringTable, StringID: u32, pcchString: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteString: fn( self: *const IStringTable, StringID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAllStrings: fn( self: *const IStringTable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindString: fn( self: *const IStringTable, pszFind: ?[*:0]const u16, pStringID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Enumerate: fn( self: *const IStringTable, ppEnum: ?*?*IEnumString, ) 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 IStringTable_AddString(self: *const T, pszAdd: ?[*:0]const u16, pStringID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).AddString(@ptrCast(*const IStringTable, self), pszAdd, pStringID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_GetString(self: *const T, StringID: u32, cchBuffer: u32, lpBuffer: [*:0]u16, pcchOut: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).GetString(@ptrCast(*const IStringTable, self), StringID, cchBuffer, lpBuffer, pcchOut); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_GetStringLength(self: *const T, StringID: u32, pcchString: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).GetStringLength(@ptrCast(*const IStringTable, self), StringID, pcchString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_DeleteString(self: *const T, StringID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).DeleteString(@ptrCast(*const IStringTable, self), StringID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_DeleteAllStrings(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).DeleteAllStrings(@ptrCast(*const IStringTable, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_FindString(self: *const T, pszFind: ?[*:0]const u16, pStringID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).FindString(@ptrCast(*const IStringTable, self), pszFind, pStringID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStringTable_Enumerate(self: *const T, ppEnum: ?*?*IEnumString) callconv(.Inline) HRESULT { return @ptrCast(*const IStringTable.VTable, self.vtable).Enumerate(@ptrCast(*const IStringTable, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; pub const MMC_COLUMN_DATA = extern struct { nColIndex: i32, dwFlags: u32, nWidth: i32, ulReserved: usize, }; pub const MMC_COLUMN_SET_DATA = extern struct { cbSize: i32, nNumCols: i32, pColData: ?*MMC_COLUMN_DATA, }; pub const MMC_SORT_DATA = extern struct { nColIndex: i32, dwSortOptions: u32, ulReserved: usize, }; pub const MMC_SORT_SET_DATA = extern struct { cbSize: i32, nNumItems: i32, pSortData: ?*MMC_SORT_DATA, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IColumnData_Value = Guid.initString("547c1354-024d-11d3-a707-00c04f8ef4cb"); pub const IID_IColumnData = &IID_IColumnData_Value; pub const IColumnData = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetColumnConfigData: fn( self: *const IColumnData, pColID: ?*SColumnSetID, pColSetData: ?*MMC_COLUMN_SET_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnConfigData: fn( self: *const IColumnData, pColID: ?*SColumnSetID, ppColSetData: ?*?*MMC_COLUMN_SET_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumnSortData: fn( self: *const IColumnData, pColID: ?*SColumnSetID, pColSortData: ?*MMC_SORT_SET_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnSortData: fn( self: *const IColumnData, pColID: ?*SColumnSetID, ppColSortData: ?*?*MMC_SORT_SET_DATA, ) 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 IColumnData_SetColumnConfigData(self: *const T, pColID: ?*SColumnSetID, pColSetData: ?*MMC_COLUMN_SET_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IColumnData.VTable, self.vtable).SetColumnConfigData(@ptrCast(*const IColumnData, self), pColID, pColSetData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IColumnData_GetColumnConfigData(self: *const T, pColID: ?*SColumnSetID, ppColSetData: ?*?*MMC_COLUMN_SET_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IColumnData.VTable, self.vtable).GetColumnConfigData(@ptrCast(*const IColumnData, self), pColID, ppColSetData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IColumnData_SetColumnSortData(self: *const T, pColID: ?*SColumnSetID, pColSortData: ?*MMC_SORT_SET_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IColumnData.VTable, self.vtable).SetColumnSortData(@ptrCast(*const IColumnData, self), pColID, pColSortData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IColumnData_GetColumnSortData(self: *const T, pColID: ?*SColumnSetID, ppColSortData: ?*?*MMC_SORT_SET_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IColumnData.VTable, self.vtable).GetColumnSortData(@ptrCast(*const IColumnData, self), pColID, ppColSortData); } };} pub usingnamespace MethodMixin(@This()); }; pub const IconIdentifier = enum(i32) { None = 0, Error = 32513, Question = 32514, Warning = 32515, Information = 32516, // First = 32513, this enum value conflicts with Error // Last = 32516, this enum value conflicts with Information }; pub const Icon_None = IconIdentifier.None; pub const Icon_Error = IconIdentifier.Error; pub const Icon_Question = IconIdentifier.Question; pub const Icon_Warning = IconIdentifier.Warning; pub const Icon_Information = IconIdentifier.Information; pub const Icon_First = IconIdentifier.Error; pub const Icon_Last = IconIdentifier.Information; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IMessageView_Value = Guid.initString("80f94174-fccc-11d2-b991-00c04f8ecd78"); pub const IID_IMessageView = &IID_IMessageView_Value; pub const IMessageView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetTitleText: fn( self: *const IMessageView, pszTitleText: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBodyText: fn( self: *const IMessageView, pszBodyText: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIcon: fn( self: *const IMessageView, id: IconIdentifier, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IMessageView, ) 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 IMessageView_SetTitleText(self: *const T, pszTitleText: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IMessageView.VTable, self.vtable).SetTitleText(@ptrCast(*const IMessageView, self), pszTitleText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessageView_SetBodyText(self: *const T, pszBodyText: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IMessageView.VTable, self.vtable).SetBodyText(@ptrCast(*const IMessageView, self), pszBodyText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessageView_SetIcon(self: *const T, id: IconIdentifier) callconv(.Inline) HRESULT { return @ptrCast(*const IMessageView.VTable, self.vtable).SetIcon(@ptrCast(*const IMessageView, self), id); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IMessageView_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IMessageView.VTable, self.vtable).Clear(@ptrCast(*const IMessageView, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const RDITEMHDR = extern struct { dwFlags: u32, cookie: isize, lpReserved: LPARAM, }; pub const RDCOMPARE = extern struct { cbSize: u32, dwFlags: u32, nColumn: i32, lUserParam: LPARAM, prdch1: ?*RDITEMHDR, prdch2: ?*RDITEMHDR, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IResultDataCompareEx_Value = Guid.initString("96933476-0251-11d3-aeb0-00c04f8ecd78"); pub const IID_IResultDataCompareEx = &IID_IResultDataCompareEx_Value; pub const IResultDataCompareEx = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compare: fn( self: *const IResultDataCompareEx, prdc: ?*RDCOMPARE, pnResult: ?*i32, ) 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 IResultDataCompareEx_Compare(self: *const T, prdc: ?*RDCOMPARE, pnResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IResultDataCompareEx.VTable, self.vtable).Compare(@ptrCast(*const IResultDataCompareEx, self), prdc, pnResult); } };} pub usingnamespace MethodMixin(@This()); }; pub const MMC_VIEW_TYPE = enum(i32) { LIST = 0, HTML = 1, OCX = 2, }; pub const MMC_VIEW_TYPE_LIST = MMC_VIEW_TYPE.LIST; pub const MMC_VIEW_TYPE_HTML = MMC_VIEW_TYPE.HTML; pub const MMC_VIEW_TYPE_OCX = MMC_VIEW_TYPE.OCX; pub const RESULT_VIEW_TYPE_INFO = extern struct { pstrPersistableViewDescription: ?PWSTR, eViewType: MMC_VIEW_TYPE, dwMiscOptions: u32, Anonymous: extern union { dwListOptions: u32, Anonymous1: extern struct { dwHTMLOptions: u32, pstrURL: ?PWSTR, }, Anonymous2: extern struct { dwOCXOptions: u32, pUnkControl: ?*IUnknown, }, }, }; pub const CONTEXTMENUITEM2 = extern struct { strName: ?PWSTR, strStatusBarText: ?PWSTR, lCommandID: i32, lInsertionPointID: i32, fFlags: i32, fSpecialFlags: i32, strLanguageIndependentName: ?PWSTR, }; pub const MMC_EXT_VIEW_DATA = extern struct { viewID: Guid, pszURL: ?[*:0]const u16, pszViewTitle: ?[*:0]const u16, pszTooltipText: ?[*:0]const u16, bReplacesDefaultView: BOOL, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IComponentData2_Value = Guid.initString("cca0f2d2-82de-41b5-bf47-3b2076273d5c"); pub const IID_IComponentData2 = &IID_IComponentData2_Value; pub const IComponentData2 = extern struct { pub const VTable = extern struct { base: IComponentData.VTable, QueryDispatch: fn( self: *const IComponentData2, cookie: isize, type: DATA_OBJECT_TYPES, ppDispatch: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IComponentData.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponentData2_QueryDispatch(self: *const T, cookie: isize, type_: DATA_OBJECT_TYPES, ppDispatch: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IComponentData2.VTable, self.vtable).QueryDispatch(@ptrCast(*const IComponentData2, self), cookie, type_, ppDispatch); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IComponent2_Value = Guid.initString("79a2d615-4a10-4ed4-8c65-8633f9335095"); pub const IID_IComponent2 = &IID_IComponent2_Value; pub const IComponent2 = extern struct { pub const VTable = extern struct { base: IComponent.VTable, QueryDispatch: fn( self: *const IComponent2, cookie: isize, type: DATA_OBJECT_TYPES, ppDispatch: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResultViewType2: fn( self: *const IComponent2, cookie: isize, pResultViewType: ?*RESULT_VIEW_TYPE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreResultView: fn( self: *const IComponent2, cookie: isize, pResultViewType: ?*RESULT_VIEW_TYPE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IComponent.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent2_QueryDispatch(self: *const T, cookie: isize, type_: DATA_OBJECT_TYPES, ppDispatch: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent2.VTable, self.vtable).QueryDispatch(@ptrCast(*const IComponent2, self), cookie, type_, ppDispatch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent2_GetResultViewType2(self: *const T, cookie: isize, pResultViewType: ?*RESULT_VIEW_TYPE_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent2.VTable, self.vtable).GetResultViewType2(@ptrCast(*const IComponent2, self), cookie, pResultViewType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IComponent2_RestoreResultView(self: *const T, cookie: isize, pResultViewType: ?*RESULT_VIEW_TYPE_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IComponent2.VTable, self.vtable).RestoreResultView(@ptrCast(*const IComponent2, self), cookie, pResultViewType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IContextMenuCallback2_Value = Guid.initString("e178bc0e-2ed0-4b5e-8097-42c9087e8b33"); pub const IID_IContextMenuCallback2 = &IID_IContextMenuCallback2_Value; pub const IContextMenuCallback2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddItem: fn( self: *const IContextMenuCallback2, pItem: ?*CONTEXTMENUITEM2, ) 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 IContextMenuCallback2_AddItem(self: *const T, pItem: ?*CONTEXTMENUITEM2) callconv(.Inline) HRESULT { return @ptrCast(*const IContextMenuCallback2.VTable, self.vtable).AddItem(@ptrCast(*const IContextMenuCallback2, self), pItem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IMMCVersionInfo_Value = Guid.initString("a8d2c5fe-cdcb-4b9d-bde5-a27343ff54bc"); pub const IID_IMMCVersionInfo = &IID_IMMCVersionInfo_Value; pub const IMMCVersionInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMMCVersion: fn( self: *const IMMCVersionInfo, pVersionMajor: ?*i32, pVersionMinor: ?*i32, ) 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 IMMCVersionInfo_GetMMCVersion(self: *const T, pVersionMajor: ?*i32, pVersionMinor: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IMMCVersionInfo.VTable, self.vtable).GetMMCVersion(@ptrCast(*const IMMCVersionInfo, self), pVersionMajor, pVersionMinor); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IExtendView_Value = Guid.initString("89995cee-d2ed-4c0e-ae5e-df7e76f3fa53"); pub const IID_IExtendView = &IID_IExtendView_Value; pub const IExtendView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetViews: fn( self: *const IExtendView, pDataObject: ?*IDataObject, pViewExtensionCallback: ?*IViewExtensionCallback, ) 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 IExtendView_GetViews(self: *const T, pDataObject: ?*IDataObject, pViewExtensionCallback: ?*IViewExtensionCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IExtendView.VTable, self.vtable).GetViews(@ptrCast(*const IExtendView, self), pDataObject, pViewExtensionCallback); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IViewExtensionCallback_Value = Guid.initString("34dd928a-7599-41e5-9f5e-d6bc3062c2da"); pub const IID_IViewExtensionCallback = &IID_IViewExtensionCallback_Value; pub const IViewExtensionCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddView: fn( self: *const IViewExtensionCallback, pExtViewData: ?*MMC_EXT_VIEW_DATA, ) 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 IViewExtensionCallback_AddView(self: *const T, pExtViewData: ?*MMC_EXT_VIEW_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IViewExtensionCallback.VTable, self.vtable).AddView(@ptrCast(*const IViewExtensionCallback, self), pExtViewData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsolePower_Value = Guid.initString("1cfbdd0e-62ca-49ce-a3af-dbb2de61b068"); pub const IID_IConsolePower = &IID_IConsolePower_Value; pub const IConsolePower = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetExecutionState: fn( self: *const IConsolePower, dwAdd: u32, dwRemove: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResetIdleTimer: fn( self: *const IConsolePower, dwFlags: 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 IConsolePower_SetExecutionState(self: *const T, dwAdd: u32, dwRemove: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConsolePower.VTable, self.vtable).SetExecutionState(@ptrCast(*const IConsolePower, self), dwAdd, dwRemove); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsolePower_ResetIdleTimer(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IConsolePower.VTable, self.vtable).ResetIdleTimer(@ptrCast(*const IConsolePower, self), dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsolePowerSink_Value = Guid.initString("3333759f-fe4f-4975-b143-fec0a5dd6d65"); pub const IID_IConsolePowerSink = &IID_IConsolePowerSink_Value; pub const IConsolePowerSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnPowerBroadcast: fn( self: *const IConsolePowerSink, nEvent: u32, lParam: LPARAM, plReturn: ?*LRESULT, ) 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 IConsolePowerSink_OnPowerBroadcast(self: *const T, nEvent: u32, lParam: LPARAM, plReturn: ?*LRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IConsolePowerSink.VTable, self.vtable).OnPowerBroadcast(@ptrCast(*const IConsolePowerSink, self), nEvent, lParam, plReturn); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_INodeProperties_Value = Guid.initString("15bc4d24-a522-4406-aa55-0749537a6865"); pub const IID_INodeProperties = &IID_INodeProperties_Value; pub const INodeProperties = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetProperty: fn( self: *const INodeProperties, pDataObject: ?*IDataObject, szPropertyName: ?BSTR, pbstrProperty: ?*?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INodeProperties_GetProperty(self: *const T, pDataObject: ?*IDataObject, szPropertyName: ?BSTR, pbstrProperty: ?*?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const INodeProperties.VTable, self.vtable).GetProperty(@ptrCast(*const INodeProperties, self), pDataObject, szPropertyName, pbstrProperty); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IConsole3_Value = Guid.initString("4f85efdb-d0e1-498c-8d4a-d010dfdd404f"); pub const IID_IConsole3 = &IID_IConsole3_Value; pub const IConsole3 = extern struct { pub const VTable = extern struct { base: IConsole2.VTable, RenameScopeItem: fn( self: *const IConsole3, hScopeItem: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IConsole2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IConsole3_RenameScopeItem(self: *const T, hScopeItem: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IConsole3.VTable, self.vtable).RenameScopeItem(@ptrCast(*const IConsole3, self), hScopeItem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IResultData2_Value = Guid.initString("0f36e0eb-a7f1-4a81-be5a-9247f7de4b1b"); pub const IID_IResultData2 = &IID_IResultData2_Value; pub const IResultData2 = extern struct { pub const VTable = extern struct { base: IResultData.VTable, RenameResultItem: fn( self: *const IResultData2, itemID: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IResultData.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IResultData2_RenameResultItem(self: *const T, itemID: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IResultData2.VTable, self.vtable).RenameResultItem(@ptrCast(*const IResultData2, self), itemID); } };} 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 (17) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HPROPSHEETPAGE = @import("../ui/controls.zig").HPROPSHEETPAGE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDataObject = @import("../system/com.zig").IDataObject; const IDispatch = @import("../system/com.zig").IDispatch; const IEnumString = @import("../system/com.zig").IEnumString; const IUnknown = @import("../system/com.zig").IUnknown; const LPARAM = @import("../foundation.zig").LPARAM; const LRESULT = @import("../foundation.zig").LRESULT; const PWSTR = @import("../foundation.zig").PWSTR; 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/mmc.zig
const std = @import("std"); const hzzp = @import("hzzp"); const ssl = @import("zig-bearssl"); const bot_agent = "zigbot9001/0.0.1"; pub const SslTunnel = struct { allocator: *std.mem.Allocator, trust_anchor: ssl.TrustAnchorCollection, x509: ssl.x509.Minimal, client: ssl.Client, tcp_conn: std.fs.File, tcp_reader: std.fs.File.Reader, tcp_writer: std.fs.File.Writer, conn: Stream, pub const Stream = ssl.Stream(*std.fs.File.Reader, *std.fs.File.Writer); pub fn init(args: struct { allocator: *std.mem.Allocator, pem: []const u8, host: [:0]const u8, port: u16 = 443, }) !*SslTunnel { const result = try args.allocator.create(SslTunnel); errdefer args.allocator.destroy(result); result.allocator = args.allocator; result.trust_anchor = ssl.TrustAnchorCollection.init(args.allocator); errdefer result.trust_anchor.deinit(); try result.trust_anchor.appendFromPEM(args.pem); result.x509 = ssl.x509.Minimal.init(result.trust_anchor); result.client = ssl.Client.init(result.x509.getEngine()); result.client.relocate(); try result.client.reset(args.host, false); result.tcp_conn = try std.net.tcpConnectToHost(args.allocator, args.host, args.port); errdefer result.tcp_conn.close(); result.tcp_reader = result.tcp_conn.reader(); result.tcp_writer = result.tcp_conn.writer(); result.conn = ssl.initStream(result.client.getEngine(), &result.tcp_reader, &result.tcp_writer); return result; } pub fn deinit(self: *SslTunnel) void { self.tcp_conn.close(); self.trust_anchor.deinit(); self.allocator.destroy(self); } }; pub const Https = struct { allocator: *std.mem.Allocator, ssl_tunnel: *SslTunnel, buffer: []u8, client: HzzpClient, const HzzpClient = hzzp.base.Client.Client(SslTunnel.Stream.DstInStream, SslTunnel.Stream.DstOutStream); pub fn init(args: struct { allocator: *std.mem.Allocator, pem: []const u8, host: [:0]const u8, port: u16 = 443, method: []const u8, path: []const u8, }) !Https { var ssl_tunnel = try SslTunnel.init(.{ .allocator = args.allocator, .pem = args.pem, .host = args.host, .port = args.port, }); errdefer ssl_tunnel.deinit(); const buffer = try args.allocator.alloc(u8, 0x1000); errdefer args.allocator.free(buffer); var client = hzzp.base.Client.create(buffer, ssl_tunnel.conn.inStream(), ssl_tunnel.conn.outStream()); try client.writeHead(args.method, args.path); try client.writeHeaderValue("Host", args.host); try client.writeHeaderValue("User-Agent", bot_agent); return Https{ .allocator = args.allocator, .ssl_tunnel = ssl_tunnel, .buffer = buffer, .client = client, }; } pub fn deinit(self: *Https) void { self.ssl_tunnel.deinit(); self.allocator.free(self.buffer); self.* = undefined; } // TODO: fix this name pub fn printSend(self: *Https, comptime fmt: []const u8, args: anytype) !void { var buf: [0x10]u8 = undefined; try self.client.writeHeaderValue( "Content-Length", try std.fmt.bufPrint(&buf, "{}", .{std.fmt.count(fmt, args)}), ); try self.client.writeHeadComplete(); try self.client.writer.print(fmt, args); try self.ssl_tunnel.conn.flush(); } pub fn expectSuccessStatus(self: *Https) !u16 { if (try self.client.readEvent()) |event| { if (event != .status) { return error.MissingStatus; } switch (event.status.code) { 200...299 => return event.status.code, 100...199 => return error.MiscInformation, 300...399 => return error.MiscRedirect, 400 => return error.InvalidRequest, 401 => return error.Unauthorized, 402 => return error.PaymentRequired, 403 => return error.Forbidden, 404 => return error.NotFound, 429 => return error.TooManyRequests, 405...428, 430...499 => return error.MiscClientError, 500 => return error.InternalServerError, 501...599 => return error.MiscServerError, else => unreachable, } } else { return error.NoResponse; } } pub fn completeHeaders(self: *Https) !void { while (try self.client.readEvent()) |event| { if (event == .head_complete) { return; } } } pub fn body(self: *Https) ChunkyReader(HzzpClient) { return .{ .client = self.client }; } }; pub fn ChunkyReader(comptime Chunker: type) type { return struct { const Self = @This(); const ReadEventInfo = blk: { const ReturnType = @typeInfo(@TypeOf(Chunker.readEvent)).Fn.return_type.?; break :blk @typeInfo(ReturnType).ErrorUnion; }; const Reader = std.io.Reader(*Self, ReadEventInfo.error_set, readFn); client: Chunker, complete: bool = false, event: ReadEventInfo.payload = null, loc: usize = undefined, fn readFn(self: *Self, buffer: []u8) ReadEventInfo.error_set!usize { if (self.complete) return 0; if (self.event) |event| { const remaining = event.chunk.data[self.loc..]; if (buffer.len < remaining.len) { std.mem.copy(u8, buffer, remaining[0..buffer.len]); self.loc += buffer.len; return buffer.len; } else { std.mem.copy(u8, buffer, remaining); if (event.chunk.final) { self.complete = true; } self.event = null; return remaining.len; } } else { const event = (try self.client.readEvent()) orelse { self.complete = true; return 0; }; if (event != .chunk) { self.complete = true; return 0; } self.event = event; self.loc = 0; return self.readFn(buffer); } } pub fn reader(self: *Self) Reader { return .{ .context = self }; } }; }
src/request.zig
const std = @import("std"); const print = std.debug.print; const c = @import("./postgres.zig").c; const helpers = @import("./helpers.zig"); const Parser = @import("./postgres.zig").Parser; const ColumnType = @import("./definitions.zig").ColumnType; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Definitions = @import("./definitions.zig"); const Error = Definitions.Error; pub const FieldInfo = struct { name: []const u8, type: type, }; pub const Result = struct { res: ?*c.PGresult, columns: usize, rows: usize, active_row: usize = 0, pub fn new(result: *c.PGresult) Result { const rows = @intCast(usize, c.PQntuples(result)); const columns = @intCast(usize, c.PQnfields(result)); if (rows == 0) { c.PQclear(result); return Result{ .res = null, .columns = columns, .rows = rows, }; } return Result{ .res = result, .columns = columns, .rows = rows, }; } pub fn isEmpty(self: Result) bool { return self.rows < 1; } fn columnName(self: Result, column_number: usize) []const u8 { const value = c.PQfname(self.res.?, @intCast(c_int, column_number)); return @as([*c]const u8, value)[0..std.mem.len(value)]; } fn getType(self: Result, column_number: usize) ColumnType { var oid = @intCast(usize, c.PQftype(self.res.?, @intCast(c_int, column_number))); return std.meta.intToEnum(ColumnType, oid) catch return ColumnType.Unknown; } fn getValue(self: Result, row_number: usize, column_number: usize) []const u8 { const value = c.PQgetvalue(self.res.?, @intCast(c_int, row_number), @intCast(c_int, column_number)); return @as([*c]const u8, value)[0..std.mem.len(value)]; } //Parses and returns struct with values pub fn parse(self: *Result, comptime return_type: type, allocator: ?*Allocator) ?return_type { if (self.rows < 1) return null; if (self.active_row == self.rows) return null; const type_info = @typeInfo(return_type); if (type_info != .Struct) { @compileError("Need to use struct as parser type"); } const struct_fields = type_info.Struct.fields; var result: return_type = undefined; var col_id: usize = 0; while (col_id < self.columns) : (col_id += 1) { const column_name = self.columnName(col_id); const value: []const u8 = self.getValue(self.active_row, col_id); if (value.len == 0) break; inline for (struct_fields) |field| { if (std.mem.eql(u8, field.name, column_name)) { switch (field.field_type) { ?u8, ?u16, ?u32, => { @field(result, field.name) = std.fmt.parseUnsigned(@typeInfo(field.field_type).Optional.child, value, 10) catch unreachable; }, u8, u16, u32, usize => { @field(result, field.name) = std.fmt.parseUnsigned(field.field_type, value, 10) catch unreachable; }, ?i8, ?i16, ?i32, => { @field(result, field.name) = std.fmt.parseInt(@typeInfo(field.field_type).Optional.child, value, 10) catch unreachable; }, i8, i16, i32 => { @field(result, field.name) = std.fmt.parseInt(field.field_type, value, 10) catch unreachable; }, []const u8, ?[]const u8 => { @field(result, field.name) = value; }, else => { const is_extended = @hasDecl(return_type, "onLoad"); if (is_extended) @field(result, "onLoad")(FieldInfo{ .name = field.name, .type = field.field_type }, value, Parser.init(allocator.?)) catch unreachable; }, } } } } self.active_row = self.active_row + 1; if (self.active_row == self.rows) self.deinit(); return result; } pub fn deinit(self: Result) void { c.PQclear(self.res.?); } };
src/result.zig
const Self = @This(); const std = @import("std"); const lookup_table = [256]u32{ 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; crc: u32 = 0, total_size: usize = 0, fn sum_byte(self: *Self, byte: u8) void { self.crc = (self.crc << 8) ^ lookup_table[(self.crc >> 24) ^ byte]; } pub fn sum_bytes(self: *Self, bytes: []const u8) void { for (bytes) |byte| { self.sum_byte(byte); } self.total_size += bytes.len; } pub fn get_result(self: *Self) u32 { var n = self.total_size; while (n != 0) { self.sum_byte(@truncate(u8, n)); n >>= 8; } return ~self.crc; } pub fn check(data: []const u8) u32 { var cksum = Self{}; cksum.sum_bytes(data); return cksum.get_result(); } const test_sum: u32 = 2382472371; const test_string = "The quick brown fox jumps over the lazy dog\n"; test "Cksum.sum_data" { var cksum = Self{}; cksum.sum_bytes(test_string[0..14]); cksum.sum_bytes(test_string[14..]); try std.testing.expectEqual(cksum.get_result(), test_sum); } test "Cksum.check" { try std.testing.expectEqual(check(test_string), test_sum); }
libs/utils/Cksum.zig
const FarPtr = @import("../far_ptr.zig").FarPtr; // TODO: Enforce descriptor usage rules with the type system. // // See: http://www.delorie.com/djgpp/doc/dpmi/descriptor-rules.html pub const Segment = struct { selector: u16, pub const Register = enum { cs, ds, es, fs, gs, ss, }; pub const Type = enum { code, data, }; pub fn alloc() Segment { // TODO: Check carry flag for error. const selector = asm volatile ("int $0x31" : [_] "={ax}" (-> u16), : [func] "{ax}" (@as(u16, 0)), [_] "{cx}" (@as(u16, 1)), ); return Segment{ .selector = selector }; } pub fn fromRegister(r: Register) Segment { const selector = switch (r) { .cs => asm ("movw %%cs, %[selector]" : [selector] "=r" (-> u16), ), .ds => asm ("movw %%ds, %[selector]" : [selector] "=r" (-> u16), ), .es => asm ("movw %%es, %[selector]" : [selector] "=r" (-> u16), ), .fs => asm ("movw %%fs, %[selector]" : [selector] "=r" (-> u16), ), .gs => asm ("movw %%gs, %[selector]" : [selector] "=r" (-> u16), ), .ss => asm ("movw %%ss, %[selector]" : [selector] "=r" (-> u16), ), }; return .{ .selector = selector }; } pub fn farPtr(self: Segment) FarPtr { return .{ .segment = self.selector }; } pub fn getBaseAddress(self: Segment) usize { var addr_high: u16 = undefined; var addr_low: u16 = undefined; // TODO: Check carry flag for error. asm ("int $0x31" : [_] "={cx}" (addr_high), [_] "={dx}" (addr_low), : [func] "{ax}" (@as(u16, 6)), [_] "{bx}" (self.selector), ); return @as(usize, addr_high) << 16 | addr_low; } pub fn setAccessRights(self: Segment, seg_type: Segment.Type) void { // TODO: Represent rights with packed struct? // TODO: Is hardcoding the privilege level bad? const rights: u16 = switch (seg_type) { .code => 0xc0fb, // 32-bit, ring 3, big, code, non-conforming, readable .data => 0xc0f3, // 32-bit, ring 3, big, data, R/W, expand-up }; // TODO: Check carry flag for error. asm volatile ("int $0x31" : // No outputs : [func] "{ax}" (@as(u16, 9)), [_] "{bx}" (self.selector), [_] "{cx}" (rights), ); } pub fn setBaseAddress(self: Segment, addr: usize) void { // TODO: Check carry flag for error. asm volatile ("int $0x31" : // No outputs : [func] "{ax}" (@as(u16, 7)), [_] "{bx}" (self.selector), [_] "{cx}" (@truncate(u16, addr >> 16)), [_] "{dx}" (@truncate(u16, addr)), ); } pub fn setLimit(self: Segment, limit: usize) void { // TODO: Check carry flag for error. // TODO: Check that limit meets alignment requirements. asm volatile ("int $0x31" : // No outputs : [func] "{ax}" (@as(u16, 8)), [_] "{bx}" (self.selector), [_] "{cx}" (@truncate(u16, limit >> 16)), [_] "{dx}" (@truncate(u16, limit)), ); } pub fn read(self: Segment, buffer: []u8) void { return self.farPtr().read(buffer); } pub fn write(self: Segment, bytes: []const u8) void { return self.farPtr().write(bytes); } };
src/dos/dpmi/segment.zig
const std = @import("std"); const display = @import("zbox"); const options = @import("build_options"); const page_allocator = std.heap.page_allocator; const ArrayList = std.ArrayList; pub usingnamespace @import("log_handler.zig"); const bad_char = '%'; const ship_char = '^'; const bullet_char = '.'; const bb_width = 7; const bb_height = 3; const baddie_block_init = [bb_height][bb_width]u8{ .{ 1, 0, 1, 0, 1, 0, 1 }, .{ 0, 1, 0, 1, 0, 1, 0 }, .{ 1, 0, 1, 0, 1, 0, 1 }, }; var baddie_block = baddie_block_init; var bb_y: usize = 0; var bb_countdown: usize = 3; const Bullet = struct { active: bool = false, x: usize = 0, y: usize = 0, }; var bullets = [_]Bullet{.{}} ** 4; var score: usize = 0; const width: usize = 7; const mid_width: usize = 4; const height: usize = 24; const mid_height = 11; var ship_x: usize = 4; // center of the screen. var state: enum { start, playing, win, lose, } = .playing; pub fn main() !void { var alloc = std.heap.page_allocator; // initialize the display with stdin/out try display.init(alloc); defer display.deinit(); // ignore ctrl+C try display.ignoreSignalInput(); try display.cursorHide(); defer display.cursorShow() catch {}; var game_display = try display.Buffer.init(alloc, height, width); defer game_display.deinit(); var output = try display.Buffer.init(alloc, height, width); defer output.deinit(); while (try display.nextEvent()) |e| { const size = try display.size(); output.clear(); try output.resize(size.height, size.width); if (size.height < height or size.width < width) { const row = std.math.max(0, size.height / 2); var cursor = output.cursorAt(row, 0); try cursor.writer().writeAll("display too small; resize."); try display.push(output); continue; } switch (e) { .left => if (ship_x > 0) { ship_x -= 1; }, .right => if (ship_x < width - 1) { ship_x += 1; }, .other => |data| { const eql = std.mem.eql; if (eql(u8, " ", data)) { std.log.scoped(.invaders).debug("pyoo", .{}); for (bullets) |*bullet| if (!bullet.active) { bullet.active = true; bullet.y = height - 1; bullet.x = ship_x; break; }; } }, .escape => return, else => {}, } game_display.clear(); game_display.cellRef(height - 1, ship_x).char = ship_char; for (bullets) |*bullet| { if (bullet.active) { if (bullet.y > 0) bullet.y -= 1; if (bullet.y == 0) { bullet.active = false; if (score > 0) score -= 1; } } } if (bb_countdown == 0) { bb_countdown = 6; bb_y += 1; } else bb_countdown -= 1; var baddie_count: usize = 0; for (baddie_block) |*baddie_row, row_offset| for (baddie_row.*) |*baddie, col_num| { const row_num = row_offset + bb_y; if (row_num >= height) continue; if (baddie.* > 0) { for (bullets) |*bullet| { if (bullet.x == col_num and bullet.y <= row_num and bullet.active) { score += 3; baddie.* -= 1; bullet.active = false; bullet.y = 0; bullet.x = 0; } if (row_num == height - 1) { // baddie reached bottom if (score >= 5) { score -= 5; } else { score = 0; } } } game_display.cellRef(row_num, col_num).* = .{ .char = bad_char, .attribs = .{ .fg_magenta = true }, }; baddie_count += 1; } }; if ((baddie_count == 0) or (bb_y >= height)) { bb_y = 0; baddie_block = baddie_block_init; bullets = [_]Bullet{.{}} ** 4; // clear all the bullets } for (bullets) |bullet| { if (bullet.active) game_display.cellRef(bullet.y, bullet.x).* = .{ .char = bullet_char, .attribs = .{ .fg_yellow = true }, }; } var score_curs = game_display.cursorAt(0, 3); score_curs.attribs = .{ .underline = true }; try score_curs.writer().print("{:0>4}", .{score}); const game_row = if (size.height >= height + 2) size.height / 2 - mid_height else 0; const game_col = if (size.width >= height + 2) size.width / 2 - mid_width else 0; output.blit(game_display, @intCast(isize, game_row), @intCast(isize, game_col)); try display.push(output); } }
forks/zbox/examples/invaders.zig
const std = @import("std"); const ast = @import("ast.zig"); const intrinsics = @import("intrinsics.zig"); const mem = @import("gc.zig"); const linereader = @import("linereader.zig"); const SourceLocation = @import("sourcelocation.zig").SourceLocation; const Expr = ast.Expr; const ExprType = ast.ExprType; const ExprValue = ast.ExprValue; const Env = ast.Env; const ExprErrors = ast.ExprErrors; /// The expression reader and evaluator pub const Interpreter = struct { env: *Env, exit_code: ?u8 = null, gensym_seq: u64 = 0, verbose: bool = false, has_errors: bool = false, break_seen: bool = false, /// Set up the root environment by binding a core set of intrinsics. /// The rest of the standard Bio functions are loaded from std.lisp pub fn init() !Interpreter { mem.gc = try mem.GC.init(); SourceLocation.initStack(); var instance = Interpreter{ .env = try ast.makeEnv(null, "global") }; try instance.env.put("import", &intrinsics.expr_std_import); try instance.env.put("exit", &intrinsics.expr_std_exit); try instance.env.put("gc", &intrinsics.expr_std_run_gc); try instance.env.put("#f", &intrinsics.expr_atom_false); try instance.env.put("#t", &intrinsics.expr_atom_true); try instance.env.put("#?", &intrinsics.expr_atom_nil); try instance.env.put("#!", &intrinsics.expr_atom_nil); try instance.env.put("&break", &intrinsics.expr_atom_break); try instance.env.put("nil", &intrinsics.expr_atom_nil); try instance.env.put("math.pi", &intrinsics.expr_std_math_pi); try instance.env.put("math.e", &intrinsics.expr_std_math_e); try instance.env.put("math.floor", &intrinsics.expr_std_floor); try instance.env.put("math.round", &intrinsics.expr_std_round); try instance.env.put("math.min", &intrinsics.expr_std_min); try instance.env.put("math.max", &intrinsics.expr_std_max); try instance.env.put("math.pow", &intrinsics.expr_std_pow); try instance.env.put("time.now", &intrinsics.expr_std_time_now); try instance.env.put("number?", &intrinsics.expr_std_is_number); try instance.env.put("symbol?", &intrinsics.expr_std_is_symbol); try instance.env.put("list?", &intrinsics.expr_std_is_list); try instance.env.put("hashmap?", &intrinsics.expr_std_is_hashmap); try instance.env.put("error?", &intrinsics.expr_std_is_err); try instance.env.put("callable?", &intrinsics.expr_std_is_callable); try instance.env.put("verbose", &intrinsics.expr_std_verbose); try instance.env.put("assert", &intrinsics.expr_std_assert_true); try instance.env.put("gensym", &intrinsics.expr_std_gensym); try instance.env.put("print", &intrinsics.expr_std_print); try instance.env.put("string", &intrinsics.expr_std_string); try instance.env.put("as", &intrinsics.expr_std_as); try instance.env.put("len", &intrinsics.expr_std_len); try instance.env.put("env", &intrinsics.expr_std_env); try instance.env.put("self", &intrinsics.expr_std_self); try instance.env.put("quote", &intrinsics.expr_std_quote); try instance.env.put("quasiquote", &intrinsics.expr_std_quasi_quote); try instance.env.put("unquote", &intrinsics.expr_std_unquote); try instance.env.put("unquote-splicing", &intrinsics.expr_std_unquote_splicing); try instance.env.put("double-quote", &intrinsics.expr_std_double_quote); try instance.env.put("range", &intrinsics.expr_std_range); try instance.env.put("rotate-left!", &intrinsics.expr_std_rotate_left); try instance.env.put("item-at", &intrinsics.expr_std_item_at); try instance.env.put("item-set", &intrinsics.expr_std_item_set); try instance.env.put("item-remove!", &intrinsics.expr_std_item_remove); try instance.env.put("define", &intrinsics.expr_std_define); try instance.env.put("var", &intrinsics.expr_std_define); try instance.env.put("lambda", &intrinsics.expr_std_lambda); try instance.env.put("macro", &intrinsics.expr_std_macro); try instance.env.put("λ", &intrinsics.expr_std_lambda); try instance.env.put("apply", &intrinsics.expr_std_apply); try instance.env.put("list", &intrinsics.expr_std_list); try instance.env.put("iterate", &intrinsics.expr_std_iterate); try instance.env.put("hashmap.new", &intrinsics.expr_std_map_new); try instance.env.put("hashmap.put", &intrinsics.expr_std_map_put); try instance.env.put("hashmap.get", &intrinsics.expr_std_map_get); try instance.env.put("hashmap.remove", &intrinsics.expr_std_map_remove); try instance.env.put("hashmap.clear", &intrinsics.expr_std_map_clear); try instance.env.put("loop", &intrinsics.expr_std_loop); try instance.env.put("append", &intrinsics.expr_std_append); try instance.env.put("eval", &intrinsics.expr_std_eval); try instance.env.put("eval-string", &intrinsics.expr_std_eval_string); try instance.env.put("string.split", &intrinsics.expr_std_split); try instance.env.put("atom.split", &intrinsics.expr_std_split_atom); try instance.env.put("set!", &intrinsics.expr_std_set); try instance.env.put("unset!", &intrinsics.expr_std_unset); try instance.env.put("try", &intrinsics.expr_std_try); try instance.env.put("error", &intrinsics.expr_std_error); try instance.env.put("+", &intrinsics.expr_std_sum); try instance.env.put("-", &intrinsics.expr_std_sub); try instance.env.put("*", &intrinsics.expr_std_mul); try instance.env.put("/", &intrinsics.expr_std_div); try instance.env.put("=", &intrinsics.expr_std_eq); try instance.env.put("~=", &intrinsics.expr_std_eq_approx); try instance.env.put("^=", &intrinsics.expr_std_eq_reference); try instance.env.put("order", &intrinsics.expr_std_order); try instance.env.put("io.open-file", &intrinsics.expr_std_file_open); try instance.env.put("io.close-file", &intrinsics.expr_std_file_close); try instance.env.put("io.read-line", &intrinsics.expr_std_file_read_line); try instance.env.put("io.write-line", &intrinsics.expr_std_file_write_line); try instance.env.put("io.read-byte", &intrinsics.expr_std_file_read_byte); return instance; } /// Perform a full GC sweep and check for leaks pub fn deinit(_: *Interpreter) void { mem.gc.deinit(); SourceLocation.deinitStack(); if (!@import("builtin").is_test and mem.gpa.deinit()) { std.io.getStdOut().writer().print("Memory leaks detected\n", .{}) catch unreachable; } } /// Print user friendly errors pub fn printError(_: *Interpreter, err: anyerror) !void { const err_str = switch (err) { ExprErrors.AlreadyReported => return, ExprErrors.InvalidArgumentCount => "Invalid argument count", ExprErrors.InvalidArgumentType => "Invalid argument type", ExprErrors.ExpectedNumber => "Expected a number", ExprErrors.UnexpectedRightParen => "Unexpected )", ExprErrors.MissingRightParen => "Missing )", ExprErrors.SyntaxError => "Syntax error while parsing", ExprErrors.Eof => "End of file", else => "Unknown", }; try std.io.getStdOut().writer().print("{s}\n", .{err_str}); } /// Print a formatted error message, prefixed with source location pub fn printErrorFmt(self: *Interpreter, src_loc: *SourceLocation, comptime fmt: []const u8, args: anytype) !void { try std.io.getStdOut().writer().print("ERROR: {s}, line {d}: ", .{ src_loc.file, std.math.max(1, src_loc.line) }); try std.io.getStdOut().writer().print(fmt, args); // for (SourceLocation.stack.items) |loc| { // try std.io.getStdOut().writer().print(" {s}:{d}", .{loc.file, std.math.max(1, loc.line)}); // } self.has_errors = true; } /// Run GC if needed, then parse and evaluate the expression pub fn parseAndEvalExpression(self: *Interpreter, line: []const u8) anyerror!?*Expr { mem.gc.runIfNeeded() catch {}; var input = std.mem.trimRight(u8, line, "\r\n"); // Ignore empty lines and comments if (input.len == 0 or input[0] == ';') { return null; } var expr = try self.parse(input); return try self.eval(self.env, expr); } /// Parse Bio source code into Expr objects pub fn parse(self: *Interpreter, input: []const u8) !*Expr { var it = Lisperator{ .index = 0, .buffer = input, }; return self.read(&it); } /// Evaluate an expression pub fn eval(self: *Interpreter, environment: *Env, expr: *Expr) anyerror!*Expr { var maybe_next: ?*Expr = expr; var env: *Env = environment; tailcall_optimization_loop: while (maybe_next) |e| { if (self.exit_code) |_| { return &intrinsics.expr_atom_nil; } if (e == &intrinsics.expr_atom_break) { self.break_seen = true; return &intrinsics.expr_atom_nil; } switch (e.val) { ExprValue.num, ExprValue.env, ExprValue.any => { return e; }, ExprValue.sym => |sym| { if (env.lookup(sym, true)) |val| { return val; } else { try self.printErrorFmt(&e.src, "{s} is not defined\n", .{sym}); return &intrinsics.expr_atom_nil; } }, ExprValue.lst => |list| { if (list.items.len == 0) { return &intrinsics.expr_atom_nil; } const args_slice = list.items[1..]; if (list.items[0] == &intrinsics.expr_atom_begin) { var res: *Expr = &intrinsics.expr_atom_nil; for (args_slice[0 .. args_slice.len - 1]) |arg| { res = try self.eval(env, arg); } maybe_next = args_slice[args_slice.len - 1]; continue; } else if (list.items[0] == &intrinsics.expr_atom_cond) { try intrinsics.requireMinimumArgCount(2, args_slice); const else_branch = args_slice[args_slice.len - 1]; if (else_branch.val != ExprType.lst or else_branch.val.lst.items.len != 1) { try self.printErrorFmt(&e.src, "Last expression in cond must be a single-expression list\n", .{}); return ExprErrors.AlreadyReported; } for (args_slice) |branch| { if (branch == else_branch) { maybe_next = branch.val.lst.items[0]; continue :tailcall_optimization_loop; } else if (branch.val == ExprType.lst) { try intrinsics.requireExactArgCount(2, branch.val.lst.items); const predicate = try self.eval(env, branch.val.lst.items[0]); if (predicate == &intrinsics.expr_atom_true) { maybe_next = branch.val.lst.items[1]; continue :tailcall_optimization_loop; } } else { try self.printErrorFmt(&e.src, "Invalid switch syntax\n", .{}); return ExprErrors.AlreadyReported; } } return &intrinsics.expr_atom_nil; } else if (list.items[0] == &intrinsics.expr_atom_if) { try intrinsics.requireMinimumArgCount(2, args_slice); var branch: usize = 1; const predicate = try self.eval(env, args_slice[0]); if (predicate != &intrinsics.expr_atom_true) { // Anything not defined as falsy is considered true in a boolean context if (intrinsics.isFalsy(predicate)) { branch += 1; } } if (branch < args_slice.len) { maybe_next = args_slice[branch]; continue :tailcall_optimization_loop; } else { return &intrinsics.expr_atom_nil; } } // Look up std function or lambda. If not found, the lookup has already reported the error. var func = try self.eval(env, list.items[0]); if (func == &intrinsics.expr_atom_nil) { return &intrinsics.expr_atom_nil; } const kind = func.val; switch (kind) { ExprValue.env => |target_env| { if (args_slice.len == 0 or (args_slice[0].val != ExprType.sym and args_slice[0].val != ExprType.lst)) { try self.printErrorFmt(&e.src, "Missing symbol or call in environment lookup: ", .{}); try args_slice[0].print(); return ExprErrors.AlreadyReported; } if (args_slice[0].val == ExprType.lst) { maybe_next = args_slice[0]; env = target_env; continue :tailcall_optimization_loop; } else if (target_env.lookup(args_slice[0].val.sym, false)) |match| { return match; } else { try self.printErrorFmt(&e.src, "Symbol not found in given environment: {s}\n", .{args_slice[0].val.sym}); return ExprErrors.AlreadyReported; } }, // Evaluate an intrinsic function ExprValue.fun => |fun| { return fun(self, env, args_slice) catch |err| { try self.printErrorFmt(&e.src, "", .{}); try self.printError(err); return &intrinsics.expr_atom_nil; }; }, // Evaluate a previously defined lambda or macro ExprValue.lam, ExprValue.mac => |fun| { try intrinsics.requireType(self, fun.items[0], ExprType.lst); const parent_env = if (kind == ExprType.lam) func.env else env; const kind_str = if (kind == ExprType.lam) "lambda" else "macro"; var local_env = try ast.makeEnv(parent_env, kind_str); var formal_param_count = fun.items[0].val.lst.items.len; var logical_arg_count = args_slice.len; // Bind arguments to the new environment for (fun.items[0].val.lst.items) |param, index| { if (param.val == ExprType.sym) { if (param == &intrinsics.expr_atom_rest) { formal_param_count -= 1; var rest_args = try ast.makeListExpr(null); for (args_slice[index..]) |rest_param| { logical_arg_count -= 1; if (kind == ExprType.lam) { try rest_args.val.lst.append(try self.eval(env, rest_param)); } else { try rest_args.val.lst.append(rest_param); } } logical_arg_count += 1; try local_env.putWithSymbol(fun.items[0].val.lst.items[index + 1], rest_args); break; } // Arguments are eagerly evaluated for lambdas, lazily for macros if (index < args_slice.len) { if (kind == ExprType.lam) { try local_env.putWithSymbol(param, try self.eval(env, args_slice[index])); } else { try local_env.putWithSymbol(param, args_slice[index]); } } } else { try self.printErrorFmt(&e.src, "Formal parameter to {s} is not a symbol: ", .{kind_str}); try param.print(); } } if (logical_arg_count != formal_param_count) { try self.printErrorFmt(&e.src, "{s} received {d} arguments, expected {d}\n", .{ kind_str, args_slice.len, formal_param_count }); return &intrinsics.expr_atom_nil; } // Evaluate body, except the last expression which is TCO'ed var result: *Expr = undefined; for (fun.items[1 .. fun.items.len - 1]) |body_expr| { result = self.eval(local_env, body_expr) catch |err| { try self.printErrorFmt(&body_expr.src, "Could not evaluate {s} body:", .{kind_str}); try self.printError(err); return &intrinsics.expr_atom_nil; }; if (self.has_errors) { return &intrinsics.expr_atom_nil; } } // For lambdas, we set up the next iteration to eval the last expression, while for // macros we just evaluate it, and then evaluate it again in order to evaluate the // generated expression produced by the macro. const last_expr = fun.items[fun.items.len - 1]; if (kind == ExprValue.lam) { env = local_env; maybe_next = last_expr; continue; } else { result = self.eval(local_env, last_expr) catch |err| { try self.printErrorFmt(&last_expr.src, "Could not evaluate {s} body:", .{kind_str}); try self.printError(err); return &intrinsics.expr_atom_nil; }; return self.eval(local_env, result); } }, else => { try self.printErrorFmt(&e.src, "Not a function or macro: ", .{}); try list.items[0].print(); return &intrinsics.expr_atom_nil; }, } return &intrinsics.expr_atom_nil; }, else => { try self.printErrorFmt(&e.src, "Invalid expression: {}\n", .{e}); return &intrinsics.expr_atom_nil; }, } } return &intrinsics.expr_atom_nil; } /// Recursively read expressions pub fn read(self: *Interpreter, it: *Lisperator) anyerror!*Expr { if (it.next()) |val| { if (val.len > 0) { switch (val[0]) { '(' => { var list = try ast.makeListExpr(null); while (it.peek()) |peek| { if (peek.len == 0) { return ExprErrors.SyntaxError; } if (peek[0] != ')') { try list.val.lst.append(try self.read(it)); } else { break; } } _ = it.next(); return list; }, ')' => { return ExprErrors.UnexpectedRightParen; }, ',' => { var unquote_op: *Expr = &intrinsics.expr_atom_unquote; var index_adjust: usize = 1; // The Lisperator has no understanding of the , and ,@ prefixes, so we adjust it manually // For instance, if the current token is ,@abc then the next token will be abc if (val.len > 1 and val[1] == '@') { unquote_op = &intrinsics.expr_atom_unquote_splicing; if (val.len > 2) { index_adjust += 1; } } if (index_adjust > 0) { it.index = it.prev_index + index_adjust; } return try ast.makeListExpr(&.{ unquote_op, try self.read(it) }); }, '\'' => { return try ast.makeListExpr(&.{ &intrinsics.expr_atom_quote, try self.read(it) }); }, '`' => { return try ast.makeListExpr(&.{ &intrinsics.expr_atom_quasi_quote, try self.read(it) }); }, '"' => { return try ast.makeListExpr(&.{ &intrinsics.expr_atom_quote, try ast.makeAtomByDuplicating(val[1..val.len]) }); }, else => { return ast.makeAtomByDuplicating(val); }, } } else { return ExprErrors.SyntaxError; } } else { return ExprErrors.Eof; } } /// This function helps us read a Bio expression that may span multiple lines /// If too many )'s are detected, an error is returned. We make sure to not /// count parenthesis inside string literals. pub fn readBalancedExpr(self: *Interpreter, reader: anytype, prompt: []const u8) anyerror!?[]u8 { var balance: isize = 0; var expr = std.ArrayList(u8).init(mem.allocator); defer expr.deinit(); var expr_writer = expr.writer(); try linereader.linenoise_wrapper.printPrompt(prompt); reader_loop: while (true) { if (reader.readUntilDelimiterOrEofAlloc(mem.allocator, '\n', 2048)) |maybe| { if (maybe) |line| { defer mem.allocator.free(line); SourceLocation.current().line += 1; var only_seen_ws = true; var inside_string = false; for (line) |char| { if (char == ';' and only_seen_ws) { continue :reader_loop; } only_seen_ws = only_seen_ws and std.ascii.isSpace(char); if (char == '"') { inside_string = !inside_string; } if (!inside_string) { if (char == '(') { balance += 1; } else if (char == ')') { balance -= 1; } } } if (expr.items.len > 0) { try expr_writer.writeAll(" "); } try expr_writer.writeAll(line); } else { if (balance > 0 and prompt.len == 0) { return ExprErrors.MissingRightParen; } return null; } } else |err| { try self.printErrorFmt(SourceLocation.current(), "readUntilDelimiterOrEofAlloc failed {}\n", .{err}); } if (balance <= 0) { break; } else { linereader.linenoise_wrapper.hidePrompt(); } } if (balance < 0) { std.debug.print("Missing )\n", .{}); return ExprErrors.UnexpectedRightParen; } return expr.toOwnedSlice(); } /// REPL pub fn readEvalPrint(self: *Interpreter) !void { const logo = \\ \\ .. .. \\ pd '(Ob. `bq \\ 6P M YA Bio is a Lisp written in Zig \\ 6M' db `Mb Docs at github.com/cryptocode/bio \\ MN BIO. 8M \\ MN AM'`M 8M Use arrow up/down for history \\ YM. ,M' db ,M9 You can also run bio files with \\ Mb JM' Yb./ .dM "bio run <file>" \\ Yq . .pY \\ `` '' ; try std.io.getStdOut().writer().print("{s}\n\n", .{logo}); while (true) { if (self.readBalancedExpr(&linereader.linenoise_reader, "bio> ")) |maybe| { if (maybe) |input| { defer mem.allocator.free(input); _ = try linereader.linenoise_wrapper.addToHistory(input); var maybeResult = self.parseAndEvalExpression(input) catch |err| { try self.printErrorFmt(SourceLocation.current(), "read-eval failed: \n", .{}); try self.printError(err); continue; }; if (maybeResult) |res| { // Update the last expression and print it try self.env.put("#?", res); if (res != &intrinsics.expr_atom_nil or self.verbose) { try res.print(); } try std.io.getStdOut().writer().print("\n\n", .{}); } if (self.exit_code) |exit_code| { // Defer is not called as exit is [noreturn] mem.allocator.free(input); self.deinit(); std.process.exit(exit_code); } } } else |err| { try self.printError(err); } } } }; /// A tokenizing iterator for Lisp expression pub const Lisperator = struct { buffer: []const u8, index: usize = 0, prev_index: usize = 0, pub fn peek(self: *Lisperator) ?[]const u8 { const index_now = self.index; const val = self.next(); self.index = index_now; return val; } /// Returns a slice of the next token, or null if tokenizing is complete pub fn next(self: *Lisperator) ?[]const u8 { if (self.index >= self.buffer.len) { return null; } while (self.index + 1 < self.buffer.len and (self.buffer[self.index] == ' ' or self.buffer[self.index] == '\t')) { self.index += 1; } var start = self.index; self.prev_index = start; if (self.buffer[self.index] == '"') { while (self.index + 1 < self.buffer.len and (self.buffer[self.index + 1] != '"')) { self.index += 1; } if (self.index + 1 == self.buffer.len or self.buffer[self.index + 1] != '"') { std.io.getStdOut().writer().print("Unterminated string literal\n", .{}) catch unreachable; return null; } self.index += 1; defer self.index += 1; return self.buffer[start..self.index]; } if (self.buffer[self.index] == '(' or self.buffer[self.index] == ')' or self.buffer[self.index] == '\'' or self.buffer[self.index] == '`') { self.index += 1; return self.buffer[start .. start + 1]; } else { if (std.mem.indexOfAnyPos(u8, self.buffer, start, " \t)(")) |delim_start| { const res = self.buffer[start..delim_start]; self.index = delim_start; return std.mem.trim(u8, res, "\r\n\t "); } else if (self.index <= self.buffer.len) { return std.mem.trim(u8, self.buffer[start..self.buffer.len], "\r\n\t "); } else { return null; } } } };
src/interpreter.zig
const testing = @import("std").testing; const xml = @import("xml"); const full = @import("full.zig"); test "full structure" { var doc = try xml.Document.fromString(full.file); defer doc.deinit(); var decode_result = try xml.decode(testing.allocator, full.TestStructure, doc); defer decode_result.deinit(); const result = decode_result.result; try testing.expectEqualStrings("hello", result.root.element1.__attributes__.attr1); try testing.expectEqualStrings("world", result.root.element1.__attributes__.attr2.?); try testing.expectEqualStrings("I am required", result.root.element1.child1); try testing.expectEqual(@as(i16, -23), result.root.element1.@"int-child".?); try testing.expectEqual(true, result.root.element1.@"wacky:child".?); try testing.expectEqualStrings("I am optional", result.root.element2.child2.?); try testing.expectEqual(@as(usize, 2), result.root.element2.repeated.len); try testing.expectEqualStrings("Another one", result.root.element2.repeated[0].anotherone.__item__); try testing.expectEqualStrings("Another two", result.root.element2.repeated[1].anotherone.__item__); try testing.expectEqualStrings("yes", result.root.element2.repeated[1].anotherone.__attributes__.optionalattr.?); } test "minimal structure" { var doc = try xml.Document.fromString( \\<?xml version=\"1.0\"?> \\<root> \\ <element1 attr1="hello"> \\ <child1>I am required</child1> \\ </element1> \\ <element2> \\ </element2> \\</root> ); defer doc.deinit(); var decode_result = try xml.decode(testing.allocator, full.TestStructure, doc); defer decode_result.deinit(); const result = decode_result.result; try testing.expectEqualStrings("hello", result.root.element1.__attributes__.attr1); try testing.expectEqual(@as(?[]const u8, null), result.root.element1.__attributes__.attr2); try testing.expectEqualStrings("I am required", result.root.element1.child1); try testing.expectEqual(@as(?[]const u8, null), result.root.element2.child2); try testing.expectEqual(@as(usize, 0), result.root.element2.repeated.len); } test "empty document" { var doc = try xml.Document.fromString("<?xml version=\"1.0\"?>"); defer doc.deinit(); try testing.expectError(xml.Error, xml.decode(testing.allocator, full.TestStructure, doc)); }
test/test_decode.zig
const std = @import("std"); const print = std.debug.print; const math = std.math; const testing = std.testing; const root = @import("main.zig"); usingnamespace @import("vec4.zig"); usingnamespace @import("vec3.zig"); usingnamespace @import("quaternion.zig"); pub const mat4 = Mat4(f32); pub const mat4_f64 = Mat4(f64); pub const perspective = mat4.perspective; pub const orthographic = mat4.orthographic; pub const look_at = mat4.look_at; /// A column-major 4x4 matrix. /// Note: Column-major means accessing data like m.data[COLUMN][ROW]. pub fn Mat4(comptime T: type) type { if (@typeInfo(T) != .Float) { @compileError("Mat4 not implemented for " ++ @typeName(T)); } return struct { data: [4][4]T, const Self = @This(); pub fn identity() Self { return .{ .data = .{ .{ 1., 0., 0., 0. }, .{ 0., 1., 0., 0. }, .{ 0., 0., 1., 0. }, .{ 0., 0., 0., 1. }, }, }; } /// Construct new 4x4 matrix from given slice. pub fn from_slice(data: *const [16]T) Self { return .{ .data = .{ data[0..4].*, data[4..8].*, data[8..12].*, data[12..16].*, }, }; } /// Return a pointer to the inner data of the matrix. pub fn get_data(mat: *const Self) *const T { return @ptrCast(*const T, &mat.data); } pub fn is_eq(left: Self, right: Self) bool { var col: usize = 0; var row: usize = 0; while (col < 4) : (col += 1) { while (row < 4) : (row += 1) { if (left.data[col][row] != right.data[col][row]) { return false; } } } return true; } pub fn mult_by_vec4(mat: Self, v: Vec4(T)) Vec4(T) { var result: Vec4(T) = undefined; result.x = (mat.data[0][0] * v.x) + (mat.data[1][0] * v.y) + (mat.data[2][0] * v.z) + (mat.data[3][0] * v.w); result.y = (mat.data[0][1] * v.x) + (mat.data[1][1] * v.y) + (mat.data[2][1] * v.z) + (mat.data[3][1] * v.w); result.z = (mat.data[0][2] * v.x) + (mat.data[1][2] * v.y) + (mat.data[2][2] * v.z) + (mat.data[3][2] * v.w); result.w = (mat.data[0][3] * v.x) + (mat.data[1][3] * v.y) + (mat.data[2][3] * v.z) + (mat.data[3][3] * v.w); return result; } /// Construct 4x4 translation matrix by multiplying identity matrix and /// given translation vector. pub fn from_translate(axis: Vec3(T)) Self { var mat = Self.identity(); mat.data[3][0] = axis.x; mat.data[3][1] = axis.y; mat.data[3][2] = axis.z; return mat; } /// Make a translation between the given matrix and the given axis. pub fn translate(mat: Self, axis: Vec3(T)) Self { const trans_mat = Self.from_translate(axis); return Self.mult(trans_mat, mat); } /// Get translation Vec3 from current matrix. pub fn extract_translation(self: Self) Vec3(T) { return Vec3(T).new(self.data[3][0], self.data[3][1], self.data[3][2]); } /// Construct a 4x4 matrix from given axis and angle (in degrees). pub fn from_rotation(angle_in_degrees: T, axis: Vec3(T)) Self { var mat = Self.identity(); const norm_axis = axis.norm(); const sin_theta = math.sin(root.to_radians(angle_in_degrees)); const cos_theta = math.cos(root.to_radians(angle_in_degrees)); const cos_value = 1.0 - cos_theta; mat.data[0][0] = (norm_axis.x * norm_axis.x * cos_value) + cos_theta; mat.data[0][1] = (norm_axis.x * norm_axis.y * cos_value) + (norm_axis.z * sin_theta); mat.data[0][2] = (norm_axis.x * norm_axis.z * cos_value) - (norm_axis.y * sin_theta); mat.data[1][0] = (norm_axis.y * norm_axis.x * cos_value) - (norm_axis.z * sin_theta); mat.data[1][1] = (norm_axis.y * norm_axis.y * cos_value) + cos_theta; mat.data[1][2] = (norm_axis.y * norm_axis.z * cos_value) + (norm_axis.x * sin_theta); mat.data[2][0] = (norm_axis.z * norm_axis.x * cos_value) + (norm_axis.y * sin_theta); mat.data[2][1] = (norm_axis.z * norm_axis.y * cos_value) - (norm_axis.x * sin_theta); mat.data[2][2] = (norm_axis.z * norm_axis.z * cos_value) + cos_theta; return mat; } pub fn rotate(mat: Self, angle_in_degrees: T, axis: Vec3(T)) Self { const rotation_mat = Self.from_rotation(angle_in_degrees, axis); return Self.mult(mat, rotation_mat); } /// Construct a rotation matrix from euler angles (X * Y * Z). /// Order matters because matrix multiplication are NOT commutative. pub fn from_euler_angle(euler_angle: Vec3(T)) Self { const x = Self.from_rotation(euler_angle.x, vec3.new(1, 0, 0)); const y = Self.from_rotation(euler_angle.y, vec3.new(0, 1, 0)); const z = Self.from_rotation(euler_angle.z, vec3.new(0, 0, 1)); return z.mult(y.mult(x)); } /// Ortho normalize given matrix. pub fn ortho_normalize(mat: Self) Self { const column_1 = vec3.new(mat.data[0][0], mat.data[0][1], mat.data[0][2]).norm(); const column_2 = vec3.new(mat.data[1][0], mat.data[1][1], mat.data[1][2]).norm(); const column_3 = vec3.new(mat.data[2][0], mat.data[2][1], mat.data[2][2]).norm(); var result = mat; result.data[0][0] = column_1.x; result.data[0][1] = column_1.y; result.data[0][2] = column_1.z; result.data[1][0] = column_2.x; result.data[1][1] = column_2.y; result.data[1][2] = column_2.z; result.data[2][0] = column_3.x; result.data[2][1] = column_3.y; result.data[2][2] = column_3.z; return result; } /// Return the rotation as Euler angles in degrees. /// Taken from Mike Day at Insomniac Games (and `glm` as the same function). /// For more details: https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2012/07/euler-angles1.pdf pub fn extract_rotation(self: Self) Vec3(T) { const m = self.ortho_normalize(); const theta_x = math.atan2(T, m.data[1][2], m.data[2][2]); const c2 = math.sqrt(math.pow(f32, m.data[0][0], 2) + math.pow(f32, m.data[0][1], 2)); const theta_y = math.atan2(T, -m.data[0][2], math.sqrt(c2)); const s1 = math.sin(theta_x); const c1 = math.cos(theta_x); const theta_z = math.atan2(T, s1 * m.data[2][0] - c1 * m.data[1][0], c1 * m.data[1][1] - s1 * m.data[2][1]); return vec3.new(root.to_degrees(theta_x), root.to_degrees(theta_y), root.to_degrees(theta_z)); } pub fn from_scale(axis: Vec3(T)) Self { var mat = Self.identity(); mat.data[0][0] = axis.x; mat.data[1][1] = axis.y; mat.data[2][2] = axis.z; return mat; } pub fn scale(mat: Self, axis: Vec3(T)) Self { const scale_mat = Self.from_scale(axis); return Self.mult(scale_mat, mat); } pub fn extract_scale(mat: Self) Vec3(T) { const scale_x = vec3.new(mat.data[0][0], mat.data[0][1], mat.data[0][2]).length(); const scale_y = vec3.new(mat.data[1][0], mat.data[1][1], mat.data[1][2]).length(); const scale_z = vec3.new(mat.data[2][0], mat.data[2][1], mat.data[2][2]).length(); return Vec3(T).new(scale_x, scale_y, scale_z); } /// Construct a perspective 4x4 matrix. /// Note: Field of view is given in degrees. /// Also for more details https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml. pub fn perspective(fovy_in_degrees: T, aspect_ratio: T, z_near: T, z_far: T) Self { var mat: Self = Self.identity(); const f = 1.0 / math.tan(root.to_radians(fovy_in_degrees) * 0.5); mat.data[0][0] = f / aspect_ratio; mat.data[1][1] = f; mat.data[2][2] = (z_near + z_far) / (z_near - z_far); mat.data[2][3] = -1; mat.data[3][2] = 2 * z_far * z_near / (z_near - z_far); mat.data[3][3] = 0; return mat; } /// Construct an orthographic 4x4 matrix. pub fn orthographic(left: T, right: T, bottom: T, top: T, z_near: T, z_far: T) Self { var mat: Self = undefined; mat.data[0][0] = 2.0 / (right - left); mat.data[1][1] = 2.0 / (top - bottom); mat.data[2][2] = 2.0 / (z_near - z_far); mat.data[3][3] = 1.0; mat.data[3][0] = (left + right) / (left - right); mat.data[3][1] = (bottom + top) / (bottom - top); mat.data[3][2] = (z_far + z_near) / (z_near - z_far); return mat; } /// Right-handed look_at function. pub fn look_at(eye: Vec3(T), target: Vec3(T), up: Vec3(T)) Self { const f = Vec3(T).norm(Vec3(T).sub(target, eye)); const s = Vec3(T).norm(Vec3(T).cross(f, up)); const u = Vec3(T).cross(s, f); var mat: Self = undefined; mat.data[0][0] = s.x; mat.data[0][1] = u.x; mat.data[0][2] = -f.x; mat.data[0][3] = 0.0; mat.data[1][0] = s.y; mat.data[1][1] = u.y; mat.data[1][2] = -f.y; mat.data[1][3] = 0.0; mat.data[2][0] = s.z; mat.data[2][1] = u.z; mat.data[2][2] = -f.z; mat.data[2][3] = 0.0; mat.data[3][0] = -Vec3(T).dot(s, eye); mat.data[3][1] = -Vec3(T).dot(u, eye); mat.data[3][2] = Vec3(T).dot(f, eye); mat.data[3][3] = 1.0; return mat; } /// Matrices multiplication. /// Produce a new matrix from given two matrices. pub fn mult(left: Self, right: Self) Self { var mat = Self.identity(); var columns: usize = 0; while (columns < 4) : (columns += 1) { var rows: usize = 0; while (rows < 4) : (rows += 1) { var sum: T = 0.0; var current_mat: usize = 0; while (current_mat < 4) : (current_mat += 1) { sum += left.data[current_mat][rows] * right.data[columns][current_mat]; } mat.data[columns][rows] = sum; } } return mat; } /// Construct inverse 4x4 from given matrix. /// Note: This is not the most efficient way to do this. /// TODO: Make it more efficient. pub fn inv(mat: Self) Self { var inv_mat: Self = undefined; var s: [6]T = undefined; var c: [6]T = undefined; s[0] = mat.data[0][0] * mat.data[1][1] - mat.data[1][0] * mat.data[0][1]; s[1] = mat.data[0][0] * mat.data[1][2] - mat.data[1][0] * mat.data[0][2]; s[2] = mat.data[0][0] * mat.data[1][3] - mat.data[1][0] * mat.data[0][3]; s[3] = mat.data[0][1] * mat.data[1][2] - mat.data[1][1] * mat.data[0][2]; s[4] = mat.data[0][1] * mat.data[1][3] - mat.data[1][1] * mat.data[0][3]; s[5] = mat.data[0][2] * mat.data[1][3] - mat.data[1][2] * mat.data[0][3]; c[0] = mat.data[2][0] * mat.data[3][1] - mat.data[3][0] * mat.data[2][1]; c[1] = mat.data[2][0] * mat.data[3][2] - mat.data[3][0] * mat.data[2][2]; c[2] = mat.data[2][0] * mat.data[3][3] - mat.data[3][0] * mat.data[2][3]; c[3] = mat.data[2][1] * mat.data[3][2] - mat.data[3][1] * mat.data[2][2]; c[4] = mat.data[2][1] * mat.data[3][3] - mat.data[3][1] * mat.data[2][3]; c[5] = mat.data[2][2] * mat.data[3][3] - mat.data[3][2] * mat.data[2][3]; const determ = 1.0 / (s[0] * c[5] - s[1] * c[4] + s[2] * c[3] + s[3] * c[2] - s[4] * c[1] + s[5] * c[0]); inv_mat.data[0][0] = (mat.data[1][1] * c[5] - mat.data[1][2] * c[4] + mat.data[1][3] * c[3]) * determ; inv_mat.data[0][1] = (-mat.data[0][1] * c[5] + mat.data[0][2] * c[4] - mat.data[0][3] * c[3]) * determ; inv_mat.data[0][2] = (mat.data[3][1] * s[5] - mat.data[3][2] * s[4] + mat.data[3][3] * s[3]) * determ; inv_mat.data[0][3] = (-mat.data[2][1] * s[5] + mat.data[2][2] * s[4] - mat.data[2][3] * s[3]) * determ; inv_mat.data[1][0] = (-mat.data[1][0] * c[5] + mat.data[1][2] * c[2] - mat.data[1][3] * c[1]) * determ; inv_mat.data[1][1] = (mat.data[0][0] * c[5] - mat.data[0][2] * c[2] + mat.data[0][3] * c[1]) * determ; inv_mat.data[1][2] = (-mat.data[3][0] * s[5] + mat.data[3][2] * s[2] - mat.data[3][3] * s[1]) * determ; inv_mat.data[1][3] = (mat.data[2][0] * s[5] - mat.data[2][2] * s[2] + mat.data[2][3] * s[1]) * determ; inv_mat.data[2][0] = (mat.data[1][0] * c[4] - mat.data[1][1] * c[2] + mat.data[1][3] * c[0]) * determ; inv_mat.data[2][1] = (-mat.data[0][0] * c[4] + mat.data[0][1] * c[2] - mat.data[0][3] * c[0]) * determ; inv_mat.data[2][2] = (mat.data[3][0] * s[4] - mat.data[3][1] * s[2] + mat.data[3][3] * s[0]) * determ; inv_mat.data[2][3] = (-mat.data[2][0] * s[4] + mat.data[2][1] * s[2] - mat.data[2][3] * s[0]) * determ; inv_mat.data[3][0] = (-mat.data[1][0] * c[3] + mat.data[1][1] * c[1] - mat.data[1][2] * c[0]) * determ; inv_mat.data[3][1] = (mat.data[0][0] * c[3] - mat.data[0][1] * c[1] + mat.data[0][2] * c[0]) * determ; inv_mat.data[3][2] = (-mat.data[3][0] * s[3] + mat.data[3][1] * s[1] - mat.data[3][2] * s[0]) * determ; inv_mat.data[3][3] = (mat.data[2][0] * s[3] - mat.data[2][1] * s[1] + mat.data[2][2] * s[0]) * determ; return inv_mat; } /// Return 4x4 matrix from given all transform components; `translation`, `rotation` and `sclale`. /// The final order is T * R * S. /// Note: `rotation` could be `vec3` (Euler angles) or a `quat`. pub fn recompose(translation: Vec3(T), rotation: anytype, scaler: Vec3(T)) Self { const t = Self.from_translate(translation); const s = Self.from_scale(scaler); const r = switch (@TypeOf(rotation)) { Quaternion(T) => Quaternion(T).to_mat4(rotation), Vec3(T) => Self.from_euler_angle(rotation), else => @compileError("Recompose not implemented for " ++ @typeName(@TypeOf(rotation))), }; return t.mult(r.mult(s)); } /// Return `translation`, `rotation` and `scale` components from given matrix. /// For now, the rotation returned is a quaternion. If you want to get Euler angles /// from it, just do: `returned_quat.extract_rotation()`. /// Note: We ortho nornalize the given matrix before extracting the rotation. pub fn decompose(mat: Self) struct { t: Vec3(T), r: Quaternion(T), s: Vec3(T) } { const t = mat.extract_translation(); const s = mat.extract_scale(); const r = quat.from_mat4(mat.ortho_normalize()); return .{ .t = t, .r = r, .s = s, }; } /// Display the 4x4 matrix. pub fn fmt(self: Self) void { print("\n", .{}); print("({d}, {d}, {d}, {d})\n", .{ self.data[0][0], self.data[1][0], self.data[2][0], self.data[3][0] }); print("({d}, {d}, {d}, {d})\n", .{ self.data[0][1], self.data[1][1], self.data[2][1], self.data[3][1] }); print("({d}, {d}, {d}, {d})\n", .{ self.data[0][2], self.data[1][2], self.data[2][2], self.data[3][2] }); print("({d}, {d}, {d}, {d})\n", .{ self.data[0][3], self.data[1][3], self.data[2][3], self.data[3][3] }); print("\n", .{}); } }; } test "zalgebra.Mat4.is_eq" { const mat_0 = mat4.identity(); const mat_1 = mat4.identity(); const mat_2 = mat4{ .data = .{ .{ 0., 0., 0., 0. }, .{ 0., 0., 0., 0. }, .{ 0., 0., 0., 0. }, .{ 0., 0., 0., 0. }, }, }; testing.expectEqual(mat4.is_eq(mat_0, mat_1), true); testing.expectEqual(mat4.is_eq(mat_0, mat_2), false); } test "zalgebra.Mat4.from_slice" { const data = [_]f32{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; const result = mat4.from_slice(&data); testing.expectEqual(mat4.is_eq(result, mat4.identity()), true); } test "zalgebra.Mat4.from_translate" { const mat4_trans = mat4.from_translate(vec3.new(2, 3, 4)); testing.expectEqual(mat4.is_eq(mat4_trans, mat4{ .data = .{ .{ 1., 0., 0., 0. }, .{ 0., 1., 0., 0. }, .{ 0., 0., 1., 0. }, .{ 2., 3., 4., 1. }, }, }), true); } test "zalgebra.Mat4.translate" { const base = mat4.from_translate(vec3.new(2, 3, 2)); const result = mat4.translate(base, vec3.new(2, 3, 4)); testing.expectEqual(mat4.is_eq(result, mat4{ .data = .{ .{ 1., 0., 0., 0. }, .{ 0., 1., 0., 0. }, .{ 0., 0., 1., 0. }, .{ 4., 9., 8., 1. }, }, }), true); } test "zalgebra.Mat4.from_scale" { const mat4_scale = mat4.from_scale(vec3.new(2, 3, 4)); testing.expectEqual(mat4.is_eq(mat4_scale, mat4{ .data = .{ .{ 2., 0., 0., 0. }, .{ 0., 3., 0., 0. }, .{ 0., 0., 4., 0. }, .{ 0., 0., 0., 1. }, }, }), true); } test "zalgebra.Mat4.scale" { const base = mat4.from_scale(vec3.new(2, 3, 4)); const result = mat4.scale(base, vec3.new(2, 2, 2)); testing.expectEqual(mat4.is_eq(result, mat4{ .data = .{ .{ 4., 0., 0., 0. }, .{ 0., 6., 0., 0. }, .{ 0., 0., 4., 0. }, .{ 0., 0., 0., 1. }, }, }), true); } test "zalgebra.Mat4.inv" { const base: mat4 = .{ .data = .{ .{ 2., 0., 0., 4. }, .{ 0., 2., 0., 0. }, .{ 0., 0., 2., 0. }, .{ 4., 0., 0., 2. }, }, }; testing.expectEqual(mat4.is_eq(base.inv(), mat4{ .data = .{ .{ -0.1666666716337204, 0., 0., 0.3333333432674408 }, .{ 0., 0.5, 0., 0. }, .{ 0., 0., 0.5, 0. }, .{ 0.3333333432674408, 0., 0., -0.1666666716337204 }, }, }), true); } test "zalgebra.Mat4.extract_translation" { var base = mat4.from_translate(vec3.new(2, 3, 2)); base = base.translate(vec3.new(2, 3, 2)); testing.expectEqual(vec3.is_eq(base.extract_translation(), vec3.new(4, 6, 4)), true); } test "zalgebra.Mat4.extract_rotation" { const lhs = mat4.from_euler_angle(vec3.new(45., -5., 20.)); testing.expectEqual(vec3.is_eq(lhs.extract_rotation(), vec3.new(45.000003814697266, -4.99052524, 19.999998092651367)), true); } test "zalgebra.Mat4.extract_scale" { var base = mat4.from_scale(vec3.new(2, 4, 8)); base = base.scale(vec3.new(2, 4, 8)); testing.expectEqual(vec3.is_eq(base.extract_scale(), vec3.new(4, 16, 64)), true); } test "zalgebra.Mat4.recompose" { const result = mat4.recompose( vec3.new(2, 2, 2), vec3.new(45, 5, 0), vec3.new(1, 1, 1), ); testing.expectEqual(mat4.is_eq(result, mat4{ .data = .{ .{ 0.9961947202682495, 0., -0.08715573698282242, 0. }, .{ 0.06162841618061066, 0.7071067690849304, 0.7044160962104797, 0. }, .{ 0.06162841245532036, -0.7071068286895752, 0.704416036605835, 0. }, .{ 2., 2., 2., 1 }, }, }), true); } test "zalgebra.Mat4.decompose" { const base = mat4.recompose( vec3.new(10, 5, 5), vec3.new(45, 5, 0), vec3.new(1, 1, 1), ); const result = base.decompose(); testing.expectEqual(result.t.is_eq(vec3.new(10, 5, 5)), true); testing.expectEqual(result.s.is_eq(vec3.new(1, 1, 1)), true); testing.expectEqual(result.r.extract_rotation().is_eq(vec3.new(45, 5, -0.00000010712935250012379)), true); }
src/mat4.zig
const std = @import("std"); const assert = std.debug.assert; pub const Shift = struct { const allocator = std.heap.direct_allocator; // data{guard}{julian}{stamp} => asleep pub const SData = struct { asleep: bool, pub fn init() SData { return SData{ .asleep = undefined, }; } pub fn deinit(self: *SData) void { // std.debug.warn("SData deinit\n"); } pub fn add_entry(self: *SData, a: bool) void { self.asleep = a; // std.debug.warn("SData add_entry {}\n", a); } }; pub const JData = struct { j: usize, sdata: std.AutoHashMap(usize, SData), smin: usize, smax: usize, pub fn init(j: usize) JData { // std.debug.warn("JData init {}\n", j); return JData{ .j = j, .sdata = std.AutoHashMap(usize, SData).init(allocator), .smin = std.math.maxInt(usize), .smax = 0, }; } pub fn deinit(self: *JData) void { var it = self.sdata.iterator(); while (it.next()) |data| { data.value.deinit(); } self.sdata.deinit(); // std.debug.warn("JData deinit\n"); } pub fn show(self: *JData) void { std.debug.warn("JData [{}]:\n", self.j); var it = self.sdata.iterator(); while (it.next()) |data| { std.debug.warn("sdata {} = {}\n", data.key, data.value.asleep); } } pub fn add_entry(self: *JData, s: usize, a: bool) void { var d: SData = undefined; if (self.sdata.contains(s)) { d = self.sdata.get(s).?.value; } else { d = SData.init(); } d.add_entry(a); _ = self.sdata.put(s, d) catch unreachable; if (self.smin > s) self.smin = s; if (self.smax < s) self.smax = s; // std.debug.warn("JData add_entry {} {}\n", s, a); } }; pub const GData = struct { g: usize, jdata: std.AutoHashMap(usize, JData), jmin: usize, jmax: usize, pub fn init(g: usize) GData { // std.debug.warn("GData init {}\n", g); return GData{ .g = g, .jdata = std.AutoHashMap(usize, JData).init(allocator), .jmin = std.math.maxInt(usize), .jmax = 0, }; } pub fn deinit(self: *GData) void { var it = self.jdata.iterator(); while (it.next()) |data| { // std.debug.warn("Calling deinit for jdata {}\n", data.key); data.value.deinit(); } self.jdata.deinit(); // std.debug.warn("GData deinit\n"); } pub fn show(self: *GData) void { std.debug.warn("GData [{}]:\n", self.g); var it = self.jdata.iterator(); while (it.next()) |data| { std.debug.warn("jdata {} =\n", data.key); data.value.show(); } } pub fn add_entry(self: *GData, j: usize, s: usize, a: bool) void { // std.debug.warn("jdata {} has {} elements\n", self.g, self.jdata.count()); var d: JData = undefined; if (self.jdata.contains(j)) { d = self.jdata.get(j).?.value; } else { d = JData.init(j); // std.debug.warn("GData created jdata for {}\n", j); } // std.debug.warn("jdata {} has {} elements\n", self.g, self.jdata.count()); // if (!self.jdata.contains(j)) { // std.debug.warn("GData stil does not have jdata for {}\n", j); // } else { // std.debug.warn("GData now has jdata for {}\n", j); // } // std.debug.warn("GData got jdata for {}\n", j); d.add_entry(s, a); _ = self.jdata.put(j, d) catch unreachable; if (self.jmin > j) self.jmin = j; if (self.jmax < j) self.jmax = j; // std.debug.warn("GData add_entry {} {} {}\n", j, s, a); // self.show(); } }; gdata: std.AutoHashMap(usize, GData), gcur: usize, pub fn init() Shift { // std.debug.warn("Shift init\n"); return Shift{ .gdata = std.AutoHashMap(usize, GData).init(allocator), .gcur = std.math.maxInt(usize), }; } pub fn deinit(self: *Shift) void { var it = self.gdata.iterator(); while (it.next()) |data| { // std.debug.warn("Calling deinit for gdata {}\n", data.key); data.value.deinit(); } self.gdata.deinit(); // std.debug.warn("Shift deinit\n"); } pub fn show(self: *Shift) void { std.debug.warn("Shift:\n"); var itg = self.gdata.iterator(); while (itg.next()) |dg| { const g = dg.key; var itj = dg.value.jdata.iterator(); while (itj.next()) |dj| { const j = dj.key; var Y: usize = 0; var M: usize = 0; var D: usize = 0; julian_to_YMD(j, &Y, &M, &D); std.debug.warn("{:2}-{:2} #{:2} ", M, D, g); var la: bool = false; var ls: usize = 0; var its = dj.value.sdata.iterator(); while (its.next()) |ds| { const s = ds.key; const a = ds.value; var l: u8 = '.'; if (a.asleep) l = '#'; std.debug.warn(" {}:{c}", s, l); } std.debug.warn("\n"); } } } pub fn add_entry(self: *Shift, g: usize, j: usize, s: usize, a: bool, t: []const u8) void { if (g != std.math.maxInt(usize)) { self.gcur = g; } // std.debug.warn("CUT [{}]: {} - {} - {} - {}\n", t, self.gcur, j, s, a); // std.debug.warn("gdata has {} elements\n", self.gdata.count()); var d: GData = undefined; if (self.gdata.contains(self.gcur)) { d = self.gdata.get(self.gcur).?.value; } else { d = GData.init(self.gcur); // std.debug.warn("Shift created gdata for {}\n", self.gcur); } // std.debug.warn("gdata has {} elements\n", self.gdata.count()); // std.debug.warn("Shift got gdata for {}\n", self.gcur); d.add_entry(j, s, a); _ = self.gdata.put(self.gcur, d) catch unreachable; } // data{guard}{julian}{stamp} => asleep pub fn parse_line(self: *Shift, line: []const u8) void { std.debug.warn("CUT [{}]\n", line); // @breakpoint(); const Y = std.fmt.parseInt(isize, line[1..5], 10) catch 0; const M = std.fmt.parseInt(isize, line[6..8], 10) catch 0; const D = std.fmt.parseInt(isize, line[9..11], 10) catch 0; const j = YMD_to_julian(Y, M, D); const h = std.fmt.parseInt(isize, line[12..14], 10) catch 0; const m = std.fmt.parseInt(isize, line[15..17], 10) catch 0; const s = hms_to_stamp(h, m, 0); const t = line[19..]; var a: bool = undefined; var g: usize = std.math.maxInt(usize); var it = std.mem.separate(t, " "); var p: bool = false; var q: usize = 0; while (it.next()) |piece| { q += 1; if (q == 1) { if (std.mem.compare(u8, piece, "Guard") == std.mem.Compare.Equal) { a = false; p = true; continue; } if (std.mem.compare(u8, piece, "falls") == std.mem.Compare.Equal) { a = true; continue; } if (std.mem.compare(u8, piece, "wakes") == std.mem.Compare.Equal) { a = false; continue; } continue; } if (q == 2) { if (p) { g = std.fmt.parseInt(usize, piece[1..], 10) catch 0; p = false; } continue; } } self.add_entry(g, j, s, a, t); self.show(); } fn YMD_to_julian(Y: isize, M: isize, D: isize) usize { const p = @divTrunc(M - 14, 12); const x = @divTrunc(1461 * (Y + 4800 + p), 4) + @divTrunc(367 * (M - 2 - 12 * p), 12) - @divTrunc(3 * @divTrunc(Y + 4900 + p, 100), 4) + (D - 32075); return @intCast(usize, x); } fn julian_to_YMD(j: usize, Y: *usize, M: *usize, D: *usize) void { var l: isize = @intCast(isize, j + 68569); const n = @divTrunc(4 * l, 146097); l -= @divTrunc(146097 * n + 3, 4); const i = @divTrunc(4000 * (l + 1), 1461001); l -= @divTrunc(1461 * i, 4) - 31; const h = @divTrunc(80 * l, 2447); const k = @divTrunc(h, 11); const dd = l - @divTrunc(2447 * h, 80); const mm = h + 2 - (12 * k); const yy = 100 * (n - 49) + i + k; D.* = @intCast(usize, dd); M.* = @intCast(usize, mm); Y.* = @intCast(usize, yy); } fn hms_to_stamp(h: isize, m: isize, s: isize) usize { const x = (h * 60 + m) * 60 + s; return @intCast(usize, x); } }; test "simple" { std.debug.warn("\n"); const data = \\[1518-11-01 00:00] Guard #10 begins shift \\[1518-11-01 00:05] falls asleep \\[1518-11-01 00:25] wakes up \\[1518-11-01 00:30] falls asleep \\[1518-11-01 00:55] wakes up \\[1518-11-01 23:58] Guard #99 begins shift \\[1518-11-02 00:40] falls asleep \\[1518-11-02 00:50] wakes up \\[1518-11-03 00:05] Guard #10 begins shift \\[1518-11-03 00:24] falls asleep \\[1518-11-03 00:29] wakes up \\[1518-11-04 00:02] Guard #99 begins shift \\[1518-11-04 00:36] falls asleep \\[1518-11-04 00:46] wakes up \\[1518-11-05 00:03] Guard #99 begins shift \\[1518-11-05 00:45] falls asleep \\[1518-11-05 00:55] wakes up ; var shift = Shift.init(); defer shift.deinit(); var it = std.mem.separate(data, "\n"); while (it.next()) |line| { shift.parse_line(line); } }
2018/p04/shift.zig
const std = @import("std"); const fs = std.fs; const Instruction = struct { op: u8, val: i32, const Self = @This(); pub fn fromString(str: []const u8) !Self { return Self{ .op = str[0], .val = try std.fmt.parseInt(i32, str[1..], 10) }; } }; // I assume somewhere in the standard library this function exits, but I can't // find it. fn abs(comptime T: type, v: T) T { return if (v >= 0) v else -v; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_12_1.txt", std.math.maxInt(usize)); const DIRECTIONS = [_]u8{'E', 'S', 'W', 'N'}; var lines = std.mem.tokenize(input, "\n"); var instrs = std.ArrayList(Instruction).init(allocator); defer instrs.deinit(); while (lines.next()) |raw_line| { var line = std.mem.trim(u8, raw_line, " \r\n"); if (line.len == 0) break; try instrs.append(try Instruction.fromString(line)); } { // Solution 1 var px: i32 = 0; var py: i32 = 0; var dir: i32 = 0; for (instrs.items) |instr| { switch (instr.op) { 'E' => { px += instr.val; }, 'S' => { py -= instr.val; }, 'W' => { px -= instr.val; }, 'N' => { py += instr.val; }, 'L' => { var turn = @divFloor(instr.val, 90); dir = @mod(@intCast(i32, DIRECTIONS.len) + dir - turn, @intCast(i32, DIRECTIONS.len)); }, 'R' => { var turn = @divFloor(instr.val, 90); dir = @mod(dir + turn, @intCast(i32, DIRECTIONS.len)); }, 'F' => { const diri = @intCast(usize, dir); switch (DIRECTIONS[diri]) { 'E' => { px += instr.val; }, 'S' => { py -= instr.val; }, 'W' => { px -= instr.val; }, 'N' => { py += instr.val; }, else => { unreachable; } } }, else => { unreachable; } } } std.debug.print("Day 12 - Solution 1: {}\n", .{abs(i32, px) + abs(i32, py)}); } { // Solution 2 var px: i32 = 0; var py: i32 = 0; var wx: i32 = 10; var wy: i32 = 1; for (instrs.items) |instr| { switch (instr.op) { 'E' => { wx += instr.val; }, 'S' => { wy -= instr.val; }, 'W' => { wx -= instr.val; }, 'N' => { wy += instr.val; }, 'L' => { var turn = @mod(@divFloor(instr.val, 90), 4); switch (turn) { 0 => { }, 1 => { const tmp = wx; wx = -wy; wy = tmp; }, 2 => { wx = -wx; wy = -wy; }, 3 => { const tmp = wx; wx = wy; wy = -tmp; }, else => { unreachable; } } }, 'R' => { var turn = @mod(@divFloor(instr.val, 90), 4); switch (turn) { 0 => { }, 1 => { const tmp = wx; wx = wy; wy = -tmp; }, 2 => { wx = -wx; wy = -wy; }, 3 => { const tmp = wx; wx = -wy; wy = tmp; }, else => { unreachable; } } }, 'F' => { px += wx * instr.val; py += wy * instr.val; }, else => { unreachable; } } } std.debug.print("Day 12 - Solution 2: {}\n", .{abs(i32, px) + abs(i32, py)}); } }
2020/src/day_12.zig