code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const builtin = @import("builtin"); const native_arch = builtin.cpu.arch; // AArch64 is the only ABI (at the moment) to support f16 arguments without the // need for extending them to wider fp types. pub const F16T = if (native_arch.isAARCH64()) f16 else u16; pub fn __truncxfhf2(a: f80) callconv(.C) F16T { return @bitCast(F16T, trunc(f16, a)); } pub fn __truncxfff2(a: f80) callconv(.C) f32 { return trunc(f32, a); } pub fn __truncxfdf2(a: f80) callconv(.C) f64 { return trunc(f64, a); } inline fn trunc(comptime dst_t: type, a: f80) dst_t { @setRuntimeSafety(builtin.is_test); const dst_rep_t = std.meta.Int(.unsigned, @typeInfo(dst_t).Float.bits); const src_sig_bits = std.math.floatMantissaBits(f80) - 1; // -1 for the integer bit const dst_sig_bits = std.math.floatMantissaBits(dst_t); const src_exp_bias = 16383; const round_mask = (1 << (src_sig_bits - dst_sig_bits)) - 1; const halfway = 1 << (src_sig_bits - dst_sig_bits - 1); const dst_bits = @typeInfo(dst_t).Float.bits; const dst_exp_bits = dst_bits - dst_sig_bits - 1; const dst_inf_exp = (1 << dst_exp_bits) - 1; const dst_exp_bias = dst_inf_exp >> 1; const underflow = src_exp_bias + 1 - dst_exp_bias; const overflow = src_exp_bias + dst_inf_exp - dst_exp_bias; const dst_qnan = 1 << (dst_sig_bits - 1); const dst_nan_mask = dst_qnan - 1; // Break a into a sign and representation of the absolute value var a_rep = @ptrCast(*const std.math.F80Repr, &a).*; const sign = a_rep.exp & 0x8000; a_rep.exp &= 0x7FFF; a_rep.fraction &= 0x7FFFFFFFFFFFFFFF; var abs_result: dst_rep_t = undefined; if (a_rep.exp -% underflow < a_rep.exp -% overflow) { // The exponent of a is within the range of normal numbers in the // destination format. We can convert by simply right-shifting with // rounding and adjusting the exponent. abs_result = @as(dst_rep_t, a_rep.exp) << dst_sig_bits; abs_result |= @truncate(dst_rep_t, a_rep.fraction >> (src_sig_bits - dst_sig_bits)); abs_result -%= @as(dst_rep_t, src_exp_bias - dst_exp_bias) << dst_sig_bits; const round_bits = a_rep.fraction & round_mask; if (round_bits > halfway) { // Round to nearest abs_result += 1; } else if (round_bits == halfway) { // Ties to even abs_result += abs_result & 1; } } else if (a_rep.exp == 0x7FFF and a_rep.fraction != 0) { // a is NaN. // Conjure the result by beginning with infinity, setting the qNaN // bit and inserting the (truncated) trailing NaN field. abs_result = @intCast(dst_rep_t, dst_inf_exp) << dst_sig_bits; abs_result |= dst_qnan; abs_result |= @intCast(dst_rep_t, (a_rep.fraction >> (src_sig_bits - dst_sig_bits)) & dst_nan_mask); } else if (a_rep.exp >= overflow) { // a overflows to infinity. abs_result = @intCast(dst_rep_t, dst_inf_exp) << dst_sig_bits; } else { // a underflows on conversion to the destination type or is an exact // zero. The result may be a denormal or zero. Extract the exponent // to get the shift amount for the denormalization. const shift = src_exp_bias - dst_exp_bias - a_rep.exp; // Right shift by the denormalization amount with sticky. if (shift > src_sig_bits) { abs_result = 0; } else { const sticky = @boolToInt(a_rep.fraction << @intCast(u6, shift) != 0); const denormalized_significand = a_rep.fraction >> @intCast(u6, shift) | sticky; abs_result = @intCast(dst_rep_t, denormalized_significand >> (src_sig_bits - dst_sig_bits)); const round_bits = denormalized_significand & round_mask; if (round_bits > halfway) { // Round to nearest abs_result += 1; } else if (round_bits == halfway) { // Ties to even abs_result += abs_result & 1; } } } const result align(@alignOf(dst_t)) = abs_result | @as(dst_rep_t, sign) << dst_bits - 16; return @bitCast(dst_t, result); } pub fn __trunctfxf2(a: f128) callconv(.C) f80 { const src_sig_bits = std.math.floatMantissaBits(f128); const dst_sig_bits = std.math.floatMantissaBits(f80) - 1; // -1 for the integer bit // Various constants whose values follow from the type parameters. // Any reasonable optimizer will fold and propagate all of these. const src_bits = @typeInfo(f128).Float.bits; const src_exp_bits = src_bits - src_sig_bits - 1; const src_inf_exp = 0x7FFF; const src_inf = src_inf_exp << src_sig_bits; const src_sign_mask = 1 << (src_sig_bits + src_exp_bits); const src_abs_mask = src_sign_mask - 1; const round_mask = (1 << (src_sig_bits - dst_sig_bits)) - 1; const halfway = 1 << (src_sig_bits - dst_sig_bits - 1); const src_qnan = 1 << (src_sig_bits - 1); const src_nan_mask = src_qnan - 1; // Break a into a sign and representation of the absolute value const a_rep = @bitCast(u128, a); const a_abs = a_rep & src_abs_mask; const sign: u16 = if (a_rep & src_sign_mask != 0) 0x8000 else 0; var res: std.math.F80Repr align(16) = undefined; if (a_abs > src_inf) { // a is NaN. // Conjure the result by beginning with infinity, setting the qNaN // bit and inserting the (truncated) trailing NaN field. res.exp = 0x7fff; res.fraction = 0x8000000000000000; res.fraction |= @truncate(u64, (a_abs & src_qnan) << (src_sig_bits - dst_sig_bits)); res.fraction |= @truncate(u64, (a_abs & src_nan_mask) << (src_sig_bits - dst_sig_bits)); } else { // The exponent of a is within the range of normal numbers in the // destination format. We can convert by simply right-shifting with // rounding and adjusting the exponent. res.fraction = @truncate(u64, a_abs >> (src_sig_bits - dst_sig_bits)); res.exp = @truncate(u16, a_abs >> src_sig_bits); const round_bits = a_abs & round_mask; if (round_bits > halfway) { // Round to nearest const exp = @addWithOverflow(u64, res.fraction, 1, &res.fraction); res.exp += @boolToInt(exp); } else if (round_bits == halfway) { // Ties to even const exp = @addWithOverflow(u64, res.fraction, res.fraction & 1, &res.fraction); res.exp += @boolToInt(exp); } } res.exp |= sign; return @ptrCast(*const f80, &res).*; }
lib/std/special/compiler_rt/trunc_f80.zig
const std = @import("std"); const math = std.math; const windows = std.os.windows; const kernel32 = windows.kernel32; const INT = windows.INT; const BOOL = windows.BOOL; const CHAR = windows.CHAR; const SHORT = windows.SHORT; const DWORD = windows.DWORD; const WINAPI = windows.WINAPI; const LPVOID = windows.LPVOID; const HMODULE = windows.HMODULE; const HINSTANCE = windows.HINSTANCE; const vk_r_shift = 0xA1; const dll_process_attach = 1; extern "user32" fn GetAsyncKeyState(vKey: INT) callconv(WINAPI) SHORT; extern "kernel32" fn DisableThreadLibraryCalls(hLibModule: HMODULE) callconv(WINAPI) BOOL; const Vec3 = struct { x: f32, y: f32, z: f32, pub fn distance(self: Vec3, other: Vec3) f32 { return math.sqrt(math.pow(f32, other.x - self.x, 2.0) + math.pow(f32, other.y - self.y, 2.0) + math.pow(f32, other.z - self.z, 2.0)); } pub fn angle(self: Vec3, other: Vec3) Vec3 { return Vec3{ .x = -math.atan2(f32, other.x - self.x, other.y - self.y) / math.pi * 180.0, .y = math.asin((other.z - self.z) / self.distance(other)) * 180.0 / math.pi, .z = 0.0, }; } }; const Entity = struct { pad_0000: [48]CHAR, pos: Vec3, angle: Vec3, pad_0048: [47]CHAR, is_dead: bool, pad_0078: [280]CHAR, delay: i32, pad_0194: [788]CHAR, }; pub export fn DllMain(hinst_dll: HINSTANCE, fdw_reason: DWORD, _: LPVOID) BOOL { switch (fdw_reason) { dll_process_attach => { _ = DisableThreadLibraryCalls(@ptrCast(HMODULE, hinst_dll)); const optional_handle = kernel32.CreateThread(null, 0, entry, hinst_dll, 0, null); if (optional_handle) |handle| { _ = kernel32.CloseHandle(handle); } }, else => {}, } return 1; } export fn entry(_: *anyopaque) DWORD { const base_addr = @ptrToInt(kernel32.GetModuleHandleW(null).?); const local_entity = @intToPtr(**Entity, (base_addr + 0x002A3528)).*; const entity_list = @intToPtr(*u64, (base_addr + 0x346C90)); const entity_list_count = @intToPtr(*i32, (base_addr + 0x3472EC)); var enabled = false; while (true) { if ((GetAsyncKeyState(vk_r_shift) & 1) != 0) { enabled = !enabled; } if (!enabled or local_entity.*.is_dead) continue; var optional_target: ?*Entity = null; var lowest_coefficient: f32 = math.f32_max; var i: usize = 0; while (i < entity_list_count.*) { const entity = @intToPtr(**Entity, entity_list.* + i * 0x08).*; if (entity.*.is_dead) continue; const angle = local_entity.*.pos.angle(entity.*.pos).distance(local_entity.*.angle); const distance = local_entity.*.pos.distance(entity.*.pos); const coefficient = distance * 0.3 + angle * 0.7; if (coefficient < lowest_coefficient) { lowest_coefficient = coefficient; optional_target = entity; } i += 1; } if (optional_target) |target| { local_entity.*.angle = local_entity.*.pos.angle(target.*.pos); } } }
src/main.zig
const std = @import("std"); //! This contains the logic for errors //! Errors can be written to a writer compliant to std.io.writer interface pub const Error = struct { /// The formatted message fmt: []const u8, /// type of the error: Error, Warning, Info kind: ErrorType, /// index of the token which caused the error index: usize, const ErrorType = enum { err, info, warn, }; }; pub const Errors = struct { /// internal list, containing all errors /// call deinit() on `Errors` to free its memory list: std.ArrayListUnmanaged(Error), /// Allocator used to allocPrint error messages allocator: *std.mem.Allocator, /// Creates a new Errors object that can be catch errors and print them out to a writer pub fn init(allocator: *std.mem.Allocator) Errors { return .{ .list = std.ArrayListUnmanaged(Error){}, .allocator = allocator }; } /// Appends a new error to the error list pub fn add(self: *Errors, comptime fmt: []const u8, index: usize, kind: Error.ErrorType, args: anytype) !void { const msg = try std.fmt.allocPrint(self.allocator, fmt, args); errdefer self.allocator.free(msg); return self.list.append(self.allocator, .{ .fmt = msg, .kind = kind, .index = index, }); } /// Frees the memory of the errors pub fn deinit(self: *Errors) void { for (self.list.items) |err| { self.allocator.free(err.fmt); } self.list.deinit(self.allocator); self.* = undefined; } /// Consumes the errors and writes the errors to the writer interface /// source is required as we do not necessarily know the source when we init() `Errors` pub fn write(self: *Errors, source: []const u8, writer: anytype) !void { while (self.list.popOrNull()) |err| { defer self.allocator.free(err.fmt); const color_prefix = switch (err.kind) { .err => "\x1b[0;31m", .info => "\x1b[0;37m", .warn => "\x1b[0;36m", }; try writer.print("{s}error: \x1b[0m{s}\n", .{ color_prefix, err.fmt }); const start = findStart(source, err.index); const end = findEnd(source[err.index..]); //write the source code lines and point to token's index try writer.print("{s}\n", .{source[start .. err.index + end]}); try writer.writeByteNTimes('~', err.index - start); try writer.writeAll("\x1b[0;35m^\n\x1b[0m"); } } /// Finds the position of the first character of the token's index fn findStart(source: []const u8, index: usize) usize { var i = index; while (i != 0) : (i -= 1) if (source[i] == '\n') return i + 1; return 0; } /// finds the line ending in the given slice fn findEnd(slice: []const u8) usize { var count: usize = 0; for (slice) |c, i| count += if (c == '\n') return i else @as(usize, 1); return count; } };
src/error.zig
const std = @import("std"); const vector = @import("vector.zig"); const Vec4 = Vec4; const initPoint = vector.initPoint; const initVector = vector.initVector; const Mat4 = @import("matrix.zig").Mat4; const Canvas = @import("canvas.zig").Canvas; const Color = @import("color.zig").Color; const Pattern = @import("pattern.zig").Pattern; const canvasToPPM = @import("ppm.zig").canvasToPPM; const Shape = @import("shape.zig").Shape; const Ray = @import("ray.zig").Ray; const Material = @import("material.zig").Material; const PointLight = @import("light.zig").PointLight; const World = @import("world.zig").World; const Camera = @import("camera.zig").Camera; const calc = @import("calc.zig"); pub fn main() !void { // https://forum.raytracerchallenge.com/thread/4/reflection-refraction-scene-description var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var world = World.init(allocator); defer world.deinit(); var camera = Camera.init(900, 450, 1.152); const from = initVector(-2.6, 1.5, -3.9); const to = initVector(-0.6, 1, -0.8); const up = initVector(0, 1, 0); camera.transform = calc.viewTransform(from, to, up); world.light = PointLight{ .position = initPoint(-4.9, 4.9, -1), .intensity = Color.White, }; const wall_pattern = Pattern{ .pattern = .{ .stripe = .{ .a = Color.init(0.45, 0.45, 0.45), .b = Color.init(0.55, 0.55, 0.55) } }, .transform = Mat4.identity().scale(0.25, 0.25, 0.25).rotateY(1.5708), }; const wall_material = Material{ .pattern = wall_pattern, .ambient = 0, .diffuse = 0.4, .specular = 0, .reflective = 0.3, }; const floor_pattern = Pattern{ .pattern = .{ .checkers = .{ .a = Color.init(0.35, 0.35, 0.35), .b = Color.init(0.65, 0.65, 0.65) } }, .transform = Mat4.identity().rotateY(0.31415), }; const floor = Shape{ .material = .{ .pattern = floor_pattern, .specular = 0, .reflective = 0.4, }, .geo = .{ .plane = .{} }, }; try world.objects.append(floor); const ceiling = Shape{ .material = .{ .color = Color.init(0.8, 0.8, 0.8), .ambient = 0.3, .specular = 0, }, .transform = Mat4.identity().translate(0, 5, 0), .geo = .{ .plane = .{} }, }; try world.objects.append(ceiling); // west wall const west_wall = Shape{ .material = wall_material, .transform = Mat4.identity().rotateY(1.5708).rotateZ(1.5708).translate(-5, 0, 0), .geo = .{ .plane = .{} }, }; try world.objects.append(west_wall); // east wall const east_wall = Shape{ .material = wall_material, .transform = Mat4.identity().rotateY(1.5708).rotateZ(1.5708).translate(5, 0, 0), .geo = .{ .plane = .{} }, }; try world.objects.append(east_wall); // north wall const north_wall = Shape{ .material = wall_material, .transform = Mat4.identity().rotateX(1.5708).translate(0, 0, 5), .geo = .{ .plane = .{} }, }; try world.objects.append(north_wall); // south wall const south_wall = Shape{ .material = wall_material, .transform = Mat4.identity().rotateX(1.5708).translate(0, 0, -5), .geo = .{ .plane = .{} }, }; try world.objects.append(south_wall); // background balls try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.4, 0.4, 0.4).translate(4.6, 0.4, 1.0), .material = Material{ .color = Color.init(0.8, 0.5, 0.3), .shininess = 50, }, }); try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.3, 0.3, 0.3).translate(4.7, 0.3, 0.4), .material = Material{ .color = Color.init(0.9, 0.4, 0.5), .shininess = 50, }, }); try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.5, 0.5, 0.5).translate(-1, 0.5, 4.5), .material = Material{ .color = Color.init(0.4, 0.9, 0.6), .shininess = 50, }, }); try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.3, 0.3, 0.3).translate(-1.7, 0.3, 4.7), .material = Material{ .color = Color.init(0.4, 0.6, 0.9), .shininess = 50, }, }); // foreground balls // red sphere try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().translate(-0.6, 1, 0.6), .material = Material{ .color = Color.init(1.0, 0.3, 0.2), .specular = 0.4, .shininess = 5, }, }); // blue glass sphere try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.7, 0.7, 0.7).translate(0.6, 0.7, -0.6), .material = Material{ .color = Color.init(0, 0, 0.2), .ambient = 0, .diffuse = 0.4, .specular = 0.9, .shininess = 300, .reflective = 0.9, .transparency = 0.9, .refractive_index = 1.5, }, }); // green glass sphere try world.objects.append(Shape{ .geo = .{ .sphere = .{} }, .transform = Mat4.identity().scale(0.5, 0.5, 0.5).translate(-0.7, 0.5, -0.8), .material = Material{ .color = Color.init(0, 0.2, 0), .ambient = 0, .diffuse = 0.4, .specular = 0.9, .shininess = 300, .reflective = 0.9, .transparency = 0.9, .refractive_index = 1.5, }, }); var canvas = try camera.render(allocator, world); defer canvas.deinit(); const dir: std.fs.Dir = std.fs.cwd(); const file: std.fs.File = try dir.createFile("result.ppm", .{}); defer file.close(); try canvasToPPM(canvas, file.writer()); }
draw_world.zig
const std = @import("std"); const tests = &[_]Test{ .{ .success = false }, .{ .args = &[_][]const u8{"help"} }, Test.help(.parse), Test.hello(.parse, null, null), Test.help(.build), Test.hello(.build, null, null), Test.hello(.build, &[_][]const u8{"--format=compact"}, null), Test.ok(.build, "samples/fizzbuzz.wala", &[_][]const u8{"--format=compact"}, null), Test.help(.run), Test.hello(.run, null, "Hello, W0rld!\n"), Test.runSample("hello.wat", null, "Hello, W0rld!\n"), Test.runTestFlat("hello.wat", null, "Hello, W0rld!\n"), //FIXME: Test.ok(.run, "test/hello.wasm", null, "Hello, W0rld!\n"), Test.runSample("fib.wala", &[_][]const u8{ "--", "--invoke", "fib", "20" }, "6765\n"), Test.runTestFlat("fib.wat", &[_][]const u8{ "--", "--invoke", "fib", "20" }, "6765\n"), Test.runSample("gcd.wala", &[_][]const u8{ "--", "--invoke", "gcd", "132", "56" }, "4\n"), Test.runSample("gcd.wat", &[_][]const u8{ "--", "--invoke", "gcd", "132", "56" }, "4\n"), Test.runSample("pi.wala", &[_][]const u8{ "--", "--invoke", "pi", "1000000" }, "3.1415916535897743\n"), Test.runSampleContains("99-bottles-of-beer.wala", null, "1 bottle of beer."), Test.runSampleContains("fizzbuzz.wala", null, "Buzz Fizz 22"), Test.errTest(.parse, "FileNotFound"), Test.errTest(.parse, "TopLevelIndent"), Test.errTest(.parse, "IndentMismatch"), Test.errTest(.build, "TypeMismatch"), Test.ok(.build, "test/custom/importMem.wat", null, null), }; pub fn main() void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const argv = std.process.argsAlloc(gpa.allocator()) catch unreachable; defer std.process.argsFree(gpa.allocator(), argv); const run_cmd = argv[1..]; var n_ok: usize = 0; var progress: std.Progress = .{}; const root_node = progress.start("Test", tests.len) catch unreachable; for (tests) |task| { const test_name = task.name(gpa.allocator()) catch unreachable; defer gpa.allocator().free(test_name); var test_node = root_node.start(test_name, 0); test_node.activate(); progress.refresh(); const result = task.run(run_cmd, gpa.allocator()); test_node.end(); if (result) |_| { n_ok += 1; } else |err| { progress.log("{s}... FAIL ({s})\n", .{ test_name, @errorName(err) }); std.debug.dumpStackTrace(@errorReturnTrace().?.*); } } root_node.end(); if (n_ok == tests.len) { std.debug.print("All {} cases passed.\n", .{tests.len}); } else { std.debug.print("{} of {} cases passed.\n", .{ n_ok, tests.len }); std.process.exit(1); } } const Test = struct { const Do = enum { parse, build, run }; do: ?Do = null, on: ?[]const u8 = null, args: []const []const u8 = &[_][]u8{}, success: bool = true, output: ?[]const u8 = null, output_match: enum { equals, contains } = .equals, inline fn help(do: Do) Test { return .{ .do = do, .on = "--help" }; } inline fn hello(do: Do, args: ?[]const []const u8, output: ?[]const u8) Test { return ok(do, "samples/hello.wala", args, output); } inline fn ok(do: Do, comptime on: []const u8, args: ?[]const []const u8, output: ?[]const u8) Test { return .{ .do = do, .on = on, .args = args orelse &[_][]u8{}, .output = output }; } inline fn runSample(comptime on: []const u8, args: ?[]const []const u8, output: ?[]const u8) Test { return ok(.run, "samples/" ++ on, args, output); } inline fn runSampleContains(comptime on: []const u8, args: ?[]const []const u8, output: ?[]const u8) Test { var t = ok(.run, "samples/" ++ on, args, output); t.output_match = .contains; return t; } inline fn runTestFlat(comptime on: []const u8, args: ?[]const []const u8, output: ?[]const u8) Test { return ok(.run, "test/flat/" ++ on, args, output); } inline fn errTest(do: Do, comptime with: []const u8) Test { return .{ .success = false, .do = do, .on = "test/error/" ++ with ++ ".wala", .output = "error." ++ with, .output_match = .contains }; } fn name(self: Test, allocator: std.mem.Allocator) ![]const u8 { var args = std.ArrayList(u8).init(allocator); if (self.do) |do| { try args.appendSlice(@tagName(do)); try args.append(' '); } if (self.on) |on| { try args.appendSlice(on); try args.append(' '); } for (self.args) |arg| { try args.appendSlice(arg); try args.append(' '); } return args.toOwnedSlice(); } fn run(self: Test, cmd: []const []const u8, allocator: std.mem.Allocator) !void { var args = std.ArrayList([]const u8).init(allocator); defer args.deinit(); try args.appendSlice(cmd); if (self.do) |do| try args.append(@tagName(do)); if (self.on) |on| try args.append(on); try args.appendSlice(self.args); const result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = args.items }); defer allocator.free(result.stdout); defer allocator.free(result.stderr); const exit_code = switch (result.term) { .Exited => |code| code, else => return error.NotExited, }; if (exit_code != @boolToInt(!self.success)) return error.BadExitCode; if (self.output) |expect| { const out = if (self.success) result.stdout else result.stderr; if (!switch (self.output_match) { .equals => std.mem.eql(u8, out, expect), .contains => std.mem.indexOf(u8, out, expect) != null, }) try std.testing.expectEqualStrings(expect, out); } } };
test/cases.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const HashMap = std.StringHashMap; const bindings = @import("bindings.zig"); const c = bindings.c; const Sdl = bindings.Sdl; const Gl = bindings.Gl; const Imgui = bindings.Imgui; const Context = @import("context.zig").Context; const PixelBuffer = @import("basic_video.zig").PixelBuffer; const Console = @import("../console.zig").Console; pub const ImguiContext = struct { console: *Console(.{ .precision = .accurate, .method = .sdl }), windows: HashMap(Window), game_pixel_buffer: PixelBuffer, const FileDialogReason = enum { open_rom, }; pub fn init( parent_context: *Context(true), console: *Console(.{ .precision = .accurate, .method = .sdl }), ) !ImguiContext { Sdl.setWindowSize(.{ parent_context.window, 1920, 1080 }); Sdl.setWindowPosition(.{ parent_context.window, c.SDL_WINDOWPOS_CENTERED, c.SDL_WINDOWPOS_CENTERED }); _ = try Imgui.createContext(.{null}); try Imgui.sdl2InitForOpengl(.{ parent_context.window, parent_context.gl_context }); try Imgui.opengl3Init(.{"#version 130"}); Imgui.styleColorsDark(.{null}); var self = ImguiContext{ .console = console, .windows = HashMap(Window).init(parent_context.allocator), .game_pixel_buffer = try PixelBuffer.init(parent_context.allocator, 256, 240), }; self.game_pixel_buffer.scale = 3; errdefer self.deinit(parent_context.allocator); const game_window = Window.init( .{ .game_window = .{} }, "NES", Imgui.windowFlagsAlwaysAutoResize, ); try self.addWindow(game_window); return self; } pub fn deinit(self: *ImguiContext, allocator: *Allocator) void { var values = self.windows.valueIterator(); while (values.next()) |window| { window.deinit(allocator); } self.windows.deinit(); self.game_pixel_buffer.deinit(allocator); Imgui.opengl3Shutdown(); Imgui.sdl2Shutdown(); } fn getWindowAvailable(self: ImguiContext, name: []const u8) bool { if (self.windows.get(name)) |window| { return window.closed; } return true; } // TODO: very inefficient, not my focus right now fn makeWindowNameUnique(self: *ImguiContext, comptime name: []const u8) []const u8 { if (self.getWindowAvailable(name)) { const tagged = comptime if (std.mem.indexOf(u8, name, "##") != null) true else false; var new_name = comptime blk: { break :blk name ++ if (tagged) "00000" else "##00000"; }; const num_index = comptime if (tagged) name.len else name.len + 2; var i: u16 = 0; while (i < 65535) : (i += 1) { if (self.getWindowAvailable(new_name)) { return new_name; } std.fmt.bufPrintIntToSlice( new_name[num_index..], i, 10, .lower, .{ .width = 5, .fill = '0' }, ); } @panic("Someone really went and made 65535 instances of the same window"); } else { return name; } } fn addWindow(self: *ImguiContext, window: Window) !void { return self.windows.put(window.title, window); } fn getParentContext(self: *ImguiContext) *Context(true) { return @fieldParentPtr(Context(true), "extension_context", self); } pub fn getGamePixelBuffer(self: *ImguiContext) *PixelBuffer { return &self.game_pixel_buffer; } pub fn handleEvent(_: *ImguiContext, event: c.SDL_Event) bool { _ = Imgui.sdl2ProcessEvent(.{&event}); switch (event.type) { c.SDL_KEYUP => switch (event.key.keysym.sym) { c.SDLK_q => return false, else => {}, }, c.SDL_QUIT => return false, else => {}, } return true; } pub fn draw(self: *ImguiContext) !void { Imgui.opengl3NewFrame(); Imgui.sdl2NewFrame(); Imgui.newFrame(); try self.drawMainMenu(); var values = self.windows.valueIterator(); while (values.next()) |window| { try window.draw(self); } try Gl.bindTexture(.{ c.GL_TEXTURE_2D, 0 }); Gl.clearColor(.{ 0x00, 0x00, 0x00, 0xff }); try Gl.clear(.{c.GL_COLOR_BUFFER_BIT}); Imgui.render(); Imgui.opengl3RenderDrawData(.{try Imgui.getDrawData()}); } fn drawMainMenu(self: *ImguiContext) !void { if (!Imgui.beginMainMenuBar()) { return; } if (Imgui.beginMenu(.{ "File", true })) { if (Imgui.menuItem(.{ "Open Rom", null, false, true })) { try self.openFileDialog(.open_rom); } Imgui.endMenu(); } Imgui.endMainMenuBar(); } fn openFileDialog(self: *ImguiContext, comptime reason: FileDialogReason) !void { const name = "Choose a file##" ++ @tagName(reason); if (!self.getWindowAvailable(name)) { return; } const file_dialog = Window.init( .{ .file_dialog = .{} }, name, Imgui.windowFlagsNone, ); try self.addWindow(file_dialog); } }; const Window = struct { const Flags = @TypeOf(c.ImGuiWindowFlags_None); impl: WindowImpl, title: []const u8, flags: Flags, closed: bool = false, fn init(impl: WindowImpl, title: []const u8, flags: Flags) Window { return Window{ .impl = impl, .title = title, .flags = flags, }; } fn deinit(self: Window, allocator: *Allocator) void { self.impl.deinit(allocator); } fn draw(self: *Window, context: *ImguiContext) !void { if (self.closed) { return; } const c_title = @ptrCast([*]const u8, self.title); if (Imgui.begin(.{ c_title, null, self.flags })) { self.closed = !(try self.impl.draw(context)); } Imgui.end(); } }; const WindowImpl = union(enum) { game_window: GameWindow, file_dialog: FileDialog, fn deinit(self: WindowImpl, allocator: *Allocator) void { _ = allocator; switch (self) { .game_window => {}, .file_dialog => {}, } } fn draw(self: WindowImpl, context: *ImguiContext) !bool { switch (self) { .game_window => |x| return x.draw(context.*), .file_dialog => |x| return x.draw(context), } } }; const GameWindow = struct { fn draw(_: GameWindow, context: ImguiContext) !bool { const pixel_buffer = &context.game_pixel_buffer; try Gl.bindTexture(.{ c.GL_TEXTURE_2D, pixel_buffer.texture }); try pixel_buffer.copyTextureInternal(); const texture_ptr = @intToPtr(*c_void, pixel_buffer.texture); const f_width = @intToFloat(f32, pixel_buffer.width * pixel_buffer.scale); const f_height = @intToFloat(f32, pixel_buffer.height * pixel_buffer.scale); const size = .{ .x = f_width, .y = f_height }; Imgui.image(.{ texture_ptr, size, .{ .x = 0, .y = 0 }, .{ .x = 1, .y = 1 }, .{ .x = 1, .y = 1, .z = 1, .w = 1 }, .{ .x = 0, .y = 0, .z = 0, .w = 0 }, }); return true; } }; const FileDialog = struct { fn draw(_: FileDialog, context: *ImguiContext) !bool { if (Imgui.button(.{ "Play golf lol", .{ .x = 0, .y = 0 } })) { context.console.clearState(); try context.console.loadRom( "roms/no-redist/NES Open Tournament Golf (USA).nes", ); return false; } return true; } };
src/sdl/imgui.zig
const print = std.debug.print; const std = @import("std"); const os = std.os; const assert = std.debug.assert; const mem = @import("std").mem; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; pub fn main() anyerror!void { std.log.info("All your codebase are belong to us.", .{}); print("Hello, {s}!\n", .{"world"}); // optional var optional_value: ?[]const u8 = null; assert(optional_value == null); print("\noptional 1\ntype: {s}\nvalue: {s}\n", .{ @typeName(@TypeOf(optional_value)), optional_value, }); optional_value = "hi ł \u{1f4a9} \x10ffff"; assert(optional_value != null); print("\noptional 2\ntype: {s}\nvalue: {s}\n", .{ @typeName(@TypeOf(optional_value)), optional_value, }); const multiline_string_literal = \\this is \\multiline string literal ; print("multiline:\n{s}\n", .{multiline_string_literal}); // 2^128 - 1 var max_i16_decimal: i16 = 32767; // 2^15 - 1 print("max_i16_decimal: {}\n", .{max_i16_decimal}); var max_i16_binary: i16 = 0b111_1111_1111_1111; print("max_i16_binary: {}\n", .{max_i16_binary}); var min_i16_decimal: i16 = -32768; print("min_i16_decimal: {}\n", .{min_i16_decimal}); // var min_i16_binary: i16 = -0b0100_0000_0000_0000; // var min_i16_binary: i16 = -0b1111_1111_1111_1111; var min_i16_binary: i16 = -0b1000_0000_0000_0000; print("min_i16_binary: {}\n", .{min_i16_binary}); // var var3: i16 = -0b1000_0000_0000_0001; // print("var3: {}\n", .{var3}); var var4: i16 = -0b1000_0000_0000_0000 + 1; print("var4: {}\n", .{var4}); var var5: i16 = -0b0111_1111_1111_1111; print("var5: {}\n", .{var5}); var var6: i16 = 0b0111_1111_1111_1111; print("var6: {}\n", .{var6}); var var7: i16 = -0b1000_0000_0000_0000; print("var7: {}\n", .{var7}); var var8: i16 = 0b111_1111_1111_1111; print("var8: {}\n", .{var8}); var max_u16_decimal: u16 = 65535; var max_u16_binary: u16 = 0b1111_1111_1111_1111; print("max_u16_binary: {}\n", .{max_u16_binary}); print("std.math.maxInt(i16): {}\n", .{std.math.maxInt(i16)}); print("std.math.maxInt(i16) binary: {b}\n", .{std.math.maxInt(i16)}); print("std.math.minInt(i16): {}\n", .{std.math.minInt(i16)}); print("std.math.minInt(i16) binary: {b}\n", .{std.math.minInt(i16)}); print("std.math.minInt(i16) binary: {b}\n", .{std.math.minInt(i16) + 1}); print("std.math.maxInt(u4): {}\n", .{std.math.maxInt(u4)}); print("std.math.maxInt(u8): {}\n", .{std.math.maxInt(u8)}); print("std.math.maxInt(u16): {}\n", .{std.math.maxInt(u16)}); print("std.math.maxInt(u32): {}\n", .{std.math.maxInt(u32)}); print("std.math.maxInt(u64): {}\n", .{std.math.maxInt(u64)}); print("std.math.minInt(u64): {}\n", .{std.math.minInt(u64)}); print("std.math.minInt(i64): {}\n", .{std.math.minInt(i64)}); // var var1: i16 = -65535; // var max_u32_binary: u16 = 0b1111_1111_1111_1111_1111_1111_1111_1111; // std.math.maxInt(u32) // 2^127 - 1 // var max_i128_decimal: i128 = -170141183460469231731687303715884105727; // const a = [_]u32{ 1, 2 } ++ [_]u32{ 3, 4 } == &[_]u32{ 1, 2, 3, 4 }; // print("{}", .{a}); print("{}\n", .{@as(i2, -0b10)}); print("{b}\n", .{@as(i2, -0b10)}); print("std.math.minInt(i2): {}\n", .{std.math.minInt(i2)}); print("{b}\n", .{@as(i2, -0b01)}); print("{b}\n", .{@as(i4, -0b1000)}); print("std.math.minInt(i4): {b}\n", .{std.math.minInt(i4)}); print("std.math.minInt(i4): {}\n", .{std.math.minInt(i4)}); print("std.math.minInt(i4)+1: {b}\n", .{std.math.minInt(i4) + 1}); print("std.math.minInt(i4)+1: {}\n", .{std.math.minInt(i4) + 1}); print("std.math.minInt(i4)+2: {b}\n", .{std.math.minInt(i4) + 2}); print("std.math.minInt(i4)+2: {}\n", .{std.math.minInt(i4) + 2}); print("std.math.minInt(i1): {}\n", .{std.math.minInt(i1)}); print("std.math.maxInt(i1): {}\n", .{std.math.maxInt(i1)}); print("std.math.maxInt(i0): {}\n", .{std.math.maxInt(i0)}); const array1 = [_]u32{ 1, 2 }; const array2 = [_]u32{ 3, 4 }; const together = array1 ++ array2; expect(mem.eql(u32, &together, &[_]u32{ 1, 2, 3, 4 })); print("{any}\n", .{together}); print("{s}\n", .{"ab" ** 3}); const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' }; expect(message.len == 5); print("{any}\n", .{message.len}); const same_message = "hello"; print("{any}\n", .{mem.eql(u8, &message, same_message)}); expect(mem.eql(u8, &message, same_message)); var integers = [_]i32{ 1, 2 }; print("{any}\n", .{integers}); print("{any}\n", .{integers[0]}); var some_integers: [100]i32 = undefined; for (some_integers) |*item, i| { item.* = @intCast(i32, i); } const more_integers: [4]u8 = .{ 12, 12, 32, 5 }; print("{any}\n", .{more_integers}); print("S.x: {}\n", .{S.x}); // can specify the tag type. const Value = enum(u2) { zero, one, two, four, }; expect(@enumToInt(Value.four) == 3); var_file_scope += 1; print("var_file_scope: {}\n", .{var_file_scope}); var buffer: [100]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator; const digits = try decimals(allocator, 345); print("{any}\n", .{digits.items}); print("{}\n", .{std.Target.current.os.tag}); // https://zigforum.org/t/defining-slice-of-mutable-array-literal-in-one-statement/218/13 var slice_of_mutable_array_literal: []u8 = blk: { var arr = [_]u8{ 1, 2, 3 }; break :blk arr[0..]; }; print("{any}\n", .{slice_of_mutable_array_literal}); const two_nested_blocks = blk: { { const a: i32 = 2; break :blk a; } }; print("{}\n", .{two_nested_blocks}); var two_nested_blocks_var: i32 = blk: { { var a: i32 = 2; break :blk a; } }; print("{}\n", .{two_nested_blocks_var}); var cond = true; var many_nested_blocks: usize = blk: { var a: usize = 1; { var b: usize = 2; { var c: usize = 3; if (cond) break :blk c; } if (cond) break :blk b; } break :blk a; }; print("{}\n", .{many_nested_blocks}); const s = [_][7]i32{ [_]i32{ 08, 02, 22, 97, 38, 15, 00 }, [_]i32{ 49, 49, 99, 40, 17, 81, 18 }, [_]i32{ 81, 49, 31, 73, 55, 79, 14 }, [_]i32{ 52, 70, 95, 23, 04, 60, 11 }, [_]i32{ 22, 31, 16, 71, 51, 67, 63 }, [_]i32{ 24, 47, 32, 60, 99, 03, 45 }, [_]i32{ 32, 98, 81, 28, 64, 23, 67 }, [_]i32{ 67, 26, 20, 68, 02, 62, 12 }, [_]i32{ 24, 55, 58, 05, 66, 73, 99 }, [_]i32{ 21, 36, 23, 09, 75, 00, 76 }, }; const x = .{ .y = &.{ .z = 10 } }; print("x: {}\n", x); interger_overflow(); const thing1 = 1; const thing2 = 2; @call(.{}, call_bypasses_a_tuple, .{ thing1, thing2 }); print("{d}, {d}\n", .{11} ++ .{22}); // check that the third bit is true? 0b111101101 & 0b000000100 == 0b000000100 // (1 shifted left 2 times = 3rd bit) print("3rd bit: {b}\n", .{1 << 2}); print("0b111101101 & 0b000000100: {b}\n", .{0b111101101 & 0b000000100}); print("0b111101101 & 1 << 2: {b}\n", .{0b111101101 & 1 << 2}); print("0b111101101 & 1 << 2: 0b{b:0>9}\n", .{0b111101101 & 1 << 2}); // AstroKing // I work mostly on C for low level fimware and embedded projects. I am having some trouble with casting rules. I want to call rand() (returns c_int type). I then @rem on the result with 0xFF to get a random number between 0 and 0xFE. I want to do this 3 times to get random values for R G and B for getting a random color. // https://www.reddit.com/r/Zig/comments/cdw88t/does_zig_have_random_number_and_random_string/ // https://ziglang.org/documentation/master/std/#std;rand // https://ziglearn.org/chapter-4/#linking-libc // zig build-exe src/main -lc // zig build-exe src/main --library c // The CLI now accepts -l parameters as an alias for --library. As an example, one may specify -lc rather than --library c // https://ziglang.org/download/0.5.0/release-notes.html // https://github.com/ziglang/zig/blob/6fc822a9481c0d2c8b37f26f41be603dd77ab5a4/lib/libcxx/include/stdlib.h cstd.srand(@intCast(u32, time.time(0))); const rand = cstd.rand(); print("rand: {x}\n", .{rand}); print("rand: {d}\n", .{rand}); print("0xFF: {d}\n", .{0xFF}); const R_int = @rem(rand, 0xFF); const R_hex = @bitCast(u8, @truncate(i8, R_int)); print("R_hex: {x}\n", .{R_hex}); print("R_hex: {d}\n", .{R_hex}); const R_hex2 = @truncate(u8, @bitCast(c_uint, R_int)); print("R_hex2: {x}\n", .{R_hex}); var i: usize = 0; while (i <= 10) { std.debug.warn("{} ", .{@rem(cstd.rand(), 100) + 1}); i += 1; } } const time = @cImport(@cInclude("time.h")); const cstd = @cImport(@cInclude("stdlib.h")); fn interger_overflow() void { var i: u8 = 1; // panic: integer overflow // var x: u8 = 255 + i; // this works var y: u8 = 255 - i + 1; print("y: {}\n", .{y}); } fn call_bypasses_a_tuple(thing1: i32, thing2: i32) void { print("{d}, {d}\n", .{ thing1, thing2 }); } var var_file_scope: i32 = 1; const S = struct { var x: i32 = 1234; }; fn foo() void { var y: i32 = 6587; y += 1; } fn foo2() i32 { S.x += 1; return S.x; } test "assignment" { foo(); } const expect = std.testing.expect; test "namespaced global variable" { expect(foo2() == 1235); expect(foo2() == 1236); } // https://web.archive.org/web/20210301143402/https://medium.com/swlh/zig-the-introduction-dcd173a86975 fn decimals(alloc: *Allocator, n: u32) !ArrayList(u32) { var x = n; var digits = ArrayList(u32).init(alloc); errdefer digits.deinit(); while (x >= 10) { digits.append(x % 10) catch |err| return err; x = x / 10; } digits.append(x) catch |err| return err; return digits; }
src/main.zig
const builtin = @import("builtin"); const std = @import("std"); pub const BackendAPI = enum { default, opengl, d3d11, }; pub fn usingBackendAPI(comptime backend_api: BackendAPI) type { return struct { // Graphics API abstraction pub const backend = switch (backend_api) { .default => switch (builtin.os.tag) { .linux => @import("opengl.zig"), .windows => @import("d3d11.zig"), else => @compileError("Unsupported target"), }, .opengl => @import("opengl.zig"), .d3d11 => @import("d3d11.zig"), }; pub const VertexBuffer = @import("buffers.zig").withBackend(backend).VertexBuffer; pub const Texture2d = @import("textures.zig").withBackend(backend).Texture2d; const common = @import("common.zig"); pub const ShaderProgramHandle = common.ShaderProgramHandle; pub const ConstantBufferHandle = common.ConstantBufferHandle; pub const VertexBufferHandle = common.VertexBufferHandle; pub const VertexLayoutHandle = common.VertexLayoutHandle; pub const RasteriserStateHandle = common.RasteriserStateHandle; pub const BlendStateHandle = common.BlendStateHandle; pub const TextureHandle = common.TextureHandle; pub const SamplerStateHandle = common.SamplerStateHandle; pub const VertexLayoutDesc = common.VertexLayoutDesc; pub const TextureFormat = common.TextureFormat; // Linear maths pub const zmath = @import("zmath"); pub const F32x4 = zmath.F32x4; pub const Matrix = zmath.Mat; pub const identityMatrix = zmath.identity; pub const orthographic = zmath.orthographicLh; // Module initilisation pub var builtin_pipeline_resources: struct { uniform_colour_verts: PipelineResources, textured_verts_mono: PipelineResources, textured_verts: PipelineResources, } = undefined; pub var builtin_vertex_buffers: struct { pos: VertexBuffer(Vertex), pos_uv: VertexBuffer(TexturedVertex), } = undefined; pub const ShaderConstants = extern struct { mvp: Matrix, colour: Colour, }; pub var debugfont_texture: Texture2d = undefined; pub fn init(allocator: std.mem.Allocator, platform: anytype) !void { try backend.init(platform, allocator); errdefer backend.deinit(); debugfont_texture = try Texture2d.fromPBM(allocator, @embedFile("../data/debugfont.pbm")); builtin_vertex_buffers.pos = try VertexBuffer(Vertex).init(1e3); builtin_vertex_buffers.pos_uv = try VertexBuffer(TexturedVertex).init(1e3); { // create builtin uniform_colour_verts pipeline const vertex_layout_desc = VertexLayoutDesc{ .entries = &[_]VertexLayoutDesc.Entry{ .{ .buffer_handle = builtin_vertex_buffers.pos.handle, .attributes = Vertex.getLayoutAttributes(), .offset = 0, }, }, }; builtin_pipeline_resources.uniform_colour_verts = .{ .program = try backend.createUniformColourShader(), .vertex_layout = .{ .handle = try backend.createVertexLayout(vertex_layout_desc), .desc = vertex_layout_desc, }, .rasteriser_state = try backend.createRasteriserState(), .blend_state = try backend.createBlendState(), // TODO(hazeycode): create constant buffer of exactly the required size .constant_buffer = try backend.createConstantBuffer(0x1000), }; } { // create builtin uniform_colour_verts pipeline const vertex_layout_desc = VertexLayoutDesc{ .entries = &[_]VertexLayoutDesc.Entry{ .{ .buffer_handle = builtin_vertex_buffers.pos_uv.handle, .attributes = TexturedVertex.getLayoutAttributes(), .offset = 0, }, }, }; builtin_pipeline_resources.textured_verts_mono = .{ .program = try backend.createTexturedVertsMonoShader(), .vertex_layout = .{ .handle = try backend.createVertexLayout(vertex_layout_desc), .desc = vertex_layout_desc, }, .rasteriser_state = try backend.createRasteriserState(), .blend_state = try backend.createBlendState(), // TODO(hazeycode): create constant buffer of exactly the required size .constant_buffer = try backend.createConstantBuffer(0x1000), }; } { // create builtin uniform_colour_verts pipeline const vertex_layout_desc = VertexLayoutDesc{ .entries = &[_]VertexLayoutDesc.Entry{ .{ .buffer_handle = builtin_vertex_buffers.pos_uv.handle, .attributes = TexturedVertex.getLayoutAttributes(), .offset = 0, }, }, }; builtin_pipeline_resources.textured_verts = .{ .program = try backend.createTexturedVertsShader(), .vertex_layout = .{ .handle = try backend.createVertexLayout(vertex_layout_desc), .desc = vertex_layout_desc, }, .rasteriser_state = try backend.createRasteriserState(), .blend_state = try backend.createBlendState(), // TODO(hazeycode): create constant buffer of exactly the required size .constant_buffer = try backend.createConstantBuffer(0x1000), }; } } pub fn deinit() void { backend.deinit(); } // Core DrawList API pub fn beginDrawing(allocator: std.mem.Allocator) !DrawList { try builtin_vertex_buffers.pos.map(); builtin_vertex_buffers.pos.clear(false); try builtin_vertex_buffers.pos_uv.map(); builtin_vertex_buffers.pos_uv.clear(false); return DrawList{ .entries = std.ArrayList(DrawList.Entry).init(allocator), }; } pub fn setViewport(draw_list: *DrawList, viewport: Viewport) !void { try draw_list.entries.append(.{ .set_viewport = viewport, }); } pub fn clearViewport(draw_list: *DrawList, colour: Colour) !void { try draw_list.entries.append(.{ .clear_viewport = colour, }); } pub fn bindPipelineResources(draw_list: *DrawList, resources: PipelineResources) !void { try draw_list.entries.append(.{ .bind_pipeline_resources = resources, }); } pub fn setProjectionTransform(draw_list: *DrawList, transform: Matrix) !void { try draw_list.entries.append(.{ .set_projection_transform = transform, }); } pub fn setViewTransform(draw_list: *DrawList, transform: Matrix) !void { try draw_list.entries.append(.{ .set_view_transform = transform, }); } pub fn setModelTransform(draw_list: *DrawList, transform: Matrix) !void { try draw_list.entries.append(.{ .set_model_transform = transform, }); } pub fn setColour(draw_list: *DrawList, colour: Colour) !void { try draw_list.entries.append(.{ .set_colour = colour, }); } pub fn bindTexture(draw_list: *DrawList, slot: u32, texture: Texture2d) !void { try draw_list.entries.append(.{ .bind_texture = .{ .slot = slot, .texture = texture, }, }); } pub fn draw(draw_list: *DrawList, vertex_offset: u32, vertex_count: u32) !void { try draw_list.entries.append(.{ .draw = .{ .vertex_offset = vertex_offset, .vertex_count = vertex_count, }, }); } pub fn submitDrawList(draw_list: *DrawList) !void { var model = identityMatrix(); var view = identityMatrix(); var projection = identityMatrix(); var current_colour = Colour.white; var constant_buffer_handle: ConstantBufferHandle = 0; builtin_vertex_buffers.pos.unmap(); builtin_vertex_buffers.pos_uv.unmap(); for (draw_list.entries.items) |entry| { switch (entry) { .set_viewport => |viewport| { backend.setViewport(viewport.x, viewport.y, viewport.width, viewport.height); }, .clear_viewport => |colour| { backend.clearWithColour(colour.r, colour.g, colour.b, colour.a); }, .set_projection_transform => |transform| { projection = transform; }, .set_view_transform => |transform| { view = transform; }, .set_model_transform => |transform| { model = transform; }, .set_colour => |colour| { current_colour = colour; }, .bind_pipeline_resources => |resources| { backend.setShaderProgram(resources.program); backend.bindVertexLayout(resources.vertex_layout.handle); backend.setRasteriserState(resources.rasteriser_state); backend.setBlendState(resources.blend_state); backend.setConstantBuffer(resources.constant_buffer); constant_buffer_handle = resources.constant_buffer; }, .bind_texture => |desc| { backend.bindTexture(desc.slot, desc.texture.handle); }, .draw => |desc| { try backend.updateShaderConstantBuffer( constant_buffer_handle, std.mem.asBytes(&.{ .mvp = zmath.mul(zmath.mul(model, view), projection), .colour = current_colour, }), ); backend.draw(desc.vertex_offset, desc.vertex_count); }, } } if (builtin.mode == .Debug) { try backend.logDebugMessages(); } } // High-level DrawList API pub fn drawUniformColourVerts( draw_list: *DrawList, resources: PipelineResources, colour: Colour, vertices: []const Vertex, ) !void { const vert_offset = builtin_vertex_buffers.pos.append(vertices); try bindPipelineResources(draw_list, resources); try setColour(draw_list, colour); try draw(draw_list, vert_offset, @intCast(u32, vertices.len)); } pub fn drawTexturedVerts( draw_list: *DrawList, resources: PipelineResources, texture: Texture2d, vertices: []const TexturedVertex, ) !void { const vert_offset = builtin_vertex_buffers.pos_uv.append(vertices); try bindPipelineResources(draw_list, resources); try bindTexture(draw_list, 0, texture); try draw(draw_list, vert_offset, @intCast(u32, vertices.len)); } pub fn drawTexturedQuad( draw_list: *DrawList, resources: PipelineResources, args: struct { texture: Texture2d, uv_rect: Rect = .{ .min_x = 0, .min_y = 0, .max_x = 1, .max_y = 1, }, }, ) !void { const width = @intToFloat(f32, args.texture.height); const height = @intToFloat(f32, args.texture.width); const aspect_ratio = width / height; const rect = Rect{ .min_x = -1, .min_y = 1 * aspect_ratio, .max_x = 1, .max_y = -1 * aspect_ratio, }; try drawTexturedVerts( draw_list, resources, args.texture, &rect.texturedVertices(args.uv_rect), ); } // Rendering Primitives /// pub const DrawList = struct { pub const Entry = union(enum) { set_viewport: Viewport, clear_viewport: Colour, bind_pipeline_resources: PipelineResources, set_projection_transform: Matrix, set_view_transform: Matrix, set_model_transform: Matrix, set_colour: Colour, bind_texture: struct { slot: u32, texture: Texture2d, }, draw: struct { vertex_offset: u32, vertex_count: u32, }, }; entries: std.ArrayList(Entry), }; /// pub const PipelineResources = struct { program: ShaderProgramHandle, vertex_layout: VertexLayout, constant_buffer: ConstantBufferHandle, blend_state: BlendStateHandle, rasteriser_state: RasteriserStateHandle, }; /// pub const VertexLayout = struct { handle: VertexLayoutHandle, desc: VertexLayoutDesc, }; /// pub const Vertex = extern struct { pos: [3]f32, pub fn getLayoutAttributes() []const VertexLayoutDesc.Entry.Attribute { return &[_]VertexLayoutDesc.Entry.Attribute{ .{ .format = .f32x3 }, }; } }; pub const VertexIndex = u16; pub const VertexUV = [2]f32; pub const TexturedVertex = extern struct { pos: [3]f32, uv: VertexUV, pub fn getLayoutAttributes() []const VertexLayoutDesc.Entry.Attribute { return &[_]VertexLayoutDesc.Entry.Attribute{ .{ .format = .f32x3 }, .{ .format = .f32x2 }, }; } }; /// pub const Viewport = struct { x: u16, y: u16, width: u16, height: u16 }; pub const Colour = extern struct { r: f32, g: f32, b: f32, a: f32, pub const black = fromRGB(0, 0, 0); pub const white = fromRGB(1, 1, 1); pub const red = fromRGB(1, 0, 0); pub const orange = fromRGB(1, 0.5, 0); pub fn fromRGB(r: f32, g: f32, b: f32) Colour { return .{ .r = r, .g = g, .b = b, .a = 1 }; } pub fn fromRGBA(r: f32, g: f32, b: f32, a: f32) Colour { return .{ .r = r, .g = g, .b = b, .a = a }; } /// Returns a Colour for a given hue, saturation and value /// h, s, v are assumed to be in the range 0...1 pub fn fromHSV(h: f32, s: f32, v: f32) Colour { // Modified version of HSV TO RGB from here: https://www.tlbx.app/color-converter // TODO(hazeycode): compare performance & codegen of this vs zmath.hsvToRgb const hp = (h * 360) / 60; const c = v * s; const x = c * (1 - @fabs(@mod(hp, 2) - 1)); const m = v - c; if (hp <= 1) { return Colour.fromRGB(c + m, x + m, m); } else if (hp <= 2) { return Colour.fromRGB(x + m, c + m, m); } else if (hp <= 3) { return Colour.fromRGB(m, c + m, x + m); } else if (hp <= 4) { return Colour.fromRGB(m, x + m, c + m); } else if (hp <= 5) { return Colour.fromRGB(x + m, m, c + m); } else if (hp <= 6) { return Colour.fromRGB(c + m, m, x + m); } else { std.debug.assert(false); return Colour.fromRGB(0, 0, 0); } } }; pub const Rect = extern struct { min_x: f32, min_y: f32, max_x: f32, max_y: f32, pub fn vertices(self: Rect) [6]Vertex { return [_]Vertex{ .{ .pos = .{ self.min_x, self.min_y, 0.0 } }, .{ .pos = .{ self.min_x, self.max_y, 0.0 } }, .{ .pos = .{ self.max_x, self.max_y, 0.0 } }, .{ .pos = .{ self.max_x, self.max_y, 0.0 } }, .{ .pos = .{ self.max_x, self.min_y, 0.0 } }, .{ .pos = .{ self.min_x, self.min_y, 0.0 } }, }; } pub fn texturedVertices(self: Rect, uv_rect: Rect) [6]TexturedVertex { return [_]TexturedVertex{ TexturedVertex{ .pos = .{ self.min_x, self.min_y, 0.0 }, .uv = .{ uv_rect.min_x, uv_rect.min_y }, }, TexturedVertex{ .pos = .{ self.min_x, self.max_y, 0.0 }, .uv = .{ uv_rect.min_x, uv_rect.max_y }, }, TexturedVertex{ .pos = .{ self.max_x, self.max_y, 0.0 }, .uv = .{ uv_rect.max_x, uv_rect.max_y }, }, TexturedVertex{ .pos = .{ self.max_x, self.max_y, 0.0 }, .uv = .{ uv_rect.max_x, uv_rect.max_y }, }, TexturedVertex{ .pos = .{ self.max_x, self.min_y, 0.0 }, .uv = .{ uv_rect.max_x, uv_rect.min_y }, }, TexturedVertex{ .pos = .{ self.min_x, self.min_y, 0.0 }, .uv = .{ uv_rect.min_x, uv_rect.min_y }, }, }; } pub fn containsPoint(self: Rect, x: f32, y: f32) bool { return (x >= self.min_x and x <= self.max_x and y >= self.min_y and y <= self.max_y); } pub fn inset(self: Rect, left: f32, right: f32, top: f32, bottom: f32) Rect { return .{ .min_x = self.min_x + left, .max_x = self.max_x - right, .min_y = self.min_y + top, .max_y = self.max_y - bottom, }; } }; /// pub const DebugGUI = struct { allocator: std.mem.Allocator, draw_list: *DrawList, canvas_width: f32, canvas_height: f32, cur_x: f32, cur_y: f32, text_verts: std.ArrayList(TexturedVertex), uniform_colour_verts: std.ArrayList(Vertex), state: *State, const inset = 4; const line_spacing = 4; // values for builtin debugfont const glyph_width = 7; const glyph_height = 12; pub const ElemId = u32; pub const State = struct { input: Input = .{}, hover_id: ElemId = 0, active_id: ElemId = 0, keyboard_focus: ElemId = 0, text_cur_x: f32 = 0, text_cur_y: f32 = 0, }; pub const Input = struct { mouse_btn_down: bool = false, mouse_btn_was_pressed: bool = false, mouse_btn_was_released: bool = false, mouse_x: f32 = undefined, mouse_y: f32 = undefined, /// Optional helper fn for mapping brucelib.platform.FrameInput to DebugGUI.Input /// `user_input` can be any weakly conforming type pub fn mapPlatformInput(self: *Input, user_input: anytype) void { self.mouse_x = @intToFloat(f32, user_input.mouse_position.x); self.mouse_y = @intToFloat(f32, user_input.mouse_position.y); self.mouse_btn_was_pressed = false; self.mouse_btn_was_released = false; for (user_input.mouse_button_events) |mouse_ev| { if (mouse_ev.button != .left) continue; switch (mouse_ev.action) { .press => { self.mouse_btn_was_pressed = true; self.mouse_btn_down = true; }, .release => { self.mouse_btn_was_released = true; self.mouse_btn_down = false; }, } } } }; pub fn begin( allocator: std.mem.Allocator, draw_list: *DrawList, canvas_width: f32, canvas_height: f32, state: *State, ) !DebugGUI { const projection = orthographic(canvas_width, canvas_height, 0, 1); try setProjectionTransform(draw_list, projection); const view = zmath.mul( zmath.translation(-canvas_width / 2, -canvas_height / 2, 0), zmath.scaling(1, -1, 1), ); try setViewTransform(draw_list, view); return DebugGUI{ .allocator = allocator, .draw_list = draw_list, .canvas_width = canvas_width, .canvas_height = canvas_height, .cur_x = @intToFloat(f32, inset), .cur_y = @intToFloat(f32, inset), .text_verts = std.ArrayList(TexturedVertex).init(allocator), .uniform_colour_verts = std.ArrayList(Vertex).init(allocator), .state = state, }; } pub fn end(self: *DebugGUI) !void { // calculate bounding rect var rect = Rect{ .min_x = 0, .min_y = 0, .max_x = 0, .max_y = 0 }; for (self.text_verts.items) |v| { if (v.pos[0] > rect.max_x) rect.max_x = v.pos[0]; if (v.pos[1] > rect.max_y) rect.max_y = v.pos[1]; } for (self.uniform_colour_verts.items) |v| { if (v.pos[0] > rect.max_x) rect.max_x = v.pos[0]; if (v.pos[1] > rect.max_y) rect.max_y = v.pos[0]; } rect.max_x += @intToFloat(f32, inset); rect.max_y += @intToFloat(f32, inset); // draw background try self.drawColourRect(Colour.fromRGBA(0.13, 0.13, 0.13, 0.13), rect); // draw all text try drawTexturedVerts( self.draw_list, builtin_pipeline_resources.textured_verts_mono, debugfont_texture, self.text_verts.items, ); // draw text cursor if there is an element with keyboard focus if (self.state.keyboard_focus > 0) { try self.drawColourRect( Colour.white, .{ .min_x = self.state.text_cur_x - 1, .min_y = self.state.text_cur_y - line_spacing / 2, .max_x = self.state.text_cur_x + 1, .max_y = self.state.text_cur_y + glyph_height + line_spacing / 2, }, ); } } pub fn label( self: *DebugGUI, comptime fmt: []const u8, args: anytype, ) !void { var temp_arena = std.heap.ArenaAllocator.init(self.allocator); defer temp_arena.deinit(); const temp_allocator = temp_arena.allocator(); const string = try std.fmt.allocPrint(temp_allocator, fmt, args); const bounding_rect = try drawText( self.cur_x, self.cur_y, string, &self.text_verts, ); self.cur_y += (bounding_rect.max_y - bounding_rect.min_y); } pub fn textField( self: *DebugGUI, comptime T: type, comptime fmt: []const u8, value_ptr: *T, ) !void { const id = 1; // TODO(hazeycode): obtain some sort of unique identifier var temp_arena = std.heap.ArenaAllocator.init(self.allocator); defer temp_arena.deinit(); const temp_allocator = temp_arena.allocator(); const string = try std.fmt.allocPrint(temp_allocator, fmt, .{value_ptr.*}); const text_rect = try drawText(self.cur_x, self.cur_y, string, &self.text_verts); const bounding_rect = text_rect.inset(-4, -3, -4, 1); try self.drawColourRectOutline(Colour.white, bounding_rect, 1); const input = self.state.input; const mouse_over = text_rect.containsPoint(input.mouse_x, input.mouse_y); if (id == self.state.active_id) { if (input.mouse_btn_down and id == self.state.keyboard_focus) { const column = @divFloor( @floatToInt( i32, input.mouse_x - text_rect.min_x + @as(f32, glyph_width) / 2, ), glyph_width, ); const capped_column = @intCast( u32, std.math.max( 0, std.math.min(@intCast(i32, string.len), column), ), ); const line = 0; const x_offset = capped_column * glyph_width; const y_offset = line * (glyph_height + line_spacing); self.state.text_cur_x = text_rect.min_x + @intToFloat(f32, x_offset); self.state.text_cur_y = text_rect.min_y + @intToFloat(f32, y_offset); } if (input.mouse_btn_was_released) { self.state.active_id = 0; } } else if (id == self.state.hover_id) { if (input.mouse_btn_was_pressed) { if (mouse_over) { self.state.active_id = id; self.state.keyboard_focus = id; } else { self.state.keyboard_focus = 0; } } } else { if (mouse_over) { self.state.hover_id = id; } } self.cur_y += (text_rect.max_y - text_rect.min_y); } fn drawColourRect(self: *DebugGUI, colour: Colour, rect: Rect) !void { var verts = try self.allocator.alloc(Vertex, 6); errdefer self.allocator.free(verts); std.mem.copy(Vertex, verts, &rect.vertices()); try drawUniformColourVerts( self.draw_list, builtin_pipeline_resources.uniform_colour_verts, colour, verts, ); } fn drawColourRectOutline(self: *DebugGUI, colour: Colour, rect: Rect, weight: f32) !void { const num_verts = 6; const num_sides = 4; var verts = try self.allocator.alloc(Vertex, num_verts * num_sides); errdefer self.allocator.free(verts); { // left side const side_rect = Rect{ .min_x = rect.min_x, .max_x = rect.min_x + weight, .min_y = rect.min_y, .max_y = rect.max_y, }; const offset = 0 * num_verts; std.mem.copy( Vertex, verts[offset..(offset + num_verts)], &side_rect.vertices(), ); } { // right side const side_rect = Rect{ .min_x = rect.max_x - weight, .max_x = rect.max_x, .min_y = rect.min_y, .max_y = rect.max_y, }; const offset = 1 * num_verts; std.mem.copy( Vertex, verts[offset..(offset + num_verts)], &side_rect.vertices(), ); } { // top side const side_rect = Rect{ .min_x = rect.min_x, .max_x = rect.max_x, .min_y = rect.min_y, .max_y = rect.min_y + weight, }; const offset = 2 * num_verts; std.mem.copy( Vertex, verts[offset..(offset + num_verts)], &side_rect.vertices(), ); } { // bottom side const side_rect = Rect{ .min_x = rect.min_x, .max_x = rect.max_x, .min_y = rect.max_y - weight, .max_y = rect.max_y, }; const offset = 3 * num_verts; std.mem.copy( Vertex, verts[offset..(offset + num_verts)], &side_rect.vertices(), ); } try drawUniformColourVerts( self.draw_list, builtin_pipeline_resources.uniform_colour_verts, colour, verts, ); } fn drawText( cur_x: f32, cur_y: f32, string: []const u8, verts: *std.ArrayList(TexturedVertex), ) !Rect { var cur_line: u32 = 0; var column: u32 = 0; var max_column: u32 = 0; for (string) |c| { const maybe_glyph_idx: ?u32 = switch (c) { '0'...'9' => 0 + c - 48, 'a'...'z' => 10 + c - 97, 'A'...'Z' => 36 + c - 65, ':' => 62, ';' => 63, '\'' => 64, '"' => 65, '\\' => 66, ',' => 67, '.' => 68, '?' => 69, '/' => 70, '>' => 71, '<' => 72, '-' => 73, '+' => 74, '%' => 75, '&' => 76, '*' => 77, '(' => 78, ')' => 79, '_' => 80, '=' => 81, else => null, }; if (maybe_glyph_idx) |glyph_idx| { const x = cur_x + @intToFloat(f32, column * glyph_width); const y = cur_y + @intToFloat(f32, cur_line * (glyph_height + line_spacing)); const rect = Rect{ .min_x = x, .min_y = y, .max_x = x + glyph_width, .max_y = y + glyph_height, }; // debugfont only has a single row and is tightly packed const u = @intToFloat(f32, glyph_width * glyph_idx); const v = @intToFloat(f32, 0); const uv_rect = Rect{ .min_x = u / @intToFloat(f32, debugfont_texture.width), .min_y = v / @intToFloat(f32, debugfont_texture.height), .max_x = (u + glyph_width) / @intToFloat(f32, debugfont_texture.width), .max_y = (v + glyph_height) / @intToFloat(f32, debugfont_texture.height), }; try verts.appendSlice(&rect.texturedVertices(uv_rect)); column += 1; if (column > max_column) max_column = column; } else switch (c) { '\n', '\r' => { cur_line += 1; if (column > max_column) max_column = column; column = 0; }, ' ' => { column += 1; if (column > max_column) max_column = column; }, else => { std.debug.panic("graphics.DebugGUI unmapped character {}", .{c}); }, } } cur_line += 1; return Rect{ .min_x = cur_x, .min_y = cur_y, .max_x = cur_x + @intToFloat(f32, max_column * glyph_width), .max_y = cur_y + @intToFloat(f32, cur_line * (glyph_height + line_spacing)), }; } }; }; } test { std.testing.refAllDecls(@This()); }
modules/graphics/src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const math = std.math; const Allocator = std.mem.Allocator; const MIN_DEPTH = 4; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var global_allocator = gpa.allocator(); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const n = try get_n(); const max_depth = math.max(MIN_DEPTH + 2, n); { const stretch_depth = max_depth + 1; const stretch_tree = Node.make(stretch_depth, global_allocator).?; defer stretch_tree.deinit(); stretch_tree.cal_hash(); try stdout.print("stretch tree of depth {d}\t root hash: {d} check: {d}\n", .{ stretch_depth, stretch_tree.get_hash(), stretch_tree.check() }); } const long_lived_tree = Node.make(max_depth, global_allocator).?; defer long_lived_tree.deinit(); var depth: usize = MIN_DEPTH; while (depth <= max_depth) : (depth += 2) { const iterations = @intCast(usize, 1) << @intCast(u6, max_depth - depth + MIN_DEPTH); var sum: i64 = 0; var i: usize = 0; while (i < iterations) : (i += 1) { const tree = Node.make(depth, global_allocator).?; defer tree.deinit(); tree.cal_hash(); sum += tree.get_hash(); } try stdout.print("{d}\t trees of depth {d}\t root hash sum: {d}\n", .{ iterations, depth, sum }); } long_lived_tree.cal_hash(); try stdout.print("long lived tree of depth {d}\t root hash: {d} check: {d}\n", .{ max_depth, long_lived_tree.get_hash(), long_lived_tree.check() }); } fn get_n() !usize { var arg_it = std.process.args(); _ = arg_it.skip(); const arg = arg_it.next() orelse return 10; return try std.fmt.parseInt(u32, arg, 10); } const Node = struct { const Self = @This(); allocator: Allocator, hash: ?i64 = null, value: ?i64 = null, left: ?*Self = null, right: ?*Self = null, pub fn init(allocator: Allocator) !*Self { var node = try allocator.create(Self); node.allocator = allocator; return node; } pub fn deinit(self: *Self) void { if (self.left != null) { self.left.?.deinit(); } if (self.right != null) { self.right.?.deinit(); } self.allocator.destroy(self); } pub fn make(depth: usize, allocator: Allocator) ?*Self { var node = Self.init(allocator) catch return null; if (depth > 0) { const d = depth - 1; node.left = Self.make(d, allocator); node.right = Self.make(d, allocator); } else { node.value = 1; } return node; } pub fn check(self: *Self) bool { if (self.hash == null) { return false; } if (self.value != null) { return true; } return self.left.?.check() and self.right.?.check(); } pub fn cal_hash(self: *Self) void { if (self.hash != null) { return; } if (self.value != null) { self.hash = self.value; } else { self.left.?.cal_hash(); self.right.?.cal_hash(); self.hash = self.left.?.get_hash() + self.right.?.get_hash(); } } pub fn get_hash(self: *Self) i64 { if (self.hash == null) { return 0; } return self.hash.?; } };
bench/algorithm/merkletrees/1.zig
const std = @import("std"); const math = std.math; const testing = std.testing; const vecs = @import("vec.zig"); const Vec2 = vecs.Vec2; const Vec3 = vecs.Vec3; const Vec4 = vecs.Vec4; const BiVec3 = vecs.BiVec3; const mats = @import("mat.zig"); const Mat3 = mats.Mat3; pub const Rotor2 = extern struct { dot: f32, wedge: f32, /// A rotor that rotates 0 degrees pub const Identity = Rotor2{ .dot = 1, .wedge = 0 }; /// Constructs a rotor that rotates counter-clockwise /// around the origin by the given angle. pub inline fn initAngle(angleRad: f32) Rotor2 { return Rotor2{ .dot = math.cos(angleRad), .wedge = math.sin(angleRad), }; } /// Constructs a rotor that, if applied to a, would produce b. /// a and b must be normalized. pub inline fn diffNormalized(a: Vec2, b: Vec2) Rotor2 { return Rotor2{ .dot = a.dot(b), .wedge = a.wedge(b), }; } /// Constructs a rotor that rotates a to the direction of b. /// a and b are assumed not to be normalized. /// Returns error.Singular if a or b are near zero. pub inline fn diff(a: Vec2, b: Vec2) !Rotor2 { return try (Rotor2{ .dot = a.dot(b), .wedge = a.wedge(b), }).normalize(); } /// Rotates vec around the origin pub inline fn apply(self: Rotor2, vec: Vec2) Vec2 { return Vec2{ .x = vec.x * self.dot - vec.y * self.wedge, .y = vec.x * self.wedge + vec.y * self.dot, }; } /// Creates a rotor that rotates the same amount in the opposite direction pub inline fn reverse(self: Rotor2) Rotor2 { return Rotor2{ .dot = self.dot, .wedge = -self.wedge, }; } /// Combines two rotors into one pub inline fn add(a: Rotor2, b: Rotor2) Rotor2 { return Rotor2{ .dot = a.dot * b.dot - a.wedge * b.wedge, .wedge = a.dot * b.wedge + a.wedge * b.dot, }; } /// Adds 90 degrees counterclockwise to the rotation pub inline fn addLeft(self: Rotor2) Rotor2 { return Rotor2{ .dot = -self.wedge, .wedge = self.dot, }; } /// Adds 180 degrees to the rotation pub inline fn addHalf(self: Rotor2) Rotor2 { return Rotor2{ .dot = -self.dot, .wedge = -self.wedge, }; } /// Adds 90 degrees clockwise to the rotation pub inline fn addRight(self: Rotor2) Rotor2 { return Rotor2{ .dot = self.wedge, .wedge = -self.dot, }; } /// Normalizes the rotor to unit length. /// Rotors should stay normalized most of the time. /// Normalizing the zero rotor will result in error.Singular. pub inline fn normalize(self: Rotor2) !Rotor2 { var v2 = Vec2.init(self.dot, self.wedge); v2 = try v2.normalize(); return Rotor2{ .dot = v2.x, .wedge = v2.y, }; } /// Calculates the angle that this rotor rotates in the counterclockwise direction pub inline fn toAngleRad(self: Rotor2) f32 { return math.atan2(f32, self.wedge, self.dot); } }; pub const Rotor3 = extern struct { /// The dot product of the two rotor vectors. dot: f32, /// The wedge product of the two rotor vectors. /// This is the plane in which the rotor rotates. wedge: BiVec3, /// The rotor that performs no rotation pub const Identity = Rotor3{ .dot = 1.0, .wedge = BiVec3.Zero }; pub fn init(dot: f32, yz: f32, zx: f32, xy: f32) Rotor3 { return Rotor3{ .dot = dot, .wedge = BiVec3{ .yz = yz, .zx = zx, .xy = xy, }, }; } /// Creates a rotor that reflects across two unit vectors. /// The parameters must both be unit vectors, or a.len() * b.len() must equal 1. /// The rotor will rotate in the plane of ab from a towards b, /// for double the angle between ab. pub fn initVecsNormalized(a: Vec3, b: Vec3) Rotor3 { return (Rotor3{ .dot = a.dot(b), .wedge = a.wedge(b), }).standardize(); } /// Creates a rotor that reflects across two vectors. /// The rotor will rotate in the plane of ab from a towards b, /// for double the angle between ab. /// If a or b is zero, returns error.Singular. pub fn initVecs(a: Vec3, b: Vec3) !Rotor3 { return try (Rotor3{ .dot = a.dot(b), .wedge = a.wedge(b), }).standardize().normalize(); } /// Creates a rotor that rotates a to b along the plane between a and b /// If a and b are 180 degrees apart, picks an arbitrary axis to rotate around. /// If a or b is zero, returns error.Singular. pub fn diffVec(a: Vec3, b: Vec3) !Rotor3 { const normAB = math.sqrt(a.lenSquared() * b.lenSquared()); return (Rotor3{ .dot = a.dot(b) + normAB, .wedge = a.wedge(b), }).normalize() catch Rotor3{ .dot = 0, .wedge = try a.orthogonal().toBiVec3().normalize(), }; } /// Creates a rotor that rotates along the ortho plane from a's projection to b's projection. /// The returned rotor is guaranteed to rotate in the direction of ortho, and as a result /// it may not be standardized. Call standardize() on the result if you want the shorter rotation. pub fn diffVecAlong(a: Vec3, b: Vec3, ortho: BiVec3) !Rotor3 { // get projection of a and b onto ortho. They will be rotated 90 degrees since we // are using dotVec but it doesn't matter since we only care about the angle between them. const aPerp = ortho.dotVec(a); const bPerp = ortho.dotVec(b); const normAB2 = aPerp.lenSquared() * bPerp.lenSquared(); const normAB = math.sqrt(normAB2); const dot = aPerp.dot(bPerp); const crossMag = math.sqrt(normAB2 - dot * dot); const normOrtho = try ortho.normalize(); return (Rotor3{ .dot = dot + normAB, .wedge = normOrtho.scale(crossMag), }).normalize() catch if (normAB == 0) error.Singular else Rotor3{ .dot = 0, .wedge = normOrtho, }; } /// Creates a rotor that performs half of the rotation of this one. pub fn halfway(self: Rotor3) Rotor3 { return (Rotor3{ .dot = self.dot + 1.0, .wedge = self.wedge, }).normalize() catch Rotor3.Identity; } /// Creates a rotor that rotates from to to, and changes the up direction from fromUp to toUp. /// Returns error.Singular if: /// - any input vector is zero /// - from cross fromUp is zero /// - to cross toUp is zero pub fn diffFrame(from: Vec3, fromUp: Vec3, to: Vec3, toUp: Vec3) !Rotor3 { // calculate the rotor that turns from to to const baseRotor = try diffVec(from, to); // apply that rotation to the fromOut. // rotatedFromOut is perpendicular to to. const rotatedFromUp = baseRotor.apply(fromUp); // make a second rotor that rotates around to // this fixes up the up vector const fixUpRotor = (try diffVecAlong(rotatedFromUp, toUp, to.toBiVec3())).standardize(); // combine the two into a single rotor return fixUpRotor.preMul(baseRotor); } /// Calculates the rotor that transforms a to b. /// diff(a, b)(a(x)) == b(x). pub fn diff(a: Rotor3, b: Rotor3) Rotor3 { return b.preMul(a.reverse()); } /// Creates a rotor on a given wedge for a given angle. pub fn axisAngle(axis: BiVec3, angle: f32) !Rotor3 { return axisAngleNormalized(try axis.normalize(), angle); } /// Creates a rotor on a given wedge for a given angle. /// The wedge must be normalized. pub fn axisAngleNormalized(axis: BiVec3, angle: f32) Rotor3 { const cos = math.cos(angle * 0.5); const sin = math.sin(angle * 0.5); return (Rotor3{ .dot = cos, .wedge = axis.scale(sin), }).standardize(); } /// Creates a rotor around the x axis. /// angle is in radians. pub fn aroundX(angle: f32) Rotor3 { const cos = math.cos(angle * 0.5); const sin = math.sin(angle * 0.5); return (Rotor3{ .dot = cos, .wedge = BiVec3{ .yz = sin, .zx = 0, .xy = 0, }, }).standardize(); } /// Creates a rotor around the y axis. /// angle is in radians. pub fn aroundY(angle: f32) Rotor3 { const cos = math.cos(angle * 0.5); const sin = math.sin(angle * 0.5); return (Rotor3{ .dot = cos, .wedge = BiVec3{ .yz = 0, .zx = sin, .xy = 0, }, }).standardize(); } /// Creates a rotor around the z axis. /// angle is in radians. pub fn aroundZ(angle: f32) Rotor3 { const cos = math.cos(angle * 0.5); const sin = math.sin(angle * 0.5); return (Rotor3{ .dot = cos, .wedge = BiVec3{ .yz = 0, .zx = 0, .xy = sin, }, }).standardize(); } /// Translates the quaternion w + xi + yj + zk into a Rotor. /// Assumes the identities i*j = k, j*k = i, k*i = j, ijk = -1 pub fn fromQuaternion(w: f32, x: f32, y: f32, z: f32) Rotor3 { return (Rotor3{ .dot = w, .wedge = BiVec3{ .yz = -x, .zx = -y, .xy = -z, }, }).standardize(); } pub fn fromMatrix(m: var) Rotor3 { var result: Rotor3 = undefined; var trace: f32 = undefined; if (m.z.z < 0) { if (m.x.x > m.y.y) { trace = 1 + m.x.x - m.y.y - m.z.z; result = Rotor3.init(m.y.z - m.z.y, trace, m.x.y + m.y.x, m.z.x + m.x.z); } else { trace = 1 - m.x.x + m.y.y - m.z.z; result = Rotor3.init(m.z.x - m.x.z, m.x.y + m.y.x, trace, m.y.z + m.z.y); } } else { if (m.x.x < -m.y.y) { trace = 1 - m.x.x - m.y.y + m.z.z; result = Rotor3.init(m.x.y - m.y.x, m.z.x + m.x.z, m.y.z + m.z.y, trace); } else { trace = 1 + m.x.x + m.y.y + m.z.z; result = Rotor3.init(trace, m.y.z - m.z.y, m.z.x - m.x.z, m.x.y - m.y.x); } } var mult = 0.5 / math.sqrt(trace); // ensure dot ends up positive to standardize the rotation mult = math.copysign(f32, mult, result.dot); result.dot *= mult; result.wedge = result.wedge.scale(mult); return result; } /// Normalizes the rotor to unit length. /// Rotors should stay normalized most of the time. pub fn normalize(self: Rotor3) !Rotor3 { const v4 = @bitCast(Vec4, self); const norm = try v4.normalize(); return @bitCast(Rotor3, norm); } /// Standardizes the rotor to avoid double-cover. /// A standardized rotor has the property that its first /// non-zero component is positive. pub fn standardize(self: Rotor3) Rotor3 { if (self.dot >= -0.0) return self; return Rotor3{ .dot = -self.dot, .wedge = BiVec3{ .yz = -self.wedge.yz, .zx = -self.wedge.zx, .xy = -self.wedge.xy, }, }; } /// Composes two rotors into one that applies b first then a. pub fn preMul(a: Rotor3, b: Rotor3) Rotor3 { return Rotor3{ .dot = a.dot * b.dot + b.wedge.dot(a.wedge), .wedge = b.wedge.scale(a.dot).add(a.wedge.scale(b.dot)).add(b.wedge.wedge(a.wedge)), }; } /// Returns a rotor that rotates the same amount in the opposite direction. pub fn reverse(r: Rotor3) Rotor3 { return Rotor3{ .dot = r.dot, .wedge = r.wedge.negate(), }; } /// Interpolates evenly between two rotors along the shortest path. /// If one parameter is standardized and the other is not, will interpolate /// on the longest path instead. pub fn slerp(self: Rotor3, target: Rotor3, alpha: f32) Rotor3 { const va = @bitCast(Vec4, self); const vb = @bitCast(Vec4, target); const cosAngle = va.dot(vb); if (math.fabs(cosAngle) > 0.999) return self.nlerp(target, alpha) catch unreachable; const angle = math.acos(cosAngle); const scale = 1.0 / math.sin(angle); const fromMult = math.sin((1.0 - alpha) * angle) * scale; const toMult = math.sin(alpha * angle) * scale; const blended = va.scale(fromMult).add(vb.scale(toMult)); return @bitCast(Rotor3, blended); } /// Interpolates between two rotors, but is slightly faster in the /// middle and slower on each end. Useful for rotors that are close /// to each other where this effect is not noticeable. pub fn nlerp(self: Rotor3, target: Rotor3, alpha: f32) !Rotor3 { const a = @bitCast(Vec4, self); const b = @bitCast(Vec4, target); const lerped = a.lerp(b, alpha); const norm = try lerped.normalize(); return @bitCast(Rotor3, norm); } /// Rotates a vector pub fn apply(self: Rotor3, in: Vec3) Vec3 { // compute all distributive products const dot2 = self.dot * self.dot; const yz2 = self.wedge.yz * self.wedge.yz; const zx2 = self.wedge.zx * self.wedge.zx; const xy2 = self.wedge.xy * self.wedge.xy; // multiply these by 2 since they are always used in pairs const dotyz = self.dot * self.wedge.yz * 2; const dotzx = self.dot * self.wedge.zx * 2; const dotxy = self.dot * self.wedge.xy * 2; const yzzx = self.wedge.yz * self.wedge.zx * 2; const zxxy = self.wedge.zx * self.wedge.xy * 2; const xyyz = self.wedge.xy * self.wedge.yz * 2; // calculate the rotated components const x = (dot2 + yz2 - zx2 - xy2) * in.x + (yzzx - dotxy) * in.y + (xyyz + dotzx) * in.z; const y = (dot2 - yz2 + zx2 - xy2) * in.y + (zxxy - dotyz) * in.z + (yzzx + dotxy) * in.x; const z = (dot2 - yz2 - zx2 + xy2) * in.z + (xyyz - dotzx) * in.x + (zxxy + dotyz) * in.y; return Vec3.init(x, y, z); } /// Creates a Mat3 that performs the same transform as this rotor pub fn toMat3(self: Rotor3) Mat3 { // compute all distributive products const dot2 = self.dot * self.dot; const yz2 = self.wedge.yz * self.wedge.yz; const zx2 = self.wedge.zx * self.wedge.zx; const xy2 = self.wedge.xy * self.wedge.xy; // multiply these by 2 since they are always used in pairs const dotyz = self.dot * self.wedge.yz * 2; const dotzx = self.dot * self.wedge.zx * 2; const dotxy = self.dot * self.wedge.xy * 2; const yzzx = self.wedge.yz * self.wedge.zx * 2; const zxxy = self.wedge.zx * self.wedge.xy * 2; const xyyz = self.wedge.xy * self.wedge.yz * 2; return Mat3{ .x = Vec3{ .x = dot2 + yz2 - zx2 - xy2, .y = yzzx + dotxy, .z = xyyz - dotzx, }, .y = Vec3{ .x = yzzx - dotxy, .y = dot2 - yz2 + zx2 - xy2, .z = zxxy + dotyz, }, .z = Vec3{ .x = xyyz + dotzx, .y = zxxy - dotyz, .z = dot2 - yz2 - zx2 + xy2, }, }; } /// Calculates the axis of rotation as a unit vector pub inline fn calcRotationAxis(self: Rotor3) !BiVec3 { const mult = 1.0 / math.sqrt(math.max(0.0, 1.0 - self.dot * self.dot)); if (!math.isFinite(mult)) return error.Singular; return self.wedge.scale(mult); } /// Calculates the angle of rotation pub inline fn calcRotationAngle(self: Rotor3) f32 { return math.acos(self.dot); } pub fn expectNear(expected: Rotor3, actual: Rotor3, epsilon: f32) void { if (!math.approxEq(f32, expected.dot, actual.dot, epsilon) or !math.approxEq(f32, expected.wedge.yz, actual.wedge.yz, epsilon) or !math.approxEq(f32, expected.wedge.zx, actual.wedge.zx, epsilon) or !math.approxEq(f32, expected.wedge.xy, actual.wedge.xy, epsilon)) { std.debug.panic("Expected Rotor3({}, ({}, {}, {})), found Rotor3({}, ({}, {}, {}))", .{ expected.dot, expected.wedge.yz, expected.wedge.zx, expected.wedge.xy, actual.dot, actual.wedge.yz, actual.wedge.zx, actual.wedge.xy, }); } } }; test "compile Rotor2" { var x = Vec2.X; var y = Vec2.Y; var a = Rotor2.initAngle(32); var b = try Rotor2.diff(x, y); _ = Rotor2.diffNormalized(x, y); _ = a.apply(x); _ = a.reverse(); _ = a.add(b); _ = a.addLeft(); _ = a.addHalf(); _ = a.addRight(); _ = try a.normalize(); _ = a.toAngleRad(); } test "compile Rotor3" { var a = Rotor3.Identity; var b = Rotor3.fromQuaternion(0, 1, 0, 0); var c = try b.normalize(); _ = b.standardize(); _ = b.preMul(c); _ = a.slerp(b, 0.25); _ = try a.nlerp(c, 0.25); _ = a.apply(Vec3.X); } test "Rotor3.initVecs" { const epsilon = 1e-5; const Identity = Rotor3.Identity; const expectNear = Rotor3.expectNear; expectNear(Identity, try Rotor3.initVecs(Vec3.X, Vec3.X), epsilon); expectNear(Identity, try Rotor3.initVecs(Vec3.Y, Vec3.Y), epsilon); expectNear(Identity, try Rotor3.initVecs(Vec3.Z, Vec3.Z), epsilon); expectNear(Rotor3.init(0, 0, 0, 1), try Rotor3.initVecs(Vec3.X, Vec3.Y), epsilon); expectNear(Rotor3.init(0, 0, -1, 0), try Rotor3.initVecs(Vec3.X, Vec3.Z), epsilon); expectNear(Rotor3.init(0, 0, 1, 0), try Rotor3.initVecs(Vec3.Z, Vec3.X), epsilon); expectNear(Rotor3.init(0, 1, 0, 0), try Rotor3.initVecs(Vec3.Y, Vec3.Z), epsilon); const isqrt2 = 1.0 / math.sqrt(2.0); expectNear(Rotor3.init(isqrt2, 0, 0, isqrt2), try Rotor3.initVecs(Vec3.X, Vec3.init(isqrt2, isqrt2, 0)), epsilon); expectNear(Rotor3.init(isqrt2, 0, 0, isqrt2), try Rotor3.initVecs(Vec3.X.scale(5), Vec3.init(10, 10, 0)), epsilon); expectNear(Rotor3.init(isqrt2, 0, 0, isqrt2), Rotor3.initVecsNormalized(Vec3.X, Vec3.init(isqrt2, isqrt2, 0)), epsilon); } test "Rotor3.diffVec" { const epsilon = 1e-5; const Identity = Rotor3.Identity; const expectNear = Rotor3.expectNear; expectNear(Identity, try Rotor3.diffVec(Vec3.X, Vec3.X), epsilon); expectNear(Identity, try Rotor3.diffVec(Vec3.Y, Vec3.Y), epsilon); expectNear(Identity, try Rotor3.diffVec(Vec3.Z, Vec3.Z), epsilon); expectNear(Rotor3.init(0, 0, -1, 0), try Rotor3.diffVec(Vec3.X, Vec3.X.negate()), epsilon); expectNear(Rotor3.init(0, 0, 0, 1), try Rotor3.diffVecAlong(Vec3.X, Vec3.X.negate(), BiVec3.XY), epsilon); expectNear(Rotor3.init(0, 0, 0, -1), try Rotor3.diffVecAlong(Vec3.X, Vec3.X.negate(), BiVec3.XY.negate()), epsilon); expectNear(Rotor3.init(0, 0, -1, 0), try Rotor3.diffVecAlong(Vec3.X, Vec3.X.negate(), BiVec3.ZX.negate()), epsilon); testing.expectError(error.Singular, Rotor3.diffVecAlong(Vec3.X, Vec3.X.negate(), BiVec3.YZ.negate())); const isqrt2 = 1.0 / math.sqrt(2.0); expectNear(Rotor3.init(isqrt2, 0, 0, isqrt2), try Rotor3.diffVec(Vec3.X, Vec3.Y), epsilon); expectNear(Rotor3.init(isqrt2, 0, 0, isqrt2), try Rotor3.diffVec(Vec3.X.scale(5), Vec3.Y.scale(10)), epsilon); expectNear(Rotor3.init(isqrt2, 0, -isqrt2, 0), try Rotor3.diffVec(Vec3.X, Vec3.Z), epsilon); } test "Rotor3.halfway" { const epsilon = 1e-5; const rotor = try Rotor3.init(1, 2, -3, 4).normalize(); var half = rotor.halfway(); const vec = Vec3.init(4, -2, 12); const rotated = rotor.apply(vec); const hrotated = half.apply(half.apply(vec)); Vec3.expectNear(rotated, hrotated, epsilon); var c: u32 = 0; while (c < 32) : (c += 1) { half = half.halfway(); } Rotor3.expectNear(Rotor3.Identity, half, epsilon); } test "Rotor3.apply" { const epsilon = 1e-5; const Identity = Rotor3.Identity; const expectNear = Rotor3.expectNear; const isqrt2 = 1.0 / math.sqrt(2.0); var rotor = Rotor3.init(isqrt2, 0, 0, isqrt2); Vec3.expectNear(Vec3.Y, rotor.apply(Vec3.X), epsilon); } test "Rotor3.diffFrame" { const epsilon = 1e-5; const expectNear = Rotor3.expectNear; const rotor = try Rotor3.diffFrame( Vec3.init(4, 0, 0), Vec3.init(-0.5, 0, 1), Vec3.init(0, 0.25, 0), Vec3.init(1, 0.5, 0), ); Vec3.expectNear(Vec3.Y, rotor.apply(Vec3.X), epsilon); Vec3.expectNear(Vec3.Y.add(Vec3.X), rotor.apply(Vec3.X.add(Vec3.Z)), epsilon); } fn randRotor3(rnd: *std.rand.Random) Rotor3 { return Rotor3.init( rnd.float(f32) * 2 - 1, rnd.float(f32) * 2 - 1, rnd.float(f32) * 2 - 1, rnd.float(f32) * 2 - 1, ).standardize().normalize() catch Rotor3.Identity; } fn randVec3(rnd: *std.rand.Random) Vec3 { return Vec3.init( rnd.float(f32) * 4 - 2, rnd.float(f32) * 4 - 2, rnd.float(f32) * 4 - 2, ); } test "Rotor3.diff" { const epsilon = 1e-5; var bigRnd = std.rand.DefaultPrng.init(42); const rnd = &bigRnd.random; var i = @as(u32, 0); while (i < 10) : (i += 1) { const a = randRotor3(rnd); const b = randRotor3(rnd); const diff = a.diff(b); const recombined = diff.preMul(a); Rotor3.expectNear(b, recombined, epsilon); var j = @as(u32, 0); while (j < 10) : (j += 1) { const vec = randVec3(rnd); Vec3.expectNear(b.apply(vec), diff.apply(a.apply(vec)), epsilon); } } } test "Rotor3.lerp" { const epsilon = 1e-5; var bigRnd = std.rand.DefaultPrng.init(42); const rnd = &bigRnd.random; var i = @as(u32, 0); while (i < 10) : (i += 1) { const a = randRotor3(rnd); const b = randRotor3(rnd); const halfDiff = a.diff(b).halfway().preMul(a); const slerp = a.slerp(b, 0.5); const nlerp = try a.nlerp(b, 0.5); Rotor3.expectNear(slerp, nlerp, epsilon); Rotor3.expectNear(slerp, halfDiff, epsilon); } }
src/geo/rotor.zig
const std = @import("std.zig"); const testing = std.testing; // TODO: Add support for multi-byte ops (e.g. table operations) /// Wasm instruction opcodes /// /// All instructions are defined as per spec: /// https://webassembly.github.io/spec/core/appendix/index-instructions.html pub const Opcode = enum(u8) { @"unreachable" = 0x00, nop = 0x01, block = 0x02, loop = 0x03, @"if" = 0x04, @"else" = 0x05, end = 0x0B, br = 0x0C, br_if = 0x0D, br_table = 0x0E, @"return" = 0x0F, call = 0x10, call_indirect = 0x11, drop = 0x1A, select = 0x1B, local_get = 0x20, local_set = 0x21, local_tee = 0x22, global_get = 0x23, global_set = 0x24, i32_load = 0x28, i64_load = 0x29, f32_load = 0x2A, f64_load = 0x2B, i32_load8_s = 0x2C, i32_load8_u = 0x2D, i32_load16_s = 0x2E, i32_load16_u = 0x2F, i64_load8_s = 0x30, i64_load8_u = 0x31, i64_load16_s = 0x32, i64_load16_u = 0x33, i64_load32_s = 0x34, i64_load32_u = 0x35, i32_store = 0x36, i64_store = 0x37, f32_store = 0x38, f64_store = 0x39, i32_store8 = 0x3A, i32_store16 = 0x3B, i64_store8 = 0x3C, i64_store16 = 0x3D, i64_store32 = 0x3E, memory_size = 0x3F, memory_grow = 0x40, i32_const = 0x41, i64_const = 0x42, f32_const = 0x43, f64_const = 0x44, i32_eqz = 0x45, i32_eq = 0x46, i32_ne = 0x47, i32_lt_s = 0x48, i32_lt_u = 0x49, i32_gt_s = 0x4A, i32_gt_u = 0x4B, i32_le_s = 0x4C, i32_le_u = 0x4D, i32_ge_s = 0x4E, i32_ge_u = 0x4F, i64_eqz = 0x50, i64_eq = 0x51, i64_ne = 0x52, i64_lt_s = 0x53, i64_lt_u = 0x54, i64_gt_s = 0x55, i64_gt_u = 0x56, i64_le_s = 0x57, i64_le_u = 0x58, i64_ge_s = 0x59, i64_ge_u = 0x5A, f32_eq = 0x5B, f32_ne = 0x5C, f32_lt = 0x5D, f32_gt = 0x5E, f32_le = 0x5F, f32_ge = 0x60, f64_eq = 0x61, f64_ne = 0x62, f64_lt = 0x63, f64_gt = 0x64, f64_le = 0x65, f64_ge = 0x66, i32_clz = 0x67, i32_ctz = 0x68, i32_popcnt = 0x69, i32_add = 0x6A, i32_sub = 0x6B, i32_mul = 0x6C, i32_div_s = 0x6D, i32_div_u = 0x6E, i32_rem_s = 0x6F, i32_rem_u = 0x70, i32_and = 0x71, i32_or = 0x72, i32_xor = 0x73, i32_shl = 0x74, i32_shr_s = 0x75, i32_shr_u = 0x76, i32_rotl = 0x77, i32_rotr = 0x78, i64_clz = 0x79, i64_ctz = 0x7A, i64_popcnt = 0x7B, i64_add = 0x7C, i64_sub = 0x7D, i64_mul = 0x7E, i64_div_s = 0x7F, i64_div_u = 0x80, i64_rem_s = 0x81, i64_rem_u = 0x82, i64_and = 0x83, i64_or = 0x84, i64_xor = 0x85, i64_shl = 0x86, i64_shr_s = 0x87, i64_shr_u = 0x88, i64_rotl = 0x89, i64_rotr = 0x8A, f32_abs = 0x8B, f32_neg = 0x8C, f32_ceil = 0x8D, f32_floor = 0x8E, f32_trunc = 0x8F, f32_nearest = 0x90, f32_sqrt = 0x91, f32_add = 0x92, f32_sub = 0x93, f32_mul = 0x94, f32_div = 0x95, f32_min = 0x96, f32_max = 0x97, f32_copysign = 0x98, f64_abs = 0x99, f64_neg = 0x9A, f64_ceil = 0x9B, f64_floor = 0x9C, f64_trunc = 0x9D, f64_nearest = 0x9E, f64_sqrt = 0x9F, f64_add = 0xA0, f64_sub = 0xA1, f64_mul = 0xA2, f64_div = 0xA3, f64_min = 0xA4, f64_max = 0xA5, f64_copysign = 0xA6, i32_wrap_i64 = 0xA7, i32_trunc_f32_s = 0xA8, i32_trunc_f32_u = 0xA9, i32_trunc_f64_s = 0xAA, i32_trunc_f64_u = 0xAB, i64_extend_i32_s = 0xAC, i64_extend_i32_u = 0xAD, i64_trunc_f32_s = 0xAE, i64_trunc_f32_u = 0xAF, i64_trunc_f64_s = 0xB0, i64_trunc_f64_u = 0xB1, f32_convert_i32_s = 0xB2, f32_convert_i32_u = 0xB3, f32_convert_i64_s = 0xB4, f32_convert_i64_u = 0xB5, f32_demote_f64 = 0xB6, f64_convert_i32_s = 0xB7, f64_convert_i32_u = 0xB8, f64_convert_i64_s = 0xB9, f64_convert_i64_u = 0xBA, f64_promote_f32 = 0xBB, i32_reinterpret_f32 = 0xBC, i64_reinterpret_f64 = 0xBD, f32_reinterpret_i32 = 0xBE, f64_reinterpret_i64 = 0xBF, i32_extend8_s = 0xC0, i32_extend16_s = 0xC1, i64_extend8_s = 0xC2, i64_extend16_s = 0xC3, i64_extend32_s = 0xC4, _, }; /// Returns the integer value of an `Opcode`. Used by the Zig compiler /// to write instructions to the wasm binary file pub fn opcode(op: Opcode) u8 { return @enumToInt(op); } test "Wasm - opcodes" { // Ensure our opcodes values remain intact as certain values are skipped due to them being reserved const i32_const = opcode(.i32_const); const end = opcode(.end); const drop = opcode(.drop); const local_get = opcode(.local_get); const i64_extend32_s = opcode(.i64_extend32_s); try testing.expectEqual(@as(u16, 0x41), i32_const); try testing.expectEqual(@as(u16, 0x0B), end); try testing.expectEqual(@as(u16, 0x1A), drop); try testing.expectEqual(@as(u16, 0x20), local_get); try testing.expectEqual(@as(u16, 0xC4), i64_extend32_s); } /// Enum representing all Wasm value types as per spec: /// https://webassembly.github.io/spec/core/binary/types.html pub const Valtype = enum(u8) { i32 = 0x7F, i64 = 0x7E, f32 = 0x7D, f64 = 0x7C, }; /// Returns the integer value of a `Valtype` pub fn valtype(value: Valtype) u8 { return @enumToInt(value); } /// Reference types, where the funcref references to a function regardless of its type /// and ref references an object from the embedder. pub const RefType = enum(u8) { funcref = 0x70, externref = 0x6F, }; /// Returns the integer value of a `Reftype` pub fn reftype(value: RefType) u8 { return @enumToInt(value); } test "Wasm - valtypes" { const _i32 = valtype(.i32); const _i64 = valtype(.i64); const _f32 = valtype(.f32); const _f64 = valtype(.f64); try testing.expectEqual(@as(u8, 0x7F), _i32); try testing.expectEqual(@as(u8, 0x7E), _i64); try testing.expectEqual(@as(u8, 0x7D), _f32); try testing.expectEqual(@as(u8, 0x7C), _f64); } /// Limits classify the size range of resizeable storage associated with memory types and table types. pub const Limits = struct { min: u32, max: ?u32, }; /// Initialization expressions are used to set the initial value on an object /// when a wasm module is being loaded. pub const InitExpression = union(enum) { i32_const: i32, i64_const: i64, f32_const: f32, f64_const: f64, global_get: u32, }; /// pub const Func = struct { type_index: u32, }; /// Tables are used to hold pointers to opaque objects. /// This can either by any function, or an object from the host. pub const Table = struct { limits: Limits, reftype: RefType, }; /// Describes the layout of the memory where `min` represents /// the minimal amount of pages, and the optional `max` represents /// the max pages. When `null` will allow the host to determine the /// amount of pages. pub const Memory = struct { limits: Limits, }; /// Represents the type of a `Global` or an imported global. pub const GlobalType = struct { valtype: Valtype, mutable: bool, }; pub const Global = struct { global_type: GlobalType, init: InitExpression, }; /// Notates an object to be exported from wasm /// to the host. pub const Export = struct { name: []const u8, kind: ExternalKind, index: u32, }; /// Element describes the layout of the table that can /// be found at `table_index` pub const Element = struct { table_index: u32, offset: InitExpression, func_indexes: []const u32, }; /// Imports are used to import objects from the host pub const Import = struct { module_name: []const u8, name: []const u8, kind: Kind, pub const Kind = union(ExternalKind) { function: u32, table: Table, memory: Limits, global: GlobalType, }; }; /// `Type` represents a function signature type containing both /// a slice of parameters as well as a slice of return values. pub const Type = struct { params: []const Valtype, returns: []const Valtype, pub fn format(self: Type, comptime fmt: []const u8, opt: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = opt; try writer.writeByte('('); for (self.params) |param, i| { try writer.print("{s}", .{@tagName(param)}); if (i + 1 != self.params.len) { try writer.writeAll(", "); } } try writer.writeAll(") -> "); if (self.returns.len == 0) { try writer.writeAll("nil"); } else { for (self.returns) |return_ty, i| { try writer.print("{s}", .{@tagName(return_ty)}); if (i + 1 != self.returns.len) { try writer.writeAll(", "); } } } } pub fn eql(self: Type, other: Type) bool { return std.mem.eql(Valtype, self.params, other.params) and std.mem.eql(Valtype, self.returns, other.returns); } pub fn deinit(self: *Type, gpa: *std.mem.Allocator) void { gpa.free(self.params); gpa.free(self.returns); self.* = undefined; } }; /// Wasm module sections as per spec: /// https://webassembly.github.io/spec/core/binary/modules.html pub const Section = enum(u8) { custom, type, import, function, table, memory, global, @"export", start, element, code, data, data_count, _, }; /// Returns the integer value of a given `Section` pub fn section(val: Section) u8 { return @enumToInt(val); } /// The kind of the type when importing or exporting to/from the host environment /// https://webassembly.github.io/spec/core/syntax/modules.html pub const ExternalKind = enum(u8) { function, table, memory, global, }; /// Returns the integer value of a given `ExternalKind` pub fn externalKind(val: ExternalKind) u8 { return @enumToInt(val); } // type constants pub const element_type: u8 = 0x70; pub const function_type: u8 = 0x60; pub const result_type: u8 = 0x40; /// Represents a block which will not return a value pub const block_empty: u8 = 0x40; // binary constants pub const magic = [_]u8{ 0x00, 0x61, 0x73, 0x6D }; // \0asm pub const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; // version 1 (MVP) // Each wasm page size is 64kB pub const page_size = 64 * 1024;
lib/std/wasm.zig
const std = @import("std"); const testing = std.testing; // Probably broken version of Russ Cox's Simple Glob at https://research.swtch.com/glob pub fn globMatch(pattern: []const u8, name: []const u8) bool { // Current position in the pattern var p_x: usize = 0; // Current position in the compared text var p_n: usize = 0; // If matching a wildcard fails, p_x and p_n will be reset to var next_p_x: usize = 0; var next_p_n: usize = 0; while (p_n < name.len or p_x < pattern.len) { if (p_x < pattern.len) { const c = pattern[p_x]; switch (c) { // Successful single character match '?' => { if (p_n < name.len) { p_x += 1; p_n += 1; continue; } }, // Wildcard moment '*' => { // Set up restat. Attempt assume one more character is subsumed by the * next_p_x = p_x; next_p_n = p_n + 1; p_x += 1; continue; }, else => { if (p_n < name.len and c == name[p_n]) { p_n += 1; p_x += 1; continue; } }, } } // No match. Restart time. if (next_p_n > 0 and next_p_n <= name.len) { p_n = next_p_n; p_x = next_p_x; continue; } // No match and no hope of restarting. Failed. return false; } return true; } test { try testing.expect(globMatch("?", "xx") == false); try testing.expect(globMatch("???", "x") == false); try testing.expect(globMatch("??", "xx") == true); try testing.expect(globMatch("zig ???", "zig fmt") == true); try testing.expect(globMatch("*?", "xx") == true); try testing.expect(globMatch("*??*", "xx") == true); try testing.expect(globMatch("m*x", "mega man") == false); try testing.expect(globMatch("*sip*", "mississipi") == true); try testing.expect(globMatch("*si*si*si", "mississipi") == false); }
src/glob.zig
const std = @import("std"); const Mutex = std.Thread.Mutex; const expect = std.testing.expect; extern fn cbtAlignedAllocSetCustomAligned( alloc: fn (size: usize, alignment: i32) callconv(.C) ?*anyopaque, free: fn (ptr: ?*anyopaque) callconv(.C) void, ) void; var allocator: ?std.mem.Allocator = null; var allocations: ?std.AutoHashMap(usize, usize) = null; var mutex: Mutex = .{}; export fn zbulletAlloc(size: usize, alignment: i32) callconv(.C) ?*anyopaque { mutex.lock(); defer mutex.unlock(); var slice = allocator.?.allocBytes( @intCast(u29, alignment), size, 0, @returnAddress(), ) catch @panic("zbullet: out of memory"); allocations.?.put(@ptrToInt(slice.ptr), size) catch @panic("zbullet: out of memory"); return slice.ptr; } export fn zbulletFree(ptr: ?*anyopaque) callconv(.C) void { if (ptr != null) { mutex.lock(); defer mutex.unlock(); const size = allocations.?.fetchRemove(@ptrToInt(ptr.?)).?.value; const slice = @ptrCast([*]u8, ptr.?)[0..size]; allocator.?.free(slice); } } pub fn init(alloc: std.mem.Allocator) void { std.debug.assert(allocator == null and allocations == null); allocator = alloc; allocations = std.AutoHashMap(usize, usize).init(allocator.?); allocations.?.ensureTotalCapacity(256) catch @panic("zbullet: out of memory"); cbtAlignedAllocSetCustomAligned(zbulletAlloc, zbulletFree); } pub fn deinit() void { allocations.?.deinit(); allocations = null; allocator = null; } pub const World = opaque { pub fn init(params: struct {}) *const World { _ = params; std.debug.assert(allocator != null and allocations != null); return cbtWorldCreate(); } extern fn cbtWorldCreate() *const World; pub fn deinit(world: *const World) void { std.debug.assert(world.getNumBodies() == 0); cbtWorldDestroy(world); } extern fn cbtWorldDestroy(world: *const World) void; pub const setGravity = cbtWorldSetGravity; extern fn cbtWorldSetGravity(world: *const World, gravity: *const [3]f32) void; pub const getGravity = cbtWorldGetGravity; extern fn cbtWorldGetGravity(world: *const World, gravity: *[3]f32) void; pub fn stepSimulation(world: *const World, time_step: f32, params: struct { max_sub_steps: u32 = 1, fixed_time_step: f32 = 1.0 / 60.0, }) u32 { return cbtWorldStepSimulation( world, time_step, params.max_sub_steps, params.fixed_time_step, ); } extern fn cbtWorldStepSimulation( world: *const World, time_step: f32, max_sub_steps: u32, fixed_time_step: f32, ) u32; pub const addBody = cbtWorldAddBody; extern fn cbtWorldAddBody(world: *const World, body: *const Body) void; pub const removeBody = cbtWorldRemoveBody; extern fn cbtWorldRemoveBody(world: *const World, body: *const Body) void; pub const getBody = cbtWorldGetBody; extern fn cbtWorldGetBody(world: *const World, index: i32) *const Body; pub const getNumBodies = cbtWorldGetNumBodies; extern fn cbtWorldGetNumBodies(world: *const World) i32; pub const addConstraint = cbtWorldAddConstraint; extern fn cbtWorldAddConstraint( world: *const World, con: *const Constraint, disable_collision_between_linked_bodies: bool, ) void; pub const removeConstraint = cbtWorldRemoveConstraint; extern fn cbtWorldRemoveConstraint( world: *const World, con: *const Constraint, ) void; pub const getConstraint = cbtWorldGetConstraint; extern fn cbtWorldGetConstraint( world: *const World, index: i32, ) *const Constraint; pub const getNumConstraints = cbtWorldGetNumConstraints; extern fn cbtWorldGetNumConstraints(world: *const World) i32; pub const debugSetDrawer = cbtWorldDebugSetDrawer; extern fn cbtWorldDebugSetDrawer( world: *const World, debug: *const DebugDraw, ) void; pub const debugSetMode = cbtWorldDebugSetMode; extern fn cbtWorldDebugSetMode(world: *const World, mode: DebugMode) void; pub const debugDrawAll = cbtWorldDebugDrawAll; extern fn cbtWorldDebugDrawAll(world: *const World) void; pub const debugDrawLine1 = cbtWorldDebugDrawLine1; extern fn cbtWorldDebugDrawLine1( world: *const World, p0: *const [3]f32, p1: *const [3]f32, color: *const [3]f32, ) void; pub const debugDrawLine2 = cbtWorldDebugDrawLine2; extern fn cbtWorldDebugDrawLine2( world: *const World, p0: *const [3]f32, p1: *const [3]f32, color0: *const [3]f32, color1: *const [3]f32, ) void; pub const debugDrawSphere = cbtWorldDebugDrawSphere; extern fn cbtWorldDebugDrawSphere( world: *const World, position: *const [3]f32, radius: f32, color: *const [3]f32, ) void; }; pub const Axis = enum(c_int) { x = 0, y = 1, z = 2, }; pub const ShapeType = enum(c_int) { box = 0, sphere = 8, capsule = 10, cylinder = 13, compound = 31, trimesh = 21, }; pub const Shape = opaque { pub const allocate = cbtShapeAllocate; extern fn cbtShapeAllocate(stype: ShapeType) *const Shape; pub const deallocate = cbtShapeDeallocate; extern fn cbtShapeDeallocate(shape: *const Shape) void; pub fn deinit(shape: *const Shape) void { shape.destroy(); shape.deallocate(); } pub fn destroy(shape: *const Shape) void { switch (shape.getType()) { .box, .sphere, .capsule, .cylinder, .compound, => cbtShapeDestroy(shape), .trimesh => cbtShapeTriMeshDestroy(shape), } } extern fn cbtShapeDestroy(shape: *const Shape) void; extern fn cbtShapeTriMeshDestroy(shape: *const Shape) void; pub const isCreated = cbtShapeIsCreated; extern fn cbtShapeIsCreated(shape: *const Shape) bool; pub const getType = cbtShapeGetType; extern fn cbtShapeGetType(shape: *const Shape) ShapeType; pub const setMargin = cbtShapeSetMargin; extern fn cbtShapeSetMargin(shape: *const Shape, margin: f32) void; pub const getMargin = cbtShapeGetMargin; extern fn cbtShapeGetMargin(shape: *const Shape) f32; pub const isPolyhedral = cbtShapeIsPolyhedral; extern fn cbtShapeIsPolyhedral(shape: *const Shape) bool; pub const isConvex2d = cbtShapeIsConvex2d; extern fn cbtShapeIsConvex2d(shape: *const Shape) bool; pub const isConvex = cbtShapeIsConvex; extern fn cbtShapeIsConvex(shape: *const Shape) bool; pub const isNonMoving = cbtShapeIsNonMoving; extern fn cbtShapeIsNonMoving(shape: *const Shape) bool; pub const isConcave = cbtShapeIsConcave; extern fn cbtShapeIsConcave(shape: *const Shape) bool; pub const isCompound = cbtShapeIsCompound; extern fn cbtShapeIsCompound(shape: *const Shape) bool; pub const calculateLocalInertia = cbtShapeCalculateLocalInertia; extern fn cbtShapeCalculateLocalInertia( shape: *const Shape, mass: f32, inertia: *[3]f32, ) void; pub const setUserPointer = cbtShapeSetUserPointer; extern fn cbtShapeSetUserPointer(shape: *const Shape, ptr: ?*anyopaque) void; pub const getUserPointer = cbtShapeGetUserPointer; extern fn cbtShapeGetUserPointer(shape: *const Shape) ?*anyopaque; pub const setUserIndex = cbtShapeSetUserIndex; extern fn cbtShapeSetUserIndex(shape: *const Shape, slot: u32, index: i32) void; pub const getUserIndex = cbtShapeGetUserIndex; extern fn cbtShapeGetUserIndex(shape: *const Shape, slot: u32) i32; }; fn ShapeFunctions(comptime T: type) type { return struct { pub fn asShape(shape: *const T) *const Shape { return @ptrCast(*const Shape, shape); } pub fn deallocate(shape: *const T) void { shape.asShape().deallocate(); } pub fn destroy(shape: *const T) void { shape.asShape().destroy(); } pub fn deinit(shape: *const T) void { shape.asShape().deinit(); } pub fn isCreated(shape: *const T) bool { return shape.asShape().isCreated(); } pub fn getType(shape: *const T) ShapeType { return shape.asShape().getType(); } pub fn setMargin(shape: *const T, margin: f32) void { shape.asShape().setMargin(margin); } pub fn getMargin(shape: *const T) f32 { return shape.asShape().getMargin(); } pub fn isPolyhedral(shape: *const T) bool { return shape.asShape().isPolyhedral(); } pub fn isConvex2d(shape: *const T) bool { return shape.asShape().isConvex2d(); } pub fn isConvex(shape: *const T) bool { return shape.asShape().isConvex(); } pub fn isNonMoving(shape: *const T) bool { return shape.asShape().isNonMoving(); } pub fn isConcave(shape: *const T) bool { return shape.asShape().isConcave(); } pub fn isCompound(shape: *const T) bool { return shape.asShape().isCompound(); } pub fn calculateLocalInertia( shape: *const Shape, mass: f32, inertia: *[3]f32, ) void { shape.asShape().calculateLocalInertia(shape, mass, inertia); } pub fn setUserPointer(shape: *const T, ptr: ?*anyopaque) void { shape.asShape().setUserPointer(ptr); } pub fn getUserPointer(shape: *const T) ?*anyopaque { return shape.asShape().getUserPointer(); } pub fn setUserIndex(shape: *const T, slot: u32, index: i32) void { shape.asShape().setUserIndex(slot, index); } pub fn getUserIndex(shape: *const T, slot: u32) i32 { return shape.asShape().getUserIndex(slot); } }; } pub const BoxShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init(half_extents: *const [3]f32) *const BoxShape { const box = allocate(); box.create(half_extents); return box; } pub fn allocate() *const BoxShape { return @ptrCast(*const BoxShape, Shape.allocate(.box)); } pub const create = cbtShapeBoxCreate; extern fn cbtShapeBoxCreate( box: *const BoxShape, half_extents: *const [3]f32, ) void; pub const getHalfExtentsWithoutMargin = cbtShapeBoxGetHalfExtentsWithoutMargin; extern fn cbtShapeBoxGetHalfExtentsWithoutMargin( box: *const BoxShape, half_extents: *[3]f32, ) void; pub const getHalfExtentsWithMargin = cbtShapeBoxGetHalfExtentsWithMargin; extern fn cbtShapeBoxGetHalfExtentsWithMargin( box: *const BoxShape, half_extents: *[3]f32, ) void; }; pub const SphereShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init(radius: f32) *const SphereShape { const sphere = allocate(); sphere.create(radius); return sphere; } pub fn allocate() *const SphereShape { return @ptrCast(*const SphereShape, Shape.allocate(.sphere)); } pub const create = cbtShapeSphereCreate; extern fn cbtShapeSphereCreate(sphere: *const SphereShape, radius: f32) void; pub const getRadius = cbtShapeSphereGetRadius; extern fn cbtShapeSphereGetRadius(sphere: *const SphereShape) f32; pub const setUnscaledRadius = cbtShapeSphereSetUnscaledRadius; extern fn cbtShapeSphereSetUnscaledRadius( sphere: *const SphereShape, radius: f32, ) void; }; pub const CapsuleShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init(radius: f32, height: f32, upaxis: Axis) *const CapsuleShape { const capsule = allocate(); capsule.create(radius, height, upaxis); return capsule; } pub fn allocate() *const CapsuleShape { return @ptrCast(*const CapsuleShape, Shape.allocate(.capsule)); } pub const create = cbtShapeCapsuleCreate; extern fn cbtShapeCapsuleCreate( capsule: *const CapsuleShape, radius: f32, height: f32, upaxis: Axis, ) void; pub const getUpAxis = cbtShapeCapsuleGetUpAxis; extern fn cbtShapeCapsuleGetUpAxis(capsule: *const CapsuleShape) Axis; pub const getHalfHeight = cbtShapeCapsuleGetHalfHeight; extern fn cbtShapeCapsuleGetHalfHeight(capsule: *const CapsuleShape) f32; pub const getRadius = cbtShapeCapsuleGetRadius; extern fn cbtShapeCapsuleGetRadius(capsule: *const CapsuleShape) f32; }; pub const CylinderShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init( half_extents: *const [3]f32, upaxis: Axis, ) *const CylinderShape { const cylinder = allocate(); cylinder.create(half_extents, upaxis); return cylinder; } pub fn allocate() *const CylinderShape { return @ptrCast(*const CylinderShape, Shape.allocate(.cylinder)); } pub const create = cbtShapeCylinderCreate; extern fn cbtShapeCylinderCreate( cylinder: *const CylinderShape, half_extents: *const [3]f32, upaxis: Axis, ) void; pub const getHalfExtentsWithoutMargin = cbtShapeCylinderGetHalfExtentsWithoutMargin; extern fn cbtShapeCylinderGetHalfExtentsWithoutMargin( cylinder: *const CylinderShape, half_extents: *[3]f32, ) void; pub const getHalfExtentsWithMargin = cbtShapeCylinderGetHalfExtentsWithMargin; extern fn cbtShapeCylinderGetHalfExtentsWithMargin( cylinder: *const CylinderShape, half_extents: *[3]f32, ) void; pub const getUpAxis = cbtShapeCylinderGetUpAxis; extern fn cbtShapeCylinderGetUpAxis(capsule: *const CylinderShape) Axis; }; pub const CompoundShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init( params: struct { enable_dynamic_aabb_tree: bool = true, initial_child_capacity: u32 = 0, }, ) *const CompoundShape { const cshape = allocate(); cshape.create( params.enable_dynamic_aabb_tree, params.initial_child_capacity, ); return cshape; } pub fn allocate() *const CompoundShape { return @ptrCast(*const CompoundShape, Shape.allocate(.compound)); } pub const create = cbtShapeCompoundCreate; extern fn cbtShapeCompoundCreate( cshape: *const CompoundShape, enable_dynamic_aabb_tree: bool, initial_child_capacity: u32, ) void; pub const addChild = cbtShapeCompoundAddChild; extern fn cbtShapeCompoundAddChild( cshape: *const CompoundShape, local_transform: *[12]f32, child_shape: *const Shape, ) void; pub const removeChild = cbtShapeCompoundRemoveChild; extern fn cbtShapeCompoundRemoveChild( cshape: *const CompoundShape, child_shape: *const Shape, ) void; pub const removeChildByIndex = cbtShapeCompoundRemoveChildByIndex; extern fn cbtShapeCompoundRemoveChildByIndex( cshape: *const CompoundShape, index: i32, ) void; pub const getNumChilds = cbtShapeCompoundGetNumChilds; extern fn cbtShapeCompoundGetNumChilds(cshape: *const CompoundShape) i32; pub const getChild = cbtShapeCompoundGetChild; extern fn cbtShapeCompoundGetChild( cshape: *const CompoundShape, index: i32, ) *const Shape; pub const getChildTransform = cbtShapeCompoundGetChildTransform; extern fn cbtShapeCompoundGetChildTransform( cshape: *const CompoundShape, index: i32, local_transform: *[12]f32, ) void; }; pub const TriangleMeshShape = opaque { usingnamespace ShapeFunctions(@This()); pub fn init() *const TriangleMeshShape { const trimesh = allocate(); trimesh.createBegin(); return trimesh; } pub fn finalize(trimesh: *const TriangleMeshShape) void { trimesh.createEnd(); } pub fn allocate() *const TriangleMeshShape { return @ptrCast(*const TriangleMeshShape, Shape.allocate(.trimesh)); } pub const addIndexVertexArray = cbtShapeTriMeshAddIndexVertexArray; extern fn cbtShapeTriMeshAddIndexVertexArray( trimesh: *const TriangleMeshShape, num_triangles: u32, triangles_base: *const anyopaque, triangle_stride: u32, num_vertices: u32, vertices_base: *const anyopaque, vertex_stride: u32, ) void; pub const createBegin = cbtShapeTriMeshCreateBegin; extern fn cbtShapeTriMeshCreateBegin(trimesh: *const TriangleMeshShape) void; pub const createEnd = cbtShapeTriMeshCreateEnd; extern fn cbtShapeTriMeshCreateEnd(trimesh: *const TriangleMeshShape) void; }; pub const Body = opaque { pub fn init( mass: f32, transform: *const [12]f32, shape: *const Shape, ) *const Body { const body = allocate(); body.create(mass, transform, shape); return body; } pub fn deinit(body: *const Body) void { body.destroy(); body.deallocate(); } pub const allocate = cbtBodyAllocate; extern fn cbtBodyAllocate() *const Body; pub const deallocate = cbtBodyDeallocate; extern fn cbtBodyDeallocate(body: *const Body) void; pub const create = cbtBodyCreate; extern fn cbtBodyCreate( body: *const Body, mass: f32, transform: *const [12]f32, shape: *const Shape, ) void; pub const destroy = cbtBodyDestroy; extern fn cbtBodyDestroy(body: *const Body) void; pub const isCreated = cbtBodyIsCreated; extern fn cbtBodyIsCreated(body: *const Body) bool; pub const setShape = cbtBodySetShape; extern fn cbtBodySetShape(body: *const Body, shape: *const Shape) void; pub const getShape = cbtBodyGetShape; extern fn cbtBodyGetShape(body: *const Body) *const Shape; pub const getMass = cbtBodyGetMass; extern fn cbtBodyGetMass(body: *const Body) f32; pub const setRestitution = cbtBodySetRestitution; extern fn cbtBodySetRestitution(body: *const Body, restitution: f32) void; pub const getRestitution = cbtBodyGetRestitution; extern fn cbtBodyGetRestitution(body: *const Body) f32; pub const setFriction = cbtBodySetFriction; extern fn cbtBodySetFriction(body: *const Body, friction: f32) void; pub const getGraphicsWorldTransform = cbtBodyGetGraphicsWorldTransform; extern fn cbtBodyGetGraphicsWorldTransform( body: *const Body, transform: *[12]f32, ) void; pub const applyCentralImpulse = cbtBodyApplyCentralImpulse; extern fn cbtBodyApplyCentralImpulse(body: *const Body, impulse: *[3]f32) void; }; pub const ConstraintType = enum(c_int) { point2point = 3, }; pub const Constraint = opaque { pub const getFixedBody = cbtConGetFixedBody; extern fn cbtConGetFixedBody() *const Body; pub const allocate = cbtConAllocate; extern fn cbtConAllocate(ctype: ConstraintType) *const Constraint; pub const deallocate = cbtConDeallocate; extern fn cbtConDeallocate(con: *const Constraint) void; pub const destroy = cbtConDestroy; extern fn cbtConDestroy(con: *const Constraint) void; pub const isCreated = cbtConIsCreated; extern fn cbtConIsCreated(con: *const Constraint) bool; pub const getType = cbtConGetType; extern fn cbtConGetType(con: *const Constraint) ConstraintType; pub const setEnabled = cbtConSetEnabled; extern fn cbtConSetEnabled(con: *const Constraint, enabled: bool) void; pub const isEnabled = cbtConIsEnabled; extern fn cbtConIsEnabled(con: *const Constraint) bool; pub const getBodyA = cbtConGetBodyA; extern fn cbtConGetBodyA(con: *const Constraint) *const Body; pub const getBodyB = cbtConGetBodyB; extern fn cbtConGetBodyB(con: *const Constraint) *const Body; }; fn ConstraintFunctions(comptime T: type) type { return struct { pub fn asConstraint(con: *const T) *const Constraint { return @ptrCast(*const Constraint, con); } pub fn deallocate(con: *const T) void { con.asConstraint().deallocate(); } pub fn destroy(con: *const T) void { con.asConstraint().destroy(); } pub fn getType(con: *const T) ConstraintType { return con.asConstraint().getType(); } pub fn isCreated(con: *const T) bool { return con.asConstraint().isCreated(); } pub fn setEnabled(con: *const T, enabled: bool) void { con.asConstraint().setEnabled(enabled); } pub fn isEnabled(con: *const T) bool { return con.asConstraint().isEnabled(); } pub fn getBodyA(con: *const T) *const Body { return con.asConstraint().getBodyA(); } pub fn getBodyB(con: *const T) *const Body { return con.asConstraint().getBodyB(); } }; } pub const Point2PointConstraint = opaque { usingnamespace ConstraintFunctions(@This()); pub fn allocate() *const Point2PointConstraint { return @ptrCast( *const Point2PointConstraint, Constraint.allocate(.point2point), ); } pub const create1 = cbtConPoint2PointCreate1; extern fn cbtConPoint2PointCreate1( con: *const Point2PointConstraint, body: *const Body, pivot: *const [3]f32, ) void; pub const create2 = cbtConPoint2PointCreate2; extern fn cbtConPoint2PointCreate2( con: *const Point2PointConstraint, body_a: *const Body, body_b: *const Body, pivot_a: *const [3]f32, pivot_b: *const [3]f32, ) void; pub const setPivotA = cbtConPoint2PointSetPivotA; extern fn cbtConPoint2PointSetPivotA( con: *const Point2PointConstraint, pivot: *const [3]f32, ) void; pub const setPivotB = cbtConPoint2PointSetPivotB; extern fn cbtConPoint2PointSetPivotB( con: *const Point2PointConstraint, pivot: *const [3]f32, ) void; pub const getPivotA = cbtConPoint2PointGetPivotA; extern fn cbtConPoint2PointGetPivotA( con: *const Point2PointConstraint, pivot: *[3]f32, ) void; pub const getPivotB = cbtConPoint2PointGetPivotB; extern fn cbtConPoint2PointGetPivotB( con: *const Point2PointConstraint, pivot: *[3]f32, ) void; pub const setTau = cbtConPoint2PointSetPivotB; extern fn cbtConPoint2PointSetTau( con: *const Point2PointConstraint, tau: f32, ) void; pub const setDamping = cbtConPoint2PointSetDamping; extern fn cbtConPoint2PointSetDamping( con: *const Point2PointConstraint, damping: f32, ) void; pub const setImpulseClamp = cbtConPoint2PointSetImpulseClamp; extern fn cbtConPoint2PointSetImpulseClamp( con: *const Point2PointConstraint, damping: f32, ) void; }; pub const DebugMode = i32; pub const dbgmode_disabled: DebugMode = -1; pub const dbgmode_no_debug: DebugMode = 0; pub const dbgmode_draw_wireframe: DebugMode = 1; pub const dbgmode_draw_aabb: DebugMode = 2; pub const DebugDraw = extern struct { drawLine1: fn ( ?*anyopaque, *const [3]f32, *const [3]f32, *const [3]f32, ) callconv(.C) void, drawLine2: ?fn ( ?*anyopaque, *const [3]f32, *const [3]f32, *const [3]f32, *const [3]f32, ) callconv(.C) void, drawContactPoint: ?fn ( ?*anyopaque, *const [3]f32, *const [3]f32, f32, *const [3]f32, ) callconv(.C) void, context: ?*anyopaque, }; pub const DebugDrawer = struct { lines: std.ArrayList(Vertex), pub const Vertex = struct { position: [3]f32, color: u32, }; pub fn init(alloc: std.mem.Allocator) DebugDrawer { return .{ .lines = std.ArrayList(Vertex).init(alloc) }; } pub fn deinit(debug: *DebugDrawer) void { debug.lines.deinit(); debug.* = undefined; } pub fn getDebugDraw(debug: *DebugDrawer) DebugDraw { return .{ .drawLine1 = drawLine1, .drawLine2 = drawLine2, .drawContactPoint = null, .context = debug, }; } fn drawLine1( context: ?*anyopaque, p0: *const [3]f32, p1: *const [3]f32, color: *const [3]f32, ) callconv(.C) void { const debug = @ptrCast( *DebugDrawer, @alignCast(@alignOf(DebugDrawer), context.?), ); const r = @floatToInt(u32, color[0] * 255.0); const g = @floatToInt(u32, color[1] * 255.0) << 8; const b = @floatToInt(u32, color[2] * 255.0) << 16; const rgb = r | g | b; debug.lines.append( .{ .position = .{ p0[0], p0[1], p0[2] }, .color = rgb }, ) catch unreachable; debug.lines.append( .{ .position = .{ p1[0], p1[1], p1[2] }, .color = rgb }, ) catch unreachable; } fn drawLine2( context: ?*anyopaque, p0: *const [3]f32, p1: *const [3]f32, color0: *const [3]f32, color1: *const [3]f32, ) callconv(.C) void { const debug = @ptrCast( *DebugDrawer, @alignCast(@alignOf(DebugDrawer), context.?), ); const r0 = @floatToInt(u32, color0[0] * 255.0); const g0 = @floatToInt(u32, color0[1] * 255.0) << 8; const b0 = @floatToInt(u32, color0[2] * 255.0) << 16; const rgb0 = r0 | g0 | b0; const r1 = @floatToInt(u32, color1[0] * 255.0); const g1 = @floatToInt(u32, color1[1] * 255.0) << 8; const b1 = @floatToInt(u32, color1[2] * 255.0) << 16; const rgb1 = r1 | g1 | b1; debug.lines.append( .{ .position = .{ p0[0], p0[1], p0[2] }, .color = rgb0 }, ) catch unreachable; debug.lines.append( .{ .position = .{ p1[0], p1[1], p1[2] }, .color = rgb1 }, ) catch unreachable; } }; test "zbullet.world.gravity" { const zm = @import("zmath"); init(std.testing.allocator); defer deinit(); const world = World.init(.{}); defer world.deinit(); world.setGravity(&.{ 0.0, -10.0, 0.0 }); const num_substeps = world.stepSimulation(1.0 / 60.0, .{}); try expect(num_substeps == 1); var gravity: [3]f32 = undefined; world.getGravity(&gravity); try expect(gravity[0] == 0.0 and gravity[1] == -10.0 and gravity[2] == 0.0); world.setGravity(&zm.vec3ToArray(zm.f32x4(1.0, 2.0, 3.0, 0.0))); world.getGravity(&gravity); try expect(gravity[0] == 1.0 and gravity[1] == 2.0 and gravity[2] == 3.0); } test "zbullet.shape.box" { init(std.testing.allocator); defer deinit(); { const box = BoxShape.init(&.{ 4.0, 4.0, 4.0 }); defer box.deinit(); try expect(box.isCreated()); try expect(box.getType() == .box); box.setMargin(0.1); try expect(box.getMargin() == 0.1); var half_extents: [3]f32 = undefined; box.getHalfExtentsWithoutMargin(&half_extents); try expect(half_extents[0] == 3.9 and half_extents[1] == 3.9 and half_extents[2] == 3.9); box.getHalfExtentsWithMargin(&half_extents); try expect(half_extents[0] == 4.0 and half_extents[1] == 4.0 and half_extents[2] == 4.0); try expect(box.isPolyhedral() == true); try expect(box.isConvex() == true); box.setUserIndex(0, 123); try expect(box.getUserIndex(0) == 123); box.setUserPointer(null); try expect(box.getUserPointer() == null); box.setUserPointer(&half_extents); try expect(box.getUserPointer() == @ptrCast(*anyopaque, &half_extents)); const shape = box.asShape(); try expect(shape.getType() == .box); try expect(shape.isCreated()); } { const box = BoxShape.allocate(); defer box.deallocate(); try expect(box.isCreated() == false); box.create(&.{ 1.0, 2.0, 3.0 }); defer box.destroy(); try expect(box.getType() == .box); try expect(box.isCreated() == true); } } test "zbullet.shape.sphere" { init(std.testing.allocator); defer deinit(); { const sphere = SphereShape.init(3.0); defer sphere.deinit(); try expect(sphere.isCreated()); try expect(sphere.getType() == .sphere); sphere.setMargin(0.1); try expect(sphere.getMargin() == 3.0); // For spheres margin == radius. try expect(sphere.getRadius() == 3.0); sphere.setUnscaledRadius(1.0); try expect(sphere.getRadius() == 1.0); const shape = sphere.asShape(); try expect(shape.getType() == .sphere); try expect(shape.isCreated()); } { const sphere = SphereShape.allocate(); errdefer sphere.deallocate(); try expect(sphere.isCreated() == false); sphere.create(1.0); try expect(sphere.getType() == .sphere); try expect(sphere.isCreated() == true); try expect(sphere.getRadius() == 1.0); sphere.destroy(); try expect(sphere.isCreated() == false); sphere.create(2.0); try expect(sphere.getType() == .sphere); try expect(sphere.isCreated() == true); try expect(sphere.getRadius() == 2.0); sphere.destroy(); try expect(sphere.isCreated() == false); sphere.deallocate(); } } test "zbullet.shape.capsule" { init(std.testing.allocator); defer deinit(); const capsule = CapsuleShape.init(2.0, 1.0, .y); defer capsule.deinit(); try expect(capsule.isCreated()); try expect(capsule.getType() == .capsule); capsule.setMargin(0.1); try expect(capsule.getMargin() == 2.0); // For capsules margin == radius. try expect(capsule.getRadius() == 2.0); try expect(capsule.getHalfHeight() == 0.5); try expect(capsule.getUpAxis() == .y); } test "zbullet.shape.cylinder" { init(std.testing.allocator); defer deinit(); const cylinder = CylinderShape.init(&.{ 1.0, 2.0, 3.0 }, .y); defer cylinder.deinit(); try expect(cylinder.isCreated()); try expect(cylinder.getType() == .cylinder); cylinder.setMargin(0.1); try expect(cylinder.getMargin() == 0.1); try expect(cylinder.getUpAxis() == .y); try expect(cylinder.isPolyhedral() == false); try expect(cylinder.isConvex() == true); var half_extents: [3]f32 = undefined; cylinder.getHalfExtentsWithoutMargin(&half_extents); try expect(half_extents[0] == 0.9 and half_extents[1] == 1.9 and half_extents[2] == 2.9); cylinder.getHalfExtentsWithMargin(&half_extents); try expect(half_extents[0] == 1.0 and half_extents[1] == 2.0 and half_extents[2] == 3.0); } test "zbullet.shape.compound" { const zm = @import("zmath"); init(std.testing.allocator); defer deinit(); const cshape = CompoundShape.init(.{}); defer cshape.deinit(); try expect(cshape.isCreated()); try expect(cshape.getType() == .compound); try expect(cshape.isPolyhedral() == false); try expect(cshape.isConvex() == false); try expect(cshape.isCompound() == true); const sphere = SphereShape.init(3.0); defer sphere.deinit(); const box = BoxShape.init(&.{ 1.0, 2.0, 3.0 }); defer box.deinit(); cshape.addChild( &zm.mat43ToArray(zm.translation(1.0, 2.0, 3.0)), sphere.asShape(), ); cshape.addChild( &zm.mat43ToArray(zm.translation(-1.0, -2.0, -3.0)), box.asShape(), ); try expect(cshape.getNumChilds() == 2); try expect(cshape.getChild(0) == sphere.asShape()); try expect(cshape.getChild(1) == box.asShape()); var transform: [12]f32 = undefined; cshape.getChildTransform(1, &transform); const m = zm.loadMat43(transform[0..]); try expect(zm.approxEqAbs(m[0], zm.f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[1], zm.f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[2], zm.f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[3], zm.f32x4(-1.0, -2.0, -3.0, 1.0), 0.0001)); cshape.removeChild(sphere.asShape()); try expect(cshape.getNumChilds() == 1); try expect(cshape.getChild(0) == box.asShape()); cshape.removeChildByIndex(0); try expect(cshape.getNumChilds() == 0); } test "zbullet.shape.trimesh" { init(std.testing.allocator); defer deinit(); const trimesh = TriangleMeshShape.init(); const triangles = [3]u32{ 0, 1, 2 }; const vertices = [_]f32{0.0} ** 9; trimesh.addIndexVertexArray( 1, // num_triangles &triangles, // triangles_base 12, // triangle_stride 3, // num_vertices &vertices, // vertices_base 12, // vertex_stride ); trimesh.finalize(); defer trimesh.deinit(); try expect(trimesh.isCreated()); try expect(trimesh.isNonMoving()); try expect(trimesh.getType() == .trimesh); } test "zbullet.body.basic" { init(std.testing.allocator); defer deinit(); { const world = World.init(.{}); defer world.deinit(); const sphere = SphereShape.init(3.0); defer sphere.deinit(); const transform = [12]f32{ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0, }; const body = Body.init(1.0, &transform, sphere.asShape()); defer body.deinit(); try expect(body.isCreated() == true); try expect(body.getShape() == sphere.asShape()); world.addBody(body); try expect(world.getNumBodies() == 1); try expect(world.getBody(0) == body); world.removeBody(body); try expect(world.getNumBodies() == 0); } { const zm = @import("zmath"); const sphere = SphereShape.init(3.0); defer sphere.deinit(); var transform: [12]f32 = undefined; zm.storeMat43(transform[0..], zm.translation(2.0, 3.0, 4.0)); const body = Body.init(1.0, &transform, sphere.asShape()); errdefer body.deinit(); try expect(body.isCreated() == true); try expect(body.getShape() == sphere.asShape()); body.destroy(); try expect(body.isCreated() == false); body.deallocate(); } { const zm = @import("zmath"); const sphere = SphereShape.init(3.0); defer sphere.deinit(); const body = Body.init( 0.0, // static body &zm.mat43ToArray(zm.translation(2.0, 3.0, 4.0)), sphere.asShape(), ); defer body.deinit(); var transform: [12]f32 = undefined; body.getGraphicsWorldTransform(&transform); const m = zm.loadMat43(transform[0..]); try expect(zm.approxEqAbs(m[0], zm.f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[1], zm.f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[2], zm.f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); try expect(zm.approxEqAbs(m[3], zm.f32x4(2.0, 3.0, 4.0, 1.0), 0.0001)); } } test "zbullet.constraint.point2point" { const zm = @import("zmath"); init(std.testing.allocator); defer deinit(); { const world = World.init(.{}); defer world.deinit(); const sphere = SphereShape.init(3.0); defer sphere.deinit(); const body = Body.init( 1.0, &zm.mat43ToArray(zm.translation(2.0, 3.0, 4.0)), sphere.asShape(), ); defer body.deinit(); const p2p = Point2PointConstraint.allocate(); defer p2p.deallocate(); try expect(p2p.getType() == .point2point); try expect(p2p.isCreated() == false); p2p.create1(body, &.{ 1.0, 2.0, 3.0 }); defer p2p.destroy(); try expect(p2p.getType() == .point2point); try expect(p2p.isCreated() == true); try expect(p2p.isEnabled() == true); try expect(p2p.getBodyA() == body); try expect(p2p.getBodyB() == Constraint.getFixedBody()); var pivot: [3]f32 = undefined; p2p.getPivotA(&pivot); try expect(pivot[0] == 1.0 and pivot[1] == 2.0 and pivot[2] == 3.0); p2p.setPivotA(&.{ -1.0, -2.0, -3.0 }); p2p.getPivotA(&pivot); try expect(pivot[0] == -1.0 and pivot[1] == -2.0 and pivot[2] == -3.0); } { const world = World.init(.{}); defer world.deinit(); const sphere = SphereShape.init(3.0); defer sphere.deinit(); const body0 = Body.init( 1.0, &zm.mat43ToArray(zm.translation(2.0, 3.0, 4.0)), sphere.asShape(), ); defer body0.deinit(); const body1 = Body.init( 1.0, &zm.mat43ToArray(zm.translation(2.0, 3.0, 4.0)), sphere.asShape(), ); defer body1.deinit(); const p2p = Point2PointConstraint.allocate(); defer p2p.deallocate(); p2p.create2(body0, body1, &.{ 1.0, 2.0, 3.0 }, &.{ -1.0, -2.0, -3.0 }); defer p2p.destroy(); try expect(p2p.isEnabled() == true); try expect(p2p.getBodyA() == body0); try expect(p2p.getBodyB() == body1); try expect(p2p.getType() == .point2point); try expect(p2p.isCreated() == true); var pivot: [3]f32 = undefined; p2p.getPivotA(&pivot); try expect(pivot[0] == 1.0 and pivot[1] == 2.0 and pivot[2] == 3.0); p2p.getPivotB(&pivot); try expect(pivot[0] == -1.0 and pivot[1] == -2.0 and pivot[2] == -3.0); world.addConstraint(p2p.asConstraint(), false); try expect(world.getNumConstraints() == 1); try expect(world.getConstraint(0) == p2p.asConstraint()); world.removeConstraint(p2p.asConstraint()); try expect(world.getNumConstraints() == 0); } }
libs/zbullet/src/zbullet.zig
const sf = @import("../sfml.zig"); const Transform = @This(); /// Identity matrix (doesn't do anything) pub const Identity = Transform{ .matrix = .{ 1, 0, 0, 0, 1, 0, 0, 0, 1 } }; /// Converts this transform to a csfml one /// For inner workings pub fn _toCSFML(self: Transform) sf.c.sfTransform { return @bitCast(sf.c.sfTransform, self); } /// Converts a transform from a csfml object /// For inner workings pub fn _fromCSFML(transform: sf.c.sfTransform) Transform { return @bitCast(Transform, transform); } // Matrix transformations /// Transforms a point by this matrix pub fn transformPoint(self: Transform, point: sf.system.Vector2f) sf.system.Vector2f { const ptr = @ptrCast(*const sf.c.sfTransform, &self); return sf.system.Vector2f._fromCSFML(sf.c.sfTransform_transformPoint(ptr, point._toCSFML())); } /// Transforms a rectangle by this matrix pub fn transformRect(self: Transform, rect: sf.graphics.FloatRect) sf.graphics.FloatRect { const ptr = @ptrCast(*const sf.c.sfTransform, &self); return sf.system.Vector2f._fromCSFML(sf.c.sfTransform_transformRect(ptr, rect._toCSFML())); } // Operations /// Gets the inverse of this transformation /// Returns the identity if it can't be calculated pub fn getInverse(self: Transform) Transform { const ptr = @ptrCast(*const sf.c.sfTransform, &self); return _fromCSFML(sf.c.sfTransform_getInverse(ptr)); } /// Combines two transformations pub fn combine(self: Transform, other: Transform) Transform { const ptr = @ptrCast(*const sf.c.sfTransform, &self); return _fromCSFML(sf.c.sfTransform_combine(ptr, other._toCSFML(other))); } /// Translates this transform by x and y pub fn translate(self: *Transform, translation: sf.system.Vector2f) void { const ptr = @ptrCast(*sf.c.sfTransform, self); sf.c.sfTransform_translate(ptr, translation.x, translation.y); } /// Rotates this transform pub fn rotate(self: *Transform, angle: f32) void { const ptr = @ptrCast(*sf.c.sfTransform, self); sf.c.sfTransform_rotate(ptr, angle); } /// Scales this transform pub fn scale(self: *Transform, factor: sf.system.Vector2f) void { const ptr = @ptrCast(*sf.c.sfTransform, self); sf.c.sfTransform_scale(ptr, factor.x, factor.y); } /// Transform comparison pub const equal = @compileError("Use std.mem.eql instead"); /// The matrix defining this transform matrix: [9]f32
src/sfml/graphics/Transform.zig
const assert = @import("std").debug.assert; const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const ConvexShape = @This(); // Constructor/destructor /// Creates a new empty convex shape pub fn create() !ConvexShape { var shape = sf.c.sfConvexShape_create(); if (shape == null) return sf.Error.nullptrUnknownReason; return ConvexShape{ ._ptr = shape.? }; } /// Destroys a convex shape pub fn destroy(self: *ConvexShape) void { sf.c.sfConvexShape_destroy(self._ptr); self._ptr = undefined; } // Draw function /// The draw function of this shape /// Meant to be called by your_target.draw(your_shape, .{}); pub fn sfDraw(self: ConvexShape, target: anytype, states: ?*sf.c.sfRenderStates) void { switch (@TypeOf(target)) { sf.RenderWindow => sf.c.sfRenderWindow_drawConvexShape(target._ptr, self._ptr, states), sf.RenderTexture => sf.c.sfRenderTexture_drawConvexShape(target._ptr, self._ptr, states), else => @compileError("target must be a render target"), } } // Getters/setters /// Gets how many points this convex polygon shape has pub fn getPointCount(self: ConvexShape) usize { return sf.c.sfConvexShape_getPointCount(self._ptr); } /// Sets how many points this convex polygon shape has /// Must be greater than 2 to get a valid shape pub fn setPointCount(self: *ConvexShape, count: usize) void { sf.c.sfConvexShape_setPointCount(self._ptr, count); } /// Gets a point using its index (asserts the index is within range) pub fn getPoint(self: ConvexShape, index: usize) sf.Vector2f { assert(index < self.getPointCount()); return sf.Vector2f._fromCSFML(sf.c.sfConvexShape_getPoint(self._ptr, index)); } /// Sets a point using its index (asserts the index is within range) /// setPointCount must be called first /// Shape must remain convex and the points have to be ordered! pub fn setPoint(self: *ConvexShape, index: usize, point: sf.Vector2f) void { assert(index < self.getPointCount()); sf.c.sfConvexShape_setPoint(self._ptr, index, point._toCSFML()); } /// Gets the fill color of this convex shape pub fn getFillColor(self: ConvexShape) sf.Color { return sf.Color._fromCSFML(sf.c.sfConvexShape_getFillColor(self._ptr)); } /// Sets the fill color of this convex shape pub fn setFillColor(self: *ConvexShape, color: sf.Color) void { sf.c.sfConvexShape_setFillColor(self._ptr, color._toCSFML()); } /// Gets the outline color of this convex shape pub fn getOutlineColor(self: ConvexShape) sf.Color { return sf.Color._fromCSFML(sf.c.sfConvexShape_getOutlineColor(self._ptr)); } /// Sets the outline color of this convex shape pub fn setOutlineColor(self: *ConvexShape, color: sf.Color) void { sf.c.sfConvexShape_setOutlineColor(self._ptr, color._toCSFML()); } /// Gets the outline thickness of this convex shape pub fn getOutlineThickness(self: ConvexShape) f32 { return sf.c.sfConvexShape_getOutlineThickness(self._ptr); } /// Sets the outline thickness of this convex shape pub fn setOutlineThickness(self: *ConvexShape, thickness: f32) void { sf.c.sfConvexShape_setOutlineThickness(self._ptr, thickness); } /// Gets the position of this convex shape pub fn getPosition(self: ConvexShape) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfConvexShape_getPosition(self._ptr)); } /// Sets the position of this convex shape pub fn setPosition(self: *ConvexShape, pos: sf.Vector2f) void { sf.c.sfConvexShape_setPosition(self._ptr, pos._toCSFML()); } /// Adds the offset to this shape's position pub fn move(self: *ConvexShape, offset: sf.Vector2f) void { sf.c.sfConvexShape_move(self._ptr, offset._toCSFML()); } /// Gets the origin of this convex shape pub fn getOrigin(self: ConvexShape) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfConvexShape_getOrigin(self._ptr)); } /// Sets the origin of this convex shape pub fn setOrigin(self: *ConvexShape, origin: sf.Vector2f) void { sf.c.sfConvexShape_setOrigin(self._ptr, origin._toCSFML()); } /// Gets the rotation of this convex shape pub fn getRotation(self: ConvexShape) f32 { return sf.c.sfConvexShape_getRotation(self._ptr); } /// Sets the rotation of this convex shape pub fn setRotation(self: *ConvexShape, angle: f32) void { sf.c.sfConvexShape_setRotation(self._ptr, angle); } /// Rotates this shape by a given amount pub fn rotate(self: *ConvexShape, angle: f32) void { sf.c.sfConvexShape_rotate(self._ptr, angle); } /// Gets the texture of this shape pub fn getTexture(self: ConvexShape) ?sf.Texture { const t = sf.c.sfConvexShape_getTexture(self._ptr); if (t) |tex| { return sf.Texture{ ._const_ptr = tex }; } else return null; } /// Sets the texture of this shape pub fn setTexture(self: *ConvexShape, texture: ?sf.Texture) void { var tex = if (texture) |t| t._get() else null; sf.c.sfConvexShape_setTexture(self._ptr, tex, 0); } /// Gets the sub-shapeangle of the texture that the shape will display pub fn getTextureRect(self: ConvexShape) sf.IntRect { return sf.IntRect._fromCSFML(sf.c.sfConvexShape_getTextureRect(self._ptr)); } /// Sets the sub-shapeangle of the texture that the shape will display pub fn setTextureRect(self: *ConvexShape, shape: sf.IntRect) void { sf.c.sfConvexShape_getTextureRect(self._ptr, shape._toCSFML()); } /// Gets the bounds in the local coordinates system pub fn getLocalBounds(self: ConvexShape) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfConvexShape_getLocalBounds(self._ptr)); } /// Gets the bounds in the global coordinates pub fn getGlobalBounds(self: ConvexShape) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfConvexShape_getGlobalBounds(self._ptr)); } /// Pointer to the csfml structure _ptr: *sf.c.sfConvexShape, test "convex shape: sane getters and setters" { const tst = @import("std").testing; var shape = try ConvexShape.create(); defer shape.destroy(); shape.setPointCount(3); shape.setPoint(0, .{ .x = 0, .y = 0 }); shape.setPoint(1, .{ .x = 1, .y = 1 }); shape.setPoint(2, .{ .x = -1, .y = 1 }); try tst.expectEqual(@as(usize, 3), shape.getPointCount()); // TODO: find out why that doesn't work //try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 1 }, shape.getPoint(1)); _ = shape.getPoint(0); shape.setFillColor(sf.Color.Yellow); shape.setOutlineColor(sf.Color.Red); shape.setOutlineThickness(3); shape.setRotation(15); shape.setPosition(.{ .x = 1, .y = 2 }); shape.setOrigin(.{ .x = 20, .y = 25 }); shape.setTexture(null); //Weirdly, getTexture if texture wasn't set gives a wrong pointer try tst.expectEqual(sf.Color.Yellow, shape.getFillColor()); try tst.expectEqual(sf.Color.Red, shape.getOutlineColor()); try tst.expectEqual(@as(f32, 3), shape.getOutlineThickness()); try tst.expectEqual(@as(f32, 15), shape.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, shape.getPosition()); try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, shape.getOrigin()); try tst.expectEqual(@as(?sf.Texture, null), shape.getTexture()); shape.rotate(5); shape.move(.{ .x = -5, .y = 5 }); try tst.expectEqual(@as(f32, 20), shape.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, shape.getPosition()); _ = shape.getTextureRect(); _ = shape.getGlobalBounds(); _ = shape.getLocalBounds(); }
src/sfml/graphics/ConvexShape.zig
const std = @import("std"); pub fn Json(comptime T: type) type { return struct { data: T, pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; // TODO: convert stringify options return std.json.stringify(self.data, .{ .string = .{ .String = .{} } }, writer); } }; } pub fn json(data: anytype) Json(@TypeOf(data)) { return .{ .data = data }; } pub fn time(millis: i64) Time { return .{ .millis = millis }; } const Time = struct { millis: i64, pub fn format(self: Time, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; const hours = @intCast(u16, @divFloor(self.millis, std.time.ms_per_hour)); const mins = @intCast(u8, @mod(@divFloor(self.millis, std.time.ms_per_min), 60)); const secs = @intCast(u8, @mod(@divFloor(self.millis, std.time.ms_per_s), 60)); const mill = @intCast(u16, @mod(self.millis, 1000)); return std.fmt.format(writer, "{: >4}:{:0>2}:{:0>2}.{:0>3}", .{ hours, mins, secs, mill }); } }; pub fn concat(segments: []const []const u8) Concat { return .{ .segments = segments }; } const Concat = struct { segments: []const []const u8, pub fn format(self: Concat, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; for (self.segments) |segment| { try writer.writeAll(segment); } } pub fn jsonStringify(self: Concat, options: std.json.StringifyOptions, writer: anytype) !void { _ = options; try writer.writeAll("\""); for (self.segments) |segment| { try writeJsonSegment(writer, segment); } try writer.writeAll("\""); } fn writeJsonSegment(writer: anytype, string: []const u8) !void { var prev: usize = 0; for (string) |char, i| { const escaped = switch (char) { '\\' => "\\\\", '\"' => "\\\"", 0x8 => "\\b", 0xC => "\\f", '\n' => "\\n", '\r' => "\\r", '\t' => "\\t", else => continue, }; if (prev < i) { try writer.writeAll(string[prev..i]); } try writer.writeAll(escaped); prev = i + 1; } if (prev < string.len) { try writer.writeAll(string[prev..]); } } };
src/format.zig
const std = @import("std"); const print = std.debug.print; const Distances = std.StringHashMap(std.StringHashMap(usize)); pub fn main() anyerror!void { const global_allocator = std.heap.page_allocator; var file = try std.fs.cwd().openFile( "./inputs/day09.txt", .{ .read = true, }, ); var reader = std.io.bufferedReader(file.reader()).reader(); var line = std.ArrayList(u8).init(global_allocator); defer line.deinit(); var distances = Distances.init(global_allocator); defer distances.deinit(); var arena = std.heap.ArenaAllocator.init(global_allocator); defer arena.deinit(); var allocator = &arena.allocator; while (reader.readUntilDelimiterArrayList(&line, '\n', 100)) { var tokens = std.mem.tokenize(u8, line.items, " "); const from = try std.mem.Allocator.dupe(allocator, u8, tokens.next().?); _ = tokens.next(); const to = try std.mem.Allocator.dupe(allocator, u8, tokens.next().?); _ = tokens.next(); const distance = try std.fmt.parseInt(usize, tokens.next().?, 10); if (distances.getPtr(from)) |m| { try m.put(to, distance); } else { var m = std.StringHashMap(usize).init(allocator); try m.put(to, distance); try distances.put(from, m); } if (distances.getPtr(to)) |m| { try m.put(from, distance); } else { var m = std.StringHashMap(usize).init(allocator); try m.put(from, distance); try distances.put(to, m); } } else |err| { if (err != error.EndOfStream) { return err; } } var so_far = std.StringArrayHashMap(void).init(global_allocator); defer so_far.deinit(); const shortest = try shortest_path(false, distances, so_far, 0); print("Part 1: {d}\n", .{shortest}); so_far.clearRetainingCapacity(); const longest = try shortest_path(true, distances, so_far, 0); print("Part 2: {d}\n", .{longest}); } fn shortest_path(longest: bool, distances: Distances, so_far_const: std.StringArrayHashMap(void), distance_so_far: usize) anyerror!usize { var so_far = try so_far_const.clone(); defer so_far.deinit(); var keys = distances.keyIterator(); var best_route: ?usize = null; var current_distances: ?*std.StringHashMap(usize) = null; if (so_far.popOrNull()) |current| { try so_far.put(current.key, .{}); current_distances = distances.getPtr(current.key).?; } while (keys.next()) |k| { if (!so_far.contains(k.*)) { try so_far.put(k.*, .{}); defer _ = so_far.pop(); var d_so_far = distance_so_far; if (current_distances) |d| { d_so_far += d.get(k.*).?; } const distance = try shortest_path(longest, distances, so_far, d_so_far); if (best_route) |r| { if (longest and distance > r) { best_route = distance; } else if (!longest and distance < r) { best_route = distance; } } else { best_route = distance; } } } if (best_route) |s| { return s; } else { return distance_so_far; } }
src/day09.zig
const std = @import("std"); const ascii = std.ascii; const mem = std.mem; const io = std.io; const Buffer = std.Buffer; pub const EXTENSION_NO_INTRA_EMPHASIS = 1; pub const EXTENSION_TABLES = 2; pub const EXTENSION_FENCED_CODE = 4; pub const EXTENSION_AUTOLINK = 8; pub const EXTENSION_STRIKETHROUGH = 16; pub const EXTENSION_LAX_HTML_BLOCKS = 32; pub const EXTENSION_SPACE_HEADERS = 64; pub const EXTENSION_HARD_LINE_BREAK = 128; pub const EXTENSION_TAB_SIZE_EIGHT = 256; pub const EXTENSION_FOOTNOTES = 512; pub const EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK = 1024; pub const EXTENSION_HEADER_IDS = 2048; pub const EXTENSION_TITLEBLOCK = 4096; pub const EXTENSION_AUTO_HEADER_IDS = 8192; pub const EXTENSION_BACKSLASH_LINE_BREAK = 16384; pub const EXTENSION_DEFINITION_LISTS = 32768; pub const EXTENSION_JOIN_LINES = 65536; const common_extensions = 0 | EXTENSION_NO_INTRA_EMPHASIS | EXTENSION_TABLES | EXTENSION_FENCED_CODE | EXTENSION_AUTOLINK | EXTENSION_STRIKETHROUGH | EXTENSION_SPACE_HEADERS | EXTENSION_HEADER_IDS | EXTENSION_BACKSLASH_LINE_BREAK | EXTENSION_DEFINITION_LISTS; pub const LINK_TYPE_NOT_AUTOLINK = 1; pub const LINK_TYPE_NORMAL = 2; pub const LINK_TYPE_EMAIL = 4; pub const LIST_TYPE_ORDERED = 1; pub const LIST_TYPE_DEFINITION = 2; pub const LIST_TYPE_TERM = 4; pub const LIST_ITEM_CONTAINS_BLOCK = 8; pub const LIST_ITEM_BEGINNING_OF_LIST = 16; pub const LIST_ITEM_END_OF_LIST = 32; pub const TABLE_ALIGNMENT_LEFT = 1; pub const TABLE_ALIGNMENT_RIGHT = 2; pub const TABLE_ALIGNMENT_CENTER = 3; pub const TAB_SIZE_DEFAULT = 4; pub const TAB_SIZE_EIGHT = 8; pub const TextIter = struct { nextFn: fn (x: *TextIter) bool, pub fn text(self: *TextIter) bool { return self.nextFn(self); } }; pub const Renderer = struct { //block-level blockCodeFn: fn (r: *Renderer, out: *Buffer, text: []const u8, info_string: []const u8) anyerror!void, blockQuoteFn: fn (r: *Renderer, out: *Buffer, text: []const u8) anyerror!void, blockHtmlFn: fn (r: *Renderer, out: *Buffer, text: []const u8) anyerror!void, headerFn: fn (r: *Renderer, out: *Buffer, text: *TextIter, level: usize, id: ?[]const u8) anyerror!void, hruleFn: fn (r: *Renderer, out: *Buffer) anyerror!void, listFn: fn (r: *Renderer, out: *Buffer, text: *TextIter, flags: usize) anyerror!void, listItemFn: fn (r: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void, paragraphFn: fn (r: *Renderer, out: *Buffer, text: *TextIter) anyerror!void, tableFn: fn (r: *Renderer, out: *Buffer, header: []const u8, body: []const u8, colum_data: []usize) anyerror!void, tableRowFn: fn (r: *Renderer, out: *Buffer, text: []const u8) anyerror!void, tableHeaderCellFn: fn (r: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void, tableCellFn: fn (r: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void, footnotesFn: fn (r: *Renderer, out: *Buffer, text: *TextIter) anyerror!void, footnoteItemFn: fn (r: *Renderer, out: *Buffer, name: []const u8, text: []const u8, flags: usize) anyerror!void, titleBlockFn: fn (r: *Renderer, out: *Buffer, text: []const u8) anyerror!void, // Span-level callbacks autoLinkFn: fn (r: *Renderer, buf: *Buffer, link: []const u8, kind: usize) anyerror!void, codeSpanFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, doubleEmphasisFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, emphasisFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, imageFn: fn (r: *Renderer, buf: *Buffer, link: []const u8, title: ?[]const u8, alt: ?[]const u8) anyerror!void, lineBreakFn: fn (r: *Renderer, buf: *Buffer) anyerror!void, linkFn: fn (r: *Renderer, buf: *Buffer, link: []const u8, title: ?[]const u8, content: []const u8) anyerror!void, rawHtmlTagFn: fn (r: *Renderer, buf: *Buffer, tag: []const u8) anyerror!void, tripleEmphasisFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, strikeThroughFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, footnoteRefFn: fn (r: *Renderer, buf: *Buffer, ref: []const u8, id: usize) anyerror!void, // Low-level callbacks entityFn: fn (r: *Renderer, buf: *Buffer, entity: []const u8) anyerror!void, normalTextFn: fn (r: *Renderer, buf: *Buffer, text: []const u8) anyerror!void, // Header and footer documentHeaderFn: fn (r: *Renderer, buf: *Buffer) anyerror!void, documentFooterFn: fn (r: *Renderer, buf: *Buffer) anyerror!void, getFlagsFn: fn (r: *Renderer) usize, pub fn blockCode(self: *Renderer, out: *Buffer, text: []const u8, info_string: []const u8) anyerror!void { try self.blockCodeFn(self, out, text, info_string); } pub fn blockQuote(self: *Renderer, out: *Buffer, text: []const u8) anyerror!void { try self.blockQuoteFn(self, out, text); } pub fn blockHtml(self: *Renderer, out: *Buffer, text: []const u8) anyerror!void { try self.blockHtmlFn(self, out, text); } pub fn header(self: *Renderer, out: *Buffer, text: *TextIter, level: usize, id: []const u8) anyerror!void { try self.headerFn(self, out, text, level, id); } pub fn hrule(self: *Renderer, out: *Buffer) anyerror!void { try self.hruleFn(self, out); } pub fn list(self: *Renderer, out: *Buffer, text: *TextIter, flags: usize) anyerror!void { try self.listFn(self, out, text, flags); } pub fn listItem(self: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void { try self.listItemFn(self, out, text, flags); } pub fn paragraph(self: *Renderer, out: *Buffer, text: *TextIter) anyerror!void { try self.paragraphFn(self, out, text); } pub fn table(self: *Renderer, out: *Buffer, header: []const u8, body: []const u8, colum_data: []usize) anyerror!void { try self.tableFn(self, out, header, body, colum_data); } pub fn tableRow(self: *Renderer, out: *Buffer, text: []const u8) anyerror!void { try self.tableRowFn(self, out, text); } pub fn tableHeaderCell(self: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void { try self.tableHeaderCellFn(self, out, text, flags); } pub fn tableCell(self: *Renderer, out: *Buffer, text: []const u8, flags: usize) anyerror!void { try self.tableCellFn(self, out, text, flags); } pub fn footnotes(self: *Renderer, out: *Buffer, text: *TextIter) anyerror!void { try self.footnotesFn(self, out, text); } pub fn footnoteItem(self: *Renderer, out: *Buffer, name: []const u8, text: []const u8, flags: usize) anyerror!void { try self.footnoteItemFn(self, out, name, text, flags); } pub fn titleBlock(self: *Renderer, out: *Buffer, text: []const u8) anyerror!void { try self.titleBlockFn(self, out, text); } pub fn autoLink(self: *Renderer, buf: *Buffer, link: []const u8, kind: usize) anyerror!void { try self.autoLinkFn(self, buf, link, kind); } pub fn codeSpan(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.codeSpanFn(self, buf, text); } pub fn doubleEmphasis(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.doubleEmphasisFn(self, buf, text); } pub fn emphasis(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.emphasisFn(self, buf, text); } pub fn image(self: *Renderer, buf: *Buffer, link: []const u8, title: []const u8, alt: []const u8) anyerror!void { try self.imageFn(self, buf, link, title, alt); } pub fn lineBreak(self: *Renderer, buf: *Buffer) anyerror!void { try self.lineBreakFn(self, buf); } pub fn link(self: *Renderer, buf: *Buffer, link: []const u8, title: ?[]const u8, content: []const u8) anyerror!void { try self.linkFn(self, buf, link, title, content); } pub fn rawHtmlTag(self: *Renderer, buf: *Buffer, tag: []const u8) anyerror!void { try self.rawHtmlTagFn(self, buf, tag); } pub fn tripleEmphasis(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.tripleEmphasisFn(self, buf, text); } pub fn strikeThrough(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.strikeThroughFn(self, buf, text); } pub fn footnoteRef(self: *Renderer, buf: *Buffer, ref: []const u8, id: usize) anyerror!void { try self.footnoteRefFn(self, buf, id); } pub fn entity(self: *Renderer, buf: *Buffer, entity: []const u8) anyerror!void { try self.entityFn(self, buf, entity); } pub fn normalText(self: *Renderer, buf: *Buffer, text: []const u8) anyerror!void { try self.normalTextFn(self, buf, text); } pub fn documentHeader(self: *Renderer, buf: *Buffer) anyerror!void { try self.documentHeaderFn(self, buf); } pub fn documentFooter(self: *Renderer, buf: *Buffer) anyerror!void { try self.documentFooterFn(self, buf); } pub fn getFlags(self: *Renderer) usize { try self.getFlagsFn(self); } }; pub const HTML_SKIP_HTML = 1; pub const HTML_SKIP_STYLE = 2; pub const HTML_SKIP_IMAGES = 4; pub const HTML_SKIP_LINKS = 8; pub const HTML_SAFELINK = 16; pub const HTML_NOFOLLOW_LINKS = 32; pub const HTML_NOREFERRER_LINKS = 64; pub const HTML_HREF_TARGET_BLANK = 128; pub const HTML_TOC = 256; pub const HTML_OMIT_CONTENTS = 512; pub const HTML_COMPLETE_PAGE = 1024; pub const HTML_USE_XHTML = 2048; pub const HTML_USE_SMARTYPANTS = 4096; pub const HTML_SMARTYPANTS_FRACTIONS = 8192; pub const HTML_SMARTYPANTS_DASHES = 16384; pub const HTML_SMARTYPANTS_LATEX_DASHES = 32768; pub const HTML_SMARTYPANTS_ANGLED_QUOTES = 65536; pub const HTML_SMARTYPANTS_QUOTES_NBSP = 131072; pub const HTML_FOOTNOTE_RETURN_LINKS = 262144; const common_html_flags = 0 | HTML_USE_XHTML | HTML_USE_SMARTYPANTS | HTML_SMARTYPANTS_FRACTIONS | HTML_SMARTYPANTS_DASHES | HTML_SMARTYPANTS_LATEX_DASHES; pub const ID = struct { txt: ?[]const u8, prefix: ?[]const u8, suffix: ?[]const u8, index: i64, toc: bool, pub fn init( txt: ?[]const u8, prefix: ?[]const u8, suffix: ?[]const u8, index: i64, toc: bool, ) ID { return ID{ .txt = txt, .prefix = prefix, .suffix = suffix, .index = index, .toc = toc, }; } pub fn valid(self: ID) bool { if (self.txt != null or self.toc) return true; return false; } pub fn format( self: ID, comptime fmt: []const u8, comptime options: std.fmt.FormatOptions, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void, ) Errors!void { if (self.prefix) |prefix| { try output(context, prefix); } if (self.txt) |txt| { try output(context, txt); } else if (self.toc) { try output(context, "toc"); } try std.fmt.format( context, Errors, output, "_{}", self.index, ); if (self.suffix) |suffix| { try output(context, suffix); } } }; pub const HTML = struct { flags: usize, close_tag: []const u8, title: ?[]const u8, css: ?[]const u8, params: Params, toc_marker: usize, header_count: i64, current_level: usize, toc: Buffer, renderer: Renderer, pub const Params = struct { absolute_prefix: ?[]const u8, footnote_anchor_prefix: ?[]const u8, footnote_return_link_contents: ?[]const u8, header_id_prefix: ?[]const u8, header_id_suffix: ?[]const u8, }; const xhtml_close = "/>"; const html_close = ">"; pub fn init(a: *mem.Allocator) !HTML { return HTML{ .flags = common_html_flags, .close_tag = html_close, .title = null, .css = null, .params = Params{ .absolute_prefix = null, .footnote_anchor_prefix = null, .footnote_return_link_contents = "<sup>[return]</sup>", .header_id_prefix = null, .header_id_suffix = null, }, .toc_marker = 0, .header_count = 0, .current_level = 0, .toc = try Buffer.init(a, ""), .renderer = Renderer{ .blockCodeFn = blockCode, .blockQuoteFn = blockQuote, .blockHtmlFn = blockQuote, .headerFn = header, .hruleFn = hrule, .listFn = list, .listItemFn = listItem, .paragraphFn = paragraph, .tableFn = table, .tableRowFn = tableRow, .tableHeaderCellFn = tableHeaderCell, .tableCellFn = tableCell, .footnotesFn = footnotes, .footnoteItemFn = footnoteItem, .titleBlockFn = titleBlock, .autoLinkFn = autoLink, .codeSpanFn = codeSpan, .doubleEmphasisFn = doubleEmphasis, .emphasisFn = emphasis, .imageFn = image, .lineBreakFn = lineBreak, .linkFn = link, .rawHtmlTagFn = rawHtmlTag, .tripleEmphasisFn = tripleEmphasis, .strikeThroughFn = strikeThrough, .footnoteRefFn = footnoteRef, .entityFn = entity, .normalTextFn = normalText, .documentHeaderFn = documentHeader, .documentFooterFn = documentFooter, .getFlagsFn = getFlags, }, }; } fn escapeChar(ch: u8) bool { return switch (ch) { '"', '&', '<', '>' => true, else => false, }; } fn escapeSingleChar(buf: *Buffer, char: u8) !void { switch (char) { '"' => { try buf.append("&quot;"); }, '&' => { try buf.append("&amp;"); }, '<' => { try buf.append("&lt;"); }, '>' => { try buf.append("&gt;"); }, else => {}, } } fn attrEscape(buf: *Buffer, src: []const u8) !void { var o: usize = 0; for (src) |s, i| { if (escapeChar(s)) { if (i > o) { try buf.append(src[o..i]); } o = i + 1; try escapeSingleChar(buf, s); } } if (o < src.len) { try buf.append(src[o..]); } } // naiveReplace simple replacing occurance of orig ,with with contents while // writing the result to buf. // Not optimized. fn naiveReplace(buf: *Buffer, src: []const u8, orig: []const u8, with: []const u8) !void { if (src.len < orig.len) return; var s = src; var start: usize = 0; while (orig.len < s.len) { if (mem.indexOf(u8, s, orig)) |idx| { try buf.append(s[start..idx]); try buf.append(with); start += idx + with.len; } else { break; } } if (start < s.len) { try buf.append(s[start..]); } } fn titleBlock(r: *Renderer, buf: *Buffer, text: []const u8) !void { try buf.append("<h1 class=\"title\">"); const txt = mem.trimLeft(u8, text, "% "); try naiveReplace(buf, txt, "\n% ", "\n"); try buf.append("\n</h1>"); } fn doubleSpace(buf: *Buffer) !void { if (buf.len() > 0) { try buf.appendByte('\n'); } } fn getHeaderID(self: *HTML) i64 { const id = self.header_count; self.header_count += 1; return id; } fn printBuffer(buf: *Buffer, comptime fmt: []const u8, args: ...) !void { var stream = &io.BufferOutStream.init(buf).stream; try stream.print(fmt, args); } fn header( r: *Renderer, buf: *Buffer, text: *TextIter, level: usize, id: ?[]const u8, ) !void { const marker = buf.len(); try doubleSpace(buf); const self = @fieldParentPtr(HTML, "renderer", r); var stream = &io.BufferOutStream.init(buf).stream; const hid = ID.init( id, self.params.header_id_prefix, self.params.header_id_suffix, self.getHeaderID(), self.flags & HTML_TOC != 0, ); if (hid.valid()) { try stream.print("<{} id=\"{}\"", level, hid); } else { try stream.print("<{}", level); } const toc_marker = buf.len(); if (!text.text()) { try buf.resize(marker); return; } try stream.print("</h{}>\n", level); } fn blockHtml(r: *Renderer, buf: *Buffer, text: []const u8) !void { const self = @fieldParentPtr(HTML, "renderer", r); if (self.flags & HTML_SKIP_HTML != 0) { return; } try doubleSpace(buf); try buf.append(text); try buf.appendByte('\n'); } fn hrule(r: *Renderer, buf: *Buffer) !void { const self = @fieldParentPtr(HTML, "renderer", r); try doubleSpace(buf); try buf.append("<hr"); try buf.append(self.close_tag); try buf.appendByte('\n'); } fn blockCode( r: *Renderer, buf: *Buffer, text: []const u8, info: []const u8, ) !void { try doubleSpace(buf); const self = @fieldParentPtr(HTML, "renderer", r); var end_of_lang: usize = 0; if (mem.indexOfAny(u8, info, "\t ")) |idx| { end_of_lang = idx; } const lang = if (end_of_lang != 0) info[0..end_of_lang] else ""; if (lang.len == 0 or lang[0] == '.') { try buf.append("<pre><code>"); } else { try buf.append("<pre><code class=\"language-)"); try attrEscape(buf, lang); try buf.append("\">"); } try buf.append(text); try buf.append("</code></pre>\n"); } fn blockQuote( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try doubleSpace(buf); try buf.append("<blockquote>\n"); try buf.append(text); try buf.append("</blockquote>\n"); } fn table( r: *Renderer, buf: *Buffer, table_header: []const u8, body: []const u8, colum_data: []const usize, ) !void { try doubleSpace(buf); try buf.append("<table>\n<thead>\n"); try buf.append(table_header); try buf.append("</thead>\n\n<tbody>\n"); try buf.append(body); try buf.append("</tbody>\n</table>\n"); } fn tableRow( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try doubleSpace(buf); try buf.append("<tr>\n"); try buf.append(text); try buf.append("\n</tr>\n"); } fn tableHeaderCell( r: *Renderer, buf: *Buffer, text: []const u8, alignment: usize, ) !void { try doubleSpace(buf); switch (alignment) { TABLE_ALIGNMENT_LEFT => { try buf.append("<th align=\"left\">"); }, TABLE_ALIGNMENT_RIGHT => { try buf.append("<th align=\"right\">"); }, TABLE_ALIGNMENT_CENTER => { try buf.append("<th align=\"center\">"); }, else => { try buf.append("<th>"); }, } try buf.append(text); try buf.append("</th>"); } fn tableCell( r: *Renderer, buf: *Buffer, text: []const u8, alignment: usize, ) !void { try doubleSpace(buf); switch (alignment) { TABLE_ALIGNMENT_LEFT => { try buf.append("<td align=\"left\">"); }, TABLE_ALIGNMENT_RIGHT => { try buf.append("<td align=\"right\">"); }, TABLE_ALIGNMENT_CENTER => { try buf.append("<td align=\"center\">"); }, else => { try buf.append("<td>"); }, } try buf.append(text); try buf.append("</td>"); } fn footnotes( r: *Renderer, buf: *Buffer, text: *TextIter, ) !void { try buf.append("<div class=\"footnotes\">\n"); try r.hrule(buf); try r.list(buf, text, LIST_TYPE_ORDERED); try buf.append("</div>\n"); } fn slugify(buf: *Buffer, src: []const u8) !void { if (src.len == 0) return; const m = buf.len(); try buf.resize(m + src.len); var s = buf.toSlice()[m..]; var sym = false; for (src) |ch, i| { if (ascii.isAlNum(ch)) { s[i] = ch; } else { s[i] = '-'; } } } fn footnoteItem( r: *Renderer, buf: *Buffer, name: []const u8, text: []const u8, flags: usize, ) !void { if ((flags & LIST_ITEM_CONTAINS_BLOCK != 0) or (flags & LIST_ITEM_BEGINNING_OF_LIST != 0)) { try doubleSpace(buf); } const self = @fieldParentPtr(HTML, "renderer", r); try buf.append("<li id=\"fn:"); if (self.params.footnote_anchor_prefix) |v| { try buf.append(v); } try slugify(buf, name); try buf.appendByte('>'); try buf.append(text); if (self.flags & HTML_FOOTNOTE_RETURN_LINKS != 0) { try buf.append(" <a class=\"footnote-return\" href=\"#fnref:"); if (self.params.footnote_anchor_prefix) |v| { try buf.append(v); } try slugify(buf, name); try buf.appendByte('>'); if (self.params.footnote_return_link_contents) |v| { try buf.append(v); } try buf.append("</a>"); } try buf.append("</li>\n"); } fn list( r: *Renderer, buf: *Buffer, text: *TextIter, flags: usize, ) !void { const marker = buf.len(); try doubleSpace(buf); if (flags & LIST_TYPE_DEFINITION != 0) { try buf.append("<dl>"); } else if (flags & LIST_TYPE_ORDERED != 0) { try buf.append("<oll>"); } else { try buf.append("<ul>"); } if (!text.text()) { try buf.resize(marker); } if (flags & LIST_TYPE_DEFINITION != 0) { try buf.append("</dl>\n"); } else if (flags & LIST_TYPE_ORDERED != 0) { try buf.append("</oll>\n"); } else { try buf.append("</ul>\n"); } } fn listItem( r: *Renderer, buf: *Buffer, text: []const u8, flags: usize, ) !void { if ((flags & LIST_ITEM_CONTAINS_BLOCK != 0 and flags & LIST_TYPE_DEFINITION != 0) or flags & LIST_ITEM_BEGINNING_OF_LIST != 0) { try doubleSpace(buf); } if (flags & LIST_TYPE_TERM != 0) { try buf.append("<dt>"); } else if (flags & LIST_TYPE_DEFINITION != 0) { try buf.append("<dd>"); } else { try buf.append("<li>"); } try buf.append(text); if (flags & LIST_TYPE_TERM != 0) { try buf.append("</dt>\n"); } else if (flags & LIST_TYPE_DEFINITION != 0) { try buf.append("</dd>\n"); } else { try buf.append("</li>\n"); } } fn paragraph( r: *Renderer, buf: *Buffer, text: *TextIter, ) !void { const marker = buf.len(); try doubleSpace(buf); try buf.append("<p>"); if (!text.text()) { try buf.resize(marker); return; } try buf.append("</p>\n"); } fn autoLink( r: *Renderer, buf: *Buffer, link_: []const u8, kind: usize, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); if (self.flags & HTML_SAFELINK != 0 and !Util.isSafeLink(link_) and kind != LINK_TYPE_EMAIL) { try buf.append("<tt>"); try attrEscape(buf, link_); try buf.append("</tt>"); return; } try buf.append("<a href=\""); if (kind == LINK_TYPE_EMAIL) { try buf.append("mailto:"); } else { try self.maybeWriteAbsolutePrefix(buf, link_); } try attrEscape(buf, link_); var no_follow = false; var no_referer = false; if (self.flags & HTML_NOFOLLOW_LINKS != 0 and !Util.isRelativeLink(link_)) { no_follow = true; } if (self.flags & HTML_NOREFERRER_LINKS != 0 and !Util.isRelativeLink(link_)) { no_referer = true; } if (no_follow or no_referer) { try buf.append("\" rel=\""); if (no_follow) { try buf.append("nofollow"); } if (no_referer) { try buf.append(" noreferrer"); } try buf.appendByte('"'); } if (self.flags & HTML_HREF_TARGET_BLANK != 0 and !Util.isRelativeLink(link_)) { try buf.append("\" target=\"_blank"); } // Pretty print: if we get an email address as // an actual URI, e.g. `mailto:foo@bar.<EMAIL>`, we don't // want to print the `mailto:` prefix const mailto = "mailto://"; if (mem.startsWith(u8, link_, mailto)) { try attrEscape(buf, link_[mailto.len..]); } else if (mem.startsWith(u8, link_, mailto[0 .. mailto.len - 2])) { try attrEscape(buf, link_[mailto.len - 2 ..]); } else { try attrEscape(buf, link_); } try buf.append("</a>"); } fn maybeWriteAbsolutePrefix( self: *HTML, buf: *Buffer, link_: []const u8, ) !void { if (self.params.absolute_prefix != null and Util.isRelativeLink(link_) and link_[0] != '.') { try buf.append(self.params.absolute_prefix.?); if (link_[0] != '/') { try buf.appendByte('/'); } } } fn codeSpan( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try buf.append("<code>"); try attrEscape(buf, text); try buf.append("</code>"); } fn doubleEmphasis( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try buf.append("<strong>"); try attrEscape(buf, text); try buf.append("</strong>"); } fn emphasis( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { if (text.len == 0) return; try buf.append("<em>"); try attrEscape(buf, text); try buf.append("</em>"); } fn image( r: *Renderer, buf: *Buffer, link_: []const u8, title: ?[]const u8, alt: ?[]const u8, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); if (self.flags & HTML_SKIP_IMAGES != 0) return; try buf.append("<img src=\""); try self.maybeWriteAbsolutePrefix(buf, link_); try attrEscape(buf, link_); try buf.append("\" alt=\""); if (alt) |v| { try attrEscape(buf, v); } if (title) |v| { try buf.append("\" title=\""); try attrEscape(buf, v); } try buf.appendByte('"'); try buf.append(self.close_tag); } fn lineBreak( r: *Renderer, buf: *Buffer, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); try buf.append("<br"); try buf.append(self.close_tag); try buf.appendByte('\n'); } fn link( r: *Renderer, buf: *Buffer, link_: []const u8, title: ?[]const u8, content: []const u8, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); if (self.flags & HTML_SKIP_LINKS != 0) { try buf.append("<tt>"); try attrEscape(buf, content); try buf.append("</tt>"); return; } try buf.append("<a href=\""); try self.maybeWriteAbsolutePrefix(buf, link_); try attrEscape(buf, link_); if (title) |v| { try buf.append("\" title=\""); try attrEscape(buf, v); } var no_follow = false; var no_referer = false; if (self.flags & HTML_NOFOLLOW_LINKS != 0 and !Util.isRelativeLink(link_)) { no_follow = true; } if (self.flags & HTML_NOREFERRER_LINKS != 0 and !Util.isRelativeLink(link_)) { no_referer = true; } if (no_follow or no_referer) { try buf.append("\" rel=\""); if (no_follow) { try buf.append("nofollow"); } if (no_referer) { try buf.append(" noreferrer"); } try buf.appendByte('"'); } if (self.flags & HTML_HREF_TARGET_BLANK != 0 and !Util.isRelativeLink(link_)) { try buf.append("\" target=\"_blank"); } try buf.append("\">"); try buf.append(content); try buf.append("</a>"); } fn rawHtmlTag( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); if (self.flags & HTML_SKIP_HTML != 0) { return; } if (self.flags & HTML_SKIP_STYLE != 0 and Util.isHtmlTag(text, "style")) { return; } if (self.flags & HTML_SKIP_LINKS != 0 and Util.isHtmlTag(text, "a")) { return; } if (self.flags & HTML_SKIP_IMAGES != 0 and Util.isHtmlTag(text, "img")) { return; } try buf.append(text); } fn tripleEmphasis( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try buf.append("<strong><em>"); try buf.append(text); try buf.append("</em></strong>"); } fn strikeThrough( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try buf.append("<del>"); try buf.append(text); try buf.append("</del>"); } fn footnoteRef( r: *Renderer, buf: *Buffer, ref: []const u8, id: usize, ) !void { const self = @fieldParentPtr(HTML, "renderer", r); try buf.append("<sup class=\"footnote-ref\" id=\"fnref:"); if (self.params.footnote_anchor_prefix) |v| { try buf.append(v); } try slugify(buf, ref); try buf.append("\"><a href=\"#fn:"); if (self.params.footnote_anchor_prefix) |v| { try buf.append(v); } try slugify(buf, ref); try buf.append("\">"); try printBuffer(buf, "{}", id); try buf.append("</a></sup>"); } fn entity( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try buf.append(text); } fn normalText( r: *Renderer, buf: *Buffer, text: []const u8, ) !void { try attrEscape(buf, text); } fn documentHeader( r: *Renderer, buf: *Buffer, ) anyerror!void { //noop } fn documentFooter( r: *Renderer, buf: *Buffer, ) anyerror!void { //noop } fn getFlags( r: *Renderer, ) usize { const self = @fieldParentPtr(HTML, "renderer", r); return self.flags; } }; pub const Util = struct { const valid_urls = [_][]const u8{ "http://", "https://", "ftp://", "mailto://", }; const valid_paths = [_][]const u8{ "/", "https://", "./", "../", }; pub fn isSafeLink(link: []const u8) bool { for (valid_paths) |p| { if (mem.startsWith(u8, link, p)) { if (link.len == p.len) { return true; } if (ascii.isAlNum(link[p.len])) { return true; } } } for (valid_urls) |u| { if (link.len > u.len and eqlLower(link[0..u.len], u) and ascii.isAlNum(link[u.len])) { return true; } } return false; } /// eqlLower compares a, and b with all caharacters from aconverted to lower /// case. pub fn eqlLower(a: []const u8, b: []const u8) bool { if (a.len != b.len) return false; for (b) |v, i| { if (ascii.toLower(a[i]) != v) return false; } return true; } pub fn isRelativeLink(link: []const u8) bool { if (link.len == 0) return false; if (link[0] == '#') return true; // link begin with '/' but not '//', the second maybe a protocol relative link if (link.len >= 2 and link[0] == '/' and link[1] != '/') { return true; } // only the root '/' if (link.len == 1 and link[0] == '/') { return true; } // current directory : begin with "./" if (mem.startsWith(u8, link, "./")) { return true; } // parent directory : begin with "../" if (mem.startsWith(u8, link, "../")) { return true; } return false; } pub fn isHtmlTag( tag: []const u8, tag_name: []const u8, ) bool { if (findHtmlTagPos(tag, tag_name)) |_| return true; return false; } pub fn findHtmlTagPos( tag: []const u8, tag_name: []const u8, ) ?usize { var t = tag; var i: usize = 0; if (i < tag.len and tag[0] != '<') return null; i += 1; i = skipSpace(t, i); if (i < tag.len and tag[0] == '/') i += 1; i = skipSpace(t, i); var j: usize = 0; while (i < t.len) : ({ i += 1; j += 1; }) { if (j >= tag_name.len) { break; } if (ascii.toLower(t[i]) != tag_name[j]) { return null; } } if (i == t.len) { return null; } const a = skipUntilCharIgnoreQuotes(t, i, '>'); if (a > i) return a; return null; } fn skipUntilCharIgnoreQuotes(html: []const u8, start: usize, char: u8) usize { var s = false; var d = false; var g = false; var i = start; while (i < html.len) { if (html[i] == char and !s and !d and !g) { return i; } else if (html[i] == '\'') { s = !s; } else if (html[i] == '"') { d = !d; } else if (html[i] == '`') { g = !g; } i += 1; } return start; } pub fn skipSpace(s: []const u8, at: usize) usize { var v = s; var i = at; while (i < s.len) : (i += 1) { if (!ascii.isSpace(s[i])) { break; } } return i; } }; pub const OkMap = std.AutoHash([]const u8, void); pub const Parser = struct { allocator: *Allocator, r: *Renderer, refs: ReferenceMap, inline_callback: [256]?fn ( p: *Parser, buf: *Buffer, data: []const u8, offset: usize, ) !usize, flags: usize, nesting: usize, max_nesting: usize, inside_link: bool, notes: std.ArrayList(*Reference), notes_record: OkMap, pub const ReferenceMap = std.AutoHash([]const u8, *Reference); pub const Reference = struct { link: ?[]const u8, title: ?[]const u8, note_id: usize, has_block: bool, text: ?[]const u8, }; fn isSpace(c: u8) bool { return switch (c) { ' ', '\t', '\n', '\r', '\f', '\v' => true, else => false, }; } // INLINE fn inlineFn( self: *Parser, buf: *Buffer, data: []const u8, ) !void { if (self.nesting >= self.max_nesting) { return; } self.nesting += 1; var i: usize = 0; var end: usize = 0; while (i < data.len) { while (end < data.len and self.inline_callback[data[end]] == null) { end += 1; } try self.r.normalText(buf, data[i..end]); if (end >= data.len) { break; } i = end; const h = self.inline_callback[data[end]].?; const c = try h(self, buf, data, i); if (c == 0) { end = i + 1; } else { i += c; end = i; } } self.nesting -= 1; } fn helperFindEmphChar( data: []const u8, c: u8, ) usize { var i: usize = 0; while (i < data.len) { while (i < data.len and data[i] != c and data[i] != '`' and data[i] != '[') { i += 1; } if (i >= data.len) { return 0; } if (i != 0 and data[i - 1] == '\\') { i += 1; continue; } if (data[i] == c) { return i; } if (data[i] == '`') { var tmp: usize = 0; i += 1; while (i < data.len and data[i] != '`') { if (tmp == 0 and data[i] == c) { tmp = i; } i += 1; } if (i >= data.len) { return tmp; } i += 1; } else if (data[i] == '[') { var tmp: usize = 0; i += 1; while (i < data.len and data[i] != ']') { if (tmp == 0 and data[i] == c) { tmp = i; } i += 1; } i += 1; while (i < data.len and (data[i] == ' ' or data[i] == '\n')) { i += 1; } if (i >= data.len) return tmp; if (data[i] != '[' and data[i] != '(') { if (tmp > 0) return tmp; continue; } var cc = data[i]; while (i < data.len and data[i] != cc) { if (tmp == 0 and data[i] == c) { return i; } i += 1; } if (i >= data.len) { return tmp; } i += 1; } } return 0; } fn helperEmphasis( self: *Parser, buf: *Buffer, data: []const u8, c: u8, ) !usize { var i: usize = 0; if (data.len > 1 and data[0] == c and data[1] == c) { i = 1; } while (i < data.len) { const l = helperFindEmphChar(data[i..], c); if (l == 0) return 0; i += l; if (i >= data.len) return 0; if (i + 1 < data.len and data[i + 1] == c) { i += 1; continue; } if (data[i] == c and isSpace(data[i - 1])) { if (self.flags & EXTENSION_NO_INTRA_EMPHASIS != 0) { if (!(i + 1 == data.len or isspace(data[i + 1]) or ispunct(data[i + 1]))) { continue; } } var w = &try Buffer.init(self.allocator, ""); try self.inlineFn(w, data[0..i]); try self.r.empasis(buf, w.toSlice()); w.deinit(); return i + 1; } } return 0; } fn helperDoubleEmphasis( self: *Parser, buf: *Buffer, data: []const u8, c: u8, ) !usize { var i: usize = 0; while (i < data.len) { const l = helperFindEmphChar(data[i..], c); if (l == 0) return 0; i += 1; if (i + 1 < data.len and data[i] == c and data[i + 1] == c and i > 0 and !isSpace(data[i - 1])) { try self.inlineFn(w, data[i..]); var w = &try Buffer.init(self.allocator, ""); if (w.len() > 0) { if (c == '~') { try self.r.strikeThrough(buf, w.toSlice()); } else { try self.r.doubleEmphasis(buf, w.toSlice()); } } w.deinit(); return i += 2; } i += 1; } } fn empasis( self: *Parser, buf: *Buffer, text: []const u8, offset: usize, ) !usize { var data = text[offset..]; const c = data[0]; } }; test "HTML.test" { var a = std.debug.global_allocator; var h = try HTML.init(a); }
src/markdown/markdown.zig
const std = @import("std"); const build = std.build; usingnamespace @import("dcommon.zig"); pub fn getBoard(b: *build.Builder) !Board { return b.option(Board, "board", "Target board.") orelse error.UnknownBoard; } pub fn getArch(board: Board) Arch { return switch (board) { .qemu_arm64, .rockpro64 => .arm64, .qemu_riscv64 => .riscv64, }; } pub fn crossTargetFor(board: Board) std.zig.CrossTarget { switch (board) { .qemu_arm64, .rockpro64 => { var features = std.Target.Cpu.Feature.Set.empty; // Unaligned LDR in daintree_mmu_start (before MMU bring up) is // causing crashes. I wish I could turn this on just for that one // function. Can't seem to find a register setting (like in SCTLR_EL1 // or something) that stops this happening. Reproduced on both // QEMU and rockpro64 so giving up for now. features.addFeature(@enumToInt(std.Target.aarch64.Feature.strict_align)); return .{ .cpu_arch = .aarch64, .cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_a53 }, .cpu_features_add = features, }; }, .qemu_riscv64 => return .{ .cpu_arch = .riscv64, .cpu_model = .baseline, }, } } pub fn efiTagFor(cpu_arch: std.Target.Cpu.Arch) []const u8 { return switch (cpu_arch) { .aarch64 => "AA64", .riscv64 => "RISCV64", else => @panic("can't handle other arch in efiTagFor"), }; } pub fn addBuildOptions(b: *build.Builder, exe: *build.LibExeObjStep, board: Board) !void { exe.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, try getVersion(b))); exe.addBuildOption([:0]const u8, "board", try b.allocator.dupeZ(u8, @tagName(board))); } // adapted from Zig's own build.zig: // https://github.com/ziglang/zig/blob/a021c7b1b2428ecda85e79e281d43fa1c92f8c94/build.zig#L140-L188 fn getVersion(b: *build.Builder) ![]u8 { const version_string = b.fmt("{d}.{d}.{d}", .{ daintree_version.major, daintree_version.minor, daintree_version.patch }); var code: u8 = undefined; const git_describe_untrimmed = b.execAllowFail(&[_][]const u8{ "git", "-C", b.build_root, "describe", "--match", "*.*.*", "--tags", }, &code, .Ignore) catch { return version_string; }; const git_describe = std.mem.trim(u8, git_describe_untrimmed, " \n\r"); switch (std.mem.count(u8, git_describe, "-")) { 0 => { // Tagged release version (e.g. 0.7.0). if (!std.mem.eql(u8, git_describe, version_string)) { std.debug.print("Daintree version '{s}' does not match Git tag '{s}'\n", .{ version_string, git_describe }); std.process.exit(1); } return version_string; }, 2 => { // Untagged development build (e.g. 0.7.0-684-gbbe2cca1a). var it = std.mem.split(git_describe, "-"); const tagged_ancestor = it.next() orelse unreachable; const commit_height = it.next() orelse unreachable; const commit_id = it.next() orelse unreachable; const ancestor_ver = try std.builtin.Version.parse(tagged_ancestor); if (daintree_version.order(ancestor_ver) != .gt) { std.debug.print("Daintree version '{}' must be greater than tagged ancestor '{}'\n", .{ daintree_version, ancestor_ver }); std.process.exit(1); } // Check that the commit hash is prefixed with a 'g' (a Git convention). if (commit_id.len < 1 or commit_id[0] != 'g') { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); return version_string; } // The version is reformatted in accordance with the https://semver.org specification. return b.fmt("{s}-dev.{s}+{s}", .{ version_string, commit_height, commit_id[1..] }); }, else => { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); return version_string; }, } }
common/dbuild.zig
const std = @import("std"); const core = @import("../index.zig"); const Coord = core.geometry.Coord; pub fn Matrix(comptime T: type) type { return struct { const Self = @This(); width: u16, height: u16, data: []T, pub fn initEmpty() Self { return Self{ .width = 0, .height = 0, .data = &[_]T{}, }; } fn init(allocator: *std.mem.Allocator, width: u16, height: u16) !Self { return Self{ .width = width, .height = height, .data = try allocator.alloc(T, width * height), }; } pub fn initFill(allocator: *std.mem.Allocator, width: u16, height: u16, fill_value: T) !Self { var self = try Self.init(allocator, width, height); self.fill(fill_value); return self; } pub fn initData(width: u16, height: u16, data: []T) Self { std.debug.assert(data.len == height * width); return Self{ .width = width, .height = height, .data = data, }; } pub fn clone(self: Self, allocator: *std.mem.Allocator) !Self { var other = try Self.init(allocator, self.width, self.height); std.mem.copy(T, other.data, self.data); return other; } pub fn fill(self: Self, fill_value: T) void { for (self.data) |*x| { x.* = fill_value; } } pub fn atCoord(self: Self, coord: Coord) ?*T { return self.at(coord.x, coord.y); } pub fn at(self: Self, x: i32, y: i32) ?*T { if (0 <= x and x < @as(i32, self.width) and 0 <= y and y < @as(i32, self.height)) { return self.atUnchecked(@intCast(usize, x), @intCast(usize, y)); } return null; } pub fn atUnchecked(self: Self, x: usize, y: usize) *T { return &self.data[y * self.width + x]; } pub fn getCoord(self: Self, coord: Coord) ?T { return self.get(coord.x, coord.y); } pub fn get(self: Self, x: i32, y: i32) ?T { if (0 <= x and x < @as(i32, self.width) and 0 <= y and y < @as(i32, self.height)) { return self.getUnchecked(@intCast(usize, x), @intCast(usize, y)); } return null; } pub fn getUnchecked(self: Self, x: usize, y: usize) T { return self.atUnchecked(x, y).*; } pub fn indexToCoord(self: Self, index: usize) Coord { return Coord{ .x = @intCast(i32, index % self.width), .y = @intCast(i32, index / self.width), }; } pub fn copy(dest: Self, source: Self, dx: u16, dy: u16, sx: u16, sy: u16, width: u16, height: u16) void { std.debug.assert(dx + width <= dest.width); std.debug.assert(dy + height <= dest.height); std.debug.assert(sx + width <= source.width); std.debug.assert(sy + height <= source.height); var y: u16 = 0; while (y < height) : (y += 1) { var x: u16 = 0; while (x < width) : (x += 1) { dest.atUnchecked(dx + x, dy + y).* = source.getUnchecked(sx + x, sy + y); } } } }; } test "Matrix" { var m = try Matrix(u8).initFill(std.debug.global_allocator, 3, 2, 0); std.testing.expect(m.at(-1, 0) == null); std.testing.expect(m.get(0, -1) == null); std.testing.expect(m.get(3, 0) == null); std.testing.expect(m.at(0, 2) == null); std.testing.expect(m.at(0, 0).?.* == 0); std.testing.expect(m.at(2, 1).?.* == 0); std.testing.expect(m.get(1, 1).? == 0); m.atUnchecked(1, 1).* = 3; std.testing.expect(m.at(1, 1).?.* == 3); var other = try m.clone(std.debug.global_allocator); std.testing.expect(other.at(0, 0).?.* == 0); std.testing.expect(other.get(1, 1).? == 3); m.atUnchecked(1, 1).* = 4; std.testing.expect(m.get(1, 1).? == 4); std.testing.expect(other.get(1, 1).? == 3); }
src/core/matrix.zig
const std = @import("std"); const assert = std.debug.assert; const expect = std.testing.expect; /// Similiar to std.meta.eql but pointers are followed. /// Also Unions and ErrorUnions are excluded. pub fn eq(a: anytype, b: @TypeOf(a)) bool { const T = @TypeOf(a); switch (@typeInfo(T)) { .Int, .ComptimeInt, .Float, .ComptimeFloat => { return a == b; }, .Struct => { if (!@hasDecl(T, "eq")) { @compileError("An 'eq' comparison method has to implemented for Type '" ++ @typeName(T) ++ "'"); } return T.eq(a, b); }, .Array => { for (a) |_, i| if (!eq(a[i], b[i])) return false; return true; }, .Vector => |info| { var i: usize = 0; while (i < info.len) : (i += 1) { if (!eq(a[i], b[i])) return false; } return true; }, .Pointer => |info| { switch (info.size) { .One => return eq(a.*, b.*), .Slice => { if (a.len != b.len) return false; for (a) |_, i| if (!eq(a[i], b[i])) return false; return true; }, .Many => { if (info.sentinel) { if (std.mem.len(a) != std.mem.len(b)) return false; var i: usize = 0; while (i < std.mem.len(a)) : (i += 1) if (!eq(a[i], b[i])) return false; return true; } @compileError("Cannot compare many-item pointer to unknown number of items without sentinel value"); }, .C => @compileError("Cannot compare C pointers"), } }, .Optional => { if (a == null and b == null) return true; if (a == null or b == null) return false; return eq(a.?, b.?); }, else => { @compileError("Cannot compare type '" ++ @typeName(T) ++ "'"); }, } } pub fn lt(a: anytype, b: @TypeOf(a)) bool { const T = @TypeOf(a); switch (@typeInfo(T)) { .Int, .ComptimeInt, .Float, .ComptimeFloat => { return a < b; }, .Struct => { if (!@hasDecl(T, "lt")) { @compileError("A 'lt' comparison method has to implemented for Type '" ++ @typeName(T) ++ "'"); } return T.lt(a, b); }, .Array => { for (a) |_, i| { if (lt(a[i], b[i])) { return true; } else if (eq(a[i], b[i])) { continue; } else { return false; } } return false; }, .Vector => |info| { var i: usize = 0; while (i < info.len) : (i += 1) { if (lt(a[i], b[i])) { return true; } else if (eq(a[i], b[i])) { continue; } else { return false; } } return false; }, .Pointer => |info| { switch (info.size) { .One => return lt(a.*, b.*), .Slice => { const n = std.math.min(a.len, b.len); for (a[0..n]) |_, i| { if (lt(a[i], b[i])) { return true; } else if (eq(a[i], b[i])) { continue; } else { return false; } } return lt(a.len, b.len); }, .Many => { if (info.sentinel) { const n = std.math.min(std.mem.len(a), std.mem.len(b)); var i: usize = 0; while (i < n) : (i += 1) { if (lt(a[i], b[i])) { return true; } else if (eq(a[i], b[i])) { continue; } else { return false; } } return lt(std.mem.len(a), std.mem.len(b)); } @compileError("Cannot compare many-item pointer to unknown number of items without sentinel value"); }, .C => @compileError("Cannot compare C pointers"), } }, .Optional => { if (a == null or b == null) return false; return lt(a.?, b.?); }, else => { @compileError("Cannot compare type '" ++ @typeName(T) ++ "'"); }, } } pub fn le(a: anytype, b: @TypeOf(a)) bool { return lt(a, b) or eq(a, b); } pub fn gt(a: anytype, b: @TypeOf(a)) bool { return !lt(a, b) and !eq(a, b); } pub fn ge(a: anytype, b: @TypeOf(a)) bool { return !lt(a, b); } test "numerals" { try expect(eq(1.0, 1.0)); try expect(!eq(1.0, 1.1)); try expect(lt(1.0, 2.0)); try expect(!lt(1, 1)); try expect(!lt(2, 1)); } test "Arrays" { try expect(eq("abc", "abc")); try expect(!eq("abc", "abb")); try expect(lt("ab", "ba")); try expect(lt("aaa", "aab")); try expect(!lt("aaa", "aaa")); try expect(!lt("aab", "aaa")); } test "structs" { const Car = struct { power: i32, pub fn lt(a: @This(), b: @This()) bool { return a.power < b.power; } pub fn eq(a: @This(), b: @This()) bool { return a.power == b.power; } }; var car1 = Car{ .power = 100 }; var car2 = Car{ .power = 200 }; try expect(eq(car1, car1)); try expect(!eq(car1, car2)); try expect(lt(car1, car2)); try expect(!lt(car1, car1)); } test "Slices" { var o: usize = 0; assert(@TypeOf("abc"[o..]) == [:0]const u8); try expect(eq("abc"[o..], "abc")); try expect(!eq("abc"[o..], "abb")); try expect(lt("aba"[o..], "ba")); try expect(lt("aaa"[o..], "bb")); try expect(!lt("aba"[o..], "aa")); try expect(!lt("aaa"[o..], "aaa")); try expect(lt("aaa"[o..], "aaaa")); try expect(!lt("aaa"[o..], "aa")); try expect(lt("aab"[o..], "aaba")); } test "Optionals" { var x: ?i32 = 1; var y: ?i32 = 2; try expect(lt(x, y)); } test "sentinel terminated pointers" { // TODO } test "Vectors" { // TODO }
src/meta.zig
const std = @import("std"); fn root() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } fn pathJoinRoot(comptime components: []const []const u8) []const u8 { var ret = root(); inline for (components) |component| ret = ret ++ std.fs.path.sep_str ++ component; return ret; } const srcs = blk: { var ret = &.{ pathJoinRoot(&.{ "c", "src", "channel.c" }), pathJoinRoot(&.{ "c", "src", "comp.c" }), pathJoinRoot(&.{ "c", "src", "crypt.c" }), pathJoinRoot(&.{ "c", "src", "hostkey.c" }), pathJoinRoot(&.{ "c", "src", "kex.c" }), pathJoinRoot(&.{ "c", "src", "mac.c" }), pathJoinRoot(&.{ "c", "src", "misc.c" }), pathJoinRoot(&.{ "c", "src", "packet.c" }), pathJoinRoot(&.{ "c", "src", "publickey.c" }), pathJoinRoot(&.{ "c", "src", "scp.c" }), pathJoinRoot(&.{ "c", "src", "session.c" }), pathJoinRoot(&.{ "c", "src", "sftp.c" }), pathJoinRoot(&.{ "c", "src", "userauth.c" }), pathJoinRoot(&.{ "c", "src", "transport.c" }), pathJoinRoot(&.{ "c", "src", "version.c" }), pathJoinRoot(&.{ "c", "src", "knownhost.c" }), pathJoinRoot(&.{ "c", "src", "agent.c" }), pathJoinRoot(&.{ "c", "src", "mbedtls.c" }), pathJoinRoot(&.{ "c", "src", "pem.c" }), pathJoinRoot(&.{ "c", "src", "keepalive.c" }), pathJoinRoot(&.{ "c", "src", "global.c" }), pathJoinRoot(&.{ "c", "src", "blowfish.c" }), pathJoinRoot(&.{ "c", "src", "bcrypt_pbkdf.c" }), pathJoinRoot(&.{ "c", "src", "agent_win.c" }), }; break :blk ret; }; const include_dir = pathJoinRoot(&.{ "c", "include" }); const config_dir = pathJoinRoot(&.{"config"}); pub fn link( b: *std.build.Builder, artifact: *std.build.LibExeObjStep, ) !void { var flags = std.ArrayList([]const u8).init(b.allocator); try flags.appendSlice(&.{ "-DLIBSSH2_MBEDTLS", }); if (artifact.target.isWindows()) { try flags.appendSlice(&.{ "-D_CRT_SECURE_NO_DEPRECATE=1", "-DHAVE_LIBCRYPT32", "-DHAVE_WINSOCK2_H", "-DHAVE_IOCTLSOCKET", "-DHAVE_SELECT", "-DLIBSSH2_DH_GEX_NEW=1", }); if (artifact.target.getAbi().isGnu()) try flags.appendSlice(&.{ "-DHAVE_UNISTD_H", "-DHAVE_INTTYPES_H", "-DHAVE_SYS_TIME_H", "-DHAVE_GETTIMEOFDAY", }); } else try flags.appendSlice(&.{ "-DHAVE_UNISTD_H", "-DHAVE_INTTYPES_H", "-DHAVE_STDLIB_H", "-DHAVE_SYS_SELECT_H", "-DHAVE_SYS_UIO_H", "-DHAVE_SYS_SOCKET_H", "-DHAVE_SYS_IOCTL_H", "-DHAVE_SYS_TIME_H", "-DHAVE_SYS_UN_H", "-DHAVE_LONGLONG", "-DHAVE_GETTIMEOFDAY", "-DHAVE_INET_ADDR", "-DHAVE_POLL", "-DHAVE_SELECT", "-DHAVE_SOCKET", "-DHAVE_STRTOLL", "-DHAVE_SNPRINTF", "-DHAVE_O_NONBLOCK", }); artifact.addIncludeDir(include_dir); artifact.addIncludeDir(config_dir); artifact.addCSourceFiles(srcs, flags.items); artifact.linkLibC(); }
libs/libssh2/libssh2.zig
const std = @import("std"); const cast = std.meta.cast; const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels pub const Limbs = [4]u64; /// The function addcarryxU64 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] fn addcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); var t: u64 = undefined; const carry1 = @addWithOverflow(u64, arg2, arg3, &t); const carry2 = @addWithOverflow(u64, t, arg1, out1); out2.* = @boolToInt(carry1) | @boolToInt(carry2); } /// The function subborrowxU64 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] fn subborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); var t: u64 = undefined; const carry1 = @subWithOverflow(u64, arg2, arg3, &t); const carry2 = @subWithOverflow(u64, t, arg1, out1); out2.* = @boolToInt(carry1) | @boolToInt(carry2); } /// The function mulxU64 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] fn mulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const x = @as(u128, arg1) * @as(u128, arg2); out1.* = @truncate(u64, x); out2.* = @truncate(u64, x >> 64); } /// The function cmovznzU64 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) callconv(.Inline) void { @setRuntimeSafety(mode == .Debug); const mask = 0 -% @as(u64, arg1); out1.* = (mask & arg3) | ((~mask) & arg2); } /// The function mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn mul(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg2[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg2[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg2[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg2[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (cast(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xccd1c8aaee00bc4f); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x20, 0xffffffff00000000); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; mulxU64(&x26, &x27, x20, 0xbce6faada7179e84); var x28: u64 = undefined; var x29: u64 = undefined; mulxU64(&x28, &x29, x20, 0xf3b9cac2fc632551); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, x25, x22); const x36 = (cast(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; addcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, (arg2[3])); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, (arg2[2])); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, (arg2[1])); var x53: u64 = undefined; var x54: u64 = undefined; mulxU64(&x53, &x54, x1, (arg2[0])); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x50, x47); const x61 = (cast(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, cast(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; mulxU64(&x72, &x73, x62, 0xccd1c8aaee00bc4f); var x74: u64 = undefined; var x75: u64 = undefined; mulxU64(&x74, &x75, x72, 0xffffffff00000000); var x76: u64 = undefined; var x77: u64 = undefined; mulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x72, 0xbce6faada7179e84); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x72, 0xf3b9cac2fc632551); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x77, x74); const x88 = (cast(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; addcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; addcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; addcarryxU64(&x97, &x98, x96, x70, x88); const x99 = (cast(u64, x98) + cast(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x2, (arg2[3])); var x102: u64 = undefined; var x103: u64 = undefined; mulxU64(&x102, &x103, x2, (arg2[2])); var x104: u64 = undefined; var x105: u64 = undefined; mulxU64(&x104, &x105, x2, (arg2[1])); var x106: u64 = undefined; var x107: u64 = undefined; mulxU64(&x106, &x107, x2, (arg2[0])); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x103, x100); const x114 = (cast(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; addcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; addcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x115, 0xccd1c8aaee00bc4f); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x125, 0xffffffff00000000); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x125, 0xbce6faada7179e84); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x125, 0xf3b9cac2fc632551); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); const x141 = (cast(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x123, x141); const x152 = (cast(u64, x151) + cast(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; mulxU64(&x153, &x154, x3, (arg2[3])); var x155: u64 = undefined; var x156: u64 = undefined; mulxU64(&x155, &x156, x3, (arg2[2])); var x157: u64 = undefined; var x158: u64 = undefined; mulxU64(&x157, &x158, x3, (arg2[1])); var x159: u64 = undefined; var x160: u64 = undefined; mulxU64(&x159, &x160, x3, (arg2[0])); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x156, x153); const x167 = (cast(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; addcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; addcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; mulxU64(&x178, &x179, x168, 0xccd1c8aaee00bc4f); var x180: u64 = undefined; var x181: u64 = undefined; mulxU64(&x180, &x181, x178, 0xffffffff00000000); var x182: u64 = undefined; var x183: u64 = undefined; mulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; mulxU64(&x184, &x185, x178, 0xbce6faada7179e84); var x186: u64 = undefined; var x187: u64 = undefined; mulxU64(&x186, &x187, x178, 0xf3b9cac2fc632551); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, x183, x180); const x194 = (cast(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; addcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; addcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; addcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; addcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; addcarryxU64(&x203, &x204, x202, x176, x194); const x205 = (cast(u64, x204) + cast(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; subborrowxU64(&x206, &x207, 0x0, x197, 0xf3b9cac2fc632551); var x208: u64 = undefined; var x209: u1 = undefined; subborrowxU64(&x208, &x209, x207, x199, 0xbce6faada7179e84); var x210: u64 = undefined; var x211: u1 = undefined; subborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; subborrowxU64(&x212, &x213, x211, x203, 0xffffffff00000000); var x214: u64 = undefined; var x215: u1 = undefined; subborrowxU64(&x214, &x215, x213, x205, cast(u64, 0x0)); var x216: u64 = undefined; cmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; cmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; cmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; cmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn square(out1: *[4]u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg1[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg1[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg1[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg1[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (cast(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xccd1c8aaee00bc4f); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x20, 0xffffffff00000000); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; mulxU64(&x26, &x27, x20, 0xbce6faada7179e84); var x28: u64 = undefined; var x29: u64 = undefined; mulxU64(&x28, &x29, x20, 0xf3b9cac2fc632551); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, x25, x22); const x36 = (cast(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; addcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, (arg1[3])); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, (arg1[2])); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, (arg1[1])); var x53: u64 = undefined; var x54: u64 = undefined; mulxU64(&x53, &x54, x1, (arg1[0])); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x50, x47); const x61 = (cast(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, cast(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; mulxU64(&x72, &x73, x62, 0xccd1c8aaee00bc4f); var x74: u64 = undefined; var x75: u64 = undefined; mulxU64(&x74, &x75, x72, 0xffffffff00000000); var x76: u64 = undefined; var x77: u64 = undefined; mulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x72, 0xbce6faada7179e84); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x72, 0xf3b9cac2fc632551); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x77, x74); const x88 = (cast(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; addcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; addcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; addcarryxU64(&x97, &x98, x96, x70, x88); const x99 = (cast(u64, x98) + cast(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x2, (arg1[3])); var x102: u64 = undefined; var x103: u64 = undefined; mulxU64(&x102, &x103, x2, (arg1[2])); var x104: u64 = undefined; var x105: u64 = undefined; mulxU64(&x104, &x105, x2, (arg1[1])); var x106: u64 = undefined; var x107: u64 = undefined; mulxU64(&x106, &x107, x2, (arg1[0])); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x103, x100); const x114 = (cast(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; addcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; addcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x115, 0xccd1c8aaee00bc4f); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x125, 0xffffffff00000000); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x125, 0xbce6faada7179e84); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x125, 0xf3b9cac2fc632551); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); const x141 = (cast(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x123, x141); const x152 = (cast(u64, x151) + cast(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; mulxU64(&x153, &x154, x3, (arg1[3])); var x155: u64 = undefined; var x156: u64 = undefined; mulxU64(&x155, &x156, x3, (arg1[2])); var x157: u64 = undefined; var x158: u64 = undefined; mulxU64(&x157, &x158, x3, (arg1[1])); var x159: u64 = undefined; var x160: u64 = undefined; mulxU64(&x159, &x160, x3, (arg1[0])); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x156, x153); const x167 = (cast(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; addcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; addcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; mulxU64(&x178, &x179, x168, 0xccd1c8aaee00bc4f); var x180: u64 = undefined; var x181: u64 = undefined; mulxU64(&x180, &x181, x178, 0xffffffff00000000); var x182: u64 = undefined; var x183: u64 = undefined; mulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; mulxU64(&x184, &x185, x178, 0xbce6faada7179e84); var x186: u64 = undefined; var x187: u64 = undefined; mulxU64(&x186, &x187, x178, 0xf3b9cac2fc632551); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, x183, x180); const x194 = (cast(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; addcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; addcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; addcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; addcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; addcarryxU64(&x203, &x204, x202, x176, x194); const x205 = (cast(u64, x204) + cast(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; subborrowxU64(&x206, &x207, 0x0, x197, 0xf3b9cac2fc632551); var x208: u64 = undefined; var x209: u1 = undefined; subborrowxU64(&x208, &x209, x207, x199, 0xbce6faada7179e84); var x210: u64 = undefined; var x211: u1 = undefined; subborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; subborrowxU64(&x212, &x213, x211, x203, 0xffffffff00000000); var x214: u64 = undefined; var x215: u1 = undefined; subborrowxU64(&x214, &x215, x213, x205, cast(u64, 0x0)); var x216: u64 = undefined; cmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; cmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; cmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; cmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn add(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; addcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; addcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; addcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU64(&x9, &x10, 0x0, x1, 0xf3b9cac2fc632551); var x11: u64 = undefined; var x12: u1 = undefined; subborrowxU64(&x11, &x12, x10, x3, 0xbce6faada7179e84); var x13: u64 = undefined; var x14: u1 = undefined; subborrowxU64(&x13, &x14, x12, x5, 0xffffffffffffffff); var x15: u64 = undefined; var x16: u1 = undefined; subborrowxU64(&x15, &x16, x14, x7, 0xffffffff00000000); var x17: u64 = undefined; var x18: u1 = undefined; subborrowxU64(&x17, &x18, x16, cast(u64, x8), cast(u64, 0x0)); var x19: u64 = undefined; cmovznzU64(&x19, x18, x9, x1); var x20: u64 = undefined; cmovznzU64(&x20, x18, x11, x3); var x21: u64 = undefined; cmovznzU64(&x21, x18, x13, x5); var x22: u64 = undefined; cmovznzU64(&x22, x18, x15, x7); out1[0] = x19; out1[1] = x20; out1[2] = x21; out1[3] = x22; } /// The function sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn sub(out1: *[4]u64, arg1: [4]u64, arg2: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, cast(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xf3b9cac2fc632551)); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xbce6faada7179e84)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000000)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn opp(out1: *[4]u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, cast(u64, 0x0), (arg1[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, cast(u64, 0x0), (arg1[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, cast(u64, 0x0), (arg1[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, cast(u64, 0x0), (arg1[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, cast(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xf3b9cac2fc632551)); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xbce6faada7179e84)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000000)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function fromMontgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fromMontgomery(out1: *[4]u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); var x2: u64 = undefined; var x3: u64 = undefined; mulxU64(&x2, &x3, x1, 0xccd1c8aaee00bc4f); var x4: u64 = undefined; var x5: u64 = undefined; mulxU64(&x4, &x5, x2, 0xffffffff00000000); var x6: u64 = undefined; var x7: u64 = undefined; mulxU64(&x6, &x7, x2, 0xffffffffffffffff); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x2, 0xbce6faada7179e84); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x2, 0xf3b9cac2fc632551); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, 0x0, x11, x8); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x9, x6); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, x4); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, 0x0, x1, x10); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, cast(u64, 0x0), x12); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, x21, cast(u64, 0x0), x14); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, cast(u64, 0x0), x16); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, 0x0, x20, (arg1[1])); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x22, cast(u64, 0x0)); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x24, cast(u64, 0x0)); var x32: u64 = undefined; var x33: u64 = undefined; mulxU64(&x32, &x33, x26, 0xccd1c8aaee00bc4f); var x34: u64 = undefined; var x35: u64 = undefined; mulxU64(&x34, &x35, x32, 0xffffffff00000000); var x36: u64 = undefined; var x37: u64 = undefined; mulxU64(&x36, &x37, x32, 0xffffffffffffffff); var x38: u64 = undefined; var x39: u64 = undefined; mulxU64(&x38, &x39, x32, 0xbce6faada7179e84); var x40: u64 = undefined; var x41: u64 = undefined; mulxU64(&x40, &x41, x32, 0xf3b9cac2fc632551); var x42: u64 = undefined; var x43: u1 = undefined; addcarryxU64(&x42, &x43, 0x0, x41, x38); var x44: u64 = undefined; var x45: u1 = undefined; addcarryxU64(&x44, &x45, x43, x39, x36); var x46: u64 = undefined; var x47: u1 = undefined; addcarryxU64(&x46, &x47, x45, x37, x34); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, 0x0, x26, x40); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x28, x42); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, x30, x44); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, x53, (cast(u64, x31) + (cast(u64, x25) + (cast(u64, x17) + x5))), x46); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, 0x0, x50, (arg1[2])); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x52, cast(u64, 0x0)); var x60: u64 = undefined; var x61: u1 = undefined; addcarryxU64(&x60, &x61, x59, x54, cast(u64, 0x0)); var x62: u64 = undefined; var x63: u64 = undefined; mulxU64(&x62, &x63, x56, 0xccd1c8aaee00bc4f); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x62, 0xffffffff00000000); var x66: u64 = undefined; var x67: u64 = undefined; mulxU64(&x66, &x67, x62, 0xffffffffffffffff); var x68: u64 = undefined; var x69: u64 = undefined; mulxU64(&x68, &x69, x62, 0xbce6faada7179e84); var x70: u64 = undefined; var x71: u64 = undefined; mulxU64(&x70, &x71, x62, 0xf3b9cac2fc632551); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, 0x0, x71, x68); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, x69, x66); var x76: u64 = undefined; var x77: u1 = undefined; addcarryxU64(&x76, &x77, x75, x67, x64); var x78: u64 = undefined; var x79: u1 = undefined; addcarryxU64(&x78, &x79, 0x0, x56, x70); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, x79, x58, x72); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x60, x74); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, (cast(u64, x61) + (cast(u64, x55) + (cast(u64, x47) + x35))), x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, 0x0, x80, (arg1[3])); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x82, cast(u64, 0x0)); var x90: u64 = undefined; var x91: u1 = undefined; addcarryxU64(&x90, &x91, x89, x84, cast(u64, 0x0)); var x92: u64 = undefined; var x93: u64 = undefined; mulxU64(&x92, &x93, x86, 0xccd1c8aaee00bc4f); var x94: u64 = undefined; var x95: u64 = undefined; mulxU64(&x94, &x95, x92, 0xffffffff00000000); var x96: u64 = undefined; var x97: u64 = undefined; mulxU64(&x96, &x97, x92, 0xffffffffffffffff); var x98: u64 = undefined; var x99: u64 = undefined; mulxU64(&x98, &x99, x92, 0xbce6faada7179e84); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x92, 0xf3b9cac2fc632551); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, 0x0, x101, x98); var x104: u64 = undefined; var x105: u1 = undefined; addcarryxU64(&x104, &x105, x103, x99, x96); var x106: u64 = undefined; var x107: u1 = undefined; addcarryxU64(&x106, &x107, x105, x97, x94); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x86, x100); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x88, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x90, x104); var x114: u64 = undefined; var x115: u1 = undefined; addcarryxU64(&x114, &x115, x113, (cast(u64, x91) + (cast(u64, x85) + (cast(u64, x77) + x65))), x106); const x116 = (cast(u64, x115) + (cast(u64, x107) + x95)); var x117: u64 = undefined; var x118: u1 = undefined; subborrowxU64(&x117, &x118, 0x0, x110, 0xf3b9cac2fc632551); var x119: u64 = undefined; var x120: u1 = undefined; subborrowxU64(&x119, &x120, x118, x112, 0xbce6faada7179e84); var x121: u64 = undefined; var x122: u1 = undefined; subborrowxU64(&x121, &x122, x120, x114, 0xffffffffffffffff); var x123: u64 = undefined; var x124: u1 = undefined; subborrowxU64(&x123, &x124, x122, x116, 0xffffffff00000000); var x125: u64 = undefined; var x126: u1 = undefined; subborrowxU64(&x125, &x126, x124, cast(u64, 0x0), cast(u64, 0x0)); var x127: u64 = undefined; cmovznzU64(&x127, x126, x117, x110); var x128: u64 = undefined; cmovznzU64(&x128, x126, x119, x112); var x129: u64 = undefined; cmovznzU64(&x129, x126, x121, x114); var x130: u64 = undefined; cmovznzU64(&x130, x126, x123, x116); out1[0] = x127; out1[1] = x128; out1[2] = x129; out1[3] = x130; } /// The function toMontgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn toMontgomery(out1: *[4]u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, 0x66e12d94f3d95620); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, 0x2845b2392b6bec59); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, 0x4699799c49bd6fa6); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, 0x83244c95be79eea2); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); var x19: u64 = undefined; var x20: u64 = undefined; mulxU64(&x19, &x20, x11, 0xccd1c8aaee00bc4f); var x21: u64 = undefined; var x22: u64 = undefined; mulxU64(&x21, &x22, x19, 0xffffffff00000000); var x23: u64 = undefined; var x24: u64 = undefined; mulxU64(&x23, &x24, x19, 0xffffffffffffffff); var x25: u64 = undefined; var x26: u64 = undefined; mulxU64(&x25, &x26, x19, 0xbce6faada7179e84); var x27: u64 = undefined; var x28: u64 = undefined; mulxU64(&x27, &x28, x19, 0xf3b9cac2fc632551); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, 0x0, x28, x25); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, x30, x26, x23); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x24, x21); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, 0x0, x11, x27); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x13, x29); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x15, x31); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x17, x33); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, (cast(u64, x18) + x6), (cast(u64, x34) + x22)); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x1, 0x66e12d94f3d95620); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, 0x2845b2392b6bec59); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, 0x4699799c49bd6fa6); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, 0x83244c95be79eea2); var x53: u64 = undefined; var x54: u1 = undefined; addcarryxU64(&x53, &x54, 0x0, x52, x49); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, x54, x50, x47); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x48, x45); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, 0x0, x37, x51); var x61: u64 = undefined; var x62: u1 = undefined; addcarryxU64(&x61, &x62, x60, x39, x53); var x63: u64 = undefined; var x64: u1 = undefined; addcarryxU64(&x63, &x64, x62, x41, x55); var x65: u64 = undefined; var x66: u1 = undefined; addcarryxU64(&x65, &x66, x64, x43, x57); var x67: u64 = undefined; var x68: u64 = undefined; mulxU64(&x67, &x68, x59, 0xccd1c8aaee00bc4f); var x69: u64 = undefined; var x70: u64 = undefined; mulxU64(&x69, &x70, x67, 0xffffffff00000000); var x71: u64 = undefined; var x72: u64 = undefined; mulxU64(&x71, &x72, x67, 0xffffffffffffffff); var x73: u64 = undefined; var x74: u64 = undefined; mulxU64(&x73, &x74, x67, 0xbce6faada7179e84); var x75: u64 = undefined; var x76: u64 = undefined; mulxU64(&x75, &x76, x67, 0xf3b9cac2fc632551); var x77: u64 = undefined; var x78: u1 = undefined; addcarryxU64(&x77, &x78, 0x0, x76, x73); var x79: u64 = undefined; var x80: u1 = undefined; addcarryxU64(&x79, &x80, x78, x74, x71); var x81: u64 = undefined; var x82: u1 = undefined; addcarryxU64(&x81, &x82, x80, x72, x69); var x83: u64 = undefined; var x84: u1 = undefined; addcarryxU64(&x83, &x84, 0x0, x59, x75); var x85: u64 = undefined; var x86: u1 = undefined; addcarryxU64(&x85, &x86, x84, x61, x77); var x87: u64 = undefined; var x88: u1 = undefined; addcarryxU64(&x87, &x88, x86, x63, x79); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, x88, x65, x81); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, ((cast(u64, x66) + cast(u64, x44)) + (cast(u64, x58) + x46)), (cast(u64, x82) + x70)); var x93: u64 = undefined; var x94: u64 = undefined; mulxU64(&x93, &x94, x2, 0x66e12d94f3d95620); var x95: u64 = undefined; var x96: u64 = undefined; mulxU64(&x95, &x96, x2, 0x2845b2392b6bec59); var x97: u64 = undefined; var x98: u64 = undefined; mulxU64(&x97, &x98, x2, 0x4699799c49bd6fa6); var x99: u64 = undefined; var x100: u64 = undefined; mulxU64(&x99, &x100, x2, 0x83244c95be79eea2); var x101: u64 = undefined; var x102: u1 = undefined; addcarryxU64(&x101, &x102, 0x0, x100, x97); var x103: u64 = undefined; var x104: u1 = undefined; addcarryxU64(&x103, &x104, x102, x98, x95); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, x104, x96, x93); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, 0x0, x85, x99); var x109: u64 = undefined; var x110: u1 = undefined; addcarryxU64(&x109, &x110, x108, x87, x101); var x111: u64 = undefined; var x112: u1 = undefined; addcarryxU64(&x111, &x112, x110, x89, x103); var x113: u64 = undefined; var x114: u1 = undefined; addcarryxU64(&x113, &x114, x112, x91, x105); var x115: u64 = undefined; var x116: u64 = undefined; mulxU64(&x115, &x116, x107, 0xccd1c8aaee00bc4f); var x117: u64 = undefined; var x118: u64 = undefined; mulxU64(&x117, &x118, x115, 0xffffffff00000000); var x119: u64 = undefined; var x120: u64 = undefined; mulxU64(&x119, &x120, x115, 0xffffffffffffffff); var x121: u64 = undefined; var x122: u64 = undefined; mulxU64(&x121, &x122, x115, 0xbce6faada7179e84); var x123: u64 = undefined; var x124: u64 = undefined; mulxU64(&x123, &x124, x115, 0xf3b9cac2fc632551); var x125: u64 = undefined; var x126: u1 = undefined; addcarryxU64(&x125, &x126, 0x0, x124, x121); var x127: u64 = undefined; var x128: u1 = undefined; addcarryxU64(&x127, &x128, x126, x122, x119); var x129: u64 = undefined; var x130: u1 = undefined; addcarryxU64(&x129, &x130, x128, x120, x117); var x131: u64 = undefined; var x132: u1 = undefined; addcarryxU64(&x131, &x132, 0x0, x107, x123); var x133: u64 = undefined; var x134: u1 = undefined; addcarryxU64(&x133, &x134, x132, x109, x125); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, x134, x111, x127); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x113, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, ((cast(u64, x114) + cast(u64, x92)) + (cast(u64, x106) + x94)), (cast(u64, x130) + x118)); var x141: u64 = undefined; var x142: u64 = undefined; mulxU64(&x141, &x142, x3, 0x66e12d94f3d95620); var x143: u64 = undefined; var x144: u64 = undefined; mulxU64(&x143, &x144, x3, 0x2845b2392b6bec59); var x145: u64 = undefined; var x146: u64 = undefined; mulxU64(&x145, &x146, x3, 0x4699799c49bd6fa6); var x147: u64 = undefined; var x148: u64 = undefined; mulxU64(&x147, &x148, x3, 0x83244c95be79eea2); var x149: u64 = undefined; var x150: u1 = undefined; addcarryxU64(&x149, &x150, 0x0, x148, x145); var x151: u64 = undefined; var x152: u1 = undefined; addcarryxU64(&x151, &x152, x150, x146, x143); var x153: u64 = undefined; var x154: u1 = undefined; addcarryxU64(&x153, &x154, x152, x144, x141); var x155: u64 = undefined; var x156: u1 = undefined; addcarryxU64(&x155, &x156, 0x0, x133, x147); var x157: u64 = undefined; var x158: u1 = undefined; addcarryxU64(&x157, &x158, x156, x135, x149); var x159: u64 = undefined; var x160: u1 = undefined; addcarryxU64(&x159, &x160, x158, x137, x151); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, x160, x139, x153); var x163: u64 = undefined; var x164: u64 = undefined; mulxU64(&x163, &x164, x155, 0xccd1c8aaee00bc4f); var x165: u64 = undefined; var x166: u64 = undefined; mulxU64(&x165, &x166, x163, 0xffffffff00000000); var x167: u64 = undefined; var x168: u64 = undefined; mulxU64(&x167, &x168, x163, 0xffffffffffffffff); var x169: u64 = undefined; var x170: u64 = undefined; mulxU64(&x169, &x170, x163, 0xbce6faada7179e84); var x171: u64 = undefined; var x172: u64 = undefined; mulxU64(&x171, &x172, x163, 0xf3b9cac2fc632551); var x173: u64 = undefined; var x174: u1 = undefined; addcarryxU64(&x173, &x174, 0x0, x172, x169); var x175: u64 = undefined; var x176: u1 = undefined; addcarryxU64(&x175, &x176, x174, x170, x167); var x177: u64 = undefined; var x178: u1 = undefined; addcarryxU64(&x177, &x178, x176, x168, x165); var x179: u64 = undefined; var x180: u1 = undefined; addcarryxU64(&x179, &x180, 0x0, x155, x171); var x181: u64 = undefined; var x182: u1 = undefined; addcarryxU64(&x181, &x182, x180, x157, x173); var x183: u64 = undefined; var x184: u1 = undefined; addcarryxU64(&x183, &x184, x182, x159, x175); var x185: u64 = undefined; var x186: u1 = undefined; addcarryxU64(&x185, &x186, x184, x161, x177); var x187: u64 = undefined; var x188: u1 = undefined; addcarryxU64(&x187, &x188, x186, ((cast(u64, x162) + cast(u64, x140)) + (cast(u64, x154) + x142)), (cast(u64, x178) + x166)); var x189: u64 = undefined; var x190: u1 = undefined; subborrowxU64(&x189, &x190, 0x0, x181, 0xf3b9cac2fc632551); var x191: u64 = undefined; var x192: u1 = undefined; subborrowxU64(&x191, &x192, x190, x183, 0xbce6faada7179e84); var x193: u64 = undefined; var x194: u1 = undefined; subborrowxU64(&x193, &x194, x192, x185, 0xffffffffffffffff); var x195: u64 = undefined; var x196: u1 = undefined; subborrowxU64(&x195, &x196, x194, x187, 0xffffffff00000000); var x197: u64 = undefined; var x198: u1 = undefined; subborrowxU64(&x197, &x198, x196, cast(u64, x188), cast(u64, 0x0)); var x199: u64 = undefined; cmovznzU64(&x199, x198, x189, x181); var x200: u64 = undefined; cmovznzU64(&x200, x198, x191, x183); var x201: u64 = undefined; cmovznzU64(&x201, x198, x193, x185); var x202: u64 = undefined; cmovznzU64(&x202, x198, x195, x187); out1[0] = x199; out1[1] = x200; out1[2] = x201; out1[3] = x202; } /// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] pub fn nonzero(out1: *u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3])))); out1.* = x1; } /// The function selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[4]u64, arg1: u1, arg2: [4]u64, arg3: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; } /// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] pub fn toBytes(out1: *[32]u8, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[3]); const x2 = (arg1[2]); const x3 = (arg1[1]); const x4 = (arg1[0]); const x5 = cast(u8, (x4 & cast(u64, 0xff))); const x6 = (x4 >> 8); const x7 = cast(u8, (x6 & cast(u64, 0xff))); const x8 = (x6 >> 8); const x9 = cast(u8, (x8 & cast(u64, 0xff))); const x10 = (x8 >> 8); const x11 = cast(u8, (x10 & cast(u64, 0xff))); const x12 = (x10 >> 8); const x13 = cast(u8, (x12 & cast(u64, 0xff))); const x14 = (x12 >> 8); const x15 = cast(u8, (x14 & cast(u64, 0xff))); const x16 = (x14 >> 8); const x17 = cast(u8, (x16 & cast(u64, 0xff))); const x18 = cast(u8, (x16 >> 8)); const x19 = cast(u8, (x3 & cast(u64, 0xff))); const x20 = (x3 >> 8); const x21 = cast(u8, (x20 & cast(u64, 0xff))); const x22 = (x20 >> 8); const x23 = cast(u8, (x22 & cast(u64, 0xff))); const x24 = (x22 >> 8); const x25 = cast(u8, (x24 & cast(u64, 0xff))); const x26 = (x24 >> 8); const x27 = cast(u8, (x26 & cast(u64, 0xff))); const x28 = (x26 >> 8); const x29 = cast(u8, (x28 & cast(u64, 0xff))); const x30 = (x28 >> 8); const x31 = cast(u8, (x30 & cast(u64, 0xff))); const x32 = cast(u8, (x30 >> 8)); const x33 = cast(u8, (x2 & cast(u64, 0xff))); const x34 = (x2 >> 8); const x35 = cast(u8, (x34 & cast(u64, 0xff))); const x36 = (x34 >> 8); const x37 = cast(u8, (x36 & cast(u64, 0xff))); const x38 = (x36 >> 8); const x39 = cast(u8, (x38 & cast(u64, 0xff))); const x40 = (x38 >> 8); const x41 = cast(u8, (x40 & cast(u64, 0xff))); const x42 = (x40 >> 8); const x43 = cast(u8, (x42 & cast(u64, 0xff))); const x44 = (x42 >> 8); const x45 = cast(u8, (x44 & cast(u64, 0xff))); const x46 = cast(u8, (x44 >> 8)); const x47 = cast(u8, (x1 & cast(u64, 0xff))); const x48 = (x1 >> 8); const x49 = cast(u8, (x48 & cast(u64, 0xff))); const x50 = (x48 >> 8); const x51 = cast(u8, (x50 & cast(u64, 0xff))); const x52 = (x50 >> 8); const x53 = cast(u8, (x52 & cast(u64, 0xff))); const x54 = (x52 >> 8); const x55 = cast(u8, (x54 & cast(u64, 0xff))); const x56 = (x54 >> 8); const x57 = cast(u8, (x56 & cast(u64, 0xff))); const x58 = (x56 >> 8); const x59 = cast(u8, (x58 & cast(u64, 0xff))); const x60 = cast(u8, (x58 >> 8)); out1[0] = x5; out1[1] = x7; out1[2] = x9; out1[3] = x11; out1[4] = x13; out1[5] = x15; out1[6] = x17; out1[7] = x18; out1[8] = x19; out1[9] = x21; out1[10] = x23; out1[11] = x25; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x39; out1[20] = x41; out1[21] = x43; out1[22] = x45; out1[23] = x46; out1[24] = x47; out1[25] = x49; out1[26] = x51; out1[27] = x53; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; } /// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fromBytes(out1: *[4]u64, arg1: [32]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[31])) << 56); const x2 = (cast(u64, (arg1[30])) << 48); const x3 = (cast(u64, (arg1[29])) << 40); const x4 = (cast(u64, (arg1[28])) << 32); const x5 = (cast(u64, (arg1[27])) << 24); const x6 = (cast(u64, (arg1[26])) << 16); const x7 = (cast(u64, (arg1[25])) << 8); const x8 = (arg1[24]); const x9 = (cast(u64, (arg1[23])) << 56); const x10 = (cast(u64, (arg1[22])) << 48); const x11 = (cast(u64, (arg1[21])) << 40); const x12 = (cast(u64, (arg1[20])) << 32); const x13 = (cast(u64, (arg1[19])) << 24); const x14 = (cast(u64, (arg1[18])) << 16); const x15 = (cast(u64, (arg1[17])) << 8); const x16 = (arg1[16]); const x17 = (cast(u64, (arg1[15])) << 56); const x18 = (cast(u64, (arg1[14])) << 48); const x19 = (cast(u64, (arg1[13])) << 40); const x20 = (cast(u64, (arg1[12])) << 32); const x21 = (cast(u64, (arg1[11])) << 24); const x22 = (cast(u64, (arg1[10])) << 16); const x23 = (cast(u64, (arg1[9])) << 8); const x24 = (arg1[8]); const x25 = (cast(u64, (arg1[7])) << 56); const x26 = (cast(u64, (arg1[6])) << 48); const x27 = (cast(u64, (arg1[5])) << 40); const x28 = (cast(u64, (arg1[4])) << 32); const x29 = (cast(u64, (arg1[3])) << 24); const x30 = (cast(u64, (arg1[2])) << 16); const x31 = (cast(u64, (arg1[1])) << 8); const x32 = (arg1[0]); const x33 = (x31 + cast(u64, x32)); const x34 = (x30 + x33); const x35 = (x29 + x34); const x36 = (x28 + x35); const x37 = (x27 + x36); const x38 = (x26 + x37); const x39 = (x25 + x38); const x40 = (x23 + cast(u64, x24)); const x41 = (x22 + x40); const x42 = (x21 + x41); const x43 = (x20 + x42); const x44 = (x19 + x43); const x45 = (x18 + x44); const x46 = (x17 + x45); const x47 = (x15 + cast(u64, x16)); const x48 = (x14 + x47); const x49 = (x13 + x48); const x50 = (x12 + x49); const x51 = (x11 + x50); const x52 = (x10 + x51); const x53 = (x9 + x52); const x54 = (x7 + cast(u64, x8)); const x55 = (x6 + x54); const x56 = (x5 + x55); const x57 = (x4 + x56); const x58 = (x3 + x57); const x59 = (x2 + x58); const x60 = (x1 + x59); out1[0] = x39; out1[1] = x46; out1[2] = x53; out1[3] = x60; } /// The function setOne returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn setOne(out1: *[4]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xc46353d039cdaaf; out1[1] = 0x4319055258e8617b; out1[2] = cast(u64, 0x0); out1[3] = 0xffffffff; } /// The function msat returns the saturated representation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn msat(out1: *[5]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xf3b9cac2fc632551; out1[1] = 0xbce6faada7179e84; out1[2] = 0xffffffffffffffff; out1[3] = 0xffffffff00000000; out1[4] = cast(u64, 0x0); } /// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstepPrecomp(out1: *[4]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xd739262fb7fcfbb5; out1[1] = 0x8ac6f75d20074414; out1[2] = 0xc67428bfb5e3c256; out1[3] = 0x444962f2eda7aedf; } /// The function divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstep(out1: *u64, out2: *[5]u64, out3: *[5]u64, out4: *[4]u64, out5: *[4]u64, arg1: u64, arg2: [5]u64, arg3: [5]u64, arg4: [4]u64, arg5: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (~arg1), cast(u64, 0x1)); const x3 = (cast(u1, (x1 >> 63)) & cast(u1, ((arg3[0]) & cast(u64, 0x1)))); var x4: u64 = undefined; var x5: u1 = undefined; addcarryxU64(&x4, &x5, 0x0, (~arg1), cast(u64, 0x1)); var x6: u64 = undefined; cmovznzU64(&x6, x3, arg1, x4); var x7: u64 = undefined; cmovznzU64(&x7, x3, (arg2[0]), (arg3[0])); var x8: u64 = undefined; cmovznzU64(&x8, x3, (arg2[1]), (arg3[1])); var x9: u64 = undefined; cmovznzU64(&x9, x3, (arg2[2]), (arg3[2])); var x10: u64 = undefined; cmovznzU64(&x10, x3, (arg2[3]), (arg3[3])); var x11: u64 = undefined; cmovznzU64(&x11, x3, (arg2[4]), (arg3[4])); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, 0x0, cast(u64, 0x1), (~(arg2[0]))); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, cast(u64, 0x0), (~(arg2[1]))); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, cast(u64, 0x0), (~(arg2[2]))); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, cast(u64, 0x0), (~(arg2[3]))); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, cast(u64, 0x0), (~(arg2[4]))); var x22: u64 = undefined; cmovznzU64(&x22, x3, (arg3[0]), x12); var x23: u64 = undefined; cmovznzU64(&x23, x3, (arg3[1]), x14); var x24: u64 = undefined; cmovznzU64(&x24, x3, (arg3[2]), x16); var x25: u64 = undefined; cmovznzU64(&x25, x3, (arg3[3]), x18); var x26: u64 = undefined; cmovznzU64(&x26, x3, (arg3[4]), x20); var x27: u64 = undefined; cmovznzU64(&x27, x3, (arg4[0]), (arg5[0])); var x28: u64 = undefined; cmovznzU64(&x28, x3, (arg4[1]), (arg5[1])); var x29: u64 = undefined; cmovznzU64(&x29, x3, (arg4[2]), (arg5[2])); var x30: u64 = undefined; cmovznzU64(&x30, x3, (arg4[3]), (arg5[3])); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, 0x0, x27, x27); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x28, x28); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, x29, x29); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x30, x30); var x39: u64 = undefined; var x40: u1 = undefined; subborrowxU64(&x39, &x40, 0x0, x31, 0xf3b9cac2fc632551); var x41: u64 = undefined; var x42: u1 = undefined; subborrowxU64(&x41, &x42, x40, x33, 0xbce6faada7179e84); var x43: u64 = undefined; var x44: u1 = undefined; subborrowxU64(&x43, &x44, x42, x35, 0xffffffffffffffff); var x45: u64 = undefined; var x46: u1 = undefined; subborrowxU64(&x45, &x46, x44, x37, 0xffffffff00000000); var x47: u64 = undefined; var x48: u1 = undefined; subborrowxU64(&x47, &x48, x46, cast(u64, x38), cast(u64, 0x0)); const x49 = (arg4[3]); const x50 = (arg4[2]); const x51 = (arg4[1]); const x52 = (arg4[0]); var x53: u64 = undefined; var x54: u1 = undefined; subborrowxU64(&x53, &x54, 0x0, cast(u64, 0x0), x52); var x55: u64 = undefined; var x56: u1 = undefined; subborrowxU64(&x55, &x56, x54, cast(u64, 0x0), x51); var x57: u64 = undefined; var x58: u1 = undefined; subborrowxU64(&x57, &x58, x56, cast(u64, 0x0), x50); var x59: u64 = undefined; var x60: u1 = undefined; subborrowxU64(&x59, &x60, x58, cast(u64, 0x0), x49); var x61: u64 = undefined; cmovznzU64(&x61, x60, cast(u64, 0x0), 0xffffffffffffffff); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x53, (x61 & 0xf3b9cac2fc632551)); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x55, (x61 & 0xbce6faada7179e84)); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x57, x61); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x59, (x61 & 0xffffffff00000000)); var x70: u64 = undefined; cmovznzU64(&x70, x3, (arg5[0]), x62); var x71: u64 = undefined; cmovznzU64(&x71, x3, (arg5[1]), x64); var x72: u64 = undefined; cmovznzU64(&x72, x3, (arg5[2]), x66); var x73: u64 = undefined; cmovznzU64(&x73, x3, (arg5[3]), x68); const x74 = cast(u1, (x22 & cast(u64, 0x1))); var x75: u64 = undefined; cmovznzU64(&x75, x74, cast(u64, 0x0), x7); var x76: u64 = undefined; cmovznzU64(&x76, x74, cast(u64, 0x0), x8); var x77: u64 = undefined; cmovznzU64(&x77, x74, cast(u64, 0x0), x9); var x78: u64 = undefined; cmovznzU64(&x78, x74, cast(u64, 0x0), x10); var x79: u64 = undefined; cmovznzU64(&x79, x74, cast(u64, 0x0), x11); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, 0x0, x22, x75); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x23, x76); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x24, x77); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x25, x78); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x26, x79); var x90: u64 = undefined; cmovznzU64(&x90, x74, cast(u64, 0x0), x27); var x91: u64 = undefined; cmovznzU64(&x91, x74, cast(u64, 0x0), x28); var x92: u64 = undefined; cmovznzU64(&x92, x74, cast(u64, 0x0), x29); var x93: u64 = undefined; cmovznzU64(&x93, x74, cast(u64, 0x0), x30); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, 0x0, x70, x90); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x71, x91); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x72, x92); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x73, x93); var x102: u64 = undefined; var x103: u1 = undefined; subborrowxU64(&x102, &x103, 0x0, x94, 0xf3b9cac2fc632551); var x104: u64 = undefined; var x105: u1 = undefined; subborrowxU64(&x104, &x105, x103, x96, 0xbce6faada7179e84); var x106: u64 = undefined; var x107: u1 = undefined; subborrowxU64(&x106, &x107, x105, x98, 0xffffffffffffffff); var x108: u64 = undefined; var x109: u1 = undefined; subborrowxU64(&x108, &x109, x107, x100, 0xffffffff00000000); var x110: u64 = undefined; var x111: u1 = undefined; subborrowxU64(&x110, &x111, x109, cast(u64, x101), cast(u64, 0x0)); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, 0x0, x6, cast(u64, 0x1)); const x114 = ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)); const x115 = ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)); const x116 = ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)); const x117 = ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)); const x118 = ((x88 & 0x8000000000000000) | (x88 >> 1)); var x119: u64 = undefined; cmovznzU64(&x119, x48, x39, x31); var x120: u64 = undefined; cmovznzU64(&x120, x48, x41, x33); var x121: u64 = undefined; cmovznzU64(&x121, x48, x43, x35); var x122: u64 = undefined; cmovznzU64(&x122, x48, x45, x37); var x123: u64 = undefined; cmovznzU64(&x123, x111, x102, x94); var x124: u64 = undefined; cmovznzU64(&x124, x111, x104, x96); var x125: u64 = undefined; cmovznzU64(&x125, x111, x106, x98); var x126: u64 = undefined; cmovznzU64(&x126, x111, x108, x100); out1.* = x112; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out3[0] = x114; out3[1] = x115; out3[2] = x116; out3[3] = x117; out3[4] = x118; out4[0] = x119; out4[1] = x120; out4[2] = x121; out4[3] = x122; out5[0] = x123; out5[1] = x124; out5[2] = x125; out5[3] = x126; }
lib/std/crypto/pcurves/p256/p256_scalar_64.zig
const builtin = @import("builtin"); const expect = std.testing.expect; const std = @import("../std.zig"); const math = std.math; /// Returns x rounded to the nearest integer, rounding half away from zero. /// /// Special Cases: /// - round(+-0) = +-0 /// - round(+-inf) = +-inf /// - round(nan) = nan pub fn round(x: var) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => round32(x), f64 => round64(x), f128 => round128(x), else => @compileError("round not implemented for " ++ @typeName(T)), }; } fn round32(x_: f32) f32 { var x = x_; const u = @bitCast(u32, x); const e = (u >> 23) & 0xFF; var y: f32 = undefined; if (e >= 0x7F + 23) { return x; } if (u >> 31 != 0) { x = -x; } if (e < 0x7F - 1) { math.forceEval(x + math.f32_toint); return 0 * @bitCast(f32, u); } y = x + math.f32_toint - math.f32_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 31 != 0) { return -y; } else { return y; } } fn round64(x_: f64) f64 { var x = x_; const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52) { return x; } if (u >> 63 != 0) { x = -x; } if (e < 0x3ff - 1) { math.forceEval(x + math.f64_toint); return 0 * @bitCast(f64, u); } y = x + math.f64_toint - math.f64_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 63 != 0) { return -y; } else { return y; } } fn round128(x_: f128) f128 { var x = x_; const u = @bitCast(u128, x); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112) { return x; } if (u >> 127 != 0) { x = -x; } if (e < 0x3FFF - 1) { math.forceEval(x + math.f64_toint); return 0 * @bitCast(f128, u); } y = x + math.f128_toint - math.f128_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 127 != 0) { return -y; } else { return y; } } test "math.round" { expect(round(@as(f32, 1.3)) == round32(1.3)); expect(round(@as(f64, 1.3)) == round64(1.3)); expect(round(@as(f128, 1.3)) == round128(1.3)); } test "math.round32" { expect(round32(1.3) == 1.0); expect(round32(-1.3) == -1.0); expect(round32(0.2) == 0.0); expect(round32(1.8) == 2.0); } test "math.round64" { expect(round64(1.3) == 1.0); expect(round64(-1.3) == -1.0); expect(round64(0.2) == 0.0); expect(round64(1.8) == 2.0); } test "math.round128" { expect(round128(1.3) == 1.0); expect(round128(-1.3) == -1.0); expect(round128(0.2) == 0.0); expect(round128(1.8) == 2.0); } test "math.round32.special" { expect(round32(0.0) == 0.0); expect(round32(-0.0) == -0.0); expect(math.isPositiveInf(round32(math.inf(f32)))); expect(math.isNegativeInf(round32(-math.inf(f32)))); expect(math.isNan(round32(math.nan(f32)))); } test "math.round64.special" { expect(round64(0.0) == 0.0); expect(round64(-0.0) == -0.0); expect(math.isPositiveInf(round64(math.inf(f64)))); expect(math.isNegativeInf(round64(-math.inf(f64)))); expect(math.isNan(round64(math.nan(f64)))); } test "math.round128.special" { expect(round128(0.0) == 0.0); expect(round128(-0.0) == -0.0); expect(math.isPositiveInf(round128(math.inf(f128)))); expect(math.isNegativeInf(round128(-math.inf(f128)))); expect(math.isNan(round128(math.nan(f128)))); }
lib/std/math/round.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const builtin = @import("builtin"); const glfw = @import("glfw"); const gpu = @import("gpu"); const platform = @import("platform.zig"); const structs = @import("structs.zig"); const enums = @import("enums.zig"); const Timer = @import("Timer.zig"); const Engine = @This(); /// Window, events, inputs etc. core: Core, /// WebGPU driver - stores device, swap chains, targets and more gpu_driver: GpuDriver, allocator: Allocator, options: structs.Options, /// The amount of time (in seconds) that has passed since the last frame was rendered. /// /// For example, if you are animating a cube which should rotate 360 degrees every second, /// instead of writing (360.0 / 60.0) and assuming the frame rate is 60hz, write /// (360.0 * engine.delta_time) delta_time: f32 = 0, delta_time_ns: u64 = 0, timer: Timer, pub const Core = struct { internal: platform.CoreType, pub fn setShouldClose(core: *Core, value: bool) void { core.internal.setShouldClose(value); } // Returns the framebuffer size, in subpixel units. // // e.g. returns 1280x960 on macOS for a window that is 640x480 pub fn getFramebufferSize(core: *Core) structs.Size { return core.internal.getFramebufferSize(); } // Returns the widow size, in pixel units. // // e.g. returns 640x480 on macOS for a window that is 640x480 pub fn getWindowSize(core: *Core) structs.Size { return core.internal.getWindowSize(); } pub fn setSizeLimits(core: *Core, min: structs.SizeOptional, max: structs.SizeOptional) !void { return core.internal.setSizeLimits(min, max); } pub fn pollEvent(core: *Core) ?structs.Event { return core.internal.pollEvent(); } }; pub const GpuDriver = struct { internal: platform.GpuDriverType, device: gpu.Device, backend_type: gpu.Adapter.BackendType, swap_chain: ?gpu.SwapChain, swap_chain_format: gpu.Texture.Format, surface: ?gpu.Surface, current_desc: gpu.SwapChain.Descriptor, target_desc: gpu.SwapChain.Descriptor, }; pub fn init(allocator: std.mem.Allocator, options: structs.Options) !Engine { var engine = Engine{ .allocator = allocator, .options = options, .timer = try Timer.start(), .core = undefined, .gpu_driver = undefined, }; // Note: if in future, there is a conflict in init() signature of different backends, // move these calls to the entry point file, which is native.zig for Glfw, for example engine.core.internal = try platform.CoreType.init(allocator, &engine); engine.gpu_driver.internal = try platform.GpuDriverType.init(allocator, &engine); return engine; }
src/Engine.zig
const std = @import("std"); const network = @import("zig-network"); const uri = @import("zig-uri"); const args_parse = @import("zig-args"); const known_folder = @import("known-folders"); const ssl = @import("zig-bearssl"); const app_name = "gurl"; const TrustLevel = enum { all, ca, tofu, }; pub fn main() !u8 { const stdout = std.io.getStdOut().outStream(); const stderr = std.io.getStdErr().outStream(); const stdin = std.io.getStdIn().inStream(); const generic_allocator = std.heap.page_allocator; // THIS IS INEFFICIENT AS FUCK var path_arena = std.heap.ArenaAllocator.init(generic_allocator); defer path_arena.deinit(); var config_root = if (try known_folder.getPath(generic_allocator, .roaming_configuration)) |path| path else { try stderr.writeAll("Could not get the root configuration folder!\n"); return 1; }; defer generic_allocator.free(config_root); const app_config_file_name = try std.fs.path.join(&path_arena.allocator, &[_][]const u8{ config_root, app_name, "config.json" }); var cli = try args_parse.parseForCurrentProcess(struct { @"remote-name": bool = false, output: ?[]const u8 = null, help: bool = false, trust: TrustLevel = .ca, @"trust-anchor": []const u8 = "/etc/ssl/cert.pem", @"trust-store": ?[]const u8 = null, @"accept-host": bool = false, @"ignore-hostname-mismatch": bool = false, @"force-binary-on-stdout": bool = false, raw: bool = false, pub const shorthands = .{ .O = "remote-name", .o = "output", .h = "help", .t = "trust", .a = "accept-host", .r = "raw", }; }, generic_allocator); defer cli.deinit(); if (cli.options.help or cli.positionals.len != 1) { try stderr.print( "{} [--help] [--remote-name] [--output <file>] <url>\n", .{std.fs.path.basename(cli.executable_name.?)}, ); try stderr.writeAll(@embedFile("helpmessage.txt")); return if (cli.options.help) @as(u8, 0) else 1; } const parsed_url = uri.parse(cli.positionals[0]) catch { try stderr.print("{} is not a valid URL!\n", .{cli.positionals[0]}); return 1; }; if (parsed_url.host == null) { try stderr.writeAll("The url does not contain a host name!\n"); return 1; } // Check for remote name option if (cli.options.@"remote-name") { if (cli.options.output != null) { try stderr.writeAll("--remote-name and --output are not allowed to be used both. Chose one!\n"); return 1; } const file_name = std.fs.path.basename(parsed_url.path.?); if (file_name.len == 0) { try stderr.writeAll("The url does not contain a file name. Use --output to specify a file name!\n"); return 1; } cli.options.output = file_name; } const app_trust_store_dir = try std.fs.path.join(&path_arena.allocator, &[_][]const u8{ config_root, app_name, "trust-store" }); var app_trust_store: ?std.fs.Dir = std.fs.cwd().openDir(cli.options.@"trust-store" orelse app_trust_store_dir, .{ .access_sub_paths = true, .iterate = true }) catch |open_dir_err| switch (open_dir_err) { error.FileNotFound => blk: { var backing_buffer: [10]u8 = undefined; const create_dir = while (true) { try stderr.print("Trust store directory {} not found. Do you want to create it? [Y/N] ", .{ app_trust_store_dir, }); const answer = std.mem.trim(u8, if (try stdin.readUntilDelimiterOrEof(&backing_buffer, '\n')) |a| a else { break :blk null; }, "\r"); std.debug.warn("{X}\n", .{answer}); if (std.mem.eql(u8, answer, "Y") or std.mem.eql(u8, answer, "y")) { break true; } if (std.mem.eql(u8, answer, "N") or std.mem.eql(u8, answer, "n")) { break false; } } else unreachable; if (create_dir) { const dir = std.fs.cwd().makeOpenPath(app_trust_store_dir, .{ .access_sub_paths = true, .iterate = true }) catch |err| { try stderr.print("Could not create directory {}: {}\n", .{ app_trust_store_dir, err }); return 1; }; break :blk dir; } else { break :blk null; } }, else => { try stderr.print("Could not access {}: {}\n", .{ app_trust_store_dir, open_dir_err }); return 1; }, }; defer if (app_trust_store) |*dir| { dir.close(); }; if (cli.options.@"accept-host" and app_trust_store == null) { try stderr.writeAll("--accept-host cannot store server public key: trust store does not exist.\n"); return 1; } var trust_anchors = ssl.TrustAnchorCollection.init(generic_allocator); defer trust_anchors.deinit(); if (cli.options.trust == .ca) { var file = try std.fs.cwd().openFile(cli.options.@"trust-anchor", .{ .read = true, .write = false }); defer file.close(); const pem_text = try file.inStream().readAllAlloc(generic_allocator, 1 << 20); // 1 MB defer generic_allocator.free(pem_text); try trust_anchors.appendFromPEM(pem_text); } // TODO: // - "gemini://heavysquare.com/" does not send an end-of-stream?! // - ""gemini://typed-hole.org/topkek" does not send an end-of-stream?! var known_certificate_verification: ?RequestVerification = null; defer if (known_certificate_verification) |v| { // we know that it's always a public_key for TOFU v.public_key.deinit(); }; if (app_trust_store) |dir| { if (dir.openFile(parsed_url.host.?, .{ .read = true, .write = false })) |file| { defer file.close(); known_certificate_verification = RequestVerification{ .public_key = try parsePublicKeyFile(generic_allocator, file), }; } else |err| { switch (err) { error.FileNotFound => {}, // ignore missing file, we just don't know the server yet else => return err, } } } const request_options = RequestOptions{ .memory_limit = 100 * mebi_bytes, .verification = switch (cli.options.trust) { // no verification for .all => RequestVerification{ .none = {} }, // use known_certificate_verification when possible .ca => known_certificate_verification orelse RequestVerification{ .trust_anchor = trust_anchors }, .tofu => known_certificate_verification orelse RequestVerification{ .none = {} }, }, }; var response = requestRaw(generic_allocator, cli.positionals[0], request_options) catch |err| switch (err) { error.MissingAuthority => { try stderr.writeAll("The url does not contain a host name!\n"); return 1; }, error.UnsupportedScheme => { try stderr.writeAll("The url scheme is not supported!\n"); return 1; }, error.CouldNotConnect => { try stderr.writeAll("Failed to connect to the server. Is the address correct and the server reachable?\n"); return 1; }, error.BadServerName => { try stderr.writeAll("The server certificate is not valid for the given host name!\n"); return 1; }, else => return err, }; defer response.free(generic_allocator); // Add server to trust store if requested // when tofu and no verification means we see the host for the first time → accept the cert as well if (cli.options.@"accept-host" or (cli.options.trust == .tofu and request_options.verification == .none)) { // app_trust_store is not null, we verified this above! // parsed_url.host is not null, we already used it for requesting var file = app_trust_store.?.createFile(parsed_url.host.?, .{ .exclusive = true }) catch |create_file_err| switch (create_file_err) { error.PathAlreadyExists => { // TODO: Verify here that the key didn't actually change between // two --accept-host calls. This is unlikely as we already accepted the server try stderr.writeAll("The server public key is already in the trust store!\n"); return 1; }, else => return create_file_err, }; errdefer app_trust_store.?.deleteFile(parsed_url.host.?) catch |err| { stderr.print("Failed to delete server public key {}: Please delete this file by hand or you may not be able to connect to this server in the future!\n", .{ parsed_url.host.?, }) catch {}; }; defer file.close(); // using the "gurl very simple key format": // Line 1: RSA or EC // Line 2: RSA n or EC curve // Line 3: RSA e or EC q // Line 4: key usages // All values (n,e,q) are hex-encoded var outstream = file.outStream(); switch (response.public_key.key) { .rsa => |rsa| { try outstream.writeAll("RSA\n"); try outstream.print("{X}\n", .{rsa.n}); try outstream.print("{X}\n", .{rsa.e}); }, .ec => |ec| { const usages = response.public_key.usages orelse @as(c_uint, 0); try outstream.writeAll("EC"); try outstream.print("{X}\n", .{ec.curve}); try outstream.print("{X}\n", .{ec.q}); }, } const usages = response.public_key.usages orelse @as(c_uint, 0); try outstream.print("{X}\n", .{usages}); } switch (response.content) { .success => |body| { // what are we doing with the mime type here? try stderr.print("MIME: {0}\n", .{body.mime}); if (cli.options.output) |file_name| { var outfile = try std.fs.cwd().createFile(file_name, .{ .exclusive = false }); defer outfile.close(); try outfile.writeAll(body.data); } else { if (!std.mem.startsWith(u8, body.mime, "text/") and !cli.options.@"force-binary-on-stdout") { try stderr.print("Will not write data of type {} to stdout unless --force-binary-on-stdout is used.\n", .{ body.mime, }); return 1; } try stdout.writeAll(body.data); } }, .untrustedCertificate => { try stdout.writeAll("Server is not trusted. Use --accept-host to add the server to your trust store!\n"); return 1; }, .badSignature => { try stderr.print( "Signature mismatch! The host {} could not be verified!\n", .{ parsed_url.host, }, ); return 1; }, else => try stdout.print("unimplemented response type: {}\n", .{response}), } return 0; } fn convertHexToArray(allocator: *std.mem.Allocator, input: []const u8) ![]u8 { if ((input.len % 2) != 0) return error.StringMustHaveEvenLength; var data = try allocator.alloc(u8, input.len / 2); errdefer allocator.free(data); var i: usize = 0; while (i < input.len) : (i += 2) { data[i / 2] = try std.fmt.parseInt(u8, input[i..][0..2], 16); } return data; } fn parsePublicKeyFile(allocator: *std.mem.Allocator, file: std.fs.File) !ssl.PublicKey { const instream = file.inStream(); // RSA is supported up to 4096 bits, so 512 byte. var backing_buffer: [520]u8 = undefined; const type_id = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; var key = ssl.PublicKey{ .arena = std.heap.ArenaAllocator.init(allocator), .key = undefined, .usages = null, }; errdefer key.deinit(); if (std.mem.eql(u8, type_id, "RSA")) { var rsa = ssl.PublicKey.KeyStore.RSA{ .n = undefined, .e = undefined, }; const n_string = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; rsa.n = try convertHexToArray(&key.arena.allocator, n_string); const e_string = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; rsa.e = try convertHexToArray(&key.arena.allocator, e_string); key.key = ssl.PublicKey.KeyStore{ .rsa = rsa, }; } else if (std.mem.eql(u8, type_id, "EC")) { var ec = ssl.PublicKey.KeyStore.EC{ .curve = undefined, .q = undefined, }; const curve_string = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; ec.curve = try std.fmt.parseInt(c_int, curve_string, 16); const q_string = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; ec.q = try convertHexToArray(&key.arena.allocator, q_string); key.key = ssl.PublicKey.KeyStore{ .ec = ec, }; } else { return error.UnsupportedKeyType; } const usages_text = (try instream.readUntilDelimiterOrEof(&backing_buffer, '\n')) orelse return error.InvalidFormat; key.usages = try std.fmt.parseInt(c_uint, usages_text, 16); return key; } // gemini://gemini.circumlunar.space/docs/spec-spec.txt // gemini://gemini.conman.org/test/torture/0000 // /* // * Check whether we closed properly or not. If the engine is // * closed, then its error status allows to distinguish between // * a normal closure and a SSL error. // * // * If the engine is NOT closed, then this means that the // * underlying network socket was closed or failed in some way. // * Note that many Web servers out there do not properly close // * their SSL connections (they don't send a close_notify alert), // * which will be reported here as "socket closed without proper // * SSL termination". // */ // // if (br_ssl_engine_current_state(&sc.eng) == BR_SSL_CLOSED) { // int err; // err = br_ssl_engine_last_error(&sc.eng); // if (err == 0) { // fprintf(stderr, "closed.\n"); // return EXIT_SUCCESS; // } else { // fprintf(stderr, "SSL error %d\n", err); // return EXIT_FAILURE; // } // } else { // fprintf(stderr, // "socket closed without proper SSL termination\n"); // return EXIT_FAILURE; // } /// Response from the server. Must call free to release the resources in the response. pub const Response = struct { const Self = @This(); /// Contains the response from the server content: Content, /// Contains the certificate chain returned by the server. certificate_chain: []ssl.DERCertificate, /// The public key of the server extracted from the certificate chain public_key: ssl.PublicKey, /// Releases the stored resources in the response. fn free(self: Self, allocator: *std.mem.Allocator) void { allocator.free(self.certificate_chain); self.public_key.deinit(); switch (self.content) { .untrustedCertificate => {}, .badSignature => {}, .input => |input| { allocator.free(input.prompt); }, .redirect => |redir| { allocator.free(redir.target); }, .success => |body| { allocator.free(body.mime); allocator.free(body.data); }, .temporaryFailure, .permanentFailure => |fail| { allocator.free(fail.message); }, .clientCertificateRequired => |cert| { allocator.free(cert.message); }, } } const Content = union(enum) { /// When the server is not known or trusted yet, it just returns a nil value showing that /// the server could be reached, but we don't trust it. untrustedCertificate: void, /// The server responded with a different signature than the one stored in the trust store. badSignature: void, /// Status Code = 1* input: Input, /// Status Code = 2* success: Body, /// Status Code = 3* redirect: Redirect, /// Status Code = 4* temporaryFailure: Failure, /// Status Code = 5* permanentFailure: Failure, /// Status Code = 6* clientCertificateRequired: CertificateAction, }; pub const Input = struct { prompt: []const u8, }; pub const Body = struct { mime: []const u8, data: []const u8, isEndOfClientCertificateSession: bool, }; pub const Redirect = struct { pub const Type = enum { permanent, temporary }; target: []const u8, type: Type, }; pub const Failure = struct { pub const Type = enum { unspecified, serverUnavailable, cgiError, proxyError, slowDown, notFound, gone, proxyRequestRefused, badRequest, }; type: Type, message: []const u8, }; pub const CertificateAction = struct { pub const Type = enum { unspecified, transientCertificateRequested, authorisedCertificateRequired, certificateNotAccepted, futureCertificateRejected, expiredCertificateRejected, }; type: Type, message: []const u8, }; }; pub const ResponseType = @TagType(Response.Content); const empty_trust_anchor_set = ssl.TrustAnchorCollection.init(std.testing.failing_allocator); const RequestOptions = struct { memory_limit: usize = 100 * mega_bytes, verification: RequestVerification, }; const RequestVerification = union(enum) { trust_anchor: ssl.TrustAnchorCollection, public_key: ssl.PublicKey, none: void, }; /// Performs a raw request without any redirection handling or somilar. /// Either errors out when the request is malformed or returns a response from the server. pub fn requestRaw(allocator: *std.mem.Allocator, url: []const u8, options: RequestOptions) !Response { if (url.len > 1024) return error.InvalidUrl; var temp_allocator_buffer: [5000]u8 = undefined; var temp_allocator = std.heap.FixedBufferAllocator.init(&temp_allocator_buffer); const parsed_url = uri.parse(url) catch return error.InvalidUrl; if (parsed_url.scheme == null) return error.InvalidUrl; if (!std.mem.eql(u8, parsed_url.scheme.?, "gemini")) return error.UnsupportedScheme; if (parsed_url.host == null) return error.MissingAuthority; const hostname_z = try std.mem.dupeZ(&temp_allocator.allocator, u8, parsed_url.host.?); var socket = try network.connectToHost(&temp_allocator.allocator, hostname_z, parsed_url.port orelse 1965, .tcp); defer socket.close(); var x509 = switch (options.verification) { .trust_anchor => |list| CertificateValidator.initTrustAnchor(allocator, list), .none => CertificateValidator.initTrustAll(allocator), .public_key => |key| CertificateValidator.initPubKey(allocator, key), }; defer x509.deinit(); var ssl_context = ssl.Client.init(x509.getEngine()); ssl_context.relocate(); try ssl_context.reset(hostname_z, false); // std.debug.warn("ssl initialized.\n", .{}); var tcp_in = socket.inStream(); var tcp_out = socket.outStream(); var ssl_stream = ssl.initStream(ssl_context.getEngine(), &tcp_in, &tcp_out); defer if (ssl_stream.close()) {} else |err| { std.debug.warn("error when closing the stream: {}\n", .{err}); }; const in = ssl_stream.inStream(); const out = ssl_stream.outStream(); var work_buf: [1500]u8 = undefined; const request_str = try std.fmt.bufPrint(&work_buf, "{}\r\n", .{url}); const request_response = out.writeAll(request_str); var response = Response{ .certificate_chain = undefined, .public_key = undefined, .content = undefined, }; response.public_key = try x509.extractPublicKey(allocator); errdefer response.public_key.deinit(); response.certificate_chain = x509.certificates.toOwnedSlice(); for (response.certificate_chain) |cert| { cert.deinit(); } errdefer allocator.free(response.certificate_chain); request_response catch |err| switch (err) { error.X509_NOT_TRUSTED => { response.content = Response.Content{ .untrustedCertificate = {} }; return response; }, error.BAD_SIGNATURE => { response.content = Response.Content{ .badSignature = {} }; return response; }, error.X509_BAD_SERVER_NAME => return error.BadServerName, else => return err, }; try ssl_stream.flush(); const response_header = if (try in.readUntilDelimiterOrEof(&work_buf, '\n')) |buf| buf else return error.InvalidResponse; if (response_header.len < 3) return error.InvalidResponse; if (response_header[response_header.len - 1] != '\r') // not delimited by \r\n return error.InvalidResponse; if (!std.ascii.isDigit(response_header[0])) // not a number return error.InvalidResponse; if (!std.ascii.isDigit(response_header[1])) // not a number return error.InvalidResponse; const meta = std.mem.trim(u8, response_header[2..], " \t\r\n"); if (meta.len > 1024) return error.InvalidResponse; // std.debug.warn("handshake complete: {}\n", .{response}); response.content = switch (response_header[0]) { // primary status code '1' => blk: { // INPUT var prompt = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(prompt); break :blk Response.Content{ .input = Response.Input{ .prompt = prompt, }, }; }, '2' => blk: { // SUCCESS var mime = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(mime); var data = try in.readAllAlloc(allocator, options.memory_limit); break :blk Response.Content{ .success = Response.Body{ .mime = mime, .data = data, .isEndOfClientCertificateSession = (response_header[1] == '1'), // check for 21 }, }; }, '3' => blk: { // REDIRECT var target = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(target); break :blk Response.Content{ .redirect = Response.Redirect{ .target = target, .type = if (response_header[1] == '1') Response.Redirect.Type.permanent else Response.Redirect.Type.temporary, }, }; }, '4' => blk: { // TEMPORARY FAILURE var message = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(message); break :blk Response.Content{ .temporaryFailure = Response.Failure{ .type = switch (response_header[1]) { '1' => Response.Failure.Type.serverUnavailable, '2' => Response.Failure.Type.cgiError, '3' => Response.Failure.Type.proxyError, '4' => Response.Failure.Type.slowDown, else => Response.Failure.Type.unspecified, }, .message = message, }, }; }, '5' => blk: { // PERMANENT FAILURE var message = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(message); break :blk Response.Content{ .permanentFailure = Response.Failure{ .type = switch (response_header[1]) { '1' => Response.Failure.Type.notFound, '2' => Response.Failure.Type.gone, '3' => Response.Failure.Type.proxyRequestRefused, '4' => Response.Failure.Type.badRequest, else => Response.Failure.Type.unspecified, }, .message = message, }, }; }, '6' => blk: { // CLIENT CERTIFICATE REQUIRED var message = try std.mem.dupe(allocator, u8, meta); errdefer allocator.free(message); break :blk Response.Content{ .clientCertificateRequired = Response.CertificateAction{ .type = switch (response_header[1]) { '1' => Response.CertificateAction.Type.transientCertificateRequested, '2' => Response.CertificateAction.Type.authorisedCertificateRequired, '3' => Response.CertificateAction.Type.certificateNotAccepted, '4' => Response.CertificateAction.Type.futureCertificateRejected, '5' => Response.CertificateAction.Type.expiredCertificateRejected, else => Response.CertificateAction.Type.unspecified, }, .message = message, }, }; }, else => return error.UnknownStatusCode, }; return response; } /// Processes redirects and such pub fn request(allocator: *std.mem.Allocator, url: []const u8, options: RequestOptions) !Response { var url_buffer = std.heap.ArenaAllocator.init(allocator); defer url_buffer.deinit(); var next_url = url; var redirection_count: usize = 0; while (redirection_count < 5) : (redirection_count += 1) { var response = try requestRaw(allocator, next_url, options); switch (response.content) { .redirect => |redirection| { std.debug.warn("iteration {} → {}\n", .{ redirection_count, redirection.target, }); next_url = try std.mem.dupe(&url_buffer.allocator, u8, redirection.target); response.free(allocator); }, else => return response, } } return error.TooManyRedirections; } const kibi_bytes = 1024; const mebi_bytes = 1024 * 1024; const gibi_bytes = 1024 * 1024 * 1024; const kilo_bytes = 1000; const mega_bytes = 1000_000; const giga_bytes = 1000_000_000; /// Custom x509 engine that uses the minimal engine and ignores missing trust. /// First step in TOFU direction pub const CertificateValidator = struct { const Self = @This(); const Options = struct { ignore_untrusted: bool = false, ignore_hostname_mismatch: bool = false, }; const class = ssl.c.br_x509_class{ .context_size = @sizeOf(Self), .start_chain = start_chain, .start_cert = start_cert, .append = append, .end_cert = end_cert, .end_chain = end_chain, .get_pkey = get_pkey, }; vtable: [*c]const ssl.c.br_x509_class = &class, x509: union(enum) { minimal: ssl.c.br_x509_minimal_context, known_key: ssl.c.br_x509_knownkey_context, }, allocator: *std.mem.Allocator, certificates: std.ArrayList(ssl.DERCertificate), current_cert_valid: bool = undefined, temp_buffer: FixedGrowBuffer(u8, 2048) = undefined, server_name: ?[]const u8 = null, options: Options = Options{}, fn initTrustAnchor(allocator: *std.mem.Allocator, list: ssl.TrustAnchorCollection) Self { return Self{ .x509 = .{ .minimal = ssl.x509.Minimal.init(list).engine, }, .allocator = allocator, .certificates = std.ArrayList(ssl.DERCertificate).init(allocator), }; } fn initTrustAll(allocator: *std.mem.Allocator) Self { return Self{ .x509 = .{ .minimal = ssl.x509.Minimal.init(empty_trust_anchor_set).engine, }, .allocator = allocator, .certificates = std.ArrayList(ssl.DERCertificate).init(allocator), .options = .{ .ignore_untrusted = true, }, }; } fn initPubKey(allocator: *std.mem.Allocator, key: ssl.PublicKey) Self { return Self{ .x509 = .{ .known_key = ssl.x509.KnownKey.init(key, true, true).engine, }, .allocator = allocator, .certificates = std.ArrayList(ssl.DERCertificate).init(allocator), .options = .{ .ignore_untrusted = true, }, }; } pub fn deinit(self: Self) void { for (self.certificates.items) |cert| { cert.deinit(); } self.certificates.deinit(); if (self.server_name) |name| { self.allocator.free(name); } } pub fn setToKnownKey(self: *Self, key: PublicKey) void { self.x509.x509_known_key = ssl.c.br_x509_knownkey_context{ .vtable = &c.br_x509_knownkey_vtable, .pkey = key.toX509(), .usages = (key.usages orelse 0) | ssl.c.BR_KEYTYPE_KEYX | ssl.c.BR_KEYTYPE_SIGN, // always allow a stored key for key-exchange }; } fn returnTypeOf(comptime Class: type, comptime name: []const u8) type { return @typeInfo(std.meta.Child(std.meta.fieldInfo(Class, name).field_type)).Fn.return_type.?; } fn virtualCall(object: var, comptime name: []const u8, args: var) returnTypeOf(ssl.c.br_x509_class, name) { return @call(.{}, @field(object.vtable.?.*, name).?, .{&object.vtable} ++ args); } fn proxyCall(self: var, comptime name: []const u8, args: var) returnTypeOf(ssl.c.br_x509_class, name) { return switch (self.x509) { .minimal => |*m| virtualCall(m, name, args), .known_key => |*k| virtualCall(k, name, args), }; } fn fromPointer(ctx: var) if (@typeInfo(@TypeOf(ctx)).Pointer.is_const) *const Self else *Self { return if (@typeInfo(@TypeOf(ctx)).Pointer.is_const) return @fieldParentPtr(Self, "vtable", @ptrCast(*const [*c]const ssl.c.br_x509_class, ctx)) else return @fieldParentPtr(Self, "vtable", @ptrCast(*[*c]const ssl.c.br_x509_class, ctx)); } fn start_chain(ctx: [*c][*c]const ssl.c.br_x509_class, server_name: [*c]const u8) callconv(.C) void { const self = fromPointer(ctx); // std.debug.warn("start_chain({0}, {1})\n", .{ // ctx, // std.mem.spanZ(server_name), // }); self.proxyCall("start_chain", .{server_name}); for (self.certificates.items) |cert| { cert.deinit(); } self.certificates.shrink(0); if (self.server_name) |name| { self.allocator.free(name); } self.server_name = null; self.server_name = std.mem.dupe(self.allocator, u8, std.mem.spanZ(server_name)) catch null; } fn start_cert(ctx: [*c][*c]const ssl.c.br_x509_class, length: u32) callconv(.C) void { const self = fromPointer(ctx); // std.debug.warn("start_cert({0}, {1})\n", .{ // ctx, // length, // }); self.proxyCall("start_cert", .{length}); self.temp_buffer = FixedGrowBuffer(u8, 2048).init(); self.current_cert_valid = true; } fn append(ctx: [*c][*c]const ssl.c.br_x509_class, buf: [*c]const u8, len: usize) callconv(.C) void { const self = fromPointer(ctx); // std.debug.warn("append({0}, {1}, {2})\n", .{ // ctx, // buf, // len, // }); self.proxyCall("append", .{ buf, len }); self.temp_buffer.write(buf[0..len]) catch { std.debug.warn("too much memory!\n", .{}); self.current_cert_valid = false; }; } fn end_cert(ctx: [*c][*c]const ssl.c.br_x509_class) callconv(.C) void { const self = fromPointer(ctx); // std.debug.warn("end_cert({})\n", .{ // ctx, // }); self.proxyCall("end_cert", .{}); if (self.current_cert_valid) { const cert = ssl.DERCertificate{ .allocator = self.allocator, .data = std.mem.dupe(self.allocator, u8, self.temp_buffer.constSpan()) catch return, // sad, but no other choise }; errdefer cert.deinit(); self.certificates.append(cert) catch return; } } fn end_chain(ctx: [*c][*c]const ssl.c.br_x509_class) callconv(.C) c_uint { const self = fromPointer(ctx); const err = self.proxyCall("end_chain", .{}); // std.debug.warn("end_chain({}) → {}\n", .{ // ctx, // err, // }); // std.debug.warn("Received {} certificates for {}!\n", .{ // self.certificates.items.len, // self.server_name, // }); // Patch the error code and just accept in case of ignoring this error. if (err == ssl.c.BR_ERR_X509_NOT_TRUSTED and self.options.ignore_untrusted) { return 0; } // Patch the error code and just accept in case of ignoring this error. if (err == ssl.c.BR_ERR_X509_BAD_SERVER_NAME and self.options.ignore_hostname_mismatch) { return 0; } return err; } fn get_pkey(ctx: [*c]const [*c]const ssl.c.br_x509_class, usages: [*c]c_uint) callconv(.C) [*c]const ssl.c.br_x509_pkey { const self = fromPointer(ctx); const pkey = self.proxyCall("get_pkey", .{usages}); // std.debug.warn("get_pkey({}, {}) → {}\n", .{ // ctx, // usages, // pkey, // }); return pkey; } fn saveCertificates(self: Self, folder: []const u8) !void { var trust_store_dir = try std.fs.cwd().openDir("trust-store", .{ .access_sub_paths = true, .iterate = false }); defer trust_store_dir.close(); trust_store_dir.makeDir(folder) catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; var server_dir = try trust_store_dir.openDir(folder, .{ .access_sub_paths = true, .iterate = false }); defer server_dir.close(); for (self.certificates.items) |cert, index| { var name_buf: [64]u8 = undefined; var name = try std.fmt.bufPrint(&name_buf, "cert-{}.der", .{index}); var file = try server_dir.createFile(name, .{ .exclusive = false }); defer file.close(); try file.writeAll(cert.data); } } pub fn extractPublicKey(self: Self, allocator: *std.mem.Allocator) !ssl.PublicKey { var usages: c_uint = 0; const pkey = self.proxyCall("get_pkey", .{usages}); std.debug.assert(pkey != null); var key = try ssl.PublicKey.fromX509(allocator, pkey.*); key.usages = usages; return key; } fn getEngine(self: *Self) *[*c]const ssl.c.br_x509_class { return &self.vtable; } }; fn FixedGrowBuffer(comptime T: type, comptime max_len: usize) type { return struct { const Self = @This(); offset: usize, buffer: [max_len]T, pub fn init() Self { return Self{ .offset = 0, .buffer = undefined, }; } pub fn reset(self: *Self) void { self.offset = 0; } pub fn write(self: *Self, data: []const T) error{OutOfMemory}!void { if (self.offset + data.len > self.buffer.len) return error.OutOfMemory; std.mem.copy(T, self.buffer[self.offset..], data); self.offset += data.len; } pub fn span(self: *Self) []T { return self.buffer[0..self.offset]; } pub fn constSpan(self: *Self) []const T { return self.buffer[0..self.offset]; } }; } // tests test "loading system certs" { var file = try std.fs.cwd().openFile("/etc/ssl/cert.pem", .{ .read = true, .write = false }); defer file.close(); const pem_text = try file.inStream().readAllAlloc(std.testing.allocator, 1 << 20); // 1 MB defer std.testing.allocator.free(pem_text); var trust_anchors = ssl.TrustAnchorCollection.init(std.testing.allocator); defer trust_anchors.deinit(); try trust_anchors.appendFromPEM(pem_text); } const TestExpection = union(enum) { response: ResponseType, err: anyerror, }; fn runRawTestRequest(url: []const u8, expected_response: TestExpection) !void { if (requestRaw(std.testing.allocator, url, .{ .verification = .none, })) |response| { defer response.free(std.testing.allocator); if (expected_response != .response) { std.debug.warn("Expected error, but got {}\n", .{@as(ResponseType, response.content)}); return error.UnexpectedResponse; } if (response.content != expected_response.response) { std.debug.warn("Expected {}, but got {}\n", .{ expected_response.response, @as(ResponseType, response.content) }); return error.UnexpectedResponse; } } else |err| { if (expected_response != .err) { std.debug.warn("Expected {}, but got error {}\n", .{ expected_response.response, err }); return error.UnexpectedResponse; } if (err != expected_response.err) { std.debug.warn("Expected error {}, but got error {}\n", .{ expected_response.err, err }); return error.UnexpectedResponse; } } } fn runTestRequest(url: []const u8, expected_response: TestExpection) !void { if (request(std.testing.allocator, url, .{ .verification = .none, })) |response| { defer response.free(std.testing.allocator); if (expected_response != .response) { std.debug.warn("Expected error, but got {}\n", .{@as(ResponseType, response.content)}); return error.UnexpectedResponse; } if (response.content != expected_response.response) { std.debug.warn("Expected {}, but got {}\n", .{ expected_response.response, @as(ResponseType, response.content) }); return error.UnexpectedResponse; } } else |err| { if (expected_response != .err) { std.debug.warn("Expected {}, but got error {}\n", .{ expected_response.response, err }); return error.UnexpectedResponse; } if (err != expected_response.err) { std.debug.warn("Expected error {}, but got error {}\n", .{ expected_response.err, err }); return error.UnexpectedResponse; } } } // Test some API invariants: test "invalid url scheme" { if (requestRaw(std.testing.allocator, "madeup+uri://lolwat/wellheck", RequestOptions{ .verification = .none, })) |val| { val.free(std.testing.allocator); } else |err| { switch (err) { error.UnsupportedScheme => return, // this is actually the success vector! else => return err, } } } // Test several different responses test "10 INPUT: query gus" { try runRawTestRequest("gemini://gus.guru/search", .{ .response = .input }); } test "51 PERMANENT FAILURE: query mozz.us" { try runRawTestRequest("gemini://mozz.us/topkek", .{ .response = .permanentFailure }); } // Run test suite against conmans torture suit // Index page test "torture suite/raw (0000)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0000", .{ .response = .success }); } // Redirect-continous temporary redirects test "torture suite/raw (0022)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell/", .{ .response = .redirect }); } // Redirect-continous permanent redirects test "torture suite/raw (0023)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell2/", .{ .response = .redirect }); } // Redirect-continous random temporary or permanent redirects test "torture suite/raw (0024)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell3/", .{ .response = .redirect }); } // Redirect-continous temporary redirects to itself test "torture suite/raw (0025)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell4", .{ .response = .redirect }); } // Redirect-continous permanent redirects to itself test "torture suite/raw (0026)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell5", .{ .response = .redirect }); } // Redirect-to a non-gemini link test "torture suite/raw (0027)" { try runRawTestRequest("gemini://gemini.conman.org/test/redirhell6", .{ .response = .redirect }); } // Status-undefined status code test "torture suite/raw (0034)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0034a", .{ .err = error.UnknownStatusCode }); } // Status-undefined success status code test "torture suite/raw (0035)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0035a", .{ .response = .success }); } // Status-undefined redirect status code test "torture suite/raw (0036)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0036a", .{ .response = .redirect }); } // Status-undefined temporary status code test "torture suite/raw (0037)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0037a", .{ .response = .temporaryFailure }); } // Status-undefined permanent status code test "torture suite/raw (0038)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0038a", .{ .response = .permanentFailure }); } // Status-one digit status code test "torture suite/raw (0039)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0039a", .{ .err = error.InvalidResponse }); } // Status-complete blank line test "torture suite/raw (0040)" { try runRawTestRequest("gemini://gemini.conman.org/test/torture/0040a", .{ .err = error.InvalidResponse }); } // Run test suite against conmans torture suit // Index page test "torture suite (0000)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0000", .{ .response = .success }); } // Redirect-continous temporary redirects test "torture suite (0022)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell/", .{ .err = error.TooManyRedirections }); } // Redirect-continous permanent redirects test "torture suite (0023)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell2/", .{ .err = error.TooManyRedirections }); } // Redirect-continous random temporary or permanent redirects test "torture suite (0024)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell3/", .{ .err = error.TooManyRedirections }); } // Redirect-continous temporary redirects to itself test "torture suite (0025)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell4", .{ .err = error.TooManyRedirections }); } // Redirect-continous permanent redirects to itself test "torture suite (0026)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell5", .{ .err = error.TooManyRedirections }); } // Redirect-to a non-gemini link test "torture suite (0027)" { try runTestRequest("gemini://gemini.conman.org/test/redirhell6", .{ .err = error.UnsupportedScheme }); } // Status-undefined status code test "torture suite (0034)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0034a", .{ .err = error.UnknownStatusCode }); } // Status-undefined success status code test "torture suite (0035)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0035a", .{ .response = .success }); } // Status-undefined redirect status code test "torture suite (0036)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0036a", .{ .response = .success }); } // Status-undefined temporary status code test "torture suite (0037)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0037a", .{ .response = .temporaryFailure }); } // Status-undefined permanent status code test "torture suite (0038)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0038a", .{ .response = .permanentFailure }); } // Status-one digit status code test "torture suite (0039)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0039a", .{ .err = error.InvalidResponse }); } // Status-complete blank line test "torture suite (0040)" { try runTestRequest("gemini://gemini.conman.org/test/torture/0040a", .{ .err = error.InvalidResponse }); }
src/main.zig
const std = @import("std"); const root = @import("root"); const builtin = @import("builtin"); pub const KnownFolder = enum { home, documents, pictures, music, videos, desktop, downloads, public, fonts, app_menu, cache, roaming_configuration, local_configuration, global_configuration, data, runtime, executable_dir, }; // Explicitly define possible errors to make it clearer what callers need to handle pub const Error = error{ ParseError, OutOfMemory }; pub const KnownFolderConfig = struct { xdg_on_mac: bool = false, }; /// Returns a directory handle, or, if the folder does not exist, `null`. pub fn open(allocator: std.mem.Allocator, folder: KnownFolder, args: std.fs.Dir.OpenDirOptions) (std.fs.Dir.OpenError || Error)!?std.fs.Dir { var path_or_null = try getPath(allocator, folder); if (path_or_null) |path| { defer allocator.free(path); return try std.fs.cwd().openDir(path, args); } else { return null; } } /// Returns the path to the folder or, if the folder does not exist, `null`. pub fn getPath(allocator: std.mem.Allocator, folder: KnownFolder) Error!?[]const u8 { if (folder == .executable_dir) { return std.fs.selfExeDirPathAlloc(allocator) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => null, }; } // used for temporary allocations var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); switch (builtin.os.tag) { .windows => { const folder_spec = windows_folder_spec.get(folder); switch (folder_spec) { .by_guid => |guid| { var dir_path_ptr: [*:0]u16 = undefined; switch (std.os.windows.shell32.SHGetKnownFolderPath( &guid, std.os.windows.KF_FLAG_CREATE, // TODO: Chose sane option here? null, &dir_path_ptr, )) { std.os.windows.S_OK => { defer std.os.windows.ole32.CoTaskMemFree(@ptrCast(*anyopaque, dir_path_ptr)); const global_dir = std.unicode.utf16leToUtf8Alloc(allocator, std.mem.sliceTo(dir_path_ptr, 0)) catch |err| switch (err) { error.UnexpectedSecondSurrogateHalf => return null, error.ExpectedSecondSurrogateHalf => return null, error.DanglingSurrogateHalf => return null, error.OutOfMemory => return error.OutOfMemory, }; return global_dir; }, std.os.windows.E_OUTOFMEMORY => return error.OutOfMemory, else => return null, } }, .by_env => |env_path| { if (env_path.subdir) |sub_dir| { const root_path = std.process.getEnvVarOwned(arena.allocator(), env_path.env_var) catch |err| switch (err) { error.EnvironmentVariableNotFound => return null, error.InvalidUtf8 => return null, error.OutOfMemory => |e| return e, }; return try std.fs.path.join(allocator, &[_][]const u8{ root_path, sub_dir }); } else { return std.process.getEnvVarOwned(allocator, env_path.env_var) catch |err| switch (err) { error.EnvironmentVariableNotFound => return null, error.InvalidUtf8 => return null, error.OutOfMemory => |e| return e, }; } }, } }, .macos => { if (@hasDecl(root, "known_folders_config") and root.known_folders_config.xdg_on_mac) { return getPathXdg(allocator, &arena, folder); } switch (mac_folder_spec.get(folder)) { .absolute => |abs| { return try allocator.dupe(u8, abs); }, .suffix => |s| { const home_dir = if (std.os.getenv("HOME")) |home| home else return null; if (s) |suffix| { return try std.fs.path.join(allocator, &[_][]const u8{ home_dir, suffix }); } else { return try allocator.dupe(u8, home_dir); } }, } }, // Assume unix derivatives with XDG else => { return getPathXdg(allocator, &arena, folder); }, } unreachable; } fn getPathXdg(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, folder: KnownFolder) Error!?[]const u8 { const folder_spec = xdg_folder_spec.get(folder); var env_opt = std.os.getenv(folder_spec.env.name); // TODO: add caching so we only need to read once in a run if (env_opt == null and folder_spec.env.user_dir) block: { const config_dir_path = getPathXdg(arena.allocator(), arena, .local_configuration) catch null orelse break :block; const config_dir = std.fs.cwd().openDir(config_dir_path, .{}) catch break :block; const home = std.os.getenv("HOME") orelse break :block; const user_dirs = config_dir.openFile("user-dirs.dirs", .{}) catch null orelse break :block; var read: [1024 * 8]u8 = undefined; _ = user_dirs.readAll(&read) catch null orelse break :block; const start = folder_spec.env.name.len + "=\"$HOME".len; var line_it = std.mem.split(&read, "\n"); while (line_it.next()) |line| { if (std.mem.startsWith(u8, line, folder_spec.env.name)) { const end = line.len - 1; if (start >= end) { return error.ParseError; } var subdir = line[start..end]; env_opt = try std.mem.concat(arena.allocator(), u8, &[_][]const u8{ home, subdir }); break; } } } if (env_opt) |env| { if (folder_spec.env.suffix) |suffix| { return try std.mem.concat(allocator, u8, &[_][]const u8{ env, suffix }); } else { return try allocator.dupe(u8, env); } } else { const default = folder_spec.default orelse return null; if (default[0] == '~') { const home = std.os.getenv("HOME") orelse return null; return try std.mem.concat(allocator, u8, &[_][]const u8{ home, default[1..] }); } else { return try allocator.dupe(u8, default); } } } /// Contains the GUIDs for each available known-folder on windows const WindowsFolderSpec = union(enum) { by_guid: std.os.windows.GUID, by_env: struct { env_var: []const u8, subdir: ?[]const u8, }, }; /// Contains the xdg environment variable amd the default value for each available known-folder on windows const XdgFolderSpec = struct { env: struct { name: []const u8, user_dir: bool, suffix: ?[]const u8, }, default: ?[]const u8, }; /// Contains the folder items for macOS const MacFolderSpec = union(enum) { suffix: ?[]const u8, absolute: []const u8, }; /// This returns a struct type with one field per KnownFolder of type `T`. /// used for storing different config data per field fn KnownFolderSpec(comptime T: type) type { return struct { const Self = @This(); home: T, documents: T, pictures: T, music: T, videos: T, desktop: T, downloads: T, public: T, fonts: T, app_menu: T, cache: T, roaming_configuration: T, local_configuration: T, global_configuration: T, data: T, runtime: T, fn get(self: Self, folder: KnownFolder) T { inline for (std.meta.fields(Self)) |fld| { if (folder == @field(KnownFolder, fld.name)) return @field(self, fld.name); } unreachable; } }; } /// Stores how to find each known folder on windows. const windows_folder_spec = blk: { // workaround for zig eval branch quota when parsing the GUIDs @setEvalBranchQuota(10_000); break :blk KnownFolderSpec(WindowsFolderSpec){ .home = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{5E6C858F-0E22-4760-9AFE-EA3317B67173}") }, // FOLDERID_Profile .documents = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{FDD39AD0-238F-46AF-ADB4-6C85480369C7}") }, // FOLDERID_Documents .pictures = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{33E28130-4E1E-4676-835A-98395C3BC3BB}") }, // FOLDERID_Pictures .music = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{4BD8D571-6D19-48D3-BE97-422220080E43}") }, // FOLDERID_Music .videos = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{18989B1D-99B5-455B-841C-AB7C74E4DDFC}") }, // FOLDERID_Videos .desktop = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}") }, // FOLDERID_Desktop .downloads = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{374DE290-123F-4565-9164-39C4925E467B}") }, // FOLDERID_Downloads .public = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{DFDF76A2-C82A-4D63-906A-5644AC457385}") }, // FOLDERID_Public .fonts = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}") }, // FOLDERID_Fonts .app_menu = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}") }, // FOLDERID_StartMenu .cache = WindowsFolderSpec{ .by_env = .{ .env_var = "LOCALAPPDATA", .subdir = "Temp" } }, // %LOCALAPPDATA%\Temp .roaming_configuration = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}") }, // FOLDERID_RoamingAppData .local_configuration = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}") }, // FOLDERID_LocalAppData .global_configuration = WindowsFolderSpec{ .by_guid = std.os.windows.GUID.parse("{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}") }, // FOLDERID_ProgramData .data = WindowsFolderSpec{ .by_env = .{ .env_var = "APPDATA", .subdir = null } }, // %LOCALAPPDATA%\Temp .runtime = WindowsFolderSpec{ .by_env = .{ .env_var = "LOCALAPPDATA", .subdir = "Temp" } }, }; }; /// Stores how to find each known folder in xdg. const xdg_folder_spec = KnownFolderSpec(XdgFolderSpec){ .home = XdgFolderSpec{ .env = .{ .name = "HOME", .user_dir = false, .suffix = null }, .default = null }, .documents = XdgFolderSpec{ .env = .{ .name = "XDG_DOCUMENTS_DIR", .user_dir = true, .suffix = null }, .default = "~/Documents" }, .pictures = XdgFolderSpec{ .env = .{ .name = "XDG_PICTURES_DIR", .user_dir = true, .suffix = null }, .default = "~/Pictures" }, .music = XdgFolderSpec{ .env = .{ .name = "XDG_MUSIC_DIR", .user_dir = true, .suffix = null }, .default = "~/Music" }, .videos = XdgFolderSpec{ .env = .{ .name = "XDG_VIDEOS_DIR", .user_dir = true, .suffix = null }, .default = "~/Videos" }, .desktop = XdgFolderSpec{ .env = .{ .name = "XDG_DESKTOP_DIR", .user_dir = true, .suffix = null }, .default = "~/Desktop" }, .downloads = XdgFolderSpec{ .env = .{ .name = "XDG_DOWNLOAD_DIR", .user_dir = true, .suffix = null }, .default = "~/Downloads" }, .public = XdgFolderSpec{ .env = .{ .name = "XDG_PUBLICSHARE_DIR", .user_dir = true, .suffix = null }, .default = "~/Public" }, .fonts = XdgFolderSpec{ .env = .{ .name = "XDG_DATA_HOME", .user_dir = false, .suffix = "/fonts" }, .default = "~/.local/share/fonts" }, .app_menu = XdgFolderSpec{ .env = .{ .name = "XDG_DATA_HOME", .user_dir = false, .suffix = "/applications" }, .default = "~/.local/share/applications" }, .cache = XdgFolderSpec{ .env = .{ .name = "XDG_CACHE_HOME", .user_dir = false, .suffix = null }, .default = "~/.cache" }, .roaming_configuration = XdgFolderSpec{ .env = .{ .name = "XDG_CONFIG_HOME", .user_dir = false, .suffix = null }, .default = "~/.config" }, .local_configuration = XdgFolderSpec{ .env = .{ .name = "XDG_CONFIG_HOME", .user_dir = false, .suffix = null }, .default = "~/.config" }, .global_configuration = XdgFolderSpec{ .env = .{ .name = "XDG_CONFIG_DIRS", .user_dir = false, .suffix = null }, .default = "/etc" }, .data = XdgFolderSpec{ .env = .{ .name = "XDG_DATA_HOME", .user_dir = false, .suffix = null }, .default = "~/.local/share" }, .runtime = XdgFolderSpec{ .env = .{ .name = "XDG_RUNTIME_DIR", .user_dir = false, .suffix = null }, .default = null }, }; const mac_folder_spec = KnownFolderSpec(MacFolderSpec){ .home = MacFolderSpec{ .suffix = null }, .documents = MacFolderSpec{ .suffix = "Documents" }, .pictures = MacFolderSpec{ .suffix = "Pictures" }, .music = MacFolderSpec{ .suffix = "Music" }, .videos = MacFolderSpec{ .suffix = "Movies" }, .desktop = MacFolderSpec{ .suffix = "Desktop" }, .downloads = MacFolderSpec{ .suffix = "Downloads" }, .public = MacFolderSpec{ .suffix = "Public" }, .fonts = MacFolderSpec{ .suffix = "Library/Fonts" }, .app_menu = MacFolderSpec{ .suffix = "Applications" }, .cache = MacFolderSpec{ .suffix = "Library/Caches" }, .roaming_configuration = MacFolderSpec{ .suffix = "Library/Preferences" }, .local_configuration = MacFolderSpec{ .suffix = "Library/Application Support" }, .global_configuration = MacFolderSpec{ .absolute = "/Library/Preferences" }, .data = MacFolderSpec{ .suffix = "Library/Application Support" }, .runtime = MacFolderSpec{ .suffix = "Library/Application Support" }, }; // Ref decls comptime { _ = KnownFolder; _ = Error; _ = open; _ = getPath; } test "query each known folders" { inline for (std.meta.fields(KnownFolder)) |fld| { var path_or_null = try getPath(std.testing.allocator, @field(KnownFolder, fld.name)); if (path_or_null) |path| { // TODO: Remove later std.debug.print("{s} => '{s}'\n", .{ fld.name, path }); std.testing.allocator.free(path); } } } test "open each known folders" { inline for (std.meta.fields(KnownFolder)) |fld| { var dir_or_null = open(std.testing.allocator, @field(KnownFolder, fld.name), .{ .iterate = false, .access_sub_paths = true }) catch |e| switch (e) { error.FileNotFound => return, else => return e, }; if (dir_or_null) |*dir| { dir.close(); } } }
src/pkg/known_folders.zig
const std = @import("std"); const utils = @import("utils"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const print = utils.print; const Instruction = union(enum) { Forward: i32, Down: i32, Up: i32 }; pub fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror![]Instruction { var allocator = &arena.allocator; var numbers = try std.ArrayList(Instruction).initCapacity(allocator, 4096); while (lines_it.next()) |line| { var line_it = std.mem.split(u8, line, " "); const dir = line_it.next() orelse unreachable; const dist = line_it.next() orelse unreachable; const dist_num = try std.fmt.parseInt(i32, dist, 10); const inst = if (std.mem.eql(u8, dir, "forward")) Instruction{ .Forward = dist_num } else if (std.mem.eql(u8, dir, "down")) Instruction{ .Down = dist_num } else if (std.mem.eql(u8, dir, "up")) Instruction{ .Up = dist_num } else unreachable; try numbers.append(inst); } print("File ok :) Number of inputs: {d}", .{numbers.items.len}); return numbers.items; } pub fn part1(instructions: []Instruction) i32 { var i: usize = 0; var horizontal: i32 = 0; var depth: i32 = 0; while (i < instructions.len) : (i += 1) { switch (instructions[i]) { .Forward => |dist| { horizontal += dist; }, .Down => |dist| { depth += dist; }, .Up => |dist| { depth -= dist; }, } } return horizontal * depth; } pub fn part2(instructions: []Instruction) i64 { var i: usize = 0; var horizontal: i64 = 0; var depth: i64 = 0; var aim: i64 = 0; while (i < instructions.len) : (i += 1) { switch (instructions[i]) { .Forward => |dist| { horizontal += dist; depth += aim * dist; }, .Down => |dist| { aim += dist; }, .Up => |dist| { aim -= dist; }, } } return horizontal * depth; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt"); defer lines_it.deinit(); const input = try readInput(&arena, &lines_it); const part1_result = part1(input); print("Part 1: {d}", .{part1_result}); const part2_result = part2(input); print("Part 2: {d}", .{part2_result}); }
day2/src/main.zig
const std = @import("std"); const Sha1 = std.crypto.hash.Sha1; const opt = @import("opt.zig"); const Allocator = std.mem.Allocator; const stdout = &std.io.getStdOut().writer(); const warn = std.debug.warn; const BUFSIZ = 4096; pub fn sha1(allocator: *Allocator, file: std.fs.File) ![40]u8 { var h = Sha1.init(.{}); var hash: [20]u8 = undefined; var real_out: [40]u8 = undefined; var file_buffer = std.ArrayList(u8).init(allocator); defer file_buffer.deinit(); var read_buffer: [BUFSIZ]u8 = undefined; var size = try file.readAll(&read_buffer); while (size > 0) : (size = try file.readAll(&read_buffer)) { try file_buffer.insertSlice(file_buffer.items.len, read_buffer[0..size]); } h.update(file_buffer.items[0..]); h.final(hash[0..]); var i: u8 = 0; while (i < 20) : (i += 1) { if (hash[i] <= 15) { _ = try std.fmt.bufPrint(real_out[i * 2 ..], "0{x}", .{hash[i]}); } else { _ = try std.fmt.bufPrint(real_out[i * 2 ..], "{x}", .{hash[i]}); } } return real_out; } const Sha1Flags = enum { Help, Version, }; var flags = [_]opt.Flag(Sha1Flags){ .{ .name = Sha1Flags.Help, .long = "help", }, .{ .name = Sha1Flags.Version, .long = "version", }, }; pub fn main(args: [][]u8) anyerror!u8 { var it = opt.FlagIterator(Sha1Flags).init(flags[0..], args); while (it.next_flag() catch { return 1; }) |flag| { switch (flag.name) { Sha1Flags.Help => { warn("sha1 [FILE_NAME ..]\n", .{}); return 1; }, Sha1Flags.Version => { warn("(version info here)\n", .{}); return 1; }, } } var files = std.ArrayList([]u8).init(std.heap.page_allocator); while (it.next_arg()) |file_name| { try files.append(file_name); } if (files.items.len > 0) { for (files.items) |file_name| { const file = std.fs.cwd().openFile(file_name[0..], std.fs.File.OpenFlags{ .read = true, .write = false }) catch |err| { try stdout.print("Error: cannot open file {s}\n", .{file_name}); return 1; }; // run command var result = sha1(std.heap.page_allocator, file) catch |err| { try stdout.print("Error: {}\n", .{err}); return 1; }; try stdout.print("{s}\n", .{result}); file.close(); } } else { var result = sha1(std.heap.page_allocator, std.io.getStdIn()) catch |err| { try stdout.print("Error: {}\n", .{err}); return 1; }; try stdout.print("{s}\n", .{result}); } return 0; } test "hash on license" { var file = try std.fs.cwd().openFile("LICENSE", std.fs.File.OpenFlags{ .read = true }); var result = try sha1(std.heap.page_allocator, file); std.debug.assert(std.mem.eql(u8, result[0..], "2b5c4a97ba0ed7175825ab99052952111ddcd1db")); }
src/sha1.zig
const std = @import("../../index.zig"); const assert = std.debug.assert; const builtin = @import("builtin"); const vdso = @import("vdso.zig"); pub use switch (builtin.arch) { builtin.Arch.x86_64 => @import("x86_64.zig"), builtin.Arch.i386 => @import("i386.zig"), else => @compileError("unsupported arch"), }; pub use @import("errno.zig"); pub const PATH_MAX = 4096; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const FUTEX_WAIT = 0; pub const FUTEX_WAKE = 1; pub const FUTEX_FD = 2; pub const FUTEX_REQUEUE = 3; pub const FUTEX_CMP_REQUEUE = 4; pub const FUTEX_WAKE_OP = 5; pub const FUTEX_LOCK_PI = 6; pub const FUTEX_UNLOCK_PI = 7; pub const FUTEX_TRYLOCK_PI = 8; pub const FUTEX_WAIT_BITSET = 9; pub const FUTEX_PRIVATE_FLAG = 128; pub const FUTEX_CLOCK_REALTIME = 256; pub const PROT_NONE = 0; pub const PROT_READ = 1; pub const PROT_WRITE = 2; pub const PROT_EXEC = 4; pub const PROT_GROWSDOWN = 0x01000000; pub const PROT_GROWSUP = 0x02000000; pub const MAP_FAILED = @maxValue(usize); pub const MAP_SHARED = 0x01; pub const MAP_PRIVATE = 0x02; pub const MAP_TYPE = 0x0f; pub const MAP_FIXED = 0x10; pub const MAP_ANONYMOUS = 0x20; pub const MAP_NORESERVE = 0x4000; pub const MAP_GROWSDOWN = 0x0100; pub const MAP_DENYWRITE = 0x0800; pub const MAP_EXECUTABLE = 0x1000; pub const MAP_LOCKED = 0x2000; pub const MAP_POPULATE = 0x8000; pub const MAP_NONBLOCK = 0x10000; pub const MAP_STACK = 0x20000; pub const MAP_HUGETLB = 0x40000; pub const MAP_FILE = 0; pub const F_OK = 0; pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; pub const WNOHANG = 1; pub const WUNTRACED = 2; pub const WSTOPPED = 2; pub const WEXITED = 4; pub const WCONTINUED = 8; pub const WNOWAIT = 0x1000000; pub const SA_NOCLDSTOP = 1; pub const SA_NOCLDWAIT = 2; pub const SA_SIGINFO = 4; pub const SA_ONSTACK = 0x08000000; pub const SA_RESTART = 0x10000000; pub const SA_NODEFER = 0x40000000; pub const SA_RESETHAND = 0x80000000; pub const SA_RESTORER = 0x04000000; 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 SIGBUS = 7; pub const SIGFPE = 8; pub const SIGKILL = 9; pub const SIGUSR1 = 10; pub const SIGSEGV = 11; pub const SIGUSR2 = 12; pub const SIGPIPE = 13; pub const SIGALRM = 14; pub const SIGTERM = 15; pub const SIGSTKFLT = 16; pub const SIGCHLD = 17; pub const SIGCONT = 18; pub const SIGSTOP = 19; pub const SIGTSTP = 20; pub const SIGTTIN = 21; pub const SIGTTOU = 22; pub const SIGURG = 23; pub const SIGXCPU = 24; pub const SIGXFSZ = 25; pub const SIGVTALRM = 26; pub const SIGPROF = 27; pub const SIGWINCH = 28; pub const SIGIO = 29; pub const SIGPOLL = 29; pub const SIGPWR = 30; pub const SIGSYS = 31; pub const SIGUNUSED = SIGSYS; pub const O_RDONLY = 0o0; pub const O_WRONLY = 0o1; pub const O_RDWR = 0o2; pub const SEEK_SET = 0; pub const SEEK_CUR = 1; pub const SEEK_END = 2; pub const SIG_BLOCK = 0; pub const SIG_UNBLOCK = 1; pub const SIG_SETMASK = 2; pub const PROTO_ip = 0o000; pub const PROTO_icmp = 0o001; pub const PROTO_igmp = 0o002; pub const PROTO_ggp = 0o003; pub const PROTO_ipencap = 0o004; pub const PROTO_st = 0o005; pub const PROTO_tcp = 0o006; pub const PROTO_egp = 0o010; pub const PROTO_pup = 0o014; pub const PROTO_udp = 0o021; pub const PROTO_hmp = 0o024; pub const PROTO_xns_idp = 0o026; pub const PROTO_rdp = 0o033; pub const PROTO_iso_tp4 = 0o035; pub const PROTO_xtp = 0o044; pub const PROTO_ddp = 0o045; pub const PROTO_idpr_cmtp = 0o046; pub const PROTO_ipv6 = 0o051; pub const PROTO_ipv6_route = 0o053; pub const PROTO_ipv6_frag = 0o054; pub const PROTO_idrp = 0o055; pub const PROTO_rsvp = 0o056; pub const PROTO_gre = 0o057; pub const PROTO_esp = 0o062; pub const PROTO_ah = 0o063; pub const PROTO_skip = 0o071; pub const PROTO_ipv6_icmp = 0o072; pub const PROTO_ipv6_nonxt = 0o073; pub const PROTO_ipv6_opts = 0o074; pub const PROTO_rspf = 0o111; pub const PROTO_vmtp = 0o121; pub const PROTO_ospf = 0o131; pub const PROTO_ipip = 0o136; pub const PROTO_encap = 0o142; pub const PROTO_pim = 0o147; pub const PROTO_raw = 0o377; pub const SHUT_RD = 0; pub const SHUT_WR = 1; pub const SHUT_RDWR = 2; 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_DCCP = 6; pub const SOCK_PACKET = 10; pub const SOCK_CLOEXEC = 0o2000000; pub const SOCK_NONBLOCK = 0o4000; pub const PF_UNSPEC = 0; pub const PF_LOCAL = 1; pub const PF_UNIX = PF_LOCAL; pub const PF_FILE = PF_LOCAL; pub const PF_INET = 2; pub const PF_AX25 = 3; pub const PF_IPX = 4; pub const PF_APPLETALK = 5; pub const PF_NETROM = 6; pub const PF_BRIDGE = 7; pub const PF_ATMPVC = 8; pub const PF_X25 = 9; pub const PF_INET6 = 10; pub const PF_ROSE = 11; pub const PF_DECnet = 12; pub const PF_NETBEUI = 13; pub const PF_SECURITY = 14; pub const PF_KEY = 15; pub const PF_NETLINK = 16; pub const PF_ROUTE = PF_NETLINK; pub const PF_PACKET = 17; pub const PF_ASH = 18; pub const PF_ECONET = 19; pub const PF_ATMSVC = 20; pub const PF_RDS = 21; pub const PF_SNA = 22; pub const PF_IRDA = 23; pub const PF_PPPOX = 24; pub const PF_WANPIPE = 25; pub const PF_LLC = 26; pub const PF_IB = 27; pub const PF_MPLS = 28; pub const PF_CAN = 29; pub const PF_TIPC = 30; pub const PF_BLUETOOTH = 31; pub const PF_IUCV = 32; pub const PF_RXRPC = 33; pub const PF_ISDN = 34; pub const PF_PHONET = 35; pub const PF_IEEE802154 = 36; pub const PF_CAIF = 37; pub const PF_ALG = 38; pub const PF_NFC = 39; pub const PF_VSOCK = 40; pub const PF_KCM = 41; pub const PF_QIPCRTR = 42; pub const PF_SMC = 43; pub const PF_MAX = 44; pub const AF_UNSPEC = PF_UNSPEC; pub const AF_LOCAL = PF_LOCAL; pub const AF_UNIX = AF_LOCAL; pub const AF_FILE = AF_LOCAL; pub const AF_INET = PF_INET; pub const AF_AX25 = PF_AX25; pub const AF_IPX = PF_IPX; pub const AF_APPLETALK = PF_APPLETALK; pub const AF_NETROM = PF_NETROM; pub const AF_BRIDGE = PF_BRIDGE; pub const AF_ATMPVC = PF_ATMPVC; pub const AF_X25 = PF_X25; pub const AF_INET6 = PF_INET6; pub const AF_ROSE = PF_ROSE; pub const AF_DECnet = PF_DECnet; pub const AF_NETBEUI = PF_NETBEUI; pub const AF_SECURITY = PF_SECURITY; pub const AF_KEY = PF_KEY; pub const AF_NETLINK = PF_NETLINK; pub const AF_ROUTE = PF_ROUTE; pub const AF_PACKET = PF_PACKET; pub const AF_ASH = PF_ASH; pub const AF_ECONET = PF_ECONET; pub const AF_ATMSVC = PF_ATMSVC; pub const AF_RDS = PF_RDS; pub const AF_SNA = PF_SNA; pub const AF_IRDA = PF_IRDA; pub const AF_PPPOX = PF_PPPOX; pub const AF_WANPIPE = PF_WANPIPE; pub const AF_LLC = PF_LLC; pub const AF_IB = PF_IB; pub const AF_MPLS = PF_MPLS; pub const AF_CAN = PF_CAN; pub const AF_TIPC = PF_TIPC; pub const AF_BLUETOOTH = PF_BLUETOOTH; pub const AF_IUCV = PF_IUCV; pub const AF_RXRPC = PF_RXRPC; pub const AF_ISDN = PF_ISDN; pub const AF_PHONET = PF_PHONET; pub const AF_IEEE802154 = PF_IEEE802154; pub const AF_CAIF = PF_CAIF; pub const AF_ALG = PF_ALG; pub const AF_NFC = PF_NFC; pub const AF_VSOCK = PF_VSOCK; pub const AF_KCM = PF_KCM; pub const AF_QIPCRTR = PF_QIPCRTR; pub const AF_SMC = PF_SMC; pub const AF_MAX = PF_MAX; pub const SO_DEBUG = 1; pub const SO_REUSEADDR = 2; pub const SO_TYPE = 3; pub const SO_ERROR = 4; pub const SO_DONTROUTE = 5; pub const SO_BROADCAST = 6; pub const SO_SNDBUF = 7; pub const SO_RCVBUF = 8; pub const SO_KEEPALIVE = 9; pub const SO_OOBINLINE = 10; pub const SO_NO_CHECK = 11; pub const SO_PRIORITY = 12; pub const SO_LINGER = 13; pub const SO_BSDCOMPAT = 14; pub const SO_REUSEPORT = 15; pub const SO_PASSCRED = 16; pub const SO_PEERCRED = 17; pub const SO_RCVLOWAT = 18; pub const SO_SNDLOWAT = 19; pub const SO_RCVTIMEO = 20; pub const SO_SNDTIMEO = 21; pub const SO_ACCEPTCONN = 30; pub const SO_SNDBUFFORCE = 32; pub const SO_RCVBUFFORCE = 33; pub const SO_PROTOCOL = 38; pub const SO_DOMAIN = 39; pub const SO_SECURITY_AUTHENTICATION = 22; pub const SO_SECURITY_ENCRYPTION_TRANSPORT = 23; pub const SO_SECURITY_ENCRYPTION_NETWORK = 24; pub const SO_BINDTODEVICE = 25; pub const SO_ATTACH_FILTER = 26; pub const SO_DETACH_FILTER = 27; pub const SO_GET_FILTER = SO_ATTACH_FILTER; pub const SO_PEERNAME = 28; pub const SO_TIMESTAMP = 29; pub const SCM_TIMESTAMP = SO_TIMESTAMP; pub const SO_PEERSEC = 31; pub const SO_PASSSEC = 34; pub const SO_TIMESTAMPNS = 35; pub const SCM_TIMESTAMPNS = SO_TIMESTAMPNS; pub const SO_MARK = 36; pub const SO_TIMESTAMPING = 37; pub const SCM_TIMESTAMPING = SO_TIMESTAMPING; pub const SO_RXQ_OVFL = 40; pub const SO_WIFI_STATUS = 41; pub const SCM_WIFI_STATUS = SO_WIFI_STATUS; pub const SO_PEEK_OFF = 42; pub const SO_NOFCS = 43; pub const SO_LOCK_FILTER = 44; pub const SO_SELECT_ERR_QUEUE = 45; pub const SO_BUSY_POLL = 46; pub const SO_MAX_PACING_RATE = 47; pub const SO_BPF_EXTENSIONS = 48; pub const SO_INCOMING_CPU = 49; pub const SO_ATTACH_BPF = 50; pub const SO_DETACH_BPF = SO_DETACH_FILTER; pub const SO_ATTACH_REUSEPORT_CBPF = 51; pub const SO_ATTACH_REUSEPORT_EBPF = 52; pub const SO_CNX_ADVICE = 53; pub const SCM_TIMESTAMPING_OPT_STATS = 54; pub const SO_MEMINFO = 55; pub const SO_INCOMING_NAPI_ID = 56; pub const SO_COOKIE = 57; pub const SCM_TIMESTAMPING_PKTINFO = 58; pub const SO_PEERGROUPS = 59; pub const SO_ZEROCOPY = 60; pub const SOL_SOCKET = 1; pub const SOL_IP = 0; pub const SOL_IPV6 = 41; pub const SOL_ICMPV6 = 58; pub const SOL_RAW = 255; pub const SOL_DECNET = 261; pub const SOL_X25 = 262; pub const SOL_PACKET = 263; pub const SOL_ATM = 264; pub const SOL_AAL = 265; pub const SOL_IRDA = 266; pub const SOL_NETBEUI = 267; pub const SOL_LLC = 268; pub const SOL_DCCP = 269; pub const SOL_NETLINK = 270; pub const SOL_TIPC = 271; pub const SOL_RXRPC = 272; pub const SOL_PPPOL2TP = 273; pub const SOL_BLUETOOTH = 274; pub const SOL_PNPIPE = 275; pub const SOL_RDS = 276; pub const SOL_IUCV = 277; pub const SOL_CAIF = 278; pub const SOL_ALG = 279; pub const SOL_NFC = 280; pub const SOL_KCM = 281; pub const SOL_TLS = 282; pub const SOMAXCONN = 128; pub const MSG_OOB = 0x0001; pub const MSG_PEEK = 0x0002; pub const MSG_DONTROUTE = 0x0004; pub const MSG_CTRUNC = 0x0008; pub const MSG_PROXY = 0x0010; pub const MSG_TRUNC = 0x0020; pub const MSG_DONTWAIT = 0x0040; pub const MSG_EOR = 0x0080; pub const MSG_WAITALL = 0x0100; pub const MSG_FIN = 0x0200; pub const MSG_SYN = 0x0400; pub const MSG_CONFIRM = 0x0800; pub const MSG_RST = 0x1000; pub const MSG_ERRQUEUE = 0x2000; pub const MSG_NOSIGNAL = 0x4000; pub const MSG_MORE = 0x8000; pub const MSG_WAITFORONE = 0x10000; pub const MSG_BATCH = 0x40000; pub const MSG_ZEROCOPY = 0x4000000; pub const MSG_FASTOPEN = 0x20000000; pub const MSG_CMSG_CLOEXEC = 0x40000000; 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; pub const TCGETS = 0x5401; pub const TCSETS = 0x5402; pub const TCSETSW = 0x5403; pub const TCSETSF = 0x5404; pub const TCGETA = 0x5405; pub const TCSETA = 0x5406; pub const TCSETAW = 0x5407; pub const TCSETAF = 0x5408; pub const TCSBRK = 0x5409; pub const TCXONC = 0x540A; pub const TCFLSH = 0x540B; pub const TIOCEXCL = 0x540C; pub const TIOCNXCL = 0x540D; pub const TIOCSCTTY = 0x540E; pub const TIOCGPGRP = 0x540F; pub const TIOCSPGRP = 0x5410; pub const TIOCOUTQ = 0x5411; pub const TIOCSTI = 0x5412; pub const TIOCGWINSZ = 0x5413; pub const TIOCSWINSZ = 0x5414; pub const TIOCMGET = 0x5415; pub const TIOCMBIS = 0x5416; pub const TIOCMBIC = 0x5417; pub const TIOCMSET = 0x5418; pub const TIOCGSOFTCAR = 0x5419; pub const TIOCSSOFTCAR = 0x541A; pub const FIONREAD = 0x541B; pub const TIOCINQ = FIONREAD; pub const TIOCLINUX = 0x541C; pub const TIOCCONS = 0x541D; pub const TIOCGSERIAL = 0x541E; pub const TIOCSSERIAL = 0x541F; pub const TIOCPKT = 0x5420; pub const FIONBIO = 0x5421; pub const TIOCNOTTY = 0x5422; pub const TIOCSETD = 0x5423; pub const TIOCGETD = 0x5424; pub const TCSBRKP = 0x5425; pub const TIOCSBRK = 0x5427; pub const TIOCCBRK = 0x5428; pub const TIOCGSID = 0x5429; pub const TIOCGRS485 = 0x542E; pub const TIOCSRS485 = 0x542F; pub const TIOCGPTN = 0x80045430; pub const TIOCSPTLCK = 0x40045431; pub const TIOCGDEV = 0x80045432; pub const TCGETX = 0x5432; pub const TCSETX = 0x5433; pub const TCSETXF = 0x5434; pub const TCSETXW = 0x5435; pub const TIOCSIG = 0x40045436; pub const TIOCVHANGUP = 0x5437; pub const TIOCGPKT = 0x80045438; pub const TIOCGPTLCK = 0x80045439; pub const TIOCGEXCL = 0x80045440; pub const EPOLL_CLOEXEC = O_CLOEXEC; pub const EPOLL_CTL_ADD = 1; pub const EPOLL_CTL_DEL = 2; pub const EPOLL_CTL_MOD = 3; pub const EPOLLIN = 0x001; pub const EPOLLPRI = 0x002; pub const EPOLLOUT = 0x004; pub const EPOLLRDNORM = 0x040; pub const EPOLLRDBAND = 0x080; pub const EPOLLWRNORM = 0x100; pub const EPOLLWRBAND = 0x200; pub const EPOLLMSG = 0x400; pub const EPOLLERR = 0x008; pub const EPOLLHUP = 0x010; pub const EPOLLRDHUP = 0x2000; pub const EPOLLEXCLUSIVE = (u32(1) << 28); pub const EPOLLWAKEUP = (u32(1) << 29); pub const EPOLLONESHOT = (u32(1) << 30); pub const EPOLLET = (u32(1) << 31); pub const CLOCK_REALTIME = 0; pub const CLOCK_MONOTONIC = 1; pub const CLOCK_PROCESS_CPUTIME_ID = 2; pub const CLOCK_THREAD_CPUTIME_ID = 3; pub const CLOCK_MONOTONIC_RAW = 4; pub const CLOCK_REALTIME_COARSE = 5; pub const CLOCK_MONOTONIC_COARSE = 6; pub const CLOCK_BOOTTIME = 7; pub const CLOCK_REALTIME_ALARM = 8; pub const CLOCK_BOOTTIME_ALARM = 9; pub const CLOCK_SGI_CYCLE = 10; pub const CLOCK_TAI = 11; pub const CSIGNAL = 0x000000ff; pub const CLONE_VM = 0x00000100; pub const CLONE_FS = 0x00000200; pub const CLONE_FILES = 0x00000400; pub const CLONE_SIGHAND = 0x00000800; pub const CLONE_PTRACE = 0x00002000; pub const CLONE_VFORK = 0x00004000; pub const CLONE_PARENT = 0x00008000; pub const CLONE_THREAD = 0x00010000; pub const CLONE_NEWNS = 0x00020000; pub const CLONE_SYSVSEM = 0x00040000; pub const CLONE_SETTLS = 0x00080000; pub const CLONE_PARENT_SETTID = 0x00100000; pub const CLONE_CHILD_CLEARTID = 0x00200000; pub const CLONE_DETACHED = 0x00400000; pub const CLONE_UNTRACED = 0x00800000; pub const CLONE_CHILD_SETTID = 0x01000000; pub const CLONE_NEWCGROUP = 0x02000000; pub const CLONE_NEWUTS = 0x04000000; pub const CLONE_NEWIPC = 0x08000000; pub const CLONE_NEWUSER = 0x10000000; pub const CLONE_NEWPID = 0x20000000; pub const CLONE_NEWNET = 0x40000000; pub const CLONE_IO = 0x80000000; pub const MS_RDONLY = 1; pub const MS_NOSUID = 2; pub const MS_NODEV = 4; pub const MS_NOEXEC = 8; pub const MS_SYNCHRONOUS = 16; pub const MS_REMOUNT = 32; pub const MS_MANDLOCK = 64; pub const MS_DIRSYNC = 128; pub const MS_NOATIME = 1024; pub const MS_NODIRATIME = 2048; pub const MS_BIND = 4096; pub const MS_MOVE = 8192; pub const MS_REC = 16384; pub const MS_SILENT = 32768; pub const MS_POSIXACL = (1<<16); pub const MS_UNBINDABLE = (1<<17); pub const MS_PRIVATE = (1<<18); pub const MS_SLAVE = (1<<19); pub const MS_SHARED = (1<<20); pub const MS_RELATIME = (1<<21); pub const MS_KERNMOUNT = (1<<22); pub const MS_I_VERSION = (1<<23); pub const MS_STRICTATIME = (1<<24); pub const MS_LAZYTIME = (1<<25); pub const MS_NOREMOTELOCK = (1<<27); pub const MS_NOSEC = (1<<28); pub const MS_BORN = (1<<29); pub const MS_ACTIVE = (1<<30); pub const MS_NOUSER = (1<<31); pub const MS_RMT_MASK = (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|MS_LAZYTIME); pub const MS_MGC_VAL = 0xc0ed0000; pub const MS_MGC_MSK = 0xffff0000; pub const MNT_FORCE = 1; pub const MNT_DETACH = 2; pub const MNT_EXPIRE = 4; pub const UMOUNT_NOFOLLOW = 8; pub const S_IFMT = 0o170000; pub const S_IFDIR = 0o040000; pub const S_IFCHR = 0o020000; pub const S_IFBLK = 0o060000; pub const S_IFREG = 0o100000; pub const S_IFIFO = 0o010000; pub const S_IFLNK = 0o120000; pub const S_IFSOCK = 0o140000; pub const S_ISUID = 0o4000; pub const S_ISGID = 0o2000; pub const S_ISVTX = 0o1000; pub const S_IRUSR = 0o400; pub const S_IWUSR = 0o200; pub const S_IXUSR = 0o100; pub const S_IRWXU = 0o700; pub const S_IRGRP = 0o040; pub const S_IWGRP = 0o020; pub const S_IXGRP = 0o010; pub const S_IRWXG = 0o070; pub const S_IROTH = 0o004; pub const S_IWOTH = 0o002; pub const S_IXOTH = 0o001; pub const S_IRWXO = 0o007; pub fn S_ISREG(m: u32) bool { return m & S_IFMT == S_IFREG; } pub fn S_ISDIR(m: u32) bool { return m & S_IFMT == S_IFDIR; } pub fn S_ISCHR(m: u32) bool { return m & S_IFMT == S_IFCHR; } pub fn S_ISBLK(m: u32) bool { return m & S_IFMT == S_IFBLK; } pub fn S_ISFIFO(m: u32) bool { return m & S_IFMT == S_IFIFO; } 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 const TFD_NONBLOCK = O_NONBLOCK; pub const TFD_CLOEXEC = O_CLOEXEC; pub const TFD_TIMER_ABSTIME = 1; pub const TFD_TIMER_CANCEL_ON_SET = (1 << 1); fn unsigned(s: i32) u32 { return @bitCast(u32, s); } fn signed(s: u32) i32 { return @bitCast(i32, s); } pub fn WEXITSTATUS(s: i32) i32 { return signed((unsigned(s) & 0xff00) >> 8); } pub fn WTERMSIG(s: i32) i32 { return signed(unsigned(s) & 0x7f); } pub fn WSTOPSIG(s: i32) i32 { return WEXITSTATUS(s); } pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } pub fn WIFSTOPPED(s: i32) bool { return (u16)(((unsigned(s)&0xffff)*%0x10001)>>8) > 0x7f00; } pub fn WIFSIGNALED(s: i32) bool { return (unsigned(s)&0xffff)-%1 < 0xff; } pub const winsize = extern struct { ws_row: u16, ws_col: u16, ws_xpixel: u16, ws_ypixel: u16, }; /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); return if (signed_r > -4096 and signed_r < 0) usize(-signed_r) else 0; } pub fn dup2(old: i32, new: i32) usize { return syscall2(SYS_dup2, usize(old), usize(new)); } pub fn chdir(path: &const u8) usize { return syscall1(SYS_chdir, @ptrToInt(path)); } pub fn chroot(path: &const u8) usize { return syscall1(SYS_chroot, @ptrToInt(path)); } pub fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) usize { return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); } pub fn fork() usize { return syscall0(SYS_fork); } pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?&timespec) usize { return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout)); } pub fn getcwd(buf: &u8, size: usize) usize { return syscall2(SYS_getcwd, @ptrToInt(buf), size); } pub fn getdents(fd: i32, dirp: &u8, count: usize) usize { return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count); } pub fn isatty(fd: i32) bool { var wsz: winsize = undefined; return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) usize { return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } pub fn mkdir(path: &const u8, mode: u32) usize { return syscall2(SYS_mkdir, @ptrToInt(path), mode); } pub fn mount(special: &const u8, dir: &const u8, fstype: &const u8, flags: usize, data: usize) usize { return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); } pub fn umount(special: &const u8) usize { return syscall2(SYS_umount2, @ptrToInt(special), 0); } pub fn umount2(special: &const u8, flags: u32) usize { return syscall2(SYS_umount2, @ptrToInt(special), flags); } pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: usize, fd: i32, offset: isize) usize { return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } pub fn munmap(address: &u8, length: usize) usize { return syscall2(SYS_munmap, @ptrToInt(address), length); } pub fn read(fd: i32, buf: &u8, count: usize) usize { return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count); } pub fn rmdir(path: &const u8) usize { return syscall1(SYS_rmdir, @ptrToInt(path)); } pub fn symlink(existing: &const u8, new: &const u8) usize { return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new)); } pub fn pread(fd: i32, buf: &u8, count: usize, offset: usize) usize { return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset); } pub fn access(path: &const u8, mode: u32) usize { return syscall2(SYS_access, @ptrToInt(path), mode); } pub fn pipe(fd: &[2]i32) usize { return pipe2(fd, 0); } pub fn pipe2(fd: &[2]i32, flags: usize) usize { return syscall2(SYS_pipe2, @ptrToInt(fd), flags); } pub fn write(fd: i32, buf: &const u8, count: usize) usize { return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count); } pub fn pwrite(fd: i32, buf: &const u8, count: usize, offset: usize) usize { return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset); } pub fn rename(old: &const u8, new: &const u8) usize { return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new)); } pub fn open(path: &const u8, flags: u32, perm: usize) usize { return syscall3(SYS_open, @ptrToInt(path), flags, perm); } pub fn create(path: &const u8, perm: usize) usize { return syscall2(SYS_creat, @ptrToInt(path), perm); } pub fn openat(dirfd: i32, path: &const u8, flags: usize, mode: usize) usize { return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: &i32, child_tid: &i32, newtls: usize) usize { return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); } /// See also `clone` (from the arch-specific include) pub fn clone2(flags: usize, child_stack_ptr: usize) usize { return syscall2(SYS_clone, flags, child_stack_ptr); } pub fn close(fd: i32) usize { return syscall1(SYS_close, usize(fd)); } pub fn lseek(fd: i32, offset: isize, ref_pos: usize) usize { return syscall3(SYS_lseek, usize(fd), @bitCast(usize, offset), ref_pos); } pub fn exit(status: i32) noreturn { _ = syscall1(SYS_exit, @bitCast(usize, isize(status))); unreachable; } pub fn getrandom(buf: &u8, count: usize, flags: u32) usize { return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags)); } pub fn kill(pid: i32, sig: i32) usize { return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig)); } pub fn unlink(path: &const u8) usize { return syscall1(SYS_unlink, @ptrToInt(path)); } pub fn waitpid(pid: i32, status: &i32, options: i32) usize { return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0); } pub fn clock_gettime(clk_id: i32, tp: &timespec) usize { if (VDSO_CGT_SYM.len != 0) { const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered); if (@ptrToInt(f) != 0) { const rc = f(clk_id, tp); switch (rc) { 0, @bitCast(usize, isize(-EINVAL)) => return rc, else => {}, } } } return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } var vdso_clock_gettime = init_vdso_clock_gettime; extern fn init_vdso_clock_gettime(clk: i32, ts: &timespec) usize { const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM); var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr); _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); if (@ptrToInt(f) == 0) return @bitCast(usize, isize(-ENOSYS)); return f(clk, ts); } pub fn clock_getres(clk_id: i32, tp: &timespec) usize { return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } pub fn clock_settime(clk_id: i32, tp: &const timespec) usize { return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } pub fn gettimeofday(tv: &timeval, tz: &timezone) usize { return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize { return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize { return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem)); } pub fn setuid(uid: u32) usize { return syscall1(SYS_setuid, uid); } pub fn setgid(gid: u32) usize { return syscall1(SYS_setgid, gid); } pub fn setreuid(ruid: u32, euid: u32) usize { return syscall2(SYS_setreuid, ruid, euid); } pub fn setregid(rgid: u32, egid: u32) usize { return syscall2(SYS_setregid, rgid, egid); } pub fn getuid() u32 { return u32(syscall0(SYS_getuid)); } pub fn getgid() u32 { return u32(syscall0(SYS_getgid)); } pub fn geteuid() u32 { return u32(syscall0(SYS_geteuid)); } pub fn getegid() u32 { return u32(syscall0(SYS_getegid)); } pub fn seteuid(euid: u32) usize { return syscall1(SYS_seteuid, euid); } pub fn setegid(egid: u32) usize { return syscall1(SYS_setegid, egid); } pub fn getresuid(ruid: &u32, euid: &u32, suid: &u32) usize { return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } pub fn getresgid(rgid: &u32, egid: &u32, sgid: &u32) usize { return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } pub fn setresuid(ruid: u32, euid: u32, suid: u32) usize { return syscall3(SYS_setresuid, ruid, euid, suid); } pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize { return syscall3(SYS_setresgid, rgid, egid, sgid); } pub fn getgroups(size: usize, list: &u32) usize { return syscall2(SYS_getgroups, size, @ptrToInt(list)); } pub fn setgroups(size: usize, list: &const u32) usize { return syscall2(SYS_setgroups, size, @ptrToInt(list)); } pub fn getpid() i32 { return @bitCast(i32, u32(syscall0(SYS_getpid))); } pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize { return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG/8); } pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { assert(sig >= 1); assert(sig != SIGKILL); assert(sig != SIGSTOP); var ksa = k_sigaction { .handler = act.handler, .flags = act.flags | SA_RESTORER, .mask = undefined, .restorer = @ptrCast(extern fn()void, restore_rt), }; var ksa_old: k_sigaction = undefined; @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8); const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask))); const err = getErrno(result); if (err != 0) { return result; } if (oact) |old| { old.handler = ksa_old.handler; old.flags = @truncate(u32, ksa_old.flags); @memcpy(@ptrCast(&u8, &old.mask), @ptrCast(&const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask))); } return 0; } const NSIG = 65; const sigset_t = [128 / @sizeOf(usize)]usize; const all_mask = []usize{@maxValue(usize)}; const app_mask = []usize{0xfffffffc7fffffff}; const k_sigaction = extern struct { handler: extern fn(i32)void, flags: usize, restorer: extern fn()void, mask: [2]u32, }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { handler: extern fn(i32)void, mask: sigset_t, flags: u32, }; pub const SIG_ERR = @intToPtr(extern fn(i32)void, @maxValue(usize)); pub const SIG_DFL = @intToPtr(extern fn(i32)void, 0); pub const SIG_IGN = @intToPtr(extern fn(i32)void, 1); pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { var set: sigset_t = undefined; blockAppSignals(&set); const tid = i32(syscall0(SYS_gettid)); const ret = syscall2(SYS_tkill, usize(tid), usize(sig)); restoreSignals(&set); return ret; } fn blockAllSignals(set: &sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG/8); } fn blockAppSignals(set: &sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG/8); } fn restoreSignals(set: &sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG/8); } pub fn sigaddset(set: &sigset_t, sig: u6) void { const s = sig - 1; (*set)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); } pub fn sigismember(set: &const sigset_t, sig: u6) bool { const s = sig - 1; return ((*set)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; } pub const in_port_t = u16; pub const sa_family_t = u16; pub const socklen_t = u32; pub const sockaddr = extern union { in: sockaddr_in, in6: sockaddr_in6, }; pub const sockaddr_in = extern struct { family: sa_family_t, port: in_port_t, addr: u32, zero: [8]u8, }; pub const sockaddr_in6 = extern struct { family: sa_family_t, port: in_port_t, flowinfo: u32, addr: [16]u8, scope_id: u32, }; pub const iovec = extern struct { iov_base: &u8, iov_len: usize, }; pub fn getsockname(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn getpeername(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { return syscall3(SYS_socket, domain, socket_type, protocol); } pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: &const u8, optlen: socklen_t) usize { return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen)); } pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: &u8, noalias optlen: &socklen_t) usize { return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } pub fn sendmsg(fd: i32, msg: &const msghdr, flags: u32) usize { return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags); } pub fn connect(fd: i32, addr: &const sockaddr, len: socklen_t) usize { return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len)); } pub fn recvmsg(fd: i32, msg: &msghdr, flags: u32) usize { return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); } pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize { return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } pub fn shutdown(fd: i32, how: i32) usize { return syscall2(SYS_shutdown, usize(fd), usize(how)); } pub fn bind(fd: i32, addr: &const sockaddr, len: socklen_t) usize { return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len)); } pub fn listen(fd: i32, backlog: u32) usize { return syscall2(SYS_listen, usize(fd), backlog); } pub fn sendto(fd: i32, buf: &const u8, len: usize, flags: u32, addr: ?&const sockaddr, alen: socklen_t) usize { return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen)); } pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize { return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(&fd[0])); } pub fn accept(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { return accept4(fd, addr, len, 0); } pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags: u32) usize { return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags); } pub fn fstat(fd: i32, stat_buf: &Stat) usize { return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf)); } pub fn stat(pathname: &const u8, statbuf: &Stat) usize { return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf)); } pub fn lstat(pathname: &const u8, statbuf: &Stat) usize { return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); } pub fn listxattr(path: &const u8, list: &u8, size: usize) usize { return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn llistxattr(path: &const u8, list: &u8, size: usize) usize { return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn flistxattr(fd: usize, list: &u8, size: usize) usize { return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size); } pub fn getxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize { return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn lgetxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize { return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn fgetxattr(fd: usize, name: &const u8, value: &void, size: usize) usize { return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } pub fn setxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, size: usize, flags: usize) usize { return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn removexattr(path: &const u8, name: &const u8) usize { return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn lremovexattr(path: &const u8, name: &const u8) usize { return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn fremovexattr(fd: usize, name: &const u8) usize { return syscall2(SYS_fremovexattr, fd, @ptrToInt(name)); } pub const epoll_data = packed union { ptr: usize, fd: i32, @"u32": u32, @"u64": u64, }; pub const epoll_event = packed struct { events: u32, data: epoll_data, }; pub fn epoll_create() usize { return epoll_create1(0); } pub fn epoll_create1(flags: usize) usize { return syscall1(SYS_epoll_create1, flags); } pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: &epoll_event) usize { return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev)); } pub fn epoll_wait(epoll_fd: i32, events: &epoll_event, maxevents: u32, timeout: i32) usize { return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout)); } pub fn timerfd_create(clockid: i32, flags: u32) usize { return syscall2(SYS_timerfd_create, usize(clockid), usize(flags)); } pub const itimerspec = extern struct { it_interval: timespec, it_value: timespec }; pub fn timerfd_gettime(fd: i32, curr_value: &itimerspec) usize { return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value)); } pub fn timerfd_settime(fd: i32, flags: u32, new_value: &const itimerspec, old_value: ?&itimerspec) usize { return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value)); } pub const _LINUX_CAPABILITY_VERSION_1 = 0x19980330; pub const _LINUX_CAPABILITY_U32S_1 = 1; pub const _LINUX_CAPABILITY_VERSION_2 = 0x20071026; pub const _LINUX_CAPABILITY_U32S_2 = 2; pub const _LINUX_CAPABILITY_VERSION_3 = 0x20080522; pub const _LINUX_CAPABILITY_U32S_3 = 2; pub const VFS_CAP_REVISION_MASK = 0xFF000000; pub const VFS_CAP_REVISION_SHIFT = 24; pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK; pub const VFS_CAP_FLAGS_EFFECTIVE = 0x000001; pub const VFS_CAP_REVISION_1 = 0x01000000; pub const VFS_CAP_U32_1 = 1; pub const XATTR_CAPS_SZ_1 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_1); pub const VFS_CAP_REVISION_2 = 0x02000000; pub const VFS_CAP_U32_2 = 2; pub const XATTR_CAPS_SZ_2 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_2); pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2; pub const VFS_CAP_U32 = VFS_CAP_U32_2; pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2; pub const vfs_cap_data = extern struct { //all of these are mandated as little endian //when on disk. const Data = struct { permitted: u32, inheritable: u32, }; magic_etc: u32, data: [VFS_CAP_U32]Data, }; pub const CAP_CHOWN = 0; pub const CAP_DAC_OVERRIDE = 1; pub const CAP_DAC_READ_SEARCH = 2; pub const CAP_FOWNER = 3; pub const CAP_FSETID = 4; pub const CAP_KILL = 5; pub const CAP_SETGID = 6; pub const CAP_SETUID = 7; pub const CAP_SETPCAP = 8; pub const CAP_LINUX_IMMUTABLE = 9; pub const CAP_NET_BIND_SERVICE = 10; pub const CAP_NET_BROADCAST = 11; pub const CAP_NET_ADMIN = 12; pub const CAP_NET_RAW = 13; pub const CAP_IPC_LOCK = 14; pub const CAP_IPC_OWNER = 15; pub const CAP_SYS_MODULE = 16; pub const CAP_SYS_RAWIO = 17; pub const CAP_SYS_CHROOT = 18; pub const CAP_SYS_PTRACE = 19; pub const CAP_SYS_PACCT = 20; pub const CAP_SYS_ADMIN = 21; pub const CAP_SYS_BOOT = 22; pub const CAP_SYS_NICE = 23; pub const CAP_SYS_RESOURCE = 24; pub const CAP_SYS_TIME = 25; pub const CAP_SYS_TTY_CONFIG = 26; pub const CAP_MKNOD = 27; pub const CAP_LEASE = 28; pub const CAP_AUDIT_WRITE = 29; pub const CAP_AUDIT_CONTROL = 30; pub const CAP_SETFCAP = 31; pub const CAP_MAC_OVERRIDE = 32; pub const CAP_MAC_ADMIN = 33; pub const CAP_SYSLOG = 34; pub const CAP_WAKE_ALARM = 35; pub const CAP_BLOCK_SUSPEND = 36; pub const CAP_AUDIT_READ = 37; pub const CAP_LAST_CAP = CAP_AUDIT_READ; pub fn cap_valid(u8: x) bool { return x >= 0 and x <= CAP_LAST_CAP; } pub fn CAP_TO_MASK(cap: u8) u32 { return u32(1) << u5(cap & 31); } pub fn CAP_TO_INDEX(cap: u8) u8 { return cap >> 5; } pub const cap_t = extern struct { hdrp: &cap_user_header_t, datap: &cap_user_data_t, }; pub const cap_user_header_t = extern struct { version: u32, pid: usize, }; pub const cap_user_data_t = extern struct { effective: u32, permitted: u32, inheritable: u32, }; pub fn unshare(flags: usize) usize { return syscall1(SYS_unshare, usize(flags)); } pub fn capget(hdrp: &cap_user_header_t, datap: &cap_user_data_t) usize { return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap)); } pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize { return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap)); } test "import" { if (builtin.os == builtin.Os.linux) { _ = @import("test.zig"); } }
std/os/linux/index.zig
const std = @import("std"); const deps = @import("deps.zig"); // const mode_names = blk: { // const fields = @typeInfo(std.builtin.Mode).Enum.fields; // var names: [fields.len][]const u8 = undefined; // inline for (fields) |field, i| names[i] = "[ " ++ field.name ++ " ] "; // break :blk names; // }; // var mode_name_idx: usize = undefined; // comptime options var build_options: *std.build.OptionsStep = undefined; // fn addTest( // comptime root_src: []const u8, // test_name: []const u8, // b: *std.build.Builder, // ) *std.build.LibExeObjStep { // const t = b.addTest(root_src); // t.setNamePrefix(mode_names[mode_name_idx]); // t.addIncludeDir("test"); // private // b.step( // if (test_name.len != 0) test_name else "test:" ++ root_src, // "Run tests from " ++ root_src, // ).dependOn(&t.step); // return t; // } fn addExecutable( comptime name: []const u8, root_src: []const u8, run_name: []const u8, run_description: []const u8, b: *std.build.Builder, ) *std.build.LibExeObjStep { const exe = b.addExecutable(name, root_src); exe.addOptions("build_options", build_options); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); b.step( if (run_name.len != 0) run_name else "run:" ++ name, if (run_description.len != 0) run_description else "Run " ++ name, ).dependOn(&run_cmd.step); return exe; } pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); //mode_name_idx = @enumToInt(mode); // options const version: []const u8 = b.option( []const u8, "version", "the app version", ) orelse parseGitRevHead(b.allocator) catch "master"; // will not be used/referenced after the surrounding function returns build_options = b.addOptions(); build_options.addOption([]const u8, "version", version); // tests // const test_all = b.step("test", "Run all tests"); // const tests = &[_]*std.build.LibExeObjStep{ // deps.addAllTo( // addTest("test/test.zig", "test:lib", b), // b, target, mode, // ), // }; // for (tests) |t| test_all.dependOn(&t.step); // executables deps.addAllTo( addExecutable( "zpp", "src/main.zig", "run", "Run the app", b, ), b, target, mode, ).install(); } /// Returns the output of `git rev-parse HEAD` pub fn parseGitRevHead(a: std.mem.Allocator) ![]const u8 { const max = std.math.maxInt(usize); const git_dir = try std.fs.cwd().openDir(".git", .{}); // content of `.git/HEAD` -> `ref: refs/heads/master` const h = std.mem.trim(u8, try git_dir.readFileAlloc(a, "HEAD", max), "\n"); // content of `refs/heads/master` return std.mem.trim(u8, try git_dir.readFileAlloc(a, h[5..], max), "\n"); }
build.zig
const std = @import("std"); const testing = std.testing; const winmd = @import("winmd.zig"); test "TypeReader with no files" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); if (leaked) testing.expect(false); //fail test } var allocator = &gpa.allocator; var reader = try winmd.TypeReader.init(allocator, null); defer reader.deinit(); testing.expect(reader.files.items.len == 2); } test "TypeReader with specified file" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); if (leaked) testing.expect(false); } var allocator = &gpa.allocator; const foundation_winmd = "test/data/Windows.Foundation.FoundationContract.winmd"; const foundation_file = try std.fs.cwd().readFileAlloc(allocator, foundation_winmd, std.math.maxInt(usize)); defer allocator.free(foundation_file); const files = &[_][]const u8{foundation_file}; var reader = try winmd.TypeReader.init(allocator, files); defer reader.deinit(); testing.expect(reader.files.items.len == 1); // verify type layout, mostly mimicing what is laid out here: // https://github.com/microsoft/winmd-rs/blob/master/tests/stringable.rs const def = reader.findTypeDef("Windows.Foundation", "IStringable"); testing.expect(def != null); testing.expect(std.mem.eql(u8, def.?.namespace(), "Windows.Foundation")); testing.expect(std.mem.eql(u8, def.?.name(), "IStringable")); } test "read DatabaseFile fromBytes" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); if (leaked) testing.expect(false); } var allocator = &gpa.allocator; const foundation_winmd = "test/data/Windows.Foundation.FoundationContract.winmd"; const foundation_file = try std.fs.cwd().readFileAlloc(allocator, foundation_winmd, std.math.maxInt(usize)); defer allocator.free(foundation_file); const foundation_database_file = try winmd.DatabaseFile.fromBytes(foundation_file); testing.expect(foundation_database_file.blobs == 19360); testing.expect(foundation_database_file.strings == 14148); // expected table layout const tables = [_]winmd.TableData{ winmd.TableData{ .data = 11152, .row_count = 83, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 11650, .row_count = 235, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 2864, .row_count = 109, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 13880, .row_count = 33, .row_size = 8, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 6, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 10784, .row_count = 29, .row_size = 4, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 10900, .row_count = 42, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 3518, .row_count = 318, .row_size = 14, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 4 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 6, .size = 2 }, winmd.TableColumn{ .offset = 8, .size = 2 }, winmd.TableColumn{ .offset = 10, .size = 2 }, winmd.TableColumn{ .offset = 12, .size = 2 }, }, }, winmd.TableData{ .data = 7970, .row_count = 469, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 1464, .row_count = 100, .row_size = 14, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 4 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 6, .size = 2 }, winmd.TableColumn{ .offset = 8, .size = 2 }, winmd.TableColumn{ .offset = 10, .size = 2 }, winmd.TableColumn{ .offset = 12, .size = 2 }, }, }, winmd.TableData{ .data = 822, .row_count = 107, .row_size = 6, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 13810, .row_count = 14, .row_size = 2, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 0, .row_count = 0, .row_size = 8, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 6, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 0, .row_count = 0, .row_size = 2, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 0, .row_count = 0, .row_size = 4, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 812, .row_count = 1, .row_size = 10, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 2 }, winmd.TableColumn{ .offset = 2, .size = 2 }, winmd.TableColumn{ .offset = 4, .size = 2 }, winmd.TableColumn{ .offset = 6, .size = 2 }, winmd.TableColumn{ .offset = 8, .size = 2 }, winmd.TableColumn{ .offset = 0, .size = 0 }, }, }, winmd.TableData{ .data = 13860, .row_count = 1, .row_size = 20, .columns = [6]winmd.TableColumn{ winmd.TableColumn{ .offset = 0, .size = 8 }, winmd.TableColumn{ .offset = 8, .size = 4 }, winmd.TableColumn{ .offset = 12, .size = 2 }, winmd.TableColumn{ .offset = 14, .size = 2 }, winmd.TableColumn{ .offset = 16, .size = 2 }, winmd.TableColumn{ .offset = 18, .size = 2 }, }, }, }; testing.expect(std.mem.eql(u8, std.mem.sliceAsBytes(foundation_database_file.tables[0..]), std.mem.sliceAsBytes(tables[0..]))); }
src/winmd_test.zig
pub const XPS_E_SIGREQUESTID_DUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108795)); pub const XPS_E_PACKAGE_NOT_OPENED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108794)); pub const XPS_E_PACKAGE_ALREADY_OPENED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108793)); pub const XPS_E_SIGNATUREID_DUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108792)); pub const XPS_E_MARKUP_COMPATIBILITY_ELEMENTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108791)); pub const XPS_E_OBJECT_DETACHED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108790)); pub const XPS_E_INVALID_SIGNATUREBLOCK_MARKUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108789)); pub const XPS_E_INVALID_NUMBER_OF_POINTS_IN_CURVE_SEGMENTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108160)); pub const XPS_E_ABSOLUTE_REFERENCE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108159)); pub const XPS_E_INVALID_NUMBER_OF_COLOR_CHANNELS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108158)); pub const XPS_E_INVALID_LANGUAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109696)); pub const XPS_E_INVALID_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109695)); pub const XPS_E_INVALID_RESOURCE_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109694)); pub const XPS_E_INVALID_PAGE_SIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109693)); pub const XPS_E_INVALID_BLEED_BOX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109692)); pub const XPS_E_INVALID_THUMBNAIL_IMAGE_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109691)); pub const XPS_E_INVALID_LOOKUP_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109690)); pub const XPS_E_INVALID_FLOAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109689)); pub const XPS_E_UNEXPECTED_CONTENT_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109688)); pub const XPS_E_INVALID_FONT_URI = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109686)); pub const XPS_E_INVALID_CONTENT_BOX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109685)); pub const XPS_E_INVALID_MARKUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109684)); pub const XPS_E_INVALID_XML_ENCODING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109683)); pub const XPS_E_INVALID_CONTENT_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109682)); pub const XPS_E_INVALID_OBFUSCATED_FONT_URI = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109681)); pub const XPS_E_UNEXPECTED_RELATIONSHIP_TYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109680)); pub const XPS_E_UNEXPECTED_RESTRICTED_FONT_RELATIONSHIP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109679)); pub const XPS_E_MISSING_NAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109440)); pub const XPS_E_MISSING_LOOKUP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109439)); pub const XPS_E_MISSING_GLYPHS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109438)); pub const XPS_E_MISSING_SEGMENT_DATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109437)); pub const XPS_E_MISSING_COLORPROFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109436)); pub const XPS_E_MISSING_RELATIONSHIP_TARGET = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109435)); pub const XPS_E_MISSING_RESOURCE_RELATIONSHIP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109434)); pub const XPS_E_MISSING_FONTURI = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109433)); pub const XPS_E_MISSING_DOCUMENTSEQUENCE_RELATIONSHIP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109432)); pub const XPS_E_MISSING_DOCUMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109431)); pub const XPS_E_MISSING_REFERRED_DOCUMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109430)); pub const XPS_E_MISSING_REFERRED_PAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109429)); pub const XPS_E_MISSING_PAGE_IN_DOCUMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109428)); pub const XPS_E_MISSING_PAGE_IN_PAGEREFERENCE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109427)); pub const XPS_E_MISSING_IMAGE_IN_IMAGEBRUSH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109426)); pub const XPS_E_MISSING_RESOURCE_KEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109425)); pub const XPS_E_MISSING_PART_REFERENCE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109424)); pub const XPS_E_MISSING_RESTRICTED_FONT_RELATIONSHIP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109423)); pub const XPS_E_MISSING_DISCARDCONTROL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109422)); pub const XPS_E_MISSING_PART_STREAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109421)); pub const XPS_E_UNAVAILABLE_PACKAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109420)); pub const XPS_E_DUPLICATE_RESOURCE_KEYS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109184)); pub const XPS_E_MULTIPLE_RESOURCES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109183)); pub const XPS_E_MULTIPLE_DOCUMENTSEQUENCE_RELATIONSHIPS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109182)); pub const XPS_E_MULTIPLE_THUMBNAILS_ON_PAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109181)); pub const XPS_E_MULTIPLE_THUMBNAILS_ON_PACKAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109180)); pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_PAGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109179)); pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_DOCUMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109178)); pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_DOCUMENTSEQUENCE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109177)); pub const XPS_E_MULTIPLE_REFERENCES_TO_PART = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109176)); pub const XPS_E_DUPLICATE_NAMES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142109175)); pub const XPS_E_STRING_TOO_LONG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108928)); pub const XPS_E_TOO_MANY_INDICES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108927)); pub const XPS_E_MAPPING_OUT_OF_ORDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108926)); pub const XPS_E_MAPPING_OUTSIDE_STRING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108925)); pub const XPS_E_MAPPING_OUTSIDE_INDICES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108924)); pub const XPS_E_CARET_OUTSIDE_STRING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108923)); pub const XPS_E_CARET_OUT_OF_ORDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108922)); pub const XPS_E_ODD_BIDILEVEL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108921)); pub const XPS_E_ONE_TO_ONE_MAPPING_EXPECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108920)); pub const XPS_E_RESTRICTED_FONT_NOT_OBFUSCATED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108919)); pub const XPS_E_NEGATIVE_FLOAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108918)); pub const XPS_E_XKEY_ATTR_PRESENT_OUTSIDE_RES_DICT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108672)); pub const XPS_E_DICTIONARY_ITEM_NAMED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108671)); pub const XPS_E_NESTED_REMOTE_DICTIONARY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108670)); pub const XPS_E_INDEX_OUT_OF_RANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108416)); pub const XPS_E_VISUAL_CIRCULAR_REF = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108415)); pub const XPS_E_NO_CUSTOM_OBJECTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108414)); pub const XPS_E_ALREADY_OWNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108413)); pub const XPS_E_RESOURCE_NOT_OWNED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108412)); pub const XPS_E_UNEXPECTED_COLORPROFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108411)); pub const XPS_E_COLOR_COMPONENT_OUT_OF_RANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108410)); pub const XPS_E_BOTH_PATHFIGURE_AND_ABBR_SYNTAX_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108409)); pub const XPS_E_BOTH_RESOURCE_AND_SOURCEATTR_PRESENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108408)); pub const XPS_E_BLEED_BOX_PAGE_DIMENSIONS_NOT_IN_SYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108407)); pub const XPS_E_RELATIONSHIP_EXTERNAL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108406)); pub const XPS_E_NOT_ENOUGH_GRADIENT_STOPS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108405)); pub const XPS_E_PACKAGE_WRITER_NOT_CLOSED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2142108404)); //-------------------------------------------------------------------------------- // Section: Types (110) //-------------------------------------------------------------------------------- pub const PRINT_WINDOW_FLAGS = enum(u32) { Y = 1, }; pub const PW_CLIENTONLY = PRINT_WINDOW_FLAGS.Y; pub const DEVICE_CAPABILITIES = enum(u32) { BINNAMES = 12, BINS = 6, COLLATE = 22, COLORDEVICE = 32, COPIES = 18, DRIVER = 11, DUPLEX = 7, ENUMRESOLUTIONS = 13, EXTRA = 9, FIELDS = 1, FILEDEPENDENCIES = 14, MAXEXTENT = 5, MEDIAREADY = 29, MEDIATYPENAMES = 34, MEDIATYPES = 35, MINEXTENT = 4, ORIENTATION = 17, NUP = 33, PAPERNAMES = 16, PAPERS = 2, PAPERSIZE = 3, PERSONALITY = 25, PRINTERMEM = 28, PRINTRATE = 26, PRINTRATEPPM = 31, PRINTRATEUNIT = 27, SIZE = 8, STAPLE = 30, TRUETYPE = 15, VERSION = 10, }; pub const DC_BINNAMES = DEVICE_CAPABILITIES.BINNAMES; pub const DC_BINS = DEVICE_CAPABILITIES.BINS; pub const DC_COLLATE = DEVICE_CAPABILITIES.COLLATE; pub const DC_COLORDEVICE = DEVICE_CAPABILITIES.COLORDEVICE; pub const DC_COPIES = DEVICE_CAPABILITIES.COPIES; pub const DC_DRIVER = DEVICE_CAPABILITIES.DRIVER; pub const DC_DUPLEX = DEVICE_CAPABILITIES.DUPLEX; pub const DC_ENUMRESOLUTIONS = DEVICE_CAPABILITIES.ENUMRESOLUTIONS; pub const DC_EXTRA = DEVICE_CAPABILITIES.EXTRA; pub const DC_FIELDS = DEVICE_CAPABILITIES.FIELDS; pub const DC_FILEDEPENDENCIES = DEVICE_CAPABILITIES.FILEDEPENDENCIES; pub const DC_MAXEXTENT = DEVICE_CAPABILITIES.MAXEXTENT; pub const DC_MEDIAREADY = DEVICE_CAPABILITIES.MEDIAREADY; pub const DC_MEDIATYPENAMES = DEVICE_CAPABILITIES.MEDIATYPENAMES; pub const DC_MEDIATYPES = DEVICE_CAPABILITIES.MEDIATYPES; pub const DC_MINEXTENT = DEVICE_CAPABILITIES.MINEXTENT; pub const DC_ORIENTATION = DEVICE_CAPABILITIES.ORIENTATION; pub const DC_NUP = DEVICE_CAPABILITIES.NUP; pub const DC_PAPERNAMES = DEVICE_CAPABILITIES.PAPERNAMES; pub const DC_PAPERS = DEVICE_CAPABILITIES.PAPERS; pub const DC_PAPERSIZE = DEVICE_CAPABILITIES.PAPERSIZE; pub const DC_PERSONALITY = DEVICE_CAPABILITIES.PERSONALITY; pub const DC_PRINTERMEM = DEVICE_CAPABILITIES.PRINTERMEM; pub const DC_PRINTRATE = DEVICE_CAPABILITIES.PRINTRATE; pub const DC_PRINTRATEPPM = DEVICE_CAPABILITIES.PRINTRATEPPM; pub const DC_PRINTRATEUNIT = DEVICE_CAPABILITIES.PRINTRATEUNIT; pub const DC_SIZE = DEVICE_CAPABILITIES.SIZE; pub const DC_STAPLE = DEVICE_CAPABILITIES.STAPLE; pub const DC_TRUETYPE = DEVICE_CAPABILITIES.TRUETYPE; pub const DC_VERSION = DEVICE_CAPABILITIES.VERSION; pub const PSINJECT_POINT = enum(u16) { BEGINSTREAM = 1, PSADOBE = 2, PAGESATEND = 3, PAGES = 4, DOCNEEDEDRES = 5, DOCSUPPLIEDRES = 6, PAGEORDER = 7, ORIENTATION = 8, BOUNDINGBOX = 9, DOCUMENTPROCESSCOLORS = 10, COMMENTS = 11, BEGINDEFAULTS = 12, ENDDEFAULTS = 13, BEGINPROLOG = 14, ENDPROLOG = 15, BEGINSETUP = 16, ENDSETUP = 17, TRAILER = 18, EOF = 19, ENDSTREAM = 20, DOCUMENTPROCESSCOLORSATEND = 21, PAGENUMBER = 100, BEGINPAGESETUP = 101, ENDPAGESETUP = 102, PAGETRAILER = 103, PLATECOLOR = 104, SHOWPAGE = 105, PAGEBBOX = 106, ENDPAGECOMMENTS = 107, VMSAVE = 200, VMRESTORE = 201, _, pub fn initFlags(o: struct { BEGINSTREAM: u1 = 0, PSADOBE: u1 = 0, PAGESATEND: u1 = 0, PAGES: u1 = 0, DOCNEEDEDRES: u1 = 0, DOCSUPPLIEDRES: u1 = 0, PAGEORDER: u1 = 0, ORIENTATION: u1 = 0, BOUNDINGBOX: u1 = 0, DOCUMENTPROCESSCOLORS: u1 = 0, COMMENTS: u1 = 0, BEGINDEFAULTS: u1 = 0, ENDDEFAULTS: u1 = 0, BEGINPROLOG: u1 = 0, ENDPROLOG: u1 = 0, BEGINSETUP: u1 = 0, ENDSETUP: u1 = 0, TRAILER: u1 = 0, EOF: u1 = 0, ENDSTREAM: u1 = 0, DOCUMENTPROCESSCOLORSATEND: u1 = 0, PAGENUMBER: u1 = 0, BEGINPAGESETUP: u1 = 0, ENDPAGESETUP: u1 = 0, PAGETRAILER: u1 = 0, PLATECOLOR: u1 = 0, SHOWPAGE: u1 = 0, PAGEBBOX: u1 = 0, ENDPAGECOMMENTS: u1 = 0, VMSAVE: u1 = 0, VMRESTORE: u1 = 0, }) PSINJECT_POINT { return @intToEnum(PSINJECT_POINT, (if (o.BEGINSTREAM == 1) @enumToInt(PSINJECT_POINT.BEGINSTREAM) else 0) | (if (o.PSADOBE == 1) @enumToInt(PSINJECT_POINT.PSADOBE) else 0) | (if (o.PAGESATEND == 1) @enumToInt(PSINJECT_POINT.PAGESATEND) else 0) | (if (o.PAGES == 1) @enumToInt(PSINJECT_POINT.PAGES) else 0) | (if (o.DOCNEEDEDRES == 1) @enumToInt(PSINJECT_POINT.DOCNEEDEDRES) else 0) | (if (o.DOCSUPPLIEDRES == 1) @enumToInt(PSINJECT_POINT.DOCSUPPLIEDRES) else 0) | (if (o.PAGEORDER == 1) @enumToInt(PSINJECT_POINT.PAGEORDER) else 0) | (if (o.ORIENTATION == 1) @enumToInt(PSINJECT_POINT.ORIENTATION) else 0) | (if (o.BOUNDINGBOX == 1) @enumToInt(PSINJECT_POINT.BOUNDINGBOX) else 0) | (if (o.DOCUMENTPROCESSCOLORS == 1) @enumToInt(PSINJECT_POINT.DOCUMENTPROCESSCOLORS) else 0) | (if (o.COMMENTS == 1) @enumToInt(PSINJECT_POINT.COMMENTS) else 0) | (if (o.BEGINDEFAULTS == 1) @enumToInt(PSINJECT_POINT.BEGINDEFAULTS) else 0) | (if (o.ENDDEFAULTS == 1) @enumToInt(PSINJECT_POINT.ENDDEFAULTS) else 0) | (if (o.BEGINPROLOG == 1) @enumToInt(PSINJECT_POINT.BEGINPROLOG) else 0) | (if (o.ENDPROLOG == 1) @enumToInt(PSINJECT_POINT.ENDPROLOG) else 0) | (if (o.BEGINSETUP == 1) @enumToInt(PSINJECT_POINT.BEGINSETUP) else 0) | (if (o.ENDSETUP == 1) @enumToInt(PSINJECT_POINT.ENDSETUP) else 0) | (if (o.TRAILER == 1) @enumToInt(PSINJECT_POINT.TRAILER) else 0) | (if (o.EOF == 1) @enumToInt(PSINJECT_POINT.EOF) else 0) | (if (o.ENDSTREAM == 1) @enumToInt(PSINJECT_POINT.ENDSTREAM) else 0) | (if (o.DOCUMENTPROCESSCOLORSATEND == 1) @enumToInt(PSINJECT_POINT.DOCUMENTPROCESSCOLORSATEND) else 0) | (if (o.PAGENUMBER == 1) @enumToInt(PSINJECT_POINT.PAGENUMBER) else 0) | (if (o.BEGINPAGESETUP == 1) @enumToInt(PSINJECT_POINT.BEGINPAGESETUP) else 0) | (if (o.ENDPAGESETUP == 1) @enumToInt(PSINJECT_POINT.ENDPAGESETUP) else 0) | (if (o.PAGETRAILER == 1) @enumToInt(PSINJECT_POINT.PAGETRAILER) else 0) | (if (o.PLATECOLOR == 1) @enumToInt(PSINJECT_POINT.PLATECOLOR) else 0) | (if (o.SHOWPAGE == 1) @enumToInt(PSINJECT_POINT.SHOWPAGE) else 0) | (if (o.PAGEBBOX == 1) @enumToInt(PSINJECT_POINT.PAGEBBOX) else 0) | (if (o.ENDPAGECOMMENTS == 1) @enumToInt(PSINJECT_POINT.ENDPAGECOMMENTS) else 0) | (if (o.VMSAVE == 1) @enumToInt(PSINJECT_POINT.VMSAVE) else 0) | (if (o.VMRESTORE == 1) @enumToInt(PSINJECT_POINT.VMRESTORE) else 0) ); } }; pub const PSINJECT_BEGINSTREAM = PSINJECT_POINT.BEGINSTREAM; pub const PSINJECT_PSADOBE = PSINJECT_POINT.PSADOBE; pub const PSINJECT_PAGESATEND = PSINJECT_POINT.PAGESATEND; pub const PSINJECT_PAGES = PSINJECT_POINT.PAGES; pub const PSINJECT_DOCNEEDEDRES = PSINJECT_POINT.DOCNEEDEDRES; pub const PSINJECT_DOCSUPPLIEDRES = PSINJECT_POINT.DOCSUPPLIEDRES; pub const PSINJECT_PAGEORDER = PSINJECT_POINT.PAGEORDER; pub const PSINJECT_ORIENTATION = PSINJECT_POINT.ORIENTATION; pub const PSINJECT_BOUNDINGBOX = PSINJECT_POINT.BOUNDINGBOX; pub const PSINJECT_DOCUMENTPROCESSCOLORS = PSINJECT_POINT.DOCUMENTPROCESSCOLORS; pub const PSINJECT_COMMENTS = PSINJECT_POINT.COMMENTS; pub const PSINJECT_BEGINDEFAULTS = PSINJECT_POINT.BEGINDEFAULTS; pub const PSINJECT_ENDDEFAULTS = PSINJECT_POINT.ENDDEFAULTS; pub const PSINJECT_BEGINPROLOG = PSINJECT_POINT.BEGINPROLOG; pub const PSINJECT_ENDPROLOG = PSINJECT_POINT.ENDPROLOG; pub const PSINJECT_BEGINSETUP = PSINJECT_POINT.BEGINSETUP; pub const PSINJECT_ENDSETUP = PSINJECT_POINT.ENDSETUP; pub const PSINJECT_TRAILER = PSINJECT_POINT.TRAILER; pub const PSINJECT_EOF = PSINJECT_POINT.EOF; pub const PSINJECT_ENDSTREAM = PSINJECT_POINT.ENDSTREAM; pub const PSINJECT_DOCUMENTPROCESSCOLORSATEND = PSINJECT_POINT.DOCUMENTPROCESSCOLORSATEND; pub const PSINJECT_PAGENUMBER = PSINJECT_POINT.PAGENUMBER; pub const PSINJECT_BEGINPAGESETUP = PSINJECT_POINT.BEGINPAGESETUP; pub const PSINJECT_ENDPAGESETUP = PSINJECT_POINT.ENDPAGESETUP; pub const PSINJECT_PAGETRAILER = PSINJECT_POINT.PAGETRAILER; pub const PSINJECT_PLATECOLOR = PSINJECT_POINT.PLATECOLOR; pub const PSINJECT_SHOWPAGE = PSINJECT_POINT.SHOWPAGE; pub const PSINJECT_PAGEBBOX = PSINJECT_POINT.PAGEBBOX; pub const PSINJECT_ENDPAGECOMMENTS = PSINJECT_POINT.ENDPAGECOMMENTS; pub const PSINJECT_VMSAVE = PSINJECT_POINT.VMSAVE; pub const PSINJECT_VMRESTORE = PSINJECT_POINT.VMRESTORE; pub const HPTPROVIDER = *opaque{}; pub const DRAWPATRECT = extern struct { ptPosition: POINT, ptSize: POINT, wStyle: u16, wPattern: u16, }; pub const PSINJECTDATA = extern struct { DataBytes: u32, InjectionPoint: PSINJECT_POINT, PageNumber: u16, }; pub const PSFEATURE_OUTPUT = extern struct { bPageIndependent: BOOL, bSetPageDevice: BOOL, }; pub const PSFEATURE_CUSTPAPER = extern struct { lOrientation: i32, lWidth: i32, lHeight: i32, lWidthOffset: i32, lHeightOffset: i32, }; pub const ABORTPROC = fn( param0: ?HDC, param1: i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const DOCINFOA = extern struct { cbSize: i32, lpszDocName: ?[*:0]const u8, lpszOutput: ?[*:0]const u8, lpszDatatype: ?[*:0]const u8, fwType: u32, }; pub const DOCINFOW = extern struct { cbSize: i32, lpszDocName: ?[*:0]const u16, lpszOutput: ?[*:0]const u16, lpszDatatype: ?[*:0]const u16, fwType: u32, }; const CLSID_XpsOMObjectFactory_Value = Guid.initString("e974d26d-3d9b-4d47-88cc-3872f2dc3585"); pub const CLSID_XpsOMObjectFactory = &CLSID_XpsOMObjectFactory_Value; const CLSID_XpsOMThumbnailGenerator_Value = Guid.initString("7e4a23e2-b969-4761-be35-1a8ced58e323"); pub const CLSID_XpsOMThumbnailGenerator = &CLSID_XpsOMThumbnailGenerator_Value; pub const XPS_TILE_MODE = enum(i32) { NONE = 1, TILE = 2, FLIPX = 3, FLIPY = 4, FLIPXY = 5, }; pub const XPS_TILE_MODE_NONE = XPS_TILE_MODE.NONE; pub const XPS_TILE_MODE_TILE = XPS_TILE_MODE.TILE; pub const XPS_TILE_MODE_FLIPX = XPS_TILE_MODE.FLIPX; pub const XPS_TILE_MODE_FLIPY = XPS_TILE_MODE.FLIPY; pub const XPS_TILE_MODE_FLIPXY = XPS_TILE_MODE.FLIPXY; pub const XPS_COLOR_INTERPOLATION = enum(i32) { CRGBLINEAR = 1, RGBLINEAR = 2, }; pub const XPS_COLOR_INTERPOLATION_SCRGBLINEAR = XPS_COLOR_INTERPOLATION.CRGBLINEAR; pub const XPS_COLOR_INTERPOLATION_SRGBLINEAR = XPS_COLOR_INTERPOLATION.RGBLINEAR; pub const XPS_SPREAD_METHOD = enum(i32) { PAD = 1, REFLECT = 2, REPEAT = 3, }; pub const XPS_SPREAD_METHOD_PAD = XPS_SPREAD_METHOD.PAD; pub const XPS_SPREAD_METHOD_REFLECT = XPS_SPREAD_METHOD.REFLECT; pub const XPS_SPREAD_METHOD_REPEAT = XPS_SPREAD_METHOD.REPEAT; pub const XPS_STYLE_SIMULATION = enum(i32) { NONE = 1, ITALIC = 2, BOLD = 3, BOLDITALIC = 4, }; pub const XPS_STYLE_SIMULATION_NONE = XPS_STYLE_SIMULATION.NONE; pub const XPS_STYLE_SIMULATION_ITALIC = XPS_STYLE_SIMULATION.ITALIC; pub const XPS_STYLE_SIMULATION_BOLD = XPS_STYLE_SIMULATION.BOLD; pub const XPS_STYLE_SIMULATION_BOLDITALIC = XPS_STYLE_SIMULATION.BOLDITALIC; pub const XPS_LINE_CAP = enum(i32) { FLAT = 1, ROUND = 2, SQUARE = 3, TRIANGLE = 4, }; pub const XPS_LINE_CAP_FLAT = XPS_LINE_CAP.FLAT; pub const XPS_LINE_CAP_ROUND = XPS_LINE_CAP.ROUND; pub const XPS_LINE_CAP_SQUARE = XPS_LINE_CAP.SQUARE; pub const XPS_LINE_CAP_TRIANGLE = XPS_LINE_CAP.TRIANGLE; pub const XPS_DASH_CAP = enum(i32) { FLAT = 1, ROUND = 2, SQUARE = 3, TRIANGLE = 4, }; pub const XPS_DASH_CAP_FLAT = XPS_DASH_CAP.FLAT; pub const XPS_DASH_CAP_ROUND = XPS_DASH_CAP.ROUND; pub const XPS_DASH_CAP_SQUARE = XPS_DASH_CAP.SQUARE; pub const XPS_DASH_CAP_TRIANGLE = XPS_DASH_CAP.TRIANGLE; pub const XPS_LINE_JOIN = enum(i32) { MITER = 1, BEVEL = 2, ROUND = 3, }; pub const XPS_LINE_JOIN_MITER = XPS_LINE_JOIN.MITER; pub const XPS_LINE_JOIN_BEVEL = XPS_LINE_JOIN.BEVEL; pub const XPS_LINE_JOIN_ROUND = XPS_LINE_JOIN.ROUND; pub const XPS_IMAGE_TYPE = enum(i32) { JPEG = 1, PNG = 2, TIFF = 3, WDP = 4, JXR = 5, }; pub const XPS_IMAGE_TYPE_JPEG = XPS_IMAGE_TYPE.JPEG; pub const XPS_IMAGE_TYPE_PNG = XPS_IMAGE_TYPE.PNG; pub const XPS_IMAGE_TYPE_TIFF = XPS_IMAGE_TYPE.TIFF; pub const XPS_IMAGE_TYPE_WDP = XPS_IMAGE_TYPE.WDP; pub const XPS_IMAGE_TYPE_JXR = XPS_IMAGE_TYPE.JXR; pub const XPS_COLOR_TYPE = enum(i32) { SRGB = 1, SCRGB = 2, CONTEXT = 3, }; pub const XPS_COLOR_TYPE_SRGB = XPS_COLOR_TYPE.SRGB; pub const XPS_COLOR_TYPE_SCRGB = XPS_COLOR_TYPE.SCRGB; pub const XPS_COLOR_TYPE_CONTEXT = XPS_COLOR_TYPE.CONTEXT; pub const XPS_FILL_RULE = enum(i32) { EVENODD = 1, NONZERO = 2, }; pub const XPS_FILL_RULE_EVENODD = XPS_FILL_RULE.EVENODD; pub const XPS_FILL_RULE_NONZERO = XPS_FILL_RULE.NONZERO; pub const XPS_SEGMENT_TYPE = enum(i32) { ARC_LARGE_CLOCKWISE = 1, ARC_LARGE_COUNTERCLOCKWISE = 2, ARC_SMALL_CLOCKWISE = 3, ARC_SMALL_COUNTERCLOCKWISE = 4, BEZIER = 5, LINE = 6, QUADRATIC_BEZIER = 7, }; pub const XPS_SEGMENT_TYPE_ARC_LARGE_CLOCKWISE = XPS_SEGMENT_TYPE.ARC_LARGE_CLOCKWISE; pub const XPS_SEGMENT_TYPE_ARC_LARGE_COUNTERCLOCKWISE = XPS_SEGMENT_TYPE.ARC_LARGE_COUNTERCLOCKWISE; pub const XPS_SEGMENT_TYPE_ARC_SMALL_CLOCKWISE = XPS_SEGMENT_TYPE.ARC_SMALL_CLOCKWISE; pub const XPS_SEGMENT_TYPE_ARC_SMALL_COUNTERCLOCKWISE = XPS_SEGMENT_TYPE.ARC_SMALL_COUNTERCLOCKWISE; pub const XPS_SEGMENT_TYPE_BEZIER = XPS_SEGMENT_TYPE.BEZIER; pub const XPS_SEGMENT_TYPE_LINE = XPS_SEGMENT_TYPE.LINE; pub const XPS_SEGMENT_TYPE_QUADRATIC_BEZIER = XPS_SEGMENT_TYPE.QUADRATIC_BEZIER; pub const XPS_SEGMENT_STROKE_PATTERN = enum(i32) { ALL = 1, NONE = 2, MIXED = 3, }; pub const XPS_SEGMENT_STROKE_PATTERN_ALL = XPS_SEGMENT_STROKE_PATTERN.ALL; pub const XPS_SEGMENT_STROKE_PATTERN_NONE = XPS_SEGMENT_STROKE_PATTERN.NONE; pub const XPS_SEGMENT_STROKE_PATTERN_MIXED = XPS_SEGMENT_STROKE_PATTERN.MIXED; pub const XPS_FONT_EMBEDDING = enum(i32) { NORMAL = 1, OBFUSCATED = 2, RESTRICTED = 3, RESTRICTED_UNOBFUSCATED = 4, }; pub const XPS_FONT_EMBEDDING_NORMAL = XPS_FONT_EMBEDDING.NORMAL; pub const XPS_FONT_EMBEDDING_OBFUSCATED = XPS_FONT_EMBEDDING.OBFUSCATED; pub const XPS_FONT_EMBEDDING_RESTRICTED = XPS_FONT_EMBEDDING.RESTRICTED; pub const XPS_FONT_EMBEDDING_RESTRICTED_UNOBFUSCATED = XPS_FONT_EMBEDDING.RESTRICTED_UNOBFUSCATED; pub const XPS_OBJECT_TYPE = enum(i32) { CANVAS = 1, GLYPHS = 2, PATH = 3, MATRIX_TRANSFORM = 4, GEOMETRY = 5, SOLID_COLOR_BRUSH = 6, IMAGE_BRUSH = 7, LINEAR_GRADIENT_BRUSH = 8, RADIAL_GRADIENT_BRUSH = 9, VISUAL_BRUSH = 10, }; pub const XPS_OBJECT_TYPE_CANVAS = XPS_OBJECT_TYPE.CANVAS; pub const XPS_OBJECT_TYPE_GLYPHS = XPS_OBJECT_TYPE.GLYPHS; pub const XPS_OBJECT_TYPE_PATH = XPS_OBJECT_TYPE.PATH; pub const XPS_OBJECT_TYPE_MATRIX_TRANSFORM = XPS_OBJECT_TYPE.MATRIX_TRANSFORM; pub const XPS_OBJECT_TYPE_GEOMETRY = XPS_OBJECT_TYPE.GEOMETRY; pub const XPS_OBJECT_TYPE_SOLID_COLOR_BRUSH = XPS_OBJECT_TYPE.SOLID_COLOR_BRUSH; pub const XPS_OBJECT_TYPE_IMAGE_BRUSH = XPS_OBJECT_TYPE.IMAGE_BRUSH; pub const XPS_OBJECT_TYPE_LINEAR_GRADIENT_BRUSH = XPS_OBJECT_TYPE.LINEAR_GRADIENT_BRUSH; pub const XPS_OBJECT_TYPE_RADIAL_GRADIENT_BRUSH = XPS_OBJECT_TYPE.RADIAL_GRADIENT_BRUSH; pub const XPS_OBJECT_TYPE_VISUAL_BRUSH = XPS_OBJECT_TYPE.VISUAL_BRUSH; pub const XPS_THUMBNAIL_SIZE = enum(i32) { VERYSMALL = 1, SMALL = 2, MEDIUM = 3, LARGE = 4, }; pub const XPS_THUMBNAIL_SIZE_VERYSMALL = XPS_THUMBNAIL_SIZE.VERYSMALL; pub const XPS_THUMBNAIL_SIZE_SMALL = XPS_THUMBNAIL_SIZE.SMALL; pub const XPS_THUMBNAIL_SIZE_MEDIUM = XPS_THUMBNAIL_SIZE.MEDIUM; pub const XPS_THUMBNAIL_SIZE_LARGE = XPS_THUMBNAIL_SIZE.LARGE; pub const XPS_INTERLEAVING = enum(i32) { FF = 1, N = 2, }; pub const XPS_INTERLEAVING_OFF = XPS_INTERLEAVING.FF; pub const XPS_INTERLEAVING_ON = XPS_INTERLEAVING.N; pub const XPS_POINT = extern struct { x: f32, y: f32, }; pub const XPS_SIZE = extern struct { width: f32, height: f32, }; pub const XPS_RECT = extern struct { x: f32, y: f32, width: f32, height: f32, }; pub const XPS_DASH = extern struct { length: f32, gap: f32, }; pub const XPS_GLYPH_INDEX = extern struct { index: i32, advanceWidth: f32, horizontalOffset: f32, verticalOffset: f32, }; pub const XPS_GLYPH_MAPPING = extern struct { unicodeStringStart: u32, unicodeStringLength: u16, glyphIndicesStart: u32, glyphIndicesLength: u16, }; pub const XPS_MATRIX = extern struct { m11: f32, m12: f32, m21: f32, m22: f32, m31: f32, m32: f32, }; pub const XPS_COLOR = extern struct { pub const XPS_COLOR_VALUE = extern union { sRGB: extern struct { alpha: u8, red: u8, green: u8, blue: u8, }, scRGB: extern struct { alpha: f32, red: f32, green: f32, blue: f32, }, context: extern struct { channelCount: u8, channels: [9]f32, }, }; colorType: XPS_COLOR_TYPE, value: XPS_COLOR_VALUE, }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMShareable_Value = Guid.initString("7137398f-2fc1-454d-8c6a-2c3115a16ece"); pub const IID_IXpsOMShareable = &IID_IXpsOMShareable_Value; pub const IXpsOMShareable = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwner: fn( self: *const IXpsOMShareable, owner: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetType: fn( self: *const IXpsOMShareable, type: ?*XPS_OBJECT_TYPE, ) 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 IXpsOMShareable_GetOwner(self: *const T, owner: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMShareable.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMShareable, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMShareable_GetType(self: *const T, type_: ?*XPS_OBJECT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMShareable.VTable, self.vtable).GetType(@ptrCast(*const IXpsOMShareable, self), type_); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMVisual_Value = Guid.initString("bc3e7333-fb0b-4af3-a819-0b4eaad0d2fd"); pub const IID_IXpsOMVisual = &IID_IXpsOMVisual_Value; pub const IXpsOMVisual = extern struct { pub const VTable = extern struct { base: IXpsOMShareable.VTable, GetTransform: fn( self: *const IXpsOMVisual, matrixTransform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLocal: fn( self: *const IXpsOMVisual, matrixTransform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLocal: fn( self: *const IXpsOMVisual, matrixTransform: ?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLookup: fn( self: *const IXpsOMVisual, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLookup: fn( self: *const IXpsOMVisual, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipGeometry: fn( self: *const IXpsOMVisual, clipGeometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipGeometryLocal: fn( self: *const IXpsOMVisual, clipGeometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipGeometryLocal: fn( self: *const IXpsOMVisual, clipGeometry: ?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipGeometryLookup: fn( self: *const IXpsOMVisual, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipGeometryLookup: fn( self: *const IXpsOMVisual, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOpacity: fn( self: *const IXpsOMVisual, opacity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOpacity: fn( self: *const IXpsOMVisual, opacity: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOpacityMaskBrush: fn( self: *const IXpsOMVisual, opacityMaskBrush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOpacityMaskBrushLocal: fn( self: *const IXpsOMVisual, opacityMaskBrush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOpacityMaskBrushLocal: fn( self: *const IXpsOMVisual, opacityMaskBrush: ?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOpacityMaskBrushLookup: fn( self: *const IXpsOMVisual, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOpacityMaskBrushLookup: fn( self: *const IXpsOMVisual, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetName: fn( self: *const IXpsOMVisual, name: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const IXpsOMVisual, name: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsHyperlinkTarget: fn( self: *const IXpsOMVisual, isHyperlink: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIsHyperlinkTarget: fn( self: *const IXpsOMVisual, isHyperlink: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHyperlinkNavigateUri: fn( self: *const IXpsOMVisual, hyperlinkUri: ?*?*IUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHyperlinkNavigateUri: fn( self: *const IXpsOMVisual, hyperlinkUri: ?*IUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguage: fn( self: *const IXpsOMVisual, language: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLanguage: fn( self: *const IXpsOMVisual, language: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMShareable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetTransform(self: *const T, matrixTransform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetTransform(@ptrCast(*const IXpsOMVisual, self), matrixTransform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetTransformLocal(self: *const T, matrixTransform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetTransformLocal(@ptrCast(*const IXpsOMVisual, self), matrixTransform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetTransformLocal(self: *const T, matrixTransform: ?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetTransformLocal(@ptrCast(*const IXpsOMVisual, self), matrixTransform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetTransformLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetTransformLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetTransformLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetTransformLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetClipGeometry(self: *const T, clipGeometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetClipGeometry(@ptrCast(*const IXpsOMVisual, self), clipGeometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetClipGeometryLocal(self: *const T, clipGeometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetClipGeometryLocal(@ptrCast(*const IXpsOMVisual, self), clipGeometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetClipGeometryLocal(self: *const T, clipGeometry: ?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetClipGeometryLocal(@ptrCast(*const IXpsOMVisual, self), clipGeometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetClipGeometryLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetClipGeometryLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetClipGeometryLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetClipGeometryLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetOpacity(self: *const T, opacity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetOpacity(@ptrCast(*const IXpsOMVisual, self), opacity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetOpacity(self: *const T, opacity: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetOpacity(@ptrCast(*const IXpsOMVisual, self), opacity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetOpacityMaskBrush(self: *const T, opacityMaskBrush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetOpacityMaskBrush(@ptrCast(*const IXpsOMVisual, self), opacityMaskBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetOpacityMaskBrushLocal(self: *const T, opacityMaskBrush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetOpacityMaskBrushLocal(@ptrCast(*const IXpsOMVisual, self), opacityMaskBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetOpacityMaskBrushLocal(self: *const T, opacityMaskBrush: ?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetOpacityMaskBrushLocal(@ptrCast(*const IXpsOMVisual, self), opacityMaskBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetOpacityMaskBrushLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetOpacityMaskBrushLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetOpacityMaskBrushLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetOpacityMaskBrushLookup(@ptrCast(*const IXpsOMVisual, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetName(self: *const T, name: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetName(@ptrCast(*const IXpsOMVisual, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetName(self: *const T, name: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetName(@ptrCast(*const IXpsOMVisual, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetIsHyperlinkTarget(self: *const T, isHyperlink: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetIsHyperlinkTarget(@ptrCast(*const IXpsOMVisual, self), isHyperlink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetIsHyperlinkTarget(self: *const T, isHyperlink: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetIsHyperlinkTarget(@ptrCast(*const IXpsOMVisual, self), isHyperlink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetHyperlinkNavigateUri(self: *const T, hyperlinkUri: ?*?*IUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetHyperlinkNavigateUri(@ptrCast(*const IXpsOMVisual, self), hyperlinkUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetHyperlinkNavigateUri(self: *const T, hyperlinkUri: ?*IUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetHyperlinkNavigateUri(@ptrCast(*const IXpsOMVisual, self), hyperlinkUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_GetLanguage(self: *const T, language: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).GetLanguage(@ptrCast(*const IXpsOMVisual, self), language); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisual_SetLanguage(self: *const T, language: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisual.VTable, self.vtable).SetLanguage(@ptrCast(*const IXpsOMVisual, self), language); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPart_Value = Guid.initString("74eb2f0b-a91e-4486-afac-0fabeca3dfc6"); pub const IID_IXpsOMPart = &IID_IXpsOMPart_Value; pub const IXpsOMPart = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetPartName: fn( self: *const IXpsOMPart, partUri: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPartName: fn( self: *const IXpsOMPart, partUri: ?*IOpcPartUri, ) 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 IXpsOMPart_GetPartName(self: *const T, partUri: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPart.VTable, self.vtable).GetPartName(@ptrCast(*const IXpsOMPart, self), partUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPart_SetPartName(self: *const T, partUri: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPart.VTable, self.vtable).SetPartName(@ptrCast(*const IXpsOMPart, self), partUri); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGlyphsEditor_Value = Guid.initString("a5ab8616-5b16-4b9f-9629-89b323ed7909"); pub const IID_IXpsOMGlyphsEditor = &IID_IXpsOMGlyphsEditor_Value; pub const IXpsOMGlyphsEditor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ApplyEdits: fn( self: *const IXpsOMGlyphsEditor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUnicodeString: fn( self: *const IXpsOMGlyphsEditor, unicodeString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUnicodeString: fn( self: *const IXpsOMGlyphsEditor, unicodeString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphIndexCount: fn( self: *const IXpsOMGlyphsEditor, indexCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphIndices: fn( self: *const IXpsOMGlyphsEditor, indexCount: ?*u32, glyphIndices: ?*XPS_GLYPH_INDEX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGlyphIndices: fn( self: *const IXpsOMGlyphsEditor, indexCount: u32, glyphIndices: ?*const XPS_GLYPH_INDEX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphMappingCount: fn( self: *const IXpsOMGlyphsEditor, glyphMappingCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphMappings: fn( self: *const IXpsOMGlyphsEditor, glyphMappingCount: ?*u32, glyphMappings: ?*XPS_GLYPH_MAPPING, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGlyphMappings: fn( self: *const IXpsOMGlyphsEditor, glyphMappingCount: u32, glyphMappings: ?*const XPS_GLYPH_MAPPING, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProhibitedCaretStopCount: fn( self: *const IXpsOMGlyphsEditor, prohibitedCaretStopCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProhibitedCaretStops: fn( self: *const IXpsOMGlyphsEditor, count: ?*u32, prohibitedCaretStops: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProhibitedCaretStops: fn( self: *const IXpsOMGlyphsEditor, count: u32, prohibitedCaretStops: ?*const u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBidiLevel: fn( self: *const IXpsOMGlyphsEditor, bidiLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBidiLevel: fn( self: *const IXpsOMGlyphsEditor, bidiLevel: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsSideways: fn( self: *const IXpsOMGlyphsEditor, isSideways: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIsSideways: fn( self: *const IXpsOMGlyphsEditor, isSideways: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceFontName: fn( self: *const IXpsOMGlyphsEditor, deviceFontName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDeviceFontName: fn( self: *const IXpsOMGlyphsEditor, deviceFontName: ?[*:0]const 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 IXpsOMGlyphsEditor_ApplyEdits(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).ApplyEdits(@ptrCast(*const IXpsOMGlyphsEditor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetUnicodeString(self: *const T, unicodeString: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetUnicodeString(@ptrCast(*const IXpsOMGlyphsEditor, self), unicodeString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetUnicodeString(self: *const T, unicodeString: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetUnicodeString(@ptrCast(*const IXpsOMGlyphsEditor, self), unicodeString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetGlyphIndexCount(self: *const T, indexCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetGlyphIndexCount(@ptrCast(*const IXpsOMGlyphsEditor, self), indexCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetGlyphIndices(self: *const T, indexCount: ?*u32, glyphIndices: ?*XPS_GLYPH_INDEX) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetGlyphIndices(@ptrCast(*const IXpsOMGlyphsEditor, self), indexCount, glyphIndices); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetGlyphIndices(self: *const T, indexCount: u32, glyphIndices: ?*const XPS_GLYPH_INDEX) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetGlyphIndices(@ptrCast(*const IXpsOMGlyphsEditor, self), indexCount, glyphIndices); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetGlyphMappingCount(self: *const T, glyphMappingCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetGlyphMappingCount(@ptrCast(*const IXpsOMGlyphsEditor, self), glyphMappingCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetGlyphMappings(self: *const T, glyphMappingCount: ?*u32, glyphMappings: ?*XPS_GLYPH_MAPPING) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetGlyphMappings(@ptrCast(*const IXpsOMGlyphsEditor, self), glyphMappingCount, glyphMappings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetGlyphMappings(self: *const T, glyphMappingCount: u32, glyphMappings: ?*const XPS_GLYPH_MAPPING) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetGlyphMappings(@ptrCast(*const IXpsOMGlyphsEditor, self), glyphMappingCount, glyphMappings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetProhibitedCaretStopCount(self: *const T, prohibitedCaretStopCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetProhibitedCaretStopCount(@ptrCast(*const IXpsOMGlyphsEditor, self), prohibitedCaretStopCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetProhibitedCaretStops(self: *const T, count: ?*u32, prohibitedCaretStops: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetProhibitedCaretStops(@ptrCast(*const IXpsOMGlyphsEditor, self), count, prohibitedCaretStops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetProhibitedCaretStops(self: *const T, count: u32, prohibitedCaretStops: ?*const u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetProhibitedCaretStops(@ptrCast(*const IXpsOMGlyphsEditor, self), count, prohibitedCaretStops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetBidiLevel(self: *const T, bidiLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetBidiLevel(@ptrCast(*const IXpsOMGlyphsEditor, self), bidiLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetBidiLevel(self: *const T, bidiLevel: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetBidiLevel(@ptrCast(*const IXpsOMGlyphsEditor, self), bidiLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetIsSideways(self: *const T, isSideways: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetIsSideways(@ptrCast(*const IXpsOMGlyphsEditor, self), isSideways); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetIsSideways(self: *const T, isSideways: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetIsSideways(@ptrCast(*const IXpsOMGlyphsEditor, self), isSideways); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_GetDeviceFontName(self: *const T, deviceFontName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).GetDeviceFontName(@ptrCast(*const IXpsOMGlyphsEditor, self), deviceFontName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphsEditor_SetDeviceFontName(self: *const T, deviceFontName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphsEditor.VTable, self.vtable).SetDeviceFontName(@ptrCast(*const IXpsOMGlyphsEditor, self), deviceFontName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGlyphs_Value = Guid.initString("819b3199-0a5a-4b64-bec7-a9e17e780de2"); pub const IID_IXpsOMGlyphs = &IID_IXpsOMGlyphs_Value; pub const IXpsOMGlyphs = extern struct { pub const VTable = extern struct { base: IXpsOMVisual.VTable, GetUnicodeString: fn( self: *const IXpsOMGlyphs, unicodeString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphIndexCount: fn( self: *const IXpsOMGlyphs, indexCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphIndices: fn( self: *const IXpsOMGlyphs, indexCount: ?*u32, glyphIndices: ?*XPS_GLYPH_INDEX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphMappingCount: fn( self: *const IXpsOMGlyphs, glyphMappingCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphMappings: fn( self: *const IXpsOMGlyphs, glyphMappingCount: ?*u32, glyphMappings: ?*XPS_GLYPH_MAPPING, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProhibitedCaretStopCount: fn( self: *const IXpsOMGlyphs, prohibitedCaretStopCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProhibitedCaretStops: fn( self: *const IXpsOMGlyphs, prohibitedCaretStopCount: ?*u32, prohibitedCaretStops: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBidiLevel: fn( self: *const IXpsOMGlyphs, bidiLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsSideways: fn( self: *const IXpsOMGlyphs, isSideways: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceFontName: fn( self: *const IXpsOMGlyphs, deviceFontName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStyleSimulations: fn( self: *const IXpsOMGlyphs, styleSimulations: ?*XPS_STYLE_SIMULATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStyleSimulations: fn( self: *const IXpsOMGlyphs, styleSimulations: XPS_STYLE_SIMULATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOrigin: fn( self: *const IXpsOMGlyphs, origin: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOrigin: fn( self: *const IXpsOMGlyphs, origin: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFontRenderingEmSize: fn( self: *const IXpsOMGlyphs, fontRenderingEmSize: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFontRenderingEmSize: fn( self: *const IXpsOMGlyphs, fontRenderingEmSize: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFontResource: fn( self: *const IXpsOMGlyphs, fontResource: ?*?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFontResource: fn( self: *const IXpsOMGlyphs, fontResource: ?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFontFaceIndex: fn( self: *const IXpsOMGlyphs, fontFaceIndex: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFontFaceIndex: fn( self: *const IXpsOMGlyphs, fontFaceIndex: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrush: fn( self: *const IXpsOMGlyphs, fillBrush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrushLocal: fn( self: *const IXpsOMGlyphs, fillBrush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFillBrushLocal: fn( self: *const IXpsOMGlyphs, fillBrush: ?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrushLookup: fn( self: *const IXpsOMGlyphs, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFillBrushLookup: fn( self: *const IXpsOMGlyphs, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlyphsEditor: fn( self: *const IXpsOMGlyphs, editor: ?*?*IXpsOMGlyphsEditor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMGlyphs, glyphs: ?*?*IXpsOMGlyphs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMVisual.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetUnicodeString(self: *const T, unicodeString: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetUnicodeString(@ptrCast(*const IXpsOMGlyphs, self), unicodeString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetGlyphIndexCount(self: *const T, indexCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetGlyphIndexCount(@ptrCast(*const IXpsOMGlyphs, self), indexCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetGlyphIndices(self: *const T, indexCount: ?*u32, glyphIndices: ?*XPS_GLYPH_INDEX) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetGlyphIndices(@ptrCast(*const IXpsOMGlyphs, self), indexCount, glyphIndices); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetGlyphMappingCount(self: *const T, glyphMappingCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetGlyphMappingCount(@ptrCast(*const IXpsOMGlyphs, self), glyphMappingCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetGlyphMappings(self: *const T, glyphMappingCount: ?*u32, glyphMappings: ?*XPS_GLYPH_MAPPING) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetGlyphMappings(@ptrCast(*const IXpsOMGlyphs, self), glyphMappingCount, glyphMappings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetProhibitedCaretStopCount(self: *const T, prohibitedCaretStopCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetProhibitedCaretStopCount(@ptrCast(*const IXpsOMGlyphs, self), prohibitedCaretStopCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetProhibitedCaretStops(self: *const T, prohibitedCaretStopCount: ?*u32, prohibitedCaretStops: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetProhibitedCaretStops(@ptrCast(*const IXpsOMGlyphs, self), prohibitedCaretStopCount, prohibitedCaretStops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetBidiLevel(self: *const T, bidiLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetBidiLevel(@ptrCast(*const IXpsOMGlyphs, self), bidiLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetIsSideways(self: *const T, isSideways: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetIsSideways(@ptrCast(*const IXpsOMGlyphs, self), isSideways); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetDeviceFontName(self: *const T, deviceFontName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetDeviceFontName(@ptrCast(*const IXpsOMGlyphs, self), deviceFontName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetStyleSimulations(self: *const T, styleSimulations: ?*XPS_STYLE_SIMULATION) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetStyleSimulations(@ptrCast(*const IXpsOMGlyphs, self), styleSimulations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetStyleSimulations(self: *const T, styleSimulations: XPS_STYLE_SIMULATION) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetStyleSimulations(@ptrCast(*const IXpsOMGlyphs, self), styleSimulations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetOrigin(self: *const T, origin: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetOrigin(@ptrCast(*const IXpsOMGlyphs, self), origin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetOrigin(self: *const T, origin: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetOrigin(@ptrCast(*const IXpsOMGlyphs, self), origin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFontRenderingEmSize(self: *const T, fontRenderingEmSize: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFontRenderingEmSize(@ptrCast(*const IXpsOMGlyphs, self), fontRenderingEmSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetFontRenderingEmSize(self: *const T, fontRenderingEmSize: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetFontRenderingEmSize(@ptrCast(*const IXpsOMGlyphs, self), fontRenderingEmSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFontResource(self: *const T, fontResource: ?*?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFontResource(@ptrCast(*const IXpsOMGlyphs, self), fontResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetFontResource(self: *const T, fontResource: ?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetFontResource(@ptrCast(*const IXpsOMGlyphs, self), fontResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFontFaceIndex(self: *const T, fontFaceIndex: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFontFaceIndex(@ptrCast(*const IXpsOMGlyphs, self), fontFaceIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetFontFaceIndex(self: *const T, fontFaceIndex: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetFontFaceIndex(@ptrCast(*const IXpsOMGlyphs, self), fontFaceIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFillBrush(self: *const T, fillBrush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFillBrush(@ptrCast(*const IXpsOMGlyphs, self), fillBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFillBrushLocal(self: *const T, fillBrush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFillBrushLocal(@ptrCast(*const IXpsOMGlyphs, self), fillBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetFillBrushLocal(self: *const T, fillBrush: ?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetFillBrushLocal(@ptrCast(*const IXpsOMGlyphs, self), fillBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetFillBrushLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetFillBrushLookup(@ptrCast(*const IXpsOMGlyphs, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_SetFillBrushLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).SetFillBrushLookup(@ptrCast(*const IXpsOMGlyphs, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_GetGlyphsEditor(self: *const T, editor: ?*?*IXpsOMGlyphsEditor) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).GetGlyphsEditor(@ptrCast(*const IXpsOMGlyphs, self), editor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGlyphs_Clone(self: *const T, glyphs: ?*?*IXpsOMGlyphs) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGlyphs.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMGlyphs, self), glyphs); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDashCollection_Value = Guid.initString("081613f4-74eb-48f2-83b3-37a9ce2d7dc6"); pub const IID_IXpsOMDashCollection = &IID_IXpsOMDashCollection_Value; pub const IXpsOMDashCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMDashCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMDashCollection, index: u32, dash: ?*XPS_DASH, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMDashCollection, index: u32, dash: ?*const XPS_DASH, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMDashCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMDashCollection, index: u32, dash: ?*const XPS_DASH, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMDashCollection, dash: ?*const XPS_DASH, ) 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 IXpsOMDashCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMDashCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDashCollection_GetAt(self: *const T, index: u32, dash: ?*XPS_DASH) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMDashCollection, self), index, dash); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDashCollection_InsertAt(self: *const T, index: u32, dash: ?*const XPS_DASH) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMDashCollection, self), index, dash); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDashCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMDashCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDashCollection_SetAt(self: *const T, index: u32, dash: ?*const XPS_DASH) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMDashCollection, self), index, dash); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDashCollection_Append(self: *const T, dash: ?*const XPS_DASH) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDashCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMDashCollection, self), dash); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMMatrixTransform_Value = Guid.initString("b77330ff-bb37-4501-a93e-f1b1e50bfc46"); pub const IID_IXpsOMMatrixTransform = &IID_IXpsOMMatrixTransform_Value; pub const IXpsOMMatrixTransform = extern struct { pub const VTable = extern struct { base: IXpsOMShareable.VTable, GetMatrix: fn( self: *const IXpsOMMatrixTransform, matrix: ?*XPS_MATRIX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMatrix: fn( self: *const IXpsOMMatrixTransform, matrix: ?*const XPS_MATRIX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMMatrixTransform, matrixTransform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMShareable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMMatrixTransform_GetMatrix(self: *const T, matrix: ?*XPS_MATRIX) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMMatrixTransform.VTable, self.vtable).GetMatrix(@ptrCast(*const IXpsOMMatrixTransform, self), matrix); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMMatrixTransform_SetMatrix(self: *const T, matrix: ?*const XPS_MATRIX) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMMatrixTransform.VTable, self.vtable).SetMatrix(@ptrCast(*const IXpsOMMatrixTransform, self), matrix); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMMatrixTransform_Clone(self: *const T, matrixTransform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMMatrixTransform.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMMatrixTransform, self), matrixTransform); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGeometry_Value = Guid.initString("64fcf3d7-4d58-44ba-ad73-a13af6492072"); pub const IID_IXpsOMGeometry = &IID_IXpsOMGeometry_Value; pub const IXpsOMGeometry = extern struct { pub const VTable = extern struct { base: IXpsOMShareable.VTable, GetFigures: fn( self: *const IXpsOMGeometry, figures: ?*?*IXpsOMGeometryFigureCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillRule: fn( self: *const IXpsOMGeometry, fillRule: ?*XPS_FILL_RULE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFillRule: fn( self: *const IXpsOMGeometry, fillRule: XPS_FILL_RULE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransform: fn( self: *const IXpsOMGeometry, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLocal: fn( self: *const IXpsOMGeometry, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLocal: fn( self: *const IXpsOMGeometry, transform: ?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLookup: fn( self: *const IXpsOMGeometry, lookup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLookup: fn( self: *const IXpsOMGeometry, lookup: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMGeometry, geometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMShareable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_GetFigures(self: *const T, figures: ?*?*IXpsOMGeometryFigureCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).GetFigures(@ptrCast(*const IXpsOMGeometry, self), figures); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_GetFillRule(self: *const T, fillRule: ?*XPS_FILL_RULE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).GetFillRule(@ptrCast(*const IXpsOMGeometry, self), fillRule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_SetFillRule(self: *const T, fillRule: XPS_FILL_RULE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).SetFillRule(@ptrCast(*const IXpsOMGeometry, self), fillRule); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_GetTransform(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).GetTransform(@ptrCast(*const IXpsOMGeometry, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_GetTransformLocal(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).GetTransformLocal(@ptrCast(*const IXpsOMGeometry, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_SetTransformLocal(self: *const T, transform: ?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).SetTransformLocal(@ptrCast(*const IXpsOMGeometry, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_GetTransformLookup(self: *const T, lookup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).GetTransformLookup(@ptrCast(*const IXpsOMGeometry, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_SetTransformLookup(self: *const T, lookup: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).SetTransformLookup(@ptrCast(*const IXpsOMGeometry, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometry_Clone(self: *const T, geometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometry.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMGeometry, self), geometry); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGeometryFigure_Value = Guid.initString("d410dc83-908c-443e-8947-b1795d3c165a"); pub const IID_IXpsOMGeometryFigure = &IID_IXpsOMGeometryFigure_Value; pub const IXpsOMGeometryFigure = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwner: fn( self: *const IXpsOMGeometryFigure, owner: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentData: fn( self: *const IXpsOMGeometryFigure, dataCount: ?*u32, segmentData: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentTypes: fn( self: *const IXpsOMGeometryFigure, segmentCount: ?*u32, segmentTypes: ?*XPS_SEGMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentStrokes: fn( self: *const IXpsOMGeometryFigure, segmentCount: ?*u32, segmentStrokes: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSegments: fn( self: *const IXpsOMGeometryFigure, segmentCount: u32, segmentDataCount: u32, segmentTypes: ?*const XPS_SEGMENT_TYPE, segmentData: ?*const f32, segmentStrokes: ?*const BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStartPoint: fn( self: *const IXpsOMGeometryFigure, startPoint: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStartPoint: fn( self: *const IXpsOMGeometryFigure, startPoint: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsClosed: fn( self: *const IXpsOMGeometryFigure, isClosed: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIsClosed: fn( self: *const IXpsOMGeometryFigure, isClosed: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsFilled: fn( self: *const IXpsOMGeometryFigure, isFilled: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIsFilled: fn( self: *const IXpsOMGeometryFigure, isFilled: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentCount: fn( self: *const IXpsOMGeometryFigure, segmentCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentDataCount: fn( self: *const IXpsOMGeometryFigure, segmentDataCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSegmentStrokePattern: fn( self: *const IXpsOMGeometryFigure, segmentStrokePattern: ?*XPS_SEGMENT_STROKE_PATTERN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMGeometryFigure, geometryFigure: ?*?*IXpsOMGeometryFigure, ) 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 IXpsOMGeometryFigure_GetOwner(self: *const T, owner: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMGeometryFigure, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentData(self: *const T, dataCount: ?*u32, segmentData: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentData(@ptrCast(*const IXpsOMGeometryFigure, self), dataCount, segmentData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentTypes(self: *const T, segmentCount: ?*u32, segmentTypes: ?*XPS_SEGMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentTypes(@ptrCast(*const IXpsOMGeometryFigure, self), segmentCount, segmentTypes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentStrokes(self: *const T, segmentCount: ?*u32, segmentStrokes: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentStrokes(@ptrCast(*const IXpsOMGeometryFigure, self), segmentCount, segmentStrokes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_SetSegments(self: *const T, segmentCount: u32, segmentDataCount: u32, segmentTypes: ?*const XPS_SEGMENT_TYPE, segmentData: ?*const f32, segmentStrokes: ?*const BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).SetSegments(@ptrCast(*const IXpsOMGeometryFigure, self), segmentCount, segmentDataCount, segmentTypes, segmentData, segmentStrokes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetStartPoint(self: *const T, startPoint: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetStartPoint(@ptrCast(*const IXpsOMGeometryFigure, self), startPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_SetStartPoint(self: *const T, startPoint: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).SetStartPoint(@ptrCast(*const IXpsOMGeometryFigure, self), startPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetIsClosed(self: *const T, isClosed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetIsClosed(@ptrCast(*const IXpsOMGeometryFigure, self), isClosed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_SetIsClosed(self: *const T, isClosed: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).SetIsClosed(@ptrCast(*const IXpsOMGeometryFigure, self), isClosed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetIsFilled(self: *const T, isFilled: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetIsFilled(@ptrCast(*const IXpsOMGeometryFigure, self), isFilled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_SetIsFilled(self: *const T, isFilled: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).SetIsFilled(@ptrCast(*const IXpsOMGeometryFigure, self), isFilled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentCount(self: *const T, segmentCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentCount(@ptrCast(*const IXpsOMGeometryFigure, self), segmentCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentDataCount(self: *const T, segmentDataCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentDataCount(@ptrCast(*const IXpsOMGeometryFigure, self), segmentDataCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_GetSegmentStrokePattern(self: *const T, segmentStrokePattern: ?*XPS_SEGMENT_STROKE_PATTERN) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).GetSegmentStrokePattern(@ptrCast(*const IXpsOMGeometryFigure, self), segmentStrokePattern); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigure_Clone(self: *const T, geometryFigure: ?*?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigure.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMGeometryFigure, self), geometryFigure); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGeometryFigureCollection_Value = Guid.initString("fd48c3f3-a58e-4b5a-8826-1de54abe72b2"); pub const IID_IXpsOMGeometryFigureCollection = &IID_IXpsOMGeometryFigureCollection_Value; pub const IXpsOMGeometryFigureCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMGeometryFigureCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMGeometryFigureCollection, index: u32, geometryFigure: ?*?*IXpsOMGeometryFigure, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMGeometryFigureCollection, index: u32, geometryFigure: ?*IXpsOMGeometryFigure, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMGeometryFigureCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMGeometryFigureCollection, index: u32, geometryFigure: ?*IXpsOMGeometryFigure, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMGeometryFigureCollection, geometryFigure: ?*IXpsOMGeometryFigure, ) 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 IXpsOMGeometryFigureCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMGeometryFigureCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigureCollection_GetAt(self: *const T, index: u32, geometryFigure: ?*?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMGeometryFigureCollection, self), index, geometryFigure); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigureCollection_InsertAt(self: *const T, index: u32, geometryFigure: ?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMGeometryFigureCollection, self), index, geometryFigure); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigureCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMGeometryFigureCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigureCollection_SetAt(self: *const T, index: u32, geometryFigure: ?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMGeometryFigureCollection, self), index, geometryFigure); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGeometryFigureCollection_Append(self: *const T, geometryFigure: ?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGeometryFigureCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMGeometryFigureCollection, self), geometryFigure); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPath_Value = Guid.initString("37d38bb6-3ee9-4110-9312-14b194163337"); pub const IID_IXpsOMPath = &IID_IXpsOMPath_Value; pub const IXpsOMPath = extern struct { pub const VTable = extern struct { base: IXpsOMVisual.VTable, GetGeometry: fn( self: *const IXpsOMPath, geometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGeometryLocal: fn( self: *const IXpsOMPath, geometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGeometryLocal: fn( self: *const IXpsOMPath, geometry: ?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGeometryLookup: fn( self: *const IXpsOMPath, lookup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGeometryLookup: fn( self: *const IXpsOMPath, lookup: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAccessibilityShortDescription: fn( self: *const IXpsOMPath, shortDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAccessibilityShortDescription: fn( self: *const IXpsOMPath, shortDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAccessibilityLongDescription: fn( self: *const IXpsOMPath, longDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAccessibilityLongDescription: fn( self: *const IXpsOMPath, longDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSnapsToPixels: fn( self: *const IXpsOMPath, snapsToPixels: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSnapsToPixels: fn( self: *const IXpsOMPath, snapsToPixels: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeBrush: fn( self: *const IXpsOMPath, brush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeBrushLocal: fn( self: *const IXpsOMPath, brush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeBrushLocal: fn( self: *const IXpsOMPath, brush: ?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeBrushLookup: fn( self: *const IXpsOMPath, lookup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeBrushLookup: fn( self: *const IXpsOMPath, lookup: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeDashes: fn( self: *const IXpsOMPath, strokeDashes: ?*?*IXpsOMDashCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeDashCap: fn( self: *const IXpsOMPath, strokeDashCap: ?*XPS_DASH_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeDashCap: fn( self: *const IXpsOMPath, strokeDashCap: XPS_DASH_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeDashOffset: fn( self: *const IXpsOMPath, strokeDashOffset: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeDashOffset: fn( self: *const IXpsOMPath, strokeDashOffset: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeStartLineCap: fn( self: *const IXpsOMPath, strokeStartLineCap: ?*XPS_LINE_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeStartLineCap: fn( self: *const IXpsOMPath, strokeStartLineCap: XPS_LINE_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeEndLineCap: fn( self: *const IXpsOMPath, strokeEndLineCap: ?*XPS_LINE_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeEndLineCap: fn( self: *const IXpsOMPath, strokeEndLineCap: XPS_LINE_CAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeLineJoin: fn( self: *const IXpsOMPath, strokeLineJoin: ?*XPS_LINE_JOIN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeLineJoin: fn( self: *const IXpsOMPath, strokeLineJoin: XPS_LINE_JOIN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeMiterLimit: fn( self: *const IXpsOMPath, strokeMiterLimit: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeMiterLimit: fn( self: *const IXpsOMPath, strokeMiterLimit: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStrokeThickness: fn( self: *const IXpsOMPath, strokeThickness: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStrokeThickness: fn( self: *const IXpsOMPath, strokeThickness: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrush: fn( self: *const IXpsOMPath, brush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrushLocal: fn( self: *const IXpsOMPath, brush: ?*?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFillBrushLocal: fn( self: *const IXpsOMPath, brush: ?*IXpsOMBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFillBrushLookup: fn( self: *const IXpsOMPath, lookup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFillBrushLookup: fn( self: *const IXpsOMPath, lookup: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMPath, path: ?*?*IXpsOMPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMVisual.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetGeometry(self: *const T, geometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetGeometry(@ptrCast(*const IXpsOMPath, self), geometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetGeometryLocal(self: *const T, geometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetGeometryLocal(@ptrCast(*const IXpsOMPath, self), geometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetGeometryLocal(self: *const T, geometry: ?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetGeometryLocal(@ptrCast(*const IXpsOMPath, self), geometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetGeometryLookup(self: *const T, lookup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetGeometryLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetGeometryLookup(self: *const T, lookup: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetGeometryLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetAccessibilityShortDescription(self: *const T, shortDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetAccessibilityShortDescription(@ptrCast(*const IXpsOMPath, self), shortDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetAccessibilityShortDescription(self: *const T, shortDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetAccessibilityShortDescription(@ptrCast(*const IXpsOMPath, self), shortDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetAccessibilityLongDescription(self: *const T, longDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetAccessibilityLongDescription(@ptrCast(*const IXpsOMPath, self), longDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetAccessibilityLongDescription(self: *const T, longDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetAccessibilityLongDescription(@ptrCast(*const IXpsOMPath, self), longDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetSnapsToPixels(self: *const T, snapsToPixels: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetSnapsToPixels(@ptrCast(*const IXpsOMPath, self), snapsToPixels); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetSnapsToPixels(self: *const T, snapsToPixels: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetSnapsToPixels(@ptrCast(*const IXpsOMPath, self), snapsToPixels); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeBrush(self: *const T, brush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeBrush(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeBrushLocal(self: *const T, brush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeBrushLocal(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeBrushLocal(self: *const T, brush: ?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeBrushLocal(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeBrushLookup(self: *const T, lookup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeBrushLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeBrushLookup(self: *const T, lookup: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeBrushLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeDashes(self: *const T, strokeDashes: ?*?*IXpsOMDashCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeDashes(@ptrCast(*const IXpsOMPath, self), strokeDashes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeDashCap(self: *const T, strokeDashCap: ?*XPS_DASH_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeDashCap(@ptrCast(*const IXpsOMPath, self), strokeDashCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeDashCap(self: *const T, strokeDashCap: XPS_DASH_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeDashCap(@ptrCast(*const IXpsOMPath, self), strokeDashCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeDashOffset(self: *const T, strokeDashOffset: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeDashOffset(@ptrCast(*const IXpsOMPath, self), strokeDashOffset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeDashOffset(self: *const T, strokeDashOffset: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeDashOffset(@ptrCast(*const IXpsOMPath, self), strokeDashOffset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeStartLineCap(self: *const T, strokeStartLineCap: ?*XPS_LINE_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeStartLineCap(@ptrCast(*const IXpsOMPath, self), strokeStartLineCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeStartLineCap(self: *const T, strokeStartLineCap: XPS_LINE_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeStartLineCap(@ptrCast(*const IXpsOMPath, self), strokeStartLineCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeEndLineCap(self: *const T, strokeEndLineCap: ?*XPS_LINE_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeEndLineCap(@ptrCast(*const IXpsOMPath, self), strokeEndLineCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeEndLineCap(self: *const T, strokeEndLineCap: XPS_LINE_CAP) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeEndLineCap(@ptrCast(*const IXpsOMPath, self), strokeEndLineCap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeLineJoin(self: *const T, strokeLineJoin: ?*XPS_LINE_JOIN) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeLineJoin(@ptrCast(*const IXpsOMPath, self), strokeLineJoin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeLineJoin(self: *const T, strokeLineJoin: XPS_LINE_JOIN) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeLineJoin(@ptrCast(*const IXpsOMPath, self), strokeLineJoin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeMiterLimit(self: *const T, strokeMiterLimit: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeMiterLimit(@ptrCast(*const IXpsOMPath, self), strokeMiterLimit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeMiterLimit(self: *const T, strokeMiterLimit: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeMiterLimit(@ptrCast(*const IXpsOMPath, self), strokeMiterLimit); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetStrokeThickness(self: *const T, strokeThickness: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetStrokeThickness(@ptrCast(*const IXpsOMPath, self), strokeThickness); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetStrokeThickness(self: *const T, strokeThickness: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetStrokeThickness(@ptrCast(*const IXpsOMPath, self), strokeThickness); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetFillBrush(self: *const T, brush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetFillBrush(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetFillBrushLocal(self: *const T, brush: ?*?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetFillBrushLocal(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetFillBrushLocal(self: *const T, brush: ?*IXpsOMBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetFillBrushLocal(@ptrCast(*const IXpsOMPath, self), brush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_GetFillBrushLookup(self: *const T, lookup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).GetFillBrushLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_SetFillBrushLookup(self: *const T, lookup: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).SetFillBrushLookup(@ptrCast(*const IXpsOMPath, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPath_Clone(self: *const T, path: ?*?*IXpsOMPath) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPath.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMPath, self), path); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMBrush_Value = Guid.initString("56a3f80c-ea4c-4187-a57b-a2a473b2b42b"); pub const IID_IXpsOMBrush = &IID_IXpsOMBrush_Value; pub const IXpsOMBrush = extern struct { pub const VTable = extern struct { base: IXpsOMShareable.VTable, GetOpacity: fn( self: *const IXpsOMBrush, opacity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOpacity: fn( self: *const IXpsOMBrush, opacity: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMShareable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMBrush_GetOpacity(self: *const T, opacity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMBrush.VTable, self.vtable).GetOpacity(@ptrCast(*const IXpsOMBrush, self), opacity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMBrush_SetOpacity(self: *const T, opacity: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMBrush.VTable, self.vtable).SetOpacity(@ptrCast(*const IXpsOMBrush, self), opacity); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGradientStopCollection_Value = Guid.initString("c9174c3a-3cd3-4319-bda4-11a39392ceef"); pub const IID_IXpsOMGradientStopCollection = &IID_IXpsOMGradientStopCollection_Value; pub const IXpsOMGradientStopCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMGradientStopCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMGradientStopCollection, index: u32, stop: ?*?*IXpsOMGradientStop, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMGradientStopCollection, index: u32, stop: ?*IXpsOMGradientStop, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMGradientStopCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMGradientStopCollection, index: u32, stop: ?*IXpsOMGradientStop, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMGradientStopCollection, stop: ?*IXpsOMGradientStop, ) 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 IXpsOMGradientStopCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMGradientStopCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStopCollection_GetAt(self: *const T, index: u32, stop: ?*?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMGradientStopCollection, self), index, stop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStopCollection_InsertAt(self: *const T, index: u32, stop: ?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMGradientStopCollection, self), index, stop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStopCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMGradientStopCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStopCollection_SetAt(self: *const T, index: u32, stop: ?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMGradientStopCollection, self), index, stop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStopCollection_Append(self: *const T, stop: ?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStopCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMGradientStopCollection, self), stop); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMSolidColorBrush_Value = Guid.initString("a06f9f05-3be9-4763-98a8-094fc672e488"); pub const IID_IXpsOMSolidColorBrush = &IID_IXpsOMSolidColorBrush_Value; pub const IXpsOMSolidColorBrush = extern struct { pub const VTable = extern struct { base: IXpsOMBrush.VTable, GetColor: fn( self: *const IXpsOMSolidColorBrush, color: ?*XPS_COLOR, colorProfile: ?*?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColor: fn( self: *const IXpsOMSolidColorBrush, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMSolidColorBrush, solidColorBrush: ?*?*IXpsOMSolidColorBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSolidColorBrush_GetColor(self: *const T, color: ?*XPS_COLOR, colorProfile: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSolidColorBrush.VTable, self.vtable).GetColor(@ptrCast(*const IXpsOMSolidColorBrush, self), color, colorProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSolidColorBrush_SetColor(self: *const T, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSolidColorBrush.VTable, self.vtable).SetColor(@ptrCast(*const IXpsOMSolidColorBrush, self), color, colorProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSolidColorBrush_Clone(self: *const T, solidColorBrush: ?*?*IXpsOMSolidColorBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSolidColorBrush.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMSolidColorBrush, self), solidColorBrush); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMTileBrush_Value = Guid.initString("0fc2328d-d722-4a54-b2ec-be90218a789e"); pub const IID_IXpsOMTileBrush = &IID_IXpsOMTileBrush_Value; pub const IXpsOMTileBrush = extern struct { pub const VTable = extern struct { base: IXpsOMBrush.VTable, GetTransform: fn( self: *const IXpsOMTileBrush, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLocal: fn( self: *const IXpsOMTileBrush, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLocal: fn( self: *const IXpsOMTileBrush, transform: ?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLookup: fn( self: *const IXpsOMTileBrush, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLookup: fn( self: *const IXpsOMTileBrush, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetViewbox: fn( self: *const IXpsOMTileBrush, viewbox: ?*XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetViewbox: fn( self: *const IXpsOMTileBrush, viewbox: ?*const XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetViewport: fn( self: *const IXpsOMTileBrush, viewport: ?*XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetViewport: fn( self: *const IXpsOMTileBrush, viewport: ?*const XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTileMode: fn( self: *const IXpsOMTileBrush, tileMode: ?*XPS_TILE_MODE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTileMode: fn( self: *const IXpsOMTileBrush, tileMode: XPS_TILE_MODE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetTransform(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetTransform(@ptrCast(*const IXpsOMTileBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetTransformLocal(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetTransformLocal(@ptrCast(*const IXpsOMTileBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_SetTransformLocal(self: *const T, transform: ?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).SetTransformLocal(@ptrCast(*const IXpsOMTileBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetTransformLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetTransformLookup(@ptrCast(*const IXpsOMTileBrush, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_SetTransformLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).SetTransformLookup(@ptrCast(*const IXpsOMTileBrush, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetViewbox(self: *const T, viewbox: ?*XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetViewbox(@ptrCast(*const IXpsOMTileBrush, self), viewbox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_SetViewbox(self: *const T, viewbox: ?*const XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).SetViewbox(@ptrCast(*const IXpsOMTileBrush, self), viewbox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetViewport(self: *const T, viewport: ?*XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetViewport(@ptrCast(*const IXpsOMTileBrush, self), viewport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_SetViewport(self: *const T, viewport: ?*const XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).SetViewport(@ptrCast(*const IXpsOMTileBrush, self), viewport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_GetTileMode(self: *const T, tileMode: ?*XPS_TILE_MODE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).GetTileMode(@ptrCast(*const IXpsOMTileBrush, self), tileMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMTileBrush_SetTileMode(self: *const T, tileMode: XPS_TILE_MODE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMTileBrush.VTable, self.vtable).SetTileMode(@ptrCast(*const IXpsOMTileBrush, self), tileMode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMVisualBrush_Value = Guid.initString("97e294af-5b37-46b4-8057-874d2f64119b"); pub const IID_IXpsOMVisualBrush = &IID_IXpsOMVisualBrush_Value; pub const IXpsOMVisualBrush = extern struct { pub const VTable = extern struct { base: IXpsOMTileBrush.VTable, GetVisual: fn( self: *const IXpsOMVisualBrush, visual: ?*?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVisualLocal: fn( self: *const IXpsOMVisualBrush, visual: ?*?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVisualLocal: fn( self: *const IXpsOMVisualBrush, visual: ?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVisualLookup: fn( self: *const IXpsOMVisualBrush, lookup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVisualLookup: fn( self: *const IXpsOMVisualBrush, lookup: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMVisualBrush, visualBrush: ?*?*IXpsOMVisualBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMTileBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_GetVisual(self: *const T, visual: ?*?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).GetVisual(@ptrCast(*const IXpsOMVisualBrush, self), visual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_GetVisualLocal(self: *const T, visual: ?*?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).GetVisualLocal(@ptrCast(*const IXpsOMVisualBrush, self), visual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_SetVisualLocal(self: *const T, visual: ?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).SetVisualLocal(@ptrCast(*const IXpsOMVisualBrush, self), visual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_GetVisualLookup(self: *const T, lookup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).GetVisualLookup(@ptrCast(*const IXpsOMVisualBrush, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_SetVisualLookup(self: *const T, lookup: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).SetVisualLookup(@ptrCast(*const IXpsOMVisualBrush, self), lookup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualBrush_Clone(self: *const T, visualBrush: ?*?*IXpsOMVisualBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualBrush.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMVisualBrush, self), visualBrush); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMImageBrush_Value = Guid.initString("3df0b466-d382-49ef-8550-dd94c80242e4"); pub const IID_IXpsOMImageBrush = &IID_IXpsOMImageBrush_Value; pub const IXpsOMImageBrush = extern struct { pub const VTable = extern struct { base: IXpsOMTileBrush.VTable, GetImageResource: fn( self: *const IXpsOMImageBrush, imageResource: ?*?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetImageResource: fn( self: *const IXpsOMImageBrush, imageResource: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorProfileResource: fn( self: *const IXpsOMImageBrush, colorProfileResource: ?*?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorProfileResource: fn( self: *const IXpsOMImageBrush, colorProfileResource: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMImageBrush, imageBrush: ?*?*IXpsOMImageBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMTileBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageBrush_GetImageResource(self: *const T, imageResource: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageBrush.VTable, self.vtable).GetImageResource(@ptrCast(*const IXpsOMImageBrush, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageBrush_SetImageResource(self: *const T, imageResource: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageBrush.VTable, self.vtable).SetImageResource(@ptrCast(*const IXpsOMImageBrush, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageBrush_GetColorProfileResource(self: *const T, colorProfileResource: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageBrush.VTable, self.vtable).GetColorProfileResource(@ptrCast(*const IXpsOMImageBrush, self), colorProfileResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageBrush_SetColorProfileResource(self: *const T, colorProfileResource: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageBrush.VTable, self.vtable).SetColorProfileResource(@ptrCast(*const IXpsOMImageBrush, self), colorProfileResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageBrush_Clone(self: *const T, imageBrush: ?*?*IXpsOMImageBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageBrush.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMImageBrush, self), imageBrush); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGradientStop_Value = Guid.initString("5cf4f5cc-3969-49b5-a70a-5550b618fe49"); pub const IID_IXpsOMGradientStop = &IID_IXpsOMGradientStop_Value; pub const IXpsOMGradientStop = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwner: fn( self: *const IXpsOMGradientStop, owner: ?*?*IXpsOMGradientBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOffset: fn( self: *const IXpsOMGradientStop, offset: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOffset: fn( self: *const IXpsOMGradientStop, offset: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColor: fn( self: *const IXpsOMGradientStop, color: ?*XPS_COLOR, colorProfile: ?*?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColor: fn( self: *const IXpsOMGradientStop, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMGradientStop, gradientStop: ?*?*IXpsOMGradientStop, ) 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 IXpsOMGradientStop_GetOwner(self: *const T, owner: ?*?*IXpsOMGradientBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMGradientStop, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStop_GetOffset(self: *const T, offset: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).GetOffset(@ptrCast(*const IXpsOMGradientStop, self), offset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStop_SetOffset(self: *const T, offset: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).SetOffset(@ptrCast(*const IXpsOMGradientStop, self), offset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStop_GetColor(self: *const T, color: ?*XPS_COLOR, colorProfile: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).GetColor(@ptrCast(*const IXpsOMGradientStop, self), color, colorProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStop_SetColor(self: *const T, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).SetColor(@ptrCast(*const IXpsOMGradientStop, self), color, colorProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientStop_Clone(self: *const T, gradientStop: ?*?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientStop.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMGradientStop, self), gradientStop); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMGradientBrush_Value = Guid.initString("edb59622-61a2-42c3-bace-acf2286c06bf"); pub const IID_IXpsOMGradientBrush = &IID_IXpsOMGradientBrush_Value; pub const IXpsOMGradientBrush = extern struct { pub const VTable = extern struct { base: IXpsOMBrush.VTable, GetGradientStops: fn( self: *const IXpsOMGradientBrush, gradientStops: ?*?*IXpsOMGradientStopCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransform: fn( self: *const IXpsOMGradientBrush, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLocal: fn( self: *const IXpsOMGradientBrush, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLocal: fn( self: *const IXpsOMGradientBrush, transform: ?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTransformLookup: fn( self: *const IXpsOMGradientBrush, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformLookup: fn( self: *const IXpsOMGradientBrush, key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSpreadMethod: fn( self: *const IXpsOMGradientBrush, spreadMethod: ?*XPS_SPREAD_METHOD, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSpreadMethod: fn( self: *const IXpsOMGradientBrush, spreadMethod: XPS_SPREAD_METHOD, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorInterpolationMode: fn( self: *const IXpsOMGradientBrush, colorInterpolationMode: ?*XPS_COLOR_INTERPOLATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorInterpolationMode: fn( self: *const IXpsOMGradientBrush, colorInterpolationMode: XPS_COLOR_INTERPOLATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetGradientStops(self: *const T, gradientStops: ?*?*IXpsOMGradientStopCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetGradientStops(@ptrCast(*const IXpsOMGradientBrush, self), gradientStops); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetTransform(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetTransform(@ptrCast(*const IXpsOMGradientBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetTransformLocal(self: *const T, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetTransformLocal(@ptrCast(*const IXpsOMGradientBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_SetTransformLocal(self: *const T, transform: ?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).SetTransformLocal(@ptrCast(*const IXpsOMGradientBrush, self), transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetTransformLookup(self: *const T, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetTransformLookup(@ptrCast(*const IXpsOMGradientBrush, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_SetTransformLookup(self: *const T, key: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).SetTransformLookup(@ptrCast(*const IXpsOMGradientBrush, self), key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetSpreadMethod(self: *const T, spreadMethod: ?*XPS_SPREAD_METHOD) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetSpreadMethod(@ptrCast(*const IXpsOMGradientBrush, self), spreadMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_SetSpreadMethod(self: *const T, spreadMethod: XPS_SPREAD_METHOD) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).SetSpreadMethod(@ptrCast(*const IXpsOMGradientBrush, self), spreadMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_GetColorInterpolationMode(self: *const T, colorInterpolationMode: ?*XPS_COLOR_INTERPOLATION) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).GetColorInterpolationMode(@ptrCast(*const IXpsOMGradientBrush, self), colorInterpolationMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMGradientBrush_SetColorInterpolationMode(self: *const T, colorInterpolationMode: XPS_COLOR_INTERPOLATION) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMGradientBrush.VTable, self.vtable).SetColorInterpolationMode(@ptrCast(*const IXpsOMGradientBrush, self), colorInterpolationMode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMLinearGradientBrush_Value = Guid.initString("005e279f-c30d-40ff-93ec-1950d3c528db"); pub const IID_IXpsOMLinearGradientBrush = &IID_IXpsOMLinearGradientBrush_Value; pub const IXpsOMLinearGradientBrush = extern struct { pub const VTable = extern struct { base: IXpsOMGradientBrush.VTable, GetStartPoint: fn( self: *const IXpsOMLinearGradientBrush, startPoint: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStartPoint: fn( self: *const IXpsOMLinearGradientBrush, startPoint: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndPoint: fn( self: *const IXpsOMLinearGradientBrush, endPoint: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEndPoint: fn( self: *const IXpsOMLinearGradientBrush, endPoint: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMLinearGradientBrush, linearGradientBrush: ?*?*IXpsOMLinearGradientBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMGradientBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMLinearGradientBrush_GetStartPoint(self: *const T, startPoint: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMLinearGradientBrush.VTable, self.vtable).GetStartPoint(@ptrCast(*const IXpsOMLinearGradientBrush, self), startPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMLinearGradientBrush_SetStartPoint(self: *const T, startPoint: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMLinearGradientBrush.VTable, self.vtable).SetStartPoint(@ptrCast(*const IXpsOMLinearGradientBrush, self), startPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMLinearGradientBrush_GetEndPoint(self: *const T, endPoint: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMLinearGradientBrush.VTable, self.vtable).GetEndPoint(@ptrCast(*const IXpsOMLinearGradientBrush, self), endPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMLinearGradientBrush_SetEndPoint(self: *const T, endPoint: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMLinearGradientBrush.VTable, self.vtable).SetEndPoint(@ptrCast(*const IXpsOMLinearGradientBrush, self), endPoint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMLinearGradientBrush_Clone(self: *const T, linearGradientBrush: ?*?*IXpsOMLinearGradientBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMLinearGradientBrush.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMLinearGradientBrush, self), linearGradientBrush); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMRadialGradientBrush_Value = Guid.initString("75f207e5-08bf-413c-96b1-b82b4064176b"); pub const IID_IXpsOMRadialGradientBrush = &IID_IXpsOMRadialGradientBrush_Value; pub const IXpsOMRadialGradientBrush = extern struct { pub const VTable = extern struct { base: IXpsOMGradientBrush.VTable, GetCenter: fn( self: *const IXpsOMRadialGradientBrush, center: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCenter: fn( self: *const IXpsOMRadialGradientBrush, center: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRadiiSizes: fn( self: *const IXpsOMRadialGradientBrush, radiiSizes: ?*XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRadiiSizes: fn( self: *const IXpsOMRadialGradientBrush, radiiSizes: ?*const XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGradientOrigin: fn( self: *const IXpsOMRadialGradientBrush, origin: ?*XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGradientOrigin: fn( self: *const IXpsOMRadialGradientBrush, origin: ?*const XPS_POINT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMRadialGradientBrush, radialGradientBrush: ?*?*IXpsOMRadialGradientBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMGradientBrush.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_GetCenter(self: *const T, center: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).GetCenter(@ptrCast(*const IXpsOMRadialGradientBrush, self), center); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_SetCenter(self: *const T, center: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).SetCenter(@ptrCast(*const IXpsOMRadialGradientBrush, self), center); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_GetRadiiSizes(self: *const T, radiiSizes: ?*XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).GetRadiiSizes(@ptrCast(*const IXpsOMRadialGradientBrush, self), radiiSizes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_SetRadiiSizes(self: *const T, radiiSizes: ?*const XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).SetRadiiSizes(@ptrCast(*const IXpsOMRadialGradientBrush, self), radiiSizes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_GetGradientOrigin(self: *const T, origin: ?*XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).GetGradientOrigin(@ptrCast(*const IXpsOMRadialGradientBrush, self), origin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_SetGradientOrigin(self: *const T, origin: ?*const XPS_POINT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).SetGradientOrigin(@ptrCast(*const IXpsOMRadialGradientBrush, self), origin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRadialGradientBrush_Clone(self: *const T, radialGradientBrush: ?*?*IXpsOMRadialGradientBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRadialGradientBrush.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMRadialGradientBrush, self), radialGradientBrush); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMResource_Value = Guid.initString("da2ac0a2-73a2-4975-ad14-74097c3ff3a5"); pub const IID_IXpsOMResource = &IID_IXpsOMResource_Value; pub const IXpsOMResource = extern struct { pub const VTable = extern struct { base: IXpsOMPart.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPart.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPartResources_Value = Guid.initString("f4cf7729-4864-4275-99b3-a8717163ecaf"); pub const IID_IXpsOMPartResources = &IID_IXpsOMPartResources_Value; pub const IXpsOMPartResources = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetFontResources: fn( self: *const IXpsOMPartResources, fontResources: ?*?*IXpsOMFontResourceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImageResources: fn( self: *const IXpsOMPartResources, imageResources: ?*?*IXpsOMImageResourceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorProfileResources: fn( self: *const IXpsOMPartResources, colorProfileResources: ?*?*IXpsOMColorProfileResourceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRemoteDictionaryResources: fn( self: *const IXpsOMPartResources, dictionaryResources: ?*?*IXpsOMRemoteDictionaryResourceCollection, ) 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 IXpsOMPartResources_GetFontResources(self: *const T, fontResources: ?*?*IXpsOMFontResourceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartResources.VTable, self.vtable).GetFontResources(@ptrCast(*const IXpsOMPartResources, self), fontResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartResources_GetImageResources(self: *const T, imageResources: ?*?*IXpsOMImageResourceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartResources.VTable, self.vtable).GetImageResources(@ptrCast(*const IXpsOMPartResources, self), imageResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartResources_GetColorProfileResources(self: *const T, colorProfileResources: ?*?*IXpsOMColorProfileResourceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartResources.VTable, self.vtable).GetColorProfileResources(@ptrCast(*const IXpsOMPartResources, self), colorProfileResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartResources_GetRemoteDictionaryResources(self: *const T, dictionaryResources: ?*?*IXpsOMRemoteDictionaryResourceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartResources.VTable, self.vtable).GetRemoteDictionaryResources(@ptrCast(*const IXpsOMPartResources, self), dictionaryResources); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDictionary_Value = Guid.initString("897c86b8-8eaf-4ae3-bdde-56419fcf4236"); pub const IID_IXpsOMDictionary = &IID_IXpsOMDictionary_Value; pub const IXpsOMDictionary = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwner: fn( self: *const IXpsOMDictionary, owner: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const IXpsOMDictionary, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMDictionary, index: u32, key: ?*?PWSTR, entry: ?*?*IXpsOMShareable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByKey: fn( self: *const IXpsOMDictionary, key: ?[*:0]const u16, beforeEntry: ?*IXpsOMShareable, entry: ?*?*IXpsOMShareable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIndex: fn( self: *const IXpsOMDictionary, entry: ?*IXpsOMShareable, index: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMDictionary, key: ?[*:0]const u16, entry: ?*IXpsOMShareable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMDictionary, index: u32, key: ?[*:0]const u16, entry: ?*IXpsOMShareable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMDictionary, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMDictionary, index: u32, key: ?[*:0]const u16, entry: ?*IXpsOMShareable, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMDictionary, dictionary: ?*?*IXpsOMDictionary, ) 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 IXpsOMDictionary_GetOwner(self: *const T, owner: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMDictionary, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMDictionary, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_GetAt(self: *const T, index: u32, key: ?*?PWSTR, entry: ?*?*IXpsOMShareable) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMDictionary, self), index, key, entry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_GetByKey(self: *const T, key: ?[*:0]const u16, beforeEntry: ?*IXpsOMShareable, entry: ?*?*IXpsOMShareable) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).GetByKey(@ptrCast(*const IXpsOMDictionary, self), key, beforeEntry, entry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_GetIndex(self: *const T, entry: ?*IXpsOMShareable, index: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).GetIndex(@ptrCast(*const IXpsOMDictionary, self), entry, index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_Append(self: *const T, key: ?[*:0]const u16, entry: ?*IXpsOMShareable) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).Append(@ptrCast(*const IXpsOMDictionary, self), key, entry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_InsertAt(self: *const T, index: u32, key: ?[*:0]const u16, entry: ?*IXpsOMShareable) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMDictionary, self), index, key, entry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMDictionary, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_SetAt(self: *const T, index: u32, key: ?[*:0]const u16, entry: ?*IXpsOMShareable) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMDictionary, self), index, key, entry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDictionary_Clone(self: *const T, dictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDictionary.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMDictionary, self), dictionary); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMFontResource_Value = Guid.initString("a8c45708-47d9-4af4-8d20-33b48c9b8485"); pub const IID_IXpsOMFontResource = &IID_IXpsOMFontResource_Value; pub const IXpsOMFontResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetStream: fn( self: *const IXpsOMFontResource, readerStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMFontResource, sourceStream: ?*IStream, embeddingOption: XPS_FONT_EMBEDDING, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEmbeddingOption: fn( self: *const IXpsOMFontResource, embeddingOption: ?*XPS_FONT_EMBEDDING, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResource_GetStream(self: *const T, readerStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMFontResource, self), readerStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResource_SetContent(self: *const T, sourceStream: ?*IStream, embeddingOption: XPS_FONT_EMBEDDING, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMFontResource, self), sourceStream, embeddingOption, partName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResource_GetEmbeddingOption(self: *const T, embeddingOption: ?*XPS_FONT_EMBEDDING) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResource.VTable, self.vtable).GetEmbeddingOption(@ptrCast(*const IXpsOMFontResource, self), embeddingOption); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMFontResourceCollection_Value = Guid.initString("70b4a6bb-88d4-4fa8-aaf9-6d9c596fdbad"); pub const IID_IXpsOMFontResourceCollection = &IID_IXpsOMFontResourceCollection_Value; pub const IXpsOMFontResourceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMFontResourceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMFontResourceCollection, index: u32, value: ?*?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMFontResourceCollection, index: u32, value: ?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMFontResourceCollection, index: u32, value: ?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMFontResourceCollection, value: ?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMFontResourceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByPartName: fn( self: *const IXpsOMFontResourceCollection, partName: ?*IOpcPartUri, part: ?*?*IXpsOMFontResource, ) 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 IXpsOMFontResourceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMFontResourceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_GetAt(self: *const T, index: u32, value: ?*?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMFontResourceCollection, self), index, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_SetAt(self: *const T, index: u32, value: ?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMFontResourceCollection, self), index, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_InsertAt(self: *const T, index: u32, value: ?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMFontResourceCollection, self), index, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_Append(self: *const T, value: ?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMFontResourceCollection, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMFontResourceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMFontResourceCollection_GetByPartName(self: *const T, partName: ?*IOpcPartUri, part: ?*?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMFontResourceCollection.VTable, self.vtable).GetByPartName(@ptrCast(*const IXpsOMFontResourceCollection, self), partName, part); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMImageResource_Value = Guid.initString("3db8417d-ae50-485e-9a44-d7758f78a23f"); pub const IID_IXpsOMImageResource = &IID_IXpsOMImageResource_Value; pub const IXpsOMImageResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetStream: fn( self: *const IXpsOMImageResource, readerStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMImageResource, sourceStream: ?*IStream, imageType: XPS_IMAGE_TYPE, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImageType: fn( self: *const IXpsOMImageResource, imageType: ?*XPS_IMAGE_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResource_GetStream(self: *const T, readerStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMImageResource, self), readerStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResource_SetContent(self: *const T, sourceStream: ?*IStream, imageType: XPS_IMAGE_TYPE, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMImageResource, self), sourceStream, imageType, partName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResource_GetImageType(self: *const T, imageType: ?*XPS_IMAGE_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResource.VTable, self.vtable).GetImageType(@ptrCast(*const IXpsOMImageResource, self), imageType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMImageResourceCollection_Value = Guid.initString("7a4a1a71-9cde-4b71-b33f-62de843eabfe"); pub const IID_IXpsOMImageResourceCollection = &IID_IXpsOMImageResourceCollection_Value; pub const IXpsOMImageResourceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMImageResourceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMImageResourceCollection, index: u32, object: ?*?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMImageResourceCollection, index: u32, object: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMImageResourceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMImageResourceCollection, index: u32, object: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMImageResourceCollection, object: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByPartName: fn( self: *const IXpsOMImageResourceCollection, partName: ?*IOpcPartUri, part: ?*?*IXpsOMImageResource, ) 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 IXpsOMImageResourceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMImageResourceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_GetAt(self: *const T, index: u32, object: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMImageResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_InsertAt(self: *const T, index: u32, object: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMImageResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMImageResourceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_SetAt(self: *const T, index: u32, object: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMImageResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_Append(self: *const T, object: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMImageResourceCollection, self), object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMImageResourceCollection_GetByPartName(self: *const T, partName: ?*IOpcPartUri, part: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMImageResourceCollection.VTable, self.vtable).GetByPartName(@ptrCast(*const IXpsOMImageResourceCollection, self), partName, part); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMColorProfileResource_Value = Guid.initString("67bd7d69-1eef-4bb1-b5e7-6f4f87be8abe"); pub const IID_IXpsOMColorProfileResource = &IID_IXpsOMColorProfileResource_Value; pub const IXpsOMColorProfileResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetStream: fn( self: *const IXpsOMColorProfileResource, stream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMColorProfileResource, sourceStream: ?*IStream, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResource_GetStream(self: *const T, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMColorProfileResource, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResource_SetContent(self: *const T, sourceStream: ?*IStream, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMColorProfileResource, self), sourceStream, partName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMColorProfileResourceCollection_Value = Guid.initString("12759630-5fba-4283-8f7d-cca849809edb"); pub const IID_IXpsOMColorProfileResourceCollection = &IID_IXpsOMColorProfileResourceCollection_Value; pub const IXpsOMColorProfileResourceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMColorProfileResourceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMColorProfileResourceCollection, index: u32, object: ?*?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMColorProfileResourceCollection, index: u32, object: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMColorProfileResourceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMColorProfileResourceCollection, index: u32, object: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMColorProfileResourceCollection, object: ?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByPartName: fn( self: *const IXpsOMColorProfileResourceCollection, partName: ?*IOpcPartUri, part: ?*?*IXpsOMColorProfileResource, ) 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 IXpsOMColorProfileResourceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_GetAt(self: *const T, index: u32, object: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_InsertAt(self: *const T, index: u32, object: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_SetAt(self: *const T, index: u32, object: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_Append(self: *const T, object: ?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMColorProfileResourceCollection_GetByPartName(self: *const T, partName: ?*IOpcPartUri, part: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMColorProfileResourceCollection.VTable, self.vtable).GetByPartName(@ptrCast(*const IXpsOMColorProfileResourceCollection, self), partName, part); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPrintTicketResource_Value = Guid.initString("e7ff32d2-34aa-499b-bbe9-9cd4ee6c59f7"); pub const IID_IXpsOMPrintTicketResource = &IID_IXpsOMPrintTicketResource_Value; pub const IXpsOMPrintTicketResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetStream: fn( self: *const IXpsOMPrintTicketResource, stream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMPrintTicketResource, sourceStream: ?*IStream, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPrintTicketResource_GetStream(self: *const T, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPrintTicketResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMPrintTicketResource, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPrintTicketResource_SetContent(self: *const T, sourceStream: ?*IStream, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPrintTicketResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMPrintTicketResource, self), sourceStream, partName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMRemoteDictionaryResource_Value = Guid.initString("c9bd7cd4-e16a-4bf8-8c84-c950af7a3061"); pub const IID_IXpsOMRemoteDictionaryResource = &IID_IXpsOMRemoteDictionaryResource_Value; pub const IXpsOMRemoteDictionaryResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetDictionary: fn( self: *const IXpsOMRemoteDictionaryResource, dictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDictionary: fn( self: *const IXpsOMRemoteDictionaryResource, dictionary: ?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResource_GetDictionary(self: *const T, dictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResource.VTable, self.vtable).GetDictionary(@ptrCast(*const IXpsOMRemoteDictionaryResource, self), dictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResource_SetDictionary(self: *const T, dictionary: ?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResource.VTable, self.vtable).SetDictionary(@ptrCast(*const IXpsOMRemoteDictionaryResource, self), dictionary); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMRemoteDictionaryResourceCollection_Value = Guid.initString("5c38db61-7fec-464a-87bd-41e3bef018be"); pub const IID_IXpsOMRemoteDictionaryResourceCollection = &IID_IXpsOMRemoteDictionaryResourceCollection_Value; pub const IXpsOMRemoteDictionaryResourceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, index: u32, object: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, index: u32, object: ?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, index: u32, object: ?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, object: ?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByPartName: fn( self: *const IXpsOMRemoteDictionaryResourceCollection, partName: ?*IOpcPartUri, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) 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 IXpsOMRemoteDictionaryResourceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_GetAt(self: *const T, index: u32, object: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_InsertAt(self: *const T, index: u32, object: ?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_SetAt(self: *const T, index: u32, object: ?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_Append(self: *const T, object: ?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResourceCollection_GetByPartName(self: *const T, partName: ?*IOpcPartUri, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResourceCollection.VTable, self.vtable).GetByPartName(@ptrCast(*const IXpsOMRemoteDictionaryResourceCollection, self), partName, remoteDictionaryResource); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMSignatureBlockResourceCollection_Value = Guid.initString("ab8f5d8e-351b-4d33-aaed-fa56f0022931"); pub const IID_IXpsOMSignatureBlockResourceCollection = &IID_IXpsOMSignatureBlockResourceCollection_Value; pub const IXpsOMSignatureBlockResourceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMSignatureBlockResourceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMSignatureBlockResourceCollection, index: u32, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMSignatureBlockResourceCollection, index: u32, signatureBlockResource: ?*IXpsOMSignatureBlockResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMSignatureBlockResourceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMSignatureBlockResourceCollection, index: u32, signatureBlockResource: ?*IXpsOMSignatureBlockResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMSignatureBlockResourceCollection, signatureBlockResource: ?*IXpsOMSignatureBlockResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetByPartName: fn( self: *const IXpsOMSignatureBlockResourceCollection, partName: ?*IOpcPartUri, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource, ) 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 IXpsOMSignatureBlockResourceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_GetAt(self: *const T, index: u32, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), index, signatureBlockResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_InsertAt(self: *const T, index: u32, signatureBlockResource: ?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), index, signatureBlockResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_SetAt(self: *const T, index: u32, signatureBlockResource: ?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), index, signatureBlockResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_Append(self: *const T, signatureBlockResource: ?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), signatureBlockResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResourceCollection_GetByPartName(self: *const T, partName: ?*IOpcPartUri, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResourceCollection.VTable, self.vtable).GetByPartName(@ptrCast(*const IXpsOMSignatureBlockResourceCollection, self), partName, signatureBlockResource); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDocumentStructureResource_Value = Guid.initString("85febc8a-6b63-48a9-af07-7064e4ecff30"); pub const IID_IXpsOMDocumentStructureResource = &IID_IXpsOMDocumentStructureResource_Value; pub const IXpsOMDocumentStructureResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetOwner: fn( self: *const IXpsOMDocumentStructureResource, owner: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStream: fn( self: *const IXpsOMDocumentStructureResource, stream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMDocumentStructureResource, sourceStream: ?*IStream, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentStructureResource_GetOwner(self: *const T, owner: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentStructureResource.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMDocumentStructureResource, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentStructureResource_GetStream(self: *const T, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentStructureResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMDocumentStructureResource, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentStructureResource_SetContent(self: *const T, sourceStream: ?*IStream, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentStructureResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMDocumentStructureResource, self), sourceStream, partName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMStoryFragmentsResource_Value = Guid.initString("c2b3ca09-0473-4282-87ae-1780863223f0"); pub const IID_IXpsOMStoryFragmentsResource = &IID_IXpsOMStoryFragmentsResource_Value; pub const IXpsOMStoryFragmentsResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetOwner: fn( self: *const IXpsOMStoryFragmentsResource, owner: ?*?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStream: fn( self: *const IXpsOMStoryFragmentsResource, stream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMStoryFragmentsResource, sourceStream: ?*IStream, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMStoryFragmentsResource_GetOwner(self: *const T, owner: ?*?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMStoryFragmentsResource.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMStoryFragmentsResource, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMStoryFragmentsResource_GetStream(self: *const T, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMStoryFragmentsResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMStoryFragmentsResource, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMStoryFragmentsResource_SetContent(self: *const T, sourceStream: ?*IStream, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMStoryFragmentsResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMStoryFragmentsResource, self), sourceStream, partName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMSignatureBlockResource_Value = Guid.initString("4776ad35-2e04-4357-8743-ebf6c171a905"); pub const IID_IXpsOMSignatureBlockResource = &IID_IXpsOMSignatureBlockResource_Value; pub const IXpsOMSignatureBlockResource = extern struct { pub const VTable = extern struct { base: IXpsOMResource.VTable, GetOwner: fn( self: *const IXpsOMSignatureBlockResource, owner: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStream: fn( self: *const IXpsOMSignatureBlockResource, stream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContent: fn( self: *const IXpsOMSignatureBlockResource, sourceStream: ?*IStream, partName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResource_GetOwner(self: *const T, owner: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResource.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMSignatureBlockResource, self), owner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResource_GetStream(self: *const T, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResource.VTable, self.vtable).GetStream(@ptrCast(*const IXpsOMSignatureBlockResource, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMSignatureBlockResource_SetContent(self: *const T, sourceStream: ?*IStream, partName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMSignatureBlockResource.VTable, self.vtable).SetContent(@ptrCast(*const IXpsOMSignatureBlockResource, self), sourceStream, partName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMVisualCollection_Value = Guid.initString("94d8abde-ab91-46a8-82b7-f5b05ef01a96"); pub const IID_IXpsOMVisualCollection = &IID_IXpsOMVisualCollection_Value; pub const IXpsOMVisualCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMVisualCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMVisualCollection, index: u32, object: ?*?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMVisualCollection, index: u32, object: ?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMVisualCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMVisualCollection, index: u32, object: ?*IXpsOMVisual, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMVisualCollection, object: ?*IXpsOMVisual, ) 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 IXpsOMVisualCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMVisualCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualCollection_GetAt(self: *const T, index: u32, object: ?*?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMVisualCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualCollection_InsertAt(self: *const T, index: u32, object: ?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMVisualCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMVisualCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualCollection_SetAt(self: *const T, index: u32, object: ?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMVisualCollection, self), index, object); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMVisualCollection_Append(self: *const T, object: ?*IXpsOMVisual) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMVisualCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMVisualCollection, self), object); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMCanvas_Value = Guid.initString("221d1452-331e-47c6-87e9-6ccefb9b5ba3"); pub const IID_IXpsOMCanvas = &IID_IXpsOMCanvas_Value; pub const IXpsOMCanvas = extern struct { pub const VTable = extern struct { base: IXpsOMVisual.VTable, GetVisuals: fn( self: *const IXpsOMCanvas, visuals: ?*?*IXpsOMVisualCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUseAliasedEdgeMode: fn( self: *const IXpsOMCanvas, useAliasedEdgeMode: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUseAliasedEdgeMode: fn( self: *const IXpsOMCanvas, useAliasedEdgeMode: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAccessibilityShortDescription: fn( self: *const IXpsOMCanvas, shortDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAccessibilityShortDescription: fn( self: *const IXpsOMCanvas, shortDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAccessibilityLongDescription: fn( self: *const IXpsOMCanvas, longDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAccessibilityLongDescription: fn( self: *const IXpsOMCanvas, longDescription: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionary: fn( self: *const IXpsOMCanvas, resourceDictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionaryLocal: fn( self: *const IXpsOMCanvas, resourceDictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDictionaryLocal: fn( self: *const IXpsOMCanvas, resourceDictionary: ?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionaryResource: fn( self: *const IXpsOMCanvas, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDictionaryResource: fn( self: *const IXpsOMCanvas, remoteDictionaryResource: ?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMCanvas, canvas: ?*?*IXpsOMCanvas, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMVisual.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetVisuals(self: *const T, visuals: ?*?*IXpsOMVisualCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetVisuals(@ptrCast(*const IXpsOMCanvas, self), visuals); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetUseAliasedEdgeMode(self: *const T, useAliasedEdgeMode: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetUseAliasedEdgeMode(@ptrCast(*const IXpsOMCanvas, self), useAliasedEdgeMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_SetUseAliasedEdgeMode(self: *const T, useAliasedEdgeMode: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).SetUseAliasedEdgeMode(@ptrCast(*const IXpsOMCanvas, self), useAliasedEdgeMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetAccessibilityShortDescription(self: *const T, shortDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetAccessibilityShortDescription(@ptrCast(*const IXpsOMCanvas, self), shortDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_SetAccessibilityShortDescription(self: *const T, shortDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).SetAccessibilityShortDescription(@ptrCast(*const IXpsOMCanvas, self), shortDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetAccessibilityLongDescription(self: *const T, longDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetAccessibilityLongDescription(@ptrCast(*const IXpsOMCanvas, self), longDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_SetAccessibilityLongDescription(self: *const T, longDescription: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).SetAccessibilityLongDescription(@ptrCast(*const IXpsOMCanvas, self), longDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetDictionary(self: *const T, resourceDictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetDictionary(@ptrCast(*const IXpsOMCanvas, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetDictionaryLocal(self: *const T, resourceDictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetDictionaryLocal(@ptrCast(*const IXpsOMCanvas, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_SetDictionaryLocal(self: *const T, resourceDictionary: ?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).SetDictionaryLocal(@ptrCast(*const IXpsOMCanvas, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_GetDictionaryResource(self: *const T, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).GetDictionaryResource(@ptrCast(*const IXpsOMCanvas, self), remoteDictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_SetDictionaryResource(self: *const T, remoteDictionaryResource: ?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).SetDictionaryResource(@ptrCast(*const IXpsOMCanvas, self), remoteDictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCanvas_Clone(self: *const T, canvas: ?*?*IXpsOMCanvas) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCanvas.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMCanvas, self), canvas); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPage_Value = Guid.initString("d3e18888-f120-4fee-8c68-35296eae91d4"); pub const IID_IXpsOMPage = &IID_IXpsOMPage_Value; pub const IXpsOMPage = extern struct { pub const VTable = extern struct { base: IXpsOMPart.VTable, GetOwner: fn( self: *const IXpsOMPage, pageReference: ?*?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVisuals: fn( self: *const IXpsOMPage, visuals: ?*?*IXpsOMVisualCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPageDimensions: fn( self: *const IXpsOMPage, pageDimensions: ?*XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPageDimensions: fn( self: *const IXpsOMPage, pageDimensions: ?*const XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContentBox: fn( self: *const IXpsOMPage, contentBox: ?*XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContentBox: fn( self: *const IXpsOMPage, contentBox: ?*const XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBleedBox: fn( self: *const IXpsOMPage, bleedBox: ?*XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBleedBox: fn( self: *const IXpsOMPage, bleedBox: ?*const XPS_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguage: fn( self: *const IXpsOMPage, language: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLanguage: fn( self: *const IXpsOMPage, language: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetName: fn( self: *const IXpsOMPage, name: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetName: fn( self: *const IXpsOMPage, name: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIsHyperlinkTarget: fn( self: *const IXpsOMPage, isHyperlinkTarget: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIsHyperlinkTarget: fn( self: *const IXpsOMPage, isHyperlinkTarget: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionary: fn( self: *const IXpsOMPage, resourceDictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionaryLocal: fn( self: *const IXpsOMPage, resourceDictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDictionaryLocal: fn( self: *const IXpsOMPage, resourceDictionary: ?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDictionaryResource: fn( self: *const IXpsOMPage, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDictionaryResource: fn( self: *const IXpsOMPage, remoteDictionaryResource: ?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Write: fn( self: *const IXpsOMPage, stream: ?*ISequentialStream, optimizeMarkupSize: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GenerateUnusedLookupKey: fn( self: *const IXpsOMPage, type: XPS_OBJECT_TYPE, key: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMPage, page: ?*?*IXpsOMPage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPart.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetOwner(self: *const T, pageReference: ?*?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMPage, self), pageReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetVisuals(self: *const T, visuals: ?*?*IXpsOMVisualCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetVisuals(@ptrCast(*const IXpsOMPage, self), visuals); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetPageDimensions(self: *const T, pageDimensions: ?*XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetPageDimensions(@ptrCast(*const IXpsOMPage, self), pageDimensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetPageDimensions(self: *const T, pageDimensions: ?*const XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetPageDimensions(@ptrCast(*const IXpsOMPage, self), pageDimensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetContentBox(self: *const T, contentBox: ?*XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetContentBox(@ptrCast(*const IXpsOMPage, self), contentBox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetContentBox(self: *const T, contentBox: ?*const XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetContentBox(@ptrCast(*const IXpsOMPage, self), contentBox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetBleedBox(self: *const T, bleedBox: ?*XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetBleedBox(@ptrCast(*const IXpsOMPage, self), bleedBox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetBleedBox(self: *const T, bleedBox: ?*const XPS_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetBleedBox(@ptrCast(*const IXpsOMPage, self), bleedBox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetLanguage(self: *const T, language: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetLanguage(@ptrCast(*const IXpsOMPage, self), language); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetLanguage(self: *const T, language: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetLanguage(@ptrCast(*const IXpsOMPage, self), language); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetName(self: *const T, name: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetName(@ptrCast(*const IXpsOMPage, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetName(self: *const T, name: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetName(@ptrCast(*const IXpsOMPage, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetIsHyperlinkTarget(self: *const T, isHyperlinkTarget: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetIsHyperlinkTarget(@ptrCast(*const IXpsOMPage, self), isHyperlinkTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetIsHyperlinkTarget(self: *const T, isHyperlinkTarget: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetIsHyperlinkTarget(@ptrCast(*const IXpsOMPage, self), isHyperlinkTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetDictionary(self: *const T, resourceDictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetDictionary(@ptrCast(*const IXpsOMPage, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetDictionaryLocal(self: *const T, resourceDictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetDictionaryLocal(@ptrCast(*const IXpsOMPage, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetDictionaryLocal(self: *const T, resourceDictionary: ?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetDictionaryLocal(@ptrCast(*const IXpsOMPage, self), resourceDictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GetDictionaryResource(self: *const T, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GetDictionaryResource(@ptrCast(*const IXpsOMPage, self), remoteDictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_SetDictionaryResource(self: *const T, remoteDictionaryResource: ?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).SetDictionaryResource(@ptrCast(*const IXpsOMPage, self), remoteDictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_Write(self: *const T, stream: ?*ISequentialStream, optimizeMarkupSize: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).Write(@ptrCast(*const IXpsOMPage, self), stream, optimizeMarkupSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_GenerateUnusedLookupKey(self: *const T, type_: XPS_OBJECT_TYPE, key: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).GenerateUnusedLookupKey(@ptrCast(*const IXpsOMPage, self), type_, key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage_Clone(self: *const T, page: ?*?*IXpsOMPage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMPage, self), page); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPageReference_Value = Guid.initString("ed360180-6f92-4998-890d-2f208531a0a0"); pub const IID_IXpsOMPageReference = &IID_IXpsOMPageReference_Value; pub const IXpsOMPageReference = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwner: fn( self: *const IXpsOMPageReference, document: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPage: fn( self: *const IXpsOMPageReference, page: ?*?*IXpsOMPage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPage: fn( self: *const IXpsOMPageReference, page: ?*IXpsOMPage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DiscardPage: fn( self: *const IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsPageLoaded: fn( self: *const IXpsOMPageReference, isPageLoaded: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAdvisoryPageDimensions: fn( self: *const IXpsOMPageReference, pageDimensions: ?*XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAdvisoryPageDimensions: fn( self: *const IXpsOMPageReference, pageDimensions: ?*const XPS_SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStoryFragmentsResource: fn( self: *const IXpsOMPageReference, storyFragmentsResource: ?*?*IXpsOMStoryFragmentsResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStoryFragmentsResource: fn( self: *const IXpsOMPageReference, storyFragmentsResource: ?*IXpsOMStoryFragmentsResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintTicketResource: fn( self: *const IXpsOMPageReference, printTicketResource: ?*?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPrintTicketResource: fn( self: *const IXpsOMPageReference, printTicketResource: ?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThumbnailResource: fn( self: *const IXpsOMPageReference, imageResource: ?*?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThumbnailResource: fn( self: *const IXpsOMPageReference, imageResource: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollectLinkTargets: fn( self: *const IXpsOMPageReference, linkTargets: ?*?*IXpsOMNameCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CollectPartResources: fn( self: *const IXpsOMPageReference, partResources: ?*?*IXpsOMPartResources, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HasRestrictedFonts: fn( self: *const IXpsOMPageReference, restrictedFonts: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMPageReference, pageReference: ?*?*IXpsOMPageReference, ) 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 IXpsOMPageReference_GetOwner(self: *const T, document: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMPageReference, self), document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_GetPage(self: *const T, page: ?*?*IXpsOMPage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetPage(@ptrCast(*const IXpsOMPageReference, self), page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_SetPage(self: *const T, page: ?*IXpsOMPage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).SetPage(@ptrCast(*const IXpsOMPageReference, self), page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_DiscardPage(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).DiscardPage(@ptrCast(*const IXpsOMPageReference, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_IsPageLoaded(self: *const T, isPageLoaded: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).IsPageLoaded(@ptrCast(*const IXpsOMPageReference, self), isPageLoaded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_GetAdvisoryPageDimensions(self: *const T, pageDimensions: ?*XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetAdvisoryPageDimensions(@ptrCast(*const IXpsOMPageReference, self), pageDimensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_SetAdvisoryPageDimensions(self: *const T, pageDimensions: ?*const XPS_SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).SetAdvisoryPageDimensions(@ptrCast(*const IXpsOMPageReference, self), pageDimensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_GetStoryFragmentsResource(self: *const T, storyFragmentsResource: ?*?*IXpsOMStoryFragmentsResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetStoryFragmentsResource(@ptrCast(*const IXpsOMPageReference, self), storyFragmentsResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_SetStoryFragmentsResource(self: *const T, storyFragmentsResource: ?*IXpsOMStoryFragmentsResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).SetStoryFragmentsResource(@ptrCast(*const IXpsOMPageReference, self), storyFragmentsResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_GetPrintTicketResource(self: *const T, printTicketResource: ?*?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetPrintTicketResource(@ptrCast(*const IXpsOMPageReference, self), printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_SetPrintTicketResource(self: *const T, printTicketResource: ?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).SetPrintTicketResource(@ptrCast(*const IXpsOMPageReference, self), printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_GetThumbnailResource(self: *const T, imageResource: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).GetThumbnailResource(@ptrCast(*const IXpsOMPageReference, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_SetThumbnailResource(self: *const T, imageResource: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).SetThumbnailResource(@ptrCast(*const IXpsOMPageReference, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_CollectLinkTargets(self: *const T, linkTargets: ?*?*IXpsOMNameCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).CollectLinkTargets(@ptrCast(*const IXpsOMPageReference, self), linkTargets); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_CollectPartResources(self: *const T, partResources: ?*?*IXpsOMPartResources) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).CollectPartResources(@ptrCast(*const IXpsOMPageReference, self), partResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_HasRestrictedFonts(self: *const T, restrictedFonts: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).HasRestrictedFonts(@ptrCast(*const IXpsOMPageReference, self), restrictedFonts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReference_Clone(self: *const T, pageReference: ?*?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReference.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMPageReference, self), pageReference); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPageReferenceCollection_Value = Guid.initString("ca16ba4d-e7b9-45c5-958b-f98022473745"); pub const IID_IXpsOMPageReferenceCollection = &IID_IXpsOMPageReferenceCollection_Value; pub const IXpsOMPageReferenceCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMPageReferenceCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMPageReferenceCollection, index: u32, pageReference: ?*?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMPageReferenceCollection, index: u32, pageReference: ?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMPageReferenceCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMPageReferenceCollection, index: u32, pageReference: ?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMPageReferenceCollection, pageReference: ?*IXpsOMPageReference, ) 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 IXpsOMPageReferenceCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMPageReferenceCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReferenceCollection_GetAt(self: *const T, index: u32, pageReference: ?*?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMPageReferenceCollection, self), index, pageReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReferenceCollection_InsertAt(self: *const T, index: u32, pageReference: ?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMPageReferenceCollection, self), index, pageReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReferenceCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMPageReferenceCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReferenceCollection_SetAt(self: *const T, index: u32, pageReference: ?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMPageReferenceCollection, self), index, pageReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPageReferenceCollection_Append(self: *const T, pageReference: ?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPageReferenceCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMPageReferenceCollection, self), pageReference); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDocument_Value = Guid.initString("2c2c94cb-ac5f-4254-8ee9-23948309d9f0"); pub const IID_IXpsOMDocument = &IID_IXpsOMDocument_Value; pub const IXpsOMDocument = extern struct { pub const VTable = extern struct { base: IXpsOMPart.VTable, GetOwner: fn( self: *const IXpsOMDocument, documentSequence: ?*?*IXpsOMDocumentSequence, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPageReferences: fn( self: *const IXpsOMDocument, pageReferences: ?*?*IXpsOMPageReferenceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintTicketResource: fn( self: *const IXpsOMDocument, printTicketResource: ?*?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPrintTicketResource: fn( self: *const IXpsOMDocument, printTicketResource: ?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentStructureResource: fn( self: *const IXpsOMDocument, documentStructureResource: ?*?*IXpsOMDocumentStructureResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDocumentStructureResource: fn( self: *const IXpsOMDocument, documentStructureResource: ?*IXpsOMDocumentStructureResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureBlockResources: fn( self: *const IXpsOMDocument, signatureBlockResources: ?*?*IXpsOMSignatureBlockResourceCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMDocument, document: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPart.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_GetOwner(self: *const T, documentSequence: ?*?*IXpsOMDocumentSequence) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMDocument, self), documentSequence); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_GetPageReferences(self: *const T, pageReferences: ?*?*IXpsOMPageReferenceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).GetPageReferences(@ptrCast(*const IXpsOMDocument, self), pageReferences); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_GetPrintTicketResource(self: *const T, printTicketResource: ?*?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).GetPrintTicketResource(@ptrCast(*const IXpsOMDocument, self), printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_SetPrintTicketResource(self: *const T, printTicketResource: ?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).SetPrintTicketResource(@ptrCast(*const IXpsOMDocument, self), printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_GetDocumentStructureResource(self: *const T, documentStructureResource: ?*?*IXpsOMDocumentStructureResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).GetDocumentStructureResource(@ptrCast(*const IXpsOMDocument, self), documentStructureResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_SetDocumentStructureResource(self: *const T, documentStructureResource: ?*IXpsOMDocumentStructureResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).SetDocumentStructureResource(@ptrCast(*const IXpsOMDocument, self), documentStructureResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_GetSignatureBlockResources(self: *const T, signatureBlockResources: ?*?*IXpsOMSignatureBlockResourceCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).GetSignatureBlockResources(@ptrCast(*const IXpsOMDocument, self), signatureBlockResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocument_Clone(self: *const T, document: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocument.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMDocument, self), document); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDocumentCollection_Value = Guid.initString("d1c87f0d-e947-4754-8a25-971478f7e83e"); pub const IID_IXpsOMDocumentCollection = &IID_IXpsOMDocumentCollection_Value; pub const IXpsOMDocumentCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMDocumentCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMDocumentCollection, index: u32, document: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMDocumentCollection, index: u32, document: ?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMDocumentCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMDocumentCollection, index: u32, document: ?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMDocumentCollection, document: ?*IXpsOMDocument, ) 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 IXpsOMDocumentCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMDocumentCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentCollection_GetAt(self: *const T, index: u32, document: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMDocumentCollection, self), index, document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentCollection_InsertAt(self: *const T, index: u32, document: ?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMDocumentCollection, self), index, document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMDocumentCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentCollection_SetAt(self: *const T, index: u32, document: ?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMDocumentCollection, self), index, document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentCollection_Append(self: *const T, document: ?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMDocumentCollection, self), document); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMDocumentSequence_Value = Guid.initString("56492eb4-d8d5-425e-8256-4c2b64ad0264"); pub const IID_IXpsOMDocumentSequence = &IID_IXpsOMDocumentSequence_Value; pub const IXpsOMDocumentSequence = extern struct { pub const VTable = extern struct { base: IXpsOMPart.VTable, GetOwner: fn( self: *const IXpsOMDocumentSequence, package: ?*?*IXpsOMPackage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocuments: fn( self: *const IXpsOMDocumentSequence, documents: ?*?*IXpsOMDocumentCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintTicketResource: fn( self: *const IXpsOMDocumentSequence, printTicketResource: ?*?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPrintTicketResource: fn( self: *const IXpsOMDocumentSequence, printTicketResource: ?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPart.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentSequence_GetOwner(self: *const T, package: ?*?*IXpsOMPackage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentSequence.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMDocumentSequence, self), package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentSequence_GetDocuments(self: *const T, documents: ?*?*IXpsOMDocumentCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentSequence.VTable, self.vtable).GetDocuments(@ptrCast(*const IXpsOMDocumentSequence, self), documents); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentSequence_GetPrintTicketResource(self: *const T, printTicketResource: ?*?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentSequence.VTable, self.vtable).GetPrintTicketResource(@ptrCast(*const IXpsOMDocumentSequence, self), printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMDocumentSequence_SetPrintTicketResource(self: *const T, printTicketResource: ?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMDocumentSequence.VTable, self.vtable).SetPrintTicketResource(@ptrCast(*const IXpsOMDocumentSequence, self), printTicketResource); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMCoreProperties_Value = Guid.initString("3340fe8f-4027-4aa1-8f5f-d35ae45fe597"); pub const IID_IXpsOMCoreProperties = &IID_IXpsOMCoreProperties_Value; pub const IXpsOMCoreProperties = extern struct { pub const VTable = extern struct { base: IXpsOMPart.VTable, GetOwner: fn( self: *const IXpsOMCoreProperties, package: ?*?*IXpsOMPackage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCategory: fn( self: *const IXpsOMCoreProperties, category: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCategory: fn( self: *const IXpsOMCoreProperties, category: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContentStatus: fn( self: *const IXpsOMCoreProperties, contentStatus: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContentStatus: fn( self: *const IXpsOMCoreProperties, contentStatus: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContentType: fn( self: *const IXpsOMCoreProperties, contentType: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContentType: fn( self: *const IXpsOMCoreProperties, contentType: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCreated: fn( self: *const IXpsOMCoreProperties, created: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCreated: fn( self: *const IXpsOMCoreProperties, created: ?*const SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCreator: fn( self: *const IXpsOMCoreProperties, creator: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCreator: fn( self: *const IXpsOMCoreProperties, creator: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const IXpsOMCoreProperties, description: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDescription: fn( self: *const IXpsOMCoreProperties, description: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIdentifier: fn( self: *const IXpsOMCoreProperties, identifier: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIdentifier: fn( self: *const IXpsOMCoreProperties, identifier: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKeywords: fn( self: *const IXpsOMCoreProperties, keywords: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetKeywords: fn( self: *const IXpsOMCoreProperties, keywords: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguage: fn( self: *const IXpsOMCoreProperties, language: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLanguage: fn( self: *const IXpsOMCoreProperties, language: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLastModifiedBy: fn( self: *const IXpsOMCoreProperties, lastModifiedBy: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLastModifiedBy: fn( self: *const IXpsOMCoreProperties, lastModifiedBy: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLastPrinted: fn( self: *const IXpsOMCoreProperties, lastPrinted: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLastPrinted: fn( self: *const IXpsOMCoreProperties, lastPrinted: ?*const SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetModified: fn( self: *const IXpsOMCoreProperties, modified: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetModified: fn( self: *const IXpsOMCoreProperties, modified: ?*const SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRevision: fn( self: *const IXpsOMCoreProperties, revision: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRevision: fn( self: *const IXpsOMCoreProperties, revision: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSubject: fn( self: *const IXpsOMCoreProperties, subject: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSubject: fn( self: *const IXpsOMCoreProperties, subject: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTitle: fn( self: *const IXpsOMCoreProperties, title: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTitle: fn( self: *const IXpsOMCoreProperties, title: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVersion: fn( self: *const IXpsOMCoreProperties, version: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVersion: fn( self: *const IXpsOMCoreProperties, version: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IXpsOMCoreProperties, coreProperties: ?*?*IXpsOMCoreProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPart.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetOwner(self: *const T, package: ?*?*IXpsOMPackage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetOwner(@ptrCast(*const IXpsOMCoreProperties, self), package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetCategory(self: *const T, category: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetCategory(@ptrCast(*const IXpsOMCoreProperties, self), category); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetCategory(self: *const T, category: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetCategory(@ptrCast(*const IXpsOMCoreProperties, self), category); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetContentStatus(self: *const T, contentStatus: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetContentStatus(@ptrCast(*const IXpsOMCoreProperties, self), contentStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetContentStatus(self: *const T, contentStatus: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetContentStatus(@ptrCast(*const IXpsOMCoreProperties, self), contentStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetContentType(self: *const T, contentType: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetContentType(@ptrCast(*const IXpsOMCoreProperties, self), contentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetContentType(self: *const T, contentType: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetContentType(@ptrCast(*const IXpsOMCoreProperties, self), contentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetCreated(self: *const T, created: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetCreated(@ptrCast(*const IXpsOMCoreProperties, self), created); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetCreated(self: *const T, created: ?*const SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetCreated(@ptrCast(*const IXpsOMCoreProperties, self), created); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetCreator(self: *const T, creator: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetCreator(@ptrCast(*const IXpsOMCoreProperties, self), creator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetCreator(self: *const T, creator: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetCreator(@ptrCast(*const IXpsOMCoreProperties, self), creator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetDescription(self: *const T, description: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetDescription(@ptrCast(*const IXpsOMCoreProperties, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetDescription(self: *const T, description: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetDescription(@ptrCast(*const IXpsOMCoreProperties, self), description); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetIdentifier(self: *const T, identifier: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetIdentifier(@ptrCast(*const IXpsOMCoreProperties, self), identifier); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetIdentifier(self: *const T, identifier: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetIdentifier(@ptrCast(*const IXpsOMCoreProperties, self), identifier); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetKeywords(self: *const T, keywords: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetKeywords(@ptrCast(*const IXpsOMCoreProperties, self), keywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetKeywords(self: *const T, keywords: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetKeywords(@ptrCast(*const IXpsOMCoreProperties, self), keywords); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetLanguage(self: *const T, language: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetLanguage(@ptrCast(*const IXpsOMCoreProperties, self), language); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetLanguage(self: *const T, language: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetLanguage(@ptrCast(*const IXpsOMCoreProperties, self), language); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetLastModifiedBy(self: *const T, lastModifiedBy: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetLastModifiedBy(@ptrCast(*const IXpsOMCoreProperties, self), lastModifiedBy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetLastModifiedBy(self: *const T, lastModifiedBy: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetLastModifiedBy(@ptrCast(*const IXpsOMCoreProperties, self), lastModifiedBy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetLastPrinted(self: *const T, lastPrinted: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetLastPrinted(@ptrCast(*const IXpsOMCoreProperties, self), lastPrinted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetLastPrinted(self: *const T, lastPrinted: ?*const SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetLastPrinted(@ptrCast(*const IXpsOMCoreProperties, self), lastPrinted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetModified(self: *const T, modified: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetModified(@ptrCast(*const IXpsOMCoreProperties, self), modified); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetModified(self: *const T, modified: ?*const SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetModified(@ptrCast(*const IXpsOMCoreProperties, self), modified); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetRevision(self: *const T, revision: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetRevision(@ptrCast(*const IXpsOMCoreProperties, self), revision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetRevision(self: *const T, revision: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetRevision(@ptrCast(*const IXpsOMCoreProperties, self), revision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetSubject(self: *const T, subject: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetSubject(@ptrCast(*const IXpsOMCoreProperties, self), subject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetSubject(self: *const T, subject: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetSubject(@ptrCast(*const IXpsOMCoreProperties, self), subject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetTitle(self: *const T, title: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetTitle(@ptrCast(*const IXpsOMCoreProperties, self), title); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetTitle(self: *const T, title: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetTitle(@ptrCast(*const IXpsOMCoreProperties, self), title); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_GetVersion(self: *const T, version: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).GetVersion(@ptrCast(*const IXpsOMCoreProperties, self), version); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_SetVersion(self: *const T, version: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).SetVersion(@ptrCast(*const IXpsOMCoreProperties, self), version); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMCoreProperties_Clone(self: *const T, coreProperties: ?*?*IXpsOMCoreProperties) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMCoreProperties.VTable, self.vtable).Clone(@ptrCast(*const IXpsOMCoreProperties, self), coreProperties); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPackage_Value = Guid.initString("18c3df65-81e1-4674-91dc-fc452f5a416f"); pub const IID_IXpsOMPackage = &IID_IXpsOMPackage_Value; pub const IXpsOMPackage = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDocumentSequence: fn( self: *const IXpsOMPackage, documentSequence: ?*?*IXpsOMDocumentSequence, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDocumentSequence: fn( self: *const IXpsOMPackage, documentSequence: ?*IXpsOMDocumentSequence, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCoreProperties: fn( self: *const IXpsOMPackage, coreProperties: ?*?*IXpsOMCoreProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCoreProperties: fn( self: *const IXpsOMPackage, coreProperties: ?*IXpsOMCoreProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDiscardControlPartName: fn( self: *const IXpsOMPackage, discardControlPartUri: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDiscardControlPartName: fn( self: *const IXpsOMPackage, discardControlPartUri: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThumbnailResource: fn( self: *const IXpsOMPackage, imageResource: ?*?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThumbnailResource: fn( self: *const IXpsOMPackage, imageResource: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteToFile: fn( self: *const IXpsOMPackage, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteToStream: fn( self: *const IXpsOMPackage, stream: ?*ISequentialStream, optimizeMarkupSize: 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 IXpsOMPackage_GetDocumentSequence(self: *const T, documentSequence: ?*?*IXpsOMDocumentSequence) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).GetDocumentSequence(@ptrCast(*const IXpsOMPackage, self), documentSequence); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_SetDocumentSequence(self: *const T, documentSequence: ?*IXpsOMDocumentSequence) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).SetDocumentSequence(@ptrCast(*const IXpsOMPackage, self), documentSequence); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_GetCoreProperties(self: *const T, coreProperties: ?*?*IXpsOMCoreProperties) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).GetCoreProperties(@ptrCast(*const IXpsOMPackage, self), coreProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_SetCoreProperties(self: *const T, coreProperties: ?*IXpsOMCoreProperties) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).SetCoreProperties(@ptrCast(*const IXpsOMPackage, self), coreProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_GetDiscardControlPartName(self: *const T, discardControlPartUri: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).GetDiscardControlPartName(@ptrCast(*const IXpsOMPackage, self), discardControlPartUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_SetDiscardControlPartName(self: *const T, discardControlPartUri: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).SetDiscardControlPartName(@ptrCast(*const IXpsOMPackage, self), discardControlPartUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_GetThumbnailResource(self: *const T, imageResource: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).GetThumbnailResource(@ptrCast(*const IXpsOMPackage, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_SetThumbnailResource(self: *const T, imageResource: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).SetThumbnailResource(@ptrCast(*const IXpsOMPackage, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_WriteToFile(self: *const T, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).WriteToFile(@ptrCast(*const IXpsOMPackage, self), fileName, securityAttributes, flagsAndAttributes, optimizeMarkupSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage_WriteToStream(self: *const T, stream: ?*ISequentialStream, optimizeMarkupSize: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage.VTable, self.vtable).WriteToStream(@ptrCast(*const IXpsOMPackage, self), stream, optimizeMarkupSize); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMObjectFactory_Value = Guid.initString("f9b2a685-a50d-4fc2-b764-b56e093ea0ca"); pub const IID_IXpsOMObjectFactory = &IID_IXpsOMObjectFactory_Value; pub const IXpsOMObjectFactory = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreatePackage: fn( self: *const IXpsOMObjectFactory, package: ?*?*IXpsOMPackage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageFromFile: fn( self: *const IXpsOMObjectFactory, filename: ?[*:0]const u16, reuseObjects: BOOL, package: ?*?*IXpsOMPackage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageFromStream: fn( self: *const IXpsOMObjectFactory, stream: ?*IStream, reuseObjects: BOOL, package: ?*?*IXpsOMPackage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateStoryFragmentsResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, storyFragmentsResource: ?*?*IXpsOMStoryFragmentsResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDocumentStructureResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, documentStructureResource: ?*?*IXpsOMDocumentStructureResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSignatureBlockResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRemoteDictionaryResource: fn( self: *const IXpsOMObjectFactory, dictionary: ?*IXpsOMDictionary, partUri: ?*IOpcPartUri, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRemoteDictionaryResourceFromStream: fn( self: *const IXpsOMObjectFactory, dictionaryMarkupStream: ?*IStream, dictionaryPartUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, dictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePartResources: fn( self: *const IXpsOMObjectFactory, partResources: ?*?*IXpsOMPartResources, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDocumentSequence: fn( self: *const IXpsOMObjectFactory, partUri: ?*IOpcPartUri, documentSequence: ?*?*IXpsOMDocumentSequence, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDocument: fn( self: *const IXpsOMObjectFactory, partUri: ?*IOpcPartUri, document: ?*?*IXpsOMDocument, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePageReference: fn( self: *const IXpsOMObjectFactory, advisoryPageDimensions: ?*const XPS_SIZE, pageReference: ?*?*IXpsOMPageReference, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePage: fn( self: *const IXpsOMObjectFactory, pageDimensions: ?*const XPS_SIZE, language: ?[*:0]const u16, partUri: ?*IOpcPartUri, page: ?*?*IXpsOMPage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePageFromStream: fn( self: *const IXpsOMObjectFactory, pageMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, reuseObjects: BOOL, page: ?*?*IXpsOMPage, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateCanvas: fn( self: *const IXpsOMObjectFactory, canvas: ?*?*IXpsOMCanvas, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGlyphs: fn( self: *const IXpsOMObjectFactory, fontResource: ?*IXpsOMFontResource, glyphs: ?*?*IXpsOMGlyphs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePath: fn( self: *const IXpsOMObjectFactory, path: ?*?*IXpsOMPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGeometry: fn( self: *const IXpsOMObjectFactory, geometry: ?*?*IXpsOMGeometry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGeometryFigure: fn( self: *const IXpsOMObjectFactory, startPoint: ?*const XPS_POINT, figure: ?*?*IXpsOMGeometryFigure, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateMatrixTransform: fn( self: *const IXpsOMObjectFactory, matrix: ?*const XPS_MATRIX, transform: ?*?*IXpsOMMatrixTransform, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSolidColorBrush: fn( self: *const IXpsOMObjectFactory, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, solidColorBrush: ?*?*IXpsOMSolidColorBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateColorProfileResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, colorProfileResource: ?*?*IXpsOMColorProfileResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateImageBrush: fn( self: *const IXpsOMObjectFactory, image: ?*IXpsOMImageResource, viewBox: ?*const XPS_RECT, viewPort: ?*const XPS_RECT, imageBrush: ?*?*IXpsOMImageBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateVisualBrush: fn( self: *const IXpsOMObjectFactory, viewBox: ?*const XPS_RECT, viewPort: ?*const XPS_RECT, visualBrush: ?*?*IXpsOMVisualBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateImageResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, contentType: XPS_IMAGE_TYPE, partUri: ?*IOpcPartUri, imageResource: ?*?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePrintTicketResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, printTicketResource: ?*?*IXpsOMPrintTicketResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateFontResource: fn( self: *const IXpsOMObjectFactory, acquiredStream: ?*IStream, fontEmbedding: XPS_FONT_EMBEDDING, partUri: ?*IOpcPartUri, isObfSourceStream: BOOL, fontResource: ?*?*IXpsOMFontResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateGradientStop: fn( self: *const IXpsOMObjectFactory, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, offset: f32, gradientStop: ?*?*IXpsOMGradientStop, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateLinearGradientBrush: fn( self: *const IXpsOMObjectFactory, gradStop1: ?*IXpsOMGradientStop, gradStop2: ?*IXpsOMGradientStop, startPoint: ?*const XPS_POINT, endPoint: ?*const XPS_POINT, linearGradientBrush: ?*?*IXpsOMLinearGradientBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRadialGradientBrush: fn( self: *const IXpsOMObjectFactory, gradStop1: ?*IXpsOMGradientStop, gradStop2: ?*IXpsOMGradientStop, centerPoint: ?*const XPS_POINT, gradientOrigin: ?*const XPS_POINT, radiiSizes: ?*const XPS_SIZE, radialGradientBrush: ?*?*IXpsOMRadialGradientBrush, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateCoreProperties: fn( self: *const IXpsOMObjectFactory, partUri: ?*IOpcPartUri, coreProperties: ?*?*IXpsOMCoreProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDictionary: fn( self: *const IXpsOMObjectFactory, dictionary: ?*?*IXpsOMDictionary, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePartUriCollection: fn( self: *const IXpsOMObjectFactory, partUriCollection: ?*?*IXpsOMPartUriCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageWriterOnFile: fn( self: *const IXpsOMObjectFactory, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageWriterOnStream: fn( self: *const IXpsOMObjectFactory, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePartUri: fn( self: *const IXpsOMObjectFactory, uri: ?[*:0]const u16, partUri: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateReadOnlyStreamOnFile: fn( self: *const IXpsOMObjectFactory, filename: ?[*:0]const u16, stream: ?*?*IStream, ) 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 IXpsOMObjectFactory_CreatePackage(self: *const T, package: ?*?*IXpsOMPackage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePackage(@ptrCast(*const IXpsOMObjectFactory, self), package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePackageFromFile(self: *const T, filename: ?[*:0]const u16, reuseObjects: BOOL, package: ?*?*IXpsOMPackage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePackageFromFile(@ptrCast(*const IXpsOMObjectFactory, self), filename, reuseObjects, package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePackageFromStream(self: *const T, stream: ?*IStream, reuseObjects: BOOL, package: ?*?*IXpsOMPackage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePackageFromStream(@ptrCast(*const IXpsOMObjectFactory, self), stream, reuseObjects, package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateStoryFragmentsResource(self: *const T, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, storyFragmentsResource: ?*?*IXpsOMStoryFragmentsResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateStoryFragmentsResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, partUri, storyFragmentsResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateDocumentStructureResource(self: *const T, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, documentStructureResource: ?*?*IXpsOMDocumentStructureResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateDocumentStructureResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, partUri, documentStructureResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateSignatureBlockResource(self: *const T, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, signatureBlockResource: ?*?*IXpsOMSignatureBlockResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateSignatureBlockResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, partUri, signatureBlockResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateRemoteDictionaryResource(self: *const T, dictionary: ?*IXpsOMDictionary, partUri: ?*IOpcPartUri, remoteDictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateRemoteDictionaryResource(@ptrCast(*const IXpsOMObjectFactory, self), dictionary, partUri, remoteDictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateRemoteDictionaryResourceFromStream(self: *const T, dictionaryMarkupStream: ?*IStream, dictionaryPartUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, dictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateRemoteDictionaryResourceFromStream(@ptrCast(*const IXpsOMObjectFactory, self), dictionaryMarkupStream, dictionaryPartUri, resources, dictionaryResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePartResources(self: *const T, partResources: ?*?*IXpsOMPartResources) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePartResources(@ptrCast(*const IXpsOMObjectFactory, self), partResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateDocumentSequence(self: *const T, partUri: ?*IOpcPartUri, documentSequence: ?*?*IXpsOMDocumentSequence) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateDocumentSequence(@ptrCast(*const IXpsOMObjectFactory, self), partUri, documentSequence); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateDocument(self: *const T, partUri: ?*IOpcPartUri, document: ?*?*IXpsOMDocument) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateDocument(@ptrCast(*const IXpsOMObjectFactory, self), partUri, document); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePageReference(self: *const T, advisoryPageDimensions: ?*const XPS_SIZE, pageReference: ?*?*IXpsOMPageReference) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePageReference(@ptrCast(*const IXpsOMObjectFactory, self), advisoryPageDimensions, pageReference); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePage(self: *const T, pageDimensions: ?*const XPS_SIZE, language: ?[*:0]const u16, partUri: ?*IOpcPartUri, page: ?*?*IXpsOMPage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePage(@ptrCast(*const IXpsOMObjectFactory, self), pageDimensions, language, partUri, page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePageFromStream(self: *const T, pageMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, reuseObjects: BOOL, page: ?*?*IXpsOMPage) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePageFromStream(@ptrCast(*const IXpsOMObjectFactory, self), pageMarkupStream, partUri, resources, reuseObjects, page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateCanvas(self: *const T, canvas: ?*?*IXpsOMCanvas) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateCanvas(@ptrCast(*const IXpsOMObjectFactory, self), canvas); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateGlyphs(self: *const T, fontResource: ?*IXpsOMFontResource, glyphs: ?*?*IXpsOMGlyphs) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateGlyphs(@ptrCast(*const IXpsOMObjectFactory, self), fontResource, glyphs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePath(self: *const T, path: ?*?*IXpsOMPath) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePath(@ptrCast(*const IXpsOMObjectFactory, self), path); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateGeometry(self: *const T, geometry: ?*?*IXpsOMGeometry) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateGeometry(@ptrCast(*const IXpsOMObjectFactory, self), geometry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateGeometryFigure(self: *const T, startPoint: ?*const XPS_POINT, figure: ?*?*IXpsOMGeometryFigure) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateGeometryFigure(@ptrCast(*const IXpsOMObjectFactory, self), startPoint, figure); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateMatrixTransform(self: *const T, matrix: ?*const XPS_MATRIX, transform: ?*?*IXpsOMMatrixTransform) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateMatrixTransform(@ptrCast(*const IXpsOMObjectFactory, self), matrix, transform); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateSolidColorBrush(self: *const T, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, solidColorBrush: ?*?*IXpsOMSolidColorBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateSolidColorBrush(@ptrCast(*const IXpsOMObjectFactory, self), color, colorProfile, solidColorBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateColorProfileResource(self: *const T, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, colorProfileResource: ?*?*IXpsOMColorProfileResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateColorProfileResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, partUri, colorProfileResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateImageBrush(self: *const T, image: ?*IXpsOMImageResource, viewBox: ?*const XPS_RECT, viewPort: ?*const XPS_RECT, imageBrush: ?*?*IXpsOMImageBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateImageBrush(@ptrCast(*const IXpsOMObjectFactory, self), image, viewBox, viewPort, imageBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateVisualBrush(self: *const T, viewBox: ?*const XPS_RECT, viewPort: ?*const XPS_RECT, visualBrush: ?*?*IXpsOMVisualBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateVisualBrush(@ptrCast(*const IXpsOMObjectFactory, self), viewBox, viewPort, visualBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateImageResource(self: *const T, acquiredStream: ?*IStream, contentType: XPS_IMAGE_TYPE, partUri: ?*IOpcPartUri, imageResource: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateImageResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, contentType, partUri, imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePrintTicketResource(self: *const T, acquiredStream: ?*IStream, partUri: ?*IOpcPartUri, printTicketResource: ?*?*IXpsOMPrintTicketResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePrintTicketResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, partUri, printTicketResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateFontResource(self: *const T, acquiredStream: ?*IStream, fontEmbedding: XPS_FONT_EMBEDDING, partUri: ?*IOpcPartUri, isObfSourceStream: BOOL, fontResource: ?*?*IXpsOMFontResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateFontResource(@ptrCast(*const IXpsOMObjectFactory, self), acquiredStream, fontEmbedding, partUri, isObfSourceStream, fontResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateGradientStop(self: *const T, color: ?*const XPS_COLOR, colorProfile: ?*IXpsOMColorProfileResource, offset: f32, gradientStop: ?*?*IXpsOMGradientStop) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateGradientStop(@ptrCast(*const IXpsOMObjectFactory, self), color, colorProfile, offset, gradientStop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateLinearGradientBrush(self: *const T, gradStop1: ?*IXpsOMGradientStop, gradStop2: ?*IXpsOMGradientStop, startPoint: ?*const XPS_POINT, endPoint: ?*const XPS_POINT, linearGradientBrush: ?*?*IXpsOMLinearGradientBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateLinearGradientBrush(@ptrCast(*const IXpsOMObjectFactory, self), gradStop1, gradStop2, startPoint, endPoint, linearGradientBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateRadialGradientBrush(self: *const T, gradStop1: ?*IXpsOMGradientStop, gradStop2: ?*IXpsOMGradientStop, centerPoint: ?*const XPS_POINT, gradientOrigin: ?*const XPS_POINT, radiiSizes: ?*const XPS_SIZE, radialGradientBrush: ?*?*IXpsOMRadialGradientBrush) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateRadialGradientBrush(@ptrCast(*const IXpsOMObjectFactory, self), gradStop1, gradStop2, centerPoint, gradientOrigin, radiiSizes, radialGradientBrush); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateCoreProperties(self: *const T, partUri: ?*IOpcPartUri, coreProperties: ?*?*IXpsOMCoreProperties) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateCoreProperties(@ptrCast(*const IXpsOMObjectFactory, self), partUri, coreProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateDictionary(self: *const T, dictionary: ?*?*IXpsOMDictionary) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateDictionary(@ptrCast(*const IXpsOMObjectFactory, self), dictionary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePartUriCollection(self: *const T, partUriCollection: ?*?*IXpsOMPartUriCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePartUriCollection(@ptrCast(*const IXpsOMObjectFactory, self), partUriCollection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePackageWriterOnFile(self: *const T, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePackageWriterOnFile(@ptrCast(*const IXpsOMObjectFactory, self), fileName, securityAttributes, flagsAndAttributes, optimizeMarkupSize, interleaving, documentSequencePartName, coreProperties, packageThumbnail, documentSequencePrintTicket, discardControlPartName, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePackageWriterOnStream(self: *const T, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePackageWriterOnStream(@ptrCast(*const IXpsOMObjectFactory, self), outputStream, optimizeMarkupSize, interleaving, documentSequencePartName, coreProperties, packageThumbnail, documentSequencePrintTicket, discardControlPartName, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreatePartUri(self: *const T, uri: ?[*:0]const u16, partUri: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreatePartUri(@ptrCast(*const IXpsOMObjectFactory, self), uri, partUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory_CreateReadOnlyStreamOnFile(self: *const T, filename: ?[*:0]const u16, stream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory.VTable, self.vtable).CreateReadOnlyStreamOnFile(@ptrCast(*const IXpsOMObjectFactory, self), filename, stream); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMNameCollection_Value = Guid.initString("4bddf8ec-c915-421b-a166-d173d25653d2"); pub const IID_IXpsOMNameCollection = &IID_IXpsOMNameCollection_Value; pub const IXpsOMNameCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMNameCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMNameCollection, index: u32, name: ?*?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 IXpsOMNameCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMNameCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMNameCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMNameCollection_GetAt(self: *const T, index: u32, name: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMNameCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMNameCollection, self), index, name); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPartUriCollection_Value = Guid.initString("57c650d4-067c-4893-8c33-f62a0633730f"); pub const IID_IXpsOMPartUriCollection = &IID_IXpsOMPartUriCollection_Value; pub const IXpsOMPartUriCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsOMPartUriCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsOMPartUriCollection, index: u32, partUri: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertAt: fn( self: *const IXpsOMPartUriCollection, index: u32, partUri: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsOMPartUriCollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAt: fn( self: *const IXpsOMPartUriCollection, index: u32, partUri: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IXpsOMPartUriCollection, partUri: ?*IOpcPartUri, ) 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 IXpsOMPartUriCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsOMPartUriCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartUriCollection_GetAt(self: *const T, index: u32, partUri: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsOMPartUriCollection, self), index, partUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartUriCollection_InsertAt(self: *const T, index: u32, partUri: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).InsertAt(@ptrCast(*const IXpsOMPartUriCollection, self), index, partUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartUriCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsOMPartUriCollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartUriCollection_SetAt(self: *const T, index: u32, partUri: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).SetAt(@ptrCast(*const IXpsOMPartUriCollection, self), index, partUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPartUriCollection_Append(self: *const T, partUri: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPartUriCollection.VTable, self.vtable).Append(@ptrCast(*const IXpsOMPartUriCollection, self), partUri); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPackageWriter_Value = Guid.initString("4e2aa182-a443-42c6-b41b-4f8e9de73ff9"); pub const IID_IXpsOMPackageWriter = &IID_IXpsOMPackageWriter_Value; pub const IXpsOMPackageWriter = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartNewDocument: fn( self: *const IXpsOMPackageWriter, documentPartName: ?*IOpcPartUri, documentPrintTicket: ?*IXpsOMPrintTicketResource, documentStructure: ?*IXpsOMDocumentStructureResource, signatureBlockResources: ?*IXpsOMSignatureBlockResourceCollection, restrictedFonts: ?*IXpsOMPartUriCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPage: fn( self: *const IXpsOMPackageWriter, page: ?*IXpsOMPage, advisoryPageDimensions: ?*const XPS_SIZE, discardableResourceParts: ?*IXpsOMPartUriCollection, storyFragments: ?*IXpsOMStoryFragmentsResource, pagePrintTicket: ?*IXpsOMPrintTicketResource, pageThumbnail: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddResource: fn( self: *const IXpsOMPackageWriter, resource: ?*IXpsOMResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsClosed: fn( self: *const IXpsOMPackageWriter, isClosed: ?*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 IXpsOMPackageWriter_StartNewDocument(self: *const T, documentPartName: ?*IOpcPartUri, documentPrintTicket: ?*IXpsOMPrintTicketResource, documentStructure: ?*IXpsOMDocumentStructureResource, signatureBlockResources: ?*IXpsOMSignatureBlockResourceCollection, restrictedFonts: ?*IXpsOMPartUriCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter.VTable, self.vtable).StartNewDocument(@ptrCast(*const IXpsOMPackageWriter, self), documentPartName, documentPrintTicket, documentStructure, signatureBlockResources, restrictedFonts); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter_AddPage(self: *const T, page: ?*IXpsOMPage, advisoryPageDimensions: ?*const XPS_SIZE, discardableResourceParts: ?*IXpsOMPartUriCollection, storyFragments: ?*IXpsOMStoryFragmentsResource, pagePrintTicket: ?*IXpsOMPrintTicketResource, pageThumbnail: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter.VTable, self.vtable).AddPage(@ptrCast(*const IXpsOMPackageWriter, self), page, advisoryPageDimensions, discardableResourceParts, storyFragments, pagePrintTicket, pageThumbnail); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter_AddResource(self: *const T, resource: ?*IXpsOMResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter.VTable, self.vtable).AddResource(@ptrCast(*const IXpsOMPackageWriter, self), resource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter.VTable, self.vtable).Close(@ptrCast(*const IXpsOMPackageWriter, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter_IsClosed(self: *const T, isClosed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter.VTable, self.vtable).IsClosed(@ptrCast(*const IXpsOMPackageWriter, self), isClosed); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMPackageTarget_Value = Guid.initString("219a9db0-4959-47d0-8034-b1ce84f41a4d"); pub const IID_IXpsOMPackageTarget = &IID_IXpsOMPackageTarget_Value; pub const IXpsOMPackageTarget = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateXpsOMPackageWriter: fn( self: *const IXpsOMPackageTarget, documentSequencePartName: ?*IOpcPartUri, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter, ) 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 IXpsOMPackageTarget_CreateXpsOMPackageWriter(self: *const T, documentSequencePartName: ?*IOpcPartUri, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageTarget.VTable, self.vtable).CreateXpsOMPackageWriter(@ptrCast(*const IXpsOMPackageTarget, self), documentSequencePartName, documentSequencePrintTicket, discardControlPartName, packageWriter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsOMThumbnailGenerator_Value = Guid.initString("15b873d5-1971-41e8-83a3-6578403064c7"); pub const IID_IXpsOMThumbnailGenerator = &IID_IXpsOMThumbnailGenerator_Value; pub const IXpsOMThumbnailGenerator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GenerateThumbnail: fn( self: *const IXpsOMThumbnailGenerator, page: ?*IXpsOMPage, thumbnailType: XPS_IMAGE_TYPE, thumbnailSize: XPS_THUMBNAIL_SIZE, imageResourcePartName: ?*IOpcPartUri, imageResource: ?*?*IXpsOMImageResource, ) 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 IXpsOMThumbnailGenerator_GenerateThumbnail(self: *const T, page: ?*IXpsOMPage, thumbnailType: XPS_IMAGE_TYPE, thumbnailSize: XPS_THUMBNAIL_SIZE, imageResourcePartName: ?*IOpcPartUri, imageResource: ?*?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMThumbnailGenerator.VTable, self.vtable).GenerateThumbnail(@ptrCast(*const IXpsOMThumbnailGenerator, self), page, thumbnailType, thumbnailSize, imageResourcePartName, imageResource); } };} pub usingnamespace MethodMixin(@This()); }; pub const XPS_DOCUMENT_TYPE = enum(i32) { UNSPECIFIED = 1, XPS = 2, OPENXPS = 3, }; pub const XPS_DOCUMENT_TYPE_UNSPECIFIED = XPS_DOCUMENT_TYPE.UNSPECIFIED; pub const XPS_DOCUMENT_TYPE_XPS = XPS_DOCUMENT_TYPE.XPS; pub const XPS_DOCUMENT_TYPE_OPENXPS = XPS_DOCUMENT_TYPE.OPENXPS; // TODO: this type is limited to platform 'windows8.0' const IID_IXpsOMObjectFactory1_Value = Guid.initString("0a91b617-d612-4181-bf7c-be5824e9cc8f"); pub const IID_IXpsOMObjectFactory1 = &IID_IXpsOMObjectFactory1_Value; pub const IXpsOMObjectFactory1 = extern struct { pub const VTable = extern struct { base: IXpsOMObjectFactory.VTable, GetDocumentTypeFromFile: fn( self: *const IXpsOMObjectFactory1, filename: ?[*:0]const u16, documentType: ?*XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentTypeFromStream: fn( self: *const IXpsOMObjectFactory1, xpsDocumentStream: ?*IStream, documentType: ?*XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertHDPhotoToJpegXR: fn( self: *const IXpsOMObjectFactory1, imageResource: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertJpegXRToHDPhoto: fn( self: *const IXpsOMObjectFactory1, imageResource: ?*IXpsOMImageResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageWriterOnFile1: fn( self: *const IXpsOMObjectFactory1, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, documentType: XPS_DOCUMENT_TYPE, packageWriter: ?*?*IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageWriterOnStream1: fn( self: *const IXpsOMObjectFactory1, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, documentType: XPS_DOCUMENT_TYPE, packageWriter: ?*?*IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackage1: fn( self: *const IXpsOMObjectFactory1, package: ?*?*IXpsOMPackage1, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageFromStream1: fn( self: *const IXpsOMObjectFactory1, stream: ?*IStream, reuseObjects: BOOL, package: ?*?*IXpsOMPackage1, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePackageFromFile1: fn( self: *const IXpsOMObjectFactory1, filename: ?[*:0]const u16, reuseObjects: BOOL, package: ?*?*IXpsOMPackage1, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePage1: fn( self: *const IXpsOMObjectFactory1, pageDimensions: ?*const XPS_SIZE, language: ?[*:0]const u16, partUri: ?*IOpcPartUri, page: ?*?*IXpsOMPage1, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePageFromStream1: fn( self: *const IXpsOMObjectFactory1, pageMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, reuseObjects: BOOL, page: ?*?*IXpsOMPage1, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRemoteDictionaryResourceFromStream1: fn( self: *const IXpsOMObjectFactory1, dictionaryMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, dictionaryResource: ?*?*IXpsOMRemoteDictionaryResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMObjectFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_GetDocumentTypeFromFile(self: *const T, filename: ?[*:0]const u16, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).GetDocumentTypeFromFile(@ptrCast(*const IXpsOMObjectFactory1, self), filename, documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_GetDocumentTypeFromStream(self: *const T, xpsDocumentStream: ?*IStream, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).GetDocumentTypeFromStream(@ptrCast(*const IXpsOMObjectFactory1, self), xpsDocumentStream, documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_ConvertHDPhotoToJpegXR(self: *const T, imageResource: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).ConvertHDPhotoToJpegXR(@ptrCast(*const IXpsOMObjectFactory1, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_ConvertJpegXRToHDPhoto(self: *const T, imageResource: ?*IXpsOMImageResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).ConvertJpegXRToHDPhoto(@ptrCast(*const IXpsOMObjectFactory1, self), imageResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePackageWriterOnFile1(self: *const T, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, documentType: XPS_DOCUMENT_TYPE, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePackageWriterOnFile1(@ptrCast(*const IXpsOMObjectFactory1, self), fileName, securityAttributes, flagsAndAttributes, optimizeMarkupSize, interleaving, documentSequencePartName, coreProperties, packageThumbnail, documentSequencePrintTicket, discardControlPartName, documentType, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePackageWriterOnStream1(self: *const T, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, interleaving: XPS_INTERLEAVING, documentSequencePartName: ?*IOpcPartUri, coreProperties: ?*IXpsOMCoreProperties, packageThumbnail: ?*IXpsOMImageResource, documentSequencePrintTicket: ?*IXpsOMPrintTicketResource, discardControlPartName: ?*IOpcPartUri, documentType: XPS_DOCUMENT_TYPE, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePackageWriterOnStream1(@ptrCast(*const IXpsOMObjectFactory1, self), outputStream, optimizeMarkupSize, interleaving, documentSequencePartName, coreProperties, packageThumbnail, documentSequencePrintTicket, discardControlPartName, documentType, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePackage1(self: *const T, package: ?*?*IXpsOMPackage1) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePackage1(@ptrCast(*const IXpsOMObjectFactory1, self), package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePackageFromStream1(self: *const T, stream: ?*IStream, reuseObjects: BOOL, package: ?*?*IXpsOMPackage1) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePackageFromStream1(@ptrCast(*const IXpsOMObjectFactory1, self), stream, reuseObjects, package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePackageFromFile1(self: *const T, filename: ?[*:0]const u16, reuseObjects: BOOL, package: ?*?*IXpsOMPackage1) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePackageFromFile1(@ptrCast(*const IXpsOMObjectFactory1, self), filename, reuseObjects, package); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePage1(self: *const T, pageDimensions: ?*const XPS_SIZE, language: ?[*:0]const u16, partUri: ?*IOpcPartUri, page: ?*?*IXpsOMPage1) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePage1(@ptrCast(*const IXpsOMObjectFactory1, self), pageDimensions, language, partUri, page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreatePageFromStream1(self: *const T, pageMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, reuseObjects: BOOL, page: ?*?*IXpsOMPage1) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreatePageFromStream1(@ptrCast(*const IXpsOMObjectFactory1, self), pageMarkupStream, partUri, resources, reuseObjects, page); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMObjectFactory1_CreateRemoteDictionaryResourceFromStream1(self: *const T, dictionaryMarkupStream: ?*IStream, partUri: ?*IOpcPartUri, resources: ?*IXpsOMPartResources, dictionaryResource: ?*?*IXpsOMRemoteDictionaryResource) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMObjectFactory1.VTable, self.vtable).CreateRemoteDictionaryResourceFromStream1(@ptrCast(*const IXpsOMObjectFactory1, self), dictionaryMarkupStream, partUri, resources, dictionaryResource); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IXpsOMPackage1_Value = Guid.initString("95a9435e-12bb-461b-8e7f-c6adb04cd96a"); pub const IID_IXpsOMPackage1 = &IID_IXpsOMPackage1_Value; pub const IXpsOMPackage1 = extern struct { pub const VTable = extern struct { base: IXpsOMPackage.VTable, GetDocumentType: fn( self: *const IXpsOMPackage1, documentType: ?*XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteToFile1: fn( self: *const IXpsOMPackage1, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteToStream1: fn( self: *const IXpsOMPackage1, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPackage.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage1_GetDocumentType(self: *const T, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage1.VTable, self.vtable).GetDocumentType(@ptrCast(*const IXpsOMPackage1, self), documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage1_WriteToFile1(self: *const T, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage1.VTable, self.vtable).WriteToFile1(@ptrCast(*const IXpsOMPackage1, self), fileName, securityAttributes, flagsAndAttributes, optimizeMarkupSize, documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackage1_WriteToStream1(self: *const T, outputStream: ?*ISequentialStream, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackage1.VTable, self.vtable).WriteToStream1(@ptrCast(*const IXpsOMPackage1, self), outputStream, optimizeMarkupSize, documentType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IXpsOMPage1_Value = Guid.initString("305b60ef-6892-4dda-9cbb-3aa65974508a"); pub const IID_IXpsOMPage1 = &IID_IXpsOMPage1_Value; pub const IXpsOMPage1 = extern struct { pub const VTable = extern struct { base: IXpsOMPage.VTable, GetDocumentType: fn( self: *const IXpsOMPage1, documentType: ?*XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Write1: fn( self: *const IXpsOMPage1, stream: ?*ISequentialStream, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPage.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage1_GetDocumentType(self: *const T, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage1.VTable, self.vtable).GetDocumentType(@ptrCast(*const IXpsOMPage1, self), documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPage1_Write1(self: *const T, stream: ?*ISequentialStream, optimizeMarkupSize: BOOL, documentType: XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPage1.VTable, self.vtable).Write1(@ptrCast(*const IXpsOMPage1, self), stream, optimizeMarkupSize, documentType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IXpsDocumentPackageTarget_Value = Guid.initString("3b0b6d38-53ad-41da-b212-d37637a6714e"); pub const IID_IXpsDocumentPackageTarget = &IID_IXpsDocumentPackageTarget_Value; pub const IXpsDocumentPackageTarget = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetXpsOMPackageWriter: fn( self: *const IXpsDocumentPackageTarget, documentSequencePartName: ?*IOpcPartUri, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXpsOMFactory: fn( self: *const IXpsDocumentPackageTarget, xpsFactory: ?*?*IXpsOMObjectFactory, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXpsType: fn( self: *const IXpsDocumentPackageTarget, documentType: ?*XPS_DOCUMENT_TYPE, ) 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 IXpsDocumentPackageTarget_GetXpsOMPackageWriter(self: *const T, documentSequencePartName: ?*IOpcPartUri, discardControlPartName: ?*IOpcPartUri, packageWriter: ?*?*IXpsOMPackageWriter) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsDocumentPackageTarget.VTable, self.vtable).GetXpsOMPackageWriter(@ptrCast(*const IXpsDocumentPackageTarget, self), documentSequencePartName, discardControlPartName, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsDocumentPackageTarget_GetXpsOMFactory(self: *const T, xpsFactory: ?*?*IXpsOMObjectFactory) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsDocumentPackageTarget.VTable, self.vtable).GetXpsOMFactory(@ptrCast(*const IXpsDocumentPackageTarget, self), xpsFactory); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsDocumentPackageTarget_GetXpsType(self: *const T, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsDocumentPackageTarget.VTable, self.vtable).GetXpsType(@ptrCast(*const IXpsDocumentPackageTarget, self), documentType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IXpsOMRemoteDictionaryResource1_Value = Guid.initString("bf8fc1d4-9d46-4141-ba5f-94bb9250d041"); pub const IID_IXpsOMRemoteDictionaryResource1 = &IID_IXpsOMRemoteDictionaryResource1_Value; pub const IXpsOMRemoteDictionaryResource1 = extern struct { pub const VTable = extern struct { base: IXpsOMRemoteDictionaryResource.VTable, GetDocumentType: fn( self: *const IXpsOMRemoteDictionaryResource1, documentType: ?*XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Write1: fn( self: *const IXpsOMRemoteDictionaryResource1, stream: ?*ISequentialStream, documentType: XPS_DOCUMENT_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMRemoteDictionaryResource.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResource1_GetDocumentType(self: *const T, documentType: ?*XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResource1.VTable, self.vtable).GetDocumentType(@ptrCast(*const IXpsOMRemoteDictionaryResource1, self), documentType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMRemoteDictionaryResource1_Write1(self: *const T, stream: ?*ISequentialStream, documentType: XPS_DOCUMENT_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMRemoteDictionaryResource1.VTable, self.vtable).Write1(@ptrCast(*const IXpsOMRemoteDictionaryResource1, self), stream, documentType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IXpsOMPackageWriter3D_Value = Guid.initString("e8a45033-640e-43fa-9bdf-fddeaa31c6a0"); pub const IID_IXpsOMPackageWriter3D = &IID_IXpsOMPackageWriter3D_Value; pub const IXpsOMPackageWriter3D = extern struct { pub const VTable = extern struct { base: IXpsOMPackageWriter.VTable, AddModelTexture: fn( self: *const IXpsOMPackageWriter3D, texturePartName: ?*IOpcPartUri, textureData: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetModelPrintTicket: fn( self: *const IXpsOMPackageWriter3D, printTicketPartName: ?*IOpcPartUri, printTicketData: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IXpsOMPackageWriter.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter3D_AddModelTexture(self: *const T, texturePartName: ?*IOpcPartUri, textureData: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter3D.VTable, self.vtable).AddModelTexture(@ptrCast(*const IXpsOMPackageWriter3D, self), texturePartName, textureData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsOMPackageWriter3D_SetModelPrintTicket(self: *const T, printTicketPartName: ?*IOpcPartUri, printTicketData: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsOMPackageWriter3D.VTable, self.vtable).SetModelPrintTicket(@ptrCast(*const IXpsOMPackageWriter3D, self), printTicketPartName, printTicketData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IXpsDocumentPackageTarget3D_Value = Guid.initString("60ba71b8-3101-4984-9199-f4ea775ff01d"); pub const IID_IXpsDocumentPackageTarget3D = &IID_IXpsDocumentPackageTarget3D_Value; pub const IXpsDocumentPackageTarget3D = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetXpsOMPackageWriter3D: fn( self: *const IXpsDocumentPackageTarget3D, documentSequencePartName: ?*IOpcPartUri, discardControlPartName: ?*IOpcPartUri, modelPartName: ?*IOpcPartUri, modelData: ?*IStream, packageWriter: ?*?*IXpsOMPackageWriter3D, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXpsOMFactory: fn( self: *const IXpsDocumentPackageTarget3D, xpsFactory: ?*?*IXpsOMObjectFactory, ) 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 IXpsDocumentPackageTarget3D_GetXpsOMPackageWriter3D(self: *const T, documentSequencePartName: ?*IOpcPartUri, discardControlPartName: ?*IOpcPartUri, modelPartName: ?*IOpcPartUri, modelData: ?*IStream, packageWriter: ?*?*IXpsOMPackageWriter3D) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsDocumentPackageTarget3D.VTable, self.vtable).GetXpsOMPackageWriter3D(@ptrCast(*const IXpsDocumentPackageTarget3D, self), documentSequencePartName, discardControlPartName, modelPartName, modelData, packageWriter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsDocumentPackageTarget3D_GetXpsOMFactory(self: *const T, xpsFactory: ?*?*IXpsOMObjectFactory) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsDocumentPackageTarget3D.VTable, self.vtable).GetXpsOMFactory(@ptrCast(*const IXpsDocumentPackageTarget3D, self), xpsFactory); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_XpsSignatureManager_Value = Guid.initString("b0c43320-2315-44a2-b70a-0943a140a8ee"); pub const CLSID_XpsSignatureManager = &CLSID_XpsSignatureManager_Value; pub const XPS_SIGNATURE_STATUS = enum(i32) { INCOMPLIANT = 1, INCOMPLETE = 2, BROKEN = 3, QUESTIONABLE = 4, VALID = 5, }; pub const XPS_SIGNATURE_STATUS_INCOMPLIANT = XPS_SIGNATURE_STATUS.INCOMPLIANT; pub const XPS_SIGNATURE_STATUS_INCOMPLETE = XPS_SIGNATURE_STATUS.INCOMPLETE; pub const XPS_SIGNATURE_STATUS_BROKEN = XPS_SIGNATURE_STATUS.BROKEN; pub const XPS_SIGNATURE_STATUS_QUESTIONABLE = XPS_SIGNATURE_STATUS.QUESTIONABLE; pub const XPS_SIGNATURE_STATUS_VALID = XPS_SIGNATURE_STATUS.VALID; pub const XPS_SIGN_POLICY = enum(i32) { NONE = 0, CORE_PROPERTIES = 1, SIGNATURE_RELATIONSHIPS = 2, PRINT_TICKET = 4, DISCARD_CONTROL = 8, ALL = 15, }; pub const XPS_SIGN_POLICY_NONE = XPS_SIGN_POLICY.NONE; pub const XPS_SIGN_POLICY_CORE_PROPERTIES = XPS_SIGN_POLICY.CORE_PROPERTIES; pub const XPS_SIGN_POLICY_SIGNATURE_RELATIONSHIPS = XPS_SIGN_POLICY.SIGNATURE_RELATIONSHIPS; pub const XPS_SIGN_POLICY_PRINT_TICKET = XPS_SIGN_POLICY.PRINT_TICKET; pub const XPS_SIGN_POLICY_DISCARD_CONTROL = XPS_SIGN_POLICY.DISCARD_CONTROL; pub const XPS_SIGN_POLICY_ALL = XPS_SIGN_POLICY.ALL; pub const XPS_SIGN_FLAGS = enum(i32) { NONE = 0, IGNORE_MARKUP_COMPATIBILITY = 1, }; pub const XPS_SIGN_FLAGS_NONE = XPS_SIGN_FLAGS.NONE; pub const XPS_SIGN_FLAGS_IGNORE_MARKUP_COMPATIBILITY = XPS_SIGN_FLAGS.IGNORE_MARKUP_COMPATIBILITY; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSigningOptions_Value = Guid.initString("7718eae4-3215-49be-af5b-594fef7fcfa6"); pub const IID_IXpsSigningOptions = &IID_IXpsSigningOptions_Value; pub const IXpsSigningOptions = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSignatureId: fn( self: *const IXpsSigningOptions, signatureId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSignatureId: fn( self: *const IXpsSigningOptions, signatureId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureMethod: fn( self: *const IXpsSigningOptions, signatureMethod: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSignatureMethod: fn( self: *const IXpsSigningOptions, signatureMethod: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDigestMethod: fn( self: *const IXpsSigningOptions, digestMethod: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDigestMethod: fn( self: *const IXpsSigningOptions, digestMethod: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignaturePartName: fn( self: *const IXpsSigningOptions, signaturePartName: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSignaturePartName: fn( self: *const IXpsSigningOptions, signaturePartName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPolicy: fn( self: *const IXpsSigningOptions, policy: ?*XPS_SIGN_POLICY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPolicy: fn( self: *const IXpsSigningOptions, policy: XPS_SIGN_POLICY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSigningTimeFormat: fn( self: *const IXpsSigningOptions, timeFormat: ?*OPC_SIGNATURE_TIME_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSigningTimeFormat: fn( self: *const IXpsSigningOptions, timeFormat: OPC_SIGNATURE_TIME_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCustomObjects: fn( self: *const IXpsSigningOptions, customObjectSet: ?*?*IOpcSignatureCustomObjectSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCustomReferences: fn( self: *const IXpsSigningOptions, customReferenceSet: ?*?*IOpcSignatureReferenceSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCertificateSet: fn( self: *const IXpsSigningOptions, certificateSet: ?*?*IOpcCertificateSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlags: fn( self: *const IXpsSigningOptions, flags: ?*XPS_SIGN_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFlags: fn( self: *const IXpsSigningOptions, flags: XPS_SIGN_FLAGS, ) 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 IXpsSigningOptions_GetSignatureId(self: *const T, signatureId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetSignatureId(@ptrCast(*const IXpsSigningOptions, self), signatureId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetSignatureId(self: *const T, signatureId: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetSignatureId(@ptrCast(*const IXpsSigningOptions, self), signatureId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetSignatureMethod(self: *const T, signatureMethod: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetSignatureMethod(@ptrCast(*const IXpsSigningOptions, self), signatureMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetSignatureMethod(self: *const T, signatureMethod: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetSignatureMethod(@ptrCast(*const IXpsSigningOptions, self), signatureMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetDigestMethod(self: *const T, digestMethod: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetDigestMethod(@ptrCast(*const IXpsSigningOptions, self), digestMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetDigestMethod(self: *const T, digestMethod: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetDigestMethod(@ptrCast(*const IXpsSigningOptions, self), digestMethod); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetSignaturePartName(self: *const T, signaturePartName: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetSignaturePartName(@ptrCast(*const IXpsSigningOptions, self), signaturePartName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetSignaturePartName(self: *const T, signaturePartName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetSignaturePartName(@ptrCast(*const IXpsSigningOptions, self), signaturePartName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetPolicy(self: *const T, policy: ?*XPS_SIGN_POLICY) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetPolicy(@ptrCast(*const IXpsSigningOptions, self), policy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetPolicy(self: *const T, policy: XPS_SIGN_POLICY) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetPolicy(@ptrCast(*const IXpsSigningOptions, self), policy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetSigningTimeFormat(self: *const T, timeFormat: ?*OPC_SIGNATURE_TIME_FORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetSigningTimeFormat(@ptrCast(*const IXpsSigningOptions, self), timeFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetSigningTimeFormat(self: *const T, timeFormat: OPC_SIGNATURE_TIME_FORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetSigningTimeFormat(@ptrCast(*const IXpsSigningOptions, self), timeFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetCustomObjects(self: *const T, customObjectSet: ?*?*IOpcSignatureCustomObjectSet) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetCustomObjects(@ptrCast(*const IXpsSigningOptions, self), customObjectSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetCustomReferences(self: *const T, customReferenceSet: ?*?*IOpcSignatureReferenceSet) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetCustomReferences(@ptrCast(*const IXpsSigningOptions, self), customReferenceSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetCertificateSet(self: *const T, certificateSet: ?*?*IOpcCertificateSet) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetCertificateSet(@ptrCast(*const IXpsSigningOptions, self), certificateSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_GetFlags(self: *const T, flags: ?*XPS_SIGN_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).GetFlags(@ptrCast(*const IXpsSigningOptions, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSigningOptions_SetFlags(self: *const T, flags: XPS_SIGN_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSigningOptions.VTable, self.vtable).SetFlags(@ptrCast(*const IXpsSigningOptions, self), flags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureCollection_Value = Guid.initString("a2d1d95d-add2-4dff-ab27-6b9c645ff322"); pub const IID_IXpsSignatureCollection = &IID_IXpsSignatureCollection_Value; pub const IXpsSignatureCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsSignatureCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsSignatureCollection, index: u32, signature: ?*?*IXpsSignature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsSignatureCollection, index: 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 IXpsSignatureCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsSignatureCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureCollection_GetAt(self: *const T, index: u32, signature: ?*?*IXpsSignature) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsSignatureCollection, self), index, signature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsSignatureCollection, self), index); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignature_Value = Guid.initString("6ae4c93e-1ade-42fb-898b-3a5658284857"); pub const IID_IXpsSignature = &IID_IXpsSignature_Value; pub const IXpsSignature = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSignatureId: fn( self: *const IXpsSignature, sigId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureValue: fn( self: *const IXpsSignature, signatureHashValue: [*]?*u8, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCertificateEnumerator: fn( self: *const IXpsSignature, certificateEnumerator: ?*?*IOpcCertificateEnumerator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSigningTime: fn( self: *const IXpsSignature, sigDateTimeString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSigningTimeFormat: fn( self: *const IXpsSignature, timeFormat: ?*OPC_SIGNATURE_TIME_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignaturePartName: fn( self: *const IXpsSignature, signaturePartName: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Verify: fn( self: *const IXpsSignature, x509Certificate: ?*const CERT_CONTEXT, sigStatus: ?*XPS_SIGNATURE_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPolicy: fn( self: *const IXpsSignature, policy: ?*XPS_SIGN_POLICY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCustomObjectEnumerator: fn( self: *const IXpsSignature, customObjectEnumerator: ?*?*IOpcSignatureCustomObjectEnumerator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCustomReferenceEnumerator: fn( self: *const IXpsSignature, customReferenceEnumerator: ?*?*IOpcSignatureReferenceEnumerator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureXml: fn( self: *const IXpsSignature, signatureXml: [*]?*u8, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSignatureXml: fn( self: *const IXpsSignature, signatureXml: [*:0]const u8, count: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSignatureId(self: *const T, sigId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSignatureId(@ptrCast(*const IXpsSignature, self), sigId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSignatureValue(self: *const T, signatureHashValue: [*]?*u8, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSignatureValue(@ptrCast(*const IXpsSignature, self), signatureHashValue, count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetCertificateEnumerator(self: *const T, certificateEnumerator: ?*?*IOpcCertificateEnumerator) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetCertificateEnumerator(@ptrCast(*const IXpsSignature, self), certificateEnumerator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSigningTime(self: *const T, sigDateTimeString: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSigningTime(@ptrCast(*const IXpsSignature, self), sigDateTimeString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSigningTimeFormat(self: *const T, timeFormat: ?*OPC_SIGNATURE_TIME_FORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSigningTimeFormat(@ptrCast(*const IXpsSignature, self), timeFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSignaturePartName(self: *const T, signaturePartName: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSignaturePartName(@ptrCast(*const IXpsSignature, self), signaturePartName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_Verify(self: *const T, x509Certificate: ?*const CERT_CONTEXT, sigStatus: ?*XPS_SIGNATURE_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).Verify(@ptrCast(*const IXpsSignature, self), x509Certificate, sigStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetPolicy(self: *const T, policy: ?*XPS_SIGN_POLICY) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetPolicy(@ptrCast(*const IXpsSignature, self), policy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetCustomObjectEnumerator(self: *const T, customObjectEnumerator: ?*?*IOpcSignatureCustomObjectEnumerator) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetCustomObjectEnumerator(@ptrCast(*const IXpsSignature, self), customObjectEnumerator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetCustomReferenceEnumerator(self: *const T, customReferenceEnumerator: ?*?*IOpcSignatureReferenceEnumerator) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetCustomReferenceEnumerator(@ptrCast(*const IXpsSignature, self), customReferenceEnumerator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_GetSignatureXml(self: *const T, signatureXml: [*]?*u8, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).GetSignatureXml(@ptrCast(*const IXpsSignature, self), signatureXml, count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignature_SetSignatureXml(self: *const T, signatureXml: [*:0]const u8, count: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignature.VTable, self.vtable).SetSignatureXml(@ptrCast(*const IXpsSignature, self), signatureXml, count); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureBlockCollection_Value = Guid.initString("23397050-fe99-467a-8dce-9237f074ffe4"); pub const IID_IXpsSignatureBlockCollection = &IID_IXpsSignatureBlockCollection_Value; pub const IXpsSignatureBlockCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsSignatureBlockCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsSignatureBlockCollection, index: u32, signatureBlock: ?*?*IXpsSignatureBlock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsSignatureBlockCollection, index: 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 IXpsSignatureBlockCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlockCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsSignatureBlockCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlockCollection_GetAt(self: *const T, index: u32, signatureBlock: ?*?*IXpsSignatureBlock) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlockCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsSignatureBlockCollection, self), index, signatureBlock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlockCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlockCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsSignatureBlockCollection, self), index); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureBlock_Value = Guid.initString("151fac09-0b97-4ac6-a323-5e4297d4322b"); pub const IID_IXpsSignatureBlock = &IID_IXpsSignatureBlock_Value; pub const IXpsSignatureBlock = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetRequests: fn( self: *const IXpsSignatureBlock, requests: ?*?*IXpsSignatureRequestCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPartName: fn( self: *const IXpsSignatureBlock, partName: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentIndex: fn( self: *const IXpsSignatureBlock, fixedDocumentIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentName: fn( self: *const IXpsSignatureBlock, fixedDocumentName: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRequest: fn( self: *const IXpsSignatureBlock, requestId: ?[*:0]const u16, signatureRequest: ?*?*IXpsSignatureRequest, ) 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 IXpsSignatureBlock_GetRequests(self: *const T, requests: ?*?*IXpsSignatureRequestCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlock.VTable, self.vtable).GetRequests(@ptrCast(*const IXpsSignatureBlock, self), requests); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlock_GetPartName(self: *const T, partName: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlock.VTable, self.vtable).GetPartName(@ptrCast(*const IXpsSignatureBlock, self), partName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlock_GetDocumentIndex(self: *const T, fixedDocumentIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlock.VTable, self.vtable).GetDocumentIndex(@ptrCast(*const IXpsSignatureBlock, self), fixedDocumentIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlock_GetDocumentName(self: *const T, fixedDocumentName: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlock.VTable, self.vtable).GetDocumentName(@ptrCast(*const IXpsSignatureBlock, self), fixedDocumentName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureBlock_CreateRequest(self: *const T, requestId: ?[*:0]const u16, signatureRequest: ?*?*IXpsSignatureRequest) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureBlock.VTable, self.vtable).CreateRequest(@ptrCast(*const IXpsSignatureBlock, self), requestId, signatureRequest); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureRequestCollection_Value = Guid.initString("f0253e68-9f19-412e-9b4f-54d3b0ac6cd9"); pub const IID_IXpsSignatureRequestCollection = &IID_IXpsSignatureRequestCollection_Value; pub const IXpsSignatureRequestCollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IXpsSignatureRequestCollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IXpsSignatureRequestCollection, index: u32, signatureRequest: ?*?*IXpsSignatureRequest, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IXpsSignatureRequestCollection, index: 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 IXpsSignatureRequestCollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequestCollection.VTable, self.vtable).GetCount(@ptrCast(*const IXpsSignatureRequestCollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequestCollection_GetAt(self: *const T, index: u32, signatureRequest: ?*?*IXpsSignatureRequest) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequestCollection.VTable, self.vtable).GetAt(@ptrCast(*const IXpsSignatureRequestCollection, self), index, signatureRequest); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequestCollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequestCollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IXpsSignatureRequestCollection, self), index); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureRequest_Value = Guid.initString("ac58950b-7208-4b2d-b2c4-951083d3b8eb"); pub const IID_IXpsSignatureRequest = &IID_IXpsSignatureRequest_Value; pub const IXpsSignatureRequest = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetIntent: fn( self: *const IXpsSignatureRequest, intent: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetIntent: fn( self: *const IXpsSignatureRequest, intent: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRequestedSigner: fn( self: *const IXpsSignatureRequest, signerName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRequestedSigner: fn( self: *const IXpsSignatureRequest, signerName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRequestSignByDate: fn( self: *const IXpsSignatureRequest, dateString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRequestSignByDate: fn( self: *const IXpsSignatureRequest, dateString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSigningLocale: fn( self: *const IXpsSignatureRequest, place: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSigningLocale: fn( self: *const IXpsSignatureRequest, place: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSpotLocation: fn( self: *const IXpsSignatureRequest, pageIndex: ?*i32, pagePartName: ?*?*IOpcPartUri, x: ?*f32, y: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSpotLocation: fn( self: *const IXpsSignatureRequest, pageIndex: i32, x: f32, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRequestId: fn( self: *const IXpsSignatureRequest, requestId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignature: fn( self: *const IXpsSignatureRequest, signature: ?*?*IXpsSignature, ) 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 IXpsSignatureRequest_GetIntent(self: *const T, intent: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetIntent(@ptrCast(*const IXpsSignatureRequest, self), intent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_SetIntent(self: *const T, intent: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).SetIntent(@ptrCast(*const IXpsSignatureRequest, self), intent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetRequestedSigner(self: *const T, signerName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetRequestedSigner(@ptrCast(*const IXpsSignatureRequest, self), signerName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_SetRequestedSigner(self: *const T, signerName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).SetRequestedSigner(@ptrCast(*const IXpsSignatureRequest, self), signerName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetRequestSignByDate(self: *const T, dateString: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetRequestSignByDate(@ptrCast(*const IXpsSignatureRequest, self), dateString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_SetRequestSignByDate(self: *const T, dateString: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).SetRequestSignByDate(@ptrCast(*const IXpsSignatureRequest, self), dateString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetSigningLocale(self: *const T, place: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetSigningLocale(@ptrCast(*const IXpsSignatureRequest, self), place); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_SetSigningLocale(self: *const T, place: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).SetSigningLocale(@ptrCast(*const IXpsSignatureRequest, self), place); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetSpotLocation(self: *const T, pageIndex: ?*i32, pagePartName: ?*?*IOpcPartUri, x: ?*f32, y: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetSpotLocation(@ptrCast(*const IXpsSignatureRequest, self), pageIndex, pagePartName, x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_SetSpotLocation(self: *const T, pageIndex: i32, x: f32, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).SetSpotLocation(@ptrCast(*const IXpsSignatureRequest, self), pageIndex, x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetRequestId(self: *const T, requestId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetRequestId(@ptrCast(*const IXpsSignatureRequest, self), requestId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureRequest_GetSignature(self: *const T, signature: ?*?*IXpsSignature) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureRequest.VTable, self.vtable).GetSignature(@ptrCast(*const IXpsSignatureRequest, self), signature); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IXpsSignatureManager_Value = Guid.initString("d3e8d338-fdc4-4afc-80b5-d532a1782ee1"); pub const IID_IXpsSignatureManager = &IID_IXpsSignatureManager_Value; pub const IXpsSignatureManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, LoadPackageFile: fn( self: *const IXpsSignatureManager, fileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadPackageStream: fn( self: *const IXpsSignatureManager, stream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Sign: fn( self: *const IXpsSignatureManager, signOptions: ?*IXpsSigningOptions, x509Certificate: ?*const CERT_CONTEXT, signature: ?*?*IXpsSignature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureOriginPartName: fn( self: *const IXpsSignatureManager, signatureOriginPartName: ?*?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSignatureOriginPartName: fn( self: *const IXpsSignatureManager, signatureOriginPartName: ?*IOpcPartUri, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatures: fn( self: *const IXpsSignatureManager, signatures: ?*?*IXpsSignatureCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddSignatureBlock: fn( self: *const IXpsSignatureManager, partName: ?*IOpcPartUri, fixedDocumentIndex: u32, signatureBlock: ?*?*IXpsSignatureBlock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignatureBlocks: fn( self: *const IXpsSignatureManager, signatureBlocks: ?*?*IXpsSignatureBlockCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSigningOptions: fn( self: *const IXpsSignatureManager, signingOptions: ?*?*IXpsSigningOptions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SavePackageToFile: fn( self: *const IXpsSignatureManager, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SavePackageToStream: fn( self: *const IXpsSignatureManager, stream: ?*IStream, ) 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 IXpsSignatureManager_LoadPackageFile(self: *const T, fileName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).LoadPackageFile(@ptrCast(*const IXpsSignatureManager, self), fileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_LoadPackageStream(self: *const T, stream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).LoadPackageStream(@ptrCast(*const IXpsSignatureManager, self), stream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_Sign(self: *const T, signOptions: ?*IXpsSigningOptions, x509Certificate: ?*const CERT_CONTEXT, signature: ?*?*IXpsSignature) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).Sign(@ptrCast(*const IXpsSignatureManager, self), signOptions, x509Certificate, signature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_GetSignatureOriginPartName(self: *const T, signatureOriginPartName: ?*?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).GetSignatureOriginPartName(@ptrCast(*const IXpsSignatureManager, self), signatureOriginPartName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_SetSignatureOriginPartName(self: *const T, signatureOriginPartName: ?*IOpcPartUri) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).SetSignatureOriginPartName(@ptrCast(*const IXpsSignatureManager, self), signatureOriginPartName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_GetSignatures(self: *const T, signatures: ?*?*IXpsSignatureCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).GetSignatures(@ptrCast(*const IXpsSignatureManager, self), signatures); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_AddSignatureBlock(self: *const T, partName: ?*IOpcPartUri, fixedDocumentIndex: u32, signatureBlock: ?*?*IXpsSignatureBlock) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).AddSignatureBlock(@ptrCast(*const IXpsSignatureManager, self), partName, fixedDocumentIndex, signatureBlock); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_GetSignatureBlocks(self: *const T, signatureBlocks: ?*?*IXpsSignatureBlockCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).GetSignatureBlocks(@ptrCast(*const IXpsSignatureManager, self), signatureBlocks); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_CreateSigningOptions(self: *const T, signingOptions: ?*?*IXpsSigningOptions) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).CreateSigningOptions(@ptrCast(*const IXpsSignatureManager, self), signingOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_SavePackageToFile(self: *const T, fileName: ?[*:0]const u16, securityAttributes: ?*SECURITY_ATTRIBUTES, flagsAndAttributes: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).SavePackageToFile(@ptrCast(*const IXpsSignatureManager, self), fileName, securityAttributes, flagsAndAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsSignatureManager_SavePackageToStream(self: *const T, stream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsSignatureManager.VTable, self.vtable).SavePackageToStream(@ptrCast(*const IXpsSignatureManager, self), stream); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (12) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "WINSPOOL" fn DeviceCapabilitiesA( pDevice: ?[*:0]const u8, pPort: ?[*:0]const u8, fwCapability: DEVICE_CAPABILITIES, pOutput: ?PSTR, pDevMode: ?*const DEVMODEA, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "WINSPOOL" fn DeviceCapabilitiesW( pDevice: ?[*:0]const u16, pPort: ?[*:0]const u16, fwCapability: DEVICE_CAPABILITIES, pOutput: ?PWSTR, pDevMode: ?*const DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn Escape( hdc: ?HDC, iEscape: i32, cjIn: i32, // TODO: what to do with BytesParamIndex 2? pvIn: ?[*:0]const u8, pvOut: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn ExtEscape( hdc: ?HDC, iEscape: i32, cjInput: i32, // TODO: what to do with BytesParamIndex 2? lpInData: ?[*:0]const u8, cjOutput: i32, // TODO: what to do with BytesParamIndex 4? lpOutData: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn StartDocA( hdc: ?HDC, lpdi: ?*const DOCINFOA, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn StartDocW( hdc: ?HDC, lpdi: ?*const DOCINFOW, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EndDoc( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn StartPage( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EndPage( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn AbortDoc( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetAbortProc( hdc: ?HDC, proc: ?ABORTPROC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "USER32" fn PrintWindow( hwnd: ?HWND, hdcBlt: ?HDC, nFlags: PRINT_WINDOW_FLAGS, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (3) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const DOCINFO = thismodule.DOCINFOA; pub const DeviceCapabilities = thismodule.DeviceCapabilitiesA; pub const StartDoc = thismodule.StartDocA; }, .wide => struct { pub const DOCINFO = thismodule.DOCINFOW; pub const DeviceCapabilities = thismodule.DeviceCapabilitiesW; pub const StartDoc = thismodule.StartDocW; }, .unspecified => if (@import("builtin").is_test) struct { pub const DOCINFO = *opaque{}; pub const DeviceCapabilities = *opaque{}; pub const StartDoc = *opaque{}; } else struct { pub const DOCINFO = @compileError("'DOCINFO' requires that UNICODE be set to true or false in the root module"); pub const DeviceCapabilities = @compileError("'DeviceCapabilities' requires that UNICODE be set to true or false in the root module"); pub const StartDoc = @compileError("'StartDoc' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (25) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const DEVMODEA = @import("../graphics/gdi.zig").DEVMODEA; const DEVMODEW = @import("../graphics/gdi.zig").DEVMODEW; const HDC = @import("../graphics/gdi.zig").HDC; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IOpcCertificateEnumerator = @import("../storage/packaging/opc.zig").IOpcCertificateEnumerator; const IOpcCertificateSet = @import("../storage/packaging/opc.zig").IOpcCertificateSet; const IOpcPartUri = @import("../storage/packaging/opc.zig").IOpcPartUri; const IOpcSignatureCustomObjectEnumerator = @import("../storage/packaging/opc.zig").IOpcSignatureCustomObjectEnumerator; const IOpcSignatureCustomObjectSet = @import("../storage/packaging/opc.zig").IOpcSignatureCustomObjectSet; const IOpcSignatureReferenceEnumerator = @import("../storage/packaging/opc.zig").IOpcSignatureReferenceEnumerator; const IOpcSignatureReferenceSet = @import("../storage/packaging/opc.zig").IOpcSignatureReferenceSet; const ISequentialStream = @import("../system/com.zig").ISequentialStream; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const IUri = @import("../system/com.zig").IUri; const OPC_SIGNATURE_TIME_FORMAT = @import("../storage/packaging/opc.zig").OPC_SIGNATURE_TIME_FORMAT; const POINT = @import("../foundation.zig").POINT; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "ABORTPROC")) { _ = ABORTPROC; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } } //-------------------------------------------------------------------------------- // Section: SubModules (1) //-------------------------------------------------------------------------------- pub const printing = @import("xps/printing.zig");
win32/storage/xps.zig
const DEBUGMODE = true; const std = @import("std"); pub const sg = @import("sokol").gfx; const sapp = @import("sokol").app; const stime = @import("sokol").time; const sgapp = @import("sokol").app_gfx_glue; const sdtx = @import("sokol").debugtext; const PNG = @import("fileformats").Png; const vec3 = @import("math.zig").Vec3; const mat4 = @import("math.zig").Mat4; const shd = @import("shaders/mainshader.zig"); var nothing: sg.Image = undefined; ////////////////////////////////////////////////////////////////////////////////////////////////// pub const Texture = struct { sktexture: sg.Image, width: u32, height: u32, pub fn fromRaw(data: anytype, width: u32, height: u32) Texture { var img_desc: sg.ImageDesc = .{ .width = @intCast(i32, width), .height = @intCast(i32, height) }; img_desc.data.subimage[0][0] = sg.asRange(data); return Texture { .sktexture = sg.makeImage(img_desc), .width = width, .height = height, }; } pub fn fromPNGPath(filename: []const u8) !Texture { var pngdata = try PNG.fromFile(filename); var img_desc: sg.ImageDesc = .{ .width = @intCast(i32, pngdata.width), .height = @intCast(i32, pngdata.height) }; img_desc.data.subimage[0][0] = sg.asRange(pngdata.raw); return Texture { .sktexture = sg.makeImage(img_desc), .width = pngdata.width, .height = pngdata.height, }; } pub fn draw(self: *Texture, x: f32, y: f32, sx: f32, sy: f32) void { bind.fs_images[shd.SLOT_tex] = self.sktexture; sg.applyBindings(bind); const scale = mat4.scale((@intToFloat(f32, self.width) * sx)/screenWidth, (@intToFloat(f32, self.height) * sy)/screenHeight, 1); const trans = mat4.translate(.{ .x = x / screenWidth, .y = y / -screenHeight, .z = 0 }); sg.applyUniforms(.VS, shd.SLOT_vs_params, sg.asRange(shd.VsParams { .mvp = mat4.mul(trans, scale) })); sg.draw(0, 6, 1); } }; pub fn rectangle(x: f32, y: f32, w: f32, h: f32) void { bind.fs_images[shd.SLOT_tex] = nothing; sg.applyBindings(bind); const scale = mat4.scale(w/screenWidth, h/screenHeight, 1); const trans = mat4.translate(.{ .x = x / screenWidth, .y = y / -screenHeight, .z = 0 }); sg.applyUniforms(.VS, shd.SLOT_vs_params, sg.asRange(shd.VsParams { .mvp = mat4.mul(trans, scale) })); sg.draw(0, 6, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// var pass_action: sg.PassAction = .{}; var pip: sg.Pipeline = .{}; var bind: sg.Bindings = .{}; const Vertex = packed struct { x: f32 = 0, y: f32 = 0, z: f32 = 0, color: u32 = 0xFFFFFFFF, u: i16, v: i16 }; export fn init() void { sg.setup(.{ .context = sgapp.context() }); pass_action.colors[0] = .{ .action = .CLEAR, .value = .{ .r = 0.086, .g = 0.086, .b = 0.113, .a = 1.0 } }; //std.debug.warn("{}", .{sgapp.context()}); var img_desc: sg.ImageDesc = .{ .width = 1, .height = 1 }; img_desc.data.subimage[0][0] = sg.asRange([_]u32{0xFFFFFFFF}); nothing = sg.makeImage(img_desc); bind.fs_images[shd.SLOT_tex] = nothing; const QuadVertices = [4]Vertex{ .{ .x = 2, .y = 0, .u = 6553, .v = 6553}, .{ .x = 2, .y = 2, .u = 6553, .v = 0}, .{ .x = 0, .y = 2, .u = 0, .v = 0}, .{ .x = 0, .y = 0, .u = 0, .v = 6553}, }; const QuadIndices = [6]u16{ 0, 1, 3, 1, 2, 3 }; bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(QuadVertices) }); bind.index_buffer = sg.makeBuffer(.{ .type = .INDEXBUFFER, .data = sg.asRange(QuadIndices), }); var pip_desc: sg.PipelineDesc = .{ .shader = sg.makeShader(shd.shaderDesc(sg.queryBackend())), .index_type = .UINT16, .cull_mode = .FRONT, .depth = .{ .compare = .LESS_EQUAL, .write_enabled = true, } }; pip_desc.colors[0].blend = .{ .enabled = true, .src_factor_rgb = .SRC_ALPHA, .dst_factor_rgb = .ONE_MINUS_SRC_ALPHA, .src_factor_alpha = .SRC_ALPHA, .dst_factor_alpha = .ONE_MINUS_SRC_ALPHA, }; pip_desc.layout.attrs[shd.ATTR_vs_pos].format = .FLOAT3; pip_desc.layout.attrs[shd.ATTR_vs_color0].format = .UBYTE4N; pip_desc.layout.attrs[shd.ATTR_vs_texcoord0].format = .SHORT2N; pip = sg.makePipeline(pip_desc); stime.setup(); if (comptime DEBUGMODE) { var sdtx_desc: sdtx.Desc = .{}; sdtx_desc.fonts[0] = sdtx.fontKc853(); sdtx.setup(sdtx_desc); sdtx.font(0); } setState(state.game); } ////////////////////////////////////////////////////////////////////////////////////////////////// pub const state = enum(u2) { game }; const gamestate = @import("game.zig"); pub var currentState: state = undefined; pub var screenWidth: f32 = 0; pub var screenHeight: f32 = 0; var delta: f32 = 0; var last_time: u64 = 0; export fn frame() void { screenWidth = sapp.widthf(); screenHeight = sapp.heightf(); if (comptime DEBUGMODE) { sdtx.canvas(screenWidth * 0.5, screenHeight * 0.5); sdtx.origin(1, 1); sdtx.color1i(0xFFAA67C7); sdtx.print("Project Scrumptious (Debug)\n===========================\n\n", .{}); sdtx.color1i(0xFFFFAE00); sdtx.print("hello =D\nwelcome to my little project!", .{}); } switch(currentState) { state.game => gamestate.process(delta) } sg.beginDefaultPass(pass_action, sapp.width(), sapp.height()); sg.applyPipeline(pip); sg.applyBindings(bind); switch(currentState) { state.game => gamestate.draw(delta) } if (comptime DEBUGMODE) { sdtx.draw(); } sg.endPass(); sg.commit(); delta = @floatCast(f32, stime.sec(stime.laptime(&last_time))); } ////////////////////////////////////////////////////////////////////////////////////////////////// const _keystruct = struct { up: bool = false, down: bool = false, left: bool = false, right: bool = false, attack: bool = false, up2: bool = false, down2: bool = false, left2: bool = false, right2: bool = false, attack2: bool = false, any: bool = false }; var key = _keystruct{}; export fn input(ev: ?*const sapp.Event) void { const event = ev.?; if ((event.type == .KEY_DOWN) or (event.type == .KEY_UP)) { const key_pressed = event.type == .KEY_DOWN; key.any = key_pressed; switch (event.key_code) { .W => key.up = key_pressed, .S => key.down = key_pressed, .A => key.left = key_pressed, .D => key.right = key_pressed, .UP => key.up2 = key_pressed, .DOWN => key.down2 = key_pressed, .LEFT => key.left2 = key_pressed, .RIGHT => key.right2 = key_pressed, else => {} } } } pub fn getKeys() *_keystruct { return &key; } ////////////////////////////////////////////////////////////////////////////////////////////////// pub fn main() void { sapp.run(.{ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .event_cb = input, .width = 1024, .height = 600, .window_title = "Scrumptious", }); } ////////////////////////////////////////////////////////////////////////////////////////////////// export fn cleanup() void { switch(currentState) { state.game => gamestate.cleanup() } sg.shutdown(); } ////////////////////////////////////////////////////////////////////////////////////////////////// pub fn setState(newState: state) void { switch(currentState) { state.game => gamestate.cleanup() } switch(currentState) { state.game => gamestate.init() } currentState = newState; }
src/main.zig
const std = @import("std"); const fmt = std.fmt; fn testVector(comptime fiat: type, expected_s: []const u8) !void { // Find the type of the limbs and the size of the serialized representation. const repr = switch (@typeInfo(@TypeOf(fiat.fromBytes))) { .Fn => |f| .{ .Limbs = switch (@typeInfo(f.args[0].arg_type.?)) { .Pointer => |p| p.child, else => unreachable, }, .Bytes = f.args[1].arg_type.?, }, else => unreachable, }; const Limbs = repr.Limbs; const Bytes = repr.Bytes; const encoded_length = @sizeOf(Bytes); // Trigger most available functions. var as = [_]u8{0x01} ** encoded_length; var a: Limbs = undefined; fiat.fromBytes(&a, as); if (@hasDecl(fiat, "fromMontgomery")) fiat.fromMontgomery(&a, a); var b: Limbs = undefined; fiat.opp(&b, a); if (@hasDecl(fiat, "carrySquare")) fiat.carrySquare(&a, a) else fiat.square(&a, a); if (@hasDecl(fiat, "carryMul")) fiat.carryMul(&b, a, b) else fiat.mul(&b, a, b); fiat.add(&b, a, b); fiat.sub(&a, b, a); if (@hasDecl(fiat, "carry")) fiat.carry(&a, a); if (@hasDecl(fiat, "toMontgomery")) fiat.toMontgomery(&a, a); fiat.toBytes(&as, a); // Check that the result matches the expected one. var expected: [as.len]u8 = undefined; _ = try fmt.hexToBytes(&expected, expected_s); std.debug.print("> {s}\n", .{fmt.fmtSliceHexLower(&as)}); std.testing.expectEqualSlices(u8, &expected, &as); } test "curve25519" { const expected = "ecb7120fadeccd50753ba3ac57a4922254279cb26ac4bf5c9b7bfd20e64c557f"; try testVector(@import("curve25519_32.zig"), expected); try testVector(@import("curve25519_64.zig"), expected); } test "p256" { const expected = "aee41f6077662dccf5aaebb7f4c4acab16ef34e8baacbdeddaa8db720b82527d"; try testVector(@import("p256_32.zig"), expected); try testVector(@import("p256_64.zig"), expected); } test "p384" { const expected = "bec9b37c6d3f51a25a0fecf036c9753d5bb5fd347a5ee40bf7a51e61ae0b810e5b580c77a966ac7ac3b43e6111be49b4"; try testVector(@import("p384_64.zig"), expected); } test "p448_solinas" { const expected = "8710971b9e1e9d19940c83f769da48b51f88ee52b51574d02a83d92d08e4bb906231fdc58b4e0ecb843bef9f4df89f44e68420b94ee170fd"; try testVector(@import("p448_solinas_64.zig"), expected); } test "p521" { const expected = "beecda88f62311be2a5743ef5a86711c87b19b45afd8c16ad3fbe38bf31a02a90f361cc2274d32d73b6044e84b6f52f5577a5cfe5f81620364846404648362016000"; try testVector(@import("p521_64.zig"), expected); } test "poly1305" { const expected = "cc944af0850b81e63b81b6dbf0f5eacf00"; try testVector(@import("poly1305_32.zig"), expected); try testVector(@import("poly1305_64.zig"), expected); } test "secp256k1" { const expected = "aaa4b177db43ac4d443d0171c3bd2ec9db6c0bf91c1941217b81d250614324dc"; try testVector(@import("secp256k1_64.zig"), expected); }
fiat-zig/src/main.zig
const wlr = @import("../wlroots.zig"); const os = @import("std").os; const pixman = @import("pixman"); const wayland = @import("wayland"); const wl = wayland.server.wl; pub const Output = extern struct { pub const Mode = extern struct { width: i32, height: i32, refresh: i32, preferred: bool, /// Output.modes link: wl.list.Link, }; pub const AdaptiveSyncStatus = extern enum { disabled, enabled, unknown, }; pub const State = extern struct { pub const field = struct { pub const buffer = 1 << 0; pub const damage = 1 << 1; pub const mode = 1 << 2; pub const enabled = 1 << 3; pub const scale = 1 << 4; pub const transform = 1 << 5; pub const adaptive_sync_enabled = 1 << 6; pub const gamma_lut = 1 << 7; }; pub const BufferType = extern enum { render, scanout, }; pub const ModeType = extern enum { fixed, custom, }; /// This is a bitfield of State.field members committed: u32, damage: pixman.Region32, enabled: bool, scale: f32, transform: wl.Output.Transform, adaptive_sync_enabled: bool, // if (committed & field.buffer) buffer_type: BufferType, buffer: ?*wlr.Buffer, // if (committed & field.mode) mode_type: ModeType, mode: ?*Mode, custom_mode: extern struct { width: i32, height: i32, refresh: i32, }, // if (committed & field.gamma_lut) gamma_lut: ?[*]u16, gamma_lut_size: usize, }; pub const event = struct { pub const Damage = extern struct { output: *wlr.Output, /// In output buffer local coordinates damage: *pixman.Region32, }; pub const Precommit = extern struct { output: *wlr.Output, when: *os.timespec, }; pub const Commit = extern struct { output: *wlr.Output, /// This is a bitfield of State.field members comitted: u32, }; pub const Present = extern struct { pub const flag = struct { const vsync = 1 << 0; const hw_clock = 1 << 1; const hw_completion = 1 << 2; const zero_copy = 1 << 3; }; output: *wlr.Output, commit_seq: u32, when: *os.timespec, seq: c_uint, refresh: c_int, /// This is a bitfield of Present.flag members flags: u32, }; pub const Bind = extern struct { output: *wlr.Output, resource: *wl.Output, }; }; const Impl = opaque {}; impl: *const Impl, backend: *wlr.Backend, server: *wl.Server, global: *wl.Global, resources: wl.list.Head(wl.Output, null), /// This contains a 0 terminated string, use std.mem.sliceTo(name, 0) name: [24]u8, description: ?[*:0]u8, /// This contains a 0 terminated string, use std.mem.sliceTo(make, 0) make: [56]u8, /// This contains a 0 terminated string, use std.mem.sliceTo(model, 0) model: [16]u8, /// This contains a 0 terminated string, use std.mem.sliceTo(serial, 0) serial: [16]u8, phys_width: i32, phys_height: i32, modes: wl.list.Head(Output.Mode, "link"), current_mode: ?*Output.Mode, width: i32, height: i32, refresh: i32, enabled: bool, scale: f32, subpixel: wl.Output.Subpixel, transform: wl.Output.Transform, adaptive_sync_status: AdaptiveSyncStatus, needs_frame: bool, frame_pending: bool, transform_matrix: [9]f32, pending: State, commit_seq: u32, events: extern struct { frame: wl.Signal(*Output), damage: wl.Signal(*event.Damage), needs_frame: wl.Signal(*Output), precommit: wl.Signal(*event.Precommit), commit: wl.Signal(*event.Commit), present: wl.Signal(*event.Present), bind: wl.Signal(*event.Bind), enable: wl.Signal(*Output), mode: wl.Signal(*Output), description: wl.Signal(*Output), destroy: wl.Signal(*Output), }, idle_frame: *wl.EventSource, idle_done: *wl.EventSource, attach_render_locks: c_int, cursors: wl.list.Head(OutputCursor, "link"), hardware_cursor: ?*OutputCursor, software_cursor_locks: c_int, server_destroy: wl.Listener(*wl.Server), data: usize, extern fn wlr_output_enable(output: *Output, enable: bool) void; pub const enable = wlr_output_enable; extern fn wlr_output_create_global(output: *Output) void; pub const createGlobal = wlr_output_create_global; extern fn wlr_output_destroy_global(output: *Output) void; pub const destroyGlobal = wlr_output_destroy_global; extern fn wlr_output_preferred_mode(output: *Output) ?*Mode; pub const preferredMode = wlr_output_preferred_mode; extern fn wlr_output_set_mode(output: *Output, mode: *Mode) void; pub const setMode = wlr_output_set_mode; extern fn wlr_output_set_custom_mode(output: *Output, width: i32, height: i32, refresh: i32) void; pub const setCustomMode = wlr_output_set_custom_mode; extern fn wlr_output_set_transform(output: *Output, transform: wl.Output.Transform) void; pub const setTransform = wlr_output_set_transform; extern fn wlr_output_enable_adaptive_sync(output: *Output, enabled: bool) void; pub const enableAdaptiveSync = wlr_output_enable_adaptive_sync; extern fn wlr_output_set_scale(output: *Output, scale: f32) void; pub const setScale = wlr_output_set_scale; extern fn wlr_output_set_subpixel(output: *Output, subpixel: wl.Output.Subpixel) void; pub const setSubpixel = wlr_output_set_subpixel; extern fn wlr_output_set_description(output: *Output, desc: [*:0]const u8) void; pub const setDescription = wlr_output_set_description; extern fn wlr_output_schedule_done(output: *Output) void; pub const scheduleDone = wlr_output_schedule_done; extern fn wlr_output_destroy(output: *Output) void; pub const destroy = wlr_output_destroy; extern fn wlr_output_transformed_resolution(output: *Output, width: *c_int, height: *c_int) void; pub const transformedResolution = wlr_output_transformed_resolution; extern fn wlr_output_effective_resolution(output: *Output, width: *c_int, height: *c_int) void; pub const effectiveResolution = wlr_output_effective_resolution; extern fn wlr_output_attach_render(output: *Output, buffer_age: ?*c_int) bool; pub fn attachRender(output: *Output, buffer_age: ?*c_int) !void { if (!wlr_output_attach_render(output, buffer_age)) return error.AttachRenderFailed; } extern fn wlr_output_attach_buffer(output: *Output, buffer: *wlr.Buffer) void; pub const attachBuffer = wlr_output_attach_buffer; extern fn wlr_output_preferred_read_format(output: *Output) u32; pub const preferredReadFormat = wlr_output_preferred_read_format; extern fn wlr_output_set_damage(output: *Output, damage: *pixman.Region32) void; pub const setDamage = wlr_output_set_damage; extern fn wlr_output_test(output: *Output) bool; pub const testCommit = wlr_output_test; extern fn wlr_output_commit(output: *Output) bool; pub fn commit(output: *Output) !void { if (!wlr_output_commit(output)) return error.OutputCommitFailed; } extern fn wlr_output_rollback(output: *Output) void; pub const rollback = wlr_output_rollback; extern fn wlr_output_schedule_frame(output: *Output) void; pub const scheduleFrame = wlr_output_schedule_frame; extern fn wlr_output_get_gamma_size(output: *Output) usize; pub const getGammaSize = wlr_output_get_gamma_size; extern fn wlr_output_set_gamma(output: *Output, size: usize, r: [*]const u16, g: [*]const u16, b: [*]const u16) void; pub const setGamma = wlr_output_set_gamma; extern fn wlr_output_export_dmabuf(output: *Output, attribs: *wlr.DmabufAttributes) bool; pub const exportDmabuf = wlr_output_export_dmabuf; extern fn wlr_output_from_resource(resource: *wl.Output) ?*Output; pub const fromWlOutput = wlr_output_from_resource; extern fn wlr_output_lock_attach_render(output: *Output, lock: bool) void; pub const lockAttachRender = wlr_output_lock_attach_render; extern fn wlr_output_lock_software_cursors(output: *Output, lock: bool) void; pub const lockSoftwareCursors = wlr_output_lock_software_cursors; extern fn wlr_output_render_software_cursors(output: *Output, damage: ?*pixman.Region32) void; pub const renderSoftwareCursors = wlr_output_render_software_cursors; extern fn wlr_output_transform_invert(tr: wl.Output.Transform) wl.Output.Transform; pub const transformInvert = wlr_output_transform_invert; extern fn wlr_output_transform_compose(tr_a: wl.Output.Transform, tr_b: wl.Output.Transform) wl.Output.Transform; pub const transformCompose = wlr_output_transform_compose; extern fn wlr_output_is_noop(output: *Output) bool; pub const isNoop = wlr_output_is_noop; extern fn wlr_output_is_wl(output: *Output) bool; pub const isWl = wlr_output_is_wl; extern fn wlr_output_is_x11(output: *Output) bool; pub const isX11 = wlr_output_is_x11; extern fn wlr_wl_output_set_title(output: *Output, title: ?[*:0]const u8) void; pub const wlSetTitle = wlr_wl_output_set_title; extern fn wlr_x11_output_set_title(output: *Output, title: ?[*:0]const u8) void; pub const x11SetTitle = wlr_x11_output_set_title; }; pub const OutputCursor = extern struct { output: *wlr.Output, x: f64, y: f64, enabled: bool, visible: bool, width: u32, height: u32, hotspot_x: i32, hotspot_y: i32, /// Output.cursors link: wl.list.Link, /// only when using a software cursor without a surface texture: ?*wlr.Texture, /// only when using a cursor surface surface: ?*wlr.Surface, surface_commit: wl.Listener(*wlr.Surface), surface_destroy: wl.Listener(*wlr.Surface), events: extern struct { destroy: wl.Signal(*OutputCursor), }, extern fn wlr_output_cursor_create(output: *Output) ?*OutputCursor; pub fn create(output: *Output) !*OutputCursor { return wlr_output_cursor_create(output) orelse error.OutOfMemory; } extern fn wlr_output_cursor_set_image(cursor: *OutputCursor, pixels: ?[*]const u8, stride: i32, width: u32, height: u32, hotspot_x: i32, hotspot_y: i32) bool; pub const setImage = wlr_output_cursor_set_image; extern fn wlr_output_cursor_set_surface(cursor: *OutputCursor, surface: ?*wlr.Surface, hotspot_x: i32, hotspot_y: i32) void; pub const setSurface = wlr_output_cursor_set_surface; extern fn wlr_output_cursor_move(cursor: *OutputCursor, x: f64, y: f64) bool; pub const move = wlr_output_cursor_move; extern fn wlr_output_cursor_destroy(cursor: *OutputCursor) void; pub const destroy = wlr_output_cursor_destroy; };
src/types/output.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day04.txt"); const Passport = struct { byr: ?[]const u8 = null, iyr: ?[]const u8 = null, eyr: ?[]const u8 = null, hgt: ?[]const u8 = null, hcl: ?[]const u8 = null, ecl: ?[]const u8 = null, pid: ?[]const u8 = null, //cid: ?[]const u8 = null, pub fn initFromString(string: []const u8) !Passport { var self = Passport{}; var iter = std.mem.tokenize(string, " \n"); while (iter.next()) |token| { const i = std.mem.indexOfScalar(u8, token, ':') orelse return error.InvalidToken; const identifier = token[0..i]; const value = token[i + 1..]; inline for (std.meta.fields(Passport)) |field| { if (std.mem.eql(u8, identifier, field.name)) { @field(self, field.name) = value; } } } return self; } pub fn isComplete(self: Passport) bool { inline for (std.meta.fields(Passport)) |field| { if (@field(self, field.name) == null) { return false; } } return true; } pub fn isValid(self: Passport) bool { if (!self.isComplete()) return false; const byr = std.fmt.parseUnsigned(usize, self.byr.?, 10) catch |_| return false; if (byr < 1920 or byr > 2002) return false; const iyr = std.fmt.parseUnsigned(usize, self.iyr.?, 10) catch |_| return false; if (iyr < 2010 or iyr > 2020) return false; const eyr = std.fmt.parseUnsigned(usize, self.eyr.?, 10) catch |_| return false; if (eyr < 2020 or eyr > 2030) return false; if (self.hgt.?.len < 3) return false; const hgt_unit = self.hgt.?[self.hgt.?.len - 2..self.hgt.?.len]; const hgt_value = std.fmt.parseUnsigned(usize, self.hgt.?[0..self.hgt.?.len - 2], 10) catch |_| return false; if (std.mem.eql(u8, hgt_unit, "cm")) { if (hgt_value < 150 or hgt_value > 193) return false; } else if (std.mem.eql(u8, hgt_unit, "in")) { if (hgt_value < 59 or hgt_value > 76) return false; } else { return false; } if (self.hcl.?.len != 7) return false; if (self.hcl.?[0] != '#') return false; for (self.hcl.?[1..]) |c| { if (!(('0' <= c and c <= '9') or ('a' <= c and c <= 'f'))) return false; } if (self.ecl.?.len != 3) return false; const valid_ecls = [_][]const u8{"amb", "blu", "brn", "gry", "grn", "hzl", "oth"}; var ecl_found = false; for (valid_ecls) |valid_ecl| { if (std.mem.eql(u8, self.ecl.?, valid_ecl)) { ecl_found = true; break; } } if (!ecl_found) return false; if (self.pid.?.len != 9) return false; for (self.pid.?) |c| { if (!('0' <= c and c <= '9')) return false; } return true; } }; fn completePassports(string: []const u8) usize { var count: usize = 0; const sep = "\n\n"; var iter = std.mem.split(string, sep); while (iter.next()) |token| { const passport = Passport.initFromString(token) catch |_| continue; if (passport.isComplete()) count += 1; } return count; } fn validPassports(string: []const u8) usize { var count: usize = 0; const sep = "\n\n"; var iter = std.mem.split(string, sep); while (iter.next()) |token| { const passport = Passport.initFromString(token) catch |_| continue; if (passport.isValid()) count += 1; } return count; } pub fn main() !void { print("part1 {}\n", .{completePassports(input)}); print("part2 {}\n", .{validPassports(input)}); } const example = \\ecl:gry pid:860033327 eyr:2020 hcl:#fffffd \\byr:1937 iyr:2017 cid:147 hgt:183cm \\ \\iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 \\hcl:#cfa07d byr:1929 \\ \\hcl:#ae17e1 iyr:2013 \\eyr:2024 \\ecl:brn pid:760753108 byr:1931 \\hgt:179cm \\ \\hcl:#cfa07d eyr:2025 pid:166559648 \\iyr:2011 ecl:brn hgt:59in ; test "part1 example" { std.testing.expect(completePassports(example) == 2); } const example_invalid = \\eyr:1972 cid:100 \\hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 \\ \\iyr:2019 \\hcl:#602927 eyr:1967 hgt:170cm \\ecl:grn pid:012533040 byr:1946 \\ \\hcl:dab227 iyr:2012 \\ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 \\ \\hgt:59cm ecl:zzz \\eyr:2038 hcl:74454a iyr:2023 \\pid:3556412378 byr:2007 ; const example_valid = \\pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 \\hcl:#623a2f \\ \\eyr:2029 ecl:blu cid:129 byr:1989 \\iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm \\ \\hcl:#888785 \\hgt:164cm byr:2001 iyr:2015 cid:88 \\pid:545766238 ecl:hzl \\eyr:2022 \\ \\iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 ; test "part2 examples" { std.testing.expect(validPassports(example_invalid) == 0); std.testing.expect(validPassports(example_valid) == 4); }
src/day04.zig
const std = @import("std"); 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 sqlite = b.addStaticLibrary("sqlite", null); sqlite.addIncludeDir("sqlite"); sqlite.addCSourceFile("sqlite/sqlite3.c", &[_][]const u8{"-std=c99"}); sqlite.linkLibC(); const lua = b.addStaticLibrary("lua", null); lua.addIncludeDir("lua-5.3.4/src"); lua.linkLibC(); const lua_c_files = [_][]const u8{ "lapi.c", "lauxlib.c", "lbaselib.c", "lbitlib.c", "lcode.c", "lcorolib.c", "lctype.c", "ldblib.c", "ldebug.c", "ldo.c", "ldump.c", "lfunc.c", "lgc.c", "linit.c", "liolib.c", "llex.c", "lmathlib.c", "lmem.c", "loadlib.c", "lobject.c", "lopcodes.c", "loslib.c", "lparser.c", "lstate.c", "lstring.c", "lstrlib.c", "ltable.c", "ltablib.c", "ltm.c", "lundump.c", "lutf8lib.c", "lvm.c", "lzio.c", }; const c_flags = [_][]const u8{ "-std=c99", "-O2", }; inline for (lua_c_files) |c_file| { lua.addCSourceFile("lua/src/" ++ c_file, &c_flags); } const exe = b.addExecutable("engine", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.linkLibC(); exe.addIncludeDir("sqlite"); exe.linkLibrary(sqlite); exe.addIncludeDir("lua/src"); exe.linkLibrary(lua); exe.addLibPath("/usr/lib/"); exe.addIncludeDir("/usr/include/ImageMagick-7"); exe.linkSystemLibrary("MagickWand-7.Q16HDRI"); exe.linkSystemLibrary("MagickCore-7.Q16HDRI"); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const exe_tests = b.addTest("src/main.zig"); const coverage = b.option(bool, "test-coverage", "Generate test coverage") orelse false; exe_tests.setTarget(target); exe_tests.setBuildMode(mode); exe_tests.linkLibC(); exe_tests.addIncludeDir("sqlite"); exe_tests.linkLibrary(sqlite); exe_tests.addIncludeDir("lua/src"); exe_tests.linkLibrary(lua); exe_tests.addLibPath("/usr/lib/"); exe_tests.addIncludeDir("/usr/include/ImageMagick-7"); exe_tests.linkSystemLibrary("MagickWand-7.Q16HDRI"); exe_tests.linkSystemLibrary("MagickCore-7.Q16HDRI"); if (coverage) { // with kcov exe_tests.setExecCmd(&[_]?[]const u8{ "kcov", //"--path-strip-level=3", // any kcov flags can be specified here "kcov-output", // output dir for kcov null, // to get zig to use the --test-cmd-bin flag }); } const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
engine/build.zig
const std = @import("std"); const builtin = @import("builtin"); const cpu = builtin.cpu; const arch = cpu.arch; const linkage: std.builtin.GlobalLinkage = if (builtin.is_test) .Internal else .Weak; // This parameter is true iff the target architecture supports the bare minimum // to implement the atomic load/store intrinsics. // Some architectures support atomic load/stores but no CAS, but we ignore this // detail to keep the export logic clean and because we need some kind of CAS to // implement the spinlocks. const supports_atomic_ops = switch (arch) { .msp430, .avr, .bpfel, .bpfeb => false, .arm, .armeb, .thumb, .thumbeb => // The ARM v6m ISA has no ldrex/strex and so it's impossible to do CAS // operations (unless we're targeting Linux, the kernel provides a way to // perform CAS operations). // XXX: The Linux code path is not implemented yet. !std.Target.arm.featureSetHas(builtin.cpu.features, .has_v6m), else => true, }; // The size (in bytes) of the biggest object that the architecture can // load/store atomically. // Objects bigger than this threshold require the use of a lock. const largest_atomic_size = switch (arch) { // On SPARC systems that lacks CAS and/or swap instructions, the only // available atomic operation is a test-and-set (`ldstub`), so we force // every atomic memory access to go through the lock. .sparc, .sparcel => if (cpu.features.featureSetHas(.hasleoncasa)) @sizeOf(usize) else 0, // XXX: On x86/x86_64 we could check the presence of cmpxchg8b/cmpxchg16b // and set this parameter accordingly. else => @sizeOf(usize), }; const cache_line_size = 64; const SpinlockTable = struct { // Allocate ~4096 bytes of memory for the spinlock table const max_spinlocks = 64; const Spinlock = struct { // SPARC ldstub instruction will write a 255 into the memory location. // We'll use that as a sign that the lock is currently held. // See also: Section B.7 in SPARCv8 spec & A.29 in SPARCv9 spec. const sparc_lock: type = enum(u8) { Unlocked = 0, Locked = 255 }; const other_lock: type = enum(usize) { Unlocked = 0, Locked }; // Prevent false sharing by providing enough padding between two // consecutive spinlock elements v: if (arch.isSPARC()) sparc_lock else other_lock align(cache_line_size) = .Unlocked, fn acquire(self: *@This()) void { while (true) { const flag = if (comptime arch.isSPARC()) flag: { break :flag asm volatile ("ldstub [%[addr]], %[flag]" : [flag] "=r" (-> @TypeOf(self.v)), : [addr] "r" (&self.v), : "memory" ); } else flag: { break :flag @atomicRmw(@TypeOf(self.v), &self.v, .Xchg, .Locked, .Acquire); }; switch (flag) { .Unlocked => break, .Locked => {}, } } } fn release(self: *@This()) void { if (comptime arch.isSPARC()) { _ = asm volatile ("clrb [%[addr]]" : : [addr] "r" (&self.v), : "memory" ); } else { @atomicStore(@TypeOf(self.v), &self.v, .Unlocked, .Release); } } }; list: [max_spinlocks]Spinlock = [_]Spinlock{.{}} ** max_spinlocks, // The spinlock table behaves as a really simple hash table, mapping // addresses to spinlocks. The mapping is not unique but that's only a // performance problem as the lock will be contended by more than a pair of // threads. fn get(self: *@This(), address: usize) *Spinlock { var sl = &self.list[(address >> 3) % max_spinlocks]; sl.acquire(); return sl; } }; var spinlocks: SpinlockTable = SpinlockTable{}; // The following builtins do not respect the specified memory model and instead // uses seq_cst, the strongest one, for simplicity sake. // Generic version of GCC atomic builtin functions. // Those work on any object no matter the pointer alignment nor its size. fn __atomic_load(size: u32, src: [*]u8, dest: [*]u8, model: i32) callconv(.C) void { _ = model; var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_store(size: u32, dest: [*]u8, src: [*]u8, model: i32) callconv(.C) void { _ = model; var sl = spinlocks.get(@ptrToInt(dest)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_exchange(size: u32, ptr: [*]u8, val: [*]u8, old: [*]u8, model: i32) callconv(.C) void { _ = model; var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); @memcpy(old, ptr, size); @memcpy(ptr, val, size); } fn __atomic_compare_exchange( size: u32, ptr: [*]u8, expected: [*]u8, desired: [*]u8, success: i32, failure: i32, ) callconv(.C) i32 { _ = success; _ = failure; var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); for (ptr[0..size]) |b, i| { if (expected[i] != b) break; } else { // The two objects, ptr and expected, are equal @memcpy(ptr, desired, size); return 1; } @memcpy(expected, ptr, size); return 0; } // Specialized versions of the GCC atomic builtin functions. // LLVM emits those iff the object size is known and the pointers are correctly // aligned. inline fn atomic_load_N(comptime T: type, src: *T, model: i32) T { _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); return src.*; } else { return @atomicLoad(T, src, .SeqCst); } } fn __atomic_load_1(src: *u8, model: i32) callconv(.C) u8 { return atomic_load_N(u8, src, model); } fn __atomic_load_2(src: *u16, model: i32) callconv(.C) u16 { return atomic_load_N(u16, src, model); } fn __atomic_load_4(src: *u32, model: i32) callconv(.C) u32 { return atomic_load_N(u32, src, model); } fn __atomic_load_8(src: *u64, model: i32) callconv(.C) u64 { return atomic_load_N(u64, src, model); } inline fn atomic_store_N(comptime T: type, dst: *T, value: T, model: i32) void { _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(dst)); defer sl.release(); dst.* = value; } else { @atomicStore(T, dst, value, .SeqCst); } } fn __atomic_store_1(dst: *u8, value: u8, model: i32) callconv(.C) void { return atomic_store_N(u8, dst, value, model); } fn __atomic_store_2(dst: *u16, value: u16, model: i32) callconv(.C) void { return atomic_store_N(u16, dst, value, model); } fn __atomic_store_4(dst: *u32, value: u32, model: i32) callconv(.C) void { return atomic_store_N(u32, dst, value, model); } fn __atomic_store_8(dst: *u64, value: u64, model: i32) callconv(.C) void { return atomic_store_N(u64, dst, value, model); } inline fn atomic_exchange_N(comptime T: type, ptr: *T, val: T, model: i32) T { _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; ptr.* = val; return value; } else { return @atomicRmw(T, ptr, .Xchg, val, .SeqCst); } } fn __atomic_exchange_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return atomic_exchange_N(u8, ptr, val, model); } fn __atomic_exchange_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return atomic_exchange_N(u16, ptr, val, model); } fn __atomic_exchange_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return atomic_exchange_N(u32, ptr, val, model); } fn __atomic_exchange_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return atomic_exchange_N(u64, ptr, val, model); } inline fn atomic_compare_exchange_N( comptime T: type, ptr: *T, expected: *T, desired: T, success: i32, failure: i32, ) i32 { _ = success; _ = failure; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; if (value == expected.*) { ptr.* = desired; return 1; } expected.* = value; return 0; } else { if (@cmpxchgStrong(T, ptr, expected.*, desired, .SeqCst, .SeqCst)) |old_value| { expected.* = old_value; return 0; } return 1; } } fn __atomic_compare_exchange_1(ptr: *u8, expected: *u8, desired: u8, success: i32, failure: i32) callconv(.C) i32 { return atomic_compare_exchange_N(u8, ptr, expected, desired, success, failure); } fn __atomic_compare_exchange_2(ptr: *u16, expected: *u16, desired: u16, success: i32, failure: i32) callconv(.C) i32 { return atomic_compare_exchange_N(u16, ptr, expected, desired, success, failure); } fn __atomic_compare_exchange_4(ptr: *u32, expected: *u32, desired: u32, success: i32, failure: i32) callconv(.C) i32 { return atomic_compare_exchange_N(u32, ptr, expected, desired, success, failure); } fn __atomic_compare_exchange_8(ptr: *u64, expected: *u64, desired: u64, success: i32, failure: i32) callconv(.C) i32 { return atomic_compare_exchange_N(u64, ptr, expected, desired, success, failure); } inline fn fetch_op_N(comptime T: type, comptime op: std.builtin.AtomicRmwOp, ptr: *T, val: T, model: i32) T { _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); const value = ptr.*; ptr.* = switch (op) { .Add => value +% val, .Sub => value -% val, .And => value & val, .Nand => ~(value & val), .Or => value | val, .Xor => value ^ val, else => @compileError("unsupported atomic op"), }; return value; } return @atomicRmw(T, ptr, op, val, .SeqCst); } fn __atomic_fetch_add_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .Add, ptr, val, model); } fn __atomic_fetch_add_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .Add, ptr, val, model); } fn __atomic_fetch_add_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .Add, ptr, val, model); } fn __atomic_fetch_add_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .Add, ptr, val, model); } fn __atomic_fetch_sub_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .Sub, ptr, val, model); } fn __atomic_fetch_sub_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .Sub, ptr, val, model); } fn __atomic_fetch_sub_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .Sub, ptr, val, model); } fn __atomic_fetch_sub_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .Sub, ptr, val, model); } fn __atomic_fetch_and_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .And, ptr, val, model); } fn __atomic_fetch_and_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .And, ptr, val, model); } fn __atomic_fetch_and_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .And, ptr, val, model); } fn __atomic_fetch_and_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .And, ptr, val, model); } fn __atomic_fetch_or_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .Or, ptr, val, model); } fn __atomic_fetch_or_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .Or, ptr, val, model); } fn __atomic_fetch_or_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .Or, ptr, val, model); } fn __atomic_fetch_or_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .Or, ptr, val, model); } fn __atomic_fetch_xor_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .Xor, ptr, val, model); } fn __atomic_fetch_xor_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .Xor, ptr, val, model); } fn __atomic_fetch_xor_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .Xor, ptr, val, model); } fn __atomic_fetch_xor_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .Xor, ptr, val, model); } fn __atomic_fetch_nand_1(ptr: *u8, val: u8, model: i32) callconv(.C) u8 { return fetch_op_N(u8, .Nand, ptr, val, model); } fn __atomic_fetch_nand_2(ptr: *u16, val: u16, model: i32) callconv(.C) u16 { return fetch_op_N(u16, .Nand, ptr, val, model); } fn __atomic_fetch_nand_4(ptr: *u32, val: u32, model: i32) callconv(.C) u32 { return fetch_op_N(u32, .Nand, ptr, val, model); } fn __atomic_fetch_nand_8(ptr: *u64, val: u64, model: i32) callconv(.C) u64 { return fetch_op_N(u64, .Nand, ptr, val, model); } comptime { if (supports_atomic_ops) { @export(__atomic_load, .{ .name = "__atomic_load", .linkage = linkage }); @export(__atomic_store, .{ .name = "__atomic_store", .linkage = linkage }); @export(__atomic_exchange, .{ .name = "__atomic_exchange", .linkage = linkage }); @export(__atomic_compare_exchange, .{ .name = "__atomic_compare_exchange", .linkage = linkage }); @export(__atomic_fetch_add_1, .{ .name = "__atomic_fetch_add_1", .linkage = linkage }); @export(__atomic_fetch_add_2, .{ .name = "__atomic_fetch_add_2", .linkage = linkage }); @export(__atomic_fetch_add_4, .{ .name = "__atomic_fetch_add_4", .linkage = linkage }); @export(__atomic_fetch_add_8, .{ .name = "__atomic_fetch_add_8", .linkage = linkage }); @export(__atomic_fetch_sub_1, .{ .name = "__atomic_fetch_sub_1", .linkage = linkage }); @export(__atomic_fetch_sub_2, .{ .name = "__atomic_fetch_sub_2", .linkage = linkage }); @export(__atomic_fetch_sub_4, .{ .name = "__atomic_fetch_sub_4", .linkage = linkage }); @export(__atomic_fetch_sub_8, .{ .name = "__atomic_fetch_sub_8", .linkage = linkage }); @export(__atomic_fetch_and_1, .{ .name = "__atomic_fetch_and_1", .linkage = linkage }); @export(__atomic_fetch_and_2, .{ .name = "__atomic_fetch_and_2", .linkage = linkage }); @export(__atomic_fetch_and_4, .{ .name = "__atomic_fetch_and_4", .linkage = linkage }); @export(__atomic_fetch_and_8, .{ .name = "__atomic_fetch_and_8", .linkage = linkage }); @export(__atomic_fetch_or_1, .{ .name = "__atomic_fetch_or_1", .linkage = linkage }); @export(__atomic_fetch_or_2, .{ .name = "__atomic_fetch_or_2", .linkage = linkage }); @export(__atomic_fetch_or_4, .{ .name = "__atomic_fetch_or_4", .linkage = linkage }); @export(__atomic_fetch_or_8, .{ .name = "__atomic_fetch_or_8", .linkage = linkage }); @export(__atomic_fetch_xor_1, .{ .name = "__atomic_fetch_xor_1", .linkage = linkage }); @export(__atomic_fetch_xor_2, .{ .name = "__atomic_fetch_xor_2", .linkage = linkage }); @export(__atomic_fetch_xor_4, .{ .name = "__atomic_fetch_xor_4", .linkage = linkage }); @export(__atomic_fetch_xor_8, .{ .name = "__atomic_fetch_xor_8", .linkage = linkage }); @export(__atomic_fetch_nand_1, .{ .name = "__atomic_fetch_nand_1", .linkage = linkage }); @export(__atomic_fetch_nand_2, .{ .name = "__atomic_fetch_nand_2", .linkage = linkage }); @export(__atomic_fetch_nand_4, .{ .name = "__atomic_fetch_nand_4", .linkage = linkage }); @export(__atomic_fetch_nand_8, .{ .name = "__atomic_fetch_nand_8", .linkage = linkage }); @export(__atomic_load_1, .{ .name = "__atomic_load_1", .linkage = linkage }); @export(__atomic_load_2, .{ .name = "__atomic_load_2", .linkage = linkage }); @export(__atomic_load_4, .{ .name = "__atomic_load_4", .linkage = linkage }); @export(__atomic_load_8, .{ .name = "__atomic_load_8", .linkage = linkage }); @export(__atomic_store_1, .{ .name = "__atomic_store_1", .linkage = linkage }); @export(__atomic_store_2, .{ .name = "__atomic_store_2", .linkage = linkage }); @export(__atomic_store_4, .{ .name = "__atomic_store_4", .linkage = linkage }); @export(__atomic_store_8, .{ .name = "__atomic_store_8", .linkage = linkage }); @export(__atomic_exchange_1, .{ .name = "__atomic_exchange_1", .linkage = linkage }); @export(__atomic_exchange_2, .{ .name = "__atomic_exchange_2", .linkage = linkage }); @export(__atomic_exchange_4, .{ .name = "__atomic_exchange_4", .linkage = linkage }); @export(__atomic_exchange_8, .{ .name = "__atomic_exchange_8", .linkage = linkage }); @export(__atomic_compare_exchange_1, .{ .name = "__atomic_compare_exchange_1", .linkage = linkage }); @export(__atomic_compare_exchange_2, .{ .name = "__atomic_compare_exchange_2", .linkage = linkage }); @export(__atomic_compare_exchange_4, .{ .name = "__atomic_compare_exchange_4", .linkage = linkage }); @export(__atomic_compare_exchange_8, .{ .name = "__atomic_compare_exchange_8", .linkage = linkage }); } }
lib/std/special/compiler_rt/atomics.zig
// SPDX-License-Identifier: MIT // This file is part of the `termcon` project under the MIT license. const std = @import("std"); const backend = @import("../backend.zig").backend; const view = @import("../view.zig"); pub const Cell = view.Cell; pub const Position = view.Position; pub const Rune = view.Rune; pub const Style = view.Style; pub const Cursor = view.Cursor; pub const Size = struct { rows: u16, cols: u16 }; pub const Screen = struct { // TODO: Implement mutex for screen // lock: std.Mutex allocator: *std.mem.Allocator, cursor: Cursor, default_style: Style, size: Size, buffer_size: Size, rune_buffer: std.ArrayList(Rune), style_buffer: std.ArrayList(Style), diff_buffer: std.PriorityQueue(Position), const Self = @This(); fn positionLess(a: Position, b: Position) bool { return a.less(b); } fn addChecked( diff_buffer: *std.PriorityQueue(Position), elem: Position, ) !void { for (diff_buffer.items) |item| { if (elem.equal(item)) { return; } } return diff_buffer.add(elem); } pub fn init(allocator: *std.mem.Allocator, buffer_size: ?Size) !Screen { var result: Screen = Screen{ .allocator = allocator, .cursor = Cursor{}, .default_style = Style{ .fg_color = view.Color.Default, .bg_color = view.Color.Default, .text_decorations = view.TextDecorations{ .italic = false, .bold = false, .underline = false, }, }, .size = Size{ .rows = 0, .cols = 0 }, .buffer_size = buffer_size orelse Size{ .rows = 300, .cols = 100 }, .rune_buffer = std.ArrayList(Rune).init(allocator), .style_buffer = std.ArrayList(Style).init(allocator), .diff_buffer = std.PriorityQueue(Position).init(allocator, positionLess), }; try result.updateSize(); try result.rune_buffer.ensureCapacity( result.buffer_size.rows * result.buffer_size.cols, ); result.rune_buffer.expandToCapacity(); try result.style_buffer.ensureCapacity( result.buffer_size.rows * result.buffer_size.cols, ); result.style_buffer.expandToCapacity(); std.mem.set( Rune, result.rune_buffer.items, ' ', ); std.mem.set( Style, result.style_buffer.items, result.default_style, ); return result; } pub fn deinit(self: *Self) void { self.rune_buffer.deinit(); self.style_buffer.deinit(); self.diff_buffer.deinit(); } pub fn clear(self: *Self) !void { try backend.screen.clearScreen(); } pub fn draw(self: *Self) !void { if (self.diff_buffer.count() == 0) return; const orig_cursor: Position = try self.cursor.getPosition(); while (self.diff_buffer.count() > 0) { // Get row range to draw const diff_position = self.diff_buffer.remove(); var final_col: u16 = diff_position.col; while (self.diff_buffer.peek()) |next| { if (next.row != diff_position.row) break; final_col = next.col; _ = self.diff_buffer.remove(); } // Move cursor and draw row try self.cursor.setPosition(diff_position); const range_start = diff_position.row * self.buffer_size.cols + diff_position.col; const range_end = diff_position.row * self.buffer_size.cols + final_col + 1; try backend.screen.write( self.rune_buffer.items[range_start..range_end], self.style_buffer.items[range_start..range_end], ); } try self.cursor.setPosition(orig_cursor); } pub fn getSize(self: *const Self) Size { return self.size; } pub fn updateSize(self: *Self) !void { self.size = try backend.screen.getSize(); } pub fn getBufferSize(self: *const Self) Size { return self.buffer_size; } /// Resize the buffer. This function call is expensive; try to minimize /// its use. During resize, all cells that are beyond the new row or /// column limit are ignored. Any new cells introduced from an expansion /// in rows or columns is filled with either the provided `fill_cell` or /// an empty default-style cell. pub fn setBufferSize(self: *Self, size: Size, fill_cell: ?Cell) !void { const b_rows = self.buffer_size.rows; const b_cols = self.buffer_size.cols; if (size.rows * size.cols != b_rows * b_cols) { try self.buffer.ensureCapacity(size.rows * size.cols); self.buffer.expandToCapacity(); } if (size.cols < b_cols) { var row_index: @Type(b_rows) = 1; while (row_index < b_rows) : (row_index += 1) { const start_dest = row_index * b_cols; const end_dest = row_index * b_cols + size.cols; const start_source = row_index * size.cols; const end_source = (row_index + 1) * size.cols; std.mem.copy( Rune, self.rune_buffer.items[start_dest..end_dest], self.rune_buffer.items[start_source..end_source], ); std.mem.copy( Style, self.style_buffer.items[start_dest..end_dest], self.style_buffer.items[start_source..end_source], ); } } else if (size.cols > b_cols) { var row_index: @Type(b_rows) = b_rows; while (row_index > 0) : (row_index -= 1) { const r_i = row_index - 1; const start_dest = r_i * size.cols; const end_dest = r_i * size.cols + b_cols; const start_source = r_i * b_cols; const end_source = row_index * b_cols; const start_empty = r_i * size.cols + b_cols; const end_empty = row_index * size.cols; std.mem.copyBackwards( Rune, self.rune_buffer.items[start_dest..end_dest], self.rune_buffer.items[start_source..end_source], ); std.mem.set( Rune, self.rune_buffer.items[start_empty..end_empty], fill_cell.rune orelse ' ', ); std.mem.copyBackwards( Style, self.style_buffer.items[start_dest..end_dest], self.style_buffer.items[start_source..end_source], ); std.mem.set( Style, self.style_buffer.items[start_empty..end_empty], fill_cell.style orelse self.default_style, ); { var index: u16 = start_empty; while (index < end_empty) : (index += 1) { if (self.default_style.equal(self.style_buffer[index])) { try addChecked(&self.diff_buffer, Position{ .row = index / self.buffer_size.rows, .col = index % self.buffer_size.cols, }); self.style_buffer[index] = style; } } } } } if (size.rows > b_rows) { const start_empty = b_rows * size.cols; const end_empty = size.rows * size.cols; std.mem.set( Rune, self.rune_buffer.items[start_empty..end_empty], fill_cell.rune orelse ' ', ); std.mem.set( Style, self.style_buffer.items[start_empty..end_empty], fill_cell.style orelse self.default_style, ); { var index: u16 = start_empty; while (index < end_empty) : (index += 1) { if (self.default_style.equal(self.style_buffer[index])) { try addChecked(&self.diff_buffer, Position{ .row = index / self.buffer_size.rows, .col = index % self.buffer_size.cols, }); self.style_buffer[index] = style; } } } } self.buffer_size.rows = size.rows; self.buffer_size.cols = size.cols; } pub fn getDefaultStyle(self: *const Self) Style { return self.default_style; } pub fn setDefaultStyle(self: *Self, style: Style) !void { if (self.default_style.equal(style)) return; { var index: u16 = 0; while (index < self.style_buffer.len) : (index += 1) { if (self.default_style.equal(self.style_buffer[index])) { try addChecked(&self.diff_buffer, Position{ .row = index / self.buffer_size.rows, .col = index % self.buffer_size.cols, }); self.style_buffer[index] = style; } } } self.default_style = style; } pub fn getCell(self: *const Self, position: Position) !Cell { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; return Cell{ .rune = self.rune_buffer.items[index], .style = self.style_buffer.items[index], }; } pub fn setCell(self: *Self, position: Position, cell: Cell) !void { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; if (self.rune_buffer.items[index] != cell.rune or !self.style_buffer.items[index].equal(cell.style)) try addChecked(&self.diff_buffer, position); self.rune_buffer.items[index] = cell.rune; self.style_buffer.items[index] = cell.style; } pub fn fillCells(self: *Self, position: Position, cell: Cell, length: u16) !void { if (position.row >= self.buffer_size.rows or position.col + length >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; { var offset: u16 = 0; while (offset < length) : (offset += 1) { if (self.rune_buffer.items[index + offset] != cell.rune or !cell.style.equal(self.style_buffer.items[index + offset])) try addChecked(&self.diff_buffer, Position{ .row = position.row, .col = position.col + offset, }); self.rune_buffer.items[index + offset] = cell.rune; self.style_buffer.items[index + offset] = cell.style; } } } pub fn getRune(self: *const Self, position: Position) !Rune { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; return self.rune_buffer.items[index]; } pub fn setRune(self: *Self, position: Position, rune: Rune) !void { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; if (self.rune_buffer.items[index] != rune) try addChecked(&self.diff_buffer, position); self.rune_buffer.items[index] = rune; } pub fn setRunes(self: *Self, position: Position, runes: []Rune) !void { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols or position.col + runes.len >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; for (runes) |rune, offset| { if (self.rune_buffer.items[index + offset] != rune) try addChecked(&self.diff_buffer, Position{ .row = position.row, .col = position.col + offset, }); self.rune_buffer.items[index + offset] = rune; } } pub fn fillRunes(self: *Self, position: Position, rune: Rune, length: u16) !void { if (position.row >= self.buffer_size.rows or position.col + length >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; { var offset: u16 = 0; while (offset < length) : (offset += 1) { if (self.rune_buffer.items[index + offset] != rune) try addChecked(&self.diff_buffer, Position{ .row = position.row, .col = position.col + offset, }); self.rune_buffer.items[index + offset] = rune; } } } pub fn getStyle(self: *const Self, position: Position) !Style { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; return self.style_buffer.items[index]; } pub fn setStyle(self: *Self, position: Position, style: Style) !void { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; if (!style.equal(self.style_buffer.items[index])) try addChecked(&self.diff_buffer, position); self.style_buffer.items[index] = style; } pub fn setStyles(self: *Self, position: Position, styles: []Styles) !void { if (position.row >= self.buffer_size.rows or position.col >= self.buffer_size.cols or position.col + styles.len >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; for (styles) |style, offset| { if (!style.equal(self.style_buffer.items[index + offset])) try addChecked(&self.diff_buffer, Position{ .row = position.row, .col = position.col + offset, }); self.style_buffer.items[index + offset] = style; } } pub fn fillStyles(self: *Self, position: Position, style: Style, length: u16) !void { if (position.row >= self.buffer_size.rows or position.col + length >= self.buffer_size.cols) return error.OutOfRange; const index = position.row * self.buffer_size.cols + position.col; { var offset: u16 = 0; while (offset < length) : (offset += 1) { if (!style.equal(self.style_buffer.items[index + offset])) try addChecked(&self.diff_buffer, Position{ .row = position.row, .col = position.col + offset, }); self.style_buffer.items[index + offset] = style; } } } };
src/view/screen.zig
const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const Allocator = std.mem.Allocator; // ustar tar implementation pub const Header = extern struct { name: [100]u8, mode: [7:0]u8, uid: [7:0]u8, gid: [7:0]u8, size: [11:0]u8, mtime: [11:0]u8, checksum: [7:0]u8, typeflag: FileType, linkname: [100]u8, magic: [5:0]u8, version: [2]u8, uname: [31:0]u8, gname: [31:0]u8, devmajor: [7:0]u8, devminor: [7:0]u8, prefix: [155]u8, pad: [12]u8, const Self = @This(); const FileType = enum(u8) { regular = '0', hard_link = '1', symbolic_link = '2', character = '3', block = '4', directory = '5', fifo = '6', reserved = '7', pax_global = 'g', extended = 'x', _, }; fn init() Self { var ret = std.mem.zeroes(Self); ret.magic = [_:0]u8{ 'u', 's', 't', 'a', 'r' }; ret.version = [_:0]u8{ '0', '0' }; return ret; } fn setPath(self: *Self, path: []const u8) !void { if (path.len > 100) { var i: usize = 0; while (i < path.len and path.len - i > 100) { while (path[i] != '/') : (i += 1) {} } _ = try std.fmt.bufPrint(&self.prefix, "{s}", .{path[0..i]}); _ = try std.fmt.bufPrint(&self.name, "{s}", .{path[i + 1 ..]}); } else { _ = try std.fmt.bufPrint(&self.name, "{s}", .{path}); } } fn setSize(self: *Self, size: u64) !void { _ = try std.fmt.bufPrint(&self.size, "{o:0>11}", .{size}); } fn setMtime(self: *Self, mtime: u32) !void { _ = try std.fmt.bufPrint(&self.mtime, "{o:0>11}", .{mtime}); } fn setMode(self: *Self, filetype: FileType, perm: u9) !void { switch (filetype) { .regular => _ = try std.fmt.bufPrint(&self.mode, "0100{o:0>3}", .{perm}), .directory => _ = try std.fmt.bufPrint(&self.mode, "0040{o:0>3}", .{perm}), else => return error.Unsupported, } } fn setUid(self: *Self, uid: u32) !void { _ = try std.fmt.bufPrint(&self.uid, "{o:0>7}", .{uid}); } fn setGid(self: *Self, gid: u32) !void { _ = try std.fmt.bufPrint(&self.gid, "{o:0>7}", .{gid}); } fn updateChecksum(self: *Self) !void { const offset = @offsetOf(Self, "checksum"); var checksum: usize = 0; for (std.mem.asBytes(self)) |val, i| { checksum += if (i >= offset and i < offset + @sizeOf(@TypeOf(self.checksum))) ' ' else val; } _ = try std.fmt.bufPrint(&self.checksum, "{o:0>7}", .{checksum}); } fn fromStat(stat: std.fs.File.Stat, path: []const u8) !Header { if (std.mem.indexOf(u8, path, "\\") != null) return error.NeedPosixPath; if (std.fs.path.isAbsolute(path)) return error.NeedRelPath; var ret = Self.init(); ret.typeflag = switch (stat.kind) { .File => .regular, .Directory => .directory, else => return error.UnsupportedType, }; try ret.setPath(path); try ret.setSize(stat.size); try ret.setMtime(@truncate(u32, @bitCast(u128, @divTrunc(stat.mtime, std.time.ns_per_s)))); try ret.setMode(ret.typeflag, @truncate(u9, stat.mode)); try ret.setUid(0); try ret.setGid(0); std.mem.copy(u8, &ret.uname, "root"); std.mem.copy(u8, &ret.gname, "root"); try ret.updateChecksum(); return ret; } pub fn isBlank(self: *const Header) bool { const block = std.mem.asBytes(self); return for (block) |elem| { if (elem != 0) break false; } else true; } }; test "Header size" { try testing.expectEqual(512, @sizeOf(Header)); } pub fn instantiate( allocator: Allocator, dir: std.fs.Dir, reader: anytype, skip_depth: usize, ) !void { var count: usize = 0; while (true) { const header = reader.readStruct(Header) catch |err| { return if (err == error.EndOfStream) if (count < 2) error.AbrubtEnd else break else err; }; if (header.isBlank()) { count += 1; continue; } else if (count > 0) { return error.Format; } var size = try std.fmt.parseUnsigned(usize, &header.size, 8); const block_size = ((size + 511) / 512) * 512; var components = std.ArrayList([]const u8).init(allocator); defer components.deinit(); var path_it = std.mem.tokenize(u8, &header.prefix, "/\x00"); if (header.prefix[0] != 0) { while (path_it.next()) |component| { try components.append(component); } } path_it = std.mem.tokenize(u8, &header.name, "/\x00"); while (path_it.next()) |component| { try components.append(component); } const tmp_path = try std.fs.path.join(allocator, components.items); defer allocator.free(tmp_path); if (skip_depth >= components.items.len) { try reader.skipBytes(block_size, .{}); continue; } var i: usize = 0; while (i < skip_depth) : (i += 1) { _ = components.orderedRemove(0); } const file_path = try std.fs.path.join(allocator, components.items); defer allocator.free(file_path); switch (header.typeflag) { .directory => try dir.makePath(file_path), .pax_global => try reader.skipBytes(512, .{}), .regular => { const file = try dir.createFile(file_path, .{ .read = true, .truncate = true }); defer file.close(); const skip_size = block_size - size; var buf: [std.mem.page_size]u8 = undefined; while (size > 0) { const buffered = try reader.read(buf[0..std.math.min(size, 512)]); try file.writeAll(buf[0..buffered]); size -= buffered; } try reader.skipBytes(skip_size, .{}); }, else => {}, } } } pub fn builder(allocator: Allocator, writer: anytype) Builder(@TypeOf(writer)) { return Builder(@TypeOf(writer)).init(allocator, writer); } pub fn Builder(comptime Writer: type) type { return struct { writer: Writer, arena: std.heap.ArenaAllocator, directories: std.StringHashMap(void), const Self = @This(); pub fn init(allocator: Allocator, writer: Writer) Self { return Self{ .arena = std.heap.ArenaAllocator.init(allocator), .writer = writer, .directories = std.StringHashMap(void).init(allocator), }; } pub fn deinit(self: *Self) void { self.directories.deinit(); self.arena.deinit(); } pub fn finish(self: *Self) !void { try self.writer.writeByteNTimes(0, 1024); } fn maybeAddDirectories( self: *Self, path: []const u8, ) !void { var i: usize = 0; while (i < path.len) : (i += 1) { while (path[i] != '/' and i < path.len) i += 1; if (i >= path.len) break; const dirpath = try self.arena.allocator().dupe(u8, path[0..i]); if (self.directories.contains(dirpath)) continue else try self.directories.put(dirpath, {}); const stat = std.fs.File.Stat{ .inode = undefined, .size = 0, .mode = switch (builtin.os.tag) { .windows => 0, else => 0o755, }, .kind = .Directory, .atime = undefined, .mtime = std.time.nanoTimestamp(), .ctime = undefined, }; const allocator = self.arena.child_allocator; const posix_dirpath = try std.mem.replaceOwned(u8, allocator, dirpath, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix); defer allocator.free(posix_dirpath); const header = try Header.fromStat(stat, posix_dirpath); try self.writer.writeAll(std.mem.asBytes(&header)); } } /// prefix is a path to prepend subpath with pub fn addFile( self: *Self, root: std.fs.Dir, prefix: ?[]const u8, subpath: []const u8, ) !void { const allocator = self.arena.child_allocator; const path = if (prefix) |prefix_path| try std.fs.path.join(allocator, &[_][]const u8{ prefix_path, subpath }) else subpath; defer if (prefix != null) allocator.free(path); const posix_path = try std.mem.replaceOwned(u8, allocator, path, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix); defer allocator.free(posix_path); if (std.fs.path.dirname(posix_path)) |dirname| try self.maybeAddDirectories(posix_path[0 .. dirname.len + 1]); const subfile = try root.openFile(subpath, .{ .read = true, .write = true }); defer subfile.close(); const stat = try subfile.stat(); const header = try Header.fromStat(stat, posix_path); var buf: [std.mem.page_size]u8 = undefined; try self.writer.writeAll(std.mem.asBytes(&header)); var counter = std.io.countingWriter(self.writer); while (true) { const n = try subfile.reader().read(&buf); if (n == 0) break; try counter.writer().writeAll(buf[0..n]); } const padding = blk: { const mod = counter.bytes_written % 512; break :blk if (mod > 0) 512 - mod else 0; }; try self.writer.writeByteNTimes(0, @intCast(usize, padding)); } /// add slice of bytes as file `path` pub fn addSlice(self: *Self, slice: []const u8, path: []const u8) !void { const allocator = self.arena.child_allocator; const posix_path = try std.mem.replaceOwned(u8, allocator, path, std.fs.path.sep_str_windows, std.fs.path.sep_str_posix); defer allocator.free(posix_path); const stat = std.fs.File.Stat{ .inode = undefined, .size = slice.len, .mode = switch (builtin.os.tag) { .windows => 0, else => 0o644, }, .kind = .File, .atime = undefined, .mtime = std.time.nanoTimestamp(), .ctime = undefined, }; var header = try Header.fromStat(stat, posix_path); const padding = blk: { const mod = slice.len % 512; break :blk if (mod > 0) 512 - mod else 0; }; try self.writer.writeAll(std.mem.asBytes(&header)); try self.writer.writeAll(slice); try self.writer.writeByteNTimes(0, padding); } }; } pub const PaxHeaderMap = struct { text: []const u8, map: std.StringHashMap([]const u8), const Self = @This(); pub fn init(allocator: Allocator, reader: anytype) !Self { // TODO: header verification const header = try reader.readStruct(Header); if (header.typeflag != .pax_global) return error.NotPaxGlobalHeader; const size = try std.fmt.parseInt(usize, &header.size, 8); const text = try allocator.alloc(u8, size); errdefer allocator.free(text); var i: usize = 0; while (i < size) : (i = try reader.read(text[i..])) {} var map = std.StringHashMap([]const u8).init(allocator); errdefer map.deinit(); var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line| { const begin = (std.mem.indexOf(u8, line, " ") orelse return error.BadMapEntry) + 1; const eql = std.mem.indexOf(u8, line[begin..], "=") orelse return error.BadMapEntry; try map.put(line[begin .. begin + eql], line[begin + eql + 1 ..]); } return Self{ .text = text, .map = map, }; } pub fn get(self: Self, key: []const u8) ?[]const u8 { return self.map.get(key); } pub fn deinit(self: *Self) void { self.map.allocator.free(self.text); self.map.deinit(); } }; pub fn fileExtractor(path: []const u8, reader: anytype) FileExtractor(@TypeOf(reader)) { return FileExtractor(@TypeOf(reader)).init(path, reader); } pub fn FileExtractor(comptime ReaderType: type) type { return struct { path: []const u8, internal: ReaderType, len: ?usize, const Self = @This(); pub fn init(path: []const u8, internal: ReaderType) Self { return Self{ .path = path, .internal = internal, .len = null, }; } pub const Error = ReaderType.Error || error{ FileNotFound, EndOfStream } || std.fmt.ParseIntError; pub const Reader = std.io.Reader(*Self, Error, read); pub fn read(self: *Self, buf: []u8) Error!usize { if (self.len == null) { while (true) { const header = try self.internal.readStruct(Header); for (std.mem.asBytes(&header)) |c| { if (c != 0) break; } else return error.FileNotFound; const size = try std.fmt.parseInt(usize, &header.size, 8); const name = header.name[0 .. std.mem.indexOf(u8, &header.name, "\x00") orelse header.name.len]; if (std.mem.eql(u8, name, self.path)) { self.len = size; break; } else if (size > 0) { try self.internal.skipBytes(size + (512 - (size % 512)), .{}); } } } const n = try self.internal.read(buf[0..std.math.min(self.len.?, buf.len)]); self.len.? -= n; return n; } pub fn reader(self: *Self) Reader { return .{ .context = self }; } }; }
src/main.zig
const std = @import("std"); const upaya = @import("upaya"); const ts = @import("../tilescript.zig"); usingnamespace @import("imgui"); const TileDefinitions = ts.data.TileDefinitions; pub fn draw(state: *ts.AppState) void { if (state.prefs.windows.tile_definitions) { ogSetNextWindowSize(.{ .x = 210, .y = -1 }, ImGuiCond_Always); if (igBegin("Tile Definitions", &state.prefs.windows.tile_definitions, ImGuiWindowFlags_AlwaysAutoResize)) { defer igEnd(); inline for (@typeInfo(TileDefinitions).Struct.fields) |field, i| { igPushIDInt(@intCast(c_int, i)); defer igPopID(); drawTileIcon(field.name); igDummy(.{}); igSameLine(0, igGetFrameHeight() + 7); // replace underscores with spaces var buffer = upaya.mem.tmp_allocator.alloc(u8, field.name.len) catch unreachable; for (field.name) |char, j| { buffer[j] = if (char == '_') ' ' else char; } igAlignTextToFramePadding(); igText(buffer.ptr); igSameLine(0, 0); igSetCursorPosX(igGetWindowContentRegionWidth() - 35); if (ogButton("Tiles")) { igOpenPopup("tag-tiles"); } ogSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 }); if (igBeginPopup("tag-tiles", ImGuiWindowFlags_None)) { defer igEndPopup(); var list = &@field(state.map.tile_definitions, field.name); tileSelectorPopup(state, list); } } } } } fn drawTileIcon(comptime name: []const u8) void { var tl = ogGetCursorScreenPos(); var tr = tl; tr.x += igGetFrameHeight(); var bl = tl; bl.y += igGetFrameHeight(); var br = bl; br.x += igGetFrameHeight(); var color = ts.colors.colorRgb(252, 186, 3); if (std.mem.eql(u8, name, "solid")) { ogImDrawList_AddQuadFilled(igGetWindowDrawList(), &tl, &tr, &br, &bl, color); } else if (std.mem.eql(u8, name, "slope_down")) { tl.y += igGetFrameHeight() / 2; ImDrawList_AddTriangleFilled(igGetWindowDrawList(), tl, bl, br, color); } else if (std.mem.eql(u8, name, "slope_down_steep")) { ImDrawList_AddTriangleFilled(igGetWindowDrawList(), tl, bl, br, color); } else if (std.mem.eql(u8, name, "slope_up")) { tr.y += igGetFrameHeight() / 2; ImDrawList_AddTriangleFilled(igGetWindowDrawList(), bl, br, tr, color); } else if (std.mem.eql(u8, name, "slope_up_steep")) { ImDrawList_AddTriangleFilled(igGetWindowDrawList(), bl, br, tr, color); } } fn tileSelectorPopup(state: *ts.AppState, list: anytype) void { var content_start_pos = ogGetCursorScreenPos(); const zoom: usize = if (state.texture.width < 200 and state.texture.height < 200) 2 else 1; const tile_spacing = state.map.tile_spacing * zoom; const tile_size = state.map.tile_size * zoom; ogImage(state.texture.imTextureID(), state.texture.width * @intCast(i32, zoom), state.texture.height * @intCast(i32, zoom)); const draw_list = igGetWindowDrawList(); // draw selected tiles var iter = list.iter(); while (iter.next()) |value| { ts.addTileToDrawList(tile_size, content_start_pos, value, state.tilesPerRow(), tile_spacing); } // check input for toggling state if (igIsItemHovered(ImGuiHoveredFlags_None)) { if (igIsMouseClicked(0, false)) { var tile = ts.tileIndexUnderMouse(@intCast(usize, tile_size + tile_spacing), content_start_pos); TileDefinitions.toggleSelected(list, @intCast(u8, tile.x + tile.y * state.tilesPerRow())); } } if (igButton("Clear", .{ .x = -1 })) { list.clear(); } }
tilescript/windows/tile_definitions.zig
const std = @import("std"); const ziglet = @import("../ziglet.zig"); const util = @import("util.zig"); const assert = std.debug.assert; const native = @import("windows/native.zig"); const mem = std.mem; pub const Event = ziglet.app.event.Event; pub const Key = ziglet.app.event.Key; pub const MouseButton = ziglet.app.event.MouseButton; const Backend = union(ziglet.gfx.RenderBackend) { OpenGL: @import("backend/opengl.zig").Context, DirectX11: @import("backend/directx.zig").Context, }; fn intToKey(lParam: native.LPARAM) Key { return switch (lParam & 0x1ff) { 0x00B => Key.Key0, 0x002 => Key.Key1, 0x003 => Key.Key2, 0x004 => Key.Key3, 0x005 => Key.Key4, 0x006 => Key.Key5, 0x007 => Key.Key6, 0x008 => Key.Key7, 0x009 => Key.Key8, 0x00A => Key.Key9, 0x01E => Key.A, 0x030 => Key.B, 0x02E => Key.C, 0x020 => Key.D, 0x012 => Key.E, 0x021 => Key.F, 0x022 => Key.G, 0x023 => Key.H, 0x017 => Key.I, 0x024 => Key.J, 0x025 => Key.K, 0x026 => Key.L, 0x032 => Key.M, 0x031 => Key.N, 0x018 => Key.O, 0x019 => Key.P, 0x010 => Key.Q, 0x013 => Key.R, 0x01F => Key.S, 0x014 => Key.T, 0x016 => Key.U, 0x02F => Key.V, 0x011 => Key.W, 0x02D => Key.X, 0x015 => Key.Y, 0x02C => Key.Z, 0x03B => Key.F1, 0x03C => Key.F2, 0x03D => Key.F3, 0x03E => Key.F4, 0x03F => Key.F5, 0x040 => Key.F6, 0x041 => Key.F7, 0x042 => Key.F8, 0x043 => Key.F9, 0x044 => Key.F10, 0x057 => Key.F11, 0x058 => Key.F12, 0x150 => Key.Down, 0x14B => Key.Left, 0x14D => Key.Right, 0x148 => Key.Up, 0x028 => Key.Apostrophe, 0x029 => Key.Backquote, 0x02B => Key.Backslash, 0x033 => Key.Comma, 0x00D => Key.Equal, 0x01A => Key.LeftBracket, 0x00C => Key.Minus, 0x034 => Key.Period, 0x01B => Key.RightBracket, 0x027 => Key.Semicolon, 0x035 => Key.Slash, 0x00E => Key.Backspace, 0x153 => Key.Delete, 0x14F => Key.End, 0x01C => Key.Enter, 0x001 => Key.Escape, 0x147 => Key.Home, 0x152 => Key.Insert, 0x15D => Key.Menu, 0x151 => Key.PageDown, 0x149 => Key.PageUp, 0x045 => Key.Pause, 0x039 => Key.Space, 0x00F => Key.Tab, 0x145 => Key.NumLock, 0x03A => Key.CapsLock, 0x046 => Key.ScrollLock, 0x02A => Key.LeftShift, 0x036 => Key.RightShift, 0x01D => Key.LeftControl, 0x11D => Key.RightControl, 0x052 => Key.Kp0, 0x04F => Key.Kp1, 0x050 => Key.Kp2, 0x051 => Key.Kp3, 0x04B => Key.Kp4, 0x04C => Key.Kp5, 0x04D => Key.Kp6, 0x047 => Key.Kp7, 0x048 => Key.Kp8, 0x049 => Key.Kp9, 0x053 => Key.KpDecimal, 0x135 => Key.KpDivide, 0x037 => Key.KpMultiply, 0x04A => Key.KpSubtract, 0x04E => Key.KpMultiply, 0x11C => Key.KpEnter, 0x038 => Key.LeftAlt, 0x138 => Key.RightAlt, else => Key.Unknown, }; } pub const Window = struct { handle: native.HWND, fullscreen: bool, borderless: bool, resizeable: bool, width: usize, height: usize, title: []const u8, mouse_tracked: bool, iconified: bool, pub should_close: bool, pub event_pump: ziglet.app.event.EventPump, fn window_resized(self: *Window) ?[2]i32 { var rect: native.RECT = undefined; if (native.GetClientRect(self.handle, &rect) == native.TRUE) { const new_width = @intCast(usize, rect.right - rect.left); const new_height = @intCast(usize, rect.bottom - rect.top); if ((new_width != self.width) or (new_height != self.height)) { self.width = new_width; self.height = new_height; return []i32{ @intCast(i32, new_width), @intCast(i32, new_height), }; } } else { self.width = 1; self.height = 1; } return null; } stdcallcc fn wnd_proc(hWnd: native.HWND, msg: native.UINT, wParam: native.WPARAM, lParam: native.LPARAM) native.LRESULT { var result: native.LRESULT = 0; var self = @intToPtr(?*Window, native.GetWindowLongPtrW(hWnd, native.GWLP_USERDATA)) orelse { return native.DefWindowProcW(hWnd, msg, wParam, lParam); }; switch (msg) { native.WM_CLOSE => { self.should_close = true; }, native.WM_SYSKEYDOWN, native.WM_KEYDOWN => { self.event_pump.push(Event{ .KeyDown = intToKey(lParam >> 16) }) catch unreachable; }, native.WM_SYSKEYUP, native.WM_KEYUP => { self.event_pump.push(Event{ .KeyUp = intToKey(lParam >> 16) }) catch unreachable; }, native.WM_SYSCHAR, native.WM_CHAR => { self.event_pump.push(Event{ .Char = @intCast(u8, wParam) }) catch unreachable; }, native.WM_LBUTTONDOWN => { self.event_pump.push(Event{ .MouseDown = MouseButton.Left }) catch unreachable; }, native.WM_RBUTTONDOWN => { self.event_pump.push(Event{ .MouseDown = MouseButton.Right }) catch unreachable; }, native.WM_MBUTTONDOWN => { self.event_pump.push(Event{ .MouseDown = MouseButton.Middle, }) catch unreachable; }, native.WM_LBUTTONUP => { self.event_pump.push(Event{ .MouseUp = MouseButton.Left }) catch unreachable; }, native.WM_RBUTTONUP => { self.event_pump.push(Event{ .MouseUp = MouseButton.Right }) catch unreachable; }, native.WM_MBUTTONUP => { self.event_pump.push(Event{ .MouseUp = MouseButton.Middle, }) catch unreachable; }, native.WM_MOUSEWHEEL => { if (self.mouse_tracked) { const scroll = @intToFloat(f32, @intCast(i16, @truncate(u16, (@truncate(u32, wParam) >> 16) & 0xffff))) * 0.1; self.event_pump.push(Event{ .MouseScroll = []f32{ 0.0, scroll }, }) catch unreachable; } }, native.WM_MOUSEHWHEEL => { if (self.mouse_tracked) { const scroll = @intToFloat(f32, @intCast(i16, @truncate(u16, (@truncate(u32, wParam) >> 16) & 0xffff))) * 0.1; self.event_pump.push(Event{ .MouseScroll = []f32{ scroll, 0.0 }, }) catch unreachable; } }, native.WM_MOUSEMOVE => { if (!self.mouse_tracked) { self.mouse_tracked = true; var tme: native.TRACKMOUSEEVENT = undefined; tme.cbSize = @sizeOf(native.TRACKMOUSEEVENT); tme.dwFlags = native.TME_LEAVE; tme.hwndTrack = self.handle; assert(native.TrackMouseEvent(&tme) != 0); self.event_pump.push(Event{ .MouseEnter = {}, }) catch unreachable; } self.event_pump.push(Event{ .MouseMove = []f32{ @bitCast(f32, native.GET_X_LPARAM(lParam)), @bitCast(f32, native.GET_Y_LPARAM(lParam)), }, }) catch unreachable; }, native.WM_MOUSELEAVE => { self.mouse_tracked = false; self.event_pump.push(Event{ .MouseLeave = {}, }) catch unreachable; }, native.WM_SIZE => { const iconified = wParam == native.SIZE_MINIMIZED; if (iconified != self.iconified) { self.iconified = iconified; if (iconified) { self.event_pump.push(Event{ .Iconified = {}, }) catch unreachable; } else { self.event_pump.push(Event{ .Restored = {}, }) catch unreachable; } } if (self.window_resized()) |new_size| { self.event_pump.push(Event{ .Resized = new_size, }) catch unreachable; } }, // native.WM_DROPFILES => { // const hDrop = @intToPtr(native.HDROP, wParam); // const count = native.DragQueryFileW(hDrop, 0xFFFFFFFF, null, 0); // var index: c_uint = 0; // while (index < count) : (index += 1) { // var in_buffer = []u16{0} ** (std.os.MAX_PATH_BYTES / 3 + 1); // var out_buffer = []u8{0} ** (std.os.MAX_PATH_BYTES + 1); // const len = native.DragQueryFileW(hDrop, index, in_buffer[0..].ptr, in_buffer.len); // _ = std.unicode.utf16leToUtf8(out_buffer[0..], in_buffer[0..]) catch unreachable; // self.event_pump.push(Event { // .FileDroppped = out_buffer[0..len], // }) catch unreachable; // } // native.DragFinish(hDrop); // }, else => { return native.DefWindowProcW(hWnd, msg, wParam, lParam); }, } return result; } fn open_window(options: ziglet.app.WindowOptions) ziglet.app.WindowError!native.HWND { const wtitle = util.L(options.title)[0..]; const wcex = native.WNDCLASSEX{ .cbSize = @sizeOf(native.WNDCLASSEX), .style = native.CS_HREDRAW | native.CS_VREDRAW | native.CS_OWNDC, .lpfnWndProc = wnd_proc, .cbClsExtra = 0, .cbWndExtra = 0, .hInstance = native.GetModuleHandleW(null), .hIcon = native.LoadIconW(null, native.IDI_WINLOGO).?, .hCursor = native.LoadCursorW(null, native.IDC_ARROW).?, .hbrBackground = null, .lpszMenuName = null, .lpszClassName = wtitle.ptr, .hIconSm = null, }; if (native.RegisterClassExW(&wcex) == 0) { return error.InitError; } var rect = native.RECT{ .left = 0, .right = @truncate(c_int, @intCast(isize, options.width)), .top = 0, .bottom = @truncate(c_int, @intCast(isize, options.height)), }; var dwExStyle: u32 = 0; var dwStyle: u32 = native.WS_CLIPSIBLINGS | native.WS_CLIPCHILDREN; if (options.fullscreen) { var dmScreenSettings: native.DEVMODEW = undefined; dmScreenSettings.dmSize = @sizeOf(native.DEVMODEW); dmScreenSettings.dmPelsWidth = @intCast(u32, options.width); dmScreenSettings.dmPelsHeight = @intCast(u32, options.height); dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = native.DM_BITSPERPEL | native.DM_PELSWIDTH | native.DM_PELSHEIGHT; if (native.ChangeDisplaySettingsW(&dmScreenSettings, native.CDS_FULLSCREEN) != 0) { return error.InitError; } else { dwExStyle = native.WS_EX_APPWINDOW; dwStyle |= native.WS_POPUP; _ = native.ShowCursor(native.FALSE); } } else { dwExStyle = native.WS_EX_APPWINDOW | native.WS_EX_WINDOWEDGE | native.WS_EX_ACCEPTFILES; dwStyle |= native.DWORD(native.WS_OVERLAPPEDWINDOW); if (options.resizeable) { dwStyle |= native.DWORD(native.WS_THICKFRAME) | native.DWORD(native.WS_MAXIMIZEBOX); } else { dwStyle &= ~native.DWORD(native.WS_MAXIMIZEBOX); dwStyle &= ~native.DWORD(native.WS_THICKFRAME); } if (options.borderless) { dwStyle &= ~native.DWORD(native.WS_THICKFRAME); } } if (native.AdjustWindowRectEx(&rect, dwStyle, native.FALSE, dwExStyle) == 0) { return error.InitError; } rect.right -= rect.left; rect.bottom -= rect.top; const result = native.CreateWindowExW(dwExStyle, wtitle.ptr, wtitle.ptr, dwStyle, native.CW_USEDEFAULT, native.CW_USEDEFAULT, rect.right, rect.bottom, null, null, wcex.hInstance, null) orelse return error.InitError; _ = native.ShowWindow(result, native.SW_NORMAL); return result; } pub fn init(allocator: *mem.Allocator, options: ziglet.app.WindowOptions) ziglet.app.WindowError!Window { var result = Window{ .handle = undefined, .fullscreen = options.fullscreen, .borderless = options.borderless, .resizeable = options.resizeable, .width = options.width, .height = options.height, .title = options.title, .should_close = false, .mouse_tracked = false, .iconified = false, .event_pump = ziglet.app.event.EventPump.init(allocator), }; errdefer result.deinit(); result.handle = try open_window(options); return result; } pub fn deinit(self: Window) void { if (self.fullscreen) { _ = native.ChangeDisplaySettingsW(null, 0); _ = native.ShowCursor(native.TRUE); } _ = native.UnregisterClassW(util.L(self.title)[0..].ptr, native.GetModuleHandleW(null)); } fn message_loop(self: *const Window) void { var msg: native.MSG = undefined; while (native.PeekMessageW(&msg, self.handle, 0, 0, native.PM_REMOVE) == native.TRUE) { if (msg.message == native.WM_QUIT) break; _ = native.TranslateMessage(&msg); _ = native.DispatchMessageW(&msg); } } pub fn update(self: *Window) void { _ = native.SetWindowLongPtrW(self.handle, native.GWLP_USERDATA, @ptrToInt(self)); self.message_loop(); } };
src/app/windows.zig
const debug = @import("std").debug; const stdmath = @import("std").math; const mathutil = @import("../math/MathUtil.zig"); const vec3 = @import("../math/Vec3.zig"); const mat4x4 = @import("../math/Mat4x4.zig"); const quat = @import("../math/Quat.zig"); const Vec3 = vec3.Vec3; const Mat4x4 = mat4x4.Mat4x4; const Quat = quat.Quat; const defaultAspect: comptime f32 = 16.0 / 9.0; //16:9 //TODO initialize perspective const defaultYFoV: comptime f32 = 1.353540; // 110 degrees hfov -> 77.55 vfov at 16:9 -> then convert to rad // 1.0 aspect ratio //const defaultAspect: comptime f32 = 1.0; //1:1 //const defaultYFoV: comptime f32 = 1.570796; // 90 deg -> convert to rad pub const Camera = struct { m_pos: Vec3 = vec3.zero, m_rotation: Quat = quat.identity, m_up: Vec3 = vec3.yAxis, m_fovY: f32 = defaultYFoV, //110 deg default m_aspectRatio: f32 = defaultAspect, //16:9 m_nearPlane: f32 = 0.1, m_farPlane: f32 = 100.0, //TODO reference glm lookat pub fn GetViewMatrix(self: *const Camera) Mat4x4 { const viewDirection = vec3.zAxis.RotatedByQuat(self.m_rotation); var lookAtMat = mat4x4.LookDirMat4x4(self.m_pos, viewDirection, vec3.yAxis); return lookAtMat; } pub fn GetProjectionMatrix(self: *const Camera) Mat4x4 { var returnMat = mat4x4.zero; const tanHalfFoVY = stdmath.tan(self.m_fovY * 0.5); const frustrumDepth = self.m_farPlane - self.m_nearPlane; returnMat.m[0][0] = 1.0 / (tanHalfFoVY * self.m_aspectRatio); returnMat.m[1][1] = 1.0 / tanHalfFoVY; returnMat.m[2][2] = self.m_farPlane / frustrumDepth; returnMat.m[2][3] = 1.0; returnMat.m[3][2] = -(self.m_farPlane * self.m_nearPlane) / frustrumDepth; return returnMat; } pub fn GetOrthoMatrix(self: *const Camera, left: f32, right: f32, bottom: f32, top: f32) Mat4x4 { var returnMat = mat4x4.identity; returnMat.m[0][0] = 2.0 / (right - left); returnMat.m[1][1] = 2.0 / (top - bottom); returnMat.m[2][2] = 1.0 / (self.m_farPlane - self.m_nearPlane); returnMat.m[3][0] = -(right + left) / (right - left); returnMat.m[3][1] = -(top + bottom) / (top - bottom); returnMat.m[3][2] = -self.m_nearPlane / (self.m_farPlane - self.m_nearPlane); return returnMat; } }; // takes radians, gives radians // can't be called at comptime because std tan/atan bug?? pub fn XFoVToYFoV(xFoV: f32, aspectRatio: f32) f32 { return 2.0 * stdmath.atan(stdmath.tan(xFoV * 0.5) * aspectRatio); }
src/presentation/Camera.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const assert = std.debug.assert; const Tokenizer = @This(); bytes: []const u8, index: usize = 0, pub const Location = struct { line: usize = 1, column: usize = 1, }; const log = std.log.scoped(.tokenizer); pub const Token = struct { tag: Tag, start: usize, end: usize, pub const Tag = enum(u8) { eof, nl = '\n', space = ' ', word, line = '-', hash = '#', pipe = '|', colon = ':', l_angle = '<', l_brace = '{', l_bracket = '[', l_paren = '(', r_angle = '>', r_brace = '}', r_bracket = ']', r_paren = ')', unknown, }; pub fn slice(t: Token, bytes: []const u8) []const u8 { return bytes[t.start..t.end]; } pub fn len(t: Token) usize { return t.end - t.start; } }; pub fn locationFrom(self: Tokenizer, from: Location) Location { assert(from.line != 0); assert(from.column != 0); var loc = from; const start = from.line * from.column - 1; for (self.bytes[start..self.index]) |byte| { if (byte == '\n') { loc.line += 1; loc.column = 1; } else { loc.column += 1; } } return loc; } pub fn next(self: *Tokenizer) Token { var token: Token = .{ .tag = .eof, .start = self.index, .end = undefined, }; defer log.debug("{s: >10} {d: >3} | {s}", .{ @tagName(token.tag), token.len(), token.slice(self.bytes), }); const State = enum { start, trivial, unknown, word }; var state: State = .start; var trivial: u8 = 0; while (self.index < self.bytes.len) : (self.index += 1) { const c = self.bytes[self.index]; switch (state) { .start => switch (c) { ' ', '\n' => { token.tag = @intToEnum(Token.Tag, c); trivial = c; state = .trivial; }, '-' => { token.tag = .line; trivial = '-'; state = .trivial; }, 'a'...'z' => { token.tag = .word; state = .word; }, '#', ':' => { token.tag = @intToEnum(Token.Tag, c); self.index += 1; break; }, '<', '{', '[', '(', ')', ']', '}', '>' => { token.tag = @intToEnum(Token.Tag, c); trivial = c; state = .trivial; }, '|' => { token.tag = .pipe; self.index += 1; break; }, else => { token.tag = .unknown; state = .unknown; }, }, .trivial => if (c != trivial) break, .word => switch (c) { 'a'...'z', 'A'...'Z', '#', '+', '-', '\'', '_' => {}, else => break, }, .unknown => if (mem.indexOfScalar(u8, "\n <{[()]}>:|", c)) |_| { break; }, } } token.end = self.index; return token; } test "tokenize whitespace" { try testTokenize("\n", &.{.nl}); try testTokenize(" ", &.{.space}); try testTokenize("\n\n\n\n\n", &.{.nl}); try testTokenize("\n\n \n\n\n", &.{ .nl, .space, .nl }); } test "tokenize header" { try testTokenize("-", &.{.line}); try testTokenize("#", &.{.hash}); try testTokenize(":", &.{.colon}); try testTokenize("-----------------", &.{.line}); try testTokenize("###", &.{ .hash, .hash, .hash }); try testTokenize(":::", &.{ .colon, .colon, .colon }); } test "tokenize include" { try testTokenize("|", &.{.pipe}); try testTokenize("|||", &.{ .pipe, .pipe, .pipe }); } test "tokenize unknown" { try testTokenize("/file.example/path/../__", &.{.unknown}); } fn testTokenize(text: []const u8, expected: []const Token.Tag) !void { var it: Tokenizer = .{ .bytes = text }; for (expected) |tag| { const token = it.next(); try testing.expectEqual(tag, token.tag); } const token = it.next(); try testing.expectEqual(Token.Tag.eof, token.tag); try testing.expectEqual(text.len, token.end); }
lib/Tokenizer.zig
const std = @import("std"); const warn = std.debug.warn; const TypeId = @import("builtin").TypeId; const c = @cImport({ @cInclude("sys/socket.h"); @cInclude("netinet/in.h"); @cInclude("unistd.h"); @cInclude("errno.h"); @cInclude("string.h"); @cInclude("errno-access.h"); @cInclude("signal.h"); }); const SIG_ERR = @intToPtr(extern fn (c_int) void, std.math.maxInt(usize)); const SOCK_STREAM = if (@typeId(@typeOf(c.SOCK_STREAM)) == TypeId.Enum) @enumToInt(c.SOCK_STREAM) else c.SOCK_STREAM; fn onError(what: []const u8, code: i32) void { onErrorNoExit(what, code); std.process.exit(1); } fn onErrorNoExit(what: []const u8, code: i32) void { const message = std.mem.toSliceConst(u8, c.strerror(c.get_errno())); warn("Command '{}' failed with code {}. Message: {}\n", what, code, message); } extern fn onSignal(signo: c_int) void { if (signo == c.SIGINT) { warn("Received signal 'SIGINT'. Exiting..\n"); std.process.exit(0); } else { warn("Received unknown signal {}.\n", signo); } } pub fn main() void { if (c.signal(c.SIGINT, onSignal) == SIG_ERR) { onError("signal", @intCast(i32, @ptrToInt(SIG_ERR))); } const fd = c.socket(c.AF_INET, SOCK_STREAM, 0); if (fd == 0) { onError("socket", fd); } const opt: i32 = 1; const setSockOptCode = c.setsockopt(fd, c.SOL_SOCKET, c.SO_REUSEADDR | c.SO_REUSEPORT, @intToPtr(?*const c_void, @ptrToInt(&opt)), @sizeOf(@typeOf(opt))); if (setSockOptCode != 0) { onError("setsockopt", setSockOptCode); } const inAddr = c.in_addr{ .s_addr = c.INADDR_ANY, }; var address = c.sockaddr_in{ .sin_family = c.AF_INET, .sin_addr = inAddr, .sin_port = c.htons(8080), .sin_zero = [_]u8{0} ** 8, }; const bindCode = c.bind(fd, @ptrCast([*c]const c.sockaddr, &address), @sizeOf(c.sockaddr_in)); if (bindCode != 0) { onError("bind", bindCode); } const listenCode = c.listen(fd, 3); if (listenCode != 0) { onError("listen", listenCode); } while (true) { var addrlen: c_uint = @sizeOf(c.sockaddr_in); const clientHandle = c.accept(fd, @ptrCast([*c]c.sockaddr, &address), &addrlen); defer { const closeCode = c.close(clientHandle); if (closeCode < 0) { onErrorNoExit("close", closeCode); } } if (clientHandle < 0) { onErrorNoExit("accept", clientHandle); continue; } var buffer = [_]u8{0} ** 1024; const readCode = c.read(clientHandle, @ptrCast(?*c_void, &buffer[0]), buffer.len); if (readCode < 0) { onErrorNoExit("read", @intCast(i32, readCode)); continue; } if (readCode == 0) { continue; } const bufStr = (&buffer)[0..@intCast(usize, readCode)]; var lines = std.mem.separate(bufStr, "\r\n"); const firstLine = lines.next(); var userAgent: []const u8 = ""; while (lines.next()) |line| { if (std.mem.startsWith(u8, line, "User-Agent")) { userAgent = line; break; } } warn("Access: {} | {}\n", firstLine, userAgent); const robotstxt = \\HTTP/1.1 200 OK \\Content-Length: 26 \\ \\User-agent: * \\Disallow: / \\ ; const bytesSent = c.send(clientHandle, &robotstxt, robotstxt.len, 0); if (bytesSent < 0) { onErrorNoExit("send", @intCast(i32, bytesSent)); } } }
src/server.zig
usingnamespace @import("psptypes.zig"); pub const PspSysMemBlockTypes = extern enum(c_int) { MemLow = 0, MemHigh = 1, MemAddr = 2, }; pub const SceKernelSysMemAlloc_t = c_int; // Allocate a memory block from a memory partition. // // @param partitionid - The UID of the partition to allocate from. // @param name - Name assigned to the new block. // @param type - Specifies how the block is allocated within the partition. One of ::PspSysMemBlockTypes. // @param size - Size of the memory block, in bytes. // @param addr - If type is PSP_SMEM_Addr, then addr specifies the lowest address allocate the block from. // // @return The UID of the new block, or if less than 0 an error. pub extern fn sceKernelAllocPartitionMemory(partitionid: SceUID, name: [*c]const u8, typec: c_int, size: SceSize, addr: ?*c_void) SceUID; pub fn kernelAllocPartitionMemory(partitionid: SceUID, name: [*c]const u8, typec: c_int, size: SceSize, addr: ?*c_void) !SceUID { var res = sceKernelAllocPartitionMemory(partitionid, name, typec, size, addr); if (res < 0) { return error.AllocationError; } return res; } // Free a memory block allocated with ::sceKernelAllocPartitionMemory. // // @param blockid - UID of the block to free. // // @return ? on success, less than 0 on error. pub extern fn sceKernelFreePartitionMemory(blockid: SceUID) c_int; // Get the address of a memory block. // // @param blockid - UID of the memory block. // // @return The lowest address belonging to the memory block. pub extern fn sceKernelGetBlockHeadAddr(blockid: SceUID) ?*c_void; // Get the total amount of free memory. // // @return The total amount of free memory, in bytes. pub extern fn sceKernelTotalFreeMemSize() SceSize; // Get the size of the largest free memory block. // // @return The size of the largest free memory block, in bytes. pub extern fn sceKernelMaxFreeMemSize() SceSize; // Get the firmware version. // // @return The firmware version. // 0x01000300 on v1.00 unit, // 0x01050001 on v1.50 unit, // 0x01050100 on v1.51 unit, // 0x01050200 on v1.52 unit, // 0x02000010 on v2.00/v2.01 unit, // 0x02050010 on v2.50 unit, // 0x02060010 on v2.60 unit, // 0x02070010 on v2.70 unit, // 0x02070110 on v2.71 unit. pub extern fn sceKernelDevkitVersion() c_int; // Set the version of the SDK with which the caller was compiled. // Version numbers are as for sceKernelDevkitVersion(). // // @return 0 on success, < 0 on error. pub extern fn sceKernelSetCompiledSdkVersion(version: c_int) c_int; pub fn kernelSetCompiledSdkVersion(version: c_int) !void { var res = sceKernelSetCompiledSdkVersion(version); if (res < 0) { return error.Unexpected; } } // Get the SDK version set with sceKernelSetCompiledSdkVersion(). // // @return Version number, or 0 if unset. pub extern fn sceKernelGetCompiledSdkVersion() c_int;
src/psp/sdk/pspsysmem.zig
const std = @import("std"); const slf = @import("slf.zig"); const args_parser = @import("args"); pub fn printUsage(stream: anytype) !void { try stream.writeAll( \\slf-ld [-h] [-o <file>] [-b <base>] [-s 8|16|32|64] [-a <align>] <object> ... \\ \\Links several SLF files together into a single binary. At least one <object> file in SLF format must be present. \\ \\Options: \\ -h, --help Prints this text. \\ -o, --output <file> The resulting binary file. Default is a.out. \\ -s, --symsize <size> Defines the symbol size in bits. Allowed values are 8, 16, 32, and 64. Default is guessed by the first object file. \\ -a, --align <al> Aligns each module to <al> bytes. <al> must be a power of two. Default is 16. \\ -b, --base <orig> Modules start at offset <orig>. <orig> must be aligned. Default is 0x00000000. \\ ); } const CliOptions = struct { help: bool = false, output: ?[]const u8 = null, symsize: u8 = 16, @"align": u32 = 16, base: u32 = 0, pub const shorthands = .{ .h = "help", .o = "output", .s = "symsize", .a = "align", .b = "base", }; }; pub fn main() !u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var stderr = std.io.getStdErr().writer(); var stdout = std.io.getStdOut().writer(); var cli = args_parser.parseForCurrentProcess(CliOptions, gpa.allocator(), .print) catch return 1; defer cli.deinit(); if (cli.options.help) { try printUsage(stdout); return 0; } if (cli.positionals.len == 0) { try printUsage(stderr); return 1; } const symbol_size = std.meta.intToEnum(slf.SymbolSize, cli.options.symsize / 8) catch { try stderr.print("{} is not a valid symbol size.\n", .{cli.options.symsize}); return 1; }; if (!std.math.isPowerOfTwo(cli.options.@"align")) { try stderr.print("{} is not a power of two.\n", .{cli.options.@"align"}); return 1; } if (!std.mem.isAligned(cli.options.base, cli.options.@"align")) { try stderr.print("{} is not aligned to {}.\n", .{ cli.options.base, cli.options.@"align" }); return 1; } var linker = slf.Linker.init(gpa.allocator()); defer linker.deinit(); var arena = std.heap.ArenaAllocator.init(gpa.allocator()); defer arena.deinit(); for (cli.positionals) |file_name| { var file_data = std.fs.cwd().readFileAlloc(arena.allocator(), file_name, 1 << 30) catch |err| { // 1 GB max. switch (err) { error.FileNotFound => try stderr.print("The file {s} does not exist.\n", .{file_name}), else => |e| return e, } return 1; }; errdefer arena.allocator().free(file_data); const view = slf.View.init(file_data, .{}) catch { try stderr.print("The file {s} does not seem to be a valid SLF file.\n", .{file_name}); return 1; }; try linker.addModule(view); } var result = try std.fs.cwd().createFile(cli.options.output orelse "a.out", .{ .read = true }); defer result.close(); var stream = std.io.StreamSource{ .file = result }; try linker.link(&stream, .{ .symbol_size = symbol_size, .module_alignment = cli.options.@"align", .base_address = cli.options.base, }); return 0; }
src/ld.zig
const nk = @import("nuklear"); const std = @import("std"); const c = @cImport({ @cInclude("GLFW/glfw3.h"); }); const examples = @import("examples.zig"); const heap = std.heap; const math = std.math; const mem = std.mem; const unicode = std.unicode; pub fn main() !void { const allocator = heap.c_allocator; if (c.glfwInit() == 0) return error.InitFailed; const win = c.glfwCreateWindow(800, 600, "yo", null, null) orelse return error.CouldNotCreateWindow; _ = c.glfwMakeContextCurrent(win); _ = c.glfwSetScrollCallback(win, scrollCallback); _ = c.glfwSetCharCallback(win, charCallback); var width: c_int = undefined; var height: c_int = undefined; c.glfwGetWindowSize(win, &width, &height); var atlas = nk.atlas.init(allocator); defer nk.atlas.clear(&atlas); nk.atlas.begin(&atlas); const baked = try nk.atlas.bake(&atlas, .rgba32); const font_tex = uploadAtlas(baked.data, baked.w, baked.h); var _null: nk.DrawNullTexture = undefined; nk.atlas.end( &atlas, nk.rest.nkHandleId(@intCast(c_int, font_tex)), &_null, ); var ctx = nk.init(allocator, &atlas.default_font.*.handle); defer nk.free(&ctx); ctx.clip.copy = undefined; ctx.clip.paste = undefined; ctx.clip.userdata = undefined; var program = Program{ .ctx = ctx, .null_texture = _null, .cmds = nk.Buffer.init(allocator, mem.page_size), .vbuf = nk.Buffer.init(allocator, mem.page_size), .ebuf = nk.Buffer.init(allocator, mem.page_size), .win = win, }; defer { program.cmds.free(); program.vbuf.free(); program.ebuf.free(); } c.glfwSetWindowUserPointer(win, @ptrCast(*c_void, &program)); while (c.glfwWindowShouldClose(program.win) == 0) { program.input(); examples.showcase(&program.ctx); program.render(); } } const Program = @This(); ctx: nk.Context, null_texture: nk.DrawNullTexture, cmds: nk.Buffer, vbuf: nk.Buffer, ebuf: nk.Buffer, win: *c.GLFWwindow, fn input(program: *Program) void { const ctx = &program.ctx; const win = program.win; nk.input.begin(ctx); c.glfwPollEvents(); if (ctx.input.mouse.grab != 0) { c.glfwSetInputMode(win, c.GLFW_CURSOR, c.GLFW_CURSOR_HIDDEN); } else if (ctx.input.mouse.ungrab != 0) { c.glfwSetInputMode(win, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL); } nk.input.key(ctx, .del, c.glfwGetKey(win, c.GLFW_KEY_DELETE) == c.GLFW_PRESS); nk.input.key(ctx, .enter, c.glfwGetKey(win, c.GLFW_KEY_ENTER) == c.GLFW_PRESS); nk.input.key(ctx, .tab, c.glfwGetKey(win, c.GLFW_KEY_TAB) == c.GLFW_PRESS); nk.input.key(ctx, .backspace, c.glfwGetKey(win, c.GLFW_KEY_BACKSPACE) == c.GLFW_PRESS); nk.input.key(ctx, .up, c.glfwGetKey(win, c.GLFW_KEY_UP) == c.GLFW_PRESS); nk.input.key(ctx, .down, c.glfwGetKey(win, c.GLFW_KEY_DOWN) == c.GLFW_PRESS); nk.input.key(ctx, .text_start, c.glfwGetKey(win, c.GLFW_KEY_HOME) == c.GLFW_PRESS); nk.input.key(ctx, .text_end, c.glfwGetKey(win, c.GLFW_KEY_END) == c.GLFW_PRESS); nk.input.key(ctx, .scroll_start, c.glfwGetKey(win, c.GLFW_KEY_HOME) == c.GLFW_PRESS); nk.input.key(ctx, .scroll_end, c.glfwGetKey(win, c.GLFW_KEY_END) == c.GLFW_PRESS); nk.input.key(ctx, .scroll_down, c.glfwGetKey(win, c.GLFW_KEY_PAGE_DOWN) == c.GLFW_PRESS); nk.input.key(ctx, .scroll_up, c.glfwGetKey(win, c.GLFW_KEY_PAGE_UP) == c.GLFW_PRESS); nk.input.key(ctx, .shift, c.glfwGetKey(win, c.GLFW_KEY_LEFT_SHIFT) == c.GLFW_PRESS or c.glfwGetKey(win, c.GLFW_KEY_RIGHT_SHIFT) == c.GLFW_PRESS); if (c.glfwGetKey(win, c.GLFW_KEY_LEFT_CONTROL) == c.GLFW_PRESS or c.glfwGetKey(win, c.GLFW_KEY_RIGHT_CONTROL) == c.GLFW_PRESS) { nk.input.key(ctx, .copy, c.glfwGetKey(win, c.GLFW_KEY_C) == c.GLFW_PRESS); nk.input.key(ctx, .paste, c.glfwGetKey(win, c.GLFW_KEY_V) == c.GLFW_PRESS); nk.input.key(ctx, .cut, c.glfwGetKey(win, c.GLFW_KEY_X) == c.GLFW_PRESS); nk.input.key(ctx, .text_undo, c.glfwGetKey(win, c.GLFW_KEY_Z) == c.GLFW_PRESS); nk.input.key(ctx, .text_redo, c.glfwGetKey(win, c.GLFW_KEY_R) == c.GLFW_PRESS); nk.input.key(ctx, .text_word_left, c.glfwGetKey(win, c.GLFW_KEY_LEFT) == c.GLFW_PRESS); nk.input.key(ctx, .text_word_right, c.glfwGetKey(win, c.GLFW_KEY_RIGHT) == c.GLFW_PRESS); nk.input.key(ctx, .text_line_start, c.glfwGetKey(win, c.GLFW_KEY_B) == c.GLFW_PRESS); nk.input.key(ctx, .text_line_end, c.glfwGetKey(win, c.GLFW_KEY_E) == c.GLFW_PRESS); } else { nk.input.key(ctx, .left, c.glfwGetKey(win, c.GLFW_KEY_LEFT) == c.GLFW_PRESS); nk.input.key(ctx, .right, c.glfwGetKey(win, c.GLFW_KEY_RIGHT) == c.GLFW_PRESS); nk.input.key(ctx, .copy, false); nk.input.key(ctx, .paste, false); nk.input.key(ctx, .cut, false); nk.input.key(ctx, .shift, false); } var fx: f64 = undefined; var fy: f64 = undefined; c.glfwGetCursorPos(win, &fx, &fy); const x = @floatToInt(c_int, fx); const y = @floatToInt(c_int, fy); nk.input.motion(ctx, x, y); if (ctx.input.mouse.grabbed != 0) { c.glfwSetCursorPos(win, ctx.input.mouse.prev.x, ctx.input.mouse.prev.y); ctx.input.mouse.pos.x = ctx.input.mouse.prev.x; ctx.input.mouse.pos.y = ctx.input.mouse.prev.y; } nk.input.button(ctx, .left, x, y, c.glfwGetMouseButton(win, c.GLFW_MOUSE_BUTTON_LEFT) == c.GLFW_PRESS); nk.input.button(ctx, .middle, x, y, c.glfwGetMouseButton(win, c.GLFW_MOUSE_BUTTON_MIDDLE) == c.GLFW_PRESS); nk.input.button(ctx, .right, x, y, c.glfwGetMouseButton(win, c.GLFW_MOUSE_BUTTON_RIGHT) == c.GLFW_PRESS); nk.input.end(ctx); } const GlfwVertex = extern struct { position: [2]f32, uv: [2]f32, col: [4]u8, }; fn render(program: *Program) void { const ctx = &program.ctx; const win = program.win; const cmds = &program.cmds; const ebuf = &program.ebuf; const vbuf = &program.vbuf; var width: c_int = undefined; var height: c_int = undefined; var display_width: c_int = undefined; var display_height: c_int = undefined; c.glfwGetWindowSize(win, &width, &height); c.glfwGetFramebufferSize(win, &display_width, &display_height); const fb_scale_x = @intToFloat(f32, display_width) / @intToFloat(f32, width); const fb_scale_y = @intToFloat(f32, display_height) / @intToFloat(f32, height); c.glViewport(0, 0, width, height); c.glClear(c.GL_COLOR_BUFFER_BIT); c.glClearColor(255, 255, 255, 0); c.glPushAttrib(c.GL_ENABLE_BIT | c.GL_COLOR_BUFFER_BIT | c.GL_TRANSFORM_BIT); c.glDisable(c.GL_CULL_FACE); c.glDisable(c.GL_DEPTH_TEST); c.glEnable(c.GL_SCISSOR_TEST); c.glEnable(c.GL_BLEND); c.glEnable(c.GL_TEXTURE_2D); c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA); c.glViewport(0, 0, display_width, display_height); c.glMatrixMode(c.GL_PROJECTION); c.glPushMatrix(); c.glLoadIdentity(); c.glOrtho(0.0, @intToFloat(f64, width), @intToFloat(f64, height), 0.0, -1.0, 1.0); c.glMatrixMode(c.GL_MODELVIEW); c.glPushMatrix(); c.glLoadIdentity(); c.glEnableClientState(c.GL_VERTEX_ARRAY); c.glEnableClientState(c.GL_TEXTURE_COORD_ARRAY); c.glEnableClientState(c.GL_COLOR_ARRAY); { const vs = @sizeOf(GlfwVertex); const vp = @byteOffsetOf(GlfwVertex, "position"); const vt = @byteOffsetOf(GlfwVertex, "uv"); const vc = @byteOffsetOf(GlfwVertex, "col"); const vertex_layout = [_]nk.DrawVertexLayoutElement{ .{ .attribute = .NK_VERTEX_POSITION, .format = .NK_FORMAT_FLOAT, .offset = vp }, .{ .attribute = .NK_VERTEX_TEXCOORD, .format = .NK_FORMAT_FLOAT, .offset = vt }, .{ .attribute = .NK_VERTEX_COLOR, .format = .NK_FORMAT_R8G8B8A8, .offset = vc }, .{ .attribute = .NK_VERTEX_ATTRIBUTE_COUNT, .format = .NK_FORMAT_COUNT, .offset = 0 }, }; cmds.clear(); vbuf.clear(); ebuf.clear(); _ = nk.vertex.convert(ctx, cmds, vbuf, ebuf, .{ .vertex_layout = &vertex_layout, .vertex_size = @sizeOf(GlfwVertex), .vertex_alignment = @alignOf(GlfwVertex), .@"null" = program.null_texture, .circle_segment_count = 22, .curve_segment_count = 22, .arc_segment_count = 22, .global_alpha = 1.0, .shape_AA = .NK_ANTI_ALIASING_ON, .line_AA = .NK_ANTI_ALIASING_ON, }); const vertices = vbuf.memory(); c.glVertexPointer(2, c.GL_FLOAT, vs, @ptrCast(*const c_void, @ptrCast([*]const u8, vertices) + vp)); c.glTexCoordPointer(2, c.GL_FLOAT, vs, @ptrCast(*const c_void, @ptrCast([*]const u8, vertices) + vt)); c.glColorPointer(4, c.GL_UNSIGNED_BYTE, vs, @ptrCast(*const c_void, @ptrCast([*]const u8, vertices) + vc)); var offset = @ptrCast( [*]const nk.DrawIndex, @alignCast(@alignOf(nk.DrawIndex), ebuf.memory()), ); var it = nk.vertex.iterator(ctx, cmds); while (it.next()) |cmd| { if (cmd.elem_count == 0) continue; c.glBindTexture(c.GL_TEXTURE_2D, @intCast(c.GLuint, cmd.texture.id)); c.glScissor( @floatToInt(c.GLint, cmd.clip_rect.x * fb_scale_x), @floatToInt(c.GLint, @intToFloat( f32, height - @floatToInt(c.GLint, cmd.clip_rect.y + cmd.clip_rect.h), ) * fb_scale_y), @floatToInt(c.GLint, cmd.clip_rect.w * fb_scale_x), @floatToInt(c.GLint, cmd.clip_rect.h * fb_scale_y), ); c.glDrawElements(c.GL_TRIANGLES, @intCast(c.GLsizei, cmd.elem_count), c.GL_UNSIGNED_SHORT, offset); offset += cmd.elem_count; } nk.clear(ctx); } c.glDisableClientState(c.GL_VERTEX_ARRAY); c.glDisableClientState(c.GL_TEXTURE_COORD_ARRAY); c.glDisableClientState(c.GL_COLOR_ARRAY); c.glDisable(c.GL_CULL_FACE); c.glDisable(c.GL_DEPTH_TEST); c.glDisable(c.GL_SCISSOR_TEST); c.glDisable(c.GL_BLEND); c.glDisable(c.GL_TEXTURE_2D); c.glBindTexture(c.GL_TEXTURE_2D, 0); c.glMatrixMode(c.GL_MODELVIEW); c.glPopMatrix(); c.glMatrixMode(c.GL_PROJECTION); c.glPopMatrix(); c.glPopAttrib(); c.glfwSwapBuffers(win); } fn uploadAtlas(data: [*]const u8, w: usize, h: usize) c.GLuint { var font_tex: c.GLuint = undefined; c.glGenTextures(1, &font_tex); c.glBindTexture(c.GL_TEXTURE_2D, font_tex); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR); c.glTexImage2D( c.GL_TEXTURE_2D, 0, c.GL_RGBA, @intCast(c_int, w), @intCast(c_int, h), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, data, ); return font_tex; } fn scrollCallback(win: ?*c.GLFWwindow, xoffset: f64, yoffset: f64) callconv(.C) void { const usrptr = c.glfwGetWindowUserPointer(win); const program = @ptrCast(*Program, @alignCast(@alignOf(Program), usrptr)); var new_scroll = program.ctx.input.mouse.scroll_delta; new_scroll.x += @floatCast(f32, xoffset); new_scroll.y += @floatCast(f32, yoffset); nk.input.scroll(&program.ctx, new_scroll); } fn charCallback(win: ?*c.GLFWwindow, codepoint: c_uint) callconv(.C) void { const usrptr = c.glfwGetWindowUserPointer(win); const program = @ptrCast(*Program, @alignCast(@alignOf(Program), usrptr)); nk.input.unicode(&program.ctx, @intCast(u21, codepoint)); }
examples/main.zig
const std = @import("std"); const assert = std.debug.assert; const config = @import("config.zig"); const tb = @import("tigerbeetle.zig"); const Account = tb.Account; const Transfer = tb.Transfer; const Commit = tb.Commit; const CreateAccountsResult = tb.CreateAccountsResult; const CreateTransfersResult = tb.CreateTransfersResult; const CommitTransfersResult = tb.CommitTransfersResult; const IO = @import("io.zig").IO; const MessageBus = @import("message_bus.zig").MessageBusClient; const StateMachine = @import("state_machine.zig").StateMachine; const vsr = @import("vsr.zig"); const Header = vsr.Header; const Client = vsr.Client(StateMachine, MessageBus); pub const log_level: std.log.Level = .alert; pub fn request( operation: StateMachine.Operation, batch: anytype, on_reply: fn ( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void, ) !void { const allocator = std.heap.page_allocator; const client_id = std.crypto.random.int(u128); const cluster_id: u32 = 0; var addresses = [_]std.net.Address{try std.net.Address.parseIp4("127.0.0.1", config.port)}; var io = try IO.init(32, 0); defer io.deinit(); var message_bus = try MessageBus.init(allocator, cluster_id, &addresses, client_id, &io); defer message_bus.deinit(); var client = try Client.init( allocator, client_id, cluster_id, @intCast(u8, addresses.len), &message_bus, ); defer client.deinit(); message_bus.set_on_message(*Client, &client, Client.on_message); var message = client.get_message(); defer client.unref(message); const body = std.mem.asBytes(&batch); std.mem.copy(u8, message.buffer[@sizeOf(Header)..], body); client.request( 0, on_reply, operation, message, body.len, ); while (client.request_queue.count > 0) { client.tick(); try io.run_for_ns(config.tick_ms * std.time.ns_per_ms); } } pub fn on_create_accounts( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = user_data; _ = operation; print_results(CreateAccountsResult, results); } pub fn on_lookup_accounts( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = user_data; _ = operation; print_results(Account, results); } pub fn on_lookup_transfers( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = user_data; _ = operation; print_results(Transfer, results); } pub fn on_create_transfers( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = user_data; _ = operation; print_results(CreateTransfersResult, results); } pub fn on_commit_transfers( user_data: u128, operation: StateMachine.Operation, results: Client.Error![]const u8, ) void { _ = user_data; _ = operation; print_results(CommitTransfersResult, results); } fn print_results(comptime Results: type, results: Client.Error![]const u8) void { const body = results catch unreachable; const slice = std.mem.bytesAsSlice(Results, body); for (slice) |result| { std.debug.print("{}\n", .{result}); } if (slice.len == 0) std.debug.print("OK\n", .{}); }
src/demo.zig
const std = @import("std"); const Signal = @import("signal.zig").Signal; const Delegate = @import("delegate.zig").Delegate; /// helper used to connect and disconnect listeners on the fly from a Signal. Listeners are wrapped in Delegates /// and can be either free functions or functions bound to a struct. pub fn Sink(comptime Event: type) type { return struct { const Self = @This(); insert_index: usize, /// the Signal this Sink is temporarily wrapping var owning_signal: *Signal(Event) = undefined; pub fn init(signal: *Signal(Event)) Self { owning_signal = signal; return Self{ .insert_index = owning_signal.calls.items.len }; } pub fn before(self: Self, callback: ?fn (Event) void) Self { if (callback) |cb| { if (self.indexOf(cb)) |index| { return Self{ .insert_index = index }; } } return self; } pub fn beforeBound(self: Self, ctx: anytype) Self { if (@typeInfo(@TypeOf(ctx)) == .Pointer) { if (self.indexOfBound(ctx)) |index| { return Self{ .insert_index = index }; } } return self; } pub fn connect(self: Self, callback: fn (Event) void) void { std.debug.assert(self.indexOf(callback) == null); _ = owning_signal.calls.insert(self.insert_index, Delegate(Event).initFree(callback)) catch unreachable; } pub fn connectBound(self: Self, ctx: anytype, comptime fn_name: []const u8) void { std.debug.assert(self.indexOfBound(ctx) == null); _ = owning_signal.calls.insert(self.insert_index, Delegate(Event).initBound(ctx, fn_name)) catch unreachable; } pub fn disconnect(self: Self, callback: fn (Event) void) void { if (self.indexOf(callback)) |index| { _ = owning_signal.calls.swapRemove(index); } } pub fn disconnectBound(self: Self, ctx: anytype) void { if (self.indexOfBound(ctx)) |index| { _ = owning_signal.calls.swapRemove(index); } } fn indexOf(_: Self, callback: fn (Event) void) ?usize { for (owning_signal.calls.items) |call, i| { if (call.containsFree(callback)) { return i; } } return null; } fn indexOfBound(_: Self, ctx: anytype) ?usize { for (owning_signal.calls.items) |call, i| { if (call.containsBound(ctx)) { return i; } } return null; } }; } fn tester(param: u32) void { std.testing.expectEqual(@as(u32, 666), param) catch unreachable; } const Thing = struct { field: f32 = 0, pub fn tester(_: *Thing, param: u32) void { std.testing.expectEqual(@as(u32, 666), param) catch unreachable; } }; test "Sink Before free" { var signal = Signal(u32).init(std.testing.allocator); defer signal.deinit(); signal.sink().connect(tester); try std.testing.expectEqual(signal.sink().indexOf(tester).?, 0); var thing = Thing{}; signal.sink().before(tester).connectBound(&thing, "tester"); try std.testing.expectEqual(signal.sink().indexOfBound(&thing).?, 0); } test "Sink Before bound" { var signal = Signal(u32).init(std.testing.allocator); defer signal.deinit(); var thing = Thing{}; signal.sink().connectBound(&thing, "tester"); try std.testing.expectEqual(signal.sink().indexOfBound(&thing).?, 0); signal.sink().beforeBound(&thing).connect(tester); try std.testing.expectEqual(signal.sink().indexOf(tester).?, 0); }
src/signals/sink.zig
pub const Window = @import("window.zig").Window; pub const Widget = @import("widget.zig").Widget; pub usingnamespace @import("button.zig"); pub usingnamespace @import("label.zig"); pub usingnamespace @import("text.zig"); pub usingnamespace @import("canvas.zig"); pub usingnamespace @import("containers.zig"); pub usingnamespace @import("data.zig"); pub usingnamespace @import("image.zig"); pub usingnamespace @import("color.zig"); pub const internal = @import("internal.zig"); pub const backend = @import("backend.zig"); pub const cross_platform = if (@hasDecl(backend, "backendExport")) backend.backendExport else struct {}; pub const GlBackend = @import("backends/gles/backend.zig"); pub const MouseButton = backend.MouseButton; pub const EventLoopStep = @import("backends/shared.zig").EventLoopStep; /// Posts an empty event to finish the current step started in zgt.stepEventLoop pub fn wakeEventLoop() void { backend.postEmptyEvent(); } /// Returns false if the last window has been closed. /// Even if the wanted step type is Blocking, zgt has the right /// to request an asynchronous step to the backend in order to animate /// data wrappers. pub fn stepEventLoop(stepType: EventLoopStep) bool { const data = @import("data.zig"); if (data._animatedDataWrappers.items.len > 0) { for (data._animatedDataWrappers.items) |item, i| { if (item.fnPtr(item.userdata) == false) { // animation ended _ = data._animatedDataWrappers.swapRemove(i); } } return backend.runStep(.Asynchronous); } else { return backend.runStep(stepType); } } pub fn runEventLoop() void { while (true) { if (@import("std").io.is_async) { if (!stepEventLoop(.Asynchronous)) { break; } if (@import("std").event.Loop.instance) |*loop| { loop.yield(); } } else { if (!stepEventLoop(.Blocking)) { break; } } } } test { _ = @import("fuzz.zig"); // testing the fuzzing library }
src/main.zig
const std = @import("std"); const ArrayList = std.ArrayList; const fs = std.fs; // // Build // pub fn build(b: *std.build.Builder) void { const pkg_version = "0.0.0"; const abi_version = b.version(0, 0, 0); const inst_step = b.getInstallStep(); const test_step = b.step("test", "Run tests"); const bench_step = b.step("bench", "Run benchmarks"); // // Options // b.setPreferredReleaseMode(.ReleaseFast); const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const prefix = b.option([]const u8, "prefix", "System install prefix (/usr/local)"); const enable_bench = b.option(bool, "bench", "Build benchmarks (true)") orelse true; const enable_pic = b.option(bool, "pic", "Force PIC (false)"); const enable_portable = b.option(bool, "portable", "Be as portable as possible (false)") orelse false; const enable_pthread = b.option(bool, "pthread", "Use pthread (true)") orelse true; const enable_shared = b.option(bool, "shared", "Build shared library (true)") orelse true; const enable_tests = b.option(bool, "tests", "Enable tests (true)") orelse true; const strip = (b.is_release and !target.isWindows()); // // Variables // var flags = ArrayList([]const u8).init(b.allocator); var defines = ArrayList([]const u8).init(b.allocator); var libs = ArrayList([]const u8).init(b.allocator); defer flags.deinit(); defer defines.deinit(); defer libs.deinit(); // // Global Flags // if (target.isGnuLibC()) { flags.append("-std=c89") catch unreachable; } flags.append("-fvisibility=hidden") catch unreachable; if (target.isDarwin()) { flags.append("-mmacosx-version-min=10.7") catch unreachable; } if (mode == .ReleaseFast) { flags.append("-O3") catch unreachable; } // // Feature Test Macros // if (target.isWindows()) { defines.append("_WIN32_WINNT=0x501") catch unreachable; } if (target.isGnuLibC()) { defines.append("_GNU_SOURCE") catch unreachable; } if (target.getOsTag() == .solaris) { defines.append("_TS_ERRNO") catch unreachable; } if (target.getOsTag() == .aix) { defines.append("_THREAD_SAFE_ERRNO") catch unreachable; } // // System Libraries // if (target.isWindows()) { libs.append("kernel32") catch unreachable; } else { if (enable_pthread and target.getOsTag() != .wasi) { flags.append("-pthread") catch unreachable; libs.append("pthread") catch unreachable; defines.append("LDB_PTHREAD") catch unreachable; } } // // Sources // const sources = [_][]const u8{ "src/util/arena.c", "src/util/array.c", "src/util/atomic.c", "src/util/bloom.c", "src/util/buffer.c", "src/util/cache.c", "src/util/comparator.c", "src/util/crc32c.c", "src/util/env.c", "src/util/hash.c", "src/util/internal.c", "src/util/logger.c", "src/util/options.c", "src/util/port.c", "src/util/random.c", "src/util/rbt.c", "src/util/slice.c", "src/util/snappy.c", "src/util/status.c", "src/util/strutil.c", "src/util/thread_pool.c", "src/util/vector.c", "src/table/block.c", "src/table/block_builder.c", "src/table/filter_block.c", "src/table/format.c", "src/table/iterator.c", "src/table/merger.c", "src/table/table.c", "src/table/table_builder.c", "src/table/two_level_iterator.c", "src/builder.c", "src/c.c", "src/db_impl.c", "src/db_iter.c", "src/dbformat.c", "src/dumpfile.c", "src/filename.c", "src/log_reader.c", "src/log_writer.c", "src/memtable.c", "src/repair.c", "src/skiplist.c", "src/table_cache.c", "src/version_edit.c", "src/version_set.c", "src/write_batch.c" }; // // Flags // const warn_flags = [_][]const u8{ "-pedantic", "-Wall", "-Wextra", "-Wcast-align", "-Wconditional-uninitialized", "-Wmissing-prototypes", "-Wno-implicit-fallthrough", "-Wno-long-long", "-Wno-overlength-strings", "-Wshadow", "-Wstrict-prototypes", "-Wundef" }; for (warn_flags) |flag| { flags.append(flag) catch unreachable; } // // Defines // if (mode == .Debug) { defines.append("LDB_DEBUG") catch unreachable; } if (!enable_portable) { defines.append("LDB_HAVE_FDATASYNC") catch unreachable; defines.append("LDB_HAVE_PREAD") catch unreachable; } // // Targets // const libname = if (target.isWindows()) "liblcdb" else "lcdb"; const lcdb = b.addStaticLibrary(libname, null); lcdb.setTarget(target); lcdb.setBuildMode(mode); lcdb.install(); lcdb.linkLibC(); lcdb.addIncludeDir("./include"); lcdb.addCSourceFiles(&sources, flags.items); lcdb.force_pic = enable_pic; lcdb.strip = strip; for (defines.items) |def| { lcdb.defineCMacroRaw(def); } if (enable_shared and target.getOsTag() != .wasi) { const shared = b.addSharedLibrary("lcdb", null, abi_version); shared.setTarget(target); shared.setBuildMode(mode); shared.install(); shared.linkLibC(); shared.addIncludeDir("./include"); shared.addCSourceFiles(&sources, flags.items); shared.strip = strip; for (defines.items) |def| { shared.defineCMacroRaw(def); } shared.defineCMacroRaw("LDB_EXPORT"); for (libs.items) |lib| { shared.linkSystemLibrary(lib); } } const dbutil = b.addExecutable("lcdbutil", null); dbutil.setTarget(target); dbutil.setBuildMode(mode); dbutil.install(); dbutil.linkLibC(); dbutil.linkLibrary(lcdb); dbutil.addIncludeDir("./include"); dbutil.addCSourceFile("src/dbutil.c", flags.items); dbutil.strip = strip; for (defines.items) |def| { dbutil.defineCMacroRaw(def); } for (libs.items) |lib| { dbutil.linkSystemLibrary(lib); } // // Benchmarks // const bench = b.addExecutable("db_bench", null); bench.setTarget(target); bench.setBuildMode(mode); bench.linkLibC(); bench.linkLibrary(lcdb); bench.addIncludeDir("./include"); bench.addIncludeDir("./src"); bench.addCSourceFiles(&.{ "bench/db_bench.c", "bench/histogram.c", "src/util/testutil.c" }, flags.items); for (defines.items) |def| { bench.defineCMacroRaw(def); } for (libs.items) |lib| { bench.linkSystemLibrary(lib); } if (enable_bench) { inst_step.dependOn(&bench.step); } bench_step.dependOn(&bench.run().step); // // Tests // const testutil = b.addStaticLibrary("test", null); testutil.setTarget(target); testutil.setBuildMode(mode); testutil.linkLibC(); testutil.addIncludeDir("./include"); testutil.addCSourceFile("src/util/testutil.c", flags.items); for (defines.items) |def| { testutil.defineCMacroRaw(def); } const tests = [_][]const u8{ "arena", "autocompact", "bloom", "c", "cache", "coding", "corruption", "crc32c", "db", "dbformat", "env", "filename", "filter_block", "hash", "issue178", "issue200", "issue320", "log", "rbt", "recovery", "simple", "skiplist", "snappy", "status", "strutil", "table", "version_edit", "version_set", "write_batch" }; for (tests) |name| { const t = b.addExecutable(b.fmt("t-{s}", .{ name }), null); t.setTarget(target); t.setBuildMode(mode); t.linkLibC(); t.linkLibrary(testutil); t.linkLibrary(lcdb); t.addIncludeDir("./include"); t.addIncludeDir("./src"); t.addCSourceFile(b.fmt("test/t-{s}.c", .{ name }), flags.items); for (defines.items) |def| { t.defineCMacroRaw(def); } for (libs.items) |lib| { t.linkSystemLibrary(lib); } if (enable_tests) { inst_step.dependOn(&t.step); } test_step.dependOn(&t.run().step); } // // Package Config // if (!target.isWindows() and target.getOsTag() != .wasi) { const pkg_prefix = prefix orelse "/usr/local"; const pkg_libs = if (enable_pthread) "-lpthread" else ""; const pkg_conf = b.fmt( \\prefix={s} \\exec_prefix=${{prefix}} \\libdir=${{exec_prefix}}/{s} \\includedir=${{prefix}}/{s} \\ \\Name: lcdb \\Version: {s} \\Description: Database for C. \\URL: https://github.com/chjj/lcdb \\ \\Cflags: -I${{includedir}} \\Libs: -L${{libdir}} -llcdb \\Libs.private: {s} \\ , .{ pkg_prefix, "lib", "include", pkg_version, pkg_libs } ); fs.cwd().writeFile(b.pathFromRoot("lcdb.pc"), pkg_conf) catch {}; } // // Install // b.installFile("include/lcdb.h", "include/lcdb.h"); b.installFile("include/lcdb_c.h", "include/lcdb_c.h"); if (!target.isWindows() and target.getOsTag() != .wasi) { b.installFile("LICENSE", "share/licenses/lcdb/LICENSE"); b.installFile("README.md", "share/doc/lcdb/README.md"); b.installFile("lcdb.pc", "lib/pkgconfig/lcdb.pc"); } else { b.installFile("LICENSE", "LICENSE"); b.installFile("README.md", "README.md"); } }
build.zig
pub const __int8_t = i8; pub const __uint8_t = u8; pub const __int16_t = c_short; pub const __uint16_t = c_ushort; pub const __int32_t = c_int; pub const __uint32_t = c_uint; pub const __int64_t = c_longlong; pub const __uint64_t = c_ulonglong; pub const __darwin_intptr_t = c_long; pub const __darwin_natural_t = c_uint; pub const __darwin_ct_rune_t = c_int; pub const __mbstate_t = extern union { __mbstate8: [128]u8, _mbstateL: c_longlong, }; pub const __darwin_mbstate_t = __mbstate_t; pub const __darwin_ptrdiff_t = c_long; pub const __darwin_size_t = c_ulong; pub const struct___va_list_tag = extern struct { gp_offset: c_uint, fp_offset: c_uint, overflow_arg_area: ?*c_void, reg_save_area: ?*c_void, }; pub const __builtin_va_list = [1]struct___va_list_tag; pub const __darwin_va_list = __builtin_va_list; pub const __darwin_wchar_t = c_int; pub const __darwin_rune_t = __darwin_wchar_t; pub const __darwin_wint_t = c_int; pub const __darwin_clock_t = c_ulong; pub const __darwin_socklen_t = __uint32_t; pub const __darwin_ssize_t = c_long; pub const __darwin_time_t = c_long; pub const u_int8_t = u8; pub const u_int16_t = c_ushort; pub const u_int32_t = c_uint; pub const u_int64_t = c_ulonglong; pub const register_t = i64; pub const user_addr_t = u_int64_t; pub const user_size_t = u_int64_t; pub const user_ssize_t = i64; pub const user_long_t = i64; pub const user_ulong_t = u_int64_t; pub const user_time_t = i64; pub const user_off_t = i64; pub const syscall_arg_t = u_int64_t; pub const __darwin_blkcnt_t = __int64_t; pub const __darwin_blksize_t = __int32_t; pub const __darwin_dev_t = __int32_t; pub const __darwin_fsblkcnt_t = c_uint; pub const __darwin_fsfilcnt_t = c_uint; pub const __darwin_gid_t = __uint32_t; pub const __darwin_id_t = __uint32_t; pub const __darwin_ino64_t = __uint64_t; pub const __darwin_ino_t = __darwin_ino64_t; pub const __darwin_mach_port_name_t = __darwin_natural_t; pub const __darwin_mach_port_t = __darwin_mach_port_name_t; pub const __darwin_mode_t = __uint16_t; pub const __darwin_off_t = __int64_t; pub const __darwin_pid_t = __int32_t; pub const __darwin_sigset_t = __uint32_t; pub const __darwin_suseconds_t = __int32_t; pub const __darwin_uid_t = __uint32_t; pub const __darwin_useconds_t = __uint32_t; pub const __darwin_uuid_t = [16]u8; pub const __darwin_uuid_string_t = [37]u8; pub const struct___darwin_pthread_handler_rec = extern struct { __routine: ?extern fn(?*c_void) void, __arg: ?*c_void, __next: [*c]struct___darwin_pthread_handler_rec, }; pub const struct__opaque_pthread_attr_t = extern struct { __sig: c_long, __opaque: [56]u8, }; pub const struct__opaque_pthread_cond_t = extern struct { __sig: c_long, __opaque: [40]u8, }; pub const struct__opaque_pthread_condattr_t = extern struct { __sig: c_long, __opaque: [8]u8, }; pub const struct__opaque_pthread_mutex_t = extern struct { __sig: c_long, __opaque: [56]u8, }; pub const struct__opaque_pthread_mutexattr_t = extern struct { __sig: c_long, __opaque: [8]u8, }; pub const struct__opaque_pthread_once_t = extern struct { __sig: c_long, __opaque: [8]u8, }; pub const struct__opaque_pthread_rwlock_t = extern struct { __sig: c_long, __opaque: [192]u8, }; pub const struct__opaque_pthread_rwlockattr_t = extern struct { __sig: c_long, __opaque: [16]u8, }; pub const struct__opaque_pthread_t = extern struct { __sig: c_long, __cleanup_stack: [*c]struct___darwin_pthread_handler_rec, __opaque: [8176]u8, }; pub const __darwin_pthread_attr_t = struct__opaque_pthread_attr_t; pub const __darwin_pthread_cond_t = struct__opaque_pthread_cond_t; pub const __darwin_pthread_condattr_t = struct__opaque_pthread_condattr_t; pub const __darwin_pthread_key_t = c_ulong; pub const __darwin_pthread_mutex_t = struct__opaque_pthread_mutex_t; pub const __darwin_pthread_mutexattr_t = struct__opaque_pthread_mutexattr_t; pub const __darwin_pthread_once_t = struct__opaque_pthread_once_t; pub const __darwin_pthread_rwlock_t = struct__opaque_pthread_rwlock_t; pub const __darwin_pthread_rwlockattr_t = struct__opaque_pthread_rwlockattr_t; pub const __darwin_pthread_t = [*c]struct__opaque_pthread_t; pub fn _OSSwapInt16(_data: __uint16_t) __uint16_t { return __uint16_t((c_int(_data) << @import("std").math.Log2Int(c_int)(8)) | (c_int(_data) >> @import("std").math.Log2Int(c_int)(8))); } pub const u_char = u8; pub const u_short = c_ushort; pub const u_int = c_uint; pub const u_long = c_ulong; pub const ushort = c_ushort; pub const uint = c_uint; pub const u_quad_t = u_int64_t; pub const quad_t = i64; pub const qaddr_t = [*c]quad_t; pub const caddr_t = [*c]u8; pub const daddr_t = i32; pub const dev_t = __darwin_dev_t; pub const fixpt_t = u_int32_t; pub const blkcnt_t = __darwin_blkcnt_t; pub const blksize_t = __darwin_blksize_t; pub const gid_t = __darwin_gid_t; pub const in_addr_t = __uint32_t; pub const in_port_t = __uint16_t; pub const ino_t = __darwin_ino_t; pub const ino64_t = __darwin_ino64_t; pub const key_t = __int32_t; pub const mode_t = __darwin_mode_t; pub const nlink_t = __uint16_t; pub const id_t = __darwin_id_t; pub const pid_t = __darwin_pid_t; pub const off_t = __darwin_off_t; pub const segsz_t = i32; pub const swblk_t = i32; pub const uid_t = __darwin_uid_t; pub const clock_t = __darwin_clock_t; pub const time_t = __darwin_time_t; pub const useconds_t = __darwin_useconds_t; pub const suseconds_t = __darwin_suseconds_t; pub const rsize_t = __darwin_size_t; pub const errno_t = c_int; pub const struct_fd_set = extern struct { fds_bits: [32]__int32_t, }; pub const fd_set = struct_fd_set; pub fn __darwin_fd_isset(_n: c_int, _p: [*c]const struct_fd_set) c_int { return _p.?.fds_bits[c_ulong(_n) / (@sizeOf(__int32_t) *% c_ulong(8))] & __int32_t(c_ulong(1) << @import("std").math.Log2Int(c_ulong)(c_ulong(_n) % (@sizeOf(__int32_t) *% c_ulong(8)))); } pub const fd_mask = __int32_t; pub const pthread_attr_t = __darwin_pthread_attr_t; pub const pthread_cond_t = __darwin_pthread_cond_t; pub const pthread_condattr_t = __darwin_pthread_condattr_t; pub const pthread_mutex_t = __darwin_pthread_mutex_t; pub const pthread_mutexattr_t = __darwin_pthread_mutexattr_t; pub const pthread_once_t = __darwin_pthread_once_t; pub const pthread_rwlock_t = __darwin_pthread_rwlock_t; pub const pthread_rwlockattr_t = __darwin_pthread_rwlockattr_t; pub const pthread_t = __darwin_pthread_t; pub const pthread_key_t = __darwin_pthread_key_t; pub const fsblkcnt_t = __darwin_fsblkcnt_t; pub const fsfilcnt_t = __darwin_fsfilcnt_t; pub const int_least8_t = i8; pub const int_least16_t = i16; pub const int_least32_t = i32; pub const int_least64_t = i64; pub const uint_least8_t = u8; pub const uint_least16_t = u16; pub const uint_least32_t = u32; pub const uint_least64_t = u64; pub const int_fast8_t = i8; pub const int_fast16_t = i16; pub const int_fast32_t = i32; pub const int_fast64_t = i64; pub const uint_fast8_t = u8; pub const uint_fast16_t = u16; pub const uint_fast32_t = u32; pub const uint_fast64_t = u64; pub const intmax_t = c_long; pub const uintmax_t = c_ulong; pub const __darwin_nl_item = c_int; pub const __darwin_wctrans_t = c_int; pub const __darwin_wctype_t = __uint32_t; pub const va_list = __darwin_va_list; pub extern fn renameat(arg0: c_int, arg1: [*c]const u8, arg2: c_int, arg3: [*c]const u8) c_int; pub extern fn renamex_np(arg0: [*c]const u8, arg1: [*c]const u8, arg2: c_uint) c_int; pub extern fn renameatx_np(arg0: c_int, arg1: [*c]const u8, arg2: c_int, arg3: [*c]const u8, arg4: c_uint) c_int; pub const fpos_t = __darwin_off_t; pub const struct___sbuf = extern struct { _base: [*c]u8, _size: c_int, }; pub const struct___sFILEX = @OpaqueType(); pub const struct___sFILE = extern struct { _p: [*c]u8, _r: c_int, _w: c_int, _flags: c_short, _file: c_short, _bf: struct___sbuf, _lbfsize: c_int, _cookie: ?*c_void, _close: ?extern fn(?*c_void) c_int, _read: ?extern fn(?*c_void, [*c]u8, c_int) c_int, _seek: ?extern fn(?*c_void, fpos_t, c_int) fpos_t, _write: ?extern fn(?*c_void, [*c]const u8, c_int) c_int, _ub: struct___sbuf, _extra: ?*struct___sFILEX, _ur: c_int, _ubuf: [3]u8, _nbuf: [1]u8, _lb: struct___sbuf, _blksize: c_int, _offset: fpos_t, }; pub const FILE = struct___sFILE; pub extern var __stdinp: [*c]FILE; pub extern var __stdoutp: [*c]FILE; pub extern var __stderrp: [*c]FILE; pub extern fn clearerr(arg0: [*c]FILE) void; pub extern fn fclose(arg0: [*c]FILE) c_int; pub extern fn feof(arg0: [*c]FILE) c_int; pub extern fn ferror(arg0: [*c]FILE) c_int; pub extern fn fflush(arg0: [*c]FILE) c_int; pub extern fn fgetc(arg0: [*c]FILE) c_int; pub extern fn fgetpos(noalias arg0: [*c]FILE, arg1: [*c]fpos_t) c_int; pub extern fn fgets(noalias arg0: [*c]u8, arg1: c_int, arg2: [*c]FILE) [*c]u8; pub extern fn fopen(__filename: [*c]const u8, __mode: [*c]const u8) [*c]FILE; pub extern fn fprintf(arg0: [*c]FILE, arg1: [*c]const u8, ...) c_int; pub extern fn fputc(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn fputs(noalias arg0: [*c]const u8, noalias arg1: [*c]FILE) c_int; pub extern fn fread(__ptr: ?*c_void, __size: c_ulong, __nitems: c_ulong, __stream: [*c]FILE) c_ulong; pub extern fn freopen(noalias arg0: [*c]const u8, noalias arg1: [*c]const u8, noalias arg2: [*c]FILE) [*c]FILE; pub extern fn fscanf(noalias arg0: [*c]FILE, noalias arg1: [*c]const u8, ...) c_int; pub extern fn fseek(arg0: [*c]FILE, arg1: c_long, arg2: c_int) c_int; pub extern fn fsetpos(arg0: [*c]FILE, arg1: [*c]const fpos_t) c_int; pub extern fn ftell(arg0: [*c]FILE) c_long; pub extern fn fwrite(__ptr: ?*const c_void, __size: c_ulong, __nitems: c_ulong, __stream: [*c]FILE) c_ulong; pub extern fn getc(arg0: [*c]FILE) c_int; pub extern fn getchar() c_int; pub extern fn gets(arg0: [*c]u8) [*c]u8; pub extern fn perror(arg0: [*c]const u8) void; pub extern fn printf(arg0: [*c]const u8, ...) c_int; pub extern fn putc(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn putchar(arg0: c_int) c_int; pub extern fn puts(arg0: [*c]const u8) c_int; pub extern fn remove(arg0: [*c]const u8) c_int; pub extern fn rename(__old: [*c]const u8, __new: [*c]const u8) c_int; pub extern fn rewind(arg0: [*c]FILE) void; pub extern fn scanf(noalias arg0: [*c]const u8, ...) c_int; pub extern fn setbuf(noalias arg0: [*c]FILE, noalias arg1: [*c]u8) void; pub extern fn setvbuf(noalias arg0: [*c]FILE, noalias arg1: [*c]u8, arg2: c_int, arg3: usize) c_int; pub extern fn sprintf(arg0: [*c]u8, arg1: [*c]const u8, ...) c_int; pub extern fn sscanf(noalias arg0: [*c]const u8, noalias arg1: [*c]const u8, ...) c_int; pub extern fn tmpfile() [*c]FILE; pub extern fn tmpnam(arg0: [*c]u8) [*c]u8; pub extern fn ungetc(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn vfprintf(arg0: [*c]FILE, arg1: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn vprintf(arg0: [*c]const u8, arg1: [*c]struct___va_list_tag) c_int; pub extern fn vsprintf(arg0: [*c]u8, arg1: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn ctermid(arg0: [*c]u8) [*c]u8; pub extern fn fdopen(arg0: c_int, arg1: [*c]const u8) [*c]FILE; pub extern fn fileno(arg0: [*c]FILE) c_int; pub extern fn pclose(arg0: [*c]FILE) c_int; pub extern fn popen(arg0: [*c]const u8, arg1: [*c]const u8) [*c]FILE; pub extern fn __srget(arg0: [*c]FILE) c_int; pub extern fn __svfscanf(arg0: [*c]FILE, arg1: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn __swbuf(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn flockfile(arg0: [*c]FILE) void; pub extern fn ftrylockfile(arg0: [*c]FILE) c_int; pub extern fn funlockfile(arg0: [*c]FILE) void; pub extern fn getc_unlocked(arg0: [*c]FILE) c_int; pub extern fn getchar_unlocked() c_int; pub extern fn putc_unlocked(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn putchar_unlocked(arg0: c_int) c_int; pub extern fn getw(arg0: [*c]FILE) c_int; pub extern fn putw(arg0: c_int, arg1: [*c]FILE) c_int; pub extern fn tempnam(__dir: [*c]const u8, __prefix: [*c]const u8) [*c]u8; pub extern fn fseeko(__stream: [*c]FILE, __offset: off_t, __whence: c_int) c_int; pub extern fn ftello(__stream: [*c]FILE) off_t; pub extern fn snprintf(__str: [*c]u8, __size: c_ulong, __format: [*c]const u8, ...) c_int; pub extern fn vfscanf(noalias __stream: [*c]FILE, noalias __format: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn vscanf(noalias __format: [*c]const u8, arg1: [*c]struct___va_list_tag) c_int; pub extern fn vsnprintf(__str: [*c]u8, __size: c_ulong, __format: [*c]const u8, arg3: [*c]struct___va_list_tag) c_int; pub extern fn vsscanf(noalias __str: [*c]const u8, noalias __format: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn dprintf(arg0: c_int, noalias arg1: [*c]const u8, ...) c_int; pub extern fn vdprintf(arg0: c_int, noalias arg1: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn getdelim(noalias __linep: [*c]([*c]u8), noalias __linecapp: [*c]usize, __delimiter: c_int, noalias __stream: [*c]FILE) isize; pub extern fn getline(noalias __linep: [*c]([*c]u8), noalias __linecapp: [*c]usize, noalias __stream: [*c]FILE) isize; pub extern fn fmemopen(noalias __buf: ?*c_void, __size: usize, noalias __mode: [*c]const u8) [*c]FILE; pub extern fn open_memstream(__bufp: [*c]([*c]u8), __sizep: [*c]usize) [*c]FILE; pub extern const sys_nerr: c_int; pub extern const sys_errlist: [*c]const ([*c]const u8); pub extern fn asprintf(noalias arg0: [*c]([*c]u8), noalias arg1: [*c]const u8, ...) c_int; pub extern fn ctermid_r(arg0: [*c]u8) [*c]u8; pub extern fn fgetln(arg0: [*c]FILE, arg1: [*c]usize) [*c]u8; pub extern fn fmtcheck(arg0: [*c]const u8, arg1: [*c]const u8) [*c]const u8; pub extern fn fpurge(arg0: [*c]FILE) c_int; pub extern fn setbuffer(arg0: [*c]FILE, arg1: [*c]u8, arg2: c_int) void; pub extern fn setlinebuf(arg0: [*c]FILE) c_int; pub extern fn vasprintf(noalias arg0: [*c]([*c]u8), noalias arg1: [*c]const u8, arg2: [*c]struct___va_list_tag) c_int; pub extern fn zopen(arg0: [*c]const u8, arg1: [*c]const u8, arg2: c_int) [*c]FILE; pub extern fn funopen(arg0: ?*const c_void, arg1: ?extern fn(?*c_void, [*c]u8, c_int) c_int, arg2: ?extern fn(?*c_void, [*c]const u8, c_int) c_int, arg3: ?extern fn(?*c_void, fpos_t, c_int) fpos_t, arg4: ?extern fn(?*c_void) c_int) [*c]FILE; pub extern fn __sprintf_chk(noalias arg0: [*c]u8, arg1: c_int, arg2: usize, noalias arg3: [*c]const u8, ...) c_int; pub extern fn __snprintf_chk(noalias arg0: [*c]u8, arg1: usize, arg2: c_int, arg3: usize, noalias arg4: [*c]const u8, ...) c_int; pub extern fn __vsprintf_chk(noalias arg0: [*c]u8, arg1: c_int, arg2: usize, noalias arg3: [*c]const u8, arg4: [*c]struct___va_list_tag) c_int; pub extern fn __vsnprintf_chk(noalias arg0: [*c]u8, arg1: usize, arg2: c_int, arg3: usize, noalias arg4: [*c]const u8, arg5: [*c]struct___va_list_tag) c_int; pub const RedisModuleTimerID = u64; pub const mstime_t = c_longlong; pub const struct_RedisModuleCtx = @OpaqueType(); pub const RedisModuleCtx = struct_RedisModuleCtx; pub const struct_RedisModuleKey = @OpaqueType(); pub const RedisModuleKey = struct_RedisModuleKey; pub const struct_RedisModuleString = @OpaqueType(); pub const RedisModuleString = struct_RedisModuleString; pub const struct_RedisModuleCallReply = @OpaqueType(); pub const RedisModuleCallReply = struct_RedisModuleCallReply; pub const struct_RedisModuleIO = @OpaqueType(); pub const RedisModuleIO = struct_RedisModuleIO; pub const struct_RedisModuleType = @OpaqueType(); pub const RedisModuleType = struct_RedisModuleType; pub const struct_RedisModuleDigest = @OpaqueType(); pub const RedisModuleDigest = struct_RedisModuleDigest; pub const struct_RedisModuleBlockedClient = @OpaqueType(); pub const RedisModuleBlockedClient = struct_RedisModuleBlockedClient; pub const struct_RedisModuleClusterInfo = @OpaqueType(); pub const RedisModuleClusterInfo = struct_RedisModuleClusterInfo; pub const struct_RedisModuleDict = @OpaqueType(); pub const RedisModuleDict = struct_RedisModuleDict; pub const struct_RedisModuleDictIter = @OpaqueType(); pub const RedisModuleDictIter = struct_RedisModuleDictIter; pub const struct_RedisModuleCommandFilterCtx = @OpaqueType(); pub const RedisModuleCommandFilterCtx = struct_RedisModuleCommandFilterCtx; pub const struct_RedisModuleCommandFilter = @OpaqueType(); pub const RedisModuleCommandFilter = struct_RedisModuleCommandFilter; pub const RedisModuleCmdFunc = ?extern fn(*RedisModuleCtx, [*c](*RedisModuleString), c_int) c_int; pub const RedisModuleDisconnectFunc = ?extern fn(?*RedisModuleCtx, ?*RedisModuleBlockedClient) void; pub const RedisModuleNotificationFunc = ?extern fn(?*RedisModuleCtx, c_int, [*c]const u8, ?*RedisModuleString) c_int; pub const RedisModuleTypeLoadFunc = ?extern fn(?*RedisModuleIO, c_int) ?*c_void; pub const RedisModuleTypeSaveFunc = ?extern fn(?*RedisModuleIO, ?*c_void) void; pub const RedisModuleTypeRewriteFunc = ?extern fn(?*RedisModuleIO, ?*RedisModuleString, ?*c_void) void; pub const RedisModuleTypeMemUsageFunc = ?extern fn(?*const c_void) usize; pub const RedisModuleTypeDigestFunc = ?extern fn(?*RedisModuleDigest, ?*c_void) void; pub const RedisModuleTypeFreeFunc = ?extern fn(?*c_void) void; pub const RedisModuleClusterMessageReceiver = ?extern fn(?*RedisModuleCtx, [*c]const u8, u8, [*c]const u8, u32) void; pub const RedisModuleTimerProc = ?extern fn(?*RedisModuleCtx, ?*c_void) void; pub const RedisModuleCommandFilterFunc = ?extern fn(?*RedisModuleCommandFilterCtx) void; pub const struct_RedisModuleTypeMethods = extern struct { version: u64, rdb_load: RedisModuleTypeLoadFunc, rdb_save: RedisModuleTypeSaveFunc, aof_rewrite: RedisModuleTypeRewriteFunc, mem_usage: RedisModuleTypeMemUsageFunc, digest: RedisModuleTypeDigestFunc, free: RedisModuleTypeFreeFunc, }; pub const RedisModuleTypeMethods = struct_RedisModuleTypeMethods; pub var RedisModule_Alloc: extern fn(usize) ?*c_void = undefined; pub var RedisModule_Realloc: extern fn(?*c_void, usize) ?*c_void = undefined; pub var RedisModule_Free: extern fn(?*c_void) void = undefined; pub var RedisModule_Calloc: extern fn(usize, usize) ?*c_void = undefined; pub var RedisModule_Strdup: extern fn([*c]const u8) [*c]u8 = undefined; pub var RedisModule_GetApi: ?extern fn([*c]const u8, ?*c_void) c_int = undefined; pub var RedisModule_CreateCommand: extern fn(?*RedisModuleCtx, [*c]const u8, RedisModuleCmdFunc, [*c]const u8, c_int, c_int, c_int) c_int = undefined; pub var RedisModule_SetModuleAttribs: ?extern fn(?*RedisModuleCtx, [*c]const u8, c_int, c_int) void = undefined; pub var RedisModule_IsModuleNameBusy: ?extern fn([*c]const u8) c_int = undefined; pub var RedisModule_WrongArity: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_ReplyWithLongLong: extern fn(?*RedisModuleCtx, c_longlong) c_int = undefined; pub var RedisModule_GetSelectedDb: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_SelectDb: extern fn(?*RedisModuleCtx, c_int) c_int = undefined; pub var RedisModule_OpenKey: extern fn(?*RedisModuleCtx, ?*RedisModuleString, c_int) ?*c_void = undefined; pub var RedisModule_CloseKey: extern fn(?*RedisModuleKey) void = undefined; pub var RedisModule_KeyType: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_ValueLength: extern fn(?*RedisModuleKey) usize = undefined; pub var RedisModule_ListPush: extern fn(?*RedisModuleKey, c_int, ?*RedisModuleString) c_int = undefined; pub var RedisModule_ListPop: extern fn(?*RedisModuleKey, c_int) ?*RedisModuleString = undefined; pub var RedisModule_Call: extern fn(?*RedisModuleCtx, [*c]const u8, [*c]const u8, ...) ?*RedisModuleCallReply = undefined; pub var RedisModule_CallReplyProto: extern fn(?*RedisModuleCallReply, [*c]usize) [*c]const u8 = undefined; pub var RedisModule_FreeCallReply: extern fn(?*RedisModuleCallReply) void = undefined; pub var RedisModule_CallReplyType: extern fn(?*RedisModuleCallReply) c_int = undefined; pub var RedisModule_CallReplyInteger: extern fn(?*RedisModuleCallReply) c_longlong = undefined; pub var RedisModule_CallReplyLength: extern fn(?*RedisModuleCallReply) usize = undefined; pub var RedisModule_CallReplyArrayElement: extern fn(?*RedisModuleCallReply, usize) ?*RedisModuleCallReply = undefined; pub var RedisModule_CreateString: extern fn(?*RedisModuleCtx, [*c]const u8, usize) ?*RedisModuleString = undefined; pub var RedisModule_CreateStringFromLongLong: extern fn(?*RedisModuleCtx, c_longlong) ?*RedisModuleString = undefined; pub var RedisModule_CreateStringFromString: extern fn(?*RedisModuleCtx, ?*const RedisModuleString) ?*RedisModuleString = undefined; pub var RedisModule_CreateStringPrintf: extern fn(?*RedisModuleCtx, [*c]const u8, ...) ?*RedisModuleString = undefined; pub var RedisModule_FreeString: extern fn(?*RedisModuleCtx, ?*RedisModuleString) void = undefined; pub var RedisModule_StringPtrLen: extern fn(?*const RedisModuleString, [*c]usize) [*c]const u8 = undefined; pub var RedisModule_ReplyWithError: extern fn(?*RedisModuleCtx, [*c]const u8) c_int = undefined; pub var RedisModule_ReplyWithSimpleString: extern fn(?*RedisModuleCtx, [*c]const u8) c_int = undefined; pub var RedisModule_ReplyWithArray: extern fn(?*RedisModuleCtx, c_long) c_int = undefined; pub var RedisModule_ReplySetArrayLength: extern fn(?*RedisModuleCtx, c_long) void = undefined; pub var RedisModule_ReplyWithStringBuffer: extern fn(?*RedisModuleCtx, [*c]const u8, usize) c_int = undefined; pub var RedisModule_ReplyWithString: extern fn(?*RedisModuleCtx, ?*RedisModuleString) c_int = undefined; pub var RedisModule_ReplyWithNull: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_ReplyWithDouble: extern fn(?*RedisModuleCtx, f64) c_int = undefined; pub var RedisModule_ReplyWithCallReply: extern fn(?*RedisModuleCtx, ?*RedisModuleCallReply) c_int = undefined; pub var RedisModule_StringToLongLong: extern fn(?*const RedisModuleString, [*c]c_longlong) c_int = undefined; pub var RedisModule_StringToDouble: extern fn(?*const RedisModuleString, [*c]f64) c_int = undefined; pub var RedisModule_AutoMemory: extern fn(?*RedisModuleCtx) void = undefined; pub var RedisModule_Replicate: extern fn(?*RedisModuleCtx, [*c]const u8, [*c]const u8, ...) c_int = undefined; pub var RedisModule_ReplicateVerbatim: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_CallReplyStringPtr: extern fn(?*RedisModuleCallReply, [*c]usize) [*c]const u8 = undefined; pub var RedisModule_CreateStringFromCallReply: extern fn(?*RedisModuleCallReply) ?*RedisModuleString = undefined; pub var RedisModule_DeleteKey: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_UnlinkKey: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_StringSet: extern fn(?*RedisModuleKey, ?*RedisModuleString) c_int = undefined; pub var RedisModule_StringDMA: extern fn(?*RedisModuleKey, [*c]usize, c_int) [*c]u8 = undefined; pub var RedisModule_StringTruncate: extern fn(?*RedisModuleKey, usize) c_int = undefined; pub var RedisModule_GetExpire: extern fn(?*RedisModuleKey) mstime_t = undefined; pub var RedisModule_SetExpire: extern fn(?*RedisModuleKey, mstime_t) c_int = undefined; pub var RedisModule_ZsetAdd: extern fn(?*RedisModuleKey, f64, ?*RedisModuleString, [*c]c_int) c_int = undefined; pub var RedisModule_ZsetIncrby: extern fn(?*RedisModuleKey, f64, ?*RedisModuleString, [*c]c_int, [*c]f64) c_int = undefined; pub var RedisModule_ZsetScore: extern fn(?*RedisModuleKey, ?*RedisModuleString, [*c]f64) c_int = undefined; pub var RedisModule_ZsetRem: extern fn(?*RedisModuleKey, ?*RedisModuleString, [*c]c_int) c_int = undefined; pub var RedisModule_ZsetRangeStop: extern fn(?*RedisModuleKey) void = undefined; pub var RedisModule_ZsetFirstInScoreRange: extern fn(?*RedisModuleKey, f64, f64, c_int, c_int) c_int = undefined; pub var RedisModule_ZsetLastInScoreRange: extern fn(?*RedisModuleKey, f64, f64, c_int, c_int) c_int = undefined; pub var RedisModule_ZsetFirstInLexRange: extern fn(?*RedisModuleKey, ?*RedisModuleString, ?*RedisModuleString) c_int = undefined; pub var RedisModule_ZsetLastInLexRange: extern fn(?*RedisModuleKey, ?*RedisModuleString, ?*RedisModuleString) c_int = undefined; pub var RedisModule_ZsetRangeCurrentElement: extern fn(?*RedisModuleKey, [*c]f64) ?*RedisModuleString = undefined; pub var RedisModule_ZsetRangeNext: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_ZsetRangePrev: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_ZsetRangeEndReached: extern fn(?*RedisModuleKey) c_int = undefined; pub var RedisModule_HashSet: extern fn(?*RedisModuleKey, c_int, ...) c_int = undefined; pub var RedisModule_HashGet: extern fn(?*RedisModuleKey, c_int, ...) c_int = undefined; pub var RedisModule_IsKeysPositionRequest: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_KeyAtPos: extern fn(?*RedisModuleCtx, c_int) void = undefined; pub var RedisModule_GetClientId: extern fn(?*RedisModuleCtx) c_ulonglong = undefined; pub var RedisModule_GetContextFlags: extern fn(?*RedisModuleCtx) c_int = undefined; pub var RedisModule_PoolAlloc: extern fn(?*RedisModuleCtx, usize) ?*c_void = undefined; pub var RedisModule_CreateDataType: extern fn(?*RedisModuleCtx, [*c]const u8, c_int, [*c]RedisModuleTypeMethods) ?*RedisModuleType = undefined; pub var RedisModule_ModuleTypeSetValue: extern fn(?*RedisModuleKey, ?*RedisModuleType, ?*c_void) c_int = undefined; pub var RedisModule_ModuleTypeGetType: extern fn(?*RedisModuleKey) ?*RedisModuleType = undefined; pub var RedisModule_ModuleTypeGetValue: extern fn(?*RedisModuleKey) ?*c_void = undefined; pub var RedisModule_SaveUnsigned: extern fn(?*RedisModuleIO, u64) void = undefined; pub var RedisModule_LoadUnsigned: extern fn(?*RedisModuleIO) u64 = undefined; pub var RedisModule_SaveSigned: extern fn(?*RedisModuleIO, i64) void = undefined; pub var RedisModule_LoadSigned: extern fn(?*RedisModuleIO) i64 = undefined; pub var RedisModule_EmitAOF: extern fn(?*RedisModuleIO, [*c]const u8, [*c]const u8, ...) void = undefined; pub var RedisModule_SaveString: extern fn(?*RedisModuleIO, ?*RedisModuleString) void = undefined; pub var RedisModule_SaveStringBuffer: extern fn(?*RedisModuleIO, [*c]const u8, usize) void = undefined; pub var RedisModule_LoadString: extern fn(?*RedisModuleIO) ?*RedisModuleString = undefined; pub var RedisModule_LoadStringBuffer: extern fn(?*RedisModuleIO, [*c]usize) [*c]u8 = undefined; pub var RedisModule_SaveDouble: extern fn(?*RedisModuleIO, f64) void = undefined; pub var RedisModule_LoadDouble: extern fn(?*RedisModuleIO) f64 = undefined; pub var RedisModule_SaveFloat: extern fn(?*RedisModuleIO, f32) void = undefined; pub var RedisModule_LoadFloat: extern fn(?*RedisModuleIO) f32 = undefined; pub var RedisModule_Log: extern fn(?*RedisModuleCtx, [*c]const u8, [*c]const u8, ...) void = undefined; pub var RedisModule_LogIOError: extern fn(?*RedisModuleIO, [*c]const u8, [*c]const u8, ...) void = undefined; pub var RedisModule_StringAppendBuffer: extern fn(?*RedisModuleCtx, ?*RedisModuleString, [*c]const u8, usize) c_int = undefined; pub var RedisModule_RetainString: extern fn(?*RedisModuleCtx, ?*RedisModuleString) void = undefined; pub var RedisModule_StringCompare: extern fn(?*RedisModuleString, ?*RedisModuleString) c_int = undefined; pub var RedisModule_GetContextFromIO: extern fn(?*RedisModuleIO) ?*RedisModuleCtx = undefined; pub var RedisModule_GetKeyNameFromIO: extern fn(?*RedisModuleIO) ?*const RedisModuleString = undefined; pub var RedisModule_Milliseconds: extern fn() c_longlong = undefined; pub var RedisModule_DigestAddStringBuffer: extern fn(?*RedisModuleDigest, [*c]u8, usize) void = undefined; pub var RedisModule_DigestAddLongLong: extern fn(?*RedisModuleDigest, c_longlong) void = undefined; pub var RedisModule_DigestEndSequence: extern fn(?*RedisModuleDigest) void = undefined; pub var RedisModule_CreateDict: extern fn(?*RedisModuleCtx) ?*RedisModuleDict = undefined; pub var RedisModule_FreeDict: extern fn(?*RedisModuleCtx, ?*RedisModuleDict) void = undefined; pub var RedisModule_DictSize: extern fn(?*RedisModuleDict) u64 = undefined; pub var RedisModule_DictSetC: extern fn(?*RedisModuleDict, ?*c_void, usize, ?*c_void) c_int = undefined; pub var RedisModule_DictReplaceC: extern fn(?*RedisModuleDict, ?*c_void, usize, ?*c_void) c_int = undefined; pub var RedisModule_DictSet: extern fn(?*RedisModuleDict, ?*RedisModuleString, ?*c_void) c_int = undefined; pub var RedisModule_DictReplace: extern fn(?*RedisModuleDict, ?*RedisModuleString, ?*c_void) c_int = undefined; pub var RedisModule_DictGetC: extern fn(?*RedisModuleDict, ?*c_void, usize, [*c]c_int) ?*c_void = undefined; pub var RedisModule_DictGet: extern fn(?*RedisModuleDict, ?*RedisModuleString, [*c]c_int) ?*c_void = undefined; pub var RedisModule_DictDelC: extern fn(?*RedisModuleDict, ?*c_void, usize, ?*c_void) c_int = undefined; pub var RedisModule_DictDel: extern fn(?*RedisModuleDict, ?*RedisModuleString, ?*c_void) c_int = undefined; pub var RedisModule_DictIteratorStartC: extern fn(?*RedisModuleDict, [*c]const u8, ?*c_void, usize) ?*RedisModuleDictIter = undefined; pub var RedisModule_DictIteratorStart: extern fn(?*RedisModuleDict, [*c]const u8, ?*RedisModuleString) ?*RedisModuleDictIter = undefined; pub var RedisModule_DictIteratorStop: extern fn(?*RedisModuleDictIter) void = undefined; pub var RedisModule_DictIteratorReseekC: extern fn(?*RedisModuleDictIter, [*c]const u8, ?*c_void, usize) c_int = undefined; pub var RedisModule_DictIteratorReseek: extern fn(?*RedisModuleDictIter, [*c]const u8, ?*RedisModuleString) c_int = undefined; pub var RedisModule_DictNextC: extern fn(?*RedisModuleDictIter, [*c]usize, [*c](?*c_void)) ?*c_void = undefined; pub var RedisModule_DictPrevC: extern fn(?*RedisModuleDictIter, [*c]usize, [*c](?*c_void)) ?*c_void = undefined; pub var RedisModule_DictNext: extern fn(?*RedisModuleCtx, ?*RedisModuleDictIter, [*c](?*c_void)) ?*RedisModuleString = undefined; pub var RedisModule_DictPrev: extern fn(?*RedisModuleCtx, ?*RedisModuleDictIter, [*c](?*c_void)) ?*RedisModuleString = undefined; pub var RedisModule_DictCompareC: extern fn(?*RedisModuleDictIter, [*c]const u8, ?*c_void, usize) c_int = undefined; pub var RedisModule_DictCompare: extern fn(?*RedisModuleDictIter, [*c]const u8, ?*RedisModuleString) c_int = undefined; pub fn RedisModule_Init(ctx: ?*RedisModuleCtx, name: [*c]const u8, ver: c_int, apiver: c_int) c_int { var getapifuncptr: ?*c_void = @ptrCast([*c](?*c_void), @alignCast(8, ctx))[0]; RedisModule_GetApi = @ptrCast(?extern fn([*c]const u8, ?*c_void) c_int, getapifuncptr); _ = RedisModule_GetApi.?(c"RedisModule_Alloc", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Alloc))); _ = RedisModule_GetApi.?(c"RedisModule_Calloc", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Calloc))); _ = RedisModule_GetApi.?(c"RedisModule_Free", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Free))); _ = RedisModule_GetApi.?(c"RedisModule_Realloc", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Realloc))); _ = RedisModule_GetApi.?(c"RedisModule_Strdup", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Strdup))); _ = RedisModule_GetApi.?(c"RedisModule_CreateCommand", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateCommand))); _ = RedisModule_GetApi.?(c"RedisModule_SetModuleAttribs", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SetModuleAttribs))); _ = RedisModule_GetApi.?(c"RedisModule_IsModuleNameBusy", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_IsModuleNameBusy))); _ = RedisModule_GetApi.?(c"RedisModule_WrongArity", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_WrongArity))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithLongLong", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithLongLong))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithError", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithError))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithSimpleString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithSimpleString))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithArray", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithArray))); _ = RedisModule_GetApi.?(c"RedisModule_ReplySetArrayLength", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplySetArrayLength))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithStringBuffer", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithStringBuffer))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithString))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithNull", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithNull))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithCallReply", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithCallReply))); _ = RedisModule_GetApi.?(c"RedisModule_ReplyWithDouble", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplyWithDouble))); _ = RedisModule_GetApi.?(c"RedisModule_ReplySetArrayLength", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplySetArrayLength))); _ = RedisModule_GetApi.?(c"RedisModule_GetSelectedDb", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetSelectedDb))); _ = RedisModule_GetApi.?(c"RedisModule_SelectDb", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SelectDb))); _ = RedisModule_GetApi.?(c"RedisModule_OpenKey", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_OpenKey))); _ = RedisModule_GetApi.?(c"RedisModule_CloseKey", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CloseKey))); _ = RedisModule_GetApi.?(c"RedisModule_KeyType", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_KeyType))); _ = RedisModule_GetApi.?(c"RedisModule_ValueLength", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ValueLength))); _ = RedisModule_GetApi.?(c"RedisModule_ListPush", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ListPush))); _ = RedisModule_GetApi.?(c"RedisModule_ListPop", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ListPop))); _ = RedisModule_GetApi.?(c"RedisModule_StringToLongLong", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringToLongLong))); _ = RedisModule_GetApi.?(c"RedisModule_StringToDouble", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringToDouble))); _ = RedisModule_GetApi.?(c"RedisModule_Call", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Call))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyProto", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyProto))); _ = RedisModule_GetApi.?(c"RedisModule_FreeCallReply", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_FreeCallReply))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyInteger", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyInteger))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyType", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyType))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyLength", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyLength))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyArrayElement", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyArrayElement))); _ = RedisModule_GetApi.?(c"RedisModule_CallReplyStringPtr", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CallReplyStringPtr))); _ = RedisModule_GetApi.?(c"RedisModule_CreateStringFromCallReply", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateStringFromCallReply))); _ = RedisModule_GetApi.?(c"RedisModule_CreateString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateString))); _ = RedisModule_GetApi.?(c"RedisModule_CreateStringFromLongLong", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateStringFromLongLong))); _ = RedisModule_GetApi.?(c"RedisModule_CreateStringFromString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateStringFromString))); _ = RedisModule_GetApi.?(c"RedisModule_CreateStringPrintf", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateStringPrintf))); _ = RedisModule_GetApi.?(c"RedisModule_FreeString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_FreeString))); _ = RedisModule_GetApi.?(c"RedisModule_StringPtrLen", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringPtrLen))); _ = RedisModule_GetApi.?(c"RedisModule_AutoMemory", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_AutoMemory))); _ = RedisModule_GetApi.?(c"RedisModule_Replicate", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Replicate))); _ = RedisModule_GetApi.?(c"RedisModule_ReplicateVerbatim", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ReplicateVerbatim))); _ = RedisModule_GetApi.?(c"RedisModule_DeleteKey", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DeleteKey))); _ = RedisModule_GetApi.?(c"RedisModule_UnlinkKey", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_UnlinkKey))); _ = RedisModule_GetApi.?(c"RedisModule_StringSet", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringSet))); _ = RedisModule_GetApi.?(c"RedisModule_StringDMA", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringDMA))); _ = RedisModule_GetApi.?(c"RedisModule_StringTruncate", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringTruncate))); _ = RedisModule_GetApi.?(c"RedisModule_GetExpire", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetExpire))); _ = RedisModule_GetApi.?(c"RedisModule_SetExpire", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SetExpire))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetAdd", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetAdd))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetIncrby", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetIncrby))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetScore", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetScore))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRem", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRem))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRangeStop", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRangeStop))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetFirstInScoreRange", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetFirstInScoreRange))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetLastInScoreRange", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetLastInScoreRange))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetFirstInLexRange", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetFirstInLexRange))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetLastInLexRange", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetLastInLexRange))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRangeCurrentElement", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRangeCurrentElement))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRangeNext", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRangeNext))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRangePrev", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRangePrev))); _ = RedisModule_GetApi.?(c"RedisModule_ZsetRangeEndReached", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ZsetRangeEndReached))); _ = RedisModule_GetApi.?(c"RedisModule_HashSet", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_HashSet))); _ = RedisModule_GetApi.?(c"RedisModule_HashGet", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_HashGet))); _ = RedisModule_GetApi.?(c"RedisModule_IsKeysPositionRequest", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_IsKeysPositionRequest))); _ = RedisModule_GetApi.?(c"RedisModule_KeyAtPos", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_KeyAtPos))); _ = RedisModule_GetApi.?(c"RedisModule_GetClientId", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetClientId))); _ = RedisModule_GetApi.?(c"RedisModule_GetContextFlags", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetContextFlags))); _ = RedisModule_GetApi.?(c"RedisModule_PoolAlloc", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_PoolAlloc))); _ = RedisModule_GetApi.?(c"RedisModule_CreateDataType", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateDataType))); _ = RedisModule_GetApi.?(c"RedisModule_ModuleTypeSetValue", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ModuleTypeSetValue))); _ = RedisModule_GetApi.?(c"RedisModule_ModuleTypeGetType", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ModuleTypeGetType))); _ = RedisModule_GetApi.?(c"RedisModule_ModuleTypeGetValue", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_ModuleTypeGetValue))); _ = RedisModule_GetApi.?(c"RedisModule_SaveUnsigned", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveUnsigned))); _ = RedisModule_GetApi.?(c"RedisModule_LoadUnsigned", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadUnsigned))); _ = RedisModule_GetApi.?(c"RedisModule_SaveSigned", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveSigned))); _ = RedisModule_GetApi.?(c"RedisModule_LoadSigned", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadSigned))); _ = RedisModule_GetApi.?(c"RedisModule_SaveString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveString))); _ = RedisModule_GetApi.?(c"RedisModule_SaveStringBuffer", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveStringBuffer))); _ = RedisModule_GetApi.?(c"RedisModule_LoadString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadString))); _ = RedisModule_GetApi.?(c"RedisModule_LoadStringBuffer", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadStringBuffer))); _ = RedisModule_GetApi.?(c"RedisModule_SaveDouble", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveDouble))); _ = RedisModule_GetApi.?(c"RedisModule_LoadDouble", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadDouble))); _ = RedisModule_GetApi.?(c"RedisModule_SaveFloat", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_SaveFloat))); _ = RedisModule_GetApi.?(c"RedisModule_LoadFloat", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LoadFloat))); _ = RedisModule_GetApi.?(c"RedisModule_EmitAOF", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_EmitAOF))); _ = RedisModule_GetApi.?(c"RedisModule_Log", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Log))); _ = RedisModule_GetApi.?(c"RedisModule_LogIOError", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_LogIOError))); _ = RedisModule_GetApi.?(c"RedisModule_StringAppendBuffer", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringAppendBuffer))); _ = RedisModule_GetApi.?(c"RedisModule_RetainString", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_RetainString))); _ = RedisModule_GetApi.?(c"RedisModule_StringCompare", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_StringCompare))); _ = RedisModule_GetApi.?(c"RedisModule_GetContextFromIO", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetContextFromIO))); _ = RedisModule_GetApi.?(c"RedisModule_GetKeyNameFromIO", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_GetKeyNameFromIO))); _ = RedisModule_GetApi.?(c"RedisModule_Milliseconds", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_Milliseconds))); _ = RedisModule_GetApi.?(c"RedisModule_DigestAddStringBuffer", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DigestAddStringBuffer))); _ = RedisModule_GetApi.?(c"RedisModule_DigestAddLongLong", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DigestAddLongLong))); _ = RedisModule_GetApi.?(c"RedisModule_DigestEndSequence", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DigestEndSequence))); _ = RedisModule_GetApi.?(c"RedisModule_CreateDict", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_CreateDict))); _ = RedisModule_GetApi.?(c"RedisModule_FreeDict", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_FreeDict))); _ = RedisModule_GetApi.?(c"RedisModule_DictSize", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictSize))); _ = RedisModule_GetApi.?(c"RedisModule_DictSetC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictSetC))); _ = RedisModule_GetApi.?(c"RedisModule_DictReplaceC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictReplaceC))); _ = RedisModule_GetApi.?(c"RedisModule_DictSet", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictSet))); _ = RedisModule_GetApi.?(c"RedisModule_DictReplace", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictReplace))); _ = RedisModule_GetApi.?(c"RedisModule_DictGetC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictGetC))); _ = RedisModule_GetApi.?(c"RedisModule_DictGet", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictGet))); _ = RedisModule_GetApi.?(c"RedisModule_DictDelC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictDelC))); _ = RedisModule_GetApi.?(c"RedisModule_DictDel", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictDel))); _ = RedisModule_GetApi.?(c"RedisModule_DictIteratorStartC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictIteratorStartC))); _ = RedisModule_GetApi.?(c"RedisModule_DictIteratorStart", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictIteratorStart))); _ = RedisModule_GetApi.?(c"RedisModule_DictIteratorStop", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictIteratorStop))); _ = RedisModule_GetApi.?(c"RedisModule_DictIteratorReseekC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictIteratorReseekC))); _ = RedisModule_GetApi.?(c"RedisModule_DictIteratorReseek", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictIteratorReseek))); _ = RedisModule_GetApi.?(c"RedisModule_DictNextC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictNextC))); _ = RedisModule_GetApi.?(c"RedisModule_DictPrevC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictPrevC))); _ = RedisModule_GetApi.?(c"RedisModule_DictNext", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictNext))); _ = RedisModule_GetApi.?(c"RedisModule_DictPrev", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictPrev))); _ = RedisModule_GetApi.?(c"RedisModule_DictCompare", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictCompare))); _ = RedisModule_GetApi.?(c"RedisModule_DictCompareC", @ptrCast(?*c_void, @ptrCast([*c](?*c_void), &RedisModule_DictCompareC))); if ((@ptrToInt(RedisModule_IsModuleNameBusy) != 0) and (RedisModule_IsModuleNameBusy.?(name) != 0)) return 1; RedisModule_SetModuleAttribs.?(ctx, name, ver, apiver); return 0; } pub const __IPHONE_5_1 = 50100; pub const __BIGGEST_ALIGNMENT__ = 16; pub const __DARWIN_WCHAR_MAX = __WCHAR_MAX__; pub const __INT64_FMTd__ = c"lld"; pub const __STDC_VERSION__ = c_long(201112); pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_8_2 = x; pub const __INT_LEAST8_FMTi__ = c"hhi"; pub const __LZCNT__ = 1; pub const __INVPCID__ = 1; pub const INT_FAST64_MIN = INT64_MIN; pub const __GCC_ATOMIC_LLONG_LOCK_FREE = 2; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_12_1 = x; pub const __clang_version__ = c"8.0.0 (tags/RELEASE_800/final)"; pub const __UINT_LEAST8_FMTo__ = c"hho"; pub const __INTMAX_FMTd__ = c"ld"; pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = 2; pub const __INT_LEAST16_FMTi__ = c"hi"; pub const REDISMODULE_KEYTYPE_EMPTY = 0; pub const UINTMAX_MAX = UINT64_MAX; pub const __FMA__ = 1; pub const INT_LEAST64_MAX = INT64_MAX; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_2_0 = x; pub const WINT_MIN = INT32_MIN; pub const __IPHONE_11_2 = 110200; pub const __MMX__ = 1; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = 1; pub const NBBY = __DARWIN_NBBY; pub const INTPTR_MAX = c_long(9223372036854775807); pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_11_3 = x; pub const INTMAX_MIN = INT64_MIN; pub const __RDSEED__ = 1; pub const __DARWIN_SUF_1050 = c"$1050"; pub const REDISMODULE_TYPE_METHOD_VERSION = 1; pub const __WCHAR_WIDTH__ = 32; pub const __FSGSBASE__ = 1; pub const __PTRDIFF_FMTd__ = c"ld"; pub const __FLT_EVAL_METHOD__ = 0; pub const __SSE_MATH__ = 1; pub const __TVOS_11_1 = 110100; pub const INT64_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-INT64_MAX, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-INT64_MAX, -1) else (-INT64_MAX)(-1); pub const __UINT_FAST8_FMTo__ = c"hho"; pub const __WATCHOS_4_3 = 40300; pub const __WATCHOS_3_2 = 30200; pub const __UINT_LEAST64_MAX__ = c_ulonglong(18446744073709551615); pub const __UINT_LEAST64_FMTx__ = c"llx"; pub const __INT8_MAX__ = 127; pub const __DBL_DECIMAL_DIG__ = 17; pub const __SSSE3__ = 1; pub const __IPHONE_4_1 = 40100; pub const __CONSTANT_CFSTRINGS__ = 1; pub const __IPHONE_6_0 = 60000; pub const __LDBL_MAX_EXP__ = 16384; pub const __MAC_10_13_1 = 101301; pub const __NO_MATH_INLINES = 1; pub const __WCHAR_TYPE__ = int; pub const __LONG_MAX__ = c_long(9223372036854775807); pub const __PTHREAD_RWLOCKATTR_SIZE__ = 16; pub const __pic__ = 2; pub const __PTRDIFF_WIDTH__ = 64; pub const __INT_FAST16_FMTi__ = c"hi"; pub const __LDBL_DENORM_MIN__ = 0.000000; pub const __MAC_10_13_4 = 101304; pub const _IOFBF = 0; pub const __INT64_C_SUFFIX__ = LL; pub const __SIGN = 32768; pub const REDISMODULE_KEYTYPE_HASH = 3; pub const __IPHONE_10_1 = 100100; pub const __SAPP = 256; pub const __SIZEOF_PTRDIFF_T__ = 8; pub const __SIG_ATOMIC_MAX__ = 2147483647; pub const __UINT64_MAX__ = c_ulonglong(18446744073709551615); pub const __FLT_DECIMAL_DIG__ = 9; pub const RENAME_EXCL = 4; pub const __DBL_DIG__ = 15; pub const __ATOMIC_ACQUIRE = 2; pub const __FLT16_HAS_DENORM__ = 1; pub const __UINT_FAST16_FMTu__ = c"hu"; pub const __INTPTR_FMTi__ = c"li"; pub const __UINT_FAST8_FMTX__ = c"hhX"; pub const __PTHREAD_ONCE_SIZE__ = 8; pub const __DARWIN_PDP_ENDIAN = 3412; pub const __const = @"const"; pub const __UINT8_FMTo__ = c"hho"; pub const UINT_LEAST64_MAX = UINT64_MAX; pub const __UINT_LEAST16_FMTx__ = c"hx"; pub const __UINT_FAST16_FMTX__ = c"hX"; pub const __SALC = 16384; pub const __UINT_FAST32_FMTx__ = c"x"; pub const __VERSION__ = c"4.2.1 Compatible Clang 8.0.0 (tags/RELEASE_800/final)"; pub const __UINT_FAST8_FMTu__ = c"hhu"; pub const __UINT_LEAST64_FMTo__ = c"llo"; pub const __MAC_10_10_2 = 101002; pub const __UINT_LEAST8_MAX__ = 255; pub const UINT8_MAX = 255; pub const __PTHREAD_MUTEXATTR_SIZE__ = 8; pub const __RDRND__ = 1; pub const __MOVBE__ = 1; pub const __FBSDID = s; pub const __PTHREAD_MUTEX_SIZE__ = 56; pub const __UINT16_MAX__ = 65535; pub const __x86_64 = 1; pub const __SIZEOF_WINT_T__ = 4; pub const __UINTMAX_FMTo__ = c"lo"; pub const __UINT_LEAST8_FMTX__ = c"hhX"; pub const SIG_ATOMIC_MAX = INT32_MAX; pub const __F16C__ = 1; pub const __WATCHOS_5_2 = 50200; pub const __POINTER_WIDTH__ = 64; pub const PTRDIFF_MIN = INT64_MIN; pub const __PTRDIFF_MAX__ = c_long(9223372036854775807); pub const __tune_corei7__ = 1; pub const __FLT16_DIG__ = 3; pub const __SIZEOF_LONG__ = 8; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_5_1 = x; pub const __IPHONE_8_1 = 80100; pub const __MAC_10_2 = 1020; pub const __NO_INLINE__ = 1; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_9_2 = x; pub const __PTHREAD_ATTR_SIZE__ = 56; pub const __header_inline = @"inline"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_3_0 = x; pub const __INT_FAST32_MAX__ = 2147483647; pub const REDISMODULE_KEYTYPE_LIST = 2; pub const __UINTMAX_FMTu__ = c"lu"; pub const __DARWIN_LITTLE_ENDIAN = 1234; pub const INT_FAST8_MAX = INT8_MAX; pub const __FLT_RADIX__ = 2; pub const __MAC_10_7 = 1070; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_8_4 = x; pub const __IPHONE_9_2 = 90200; pub const _DARWIN_FEATURE_ONLY_UNIX_CONFORMANCE = 1; pub const __SGX__ = 1; pub const REDISMODULE_LIST_HEAD = 0; pub const __FLT16_DECIMAL_DIG__ = 5; pub const __PRAGMA_REDEFINE_EXTNAME = 1; pub const FOPEN_MAX = 20; pub const __IPHONE_2_2 = 20200; pub const __IPHONE_5_0 = 50000; pub const __UINTMAX_WIDTH__ = 64; pub const __INT64_FMTi__ = c"lli"; pub const __UINT_FAST64_FMTu__ = c"llu"; pub const INT_LEAST16_MIN = INT16_MIN; pub const __INT_FAST16_TYPE__ = short; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_8_3 = x; pub const __IPHONE_3_1 = 30100; pub const __SLBF = 1; pub const __DBL_MAX_10_EXP__ = 308; pub const __LDBL_MIN__ = 0.000000; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_12_0 = x; pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = 2; pub const __PIC__ = 2; pub const __TVOS_10_2 = 100200; pub const REDISMODULE_KEYTYPE_SET = 4; pub const __LDBL_DECIMAL_DIG__ = 21; pub const REDISMODULE_REPLY_STRING = 0; pub const __UINT_LEAST64_FMTX__ = c"llX"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_2_1 = x; pub const __IPHONE_11_3 = 110300; pub const __clang_minor__ = 0; pub const __DARWIN_FD_SETSIZE = 1024; pub const REDISMODULE_LIST_TAIL = 1; pub const INTMAX_MAX = INT64_MAX; pub const REDISMODULE_REPLY_NULL = 4; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_11_0 = x; pub const __MAC_10_12_4 = 101204; pub const __BLOCKS__ = 1; pub const __UINT_FAST64_FMTo__ = c"llo"; pub const INT_FAST16_MIN = INT16_MIN; pub const __DBL_MAX__ = 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_10_3 = x; pub const __UINT64_FMTx__ = c"llx"; pub const P_tmpdir = c"/var/tmp/"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_4_2 = x; pub const __TVOS_11_0 = 110000; pub const __SWR = 8; pub const stderr = __stderrp; pub const __WATCHOS_3_1 = 30100; pub const SEEK_END = 2; pub const _DEBUG = 1; pub const INT32_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-INT32_MAX, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-INT32_MAX, -1) else (-INT32_MAX)(-1); pub const __UINT8_FMTX__ = c"hhX"; pub const __MAC_10_12 = 101200; pub const UINT_FAST8_MAX = UINT8_MAX; pub const __SOPT = 1024; pub const __UINTPTR_WIDTH__ = 64; pub const __IPHONE_6_1 = 60100; pub const __MAC_10_13_2 = 101302; pub const __AES__ = 1; pub const __UINT8_FMTx__ = c"hhx"; pub const __INTMAX_C_SUFFIX__ = L; pub const __STDC_WANT_LIB_EXT1__ = 1; pub const __ORDER_LITTLE_ENDIAN__ = 1234; pub const __INT16_FMTd__ = c"hd"; pub const REDISMODULE_CLUSTER_FLAG_NONE = 0; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = 1; pub const __SNPT = 2048; pub const __DARWIN_NON_CANCELABLE = 0; pub const __INTMAX_WIDTH__ = 64; pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = 2; pub const __IPHONE_10_0 = 100000; pub const __SIZE_FMTo__ = c"lo"; pub const __WATCHOS_3_1_1 = 30101; pub const REDISMODULE_REPLY_INTEGER = 2; pub const __MAC_10_14_4 = 101404; pub const __INT_FAST8_FMTi__ = c"hhi"; pub const __UINT_LEAST32_FMTo__ = c"o"; pub const __USER_LABEL_PREFIX__ = _; pub const __UINT_FAST16_FMTx__ = c"hx"; pub const __FLT_MIN_EXP__ = -125; pub const REDISMODULE_KEYTYPE_ZSET = 5; pub const __MAC_OS_X_VERSION_MAX_ALLOWED = __MAC_10_14_4; pub const __UINT_LEAST64_FMTu__ = c"llu"; pub const __DARWIN_UNIX03 = 1; pub const __GCC_ATOMIC_LONG_LOCK_FREE = 2; pub const __INT_FAST64_FMTd__ = c"lld"; pub const INT_LEAST8_MIN = INT8_MIN; pub const __STDC_NO_THREADS__ = 1; pub const __CLANG_ATOMIC_LONG_LOCK_FREE = 2; pub const __SERR = 64; pub const __GXX_ABI_VERSION = 1002; pub const INTPTR_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-INTPTR_MAX, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-INTPTR_MAX, -1) else (-INTPTR_MAX)(-1); pub const __FLT_MANT_DIG__ = 24; pub const __UINT_FAST64_FMTx__ = c"llx"; pub const __STDC__ = 1; pub const __DARWIN_ALIAS_STARTING_MAC___MAC_10_14_4 = x; pub const __INTPTR_FMTd__ = c"ld"; pub const __GNUC_PATCHLEVEL__ = 1; pub const __SIZE_WIDTH__ = 64; pub const __UINT_LEAST8_FMTx__ = c"hhx"; pub const __INT_LEAST64_FMTi__ = c"lli"; pub const __SSE4_2__ = 1; pub const __DARWIN_BYTE_ORDER = __DARWIN_LITTLE_ENDIAN; pub const __AVX__ = 1; pub const __MAC_OS_X_VERSION_MIN_REQUIRED = __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__; pub const __INT_FAST16_MAX__ = 32767; pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __DARWIN_NULL = if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Pointer) @ptrCast([*c]void, 0) else if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Int) @intToPtr([*c]void, 0) else ([*c]void)(0); pub const REDISMODULE_ERRORMSG_WRONGTYPE = c"WRONGTYPE Operation against a key holding the wrong kind of value"; pub const __SSP__ = 1; pub const __INT_MAX__ = 2147483647; pub const stdin = __stdinp; pub const __DBL_DENORM_MIN__ = 0.000000; pub const __clang_major__ = 8; pub const __FLT16_MANT_DIG__ = 11; pub const __IPHONE_12_1 = 120100; pub const UINTPTR_MAX = c_ulong(18446744073709551615); pub const __nullable = _Nullable; pub const __FLT_DENORM_MIN__ = 0.000000; pub const __DYNAMIC__ = 1; pub const __UINT_LEAST16_MAX__ = 65535; pub const SIG_ATOMIC_MIN = INT32_MIN; pub const __XSAVES__ = 1; pub const __LDBL_HAS_DENORM__ = 1; pub const __LDBL_HAS_QUIET_NAN__ = 1; pub const __API_TO_BE_DEPRECATED = 100000; pub const TMP_MAX = 308915776; pub const __UINT_FAST8_MAX__ = 255; pub const __DBL_MIN_10_EXP__ = -307; pub const __UINT8_FMTu__ = c"hhu"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_5_0 = x; pub const __SSE3__ = 1; pub const __SRW = 16; pub const __UINT16_FMTu__ = c"hu"; pub const __MAC_10_1 = 1010; pub const __SIZE_FMTu__ = c"lu"; pub const REDISMODULE_OK = 0; pub const __LDBL_MIN_EXP__ = -16381; pub const __UINT_FAST32_FMTu__ = c"u"; pub const SIZE_MAX = UINTPTR_MAX; pub const __DARWIN_C_FULL = c_long(900000); pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_9_1 = x; pub const __clang_patchlevel__ = 0; pub const __MACH__ = 1; pub const EOF = -1; pub const __PCLMUL__ = 1; pub const __FXSR__ = 1; pub const __MAC_10_6 = 1060; pub const _IOLBF = 1; pub const __UINT32_FMTx__ = c"x"; pub const __DARWIN_C_LEVEL = __DARWIN_C_FULL; pub const __IPHONE_9_1 = 90100; pub const __UINT32_FMTu__ = c"u"; pub const __SIZE_MAX__ = c_ulong(18446744073709551615); pub const __RTM__ = 1; pub const __WATCHOS_2_0 = 20000; pub const _QUAD_HIGHWORD = 1; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_8_0 = x; pub const __IPHONE_3_0 = 30000; pub const UINT32_MAX = c_uint(4294967295); pub const __x86_64__ = 1; pub const __UINTMAX_FMTx__ = c"lx"; pub const __UINT64_C_SUFFIX__ = ULL; pub const __MAC_10_12_2 = 101202; pub const __INT_LEAST16_MAX__ = 32767; pub const __SRD = 4; pub const __UINT32_FMTo__ = c"o"; pub const _IONBF = 2; pub const UINT64_MAX = c_ulonglong(18446744073709551615); pub const __INT_LEAST16_TYPE__ = short; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_2_2 = x; pub const __IPHONE_11_0 = 110000; pub const __ORDER_BIG_ENDIAN__ = 4321; pub const __LDBL_MIN_10_EXP__ = -4931; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_11_1 = x; pub const __DARWIN_BIG_ENDIAN = 4321; pub const __SIZEOF_INT__ = 4; pub const INT8_MIN = -128; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_10_2 = x; pub const WCHAR_MAX = __WCHAR_MAX__; pub const __PTHREAD_RWLOCK_SIZE__ = 192; pub const __TVOS_9_0 = 90000; pub const __MAC_10_14 = 101400; pub const __amd64 = 1; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_4_3 = x; pub const __OBJC_BOOL_IS_BOOL = 0; pub const REDISMODULE_ERR = 1; pub const __LDBL_MAX_10_EXP__ = 4932; pub const __SIZEOF_INT128__ = 16; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_11_4 = x; pub const __WATCHOS_3_0 = 30000; pub const WCHAR_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-WCHAR_MAX, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-WCHAR_MAX, -1) else (-WCHAR_MAX)(-1); pub const __MAC_10_13 = 101300; pub const __TVOS_11_4 = 110400; pub const __clang__ = 1; pub const INT_FAST16_MAX = INT16_MAX; pub const OBJC_NEW_PROPERTIES = 1; pub const __WATCHOS_4_0 = 40000; pub const __SSE4_1__ = 1; pub const __LDBL_DIG__ = 18; pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub const __DARWIN_ONLY_64_BIT_INO_T = 0; pub const _DARWIN_FEATURE_64_BIT_INODE = 1; pub const __INT_FAST32_FMTd__ = c"d"; pub const __UINT64_FMTo__ = c"llo"; pub const BIG_ENDIAN = __DARWIN_BIG_ENDIAN; pub const __SOFF = 4096; pub const __ATOMIC_ACQ_REL = 4; pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = 4; pub const __IPHONE_4_2 = 40200; pub const UINT_FAST64_MAX = UINT64_MAX; pub const __DARWIN_ONLY_UNIX_CONFORMANCE = 1; pub const __WORDSIZE = 64; pub const __INT64_MAX__ = c_longlong(9223372036854775807); pub const __DARWIN_SUF_64_BIT_INO_T = c"$INODE64"; pub const __INT_LEAST64_MAX__ = c_longlong(9223372036854775807); pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = 0; pub const __FLT_HAS_DENORM__ = 1; pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const RENAME_SWAP = 2; pub const __INT32_FMTi__ = c"i"; pub const __DBL_HAS_INFINITY__ = 1; pub const __FINITE_MATH_ONLY__ = 0; pub const REDISMODULE_KEYTYPE_MODULE = 6; pub const __WATCHOS_1_0 = 10000; pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = 1; pub const __FLT16_MAX_EXP__ = 15; pub const __SIZEOF_FLOAT__ = 4; pub const INT_FAST64_MAX = INT64_MAX; pub const __INT_LEAST32_FMTi__ = c"i"; pub const __LDBL_EPSILON__ = 0.000000; pub const __INT_LEAST32_FMTd__ = c"d"; pub const __STDC_UTF_32__ = 1; pub const __MAC_10_11_2 = 101102; pub const REDISMODULE_KEYTYPE_STRING = 1; pub const __SIG_ATOMIC_WIDTH__ = 32; pub const __UINT_FAST64_FMTX__ = c"llX"; pub const __SIZEOF_DOUBLE__ = 8; pub const REDISMODULE_POSTPONED_ARRAY_LEN = -1; pub const __DARWIN_SUF_EXTSN = c"$DARWIN_EXTSN"; pub const LITTLE_ENDIAN = __DARWIN_LITTLE_ENDIAN; pub const __GCC_ATOMIC_SHORT_LOCK_FREE = 2; pub const BYTE_ORDER = __DARWIN_BYTE_ORDER; pub const __IPHONE_12_0 = 120000; pub const __SIZE_FMTX__ = c"lX"; pub const __CTERMID_DEFINED = 1; pub const __DBL_MIN_EXP__ = -1021; pub const __TVOS_12_0 = 120000; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_7_1 = x; pub const REDISMODULE_HASH_NONE = 0; pub const __DBL_HAS_DENORM__ = 1; pub const __signed = signed; pub const __FLT16_HAS_QUIET_NAN__ = 1; pub const __ATOMIC_RELAXED = 0; pub const __XSAVEC__ = 1; pub const __SIZEOF_SHORT__ = 2; pub const __UINT16_FMTX__ = c"hX"; pub const __UINT_FAST16_MAX__ = 65535; pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = 2; pub const __MAC_10_0 = 1000; pub const __WATCHOS_5_1 = 50100; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_9_0 = x; pub const PTRDIFF_MAX = INT64_MAX; pub const __AVX2__ = 1; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_3_2 = x; pub const __WINT_MAX__ = 2147483647; pub const __STDC_HOSTED__ = 1; pub const __IPHONE_8_2 = 80200; pub const __INT_LEAST32_TYPE__ = int; pub const __SCHAR_MAX__ = 127; pub const __MAC_10_5 = 1050; pub const REDISMODULE_APIVER_1 = 1; pub const __FLT16_MIN_EXP__ = -14; pub const stdout = __stdoutp; pub const __IPHONE_9_0 = 90000; pub const __PRFCHW__ = 1; pub const USER_ADDR_NULL = if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Pointer) @ptrCast(user_addr_t, 0) else if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Int) @intToPtr(user_addr_t, 0) else user_addr_t(0); pub const __WATCHOS_2_1 = 20100; pub const __LDBL_MANT_DIG__ = 64; pub const __CLANG_ATOMIC_INT_LOCK_FREE = 2; pub const INT16_MIN = -32768; pub const __UINT64_FMTX__ = c"llX"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_8_1 = x; pub const __DBL_MANT_DIG__ = 53; pub const __INT_LEAST32_MAX__ = 2147483647; pub const _QUAD_LOWWORD = 0; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_12_2 = x; pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = 1; pub const __TVOS_10_0 = 100000; pub const __LITTLE_ENDIAN__ = 1; pub const __SSE__ = 1; pub const __SNBF = 2; pub const __FLT_HAS_QUIET_NAN__ = 1; pub const __SIZEOF_SIZE_T__ = 8; pub const __IPHONE_11_1 = 110100; pub const __UINT_LEAST16_FMTo__ = c"ho"; pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const __UINTPTR_MAX__ = c_ulong(18446744073709551615); pub const UINT16_MAX = 65535; pub const __UINT_LEAST8_FMTu__ = c"hhu"; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_10_1 = x; pub const __TVOS_9_1 = 90100; pub const __IPHONE_11_4 = 110400; pub const __SIZEOF_WCHAR_T__ = 4; pub const __DARWIN_NO_LONG_LONG = 0; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_4_0 = x; pub const __LDBL_MAX__ = inf; pub const _LP64 = 1; pub const FD_SETSIZE = __DARWIN_FD_SETSIZE; pub const __code_model_small_ = 1; pub const __FLT_DIG__ = 6; pub const __INT16_MAX__ = 32767; pub const __FLT_MAX_10_EXP__ = 38; pub const __MAC_10_10 = 101000; pub const __UINTPTR_FMTX__ = c"lX"; pub const __UINT_LEAST16_FMTu__ = c"hu"; pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = 2; pub const __WINT_WIDTH__ = 32; pub const REDISMODULE_REPLY_ERROR = 1; pub const __TVOS_11_3 = 110300; pub const __SHRT_MAX__ = 32767; pub const __GCC_ATOMIC_BOOL_LOCK_FREE = 2; pub const __WATCHOS_4_1 = 40100; pub const __INT32_FMTd__ = c"d"; pub const __DBL_MIN__ = 0.000000; pub const __INTPTR_WIDTH__ = 64; pub const __FLT16_MAX_10_EXP__ = 4; pub const __INT_FAST32_TYPE__ = int; pub const __PTHREAD_SIZE__ = 8176; pub const __IPHONE_4_3 = 40300; pub const __UINT_FAST32_FMTX__ = c"X"; pub const __corei7__ = 1; pub const __BMI__ = 1; pub const __FLT16_HAS_INFINITY__ = 1; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = 1; pub const INT_FAST8_MIN = INT8_MIN; pub const __GCC_ATOMIC_INT_LOCK_FREE = 2; pub const __TVOS_10_0_1 = 100001; pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = 3; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_6_0 = x; pub const __INT_FAST8_FMTd__ = c"hhd"; pub const __MAC_10_11_4 = 101104; pub const SEEK_SET = 0; pub const __INT32_TYPE__ = int; pub const __IPHONE_10_3 = 100300; pub const __restrict = restrict; pub const __FLT_MIN__ = 0.000000; pub const __INT8_FMTd__ = c"hhd"; pub const INT64_MAX = c_longlong(9223372036854775807); pub const __FLT_MAX_EXP__ = 128; pub const __XSAVE__ = 1; pub const __MAC_10_11_3 = 101103; pub const __INT_FAST64_FMTi__ = c"lli"; pub const __INT_LEAST8_FMTd__ = c"hhd"; pub const __UINT_LEAST32_FMTX__ = c"X"; pub const __UINTMAX_MAX__ = c_ulong(18446744073709551615); pub const __UINT_FAST16_FMTo__ = c"ho"; pub const INT_LEAST64_MIN = INT64_MIN; pub const __APPLE_CC__ = 6000; pub const __PTHREAD_CONDATTR_SIZE__ = 8; pub const __SIZE_FMTx__ = c"lx"; pub const __DBL_EPSILON__ = 0.000000; pub const INT_FAST32_MIN = INT32_MIN; pub const __TVOS_12_1 = 120100; pub const INT32_MAX = 2147483647; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_7_0 = x; pub const __CHAR_BIT__ = 8; pub const __INT16_FMTi__ = c"hi"; pub const SEEK_CUR = 1; pub const __GNUC_MINOR__ = 2; pub const INT_LEAST32_MIN = INT32_MIN; pub const __UINT_FAST32_MAX__ = c_uint(4294967295); pub const NFDBITS = __DARWIN_NFDBITS; pub const __FLT_EPSILON__ = 0.000000; pub const INT_FAST32_MAX = INT32_MAX; pub const __IPHONE_8_4 = 80400; pub const __llvm__ = 1; pub const __UINT_FAST64_MAX__ = c_ulonglong(18446744073709551615); pub const __INT_FAST32_FMTi__ = c"i"; pub const __WATCHOS_5_0 = 50000; pub const INT16_MAX = 32767; pub const __FLT_HAS_INFINITY__ = 1; pub const NULL = __DARWIN_NULL; pub const __IPHONE_8_3 = 80300; pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __null_unspecified = _Null_unspecified; pub const __UINT32_FMTX__ = c"X"; pub const __MAC_10_4 = 1040; pub const UINT_LEAST8_MAX = UINT8_MAX; pub const __DARWIN_WCHAR_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-2147483647, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-2147483647, -1) else (-2147483647)(-1); pub const _USE_FORTIFY_LEVEL = 2; pub const __IPHONE_7_1 = 70100; pub const __UINT32_C_SUFFIX__ = U; pub const __INT32_MAX__ = 2147483647; pub const __GCC_ATOMIC_CHAR_LOCK_FREE = 2; pub const __DARWIN_NBBY = 8; pub const __DBL_HAS_QUIET_NAN__ = 1; pub const __APPLE__ = 1; pub const __MAC_10_9 = 1090; pub const __STDC_UTF_16__ = 1; pub const __UINT_LEAST32_MAX__ = c_uint(4294967295); pub const __ATOMIC_RELEASE = 3; pub const __UINTMAX_C_SUFFIX__ = UL; pub const __IPHONE_3_2 = 30200; pub const __SIZEOF_LONG_DOUBLE__ = 16; pub const __ORDER_PDP_ENDIAN__ = 3412; pub const FILENAME_MAX = 1024; pub const __IPHONE_2_0 = 20000; pub const __INT16_TYPE__ = short; pub const __TVOS_10_1 = 100100; pub const __SSE2_MATH__ = 1; pub const UINT_LEAST16_MAX = UINT16_MAX; pub const REDISMODULE_REPLY_ARRAY = 3; pub const UINT_LEAST32_MAX = UINT32_MAX; pub const REDISMODULE_NO_EXPIRE = -1; pub const __INT_FAST8_MAX__ = 127; pub const __MPX__ = 1; pub const __MAC_10_12_1 = 101201; pub const REDISMODULE_NODE_ID_LEN = 40; pub const __INTPTR_MAX__ = c_long(9223372036854775807); pub const RENAME_SECLUDE = 1; pub const __WINT_TYPE__ = int; pub const __UINT64_FMTu__ = c"llu"; pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __SSE2__ = 1; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_10_0 = x; pub const __TVOS_9_2 = 90200; pub const __INTMAX_FMTi__ = c"li"; pub const __GNUC__ = 4; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_4_1 = x; pub const __UINT32_MAX__ = c_uint(4294967295); pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_11_2 = x; pub const __SMBF = 128; pub const __DBL_MAX_EXP__ = 1024; pub const __INT8_FMTi__ = c"hhi"; pub const L_tmpnam = 1024; pub const __MAC_10_11 = 101100; pub const __DARWIN_64_BIT_INO_T = 1; pub const __FLT16_MIN_10_EXP__ = -13; pub const __TVOS_11_2 = 110200; pub const _DARWIN_FEATURE_UNIX_CONFORMANCE = 3; pub const __WATCHOS_4_2 = 40200; pub const WINT_MAX = INT32_MAX; pub const UINT_FAST16_MAX = UINT16_MAX; pub const __INT_FAST64_MAX__ = c_longlong(9223372036854775807); pub const __IPHONE_4_0 = 40000; pub const __ATOMIC_SEQ_CST = 5; pub const __SIZEOF_LONG_LONG__ = 8; pub const __BMI2__ = 1; pub const __GNUC_STDC_INLINE__ = 1; pub const __UINT8_MAX__ = 255; pub const __MAC_10_14_1 = 101401; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = 1; pub const _FORTIFY_SOURCE = 2; pub const __UINT16_FMTo__ = c"ho"; pub const __POPCNT__ = 1; pub const __OPENCL_MEMORY_SCOPE_DEVICE = 2; pub const INT_LEAST8_MAX = INT8_MAX; pub const __SIZEOF_POINTER__ = 8; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_6_1 = x; pub const __IPHONE_10_2 = 100200; pub const __INT_FAST16_FMTd__ = c"hd"; pub const __UINT_LEAST32_FMTu__ = c"u"; pub const REDISMODULE_REPLY_UNKNOWN = -1; pub const __FLT_MAX__ = 340282346999999984391321947108527833088.000000; pub const __corei7 = 1; pub const BUFSIZ = 1024; pub const __SMOD = 8192; pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const __DARWIN_ALIAS_STARTING_MAC___MAC_10_14_1 = x; pub const __ATOMIC_CONSUME = 1; pub const __LDBL_HAS_INFINITY__ = 1; pub const __FLT_MIN_10_EXP__ = -37; pub const __UINTPTR_FMTo__ = c"lo"; pub const __INT_LEAST16_FMTd__ = c"hd"; pub const __UINTPTR_FMTx__ = c"lx"; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = 1; pub const __INT_LEAST64_FMTd__ = c"lld"; pub const __nonnull = _Nonnull; pub const __DARWIN_VERS_1050 = 1; pub const __INT_LEAST8_MAX__ = 127; pub const __IPHONE_12_2 = 120200; pub const __MAC_10_10_3 = 101003; pub const __DARWIN_WEOF = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(__darwin_wint_t, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(__darwin_wint_t, -1) else __darwin_wint_t(-1); pub const __GCC_ATOMIC_POINTER_LOCK_FREE = 2; pub const __PTHREAD_COND_SIZE__ = 40; pub const __TVOS_12_2 = 120200; pub const INT8_MAX = 127; pub const __ADX__ = 1; pub const L_ctermid = 1024; pub const __UINT_FAST8_FMTx__ = c"hhx"; pub const UINT_FAST32_MAX = UINT32_MAX; pub const __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ = 101400; pub const __UINT16_FMTx__ = c"hx"; pub const __DARWIN_ONLY_VERS_1050 = 0; pub const __UINTPTR_FMTu__ = c"lu"; pub const __UINT_LEAST16_FMTX__ = c"hX"; pub const __CLFLUSHOPT__ = 1; pub const __amd64__ = 1; pub const __UINT_FAST32_FMTo__ = c"o"; pub const __SSTR = 512; pub const __LP64__ = 1; pub const __PTRDIFF_FMTi__ = c"li"; pub const __volatile = @"volatile"; pub const __XSAVEOPT__ = 1; pub const PDP_ENDIAN = __DARWIN_PDP_ENDIAN; pub const __IPHONE_8_0 = 80000; pub const __LONG_LONG_MAX__ = c_longlong(9223372036854775807); pub const __MAC_10_3 = 1030; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_9_3 = x; pub const INT_LEAST16_MAX = INT16_MAX; pub const __IPHONE_7_0 = 70000; pub const __DARWIN_ALIAS_STARTING_IPHONE___IPHONE_3_1 = x; pub const INT_LEAST32_MAX = INT32_MAX; pub const __INTMAX_MAX__ = c_long(9223372036854775807); pub const __UINT_LEAST32_FMTx__ = c"x"; pub const __WCHAR_MAX__ = 2147483647; pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub const __UINTMAX_FMTX__ = c"lX"; pub const __MAC_10_8 = 1080; pub const __IPHONE_9_3 = 90300; pub const __SEOF = 32; pub const __WATCHOS_2_2 = 20200; pub const __IPHONE_2_1 = 20100; pub const __va_list_tag = struct___va_list_tag; pub const __darwin_pthread_handler_rec = struct___darwin_pthread_handler_rec; pub const _opaque_pthread_attr_t = struct__opaque_pthread_attr_t; pub const _opaque_pthread_cond_t = struct__opaque_pthread_cond_t; pub const _opaque_pthread_condattr_t = struct__opaque_pthread_condattr_t; pub const _opaque_pthread_mutex_t = struct__opaque_pthread_mutex_t; pub const _opaque_pthread_mutexattr_t = struct__opaque_pthread_mutexattr_t; pub const _opaque_pthread_once_t = struct__opaque_pthread_once_t; pub const _opaque_pthread_rwlock_t = struct__opaque_pthread_rwlock_t; pub const _opaque_pthread_rwlockattr_t = struct__opaque_pthread_rwlockattr_t; pub const _opaque_pthread_t = struct__opaque_pthread_t; pub const __sbuf = struct___sbuf; pub const __sFILEX = struct___sFILEX; pub const __sFILE = struct___sFILE;
redismodule.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const meta = std.meta; const debug = std.debug; const testing = std.testing; const TypeInfo = builtin.TypeInfo; const TypeId = builtin.TypeId; fn ByteToSliceResult(comptime Elem: type, comptime SliceOrArray: type) type { if (@typeInfo(SliceOrArray) != .Pointer) @compileError("Cannot bytesToSlice " ++ @typeName(SliceOrArray)); const ptr = @typeInfo(SliceOrArray).Pointer; if (ptr.is_const and ptr.is_volatile) return []align(ptr.alignment) const volatile Elem; if (ptr.is_const) return []align(ptr.alignment) const Elem; if (ptr.is_volatile) return []align(ptr.alignment) volatile Elem; return []align(ptr.alignment) Elem; } pub fn bytesToSlice(comptime Element: type, bytes: var) error{SizeMismatch}!ByteToSliceResult(Element, @TypeOf(bytes)) { if (bytes.len % @sizeOf(Element) != 0) return error.SizeMismatch; return std.mem.bytesAsSlice(Element, bytes); } test "generic.slice.bytesToSlice" { const S = packed struct { a: u8, b: u8, }; { const a = [_]u8{1}; const b = [_]u8{ 1, 2 }; if (bytesToSlice(S, a[0..])) |_| unreachable else |_| {} const v = bytesToSlice(S, b[0..]) catch unreachable; comptime testing.expectEqual([]align(1) const S, @TypeOf(v)); testing.expectEqual(@as(usize, 1), v.len); testing.expectEqual(@as(u8, 1), v[0].a); testing.expectEqual(@as(u8, 2), v[0].b); const v2 = bytesToSlice(S, &b) catch unreachable; comptime testing.expectEqual([]align(1) const S, @TypeOf(v2)); testing.expectEqual(@as(usize, 1), v2.len); testing.expectEqual(@as(u8, 1), v2[0].a); testing.expectEqual(@as(u8, 2), v2[0].b); } { var a = [_]u8{1}; var b = [_]u8{ 1, 2 }; if (bytesToSlice(S, a[0..])) |_| unreachable else |_| {} const v = bytesToSlice(S, b[0..]) catch unreachable; comptime testing.expectEqual([]align(1) S, @TypeOf(v)); testing.expectEqual(@as(usize, 1), v.len); testing.expectEqual(@as(u8, 1), v[0].a); testing.expectEqual(@as(u8, 2), v[0].b); const v2 = bytesToSlice(S, &b) catch unreachable; comptime testing.expectEqual([]align(1) S, @TypeOf(v2)); testing.expectEqual(@as(usize, 1), v2.len); testing.expectEqual(@as(u8, 1), v2[0].a); testing.expectEqual(@as(u8, 2), v2[0].b); } } pub fn bytesToSliceTrim(comptime Element: type, bytes: var) ByteToSliceResult(Element, @TypeOf(bytes)) { var rem = bytes.len % @sizeOf(Element); return std.mem.bytesAsSlice(Element, bytes[0 .. bytes.len - rem]); } test "generic.slice.bytesToSliceTrim" { const S = packed struct { a: u8, b: u8, }; { const a = [_]u8{1}; const b = [_]u8{ 1, 2 }; const v1 = bytesToSliceTrim(S, a[0..]); const v2 = bytesToSliceTrim(S, b[0..]); const v3 = bytesToSliceTrim(S, &a); const v4 = bytesToSliceTrim(S, &b); comptime testing.expect([]align(1) const S == @TypeOf(v1)); comptime testing.expect([]align(1) const S == @TypeOf(v2)); comptime testing.expect([]const S == @TypeOf(v3)); comptime testing.expect([]const S == @TypeOf(v4)); testing.expectEqual(@as(usize, 0), v1.len); testing.expectEqual(@as(usize, 1), v2.len); testing.expectEqual(@as(usize, 0), v3.len); testing.expectEqual(@as(usize, 1), v4.len); testing.expectEqual(@as(u8, 1), v2[0].a); testing.expectEqual(@as(u8, 2), v2[0].b); testing.expectEqual(@as(u8, 1), v4[0].a); testing.expectEqual(@as(u8, 2), v4[0].b); } { var a = [_]u8{1}; var b = [_]u8{ 1, 2 }; const v1 = bytesToSliceTrim(S, a[0..]); const v2 = bytesToSliceTrim(S, b[0..]); const v3 = bytesToSliceTrim(S, &a); const v4 = bytesToSliceTrim(S, &b); comptime testing.expectEqual([]S, @TypeOf(v1)); comptime testing.expectEqual([]S, @TypeOf(v2)); comptime testing.expectEqual([]S, @TypeOf(v3)); comptime testing.expectEqual([]S, @TypeOf(v4)); testing.expectEqual(@as(usize, 0), v1.len); testing.expectEqual(@as(usize, 1), v2.len); testing.expectEqual(@as(usize, 0), v3.len); testing.expectEqual(@as(usize, 1), v4.len); testing.expectEqual(@as(usize, 1), v2[0].a); testing.expectEqual(@as(usize, 2), v2[0].b); testing.expectEqual(@as(usize, 1), v4[0].a); testing.expectEqual(@as(usize, 2), v4[0].b); } } fn SliceResult(comptime SliceOrArray: type) type { if (@typeInfo(SliceOrArray) != .Pointer) @compileError("Cannot slice " ++ @typeName(SliceOrArray)); const ptr = @typeInfo(SliceOrArray).Pointer; const Child = switch (ptr.size) { .One => @typeInfo(ptr.child).Array.child, else => ptr.child, }; if (ptr.is_const and ptr.is_volatile) return []align(ptr.alignment) const volatile Child; if (ptr.is_const) return []align(ptr.alignment) const Child; if (ptr.is_volatile) return []align(ptr.alignment) volatile Child; return []align(ptr.alignment) Child; } /// Slices ::s from ::start to ::end. /// Returns errors instead of doing runtime asserts when ::start or ::end are out of bounds, /// or when ::end is less that ::start. pub fn slice(s: var, start: usize, end: usize) !SliceResult(@TypeOf(s)) { if (end < start) return error.EndLessThanStart; if (s.len < start or s.len < end) return error.OutOfBound; return s[start..end]; } test "generic.slice.slice" { const a = [_]u8{ 1, 2 }; const b = slice(a[0..], 0, 1) catch unreachable; const c = slice(a[0..], 1, 2) catch unreachable; const d = slice(a[0..], 0, 2) catch unreachable; const e = slice(a[0..], 2, 2) catch unreachable; const f = slice(&a, 1, 2) catch unreachable; testing.expectEqualSlices(u8, &[_]u8{1}, b); testing.expectEqualSlices(u8, &[_]u8{2}, c); testing.expectEqualSlices(u8, &[_]u8{ 1, 2 }, d); testing.expectEqualSlices(u8, &[_]u8{}, e); testing.expectEqualSlices(u8, &[_]u8{2}, f); testing.expectError(error.OutOfBound, slice(a[0..], 0, 3)); testing.expectError(error.OutOfBound, slice(a[0..], 3, 3)); testing.expectError(error.EndLessThanStart, slice(a[0..], 1, 0)); const q1 = [_]u8{ 1, 2 }; var q2 = [_]u8{ 1, 2 }; const q11 = slice(q1[0..], 0, 2) catch unreachable; const q21 = slice(q2[0..], 0, 2) catch unreachable; comptime testing.expectEqual([]const u8, @TypeOf(q11)); comptime testing.expectEqual([]u8, @TypeOf(q21)); const q12 = slice(&q1, 0, 2) catch unreachable; const q22 = slice(&q2, 0, 2) catch unreachable; comptime testing.expectEqual([]const u8, @TypeOf(q12)); comptime testing.expectEqual([]u8, @TypeOf(q22)); } /// Returns a pointer to the item at ::index in ::s. /// Returns an error instead of doing a runtime assert when ::index is out of bounds. pub fn at(s: var, index: usize) !@TypeOf(&s[0]) { if (s.len <= index) return error.OutOfBound; return &s[index]; } test "generic.slice.at" { const a = [_]u8{ 1, 2 }; const b = at(a[0..], 0) catch unreachable; const c = at(a[0..], 1) catch unreachable; const d = at(a[0..], 1) catch unreachable; testing.expectEqual(@as(u8, 1), b.*); testing.expectEqual(@as(u8, 2), c.*); testing.expectEqual(@as(u8, 2), d.*); testing.expectError(error.OutOfBound, at(a[0..], 2)); const q1 = [_]u8{ 1, 2 }; var q2 = [_]u8{ 1, 2 }; const q11 = at(q1[0..], 0) catch unreachable; const q21 = at(q2[0..], 0) catch unreachable; comptime testing.expectEqual(*const u8, @TypeOf(q11)); comptime testing.expectEqual(*u8, @TypeOf(q21)); const q31 = at(&q1, 0) catch unreachable; const q41 = at(&q2, 0) catch unreachable; comptime testing.expectEqual(*const u8, @TypeOf(q31)); comptime testing.expectEqual(*u8, @TypeOf(q41)); } pub fn all(s: var, predicate: fn (@TypeOf(s[0])) bool) bool { for (s) |v| { if (!predicate(v)) return false; } return true; } test "generic.slice.all" { const s = "aaa"[0..]; testing.expect(all(s, struct { fn l(c: u8) bool { return c == 'a'; } }.l)); testing.expect(!all(s, struct { fn l(c: u8) bool { return c != 'a'; } }.l)); } pub fn any(s: var, predicate: fn (@TypeOf(s[0])) bool) bool { for (s) |v| { if (predicate(v)) return true; } return false; } test "generic.slice.any" { const s = "abc"; testing.expect(any(s, struct { fn l(c: u8) bool { return c == 'a'; } }.l)); testing.expect(!any(s, struct { fn l(c: u8) bool { return c == 'd'; } }.l)); } pub fn populate(s: var, value: @TypeOf(s[0])) void { for (s) |*v| { v.* = value; } } test "generic.slice.populate" { var arr: [4]u8 = undefined; populate(arr[0..], 'a'); testing.expectEqualSlices(u8, "aaaa", &arr); } pub fn transform(s: var, transformer: fn (@TypeOf(s[0])) @TypeOf(s[0])) void { for (s) |*v| { v.* = transformer(v.*); } } test "generic.slice.transform" { var arr = "abcd".*; transform(arr[0..], struct { fn l(c: u8) u8 { return if ('a' <= c and c <= 'z') c - ('a' - 'A') else c; } }.l); testing.expectEqualSlices(u8, "ABCD", &arr); }
src/generic/slice.zig
const x86_64 = @import("../index.zig"); const bitjuggle = @import("bitjuggle"); const std = @import("std"); pub const EnsureNoInterrupts = struct { enabled: bool, pub fn start() EnsureNoInterrupts { return .{ .enabled = areEnabled(), }; } pub fn end(self: EnsureNoInterrupts) void { if (self.enabled) enable(); } }; /// Returns whether interrupts are enabled. pub fn areEnabled() bool { return x86_64.registers.RFlags.read().interrupt; } /// Enable interrupts. /// /// This is a wrapper around the `sti` instruction. pub fn enable() void { asm volatile ("sti"); } /// Disable interrupts. /// /// This is a wrapper around the `cli` instruction. pub fn disable() void { asm volatile ("cli"); } /// Atomically enable interrupts and put the CPU to sleep /// /// Executes the `sti; hlt` instruction sequence. Since the `sti` instruction /// keeps interrupts disabled until after the immediately following /// instruction (called "interrupt shadow"), no interrupt can occur between the /// two instructions. (One exception to this are non-maskable interrupts; this /// is explained below.) /// /// This function is useful to put the CPU to sleep without missing interrupts /// that occur immediately before the `hlt` instruction /// /// ## Non-maskable Interrupts /// /// On some processors, the interrupt shadow of `sti` does not apply to /// non-maskable interrupts (NMIs). This means that an NMI can occur between /// the `sti` and `hlt` instruction, with the result that the CPU is put to /// sleep even though a new interrupt occured. /// /// To work around this, it is recommended to check in the NMI handler if /// the interrupt occured between `sti` and `hlt` instructions. If this is the /// case, the handler should increase the instruction pointer stored in the /// interrupt stack frame so that the `hlt` instruction is skipped. /// /// See <http://lkml.iu.edu/hypermail/linux/kernel/1009.2/01406.html> for more /// information. pub fn enableAndHlt() void { asm volatile ("sti; hlt"); } pub fn disableAndHlt() noreturn { while (true) { asm volatile ("cli; hlt"); } } /// Cause a breakpoint exception by invoking the `int3` instruction. pub fn int3() void { asm volatile ("int3"); } /// Generate a software interrupt by invoking the `int` instruction. pub fn softwareInterrupt(comptime num: usize) void { asm volatile ("int %[num]" : : [num] "N" (num), ); } comptime { std.testing.refAllDecls(@This()); }
src/instructions/interrupts.zig
const std = @import("std"); const builtin = @import("builtin"); const cstr = std.cstr; const File = std.os.File; const c = @cImport({ @cInclude("stdio.h"); }); // File access var stdin_file: File = undefined; export var stdin = &stdin_file; var stdout_file: File = undefined; export var stdout = &stdout_file; var stderr_file: File = undefined; export var stderr = &stderr_file; var allocator = &@import("allocator.zig").fixed.allocator; fn initStreams() void { @setCold(true); stdin_file = std.io.getStdIn() catch unreachable; stdout_file = std.io.getStdOut() catch unreachable; stderr_file = std.io.getStdErr() catch unreachable; } var resolved: u8 = 0; inline fn readOpaqueHandle(handle: ?*c.FILE) *File { // TODO: workaround since passing resolved directly to @cmpxchgStrong treats it as comptime var non_comptime_resolved = &resolved; if (@cmpxchgStrong(u8, non_comptime_resolved, 0, 1, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst)) |_| { @noInlineCall(initStreams); } return @ptrCast(*File, @alignCast(@alignOf(File), handle.?)); } export fn fopen(filename: [*]const u8, mode: [*]const u8) ?*c.FILE { var fd = allocator.create(File(undefined)) catch return null; fd.* = File.openWrite(allocator, cstr.toSliceConst(filename)) catch return null; return @ptrCast(?*c.FILE, fd); } export fn fopen64(filename: [*]const u8, mode: [*]const u8) ?*c.FILE { return fopen(filename, mode); } export fn freopen(maybe_filename: ?[*]const u8, mode: [*]const u8, stream: ?*c.FILE) ?*c.FILE { if (maybe_filename) |filename| { // TODO: Probably a better way of doing this. var fd = readOpaqueHandle(stream); fd.close(); fd.* = File.openWrite(allocator, cstr.toSliceConst(filename)) catch return null; return @ptrCast(?*c.FILE, fd); } else { @panic("TODO: reopen existing stream with new mode"); } } export fn freopen64(maybe_filename: ?[*]const u8, mode: [*]const u8, stream: ?*c.FILE) ?*c.FILE { return freopen(maybe_filename, mode, stream); } export fn fclose(stream: ?*c.FILE) c_int { var fd = readOpaqueHandle(stream); fd.close(); return 0; } // High level file operations export fn rename(old_filename: ?[*]const u8, new_filename: ?[*]const u8) c_int { if (std.os.rename(allocator, cstr.toSliceConst(old_filename.?), cstr.toSliceConst(new_filename.?))) |_| { return 0; } else |err| { return -1; } } export fn remove(pathname: ?[*]const u8) c_int { if (std.os.deleteFile(allocator, cstr.toSliceConst(pathname.?))) |_| { return 0; } else |err| { return -1; } } // File positioning export fn fseek(stream: ?*c.FILE, offset: c_long, origin: c_int) c_int { var fd = readOpaqueHandle(stream); switch (origin) { c.SEEK_SET => fd.seekTo(@intCast(usize, offset)) catch return -1, c.SEEK_CUR => fd.seekForward(@intCast(isize, offset)) catch return -1, c.SEEK_END => @panic("TODO: unimplemented SEEK_END"), else => @panic("fseek unreachable"), } return 0; } export fn ftell(stream: ?*c.FILE) c_long { var fd = readOpaqueHandle(stream); return @intCast(c_long, fd.getPos() catch return c.EOF); } export fn rewind(stream: ?*c.FILE) void { var fd = readOpaqueHandle(stream); // TODO: Clear EOF indicator fd.seekTo(0) catch @panic("rewind unreachable"); } // NOTE: Omitted fpos_t and related functions // Unformatted file i/o export fn fread(noalias buffer: [*]u8, size: usize, count: usize, stream: ?*c.FILE) usize { var fd = readOpaqueHandle(stream); var b = buffer[0 .. count * size]; return fd.read(b) catch return 0; } export fn fwrite(buffer: [*]const u8, size: usize, count: usize, stream: ?*c.FILE) usize { var fd = readOpaqueHandle(stream); var b = buffer[0 .. count * size]; fd.write(b) catch return 0; return b.len; } export fn fgetc(stream: ?*c.FILE) c_int { var fd = readOpaqueHandle(stream); var b: [1]u8 = undefined; _ = fd.read(b[0..]) catch return c.EOF; return c_int(b[0]); } export fn getc(stream: ?*c.FILE) c_int { return fgetc(stream); } export fn _IO_getc(stream: ?*c._IO_FILE) c_int { return getc(stream); } export fn getchar() c_int { return fgetc(@ptrCast(?*c.FILE, stdin)); } export fn fputc(ch: c_int, stream: ?*c.FILE) c_int { var fd = readOpaqueHandle(stream); var b = []const u8{@intCast(u8, ch)}; _ = fd.write(b[0..]) catch return c.EOF; return 0; } export fn putc(ch: c_int, stream: ?*c.FILE) c_int { return fputc(ch, stream); } export fn putchar(ch: c_int) c_int { return fputc(ch, @ptrCast(?*c.FILE, stdout)); } export fn fputs(str: ?[*]const u8, stream: ?*c.FILE) c_int { var fd = readOpaqueHandle(stream); fd.write(cstr.toSliceConst(str.?)) catch return -1; fd.write("\n") catch return -1; return 0; } export fn puts(str: [*]const u8) c_int { return fputs(str, @ptrCast(?*c.FILE, stdout)); } export fn fgets(s: [*]u8, size: c_int, stream: ?*c.FILE) ?[*]u8 { var i: usize = 0; while (i < @intCast(usize, size) - 1) : (i += 1) { const ch = fgetc(stream); switch (ch) { c.EOF => break, '\n' => { s[i] = @intCast(u8, ch); i += 1; break; }, else => { s[i] = @intCast(u8, ch); }, } } s[i] = 0; return s; } // TODO: varargs support (access stack directly) // TODO: Write directly to stream instead of buffer export fn test_fprintf(stream: ?*c.FILE, noalias fmt: [*]const u8) c_int { var buffer: [64]u8 = undefined; var i: usize = 0; while (fmt[i] != 0) { var ch = fmt[i]; i += 1; if (ch != '%') { _ = fputc(ch, stream); continue; } // c == % ch = fmt[i]; i += 1; switch (ch) { 'd', 'i' => { const dummy: c_int = -5; const slice = std.fmt.bufPrint(buffer[0..], "{}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 'u' => { const dummy: c_uint = 5; const slice = std.fmt.bufPrint(buffer[0..], "{}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 'x', 'X' => { const dummy: c_uint = 5; const slice = std.fmt.bufPrint(buffer[0..], "{x}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 'e', 'E' => { const dummy: f32 = -5.3; const slice = std.fmt.bufPrint(buffer[0..], "{e}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 'f', 'F' => { const dummy: f32 = 5.3; const slice = std.fmt.bufPrint(buffer[0..], "{.5}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 'c' => { const dummy: u8 = 'A'; const slice = std.fmt.bufPrint(buffer[0..], "{c}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 's' => { const dummy: [*]const u8 = c"dummy"; _ = fwrite(dummy, 1, std.cstr.len(dummy), stream); }, 'p' => { const dummy: usize = @ptrToInt(&buffer); const slice = std.fmt.bufPrint(buffer[0..], "{x}", dummy) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, '%' => { _ = fputc('%', stream); }, else => { const slice = std.fmt.bufPrint(buffer[0..], "(unknown: %{c})", ch) catch unreachable; _ = fwrite(slice.ptr, 1, slice.len, stream); }, 0 => break, } } return 0; } export fn clearerr(stream: ?*c.FILE) void { // TODO: actually clear streams } export fn feof(stream: ?*c.FILE) c_int { // TODO: actually check eof return 0; } export fn ferror(stream: ?*c.FILE) c_int { // TODO: check if error has occured return 0; } export fn fflush(stream: ?*c.FILE) c_int { // TODO: actually flush the stream return 0; } export fn setvbuf(stream: ?*c.FILE, buf: [*]u8, mode: c_int, size: usize) c_int { // TODO: return 0; }
src/stdio.zig
pub const Scancode = enum(u8) { // Unknown = 0x00 // Escape EscPressed = 0x01, // Digits OnePressed = 0x02, TwoPressed = 0x03, ThreePressed = 0x04, FourPressed = 0x05, FivePressed = 0x06, SixPressed = 0x07, SevenPressed = 0x08, EightPressed = 0x09, NinePressed = 0x0a, ZeroPressed = 0x0b, // Unknown 0x0c EqualsPressed = 0x0d, BackspacePressed = 0x0e, TabPressed = 0x0f, // First row QPressed = 0x10, WPressed = 0x11, EPressed = 0x12, RPressed = 0x13, TPressed = 0x14, YPressed = 0x15, UPressed = 0x16, IPressed = 0x17, OPressed = 0x18, PPressed = 0x19, LBracePressed = 0x1a, RBracePressed = 0x1b, EnterPressed = 0x1c, LControlPressed = 0x1d, // Second row APressed = 0x1e, SPressed = 0x1f, DPressed = 0x20, FPressed = 0x21, GPressed = 0x22, HPressed = 0x23, JPressed = 0x24, KPressed = 0x25, LPressed = 0x26, SemicolonPressed = 0x27, SinglequotePressed = 0x28, BacktickPressed = 0x29, // Third row LShiftPressed = 0x2a, BackslashPressed = 0x2b, ZPressed = 0x2c, XPressed = 0x2d, CPressed = 0x2e, VPressed = 0x2f, BPressed = 0x30, NPressed = 0x31, MPressed = 0x32, CommaPressed = 0x33, DotPressed = 0x34, SlashPressed = 0x35, RShiftPressed = 0x36, KeypadMulPressed = 0x37, LAltPressed = 0x38, SpacePressed = 0x39, CapsLockPressed = 0x3a, // Function keys F1Pressed = 0x3b, F2Pressed = 0x3c, F3Pressed = 0x3d, F4Pressed = 0x3e, F5Pressed = 0x3f, F6Pressed = 0x40, F7Pressed = 0x41, F8Pressed = 0x42, F9Pressed = 0x43, F10Pressed = 0x44, // Keypad NumLockPressed = 0x45, ScrollLockPressed = 0x46, Keypad7Pressed = 0x47, Keypad8Pressed = 0x48, Keypad9Pressed = 0x49, KeypadMinusPressed = 0x4a, Keypad4Pressed = 0x4b, Keypad5Pressed = 0x4c, Keypad6Pressed = 0x4d, KeypadPlusPressed = 0x4e, Keypad1Pressed = 0x4f, Keypad2Pressed = 0x50, Keypad3Pressed = 0x51, Keypad0Pressed = 0x52, KeypadDotPressed = 0x53, // Unknown 0x54..0x56 F11Pressed = 0x57, F12Pressed = 0x58, _, pub fn to_ascii(self: @This()) ?u8 { return switch (self) { // Digits .OnePressed => '1', .TwoPressed => '2', .ThreePressed => '3', .FourPressed => '4', .FivePressed => '5', .SixPressed => '6', .SevenPressed => '7', .EightPressed => '8', .NinePressed => '9', .ZeroPressed => '0', // Letters .APressed => 'a', .BPressed => 'b', .CPressed => 'c', .DPressed => 'd', .EPressed => 'e', .FPressed => 'f', .GPressed => 'g', .HPressed => 'h', .IPressed => 'i', .JPressed => 'j', .KPressed => 'k', .LPressed => 'l', .MPressed => 'm', .NPressed => 'n', .OPressed => 'o', .PPressed => 'p', .QPressed => 'q', .RPressed => 'r', .SPressed => 's', .TPressed => 't', .UPressed => 'u', .VPressed => 'v', .WPressed => 'w', .XPressed => 'x', .YPressed => 'y', .ZPressed => 'z', .SpacePressed => ' ', .EnterPressed => '\n', else => null, }; } };
kernel/arch/x86/keyboard.zig
const std = @import("std"); const assert = std.debug.assert; const windows = std.os.windows; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const d3d12 = zwin32.d3d12; const kernel32 = windows.kernel32; const ole32 = windows.ole32; const shell32 = windows.shell32; const HMODULE = windows.HMODULE; const HRESULT = windows.HRESULT; const GUID = windows.GUID; const LPCSTR = windows.LPCSTR; const LPWSTR = windows.LPWSTR; const LPCWSTR = windows.LPCWSTR; const FARPROC = windows.FARPROC; const HWND = windows.HWND; const WINAPI = windows.WINAPI; const UINT32 = u32; const BOOL = windows.BOOL; const DWORD = windows.DWORD; const enable_pix = @import("build_options").enable_pix; pub const CAPTURE_TIMING = (1 << 0); pub const CAPTURE_GPU = (1 << 1); pub const CAPTURE_FUNCTION_SUMMARY = (1 << 2); pub const CAPTURE_FUNCTION_DETAILS = (1 << 3); pub const CAPTURE_CALLGRAPH = (1 << 4); pub const CAPTURE_INSTRUCTION_TRACE = (1 << 5); pub const CAPTURE_SYSTEM_MONITOR_COUNTERS = (1 << 6); pub const CAPTURE_VIDEO = (1 << 7); pub const CAPTURE_AUDIO = (1 << 8); pub const CAPTURE_RESERVED = (1 << 15); pub const CaptureStorage = enum(u32) { Memory = 0, }; pub const GpuCaptureParameters = extern struct { FileName: LPCWSTR, }; pub const TimingCaptureParameters = extern struct { FileName: LPCWSTR, MaximumToolingMemorySizeMb: UINT32, CaptureStorage: CaptureStorage, CaptureGpuTiming: BOOL, CaptureCallstacks: BOOL, CaptureCpuSamples: BOOL, CpuSamplesPerSecond: UINT32, CaptureFileIO: BOOL, CaptureVirtualAllocEvents: BOOL, CaptureHeapAllocEvents: BOOL, CaptureXMemEvents: BOOL, // Xbox only CapturePixMemEvents: BOOL, // Xbox only }; pub const CaptureParameters = extern union { gpu_capture_params: GpuCaptureParameters, timing_capture_params: TimingCaptureParameters, }; pub const loadGpuCapturerLibrary = if (enable_pix) impl.loadGpuCapturerLibrary else empty.loadGpuCapturerLibrary; pub const beginCapture = if (enable_pix) impl.beginCapture else empty.beginCapture; pub const endCapture = if (enable_pix) impl.endCapture else empty.endCapture; pub const setTargetWindow = if (enable_pix) impl.setTargetWindow else empty.setTargetWindow; pub const gpuCaptureNextFrames = if (enable_pix) impl.gpuCaptureNextFrames else empty.gpuCaptureNextFrames; pub const setMarker = if (enable_pix) impl.setMarker else empty.setMarker; pub const beginEvent = if (enable_pix) impl.beginEvent else empty.beginEvent; pub const endEvent = if (enable_pix) impl.endEvent else empty.endEvent; fn getFunctionPtr(func_name: LPCSTR) ?FARPROC { const module = kernel32.GetModuleHandleW(L("WinPixGpuCapturer.dll")); if (module == null) { return null; } const func = kernel32.GetProcAddress(module.?, func_name); if (func == null) { return null; } return func; } const EventType = enum(u64) { EndEvent = 0x000, BeginEvent_VarArgs = 0x001, BeginEvent_NoArgs = 0x002, SetMarker_VarArgs = 0x007, SetMarker_NoArgs = 0x008, EndEvent_OnContext = 0x010, BeginEvent_OnContext_VarArgs = 0x011, BeginEvent_OnContext_NoArgs = 0x012, SetMarker_OnContext_VarArgs = 0x017, SetMarker_OnContext_NoArgs = 0x018, }; const EventsGraphicsRecordSpaceQwords: u64 = 64; const EventsReservedTailSpaceQwords: u64 = 2; const EventsTimestampWriteMask: u64 = 0x00000FFFFFFFFFFF; const EventsTimestampBitShift: u64 = 20; const EventsTypeWriteMask: u64 = 0x00000000000003FF; const EventsTypeBitShift: u64 = 10; const WINPIX_EVENT_PIX3BLOB_VERSION: u32 = 2; const D3D12_EVENT_METADATA = WINPIX_EVENT_PIX3BLOB_VERSION; fn encodeEventInfo(timestamp: u64, event_type: EventType) u64 { const mask0 = (timestamp & EventsTimestampWriteMask) << @intCast(u6, EventsTimestampBitShift); const mask1 = (@enumToInt(event_type) & EventsTypeWriteMask) << @intCast(u6, EventsTypeBitShift); return mask0 | mask1; } const EventsStringAlignmentWriteMask: u64 = 0x000000000000000F; const EventsStringAlignmentBitShift: u64 = 60; const EventsStringCopyChunkSizeWriteMask: u64 = 0x000000000000001F; const EventsStringCopyChunkSizeBitShift: u64 = 55; const EventsStringIsANSIWriteMask: u64 = 0x0000000000000001; const EventsStringIsANSIBitShift: u64 = 54; const EventsStringIsShortcutWriteMask: u64 = 0x0000000000000001; const EventsStringIsShortcutBitShift: u64 = 53; fn encodeStringInfo(alignment: u64, copy_chunk_size: u64, is_ansi: bool, is_shortcut: bool) u64 { const mask0 = (alignment & EventsStringAlignmentWriteMask) << @intCast(u6, EventsStringAlignmentBitShift); const mask1 = (copy_chunk_size & EventsStringCopyChunkSizeWriteMask) << @intCast(u6, EventsStringCopyChunkSizeBitShift); const mask2 = (@boolToInt(is_ansi) & EventsStringIsANSIWriteMask) << @intCast(u6, EventsStringIsANSIBitShift); const mask3 = (@boolToInt(is_shortcut) & EventsStringIsShortcutWriteMask) << @intCast(u6, EventsStringIsShortcutBitShift); return mask0 | mask1 | mask2 | mask3; } const impl = struct { fn loadGpuCapturerLibrary() ?HMODULE { const module = kernel32.GetModuleHandleW(L("WinPixGpuCapturer.dll")); if (module != null) { return module; } const FOLDERID_ProgramFiles = GUID.parse("{905e63b6-c1bf-494e-b29c-65b732d3d21a}"); var program_files_path_ptr: LPWSTR = undefined; if (shell32.SHGetKnownFolderPath( &FOLDERID_ProgramFiles, windows.KF_FLAG_DEFAULT, null, &program_files_path_ptr, ) != windows.S_OK) { return null; } defer ole32.CoTaskMemFree(program_files_path_ptr); var alloc_buffer: [2048]u8 = undefined; var alloc_state = std.heap.FixedBufferAllocator.init(alloc_buffer[0..]); var alloc = alloc_state.allocator(); const program_files_path = std.unicode.utf16leToUtf8AllocZ( alloc, std.mem.span(program_files_path_ptr), ) catch unreachable; const pix_path = std.fs.path.joinZ( alloc, &[_][]const u8{ program_files_path, "Microsoft PIX" }, ) catch unreachable; const pix_dir = std.fs.openDirAbsoluteZ(pix_path, .{ .iterate = true }) catch return null; var newest_ver: f64 = 0.0; var newest_ver_name: [windows.MAX_PATH:0]u8 = undefined; var pix_dir_it = pix_dir.iterate(); while (pix_dir_it.next() catch return null) |entry| { if (entry.kind == .Directory) { const ver = std.fmt.parseFloat(f64, entry.name) catch continue; if (ver > newest_ver) { newest_ver = ver; std.mem.copy(u8, newest_ver_name[0..], entry.name); newest_ver_name[entry.name.len] = 0; } } } if (newest_ver == 0.0) { return null; } const dll_path = std.fs.path.joinZ( alloc, &[_][]const u8{ pix_path, std.mem.sliceTo(&newest_ver_name, 0), "WinPixGpuCapturer.dll" }, ) catch unreachable; const lib = std.DynLib.openZ(dll_path.ptr) catch return null; return lib.dll; } fn beginCapture(flags: DWORD, params: ?*const CaptureParameters) HRESULT { if (flags == CAPTURE_GPU) { const beginProgrammaticGpuCapture = @ptrCast( ?fn (?*const CaptureParameters) callconv(WINAPI) HRESULT, getFunctionPtr("BeginProgrammaticGpuCapture"), ); if (beginProgrammaticGpuCapture == null) { return windows.E_FAIL; } return beginProgrammaticGpuCapture.?(params); } else { return windows.E_NOTIMPL; } } fn endCapture() HRESULT { const endProgrammaticGpuCapture = @ptrCast( ?fn () callconv(WINAPI) HRESULT, getFunctionPtr("EndProgrammaticGpuCapture"), ); if (endProgrammaticGpuCapture == null) { return windows.E_FAIL; } return endProgrammaticGpuCapture.?(); } fn setTargetWindow(hwnd: HWND) HRESULT { const setGlobalTargetWindow = @ptrCast( ?fn (HWND) callconv(WINAPI) void, getFunctionPtr("SetGlobalTargetWindow"), ); if (setGlobalTargetWindow == null) { return windows.E_FAIL; } setGlobalTargetWindow.?(hwnd); return windows.S_OK; } fn gpuCaptureNextFrames(file_name: LPCWSTR, num_frames: UINT32) HRESULT { const captureNextFrame = @ptrCast( ?fn (LPCWSTR, UINT32) callconv(WINAPI) HRESULT, getFunctionPtr("CaptureNextFrame"), ); if (captureNextFrame == null) { return windows.E_FAIL; } return captureNextFrame.?(file_name, num_frames); } fn setMarkerOnContext(comptime Context: type, context: Context, name: []const u8) void { comptime { const T = @typeInfo(Context).Pointer.child; assert(@hasDecl(T, "SetMarker")); } assert(name.len > 0); const num_name_qwords: u32 = (@intCast(u32, name.len + 1) + 7) / 8; assert(num_name_qwords < (EventsGraphicsRecordSpaceQwords / 2)); var buffer: [EventsGraphicsRecordSpaceQwords]u64 = undefined; var dest: [*]u64 = &buffer; dest.* = encodeEventInfo(0, .SetMarker_NoArgs); dest += 1; dest.* = 0xff_ff_00_ff; // Color. dest += 1; dest.* = encodeStringInfo(0, 8, true, false); dest += 1; dest[num_name_qwords - 1] = 0; dest[num_name_qwords + 0] = 0; @memcpy(@ptrCast([*]u8, dest), name.ptr, name.len); context.SetMarker(D3D12_EVENT_METADATA, @ptrCast(*anyopaque, &buffer), (3 + num_name_qwords) * 8); } fn setMarker(target: anytype, name: []const u8) void { setMarkerOnContext(@TypeOf(target), target, name); } fn beginEventOnContext(comptime Context: type, context: Context, name: []const u8) void { comptime { const T = @typeInfo(Context).Pointer.child; assert(@hasDecl(T, "BeginEvent")); } assert(name.len > 0); const num_name_qwords: u32 = (@intCast(u32, name.len + 1) + 7) / 8; assert(num_name_qwords < (EventsGraphicsRecordSpaceQwords / 2)); var buffer: [EventsGraphicsRecordSpaceQwords]u64 = undefined; var dest: [*]u64 = &buffer; dest.* = encodeEventInfo(0, .BeginEvent_NoArgs); dest += 1; dest.* = 0xff_ff_00_ff; // Color. dest += 1; dest.* = encodeStringInfo(0, 8, true, false); dest += 1; dest[num_name_qwords - 1] = 0; dest[num_name_qwords + 0] = 0; @memcpy(@ptrCast([*]u8, dest), name.ptr, name.len); context.BeginEvent(D3D12_EVENT_METADATA, @ptrCast(*anyopaque, &buffer), (3 + num_name_qwords) * 8); } fn beginEvent(target: anytype, name: []const u8) void { beginEventOnContext(@TypeOf(target), target, name); } fn endEventOnContext(comptime Context: type, context: Context) void { comptime { const T = @typeInfo(Context).Pointer.child; assert(@hasDecl(T, "EndEvent")); } context.EndEvent(); } fn endEvent(target: anytype) void { endEventOnContext(@TypeOf(target), target); } }; const empty = struct { fn loadGpuCapturerLibrary() ?HMODULE { return null; } fn beginCapture(flags: DWORD, params: ?*const CaptureParameters) HRESULT { _ = flags; _ = params; return windows.S_OK; } fn endCapture() HRESULT { return windows.S_OK; } fn setTargetWindow(hwnd: HWND) HRESULT { _ = hwnd; return windows.S_OK; } fn gpuCaptureNextFrames(file_name: LPCWSTR, num_frames: UINT32) HRESULT { _ = file_name; _ = num_frames; return windows.S_OK; } fn setMarker(target: anytype, name: []const u8) void { _ = target; _ = name; } fn beginEvent(target: anytype, name: []const u8) void { _ = target; _ = name; } fn endEvent(target: anytype) void { _ = target; } };
libs/zpix/src/zpix.zig
const std = @import("std"); const string = []const u8; const range = @import("range").range; pub fn fmtByteCountIEC(alloc: std.mem.Allocator, b: u64) !string { return try reduceNumber(alloc, b, 1024, "B", "KMGTPEZY"); } pub fn reduceNumber(alloc: std.mem.Allocator, input: u64, comptime unit: u64, comptime base: string, comptime prefixes: string) !string { if (input < unit) { return std.fmt.allocPrint(alloc, "{d} {s}", .{ input, base }); } var div = unit; var exp: usize = 0; var n = input / unit; while (n >= unit) : (n /= unit) { div *= unit; exp += 1; } return try std.fmt.allocPrint(alloc, "{d:.3} {s}{s}", .{ intToFloat(input) / intToFloat(div), prefixes[exp .. exp + 1], base }); } pub fn intToFloat(n: u64) f64 { return @intToFloat(f64, n); } pub fn addSentinel(alloc: std.mem.Allocator, comptime T: type, input: []const T, comptime sentinel: T) ![:sentinel]const T { var list = try std.ArrayList(T).initCapacity(alloc, input.len + 1); try list.appendSlice(input); try list.append(sentinel); const str = list.toOwnedSlice(); return str[0 .. str.len - 1 :sentinel]; } const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; pub fn randomSlice(alloc: std.mem.Allocator, rand: *const std.rand.Random, comptime T: type, len: usize) ![]T { var buf = try alloc.alloc(T, len); var i: usize = 0; while (i < len) : (i += 1) { buf[i] = alphabet[rand.int(u8) % alphabet.len]; } return buf; } pub fn trimPrefix(in: string, prefix: string) string { if (std.mem.startsWith(u8, in, prefix)) { return in[prefix.len..]; } return in; } pub fn base64EncodeAlloc(alloc: std.mem.Allocator, input: string) !string { const base64 = std.base64.standard.Encoder; var buf = try alloc.alloc(u8, base64.calcSize(input.len)); return base64.encode(buf, input); } pub fn asciiUpper(alloc: std.mem.Allocator, input: string) ![]u8 { var buf = try alloc.dupe(u8, input); for (range(buf.len)) |_, i| { buf[i] = std.ascii.toUpper(buf[i]); } return buf; } pub fn doesFolderExist(dir: ?std.fs.Dir, fpath: []const u8) !bool { const file = (dir orelse std.fs.cwd()).openFile(fpath, .{}) catch |e| switch (e) { error.FileNotFound => return false, error.IsDir => return true, else => return e, }; defer file.close(); const s = try file.stat(); if (s.kind != .Directory) { return false; } return true; } pub fn doesFileExist(dir: ?std.fs.Dir, fpath: []const u8) !bool { const file = (dir orelse std.fs.cwd()).openFile(fpath, .{}) catch |e| switch (e) { error.FileNotFound => return false, error.IsDir => return true, else => return e, }; defer file.close(); return true; } pub fn sliceToInt(comptime T: type, comptime E: type, slice: []const E) !T { const a = @typeInfo(T).Int.bits; const b = @typeInfo(E).Int.bits; if (a < b * slice.len) return error.Overflow; var n: T = 0; for (slice) |item, i| { const shift = @intCast(std.math.Log2Int(T), b * (slice.len - 1 - i)); n = n | (@as(T, item) << shift); } return n; } pub fn FieldType(comptime T: type, comptime field: std.meta.FieldEnum(T)) type { inline for (std.meta.fields(T)) |item| { if (comptime std.mem.eql(u8, item.name, @tagName(field))) { return item.field_type; } } unreachable; } pub fn fileList(alloc: std.mem.Allocator, dir: std.fs.Dir) ![]string { var list = std.ArrayList(string).init(alloc); defer list.deinit(); var walk = try dir.walk(alloc); defer walk.deinit(); while (try walk.next()) |entry| { if (entry.kind != .File) continue; try list.append(try alloc.dupe(u8, entry.path)); } return list.toOwnedSlice(); } pub fn dirSize(alloc: std.mem.Allocator, dir: std.fs.Dir) !usize { var res: usize = 0; var walk = try dir.walk(alloc); defer walk.deinit(); while (try walk.next()) |entry| { if (entry.kind != .File) continue; res += try fileSize(dir, entry.path); } return res; } pub fn fileSize(dir: std.fs.Dir, sub_path: string) !usize { const f = try dir.openFile(sub_path, .{}); defer f.close(); const s = try f.stat(); return s.size; } pub const HashFn = enum { blake3, gimli, md5, sha1, sha224, sha256, sha384, sha512, sha3_224, sha3_256, sha3_384, sha3_512, }; pub fn hashFile(alloc: std.mem.Allocator, dir: std.fs.Dir, sub_path: string, comptime algo: HashFn) !string { const file = try dir.openFile(sub_path, .{}); defer file.close(); const hash = std.crypto.hash; const Algo = switch (algo) { .blake3 => hash.Blake3, .gimli => hash.Gimli, .md5 => hash.Md5, .sha1 => hash.Sha1, .sha224 => hash.sha2.Sha224, .sha256 => hash.sha2.Sha256, .sha384 => hash.sha2.Sha384, .sha512 => hash.sha2.Sha512, .sha3_224 => hash.sha3.Sha3_224, .sha3_256 => hash.sha3.Sha3_256, .sha3_384 => hash.sha3.Sha3_384, .sha3_512 => hash.sha3.Sha3_512, }; const h = &Algo.init(.{}); var out: [Algo.digest_length]u8 = undefined; var hw = HashWriter(Algo){ .h = h }; try pipe(file.reader(), hw.writer()); h.final(&out); var res: [Algo.digest_length * 2]u8 = undefined; var fbs = std.io.fixedBufferStream(&res); try std.fmt.format(fbs.writer(), "{x}", .{std.fmt.fmtSliceHexLower(&out)}); return try alloc.dupe(u8, &res); } fn HashWriter(comptime T: type) type { return struct { h: *T, const Self = @This(); pub const Error = error{}; pub const Writer = std.io.Writer(*Self, Error, write); fn write(self: *Self, bytes: []const u8) Error!usize { self.h.update(bytes); return bytes.len; } pub fn writer(self: *Self) Writer { return .{ .context = self }; } }; } pub fn pipe(reader_from: anytype, writer_to: anytype) !void { var buf: [std.mem.page_size]u8 = undefined; var fifo = std.fifo.LinearFifo(u8, .Slice).init(&buf); defer fifo.deinit(); try fifo.pump(reader_from, writer_to); }
src/lib.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const _chunk = @import("./chunk.zig"); const _obj = @import("./obj.zig"); const _token = @import("./token.zig"); const _vm = @import("./vm.zig"); const _value = @import("./value.zig"); const _scanner = @import("./scanner.zig"); const _disassembler = @import("./disassembler.zig"); const _utils = @import("./utils.zig"); const Config = @import("./config.zig").Config; const StringScanner = @import("./string_scanner.zig").StringScanner; const Value = _value.Value; const ValueType = _value.ValueType; const valueToHashable = _value.valueToHashable; const hashableToValue = _value.hashableToValue; const valueToString = _value.valueToString; const valueEql = _value.valueEql; const ObjType = _obj.ObjType; const Obj = _obj.Obj; const ObjNative = _obj.ObjNative; const ObjString = _obj.ObjString; const ObjUpValue = _obj.ObjUpValue; const ObjClosure = _obj.ObjClosure; const ObjFunction = _obj.ObjFunction; const ObjObjectInstance = _obj.ObjObjectInstance; const ObjObject = _obj.ObjObject; const ObjectDef = _obj.ObjectDef; const ObjList = _obj.ObjList; const ObjMap = _obj.ObjMap; const ObjEnum = _obj.ObjEnum; const ObjEnumInstance = _obj.ObjEnumInstance; const ObjTypeDef = _obj.ObjTypeDef; const PlaceholderDef = _obj.PlaceholderDef; const allocateObject = _obj.allocateObject; const allocateString = _obj.allocateString; const OpCode = _chunk.OpCode; const Chunk = _chunk.Chunk; const Token = _token.Token; const TokenType = _token.TokenType; const copyStringRaw = _obj.copyStringRaw; const Scanner = _scanner.Scanner; const VM = _vm.VM; const toNullTerminated = _utils.toNullTerminated; const NativeFn = _obj.NativeFn; const FunctionType = _obj.ObjFunction.FunctionType; extern fn dlerror() [*:0]u8; pub const CompileError = error{ Unrecoverable, Recoverable, }; pub const Local = struct { name: *ObjString, // TODO: do i need to mark those? type_def: *ObjTypeDef, depth: i32, is_captured: bool, constant: bool, }; pub const Global = struct { prefix: ?[]const u8 = null, name: *ObjString, // TODO: do i need to mark those? does it need to be an objstring? type_def: *ObjTypeDef, initialized: bool = false, exported: bool = false, export_alias: ?[]const u8 = null, hidden: bool = false, constant: bool, // When resolving a placeholder, the start of the resolution is the global // If `constant` is true, we can search for any `.Assignment` link and fail then. }; pub const UpValue = struct { index: u8, is_local: bool }; pub const ObjectCompiler = struct { name: Token, type_def: *ObjTypeDef, }; pub const ChunkCompiler = struct { const Self = @This(); enclosing: ?*ChunkCompiler = null, function: *ObjFunction, function_type: FunctionType, locals: [255]Local, local_count: u8 = 0, upvalues: [255]UpValue, scope_depth: u32 = 0, // Set at true in a `else` statement of scope_depth 2 return_counts: bool = false, // If false, `return` was omitted or within a conditionned block (if, loop, etc.) // We only count `return` emitted within the scope_depth 0 of the current function or unconditionned else statement return_emitted: bool = false, pub fn init(compiler: *Compiler, function_type: FunctionType, file_name: ?[]const u8, this: ?*ObjTypeDef) !void { const function_name: []const u8 = switch (function_type) { .EntryPoint => "main", .ScriptEntryPoint, .Script => file_name orelse "<script>", .Catch => "<catch>", else => compiler.parser.previous_token.?.lexeme, }; var function = try ObjFunction.init( compiler.allocator, try copyStringRaw(compiler.strings, compiler.allocator, function_name, false), ); // First chunk constant is the empty string _ = try function.chunk.addConstant(null, Value{ .Obj = (try copyStringRaw(compiler.strings, compiler.allocator, "", true // The substring we built is now owned by compiler )).toObj(), }); var self: Self = .{ .locals = [_]Local{undefined} ** 255, .upvalues = [_]UpValue{undefined} ** 255, .enclosing = compiler.current, .function_type = function_type, .function = try compiler.allocator.create(ObjFunction), }; self.function.* = function; compiler.current = try compiler.allocator.create(ChunkCompiler); compiler.current.?.* = self; if (function_type == .Extern) { return; } // First local is reserved for an eventual `this` or cli arguments var local: *Local = &compiler.current.?.locals[self.local_count]; compiler.current.?.local_count += 1; local.depth = 0; local.is_captured = false; switch (function_type) { .Method => { // `this` var type_def: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .ObjectInstance = this.? }; local.type_def = try compiler.getTypeDef( ObjTypeDef{ .def_type = .ObjectInstance, .resolved_type = type_def, }, ); }, .EntryPoint, .ScriptEntryPoint => { // `args` is [str] var list_def: ObjList.ListDef = ObjList.ListDef.init( compiler.allocator, try compiler.getTypeDef(.{ .def_type = .String }), ); var list_union: ObjTypeDef.TypeUnion = .{ .List = list_def }; local.type_def = try compiler.getTypeDef(ObjTypeDef{ .def_type = .List, .resolved_type = list_union }); }, else => { // TODO: do we actually need to reserve that space since we statically know if we need it? // nothing local.type_def = try compiler.getTypeDef(ObjTypeDef{ .def_type = .Void, }); }, } const name: []const u8 = switch (function_type) { .Method => "this", .EntryPoint => "$args", .ScriptEntryPoint => "args", else => "_", }; local.name = try copyStringRaw(compiler.strings, compiler.allocator, name, false); } pub fn getRootCompiler(self: *Self) *Self { return if (self.enclosing) |enclosing| enclosing.getRootCompiler() else self; } }; pub const ParserState = struct { const Self = @This(); current_token: ?Token = null, previous_token: ?Token = null, // Most of the time 1 token in advance is enough, but in some special cases we want to be able to look // some arbitrary number of token ahead ahead: std.ArrayList(Token), had_error: bool = false, panic_mode: bool = false, pub fn init(allocator: Allocator) Self { return .{ .ahead = std.ArrayList(Token).init(allocator), }; } pub fn deinit(self: *Self) void { self.ahead.deinit(); } }; pub const Compiler = struct { const Self = @This(); pub const BlockType = enum { While, Do, For, ForEach, Function, }; const Precedence = enum { None, Assignment, // =, -=, +=, *=, /= Is, // is Or, // or And, // and Xor, // xor Equality, // ==, != Comparison, // >=, <=, >, < NullCoalescing, // ?? Term, // +, - Shift, // >>, << Factor, // /, *, % Unary, // +, ++, -, --, ! Call, // call(), dot.ref, sub[script], optUnwrap? Primary, // literal, (grouped expression), super.ref, identifier, <type>[alist], <a, map>{...} }; const ParseFn = fn (compiler: *Compiler, can_assign: bool) anyerror!*ObjTypeDef; const InfixParseFn = fn (compiler: *Compiler, can_assign: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef; const ParseRule = struct { prefix: ?ParseFn, infix: ?InfixParseFn, precedence: Precedence, }; const rules = [_]ParseRule{ .{ .prefix = null, .infix = null, .precedence = .None }, // Pipe .{ .prefix = list, .infix = subscript, .precedence = .Call }, // LeftBracket .{ .prefix = null, .infix = null, .precedence = .None }, // RightBracket .{ .prefix = grouping, .infix = call, .precedence = .Call }, // LeftParen .{ .prefix = null, .infix = null, .precedence = .None }, // RightParen .{ .prefix = map, .infix = objectInit, .precedence = .Primary }, // LeftBrace .{ .prefix = null, .infix = null, .precedence = .None }, // RightBrace .{ .prefix = null, .infix = dot, .precedence = .Call }, // Dot .{ .prefix = null, .infix = null, .precedence = .None }, // Comma .{ .prefix = null, .infix = null, .precedence = .None }, // Semicolon .{ .prefix = null, .infix = binary, .precedence = .Comparison }, // Greater .{ .prefix = list, .infix = binary, .precedence = .Comparison }, // Less .{ .prefix = null, .infix = binary, .precedence = .Term }, // Plus .{ .prefix = unary, .infix = binary, .precedence = .Term }, // Minus .{ .prefix = null, .infix = binary, .precedence = .Factor }, // Star .{ .prefix = null, .infix = binary, .precedence = .Factor }, // Slash .{ .prefix = null, .infix = binary, .precedence = .Factor }, // Percent .{ .prefix = null, .infix = unwrap, .precedence = .Call }, // Question .{ .prefix = unary, .infix = forceUnwrap, .precedence = .Call }, // Bang .{ .prefix = null, .infix = null, .precedence = .None }, // Colon .{ .prefix = null, .infix = null, .precedence = .None }, // Equal .{ .prefix = null, .infix = binary, .precedence = .Equality }, // EqualEqual .{ .prefix = null, .infix = binary, .precedence = .Equality }, // BangEqual .{ .prefix = null, .infix = binary, .precedence = .Comparison }, // GreaterEqual .{ .prefix = null, .infix = binary, .precedence = .Comparison }, // LessEqual .{ .prefix = null, .infix = binary, .precedence = .NullCoalescing }, // QuestionQuestion .{ .prefix = null, .infix = null, .precedence = .None }, // PlusEqual .{ .prefix = null, .infix = null, .precedence = .None }, // MinusEqual .{ .prefix = null, .infix = null, .precedence = .None }, // StarEqual .{ .prefix = null, .infix = null, .precedence = .None }, // SlashEqual .{ .prefix = null, .infix = null, .precedence = .None }, // Increment .{ .prefix = null, .infix = null, .precedence = .None }, // Decrement .{ .prefix = null, .infix = null, .precedence = .None }, // Arrow .{ .prefix = literal, .infix = null, .precedence = .None }, // True .{ .prefix = literal, .infix = null, .precedence = .None }, // False .{ .prefix = literal, .infix = null, .precedence = .None }, // Null .{ .prefix = null, .infix = null, .precedence = .None }, // Str .{ .prefix = null, .infix = null, .precedence = .None }, // Num .{ .prefix = null, .infix = null, .precedence = .None }, // Type .{ .prefix = null, .infix = null, .precedence = .None }, // Bool .{ .prefix = null, .infix = null, .precedence = .None }, // Function .{ .prefix = null, .infix = null, .precedence = .None }, // ShiftRight .{ .prefix = null, .infix = null, .precedence = .None }, // ShiftLeft .{ .prefix = null, .infix = null, .precedence = .None }, // Xor .{ .prefix = null, .infix = or_, .precedence = .Or }, // Or .{ .prefix = null, .infix = and_, .precedence = .And }, // And .{ .prefix = null, .infix = null, .precedence = .None }, // Return .{ .prefix = null, .infix = null, .precedence = .None }, // If .{ .prefix = null, .infix = null, .precedence = .None }, // Else .{ .prefix = null, .infix = null, .precedence = .None }, // Do .{ .prefix = null, .infix = null, .precedence = .None }, // Until .{ .prefix = null, .infix = null, .precedence = .None }, // While .{ .prefix = null, .infix = null, .precedence = .None }, // For .{ .prefix = null, .infix = null, .precedence = .None }, // ForEach .{ .prefix = null, .infix = null, .precedence = .None }, // Switch .{ .prefix = null, .infix = null, .precedence = .None }, // Break .{ .prefix = null, .infix = null, .precedence = .None }, // Continue .{ .prefix = null, .infix = null, .precedence = .None }, // Default .{ .prefix = null, .infix = null, .precedence = .None }, // In .{ .prefix = null, .infix = is, .precedence = .Is }, // Is .{ .prefix = number, .infix = null, .precedence = .None }, // Number .{ .prefix = string, .infix = null, .precedence = .None }, // String .{ .prefix = variable, .infix = null, .precedence = .None }, // Identifier .{ .prefix = fun, .infix = null, .precedence = .None }, // Fun .{ .prefix = null, .infix = null, .precedence = .None }, // Object .{ .prefix = null, .infix = null, .precedence = .None }, // Class .{ .prefix = null, .infix = null, .precedence = .None }, // Enum .{ .prefix = null, .infix = null, .precedence = .None }, // Throw .{ .prefix = null, .infix = null, .precedence = .None }, // Catch .{ .prefix = null, .infix = null, .precedence = .None }, // Test .{ .prefix = null, .infix = null, .precedence = .None }, // Import .{ .prefix = null, .infix = null, .precedence = .None }, // Export .{ .prefix = null, .infix = null, .precedence = .None }, // Const .{ .prefix = null, .infix = null, .precedence = .None }, // Static .{ .prefix = super, .infix = null, .precedence = .None }, // Super .{ .prefix = super, .infix = null, .precedence = .None }, // From .{ .prefix = super, .infix = null, .precedence = .None }, // As .{ .prefix = super, .infix = null, .precedence = .None }, // Extern .{ .prefix = null, .infix = null, .precedence = .None }, // Eof .{ .prefix = null, .infix = null, .precedence = .None }, // Error .{ .prefix = null, .infix = null, .precedence = .None }, // Void }; pub const ScriptImport = struct { function: *ObjFunction, globals: std.ArrayList(Global), }; pub const OptJump = struct { jump: usize, precedence: Precedence, }; allocator: Allocator, scanner: ?Scanner = null, parser: ParserState, current: ?*ChunkCompiler = null, script_name: []const u8 = undefined, current_object: ?ObjectCompiler = null, globals: std.ArrayList(Global), // Interned typedef, find a better way of hashing a key (won't accept float so we use toString) type_defs: std.StringHashMap(*ObjTypeDef), // Interned strings, will be copied over to the vm strings: *std.StringHashMap(*ObjString), // If true the script is being imported imported: bool = false, // Cached imported functions imports: *std.StringHashMap(ScriptImport), // Jump to patch at end of current expression with a optional unwrapping in the middle of it opt_jumps: ?std.ArrayList(OptJump) = null, /// If true, will search for a `test` entry point instead of `main` testing: bool = false, test_count: u64 = 0, pub fn init(allocator: Allocator, strings: *std.StringHashMap(*ObjString), imports: *std.StringHashMap(ScriptImport), imported: bool) Self { return .{ .allocator = allocator, .parser = ParserState.init(allocator), .imports = imports, .globals = std.ArrayList(Global).init(allocator), .strings = strings, .type_defs = std.StringHashMap(*ObjTypeDef).init(allocator), .imported = imported, }; } pub fn deinit(self: *Self) void { self.parser.deinit(); self.globals.deinit(); // TODO: key are strings on the heap so free them, does this work? var it = self.type_defs.iterator(); while (it.next()) |kv| { self.allocator.free(kv.key_ptr.*); } self.type_defs.deinit(); } // TODO: walk the chain of compiler and destroy them in deinit inline fn currentCode(self: *Self) usize { return self.current.?.function.chunk.code.items.len; } pub fn compile(self: *Self, source: []const u8, file_name: []const u8, testing: bool) !?*ObjFunction { self.script_name = file_name; self.testing = testing; if (self.scanner != null) { self.scanner = null; } self.scanner = Scanner.init(source); defer self.scanner = null; try ChunkCompiler.init( self, if (self.imported) .Script else .ScriptEntryPoint, file_name, null, ); self.parser.had_error = false; self.parser.panic_mode = false; try self.advance(); // Import statement must be at top of script (mainly to avoid having to add another case to placeholders) while (!(try self.match(.Eof)) and try self.match(.Import)) { try self.importStatement(); } while (!(try self.match(.Eof))) { if (!(self.declarations() catch return null)) { return null; } } // Is there any placeholders left for (self.globals.items) |global| { if (global.type_def.def_type == .Placeholder) { try self.reportErrorAt(global.type_def.resolved_type.?.Placeholder.where, "Unknown variable."); } } var new_function: *ObjFunction = try self.endCompiler(); const function_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(self.strings, self.allocator, "$script", false), .return_type = try self.getTypeDef(.{ .def_type = .Void }), .parameters = std.StringArrayHashMap(*ObjTypeDef).init(self.allocator), .has_defaults = std.StringArrayHashMap(bool).init(self.allocator), .function_type = .ScriptEntryPoint, }; const type_def = ObjTypeDef.TypeUnion{ .Function = function_def }; new_function.type_def = try self.getTypeDef( .{ .def_type = .Function, .resolved_type = type_def, }, ); return if (self.parser.had_error) null else new_function; } pub fn getTypeDef(self: *Self, type_def: ObjTypeDef) !*ObjTypeDef { // Don't intern placeholders if (type_def.def_type == .Placeholder) { var type_def_ptr: *ObjTypeDef = try self.allocator.create(ObjTypeDef); type_def_ptr.* = type_def; return type_def_ptr; } var type_def_str: []const u8 = try type_def.toString(self.allocator); if (self.type_defs.get(type_def_str)) |type_def_ptr| { self.allocator.free(type_def_str); // If already in map, we don't need this string anymore return type_def_ptr; } var type_def_ptr: *ObjTypeDef = try self.allocator.create(ObjTypeDef); type_def_ptr.* = type_def; _ = try self.type_defs.put(type_def_str, type_def_ptr); return type_def_ptr; } pub inline fn getTypeDefByName(self: *Self, name: []const u8) ?*ObjTypeDef { return self.type_defs.get(name); } // Skip tokens until we reach something that resembles a new statement fn synchronize(self: *Self) !void { self.parser.panic_mode = false; while (self.parser.current_token.?.token_type != .Eof) : (try self.advance()) { if (self.parser.previous_token.?.token_type == .Semicolon) { return; } switch (self.parser.current_token.?.token_type) { .Class, .Object, .Enum, .Test, .Fun, .Const, .If, .While, .Do, .For, .ForEach, .Return, .Switch => return, else => {}, } } } fn report(self: *Self, token: Token, message: []const u8) !void { const lines: std.ArrayList([]const u8) = try self.scanner.?.getLines(self.allocator, if (token.line > 0) token.line - 1 else 0, 3); defer lines.deinit(); var report_line = std.ArrayList(u8).init(self.allocator); defer report_line.deinit(); var writer = report_line.writer(); try writer.print("\n", .{}); var l: usize = if (token.line > 0) token.line - 1 else 0; for (lines.items) |line| { if (l != token.line) { try writer.print("\u{001b}[2m", .{}); } var prefix_len: usize = report_line.items.len; try writer.print(" {: >5} |", .{l + 1}); prefix_len = report_line.items.len - prefix_len; try writer.print(" {s}\n\u{001b}[0m", .{line}); if (l == token.line) { try writer.writeByteNTimes(' ', token.column - 1 + prefix_len); try writer.print("^\n", .{}); } l += 1; } std.debug.print("{s}{s}:{}:{}: \u{001b}[31mError:\u{001b}[0m {s}\n", .{ report_line.items, self.current.?.getRootCompiler().function.name.string, token.line + 1, token.column + 1, message }); } fn reportErrorAt(self: *Self, token: Token, message: []const u8) !void { if (self.parser.panic_mode) { return; } self.parser.panic_mode = true; self.parser.had_error = true; try self.report(token, message); } pub fn reportErrorFmt(self: *Self, comptime fmt: []const u8, args: anytype) !void { var message = std.ArrayList(u8).init(self.allocator); defer message.deinit(); var writer = message.writer(); try writer.print(fmt, args); try self.reportError(message.items); } pub fn reportError(self: *Self, message: []const u8) !void { try self.reportErrorAt(self.parser.previous_token.?, message); } fn reportErrorAtCurrent(self: *Self, message: []const u8) !void { try self.reportErrorAt(self.parser.current_token.?, message); } fn reportTypeCheckAt(self: *Self, expected_type: *ObjTypeDef, actual_type: *ObjTypeDef, message: []const u8, at: Token) !void { var expected_str: []const u8 = try expected_type.toString(self.allocator); var actual_str: []const u8 = try actual_type.toString(self.allocator); var error_message: []u8 = try self.allocator.alloc(u8, expected_str.len + actual_str.len + 200); defer { self.allocator.free(error_message); self.allocator.free(expected_str); self.allocator.free(actual_str); } error_message = try std.fmt.bufPrint(error_message, "{s}: expected type `{s}`, got `{s}`", .{ message, expected_str, actual_str }); try self.reportErrorAt(at, error_message); } fn reportTypeCheck(self: *Self, expected_type: *ObjTypeDef, actual_type: *ObjTypeDef, message: []const u8) !void { try self.reportTypeCheckAt(expected_type, actual_type, message, self.parser.previous_token.?); } // When we encounter the missing declaration we replace it with the resolved type. // We then follow the chain of placeholders to see if their assumptions were correct. // If not we raise a compile error. pub fn resolvePlaceholder(self: *Self, placeholder: *ObjTypeDef, resolved_type: *ObjTypeDef, constant: bool) anyerror!void { assert(placeholder.def_type == .Placeholder); if (resolved_type.def_type == .Placeholder) { if (Config.debug) { std.debug.print("Attempted to resolve placeholder with placeholder.", .{}); } return; } // If two placeholders, see if they can be merged if (resolved_type.def_type == .Placeholder) { if (!resolved_type.resolved_type.?.Placeholder.eql(placeholder.resolved_type.?.Placeholder)) { try self.reportErrorAt(resolved_type.resolved_type.?.Placeholder.where, "[Incompatible assumptions] Type check error"); } else { // TODO: do we care that two equivalent placeholder exist? try resolved_type.resolved_type.?.Placeholder.enrich(&placeholder.resolved_type.?.Placeholder); } return; } var placeholder_def: PlaceholderDef = placeholder.resolved_type.?.Placeholder; if (placeholder_def.resolved_type) |assumed_type| { if (!assumed_type.eql(resolved_type)) { try self.reportTypeCheckAt(resolved_type, assumed_type, "Type check error", placeholder_def.where); return; } } if (placeholder_def.resolved_def_type) |assumed_def_type| { if (assumed_def_type != resolved_type.def_type) { try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: type check error."); return; } } if (placeholder_def.callable) |call_assumption| { if (call_assumption and resolved_type.def_type != .Object and resolved_type.def_type != .Function) { // TODO: better error messages on placeholder stuff try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: can't be called."); return; } } if (placeholder_def.subscriptable) |subscript_assumption| { if (subscript_assumption and resolved_type.def_type != .List and resolved_type.def_type != .Map) { // TODO: better error messages on placeholder stuff try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: can't be subscripted."); return; } } if (placeholder_def.field_accessible) |field_accessible_assumption| { if (field_accessible_assumption and resolved_type.def_type != .ObjectInstance and resolved_type.def_type != .Enum and resolved_type.def_type != .EnumInstance) { // TODO: better error messages on placeholder stuff try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: has no fields."); return; } } if (placeholder_def.resolved_parameters) |assumed_argument_list| { var parameters: std.StringArrayHashMap(*ObjTypeDef) = undefined; if (resolved_type.def_type == .Function) { parameters = resolved_type.resolved_type.?.Function.parameters; } else { unreachable; } if (assumed_argument_list.count() != parameters.count()) { try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: arity not matching."); return; } var it = assumed_argument_list.iterator(); var resolved_parameter_keys: [][]const u8 = parameters.keys(); while (it.next()) |kv| { // Is there a matching argument with the same type? if (parameters.get(kv.key_ptr.*)) |matching_arg| { if (!matching_arg.eql(kv.value_ptr.*)) { try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: argument not matching."); return; } } else if (mem.eql(u8, kv.key_ptr.*, "{{first}}")) { // Is the first argument argument matching if (!parameters.get(resolved_parameter_keys[0]).?.eql(kv.value_ptr.*)) { try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: argument not matching."); return; } } else { // That argument doesn't exists try self.reportErrorAt(placeholder_def.where, "[Bad assumption]: argument does not exists."); } } } // Now walk the chain of placeholders and see if they hold up for (placeholder_def.children.items) |child| { var child_placeholder: PlaceholderDef = child.resolved_type.?.Placeholder; assert(child_placeholder.parent != null); assert(child_placeholder.parent_relation != null); switch (child_placeholder.parent_relation.?) { .Call => { // Can we call the parent? if (resolved_type.def_type != .Object and resolved_type.def_type != .Function) { try self.reportErrorAt(placeholder_def.where, "Can't be called"); return; } // Is the child types resolvable with parent return type if (resolved_type.def_type == .Object) { var instance_union: ObjTypeDef.TypeUnion = .{ .ObjectInstance = resolved_type }; var instance_type: *ObjTypeDef = try self.getTypeDef(.{ .def_type = .ObjectInstance, .resolved_type = instance_union, }); try self.resolvePlaceholder(child, instance_type, false); } else if (resolved_type.def_type != .Function) { try self.resolvePlaceholder(child, resolved_type.resolved_type.?.Function.return_type, false); } }, .Subscript => { if (resolved_type.def_type == .List) { try self.resolvePlaceholder(child, resolved_type.resolved_type.?.List.item_type, false); } else if (resolved_type.def_type == .Map) { try self.resolvePlaceholder(child, resolved_type.resolved_type.?.Map.value_type, false); } else { unreachable; } }, .Key => { if (resolved_type.def_type == .Map) { try self.resolvePlaceholder(child, resolved_type.resolved_type.?.Map.key_type, false); } else { unreachable; } }, .FieldAccess => { switch (resolved_type.def_type) { .ObjectInstance => { // We can't create a field access placeholder without a name assert(child_placeholder.name != null); var object_def: ObjObject.ObjectDef = resolved_type.resolved_type.?.ObjectInstance.resolved_type.?.Object; // Search for a field matching the placeholder var resolved_as_field: bool = false; if (object_def.fields.get(child_placeholder.name.?.string)) |field| { try self.resolvePlaceholder(child, field, false); resolved_as_field = true; } // Search for a method matching the placeholder if (!resolved_as_field) { if (object_def.methods.get(child_placeholder.name.?.string)) |method_def| { try self.resolvePlaceholder(child, method_def, true); } } }, .Enum => { // We can't create a field access placeholder without a name assert(child_placeholder.name != null); var enum_def: ObjEnum.EnumDef = resolved_type.resolved_type.?.Enum; // Search for a case matching the placeholder for (enum_def.cases.items) |case| { if (mem.eql(u8, case, child_placeholder.name.?.string)) { var enum_instance_def: ObjTypeDef.TypeUnion = .{ .EnumInstance = resolved_type }; try self.resolvePlaceholder(child, try self.getTypeDef(.{ .def_type = .EnumInstance, .resolved_type = enum_instance_def, }), true); break; } } }, else => try self.reportErrorAt(placeholder_def.where, "Doesn't support field access"), } }, .Assignment => { if (constant) { try self.reportErrorAt(placeholder_def.where, "Is constant."); return; } // Assignment relation from a once Placeholder and now Class/Object/Enum is creating an instance // TODO: but does this allow `AClass = something;` ? var child_type: *ObjTypeDef = (try self.toInstance(resolved_type)) orelse resolved_type; // Is child type matching the parent? try self.resolvePlaceholder(child, child_type, false); }, } } // Overwrite placeholder with resolved_type placeholder.* = resolved_type.*; // TODO: should resolved_type be freed? // TODO: does this work with vm.type_defs? (i guess not) } fn toInstance(self: *Self, instantiable: *ObjTypeDef) !?*ObjTypeDef { return switch (instantiable.def_type) { .Object => obj_instance: { var instance_type: ObjTypeDef.TypeUnion = .{ .ObjectInstance = instantiable }; break :obj_instance try self.getTypeDef(ObjTypeDef{ .def_type = .ObjectInstance, .resolved_type = instance_type, }); }, .Enum => enum_instance: { var instance_type: ObjTypeDef.TypeUnion = .{ .EnumInstance = instantiable }; break :enum_instance try self.getTypeDef(ObjTypeDef{ .def_type = .EnumInstance, .resolved_type = instance_type, }); }, else => null, }; } pub fn advance(self: *Self) !void { self.parser.previous_token = self.parser.current_token; while (true) { self.parser.current_token = if (self.parser.ahead.items.len > 0) self.parser.ahead.swapRemove(0) else try self.scanner.?.scanToken(); if (self.parser.current_token.?.token_type != .Error) { break; } try self.reportErrorAtCurrent(self.parser.current_token.?.literal_string orelse "Unknown error."); } } pub fn consume(self: *Self, token_type: TokenType, message: []const u8) !void { if (self.parser.current_token.?.token_type == token_type) { try self.advance(); return; } try self.reportErrorAtCurrent(message); } fn check(self: *Self, token_type: TokenType) bool { return self.parser.current_token.?.token_type == token_type; } fn checkAhead(self: *Self, token_type: TokenType, n: u32) !bool { while (n + 1 > self.parser.ahead.items.len) { while (true) { const token = try self.scanner.?.scanToken(); try self.parser.ahead.append(token); if (token.token_type != .Error) { break; } try self.reportErrorAtCurrent(token.literal_string orelse "Unknown error."); } } return self.parser.ahead.items[n].token_type == token_type; } fn match(self: *Self, token_type: TokenType) !bool { if (!self.check(token_type)) { return false; } try self.advance(); return true; } fn endCompiler(self: *Self) !*ObjFunction { if (self.current.?.function_type != .Extern) { // If .Script, search for exported globals and return them in a map if (self.current.?.function_type == .Script or self.current.?.function_type == .ScriptEntryPoint) { // If top level, search `main` or `test` function(s) and call them // Then put any exported globals on the stack if (!self.testing and self.current.?.function_type == .ScriptEntryPoint) { var found_main: bool = false; for (self.globals.items) |global, index| { if (mem.eql(u8, global.name.string, "main") and !global.hidden and global.prefix == null) { found_main = true; try self.emitCodeArg(.OP_GET_GLOBAL, @intCast(u24, index)); try self.emitCodeArg(.OP_GET_LOCAL, 1); // cli args are always local 0 try self.emitCodeArgs(.OP_CALL, 1, 0); break; } } } else if (self.testing) { // Create an entry point wich runs all `test` for (self.globals.items) |global, index| { if (global.name.string.len > 5 and mem.eql(u8, global.name.string[0..5], "$test") and !global.hidden and global.prefix == null) { try self.emitCodeArg(.OP_GET_GLOBAL, @intCast(u24, index)); try self.emitCodeArgs(.OP_CALL, 0, 0); } } } // If we're being imported, put all globals on the stack if (self.imported) { var exported_count: usize = 0; for (self.globals.items) |_, index| { exported_count += 1; if (exported_count > 16777215) { try self.reportError("Can't export more than 16777215 values."); break; } try self.emitCodeArg(.OP_GET_GLOBAL, @intCast(u24, index)); } try self.emitCodeArg(.OP_EXPORT, @intCast(u24, exported_count)); } else { try self.emitOpCode(.OP_VOID); try self.emitOpCode(.OP_RETURN); } } else if (self.current.?.function.type_def.resolved_type.?.Function.return_type.def_type == .Void and !self.current.?.return_emitted) { // TODO: detect if some branches of the function body miss a return statement try self.emitReturn(); } else if (!self.current.?.return_emitted) { try self.reportError("Missing `return` statement."); } } var current_function: *ObjFunction = self.current.?.function; self.current = self.current.?.enclosing; // std.debug.print("\n\n==========================", .{}); // try disassembler.disassembleChunk( // &function.chunk, // function.name.string // ); // std.debug.print("\n\n==========================", .{}); return current_function; } inline fn beginScope(self: *Self) void { self.current.?.scope_depth += 1; } fn endScope(self: *Self) !void { var current: *ChunkCompiler = self.current.?; current.scope_depth -= 1; while (current.local_count > 0 and current.locals[current.local_count - 1].depth > current.scope_depth) { if (current.locals[current.local_count - 1].is_captured) { try self.emitOpCode(.OP_CLOSE_UPVALUE); } else { try self.emitOpCode(.OP_POP); } current.local_count -= 1; } } // BYTE EMITTING fn emit(self: *Self, code: u32) !void { try self.current.?.function.chunk.write(code, self.parser.previous_token.?.line); } fn emitTwo(self: *Self, a: u8, b: u24) !void { try self.emit((@intCast(u32, a) << 24) | @intCast(u32, b)); } // OP_ | arg pub fn emitCodeArg(self: *Self, code: OpCode, arg: u24) !void { try self.emit((@intCast(u32, @enumToInt(code)) << 24) | @intCast(u32, arg)); } // OP_ | a | b fn emitCodeArgs(self: *Self, code: OpCode, a: u8, b: u16) !void { try self.emit((@intCast(u32, @enumToInt(code)) << 24) | (@intCast(u32, a) << 16) | (@intCast(u32, b))); } pub fn emitOpCode(self: *Self, code: OpCode) !void { try self.emit(@intCast(u32, @intCast(u32, @enumToInt(code)) << 24)); } fn emitLoop(self: *Self, loop_start: usize) !void { const offset: usize = self.currentCode() - loop_start + 1; if (offset > 16777215) { try self.reportError("Loop body to large."); } try self.emitCodeArg(.OP_LOOP, @intCast(u24, offset)); } fn emitJump(self: *Self, instruction: OpCode) !usize { try self.emitCodeArg(instruction, 0xffffff); return self.currentCode() - 1; } fn patchJumpOrLoop(self: *Self, offset: usize, loop_start: ?usize) !void { const original: u32 = self.current.?.function.chunk.code.items[offset]; const instruction: u8 = @intCast(u8, original >> 24); const code: OpCode = @intToEnum(OpCode, instruction); if (code == .OP_LOOP) { // Patching a continue statement assert(loop_start != null); const loop_offset: usize = offset - loop_start.? + 1; if (loop_offset > 16777215) { try self.reportError("Loop body to large."); } self.current.?.function.chunk.code.items[offset] = (@intCast(u32, instruction) << 24) | @intCast(u32, loop_offset); } else { // Patching a break statement try self.patchJump(offset); } } fn patchJump(self: *Self, offset: usize) !void { const jump: usize = self.currentCode() - offset - 1; if (jump > 16777215) { try self.reportError("Jump to large."); } const original: u32 = self.current.?.function.chunk.code.items[offset]; const instruction: u8 = @intCast(u8, original >> 24); self.current.?.function.chunk.code.items[offset] = (@intCast(u32, instruction) << 24) | @intCast(u32, jump); } fn emitList(self: *Self) !usize { try self.emitCodeArg(.OP_LIST, 0xffffff); return self.currentCode() - 1; } fn patchList(self: *Self, offset: usize, constant: u24) !void { const original: u32 = self.current.?.function.chunk.code.items[offset]; const instruction: u8 = @intCast(u8, original >> 24); self.current.?.function.chunk.code.items[offset] = (@intCast(u32, instruction) << 24) | @intCast(u32, constant); } fn emitMap(self: *Self) !usize { try self.emitCodeArg(.OP_MAP, 0xffffff); return self.currentCode() - 1; } fn patchMap(self: *Self, offset: usize, map_type_constant: u24) !void { const original: u32 = self.current.?.function.chunk.code.items[offset]; const instruction: u8 = @intCast(u8, original >> 24); self.current.?.function.chunk.code.items[offset] = (@intCast(u32, instruction) << 24) | @intCast(u32, map_type_constant); } fn emitReturn(self: *Self) !void { try self.emitOpCode(.OP_VOID); try self.emitOpCode(.OP_RETURN); } // AST NODES // TODO: minimize code redundancy between declaration and declarationOrStatement // TODO: varDeclaration here can be an issue if they produce placeholders because opcode can be out of order // We can only allow constant expressions: `str hello = "hello";` but not `num hello = aglobal + 12;` fn declarations(self: *Self) !bool { if (try self.match(.Extern)) { try self.funDeclaration(); } else { const constant: bool = try self.match(.Const); if (!constant and try self.match(.Object)) { try self.objectDeclaration(false); } else if (!constant and try self.match(.Class)) { try self.objectDeclaration(true); } else if (!constant and try self.match(.Enum)) { try self.enumDeclaration(); } else if (!constant and try self.match(.Fun)) { try self.funDeclaration(); } else if (try self.match(.Str)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .String }), false, constant, ); } else if (try self.match(.Num)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Number }), false, constant, ); } else if (try self.match(.Bool)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Bool }), false, constant, ); } else if (try self.match(.Type)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Type }), false, constant, ); } else if (try self.match(.LeftBracket)) { try self.listDeclaration(constant); } else if (try self.match(.LeftBrace)) { try self.mapDeclaration(constant); } else if (!constant and try self.match(.Test)) { try self.testStatement(); } else if (try self.match(.Function)) { try self.varDeclaration(try self.functionType(), false, constant); // In the declaractive space, starting with an identifier is always a varDeclaration with a user type } else if (try self.match(.Identifier)) { var user_type_name: Token = self.parser.previous_token.?.clone(); var var_type: ?*ObjTypeDef = null; // Search for a global with that name if (try self.resolveGlobal(null, user_type_name)) |slot| { var_type = self.globals.items[slot].type_def; } // No placeholder at top-level if (var_type == null) { try self.reportError("Unknown identifier"); } try self.varDeclaration(var_type.?, false, constant); } else if (!constant and try self.match(.Export)) { try self.exportStatement(); } else { try self.reportError("No declaration or statement."); return false; } } if (self.parser.panic_mode) { try self.synchronize(); } return true; } fn declarationOrStatement(self: *Self, block_type: BlockType) !?std.ArrayList(usize) { var hanging: bool = false; const constant: bool = try self.match(.Const); // Things we can match with the first token if (!constant and try self.match(.Fun)) { try self.funDeclaration(); return null; } else if (try self.match(.Str)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .String }), false, constant, ); return null; } else if (try self.match(.Num)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Number }), false, constant, ); return null; } else if (try self.match(.Bool)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Bool }), false, constant, ); return null; } else if (try self.match(.Type)) { try self.varDeclaration( try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Type }), false, constant, ); return null; } else if (try self.match(.LeftBracket)) { try self.listDeclaration(constant); return null; } else if (try self.match(.LeftBrace)) { try self.mapDeclaration(constant); return null; } else if (try self.match(.Function)) { try self.varDeclaration(try self.functionType(), false, constant); return null; } else if (try self.match(.Identifier)) { // A declaration with a class/object/enum type is one of those: // - Type variable // - Type? variable // - prefix.Type variable // - prefix.Type? variable // As of now this is the only place where we need to check more than one token ahead if (self.check(.Identifier) or (self.check(.Dot) and try self.checkAhead(.Identifier, 0) and try self.checkAhead(.Identifier, 1)) or (self.check(.Dot) and try self.checkAhead(.Identifier, 0) and try self.checkAhead(.Question, 1) and try self.checkAhead(.Identifier, 2)) or (self.check(.Question) and try self.checkAhead(.Identifier, 0))) { var user_type_name: Token = self.parser.previous_token.?.clone(); var var_type: ?*ObjTypeDef = null; // Search for a global with that name if (try self.resolveGlobal(null, user_type_name)) |slot| { var_type = self.globals.items[slot].type_def; } // If none found, create a placeholder if (var_type == null) { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; placeholder_resolved_type.Placeholder.name = try copyStringRaw( self.strings, self.allocator, user_type_name.lexeme, false, ); var_type = try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }, ); _ = try self.declarePlaceholder(user_type_name, var_type); } else { try self.varDeclaration(var_type.?, false, constant); } return null; } else { hanging = true; } } if (constant) { try self.reportError("`const` not allowed here."); } return try self.statement(hanging, block_type); } // When a break statement, will return index of jump to patch fn statement(self: *Self, hanging: bool, block_type: BlockType) !?std.ArrayList(usize) { if (try self.match(.If)) { assert(!hanging); return try self.ifStatement(block_type); } else if (try self.match(.For)) { assert(!hanging); try self.forStatement(); } else if (try self.match(.ForEach)) { assert(!hanging); try self.forEachStatement(); } else if (try self.match(.While)) { assert(!hanging); try self.whileStatement(); } else if (try self.match(.Do)) { assert(!hanging); try self.doUntilStatement(); } else if (try self.match(.Return)) { assert(!hanging); try self.returnStatement(); } else if (try self.match(.Break)) { assert(!hanging); var breaks: std.ArrayList(usize) = std.ArrayList(usize).init(self.allocator); try breaks.append(try self.breakStatement(block_type)); return breaks; } else if (try self.match(.Continue)) { assert(!hanging); var continues: std.ArrayList(usize) = std.ArrayList(usize).init(self.allocator); try continues.append(try self.continueStatement(block_type)); return continues; } else if (try self.match(.Throw)) { // For now we don't care about the type. Later if we have `Error` type of data, we'll type check this _ = try self.expression(false); try self.consume(.Semicolon, "Expected `;` after `throw` expression."); try self.emitOpCode(.OP_THROW); } else { try self.expressionStatement(hanging); } return null; } fn returnStatement(self: *Self) !void { if (self.current.?.scope_depth == 0) { try self.reportError("Can't use `return` at top-level."); } else if (self.current.?.scope_depth == 1 or self.current.?.return_counts) { // scope_depth at 1 == "root" level of the function self.current.?.return_emitted = true; } if (try self.match(.Semicolon)) { try self.emitReturn(); } else { var return_type: *ObjTypeDef = try self.expression(false); if (!self.current.?.function.type_def.resolved_type.?.Function.return_type.eql(return_type)) { try self.reportTypeCheck( self.current.?.function.type_def.resolved_type.?.Function.return_type, return_type, "Return value", ); } try self.consume(.Semicolon, "Expected `;` after return value."); try self.emitOpCode(.OP_RETURN); } } fn parseTypeDef(self: *Self) anyerror!*ObjTypeDef { if (try self.match(.Str)) { return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .String }); } else if (try self.match(.Type)) { return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Type }); } else if (try self.match(.Void)) { return try self.getTypeDef(.{ .optional = false, .def_type = .Void }); } else if (try self.match(.Num)) { return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Number }); } else if (try self.match(.Bool)) { return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Bool }); } else if (try self.match(.Type)) { return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Type }); } else if (try self.match(.LeftBracket)) { var item_type: *ObjTypeDef = try self.parseTypeDef(); var list_def = ObjList.ListDef.init(self.allocator, item_type); try self.consume(.RightBracket, "Expected `]` to end list type."); const resolved_type: ObjTypeDef.TypeUnion = .{ .List = list_def }; return try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .List, .resolved_type = resolved_type, }, ); } else if (try self.match(.LeftBrace)) { var key_type: *ObjTypeDef = try self.parseTypeDef(); try self.consume(.Comma, "Expected `,` after map key type."); var value_type: *ObjTypeDef = try self.parseTypeDef(); try self.consume(.RightBrace, "Expected `}}` to end map type."); const map_def = ObjMap.MapDef.init(self.allocator, key_type, value_type); const resolved_type: ObjTypeDef.TypeUnion = .{ .Map = map_def }; return try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Map, .resolved_type = resolved_type, }, ); } else if (try self.match(.Function)) { return try self.functionType(); } else if ((try self.match(.Identifier))) { return self.globals.items[try self.parseUserType()].type_def; } else { try self.reportErrorAtCurrent("Expected type definition."); return try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .Void }); } } fn parseUserType(self: *Self) !usize { var user_type_name: Token = self.parser.previous_token.?.clone(); var var_type: ?*ObjTypeDef = null; var global_slot: ?usize = null; // Search for a global with that name if (try self.resolveGlobal(null, user_type_name)) |slot| { var_type = self.globals.items[slot].type_def; global_slot = slot; } // If none found, create a placeholder if (var_type == null) { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; placeholder_resolved_type.Placeholder.name = try copyStringRaw( self.strings, self.allocator, user_type_name.lexeme, false, ); var_type = try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }, ); global_slot = try self.declarePlaceholder(user_type_name, var_type.?); } return global_slot.?; } inline fn getRule(token: TokenType) ParseRule { return rules[@enumToInt(token)]; } fn parsePrecedence(self: *Self, precedence: Precedence, hanging: bool) !*ObjTypeDef { // If hanging is true, that means we already read the start of the expression if (!hanging) { _ = try self.advance(); } var prefixRule: ?ParseFn = getRule(self.parser.previous_token.?.token_type).prefix; if (prefixRule == null) { try self.reportError("Expected expression."); // TODO: find a way to continue or catch that error return CompileError.Unrecoverable; } var canAssign: bool = @enumToInt(precedence) <= @enumToInt(Precedence.Assignment); var parsed_type: *ObjTypeDef = try prefixRule.?(self, canAssign); while (@enumToInt(getRule(self.parser.current_token.?.token_type).precedence) >= @enumToInt(precedence)) { // Patch optional jumps if (self.opt_jumps) |jumps| { assert(jumps.items.len > 0); var first_jump: OptJump = jumps.items[0]; if (@enumToInt(getRule(self.parser.current_token.?.token_type).precedence) < @enumToInt(first_jump.precedence)) { // Hope over pop if actual value const njump: usize = try self.emitJump(.OP_JUMP); for (jumps.items) |jump| { try self.patchJump(jump.jump); } // If aborted by a null optional, will result in null on the stackl try self.emitOpCode(.OP_POP); try self.patchJump(njump); jumps.deinit(); self.opt_jumps = null; } } _ = try self.advance(); var infixRule: InfixParseFn = getRule(self.parser.previous_token.?.token_type).infix.?; parsed_type = try infixRule(self, canAssign, parsed_type); } if (canAssign and (try self.match(.Equal))) { try self.reportError("Invalid assignment target."); } return parsed_type; } pub fn expression(self: *Self, hanging: bool) !*ObjTypeDef { return try self.parsePrecedence(.Assignment, hanging); } // Returns a list of break jumps to patch fn block(self: *Self, block_type: BlockType) anyerror!std.ArrayList(usize) { var breaks = std.ArrayList(usize).init(self.allocator); while (!self.check(.RightBrace) and !self.check(.Eof)) { if (try self.declarationOrStatement(block_type)) |jumps| { try breaks.appendSlice(jumps.items); jumps.deinit(); } } try self.consume(.RightBrace, "Expected `}}` after block."); return breaks; } fn functionType(self: *Self) !*ObjTypeDef { assert(self.parser.previous_token.?.token_type == .Function); try self.consume(.LeftParen, "Expected `(` after function name."); var parameters: std.StringArrayHashMap(*ObjTypeDef) = std.StringArrayHashMap(*ObjTypeDef).init(self.allocator); var arity: usize = 0; if (!self.check(.RightParen)) { while (true) { arity += 1; if (arity > 255) { try self.reportErrorAtCurrent("Can't have more than 255 parameters."); } var param_type: *ObjTypeDef = try self.parseTypeDef(); var param_name: []const u8 = if (try self.match(.Identifier)) self.parser.previous_token.?.lexeme else "_"; try parameters.put(param_name, param_type); if (!try self.match(.Comma)) break; } } try self.consume(.RightParen, "Expected `)` after function parameters."); var return_type: *ObjTypeDef = undefined; if (try self.match(.Greater)) { return_type = try self.parseTypeDef(); } else { return_type = try self.getTypeDef(.{ .def_type = .Void }); } var function_typedef: ObjTypeDef = .{ .def_type = .Function, }; var function_def: ObjFunction.FunctionDef = .{ .name = try copyStringRaw(self.strings, self.allocator, "anonymous", false), .return_type = try self.getTypeDef(return_type.toInstance()), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(self.allocator), .function_type = .Anonymous, }; var function_resolved_type: ObjTypeDef.TypeUnion = .{ .Function = function_def }; function_typedef.resolved_type = function_resolved_type; return try self.getTypeDef(function_typedef); } fn super(self: *Self, _: bool) anyerror!*ObjTypeDef { if (self.current_object) |object| { if (object.type_def.resolved_type.?.Object.super) |obj_super| { if (obj_super.def_type == .Placeholder) { // TODO: new link? unreachable; } try self.consume(.Dot, "Expected `.` after `super`."); try self.consume(.Identifier, "Expected superclass method name."); const name_constant: u24 = try self.identifierConstant(self.parser.previous_token.?.lexeme); var super_method: ?*ObjTypeDef = obj_super.resolved_type.?.Object.methods.get(self.parser.previous_token.?.lexeme); if (super_method == null) { try self.reportErrorFmt("Method `{s}` doesn't exists.", .{self.parser.previous_token.?.lexeme}); } _ = try self.namedVariable(Token{ .token_type = .Identifier, .lexeme = "this", .line = 0, .column = 0, }, false); if (try self.match(.LeftParen)) { const arg_count: u8 = try self.argumentList(super_method.?.resolved_type.?.Function.parameters, super_method.?.resolved_type.?.Function.has_defaults); _ = try self.namedVariable(Token{ .token_type = .Identifier, .lexeme = "super", .line = 0, .column = 0, }, false); try self.emitCodeArg(.OP_SUPER_INVOKE, name_constant); try self.emitTwo(arg_count, try self.inlineCatch(super_method.?.resolved_type.?.Function.return_type)); return super_method.?.resolved_type.?.Function.return_type; } else { _ = try self.namedVariable(Token{ .token_type = .Identifier, .lexeme = "super", .line = 0, .column = 0, }, false); try self.emitCodeArg(.OP_GET_SUPER, name_constant); return super_method.?; } } else { try self.reportError("Can't use `super` in a class with no superclass."); return object.type_def; } } else { try self.reportError("Can't use `super` outside of a class."); return try self.getTypeDef(.{ .def_type = .Void, .optional = false, }); } } fn inlineCatch(self: *Self, return_type: *ObjTypeDef) !u8 { if (try self.match(.Catch)) { // Catch closures if (try self.match(.LeftBrace)) { var catch_count: u8 = 0; while (!self.check(.RightBrace) and !self.check(.Eof)) { const function_typedef: *ObjTypeDef = try self.function(null, .Catch, null, return_type); if (!return_type.eql(function_typedef.resolved_type.?.Function.return_type)) { try self.reportTypeCheck(return_type, function_typedef.resolved_type.?.Function.return_type, "Bad catch return type."); } catch_count += 1; if (catch_count > 255) { try self.reportError("Maximum catch closures is 255."); return 255; } if (self.check(.Comma) or !self.check(.RightBrace)) { try self.consume(.Comma, "Expected `,` between catch closures."); } } try self.consume(.RightBrace, "Expected `}` after catch closures."); return catch_count; } else { const default_type: *ObjTypeDef = try self.expression(false); // If `null` it changes the expression to an optional // if (default_type.def_type == .Void) { // return_type.optional = true; // } if (!return_type.eql(default_type)) { try self.reportTypeCheck(return_type, default_type, "Bad catch expression type."); } return 1; } } return 0; } fn fun(self: *Self, _: bool) anyerror!*ObjTypeDef { return try self.function(null, .Anonymous, null, null); } fn function(self: *Self, name: ?Token, function_type: FunctionType, this: ?*ObjTypeDef, inferred_return_type: ?*ObjTypeDef) !*ObjTypeDef { try ChunkCompiler.init(self, function_type, null, this); var compiler: *ChunkCompiler = self.current.?; self.beginScope(); // The functiont tyepdef is created in several steps, some need already parsed information like return type // We create the incomplete type now and enrich it. var function_typedef: ObjTypeDef = .{ .def_type = .Function, }; var function_def = ObjFunction.FunctionDef{ .name = if (name) |uname| try copyStringRaw( self.strings, self.allocator, uname.lexeme, false, ) else try copyStringRaw( self.strings, self.allocator, "anonymous", false, ), .return_type = undefined, .parameters = std.StringArrayHashMap(*ObjTypeDef).init(self.allocator), .has_defaults = std.StringArrayHashMap(bool).init(self.allocator), .function_type = function_type, }; var function_resolved_type: ObjTypeDef.TypeUnion = .{ .Function = function_def }; function_typedef.resolved_type = function_resolved_type; // We replace it with a self.getTypeDef pointer at the end self.current.?.function.type_def = &function_typedef; // Parse argument list if (function_type == .Test) { try self.consume(.String, "Expected `str` after `test`."); _ = try self.string(false); try self.emitOpCode(.OP_PRINT); } else if (function_type != .Catch or !(try self.match(.Default))) { try self.consume(.LeftParen, "Expected `(` after function name."); var arity: usize = 0; if (!self.check(.RightParen)) { while (true) { arity += 1; if (arity > 255) { try self.reportErrorAtCurrent("Can't have more than 255 parameters."); } if (function_type == .Catch and arity > 1) { try self.reportErrorAtCurrent("`catch` clause can't have more than one parameter."); } var param_type: *ObjTypeDef = try self.parseTypeDef(); // Convert to instance if revelant param_type = switch (param_type.def_type) { .Object => object: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .ObjectInstance = param_type }; break :object try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .ObjectInstance, .resolved_type = resolved_type, }, ); }, .Enum => enum_instance: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .EnumInstance = param_type }; break :enum_instance try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .EnumInstance, .resolved_type = resolved_type, }, ); }, else => param_type, }; var slot: usize = try self.parseVariable( param_type, true, // function arguments are constant "Expected parameter name", ); if (self.current.?.scope_depth > 0) { var local: Local = self.current.?.locals[slot]; try function_typedef.resolved_type.?.Function.parameters.put(local.name.string, local.type_def); } else { var global: Global = self.globals.items[slot]; try function_typedef.resolved_type.?.Function.parameters.put(global.name.string, global.type_def); } try self.defineGlobalVariable(@intCast(u24, slot)); // Default arguments if (function_type == .Function or function_type == .Method or function_type == .Anonymous) { // if (arg == void) arg = default try self.emitCodeArg(if (self.current.?.scope_depth > 0) .OP_GET_LOCAL else .OP_GET_GLOBAL, @intCast(u24, slot)); try self.emitOpCode(.OP_VOID); try self.emitOpCode(.OP_EQUAL); const exit_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); if (try self.match(.Equal)) { var expr_type: *ObjTypeDef = try self.expression(false); // If only receiver is placeholder, make the assumption that its type if what the expression's return if (param_type.def_type == .Placeholder and expr_type.def_type != .Placeholder) { param_type.resolved_type.?.Placeholder.resolved_def_type = expr_type.def_type; param_type.resolved_type.?.Placeholder.resolved_type = expr_type; // If only expression is a placeholder, make the inverse assumption } else if (expr_type.def_type == .Placeholder and param_type.def_type != .Placeholder) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); } expr_type.resolved_type.?.Placeholder.resolved_def_type = param_type.def_type; expr_type.resolved_type.?.Placeholder.resolved_type = param_type; // If both are placeholders, check that they are compatible and enrich them } else if (expr_type.def_type == .Placeholder and param_type.def_type == .Placeholder and expr_type.resolved_type.?.Placeholder.eql(param_type.resolved_type.?.Placeholder)) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); } try PlaceholderDef.link(param_type, expr_type, .Assignment); // Else do a normal type check } else if (!param_type.eql(expr_type)) { try self.reportTypeCheck(param_type, expr_type, "Wrong variable type"); } if (self.current.?.scope_depth > 0) { var local: Local = self.current.?.locals[slot]; try function_typedef.resolved_type.?.Function.has_defaults.put(local.name.string, true); } else { var global: Global = self.globals.items[slot]; try function_typedef.resolved_type.?.Function.has_defaults.put(global.name.string, true); } } else { try self.emitOpCode(if (param_type.optional) .OP_NULL else .OP_VOID); if (param_type.optional) { if (self.current.?.scope_depth > 0) { var local: Local = self.current.?.locals[slot]; try function_typedef.resolved_type.?.Function.has_defaults.put(local.name.string, true); } else { var global: Global = self.globals.items[slot]; try function_typedef.resolved_type.?.Function.has_defaults.put(global.name.string, true); } } } try self.emitCodeArg(if (self.current.?.scope_depth > 0) .OP_SET_LOCAL else .OP_SET_GLOBAL, @intCast(u24, slot)); try self.patchJump(exit_jump); } if (!try self.match(.Comma)) break; } } try self.consume(.RightParen, "Expected `)` after function parameters."); } // Parse return type if (function_type != .Test and (function_type != .Catch or self.check(.Greater))) { try self.consume(.Greater, "Expected `>` after function argument list."); function_typedef.resolved_type.?.Function.return_type = try self.getTypeDef((try self.parseTypeDef()).toInstance()); } else if (function_type == .Catch) { function_typedef.resolved_type.?.Function.return_type = inferred_return_type.?; } else { function_typedef.resolved_type.?.Function.return_type = try self.getTypeDef(.{ .def_type = .Void }); } // Parse body if (try self.match(.Arrow)) { function_typedef.resolved_type.?.Function.lambda = true; var expr_type: *ObjTypeDef = try self.expression(false); if (!function_typedef.resolved_type.?.Function.return_type.eql(expr_type)) { try self.reportTypeCheck(function_typedef.resolved_type.?.Function.return_type, expr_type, "Bad return type"); } try self.emitOpCode(.OP_RETURN); // Lambda functions returns its single expression self.current.?.return_emitted = true; } else if (function_type != .Extern) { try self.consume(.LeftBrace, "Expected `{` before function body."); _ = try self.block(.Function); } self.current.?.function.type_def = try self.getTypeDef(function_typedef); var new_function: *ObjFunction = try self.endCompiler(); // `extern` functions don't have upvalues if (function_type == .Extern) { // Search for a dylib/so/dll with the same name as the current script if (try self.importLibSymbol( self.script_name, function_def.name.string, )) |native| { try self.emitCodeArg(.OP_CONSTANT, try self.makeConstant(native.toValue())); } } else { try self.emitCodeArg(.OP_CLOSURE, try self.makeConstant(new_function.toValue())); var i: usize = 0; while (i < new_function.upvalue_count) : (i += 1) { try self.emit(if (compiler.upvalues[i].is_local) 1 else 0); try self.emit(compiler.upvalues[i].index); } } return new_function.type_def; } fn method(self: *Self, object: *ObjTypeDef, static: bool) !*ObjTypeDef { try self.consume(.Identifier, "Expected method name."); var constant: u24 = try self.identifierConstant(self.parser.previous_token.?.lexeme); var fun_type: FunctionType = .Method; var fun_typedef: *ObjTypeDef = try self.function(self.parser.previous_token.?.clone(), fun_type, object, null); if (static) { try self.emitCodeArg(.OP_PROPERTY, constant); } else { try self.emitCodeArg(.OP_METHOD, constant); } return fun_typedef; } const Property = struct { name: []const u8, type_def: *ObjTypeDef, constant: bool, with_default: bool, }; fn property(self: *Self, static: bool) !?Property { var name: ?Token = null; var type_def: ?*ObjTypeDef = null; var name_constant: ?u24 = null; const constant: bool = try self.match(.Const); // Parse type and name if (try self.match(.Str)) { type_def = try self.getTypeDef(ObjTypeDef{ .optional = try self.match(.Question), .def_type = .String, }); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.Num)) { type_def = try self.getTypeDef(ObjTypeDef{ .optional = try self.match(.Question), .def_type = .Number, }); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.Bool)) { type_def = try self.getTypeDef(ObjTypeDef{ .optional = try self.match(.Question), .def_type = .Bool, }); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.Type)) { type_def = try self.getTypeDef(ObjTypeDef{ .optional = try self.match(.Question), .def_type = .Type, }); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.LeftBracket)) { type_def = try self.parseListType(); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.LeftBrace)) { type_def = try self.parseMapType(); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.Function)) { type_def = try self.functionType(); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); name_constant = try self.identifierConstant(name.?.lexeme); } else if (try self.match(.Identifier)) { var user_type_name: Token = self.parser.previous_token.?.clone(); try self.consume(.Identifier, "Expected property name."); name = self.parser.previous_token.?.clone(); var var_type: ?*ObjTypeDef = null; if (try self.resolveGlobal(null, name.?)) |slot| { var_type = self.globals.items[slot].type_def; } name_constant = try self.identifierConstant(name.?.lexeme); // If none found, create a placeholder if (var_type == null) { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; placeholder_resolved_type.Placeholder.name = try copyStringRaw(self.strings, self.allocator, user_type_name.lexeme, false); var_type = try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }, ); } type_def = var_type.?; } if (name != null and name_constant != null and type_def != null) { // Parse default value var with_default: bool = false; if (try self.match(.Equal)) { if (static) { try self.emitOpCode(.OP_COPY); } var expr_type: *ObjTypeDef = try self.expression(false); // If only receiver is placeholder, make the assumption that its type if what the expression's return if (type_def.?.def_type == .Placeholder and expr_type.def_type != .Placeholder) { type_def.?.resolved_type.?.Placeholder.resolved_def_type = expr_type.def_type; type_def.?.resolved_type.?.Placeholder.resolved_type = expr_type; // If only expression is a placeholder, make the inverse assumption } else if (expr_type.def_type == .Placeholder and type_def.?.def_type != .Placeholder) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); return null; } expr_type.resolved_type.?.Placeholder.resolved_def_type = type_def.?.def_type; expr_type.resolved_type.?.Placeholder.resolved_type = type_def.?; // If both are placeholders, check that they are compatible and enrich them } else if (expr_type.def_type == .Placeholder and type_def.?.def_type == .Placeholder and expr_type.resolved_type.?.Placeholder.eql(type_def.?.resolved_type.?.Placeholder)) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); return null; } try PlaceholderDef.link(type_def.?, expr_type, .Assignment); // Else do a normal type check } else if (!type_def.?.eql(expr_type)) { try self.reportTypeCheck(type_def.?, expr_type, "Wrong variable type"); } // Create property default value if (static) { try self.emitCodeArg(.OP_SET_PROPERTY, name_constant.?); try self.emitOpCode(.OP_POP); } else { try self.emitCodeArg(.OP_PROPERTY, name_constant.?); with_default = true; } } if (static) { if (!self.check(.RightBrace) or self.check(.Semicolon)) { try self.consume(.Semicolon, "Expected `;` after static property definition."); } } else { if (!self.check(.RightBrace) or self.check(.Comma)) { try self.consume(.Comma, "Expected `,` after property definition."); } } return Property{ .name = name.?.lexeme, .type_def = type_def.?, .constant = constant, .with_default = with_default, }; } return null; } // `test` is just like a function but we don't parse arguments and we don't care about its return type fn testStatement(self: *Self) !void { var function_def_placeholder: ObjTypeDef = .{ .def_type = .Function, }; var test_id: []u8 = try self.allocator.alloc(u8, 11); test_id = try std.fmt.bufPrint(test_id, "$test#{}", .{self.test_count}); // TODO: this string is never freed self.test_count += 1; const name_token: Token = Token{ .token_type = .Test, .lexeme = test_id, .line = 0, .column = 0, }; var slot: usize = try self.declareVariable(&function_def_placeholder, name_token, true); self.markInitialized(); _ = try self.function(name_token, FunctionType.Test, null, null); try self.defineGlobalVariable(@intCast(u24, slot)); } fn importScript(self: *Self, file_name: []const u8, prefix: ?[]const u8, imported_symbols: *std.StringHashMap(void)) anyerror!void { var import: ?ScriptImport = self.imports.get(file_name); if (import == null) { const buzz_path: ?[]const u8 = std.os.getenv("BUZZ_PATH") orelse "."; var lib_path = std.ArrayList(u8).init(self.allocator); defer lib_path.deinit(); _ = try lib_path.writer().print( "{s}/{s}.buzz", .{ buzz_path, file_name }, ); var dir_path = std.ArrayList(u8).init(self.allocator); defer dir_path.deinit(); _ = try dir_path.writer().print( "./{s}.buzz", .{file_name}, ); // Find and read file var file: std.fs.File = (if (std.fs.path.isAbsolute(lib_path.items)) std.fs.openFileAbsolute(lib_path.items, .{}) catch null else std.fs.cwd().openFile(lib_path.items, .{}) catch null) orelse (if (std.fs.path.isAbsolute(dir_path.items)) std.fs.openFileAbsolute(dir_path.items, .{}) catch { try self.reportErrorFmt("Could not find buzz script `{s}`", .{file_name}); return; } else std.fs.cwd().openFile(dir_path.items, .{}) catch { try self.reportErrorFmt("Could not find buzz script `{s}`", .{file_name}); return; }); defer file.close(); // TODO: put source strings in a ArenaAllocator that frees everything at the end of everything const source = try self.allocator.alloc(u8, (try file.stat()).size); // defer self.allocator.free(source); _ = try file.readAll(source); var compiler = Compiler.init(self.allocator, self.strings, self.imports, true); defer compiler.deinit(); if (try compiler.compile(source, file_name, self.testing)) |import_function| { import = ScriptImport{ .function = import_function, .globals = std.ArrayList(Global).init(self.allocator), }; for (compiler.globals.items) |*global| { if (global.exported) { global.*.exported = false; if (global.export_alias) |export_alias| { global.*.name.string = export_alias; global.*.export_alias = null; } } else { global.*.hidden = true; } global.*.prefix = prefix; try import.?.globals.append(global.*); } try self.imports.put(file_name, import.?); } } if (import) |imported| { try self.emitCodeArg( .OP_CONSTANT, try self.makeConstant(Value{ .Obj = imported.function.toObj() }), ); try self.emitOpCode(.OP_IMPORT); const selective_import = imported_symbols.count() > 0; for (imported.globals.items) |*global| { if (!global.hidden) { if (imported_symbols.get(global.name.string) != null) { _ = imported_symbols.remove(global.name.string); } else if (selective_import) { global.hidden = true; } // Search for name collision if ((try self.resolveGlobal(prefix, Token.identifier(global.name.string))) != null) { try self.reportError("Shadowed global"); } } // TODO: we're forced to import all and hide some because globals are indexed and not looked up by name at runtime // Only way to avoid this is to go back to named globals at runtime. Then again, is it worth it? try self.globals.append(global.*); } } else { try self.reportError("Could not compile import."); } } // TODO: when to close the lib? fn importLibSymbol(self: *Self, file_name: []const u8, symbol: []const u8) !?*ObjNative { const buzz_path: ?[]const u8 = std.os.getenv("BUZZ_PATH") orelse "."; var lib_path = std.ArrayList(u8).init(self.allocator); defer lib_path.deinit(); try lib_path.writer().print( "{s}/{s}.{s}", .{ buzz_path, file_name, switch (builtin.os.tag) { .linux, .freebsd, .openbsd => "so", .windows => "dll", .macos, .tvos, .watchos, .ios => "dylib", else => unreachable, }, }, ); var dir_path = std.ArrayList(u8).init(self.allocator); defer dir_path.deinit(); try dir_path.writer().print( "./{s}.{s}", .{ file_name, switch (builtin.os.tag) { .linux, .freebsd, .openbsd => "so", .windows => "dll", .macos, .tvos, .watchos, .ios => "dylib", else => unreachable, }, }, ); var lib: ?std.DynLib = std.DynLib.open(lib_path.items) catch std.DynLib.open(dir_path.items) catch null; if (lib) |*dlib| { // Convert symbol names to zig slices var ssymbol = try (toNullTerminated(self.allocator, symbol) orelse Allocator.Error.OutOfMemory); defer self.allocator.free(ssymbol); // Lookup symbol NativeFn var symbol_method = dlib.lookup(NativeFn, ssymbol); if (symbol_method == null) { try self.reportErrorFmt("Could not find symbol `{s}` in lib `{s}`", .{ symbol, file_name }); return null; } // Create a ObjNative with it var native = try self.allocator.create(ObjNative); native.* = .{ .native = symbol_method.? }; return native; } if (builtin.os.tag == .macos) { try self.reportError(std.mem.sliceTo(dlerror(), 0)); } else { try self.reportErrorFmt("Could not open lib `{s}`", .{file_name}); } return null; } fn importStatement(self: *Self) anyerror!void { var imported_symbols = std.StringHashMap(void).init(self.allocator); defer imported_symbols.deinit(); while ((try self.match(.Identifier)) and !self.check(.Eof)) { try imported_symbols.put(self.parser.previous_token.?.lexeme, .{}); if (!self.check(.From) or self.check(.Comma)) { // Allow trailing comma try self.consume(.Comma, "Expected `,` after identifier."); } } var prefix: ?[]const u8 = null; if (imported_symbols.count() > 0) { try self.consume(.From, "Expected `from` after import identifier list."); } try self.consume(.String, "Expected import path."); var file_name: []const u8 = self.parser.previous_token.?.lexeme[1..(self.parser.previous_token.?.lexeme.len - 1)]; if (imported_symbols.count() == 0 and try self.match(.As)) { try self.consume(.Identifier, "Expected identifier after `as`."); prefix = self.parser.previous_token.?.lexeme; } try self.consume(.Semicolon, "Expected `;` after import."); try self.importScript(file_name, prefix, &imported_symbols); if (imported_symbols.count() > 0) { var it = imported_symbols.iterator(); while (it.next()) |kv| { try self.reportErrorFmt("Unknown import `{s}`.", .{kv.key_ptr.*}); } } } fn exportStatement(self: *Self) !void { try self.consume(.Identifier, "Expected identifier after `export`."); // Search for a global with that name if (try self.resolveGlobal(null, self.parser.previous_token.?)) |slot| { const global: *Global = &self.globals.items[slot]; global.exported = true; if (global.prefix != null or self.check(.As)) { try self.consume(.As, "Expected `as` after prefixed global."); try self.consume(.Identifier, "Expected identifier after `as`."); global.export_alias = self.parser.previous_token.?.lexeme; } try self.consume(.Semicolon, "Expected `;` after export."); return; } try self.reportError("Unknown global."); } fn funDeclaration(self: *Self) !void { var function_type: FunctionType = .Function; if (self.parser.previous_token.?.token_type == .Extern) { try self.consume(.Fun, "Expected `fun` after `extern`."); function_type = .Extern; } // Placeholder until `function()` provides all the necessary bits var function_def_placeholder: ObjTypeDef = .{ .def_type = .Function, }; try self.consume(.Identifier, "Expected function name."); var name_token: Token = self.parser.previous_token.?; var slot: usize = try self.declareVariable(&function_def_placeholder, name_token, true); self.markInitialized(); const is_main = std.mem.eql(u8, name_token.lexeme, "main") and self.current.?.function_type == .ScriptEntryPoint; if (is_main) { if (function_type == .Extern) { try self.reportError("`main` can't be `extern`."); } function_type = .EntryPoint; } var function_def: *ObjTypeDef = try self.function(name_token, function_type, null, null); if (function_def.resolved_type.?.Function.lambda) { try self.consume(.Semicolon, "Expected `;` after lambda function"); } // Now that we have the full function type, get the local and update its type_def if (self.current.?.scope_depth > 0) { self.current.?.locals[slot].type_def = function_def; } else { if (self.globals.items[slot].type_def.def_type == .Placeholder) { // Now that the function definition is complete, resolve the eventual placeholder try self.resolvePlaceholder(self.globals.items[slot].type_def, function_def, true); } else { self.globals.items[slot].type_def = function_def; } } if (is_main) { try self.checkMainSignature(function_def); } try self.defineGlobalVariable(@intCast(u24, slot)); if (function_type == .Extern) { try self.consume(.Semicolon, "Expected `;` after `extern` function declaration."); } } fn checkMainSignature(self: *Self, function_def: *ObjTypeDef) !void { if (function_def.def_type != .Function) { try self.reportError("main should be a function"); } if (function_def.resolved_type.?.Function.return_type.def_type != .Number) { try self.reportError("main should return num"); } if (function_def.resolved_type.?.Function.parameters.count() != 1) { try self.reportError("main should have one argument of type [str]"); } const parameter = function_def.resolved_type.?.Function.parameters.values()[0]; if (parameter.def_type != .List or parameter.resolved_type.?.List.item_type.def_type != .String) { try self.reportError("main should have one argument of type [str]"); } } // TODO: factorize with varDeclaration + another param fn varDeclarationOnly(self: *Self, parsed_type: *ObjTypeDef, constant: bool) !void { // If var_type is Class/Object/Enum, we expect instance of them var var_type: *ObjTypeDef = switch (parsed_type.def_type) { .Object => object: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .ObjectInstance = parsed_type, }; break :object try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .ObjectInstance, .resolved_type = resolved_type, }, ); }, .Enum => enum_instance: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .EnumInstance = parsed_type, }; break :enum_instance try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .EnumInstance, .resolved_type = resolved_type, }, ); }, else => parsed_type, }; try self.emitOpCode(.OP_NULL); try self.defineGlobalVariable(@intCast(u24, try self.parseVariable(var_type, constant, "Expected variable name."))); } fn varDeclaration(self: *Self, parsed_type: *ObjTypeDef, in_list: bool, constant: bool) !void { // If var_type is Class/Object/Enum, we expect instance of them var var_type: *ObjTypeDef = switch (parsed_type.def_type) { .Object => object: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .ObjectInstance = parsed_type, }; break :object try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .ObjectInstance, .resolved_type = resolved_type, }, ); }, .Enum => enum_instance: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .EnumInstance = parsed_type, }; break :enum_instance try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .EnumInstance, .resolved_type = resolved_type, }, ); }, else => parsed_type, }; const slot: usize = try self.parseVariable(var_type, constant, "Expected variable name."); if (try self.match(.Equal)) { var expr_type: *ObjTypeDef = try self.expression(false); // If only receiver is placeholder, make the assumption that its type if what the expression's return if (var_type.def_type == .Placeholder and expr_type.def_type != .Placeholder) { var_type.resolved_type.?.Placeholder.resolved_def_type = expr_type.def_type; var_type.resolved_type.?.Placeholder.resolved_type = expr_type; // If only expression is a placeholder, make the inverse assumption } else if (expr_type.def_type == .Placeholder and var_type.def_type != .Placeholder) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); return; } expr_type.resolved_type.?.Placeholder.resolved_def_type = var_type.def_type; expr_type.resolved_type.?.Placeholder.resolved_type = var_type; // If both are placeholders, check that they are compatible and enrich them } else if (expr_type.def_type == .Placeholder and var_type.def_type == .Placeholder and expr_type.resolved_type.?.Placeholder.eql(var_type.resolved_type.?.Placeholder)) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); return; } try PlaceholderDef.link(var_type, expr_type, .Assignment); // Else do a normal type check } else if (!var_type.eql(expr_type)) { try self.reportTypeCheck(var_type, expr_type, "Wrong variable type"); } } else { try self.emitOpCode(.OP_VOID); } if (!in_list) { try self.consume(.Semicolon, "Expected `;` after variable declaration."); } try self.defineGlobalVariable(@intCast(u24, slot)); } fn parseListType(self: *Self) !*ObjTypeDef { var list_item_type: *ObjTypeDef = try self.parseTypeDef(); try self.consume(.RightBracket, "Expected `]` after list type."); var list_def = ObjList.ListDef.init(self.allocator, list_item_type); var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .List = list_def, }; return try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .List, .resolved_type = resolved_type, }, ); } fn listDeclaration(self: *Self, constant: bool) !void { try self.varDeclaration(try self.parseListType(), false, constant); } fn parseMapType(self: *Self) !*ObjTypeDef { var key_type: *ObjTypeDef = try self.parseTypeDef(); try self.consume(.Comma, "Expected `,` after key type."); var value_type: *ObjTypeDef = try self.parseTypeDef(); try self.consume(.RightBrace, "Expected `}` after value type."); var map_def = ObjMap.MapDef.init(self.allocator, key_type, value_type); var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .Map = map_def, }; return try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Map, .resolved_type = resolved_type, }, ); } fn mapDeclaration(self: *Self, constant: bool) !void { try self.varDeclaration(try self.parseMapType(), false, constant); } fn enumDeclaration(self: *Self) !void { if (self.current.?.scope_depth > 0) { try self.reportError("Enum must be defined at top-level."); return; } var enum_case_type: *ObjTypeDef = undefined; var case_type_picked: bool = false; if (try self.match(.LeftParen)) { enum_case_type = try self.parseTypeDef(); try self.consume(.RightParen, "Expected `)` after enum type."); case_type_picked = true; } else { enum_case_type = try self.getTypeDef(.{ .def_type = .Number }); } enum_case_type = (try self.toInstance(enum_case_type)) orelse enum_case_type; try self.consume(.Identifier, "Expected enum name."); var enum_name: Token = self.parser.previous_token.?.clone(); for (self.globals.items) |global| { if (mem.eql(u8, global.name.string, enum_name.lexeme)) { try self.reportError("Global with that name already exists."); break; } } var enum_def: ObjEnum.EnumDef = ObjEnum.EnumDef.init( self.allocator, try copyStringRaw(self.strings, self.allocator, enum_name.lexeme, false), enum_case_type, ); var enum_resolved: ObjTypeDef.TypeUnion = .{ .Enum = enum_def }; var enum_type: *ObjTypeDef = try self.allocator.create(ObjTypeDef); enum_type.* = ObjTypeDef{ .def_type = .Enum, .resolved_type = enum_resolved, }; const name_constant: u24 = try self.makeConstant(Value{ .Obj = enum_type.toObj(), }); const slot: usize = try self.declareVariable(enum_type, enum_name, true); try self.emitCodeArg(.OP_ENUM, name_constant); try self.emitCodeArg(.OP_DEFINE_GLOBAL, @intCast(u24, slot)); self.markInitialized(); _ = try self.namedVariable(enum_name, false); try self.consume(.LeftBrace, "Expected `{` before enum body."); var case_index: f64 = 0; while (!self.check(.RightBrace) and !self.check(.Eof)) : (case_index += 1) { if (case_index > 255) { try self.reportError("Too many enum cases."); } try self.consume(.Identifier, "Expected case name."); const case_name: []const u8 = self.parser.previous_token.?.lexeme; if (case_type_picked) { try self.consume(.Equal, "Expected `=` after case name."); var parsed_type: *ObjTypeDef = try self.expression(false); if (!parsed_type.eql(enum_case_type)) { try self.reportTypeCheck(enum_case_type, parsed_type, "Bad enum case type."); } if (enum_case_type.def_type == .Placeholder and parsed_type.def_type != .Placeholder) { enum_case_type.resolved_type.?.Placeholder.resolved_def_type = parsed_type.def_type; enum_case_type.resolved_type.?.Placeholder.resolved_type = parsed_type; if (!enum_case_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad enum case type."); } } if (parsed_type.def_type == .Placeholder and enum_case_type.def_type != .Placeholder) { parsed_type.resolved_type.?.Placeholder.resolved_def_type = enum_case_type.def_type; parsed_type.resolved_type.?.Placeholder.resolved_type = enum_case_type; if (!parsed_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad enum case expression type."); } } try self.emitOpCode(.OP_ENUM_CASE); } else { assert(enum_case_type.def_type == .Number); try self.emitConstant(Value{ .Number = case_index }); try self.emitOpCode(.OP_ENUM_CASE); } try enum_type.resolved_type.?.Enum.cases.append(case_name); // TODO: how to not force a comma at last case? try self.consume(.Comma, "Expected `,` after case definition."); } try self.consume(.RightBrace, "Expected `}` after enum body."); if (case_index == 0) { try self.reportError("Enum must have at least one case."); } try self.emitOpCode(.OP_POP); } fn objectInit(self: *Self, _: bool, object_type: *ObjTypeDef) anyerror!*ObjTypeDef { if (object_type.def_type != .Object) { try self.reportError("Is not an object."); } try self.emitOpCode(.OP_INSTANCE); const obj_def: ObjObject.ObjectDef = object_type.resolved_type.?.Object; // To keep track of what's been initialized or not by this statement var init_properties = std.StringHashMap(void).init(self.allocator); defer init_properties.deinit(); while (!self.check(.RightBrace) and !self.check(.Eof)) { try self.consume(.Identifier, "Expected property name"); const property_name: []const u8 = self.parser.previous_token.?.lexeme; const property_name_constant: u24 = try self.identifierConstant(property_name); try self.consume(.Equal, "Expected `=` after property nane."); if (obj_def.fields.get(property_name) orelse self.getSuperField(object_type, property_name)) |prop| { try self.emitCodeArg(.OP_COPY, 0); // Will be popped by OP_SET_PROPERTY const prop_type: *ObjTypeDef = try self.expression(false); if (!prop.eql(prop_type)) { try self.reportTypeCheck(prop, prop_type, "Wrong property type"); } try init_properties.put(property_name, {}); try self.emitCodeArg(.OP_SET_PROPERTY, property_name_constant); try self.emitOpCode(.OP_POP); // Pop property value } else { try self.reportErrorFmt("Property `{s}` does not exists", .{property_name}); } if (!self.check(.RightBrace) or self.check(.Comma)) { try self.consume(.Comma, "Expected `,` after field initialization."); } } // Did we initialized all properties without a default value? try self.checkOmittedProperty(obj_def, init_properties); try self.consume(.RightBrace, "Expected `}` after object initialization."); return self.getTypeDef(object_type.toInstance()); } fn checkOmittedProperty(self: *Self, obj_def: ObjObject.ObjectDef, init_properties: std.StringHashMap(void)) anyerror!void { var it = obj_def.fields.iterator(); while (it.next()) |kv| { // If ommitted in initialization and doesn't have default value if (init_properties.get(kv.key_ptr.*) == null and obj_def.fields_defaults.get(kv.key_ptr.*) == null) { try self.reportErrorFmt("Property `{s}` was not initialized and has no default value", .{kv.key_ptr.*}); } } if (obj_def.super) |super_def| { try self.checkOmittedProperty(super_def.resolved_type.?.Object, init_properties); } } fn objectDeclaration(self: *Self, is_class: bool) !void { if (self.current.?.scope_depth > 0) { try self.reportError("Object must be defined at top-level."); return; } // Get object name try self.consume(.Identifier, "Expected object name."); var object_name: Token = self.parser.previous_token.?.clone(); // Check a global doesn't already exist for (self.globals.items) |global| { if (mem.eql(u8, global.name.string, object_name.lexeme)) { try self.reportError("Global with that name already exists."); break; } } // Create type var object_type: *ObjTypeDef = try self.allocator.create(ObjTypeDef); object_type.* = .{ .def_type = .Object, .resolved_type = .{ .Object = ObjObject.ObjectDef.init( self.allocator, try copyStringRaw(self.strings, self.allocator, object_name.lexeme, false), ), }, }; const name_constant: u24 = try self.makeConstant(Value{ .Obj = object_type.resolved_type.?.Object.name.toObj() }); const object_type_constant: u24 = try self.makeConstant(Value{ .Obj = object_type.toObj() }); const slot: usize = try self.declareVariable( object_type, object_name, true, // Object is always constant ); // Put object on the stack and define global with it try self.emitCodeArg(.OP_OBJECT, name_constant); try self.emit(@intCast(u32, object_type_constant)); try self.emitCodeArg(.OP_DEFINE_GLOBAL, @intCast(u24, slot)); // Mark initialized so we can refer to it inside its own declaration self.markInitialized(); var object_compiler: ObjectCompiler = .{ .name = object_name, .type_def = object_type, }; self.current_object = object_compiler; // Inherited class? if (is_class) { object_type.resolved_type.?.Object.inheritable = true; if (try self.match(.Less)) { try self.consume(.Identifier, "Expected identifier after `<`."); if (std.mem.eql(u8, object_name.lexeme, self.parser.previous_token.?.lexeme)) { try self.reportError("A class can't inherit itself."); } var parent_slot: usize = try self.parseUserType(); var parent: *ObjTypeDef = self.globals.items[parent_slot].type_def; if (parent.def_type != .Object and (parent.def_type != .Placeholder or !parent.resolved_type.?.Placeholder.couldBeObject())) { try self.reportErrorFmt("`{s}` is not a class.", .{self.parser.previous_token.?.lexeme}); } if (parent.def_type == .Placeholder) { parent.resolved_type.?.Placeholder.resolved_def_type = .Object; if (!parent.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorFmt("`{s}` can't be a class.", .{self.parser.previous_token.?.lexeme}); } } object_type.resolved_type.?.Object.super = parent; try self.emitCodeArg(.OP_GET_GLOBAL, @intCast(u24, parent_slot)); self.beginScope(); _ = try self.addLocal( Token{ .token_type = .Identifier, .lexeme = "super", .line = 0, .column = 0, }, try self.getTypeDef(parent.toInstance()), true, ); self.markInitialized(); _ = try self.namedVariable(object_name, false); try self.emitCodeArg(.OP_INHERIT, @intCast(u24, parent_slot)); } else { self.beginScope(); } } else { self.beginScope(); } _ = try self.namedVariable(object_name, false); // Body try self.consume(.LeftBrace, "Expected `{` before object body."); var fields = std.StringHashMap(void).init(self.allocator); defer fields.deinit(); while (!self.check(.RightBrace) and !self.check(.Eof)) { const static: bool = try self.match(.Static); if (try self.match(.Fun)) { var method_def: *ObjTypeDef = try self.method(object_type, static); var method_name: []const u8 = method_def.resolved_type.?.Function.name.string; if (fields.get(method_name) != null) { try self.reportError("A method with that name already exists."); } // Does a placeholder exists for this name ? if (static) { if (object_type.resolved_type.?.Object.static_placeholders.get(method_name)) |placeholder| { try self.resolvePlaceholder(placeholder, method_def, true); // Now we know the placeholder was a method _ = object_type.resolved_type.?.Object.static_placeholders.remove(method_name); } } else { if (object_type.resolved_type.?.Object.placeholders.get(method_name)) |placeholder| { try self.resolvePlaceholder(placeholder, method_def, true); // Now we know the placeholder was a method _ = object_type.resolved_type.?.Object.placeholders.remove(method_name); } } if (static) { try object_type.resolved_type.?.Object.static_fields.put(method_name, method_def); } else { try object_type.resolved_type.?.Object.methods.put( method_name, method_def, ); } try fields.put(method_name, {}); } else if (try self.property(static)) |prop| { if (fields.get(prop.name) != null) { try self.reportError("A property with that name already exists."); } // Does a placeholder exists for this name ? if (static) { if (object_type.resolved_type.?.Object.static_placeholders.get(prop.name)) |placeholder| { try self.resolvePlaceholder(placeholder, prop.type_def, prop.constant); // Now we know the placeholder was a field _ = object_type.resolved_type.?.Object.static_placeholders.remove(prop.name); } } else { if (object_type.resolved_type.?.Object.placeholders.get(prop.name)) |placeholder| { try self.resolvePlaceholder(placeholder, prop.type_def, prop.constant); // Now we know the placeholder was a field _ = object_type.resolved_type.?.Object.placeholders.remove(prop.name); } } if (prop.constant) { // TODO: const qualifier for objects fields unreachable; } if (static) { try object_type.resolved_type.?.Object.static_fields.put( prop.name, prop.type_def, ); } else { try object_type.resolved_type.?.Object.fields.put( prop.name, prop.type_def, ); if (prop.with_default) { try object_type.resolved_type.?.Object.fields_defaults.put(prop.name, {}); } } try fields.put(prop.name, {}); } else { try self.reportError("Expected either method or property."); return; } } // TODO: ERROR IF PLACEHOLDERS LEFT try self.consume(.RightBrace, "Expected `}` after object body."); // Pop object try self.emitOpCode(.OP_POP); try self.endScope(); self.current_object = null; } fn expressionStatement(self: *Self, hanging: bool) !void { _ = try self.expression(hanging); try self.consume(.Semicolon, "Expected `;` after expression."); try self.emitOpCode(.OP_POP); } fn breakStatement(self: *Self, block_type: BlockType) !usize { if (block_type == .Function) { try self.reportError("break is not allowed here."); } try self.consume(.Semicolon, "Expected `;` after `break`."); return try self.emitJump(.OP_JUMP); } fn continueStatement(self: *Self, block_type: BlockType) !usize { if (block_type == .Function) { try self.reportError("continue is not allowed here."); } try self.consume(.Semicolon, "Expected `;` after `continue`."); return try self.emitJump(.OP_LOOP); } fn forEachStatement(self: *Self) !void { try self.consume(.LeftParen, "Expected `(` after `foreach`."); self.beginScope(); var key_type: *ObjTypeDef = try self.parseTypeDef(); try self.varDeclarationOnly(key_type, false); var key_name: Token = self.parser.previous_token.?; var value_type: ?*ObjTypeDef = null; if (try self.match(.Comma)) { value_type = try self.parseTypeDef(); try self.varDeclarationOnly(value_type.?, false); } try self.consume(.In, "Expected `in` after `foreach` variables."); var iterable_type: *ObjTypeDef = try self.expression(false); try self.consume(.RightParen, "Expected `)` after `foreach`."); // TODO: object with `next` method // zig fmt: off if (iterable_type.def_type != .List and iterable_type.def_type != .Map and iterable_type.def_type != .Enum and iterable_type.def_type != .String and (iterable_type.def_type != .Placeholder or !iterable_type.resolved_type.?.Placeholder.isIterable())) { try self.reportError("Not iterable."); } // zig fmt: on // Check key and value type switch (iterable_type.def_type) { .String => { if (value_type == null) { try self.reportError("Missing value variable."); } const int_type: *ObjTypeDef = try self.getTypeDef(ObjTypeDef{ .def_type = .Number, }); if (!key_type.eql(int_type)) { try self.reportTypeCheck(int_type, key_type, "Bad key type"); } if (key_type.def_type == .Placeholder) { key_type.resolved_type.?.Placeholder.resolved_def_type = .Number; if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Is not a `num`."); } } if (!key_type.eql(int_type)) { try self.reportTypeCheck(int_type, key_type, "Should be"); } if (key_type.def_type == .Placeholder and iterable_type.def_type != .Placeholder) { // TODO: we could enrich with placeholder.resolved_def_type/resolved_type key_type.resolved_type.?.Placeholder.resolved_def_type = .String; key_type.resolved_type.?.Placeholder.resolved_type = try self.getTypeDef( ObjTypeDef{ .def_type = .String }, ); if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Is not a str."); } } }, .Enum => { if (value_type != null) { try self.reportError("Only one variable allowed when iterating over Enum."); } if (!key_type.eql(iterable_type)) { try self.reportTypeCheck(iterable_type, key_type, "Should be instance of"); } if (key_type.def_type == .Placeholder and iterable_type.def_type != .Placeholder) { // TODO: we could enrich with placeholder.resolved_def_type/resolved_type key_type.resolved_type.?.Placeholder.resolved_def_type = .EnumInstance; key_type.resolved_type.?.Placeholder.resolved_type = try self.getTypeDef( ObjTypeDef{ .def_type = .EnumInstance, .resolved_type = ObjTypeDef.TypeUnion{ .EnumInstance = iterable_type }, }, ); if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Is not a Enum."); } } }, .List => { if (value_type == null) { try self.reportError("Missing value variable."); } const int_type: *ObjTypeDef = try self.getTypeDef(ObjTypeDef{ .def_type = .Number, }); if (!key_type.eql(int_type)) { try self.reportTypeCheck(int_type, key_type, "Bad key type"); } if (key_type.def_type == .Placeholder) { key_type.resolved_type.?.Placeholder.resolved_def_type = .Number; if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Is not a `num`."); } } if (!value_type.?.eql(iterable_type.resolved_type.?.List.item_type)) { try self.reportTypeCheck(iterable_type.resolved_type.?.List.item_type, value_type.?, "Wrong value type"); } else if (value_type.?.def_type == .Placeholder and iterable_type.def_type != .Placeholder) { // TODO: we could enrich with placeholder.resolved_def_type/resolved_type value_type.?.resolved_type.?.Placeholder.resolved_def_type = iterable_type.resolved_type.?.List.item_type.def_type; value_type.?.resolved_type.?.Placeholder.resolved_type = iterable_type.resolved_type.?.List.item_type; if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Type mismatch."); } } }, .Map => { if (value_type == null) { try self.reportError("Missing value variable."); } var map_key_type: *ObjTypeDef = iterable_type.resolved_type.?.Map.key_type; var map_value_type: *ObjTypeDef = iterable_type.resolved_type.?.Map.value_type; if (!key_type.eql(map_key_type)) { try self.reportTypeCheck(map_key_type, key_type, "Bad key type."); } if (key_type.def_type == .Placeholder and map_key_type.def_type != .Placeholder) { key_type.resolved_type.?.Placeholder.resolved_type = map_key_type; if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportTypeCheck(map_key_type, key_type, "Wrong value type"); } } if (!value_type.?.eql(map_value_type)) { try self.reportTypeCheck(map_value_type, value_type.?, "Wrong value type"); } else if (value_type.?.def_type == .Placeholder and map_value_type.def_type != .Placeholder) { // TODO: we could enrich with placeholder.resolved_def_type/resolved_type value_type.?.resolved_type.?.Placeholder.resolved_type = map_value_type; if (!key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportTypeCheck(map_value_type, value_type.?, "Wrong value type"); } } }, else => { // If placeholder, it doesn't give any insight to what the placeholder could be // But the rest of foreachStatement should still works since the only difference // between all types iteration is the presence of the value or not. // Which doesn't impact at all the following code. unreachable; }, } var key_slot: u24 = @intCast(u24, (try self.resolveLocal(self.current.?, key_name)).?); const loop_start: usize = self.currentCode(); // Calls `next` and update key and value locals try self.emitOpCode(.OP_FOREACH); // If next key is null, exit loop try self.emitCodeArg(.OP_GET_LOCAL, key_slot); try self.emitOpCode(.OP_NULL); try self.emitOpCode(.OP_EQUAL); try self.emitOpCode(.OP_NOT); const exit_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); // Pop condition result try self.consume(.LeftBrace, "Expected `{` after `foreach` definition."); var breaks: std.ArrayList(usize) = try self.block(.ForEach); defer breaks.deinit(); try self.emitLoop(loop_start); // Patch condition jump try self.patchJump(exit_jump); // Patch breaks for (breaks.items) |jump| { try self.patchJumpOrLoop(jump, loop_start); } try self.endScope(); try self.emitOpCode(.OP_POP); // Pop element being iterated on } fn forStatement(self: *Self) !void { try self.consume(.LeftParen, "Expected `(` after `for`."); self.beginScope(); while (!self.check(.Semicolon) and !self.check(.Eof)) { try self.varDeclaration(try self.parseTypeDef(), true, false); if (!self.check(.Semicolon)) { try self.consume(.Comma, "Expected `,` after for loop variable"); } } try self.consume(.Semicolon, "Expected `;` after for loop variables."); const loop_start: usize = self.currentCode(); var expr_type: *ObjTypeDef = try self.expression(false); if (expr_type.def_type != .Bool and (expr_type.def_type != .Placeholder or !expr_type.resolved_type.?.Placeholder.isBasicType(.Bool))) { try self.reportError("Expected `bool` condition."); } else if (expr_type.def_type == .Placeholder) { expr_type.resolved_type.?.Placeholder.resolved_def_type = .Bool; if (!expr_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Type mismatch."); } } try self.consume(.Semicolon, "Expected `;` after for loop condition."); const exit_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); // Jump over expressions which will be executed at end of loop var body_jump: usize = try self.emitJump(.OP_JUMP); const expr_loop: usize = self.currentCode(); while (!self.check(.RightParen) and !self.check(.Eof)) { _ = try self.expression(false); if (!self.check(.RightParen)) { try self.consume(.Comma, "Expected `,` after for loop expression"); } } try self.consume(.RightParen, "Expected `)` after `for` expressions."); try self.emitLoop(loop_start); try self.patchJump(body_jump); try self.consume(.LeftBrace, "Expected `{` after `for` definition."); var breaks: std.ArrayList(usize) = try self.block(.For); defer breaks.deinit(); try self.emitLoop(expr_loop); try self.patchJump(exit_jump); try self.emitOpCode(.OP_POP); // Patch breaks for (breaks.items) |jump| { try self.patchJumpOrLoop(jump, loop_start); } try self.endScope(); } fn whileStatement(self: *Self) !void { const loop_start: usize = self.currentCode(); try self.consume(.LeftParen, "Expected `(` after `while`."); var parsed_type: *ObjTypeDef = try self.expression(false); if (parsed_type.def_type != .Bool and parsed_type.def_type != .Placeholder) { try self.reportTypeCheck(try self.getTypeDef(ObjTypeDef{ .def_type = .Bool }), parsed_type, "Bad `while` condition"); } try self.consume(.RightParen, "Expected `)` after `while` condition."); const exit_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); try self.consume(.LeftBrace, "Expected `{` after `if` condition."); self.beginScope(); var breaks: std.ArrayList(usize) = try self.block(.While); defer breaks.deinit(); try self.emitLoop(loop_start); try self.patchJump(exit_jump); try self.emitOpCode(.OP_POP); // Pop condition (is not necessary if broke out of the loop) // Patch breaks for (breaks.items) |jump| { try self.patchJumpOrLoop(jump, loop_start); } try self.endScope(); } fn doUntilStatement(self: *Self) !void { const loop_start: usize = self.currentCode(); try self.consume(.LeftBrace, "Expected `{` after `do`."); self.beginScope(); var breaks: std.ArrayList(usize) = try self.block(.Do); defer breaks.deinit(); try self.consume(.Until, "Expected `until` after `do` block."); try self.consume(.LeftParen, "Expected `(` after `until`."); var parsed_type: *ObjTypeDef = try self.expression(false); if (parsed_type.def_type != .Bool and parsed_type.def_type != .Placeholder) { try self.reportTypeCheck(try self.getTypeDef(ObjTypeDef{ .def_type = .Bool }), parsed_type, "Bad `while` condition"); } try self.consume(.RightParen, "Expected `)` after `until` condition."); try self.emitOpCode(.OP_NOT); const exit_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); try self.emitLoop(loop_start); try self.patchJump(exit_jump); try self.emitOpCode(.OP_POP); // Pop condition // Patch breaks for (breaks.items) |jump| { try self.patchJumpOrLoop(jump, loop_start); } try self.endScope(); } fn ifStatement(self: *Self, block_type: BlockType) anyerror!std.ArrayList(usize) { try self.consume(.LeftParen, "Expected `(` after `if`."); var parsed_type: *ObjTypeDef = try self.expression(false); if (parsed_type.def_type != .Bool and parsed_type.def_type != .Placeholder) { try self.reportTypeCheck(try self.getTypeDef(ObjTypeDef{ .def_type = .Bool }), parsed_type, "Bad `if` condition"); } try self.consume(.RightParen, "Expected `)` after `if` condition."); const then_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); try self.consume(.LeftBrace, "Expected `{` after `if` condition."); self.beginScope(); var breaks: std.ArrayList(usize) = try self.block(block_type); try self.endScope(); const else_jump: usize = try self.emitJump(.OP_JUMP); try self.patchJump(then_jump); try self.emitOpCode(.OP_POP); if (try self.match(.Else)) { if (try self.match(.If)) { var else_if_breaks: std.ArrayList(usize) = try self.ifStatement(block_type); try breaks.appendSlice(else_if_breaks.items); else_if_breaks.deinit(); } else { try self.consume(.LeftBrace, "Expected `{` after `else`."); self.beginScope(); self.current.?.return_counts = true; var else_breaks: std.ArrayList(usize) = try self.block(block_type); try breaks.appendSlice(else_breaks.items); else_breaks.deinit(); self.current.?.return_counts = false; try self.endScope(); } } try self.patchJump(else_jump); return breaks; } inline fn defineGlobalVariable(self: *Self, slot: u24) !void { self.markInitialized(); if (self.current.?.scope_depth > 0) { return; } try self.emitCodeArg(.OP_DEFINE_GLOBAL, slot); } fn declarePlaceholder(self: *Self, name: Token, placeholder: ?*ObjTypeDef) !usize { var placeholder_type: *ObjTypeDef = undefined; if (placeholder) |uplaceholder| { placeholder_type = uplaceholder; } else { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?) }; placeholder_resolved_type.Placeholder.name = try copyStringRaw(self.strings, self.allocator, name.lexeme, false); placeholder_type = try self.getTypeDef(.{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type }); } const global: usize = try self.addGlobal(name, placeholder_type, false); // markInitialized but we don't care what depth we are in self.globals.items[global].initialized = true; if (Config.debug) { std.debug.print("\u{001b}[33m[{}:{}] Warning: defining global placeholder for `{s}` at {}\u{001b}[0m\n", .{ self.parser.previous_token.?.line + 1, self.parser.previous_token.?.column + 1, name.lexeme, global }); } try self.defineGlobalVariable(@intCast(u24, global)); return global; } const ParsedArg = struct { name: ?Token, arg_type: *ObjTypeDef, }; // Like argument list but we parse all the arguments and populate the placeholder type with it // TODO: factorize with `argumentList` fn placeholderArgumentList(self: *Self, placeholder_type: *ObjTypeDef) !u8 { // If the placeholder guessed an actual full type, use argumentList with it if (placeholder_type.resolved_type.?.Placeholder.resolved_type) |resolved_type| { if (resolved_type.def_type == .Function) { return try self.argumentList(resolved_type.resolved_type.?.Function.parameters, resolved_type.resolved_type.?.Function.has_defaults); } } else if (placeholder_type.resolved_type.?.Placeholder.resolved_parameters) |parameters| { return try self.argumentList(parameters, null); } // Otherwise parse the argument list as we find it and enrich placeholder assumptions var parsed_arguments = std.StringArrayHashMap(*ObjTypeDef).init(self.allocator); var arg_count: u8 = 0; while (!self.check(.RightParen)) { var hanging = false; var arg_name: ?Token = null; if (try self.match(.Identifier)) { arg_name = self.parser.previous_token.?; } if (arg_count != 0 and arg_name == null) { try self.reportError("Expected argument name."); break; } if (arg_name != null) { if (arg_count == 0) { if (try self.match(.Colon)) { hanging = false; } else { // The identifier we just parsed is not the argument name but the start of an expression hanging = true; } } else { try self.consume(.Colon, "Expected `:` after argument name."); } } var expr_type: *ObjTypeDef = try self.expression(hanging); // If hanging, the identifier is NOT the argument name try parsed_arguments.put(if (arg_name != null and !hanging) arg_name.?.lexeme else "{{first}}", expr_type); if (arg_count == 255) { try self.reportError("Can't have more than 255 arguments."); return 0; } arg_count += 1; if (!(try self.match(.Comma))) { break; } } try self.consume(.RightParen, "Expected `)` after arguments."); placeholder_type.resolved_type.?.Placeholder.resolved_parameters = parsed_arguments; return arg_count; } fn argumentList(self: *Self, function_parameters: ?std.StringArrayHashMap(*ObjTypeDef), defaults: ?std.StringArrayHashMap(bool)) !u8 { if (function_parameters) |parameters| { var parameter_keys: [][]const u8 = parameters.keys(); var missing_parameters = std.StringArrayHashMap(usize).init(self.allocator); defer missing_parameters.deinit(); for (parameter_keys) |param_name, pindex| { try missing_parameters.put(param_name, pindex); } var arg_count: u8 = 0; if (!self.check(.RightParen)) { var parsed_arguments = std.ArrayList(ParsedArg).init(self.allocator); defer parsed_arguments.deinit(); while (arg_count < parameter_keys.len) { var hanging = false; var arg_name: ?Token = null; if (try self.match(.Identifier)) { arg_name = self.parser.previous_token.?; } if (arg_count != 0 and arg_name == null) { try self.reportError("Expected argument name."); break; } if (arg_name != null) { if (arg_count == 0) { if (try self.match(.Colon)) { _ = missing_parameters.orderedRemove(arg_name.?.lexeme); hanging = false; } else { // The identifier we just parsed is not the argument name but the start of an expression hanging = true; } } else { _ = missing_parameters.orderedRemove(arg_name.?.lexeme); try self.consume(.Colon, "Expected `:` after argument name."); } } var expr_type: *ObjTypeDef = try self.expression(hanging); try parsed_arguments.append(ParsedArg{ .name = if (!hanging) arg_name else null, // If hanging, the identifier is NOT the argument name .arg_type = expr_type, }); if (arg_count == 255) { try self.reportError("Can't have more than 255 arguments."); return 0; } arg_count += 1; if (!(try self.match(.Comma))) { break; } } // Now that we parsed all arguments, check they match function definition var order_differs = false; for (parsed_arguments.items) |argument, index| { if (argument.name) |name| { if (!order_differs and !mem.eql(u8, parameter_keys[index], name.lexeme)) { order_differs = true; } var param_type = parameters.get(name.lexeme); // Does an argument with that name exists? if (param_type) |ptype| { // Is the argument type correct? if (!ptype.eql(argument.arg_type)) { var wrong_type_str: []u8 = try self.allocator.alloc(u8, 100); var param_type_str: []const u8 = try ptype.toString(self.allocator); var expr_type_str: []const u8 = try argument.arg_type.toString(self.allocator); defer { self.allocator.free(wrong_type_str); self.allocator.free(param_type_str); self.allocator.free(expr_type_str); } try self.reportError( try std.fmt.bufPrint( wrong_type_str, "Expected argument `{s}` to be `{s}`, got `{s}`.", .{ name, param_type_str, expr_type_str }, ), ); return 0; } } else { var wrong_name_str: []u8 = try self.allocator.alloc(u8, 100); defer self.allocator.free(wrong_name_str); try self.reportError(try std.fmt.bufPrint(wrong_name_str, "Argument named `{s}`, doesn't exist.", .{name.lexeme})); return 0; } } else { assert(index == 0); // First argument without name, check its type var param_type: *ObjTypeDef = parameters.get(parameter_keys[0]).?; if (!param_type.eql(argument.arg_type)) { var param_type_str: []const u8 = try param_type.toString(self.allocator); var expr_type_str: []const u8 = try argument.arg_type.toString(self.allocator); defer { self.allocator.free(param_type_str); self.allocator.free(expr_type_str); } var name: []const u8 = parameter_keys[0]; try self.reportErrorFmt( "Expected argument `{s}` to be `{s}`, got `{s}`.", .{ name, param_type_str, expr_type_str }, ); return 0; } _ = missing_parameters.orderedRemove(parameter_keys[0]); } } // For all missing parameters that have default value, we push void on the stack if (defaults) |udefaults| { var it = missing_parameters.iterator(); while (it.next()) |entry| { if (udefaults.get(entry.key_ptr.*) orelse false) { try self.emitOpCode(.OP_VOID); try parsed_arguments.append(ParsedArg{ .name = Token.identifier(entry.key_ptr.*), .arg_type = parameters.get(entry.key_ptr.*).?, }); arg_count += 1; order_differs = true; } } } // If order differ we emit OP_SWAP so that OP_CALL know where its arguments are if (order_differs) { // Until everything is in place while (true) { var ordered: bool = true; for (parsed_arguments.items) |argument, index| { assert(argument.name != null or index == 0); var arg_name: []const u8 = if (argument.name) |uname| uname.lexeme else parameter_keys[0]; if (!mem.eql(u8, arg_name, parameter_keys[index])) { ordered = false; // Search for the correct index for this argument for (parameter_keys) |param_name, pindex| { if (mem.eql(u8, param_name, arg_name)) { // TODO: both OP_SWAP args could fit in a 32 bit instruction try self.emitCodeArg(.OP_SWAP, @intCast(u24, arg_count - index - 1)); // to where it should be try self.emit(@intCast(u32, arg_count - pindex - 1)); // Swap it for the compiler too var temp = parsed_arguments.items[index]; parsed_arguments.items[index] = parsed_arguments.items[pindex]; parsed_arguments.items[pindex] = temp; // Stop (so we can take the swap into account) and try again break; } } } } if (ordered) break; } } } if (parameter_keys.len != arg_count) { try self.reportErrorFmt("Expected {} arguments, got {}", .{ parameter_keys.len, arg_count }); return 0; } try self.consume(.RightParen, "Expected `)` after arguments."); return arg_count; } // Empty argument list try self.consume(.RightParen, "Expected `)` after arguments."); return 0; } fn unary(self: *Self, _: bool) anyerror!*ObjTypeDef { var operator_type: TokenType = self.parser.previous_token.?.token_type; var parsed_type: *ObjTypeDef = try self.parsePrecedence(.Unary, false); switch (operator_type) { .Bang => { const bool_type = try self.getTypeDef(.{ .def_type = .Bool }); if (!bool_type.eql(parsed_type)) { try self.reportTypeCheck(bool_type, parsed_type, "Wrong operand type"); } try self.emitOpCode(.OP_NOT); }, .Minus => { const number_type = try self.getTypeDef(.{ .def_type = .Number }); if (!number_type.eql(parsed_type)) { try self.reportTypeCheck(number_type, parsed_type, "Wrong operand type"); } try self.emitOpCode(.OP_NEGATE); }, else => unreachable, } return parsed_type; } fn string(self: *Self, _: bool) anyerror!*ObjTypeDef { var string_scanner: StringScanner = StringScanner.init(self, self.parser.previous_token.?.literal_string.?); try string_scanner.parse(); return try self.getTypeDef(.{ .def_type = .String, }); } fn namedVariable(self: *Self, name: Token, can_assign: bool) anyerror!*ObjTypeDef { var get_op: OpCode = undefined; var set_op: OpCode = undefined; var var_def: *ObjTypeDef = undefined; var constant: bool = false; var arg: ?usize = try self.resolveLocal(self.current.?, name); if (arg) |resolved| { const local: Local = self.current.?.locals[resolved]; var_def = local.type_def; constant = local.constant; get_op = .OP_GET_LOCAL; set_op = .OP_SET_LOCAL; } else { arg = try self.resolveUpvalue(self.current.?, name); if (arg) |resolved| { const local: Local = self.current.?.enclosing.?.locals[self.current.?.upvalues[resolved].index]; var_def = local.type_def; constant = local.constant; get_op = .OP_GET_UPVALUE; set_op = .OP_SET_UPVALUE; } else { get_op = .OP_GET_GLOBAL; set_op = .OP_SET_GLOBAL; arg = (try self.resolveGlobal(null, name)) orelse (try self.declarePlaceholder(name, null)); const global = self.globals.items[arg.?]; var_def = self.globals.items[arg.?].type_def; constant = global.constant; } } if (can_assign and try self.match(.Equal)) { if (constant) { try self.reportError("`const` variable can't be assigned to."); } var expr_type: *ObjTypeDef = try self.expression(false); if (!expr_type.eql(var_def)) { try self.reportTypeCheck(var_def, expr_type, "Wrong value type"); } try self.emitCodeArg(set_op, @intCast(u24, arg.?)); } else { try self.emitCodeArg(get_op, @intCast(u24, arg.?)); } return var_def; } fn variable(self: *Self, can_assign: bool) anyerror!*ObjTypeDef { return try self.namedVariable(self.parser.previous_token.?, can_assign); } fn and_(self: *Self, _: bool, left_operand_type: *ObjTypeDef) anyerror!*ObjTypeDef { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Bool; } else if (left_operand_type.def_type != .Bool) { try self.reportError("`and` expects operands to be `bool`"); } const end_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); try self.emitOpCode(.OP_POP); var right_operand_type: *ObjTypeDef = try self.parsePrecedence(.And, false); if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Bool; } else if (right_operand_type.def_type != .Bool) { try self.reportError("`and` expects operands to be `bool`"); } try self.patchJump(end_jump); return right_operand_type; } fn or_(self: *Self, _: bool, left_operand_type: *ObjTypeDef) anyerror!*ObjTypeDef { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Bool; } else if (left_operand_type.def_type != .Bool) { try self.reportError("`or` expects operands to be `bool`"); } const else_jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); const end_jump: usize = try self.emitJump(.OP_JUMP); try self.patchJump(else_jump); try self.emitOpCode(.OP_POP); var right_operand_type: *ObjTypeDef = try self.parsePrecedence(.Or, false); if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Bool; } else if (right_operand_type.def_type != .Bool) { try self.reportError("`and` expects operands to be `bool`"); } try self.patchJump(end_jump); return right_operand_type; } fn is(self: *Self, _: bool, _: *ObjTypeDef) anyerror!*ObjTypeDef { try self.emitCodeArg(.OP_CONSTANT, try self.makeConstant(Value{ .Obj = (try self.parseTypeDef()).toObj() })); try self.emitOpCode(.OP_IS); return self.getTypeDef(ObjTypeDef{ .optional = false, .def_type = .Bool, }); } fn binary(self: *Self, _: bool, left_operand_type: *ObjTypeDef) anyerror!*ObjTypeDef { const operator_type: TokenType = self.parser.previous_token.?.token_type; const rule: ParseRule = getRule(operator_type); const right_operand_type: *ObjTypeDef = try self.parsePrecedence(@intToEnum(Precedence, @enumToInt(rule.precedence) + 1), false); if (!left_operand_type.eql(right_operand_type) and left_operand_type.def_type != .Placeholder and right_operand_type.def_type != .Placeholder) { try self.reportTypeCheck(left_operand_type, right_operand_type, "Type mismatch"); } switch (operator_type) { .QuestionQuestion => { if (!left_operand_type.optional or (left_operand_type.def_type == .Placeholder and left_operand_type.resolved_type.?.Placeholder.resolved_type != null and !left_operand_type.resolved_type.?.Placeholder.resolved_type.?.optional)) { try self.reportError("Not an optional"); } try self.emitOpCode(.OP_NULL_OR); return right_operand_type; }, .Greater => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_GREATER); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .Less => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_LESS); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .GreaterEqual => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_LESS); try self.emitOpCode(.OP_NOT); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .LessEqual => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_GREATER); try self.emitOpCode(.OP_NOT); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .BangEqual => { if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } try self.emitOpCode(.OP_EQUAL); try self.emitOpCode(.OP_NOT); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .EqualEqual => { if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } try self.emitOpCode(.OP_EQUAL); return self.getTypeDef(ObjTypeDef{ .def_type = .Bool, }); }, .Plus => { // zig fmt: off if (left_operand_type.def_type != .Number and left_operand_type.def_type != .String and left_operand_type.def_type != .List and left_operand_type.def_type != .Map and left_operand_type.def_type != .Placeholder) { try self.reportError("Expected `num` or `str`."); } // zig fmt: on if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad type."); } try self.emitOpCode(.OP_ADD); return left_operand_type; }, .Minus => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_SUBTRACT); return left_operand_type; }, .Star => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_MULTIPLY); return left_operand_type; }, .Slash => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_DIVIDE); return left_operand_type; }, .Percent => { if (left_operand_type.def_type == .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = .Number; } else if (left_operand_type.def_type != .Number) { try self.reportError("Expected `num`."); } if (right_operand_type.def_type == .Placeholder and left_operand_type.def_type != .Placeholder) { right_operand_type.resolved_type.?.Placeholder.resolved_def_type = left_operand_type.def_type; } else if (left_operand_type.def_type == .Placeholder and right_operand_type.def_type != .Placeholder) { left_operand_type.resolved_type.?.Placeholder.resolved_def_type = right_operand_type.def_type; } if (right_operand_type.def_type == .Placeholder and !right_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } if (left_operand_type.def_type == .Placeholder and !left_operand_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Can't be `num`."); } try self.emitOpCode(.OP_MOD); return left_operand_type; }, else => unreachable, } } fn subscript(self: *Self, can_assign: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef { // zig fmt: off if (callee_type.def_type != .List and callee_type.def_type != .Map and callee_type.def_type != .String and callee_type.def_type != .Placeholder and (callee_type.def_type != .Placeholder or !callee_type.resolved_type.?.Placeholder.isSubscriptable())) { try self.reportError("Not subscriptable."); } // zig fmt: on var item_type: ?*ObjTypeDef = null; if (callee_type.def_type == .String or (callee_type.def_type == .Placeholder and callee_type.resolved_type.?.Placeholder.resolved_def_type orelse .Void == .String)) { item_type = try self.getTypeDef(.{ .def_type = .String }); if (callee_type.def_type == .Placeholder) { try PlaceholderDef.link(callee_type, item_type.?, .Subscript); } var index_type: *ObjTypeDef = try self.expression(false); if (index_type.def_type != .Number) { if (index_type.def_type == .Placeholder and (index_type.resolved_type.?.Placeholder.resolved_def_type == null or index_type.resolved_type.?.Placeholder.resolved_def_type.? == .Number) and (index_type.resolved_type.?.Placeholder.resolved_type == null or index_type.resolved_type.?.Placeholder.resolved_type.?.def_type == .Number)) { index_type.resolved_type.?.Placeholder.resolved_def_type = .Number; index_type.resolved_type.?.Placeholder.resolved_type = try self.getTypeDef(.{ .def_type = .Number, }); } else { try self.reportError("Expected `num` index."); } } } else if (callee_type.def_type == .List or (callee_type.def_type == .Placeholder and callee_type.resolved_type.?.Placeholder.couldBeList())) { if (callee_type.def_type == .List) { item_type = callee_type.resolved_type.?.List.item_type; } else { assert(callee_type.def_type == .Placeholder); // item_type is a placeholder var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?) }; if (callee_type.resolved_type.?.Placeholder.resolved_type) |resolved| { if (resolved.def_type == .List) { placeholder_resolved_type.Placeholder.resolved_def_type = resolved.resolved_type.?.List.item_type.def_type; placeholder_resolved_type.Placeholder.resolved_type = resolved.resolved_type.?.List.item_type; } else { try self.reportError("Not a list."); } } item_type = try self.getTypeDef(.{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type }); try PlaceholderDef.link(callee_type, item_type.?, .Subscript); } var index_type: *ObjTypeDef = try self.expression(false); if (index_type.def_type != .Number) { if (index_type.def_type == .Placeholder and (index_type.resolved_type.?.Placeholder.resolved_def_type == null or index_type.resolved_type.?.Placeholder.resolved_def_type.? == .Number) and (index_type.resolved_type.?.Placeholder.resolved_type == null or index_type.resolved_type.?.Placeholder.resolved_type.?.def_type == .Number)) { index_type.resolved_type.?.Placeholder.resolved_def_type = .Number; index_type.resolved_type.?.Placeholder.resolved_type = try self.getTypeDef(.{ .def_type = .Number, }); } else { try self.reportError("Expected `num` index."); } } } else if (callee_type.def_type == .Map or (callee_type.def_type == .Placeholder and callee_type.resolved_type.?.Placeholder.couldBeMap())) { if (callee_type.def_type == .Map) { item_type = callee_type.resolved_type.?.Map.value_type; } else { assert(callee_type.def_type == .Placeholder); // item_type is a placeholder var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; if (callee_type.resolved_type.?.Placeholder.resolved_type) |resolved| { placeholder_resolved_type.Placeholder.resolved_def_type = resolved.resolved_type.?.Map.value_type.def_type; placeholder_resolved_type.Placeholder.resolved_type = resolved.resolved_type.?.Map.value_type; } item_type = try self.getTypeDef(.{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type }); try PlaceholderDef.link(callee_type, item_type.?, .Subscript); } var key_type: *ObjTypeDef = try self.expression(false); if (callee_type.def_type == .Map) { if (!callee_type.resolved_type.?.Map.key_type.eql(key_type)) { try self.reportTypeCheck(callee_type.resolved_type.?.Map.key_type, key_type, "Wrong map key type"); } } else { assert(callee_type.def_type == .Placeholder); // key_type is a placeholder var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?) }; if (callee_type.resolved_type.?.Placeholder.resolved_type) |resolved| { if (resolved.def_type == .Map) { placeholder_resolved_type.Placeholder.resolved_def_type = resolved.resolved_type.?.Map.key_type.def_type; placeholder_resolved_type.Placeholder.resolved_type = resolved.resolved_type.?.Map.key_type; } else { try self.reportError("Not a map"); } } var placeholder = try self.getTypeDef(ObjTypeDef{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type }); try PlaceholderDef.link(callee_type, placeholder, .Key); if (!ObjTypeDef.eql(placeholder, key_type)) { try self.reportError("Wrong map key type."); } } } try self.consume(.RightBracket, "Expected `]`."); if (can_assign and try self.match(.Equal) and callee_type.def_type != .String and (callee_type.def_type != .Placeholder or callee_type.resolved_type.?.Placeholder.resolved_def_type orelse .Void != .String)) { var parsed_type: *ObjTypeDef = try self.expression(false); if (item_type != null and !item_type.?.eql(parsed_type)) { try self.reportTypeCheck(item_type.?, parsed_type, "Bad list assignment."); } try self.emitOpCode(.OP_SET_SUBSCRIPT); } else { if (callee_type.def_type == .Map and item_type != null) { item_type = try item_type.?.cloneOptional(self); } try self.emitOpCode(.OP_GET_SUBSCRIPT); } return item_type orelse callee_type; } fn call(self: *Self, _: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef { var arg_count: u8 = 0; if (callee_type.def_type == .Function) { arg_count = try self.argumentList(callee_type.resolved_type.?.Function.parameters, callee_type.resolved_type.?.Function.has_defaults); try self.emitCodeArgs( .OP_CALL, arg_count, try self.inlineCatch(callee_type.resolved_type.?.Function.return_type), ); return callee_type.resolved_type.?.Function.return_type; } else if (callee_type.def_type == .Native) { arg_count = try self.argumentList(callee_type.resolved_type.?.Native.parameters, callee_type.resolved_type.?.Native.has_defaults); try self.emitCodeArgs( .OP_CALL, arg_count, try self.inlineCatch(callee_type.resolved_type.?.Native.return_type), ); return callee_type.resolved_type.?.Native.return_type; } else if (callee_type.def_type == .Placeholder) { if (self.current.?.scope_depth == 0) { try self.reportError("Unknown expression type."); return callee_type; } callee_type.resolved_type.?.Placeholder.callable = callee_type.resolved_type.?.Placeholder.callable orelse true; if (!callee_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(callee_type.resolved_type.?.Placeholder.where, "Can't be called"); return callee_type; } // Call it arg_count = try self.placeholderArgumentList(callee_type); // We know nothing of the return value var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?) }; var placeholder = try self.getTypeDef(.{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type }); try PlaceholderDef.link(callee_type, placeholder, .Call); // TODO: does this work? try self.emitCodeArgs( .OP_CALL, arg_count, try self.inlineCatch(placeholder), ); return placeholder; } try self.reportError("Can't be called"); return callee_type; } fn unwrap(self: *Self, _: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef { if (!callee_type.optional or (callee_type.def_type == .Placeholder and callee_type.resolved_type.?.Placeholder.resolved_type != null and !callee_type.resolved_type.?.Placeholder.resolved_type.?.optional)) { try self.reportError("Not an optional."); } try self.emitCodeArg(.OP_COPY, 1); try self.emitOpCode(.OP_NULL); try self.emitOpCode(.OP_EQUAL); try self.emitOpCode(.OP_NOT); const jump: usize = try self.emitJump(.OP_JUMP_IF_FALSE); if (self.opt_jumps == null) { self.opt_jumps = std.ArrayList(OptJump).init(self.allocator); } try self.opt_jumps.?.append(.{ .jump = jump, .precedence = getRule(self.parser.current_token.?.token_type).precedence }); try self.emitOpCode(.OP_POP); // Pop test result var unwrapped: ObjTypeDef = callee_type.*; unwrapped.optional = false; return self.getTypeDef(unwrapped); } fn forceUnwrap(self: *Self, _: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef { if (!callee_type.optional or (callee_type.def_type == .Placeholder and callee_type.resolved_type.?.Placeholder.resolved_type != null and !callee_type.resolved_type.?.Placeholder.resolved_type.?.optional)) { try self.reportError("Not an optional."); } try self.emitOpCode(.OP_UNWRAP); var unwrapped: ObjTypeDef = callee_type.*; unwrapped.optional = false; return self.getTypeDef(unwrapped); } fn getSuperMethod(self: *Self, object: *ObjTypeDef, name: []const u8) ?*ObjTypeDef { const obj_def: ObjObject.ObjectDef = object.resolved_type.?.Object; if (obj_def.methods.get(name)) |obj_method| { return obj_method; } else if (obj_def.super) |obj_super| { return self.getSuperMethod(obj_super, name); } return null; } fn getSuperField(self: *Self, object: *ObjTypeDef, name: []const u8) ?*ObjTypeDef { const obj_def: ObjObject.ObjectDef = object.resolved_type.?.Object; if (obj_def.fields.get(name)) |obj_field| { return obj_field; } else if (obj_def.super) |obj_super| { return self.getSuperField(obj_super, name); } return null; } fn dot(self: *Self, can_assign: bool, callee_type: *ObjTypeDef) anyerror!*ObjTypeDef { // zig fmt: off if (callee_type.def_type != .ObjectInstance and callee_type.def_type != .Object and callee_type.def_type != .Enum and callee_type.def_type != .EnumInstance and callee_type.def_type != .List and callee_type.def_type != .Map and callee_type.def_type != .Placeholder and callee_type.def_type != .String) { try self.reportError("Doesn't have field access."); } // zig fmt: on try self.consume(.Identifier, "Expected property name after `.`"); var member_name: []const u8 = self.parser.previous_token.?.lexeme; var name: u24 = try self.identifierConstant(self.parser.previous_token.?.lexeme); // Check that name is a property switch (callee_type.def_type) { .String => { if (try ObjString.memberDef(self, member_name)) |member| { if (try self.match(.LeftParen)) { try self.emitOpCode(.OP_COPY); // String is first argument var arg_count: u8 = try self.argumentList(member.resolved_type.?.Native.parameters, member.resolved_type.?.Native.has_defaults); try self.emitCodeArg(.OP_INVOKE, name); try self.emitTwo(arg_count + 1, try self.inlineCatch(member.resolved_type.?.Native.return_type)); return member.resolved_type.?.Native.return_type; } // Else just get it try self.emitCodeArg(.OP_GET_PROPERTY, name); return member; } try self.reportError("String property doesn't exist."); return callee_type; }, .Object => { var obj_def: ObjObject.ObjectDef = callee_type.resolved_type.?.Object; var property_type: ?*ObjTypeDef = obj_def.static_fields.get(member_name); // Not found, create a placeholder // TODO: test with something else than a name if (property_type == null and self.current_object != null and std.mem.eql(u8, self.current_object.?.name.lexeme, obj_def.name.string)) { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; var placeholder: *ObjTypeDef = try self.getTypeDef(.{ .optional = false, .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }); try callee_type.resolved_type.?.Object.static_placeholders.put(member_name, placeholder); property_type = placeholder; } // Do we assign to it? if (can_assign and try self.match(.Equal)) { if (property_type.?.def_type == .Placeholder) { property_type.?.resolved_type.?.Placeholder.assignable = true; if (!property_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(property_type.?.resolved_type.?.Placeholder.where, "Can't be assigned to."); return property_type.?; } } var parsed_type: *ObjTypeDef = try self.expression(false); if (!parsed_type.eql(property_type.?)) { try self.reportTypeCheck(property_type.?, parsed_type, "Static field value"); } try self.emitCodeArg(.OP_SET_PROPERTY, name); return parsed_type; } // Do we call it? if (try self.match(.LeftParen)) { if (property_type.?.def_type == .Placeholder) { property_type.?.resolved_type.?.Placeholder.callable = true; if (!property_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(property_type.?.resolved_type.?.Placeholder.where, "Can't be called."); return property_type.?; } } if (property_type.?.def_type != .Function and property_type.?.def_type != .Placeholder) { try self.reportError("Can't be called."); } try self.emitCodeArg(.OP_GET_PROPERTY, name); const arg_count: u8 = try self.argumentList(property_type.?.resolved_type.?.Function.parameters, property_type.?.resolved_type.?.Function.has_defaults); try self.emitCodeArgs(.OP_CALL, arg_count, try self.inlineCatch(property_type.?.resolved_type.?.Function.return_type)); return property_type.?.resolved_type.?.Function.return_type; } // Else just get it try self.emitCodeArg(.OP_GET_PROPERTY, name); return property_type.?; }, .ObjectInstance => { var object: *ObjTypeDef = callee_type.resolved_type.?.ObjectInstance; var obj_def: ObjObject.ObjectDef = object.resolved_type.?.Object; var property_type: ?*ObjTypeDef = obj_def.methods.get(member_name) orelse self.getSuperMethod(object, member_name); var is_method: bool = property_type != null; property_type = property_type orelse obj_def.fields.get(member_name) orelse obj_def.placeholders.get(member_name) orelse self.getSuperField(object, member_name); // Else create placeholder if (property_type == null and self.current_object != null and std.mem.eql(u8, self.current_object.?.name.lexeme, obj_def.name.string)) { var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; var placeholder: *ObjTypeDef = try self.getTypeDef(.{ .optional = false, .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }); try callee_type.resolved_type.?.ObjectInstance.resolved_type.?.Object.placeholders.put(member_name, placeholder); property_type = placeholder; } else if (property_type == null) { try self.reportErrorFmt("Property or method `{s}` does not exists.", .{member_name}); } // If its a field or placeholder, we can assign to it // TODO: here get info that field is constant or not if (can_assign and try self.match(.Equal)) { if (property_type.?.def_type == .Placeholder) { property_type.?.resolved_type.?.Placeholder.assignable = true; if (!property_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(property_type.?.resolved_type.?.Placeholder.where, "Can't be assigned to."); return property_type.?; } } if (is_method and property_type.?.def_type != .Placeholder) { try self.reportError("Can't be assigned to."); } var parsed_type: *ObjTypeDef = try self.expression(false); if (!parsed_type.eql(property_type.?)) { try self.reportTypeCheck(property_type.?, parsed_type, "Property value"); } try self.emitCodeArg(.OP_SET_PROPERTY, name); return parsed_type; } // If it's a method or placeholder we can call it if (try self.match(.LeftParen)) { if (property_type.?.def_type == .Placeholder) { property_type.?.resolved_type.?.Placeholder.callable = true; if (!property_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(property_type.?.resolved_type.?.Placeholder.where, "Can't be called."); return property_type.?; } } if (!is_method and property_type.?.def_type != .Function and property_type.?.def_type != .Placeholder) { try self.reportError("Can't be called."); } var arg_count: u8 = try self.argumentList(property_type.?.resolved_type.?.Function.parameters, property_type.?.resolved_type.?.Function.has_defaults); try self.emitCodeArg(.OP_INVOKE, name); try self.emitTwo(arg_count, try self.inlineCatch(property_type.?.resolved_type.?.Function.return_type)); return property_type.?.resolved_type.?.Function.return_type; } // Else just get it try self.emitCodeArg(.OP_GET_PROPERTY, name); return property_type.?; }, .Enum => { var enum_def: ObjEnum.EnumDef = callee_type.resolved_type.?.Enum; for (enum_def.cases.items) |case, index| { if (mem.eql(u8, case, member_name)) { try self.emitCodeArg(.OP_GET_ENUM_CASE, @intCast(u24, index)); var enum_instance_resolved_type: ObjTypeDef.TypeUnion = .{ .EnumInstance = callee_type, }; var enum_instance: *ObjTypeDef = try self.getTypeDef(.{ .optional = try self.match(.Question), .def_type = .EnumInstance, .resolved_type = enum_instance_resolved_type, }); return enum_instance; } } try self.reportError("Enum case doesn't exists."); return callee_type; }, .EnumInstance => { // Only available field is `.value` to get associated value if (!mem.eql(u8, member_name, "value")) { try self.reportError("Enum provides only field `value`."); } try self.emitOpCode(.OP_GET_ENUM_CASE_VALUE); return callee_type.resolved_type.?.EnumInstance.resolved_type.?.Enum.enum_type; }, .List => { if (try ObjList.ListDef.member(callee_type, self, member_name)) |member| { if (try self.match(.LeftParen)) { try self.emitOpCode(.OP_COPY); // List is first argument var arg_count: u8 = try self.argumentList(member.resolved_type.?.Native.parameters, member.resolved_type.?.Native.has_defaults); try self.emitCodeArg(.OP_INVOKE, name); try self.emitTwo(arg_count + 1, try self.inlineCatch(member.resolved_type.?.Native.return_type)); return member.resolved_type.?.Native.return_type; } // Else just get it try self.emitCodeArg(.OP_GET_PROPERTY, name); return member; } try self.reportError("List property doesn't exist."); return callee_type; }, .Map => { if (try ObjMap.MapDef.member(callee_type, self, member_name)) |member| { if (try self.match(.LeftParen)) { try self.emitOpCode(.OP_COPY); // Map is first argument var arg_count: u8 = try self.argumentList(member.resolved_type.?.Native.parameters, member.resolved_type.?.Native.has_defaults); try self.emitCodeArg(.OP_INVOKE, name); try self.emitTwo(arg_count + 1, try self.inlineCatch(member.resolved_type.?.Native.return_type)); return member.resolved_type.?.Native.return_type; } // Else just get it try self.emitCodeArg(.OP_GET_PROPERTY, name); return member; } try self.reportError("Map property doesn't exist."); return callee_type; }, .Placeholder => { callee_type.resolved_type.?.Placeholder.field_accessible = callee_type.resolved_type.?.Placeholder.field_accessible orelse true; if (!callee_type.resolved_type.?.Placeholder.isCoherent()) { // TODO: how to have a revelant message here? try self.reportErrorAt(callee_type.resolved_type.?.Placeholder.where, "[Bad assumption] doesn't support field access (and something else)"); return callee_type; } // We know nothing of field var placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; placeholder_resolved_type.Placeholder.name = try copyStringRaw(self.strings, self.allocator, member_name, false); var placeholder = try self.getTypeDef( .{ .def_type = .Placeholder, .resolved_type = placeholder_resolved_type, }, ); try PlaceholderDef.link(callee_type, placeholder, .FieldAccess); if (can_assign and try self.match(.Equal)) { var parsed_type: *ObjTypeDef = try self.expression(false); try self.emitCodeArg(.OP_SET_PROPERTY, name); if (parsed_type.def_type != .Placeholder) { placeholder.resolved_type.?.Placeholder.resolved_def_type = parsed_type.def_type; placeholder.resolved_type.?.Placeholder.resolved_type = parsed_type; if (!placeholder.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(placeholder.resolved_type.?.Placeholder.where, "[Bad assumption] can't be set or bad type."); } } } else if (try self.match(.LeftParen)) { placeholder.resolved_type.?.Placeholder.callable = true; if (!placeholder.resolved_type.?.Placeholder.isCoherent()) { try self.reportErrorAt(placeholder.resolved_type.?.Placeholder.where, "[Bad assumption] can't be called."); } var arg_count: u8 = try self.placeholderArgumentList(placeholder); // We know nothing of the return value var return_placeholder_resolved_type: ObjTypeDef.TypeUnion = .{ .Placeholder = PlaceholderDef.init(self.allocator, self.parser.previous_token.?), }; var return_placeholder = try self.getTypeDef( .{ .def_type = .Placeholder, .resolved_type = return_placeholder_resolved_type, }, ); try PlaceholderDef.link(placeholder, return_placeholder, .Call); try self.emitCodeArg(.OP_INVOKE, name); try self.emitTwo(arg_count, try self.inlineCatch(return_placeholder)); } else { try self.emitCodeArg(.OP_GET_PROPERTY, name); } return placeholder; }, else => unreachable, } unreachable; } fn list(self: *Self, _: bool) anyerror!*ObjTypeDef { var item_type: ?*ObjTypeDef = null; // A lone list expression is prefixed by `<type>` if (self.parser.previous_token.?.token_type == .Less) { item_type = try self.parseTypeDef(); if (try self.match(.Comma)) { return try self.mapFinalise(item_type.?); } try self.consume(.Greater, "Expected `>` after list type."); try self.consume(.LeftBracket, "Expected `[` after list type."); } const list_offset: usize = try self.emitList(); while (!(try self.match(.RightBracket)) and !(try self.match(.Eof))) { var actual_item_type: *ObjTypeDef = try self.expression(false); try self.emitOpCode(.OP_LIST_APPEND); if (item_type != null and !item_type.?.eql(actual_item_type)) { try self.reportError("List can only hold one type."); } if (item_type != null and item_type.?.def_type == .Placeholder and actual_item_type.def_type != .Placeholder) { item_type.?.resolved_type.?.Placeholder.resolved_def_type = actual_item_type.def_type; item_type.?.resolved_type.?.Placeholder.resolved_type = actual_item_type; if (item_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad list type."); } } if (actual_item_type.def_type == .Placeholder and item_type != null and item_type.?.def_type != .Placeholder) { actual_item_type.resolved_type.?.Placeholder.resolved_def_type = item_type.?.def_type; actual_item_type.resolved_type.?.Placeholder.resolved_type = item_type.?; if (actual_item_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad list item type."); } } if (item_type == null) { item_type = actual_item_type; } if (!self.check(.RightBracket)) { try self.consume(.Comma, "Expected `,` after list item."); } } var list_def = ObjList.ListDef.init(self.allocator, item_type.?); var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .List = list_def }; var list_type: *ObjTypeDef = try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .List, .resolved_type = resolved_type, }, ); // Should be fine if placeholder because when resolved, it's always the same pointer const list_type_constant: u24 = try self.makeConstant(Value{ .Obj = list_type.toObj() }); try self.patchList(list_offset, list_type_constant); return list_type; } fn map(self: *Self, _: bool) anyerror!*ObjTypeDef { return try self.mapFinalise(null); } fn mapFinalise(self: *Self, parsed_key_type: ?*ObjTypeDef) anyerror!*ObjTypeDef { var value_type: ?*ObjTypeDef = null; var key_type: ?*ObjTypeDef = parsed_key_type; // A lone map expression is prefixed by `<type, type>` // When key_type != null, we come from list() which just parsed `<type,` if (key_type != null) { value_type = try self.parseTypeDef(); try self.consume(.Greater, "Expected `>` after map type."); try self.consume(.LeftBrace, "Expected `{` before map entries."); } const map_offset: usize = try self.emitMap(); while (!(try self.match(.RightBrace)) and !(try self.match(.Eof))) { var actual_key_type: *ObjTypeDef = try self.expression(false); try self.consume(.Colon, "Expected `:` after key."); var actual_value_type: *ObjTypeDef = try self.expression(false); try self.emitOpCode(.OP_SET_MAP); // Key type checking if (key_type != null and !key_type.?.eql(actual_key_type)) { try self.reportError("Map can only hold one key type."); } if (key_type != null and key_type.?.def_type == .Placeholder and actual_key_type.def_type != .Placeholder) { key_type.?.resolved_type.?.Placeholder.resolved_def_type = actual_key_type.def_type; key_type.?.resolved_type.?.Placeholder.resolved_type = actual_key_type; if (key_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad map type."); } } if (actual_key_type.def_type == .Placeholder and key_type != null and key_type.?.def_type != .Placeholder) { actual_key_type.resolved_type.?.Placeholder.resolved_def_type = key_type.?.def_type; actual_key_type.resolved_type.?.Placeholder.resolved_type = key_type; if (actual_key_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad map item type."); } } if (key_type == null) { key_type = actual_key_type; } // Value type checking if (value_type != null and !value_type.?.eql(actual_value_type)) { try self.reportError("Map can only hold one value type."); } if (value_type != null and value_type.?.def_type == .Placeholder and actual_value_type.def_type != .Placeholder) { value_type.?.resolved_type.?.Placeholder.resolved_def_type = actual_value_type.def_type; value_type.?.resolved_type.?.Placeholder.resolved_type = actual_value_type; if (value_type.?.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad map type."); } } if (actual_value_type.def_type == .Placeholder and value_type != null and value_type.?.def_type != .Placeholder) { actual_value_type.resolved_type.?.Placeholder.resolved_def_type = value_type.?.def_type; actual_value_type.resolved_type.?.Placeholder.resolved_type = value_type.?; if (actual_value_type.resolved_type.?.Placeholder.isCoherent()) { try self.reportError("Bad map item type."); } } if (value_type == null) { value_type = actual_value_type; } if (!self.check(.RightBrace)) { try self.consume(.Comma, "Expected `,` after map entry."); } } var map_def = ObjMap.MapDef.init(self.allocator, key_type.?, value_type.?); var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .Map = map_def }; var map_type: *ObjTypeDef = try self.getTypeDef( .{ .optional = try self.match(.Question), .def_type = .Map, .resolved_type = resolved_type, }, ); // Should be fine if placeholder because when resolved, it's always the same pointer const map_type_constant: u24 = try self.makeConstant(Value{ .Obj = map_type.toObj() }); try self.patchMap(map_offset, map_type_constant); return map_type; } fn grouping(self: *Self, _: bool) anyerror!*ObjTypeDef { var parsed_type: *ObjTypeDef = try self.expression(false); try self.consume(.RightParen, "Expected ')' after expression."); return parsed_type; } fn literal(self: *Self, _: bool) anyerror!*ObjTypeDef { switch (self.parser.previous_token.?.token_type) { .False => { try self.emitOpCode(.OP_FALSE); return try self.getTypeDef(.{ .def_type = .Bool, }); }, .True => { try self.emitOpCode(.OP_TRUE); return try self.getTypeDef(.{ .def_type = .Bool, }); }, .Null => { try self.emitOpCode(.OP_NULL); return try self.getTypeDef(.{ .def_type = .Void, }); }, else => unreachable, } } fn number(self: *Self, _: bool) anyerror!*ObjTypeDef { var value: f64 = self.parser.previous_token.?.literal_number.?; try self.emitConstant(Value{ .Number = value }); return try self.getTypeDef(.{ .def_type = .Number, }); } pub fn emitConstant(self: *Self, value: Value) !void { try self.emitCodeArg(.OP_CONSTANT, try self.makeConstant(value)); } // LOCALS fn addLocal(self: *Self, name: Token, local_type: *ObjTypeDef, constant: bool) !usize { if (self.current.?.local_count == 255) { try self.reportError("Too many local variables in scope."); return 0; } self.current.?.locals[self.current.?.local_count] = Local{ .name = try copyStringRaw(self.strings, self.allocator, name.lexeme, false), .depth = -1, .is_captured = false, .type_def = local_type, .constant = constant, }; self.current.?.local_count += 1; return self.current.?.local_count - 1; } fn addGlobal(self: *Self, name: Token, global_type: *ObjTypeDef, constant: bool) !usize { // Search for an existing placeholder global with the same name for (self.globals.items) |global, index| { if (global.type_def.def_type == .Placeholder and global.type_def.resolved_type.?.Placeholder.name != null and mem.eql(u8, name.lexeme, global.name.string)) { try self.resolvePlaceholder(global.type_def, global_type, constant); return index; } } if (self.globals.items.len == 255) { try self.reportError("Too many global variables."); return 0; } try self.globals.append( Global{ .name = try copyStringRaw(self.strings, self.allocator, name.lexeme, false), .type_def = global_type, .constant = constant, }, ); return self.globals.items.len - 1; } fn resolveLocal(self: *Self, compiler: *ChunkCompiler, name: Token) !?usize { if (compiler.local_count == 0) { return null; } var i: usize = compiler.local_count - 1; while (i >= 0) : (i -= 1) { var local: *Local = &compiler.locals[i]; if (mem.eql(u8, name.lexeme, local.name.string)) { if (local.depth == -1) { try self.reportError("Can't read local variable in its own initializer."); } return i; } if (i == 0) break; } return null; } // Will consume tokens if find a prefixed identifier fn resolveGlobal(self: *Self, prefix: ?[]const u8, name: Token) anyerror!?usize { if (self.globals.items.len == 0) { return null; } var i: usize = self.globals.items.len - 1; while (i >= 0) : (i -= 1) { var global: *Global = &self.globals.items[i]; if (((prefix == null and global.prefix == null) or (prefix != null and global.prefix != null and mem.eql(u8, prefix.?, global.prefix.?))) and mem.eql(u8, name.lexeme, global.name.string) and !global.hidden) { if (!global.initialized) { try self.reportError("Can't read global variable in its own initializer."); } return i; // Is it an import prefix? } else if (global.prefix != null and mem.eql(u8, name.lexeme, global.prefix.?)) { try self.consume(.Dot, "Expected `.` after import prefix."); try self.consume(.Identifier, "Expected identifier after import prefix."); return try self.resolveGlobal(global.prefix.?, self.parser.previous_token.?); } if (i == 0) break; } return null; } fn addUpvalue(self: *Self, compiler: *ChunkCompiler, index: usize, is_local: bool) !usize { var upvalue_count: u8 = compiler.function.upvalue_count; var i: usize = 0; while (i < upvalue_count) : (i += 1) { var upvalue: *UpValue = &compiler.upvalues[i]; if (upvalue.index == index and upvalue.is_local == is_local) { return i; } } if (upvalue_count == 255) { try self.reportError("Too many closure variables in function."); return 0; } compiler.upvalues[upvalue_count].is_local = is_local; compiler.upvalues[upvalue_count].index = @intCast(u8, index); compiler.function.upvalue_count += 1; return compiler.function.upvalue_count - 1; } fn resolveUpvalue(self: *Self, compiler: *ChunkCompiler, name: Token) anyerror!?usize { if (compiler.enclosing == null) { return null; } var local: ?usize = try self.resolveLocal(compiler.enclosing.?, name); if (local) |resolved| { compiler.enclosing.?.locals[resolved].is_captured = true; return try self.addUpvalue(compiler, resolved, true); } var upvalue: ?usize = try self.resolveUpvalue(compiler.enclosing.?, name); if (upvalue) |resolved| { return try self.addUpvalue(compiler, resolved, false); } return null; } fn identifiersEqual(a: Token, b: Token) bool { if (a.lexeme.len != b.lexeme.len) { return false; } return mem.eql(u8, a.lexeme, b.lexeme); } // VARIABLES fn parseVariable(self: *Self, variable_type: *ObjTypeDef, constant: bool, error_message: []const u8) !usize { try self.consume(.Identifier, error_message); return try self.declareVariable(variable_type, null, constant); } inline fn markInitialized(self: *Self) void { if (self.current.?.scope_depth == 0) { self.globals.items[self.globals.items.len - 1].initialized = true; } else { self.current.?.locals[self.current.?.local_count - 1].depth = @intCast(i32, self.current.?.scope_depth); } } fn declareVariable(self: *Self, variable_type: *ObjTypeDef, name_token: ?Token, constant: bool) !usize { var name: Token = name_token orelse self.parser.previous_token.?; if (self.current.?.scope_depth > 0) { // Check a local with the same name doesn't exists var i: usize = self.current.?.locals.len - 1; while (i >= 0) : (i -= 1) { var local: *Local = &self.current.?.locals[i]; if (local.depth != -1 and local.depth < self.current.?.scope_depth) { break; } if (mem.eql(u8, name.lexeme, local.name.string)) { try self.reportError("A variable with the same name already exists in this scope."); } if (i == 0) break; } return try self.addLocal(name, variable_type, constant); } else { // Check a global with the same name doesn't exists for (self.globals.items) |global, index| { if (mem.eql(u8, name.lexeme, global.name.string) and !global.hidden) { // If we found a placeholder with that name, try to resolve it with `variable_type` if (global.type_def.def_type == .Placeholder and global.type_def.resolved_type.?.Placeholder.name != null and mem.eql(u8, name.lexeme, global.type_def.resolved_type.?.Placeholder.name.?.string)) { // A function declares a global with an incomplete typedef so that it can handle recursion // The placeholder resolution occurs after we parsed the functions body in `funDeclaration` if (variable_type.resolved_type != null or @enumToInt(variable_type.def_type) < @enumToInt(ObjTypeDef.Type.ObjectInstance)) { try self.resolvePlaceholder(global.type_def, variable_type, constant); } return index; } else { try self.reportError("A global with the same name already exists."); } } } return try self.addGlobal(name, variable_type, constant); } } fn makeConstant(self: *Self, value: Value) !u24 { var constant: u24 = try self.current.?.function.chunk.addConstant(null, value); if (constant > Chunk.max_constants) { try self.reportError("Too many constants in one chunk."); return 0; } return constant; } fn identifierConstant(self: *Self, name: []const u8) !u24 { return try self.makeConstant(Value{ .Obj = (try copyStringRaw(self.strings, self.allocator, name, false)).toObj() }); } };
src/compiler.zig
const std = @import("std"); const rpc = @import("antiphony"); const CreateError = error{ OutOfMemory, UnknownCounter }; const UsageError = error{ OutOfMemory, UnknownCounter }; // Define our RPC service via function signatures. const RcpDefinition = rpc.CreateDefinition(.{ .host = .{ .createCounter = fn () CreateError!u32, .destroyCounter = fn (u32) void, .increment = fn (u32, u32) UsageError!u32, .getCount = fn (u32) UsageError!u32, }, .client = .{ .signalError = fn (msg: []const u8) void, }, }); fn clientImplementation(file: std.fs.File) !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const ClientImpl = struct { pub fn signalError(msg: []const u8) void { std.log.err("remote error: {s}", .{msg}); } }; const EndPoint = RcpDefinition.ClientEndPoint(std.fs.File.Reader, std.fs.File.Writer, ClientImpl); var end_point = EndPoint.init( gpa.allocator(), file.reader(), file.writer(), ); defer end_point.destroy(); var impl = ClientImpl{}; try end_point.connect(&impl); // establish RPC handshake const handle = try end_point.invoke("createCounter", .{}); std.log.info("first increment: {}", .{try end_point.invoke("increment", .{ handle, 5 })}); std.log.info("second increment: {}", .{try end_point.invoke("increment", .{ handle, 3 })}); std.log.info("third increment: {}", .{try end_point.invoke("increment", .{ handle, 7 })}); std.log.info("final count: {}", .{try end_point.invoke("getCount", .{handle})}); try end_point.invoke("destroyCounter", .{handle}); _ = end_point.invoke("getCount", .{handle}) catch |err| std.log.info("error while calling getCount() with invalid handle: {s}", .{@errorName(err)}); } fn hostImplementation(file: std.fs.File) !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const HostImpl = struct { const Self = @This(); const EndPoint = RcpDefinition.HostEndPoint(std.fs.File.Reader, std.fs.File.Writer, Self); counters: std.ArrayList(?u32), end_point: *EndPoint, fn sendErrorMessage(self: Self, msg: []const u8) void { self.end_point.invoke("signalError", .{msg}) catch |err| std.log.err("failed to send error message: {s}", .{@errorName(err)}); } pub fn createCounter(self: *Self) CreateError!u32 { const index = @truncate(u32, self.counters.items.len); try self.counters.append(0); return index; } pub fn destroyCounter(self: *Self, handle: u32) void { if (handle >= self.counters.items.len) { self.sendErrorMessage("unknown counter"); return; } self.counters.items[handle] = null; } pub fn increment(self: *Self, handle: u32, count: u32) UsageError!u32 { if (handle >= self.counters.items.len) { self.sendErrorMessage("This counter does not exist!"); return error.UnknownCounter; } if (self.counters.items[handle]) |*counter| { const previous = counter.*; counter.* +%= count; return previous; } else { self.sendErrorMessage("This counter was already deleted!"); return error.UnknownCounter; } } pub fn getCount(self: *Self, handle: u32) UsageError!u32 { if (handle >= self.counters.items.len) { self.sendErrorMessage("This counter does not exist!"); return error.UnknownCounter; } if (self.counters.items[handle]) |value| { return value; } else { self.sendErrorMessage("This counter was already deleted!"); return error.UnknownCounter; } } }; var end_point = HostImpl.EndPoint.init( gpa.allocator(), // we need some basic session management file.reader(), // data input file.writer(), // data output ); defer end_point.destroy(); var impl = HostImpl{ .counters = std.ArrayList(?u32).init(gpa.allocator()), .end_point = &end_point, }; defer impl.counters.deinit(); try end_point.connect(&impl); // establish RPC handshake try end_point.acceptCalls(); // blocks until client exits. } // This main function just creates a socket pair and hands them off to two threads that perform some RPC calls. pub fn main() !void { var sockets: [2]i32 = undefined; if (std.os.linux.socketpair(std.os.linux.AF.UNIX, std.os.linux.SOCK.STREAM, 0, &sockets) != 0) return error.SocketPairError; var socket_a = std.fs.File{ .handle = sockets[0] }; defer socket_a.close(); var socket_b = std.fs.File{ .handle = sockets[1] }; defer socket_b.close(); { var client_thread = try std.Thread.spawn(.{}, clientImplementation, .{socket_a}); defer client_thread.join(); var host_thread = try std.Thread.spawn(.{}, hostImplementation, .{socket_b}); defer host_thread.join(); } }
examples/linux.zig
const std = @import("std"); const backend = @import("backend.zig"); const Widget = @import("widget.zig").Widget; const lasting_allocator = @import("internal.zig").lasting_allocator; const Size = @import("data.zig").Size; const Rectangle = @import("data.zig").Rectangle; pub const Layout = fn (peer: Callbacks, widgets: []Widget) void; const Callbacks = struct { userdata: usize, moveResize: fn (data: usize, peer: backend.PeerType, x: u32, y: u32, w: u32, h: u32) void, getSize: fn (data: usize) Size, computingPreferredSize: bool, availableSize: ?Size = null, }; fn getExpandedCount(widgets: []Widget) u32 { var expandedCount: u32 = 0; for (widgets) |widget| { if (widget.container_expanded) expandedCount += 1; } return expandedCount; } pub fn ColumnLayout(peer: Callbacks, widgets: []Widget) void { //const count = @intCast(u32, widgets.len); const expandedCount = getExpandedCount(widgets); var childHeight = if (expandedCount == 0) 0 else @intCast(u32, peer.getSize(peer.userdata).height) / expandedCount; for (widgets) |widget| { if (!widget.container_expanded) { const available = if (expandedCount > 0) Size.init(0, 0) else peer.getSize(peer.userdata); const divider = if (expandedCount == 0) 1 else expandedCount; const takenHeight = widget.getPreferredSize(available).height / divider; if (childHeight >= takenHeight) { childHeight -= takenHeight; } else { childHeight = 0; } } } var childY: f32 = 0.0; for (widgets) |*widget| { if (widget.peer) |widgetPeer| { const available = Size{ .width = @intCast(u32, peer.getSize(peer.userdata).width), .height = if (widget.container_expanded) childHeight else (@intCast(u32, peer.getSize(peer.userdata).height) - @floatToInt(u32, childY)) }; const preferred = widget.getPreferredSize(available); const size = if (widget.container_expanded) available else Size.intersect(available, preferred); const alignX = std.math.clamp(widget.alignX.get(), 0, 1); var x = @floatToInt(u32, @floor(alignX * @intToFloat(f32, peer.getSize(peer.userdata).width -| preferred.width))); if (widget.container_expanded or peer.computingPreferredSize) x = 0; peer.moveResize(peer.userdata, widgetPeer, x, @floatToInt(u32, @floor(childY)), size.width, size.height); childY += @intToFloat(f32, size.height); } } } pub fn RowLayout(peer: Callbacks, widgets: []Widget) void { //const count = @intCast(u32, widgets.len); const expandedCount = getExpandedCount(widgets); var childWidth = if (expandedCount == 0) 0 else @intCast(u32, peer.getSize(peer.userdata).width) / expandedCount; for (widgets) |widget| { if (!widget.container_expanded) { const available = peer.getSize(peer.userdata); const divider = if (expandedCount == 0) 1 else expandedCount; const takenWidth = widget.getPreferredSize(available).width / divider; if (childWidth >= takenWidth) { childWidth -= takenWidth; } else { childWidth = 0; } } } var childX: f32 = 0.0; for (widgets) |widget| { if (widget.peer) |widgetPeer| { // if (@floatToInt(u32, childX) >= peer.getSize(peer.userdata).width) { // break; // } const available = Size{ .width = if (widget.container_expanded) childWidth else (@intCast(u32, peer.getSize(peer.userdata).width) - @floatToInt(u32, childX)), .height = @intCast(u32, peer.getSize(peer.userdata).height) }; const preferred = widget.getPreferredSize(available); const size = if (widget.container_expanded) available else Size.intersect(available, preferred); const alignY = std.math.clamp(widget.alignY.get(), 0, 1); var y = @floatToInt(u32, @floor(alignY * @intToFloat(f32, peer.getSize(peer.userdata).height -| preferred.height))); if (widget.container_expanded or peer.computingPreferredSize) y = 0; peer.moveResize(peer.userdata, widgetPeer, @floatToInt(u32, @floor(childX)), y, size.width, size.height); childX += @intToFloat(f32, size.width); } } } pub fn MarginLayout(peer: Callbacks, widgets: []Widget) void { const margin = Rectangle{ .left = 5, .top = 5, .right = 5, .bottom = 5 }; if (widgets.len > 1) { std.log.scoped(.zgt).warn("Margin container has more than one widget!", .{}); return; } if (widgets[0].peer) |widgetPeer| { const available = peer.getSize(peer.userdata); const preferredSize = widgets[0].getPreferredSize(.{ .width = 0, .height = 0 }); // const size = Size { // .width = std.math.max(@intCast(u32, preferredSize.width), margin.left + margin.right) - margin.left - margin.right, // .height = std.math.max(@intCast(u32, preferredSize.height), margin.top + margin.bottom) - margin.top - margin.bottom // }; // _ = size; //const finalSize = Size.combine(preferredSize, available); _ = widgetPeer; _ = preferredSize; _ = margin; //peer.moveResize(peer.userdata, widgetPeer, margin.left, margin.top, finalSize.width, finalSize.height); peer.moveResize(peer.userdata, widgetPeer, 0, 0, available.width, available.height); } } pub fn StackLayout(peer: Callbacks, widgets: []Widget) void { const size = peer.getSize(peer.userdata); for (widgets) |widget| { if (widget.peer) |widgetPeer| { const widgetSize = if (peer.computingPreferredSize) widget.getPreferredSize(peer.availableSize.?) else size; peer.moveResize(peer.userdata, widgetPeer, 0, 0, widgetSize.width, widgetSize.height); } } } pub const Container_Impl = struct { pub usingnamespace @import("internal.zig").All(Container_Impl); peer: ?backend.Container, handlers: Container_Impl.Handlers = undefined, dataWrappers: Container_Impl.DataWrappers = .{}, childrens: std.ArrayList(Widget), expand: bool, relayouting: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), layout: Layout, /// The widget associated to this Container_Impl widget: ?*Widget = null, pub fn init(childrens: std.ArrayList(Widget), config: GridConfig, layout: Layout) !Container_Impl { var column = Container_Impl.init_events(Container_Impl{ .peer = null, .childrens = childrens, .expand = config.expand == .Fill, .layout = layout }) .setName(config.name); try column.addResizeHandler(onResize); return column; } pub fn onResize(self: *Container_Impl, size: Size) !void { _ = size; try self.relayout(); } pub fn getAt(self: *Container_Impl, index: usize) !*Widget { if (index >= self.childrens.items.len) return error.OutOfBounds; return &self.childrens.items[index]; } pub fn get(self: *Container_Impl, name: []const u8) ?*Widget { // TODO: use hash map (maybe acting as cache?) for performance for (self.childrens.items) |*widget| { if (widget.name.*) |widgetName| { if (std.mem.eql(u8, name, widgetName)) { return widget; } } if (widget.cast(Container_Impl)) |container| { return container.get(name) orelse continue; } } return null; } pub fn getPreferredSize(self: *Container_Impl, available: Size) Size { _ = available; var size: Size = Size{ .width = 0, .height = 0 }; const callbacks = Callbacks{ .userdata = @ptrToInt(&size), .moveResize = fakeResMove, .getSize = fakeSize, .computingPreferredSize = true, .availableSize = available }; self.layout(callbacks, self.childrens.items); return size; } pub fn show(self: *Container_Impl) !void { if (self.peer == null) { var peer = try backend.Container.create(); for (self.childrens.items) |*widget| { if (self.expand) { widget.container_expanded = true; } try widget.show(); peer.add(widget.peer.?); } self.peer = peer; try self.show_events(); try self.relayout(); } } pub fn _showWidget(widget: *Widget, self: *Container_Impl) !void { self.widget = widget; for (self.childrens.items) |*child| { child.parent = widget; } } fn fakeSize(data: usize) Size { _ = data; return Size{ .width = std.math.maxInt(u32) / 2, // divide by 2 to leave some room .height = std.math.maxInt(u32) / 2, }; } fn fakeResMove(data: usize, widget: backend.PeerType, x: u32, y: u32, w: u32, h: u32) void { const size = @intToPtr(*Size, data); _ = widget; size.width = std.math.max(size.width, x + w); size.height = std.math.max(size.height, y + h); } fn getSize(data: usize) Size { const peer = @intToPtr(*backend.Container, data); return Size{ .width = @intCast(u32, peer.getWidth()), .height = @intCast(u32, peer.getHeight()) }; } fn moveResize(data: usize, widget: backend.PeerType, x: u32, y: u32, w: u32, h: u32) void { @intToPtr(*backend.Container, data).move(widget, x, y); @intToPtr(*backend.Container, data).resize(widget, w, h); } pub fn relayout(self: *Container_Impl) !void { if (self.relayouting.load(.Acquire) == true) return; if (self.peer) |peer| { self.relayouting.store(true, .Release); const callbacks = Callbacks{ .userdata = @ptrToInt(&peer), .moveResize = moveResize, .getSize = getSize, .computingPreferredSize = false }; self.layout(callbacks, self.childrens.items); self.relayouting.store(false, .Release); } } pub fn add(self: *Container_Impl, widget: anytype) !void { const ComponentType = @import("internal.zig").DereferencedType(@TypeOf(widget)); var genericWidget = try @import("internal.zig").genericWidgetFrom(widget); if (self.expand) { genericWidget.container_expanded = true; } if (self.widget) |parent| { genericWidget.parent = parent; } const slot = try self.childrens.addOne(); slot.* = genericWidget; if (@hasField(ComponentType, "dataWrappers")) { genericWidget.as(ComponentType).dataWrappers.widget = slot; } if (self.peer) |*peer| { try slot.show(); peer.add(slot.peer.?); } try self.relayout(); } pub fn _deinit(self: *Container_Impl, widget: *Widget) void { _ = widget; for (self.childrens.items) |*child| { child.deinit(); } self.childrens.deinit(); } }; fn isErrorUnion(comptime T: type) bool { return switch (@typeInfo(T)) { .ErrorUnion => true, else => false, }; } fn abstractContainerConstructor(comptime T: type, childrens: anytype, config: anytype, layout: Layout) anyerror!T { const fields = std.meta.fields(@TypeOf(childrens)); var list = std.ArrayList(Widget).init(lasting_allocator); inline for (fields) |field| { const element = @field(childrens, field.name); const child = if (comptime isErrorUnion(@TypeOf(element))) // if it is an error union, unwrap it try element else element; const ComponentType = @import("internal.zig").DereferencedType(@TypeOf(child)); const widget = try @import("internal.zig").genericWidgetFrom(child); if (ComponentType != Widget) { inline for (std.meta.fields(ComponentType)) |compField| { if (comptime @import("data.zig").isDataWrapper(compField.field_type)) { const wrapper = @field(widget.as(ComponentType), compField.name); if (wrapper.updater) |updater| { std.log.info("data updater of {s} field '{s}'", .{ @typeName(ComponentType), compField.name }); // cannot get parent as of now try @import("data.zig").proneUpdater(updater, undefined); } } } } const slot = try list.addOne(); slot.* = widget; if (ComponentType != Widget) { widget.as(ComponentType).dataWrappers.widget = slot; } } return try T.init(list, config, layout); } const Expand = enum { /// The grid should take the minimal size that its childrens want No, /// The grid should expand to its maximum size by padding non-expanded childrens Fill, }; const GridConfig = struct { expand: Expand = .No, name: ?[]const u8 = null, }; /// Set the style of the child to expanded by creating and showing the widget early. pub inline fn Expanded(child: anytype) anyerror!Widget { var widget = try @import("internal.zig").genericWidgetFrom(if (comptime isErrorUnion(@TypeOf(child))) try child else child); widget.container_expanded = true; return widget; } pub inline fn Stack(childrens: anytype) anyerror!Container_Impl { return try abstractContainerConstructor(Container_Impl, childrens, .{}, StackLayout); } pub inline fn Row(config: GridConfig, childrens: anytype) anyerror!Container_Impl { return try abstractContainerConstructor(Container_Impl, childrens, config, RowLayout); } pub inline fn Column(config: GridConfig, childrens: anytype) anyerror!Container_Impl { return try abstractContainerConstructor(Container_Impl, childrens, config, ColumnLayout); } pub inline fn Margin(child: anytype) anyerror!Container_Impl { return try abstractContainerConstructor(Container_Impl, .{child}, GridConfig{}, MarginLayout); }
src/containers.zig
const std = @import("std"); const mem = std.mem; const Ideographic = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 12294, hi: u21 = 201546, pub fn init(allocator: *mem.Allocator) !Ideographic { var instance = Ideographic{ .allocator = allocator, .array = try allocator.alloc(bool, 189253), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; instance.array[1] = true; index = 27; while (index <= 35) : (index += 1) { instance.array[index] = true; } index = 50; while (index <= 52) : (index += 1) { instance.array[index] = true; } index = 1018; while (index <= 7609) : (index += 1) { instance.array[index] = true; } index = 7674; while (index <= 28662) : (index += 1) { instance.array[index] = true; } index = 51450; while (index <= 51815) : (index += 1) { instance.array[index] = true; } index = 51818; while (index <= 51923) : (index += 1) { instance.array[index] = true; } instance.array[81886] = true; index = 81914; while (index <= 88049) : (index += 1) { instance.array[index] = true; } index = 88058; while (index <= 89295) : (index += 1) { instance.array[index] = true; } index = 89338; while (index <= 89346) : (index += 1) { instance.array[index] = true; } index = 98666; while (index <= 99061) : (index += 1) { instance.array[index] = true; } index = 118778; while (index <= 161495) : (index += 1) { instance.array[index] = true; } index = 161530; while (index <= 165678) : (index += 1) { instance.array[index] = true; } index = 165690; while (index <= 165911) : (index += 1) { instance.array[index] = true; } index = 165914; while (index <= 171675) : (index += 1) { instance.array[index] = true; } index = 171690; while (index <= 179162) : (index += 1) { instance.array[index] = true; } index = 182266; while (index <= 182807) : (index += 1) { instance.array[index] = true; } index = 184314; while (index <= 189252) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Ideographic) void { self.allocator.free(self.array); } // isIdeographic checks if cp is of the kind Ideographic. pub fn isIdeographic(self: Ideographic, 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/PropList/Ideographic.zig
const sabaton = @import("../../sabaton.zig"); comptime { asm( \\ .section .data \\ .balign 8 \\ framebuffer_tag: \\ .8byte 0x506461d2950408fa // framebuffer identifier \\ .8byte 0 // next \\ .8byte 0 // addr \\ .2byte 720 // width \\ .2byte 1440 // height \\ .2byte 720 * 4 // pitch \\ .2byte 32 // bpp \\ .byte 1 // memory model, 1 = RGB \\ .byte 8 // red mask size \\ .byte 16 // red_mask_shift \\ .byte 8 // green_mask_size \\ .byte 8 // green_mask_shift \\ .byte 8 // blue_mask_size \\ .byte 0 // blue_mask_shift ); } const de_addr = 0x01000000; const tcon0_addr = 0x01C0C000; const tcon1_addr = 0x01C0D000; const rt_mixer0_addr = de_addr + 0x10_0000; const bld_addr = rt_mixer0_addr + 0x1000; const ovl_v_addr = rt_mixer0_addr + 0x2000; comptime { if(tcon1_addr != tcon0_addr + 0x1000) @panic("Assuming the're right after eachother for mapping below"); } fn bld(comptime T: type, offset: u16) *volatile T { return @intToPtr(*volatile T, @as(usize, bld_addr) + offset); } fn olv_v(comptime T: type, offset: u24) *volatile T { return @intToPtr(*volatile T, @as(usize, ovl_v_addr) + offset); } fn tcon0(offset: u16) *volatile u32 { return @intToPtr(*volatile u32, @as(usize, tcon0_addr) + offset); } fn tcon1(offset: u16) *volatile u32 { return @intToPtr(*volatile u32, @as(usize, tcon1_addr) + offset); } // struct Pixel { // u8 blue, green, red; // }; // Allwinner A64 user manual: // 6.2.5 TCOn0 Module register description pub fn init() void { sabaton.platform.timer.init(); const fb_tag = sabaton.near("framebuffer_tag"); sabaton.add_tag(&fb_tag.addr(sabaton.Stivale2tag)[0]); // We have a 32 bit physical address space on this device, this has to work const fb_addr = @intCast(u32, @ptrToInt(sabaton.pmm.alloc_aligned(720 * 4 * 1440, .Hole).ptr)); fb_tag.addr(u64)[2] = @as(u64, fb_addr); // TCON_En tcon0(0x0000).* |= (1 << 31); // TCON0_HV_IF_REG: HV_MODE = 8bit/4cycle Dummy RGB(DRGB) tcon0(0x0058).* |= (0b1010 << 28); // We'll only use the top field and layer 0 // OVL_V_ATTCTL LAY_FBFMT VIDEO_UI_SEL olv_v(u32, 0x0000).* = (0x00 << 8) | (1 << 15); // OVL_V_MBSIZE LAY_HEIGHT LAY_WIDTH olv_v(u32, 0x0004).* = ((1440 - 1) << 16) | ((720 - 1) << 0); // // OVL_V_COOR LAY_YCOOR LAY_XCOOR // olv_v(u32, 0x0008).* = (0 << 16) | (0 << 0); // OVL_V_PITCH0 LAY_PITCH olv_v(u32, 0x000C).* = 720 * 4; // OVL_V_TOP_LADD0 LAYMB_LADD olv_v(u32, 0x0018).* = fb_addr; // Enable pipe0 from olv_v // BLD_FILL_COLOR_CTL P0_EN bld(u32, 0x0000).* = (1 << 8); // BLD_CH_ISIZE HEIGHT WIDTH bld(u32, 0x0008).* = ((1440 - 1) << 16) | ((720 - 1) << 0); // // BLD_CH_OFFSET YCOOR XCOOR // bld(u32, 0x000C).* = (0 << 16) | (0 << 0); //tcon1(0x0).* |= 1 << 31; }
src/platform/pine_aarch64/display.zig
const mon13 = @import("mon13"); const std = @import("std"); pub export const mon13_gregorian = mon13.gregorian; pub export const mon13_gregorian_year_zero = mon13.gregorian_year_zero; pub export const mon13_tranquility = mon13.tranquility; pub export const mon13_tranquility_year_zero = mon13.tranquility_year_zero; pub export const mon13_holocene = mon13.holocene; pub export const mon13_cotsworth = mon13.cotsworth; pub export const mon13_julian = mon13.julian; pub export const mon13_positivist = mon13.positivist; pub export const mon13_symmetry454 = mon13.symmetry454; pub export const mon13_symmetry010 = mon13.symmetry010; pub export const mon13_ancient_egyptian = mon13.ancient_egyptian; pub export const mon13_french_revolutionary_romme = mon13.french_revolutionary_romme; pub export const mon13_french_revolutionary_romme_sub1 = mon13.french_revolutionary_romme_sub1; pub export const mon13_names_en_US_gregorian = mon13.names_en_US_gregorian; pub export const mon13_names_en_US_tranquility = mon13.names_en_US_tranquility; pub export const mon13_names_en_US_holocene = mon13.names_en_US_holocene; pub export const mon13_names_en_US_cotsworth = mon13.names_en_US_cotsworth; pub export const mon13_names_en_US_julian = mon13.names_en_US_julian; pub export const mon13_names_en_US_positivist = mon13.names_en_US_positivist; pub export const mon13_names_en_US_symmetry454 = mon13.names_en_US_symmetry454; pub export const mon13_names_en_US_symmetry010 = mon13.names_en_US_symmetry010; pub export const mon13_names_en_US_ancient_egyptian = mon13.names_en_US_ancient_egyptian; pub export const mon13_names_en_GB_french_revolutionary = mon13.names_en_GB_french_revolutionary; pub export const mon13_names_en_GB_french_revolutionary_joke = mon13.names_en_GB_french_revolutionary_joke; pub export const mon13_names_fr_FR_gregorian = mon13.names_fr_FR_gregorian; pub export const mon13_names_fr_FR_julian = mon13.names_fr_FR_julian; pub export const mon13_names_fr_FR_positivist = mon13.names_fr_FR_positivist; pub export const mon13_names_fr_FR_french_revolutionary = mon13.names_fr_FR_french_revolutionary; pub const PublicError = enum(c_int) { NONE = 0, UNKNOWN = -1, NULL_CALENDAR = -2, NULL_NAME_LIST = -3, NULL_FORMAT = -4, NULL_INPUT = -5, NULL_RESULT = -6, NULL_DATE = -7, OVERFLOW = -64, BAD_CALENDAR = -65, DATE_NOT_FOUND = -66, DAY_OF_YEAR_NOT_FOUND = -67, INVALID_UTF8 = -69, INVALID_STATE = -70, INVALID_SEQUENCE = -71, FAILED_TO_INSERT_NULLCHAR = -72, INVALID_DATE = -73, INVALID_NAME_LIST = -74, fn make(err: anyerror) PublicError { return switch (err) { mon13.Err.Unknown => PublicError.UNKNOWN, mon13.Err.NullCalendar => PublicError.NULL_CALENDAR, mon13.Err.NullNameList => PublicError.NULL_NAME_LIST, mon13.Err.NullFormat => PublicError.NULL_FORMAT, mon13.Err.NullInput => PublicError.NULL_INPUT, mon13.Err.NullResult => PublicError.NULL_RESULT, mon13.Err.NullDate => PublicError.NULL_DATE, mon13.Err.Overflow => PublicError.OVERFLOW, mon13.Err.BadCalendar => PublicError.BAD_CALENDAR, mon13.Err.DateNotFound => PublicError.DATE_NOT_FOUND, mon13.Err.DoyNotFound => PublicError.DAY_OF_YEAR_NOT_FOUND, mon13.Err.InvalidUtf8 => PublicError.INVALID_UTF8, mon13.Err.BeyondEndState => PublicError.INVALID_STATE, mon13.Err.InvalidSequence => PublicError.INVALID_SEQUENCE, mon13.Err.FailedToInsertNullCharacter => PublicError.FAILED_TO_INSERT_NULLCHAR, mon13.Err.InvalidDate => PublicError.INVALID_DATE, mon13.Err.InvalidNameList => PublicError.INVALID_NAME_LIST, else => PublicError.UNKNOWN, }; } fn toErr(self: PublicError) mon13.Err { return switch (self) { PublicError.UNKNOWN => mon13.Err.Unknown, PublicError.NULL_CALENDAR => mon13.Err.NullCalendar, PublicError.NULL_NAME_LIST => mon13.Err.NullNameList, PublicError.NULL_FORMAT => mon13.Err.NullFormat, PublicError.NULL_INPUT => mon13.Err.NullInput, PublicError.NULL_RESULT => mon13.Err.NullResult, PublicError.NULL_DATE => mon13.Err.NullDate, PublicError.OVERFLOW => mon13.Err.Overflow, PublicError.BAD_CALENDAR => mon13.Err.BadCalendar, PublicError.DATE_NOT_FOUND => mon13.Err.DateNotFound, PublicError.DAY_OF_YEAR_NOT_FOUND => mon13.Err.DoyNotFound, PublicError.INVALID_UTF8 => mon13.Err.InvalidUtf8, PublicError.INVALID_STATE => mon13.Err.BeyondEndState, PublicError.INVALID_SEQUENCE => mon13.Err.InvalidSequence, PublicError.FAILED_TO_INSERT_NULLCHAR => mon13.Err.FailedToInsertNullCharacter, PublicError.INVALID_DATE => mon13.Err.InvalidDate, PublicError.INVALID_NAME_LIST => mon13.Err.InvalidNameList, else => mon13.Err.Unknown, }; } }; fn tail(comptime T: type, res: *T, raw: anyerror!T) c_int { if (raw) |x| { res.* = x; return @enumToInt(PublicError.NONE); } else |err| { return @enumToInt(PublicError.make(err)); } } fn extract_fmt(raw_fmt: ?[*]const u8) ![]const u8 { const fmt_p = raw_fmt orelse return mon13.Err.NullFormat; var fmt_len: usize = 0; while (fmt_p[fmt_len] != 0) : (fmt_len += 1) {} return fmt_p[0..fmt_len]; } fn bytes_used_tail(raw: anyerror!c_int) c_int { if (raw) |res| { return res; } else |err| { return @enumToInt(PublicError.make(err)); } } pub export fn mon13_validYmd( raw_cal: ?*const mon13.Cal, year: i32, month: u8, day: u8, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); return @boolToInt(mon13.validYmd(cal, year, month, day)); } pub export fn mon13_mjdFromYmd( raw_cal: ?*const mon13.Cal, year: i32, month: u8, day: u8, raw_mjd: ?*i32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_mjd = raw_mjd orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_mjd, mon13.mjdFromYmd(cal, year, month, day)); } pub export fn mon13_mjdFromC99Tm( raw_cal: ?*const mon13.Cal, raw_tm: ?*const anyopaque, raw_mjd: ?*i32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); const tm = raw_tm orelse return @enumToInt(PublicError.NULL_INPUT); var res_mjd = raw_mjd orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_mjd, mon13.mjdFromC99Tm(cal, tm)); } pub export fn mon13_mjdFromUnix( unix: i64, raw_mjd: ?*i32, ) c_int { var res_mjd = raw_mjd orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_mjd, mon13.mjdFromUnix(unix)); } pub export fn mon13_mjdFromRd( rd: i32, raw_mjd: ?*i32, ) c_int { var res_mjd = raw_mjd orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_mjd, mon13.mjdFromRd(rd)); } pub export fn mon13_mjdToYmd( mjd: i32, raw_cal: ?*const mon13.Cal, year: ?*i32, month: ?*u8, day: ?*u8, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); if (mon13.mjdToYmd(mjd, cal, year, month, day)) { return @enumToInt(PublicError.NONE); } else |err| { return @enumToInt(PublicError.make(err)); } } pub export fn mon13_mjdToC99Tm( mjd: i32, raw_cal: ?*const mon13.Cal, raw_tm: ?*anyopaque, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var tm = raw_tm orelse return @enumToInt(PublicError.NULL_INPUT); if (mon13.mjdToC99Tm(mjd, cal, tm)) { return @enumToInt(PublicError.NONE); } else |err| { return @enumToInt(PublicError.make(err)); } } pub export fn mon13_mjdToUnix( mjd: i32, raw_unix: ?*i64, ) c_int { var res_unix = raw_unix orelse return @enumToInt(PublicError.NULL_INPUT); return tail(i64, res_unix, mon13.mjdToUnix(mjd)); } pub export fn mon13_mjdToRd( mjd: i32, raw_rd: ?*i32, ) c_int { var res_rd = raw_rd orelse return @enumToInt(PublicError.NULL_INPUT); return tail(i32, res_rd, mon13.mjdToRd(mjd)); } pub export fn mon13_mjdToIsLeapYear( mjd: i32, raw_cal: ?*const mon13.Cal, raw_isLeap: ?*c_int, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_isLeap = raw_isLeap orelse return @enumToInt(PublicError.NULL_RESULT); if (mon13.mjdToIsLeapYear(mjd, cal)) |x| { res_isLeap.* = @boolToInt(x); return @enumToInt(PublicError.NONE); } else |err| { return @enumToInt(PublicError.make(err)); } } pub export fn mon13_mjdToDayOfWeek( mjd: i32, raw_cal: ?*const mon13.Cal, raw_weekday: ?*u8, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_weekday = raw_weekday orelse return @enumToInt(PublicError.NULL_RESULT); return tail(u8, res_weekday, mon13.mjdToDayOfWeek(mjd, cal)); } pub export fn mon13_mjdToDayOfYear( mjd: i32, raw_cal: ?*const mon13.Cal, raw_yearday: ?*u16, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_yearday = raw_yearday orelse return @enumToInt(PublicError.NULL_RESULT); return tail(u16, res_yearday, mon13.mjdToDayOfYear(mjd, cal)); } pub export fn mon13_addMonths( mjd: i32, raw_cal: ?*const mon13.Cal, offset: i32, raw_sum: ?*i32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_sum = raw_sum orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_sum, mon13.addMonths(mjd, cal, offset)); } pub export fn mon13_addYears( mjd: i32, raw_cal: ?*const mon13.Cal, offset: i32, raw_sum: ?*i32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_sum = raw_sum orelse return @enumToInt(PublicError.NULL_RESULT); return tail(i32, res_sum, mon13.addYears(mjd, cal, offset)); } pub export fn mon13_diffMonths( mjd0: i32, mjd1: i32, raw_cal: ?*const mon13.Cal, raw_diff: ?*c_int, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_diff = raw_diff orelse return @enumToInt(PublicError.NULL_RESULT); return tail(c_int, res_diff, mon13.diffMonths(mjd0, mjd1, cal)); } pub export fn mon13_diffYears( mjd0: i32, mjd1: i32, raw_cal: ?*const mon13.Cal, raw_diff: ?*c_int, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); var res_diff = raw_diff orelse return @enumToInt(PublicError.NULL_RESULT); return tail(c_int, res_diff, mon13.diffYears(mjd0, mjd1, cal)); } pub export fn mon13_validNameList( raw_cal: ?*const mon13.Cal, raw_nlist: ?*const mon13.NameList, ) c_int { const cal = raw_cal orelse return @boolToInt(false); if (raw_nlist) |nlist| { if (@ptrCast(?*anyopaque, nlist.month_list) == null) { return @boolToInt(false); } if (@ptrCast(?*anyopaque, nlist.weekday_list) == null) { return @boolToInt(false); } if (@ptrCast(?*anyopaque, nlist.era_list) == null) { return @boolToInt(false); } if (@ptrCast(?*anyopaque, nlist.calendar_name) == null) { return @boolToInt(false); } } return @boolToInt(mon13.validNameList(cal, raw_nlist)); } pub export fn mon13_format( mjd: i32, raw_cal: ?*const mon13.Cal, raw_nlist: ?*const mon13.NameList, raw_fmt: ?[*]const u8, raw_buf: ?[*]u8, buflen: u32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); const fmt = extract_fmt(raw_fmt) catch |err| return @enumToInt(PublicError.make(err)); var slice_buf: ?[]u8 = null; if (buflen > 0) { if (raw_buf) |ptr_buf| { slice_buf = ptr_buf[0..buflen]; } } return bytes_used_tail(mon13.format(mjd, cal, raw_nlist, fmt, slice_buf)); } pub export fn mon13_parse( raw_cal: ?*const mon13.Cal, raw_nlist: ?*const mon13.NameList, raw_fmt: ?[*]const u8, raw_buf: ?[*]u8, buflen: u32, raw_mjd: ?*i32, ) c_int { const cal = raw_cal orelse return @enumToInt(PublicError.NULL_CALENDAR); const fmt = extract_fmt(raw_fmt) catch |err| return @enumToInt(PublicError.make(err)); const res_mjd = raw_mjd orelse return @enumToInt(PublicError.NULL_RESULT); const ptr_buf = raw_buf orelse return @enumToInt(PublicError.NULL_INPUT); if (buflen < 1) { return @enumToInt(PublicError.DATE_NOT_FOUND); } var slice_buf: []u8 = ptr_buf[0..buflen]; return bytes_used_tail(mon13.parse(cal, raw_nlist, fmt, slice_buf, res_mjd)); } pub export fn mon13_errorMessage(errorCode: c_int) [*:0]const u8 { if (errorCode > std.math.minInt(i32) and errorCode < std.math.maxInt(i32)) { if (mon13.utils.validInEnum(PublicError, @intCast(i32, errorCode))) { const e = @intToEnum(PublicError, @intCast(i32, errorCode)); return mon13.errorMessage(e.toErr()); } } return mon13.errorMessage(mon13.Err.Unknown); }
binding/c/bindc.zig
const std = @import("std"); const ray = @import("../c.zig").ray; const main = @import("../main.zig"); const dice = @import("./dice.zig"); const CommandLineOptions = @import("../args.zig").CommandLineOptions; pub const State = main.State; pub const GameScreenId = enum { MainMenu, Game, WinScreen, }; var global_font: ray.Font = undefined; pub const Button = struct { const ButtonState = enum { idle, hovered, pressed, }; label: []const u8 = undefined, rect: ray.Rectangle, active: bool = true, state: ButtonState = .idle, pub fn handle(self: *Button) bool { if (!self.active) { return false; } const mouse = ray.GetMousePosition(); if (ray.CheckCollisionPointRec(mouse, self.rect)) { if (ray.IsMouseButtonDown(ray.MOUSE_LEFT_BUTTON)) { self.state = .pressed; } else { self.state = .hovered; } if (ray.IsMouseButtonReleased(ray.MOUSE_LEFT_BUTTON)) { self.state = .idle; return true; } else { return false; } } else { self.state = .idle; return false; } } pub fn draw(self: *Button) void { var color: ray.Color = blk: { if (!self.active) break :blk ray.GRAY; switch (self.state) { .pressed => break :blk ray.YELLOW, .hovered => break :blk ray.ORANGE, .idle => break :blk ray.RED, } }; ray.DrawRectangleRounded(self.rect, 0.2, 1, color); ray.DrawTextEx(global_font, self.label.ptr, .{ .x = self.rect.x + 8.0, .y = self.rect.y + 8.0 }, 24.0, 1.0, ray.BLACK); } }; var start_game_button: Button = Button{ .label = "Start Game", .rect = .{ .x = 200.0, .y = 200, .width = 200.0, .height = 80.0 }, }; var reroll_button: Button = Button{ .label = "Reroll", .rect = .{ .x = 100.0, .y = 200, .width = 150.0, .height = 80.0 }, }; var end_game: Button = Button{ .label = "End Game", .rect = .{ .x = 400.0, .y = 200, .width = 150.0, .height = 80.0 }, }; pub fn mainMenu(state: *State) GameScreenId { var result: GameScreenId = .MainMenu; if (start_game_button.handle()) { state.forceReroll(); result = .Game; } ray.BeginDrawing(); ray.ClearBackground(ray.BLACK); start_game_button.draw(); ray.EndDrawing(); return result; } fn gameScreen(state: *State) GameScreenId { var result: GameScreenId = .Game; if (reroll_button.handle()) { state.reroll(); } if (end_game.handle()) { result = .WinScreen; } ray.BeginDrawing(); ray.ClearBackground(ray.DARKGREEN); reroll_button.draw(); end_game.draw(); dice.renderDices(state); ray.EndDrawing(); return result; } pub fn start(options: CommandLineOptions, state: *State) !void { _ = options; ray.InitWindow(640, 480, "Dice Roller"); defer ray.CloseWindow(); ray.SetTargetFPS(60); global_font = ray.LoadFontEx("resources/arial.ttf", 24, 0, 256); defer ray.UnloadFont(global_font); var game_screen_id: GameScreenId = .MainMenu; var first_turn: bool = true; while (!ray.WindowShouldClose()) { switch (game_screen_id) { .MainMenu => { state.newGame(state.player.name); game_screen_id = mainMenu(state); first_turn = true; }, .Game => { if (first_turn) { state.forceReroll(); first_turn = false; } game_screen_id = gameScreen(state); }, .WinScreen => { game_screen_id = mainMenu(state); }, } } }
src/gui/ui.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 Vec2 = tools.Vec2; const Map = tools.Map(u8, 85, 85, false); const PoiDist = struct { poi: u7, dist: u32, }; const MapNode = struct { poi: u8, list: []PoiDist, }; fn compute_dists_list(map: *const Map, from: u8, buf: []PoiDist) []PoiDist { var dmap = [1]u16{65535} ** (Map.stride * Map.stride); var poi_dist = [1]u32{65535} ** (('z' - 'a' + 1) + ('Z' - 'A' + 1)); var changed = true; while (changed) { changed = false; var p = map.bbox.min; p.y = map.bbox.min.y + 1; while (p.y <= map.bbox.max.y - 1) : (p.y += 1) { p.x = map.bbox.min.x + 1; while (p.x <= map.bbox.max.x - 1) : (p.x += 1) { const offset = map.offsetof(p); const m = map.map[offset]; const cur_dist: u16 = blk: { if (m == from) { if (dmap[offset] > 0) { dmap[offset] = 0; changed = true; } break :blk 0; } else { const up = Vec2{ .x = p.x, .y = p.y - 1 }; const down = Vec2{ .x = p.x, .y = p.y + 1 }; const left = Vec2{ .x = p.x - 1, .y = p.y }; const right = Vec2{ .x = p.x + 1, .y = p.y }; const offsetup = map.offsetof(up); const offsetdown = map.offsetof(down); const offsetleft = map.offsetof(left); const offsetright = map.offsetof(right); var d: u16 = 65534; if (d > dmap[offsetup]) d = dmap[offsetup]; if (d > dmap[offsetdown]) d = dmap[offsetdown]; if (d > dmap[offsetleft]) d = dmap[offsetleft]; if (d > dmap[offsetright]) d = dmap[offsetright]; d += 1; break :blk d; } }; switch (m) { '.', '@', '1'...'4' => { if (dmap[offset] > cur_dist) { dmap[offset] = cur_dist; changed = true; } }, 'a'...'z' => { poi_dist[m - 'a'] = cur_dist; }, 'A'...'Z' => { poi_dist[m - 'A' + ('z' - 'a' + 1)] = cur_dist; }, '#' => continue, else => unreachable, } } } } var i: u32 = 0; for (poi_dist) |d, p| { if (d == 65535 or d == 0) continue; if (p <= 'z' - 'a') { buf[i] = .{ .dist = d, .poi = @intCast(u7, p + 'a') }; } else { buf[i] = .{ .dist = d, .poi = @intCast(u7, p - ('z' - 'a' + 1) + 'A') }; } i += 1; } return buf[0..i]; } fn recurse_updatedists(from: u7, keys: []const u1, graph: []const MapNode, steps: u16, dists: []u16) void { const list = graph[from].list; for (list) |l| { const p = l.poi; const is_door = (p >= 'A' and p <= 'Z'); const is_locked_door = (is_door and keys[p - 'A'] == 0); if (is_locked_door) continue; const dist = @intCast(u16, steps + l.dist); if (dist >= dists[p]) continue; dists[p] = dist; const is_key = (p >= 'a' and p <= 'z'); const is_new_key = (is_key and keys[p - 'a'] == 0); if (is_new_key) continue; recurse_updatedists(p, keys, graph, dist, dists); } } fn enumerate_capturables(from: u7, keys: []const u1, graph: []const MapNode, pool: []PoiDist) []PoiDist { var dists = [1]u16{65535} ** 127; dists[from] = 0; recurse_updatedists(from, keys, graph, 0, &dists); var len: usize = 0; for ("abcdefghijklmnopqrstuvwxyz") |k| { const d = dists[k]; if (d == 65535 or d == 0) continue; const is_new_key = (keys[k - 'a'] == 0); if (!is_new_key) continue; pool[len] = PoiDist{ .poi = @intCast(u7, k), .dist = d }; len += 1; } return pool[0..len]; } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var all_keys = [1]u1{0} ** 26; var map = Map{ .default_tile = 0 }; { var map_cursor = Vec2{ .x = 0, .y = 0 }; for (input) |c| { if (c == '\n') { map_cursor = Vec2{ .x = 0, .y = map_cursor.y + 1 }; } else { map.set(map_cursor, c); map_cursor.x += 1; } if (c >= 'a' and c <= 'z') all_keys[c - 'a'] = 1; } } const Trace = struct { poi_list: [100]u8, poi_len: usize, }; // compiler bug workl around: make unique names for the state type. const State1 = struct { cur: u7, keys: [26]u1, }; const init_state1 = State1{ .cur = '@', .keys = [1]u1{0} ** 26, }; const State2 = struct { cur: [4]u7, keys: [26]u1, }; const init_state2 = State2{ .cur = [4]u7{ '1', '2', '3', '4' }, .keys = [1]u1{0} ** 26, }; var answers: [3]u32 = undefined; inline for ([_]u2{ 1, 2 }) |part| { // patch center for phase2. if (part == 2) { const center = Vec2{ .x = @divFloor(map.bbox.min.x + map.bbox.max.x, 2), .y = @divFloor(map.bbox.min.y + map.bbox.max.y, 2) }; assert(map.at(center) == '@'); map.set(Vec2{ .x = center.x + 0, .y = center.y + 0 }, '#'); map.set(Vec2{ .x = center.x + 1, .y = center.y + 0 }, '#'); map.set(Vec2{ .x = center.x - 1, .y = center.y + 0 }, '#'); map.set(Vec2{ .x = center.x + 0, .y = center.y + 1 }, '#'); map.set(Vec2{ .x = center.x + 0, .y = center.y - 0 }, '#'); map.set(Vec2{ .x = center.x + 1, .y = center.y + 1 }, '1'); map.set(Vec2{ .x = center.x + 1, .y = center.y - 1 }, '2'); map.set(Vec2{ .x = center.x - 1, .y = center.y - 1 }, '3'); map.set(Vec2{ .x = center.x - 1, .y = center.y + 1 }, '4'); } { var buf: [15000]u8 = undefined; trace("{}\n", .{map.printToBuf(null, null, null, &buf)}); } // compute the simplified distance graph to explore: var pooldists: [1000]PoiDist = undefined; var graph: [256]MapNode = [1]MapNode{.{ .poi = 0, .list = &[0]PoiDist{} }} ** 256; { const startpoints = "@1234"; const keys = "<KEY>"; const doors = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var pool_len: usize = 0; for (startpoints ++ keys ++ doors) |poi| { const list = compute_dists_list(&map, poi, pooldists[pool_len..]); graph[poi] = MapNode{ .poi = poi, .list = list }; pool_len += list.len; } } if (with_trace) { trace("list from '@': ", .{}); for (graph['@'].list) |l| { trace("{},", .{l}); } trace("\n", .{}); } // search the best path // compiler fails with: // const State = struct { // cur: if (part == 1) u7 else [4]u8, // keys: [26]u1, // }; // const init_state = State{ // .cur = if (part == 1) '@' else [4]u8{ '1', '2', '3', '4' }, // .keys = [1]u1{0} ** 26, // }; const State = if (part == 1) State1 else State2; const init_state = if (part == 1) init_state1 else init_state2; const BFS = tools.BestFirstSearch(State, Trace); var searcher = BFS.init(allocator); defer searcher.deinit(); try searcher.insert(.{ .rating = 0, .cost = 0, .state = init_state, .trace = Trace{ .poi_list = undefined, .poi_len = 0, }, }); var trace_dep: usize = 0; var trace_visited: usize = 0; var best: u32 = 10000; while (searcher.pop()) |node| { if (node.cost >= best) continue; if (with_trace) { const history = node.trace.poi_list[0..node.trace.poi_len]; if (history.len > trace_dep or searcher.visited.count() > trace_visited + 50000) { trace_dep = history.len; trace_visited = searcher.visited.count(); trace("so far... steps={}, agendalen={}, visited={}, trace[{}]={}\n", .{ node.cost, searcher.agenda.items.len, searcher.visited.count(), history.len, history }); } } var robot: usize = 0; const nbrobots = if (part == 1) 1 else 4; while (robot < nbrobots) : (robot += 1) { const cur = if (part == 1) node.state.cur else node.state.cur[robot]; // si on fait directement "for (graph[cur].list) |l|" ça marche, mais ya trops de combinaisons d'etats inutiles: // -> on ne génère que des etats où une nouvelle clef est capturée var capturepool: [50]PoiDist = undefined; var capturelist = enumerate_capturables(cur, &node.state.keys, &graph, &capturepool); for (capturelist) |l| { const p = l.poi; const is_key = (p >= 'a' and p <= 'z'); const is_door = (p >= 'A' and p <= 'Z'); const is_locked_door = (is_door and node.state.keys[p - 'A'] == 0); if (is_locked_door) continue; var next = node; next.cost = node.cost + l.dist; if (is_key) next.state.keys[p - 'a'] = 1; if (part == 1) { next.state.cur = p; } else { next.state.cur[robot] = p; } if (is_key and node.state.keys[p - 'a'] == 0) { next.trace.poi_list[node.trace.poi_len] = p; next.trace.poi_list[node.trace.poi_len + 1] = ','; next.trace.poi_len = node.trace.poi_len + 2; } // else if (is_door) { // next.trace.poi_list[node.trace.poi_len] = p; // next.trace.poi_len = node.trace.poi_len + 1; //} // rating: var key_count: u32 = 0; for (next.state.keys) |k| { key_count += k; } next.rating = @intCast(i32, next.cost) - 100 * @intCast(i32, key_count); if (next.cost >= best) continue; if (std.mem.eql(u1, &next.state.keys, &all_keys) and next.cost < best) { trace("Solution: steps={}, agendalen={}, visited={}, trace={}\n", .{ next.cost, searcher.agenda.items.len, searcher.visited.count(), next.trace.poi_list[0..next.trace.poi_len] }); best = next.cost; continue; } try searcher.insert(next); } } } answers[part] = best; trace("PART {}: min steps={} (unique nodes visited={})\n", .{ part, best, searcher.visited.count() }); } return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{answers[1]}), try std.fmt.allocPrint(allocator, "{}", .{answers[2]}), }; } pub const main = tools.defaultMain("2019/day18.txt", run);
2019/day18.zig
const builtin = @import("builtin"); const TypeId = builtin.TypeId; const std = @import("std"); const math = std.math; const assert = std.debug.assert; const warn = std.debug.warn; const ft2 = @import("freetype2.zig"); fn mapCtoZigTypeFloat(comptime T: type) type { return switch (@sizeOf(T)) { 2 => f16, 4 => f32, 8 => f64, else => @compileError("Unsupported float type"), }; } fn mapCtoZigTypeInt(comptime T: type) type { if (T.is_signed) { return switch (@sizeOf(T)) { 1 => i8, 2 => i16, 4 => i32, 8 => i64, else => @compileError("Unsupported signed integer type"), }; } else { return switch (@sizeOf(T)) { 1 => u8, 2 => u16, 4 => u32, 8 => u64, else => @compileError("Unsupported unsigned integer type"), }; } } pub fn mapCtoZigType(comptime T: type) type { return switch (@typeId(T)) { TypeId.Int => mapCtoZigTypeInt(T), TypeId.Float => mapCtoZigTypeFloat(T), else => @compileError("Only TypeId.Int and TypeId.Float are supported"), }; } const Zcint = c_int; // mapCtoZigType(c_int); const DBG: bool = false; const PTS: Zcint = 20; // 20 "points" for character size 20/64 of inch const DPI: Zcint = 100; // dots per inch const WIDTH: Zcint = 100; // display width const HEIGHT: Zcint = 75; // display height fn scaledInt(comptime IntType: type, v: f64, scale: IntType) IntType { return @floatToInt(IntType, v * @intToFloat(f64, scale)); } fn setImage(image: *[HEIGHT][WIDTH]u8, v: u8) void { var y: Zcint = 0; while (y < HEIGHT) : (y += 1) { var x: Zcint = 0; while (x < WIDTH) : (x += 1) { image.*[@intCast(usize, y)][@intCast(usize, x)] = v; } } } fn drawBitMap(image: *[HEIGHT][WIDTH]u8, bitmap: *ft2.FT_Bitmap, x: Zcint, y: Zcint) void { var i: Zcint = 0; var j: Zcint = 0; var p: Zcint = 0; var q: Zcint = 0; var glyph_width: Zcint = @intCast(Zcint, bitmap.width); var glyph_height: Zcint = @intCast(Zcint, bitmap.rows); var x_max: Zcint = x + glyph_width; var y_max: Zcint = y + glyph_height; if (DBG) warn("drawBitMap: x={} y={} x_max={} y_max={} glyph_width={} glyph_height={} buffer={*}\n", x, y, x_max, y_max, glyph_width, glyph_height, bitmap.buffer); i = x; p = 0; while (i < x_max) { j = y; q = 0; while (j < y_max) { if ((i >= 0) and (j >= 0) and (i < WIDTH) and (j < HEIGHT)) { var idx: usize = @intCast(usize, (q * glyph_width) + p); if (bitmap.buffer == null) return; var ptr: *u8 = @intToPtr(*u8, @ptrToInt(bitmap.buffer.?) + idx); if (DBG) warn("{p}:{x} ", ptr, ptr.*); image[@intCast(usize, j)][@intCast(usize, i)] |= ptr.*; } j += 1; q += 1; } if (DBG) warn("\n"); i += 1; p += 1; } } fn showImage(image: *[HEIGHT][WIDTH]u8) void { var y: Zcint = 0; while (y < HEIGHT) : (y += 1) { var x: Zcint = 0; if (DBG) warn("{}:{} ", y, x); while (x < WIDTH) : (x += 1) { var data: u8 = image.*[@intCast(usize, y)][@intCast(usize, x)]; var ch: u8 = switch (data) { 0 => u8(' '), 1...127 => u8('+'), 128...255 => u8('*'), }; warn("{c}", ch); } warn("\n"); } } test "test-freetype2" { warn("\n"); // Setup parameters // Filename for font const cfilename = c"modules/3d-test-resources/liberation-fonts-ttf-2.00.4/LiberationSans-Regular.ttf"; // Convert Rotate angle in radians for font var angleInDegrees: f64 = 45.0; var angle = (angleInDegrees / 360.0) * math.pi * 2.0; // Text to display var text = "pinky"; // Height of display var target_height = HEIGHT; // Init FT library var pLibrary: ?*ft2.FT_Library = undefined; assert(ft2.FT_Init_FreeType(&pLibrary) == 0); defer assert(ft2.FT_Done_FreeType(pLibrary) == 0); // Load a type face var pFace: ?*ft2.FT_Face = undefined; assert(ft2.FT_New_Face(pLibrary, cfilename, 0, &pFace) == 0); defer assert(ft2.FT_Done_Face(pFace) == 0); // Set character size assert(ft2.FT_Set_Char_Size(pFace, PTS * 64, 0, DPI, 0) == 0); // Setup matrix var matrix: ft2.FT_Matrix = undefined; matrix.xx = scaledInt(ft2.FT_Fixed, math.cos(angle), 0x10000); matrix.xy = scaledInt(ft2.FT_Fixed, -math.sin(angle), 0x10000); matrix.yx = scaledInt(ft2.FT_Fixed, math.sin(angle), 0x10000); matrix.yy = scaledInt(ft2.FT_Fixed, math.cos(angle), 0x10000); // Setup pen location var pen: ft2.FT_Vector = undefined; pen.x = 10 * 64; pen.y = 10 * 64; // Create and Initialize image var image: [HEIGHT][WIDTH]u8 = undefined; setImage(&image, 0); var y: Zcint = 0; while (y < HEIGHT) : (y += 1) { var x: Zcint = 0; while (x < WIDTH) : (x += 1) { assert(image[@intCast(usize, y)][@intCast(usize, x)] == 0); } } if (DBG) showImage(&image); // Loop to print characters to image buffer var slot: *ft2.FT_GlyphSlot = (pFace.?.glyph) orelse return error.NoGlyphSlot; var n: usize = 0; while (n < text.len) : (n += 1) { // Setup transform ft2.FT_Set_Transform(pFace, &matrix, &pen); // Load glyph image into slot assert(ft2.FT_Load_Char(pFace, text[n], ft2.FT_LOAD_RENDER) == 0); // Draw the character drawBitMap(&image, &slot.bitmap, slot.bitmap_left, target_height - slot.bitmap_top); // Move the pen pen.x += slot.advance.x; pen.y += slot.advance.y; } showImage(&image); }
test.zig
pub const bucket_count: u16 = 154; pub const max_bucket_length: u16 = 4; pub const max_hash_used: u16 = 152; pub const hash_table = [_]u32 { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01fc207f, 0x00000000, 0x00000000, 0x00000000, 0x01cd2550, 0x00000000, 0x00000000, 0x00000000, 0x01ba2551, 0x00000000, 0x00000000, 0x00000000, 0x01d52552, 0x01ff00a0, 0x00000000, 0x00000000, 0x01d62553, 0x01ad00a1, 0x01e403a3, 0x00000000, 0x01c92554, 0x019b00a2, 0x00000000, 0x00000000, 0x01b82555, 0x019c00a3, 0x00000000, 0x00000000, 0x01b72556, 0x01e803a6, 0x00000000, 0x00000000, 0x01bb2557, 0x019d00a5, 0x00000000, 0x00000000, 0x01d42558, 0x00000000, 0x00000000, 0x00000000, 0x01d32559, 0x011500a7, 0x01ea03a9, 0x00000000, 0x01c8255a, 0x00000000, 0x00000000, 0x00000000, 0x01be255b, 0x00000000, 0x00000000, 0x00000000, 0x01bd255c, 0x01a600aa, 0x00000000, 0x00000000, 0x01bc255d, 0x01ae00ab, 0x00000000, 0x00000000, 0x01c6255e, 0x01aa00ac, 0x00000000, 0x00000000, 0x01c7255f, 0x00000000, 0x00000000, 0x00000000, 0x01cc2560, 0x00000000, 0x00000000, 0x00000000, 0x01b52561, 0x01e003b1, 0x00000000, 0x00000000, 0x01b62562, 0x01f800b0, 0x00000000, 0x00000000, 0x01b92563, 0x01f100b1, 0x01f02261, 0x00000000, 0x01d12564, 0x01fd00b2, 0x01eb03b4, 0x00000000, 0x01d22565, 0x01ee03b5, 0x00000000, 0x00000000, 0x01cb2566, 0x01f32264, 0x00000000, 0x00000000, 0x01cf2567, 0x01e600b5, 0x01f22265, 0x00000000, 0x01d02568, 0x011400b6, 0x00000000, 0x00000000, 0x01ca2569, 0x01fa00b7, 0x00000000, 0x00000000, 0x01d8256a, 0x017f2302, 0x00000000, 0x00000000, 0x01d7256b, 0x00000000, 0x00000000, 0x00000000, 0x01ce256c, 0x01a700ba, 0x00000000, 0x00000000, 0x01af00bb, 0x00000000, 0x00000000, 0x00000000, 0x01ac00bc, 0x00000000, 0x00000000, 0x00000000, 0x01ab00bd, 0x00000000, 0x00000000, 0x00000000, 0x01e303c0, 0x00000000, 0x00000000, 0x00000000, 0x01a800bf, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e503c3, 0x00000000, 0x00000000, 0x00000000, 0x01e703c4, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x018e00c4, 0x01ed03c6, 0x00000000, 0x00000000, 0x018f00c5, 0x019e20a7, 0x00000000, 0x00000000, 0x019200c6, 0x01a92310, 0x00000000, 0x00000000, 0x018000c7, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019000c9, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01df2580, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01a500d1, 0x00000000, 0x00000000, 0x00000000, 0x01dc2584, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019900d6, 0x01db2588, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01072022, 0x01dd258c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019a00dc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01de2590, 0x00000000, 0x00000000, 0x00000000, 0x01e100df, 0x01b02591, 0x00000000, 0x00000000, 0x018500e0, 0x01b12592, 0x00000000, 0x00000000, 0x01a000e1, 0x01b22593, 0x00000000, 0x00000000, 0x018300e2, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x018400e4, 0x00000000, 0x00000000, 0x00000000, 0x018600e5, 0x00000000, 0x00000000, 0x00000000, 0x019100e6, 0x00000000, 0x00000000, 0x00000000, 0x018700e7, 0x00000000, 0x00000000, 0x00000000, 0x018a00e8, 0x01c42500, 0x00000000, 0x00000000, 0x018200e9, 0x00000000, 0x00000000, 0x00000000, 0x018800ea, 0x01b32502, 0x00000000, 0x00000000, 0x018900eb, 0x00000000, 0x00000000, 0x00000000, 0x018d00ec, 0x00000000, 0x00000000, 0x00000000, 0x01a100ed, 0x00000000, 0x00000000, 0x00000000, 0x018c00ee, 0x0101263a, 0x01fe25a0, 0x00000000, 0x018b00ef, 0x0102263b, 0x00000000, 0x00000000, 0x010f263c, 0x00000000, 0x00000000, 0x00000000, 0x01a400f1, 0x00000000, 0x00000000, 0x00000000, 0x019500f2, 0x00000000, 0x00000000, 0x00000000, 0x01a200f3, 0x00000000, 0x00000000, 0x00000000, 0x019300f4, 0x0113203c, 0x01da250c, 0x010c2640, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019400f6, 0x010b2642, 0x00000000, 0x00000000, 0x01f600f7, 0x00000000, 0x00000000, 0x00000000, 0x019f0192, 0x01bf2510, 0x00000000, 0x00000000, 0x019700f9, 0x00000000, 0x00000000, 0x00000000, 0x01a300fa, 0x011625ac, 0x00000000, 0x00000000, 0x019600fb, 0x00000000, 0x00000000, 0x00000000, 0x018100fc, 0x01c02514, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x019800ff, 0x00000000, 0x00000000, 0x00000000, 0x01d92518, 0x011e25b2, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01f92219, 0x00000000, 0x00000000, 0x00000000, 0x01fb221a, 0x01c3251c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01ec221e, 0x011025ba, 0x00000000, 0x00000000, 0x011c221f, 0x00000000, 0x00000000, 0x00000000, 0x011f25bc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01b42524, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x011125c4, 0x00000000, 0x00000000, 0x00000000, 0x01ef2229, 0x00000000, 0x00000000, 0x00000000, 0x011b2190, 0x01c2252c, 0x01062660, 0x00000000, 0x01182191, 0x00000000, 0x00000000, 0x00000000, 0x011a2192, 0x00000000, 0x00000000, 0x00000000, 0x01192193, 0x01052663, 0x00000000, 0x00000000, 0x011d2194, 0x00000000, 0x00000000, 0x00000000, 0x01122195, 0x010925cb, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01c12534, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01c5253c, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x010825d8, 0x00000000, 0x00000000, 0x00000000, 0x010a25d9, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e20393, 0x00000000, 0x00000000, 0x00000000, 0x011721a8, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01e90398, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x01f72248, 0x00000000, 0x00000000, 0x00000000, }; pub fn contiguous_ranges(c: u16) ?u8 { if (c >= 0x0020 and c <= 0x007e) return @intCast(u8, c); if (c >= 0x2320 and c <= 0x2321) return @intCast(u8, c - 0x222c); if (c >= 0x2665 and c <= 0x2666) return @intCast(u8, c - 0x2662); if (c >= 0x266a and c <= 0x266b) return @intCast(u8, c - 0x265d); return null; }
kernel/platform/code_point_437.zig
pub const X86 = enum(usize) { restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, waitpid = 7, creat = 8, link = 9, unlink = 10, execve = 11, chdir = 12, time = 13, mknod = 14, chmod = 15, lchown = 16, @"break" = 17, oldstat = 18, lseek = 19, getpid = 20, mount = 21, umount = 22, setuid = 23, getuid = 24, stime = 25, ptrace = 26, alarm = 27, oldfstat = 28, pause = 29, utime = 30, stty = 31, gtty = 32, access = 33, nice = 34, ftime = 35, sync = 36, kill = 37, rename = 38, mkdir = 39, rmdir = 40, dup = 41, pipe = 42, times = 43, prof = 44, brk = 45, setgid = 46, getgid = 47, signal = 48, geteuid = 49, getegid = 50, acct = 51, umount2 = 52, lock = 53, ioctl = 54, fcntl = 55, mpx = 56, setpgid = 57, ulimit = 58, oldolduname = 59, umask = 60, chroot = 61, ustat = 62, dup2 = 63, getppid = 64, getpgrp = 65, setsid = 66, sigaction = 67, sgetmask = 68, ssetmask = 69, setreuid = 70, setregid = 71, sigsuspend = 72, sigpending = 73, sethostname = 74, setrlimit = 75, getrlimit = 76, getrusage = 77, gettimeofday = 78, settimeofday = 79, getgroups = 80, setgroups = 81, select = 82, symlink = 83, oldlstat = 84, readlink = 85, uselib = 86, swapon = 87, reboot = 88, readdir = 89, mmap = 90, munmap = 91, truncate = 92, ftruncate = 93, fchmod = 94, fchown = 95, getpriority = 96, setpriority = 97, profil = 98, statfs = 99, fstatfs = 100, ioperm = 101, socketcall = 102, syslog = 103, setitimer = 104, getitimer = 105, stat = 106, lstat = 107, fstat = 108, olduname = 109, iopl = 110, vhangup = 111, idle = 112, vm86old = 113, wait4 = 114, swapoff = 115, sysinfo = 116, ipc = 117, fsync = 118, sigreturn = 119, clone = 120, setdomainname = 121, uname = 122, modify_ldt = 123, adjtimex = 124, mprotect = 125, sigprocmask = 126, create_module = 127, init_module = 128, delete_module = 129, get_kernel_syms = 130, quotactl = 131, getpgid = 132, fchdir = 133, bdflush = 134, sysfs = 135, personality = 136, afs_syscall = 137, setfsuid = 138, setfsgid = 139, _llseek = 140, getdents = 141, _newselect = 142, flock = 143, msync = 144, readv = 145, writev = 146, getsid = 147, fdatasync = 148, _sysctl = 149, mlock = 150, munlock = 151, mlockall = 152, munlockall = 153, sched_setparam = 154, sched_getparam = 155, sched_setscheduler = 156, sched_getscheduler = 157, sched_yield = 158, sched_get_priority_max = 159, sched_get_priority_min = 160, sched_rr_get_interval = 161, nanosleep = 162, mremap = 163, setresuid = 164, getresuid = 165, vm86 = 166, query_module = 167, poll = 168, nfsservctl = 169, setresgid = 170, getresgid = 171, prctl = 172, rt_sigreturn = 173, rt_sigaction = 174, rt_sigprocmask = 175, rt_sigpending = 176, rt_sigtimedwait = 177, rt_sigqueueinfo = 178, rt_sigsuspend = 179, pread64 = 180, pwrite64 = 181, chown = 182, getcwd = 183, capget = 184, capset = 185, sigaltstack = 186, sendfile = 187, getpmsg = 188, putpmsg = 189, vfork = 190, ugetrlimit = 191, mmap2 = 192, truncate64 = 193, ftruncate64 = 194, stat64 = 195, lstat64 = 196, fstat64 = 197, lchown32 = 198, getuid32 = 199, getgid32 = 200, geteuid32 = 201, getegid32 = 202, setreuid32 = 203, setregid32 = 204, getgroups32 = 205, setgroups32 = 206, fchown32 = 207, setresuid32 = 208, getresuid32 = 209, setresgid32 = 210, getresgid32 = 211, chown32 = 212, setuid32 = 213, setgid32 = 214, setfsuid32 = 215, setfsgid32 = 216, pivot_root = 217, mincore = 218, madvise = 219, getdents64 = 220, fcntl64 = 221, gettid = 224, readahead = 225, setxattr = 226, lsetxattr = 227, fsetxattr = 228, getxattr = 229, lgetxattr = 230, fgetxattr = 231, listxattr = 232, llistxattr = 233, flistxattr = 234, removexattr = 235, lremovexattr = 236, fremovexattr = 237, tkill = 238, sendfile64 = 239, futex = 240, sched_setaffinity = 241, sched_getaffinity = 242, set_thread_area = 243, get_thread_area = 244, io_setup = 245, io_destroy = 246, io_getevents = 247, io_submit = 248, io_cancel = 249, fadvise64 = 250, exit_group = 252, lookup_dcookie = 253, epoll_create = 254, epoll_ctl = 255, epoll_wait = 256, remap_file_pages = 257, set_tid_address = 258, timer_create = 259, timer_settime = 260, timer_gettime = 261, timer_getoverrun = 262, timer_delete = 263, clock_settime = 264, clock_gettime = 265, clock_getres = 266, clock_nanosleep = 267, statfs64 = 268, fstatfs64 = 269, tgkill = 270, utimes = 271, fadvise64_64 = 272, vserver = 273, mbind = 274, get_mempolicy = 275, set_mempolicy = 276, mq_open = 277, mq_unlink = 278, mq_timedsend = 279, mq_timedreceive = 280, mq_notify = 281, mq_getsetattr = 282, kexec_load = 283, waitid = 284, add_key = 286, request_key = 287, keyctl = 288, ioprio_set = 289, ioprio_get = 290, inotify_init = 291, inotify_add_watch = 292, inotify_rm_watch = 293, migrate_pages = 294, openat = 295, mkdirat = 296, mknodat = 297, fchownat = 298, futimesat = 299, fstatat64 = 300, unlinkat = 301, renameat = 302, linkat = 303, symlinkat = 304, readlinkat = 305, fchmodat = 306, faccessat = 307, pselect6 = 308, ppoll = 309, unshare = 310, set_robust_list = 311, get_robust_list = 312, splice = 313, sync_file_range = 314, tee = 315, vmsplice = 316, move_pages = 317, getcpu = 318, epoll_pwait = 319, utimensat = 320, signalfd = 321, timerfd_create = 322, eventfd = 323, fallocate = 324, timerfd_settime = 325, timerfd_gettime = 326, signalfd4 = 327, eventfd2 = 328, epoll_create1 = 329, dup3 = 330, pipe2 = 331, inotify_init1 = 332, preadv = 333, pwritev = 334, rt_tgsigqueueinfo = 335, perf_event_open = 336, recvmmsg = 337, fanotify_init = 338, fanotify_mark = 339, prlimit64 = 340, name_to_handle_at = 341, open_by_handle_at = 342, clock_adjtime = 343, syncfs = 344, sendmmsg = 345, setns = 346, process_vm_readv = 347, process_vm_writev = 348, kcmp = 349, finit_module = 350, sched_setattr = 351, sched_getattr = 352, renameat2 = 353, seccomp = 354, getrandom = 355, memfd_create = 356, bpf = 357, execveat = 358, socket = 359, socketpair = 360, bind = 361, connect = 362, listen = 363, accept4 = 364, getsockopt = 365, setsockopt = 366, getsockname = 367, getpeername = 368, sendto = 369, sendmsg = 370, recvfrom = 371, recvmsg = 372, shutdown = 373, userfaultfd = 374, membarrier = 375, mlock2 = 376, copy_file_range = 377, preadv2 = 378, pwritev2 = 379, pkey_mprotect = 380, pkey_alloc = 381, pkey_free = 382, statx = 383, arch_prctl = 384, io_pgetevents = 385, rseq = 386, semget = 393, semctl = 394, shmget = 395, shmctl = 396, shmat = 397, shmdt = 398, msgget = 399, msgsnd = 400, msgrcv = 401, msgctl = 402, clock_gettime64 = 403, clock_settime64 = 404, clock_adjtime64 = 405, clock_getres_time64 = 406, clock_nanosleep_time64 = 407, timer_gettime64 = 408, timer_settime64 = 409, timerfd_gettime64 = 410, timerfd_settime64 = 411, utimensat_time64 = 412, pselect6_time64 = 413, ppoll_time64 = 414, io_pgetevents_time64 = 416, recvmmsg_time64 = 417, mq_timedsend_time64 = 418, mq_timedreceive_time64 = 419, semtimedop_time64 = 420, rt_sigtimedwait_time64 = 421, futex_time64 = 422, sched_rr_get_interval_time64 = 423, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, memfd_secret = 447, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const X64 = enum(usize) { read = 0, write = 1, open = 2, close = 3, stat = 4, fstat = 5, lstat = 6, poll = 7, lseek = 8, mmap = 9, mprotect = 10, munmap = 11, brk = 12, rt_sigaction = 13, rt_sigprocmask = 14, rt_sigreturn = 15, ioctl = 16, pread64 = 17, pwrite64 = 18, readv = 19, writev = 20, access = 21, pipe = 22, select = 23, sched_yield = 24, mremap = 25, msync = 26, mincore = 27, madvise = 28, shmget = 29, shmat = 30, shmctl = 31, dup = 32, dup2 = 33, pause = 34, nanosleep = 35, getitimer = 36, alarm = 37, setitimer = 38, getpid = 39, sendfile = 40, socket = 41, connect = 42, accept = 43, sendto = 44, recvfrom = 45, sendmsg = 46, recvmsg = 47, shutdown = 48, bind = 49, listen = 50, getsockname = 51, getpeername = 52, socketpair = 53, setsockopt = 54, getsockopt = 55, clone = 56, fork = 57, vfork = 58, execve = 59, exit = 60, wait4 = 61, kill = 62, uname = 63, semget = 64, semop = 65, semctl = 66, shmdt = 67, msgget = 68, msgsnd = 69, msgrcv = 70, msgctl = 71, fcntl = 72, flock = 73, fsync = 74, fdatasync = 75, truncate = 76, ftruncate = 77, getdents = 78, getcwd = 79, chdir = 80, fchdir = 81, rename = 82, mkdir = 83, rmdir = 84, creat = 85, link = 86, unlink = 87, symlink = 88, readlink = 89, chmod = 90, fchmod = 91, chown = 92, fchown = 93, lchown = 94, umask = 95, gettimeofday = 96, getrlimit = 97, getrusage = 98, sysinfo = 99, times = 100, ptrace = 101, getuid = 102, syslog = 103, getgid = 104, setuid = 105, setgid = 106, geteuid = 107, getegid = 108, setpgid = 109, getppid = 110, getpgrp = 111, setsid = 112, setreuid = 113, setregid = 114, getgroups = 115, setgroups = 116, setresuid = 117, getresuid = 118, setresgid = 119, getresgid = 120, getpgid = 121, setfsuid = 122, setfsgid = 123, getsid = 124, capget = 125, capset = 126, rt_sigpending = 127, rt_sigtimedwait = 128, rt_sigqueueinfo = 129, rt_sigsuspend = 130, sigaltstack = 131, utime = 132, mknod = 133, uselib = 134, personality = 135, ustat = 136, statfs = 137, fstatfs = 138, sysfs = 139, getpriority = 140, setpriority = 141, sched_setparam = 142, sched_getparam = 143, sched_setscheduler = 144, sched_getscheduler = 145, sched_get_priority_max = 146, sched_get_priority_min = 147, sched_rr_get_interval = 148, mlock = 149, munlock = 150, mlockall = 151, munlockall = 152, vhangup = 153, modify_ldt = 154, pivot_root = 155, _sysctl = 156, prctl = 157, arch_prctl = 158, adjtimex = 159, setrlimit = 160, chroot = 161, sync = 162, acct = 163, settimeofday = 164, mount = 165, umount2 = 166, swapon = 167, swapoff = 168, reboot = 169, sethostname = 170, setdomainname = 171, iopl = 172, ioperm = 173, create_module = 174, init_module = 175, delete_module = 176, get_kernel_syms = 177, query_module = 178, quotactl = 179, nfsservctl = 180, getpmsg = 181, putpmsg = 182, afs_syscall = 183, tuxcall = 184, security = 185, gettid = 186, readahead = 187, setxattr = 188, lsetxattr = 189, fsetxattr = 190, getxattr = 191, lgetxattr = 192, fgetxattr = 193, listxattr = 194, llistxattr = 195, flistxattr = 196, removexattr = 197, lremovexattr = 198, fremovexattr = 199, tkill = 200, time = 201, futex = 202, sched_setaffinity = 203, sched_getaffinity = 204, set_thread_area = 205, io_setup = 206, io_destroy = 207, io_getevents = 208, io_submit = 209, io_cancel = 210, get_thread_area = 211, lookup_dcookie = 212, epoll_create = 213, epoll_ctl_old = 214, epoll_wait_old = 215, remap_file_pages = 216, getdents64 = 217, set_tid_address = 218, restart_syscall = 219, semtimedop = 220, fadvise64 = 221, timer_create = 222, timer_settime = 223, timer_gettime = 224, timer_getoverrun = 225, timer_delete = 226, clock_settime = 227, clock_gettime = 228, clock_getres = 229, clock_nanosleep = 230, exit_group = 231, epoll_wait = 232, epoll_ctl = 233, tgkill = 234, utimes = 235, vserver = 236, mbind = 237, set_mempolicy = 238, get_mempolicy = 239, mq_open = 240, mq_unlink = 241, mq_timedsend = 242, mq_timedreceive = 243, mq_notify = 244, mq_getsetattr = 245, kexec_load = 246, waitid = 247, add_key = 248, request_key = 249, keyctl = 250, ioprio_set = 251, ioprio_get = 252, inotify_init = 253, inotify_add_watch = 254, inotify_rm_watch = 255, migrate_pages = 256, openat = 257, mkdirat = 258, mknodat = 259, fchownat = 260, futimesat = 261, fstatat64 = 262, unlinkat = 263, renameat = 264, linkat = 265, symlinkat = 266, readlinkat = 267, fchmodat = 268, faccessat = 269, pselect6 = 270, ppoll = 271, unshare = 272, set_robust_list = 273, get_robust_list = 274, splice = 275, tee = 276, sync_file_range = 277, vmsplice = 278, move_pages = 279, utimensat = 280, epoll_pwait = 281, signalfd = 282, timerfd_create = 283, eventfd = 284, fallocate = 285, timerfd_settime = 286, timerfd_gettime = 287, accept4 = 288, signalfd4 = 289, eventfd2 = 290, epoll_create1 = 291, dup3 = 292, pipe2 = 293, inotify_init1 = 294, preadv = 295, pwritev = 296, rt_tgsigqueueinfo = 297, perf_event_open = 298, recvmmsg = 299, fanotify_init = 300, fanotify_mark = 301, prlimit64 = 302, name_to_handle_at = 303, open_by_handle_at = 304, clock_adjtime = 305, syncfs = 306, sendmmsg = 307, setns = 308, getcpu = 309, process_vm_readv = 310, process_vm_writev = 311, kcmp = 312, finit_module = 313, sched_setattr = 314, sched_getattr = 315, renameat2 = 316, seccomp = 317, getrandom = 318, memfd_create = 319, kexec_file_load = 320, bpf = 321, execveat = 322, userfaultfd = 323, membarrier = 324, mlock2 = 325, copy_file_range = 326, preadv2 = 327, pwritev2 = 328, pkey_mprotect = 329, pkey_alloc = 330, pkey_free = 331, statx = 332, io_pgetevents = 333, rseq = 334, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, memfd_secret = 447, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const Arm = enum(usize) { const arm_base = 0x0f0000; restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, creat = 8, link = 9, unlink = 10, execve = 11, chdir = 12, mknod = 14, chmod = 15, lchown = 16, lseek = 19, getpid = 20, mount = 21, setuid = 23, getuid = 24, ptrace = 26, pause = 29, access = 33, nice = 34, sync = 36, kill = 37, rename = 38, mkdir = 39, rmdir = 40, dup = 41, pipe = 42, times = 43, brk = 45, setgid = 46, getgid = 47, geteuid = 49, getegid = 50, acct = 51, umount2 = 52, ioctl = 54, fcntl = 55, setpgid = 57, umask = 60, chroot = 61, ustat = 62, dup2 = 63, getppid = 64, getpgrp = 65, setsid = 66, sigaction = 67, setreuid = 70, setregid = 71, sigsuspend = 72, sigpending = 73, sethostname = 74, setrlimit = 75, getrusage = 77, gettimeofday = 78, settimeofday = 79, getgroups = 80, setgroups = 81, symlink = 83, readlink = 85, uselib = 86, swapon = 87, reboot = 88, munmap = 91, truncate = 92, ftruncate = 93, fchmod = 94, fchown = 95, getpriority = 96, setpriority = 97, statfs = 99, fstatfs = 100, syslog = 103, setitimer = 104, getitimer = 105, stat = 106, lstat = 107, fstat = 108, vhangup = 111, wait4 = 114, swapoff = 115, sysinfo = 116, fsync = 118, sigreturn = 119, clone = 120, setdomainname = 121, uname = 122, adjtimex = 124, mprotect = 125, sigprocmask = 126, init_module = 128, delete_module = 129, quotactl = 131, getpgid = 132, fchdir = 133, bdflush = 134, sysfs = 135, personality = 136, setfsuid = 138, setfsgid = 139, _llseek = 140, getdents = 141, _newselect = 142, flock = 143, msync = 144, readv = 145, writev = 146, getsid = 147, fdatasync = 148, _sysctl = 149, mlock = 150, munlock = 151, mlockall = 152, munlockall = 153, sched_setparam = 154, sched_getparam = 155, sched_setscheduler = 156, sched_getscheduler = 157, sched_yield = 158, sched_get_priority_max = 159, sched_get_priority_min = 160, sched_rr_get_interval = 161, nanosleep = 162, mremap = 163, setresuid = 164, getresuid = 165, poll = 168, nfsservctl = 169, setresgid = 170, getresgid = 171, prctl = 172, rt_sigreturn = 173, rt_sigaction = 174, rt_sigprocmask = 175, rt_sigpending = 176, rt_sigtimedwait = 177, rt_sigqueueinfo = 178, rt_sigsuspend = 179, pread64 = 180, pwrite64 = 181, chown = 182, getcwd = 183, capget = 184, capset = 185, sigaltstack = 186, sendfile = 187, vfork = 190, ugetrlimit = 191, mmap2 = 192, truncate64 = 193, ftruncate64 = 194, stat64 = 195, lstat64 = 196, fstat64 = 197, lchown32 = 198, getuid32 = 199, getgid32 = 200, geteuid32 = 201, getegid32 = 202, setreuid32 = 203, setregid32 = 204, getgroups32 = 205, setgroups32 = 206, fchown32 = 207, setresuid32 = 208, getresuid32 = 209, setresgid32 = 210, getresgid32 = 211, chown32 = 212, setuid32 = 213, setgid32 = 214, setfsuid32 = 215, setfsgid32 = 216, getdents64 = 217, pivot_root = 218, mincore = 219, madvise = 220, fcntl64 = 221, gettid = 224, readahead = 225, setxattr = 226, lsetxattr = 227, fsetxattr = 228, getxattr = 229, lgetxattr = 230, fgetxattr = 231, listxattr = 232, llistxattr = 233, flistxattr = 234, removexattr = 235, lremovexattr = 236, fremovexattr = 237, tkill = 238, sendfile64 = 239, futex = 240, sched_setaffinity = 241, sched_getaffinity = 242, io_setup = 243, io_destroy = 244, io_getevents = 245, io_submit = 246, io_cancel = 247, exit_group = 248, lookup_dcookie = 249, epoll_create = 250, epoll_ctl = 251, epoll_wait = 252, remap_file_pages = 253, set_tid_address = 256, timer_create = 257, timer_settime = 258, timer_gettime = 259, timer_getoverrun = 260, timer_delete = 261, clock_settime = 262, clock_gettime = 263, clock_getres = 264, clock_nanosleep = 265, statfs64 = 266, fstatfs64 = 267, tgkill = 268, utimes = 269, fadvise64_64 = 270, pciconfig_iobase = 271, pciconfig_read = 272, pciconfig_write = 273, mq_open = 274, mq_unlink = 275, mq_timedsend = 276, mq_timedreceive = 277, mq_notify = 278, mq_getsetattr = 279, waitid = 280, socket = 281, bind = 282, connect = 283, listen = 284, accept = 285, getsockname = 286, getpeername = 287, socketpair = 288, send = 289, sendto = 290, recv = 291, recvfrom = 292, shutdown = 293, setsockopt = 294, getsockopt = 295, sendmsg = 296, recvmsg = 297, semop = 298, semget = 299, semctl = 300, msgsnd = 301, msgrcv = 302, msgget = 303, msgctl = 304, shmat = 305, shmdt = 306, shmget = 307, shmctl = 308, add_key = 309, request_key = 310, keyctl = 311, semtimedop = 312, vserver = 313, ioprio_set = 314, ioprio_get = 315, inotify_init = 316, inotify_add_watch = 317, inotify_rm_watch = 318, mbind = 319, get_mempolicy = 320, set_mempolicy = 321, openat = 322, mkdirat = 323, mknodat = 324, fchownat = 325, futimesat = 326, fstatat64 = 327, unlinkat = 328, renameat = 329, linkat = 330, symlinkat = 331, readlinkat = 332, fchmodat = 333, faccessat = 334, pselect6 = 335, ppoll = 336, unshare = 337, set_robust_list = 338, get_robust_list = 339, splice = 340, sync_file_range = 341, tee = 342, vmsplice = 343, move_pages = 344, getcpu = 345, epoll_pwait = 346, kexec_load = 347, utimensat = 348, signalfd = 349, timerfd_create = 350, eventfd = 351, fallocate = 352, timerfd_settime = 353, timerfd_gettime = 354, signalfd4 = 355, eventfd2 = 356, epoll_create1 = 357, dup3 = 358, pipe2 = 359, inotify_init1 = 360, preadv = 361, pwritev = 362, rt_tgsigqueueinfo = 363, perf_event_open = 364, recvmmsg = 365, accept4 = 366, fanotify_init = 367, fanotify_mark = 368, prlimit64 = 369, name_to_handle_at = 370, open_by_handle_at = 371, clock_adjtime = 372, syncfs = 373, sendmmsg = 374, setns = 375, process_vm_readv = 376, process_vm_writev = 377, kcmp = 378, finit_module = 379, sched_setattr = 380, sched_getattr = 381, renameat2 = 382, seccomp = 383, getrandom = 384, memfd_create = 385, bpf = 386, execveat = 387, userfaultfd = 388, membarrier = 389, mlock2 = 390, copy_file_range = 391, preadv2 = 392, pwritev2 = 393, pkey_mprotect = 394, pkey_alloc = 395, pkey_free = 396, statx = 397, rseq = 398, io_pgetevents = 399, migrate_pages = 400, kexec_file_load = 401, clock_gettime64 = 403, clock_settime64 = 404, clock_adjtime64 = 405, clock_getres_time64 = 406, clock_nanosleep_time64 = 407, timer_gettime64 = 408, timer_settime64 = 409, timerfd_gettime64 = 410, timerfd_settime64 = 411, utimensat_time64 = 412, pselect6_time64 = 413, ppoll_time64 = 414, io_pgetevents_time64 = 416, recvmmsg_time64 = 417, mq_timedsend_time64 = 418, mq_timedreceive_time64 = 419, semtimedop_time64 = 420, rt_sigtimedwait_time64 = 421, futex_time64 = 422, sched_rr_get_interval_time64 = 423, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, breakpoint = arm_base + 1, cacheflush = arm_base + 2, usr26 = arm_base + 3, usr32 = arm_base + 4, set_tls = arm_base + 5, get_tls = arm_base + 6, }; pub const Sparc64 = enum(usize) { restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, wait4 = 7, creat = 8, link = 9, unlink = 10, execv = 11, chdir = 12, chown = 13, mknod = 14, chmod = 15, lchown = 16, brk = 17, perfctr = 18, lseek = 19, getpid = 20, capget = 21, capset = 22, setuid = 23, getuid = 24, vmsplice = 25, ptrace = 26, alarm = 27, sigaltstack = 28, pause = 29, utime = 30, access = 33, nice = 34, sync = 36, kill = 37, stat = 38, sendfile = 39, lstat = 40, dup = 41, pipe = 42, times = 43, umount2 = 45, setgid = 46, getgid = 47, signal = 48, geteuid = 49, getegid = 50, acct = 51, memory_ordering = 52, ioctl = 54, reboot = 55, symlink = 57, readlink = 58, execve = 59, umask = 60, chroot = 61, fstat = 62, fstat64 = 63, getpagesize = 64, msync = 65, vfork = 66, pread64 = 67, pwrite64 = 68, mmap = 71, munmap = 73, mprotect = 74, madvise = 75, vhangup = 76, mincore = 78, getgroups = 79, setgroups = 80, getpgrp = 81, setitimer = 83, swapon = 85, getitimer = 86, sethostname = 88, dup2 = 90, fcntl = 92, select = 93, fsync = 95, setpriority = 96, socket = 97, connect = 98, accept = 99, getpriority = 100, rt_sigreturn = 101, rt_sigaction = 102, rt_sigprocmask = 103, rt_sigpending = 104, rt_sigtimedwait = 105, rt_sigqueueinfo = 106, rt_sigsuspend = 107, setresuid = 108, getresuid = 109, setresgid = 110, getresgid = 111, recvmsg = 113, sendmsg = 114, gettimeofday = 116, getrusage = 117, getsockopt = 118, getcwd = 119, readv = 120, writev = 121, settimeofday = 122, fchown = 123, fchmod = 124, recvfrom = 125, setreuid = 126, setregid = 127, rename = 128, truncate = 129, ftruncate = 130, flock = 131, lstat64 = 132, sendto = 133, shutdown = 134, socketpair = 135, mkdir = 136, rmdir = 137, utimes = 138, stat64 = 139, sendfile64 = 140, getpeername = 141, futex = 142, gettid = 143, getrlimit = 144, setrlimit = 145, pivot_root = 146, prctl = 147, pciconfig_read = 148, pciconfig_write = 149, getsockname = 150, inotify_init = 151, inotify_add_watch = 152, poll = 153, getdents64 = 154, inotify_rm_watch = 156, statfs = 157, fstatfs = 158, umount = 159, sched_set_affinity = 160, sched_get_affinity = 161, getdomainname = 162, setdomainname = 163, utrap_install = 164, quotactl = 165, set_tid_address = 166, mount = 167, ustat = 168, setxattr = 169, lsetxattr = 170, fsetxattr = 171, getxattr = 172, lgetxattr = 173, getdents = 174, setsid = 175, fchdir = 176, fgetxattr = 177, listxattr = 178, llistxattr = 179, flistxattr = 180, removexattr = 181, lremovexattr = 182, sigpending = 183, query_module = 184, setpgid = 185, fremovexattr = 186, tkill = 187, exit_group = 188, uname = 189, init_module = 190, personality = 191, remap_file_pages = 192, epoll_create = 193, epoll_ctl = 194, epoll_wait = 195, ioprio_set = 196, getppid = 197, sigaction = 198, sgetmask = 199, ssetmask = 200, sigsuspend = 201, oldlstat = 202, uselib = 203, readdir = 204, readahead = 205, socketcall = 206, syslog = 207, lookup_dcookie = 208, fadvise64 = 209, fadvise64_64 = 210, tgkill = 211, waitpid = 212, swapoff = 213, sysinfo = 214, ipc = 215, sigreturn = 216, clone = 217, ioprio_get = 218, adjtimex = 219, sigprocmask = 220, create_module = 221, delete_module = 222, get_kernel_syms = 223, getpgid = 224, bdflush = 225, sysfs = 226, afs_syscall = 227, setfsuid = 228, setfsgid = 229, _newselect = 230, splice = 232, stime = 233, statfs64 = 234, fstatfs64 = 235, _llseek = 236, mlock = 237, munlock = 238, mlockall = 239, munlockall = 240, sched_setparam = 241, sched_getparam = 242, sched_setscheduler = 243, sched_getscheduler = 244, sched_yield = 245, sched_get_priority_max = 246, sched_get_priority_min = 247, sched_rr_get_interval = 248, nanosleep = 249, mremap = 250, _sysctl = 251, getsid = 252, fdatasync = 253, nfsservctl = 254, sync_file_range = 255, clock_settime = 256, clock_gettime = 257, clock_getres = 258, clock_nanosleep = 259, sched_getaffinity = 260, sched_setaffinity = 261, timer_settime = 262, timer_gettime = 263, timer_getoverrun = 264, timer_delete = 265, timer_create = 266, vserver = 267, io_setup = 268, io_destroy = 269, io_submit = 270, io_cancel = 271, io_getevents = 272, mq_open = 273, mq_unlink = 274, mq_timedsend = 275, mq_timedreceive = 276, mq_notify = 277, mq_getsetattr = 278, waitid = 279, tee = 280, add_key = 281, request_key = 282, keyctl = 283, openat = 284, mkdirat = 285, mknodat = 286, fchownat = 287, futimesat = 288, fstatat64 = 289, unlinkat = 290, renameat = 291, linkat = 292, symlinkat = 293, readlinkat = 294, fchmodat = 295, faccessat = 296, pselect6 = 297, ppoll = 298, unshare = 299, set_robust_list = 300, get_robust_list = 301, migrate_pages = 302, mbind = 303, get_mempolicy = 304, set_mempolicy = 305, kexec_load = 306, move_pages = 307, getcpu = 308, epoll_pwait = 309, utimensat = 310, signalfd = 311, timerfd_create = 312, eventfd = 313, fallocate = 314, timerfd_settime = 315, timerfd_gettime = 316, signalfd4 = 317, eventfd2 = 318, epoll_create1 = 319, dup3 = 320, pipe2 = 321, inotify_init1 = 322, accept4 = 323, preadv = 324, pwritev = 325, rt_tgsigqueueinfo = 326, perf_event_open = 327, recvmmsg = 328, fanotify_init = 329, fanotify_mark = 330, prlimit64 = 331, name_to_handle_at = 332, open_by_handle_at = 333, clock_adjtime = 334, syncfs = 335, sendmmsg = 336, setns = 337, process_vm_readv = 338, process_vm_writev = 339, kern_features = 340, kcmp = 341, finit_module = 342, sched_setattr = 343, sched_getattr = 344, renameat2 = 345, seccomp = 346, getrandom = 347, memfd_create = 348, bpf = 349, execveat = 350, membarrier = 351, userfaultfd = 352, bind = 353, listen = 354, setsockopt = 355, mlock2 = 356, copy_file_range = 357, preadv2 = 358, pwritev2 = 359, statx = 360, io_pgetevents = 361, pkey_mprotect = 362, pkey_alloc = 363, pkey_free = 364, rseq = 365, semtimedop = 392, semget = 393, semctl = 394, shmget = 395, shmctl = 396, shmat = 397, shmdt = 398, msgget = 399, msgsnd = 400, msgrcv = 401, msgctl = 402, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const Mips = enum(usize) { pub const Linux = 4000; syscall = Linux + 0, exit = Linux + 1, fork = Linux + 2, read = Linux + 3, write = Linux + 4, open = Linux + 5, close = Linux + 6, waitpid = Linux + 7, creat = Linux + 8, link = Linux + 9, unlink = Linux + 10, execve = Linux + 11, chdir = Linux + 12, time = Linux + 13, mknod = Linux + 14, chmod = Linux + 15, lchown = Linux + 16, @"break" = Linux + 17, lseek = Linux + 19, getpid = Linux + 20, mount = Linux + 21, umount = Linux + 22, setuid = Linux + 23, getuid = Linux + 24, stime = Linux + 25, ptrace = Linux + 26, alarm = Linux + 27, pause = Linux + 29, utime = Linux + 30, stty = Linux + 31, gtty = Linux + 32, access = Linux + 33, nice = Linux + 34, ftime = Linux + 35, sync = Linux + 36, kill = Linux + 37, rename = Linux + 38, mkdir = Linux + 39, rmdir = Linux + 40, dup = Linux + 41, pipe = Linux + 42, times = Linux + 43, prof = Linux + 44, brk = Linux + 45, setgid = Linux + 46, getgid = Linux + 47, signal = Linux + 48, geteuid = Linux + 49, getegid = Linux + 50, acct = Linux + 51, umount2 = Linux + 52, lock = Linux + 53, ioctl = Linux + 54, fcntl = Linux + 55, mpx = Linux + 56, setpgid = Linux + 57, ulimit = Linux + 58, umask = Linux + 60, chroot = Linux + 61, ustat = Linux + 62, dup2 = Linux + 63, getppid = Linux + 64, getpgrp = Linux + 65, setsid = Linux + 66, sigaction = Linux + 67, sgetmask = Linux + 68, ssetmask = Linux + 69, setreuid = Linux + 70, setregid = Linux + 71, sigsuspend = Linux + 72, sigpending = Linux + 73, sethostname = Linux + 74, setrlimit = Linux + 75, getrlimit = Linux + 76, getrusage = Linux + 77, gettimeofday = Linux + 78, settimeofday = Linux + 79, getgroups = Linux + 80, setgroups = Linux + 81, reserved82 = Linux + 82, symlink = Linux + 83, readlink = Linux + 85, uselib = Linux + 86, swapon = Linux + 87, reboot = Linux + 88, readdir = Linux + 89, mmap = Linux + 90, munmap = Linux + 91, truncate = Linux + 92, ftruncate = Linux + 93, fchmod = Linux + 94, fchown = Linux + 95, getpriority = Linux + 96, setpriority = Linux + 97, profil = Linux + 98, statfs = Linux + 99, fstatfs = Linux + 100, ioperm = Linux + 101, socketcall = Linux + 102, syslog = Linux + 103, setitimer = Linux + 104, getitimer = Linux + 105, stat = Linux + 106, lstat = Linux + 107, fstat = Linux + 108, iopl = Linux + 110, vhangup = Linux + 111, idle = Linux + 112, vm86 = Linux + 113, wait4 = Linux + 114, swapoff = Linux + 115, sysinfo = Linux + 116, ipc = Linux + 117, fsync = Linux + 118, sigreturn = Linux + 119, clone = Linux + 120, setdomainname = Linux + 121, uname = Linux + 122, modify_ldt = Linux + 123, adjtimex = Linux + 124, mprotect = Linux + 125, sigprocmask = Linux + 126, create_module = Linux + 127, init_module = Linux + 128, delete_module = Linux + 129, get_kernel_syms = Linux + 130, quotactl = Linux + 131, getpgid = Linux + 132, fchdir = Linux + 133, bdflush = Linux + 134, sysfs = Linux + 135, personality = Linux + 136, afs_syscall = Linux + 137, setfsuid = Linux + 138, setfsgid = Linux + 139, _llseek = Linux + 140, getdents = Linux + 141, _newselect = Linux + 142, flock = Linux + 143, msync = Linux + 144, readv = Linux + 145, writev = Linux + 146, cacheflush = Linux + 147, cachectl = Linux + 148, sysmips = Linux + 149, getsid = Linux + 151, fdatasync = Linux + 152, _sysctl = Linux + 153, mlock = Linux + 154, munlock = Linux + 155, mlockall = Linux + 156, munlockall = Linux + 157, sched_setparam = Linux + 158, sched_getparam = Linux + 159, sched_setscheduler = Linux + 160, sched_getscheduler = Linux + 161, sched_yield = Linux + 162, sched_get_priority_max = Linux + 163, sched_get_priority_min = Linux + 164, sched_rr_get_interval = Linux + 165, nanosleep = Linux + 166, mremap = Linux + 167, accept = Linux + 168, bind = Linux + 169, connect = Linux + 170, getpeername = Linux + 171, getsockname = Linux + 172, getsockopt = Linux + 173, listen = Linux + 174, recv = Linux + 175, recvfrom = Linux + 176, recvmsg = Linux + 177, send = Linux + 178, sendmsg = Linux + 179, sendto = Linux + 180, setsockopt = Linux + 181, shutdown = Linux + 182, socket = Linux + 183, socketpair = Linux + 184, setresuid = Linux + 185, getresuid = Linux + 186, query_module = Linux + 187, poll = Linux + 188, nfsservctl = Linux + 189, setresgid = Linux + 190, getresgid = Linux + 191, prctl = Linux + 192, rt_sigreturn = Linux + 193, rt_sigaction = Linux + 194, rt_sigprocmask = Linux + 195, rt_sigpending = Linux + 196, rt_sigtimedwait = Linux + 197, rt_sigqueueinfo = Linux + 198, rt_sigsuspend = Linux + 199, pread64 = Linux + 200, pwrite64 = Linux + 201, chown = Linux + 202, getcwd = Linux + 203, capget = Linux + 204, capset = Linux + 205, sigaltstack = Linux + 206, sendfile = Linux + 207, getpmsg = Linux + 208, putpmsg = Linux + 209, mmap2 = Linux + 210, truncate64 = Linux + 211, ftruncate64 = Linux + 212, stat64 = Linux + 213, lstat64 = Linux + 214, fstat64 = Linux + 215, pivot_root = Linux + 216, mincore = Linux + 217, madvise = Linux + 218, getdents64 = Linux + 219, fcntl64 = Linux + 220, reserved221 = Linux + 221, gettid = Linux + 222, readahead = Linux + 223, setxattr = Linux + 224, lsetxattr = Linux + 225, fsetxattr = Linux + 226, getxattr = Linux + 227, lgetxattr = Linux + 228, fgetxattr = Linux + 229, listxattr = Linux + 230, llistxattr = Linux + 231, flistxattr = Linux + 232, removexattr = Linux + 233, lremovexattr = Linux + 234, fremovexattr = Linux + 235, tkill = Linux + 236, sendfile64 = Linux + 237, futex = Linux + 238, sched_setaffinity = Linux + 239, sched_getaffinity = Linux + 240, io_setup = Linux + 241, io_destroy = Linux + 242, io_getevents = Linux + 243, io_submit = Linux + 244, io_cancel = Linux + 245, exit_group = Linux + 246, lookup_dcookie = Linux + 247, epoll_create = Linux + 248, epoll_ctl = Linux + 249, epoll_wait = Linux + 250, remap_file_pages = Linux + 251, set_tid_address = Linux + 252, restart_syscall = Linux + 253, fadvise64 = Linux + 254, statfs64 = Linux + 255, fstatfs64 = Linux + 256, timer_create = Linux + 257, timer_settime = Linux + 258, timer_gettime = Linux + 259, timer_getoverrun = Linux + 260, timer_delete = Linux + 261, clock_settime = Linux + 262, clock_gettime = Linux + 263, clock_getres = Linux + 264, clock_nanosleep = Linux + 265, tgkill = Linux + 266, utimes = Linux + 267, mbind = Linux + 268, get_mempolicy = Linux + 269, set_mempolicy = Linux + 270, mq_open = Linux + 271, mq_unlink = Linux + 272, mq_timedsend = Linux + 273, mq_timedreceive = Linux + 274, mq_notify = Linux + 275, mq_getsetattr = Linux + 276, vserver = Linux + 277, waitid = Linux + 278, add_key = Linux + 280, request_key = Linux + 281, keyctl = Linux + 282, set_thread_area = Linux + 283, inotify_init = Linux + 284, inotify_add_watch = Linux + 285, inotify_rm_watch = Linux + 286, migrate_pages = Linux + 287, openat = Linux + 288, mkdirat = Linux + 289, mknodat = Linux + 290, fchownat = Linux + 291, futimesat = Linux + 292, fstatat64 = Linux + 293, unlinkat = Linux + 294, renameat = Linux + 295, linkat = Linux + 296, symlinkat = Linux + 297, readlinkat = Linux + 298, fchmodat = Linux + 299, faccessat = Linux + 300, pselect6 = Linux + 301, ppoll = Linux + 302, unshare = Linux + 303, splice = Linux + 304, sync_file_range = Linux + 305, tee = Linux + 306, vmsplice = Linux + 307, move_pages = Linux + 308, set_robust_list = Linux + 309, get_robust_list = Linux + 310, kexec_load = Linux + 311, getcpu = Linux + 312, epoll_pwait = Linux + 313, ioprio_set = Linux + 314, ioprio_get = Linux + 315, utimensat = Linux + 316, signalfd = Linux + 317, timerfd = Linux + 318, eventfd = Linux + 319, fallocate = Linux + 320, timerfd_create = Linux + 321, timerfd_gettime = Linux + 322, timerfd_settime = Linux + 323, signalfd4 = Linux + 324, eventfd2 = Linux + 325, epoll_create1 = Linux + 326, dup3 = Linux + 327, pipe2 = Linux + 328, inotify_init1 = Linux + 329, preadv = Linux + 330, pwritev = Linux + 331, rt_tgsigqueueinfo = Linux + 332, perf_event_open = Linux + 333, accept4 = Linux + 334, recvmmsg = Linux + 335, fanotify_init = Linux + 336, fanotify_mark = Linux + 337, prlimit64 = Linux + 338, name_to_handle_at = Linux + 339, open_by_handle_at = Linux + 340, clock_adjtime = Linux + 341, syncfs = Linux + 342, sendmmsg = Linux + 343, setns = Linux + 344, process_vm_readv = Linux + 345, process_vm_writev = Linux + 346, kcmp = Linux + 347, finit_module = Linux + 348, sched_setattr = Linux + 349, sched_getattr = Linux + 350, renameat2 = Linux + 351, seccomp = Linux + 352, getrandom = Linux + 353, memfd_create = Linux + 354, bpf = Linux + 355, execveat = Linux + 356, userfaultfd = Linux + 357, membarrier = Linux + 358, mlock2 = Linux + 359, copy_file_range = Linux + 360, preadv2 = Linux + 361, pwritev2 = Linux + 362, pkey_mprotect = Linux + 363, pkey_alloc = Linux + 364, pkey_free = Linux + 365, statx = Linux + 366, rseq = Linux + 367, io_pgetevents = Linux + 368, semget = Linux + 393, semctl = Linux + 394, shmget = Linux + 395, shmctl = Linux + 396, shmat = Linux + 397, shmdt = Linux + 398, msgget = Linux + 399, msgsnd = Linux + 400, msgrcv = Linux + 401, msgctl = Linux + 402, clock_gettime64 = Linux + 403, clock_settime64 = Linux + 404, clock_adjtime64 = Linux + 405, clock_getres_time64 = Linux + 406, clock_nanosleep_time64 = Linux + 407, timer_gettime64 = Linux + 408, timer_settime64 = Linux + 409, timerfd_gettime64 = Linux + 410, timerfd_settime64 = Linux + 411, utimensat_time64 = Linux + 412, pselect6_time64 = Linux + 413, ppoll_time64 = Linux + 414, io_pgetevents_time64 = Linux + 416, recvmmsg_time64 = Linux + 417, mq_timedsend_time64 = Linux + 418, mq_timedreceive_time64 = Linux + 419, semtimedop_time64 = Linux + 420, rt_sigtimedwait_time64 = Linux + 421, futex_time64 = Linux + 422, sched_rr_get_interval_time64 = Linux + 423, pidfd_send_signal = Linux + 424, io_uring_setup = Linux + 425, io_uring_enter = Linux + 426, io_uring_register = Linux + 427, open_tree = Linux + 428, move_mount = Linux + 429, fsopen = Linux + 430, fsconfig = Linux + 431, fsmount = Linux + 432, fspick = Linux + 433, pidfd_open = Linux + 434, clone3 = Linux + 435, close_range = Linux + 436, openat2 = Linux + 437, pidfd_getfd = Linux + 438, faccessat2 = Linux + 439, process_madvise = Linux + 440, epoll_pwait2 = Linux + 441, mount_setattr = Linux + 442, quotactl_fd = Linux + 443, landlock_create_ruleset = Linux + 444, landlock_add_rule = Linux + 445, landlock_restrict_self = Linux + 446, process_mrelease = Linux + 448, futex_waitv = Linux + 449, set_mempolicy_home_node = Linux + 450, }; pub const PowerPC = enum(usize) { restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, waitpid = 7, creat = 8, link = 9, unlink = 10, execve = 11, chdir = 12, time = 13, mknod = 14, chmod = 15, lchown = 16, @"break" = 17, oldstat = 18, lseek = 19, getpid = 20, mount = 21, umount = 22, setuid = 23, getuid = 24, stime = 25, ptrace = 26, alarm = 27, oldfstat = 28, pause = 29, utime = 30, stty = 31, gtty = 32, access = 33, nice = 34, ftime = 35, sync = 36, kill = 37, rename = 38, mkdir = 39, rmdir = 40, dup = 41, pipe = 42, times = 43, prof = 44, brk = 45, setgid = 46, getgid = 47, signal = 48, geteuid = 49, getegid = 50, acct = 51, umount2 = 52, lock = 53, ioctl = 54, fcntl = 55, mpx = 56, setpgid = 57, ulimit = 58, oldolduname = 59, umask = 60, chroot = 61, ustat = 62, dup2 = 63, getppid = 64, getpgrp = 65, setsid = 66, sigaction = 67, sgetmask = 68, ssetmask = 69, setreuid = 70, setregid = 71, sigsuspend = 72, sigpending = 73, sethostname = 74, setrlimit = 75, getrlimit = 76, getrusage = 77, gettimeofday = 78, settimeofday = 79, getgroups = 80, setgroups = 81, select = 82, symlink = 83, oldlstat = 84, readlink = 85, uselib = 86, swapon = 87, reboot = 88, readdir = 89, mmap = 90, munmap = 91, truncate = 92, ftruncate = 93, fchmod = 94, fchown = 95, getpriority = 96, setpriority = 97, profil = 98, statfs = 99, fstatfs = 100, ioperm = 101, socketcall = 102, syslog = 103, setitimer = 104, getitimer = 105, stat = 106, lstat = 107, fstat = 108, olduname = 109, iopl = 110, vhangup = 111, idle = 112, vm86 = 113, wait4 = 114, swapoff = 115, sysinfo = 116, ipc = 117, fsync = 118, sigreturn = 119, clone = 120, setdomainname = 121, uname = 122, modify_ldt = 123, adjtimex = 124, mprotect = 125, sigprocmask = 126, create_module = 127, init_module = 128, delete_module = 129, get_kernel_syms = 130, quotactl = 131, getpgid = 132, fchdir = 133, bdflush = 134, sysfs = 135, personality = 136, afs_syscall = 137, setfsuid = 138, setfsgid = 139, _llseek = 140, getdents = 141, _newselect = 142, flock = 143, msync = 144, readv = 145, writev = 146, getsid = 147, fdatasync = 148, _sysctl = 149, mlock = 150, munlock = 151, mlockall = 152, munlockall = 153, sched_setparam = 154, sched_getparam = 155, sched_setscheduler = 156, sched_getscheduler = 157, sched_yield = 158, sched_get_priority_max = 159, sched_get_priority_min = 160, sched_rr_get_interval = 161, nanosleep = 162, mremap = 163, setresuid = 164, getresuid = 165, query_module = 166, poll = 167, nfsservctl = 168, setresgid = 169, getresgid = 170, prctl = 171, rt_sigreturn = 172, rt_sigaction = 173, rt_sigprocmask = 174, rt_sigpending = 175, rt_sigtimedwait = 176, rt_sigqueueinfo = 177, rt_sigsuspend = 178, pread64 = 179, pwrite64 = 180, chown = 181, getcwd = 182, capget = 183, capset = 184, sigaltstack = 185, sendfile = 186, getpmsg = 187, putpmsg = 188, vfork = 189, ugetrlimit = 190, readahead = 191, mmap2 = 192, truncate64 = 193, ftruncate64 = 194, stat64 = 195, lstat64 = 196, fstat64 = 197, pciconfig_read = 198, pciconfig_write = 199, pciconfig_iobase = 200, multiplexer = 201, getdents64 = 202, pivot_root = 203, fcntl64 = 204, madvise = 205, mincore = 206, gettid = 207, tkill = 208, setxattr = 209, lsetxattr = 210, fsetxattr = 211, getxattr = 212, lgetxattr = 213, fgetxattr = 214, listxattr = 215, llistxattr = 216, flistxattr = 217, removexattr = 218, lremovexattr = 219, fremovexattr = 220, futex = 221, sched_setaffinity = 222, sched_getaffinity = 223, tuxcall = 225, sendfile64 = 226, io_setup = 227, io_destroy = 228, io_getevents = 229, io_submit = 230, io_cancel = 231, set_tid_address = 232, fadvise64 = 233, exit_group = 234, lookup_dcookie = 235, epoll_create = 236, epoll_ctl = 237, epoll_wait = 238, remap_file_pages = 239, timer_create = 240, timer_settime = 241, timer_gettime = 242, timer_getoverrun = 243, timer_delete = 244, clock_settime = 245, clock_gettime = 246, clock_getres = 247, clock_nanosleep = 248, swapcontext = 249, tgkill = 250, utimes = 251, statfs64 = 252, fstatfs64 = 253, fadvise64_64 = 254, rtas = 255, sys_debug_setcontext = 256, migrate_pages = 258, mbind = 259, get_mempolicy = 260, set_mempolicy = 261, mq_open = 262, mq_unlink = 263, mq_timedsend = 264, mq_timedreceive = 265, mq_notify = 266, mq_getsetattr = 267, kexec_load = 268, add_key = 269, request_key = 270, keyctl = 271, waitid = 272, ioprio_set = 273, ioprio_get = 274, inotify_init = 275, inotify_add_watch = 276, inotify_rm_watch = 277, spu_run = 278, spu_create = 279, pselect6 = 280, ppoll = 281, unshare = 282, splice = 283, tee = 284, vmsplice = 285, openat = 286, mkdirat = 287, mknodat = 288, fchownat = 289, futimesat = 290, fstatat64 = 291, unlinkat = 292, renameat = 293, linkat = 294, symlinkat = 295, readlinkat = 296, fchmodat = 297, faccessat = 298, get_robust_list = 299, set_robust_list = 300, move_pages = 301, getcpu = 302, epoll_pwait = 303, utimensat = 304, signalfd = 305, timerfd_create = 306, eventfd = 307, sync_file_range = 308, fallocate = 309, subpage_prot = 310, timerfd_settime = 311, timerfd_gettime = 312, signalfd4 = 313, eventfd2 = 314, epoll_create1 = 315, dup3 = 316, pipe2 = 317, inotify_init1 = 318, perf_event_open = 319, preadv = 320, pwritev = 321, rt_tgsigqueueinfo = 322, fanotify_init = 323, fanotify_mark = 324, prlimit64 = 325, socket = 326, bind = 327, connect = 328, listen = 329, accept = 330, getsockname = 331, getpeername = 332, socketpair = 333, send = 334, sendto = 335, recv = 336, recvfrom = 337, shutdown = 338, setsockopt = 339, getsockopt = 340, sendmsg = 341, recvmsg = 342, recvmmsg = 343, accept4 = 344, name_to_handle_at = 345, open_by_handle_at = 346, clock_adjtime = 347, syncfs = 348, sendmmsg = 349, setns = 350, process_vm_readv = 351, process_vm_writev = 352, finit_module = 353, kcmp = 354, sched_setattr = 355, sched_getattr = 356, renameat2 = 357, seccomp = 358, getrandom = 359, memfd_create = 360, bpf = 361, execveat = 362, switch_endian = 363, userfaultfd = 364, membarrier = 365, mlock2 = 378, copy_file_range = 379, preadv2 = 380, pwritev2 = 381, kexec_file_load = 382, statx = 383, pkey_alloc = 384, pkey_free = 385, pkey_mprotect = 386, rseq = 387, io_pgetevents = 388, semget = 393, semctl = 394, shmget = 395, shmctl = 396, shmat = 397, shmdt = 398, msgget = 399, msgsnd = 400, msgrcv = 401, msgctl = 402, clock_gettime64 = 403, clock_settime64 = 404, clock_adjtime64 = 405, clock_getres_time64 = 406, clock_nanosleep_time64 = 407, timer_gettime64 = 408, timer_settime64 = 409, timerfd_gettime64 = 410, timerfd_settime64 = 411, utimensat_time64 = 412, pselect6_time64 = 413, ppoll_time64 = 414, io_pgetevents_time64 = 416, recvmmsg_time64 = 417, mq_timedsend_time64 = 418, mq_timedreceive_time64 = 419, semtimedop_time64 = 420, rt_sigtimedwait_time64 = 421, futex_time64 = 422, sched_rr_get_interval_time64 = 423, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const PowerPC64 = enum(usize) { restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, waitpid = 7, creat = 8, link = 9, unlink = 10, execve = 11, chdir = 12, time = 13, mknod = 14, chmod = 15, lchown = 16, @"break" = 17, oldstat = 18, lseek = 19, getpid = 20, mount = 21, umount = 22, setuid = 23, getuid = 24, stime = 25, ptrace = 26, alarm = 27, oldfstat = 28, pause = 29, utime = 30, stty = 31, gtty = 32, access = 33, nice = 34, ftime = 35, sync = 36, kill = 37, rename = 38, mkdir = 39, rmdir = 40, dup = 41, pipe = 42, times = 43, prof = 44, brk = 45, setgid = 46, getgid = 47, signal = 48, geteuid = 49, getegid = 50, acct = 51, umount2 = 52, lock = 53, ioctl = 54, fcntl = 55, mpx = 56, setpgid = 57, ulimit = 58, oldolduname = 59, umask = 60, chroot = 61, ustat = 62, dup2 = 63, getppid = 64, getpgrp = 65, setsid = 66, sigaction = 67, sgetmask = 68, ssetmask = 69, setreuid = 70, setregid = 71, sigsuspend = 72, sigpending = 73, sethostname = 74, setrlimit = 75, getrlimit = 76, getrusage = 77, gettimeofday = 78, settimeofday = 79, getgroups = 80, setgroups = 81, select = 82, symlink = 83, oldlstat = 84, readlink = 85, uselib = 86, swapon = 87, reboot = 88, readdir = 89, mmap = 90, munmap = 91, truncate = 92, ftruncate = 93, fchmod = 94, fchown = 95, getpriority = 96, setpriority = 97, profil = 98, statfs = 99, fstatfs = 100, ioperm = 101, socketcall = 102, syslog = 103, setitimer = 104, getitimer = 105, stat = 106, lstat = 107, fstat = 108, olduname = 109, iopl = 110, vhangup = 111, idle = 112, vm86 = 113, wait4 = 114, swapoff = 115, sysinfo = 116, ipc = 117, fsync = 118, sigreturn = 119, clone = 120, setdomainname = 121, uname = 122, modify_ldt = 123, adjtimex = 124, mprotect = 125, sigprocmask = 126, create_module = 127, init_module = 128, delete_module = 129, get_kernel_syms = 130, quotactl = 131, getpgid = 132, fchdir = 133, bdflush = 134, sysfs = 135, personality = 136, afs_syscall = 137, setfsuid = 138, setfsgid = 139, _llseek = 140, getdents = 141, _newselect = 142, flock = 143, msync = 144, readv = 145, writev = 146, getsid = 147, fdatasync = 148, _sysctl = 149, mlock = 150, munlock = 151, mlockall = 152, munlockall = 153, sched_setparam = 154, sched_getparam = 155, sched_setscheduler = 156, sched_getscheduler = 157, sched_yield = 158, sched_get_priority_max = 159, sched_get_priority_min = 160, sched_rr_get_interval = 161, nanosleep = 162, mremap = 163, setresuid = 164, getresuid = 165, query_module = 166, poll = 167, nfsservctl = 168, setresgid = 169, getresgid = 170, prctl = 171, rt_sigreturn = 172, rt_sigaction = 173, rt_sigprocmask = 174, rt_sigpending = 175, rt_sigtimedwait = 176, rt_sigqueueinfo = 177, rt_sigsuspend = 178, pread64 = 179, pwrite64 = 180, chown = 181, getcwd = 182, capget = 183, capset = 184, sigaltstack = 185, sendfile = 186, getpmsg = 187, putpmsg = 188, vfork = 189, ugetrlimit = 190, readahead = 191, pciconfig_read = 198, pciconfig_write = 199, pciconfig_iobase = 200, multiplexer = 201, getdents64 = 202, pivot_root = 203, madvise = 205, mincore = 206, gettid = 207, tkill = 208, setxattr = 209, lsetxattr = 210, fsetxattr = 211, getxattr = 212, lgetxattr = 213, fgetxattr = 214, listxattr = 215, llistxattr = 216, flistxattr = 217, removexattr = 218, lremovexattr = 219, fremovexattr = 220, futex = 221, sched_setaffinity = 222, sched_getaffinity = 223, tuxcall = 225, io_setup = 227, io_destroy = 228, io_getevents = 229, io_submit = 230, io_cancel = 231, set_tid_address = 232, fadvise64 = 233, exit_group = 234, lookup_dcookie = 235, epoll_create = 236, epoll_ctl = 237, epoll_wait = 238, remap_file_pages = 239, timer_create = 240, timer_settime = 241, timer_gettime = 242, timer_getoverrun = 243, timer_delete = 244, clock_settime = 245, clock_gettime = 246, clock_getres = 247, clock_nanosleep = 248, swapcontext = 249, tgkill = 250, utimes = 251, statfs64 = 252, fstatfs64 = 253, rtas = 255, sys_debug_setcontext = 256, migrate_pages = 258, mbind = 259, get_mempolicy = 260, set_mempolicy = 261, mq_open = 262, mq_unlink = 263, mq_timedsend = 264, mq_timedreceive = 265, mq_notify = 266, mq_getsetattr = 267, kexec_load = 268, add_key = 269, request_key = 270, keyctl = 271, waitid = 272, ioprio_set = 273, ioprio_get = 274, inotify_init = 275, inotify_add_watch = 276, inotify_rm_watch = 277, spu_run = 278, spu_create = 279, pselect6 = 280, ppoll = 281, unshare = 282, splice = 283, tee = 284, vmsplice = 285, openat = 286, mkdirat = 287, mknodat = 288, fchownat = 289, futimesat = 290, fstatat64 = 291, unlinkat = 292, renameat = 293, linkat = 294, symlinkat = 295, readlinkat = 296, fchmodat = 297, faccessat = 298, get_robust_list = 299, set_robust_list = 300, move_pages = 301, getcpu = 302, epoll_pwait = 303, utimensat = 304, signalfd = 305, timerfd_create = 306, eventfd = 307, sync_file_range = 308, fallocate = 309, subpage_prot = 310, timerfd_settime = 311, timerfd_gettime = 312, signalfd4 = 313, eventfd2 = 314, epoll_create1 = 315, dup3 = 316, pipe2 = 317, inotify_init1 = 318, perf_event_open = 319, preadv = 320, pwritev = 321, rt_tgsigqueueinfo = 322, fanotify_init = 323, fanotify_mark = 324, prlimit64 = 325, socket = 326, bind = 327, connect = 328, listen = 329, accept = 330, getsockname = 331, getpeername = 332, socketpair = 333, send = 334, sendto = 335, recv = 336, recvfrom = 337, shutdown = 338, setsockopt = 339, getsockopt = 340, sendmsg = 341, recvmsg = 342, recvmmsg = 343, accept4 = 344, name_to_handle_at = 345, open_by_handle_at = 346, clock_adjtime = 347, syncfs = 348, sendmmsg = 349, setns = 350, process_vm_readv = 351, process_vm_writev = 352, finit_module = 353, kcmp = 354, sched_setattr = 355, sched_getattr = 356, renameat2 = 357, seccomp = 358, getrandom = 359, memfd_create = 360, bpf = 361, execveat = 362, switch_endian = 363, userfaultfd = 364, membarrier = 365, mlock2 = 378, copy_file_range = 379, preadv2 = 380, pwritev2 = 381, kexec_file_load = 382, statx = 383, pkey_alloc = 384, pkey_free = 385, pkey_mprotect = 386, rseq = 387, io_pgetevents = 388, semtimedop = 392, semget = 393, semctl = 394, shmget = 395, shmctl = 396, shmat = 397, shmdt = 398, msgget = 399, msgsnd = 400, msgrcv = 401, msgctl = 402, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const Arm64 = enum(usize) { io_setup = 0, io_destroy = 1, io_submit = 2, io_cancel = 3, io_getevents = 4, setxattr = 5, lsetxattr = 6, fsetxattr = 7, getxattr = 8, lgetxattr = 9, fgetxattr = 10, listxattr = 11, llistxattr = 12, flistxattr = 13, removexattr = 14, lremovexattr = 15, fremovexattr = 16, getcwd = 17, lookup_dcookie = 18, eventfd2 = 19, epoll_create1 = 20, epoll_ctl = 21, epoll_pwait = 22, dup = 23, dup3 = 24, fcntl = 25, inotify_init1 = 26, inotify_add_watch = 27, inotify_rm_watch = 28, ioctl = 29, ioprio_set = 30, ioprio_get = 31, flock = 32, mknodat = 33, mkdirat = 34, unlinkat = 35, symlinkat = 36, linkat = 37, renameat = 38, umount2 = 39, mount = 40, pivot_root = 41, nfsservctl = 42, statfs = 43, fstatfs = 44, truncate = 45, ftruncate = 46, fallocate = 47, faccessat = 48, chdir = 49, fchdir = 50, chroot = 51, fchmod = 52, fchmodat = 53, fchownat = 54, fchown = 55, openat = 56, close = 57, vhangup = 58, pipe2 = 59, quotactl = 60, getdents64 = 61, lseek = 62, read = 63, write = 64, readv = 65, writev = 66, pread64 = 67, pwrite64 = 68, preadv = 69, pwritev = 70, sendfile = 71, pselect6 = 72, ppoll = 73, signalfd4 = 74, vmsplice = 75, splice = 76, tee = 77, readlinkat = 78, fstatat = 79, fstat = 80, sync = 81, fsync = 82, fdatasync = 83, sync_file_range = 84, timerfd_create = 85, timerfd_settime = 86, timerfd_gettime = 87, utimensat = 88, acct = 89, capget = 90, capset = 91, personality = 92, exit = 93, exit_group = 94, waitid = 95, set_tid_address = 96, unshare = 97, futex = 98, set_robust_list = 99, get_robust_list = 100, nanosleep = 101, getitimer = 102, setitimer = 103, kexec_load = 104, init_module = 105, delete_module = 106, timer_create = 107, timer_gettime = 108, timer_getoverrun = 109, timer_settime = 110, timer_delete = 111, clock_settime = 112, clock_gettime = 113, clock_getres = 114, clock_nanosleep = 115, syslog = 116, ptrace = 117, sched_setparam = 118, sched_setscheduler = 119, sched_getscheduler = 120, sched_getparam = 121, sched_setaffinity = 122, sched_getaffinity = 123, sched_yield = 124, sched_get_priority_max = 125, sched_get_priority_min = 126, sched_rr_get_interval = 127, restart_syscall = 128, kill = 129, tkill = 130, tgkill = 131, sigaltstack = 132, rt_sigsuspend = 133, rt_sigaction = 134, rt_sigprocmask = 135, rt_sigpending = 136, rt_sigtimedwait = 137, rt_sigqueueinfo = 138, rt_sigreturn = 139, setpriority = 140, getpriority = 141, reboot = 142, setregid = 143, setgid = 144, setreuid = 145, setuid = 146, setresuid = 147, getresuid = 148, setresgid = 149, getresgid = 150, setfsuid = 151, setfsgid = 152, times = 153, setpgid = 154, getpgid = 155, getsid = 156, setsid = 157, getgroups = 158, setgroups = 159, uname = 160, sethostname = 161, setdomainname = 162, getrlimit = 163, setrlimit = 164, getrusage = 165, umask = 166, prctl = 167, getcpu = 168, gettimeofday = 169, settimeofday = 170, adjtimex = 171, getpid = 172, getppid = 173, getuid = 174, geteuid = 175, getgid = 176, getegid = 177, gettid = 178, sysinfo = 179, mq_open = 180, mq_unlink = 181, mq_timedsend = 182, mq_timedreceive = 183, mq_notify = 184, mq_getsetattr = 185, msgget = 186, msgctl = 187, msgrcv = 188, msgsnd = 189, semget = 190, semctl = 191, semtimedop = 192, semop = 193, shmget = 194, shmctl = 195, shmat = 196, shmdt = 197, socket = 198, socketpair = 199, bind = 200, listen = 201, accept = 202, connect = 203, getsockname = 204, getpeername = 205, sendto = 206, recvfrom = 207, setsockopt = 208, getsockopt = 209, shutdown = 210, sendmsg = 211, recvmsg = 212, readahead = 213, brk = 214, munmap = 215, mremap = 216, add_key = 217, request_key = 218, keyctl = 219, clone = 220, execve = 221, mmap = 222, fadvise64 = 223, swapon = 224, swapoff = 225, mprotect = 226, msync = 227, mlock = 228, munlock = 229, mlockall = 230, munlockall = 231, mincore = 232, madvise = 233, remap_file_pages = 234, mbind = 235, get_mempolicy = 236, set_mempolicy = 237, migrate_pages = 238, move_pages = 239, rt_tgsigqueueinfo = 240, perf_event_open = 241, accept4 = 242, recvmmsg = 243, wait4 = 260, prlimit64 = 261, fanotify_init = 262, fanotify_mark = 263, name_to_handle_at = 264, open_by_handle_at = 265, clock_adjtime = 266, syncfs = 267, setns = 268, sendmmsg = 269, process_vm_readv = 270, process_vm_writev = 271, kcmp = 272, finit_module = 273, sched_setattr = 274, sched_getattr = 275, renameat2 = 276, seccomp = 277, getrandom = 278, memfd_create = 279, bpf = 280, execveat = 281, userfaultfd = 282, membarrier = 283, mlock2 = 284, copy_file_range = 285, preadv2 = 286, pwritev2 = 287, pkey_mprotect = 288, pkey_alloc = 289, pkey_free = 290, statx = 291, io_pgetevents = 292, rseq = 293, kexec_file_load = 294, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, memfd_secret = 447, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, }; pub const RiscV64 = enum(usize) { pub const arch_specific_syscall = 244; io_setup = 0, io_destroy = 1, io_submit = 2, io_cancel = 3, io_getevents = 4, setxattr = 5, lsetxattr = 6, fsetxattr = 7, getxattr = 8, lgetxattr = 9, fgetxattr = 10, listxattr = 11, llistxattr = 12, flistxattr = 13, removexattr = 14, lremovexattr = 15, fremovexattr = 16, getcwd = 17, lookup_dcookie = 18, eventfd2 = 19, epoll_create1 = 20, epoll_ctl = 21, epoll_pwait = 22, dup = 23, dup3 = 24, fcntl = 25, inotify_init1 = 26, inotify_add_watch = 27, inotify_rm_watch = 28, ioctl = 29, ioprio_set = 30, ioprio_get = 31, flock = 32, mknodat = 33, mkdirat = 34, unlinkat = 35, symlinkat = 36, linkat = 37, umount2 = 39, mount = 40, pivot_root = 41, nfsservctl = 42, statfs = 43, fstatfs = 44, truncate = 45, ftruncate = 46, fallocate = 47, faccessat = 48, chdir = 49, fchdir = 50, chroot = 51, fchmod = 52, fchmodat = 53, fchownat = 54, fchown = 55, openat = 56, close = 57, vhangup = 58, pipe2 = 59, quotactl = 60, getdents64 = 61, lseek = 62, read = 63, write = 64, readv = 65, writev = 66, pread64 = 67, pwrite64 = 68, preadv = 69, pwritev = 70, sendfile = 71, pselect6 = 72, ppoll = 73, signalfd4 = 74, vmsplice = 75, splice = 76, tee = 77, readlinkat = 78, fstatat = 79, fstat = 80, sync = 81, fsync = 82, fdatasync = 83, sync_file_range = 84, timerfd_create = 85, timerfd_settime = 86, timerfd_gettime = 87, utimensat = 88, acct = 89, capget = 90, capset = 91, personality = 92, exit = 93, exit_group = 94, waitid = 95, set_tid_address = 96, unshare = 97, futex = 98, set_robust_list = 99, get_robust_list = 100, nanosleep = 101, getitimer = 102, setitimer = 103, kexec_load = 104, init_module = 105, delete_module = 106, timer_create = 107, timer_gettime = 108, timer_getoverrun = 109, timer_settime = 110, timer_delete = 111, clock_settime = 112, clock_gettime = 113, clock_getres = 114, clock_nanosleep = 115, syslog = 116, ptrace = 117, sched_setparam = 118, sched_setscheduler = 119, sched_getscheduler = 120, sched_getparam = 121, sched_setaffinity = 122, sched_getaffinity = 123, sched_yield = 124, sched_get_priority_max = 125, sched_get_priority_min = 126, sched_rr_get_interval = 127, restart_syscall = 128, kill = 129, tkill = 130, tgkill = 131, sigaltstack = 132, rt_sigsuspend = 133, rt_sigaction = 134, rt_sigprocmask = 135, rt_sigpending = 136, rt_sigtimedwait = 137, rt_sigqueueinfo = 138, rt_sigreturn = 139, setpriority = 140, getpriority = 141, reboot = 142, setregid = 143, setgid = 144, setreuid = 145, setuid = 146, setresuid = 147, getresuid = 148, setresgid = 149, getresgid = 150, setfsuid = 151, setfsgid = 152, times = 153, setpgid = 154, getpgid = 155, getsid = 156, setsid = 157, getgroups = 158, setgroups = 159, uname = 160, sethostname = 161, setdomainname = 162, getrlimit = 163, setrlimit = 164, getrusage = 165, umask = 166, prctl = 167, getcpu = 168, gettimeofday = 169, settimeofday = 170, adjtimex = 171, getpid = 172, getppid = 173, getuid = 174, geteuid = 175, getgid = 176, getegid = 177, gettid = 178, sysinfo = 179, mq_open = 180, mq_unlink = 181, mq_timedsend = 182, mq_timedreceive = 183, mq_notify = 184, mq_getsetattr = 185, msgget = 186, msgctl = 187, msgrcv = 188, msgsnd = 189, semget = 190, semctl = 191, semtimedop = 192, semop = 193, shmget = 194, shmctl = 195, shmat = 196, shmdt = 197, socket = 198, socketpair = 199, bind = 200, listen = 201, accept = 202, connect = 203, getsockname = 204, getpeername = 205, sendto = 206, recvfrom = 207, setsockopt = 208, getsockopt = 209, shutdown = 210, sendmsg = 211, recvmsg = 212, readahead = 213, brk = 214, munmap = 215, mremap = 216, add_key = 217, request_key = 218, keyctl = 219, clone = 220, execve = 221, mmap = 222, fadvise64 = 223, swapon = 224, swapoff = 225, mprotect = 226, msync = 227, mlock = 228, munlock = 229, mlockall = 230, munlockall = 231, mincore = 232, madvise = 233, remap_file_pages = 234, mbind = 235, get_mempolicy = 236, set_mempolicy = 237, migrate_pages = 238, move_pages = 239, rt_tgsigqueueinfo = 240, perf_event_open = 241, accept4 = 242, recvmmsg = 243, wait4 = 260, prlimit64 = 261, fanotify_init = 262, fanotify_mark = 263, name_to_handle_at = 264, open_by_handle_at = 265, clock_adjtime = 266, syncfs = 267, setns = 268, sendmmsg = 269, process_vm_readv = 270, process_vm_writev = 271, kcmp = 272, finit_module = 273, sched_setattr = 274, sched_getattr = 275, renameat2 = 276, seccomp = 277, getrandom = 278, memfd_create = 279, bpf = 280, execveat = 281, userfaultfd = 282, membarrier = 283, mlock2 = 284, copy_file_range = 285, preadv2 = 286, pwritev2 = 287, pkey_mprotect = 288, pkey_alloc = 289, pkey_free = 290, statx = 291, io_pgetevents = 292, rseq = 293, kexec_file_load = 294, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, close_range = 436, openat2 = 437, pidfd_getfd = 438, faccessat2 = 439, process_madvise = 440, epoll_pwait2 = 441, mount_setattr = 442, quotactl_fd = 443, landlock_create_ruleset = 444, landlock_add_rule = 445, landlock_restrict_self = 446, process_mrelease = 448, futex_waitv = 449, set_mempolicy_home_node = 450, riscv_flush_icache = arch_specific_syscall + 15, };
lib/std/os/linux/syscalls.zig
const std = @import("std"); const term = @import("ansi-term"); usingnamespace @import("ast.zig"); usingnamespace @import("code_formatter.zig"); usingnamespace @import("code_runner.zig"); usingnamespace @import("common.zig"); usingnamespace @import("dot_printer.zig"); usingnamespace @import("error_handler.zig"); usingnamespace @import("job.zig"); usingnamespace @import("lexer.zig"); usingnamespace @import("location.zig"); usingnamespace @import("native_function.zig"); usingnamespace @import("parser.zig"); usingnamespace @import("ring_buffer.zig"); usingnamespace @import("symbol.zig"); usingnamespace @import("types.zig"); const log = std.log.scoped(.Compiler); pub const SourceFile = struct { path: StringBuf, content: StringBuf, asts: List(*Ast), const Self = @This(); pub fn init(path: StringBuf, content: StringBuf, allocator: *std.mem.Allocator) Self { return Self{ .path = path, .content = content, .asts = List(*Ast).init(allocator), }; } pub fn deinit(self: *const Self) void { self.path.deinit(); self.content.deinit(); self.asts.deinit(); } }; pub const Compiler = struct { allocator: *std.mem.Allocator, constantsAllocator: std.heap.ArenaAllocator, stackAllocator: std.heap.ArenaAllocator, astAllocator: std.heap.ArenaAllocator, errorReporter: *ErrorReporter, errorMsgBuffer: std.ArrayList(u8), typeRegistry: TypeRegistry, files: List(*SourceFile), globalScope: *SymbolTable, allFibers: List(*FiberContext), fiberPool: List(*FiberContext), unqueuedJobs: RingBuffer(*Job), fiberQueue1: RingBuffer(*FiberContext), fiberQueue2: RingBuffer(*FiberContext), readyFibers: *RingBuffer(*FiberContext) = undefined, waitingFibers: *RingBuffer(*FiberContext) = undefined, const Self = @This(); pub fn init(allocator: *std.mem.Allocator, errorReporter: *ErrorReporter) !*Self { var self = try allocator.create(Self); var globalScope = try allocator.create(SymbolTable); self.* = Self{ .allocator = allocator, .constantsAllocator = std.heap.ArenaAllocator.init(allocator), .stackAllocator = std.heap.ArenaAllocator.init(allocator), .astAllocator = std.heap.ArenaAllocator.init(allocator), .errorReporter = errorReporter, .typeRegistry = try TypeRegistry.init(allocator), .files = List(*SourceFile).init(allocator), .globalScope = globalScope, .allFibers = List(*FiberContext).init(allocator), .fiberPool = List(*FiberContext).init(allocator), .unqueuedJobs = try RingBuffer(*Job).init(allocator), .fiberQueue1 = try RingBuffer(*FiberContext).init(allocator), .fiberQueue2 = try RingBuffer(*FiberContext).init(allocator), .errorMsgBuffer = std.ArrayList(u8).init(allocator), }; globalScope.* = SymbolTable.init(null, &self.constantsAllocator.allocator, allocator); self.readyFibers = &self.fiberQueue1; self.waitingFibers = &self.fiberQueue2; if (try globalScope.define("void")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getVoidType() } }; if (try globalScope.define("bool")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getBoolType(1) } }; if (try globalScope.define("b8")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getBoolType(1) } }; if (try globalScope.define("b16")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getBoolType(2) } }; if (try globalScope.define("b32")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getBoolType(4) } }; if (try globalScope.define("b64")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getBoolType(8) } }; if (try globalScope.define("i8")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(1, true, null) } }; if (try globalScope.define("i16")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(2, true, null) } }; if (try globalScope.define("i32")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(4, true, null) } }; if (try globalScope.define("i64")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(8, true, null) } }; if (try globalScope.define("i128")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(16, true, null) } }; if (try globalScope.define("u8")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(1, false, null) } }; if (try globalScope.define("u16")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(2, false, null) } }; if (try globalScope.define("u32")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(4, false, null) } }; if (try globalScope.define("u64")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(8, false, null) } }; if (try globalScope.define("u128")) |sym| sym.kind = .{ .Type = .{ .typ = try self.typeRegistry.getIntType(16, false, null) } }; if (try globalScope.define("bar")) |sym| sym.kind = .{ .NativeFunction = .{ .typ = try self.typeRegistry.createFromNativeType(@TypeOf(bar)), .wrapper = try NativeFunctionWrapper.init(bar, &self.constantsAllocator.allocator), } }; if (try globalScope.define("__add")) |sym| sym.kind = .{ .NativeFunction = .{ .typ = try self.typeRegistry.createFromNativeType(@TypeOf(add)), .wrapper = try NativeFunctionWrapper.init(add, &self.constantsAllocator.allocator), } }; if (try globalScope.define("__sub")) |sym| sym.kind = .{ .NativeFunction = .{ .typ = try self.typeRegistry.createFromNativeType(@TypeOf(sub)), .wrapper = try NativeFunctionWrapper.init(sub, &self.constantsAllocator.allocator), } }; if (try globalScope.define("__eql")) |sym| sym.kind = .{ .NativeFunction = .{ .typ = try self.typeRegistry.createFromNativeType(@TypeOf(eql)), .wrapper = try NativeFunctionWrapper.init(eql, &self.constantsAllocator.allocator), } }; if (try globalScope.define("__not")) |sym| sym.kind = .{ .NativeFunction = .{ .typ = try self.typeRegistry.createFromNativeType(@TypeOf(not)), .wrapper = try NativeFunctionWrapper.init(not, &self.constantsAllocator.allocator), } }; return self; } fn bar(a: bool, b: bool) void { var stdOut = std.io.getStdOut().writer(); const style = term.Style{ .foreground = .{ .RGB = .{ .r = 0x7a, .g = 0xd6, .b = 0x9a } } }; term.updateStyle(stdOut, style, null) catch {}; defer term.updateStyle(stdOut, .{}, style) catch {}; std.fmt.format(stdOut, "bar({}, {})\n", .{ a, b }) catch unreachable; } fn add(a: i128, b: i128) i128 { std.log.debug("add({}, {})", .{ a, b }); return a + b; } fn sub(a: i64, b: i64) i64 { std.log.debug("sub({}, {})", .{ a, b }); return a - b; } fn eql(a: i64, b: i64) bool { std.log.debug("eql({}, {})", .{ a, b }); return a == b; } fn not(a: bool) bool { std.log.debug("not({})", .{a}); return !a; } pub fn deinit(self: *Self) void { self.typeRegistry.deinit(); self.errorMsgBuffer.deinit(); // deinit fibers for (self.allFibers.items) |fiber| { fiber.deinit(); } self.allFibers.deinit(); self.fiberPool.deinit(); self.fiberQueue1.deinit(); self.fiberQueue2.deinit(); self.unqueuedJobs.deinit(); for (self.files.items) |file| { file.deinit(); self.allocator.destroy(file); } self.files.deinit(); self.globalScope.deinit(); self.allocator.destroy(self.globalScope); self.constantsAllocator.deinit(); self.stackAllocator.deinit(); self.astAllocator.deinit(); self.allocator.destroy(self); } pub fn reportError(self: *Self, location: ?*const Location, comptime format: []const u8, args: anytype) void { self.errorMsgBuffer.resize(0) catch unreachable; std.fmt.format(self.errorMsgBuffer.writer(), format, args) catch {}; self.errorReporter.report(self.errorMsgBuffer.items, location); } pub fn allocateSourceFile(self: *Self, path: StringBuf, content: StringBuf) !*SourceFile { var file = try self.allocator.create(SourceFile); file.* = SourceFile.init(path, content, self.allocator); try self.files.append(file); return file; } fn swapReadyAndWaitingQueue(self: *Self) void { const temp = self.readyFibers; self.readyFibers = self.waitingFibers; self.waitingFibers = temp; } fn getFreeFiber(self: *Self) !*FiberContext { if (self.fiberPool.items.len == 0) { const fiber = try FiberContext.init(self); try self.allFibers.append(fiber); return fiber; } else { return self.fiberPool.pop(); } } pub fn allocateAndAddJob(self: *Self, _job: anytype) !*Job { var job = try self.allocator.create(@TypeOf(_job)); job.* = _job; try self.addJob(&job.job); return &job.job; } pub fn addJob(self: *Self, job: *Job) !void { try self.unqueuedJobs.push(job); log.debug("{}, {}, {}", .{ self.unqueuedJobs.len(), self.readyFibers.len(), self.waitingFibers.len() }); } pub fn run(self: *Self) !void { var madeProgress = false; const _log = std.log.scoped(.EventLoop); while (true) { _log.debug("{}, {}, {}", .{ self.unqueuedJobs.len(), self.readyFibers.len(), self.waitingFibers.len() }); var fiber: ?*FiberContext = null; if (self.readyFibers.len() == 0 and self.waitingFibers.len() > 0 and madeProgress) { _log.debug("Move jobs from waiting queue to ready queue.", .{}); self.swapReadyAndWaitingQueue(); madeProgress = false; } if (self.readyFibers.pop()) |f| { _log.debug("Take job from ready queue.", .{}); fiber = f; } else if (self.unqueuedJobs.pop()) |job| { _log.debug("Start next job.", .{}); job.compiler = self; fiber = try self.getFreeFiber(); fiber.?.job = job; fiber.?.madeProgress = true; fiber.?.wasCancelled = false; fiber.?.done = false; fiber.?.state = .Suspended; } else { _log.debug("No more jobs left.", .{}); break; } if (fiber) |f| { try f.step(); madeProgress = madeProgress or f.madeProgress; if (f.done) { f.job.?.free(self.allocator); f.job = null; try self.fiberPool.append(f); } else { try self.waitingFibers.push(f); } } } std.debug.assert(self.unqueuedJobs.len() == 0); std.debug.assert(self.readyFibers.len() == 0); // Cancel all waiting jobs. _log.info("There are {} fibers still waiting.", .{self.waitingFibers.len()}); var it = self.waitingFibers.iterator(); while (it.next()) |f| { _log.info("Cancelling job.", .{}); f.wasCancelled = true; try f.step(); if (f.job) |j| { j.free(self.allocator); } } var it2 = self.unqueuedJobs.iterator(); while (it2.next()) |job| { job.free(self.allocator); } // print ast graph for (self.files.items) |file| { var newFileName = StringBuf.init(self.allocator); try std.fmt.format(newFileName.writer(), "{s}.gv", .{file.path.items}); defer newFileName.deinit(); var graphFile = try std.fs.cwd().createFile(newFileName.items, .{}); defer graphFile.close(); var dotPrinter = try DotPrinter.init(graphFile.writer(), true); defer dotPrinter.deinit(graphFile.writer()); for (file.asts.items) |ast| { try dotPrinter.printGraph(graphFile.writer(), ast); } } if (self.errorReporter.errorCount > 0) { self.reportError(null, "Compilation finished with {} errors.", .{self.errorReporter.errorCount}); return error.CompilationFailed; } } };
src/compiler.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const View = @This(); /// Creates a view from a rectangle pub fn fromRect(rect: sf.FloatRect) View { var ret: View = undefined; ret.center = rect.getCorner(); ret.size = rect.getSize(); ret.center = ret.center.add(ret.size.scale(0.5)); ret.viewport = sf.FloatRect.init(0, 0, 1, 1); return ret; } /// Creates a view from a CSFML object /// This is mainly for the inner workings of this wrapper pub fn _fromCSFML(view: *const sf.c.sfView) View { var ret: View = undefined; ret.center = sf.Vector2f._fromCSFML(sf.c.sfView_getCenter(view)); ret.size = sf.Vector2f._fromCSFML(sf.c.sfView_getSize(view)); ret.viewport = sf.FloatRect._fromCSFML(sf.c.sfView_getViewport(view)); return ret; } /// Creates a CSFML view from this view /// This is mainly for the inner workings of this wrapper /// The resulting view must be destroyed! pub fn _toCSFML(self: View) *sf.c.sfView { var view = sf.c.sfView_create().?; sf.c.sfView_setCenter(view, self.center._toCSFML()); sf.c.sfView_setSize(view, self.size._toCSFML()); sf.c.sfView_setViewport(view, self.viewport._toCSFML()); return view; } pub fn getRect(self: View) sf.FloatRect { return sf.FloatRect.init( self.center.x - self.size.x / 2, self.center.y - self.size.y / 2, self.size.x, self.size.y, ); } pub fn setSize(self: *View, size: sf.Vector2f) void { self.size = size; } pub fn setCenter(self: *View, center: sf.Vector2f) void { self.center = center; } pub fn zoom(self: *View, factor: f32) void { self.size = .{ .x = self.size.x * factor, .y = self.size.y * factor }; } // View variables /// Center of the view, what this view "looks" at center: sf.Vector2f, /// Width and height of the view size: sf.Vector2f, /// The viewport of this view viewport: sf.FloatRect, test "view: from rect" { const tst = @import("std").testing; // Testing if the view from rect initialization works var rect = sf.FloatRect.init(10, -15, 700, 600); var view = sf.c.sfView_createFromRect(rect._toCSFML()); defer sf.c.sfView_destroy(view); var view2 = View.fromRect(rect); var center = sf.Vector2f._fromCSFML(sf.c.sfView_getCenter(view)); var size = sf.Vector2f._fromCSFML(sf.c.sfView_getSize(view)); try tst.expectApproxEqAbs(center.x, view2.center.x, 0.00001); try tst.expectApproxEqAbs(center.y, view2.center.y, 0.00001); try tst.expectApproxEqAbs(size.x, view2.size.x, 0.00001); try tst.expectApproxEqAbs(size.y, view2.size.y, 0.00001); var rect_ret = view2.getRect(); try tst.expectApproxEqAbs(rect.left, rect_ret.left, 0.00001); try tst.expectApproxEqAbs(rect.top, rect_ret.top, 0.00001); try tst.expectApproxEqAbs(rect.width, rect_ret.width, 0.00001); try tst.expectApproxEqAbs(rect.height, rect_ret.height, 0.00001); view2.setCenter(.{ .x = 400, .y = 300 }); view2.setSize(.{ .x = 800, .y = 600 }); rect_ret = view2.getRect(); try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.left, 0.00001); try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.top, 0.00001); try tst.expectApproxEqAbs(@as(f32, 800), rect_ret.width, 0.00001); try tst.expectApproxEqAbs(@as(f32, 600), rect_ret.height, 0.00001); }
src/sfml/graphics/View.zig
const std = @import("std"); const testing = std.testing; const tok = @import("./token.zig"); const log = std.log.scoped(.lexer); const ascii = std.ascii; const Token = tok.Token; const Cursor = tok.Cursor; const tfmt = @import("./fmt.zig"); const colors = @import("../term/colors.zig"); const Color = colors.Color; const Kind = Token.Kind; const Val = Token.Val; const @"Type" = @import("./token/type.zig").@"Type"; const Timer = std.time.Timer; const Op = @import("./token/op.zig").Op; const Block = @import("./token/block.zig").Block; const Kw = @import("./token/kw.zig").Kw; // pub fn lex(allocator: std.mem.Allocator, inp: []u8) !std.ArrayList(Token) { pub const Lexer = struct { inp: []const u8, tokens: std.ArrayList(Token), pos: Cursor, offset: usize, start: bool, allocator: std.mem.Allocator, const Self = @This(); pub fn init(inp: []const u8, a: std.mem.Allocator) Lexer { const tokens = std.ArrayList(Token).init(a); defer tokens.deinit(); return Lexer{ .inp = inp, .tokens = tokens, .pos = Cursor.default(), .offset = 0, .start = true, .allocator = a, }; } pub fn lex(self: *Self) !std.ArrayList(Token) { while (self.next()) |ch| { switch (ch) { ' ' => {}, '*' => _ = try self.push(mulOrOther), '\n' => try self.tokens.append(self.newOp(.newline)), '.' => _ = try self.push(periodOrOther), '%' => try self.tokens.append(self.newOp(.mod)), '+' => _ = try self.push(addOrOther), '-' => _ = try self.push(subOrOther), '^' => try self.tokens.append(self.newOp(.caret)), '#' => try self.tokens.append(self.newOp(.pound)), '@' => try self.tokens.append(self.newOp(.at)), '$' => try self.tokens.append(self.newOp(.dol)), '~' => try self.tokens.append(self.newOp(.tilde)), '`' => try self.tokens.append(self.newBlock(.btick)), '!' => _ = try self.push(exclOrOther), '?' => try self.tokens.append(self.newOp(.ques)), '<' => _ = try self.push(ltOrOther), '>' => _ = try self.push(gtOrOther), '=' => _ = try self.push(eqOrOther), '(' => try self.tokens.append(self.newBlock(Block{ .lpar = null })), ')' => try self.tokens.append(self.newBlock(Block{ .rpar = null })), '{' => try self.tokens.append(self.newBlock(Block{ .lbrace = null })), '}' => try self.tokens.append(self.newBlock(Block{ .rbrace = null })), ';' => try self.tokens.append(self.newOp(.semicolon)), ':' => _ = try self.push(colonOrOther), ',' => try self.tokens.append(self.newOp(.comma)), '&' => try self.tokens.append(try self.consec('&', Kind{ .op = .amp })), '|' => _ = try self.push(pipeOrOther), '/' => _ = if (try self.divOrComment()) |token| try self.tokens.append(token), '_', 'a'...'z', 'A'...'Z' => try self.tokens.append(try self.identOrKw()), '"' => try self.tokens.append(try self.strLiteral()), '0'...'9' => try self.tokens.append(try self.intLiteral()), '\'' => try self.tokens.append(try self.intChar()), else => {}, } } try self.tokens.append(self.newKind(Token.Kind.eof)); return self.tokens; } pub fn push(self: *Self, f: fn (*Self) LexerError!?Token) !?Token { if (try f(self)) |token| { self.tokens.append(token) catch { return LexerError.OutOfSpace; }; return token; } else return null; } pub fn tokenListToString(self: Self) ![]u8 { var st = std.ArrayList(u8).init(self.allocator); for (self.tokens.items) |token| { const res = try tfmt.write(token, self.allocator); try st.appendSlice(res); } return st.allocatedSlice(); } pub fn newToken() Token { return Token{ .kind = .unknown, .offset = 0, .pos = Cursor.default() }; } pub fn newKind(self: Self, kind: Kind) Token { return Token{ .offset = 0, .pos = self.pos, .kind = kind }; } pub fn newOp(self: Self, op: Op) Token { return Token{ .offset = 0, .pos = self.pos, .kind = Kind{ .op = op } }; } pub fn newKw(self: Self, kw: Kw) Token { return Token{ .offset = 0, .pos = self.pos, .kind = Kind{ .kw = kw } }; } pub fn newBlock(self: Self, block: Block) Token { return Token{ .offset = 0, .pos = self.pos, .kind = Kind{ .block = block } }; } pub fn newType(self: Self, @"type": @"Type") Token { return Token{ .offset = 0, .pos = self.pos, .kind = Kind{ .type = @"type" } }; } pub fn current(self: Self) u8 { if (self.offset < self.inp.len) { return self.inp[self.offset]; } else return 0; } pub fn fmtPosition(self: Self) void { const args = .{ self.pos.line, self.pos.col, self.offset, self.inp.len }; log.err("[ln {d}, col {d}, offset {d}, buflen {d}", args); } pub fn next(self: *Self) ?u8 { if (self.start) self.start = false else { self.offset += 1; if (self.current() == '\n') { // It's a new line self.pos.newLine(); } else self.pos.incrCol(); } if (self.offset >= self.inp.len) return null else return self.current(); } pub fn peek(self: Self) ?u8 { if (self.offset + 1 >= self.inp.len) { return null; } else { return self.inp[self.offset + 1]; } } // Called when: found '/', need to know if next char is * or else pub fn divOrComment(self: *Self) LexerError!?Token { if (self.peek()) |ch| if (ch == '*') { _ = self.next(); while (self.next()) |chs| if (chs == '*') { if (self.peek()) |nch| if (nch == '/') { _ = self.next(); return null; }; }; return LexerError.EofInComment; }; return self.newOp(Op.div); } // Called when: found ':', need to know if next char is * or else pub fn colonOrOther(self: *Lexer) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '.' => { _ = self.next(); if (self.peek()) |chn| { return switch (chn) { '.' => self.newBlock(Block{ .rsynth = null }), else => self.newBlock(Block{ .ldata = null }), }; } return LexerError.EofInComment; }, ':' => self.newOp(Op.abstractor), '-' => { _ = self.next(); if (self.peek()) |chn| { return switch (chn) { '-' => self.newBlock(Block{ .rdef = null }), else => self.newBlock(Block{ .rattr = null }), }; } return LexerError.EofInComment; }, '=' => self.newOp(Op.defn), '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.faccess), ' ' => self.newOp(Op.colon), else => null, }; _ = self.next(); return tk; } else return LexerError.EofInComment; } // Called when: found '=', need to know if next char is * or else pub fn eqOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '=' => self.newOp(Op.eq_comp), '>' => self.newOp(Op.bfarrow), '@' => self.newOp(Op.addressed), '?' => self.newOp(Op.query), '!' => self.newOp(Op.ne), // assign to something else? never? ':' => self.newOp(Op.defn), // secondary, colon 1st ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.assign), else => null, }; _ = self.next(); return tk; } else return LexerError.EofInComment; } pub fn ltOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '=' => self.newOp(Op.le), '>' => self.newOp(Op.assoc), // <> '-' => self.newOp(Op.barrow), '<' => self.newOp(Op.double_lt), // assign to something else? never? ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.lt), // OR type param? else => null, }; _ = self.next(); return tk; } else return LexerError.EofInComment; } pub fn gtOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { _ = self.next(); const tk = switch (ch) { '=' => self.newOp(Op.ge), '>' => self.newOp(Op.double_gt), // <> ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.gt), // OR type param? else => null, }; return tk; } else return LexerError.EofInComment; } // Called when: found '+', need to know if next char is * or else pub fn mulOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '*' => self.newOp(Op.exp), '=' => self.newOp(Op.mul_eq), ' ' => self.newOp(Op.mul), '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.pointer), else => null, }; return tk; } else return LexerError.EofInComment; } // Called when: found '+', need to know if next char is * or else pub fn addOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '+' => self.newOp(Op.bind), '=' => self.newOp(Op.add_eq), ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.add), else => null, }; return tk; } else return LexerError.EofInComment; } pub fn subOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk = switch (ch) { '>' => self.newOp(Op.farrow), '-' => { _ = self.next(); if (self.peek()) |chn| { const ntk = switch (chn) { '|' => self.newBlock(Block.lcomment), '?' => self.newBlock(Block.lque), '!' => self.newBlock(Block.ldoc), ':' => self.newBlock(Block{ .ldef = null }), else => self.newOp(Op.comment), }; return ntk; } return LexerError.EofInComment; }, '=' => self.newOp(Op.sub_eq), '|' => self.newBlock(Block{ .lstate = null }), '!' => self.newBlock(Block.ldocln), '?' => self.newBlock(Block.llnquery), ':' => self.newBlock(Block{ .lattr = null }), ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.sub), else => null, }; return tk; } else return LexerError.EofInComment; } // Called when: found '!', need to know if next char is * or else pub fn exclOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk: ?Token = switch (ch) { '=' => self.newOp(Op.ne), '.' => { _ = self.next(); if (self.peek()) |chn| { return switch (chn) { '.' => self.newBlock(.rawait), else => null, }; } return LexerError.EofInStr; }, '-' => { _ = self.next(); if (self.peek()) |chn| { return switch (chn) { '-' => self.newBlock(.rdoc), else => self.newBlock(.rdocln), }; } return LexerError.EofInStr; }, '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.not), ' ' => self.newOp(.excl), else => null, }; return tk; } else return LexerError.EofInComment; } // Called when: found '.', need to know if next char is * or else pub fn periodOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk: ?Token = switch (ch) { '.' => { _ = self.next(); if (self.peek()) |chn| { return switch (chn) { '.' => { _ = self.next(); const tr: ?Token = self.newOp(Op.range); return tr; }, '!' => self.newBlock(Block.lawait), '?' => self.newBlock(Block.lawaitque), ':' => self.newOp(Op.range_xr), else => self.newOp(Op.range_xx), }; } else return LexerError.EofInComment; }, '!' => self.newOp(Op.access), // deref? '?' => self.newOp(Op.access), // optional? ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(Op.access), else => null, }; return tk; } else return LexerError.EofInComment; } // Called when: found '|', need to know if next char is - or else pub fn pipeOrOther(self: *Self) LexerError!?Token { if (self.peek()) |ch| { const tk: ?Token = switch (ch) { '-' => { _ = self.next(); if (self.peek()) |chn| return switch (chn) { '-' => self.newBlock(.rcomment), else => self.newBlock(Block{ .rstate = null }), } else return LexerError.EofInStr; }, '|' => self.newOp(Op.@"or"), ' ', '_', 'a'...'z', 'A'...'Z', '0'...'9' => self.newOp(.pipe), else => null, }; return tk; } else return LexerError.EofInComment; } pub fn identOrKw(self: *Self) !Token { var outp = Self.newToken(); const p_i = self.offset; while (self.peek()) |ch| : (_ = self.next()) { switch (ch) { '_', 'a'...'z', 'A'...'Z', '0'...'9' => {}, else => break, } } const p_f = self.offset + 1; var st = self.inp[p_i..p_f]; if (Kind.isKw(st)) |kwd| { outp.kind = Kind{ .kw = kwd }; } else { outp.kind = Kind{ .type = @"Type"{ .ident = st } }; outp.val = Val{ .str = st }; } return outp; } pub fn strLiteral(self: *Self) !Token { var outp = self.newType(@"Type"{ .str = "" }); const p_i = self.offset; while (self.next()) |ch| { switch (ch) { '"' => break, '\n' => return LexerError.EolInStr, '\\' => { switch (self.peek() orelse return LexerError.EofInStr) { 'n', '\\' => _ = self.next(), else => return LexerError.UnknownEscSeq, } }, else => {}, } } else { return LexerError.EofInStr; } const p_f = self.offset + 1; outp.val = Val{ .str = self.inp[p_i..p_f] }; return outp; } pub fn followed(self: *Self, by: u8, pos_type: Kind, neg_type: Kind) Token { var outp = Self.newToken(); if (self.peek()) |ch| { if (ch == by) { _ = self.next(); outp.kind = pos_type; } else { outp.kind = neg_type; } } else { outp.kind = neg_type; } return outp; } pub fn consec(self: *Self, by: u8, kind: Kind) LexerError!Token { const outp = self.newKind(kind); if (self.peek()) |ch| { if (ch == by) { _ = self.next(); return outp; } else { return LexerError.UnknownChar; } } else { return LexerError.UnknownChar; } } pub fn intLiteral(self: *Self) LexerError!Token { var outp = self.newKind(Kind{ .type = @"Type"{ .int = 0 } }); const p_i = self.offset; while (self.peek()) |ch| { switch (ch) { '0'...'9' => { _ = self.next(); }, '_', 'a'...'z', 'A'...'Z' => { return LexerError.InvalidNum; }, else => break, } } const p_f = self.offset + 1; outp.val = Val{ .intl = std.fmt.parseInt(i32, self.inp[p_i..p_f], 10) catch { return LexerError.InvalidNum; }, }; return outp; } pub fn nextOrEmpty(self: *Self) LexerError!u8 { return self.next() orelse LexerError.EmptyCharConst; } pub fn intChar(self: *Self) LexerError!Token { var outp = self.newType(@"Type"{ .int = 0 }); switch (try self.nextOrEmpty()) { '\'', '\n' => return LexerError.EmptyCharConst, '\\' => { switch (try self.nextOrEmpty()) { 'n' => outp.val = Val{ .intl = '\n' }, '\\' => outp.val = Val{ .intl = '\\' }, else => return LexerError.EmptyCharConst, } switch (try self.nextOrEmpty()) { '\'' => {}, else => return LexerError.EmptyCharConst, } }, else => { outp.val = Val{ .intl = self.current() }; switch (try self.nextOrEmpty()) { '\'' => {}, else => return LexerError.MulticharConst, } }, } return outp; } }; pub const Tokenizer = struct { it: std.mem.SplitIterator(u8), idk: usize, const Self = @This(); pub fn init(input: []const u8) Self { return Self{ .it = std.mem.split(u8, input, "\n") }; } pub fn next(self: *Self) !?Token { while (self.it.next()) |ln| { if (ln.len == 0) return null; var tok_it = std.mem.tokenize(u8, ln, " "); const content = tok_it.next(); if (content) |t| { const token = Token.Kind.fromString(t); self.idx = t.index; return token; } } return null; } }; pub const LexerError = error{ Init, EmptyCharConst, UnknownEscSeq, MulticharConst, EofInComment, EofInStr, EolInStr, UnknownChar, InvalidNum, OutOfSpace } || std.fmt.ParseIntError; test "parses_idents_ok" { testing.expectEqual(5, 5); }
src/lang/lexer.zig
const Server = @This(); const std = @import("std"); const json = @import("json.zig"); const utils = @import("utils.zig"); const types = @import("types.zig"); const offsets = @import("offsets.zig"); const RequestHeader = @import("RequestHeader.zig"); pub const ServerMessage = union(enum) { request: types.requests.RequestMessage, notification: types.notifications.NotificationMessage, pub fn encode(self: ServerMessage, writer: anytype) @TypeOf(writer).Error!void { try json.stringify(self, .{}, writer); } pub fn decode(allocator: *std.mem.Allocator, buf: []const u8) !ServerMessage { @setEvalBranchQuota(10_000); return (try json.parse(ServerMessageParseTarget, &json.TokenStream.init(buf), .{ .allocator = allocator, .ignore_unknown_fields = true, })).toMessage(); } }; const ServerMessageParseTarget = union(enum) { request: types.requests.RequestParseTarget, notification: types.notifications.NotificationParseTarget, pub fn toMessage(self: ServerMessageParseTarget) ServerMessage { return switch (self) { .request => |r| .{ .request = r.toMessage() }, .notification => |n| .{ .notification = n.toMessage() }, }; } }; allocator: *std.mem.Allocator, arena: std.heap.ArenaAllocator, offset_encoding: offsets.Encoding, read_buf: std.ArrayList(u8), write_buf: std.ArrayList(u8), pub fn init(allocator: *std.mem.Allocator) !Server { return Server{ .allocator = allocator, .arena = std.heap.ArenaAllocator.init(allocator), .offset_encoding = .utf16, .read_buf = try std.ArrayList(u8).initCapacity(allocator, 1024), .write_buf = try std.ArrayList(u8).initCapacity(allocator, 1024), }; } /// Reads a message (request or notification). /// Caller must call `flushArena` after use. pub fn readMessage(self: *Server) !ServerMessage { const stdin = std.io.getStdIn().reader(); var header_buf: [128]u8 = undefined; var header = try RequestHeader.decode(stdin, &header_buf); try self.read_buf.ensureTotalCapacity(header.content_length); self.read_buf.items.len = header.content_length; _ = try stdin.readAll(self.read_buf.items[0..header.content_length]); std.debug.print("{s}\n", .{self.read_buf.items}); return try ServerMessage.decode(&self.arena.allocator, self.read_buf.items); } pub fn flushArena(self: *Server) void { self.arena.deinit(); self.arena.state = .{}; } pub fn respond(self: *Server, request: types.requests.RequestMessage, result: types.responses.ResponseParams) !void { try utils.send(&self.write_buf, types.responses.ResponseMessage{ .id = request.id, .result = result, }); } pub fn notify(self: *Server, params: types.notifications.NotificationParams) !void { inline for (std.meta.fields(types.notifications.NotificationParams)) |field| { if (params == @field(types.notifications.NotificationParams, field.name)) { try utils.send(&self.write_buf, types.notifications.NotificationMessage{ .method = @field(field.field_type, "method"), .params = params, }); } } } /// Processes an `initialize` message /// * Sets the offset encoding pub fn processInitialize(self: *Server, initalize: types.general.InitializeParams) void { for (initalize.capabilities.offsetEncoding) |encoding| { if (std.mem.eql(u8, encoding, "utf-8")) { self.offset_encoding = .utf8; } } }
src/Server.zig
const std = @import("std"); usingnamespace @import("common/shader.zig"); usingnamespace @import("common/font.zig"); usingnamespace @import("ui_builder"); usingnamespace @import("zalgebra"); const glfw = @import("common/c.zig").glfw; usingnamespace @import("common/c.zig").gl; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const panic = std.debug.panic; const print = std.debug.print; const WINDOW_WIDTH: i32 = 1200; const WINDOW_HEIGHT: i32 = 800; const WINDOW_NAME = "UI Builder"; var codepoint: ?u21 = null; pub fn main() !void { if (glfw.glfwInit() == glfw.GL_FALSE) { panic("Failed to intialize GLFW.\n", .{}); } glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3); glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 2); glfw.glfwWindowHint(glfw.GLFW_OPENGL_FORWARD_COMPAT, glfw.GL_TRUE); glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE); const window = glfw.glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_NAME, null, null) orelse { panic("Unable to create window.\n", .{}); }; glfw.glfwMakeContextCurrent(window); glfw.glEnable(glfw.GL_DEPTH_TEST); glfw.glfwSwapBuffers(window); glfw.glfwPollEvents(); _ = glfw.glfwSetCharCallback(window, char_callback); defer glfw.glfwDestroyWindow(window); defer glfw.glfwTerminate(); var helvetica = try Font.init("helvetica"); defer helvetica.deinit(); var shape_render_obj = create_render_object(); var text_render_obj = create_render_object(); const quad_vert = @embedFile("assets/shaders/quad.vert"); const quad_frag = @embedFile("assets/shaders/quad.fs"); const text_vert = @embedFile("assets/shaders/text.vert"); const text_frag = @embedFile("assets/shaders/text.fs"); const quad_shader = try Shader.create("quad", quad_vert, quad_frag); const text_shader = try Shader.create("text", text_vert, text_frag); var font_size: f32 = 16; var ui = try Interface(Font).init(.{ .allocator = &gpa.allocator, .font = &helvetica, .font_size = font_size, .calc_text_size = calc_text_size, }, .{}); var should_close = false; var counter: i32 = 0; var checkbox_value = false; var value_to_incr: f32 = 0.5; var options = [_][]const u8{ "Option A", "Option B", "Option C" }; var selected_opt: usize = 0; var slider_value: f32 = 50; var value_to_edit: f32 = 23.3214345345; while (!should_close) { glfw.glfwPollEvents(); glfw.glClear(glfw.GL_COLOR_BUFFER_BIT | glfw.GL_DEPTH_BUFFER_BIT); should_close = glfw.glfwWindowShouldClose(window) == glfw.GL_TRUE or glfw.glfwGetKey(window, glfw.GLFW_KEY_ESCAPE) == glfw.GLFW_PRESS; // Build the interface. ui.reset(); var cursor_x: f64 = undefined; var cursor_y: f64 = undefined; glfw.glfwGetCursorPos(window, &cursor_x, &cursor_y); ui.send_cursor_position( @floatCast(f32, cursor_x), @floatCast(f32, cursor_y), ); const mouse_left_down = glfw.glfwGetMouseButton(window, 0) == 1; // const mouse_right_down = glfw.glfwGetMouseButton(window, 1) == 1; try ui.send_input_key(.Cursor, mouse_left_down); try ui.send_input_key(.Bspc, glfw.glfwGetKey(window, 259) == 1); if (codepoint) |c| { try ui.send_codepoint(c); codepoint = null; } if (ui.panel("Graph Panel", 450, 50, 250, 400)) { ui.label("Beautiful graph:", .Left); var data = [_]f32{ 0.5, 10, 23, 35, 70, 10, 2.4, 34.5, 40.5 }; ui.graph(&data, 70); } if (ui.panel("Debug Panel", 25, 25, 400, 700)) { try ui.label_alloc("counter: {}", .{counter}, .Left); try ui.alloc_incr_value(i32, &counter, 1, 0, 100); ui.row_array_static(&[_]f32{ 100, 150 }, 0); try ui.edit_value(f32, &value_to_edit, "{d:.3}"); try ui.label_alloc("floating value: {d}", .{value_to_edit}, .Left); ui.padding_space(5); ui.label("Editing String: ", .Left); if (try ui.edit_string("test")) |str| { print("String updated: {s}\n", .{str}); } ui.padding_space(25); if (ui.tree_begin("Widgets", true, .Collapser)) { ui.row_flex(0, 3); if (ui.button("btn_1")) {} if (ui.button("btn_2")) {} if (ui.button("btn_3")) {} ui.row_flex(0, 1); if (ui.button("btn_4")) {} ui.row_array_static(&[_]f32{ 50, 150 }, 0); ui.label("Select: ", .Left); selected_opt = ui.select(&options, selected_opt); ui.label("Slider: ", .Left); slider_value = ui.slider(0, 100, slider_value, 1); ui.row_flex(0, 1); ui.checkbox_label("Checkbox!", &checkbox_value); try ui.alloc_incr_value(f32, &value_to_incr, 2.5, 0, 50); ui.label("Left", .Left); ui.label("Center", .Center); ui.label("Right", .Right); ui.tree_end(); } if (ui.button("Close")) should_close = true; } // Send shapes to GPU. const data = ui.process_ui(); send_data_to_gpu(&shape_render_obj, data.vertices, data.indices); // Draw eveything { glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); defer glDisable(GL_SCISSOR_TEST); const size = blk: { var x: c_int = 0; var y: c_int = 0; var fx: c_int = 0; var fy: c_int = 0; glfw.glfwGetFramebufferSize(window, &fx, &fy); glfw.glfwGetWindowSize(window, &x, &y); break :blk .{ .width = @intToFloat(f32, x), .height = @intToFloat(f32, y), .frame_width = @intToFloat(f32, fx), .frame_height = @intToFloat(f32, fy), }; }; for (ui.draw()) |d| { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const clip = d.clip; const fb_scale_x = size.frame_width / size.width; const fb_scale_y = size.frame_height / size.height; glScissor( @floatToInt(c_int, clip.x * fb_scale_x), @floatToInt( c_int, (size.height - (clip.y + clip.h)) * fb_scale_y, ), @floatToInt(c_int, clip.w * fb_scale_x), @floatToInt(c_int, clip.h * fb_scale_y), ); // Draw shapes { const proj = orthographic(0, size.width, size.height, 0, -1, 1); glUseProgram(quad_shader.program_id); quad_shader.setMat4("projection", &proj); glBindVertexArray(shape_render_obj.vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, shape_render_obj.ebo.?); glDrawElements( GL_TRIANGLES, @intCast(c_int, d.vertex_count), GL_UNSIGNED_INT, @intToPtr(*allowzero c_void, d.offset * @sizeOf(u32)), ); glBindVertexArray(0); } for (d.texts) |text| { glUseProgram(text_shader.program_id); const proj = orthographic(0, size.width, 0, size.height, -1, 1); text_shader.setMat4("projection", &proj); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, helvetica.texture_id); text_shader.setInteger("glyph", @as(i32, 1)); immediate_draw_text(.{ .text = text.content, .color = vec3.from_slice(&text.color.to_array()), .pos_x = text.x, .pos_y = size.height - text.y, .size = ui.cfg.font_size, }, &helvetica, &text_render_obj); glBindVertexArray(0); } } glDisable(GL_BLEND); } glfw.glfwSwapBuffers(window); // TODO: Understand this shit. WTF? glfw.glFlush(); glfw.glFinish(); } } // Render object identifier. pub const RenderObject = struct { vao: u32, vbo: u32, ebo: ?u32, triangle_count: i32, indice_type: enum { u16, u32 }, }; fn calc_text_size(font: *Font, size: f32, text: []const u8) f32 { const ratio_size = size / font.size; var text_cursor: f32 = 0; for (text) |letter| { if (font.characters.get(&[_]u8{letter})) |c| { text_cursor += c.advance * ratio_size; } } return text_cursor; } pub fn char_callback(_: ?*glfw.GLFWwindow, c: c_uint) callconv(.C) void { codepoint = @intCast(u21, c); } pub fn send_data_to_gpu( render_obj: *RenderObject, vertices: []const f32, indices: []const u32, ) void { glBindVertexArray(render_obj.vao); glBindBuffer(GL_ARRAY_BUFFER, render_obj.vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, render_obj.ebo.?); const vertex_size = @intCast(c_long, vertices.len * @sizeOf(f32)); const element_size = @intCast(c_uint, indices.len * @sizeOf(u32)); const max_vertex_size: c_long = 512 * 1024; const max_element_size: c_long = 256 * 1024; std.debug.assert(vertex_size <= max_vertex_size); glBufferData(GL_ARRAY_BUFFER, max_vertex_size, null, GL_STREAM_DRAW); glBufferData(GL_ARRAY_BUFFER, vertex_size, vertices.ptr, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, max_element_size, null, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, element_size, indices.ptr, GL_STREAM_DRAW); render_obj.triangle_count = @intCast(i32, indices.len); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } pub fn create_render_object() RenderObject { var r: RenderObject = undefined; glGenVertexArrays(1, &r.vao); glGenBuffers(1, &r.vbo); r.ebo = 0; glGenBuffers(1, &r.ebo.?); glBindVertexArray(r.vao); glBindBuffer(GL_ARRAY_BUFFER, r.vbo); const stride = 8 * @sizeOf(f32); // Vertex. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, null); glEnableVertexAttribArray(0); // UV. const uv_ptr = @intToPtr(*c_void, 2 * @sizeOf(f32)); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, uv_ptr); glEnableVertexAttribArray(1); // Color. const color_ptr = @intToPtr(*c_void, 4 * @sizeOf(f32)); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, stride, color_ptr); glEnableVertexAttribArray(2); glBindVertexArray(0); return r; }
demo/glfw_gl3.zig
const std = @import("std"); const warn = std.debug.print; const Allocator = std.mem.Allocator; const AnyErrorOutStream = std.io.OutStream(anyerror); const enabled = false; /// Formerly LoggingAllocator /// This allocator is used in front of another allocator and logs to the provided stream /// on every call to the allocator. Stream errors are ignored. /// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved. pub const WarningAllocator = struct { allocator: Allocator, parent_allocator: *Allocator, total: u64, const Self = @This(); pub fn init(parent_allocator: *Allocator) Self { return Self{ .allocator = Allocator{ .reallocFn = realloc, .shrinkFn = shrink, }, .parent_allocator = parent_allocator, .total = 0, }; } fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); if (enabled) { if (old_mem.len == 0) { warn("allocation of {} ", new_size); } else { warn("resize from {} to {} ", old_mem.len, new_size); } } const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align); if (enabled) { if (result) |buff| { //self.total = mem_size_diff; zig bug warn("success!\n"); } else |err| { warn("failure!\n"); } } return result; } fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const mem_size_diff = old_mem.len - new_size; //self.total -= mem_size_diff; const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align); if (new_size == 0) { warn("free of {} bytes success! total {}\n", old_mem.len, mem_size_diff); } else { warn("shrink from {} bytes to {} bytes success! total {}\n", old_mem.len, new_size, mem_size_diff); } return result; } };
src/warning_allocator.zig
const std = @import("std"); const main = @import("../main.zig"); const Op = @import("Op.zig"); const Reg8 = main.Cpu.Reg8; const Reg16 = main.Cpu.Reg16; test "" { _ = @import("impl_daa_test.zig"); } pub fn Result(lengt: u2, duration: anytype) type { if (duration.len == 1) { return extern struct { pub const length = lengt; pub const durations = [_]u8{duration[0]} ** 2; duration: u8 = duration[0], }; } else { return extern struct { pub const length = lengt; // Switch to this once "type coercion of anon list literal to array" // pub const durations: [2]u8 = duration; pub const durations = [_]u8{ duration[0], duration[1] }; duration: u8, }; } } pub fn ILLEGAL___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.mode = .illegal; return .{}; } pub fn nop_______(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { return .{}; } pub fn sys__mo___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.mode = op.arg0.mo; return .{}; } pub fn scf_______(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.reg.flags = .{ .Z = cpu.reg.flags.Z, .N = false, .H = 0, .C = 1, }; return .{}; } pub fn ccf_______(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.reg.flags = .{ .Z = cpu.reg.flags.Z, .N = false, .H = 0, .C = ~cpu.reg.flags.C, }; return .{}; } pub fn int__tf___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.interrupt_master = op.arg0.tf; return .{}; } pub fn daa__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { // https://www.reddit.com/r/EmuDev/comments/4ycoix/a_guide_to_the_gameboys_halfcarry_flag/d6p3rtl?utm_source=share&utm_medium=web2x // On the Z80: // If C is set OR a > 0x99, add or subtract 0x60 depending on N, and set C // If H is set OR (a & 0xf) > 9, add or subtract 6 depending on N // On the GB: // DAA after an add (N flag clear) works the same way as on the Z80 // DAA after a subtract (N flag set) only tests the C and H flags, and not the previous value of a // H is always cleared (for both add and subtract) // N is preserved, Z is set the usual way, and the rest of the Z80 flags don't exist const dst = op.arg0.rb; const start = cpu.reg._8.get(dst); var val = start; var carry = cpu.reg.flags.C; if (cpu.reg.flags.N) { // SUB -> DAA if (cpu.reg.flags.H == 1) { val -%= 0x6; } if (carry == 1) { val -%= 0x60; } } else { // ADD -> DAA if (cpu.reg.flags.H == 1 or (val >> 0 & 0xF) > 0x9) { carry |= @boolToInt(@addWithOverflow(u8, val, 0x6, &val)); } if (carry == 1 or (val >> 4 & 0xF) > 0x9) { carry |= @boolToInt(@addWithOverflow(u8, val, 0x60, &val)); } } cpu.reg._8.set(dst, val); cpu.reg.flags = .{ .Z = val == 0, .N = cpu.reg.flags.N, .H = 0, .C = carry, }; return .{}; } pub fn jr___IB___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{12}) { const jump = signedAdd(cpu.reg._16.get(.PC), op.arg0.ib); cpu.reg._16.set(.PC, jump); return .{}; } pub fn jr___zc_IB(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{ 8, 12 }) { if (op.arg0.zc.check(cpu.*)) { const jump = signedAdd(cpu.reg._16.get(.PC), op.arg1.ib); cpu.reg._16.set(.PC, jump); return .{ .duration = 12 }; } return .{ .duration = 8 }; } pub fn jp___IW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{16}) { cpu.reg._16.set(.PC, op.arg0.iw); return .{}; } pub fn jp___zc_IW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{ 12, 16 }) { if (op.arg0.zc.check(cpu.*)) { cpu.reg._16.set(.PC, op.arg1.iw); return .{ .duration = 16 }; } return .{ .duration = 12 }; } pub fn jp___RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const jump = cpu.reg._16.get(op.arg0.rw); cpu.reg._16.set(.PC, jump); return .{}; } pub fn ret_______(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{16}) { const jump = pop16(cpu, mmu); cpu.reg._16.set(.PC, jump); return .{}; } pub fn reti______(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{16}) { const jump = pop16(cpu, mmu); cpu.reg._16.set(.PC, jump); cpu.interrupt_master = true; return .{}; } pub fn ret__zc___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{ 8, 20 }) { if (op.arg0.zc.check(cpu.*)) { const jump = pop16(cpu, mmu); cpu.reg._16.set(.PC, jump); return .{ .duration = 20 }; } return .{ .duration = 8 }; } pub fn rst__ib___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{16}) { push16(cpu, mmu, cpu.reg._16.get(.PC)); cpu.reg._16.set(.PC, op.arg0.ib); return .{}; } pub fn call_IW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{24}) { push16(cpu, mmu, cpu.reg._16.get(.PC)); cpu.reg._16.set(.PC, op.arg0.iw); return .{}; } pub fn call_zc_IW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{ 12, 24 }) { if (op.arg0.zc.check(cpu.*)) { push16(cpu, mmu, cpu.reg._16.get(.PC)); cpu.reg._16.set(.PC, op.arg1.iw); return .{ .duration = 24 }; } return .{ .duration = 12 }; } pub fn rlca_rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRlc(cpu, cpu.reg._8.get(tgt))); cpu.reg.flags.Z = false; return .{}; } pub fn rla__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRl(cpu, cpu.reg._8.get(tgt))); cpu.reg.flags.Z = false; return .{}; } pub fn rrca_rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRrc(cpu, cpu.reg._8.get(tgt))); cpu.reg.flags.Z = false; return .{}; } pub fn rra__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRr(cpu, cpu.reg._8.get(tgt))); cpu.reg.flags.Z = false; return .{}; } pub fn ld___rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { cpu.reg._8.set(op.arg0.rb, op.arg1.ib); return .{}; } pub fn ld___rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { cpu.reg._8.copy(op.arg0.rb, op.arg1.rb); return .{}; } pub fn ld___rb_RB(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = @as(u16, 0xFF00) + cpu.reg._8.get(op.arg1.rb); cpu.reg._8.set(op.arg0.rb, mmu.get(addr)); return .{}; } pub fn ld___RB_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = @as(u16, 0xFF00) + cpu.reg._8.get(op.arg0.rb); mmu.set(addr, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn ld___rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { cpu.reg._8.set(op.arg0.rb, mmu.get(cpu.reg._16.get(op.arg1.rw))); return .{}; } pub fn ld___rw_iw(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{12}) { cpu.reg._16.set(op.arg0.rw, op.arg1.iw); return .{}; } pub fn ld___RW_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg0.rw); mmu.set(addr, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn ld___IW_rw(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{20}) { // TODO: verify this is correct const val = cpu.reg._16.get(op.arg1.rw); mmu.set(op.arg0.iw, @truncate(u8, val)); mmu.set(op.arg0.iw +% 1, @truncate(u8, val >> 8)); return .{}; } pub fn ld___RW_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{12}) { const addr = cpu.reg._16.get(op.arg0.rw); mmu.set(addr, op.arg1.ib); return .{}; } pub fn ld___IW_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{16}) { mmu.set(op.arg0.iw, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn ld___rb_IW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(3, .{16}) { cpu.reg._8.set(op.arg0.rb, mmu.get(op.arg1.iw)); return .{}; } pub fn ld___rw_rw(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { cpu.reg._16.copy(op.arg0.rw, op.arg1.rw); return .{}; } pub fn ldhl_rw_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const val = cpu.reg._16.get(op.arg0.rw); cpu.reg.flags = .{ .Z = false, .N = false, .H = willCarryInto(4, val, op.arg1.ib), .C = willCarryInto(8, val, op.arg1.ib), }; cpu.reg._16.set(.HL, signedAdd(val, op.arg1.ib)); return .{}; } pub fn ldi__RW_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const tgt = op.arg0.rw; const addr = cpu.reg._16.get(tgt); mmu.set(addr, cpu.reg._8.get(op.arg1.rb)); cpu.reg._16.set(tgt, addr +% 1); return .{}; } pub fn ldi__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const src = op.arg1.rw; const addr = cpu.reg._16.get(src); cpu.reg._8.set(op.arg0.rb, mmu.get(addr)); cpu.reg._16.set(src, addr +% 1); return .{}; } pub fn ldd__RW_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const tgt = op.arg0.rw; const addr = cpu.reg._16.get(tgt); mmu.set(addr, cpu.reg._8.get(op.arg1.rb)); cpu.reg._16.set(tgt, addr -% 1); return .{}; } pub fn ldd__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const src = op.arg1.rw; const addr = cpu.reg._16.get(src); cpu.reg._8.set(op.arg0.rb, mmu.get(addr)); cpu.reg._16.set(src, addr -% 1); return .{}; } pub fn ldh__IB_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{12}) { mmu.set(@as(u16, 0xFF00) + op.arg0.ib, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn ldh__rb_IB(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{12}) { cpu.reg._8.set(op.arg0.rb, mmu.get(@as(u16, 0xFF00) + op.arg1.ib)); return .{}; } pub fn inc__rw___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const val = cpu.reg._16.get(op.arg0.rw); cpu.reg._16.set(op.arg0.rw, val +% 1); return .{}; } pub fn inc__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{12}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); cpu.reg.flags = .{ .Z = (val +% 1) == 0, .N = false, .H = willCarryInto(4, val, 1), .C = cpu.reg.flags.C, }; mmu.set(addr, val +% 1); return .{}; } pub fn inc__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const val = cpu.reg._8.get(op.arg0.rb); cpu.reg.flags = .{ .Z = (val +% 1) == 0, .N = false, .H = willCarryInto(4, val, 1), .C = cpu.reg.flags.C, }; cpu.reg._8.set(op.arg0.rb, val +% 1); return .{}; } pub fn dec__rw___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const val = cpu.reg._16.get(op.arg0.rw); cpu.reg._16.set(op.arg0.rw, val -% 1); return .{}; } pub fn dec__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{12}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); cpu.reg.flags = .{ .Z = (val -% 1) == 0, .N = true, .H = willBorrowFrom(4, val, 1), .C = cpu.reg.flags.C, }; mmu.set(addr, val -% 1); return .{}; } pub fn dec__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const val = cpu.reg._8.get(op.arg0.rb); cpu.reg.flags = .{ .Z = (val -% 1) == 0, .N = true, .H = willBorrowFrom(4, val, 1), .C = cpu.reg.flags.C, }; cpu.reg._8.set(op.arg0.rb, val -% 1); return .{}; } pub fn add__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doAddRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn add__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doAddRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn add__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doAddRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn add__rw_rw(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const tgt = op.arg0.rw; const src_val = cpu.reg._16.get(op.arg1.rw); const tgt_val = cpu.reg._16.get(tgt); cpu.reg.flags = .{ .Z = cpu.reg.flags.Z, .N = false, .H = willCarryInto(12, tgt_val, src_val), .C = willCarryInto(16, tgt_val, src_val), }; cpu.reg._16.set(tgt, tgt_val +% src_val); return .{}; } pub fn add__rw_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const tgt = op.arg0.rw; const offset = op.arg1.ib; const val = cpu.reg._16.get(tgt); cpu.reg.flags = .{ .Z = false, .N = false, .H = willCarryInto(4, val, offset), .C = willCarryInto(8, val, offset), }; cpu.reg._16.set(tgt, signedAdd(val, offset)); return .{}; } pub fn adc__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doAdcRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn adc__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doAdcRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn adc__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doAdcRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn sub__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doSubRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn sub__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doSubRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn sub__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doSubRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn sbc__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doSbcRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn sbc__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doSbcRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn sbc__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doSbcRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn and__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doAndRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn and__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doAndRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn and__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doAndRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn or___rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doOrRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn or___rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doOrRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn or___rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doOrRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn xor__rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doXorRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn xor__rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doXorRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn xor__rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doXorRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn cp___rb_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { doCpRr(cpu, op.arg0.rb, cpu.reg._8.get(op.arg1.rb)); return .{}; } pub fn cp___rb_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{8}) { const addr = cpu.reg._16.get(op.arg1.rw); doCpRr(cpu, op.arg0.rb, mmu.get(addr)); return .{}; } pub fn cp___rb_ib(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { doCpRr(cpu, op.arg0.rb, op.arg1.ib); return .{}; } pub fn cpl__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{4}) { const tgt = op.arg0.rb; const val = cpu.reg._8.get(tgt); cpu.reg.flags = .{ .Z = cpu.reg.flags.Z, .N = true, .H = 1, .C = cpu.reg.flags.C, }; cpu.reg._8.set(tgt, ~val); return .{}; } pub fn push_rw___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{16}) { push16(cpu, mmu, cpu.reg._16.get(op.arg0.rw)); return .{}; } pub fn pop__rw___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(1, .{12}) { cpu.reg._16.set(op.arg0.rw, pop16(cpu, mmu)); // Always setting is faster than if check cpu.reg.flags._pad = 0; return .{}; } // -- CB prefix pub fn rlc__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRlc(cpu, cpu.reg._8.get(tgt))); return .{}; } pub fn rlc__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); mmu.set(addr, doRlc(cpu, val)); return .{}; } pub fn rrc__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRrc(cpu, cpu.reg._8.get(tgt))); return .{}; } pub fn rrc__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); mmu.set(addr, doRrc(cpu, val)); return .{}; } pub fn rl___rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRl(cpu, cpu.reg._8.get(tgt))); return .{}; } pub fn rl___RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); mmu.set(addr, doRl(cpu, val)); return .{}; } pub fn rr___rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const tgt = op.arg0.rb; cpu.reg._8.set(tgt, doRr(cpu, cpu.reg._8.get(tgt))); return .{}; } pub fn rr___RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); mmu.set(addr, doRr(cpu, val)); return .{}; } pub fn sla__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const val = cpu.reg._8.get(op.arg0.rb); cpu.reg._8.set(op.arg0.rb, flagShift(cpu, val << 1, Bit.get(val, 7))); return .{}; } pub fn sla__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); mmu.set(addr, flagShift(cpu, val << 1, Bit.get(val, 7))); return .{}; } pub fn sra__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const val = cpu.reg._8.get(op.arg0.rb); const msb = val & 0b10000000; cpu.reg._8.set(op.arg0.rb, flagShift(cpu, msb | val >> 1, Bit.get(val, 0))); return .{}; } pub fn sra__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); const msb = val & 0b10000000; mmu.set(addr, flagShift(cpu, msb | val >> 1, Bit.get(val, 0))); return .{}; } pub fn swap_rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const val = cpu.reg._8.get(op.arg0.rb); const hi = val >> 4; const lo = val & 0xF; cpu.reg._8.set(op.arg0.rb, flagShift(cpu, lo << 4 | hi, 0)); return .{}; } pub fn swap_RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); const hi = val >> 4; const lo = val & 0xF; mmu.set(addr, flagShift(cpu, lo << 4 | hi, 0)); return .{}; } pub fn srl__rb___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const val = cpu.reg._8.get(op.arg0.rb); cpu.reg._8.set(op.arg0.rb, flagShift(cpu, val >> 1, Bit.get(val, 0))); return .{}; } pub fn srl__RW___(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg0.rw); const val = mmu.get(addr); const hi = val >> 4; const lo = val & 0xF; mmu.set(addr, flagShift(cpu, val >> 1, Bit.get(val, 0))); return .{}; } pub fn bit__bt_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const val = cpu.reg._8.get(op.arg1.rb); cpu.reg.flags = .{ .Z = Bit.get(val, op.arg0.bt) == 0, .N = false, .H = 1, .C = cpu.reg.flags.C, }; return .{}; } pub fn bit__bt_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg1.rw); const val = mmu.get(addr); cpu.reg.flags = .{ .Z = Bit.get(val, op.arg0.bt) == 0, .N = false, .H = 1, .C = cpu.reg.flags.C, }; return .{}; } pub fn res__bt_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const mask = @as(u8, 1) << op.arg0.bt; const val = cpu.reg._8.get(op.arg1.rb); cpu.reg._8.set(op.arg1.rb, val & ~mask); return .{}; } pub fn res__bt_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg1.rw); const val = mmu.get(addr); const mask = @as(u8, 1) << op.arg0.bt; mmu.set(addr, val & ~mask); return .{}; } pub fn set__bt_rb(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{8}) { const mask = @as(u8, 1) << op.arg0.bt; const val = cpu.reg._8.get(op.arg1.rb); cpu.reg._8.set(op.arg1.rb, val | mask); return .{}; } pub fn set__bt_RW(cpu: *main.Cpu, mmu: *main.Mmu, op: Op) Result(2, .{16}) { const addr = cpu.reg._16.get(op.arg1.rw); const val = mmu.get(addr); const mask = @as(u8, 1) << op.arg0.bt; mmu.set(addr, val | mask); return .{}; } // -- internal fn willCarryInto(size: u5, a: i32, b: i32) u1 { if (a < 0 or b < 0) { return 0; } const mask = (@as(u32, 1) << size) - 1; return @boolToInt((@intCast(u32, a) & mask) + (@intCast(u32, b) & mask) > mask); } fn willBorrowFrom(size: u5, a: u16, b: u16) u1 { const mask = (@as(u32, 1) << size) - 1; return @boolToInt((a & mask) < (b & mask)); } fn pop8(cpu: *main.Cpu, mmu: *main.Mmu) u8 { const addr = cpu.reg._16.get(.SP); defer cpu.reg._16.set(.SP, addr +% 1); return mmu.get(addr); } fn pop16(cpu: *main.Cpu, mmu: *main.Mmu) u16 { const lb: u16 = pop8(cpu, mmu); const hb: u16 = pop8(cpu, mmu); return (hb << 8) | lb; } fn push8(cpu: *main.Cpu, mmu: *main.Mmu, val: u8) void { const new_addr = cpu.reg._16.get(.SP) -% 1; cpu.reg._16.set(.SP, new_addr); mmu.set(new_addr, val); } fn push16(cpu: *main.Cpu, mmu: *main.Mmu, val: u16) void { push8(cpu, mmu, @truncate(u8, val >> 8)); push8(cpu, mmu, @truncate(u8, val >> 0)); } pub const Bit = struct { pub fn get(data: u8, bit: u3) u1 { return @truncate(u1, data >> bit); } }; // TODO: maybe rename? Not too obvious... pub fn flagShift(cpu: *main.Cpu, val: u8, carry: u1) u8 { cpu.reg.flags = .{ .Z = val == 0, .N = false, .H = 0, .C = carry, }; return val; } pub fn doRlc(cpu: *main.Cpu, val: u8) u8 { const msb = Bit.get(val, 7); return flagShift(cpu, val << 1 | msb, msb); } pub fn doRrc(cpu: *main.Cpu, val: u8) u8 { const lsb = Bit.get(val, 0); return flagShift(cpu, val >> 1 | (@as(u8, lsb) << 7), lsb); } pub fn doRl(cpu: *main.Cpu, val: u8) u8 { const msb = Bit.get(val, 7); return flagShift(cpu, val << 1 | cpu.reg.flags.C, msb); } pub fn doRr(cpu: *main.Cpu, val: u8) u8 { const lsb = Bit.get(val, 0); return flagShift(cpu, val >> 1 | @as(u8, cpu.reg.flags.C) << 7, lsb); } fn doAddRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); cpu.reg.flags = .{ .Z = (tgt_val +% val) == 0, .N = false, .H = willCarryInto(4, tgt_val, val), .C = willCarryInto(8, tgt_val, val), }; cpu.reg._8.set(tgt, tgt_val +% val); } fn doAdcRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); const carry = cpu.reg.flags.C; cpu.reg.flags = .{ .Z = (tgt_val +% val +% carry) == 0, .N = false, .H = willCarryInto(4, tgt_val, val) | willCarryInto(4, tgt_val +% val, carry), .C = willCarryInto(8, tgt_val, val) | willCarryInto(8, tgt_val +% val, carry), }; cpu.reg._8.set(tgt, tgt_val +% val +% carry); } fn doSubRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { doCpRr(cpu, tgt, val); const tgt_val = cpu.reg._8.get(tgt); cpu.reg._8.set(tgt, tgt_val -% val); } fn doSbcRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); const carry = cpu.reg.flags.C; cpu.reg.flags = .{ .Z = (tgt_val -% val -% carry) == 0, .N = true, .H = willBorrowFrom(4, tgt_val, val) | willBorrowFrom(4, tgt_val -% val, carry), .C = willBorrowFrom(8, tgt_val, val) | willBorrowFrom(8, tgt_val -% val, carry), }; cpu.reg._8.set(tgt, tgt_val -% val -% carry); } fn doCpRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); cpu.reg.flags = .{ .Z = (tgt_val -% val) == 0, .N = true, .H = willBorrowFrom(4, tgt_val, val), .C = willBorrowFrom(8, tgt_val, val), }; } fn doAndRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); cpu.reg.flags = .{ .Z = (tgt_val & val) == 0, .N = false, .H = 1, .C = 0, }; cpu.reg._8.set(tgt, tgt_val & val); } fn doOrRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); cpu.reg._8.set(tgt, flagShift(cpu, tgt_val | val, 0)); } fn doXorRr(cpu: *main.Cpu, tgt: Reg8, val: u8) void { const tgt_val = cpu.reg._8.get(tgt); cpu.reg._8.set(tgt, flagShift(cpu, tgt_val ^ val, 0)); } fn signedAdd(a: u16, b: u8) u16 { const signed = @bitCast(i16, a) +% @bitCast(i8, b); return @bitCast(u16, signed); }
src/Cpu/impl.zig
const std = @import("../std.zig"); const mem = std.mem; const math = std.math; const debug = std.debug; const htest = @import("test.zig"); const RoundParam = struct { a: usize, b: usize, c: usize, d: usize, x: usize, y: usize, }; fn roundParam(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam { return RoundParam{ .a = a, .b = b, .c = c, .d = d, .x = x, .y = y, }; } ///////////////////// // Blake2s pub const Blake2s128 = Blake2s(128); pub const Blake2s224 = Blake2s(224); pub const Blake2s256 = Blake2s(256); pub fn Blake2s(comptime out_bits: usize) type { return struct { const Self = @This(); pub const block_length = 64; pub const digest_length = out_bits / 8; pub const key_length_min = 0; pub const key_length_max = 32; pub const key_length = 32; // recommended key length pub const Options = struct { key: ?[]const u8 = null, salt: ?[8]u8 = null, context: ?[8]u8 = null }; const iv = [8]u32{ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, }; const sigma = [10][16]u8{ [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, [_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, [_]u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, [_]u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, [_]u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, [_]u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, [_]u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, [_]u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, [_]u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, [_]u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, }; h: [8]u32, t: u64, // Streaming cache buf: [64]u8, buf_len: u8, pub fn init(options: Options) Self { comptime debug.assert(8 <= out_bits and out_bits <= 256); var d: Self = undefined; mem.copy(u32, d.h[0..], iv[0..]); const key_len = if (options.key) |key| key.len else 0; // default parameters d.h[0] ^= 0x01010000 ^ @truncate(u32, key_len << 8) ^ @intCast(u32, out_bits >> 3); d.t = 0; d.buf_len = 0; if (options.salt) |salt| { d.h[4] ^= mem.readIntLittle(u32, salt[0..4]); d.h[5] ^= mem.readIntLittle(u32, salt[4..8]); } if (options.context) |context| { d.h[6] ^= mem.readIntLittle(u32, context[0..4]); d.h[7] ^= mem.readIntLittle(u32, context[4..8]); } if (key_len > 0) { mem.set(u8, d.buf[key_len..], 0); d.update(options.key.?); d.buf_len = 64; } return d; } pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void { var d = Self.init(options); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. if (d.buf_len != 0 and d.buf_len + b.len > 64) { off += 64 - d.buf_len; mem.copy(u8, d.buf[d.buf_len..], b[0..off]); d.t += 64; d.round(d.buf[0..], false); d.buf_len = 0; } // Full middle blocks. while (off + 64 < b.len) : (off += 64) { d.t += 64; d.round(b[off..][0..64], false); } // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: *[digest_length]u8) void { mem.set(u8, d.buf[d.buf_len..], 0); d.t += d.buf_len; d.round(d.buf[0..], true); const rr = d.h[0 .. digest_length / 4]; for (rr) |s, j| { mem.writeIntSliceLittle(u32, out[4 * j ..], s); } } fn round(d: *Self, b: *const [64]u8, last: bool) void { var m: [16]u32 = undefined; var v: [16]u32 = undefined; for (m) |*r, i| { r.* = mem.readIntLittle(u32, b[4 * i ..][0..4]); } var k: usize = 0; while (k < 8) : (k += 1) { v[k] = d.h[k]; v[k + 8] = iv[k]; } v[12] ^= @truncate(u32, d.t); v[13] ^= @intCast(u32, d.t >> 32); if (last) v[14] = ~v[14]; const rounds = comptime [_]RoundParam{ roundParam(0, 4, 8, 12, 0, 1), roundParam(1, 5, 9, 13, 2, 3), roundParam(2, 6, 10, 14, 4, 5), roundParam(3, 7, 11, 15, 6, 7), roundParam(0, 5, 10, 15, 8, 9), roundParam(1, 6, 11, 12, 10, 11), roundParam(2, 7, 8, 13, 12, 13), roundParam(3, 4, 9, 14, 14, 15), }; comptime var j: usize = 0; inline while (j < 10) : (j += 1) { inline for (rounds) |r| { v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 16)); v[r.c] = v[r.c] +% v[r.d]; v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 12)); v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 8)); v[r.c] = v[r.c] +% v[r.d]; v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 7)); } } for (d.h) |*r, i| { r.* ^= v[i] ^ v[i + 8]; } } }; } test "blake2s224 single" { const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4"; htest.assertEqualHash(Blake2s224, h1, ""); const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55"; htest.assertEqualHash(Blake2s224, h2, "abc"); const h3 = "e4e5cb6c7cae41982b397bf7b7d2d9d1949823ae78435326e8db4912"; htest.assertEqualHash(Blake2s224, h3, "The quick brown fox jumps over the lazy dog"); const h4 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01"; htest.assertEqualHash(Blake2s224, h4, "a" ** 32 ++ "b" ** 32); } test "blake2s224 streaming" { var h = Blake2s224.init(.{}); var out: [28]u8 = undefined; const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55"; h = Blake2s224.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Blake2s224.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); const h3 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01"; h = Blake2s224.init(.{}); h.update("a" ** 32); h.update("b" ** 32); h.final(out[0..]); htest.assertEqual(h3, out[0..]); h = Blake2s224.init(.{}); h.update("a" ** 32 ++ "b" ** 32); h.final(out[0..]); htest.assertEqual(h3, out[0..]); const h4 = "a4d6a9d253441b80e5dfd60a04db169ffab77aec56a2855c402828c3"; h = Blake2s224.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 }); h.update("a" ** 32); h.update("b" ** 32); h.final(out[0..]); htest.assertEqual(h4, out[0..]); h = Blake2s224.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 }); h.update("a" ** 32 ++ "b" ** 32); h.final(out[0..]); htest.assertEqual(h4, out[0..]); } test "comptime blake2s224" { comptime { @setEvalBranchQuota(6000); var block = [_]u8{0} ** Blake2s224.block_length; var out: [Blake2s224.digest_length]u8 = undefined; const h1 = "86b7611563293f8c73627df7a6d6ba25ca0548c2a6481f7d116ee576"; htest.assertEqualHash(Blake2s224, h1, block[0..]); var h = Blake2s224.init(.{}); h.update(&block); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } } test "blake2s256 single" { const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9"; htest.assertEqualHash(Blake2s256, h1, ""); const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982"; htest.assertEqualHash(Blake2s256, h2, "abc"); const h3 = "606beeec743ccbeff6cbcdf5d5302aa855c256c29b88c8ed331ea1a6bf3c8812"; htest.assertEqualHash(Blake2s256, h3, "The quick brown fox jumps over the lazy dog"); const h4 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977"; htest.assertEqualHash(Blake2s256, h4, "a" ** 32 ++ "b" ** 32); } test "blake2s256 streaming" { var h = Blake2s256.init(.{}); var out: [32]u8 = undefined; const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982"; h = Blake2s256.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Blake2s256.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); const h3 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977"; h = Blake2s256.init(.{}); h.update("a" ** 32); h.update("b" ** 32); h.final(out[0..]); htest.assertEqual(h3, out[0..]); h = Blake2s256.init(.{}); h.update("a" ** 32 ++ "b" ** 32); h.final(out[0..]); htest.assertEqual(h3, out[0..]); } test "blake2s256 keyed" { var out: [32]u8 = undefined; const h1 = "10f918da4d74fab3302e48a5d67d03804b1ec95372a62a0f33b7c9fa28ba1ae6"; const key = "secret_key"; Blake2s256.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key }); htest.assertEqual(h1, out[0..]); var h = Blake2s256.init(.{ .key = key }); h.update("a" ** 64 ++ "b" ** 64); h.final(out[0..]); htest.assertEqual(h1, out[0..]); h = Blake2s256.init(.{ .key = key }); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } test "comptime blake2s256" { comptime { @setEvalBranchQuota(6000); var block = [_]u8{0} ** Blake2s256.block_length; var out: [Blake2s256.digest_length]u8 = undefined; const h1 = "ae09db7cd54f42b490ef09b6bc541af688e4959bb8c53f359a6f56e38ab454a3"; htest.assertEqualHash(Blake2s256, h1, block[0..]); var h = Blake2s256.init(.{}); h.update(&block); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } } ///////////////////// // Blake2b pub const Blake2b128 = Blake2b(128); pub const Blake2b256 = Blake2b(256); pub const Blake2b384 = Blake2b(384); pub const Blake2b512 = Blake2b(512); pub fn Blake2b(comptime out_bits: usize) type { return struct { const Self = @This(); pub const block_length = 128; pub const digest_length = out_bits / 8; pub const key_length_min = 0; pub const key_length_max = 64; pub const key_length = 32; // recommended key length pub const Options = struct { key: ?[]const u8 = null, salt: ?[16]u8 = null, context: ?[16]u8 = null }; const iv = [8]u64{ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, }; const sigma = [12][16]u8{ [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, [_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, [_]u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, [_]u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, [_]u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, [_]u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, [_]u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, [_]u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, [_]u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, [_]u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, [_]u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, }; h: [8]u64, t: u128, // Streaming cache buf: [128]u8, buf_len: u8, pub fn init(options: Options) Self { comptime debug.assert(8 <= out_bits and out_bits <= 512); var d: Self = undefined; mem.copy(u64, d.h[0..], iv[0..]); const key_len = if (options.key) |key| key.len else 0; // default parameters d.h[0] ^= 0x01010000 ^ (key_len << 8) ^ (out_bits >> 3); d.t = 0; d.buf_len = 0; if (options.salt) |salt| { d.h[4] ^= mem.readIntLittle(u64, salt[0..8]); d.h[5] ^= mem.readIntLittle(u64, salt[8..16]); } if (options.context) |context| { d.h[6] ^= mem.readIntLittle(u64, context[0..8]); d.h[7] ^= mem.readIntLittle(u64, context[8..16]); } if (key_len > 0) { mem.set(u8, d.buf[key_len..], 0); d.update(options.key.?); d.buf_len = 128; } return d; } pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void { var d = Self.init(options); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. if (d.buf_len != 0 and d.buf_len + b.len > 128) { off += 128 - d.buf_len; mem.copy(u8, d.buf[d.buf_len..], b[0..off]); d.t += 128; d.round(d.buf[0..], false); d.buf_len = 0; } // Full middle blocks. while (off + 128 < b.len) : (off += 128) { d.t += 128; d.round(b[off..][0..128], false); } // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: *[digest_length]u8) void { mem.set(u8, d.buf[d.buf_len..], 0); d.t += d.buf_len; d.round(d.buf[0..], true); const rr = d.h[0 .. digest_length / 8]; for (rr) |s, j| { mem.writeIntSliceLittle(u64, out[8 * j ..], s); } } fn round(d: *Self, b: *const [128]u8, last: bool) void { var m: [16]u64 = undefined; var v: [16]u64 = undefined; for (m) |*r, i| { r.* = mem.readIntLittle(u64, b[8 * i ..][0..8]); } var k: usize = 0; while (k < 8) : (k += 1) { v[k] = d.h[k]; v[k + 8] = iv[k]; } v[12] ^= @truncate(u64, d.t); v[13] ^= @intCast(u64, d.t >> 64); if (last) v[14] = ~v[14]; const rounds = comptime [_]RoundParam{ roundParam(0, 4, 8, 12, 0, 1), roundParam(1, 5, 9, 13, 2, 3), roundParam(2, 6, 10, 14, 4, 5), roundParam(3, 7, 11, 15, 6, 7), roundParam(0, 5, 10, 15, 8, 9), roundParam(1, 6, 11, 12, 10, 11), roundParam(2, 7, 8, 13, 12, 13), roundParam(3, 4, 9, 14, 14, 15), }; comptime var j: usize = 0; inline while (j < 12) : (j += 1) { inline for (rounds) |r| { v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 32)); v[r.c] = v[r.c] +% v[r.d]; v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 24)); v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 16)); v[r.c] = v[r.c] +% v[r.d]; v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 63)); } } for (d.h) |*r, i| { r.* ^= v[i] ^ v[i + 8]; } } }; } test "blake2b384 single" { const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100"; htest.assertEqualHash(Blake2b384, h1, ""); const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4"; htest.assertEqualHash(Blake2b384, h2, "abc"); const h3 = "b7c81b228b6bd912930e8f0b5387989691c1cee1e65aade4da3b86a3c9f678fc8018f6ed9e2906720c8d2a3aeda9c03d"; htest.assertEqualHash(Blake2b384, h3, "The quick brown fox jumps over the lazy dog"); const h4 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c"; htest.assertEqualHash(Blake2b384, h4, "a" ** 64 ++ "b" ** 64); } test "blake2b384 streaming" { var h = Blake2b384.init(.{}); var out: [48]u8 = undefined; const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4"; h = Blake2b384.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Blake2b384.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); const h3 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c"; h = Blake2b384.init(.{}); h.update("a" ** 64 ++ "b" ** 64); h.final(out[0..]); htest.assertEqual(h3, out[0..]); h = Blake2b384.init(.{}); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h3, out[0..]); h = Blake2b384.init(.{}); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h3, out[0..]); const h4 = "934c48fcb197031c71f583d92f98703510805e72142e0b46f5752d1e971bc86c355d556035613ff7a4154b4de09dac5c"; h = Blake2b384.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 }); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h4, out[0..]); h = Blake2b384.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 }); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h4, out[0..]); } test "comptime blake2b384" { comptime { @setEvalBranchQuota(7000); var block = [_]u8{0} ** Blake2b384.block_length; var out: [Blake2b384.digest_length]u8 = undefined; const h1 = "e8aa1931ea0422e4446fecdd25c16cf35c240b10cb4659dd5c776eddcaa4d922397a589404b46eb2e53d78132d05fd7d"; htest.assertEqualHash(Blake2b384, h1, block[0..]); var h = Blake2b384.init(.{}); h.update(&block); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } } test "blake2b512 single" { const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce"; htest.assertEqualHash(Blake2b512, h1, ""); const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"; htest.assertEqualHash(Blake2b512, h2, "abc"); const h3 = "a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918"; htest.assertEqualHash(Blake2b512, h3, "The quick brown fox jumps over the lazy dog"); const h4 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920"; htest.assertEqualHash(Blake2b512, h4, "a" ** 64 ++ "b" ** 64); } test "blake2b512 streaming" { var h = Blake2b512.init(.{}); var out: [64]u8 = undefined; const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"; h = Blake2b512.init(.{}); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h = Blake2b512.init(.{}); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); const h3 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920"; h = Blake2b512.init(.{}); h.update("a" ** 64 ++ "b" ** 64); h.final(out[0..]); htest.assertEqual(h3, out[0..]); h = Blake2b512.init(.{}); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h3, out[0..]); } test "blake2b512 keyed" { var out: [64]u8 = undefined; const h1 = "8a978060ccaf582f388f37454363071ac9a67e3a704585fd879fb8a419a447e389c7c6de790faa20a7a7dccf197de736bc5b40b98a930b36df5bee7555750c4d"; const key = "secret_key"; Blake2b512.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key }); htest.assertEqual(h1, out[0..]); var h = Blake2b512.init(.{ .key = key }); h.update("a" ** 64 ++ "b" ** 64); h.final(out[0..]); htest.assertEqual(h1, out[0..]); h = Blake2b512.init(.{ .key = key }); h.update("a" ** 64); h.update("b" ** 64); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } test "comptime blake2b512" { comptime { @setEvalBranchQuota(8000); var block = [_]u8{0} ** Blake2b512.block_length; var out: [Blake2b512.digest_length]u8 = undefined; const h1 = "865939e120e6805438478841afb739ae4250cf372653078a065cdcfffca4caf798e6d462b65d658fc165782640eded70963449ae1500fb0f24981d7727e22c41"; htest.assertEqualHash(Blake2b512, h1, block[0..]); var h = Blake2b512.init(.{}); h.update(&block); h.final(out[0..]); htest.assertEqual(h1, out[0..]); } }
lib/std/crypto/blake2.zig
usingnamespace @import("combn.zig"); const std = @import("std"); const mem = std.mem; const testing = std.testing; // Confirms that a direct left-recursive grammar for an empty language actually rejects // all input strings, and does not just hang indefinitely: // // ```ebnf // Expr = Expr ; // Grammar = Expr ; // ``` // // See https://cs.stackexchange.com/q/138447/134837 test "direct_left_recursion_empty_language" { nosuspend { const allocator = testing.allocator; const node = struct { name: []const u8, pub fn deinit(self: *const @This(), _allocator: *mem.Allocator) void {} }; const Payload = void; const ctx = try Context(Payload, node).init(allocator, "abcabcabc123abc", {}); defer ctx.deinit(); var parsers = [_]*Parser(Payload, node){ undefined, // placeholder for left-recursive Expr itself }; var expr = MapTo(Payload, SequenceAmbiguousValue(node), node).init(.{ .parser = (&SequenceAmbiguous(Payload, node).init(&parsers).parser).ref(), .mapTo = struct { fn mapTo(in: Result(SequenceAmbiguousValue(node)), payload: Payload, _allocator: *mem.Allocator, key: ParserPosKey, path: ParserPath) callconv(.Async) Error!?Result(node) { switch (in.result) { .err => return Result(node).initError(in.offset, in.result.err), else => { var flattened = try in.result.value.flatten(_allocator, key, path); defer flattened.deinit(); return Result(node).init(in.offset, node{ .name = "Expr" }); }, } } }.mapTo, }); parsers[0] = (&expr.parser).ref(); try expr.parser.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; try testing.expect(sub.next() == null); // stream closed // TODO(slimsag): perhaps better if it's not an error? try testing.expectEqual(@as(usize, 0), first.offset); try testing.expectEqualStrings("matches only the empty language", first.result.err); } } // Confirms that a direct left-recursive grammar for a valid languages works: // // ```ebnf // Expr = Expr?, "abc" ; // Grammar = Expr ; // ``` // test "direct_left_recursion" { const allocator = testing.allocator; const node = struct { name: std.ArrayList(u8), pub fn deinit(self: *const @This(), _allocator: *mem.Allocator) void { self.name.deinit(); } }; const Payload = void; const ctx = try Context(Payload, node).init(allocator, "abcabcabc123abc", {}); defer ctx.deinit(); var abcAsNode = MapTo(Payload, LiteralValue, node).init(.{ .parser = (&Literal(Payload).init("abc").parser).ref(), .mapTo = struct { fn mapTo(in: Result(LiteralValue), payload: Payload, _allocator: *mem.Allocator, key: ParserPosKey, path: ParserPath) callconv(.Async) Error!?Result(node) { switch (in.result) { .err => return Result(node).initError(in.offset, in.result.err), else => { var name = std.ArrayList(u8).init(_allocator); try name.appendSlice("abc"); return Result(node).init(in.offset, node{ .name = name }); }, } } }.mapTo, }); var parsers = [_]*Parser(Payload, node){ undefined, // placeholder for left-recursive Expr itself (&abcAsNode.parser).ref(), }; var expr = Reentrant(Payload, node).init( (&MapTo(Payload, SequenceAmbiguousValue(node), node).init(.{ .parser = (&SequenceAmbiguous(Payload, node).init(&parsers).parser).ref(), .mapTo = struct { fn mapTo(in: Result(SequenceAmbiguousValue(node)), payload: Payload, _allocator: *mem.Allocator, key: ParserPosKey, path: ParserPath) callconv(.Async) Error!?Result(node) { switch (in.result) { .err => return Result(node).initError(in.offset, in.result.err), else => { var name = std.ArrayList(u8).init(_allocator); var flattened = try in.result.value.flatten(_allocator, key, path); defer flattened.deinit(); var sub = flattened.subscribe(key, path, Result(node).initError(0, "matches only the empty language")); try name.appendSlice("("); var prev = false; while (sub.next()) |next| { if (prev) { try name.appendSlice(","); } prev = true; try name.appendSlice(next.result.value.name.items); } try name.appendSlice(")"); return Result(node).init(in.offset, node{ .name = name }); }, } } }.mapTo, }).parser).ref(), ); var optionalExpr = MapTo(Payload, ?node, node).init(.{ .parser = (&Optional(Payload, node).init((&expr.parser).ref()).parser).ref(), .mapTo = struct { fn mapTo(in: Result(?node), payload: Payload, _allocator: *mem.Allocator, key: ParserPosKey, path: ParserPath) callconv(.Async) Error!?Result(node) { switch (in.result) { .err => return Result(node).initError(in.offset, in.result.err), else => { if (in.result.value == null) { var name = std.ArrayList(u8).init(_allocator); try name.appendSlice("null"); return Result(node).init(in.offset, node{ .name = name }); } var name = std.ArrayList(u8).init(_allocator); try name.appendSlice(in.result.value.?.name.items); return Result(node).init(in.offset, node{ .name = name }); }, } } }.mapTo, }); parsers[0] = (&optionalExpr.parser).ref(); try expr.parser.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; try testing.expect(sub.next() == null); // stream closed try testing.expectEqual(@as(usize, 0), first.offset); try testing.expectEqualStrings("(((null,abc),abc),abc)", first.result.value.name.items); }
src/combn/test_complex.zig
const Allocator = std.mem.Allocator; const TcpConnection = @import("connection.zig").TcpConnection; const Method = @import("http").Method; const network = @import("network"); const Response = @import("response.zig").Response; const std = @import("std"); const StreamingResponse = @import("response.zig").StreamingResponse; const Uri = @import("http").Uri; pub const Client = struct { allocator: *Allocator, pub fn init(allocator: *Allocator) !Client { try network.init(); return Client { .allocator = allocator }; } pub fn deinit(self: *Client) void { network.deinit(); } pub fn connect(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Connect, url, args); } pub fn delete(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Delete, url, args); } pub fn get(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Get, url, args); } pub fn head(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Head, url, args); } pub fn options(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Options, url, args); } pub fn patch(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Patch, url, args); } pub fn post(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Post, url, args); } pub fn put(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Put, url, args); } pub fn request(self: Client, method: Method, url: []const u8, args: anytype) !Response { const uri = try Uri.parse(url, false); var connection = try self.get_connection(uri); defer connection.deinit(); return connection.request(method, uri, args); } pub fn stream(self: Client, method: Method, url: []const u8, args: anytype) !StreamingResponse(TcpConnection) { const uri = try Uri.parse(url, false); var connection = try self.get_connection(uri); return connection.stream(method, uri, args); } pub fn trace(self: Client, url: []const u8, args: anytype) !Response { return self.request(.Trace, url, args); } fn get_connection(self: Client, uri: Uri) !TcpConnection { return try TcpConnection.connect(self.allocator, uri); } };
src/client.zig
pub const platform = @import("root"); pub const io_impl = @import("io/io.zig"); pub const util = @import("lib/util.zig"); pub const dtb = @import("lib/dtb.zig"); pub const pmm = @import("lib/pmm.zig"); pub const acpi = @import("platform/acpi.zig"); pub const paging = @import("platform/paging.zig"); pub const pci = @import("platform/pci.zig"); pub const psci = @import("platform/psci.zig"); pub const fw_cfg = @import("platform/drivers/fw_cfg.zig"); pub const ramfb = @import("platform/drivers/ramfb.zig"); pub const puts = io_impl.puts; pub const log_hex = io_impl.log_hex; pub const print_hex = io_impl.print_hex; pub const print_str = io_impl.print_str; pub const log = io_impl.log; pub const putchar = io_impl.putchar; pub const near = util.near; pub const vital = util.vital; pub const io = platform.io; pub const debug = @import("builtin").mode == .Debug; pub const safety = std.debug.runtime_safety; pub const upper_half_phys_base = 0xFFFF800000000000; const std = @import("std"); pub fn panic(reason: []const u8, stacktrace: ?*std.builtin.StackTrace) noreturn { puts("PANIC!"); if(reason.len != 0) { puts(" Reason: "); print_str(reason); } if(sabaton.debug) { if(stacktrace) |t| { log("\nTrace:\n", .{}); for(t.instruction_addresses) |addr| { log(" 0x{X}\n", .{addr}); } } else { log("\nNo trace.\n", .{}); } } asm volatile( \\ // Disable interrupts \\ MSR DAIFSET, 0xF \\ \\ // Hang \\1:WFI \\ B 1b ); unreachable; } const Elf = @import("lib/elf.zig").Elf; const sabaton = @This(); pub const Stivale2tag = packed struct { ident: u64, next: ?*@This(), }; const InfoStruct = struct { brand: [64]u8 = pad_str("Sabaton - Forged in Valhalla by the hammer of Thor", 64), version: [64]u8 = pad_str(@import("build_options").board_name ++ " - " ++ @tagName(std.builtin.mode), 64), tags: ?*Stivale2tag = null, }; pub const Stivale2hdr = struct { entry_point: u64, stack: u64, flags: u64, tags: ?*Stivale2tag, }; fn pad_str(str: []const u8, comptime len: usize) [len]u8 { var ret = [1]u8{0} ** len; // Check that we fit the string and a null terminator if(str.len >= len) unreachable; @memcpy(@ptrCast([*]u8, &ret[0]), str.ptr, str.len); return ret; } var stivale2_info: InfoStruct = .{ }; pub fn add_tag(tag: *Stivale2tag) void { tag.next = stivale2_info.tags; stivale2_info.tags = tag; } var paging_root: paging.Root = undefined; comptime { if(comptime sabaton.safety) { asm( \\.section .text \\.balign 0x800 \\evt_base: \\.balign 0x80; B fatal_error // curr_el_sp0_sync \\.balign 0x80; B fatal_error // curr_el_sp0_irq \\.balign 0x80; B fatal_error // curr_el_sp0_fiq \\.balign 0x80; B fatal_error // curr_el_sp0_serror \\.balign 0x80; B fatal_error // curr_el_spx_sync \\.balign 0x80; B fatal_error // curr_el_spx_irq \\.balign 0x80; B fatal_error // curr_el_spx_fiq \\.balign 0x80; B fatal_error // curr_el_spx_serror \\.balign 0x80; B fatal_error // lower_el_aarch64_sync \\.balign 0x80; B fatal_error // lower_el_aarch64_irq \\.balign 0x80; B fatal_error // lower_el_aarch64_fiq \\.balign 0x80; B fatal_error // lower_el_aarch64_serror \\.balign 0x80; B fatal_error // lower_el_aarch32_sync \\.balign 0x80; B fatal_error // lower_el_aarch32_irq \\.balign 0x80; B fatal_error // lower_el_aarch32_fiq \\.balign 0x80; B fatal_error // lower_el_aarch32_serror ); } } export fn fatal_error() noreturn { if(comptime sabaton.safety) { const error_count = asm volatile( \\ MRS %[res], TPIDR_EL1 \\ ADD %[res], %[res], 1 \\ MSR TPIDR_EL1, %[res] : [res] "=r" (-> u64) ); if(error_count != 1) { while(true) { } } const elr = asm( \\MRS %[elr], ELR_EL1 : [elr] "=r" (-> u64) ); sabaton.log_hex("ELR: ", elr); const esr = asm( \\MRS %[elr], ESR_EL1 : [elr] "=r" (-> u64) ); sabaton.log_hex("ESR: ", esr); const ec = @truncate(u6, esr >> 26); switch(ec) { 0b000000 => sabaton.puts("Unknown reason\n"), 0b100001 => sabaton.puts("Instruction fault\n"), 0b001110 => sabaton.puts("Illegal execution state\n"), 0b100101 => { sabaton.puts("Data abort\n"); const far = asm( \\MRS %[elr], FAR_EL1 : [elr] "=r" (-> u64) ); sabaton.log_hex("FAR: ", far); }, else => sabaton.log_hex("Unknown ec: ", ec), } @panic("Fatal error"); } else { asm volatile("ERET"); unreachable; } } pub fn install_evt() void { asm volatile( \\ MSR VBAR_EL1, %[evt] \\ MSR TPIDR_EL1, XZR : : [evt] "r" (sabaton.near("evt_base").addr(u8)) ); sabaton.puts("Installed EVT\n"); } pub fn main() noreturn { if(comptime sabaton.safety) { install_evt(); } const dram = platform.get_dram(); var kernel_elf = Elf { .data = platform.get_kernel(), }; kernel_elf.init(); var kernel_header: Stivale2hdr = undefined; _ = vital( kernel_elf.load_section(".stivale2hdr", util.to_byte_slice(&kernel_header)), "loading .stivale2hdr", true, ); platform.add_platform_tags(&kernel_header); // Allocate space for backing pages of the kernel pmm.switch_state(.KernelPages); sabaton.puts("Allocating kernel memory\n"); const kernel_memory_pool = pmm.alloc_aligned(kernel_elf.paged_bytes(), .KernelPage); sabaton.log_hex("Bytes allocated for kernel: ", kernel_memory_pool.len); // TODO: Allocate and put modules here pmm.switch_state(.PageTables); paging_root = paging.init_paging(); platform.map_platform(&paging_root); { const dram_base = @ptrToInt(dram.ptr); sabaton.paging.map(dram_base, dram_base, dram.len, .rwx, .memory, &paging_root); sabaton.paging.map(dram_base + upper_half_phys_base, dram_base, dram.len, .rwx, .memory, &paging_root); } paging.apply_paging(&paging_root); // Check the flags in the stivale2 header sabaton.puts("Loading kernel into memory\n"); kernel_elf.load(kernel_memory_pool); if(sabaton.debug) sabaton.puts("Sealing PMM\n"); pmm.switch_state(.Sealed); // Maybe do these conditionally one day once we parse stivale2 kernel tags? if(@hasDecl(platform, "display")) { sabaton.puts("Starting display\n"); platform.display.init(); } if(@hasDecl(platform, "smp")) { sabaton.puts("Starting SMP\n"); platform.smp.init(); } if(@hasDecl(platform, "acpi")) { platform.acpi.init(); } pmm.write_dram_size(@ptrToInt(dram.ptr) + dram.len); add_tag(&near("memmap_tag").addr(Stivale2tag)[0]); sabaton.puts("Entering kernel...\n"); asm volatile( \\ DMB SY \\ CBZ %[stack], 1f \\ MOV SP, %[stack] \\1:BR %[entry] : : [entry] "r" (kernel_elf.entry()) , [stack] "r" (kernel_header.stack) , [info] "{X0}" (&stivale2_info) ); unreachable; } pub fn stivale2_smp_ready(context: u64) noreturn { paging.apply_paging(&paging_root); const cpu_tag = @intToPtr([*]u64, context); var goto: u64 = undefined; while(true) { goto = @atomicLoad(u64, &cpu_tag[2], .Acquire); if(goto != 0) break; asm volatile( \\YIELD ); } asm volatile( \\ MOV SP, %[stack] \\ MOV LR, #~0 \\ BR %[goto] : : [stack] "r" (cpu_tag[3]) , [arg] "{X0}" (cpu_tag) , [goto] "r" (goto) ); unreachable; } pub const fb_width = 1024; pub const fb_height = 768; pub const fb_bpp = 4; pub const fb_pitch = fb_width * fb_bpp; pub const fb_bytes = fb_pitch * fb_height; var fb: packed struct { tag: Stivale2tag = .{ .ident = 0x506461d2950408fa, .next = null, }, addr: u64 = undefined, width: u16 = fb_width, height: u16 = fb_height, pitch: u16 = fb_pitch, bpp: u16 = fb_bpp * 8, mmodel: u8 = 1, red_mask_size: u8 = 8, red_mask_shift: u8 = 0, green_mask_size: u8 = 8, green_mask_shift: u8 = 8, blue_mask_size: u8 = 8, blue_mask_shift: u8 = 16, } = .{}; pub fn add_framebuffer(addr: u64) void { add_tag(&fb.tag); fb.addr = addr; } var rsdp: packed struct { tag: Stivale2tag = .{ .ident = 0x9e1786930a375e78, .next = null, }, rsdp: u64 = undefined, } = .{}; pub fn add_rsdp(addr: u64) void { add_tag(&rsdp.tag); rsdp.rsdp = addr; }
src/sabaton.zig
const assert = @import("std").debug.assert; const testing = @import("std").testing; const Image = @import("zigimg").Image; const PixelFormat = @import("zigimg").PixelFormat; usingnamespace @import("helpers.zig"); test "Create Image Bpp1" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Bpp1); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Bpp1); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Bpp1); testing.expect(pixels.Bpp1.palette.len == 2); testing.expect(pixels.Bpp1.indices.len == 24 * 32); } } test "Create Image Bpp2" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Bpp2); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Bpp2); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Bpp2); testing.expect(pixels.Bpp2.palette.len == 4); testing.expect(pixels.Bpp2.indices.len == 24 * 32); } } test "Create Image Bpp4" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Bpp4); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Bpp4); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Bpp4); testing.expect(pixels.Bpp4.palette.len == 16); testing.expect(pixels.Bpp4.indices.len == 24 * 32); } } test "Create Image Bpp8" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Bpp8); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Bpp8); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Bpp8); testing.expect(pixels.Bpp8.palette.len == 256); testing.expect(pixels.Bpp8.indices.len == 24 * 32); } } test "Create Image Bpp16" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Bpp16); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Bpp16); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Bpp16); testing.expect(pixels.Bpp16.palette.len == 65536); testing.expect(pixels.Bpp16.indices.len == 24 * 32); } } test "Create Image Rgb24" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Rgb24); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Rgb24); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Rgb24); testing.expect(pixels.Rgb24.len == 24 * 32); } } test "Create Image Rgba32" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Rgba32); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Rgba32); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Rgba32); testing.expect(pixels.Rgba32.len == 24 * 32); } } test "Create Image Rgb565" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Rgb565); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Rgb565); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Rgb565); testing.expect(pixels.Rgb565.len == 24 * 32); } } test "Create Image Rgb555" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Rgb555); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Rgb555); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Rgb555); testing.expect(pixels.Rgb555.len == 24 * 32); } } test "Create Image Argb32" { const image = try Image.create(testing.allocator, 24, 32, PixelFormat.Argb32); defer image.deinit(); expectEq(image.width, 24); expectEq(image.height, 32); expectEq(image.pixel_format, PixelFormat.Argb32); testing.expect(image.pixels != null); if (image.pixels) |pixels| { testing.expect(pixels == .Argb32); testing.expect(pixels.Argb32.len == 24 * 32); } } const MemoryRGBABitmap = @embedFile("fixtures/bmp/windows_rgba_v5.bmp"); test "Should detect BMP properly" { const imageTests = &[_][]const u8{ "tests/fixtures/bmp/simple_v4.bmp", "tests/fixtures/bmp/windows_rgba_v5.bmp", }; for (imageTests) |image_path| { const image = try Image.fromFilePath(testing.allocator, image_path); defer image.deinit(); testing.expect(image.image_format == .Bmp); } } test "Should detect PCX properly" { const imageTests = &[_][]const u8{ "tests/fixtures/pcx/test-bpp1.pcx", "tests/fixtures/pcx/test-bpp4.pcx", "tests/fixtures/pcx/test-bpp8.pcx", "tests/fixtures/pcx/test-bpp24.pcx", }; for (imageTests) |image_path| { const image = try Image.fromFilePath(testing.allocator, image_path); defer image.deinit(); testing.expect(image.image_format == .Pcx); } } test "Should error on invalid path" { var invalidPath = Image.fromFilePath(testing.allocator, "notapathdummy"); expectError(invalidPath, error.FileNotFound); } test "Should error on invalid file" { var invalidFile = Image.fromFilePath(testing.allocator, "tests/helpers.zig"); expectError(invalidFile, error.ImageFormatInvalid); } test "Should read a 24-bit bitmap" { var image = try Image.fromFilePath(testing.allocator, "tests/fixtures/bmp/simple_v4.bmp"); defer image.deinit(); expectEq(image.width, 8); expectEq(image.height, 1); if (image.pixels) |pixels| { testing.expect(pixels == .Rgb24); const red = pixels.Rgb24[0]; expectEq(red.R, 0xFF); expectEq(red.G, 0x00); expectEq(red.B, 0x00); const green = pixels.Rgb24[1]; expectEq(green.R, 0x00); expectEq(green.G, 0xFF); expectEq(green.B, 0x00); const blue = pixels.Rgb24[2]; expectEq(blue.R, 0x00); expectEq(blue.G, 0x00); expectEq(blue.B, 0xFF); const cyan = pixels.Rgb24[3]; expectEq(cyan.R, 0x00); expectEq(cyan.G, 0xFF); expectEq(cyan.B, 0xFF); const magenta = pixels.Rgb24[4]; expectEq(magenta.R, 0xFF); expectEq(magenta.G, 0x00); expectEq(magenta.B, 0xFF); const yellow = pixels.Rgb24[5]; expectEq(yellow.R, 0xFF); expectEq(yellow.G, 0xFF); expectEq(yellow.B, 0x00); const black = pixels.Rgb24[6]; expectEq(black.R, 0x00); expectEq(black.G, 0x00); expectEq(black.B, 0x00); const white = pixels.Rgb24[7]; expectEq(white.R, 0xFF); expectEq(white.G, 0xFF); expectEq(white.B, 0xFF); } }
tests/image_test.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const str = @embedFile("../input.txt"); var values = try parseInput(allocator, str); defer allocator.free(values); const stdout = std.io.getStdOut().writer(); const part1 = depthIncrease(&values); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = slidingWindow(&values); try stdout.print("Part 2: {d}\n", .{part2}); } fn parseInput(allocator: std.mem.Allocator, str: []const u8) ![]const u64 { var nums = std.ArrayList(u64).init(allocator); defer nums.deinit(); var iter = std.mem.split(u8, str, "\n"); while (iter.next()) |str_value| { // std.log.debug("line: {s}", .{str_value}); if (str_value.len != 0) { const value = std.fmt.parseInt(u64, str_value, 10) catch |err| { std.log.debug("error: {}", .{err}); continue; }; try nums.append(value); } } return nums.toOwnedSlice(); } fn depthIncrease(depths: *[]const u64) !i64 { var count: i64 = 0; var last = depths.*[0]; for (depths.*) |curr| { if (curr > last) { count = count + 1; } last = curr; } return count; } fn slidingWindow(depths: *[]const u64) !i64 { var count: i64 = 0; var last_window = depths.*[0] + depths.*[1] + depths.*[2]; for (depths.*[3..]) |curr_value, idx| { if (idx == (depths.len - 3)) { break; } var drop_value = depths.*[(idx + 3) - 3]; var curr_window = last_window + curr_value - drop_value; if (curr_window > last_window) { count = count + 1; } last_window = curr_window; } return count; } test "part1/part2 test" { const test_input = @embedFile("../test.txt"); const test_values = [_]u64{ 199, 200, 208, 210, 200, 207, 240, 269, 260, 263, }; var values = try parseInput(test_allocator, test_input); defer test_allocator.free(values); try expect(std.mem.eql(u64, &test_values, values)); const result = try depthIncrease(&values); try std.testing.expect(7 == result); const result2 = try slidingWindow(&values); try std.testing.expect(5 == result2); }
day01/src/main.zig
// Todo: the order of the bits in the deflate format is different. const std = @import("std"); const expect = std.testing.expect; /// Appendable list of individual bits. pub const BitList = struct { bytes: std.ArrayList(u8) = undefined, bit_index: u32 = 0, pub fn init(a: *std.mem.Allocator) !BitList { return BitList {.bytes = std.ArrayList(u8).init(a)}; } pub fn deinit(self: *BitList) void { self.bytes.deinit(); } /// Shift bits into list, left-to-right. Extend if needed. pub fn append_bit(self: *BitList, bit: u1) !void { if (self.bytes.items.len*8 < self.bit_index+1) { try self.bytes.append(0); } if (bit == 1) { self.bytes.items[self.bit_index/8] |= @as(u8, 128) >> @intCast(u3, self.bit_index%8); } self.bit_index += 1; } /// Append from a slice of bytes up to `max_bit_count` bits. pub fn append_bytes(self: *BitList, bytes: []u8, max_bit_count: u32) !void { std.debug.assert(max_bit_count<=bytes.len*8); for (bytes) |byte, byte_index| { var i: u8 = 0; while (i < 8) : (i += 1) { if ((byte_index)*8+i < max_bit_count) { try self.append_bit(@intCast(u1, (byte >> @intCast(u3, 7 - i)) & 1)); } else break; } } } /// Can be safely @intCast to u3. pub fn get_trailing_bit_count(self: *BitList) u32 { return 8-(self.bit_index%8); } }; test "BitList initializes" { const allocator = std.heap.page_allocator; var bit_list = try BitList.init(allocator); defer bit_list.deinit(); try expect(bit_list.bytes.items.len == 0); } test "BitList appends bits" { const allocator = std.heap.page_allocator; var bit_list = try BitList.init(allocator); defer bit_list.deinit(); try bit_list.append_bit(1); try expect(bit_list.bytes.items.len == 1); try bit_list.append_bit(1); try bit_list.append_bit(1); try bit_list.append_bit(1); try bit_list.append_bit(0); try bit_list.append_bit(0); try bit_list.append_bit(0); try bit_list.append_bit(1); try expect(bit_list.bytes.items.len == 1); try bit_list.append_bit(1); try expect(bit_list.bytes.items.len == 2); try expect(bit_list.bytes.items[0] == 0b1111_0001); try expect(bit_list.bytes.items[1] == 0b1000_0000); } test "BitList appends byte slices with bit counts" { const allocator = std.heap.page_allocator; var bit_list = try BitList.init(allocator); defer bit_list.deinit(); var array = [_]u8{0b1110_1110, 0b1101_1010, 0b1011_1100, 0b1001_0000}; try bit_list.append_bytes(array[0..3], 19); try expect(bit_list.bytes.items.len == 3); try expect(bit_list.get_trailing_bit_count() == 5); try expect(bit_list.bytes.items[0] == 0b1110_1110); try expect(bit_list.bytes.items[1] == 0b1101_1010); try expect(bit_list.bytes.items[2] == 0b1010_0000); try bit_list.append_bytes(array[0..1], 6); try expect(bit_list.bytes.items.len == 4); try expect(bit_list.get_trailing_bit_count() == 7); try expect(bit_list.bytes.items[2] == 0b1011_1101); try expect(bit_list.bytes.items[3] == 0b1000_0000); }
src/bit_list.zig
const wlr = @import("../wlroots.zig"); const wayland = @import("wayland"); const wl = wayland.server.wl; const xdg = wayland.server.xdg; pub const XdgShell = extern struct { global: *wl.Global, clients: wl.list.Head(XdgClient, "link"), popup_grabs: wl.list.Head(XdgPopupGrab, "link"), ping_timeout: u32, server_destroy: wl.Listener(*wl.Server), events: extern struct { new_surface: wl.Signal(*wlr.XdgSurface), destroy: wl.Signal(*wlr.XdgShell), }, data: usize, extern fn wlr_xdg_shell_create(server: *wl.Server) ?*wlr.XdgShell; pub const create = wlr_xdg_shell_create; }; pub const XdgClient = extern struct { shell: *wlr.XdgShell, resource: *xdg.WmBase, client: *wl.Client, surfaces: wl.list.Head(XdgSurface, "link"), /// XdgShell.clients link: wl.list.Link, ping_serial: u32, ping_timer: *wl.EventSource, }; pub const XdgPositioner = extern struct { anchor_rect: wlr.Box, anchor: xdg.Positioner.Anchor, gravity: xdg.Positioner.Gravity, constraint_adjustment: xdg.Positioner.ConstraintAdjustment, size: extern struct { width: i32, height: i32, }, offset: extern struct { x: i32, y: i32, }, extern fn wlr_xdg_positioner_get_geometry(positioner: *wlr.XdgPositioner) wlr.Box; pub const getGeometry = wlr_xdg_positioner_get_geometry; extern fn wlr_positioner_invert_x(positioner: *wlr.XdgPositioner) void; pub const invertX = wlr_positioner_invert_x; extern fn wlr_positioner_invert_y(positioner: *wlr.XdgPositioner) void; pub const invertY = wlr_positioner_invert_y; }; pub const XdgPopupGrab = extern struct { client: *wl.Client, pointer_grab: wlr.Seat.PointerGrab, keyboard_grab: wlr.Seat.KeyboardGrab, touch_grab: wlr.Seat.TouchGrab, seat: *wlr.Seat, popups: wl.list.Head(XdgPopup, "grab_link"), /// XdgShell.popup_grabs link: wl.list.Link, seat_destroy: wl.Listener(*wlr.Seat), }; pub const XdgPopup = extern struct { base: *wlr.XdgSurface, link: wl.list.Link, resource: *xdg.Popup, committed: bool, parent: ?*wlr.Surface, seat: ?*wlr.Seat, geometry: wlr.Box, positioner: wlr.XdgPositioner, /// Grab.popups grab_link: wl.list.Link, extern fn wlr_xdg_popup_destroy(surface: *wlr.Surface) void; pub inline fn destroy(popup: *wlr.XdgPopup) void { wlr_xdg_popup_destroy(popup.base); } extern fn wlr_xdg_popup_get_anchor_point(popup: *wlr.Popup, toplevel_sx: *c_int, toplevel_sy: *c_int) void; pub const getAnchorPoint = wlr_xdg_popup_get_anchor_point; extern fn wlr_xdg_popup_get_toplevel_coords(popup: *wlr.Popup, popup_sx: c_int, popup_sy: c_int, toplevel_sx: *c_int, toplevel_sy: *c_int) void; pub const getToplevelCoords = wlr_xdg_popup_get_toplevel_coords; extern fn wlr_xdg_popup_unconstrain_from_box(popup: *wlr.Popup, toplevel_sx_box: *wlr.Box) void; pub const unconstrainFromBox = wlr_xdg_popup_unconstrain_from_box; }; pub const XdgToplevel = extern struct { pub const State = extern struct { maximized: bool, fullscreen: bool, resizing: bool, activated: bool, tiled: wlr.Edges, width: u32, height: u32, max_width: u32, max_height: u32, min_width: u32, min_height: u32, fullscreen_output: ?*wlr.Output, fullscreen_output_destroy: wl.Listener(*wlr.Output), }; pub const event = struct { pub const SetFullscreen = extern struct { surface: *wlr.XdgSurface, fullscreen: bool, output: ?*wlr.Output, }; pub const Move = extern struct { surface: *wlr.XdgSurface, seat: *wlr.Seat.Client, serial: u32, }; pub const Resize = extern struct { surface: *wlr.XdgSurface, seat: *wlr.Seat.Client, serial: u32, edges: wlr.Edges, }; pub const ShowWindowMenu = extern struct { surface: *wlr.XdgSurface, seat: *wlr.Seat.Client, serial: u32, x: u32, y: u32, }; }; resource: *xdg.Toplevel, base: *wlr.XdgSurface, added: bool, parent: ?*wlr.XdgSurface, parent_unmap: wl.Listener(*XdgSurface), client_pending: State, server_pending: State, last_acked: State, current: State, title: ?[*:0]u8, app_id: ?[*:0]u8, events: extern struct { request_maximize: wl.Signal(*wlr.XdgSurface), request_fullscreen: wl.Signal(*event.SetFullscreen), request_minimize: wl.Signal(*wlr.XdgSurface), request_move: wl.Signal(*event.Move), request_resize: wl.Signal(*event.Resize), request_show_window_menu: wl.Signal(*event.ShowWindowMenu), set_parent: wl.Signal(*wlr.XdgSurface), set_title: wl.Signal(*wlr.XdgSurface), set_app_id: wl.Signal(*wlr.XdgSurface), }, extern fn wlr_xdg_toplevel_set_size(surface: *wlr.XdgSurface, width: u32, height: u32) u32; pub fn setSize(toplevel: *wlr.XdgToplevel, width: u32, height: u32) u32 { return wlr_xdg_toplevel_set_size(toplevel.base, width, height); } extern fn wlr_xdg_toplevel_set_activated(surface: *wlr.XdgSurface, activated: bool) u32; pub fn setActivated(toplevel: *wlr.XdgToplevel, activated: bool) u32 { return wlr_xdg_toplevel_set_activated(toplevel.base, activated); } extern fn wlr_xdg_toplevel_set_maximized(surface: *wlr.XdgSurface, maximized: bool) u32; pub fn setMaximized(toplevel: *wlr.XdgToplevel, maximized: bool) u32 { return wlr_xdg_toplevel_set_maximized(toplevel.base, maximized); } extern fn wlr_xdg_toplevel_set_fullscreen(surface: *wlr.XdgSurface, fullscreen: bool) u32; pub fn setFullscreen(toplevel: *wlr.XdgToplevel, fullscreen: bool) u32 { return wlr_xdg_toplevel_set_fullscreen(toplevel.base, fullscreen); } extern fn wlr_xdg_toplevel_set_resizing(surface: *wlr.XdgSurface, resizing: bool) u32; pub fn setResizing(toplevel: *wlr.XdgToplevel, resizing: bool) u32 { return wlr_xdg_toplevel_set_resizing(toplevel.base, resizing); } extern fn wlr_xdg_toplevel_set_tiled(surface: *wlr.XdgSurface, tiled_edges: u32) u32; pub fn setTiled(toplevel: *wlr.XdgToplevel, tiled_edges: wlr.Edges) u32 { return wlr_xdg_toplevel_set_tiled(toplevel.base, @bitCast(u32, tiled_edges)); } extern fn wlr_xdg_toplevel_send_close(surface: *wlr.XdgSurface) void; pub fn sendClose(toplevel: *wlr.XdgToplevel) void { wlr_xdg_toplevel_send_close(toplevel.base); } }; pub const XdgSurface = extern struct { pub const Role = extern enum { none, toplevel, popup, }; pub const Configure = extern struct { surface: *wlr.XdgSurface, /// XdgSurface.configure_list link: wl.list.Link, serial: u32, toplevel_state: *wlr.XdgToplevel.State, }; client: *wlr.XdgClient, resource: *xdg.Surface, surface: *wlr.Surface, /// XdgClient.surfaces link: wl.list.Link, role: Role, role_data: extern union { toplevel: *wlr.XdgToplevel, popup: *wlr.XdgPopup, }, popups: wl.list.Head(XdgPopup, "link"), added: bool, configured: bool, mapped: bool, configure_serial: u32, configure_idle: ?*wl.EventSource, configure_next_serial: u32, configure_list: wl.list.Head(XdgSurface.Configure, "link"), has_next_geometry: bool, next_geometry: wlr.Box, geometry: wlr.Box, surface_destroy: wl.Listener(*wlr.Surface), surface_commit: wl.Listener(*wlr.Surface), events: extern struct { destroy: wl.Signal(*wlr.XdgSurface), ping_timeout: wl.Signal(*wlr.XdgSurface), new_popup: wl.Signal(*wlr.XdgPopup), map: wl.Signal(*wlr.XdgSurface), unmap: wl.Signal(*wlr.XdgSurface), configure: wl.Signal(*wlr.XdgSurface.Configure), ack_configure: wl.Signal(*wlr.XdgSurface.Configure), }, data: usize, extern fn wlr_xdg_surface_from_resource(resource: *xdg.Surface) ?*wlr.XdgSurface; pub const fromResource = wlr_xdg_surface_from_resource; extern fn wlr_xdg_surface_from_popup_resource(resource: *xdg.Popup) ?*wlr.XdgSurface; pub const fromPopupResource = wlr_xdg_surface_from_popup_resource; extern fn wlr_xdg_surface_from_toplevel_resource(resource: xdg.Toplevel) ?*wlr.XdgSurface; pub const fromToplevelResource = wlr_xdg_surface_from_toplevel_resource; extern fn wlr_xdg_surface_ping(surface: *wlr.XdgSurface) void; pub const ping = wlr_xdg_surface_ping; extern fn wlr_xdg_surface_surface_at(surface: *wlr.XdgSurface, sx: f64, sy: f64, sub_x: *f64, sub_y: *f64) ?*wlr.Surface; pub const surfaceAt = wlr_xdg_surface_surface_at; extern fn wlr_xdg_surface_from_wlr_surface(surface: *wlr.Surface) *wlr.XdgSurface; pub const fromWlrSurface = wlr_xdg_surface_from_wlr_surface; extern fn wlr_xdg_surface_get_geometry(surface: *wlr.XdgSurface, box: *wlr.Box) void; pub const getGeometry = wlr_xdg_surface_get_geometry; extern fn wlr_xdg_surface_for_each_surface( surface: *wlr.XdgSurface, iterator: fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, user_data: ?*c_void, ) void; pub fn forEachSurface( surface: *wlr.XdgSurface, comptime T: type, iterator: fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: T) callconv(.C) void, data: T, ) void { wlr_xdg_surface_for_each_surface( surface, @ptrCast(fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, iterator), data, ); } extern fn wlr_xdg_surface_schedule_configure(surface: *wlr.XdgSurface) u32; pub const scheduleConfigure = wlr_xdg_surface_schedule_configure; extern fn wlr_xdg_surface_for_each_popup( surface: *wlr.XdgSurface, iterator: fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, user_data: ?*c_void, ) void; pub fn forEachPopup( surface: *wlr.XdgSurface, comptime T: type, iterator: fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: T) callconv(.C) void, data: T, ) void { wlr_xdg_surface_for_each_popup( surface, @ptrCast(fn (surface: *wlr.Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, iterator), data, ); } };
src/types/xdg_shell.zig
const std = @import( "std" ); const nan = std.math.nan; const isNan = std.math.isNan; usingnamespace @import( "util.zig" ); pub const Axis = struct { tieFrac: f64, tieCoord: f64, scale: f64, /// Size may be Nan if this axis isn't visible yet! viewport_PX: Interval, /// If size is Nan, this will be used instead. defaultSpan: f64, /// If this axis will be managed by an AxisUpdatingHandler, the /// absolute value of initialScale doesn't matter. What matters /// is the ratio of initialScale to the initialScales of other /// axes managed by the same AxisUpdatingHandler. pub fn initBounds( start: f64, end: f64, initialScale: f64 ) Axis { const tieFrac = 0.5; return Axis { .tieFrac = tieFrac, .tieCoord = start + tieFrac*( end - start ), .scale = initialScale, .viewport_PX = Interval.init( 0, nan( f64 ) ), .defaultSpan = end - start, }; } pub fn span( self: *const Axis ) f64 { return self.spanForScale( self.scale ); } fn spanForScale( self: *const Axis, scale: f64 ) f64 { const size_PX = self.viewport_PX.span; if ( isNan( size_PX ) ) { return self.defaultSpan; } else { return ( size_PX / scale ); } } pub fn bounds( self: *const Axis ) Interval { const span_ = self.span( ); const start = self.tieCoord - self.tieFrac*span_; return Interval.init( start, span_ ); } pub fn set( self: *Axis, frac: f64, coord: f64, scale: f64 ) void { // TODO: Apply constraints const span_ = self.spanForScale( scale ); self.tieCoord = coord + ( self.tieFrac - frac )*span_; self.scale = scale; } }; pub fn axisBounds( comptime N: usize, axes: [N]*const Axis ) [N]Interval { var bounds = @as( [N]Interval, undefined ); for ( axes ) |axis, n| { bounds[n] = axis.bounds( ); } return bounds; } pub fn AxisDraggable( comptime N: usize ) type { return struct { const Self = @This(); axes: [N]*Axis, screenCoordIndices: [N]u1, grabCoords: [N]f64, dragger: Dragger = .{ .canHandlePressFn = canHandlePress, .handlePressFn = handlePress, .handleDragFn = handleDrag, .handleReleaseFn = handleRelease, }, pub fn init( axes: [N]*Axis, screenCoordIndices: [N]u1 ) Self { return Self { .axes = axes, .screenCoordIndices = screenCoordIndices, .grabCoords = undefined, }; } fn canHandlePress( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) bool { const self = @fieldParentPtr( Self, "dragger", dragger ); for ( self.axes ) |axis, n| { const mouseFrac = axis.viewport_PX.valueToFrac( mouse_PX[ self.screenCoordIndices[n] ] ); if ( mouseFrac < 0.0 or mouseFrac > 1.0 ) { return false; } } return true; } fn handlePress( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) void { const self = @fieldParentPtr( Self, "dragger", dragger ); for ( self.axes ) |axis, n| { const mouseFrac = axis.viewport_PX.valueToFrac( mouse_PX[ self.screenCoordIndices[n] ] ); self.grabCoords[n] = axis.bounds( ).fracToValue( mouseFrac ); } } fn handleDrag( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { const self = @fieldParentPtr( Self, "dragger", dragger ); for ( self.axes ) |axis, n| { const mouseFrac = axis.viewport_PX.valueToFrac( mouse_PX[ self.screenCoordIndices[n] ] ); axis.set( mouseFrac, self.grabCoords[n], axis.scale ); } } fn handleRelease( dragger: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { const self = @fieldParentPtr( Self, "dragger", dragger ); for ( self.axes ) |axis, n| { const mouseFrac = axis.viewport_PX.valueToFrac( mouse_PX[ self.screenCoordIndices[n] ] ); axis.set( mouseFrac, self.grabCoords[n], axis.scale ); } } }; } pub const DraggerContext = struct { lpxToPx: f64, }; pub const Dragger = struct { canHandlePressFn: fn ( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) bool, handlePressFn: fn ( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) void, handleDragFn: fn ( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void, handleReleaseFn: fn ( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void, pub fn canHandlePress( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) bool { return self.canHandlePressFn( self, context, mouse_PX, clickCount ); } pub fn handlePress( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64, clickCount: u32 ) void { self.handlePressFn( self, context, mouse_PX, clickCount ); } pub fn handleDrag( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { self.handleDragFn( self, context, mouse_PX ); } pub fn handleRelease( self: *Dragger, context: DraggerContext, mouse_PX: [2]f64 ) void { self.handleReleaseFn( self, context, mouse_PX ); } }; pub const PainterContext = struct { viewport_PX: [2]Interval, lpxToPx: f64, }; pub const Painter = struct { name: []const u8, glResourcesAreSet: bool = false, /// Called while the GL context is current, and before the first paint. glInitFn: fn ( self: *Painter, pc: *const PainterContext ) anyerror!void, // Called while the GL context is current. glPaintFn: fn ( self: *Painter, pc: *const PainterContext ) anyerror!void, // Called while the GL context is current. glDeinitFn: fn ( self: *Painter ) void, pub fn glPaint( self: *Painter, pc: *const PainterContext ) !void { if ( !self.glResourcesAreSet ) { try self.glInitFn( self, pc ); self.glResourcesAreSet = true; } return self.glPaintFn( self, pc ); } pub fn glDeinit( self: *Painter ) void { if ( self.glResourcesAreSet ) { self.glDeinitFn( self ); self.glResourcesAreSet = false; } } };
src/core/core.zig
const std = @import("std"); const c = @import("internal/c.zig"); const git = @import("git.zig"); /// Options for connecting through a proxy. /// Note that not all types may be supported, depending on the platform and compilation options. pub const ProxyOptions = struct { /// The type of proxy to use, by URL, auto-detect. proxy_type: ProxyType = .NONE, /// The URL of the proxy. url: ?[:0]const u8 = null, /// This will be called if the remote host requires authentication in order to connect to it. /// /// Return 0 for success, < 0 to indicate an error, > 0 to indicate no credential was acquired /// Returning `GIT_PASSTHROUGH` will make libgit2 behave as though this field isn't set. /// /// ## Parameters /// * `out` - The newly created credential object. /// * `url` - The resource for which we are demanding a credential. /// * `username_from_url` - The username that was embedded in a "user\@host" remote url, or `null` if not included. /// * `allowed_types` - A bitmask stating which credential types are OK to return. /// * `payload` - The payload provided when specifying this callback. credentials: ?fn ( out: **git.Credential, url: [*:0]const u8, username_from_url: [*:0]const u8, /// BUG: This is supposed to be `git.Credential.CredentialType`, but can't be due to a zig compiler bug allowed_types: c_uint, payload: ?*anyopaque, ) callconv(.C) c_int = null, /// If cert verification fails, this will be called to let the user make the final decision of whether to allow the /// connection to proceed. Returns 0 to allow the connection or a negative value to indicate an error. /// /// Return 0 to proceed with the connection, < 0 to fail the connection or > 0 to indicate that the callback refused /// to act and that the existing validity determination should be honored /// /// ## Parameters /// * `cert` - The host certificate /// * `valid` - Whether the libgit2 checks (OpenSSL or WinHTTP) think this certificate is valid. /// * `host` - Hostname of the host libgit2 connected to /// * `payload` - Payload provided by the caller certificate_check: ?fn ( cert: *git.Certificate, valid: bool, host: [*:0]const u8, payload: ?*anyopaque, ) callconv(.C) c_int = null, /// Payload to be provided to the credentials and certificate check callbacks. payload: ?*anyopaque = null, pub const ProxyType = enum(c_uint) { /// Do not attempt to connect through a proxy /// /// If built against libcurl, it itself may attempt to connect /// to a proxy if the environment variables specify it. NONE = 0, /// Try to auto-detect the proxy from the git configuration. AUTO, /// Connect via the URL given in the options SPECIFIED, }; pub fn makeCOptionsObject(self: ProxyOptions) c.git_proxy_options { return .{ .version = c.GIT_PROXY_OPTIONS_VERSION, .@"type" = @enumToInt(self.proxy_type), .url = if (self.url) |s| s.ptr else null, .credentials = @ptrCast(c.git_credential_acquire_cb, self.credentials), .payload = self.payload, .certificate_check = @ptrCast(c.git_transport_certificate_check_cb, self.certificate_check), }; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/proxy.zig
// SPDX-License-Identifier: MIT // This file is part of the `termcon` project under the MIT license. // WINAPI defines not made in standard library as of Zig commit 84d50c892 pub extern "kernel32" fn SetConsoleMode(hConsoleHandle: windows.HANDLE, dwMode: windows.DWORD) callconv(.Stdcall) windows.BOOL; pub extern "kernel32" fn SetConsoleActiveScreenBuffer(hConsoleOutput: windows.HANDLE) callconv(.Stdcall) windows.BOOL; pub extern "kernel32" fn CreateConsoleScreenBuffer(dwDesiredAccess: windows.DWORD, dwShareMode: windows.DWORD, lpSecurityAttributes: ?*const windows.SECURITY_ATTRIBUTES, dwFlags: windows.DWORD, lpScrenBufferData: ?windows.LPVOID) callconv(.Stdcall) windows.HANDLE; // pub extern "kernel32" fn WriteConsoleOutputCharacter(hConsoleOutput: windows.HANDLE, lpCharacter: windows.LPCTSTR, nLength: windows.DWORD, dwWriteCoord: windows.COORD, lpNumberOfCharsWritten: windows.LPDWORD) callconv(.Stdcall) windows.BOOL; pub const config = @import("windows/config.zig"); pub const cursor = @import("windows/cursor.zig"); pub const screen = @import("windows/screen.zig"); pub const event = @import("windows/event.zig"); const std = @import("std"); const windows = std.os.windows; const termcon = @import("../termcon.zig"); pub const SupportedFeatures = termcon.SupportedFeatures; pub var hConsoleOutCurrent: ?windows.HANDLE = null; // hConsoleOutCurrent is to be used publicly. pub var hConsoleOutMain: ?windows.HANDLE = null; // hConsoleOutMain and hConsoleOutAlt are specific handles for pub var hConsoleOutAlt: ?windows.HANDLE = null; // the primary and secondary console screen buffers. pub var hConsoleIn: ?windows.HANDLE = null; var restore_console_mode: windows.DWORD = undefined; // To restore the state of the console on exit pub fn init() !SupportedFeatures { hConsoleOutMain = try std.os.windows.GetStdHandle(std.os.windows.STD_OUTPUT_HANDLE); hConsoleOutCurrent = hConsoleOutMain; hConsoleIn = try std.os.windows.GetStdHandle(std.os.windows.STD_INPUT_HANDLE); restore_console_mode = windows.kernel32.GetConsoleMode(hConsoleOutMain, &restore_console_mode); return SupportedFeatures{ .mouse_events = true }; } pub fn deinit() void { try config.setAlternateScreen(false) catch {}; if (hConsoleOutAlt != null) { if (hConsoleOutAlt) |handle| { _ = windows.kernel32.CloseHandle(handle); } } if (SetConsoleMode(hConsoleOutMain orelse return, restore_console_mode) == 0) return; }
src/backend/windows.zig
// [~] const char* cm_get_error(void); // [x] void cm_init(int samplerate); // [~] void cm_set_lock(cm_EventHandler lock); // [x] void cm_set_master_gain(double gain); // [ ] void cm_process(cm_Int16 *dst, int len); // [ ] cm_Source* cm_new_source(const cm_SourceInfo *info); // [ ] cm_Source* cm_new_source_from_file(const char *filename); // [ ] cm_Source* cm_new_source_from_mem(void *data, int size); // [x] void cm_destroy_source(cm_Source *self); // [x] double cm_get_length(cm_Source *self); // [x] double cm_get_position(cm_Source *self); // [~] int cm_get_state(cm_Source *self); // [x] void cm_set_gain(cm_Source *self, double gain); // [x] void cm_set_pan(cm_Source *self, double pan); // [x] void cm_set_pitch(cm_Source *self, double pitch); // [~] void cm_set_loop(cm_Source *self, int loop); // [x] void cm_play(cm_Source *self); // [x] void cm_pause(cm_Source *self); // [x] void cm_stop(cm_Source *self); const std = @import("std"); const Mutex = std.Mutex; const Allocator = std.mem.Allocator; const math = std.math; pub const Player = @import("../audio.zig").Player; const BUFFER_SIZE = 512; const BUFFER_MASK = BUFFER_SIZE - 1; const FX_BITS = 12; const FX_UNIT = 1 << FX_BITS; fn fxFromFloat(f: f32) i32 { return f * FX_UNIT; } fn fxLerp(comptime T: type, a: T, b: T, p: T) T { return a + (((b - a) * p) >> FX_BITS); } fn clamp(comptime T: type, x: T, a: T, b: T) T { const max = math.max(T, a, b); const min = math.min(T, a, b); if (x > max) { return max; } else if (x < min) { return min; } else { return x; } } pub const State = enum { Stopped, Playing, Paused, }; pub const EventHandler = fn (Event) void; pub const Event = union(enum) { Lock: void, Unlock: void, Rewind: void, Destroy: void, Samples: []const i16, }; pub const SourceInfo = struct { handler: EventHandler, sample_rate: usize, length: usize, }; pub const Source = struct { const Self = @This(); mixer: *Mixer, next: ?*const Source, // next source in list buffer: [BUFFER_SIZE]i16, // internal buffer with raw stereo pcm handler: EventHandler, // event handler sample_rate: usize, // stream's native samplerate length: usize, // stream's length in frames end: usize, // end index for the current play-through pub state: State, // current state position: i64, // current playhead position (fixed point) lgain, rgain: i32, // left and right gain (fixed point) rate: usize, // playback rate (fixed point) next_fill: usize, // next frame idx where the buffer needs to be filled pub loop: bool, // whether the source will loop when `end` is reached rewind: bool, // whether the source will rewind before playing active: bool, // whether the source is part of `sources` list gain: f32, // gain set by `setGain()` pan: f32, // pan set by `setPan()` fn new(mixer: *Mixer, info: SourceInfo) !*Self { const result = try mixer.allocator.createOne(Self); result.*.handler = info.handler; result.*.length = info.length; result.*.sample_rate = info.sample_rate; result.setGain(1.0); result.setPan(0.0); result.setPitch(1.0); result.setLoop(false); result.stop(); return result; } fn rewindSource(self: *Self) void { self.handler(Event{ .Rewind = {}, }); self.position = 0; self.rewind = false; self.end = self.length; self.next_fill = 0; } fn fillBuffer(self: *Self, offset: usize, length: usize) void { const start = offset; const end = start + length; self.handler(Event{ .Samples = self.buffer[start..end], }); } fn process(self: *Self, length: usize) void { const dst = self.mixer.buffer; // do rewind if flag is set if (self.rewind) { self.rewindSource(); } // don't process if not playing if (self.state == State.Paused) { return; } // process audio while (length > 0) { // get current position frame const frame = self.position >> FX_BITS; // fill buffer if required if (frame + 3 >= self.next_fill) { self.fillBuffer((self.next_fill * 2) & BUFFER_MASK, BUFFER_SIZE / 2); self.next_fill = BUFFER_SIZE / 4; } // handle reaching the end of the playthrough if (frame >= self.end) { // ss streams continiously fill the raw buffer in a loop we simply // increment the end idx by one length and continue reading from it for // another play-through self.end = frame + self.length; // set state and stop processing if we're not set to loop if (self.loop) { self.state = State.Stopped; break; } } // work out how many frames we should process in the loop var n = math.min(usize, self.next_fill - 2, self.end) - frame; const count = blk: { var c = (n << FX_BITS) / self.rate; c = math.max(usize, c, 1); c = math.min(usize, c, length / 2); break :blk c; }; length -= count * 2; // add audio to master buffer if (self.rate == FX_UNIT) { // add audio to buffer -- basic var n = frame * 2; var i: usize = 0; while (i < count) : (i += 1) { dst[(i * 2) + 0] += (self.buffer[(n) & BUFFER_MASK] * self.lgain) >> FX_BITS; dst[(i * 2) + 1] += (self.buffer[(n + 1) & BUFFER_MASK] * self.rgain) >> FX_BITS; n += 2; } self.position += count * FX_UNIT; } else { // add audio to buffer -- interpolated var i: usize = 0; while (i < count) : (i += 1) { const p = self.position & FX_MASK; var n = (self.position >> FX_BITS) * 2; var a = self.buffer[(n) & BUFFER_MASK]; var b = self.buffer[(n + 2) & BUFFER_MASK]; dst[(i * 2) + 0] += (FX_LERP(a, b, p) * self.lgain) >> FX_BITS; n += 1; a = self.buffer[(n) & BUFFER_MASK]; b = self.buffer[(n + 2) & BUFFER_MASK]; dst[(i * 2) + 1] += (FX_LERP(a, b, p) * self.rgain) >> FX_BITS; self.position += self.rate; } } } } pub fn destroy(self: *Self) void { const held = self.mixer.lock.acquire(); if (self.active) { var source = self.mixer.sources; while (source) |*src| { if (src.* == self) { src.* = self.next; break; } } } held.release(); self.handler(Event{ .Destroy = {} }); self.mixer.allocator.free(self); self = undefined; } pub fn getLength(self: *const Self) f32 { return self.length / @intToFloat(f32, self.sample_rate); } pub fn getPosition(self: *const Self) f32 { return ((self.position >> FX_BITS) % self.length) / @intToFloat(f32, self.sample_rate); } fn recalcGains(self: *Self) void { self.lgain = fxFromFloat(self.gain * (if (self.pan <= 0.0) 1.0 else 1.0 - pan)); self.rgain = fxFromFloat(self.gain * (if (self.pan >= 0.0) 1.0 else 1.0 + pan)); } pub fn setGain(self: *Self, gain: f32) void { self.gain = gain; self.recalcGains(); } pub fn setPan(self: *Self, pan: f32) void { self.pan = clamp(f32, -1.0, 1.0); self.recalcGains(); } pub fn setPitch(self: *Self, pitch: f32) void { const rate: f32 = if (pitch > 0.0) { self.samplerate / @intToFloat(f32, self.sample_rate) * pitch; } else { 0.001; }; self.rate = fxFromFloat(rate); } pub fn play(self: *Self) void { const held = self.mixer.lock.acquire(); defer held.release(); self.state = State.Playing; if (!self.active) { self.active = true; self.next = self.mixer.sources; self.mixer.sources = self; } } pub fn pause(self: *Self) void { self.state = State.Paused; } pub fn stop(self: *Self) void { self.state = State.Stopped; self.rewind = true; } }; pub const Mixer = struct { const Self = @This(); lock: Mutex, allocator: *Allocator, sources: ?*Source, // linked list of active sources buffer: [BUFFER_SIZE]i32, // internal master buffer sample_rate: i32, // master samplerate gain: i32, // master gain (fixed point) pub fn init(allocator: *Allocator, sample_rate: i32) Self { return Self{ .allocator = allocator, .sample_rate = sample_rate, .lock = Mutex.init(), .sources = null, .gain = FX_UNIT, }; } pub fn setGain(self: *Self, gain: f32) void { self.gain = fxFromFloat(gain); } pub fn process(self: *Self, dst: []const i16) void { // process in chunks of BUFFER_SIZE if `dst.len` is larger than BUFFER_SIZE while (dst.len > BUFFER_SIZE) { self.process(dst[0..BUFFER_SIZE]); dst = dst[BUFFER_SIZE..]; } // zeroset internal buffer std.mem.secureZero(i32, self.buffer); const held = self.lock.acquire(); var source = self.src; while (source) |*src| { src.process(dst.len); // remove source from list if no longer plating if (src.*.state != State.Playing) { src.*.active = false; source.?.* = src.next; } else { source = src.next; } } held.release(); // copy internal buffer to destination and clip for (dst) |*d, i| { const x = (self.buffer[i] * self.gain) >> FX_BITS; d.* = clamp(i32, -32768, 32767); } } };
src/audio/mixer.zig
const std = @import("std"); const testing = std.testing; pub const terminfo = @import("terminfo.zig"); const History = @import("history.zig"); const terminal = @import("terminal.zig"); const Self = @This(); alloc: *std.mem.Allocator, file: std.fs.File, history: History, terminfo: terminfo.TermInfo, buffer: std.ArrayList(u8), message: ?[]const u8, pub fn init(allocator: *std.mem.Allocator, file: std.fs.File) !Self { const tinfo = try terminfo.loadTerm(allocator); return Self{ .alloc = allocator, .file = file, .history = .{}, .terminfo = tinfo, .buffer = std.ArrayList(u8).init(allocator), .message = null, }; } fn redraw(self: *Self) !void { const writer = self.file.writer(); try writer.writeAll(self.terminfo.getString(.carriage_return).?); try writer.writeAll(self.terminfo.getString(.clr_eol).?); if (self.message) |msg| { try writer.writeAll(msg); } try writer.writeAll(self.buffer.items); } pub fn prompt(self: *Self, message: []const u8) ![]u8 { self.message = message; const raw_context = terminal.RawContext.enter(self.file.handle); defer raw_context.exit(); const reader = self.file.reader(); const writer = self.file.writer(); self.buffer.clearRetainingCapacity(); while (true) { try self.redraw(); const c = try reader.readByte(); if (!std.ascii.isCntrl(c)) { try self.buffer.append(c); try writer.writeByte(c); } else if (c == 0x7f) { _ = self.buffer.pop(); } else { std.debug.print("unknown character: {x}\n", .{c}); } if (c == '\n') break; } try writer.writeAll(self.terminfo.getString(.carriage_return).?); try writer.writeAll(self.terminfo.getString(.newline).?); self.history.add(self.buffer.items); return self.buffer.items; } pub fn get(self: *Self) ![]u8 { return self.prompt(""); } pub fn destroy(self: *Self) void { self.buffer.deinit(); }
src/main.zig
const std = @import("std"); usingnamespace @import("../json.zig"); const Allocator = std.mem.Allocator; const Parser = std.json.Parser; const ObjectMap = std.json.ObjectMap; const assert = std.debug.assert; const StoS = std.StringHashMap([]const u8); const SessionGetRequest = struct { username: []const u8, password: []const u8, // TODO handle errors here pub fn handle(req: SessionGetRequest) !Session { const user_pw = cred_db.getValue(req.username) orelse return error.UserNotFound; if (!std.mem.eql(u8, pw, req.password)) { return error.WrongPassword; } std.debug.warn("Successfully authenticated session GET request!\n", .{}); const accounts = getAccounts(req.username); const primary_accounts = getPrimaryAccounts(req.username, accounts); // TODO no idea how this will work, I'm just going to stub it for now const state = getSessionState(req); return Session{ .capabilities = config.capabilities, .accounts = accounts, .primary_accounts = primary_accounts, .username = req.username, .api_url = config.api_url, .download_url = config.download_url, .upload_url = config.upload_url, .event_source_url = config.event_source_url, .state = state, }; } }; var cred_db: StoS = undefined; // TODO this should probably be done at compile time, just waiting on the // availability of a comptime allocator. If there's a better way, go ahead and // change this code. IMPLEMENT THIS. //fn generateRoutes(allocator: *Allocator) std.StringHashMap(fn ...) { // ... //} fn handleJson(allocator: *Allocator, msg: []const u8, parser: *Parser) !void { parser.reset(); const tree = try parser.parse(msg); // TODO return error on an invalid request format assert(std.meta.activeTag(tree.root) == .Array); const arr = tree.root.Array; const name = arr.at(0).String; // TODO replace this with all the types you want to consider deserializing inline for (.{SessionGetRequest}) |T| { if (std.mem.eql(u8, @typeName(T), name)) { const result = try json_deserializer.fromJson(T, allocator, arr.at(1)); std.debug.warn("deserialized: {}\n", .{result}); T.handle(result); return; } } } fn initCredDb(allocator: *Allocator) !void { cred_db = StoS.init(allocator); try cred_db.putNoClobber("siva", "password"); try cred_db.putNoClobber("another", "pw"); } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; try initCredDb(allocator); var parser = Parser.init(allocator, false); var buf = try std.Buffer.initCapacity(allocator, 1024); while (true) { const req = try std.io.readLine(&buf); try handleJson(allocator, req, &parser); } }
simple-server/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Metadata = @import("metadata.zig").Metadata; const vorbis = @import("vorbis.zig"); pub const flac_stream_marker = "fLaC"; pub const block_type_vorbis_comment = 4; /// Expects the stream to be at the start of the FLAC stream marker (i.e. /// any ID3v2 tags must be skipped before calling this function) pub fn read(allocator: Allocator, reader: anytype, seekable_stream: anytype) !Metadata { var stream_marker = try reader.readBytesNoEof(4); if (!std.mem.eql(u8, stream_marker[0..], flac_stream_marker)) { return error.InvalidStreamMarker; } while (true) { const first_byte = try reader.readByte(); const is_last_metadata_block = first_byte & @as(u8, 1 << 7) != 0; const block_type = first_byte & 0x7F; const length = try reader.readIntBig(u24); // short circuit for impossible comment lengths to avoid // giant allocations that we know are impossible to read const max_remaining_bytes = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos()); if (length > max_remaining_bytes) { return error.EndOfStream; } if (block_type == block_type_vorbis_comment) { const start_offset = try seekable_stream.getPos(); const end_offset = start_offset + length; // since we know the length, we can read it all up front // and then wrap it in a FixedBufferStream so that we can // get bounds-checking in our read calls when reading the // comment without any special casing var comments = try allocator.alloc(u8, length); defer allocator.free(comments); try reader.readNoEof(comments); var fixed_buffer_stream = std.io.fixedBufferStream(comments); var metadata = vorbis.readComment(allocator, fixed_buffer_stream.reader(), fixed_buffer_stream.seekableStream()) catch |e| switch (e) { error.EndOfStream => return error.EndOfCommentBlock, else => |err| return err, }; errdefer metadata.deinit(); metadata.start_offset = start_offset; metadata.end_offset = end_offset; // There can only be one comment block per stream, so we can return here return metadata; } else { // skipping bytes in the reader actually reads the bytes which is a // huge waste of time, this is way faster try seekable_stream.seekBy(length); } if (is_last_metadata_block) break; } return error.NoCommentBlock; }
src/flac.zig
const terminal = @import("./vga.zig").terminal; const IdtEntry = struct { func_offset_low_word: u16, selector: u16, dcount: u8, attribute: u8, func_offset_high_word: u16, pub fn setHandler(self: *IdtEntry, attr: u8, handler: HandlerFunc) void { const handler_ptr = @ptrToInt(handler); self.* = .{ .func_offset_low_word = @truncate(u16, handler_ptr), .selector = SELECTOR_K_CODE, .dcount = 0, .attribute = attr, .func_offset_high_word = @truncate(u16, handler_ptr >> 16), }; } }; const IDT_DESC_CNT = 0x21; const IDT_DESC_P = 1; const IDT_DESC_32_TYPE = 0xE; const IDT_DESC_DPL0 = 0; const IDT_DESC_ATTR_DPL0 = ((IDT_DESC_P << 7) + (IDT_DESC_DPL0 << 5) + IDT_DESC_32_TYPE); const RPL0 = 0; const TI_GDT = 0; const SELECTOR_K_CODE = ((1 << 3) + (TI_GDT << 2) + RPL0); var idt_entries: [IDT_DESC_CNT]IdtEntry = [_]IdtEntry{ .{ .func_offset_low_word = 0, .selector = 0, .dcount = 0, .attribute = 0, .func_offset_high_word = 0, }, } ** IDT_DESC_CNT; const HandlerFunc = fn () callconv(.Interrupt) void; fn general_handler() callconv(.Interrupt) void { terminal.write("EXCEPTION\n"); } fn idt_desc_init() void { var i: usize = 0; while (i < IDT_DESC_CNT) { idt_entries[i].setHandler(IDT_DESC_ATTR_DPL0, general_handler); i += 1; } terminal.write("IDT: idt_desc_init done\n"); } fn outb(port: u16, data: u8) void { asm volatile ("outb %[data], %[port]" : : [data] "{al}" (data), [port] "N{dx}" (port), ); } const PIC_M_CTRL = 0x20; const PIC_M_DATA = 0x21; const PIC_S_CTRL = 0xa0; const PIC_S_DATA = 0xa1; fn pic_init() void { // init main board outb(PIC_M_CTRL, 0x11); outb(PIC_M_DATA, 0x20); outb(PIC_M_DATA, 0x04); outb(PIC_M_DATA, 0x01); // init sub board outb(PIC_S_CTRL, 0x11); outb(PIC_S_DATA, 0x28); outb(PIC_S_DATA, 0x02); outb(PIC_S_DATA, 0x01); // open main board IR0 outb(PIC_M_DATA, 0xfe); outb(PIC_S_DATA, 0xff); terminal.write("IDT: pic_init done\n"); } const IdtPtr = packed struct { /// The total size of the IDT (minus 1) in bytes. limit: u16 = @sizeOf(IdtEntry) * IDT_DESC_CNT - 1, /// The base address where the IDT is located. base: u32, }; pub fn init() void { terminal.write("IDT: interrupt descriptor table init\n"); idt_desc_init(); pic_init(); var idt_ptr: IdtPtr = IdtPtr{ .base = @ptrToInt(&idt_entries) }; lidt(&idt_ptr); terminal.write("IDT: interrupt descriptor table init done\n"); } fn lidt(idt_ptr: *const IdtPtr) void { asm volatile ("lidt (%%eax)" : : [idt_ptr] "{eax}" (idt_ptr), ); }
x86os/src/idt.zig
pub const lib = struct { pub const Bss = struct { pub fn prepare() void { @memset(@ptrCast([*]u8, &__bss_start), 0, @ptrToInt(&__bss_end) - @ptrToInt(&__bss_start)); } }; pub const Adc = struct { pub const busy_registers = mmio(0x40007400, extern struct { busy: u32, }); pub const events = mmio(0x40007100, extern struct { end: u32, }); pub const registers = mmio(0x40007500, extern struct { enable: u32, config: u32, result: u32, }); pub const registers_config_masks = struct { pub const extrefsel = 0x30000; pub const inpsel = 0x001c; pub const psel = 0xff00; pub const refsel = 0x0060; pub const resolution = 0x00003; }; pub const tasks = mmio(0x40007000, extern struct { start: u32, stop: u32, }); }; pub const ClockManagement = struct { pub fn prepareHf() void { crystal_registers.frequency_selector = 0xff; tasks.start_hf_clock = 1; while (events.hf_clock_started == 0) {} } pub const events = mmio(0x40000100, extern struct { hf_clock_started: u32, lf_clock_started: u32, }); pub const crystal_registers = mmio(0x40000550, extern struct { frequency_selector: u32, }); pub const tasks = mmio(0x40000000, extern struct { start_hf_clock: u32, stop_hf_clock: u32, start_lf_clock: u32, stop_lf_clock: u32, }); }; pub const Exceptions = struct { var already_panicking: bool = undefined; var panic_handler: ?fn (message: []const u8, trace: ?*builtin.StackTrace) noreturn = undefined; pub fn handle(exception_number: u32) noreturn { panicf("exception number {} ... now idle in arm exception handler", .{exception_number}); } pub fn prepare() void { already_panicking = false; panic_handler = null; } pub fn setPanicHandler(new_panic_handler: ?fn (message: []const u8, trace: ?*builtin.StackTrace) noreturn) void { panic_handler = new_panic_handler; } }; pub const Ficr = struct { pub fn deviceId() u64 { return @as(u64, contents[0x64 / 4]) << 32 | contents[0x60 / 4]; } pub fn dump() void { for (contents) |word, i| { log("{x:2} {x:8}", .{ i * 4, word }); } } pub fn isQemu() bool { return deviceId() == 0x1234567800000003; } pub const contents = @intToPtr(*[64]u32, 0x10000000); pub const radio = @intToPtr(*extern struct { device_address_type: u32, device_address0: u32, device_address1: u32, }, 0x100000a0); }; pub const Gpio = struct { pub const config = mmio(0x50000700, [32]u32); pub const config_masks = struct { pub const input = 0x0; pub const output = 0x1; }; pub const led_anode_number_and_cathode_number_indexed_by_y_then_x = [5][5][2]u32{ .{ .{ 1, 1 }, .{ 2, 4 }, .{ 1, 2 }, .{ 2, 5 }, .{ 1, 3 } }, .{ .{ 3, 4 }, .{ 3, 5 }, .{ 3, 6 }, .{ 3, 7 }, .{ 3, 8 } }, .{ .{ 2, 2 }, .{ 1, 9 }, .{ 2, 3 }, .{ 3, 9 }, .{ 2, 1 } }, .{ .{ 1, 8 }, .{ 1, 7 }, .{ 1, 6 }, .{ 1, 5 }, .{ 1, 4 } }, .{ .{ 3, 3 }, .{ 2, 7 }, .{ 3, 1 }, .{ 2, 6 }, .{ 3, 2 } }, }; pub const registers = mmio(0x50000504, extern struct { out: u32, out_set: u32, out_clear: u32, in: u32, direction: u32, direction_set: u32, direction_clear: u32, }); pub const registers_masks = struct { pub const button_a_active_low: u32 = 1 << 17; pub const button_b_active_low: u32 = 1 << 26; pub const i2c_scl: u32 = 1 << 0; pub const i2c_sda: u32 = 1 << 30; pub const nine_led_cathodes_active_low: u32 = 0x1ff << 4; pub const ring0: u32 = 1 << 3; pub const ring1: u32 = 1 << 2; pub const ring2: u32 = 1 << 1; pub const three_led_anodes: u32 = 0x7 << 13; pub const uart_rx = 1 << 25; pub const uart_tx = 1 << 24; }; }; pub const Gpiote = struct { pub const config = mmio(0x40006510, [4]u32); pub const config_masks = struct { pub const disable = 0x0; }; pub const tasks = struct { pub const out = mmio(0x40006000, [4]u32); }; }; pub fn I2cInstance(instance_address: u32) type { return struct { pub fn prepare() void { registers.enable = 0; Gpio.registers.direction_set = Gpio.registers_masks.i2c_scl | Gpio.registers_masks.i2c_sda; registers.pselscl = @ctz(u32, Gpio.registers_masks.i2c_scl); registers.pselsda = @ctz(u32, Gpio.registers_masks.i2c_sda); registers.frequency = frequencies.K400; registers.enable = 5; } pub fn probe(device_address: u32) !void { device_addresses.device_address = device_address; tasks.startrx = 1; defer tasks.stop = 1; try wait(&events.byte_break); } pub fn readBlocking(device_address: u32, data: []u8, first: u32, last: u32) !void { device_addresses.device_address = device_address; tasks.starttx = 1; registers.txd = first; try wait(&events.txdsent); tasks.startrx = 1; var i = first; while (i <= last) : (i += 1) { if (i == last) { tasks.stop = 1; } try wait(&events.rxready); data[i] = @truncate(u8, registers.rxd); } } pub fn readBlockingPanic(device_address: u32, data: []u8, first: u32, last: u32) void { if (readBlocking(device_address, data, first, last)) |_| {} else |err| { panicf("i2c device 0x{x} read {} errorsrc 0x{x}", .{ device_address, err, I2c0.errorsrc_registers.errorsrc }); } } fn wait(event: *volatile u32) !void { const start = Timer0.capture(); while (true) { if (event.* != 0) { event.* = 0; return; } if (errorsrc_registers.errorsrc != 0) { return error.I2cErrorSourceRegister; } if (Timer0.capture() -% start > 500 * 1000) { return error.I2cTimeExpired; } } } pub fn writeBlocking(device_address: u32, data: []u8, first: u32, last: u32) !void { device_addresses.device_address = device_address; tasks.starttx = 1; registers.txd = first; try wait(&events.txdsent); var i = first; while (i <= last) : (i += 1) { registers.txd = data[i]; try wait(&events.txdsent); } tasks.stop = 1; } pub fn writeBlockingPanic(device_address: u32, data: []u8, first: u32, last: u32) void { if (writeBlocking(device_address, data, first, last)) |_| {} else |err| { panicf("i2c device 0x{x} write {} errorsrc 0x{x}", .{ device_address, err, I2c0.errorsrc_registers.errorsrc }); } } pub const device_addresses = mmio(instance_address + 0x588, extern struct { device_address: u32, }); pub const events = mmio(instance_address + 0x104, extern struct { stopped: u32, rxready: u32, unused1: [4]u32, txdsent: u32, unused2: [1]u32, error_event: u32, unused3: [4]u32, byte_break: u32, }); pub const frequencies = struct { pub const K100 = 0x01980000; pub const K250 = 0x04000000; pub const K400 = 0x06680000; }; pub const errorsrc_registers = mmio(instance_address + 0x4c4, extern struct { errorsrc: u32, }); pub const errorsrc_masks = struct { pub const overrun = 1 << 0; pub const address_nack = 1 << 1; pub const data_nack = 1 << 2; }; pub const registers = mmio(instance_address + 0x500, extern struct { enable: u32, unused1: [1]u32, pselscl: u32, pselsda: u32, unused2: [2]u32, rxd: u32, txd: u32, unused3: [1]u32, frequency: u32, }); pub const short_cuts = mmio(instance_address + 0x200, extern struct { shorts: u32, }); pub const tasks = mmio(instance_address + 0x000, extern struct { startrx: u32, unused1: [1]u32, starttx: u32, unused2: [2]u32, stop: u32, unused3: [1]u32, suspend_task: u32, resume_task: u32, }); }; } pub const LedMatrix = struct { pub var max_elapsed: u32 = undefined; pub var image: u32 = undefined; var scan_lines: [3]u32 = undefined; var scan_lines_index: u32 = undefined; var scan_timer: TimeKeeper = undefined; pub fn prepare() void { image = 0; max_elapsed = 0; Gpio.registers.direction_set = Gpio.registers_masks.three_led_anodes | Gpio.registers_masks.nine_led_cathodes_active_low; for (scan_lines) |*scan_line| { scan_line.* = 0; } scan_lines_index = 0; putChar('Z'); scan_timer.prepare(3 * 1000); } pub fn putChar(byte: u8) void { putImage(getImage(byte)); } pub fn putImage(new_image: u32) void { image = new_image; var mask: u32 = 0x1; var y: i32 = 4; while (y >= 0) : (y -= 1) { var x: i32 = 4; while (x >= 0) : (x -= 1) { putPixel(@intCast(u32, x), @intCast(u32, y), if (image & mask != 0) @as(u32, 1) else 0); mask <<= 1; } } } fn putPixel(x: u32, y: u32, v: u32) void { const anode_number_and_cathode_number = Gpio.led_anode_number_and_cathode_number_indexed_by_y_then_x[y][x]; const selected_scan_line_index = anode_number_and_cathode_number[0] - 1; const col_mask = @as(u32, 0x10) << @truncate(u5, anode_number_and_cathode_number[1] - 1); scan_lines[selected_scan_line_index] = scan_lines[selected_scan_line_index] & ~col_mask | v * col_mask; } pub fn update() void { if (scan_timer.isFinished()) { const elapsed = scan_timer.elapsed(); if (elapsed > max_elapsed) { max_elapsed = elapsed; } scan_timer.reset(); const keep = Gpio.registers.out & ~(Gpio.registers_masks.three_led_anodes | Gpio.registers_masks.nine_led_cathodes_active_low); const row_pins = @as(u32, 0x2000) << @truncate(u5, scan_lines_index); const col_pins = ~scan_lines[scan_lines_index] & Gpio.registers_masks.nine_led_cathodes_active_low; Gpio.registers.out = keep | row_pins | col_pins; scan_lines_index = (scan_lines_index + 1) % scan_lines.len; } } pub fn getImage(byte: u8) u32 { return switch (byte) { ' ' => 0b0000000000000000000000000, '0' => 0b1111110001100011000111111, '1' => 0b0010001100001000010001110, '2' => 0b1111100001111111000011111, '3' => 0b1111100001001110000111111, '4' => 0b1000110001111110000100001, '5' => 0b1111110000111110000111111, '6' => 0b1111110000111111000111111, '7' => 0b1111100001000100010001000, '8' => 0b1111110001111111000111111, '9' => 0b1111110001111110000100001, 'A' => 0b0111010001111111000110001, 'B' => 0b1111010001111111000111110, 'Z' => 0b1111100010001000100011111, else => 0b0000000000001000000000000, }; } }; pub const Power = struct { pub const registers = mmio(0x40000400, extern struct { reset_reason: u32, }); }; pub const Ppi = struct { pub fn setChannelEventAndTask(channel: u32, event: *volatile u32, task: *volatile u32) void { channels[channel].event_end_point = @ptrToInt(event); channels[channel].task_end_point = @ptrToInt(task); } pub const registers = mmio(0x4001f500, extern struct { channel_enable: u32, channel_enable_set: u32, channel_enable_clear: u32, }); const channels = mmio(0x4001f510, [16]struct { event_end_point: u32, task_end_point: u32, }); }; pub const Radio = struct { pub const events = mmio(0x40001100, extern struct { ready: u32, address_completed: u32, payload_completed: u32, packet_completed: u32, disabled: u32, }); pub const registers = mmio(0x40001504, struct { packet_ptr: u32, frequency: u32, tx_power: u32, mode: u32, pcnf0: u32, pcnf1: u32, base0: u32, base1: u32, prefix0: u32, prefix1: u32, tx_address: u32, rx_addresses: u32, crc_config: u32, crc_poly: u32, crc_init: u32, unused0x540: u32, unused0x544: u32, unused0x548: u32, unused0x54c: u32, state: u32, datawhiteiv: u32, }); pub const rx_registers = mmio(0x40001400, extern struct { crc_status: u32, unused0x404: u32, unused0x408: u32, rx_crc: u32, }); pub const short_cuts = mmio(0x40001200, extern struct { shorts: u32, }); pub const tasks = mmio(0x40001000, extern struct { tx_enable: u32, rx_enable: u32, start: u32, stop: u32, disable: u32, }); }; pub const Rng = struct { pub fn prepare() void { registers.config = 0x1; tasks.start = 1; } pub const events = mmio(0x4000d100, extern struct { value_ready: u32, }); pub const registers = mmio(0x4000d504, extern struct { config: u32, value: u32, }); pub const tasks = mmio(0x4000d000, extern struct { start: u32, stop: u32, }); }; pub const SystemControlBlock = struct { pub fn requestSystemReset() void { registers.aircr = 0x05fa0004; } pub const registers = mmio(0xe000ed00, extern struct { cpuid: u32, icsr: u32, unused1: u32, aircr: u32, scr: u32, ccr: u32, unused2: u32, shpr2: u32, shpr3: u32, }); }; pub const Temperature = struct { pub const events = mmio(0x4000c100, extern struct { data_ready: u32, }); pub const registers = mmio(0x4000c508, extern struct { temperature: u32, }); pub const tasks = mmio(0x4000c000, extern struct { start: u32, stop: u32, }); }; pub const Terminal = struct { pub fn attribute(n: u32) void { pair(n, 0, "m"); } pub fn clearScreen() void { pair(2, 0, "J"); } pub fn hideCursor() void { Uart.writeText(csi ++ "?25l"); } pub fn line(comptime fmt: []const u8, args: var) void { format(fmt, args); pair(0, 0, "K"); Uart.writeText("\n"); } pub fn move(row: u32, column: u32) void { pair(row, column, "H"); } pub fn pair(a: u32, b: u32, letter: []const u8) void { if (a <= 1 and b <= 1) { format("{}{}", .{ csi, letter }); } else if (b <= 1) { format("{}{}{}", .{ csi, a, letter }); } else if (a <= 1) { format("{};{}{}", .{ csi, b, letter }); } else { format("{}{};{}{}", .{ csi, a, b, letter }); } } pub fn reportCursorPosition() void { Uart.writeText(csi ++ "6n"); } pub fn restoreCursor() void { pair(0, 0, "u"); } pub fn saveCursor() void { pair(0, 0, "s"); } pub fn setScrollingRegion(top: u32, bottom: u32) void { pair(top, bottom, "r"); } pub fn showCursor() void { Uart.writeText(csi ++ "?25h"); } const csi = "\x1b["; }; pub const TimeKeeper = struct { duration: u32, start_time: u32, fn capture(self: *TimeKeeper) u32 { Timer0.capture_tasks[0] = 1; return Timer0.capture_compare_registers[0]; } fn elapsed(self: *TimeKeeper) u32 { return self.capture() -% self.start_time; } fn prepare(self: *TimeKeeper, duration: u32) void { self.duration = duration; self.reset(); } fn isFinished(self: *TimeKeeper) bool { return self.elapsed() >= self.duration; } fn reset(self: *TimeKeeper) void { self.start_time = self.capture(); } fn wait(self: *TimeKeeper) void { while (!self.isFinished()) {} self.reset(); } pub fn delay(duration: u32) void { var time_keeper: TimeKeeper = undefined; time_keeper.prepare(duration); time_keeper.wait(); } }; pub fn TimerInstance(instance_address: u32) type { return struct { pub fn capture() u32 { capture_tasks[0] = 1; return capture_compare_registers[0]; } pub fn prepare() void { registers.mode = 0x0; registers.bit_mode = if (instance_address == 0x40008000) @as(u32, 0x3) else 0x0; registers.prescaler = if (instance_address == 0x40008000) @as(u32, 4) else 9; tasks.start = 1; const now = capture(); var i: u32 = 0; while (capture() == now) : (i += 1) { if (i == 1000) { panicf("timer {} is not responding", .{instance_address}); } } // panicf("timer {} responded {} now {} capture {}", .{instance_address, i, now, capture()}); } pub const capture_compare_registers = mmio(instance_address + 0x540, [4]u32); pub const capture_tasks = mmio(instance_address + 0x040, [4]u32); pub const events = struct { pub const compare = mmio(instance_address + 0x140, [4]u32); }; pub const registers = mmio(instance_address + 0x504, extern struct { mode: u32, bit_mode: u32, unused0x50c: u32, prescaler: u32, }); pub const short_cuts = mmio(instance_address + 0x200, extern struct { shorts: u32, }); pub const tasks = mmio(instance_address + 0x000, extern struct { start: u32, stop: u32, count: u32, clear: u32, }); }; } pub const Uart = struct { var stream: std.io.OutStream(Uart, stream_error, writeTextError) = undefined; var tx_busy: bool = undefined; var tx_queue: [3]u8 = undefined; var tx_queue_read: usize = undefined; var tx_queue_write: usize = undefined; var updater: ?fn () void = undefined; pub fn drainTxQueue() void { while (tx_queue_read != tx_queue_write) { loadTxd(); } } pub fn prepare() void { updater = null; Gpio.registers.direction_set = Gpio.registers_masks.uart_tx; registers.pin_select_rxd = @ctz(u32, Gpio.registers_masks.uart_rx); registers.pin_select_txd = @ctz(u32, Gpio.registers_masks.uart_tx); registers.enable = 0x04; tasks.start_rx = 1; tasks.start_tx = 1; tx_busy = false; tx_queue_read = 0; tx_queue_write = 0; } pub fn isReadByteReady() bool { return events.rx_ready == 1; } pub fn format(comptime fmt: []const u8, args: var) void { std.fmt.format(stream, fmt, args) catch |_| {}; } pub fn loadTxd() void { if (tx_queue_read != tx_queue_write and (!tx_busy or events.tx_ready == 1)) { events.tx_ready = 0; registers.txd = tx_queue[tx_queue_read]; tx_queue_read = (tx_queue_read + 1) % tx_queue.len; tx_busy = true; if (updater) |an_updater| { an_updater(); } } } pub fn log(comptime fmt: []const u8, args: var) void { format(fmt ++ "\n", args); } pub fn readByte() u8 { events.rx_ready = 0; return @truncate(u8, registers.rxd); } pub fn setUpdater(new_updater: fn () void) void { updater = new_updater; } pub fn update() void { loadTxd(); } pub fn writeByteBlocking(byte: u8) void { const next = (tx_queue_write + 1) % tx_queue.len; while (next == tx_queue_read) { loadTxd(); } tx_queue[tx_queue_write] = byte; tx_queue_write = next; loadTxd(); } pub fn writeText(buffer: []const u8) void { for (buffer) |c| { switch (c) { '\n' => { writeByteBlocking('\r'); writeByteBlocking('\n'); }, else => writeByteBlocking(c), } } } pub fn writeTextError(context: Uart, buffer: []const u8) stream_error!u32 { writeText(buffer); return buffer.len; } const stream_error = error{UartError}; const events = mmio(0x40002108, extern struct { rx_ready: u32, unused0x10c: u32, unused0x110: u32, unused0x114: u32, unused0x118: u32, tx_ready: u32, unused0x120: u32, error_detected: u32, }); const error_registers = mmio(0x40002480, extern struct { error_source: u32, }); const registers = mmio(0x40002500, extern struct { enable: u32, unused0x504: u32, pin_select_rts: u32, pin_select_txd: u32, pin_select_cts: u32, pin_select_rxd: u32, rxd: u32, txd: u32, unused0x520: u32, baud_rate: u32, }); const tasks = mmio(0x40002000, extern struct { start_rx: u32, stop_rx: u32, start_tx: u32, stop_tx: u32, }); }; pub const Uicr = struct { pub fn dump() void { for (contents) |word, i| { log("{x:2} {x:8}", .{ i * 4, word }); } } pub const contents = @intToPtr(*[64]u32, 0x10001000); }; pub const Wdt = struct { pub const reload_request_registers = mmio(0x40010600, extern struct { reload_request: [8]u32, }); pub const registers = mmio(0x40010504, extern struct { counter_reset_value: u32, reload_rewuest_enable: u32, }); pub const tasks = mmio(0x40010000, extern struct { start: u32, }); }; pub fn hangf(comptime fmt: []const u8, args: var) noreturn { log(fmt, args); Uart.drainTxQueue(); while (true) {} } pub fn mmio(address: u32, comptime mmio_type: type) *volatile mmio_type { return @intToPtr(*volatile mmio_type, address); } pub fn panic(message: []const u8, trace: ?*builtin.StackTrace) noreturn { if (Exceptions.panic_handler) |handler| { handler(message, trace); } else { panicf("panic(): {}", .{message}); } } pub fn panicf(comptime fmt: []const u8, args: var) noreturn { @setCold(true); if (Exceptions.already_panicking) { hangf("\npanicked during panic", .{}); } Exceptions.already_panicking = true; log("\npanicf(): " ++ fmt, args); var it = std.debug.StackIterator.init(null, null); while (it.next()) |stacked_address| { dumpReturnAddress(stacked_address - 1); } hangf("panic completed", .{}); } fn dumpReturnAddress(return_address: usize) void { var symbol_index: usize = 0; var line: []const u8 = ""; var i: u32 = 0; while (i < symbols.len) { var j: u32 = i; while (symbols[j] != '\n') { j += 1; } const next_line = symbols[i..j]; const symbol_address = std.fmt.parseUnsigned(usize, next_line[0..8], 16) catch 0; if (symbol_address >= return_address) { break; } line = next_line; i = j + 1; } if (line.len >= 3) { log("{x:5} in {}", .{ return_address, line[3..] }); } else { log("{x:5}", .{return_address}); } } fn typicalVectorTable(comptime mission_id: u32) []const u8 { var buf: [1]u8 = undefined; const mission_id_string = std.fmt.bufPrint(&buf, "{}", .{mission_id}) catch |_| panicf("", .{}); for (mission_id_string) |*space| { if (space.* == ' ') { space.* = '0'; } else { break; } } return ".section .text.start.mission" ++ mission_id_string ++ "\n" ++ ".globl mission" ++ mission_id_string ++ "_vector_table\n" ++ ".balign 0x80\n" ++ "mission" ++ mission_id_string ++ "_vector_table:\n" ++ " .long 0x20004000 // sp top of 16KB\n" ++ " .long mission" ++ mission_id_string ++ "_main\n" ++ \\ .long lib_exceptionNumber02 \\ .long lib_exceptionNumber03 \\ .long lib_exceptionNumber04 \\ .long lib_exceptionNumber05 \\ .long lib_exceptionNumber06 \\ .long lib_exceptionNumber07 \\ .long lib_exceptionNumber08 \\ .long lib_exceptionNumber09 \\ .long lib_exceptionNumber10 \\ .long lib_exceptionNumber11 \\ .long lib_exceptionNumber12 \\ .long lib_exceptionNumber13 \\ .long lib_exceptionNumber14 \\ .long lib_exceptionNumber15 ; } export fn lib_exceptionNumber01() noreturn { Exceptions.handle(01); } export fn lib_exceptionNumber02() noreturn { Exceptions.handle(02); } export fn lib_exceptionNumber03() noreturn { Exceptions.handle(03); } export fn lib_exceptionNumber04() noreturn { Exceptions.handle(04); } export fn lib_exceptionNumber05() noreturn { Exceptions.handle(05); } export fn lib_exceptionNumber06() noreturn { Exceptions.handle(06); } export fn lib_exceptionNumber07() noreturn { Exceptions.handle(07); } export fn lib_exceptionNumber08() noreturn { Exceptions.handle(08); } export fn lib_exceptionNumber09() noreturn { Exceptions.handle(09); } export fn lib_exceptionNumber10() noreturn { Exceptions.handle(10); } export fn lib_exceptionNumber11() noreturn { Exceptions.handle(11); } export fn lib_exceptionNumber12() noreturn { Exceptions.handle(12); } export fn lib_exceptionNumber13() noreturn { Exceptions.handle(13); } export fn lib_exceptionNumber14() noreturn { Exceptions.handle(14); } export fn lib_exceptionNumber15() noreturn { Exceptions.handle(15); } const builtin = std.builtin; const format = Uart.format; const std = @import("std"); const symbols = @embedFile("symbols.txt"); extern var __bss_start: u8; extern var __bss_end: u8; extern var __debug_info_start: u8; extern var __debug_info_end: u8; extern var __debug_abbrev_start: u8; extern var __debug_abbrev_end: u8; extern var __debug_str_start: u8; extern var __debug_str_end: u8; extern var __debug_line_start: u8; extern var __debug_line_end: u8; extern var __debug_ranges_start: u8; extern var __debug_ranges_end: u8; pub const log = Uart.log; pub const ram_u32 = @intToPtr(*volatile [4096]u32, 0x20000000); pub const I2c0 = I2cInstance(0x40003000); pub const I2c1 = I2cInstance(0x40004000); pub const Timer0 = TimerInstance(0x40008000); pub const Timer1 = TimerInstance(0x40009000); pub const Timer2 = TimerInstance(0x4000a000); }; pub const typical = struct { pub const Adc = lib.Adc; pub const assert = std.debug.assert; pub const Bss = lib.Bss; pub const builtin = std.builtin; pub const ClockManagement = lib.ClockManagement; pub const Exceptions = lib.Exceptions; pub const Ficr = lib.Ficr; pub const format = Uart.format; pub const Gpio = lib.Gpio; pub const Gpiote = lib.Gpiote; pub const I2c0 = lib.I2c0; pub const lib_basics = lib; pub const log = Uart.log; pub const math = std.math; pub const mem = std.mem; pub const LedMatrix = lib.LedMatrix; pub const panic = lib.panic; pub const panicf = lib.panicf; pub const Power = lib.Power; pub const Ppi = lib.Ppi; pub const std = @import("std"); pub const SystemControlBlock = lib.SystemControlBlock; pub const Temperature = lib.Temperature; pub const Terminal = lib.Terminal; pub const TimeKeeper = lib.TimeKeeper; pub const Timer0 = lib.Timer0; pub const Timer1 = lib.Timer1; pub const Timer2 = lib.Timer2; pub const typicalVectorTable = lib.typicalVectorTable; pub const Uart = lib.Uart; pub const Uicr = lib.Uicr; pub const Wdt = lib.Wdt; };
lib_basics.zig
const std = @import("std"); const iup = @import("iup.zig"); const c = @cImport({ @cInclude("iup.h"); }); const trait = std.meta.trait; pub const Handle = c.Ihandle; pub const NativeCallbackFn = c.Icallback; pub const consts = struct { pub const IUP_ERROR = c.IUP_ERROR; pub const IUP_NOERROR = c.IUP_NOERROR; pub const IUP_OPENED = c.IUP_OPENED; pub const IUP_INVALID = c.IUP_INVALID; pub const IUP_INVALID_ID = c.IUP_INVALID_ID; pub const IUP_IGNORE = c.IUP_IGNORE; pub const IUP_DEFAULT = c.IUP_DEFAULT; pub const IUP_CLOSE = c.IUP_CLOSE; pub const IUP_CONTINUE = c.IUP_CONTINUE; pub const IUP_CENTER = c.IUP_CENTER; pub const IUP_LEFT = c.IUP_LEFT; pub const IUP_RIGHT = c.IUP_RIGHT; pub const IUP_MOUSEPOS = c.IUP_MOUSEPOS; pub const IUP_CURRENT = c.IUP_CURRENT; pub const IUP_CENTERPARENT = c.IUP_CENTERPARENT; pub const IUP_LEFTPARENT = c.IUP_LEFTPARENT; pub const IUP_RIGHTPARENT = c.IUP_RIGHTPARENT; pub const IUP_TOP = c.IUP_TOP; pub const IUP_BOTTOM = c.IUP_BOTTOM; pub const IUP_TOPPARENT = c.IUP_TOPPARENT; pub const IUP_BOTTOMPARENT = c.IUP_BOTTOMPARENT; pub const IUP_BUTTON1 = c.IUP_BUTTON1; pub const IUP_BUTTON2 = c.IUP_BUTTON2; pub const IUP_BUTTON3 = c.IUP_BUTTON3; pub const IUP_BUTTON4 = c.IUP_BUTTON4; pub const IUP_BUTTON5 = c.IUP_BUTTON5; }; pub inline fn getHandle(handle: anytype) *Handle { const HandleType = @TypeOf(handle); const typeInfo = @typeInfo(HandleType); if (HandleType == iup.Element) { return handle.getHandle(); } else if (typeInfo == .Pointer and @typeInfo(typeInfo.Pointer.child) == .Opaque) { return @ptrCast(*Handle, handle); } else { @compileError("Invalid handle type " ++ @typeName(@TypeOf(handle))); } } pub inline fn fromHandle(comptime T: type, handle: *Handle) *T { return @ptrCast(*T, handle); } pub inline fn fromHandleName(comptime T: type, handle_name: [:0]const u8) ?*T { var handle = c.IupGetHandle(toCStr(handle_name)); if (handle == null) return null; return fromHandle(T, handle.?); } pub inline fn toCStr(value: ?[:0]const u8) [*c]const u8 { if (value) |ptr| { return @ptrCast([*c]const u8, ptr); } else { return null; } } pub inline fn fromCStr(value: [*c]const u8) [:0]const u8 { return std.mem.sliceTo(value, 0); } pub inline fn create(comptime T: type) ?*T { return @ptrCast(*T, c.IupCreate(T.CLASS_NAME)); } pub inline fn create_image(comptime T: type, width: i32, height: i32, imgdata: ?[]const u8) ?*T { // From original C code: (*void)-1 const SENTINEL = std.math.maxInt(usize); var params = [_]usize{ @intCast(usize, width), @intCast(usize, height), if (imgdata) |valid| @ptrToInt(valid.ptr) else SENTINEL, SENTINEL }; return @ptrCast(*T, c.IupCreatev(T.CLASS_NAME, @ptrCast([*c]?*anyopaque, &params))); } pub inline fn destroy(element: anytype) void { c.IupDestroy(getHandle(element)); } pub inline fn open() iup.Error!void { const ret = c.IupOpen(null, null); if (ret == c.IUP_ERROR) return iup.Error.OpenFailed; c.IupImageLibOpen(); } pub inline fn beginLoop() void { // Discards the result, // Zig error is stored in MainLoop struct _ = c.IupMainLoop(); } pub inline fn exitLoop() void { c.IupExitLoop(); } pub inline fn close() void { c.IupClose(); } pub inline fn showVersion() void { c.IupVersionShow(); } pub inline fn setHandle(handle: anytype, name: [:0]const u8) void { _ = c.IupSetHandle(toCStr(name), getHandle(handle)); } pub inline fn getStrAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) [:0]const u8 { validateIds(ids_tuple); var ret = blk: { if (ids_tuple.len == 0) { break :blk c.IupGetAttribute(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { break :blk c.IupGetAttributeId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { break :blk c.IupGetAttributeId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } }; if (ret == null) return ""; return fromCStr(ret); } pub inline fn setStrAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: ?[:0]const u8) void { validateIds(ids_tuple); if (ids_tuple.len == 0) { c.IupSetStrAttribute(getHandle(handle), getAttribute(attribute), toCStr(value)); } else if (ids_tuple.len == 1) { c.IupSetStrAttributeId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", toCStr(value)); } else { c.IupSetStrAttributeId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", toCStr(value)); } } pub inline fn clearAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) void { validateIds(ids_tuple); // Global callbacks have null handler const handlePtr: ?*Handle = if (@TypeOf(handle) == void) null else getHandle(handle); if (ids_tuple.len == 0) { c.IupSetAttribute(handlePtr, getAttribute(attribute), null); } else if (ids_tuple.len == 1) { c.IupSetAttributeId(handlePtr, getAttribute(attribute), ids_tuple.@"0", null); } else { c.IupSetAttributeId2(handlePtr, getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", null); } } pub inline fn getBoolAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) bool { validateIds(ids_tuple); var ret = blk: { if (ids_tuple.len == 0) { break :blk c.IupGetInt(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { break :blk c.IupGetIntId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { break :blk c.IupGetIntId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } }; return ret == 1; } pub inline fn setBoolAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: bool) void { validateIds(ids_tuple); const str = if (value) "YES" else "NO"; if (ids_tuple.len == 0) { c.IupSetStrAttribute(getHandle(handle), getAttribute(attribute), str); } else if (ids_tuple.len == 1) { c.IupSetStrAttributeId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", str); } else { c.IupSetStrAttributeId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", str); } } pub inline fn getIntAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) i32 { validateIds(ids_tuple); if (ids_tuple.len == 0) { return c.IupGetInt(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { return c.IupGetIntId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { return c.IupGetIntId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } } pub inline fn setIntAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: i32) void { validateIds(ids_tuple); if (ids_tuple.len == 0) { c.IupSetInt(getHandle(handle), getAttribute(attribute), value); } else if (ids_tuple.len == 1) { c.IupSetIntId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", value); } else { c.IupSetIntId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", value); } } pub inline fn getFloatAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) f32 { validateIds(ids_tuple); if (ids_tuple.len == 0) { return c.IupGetFloat(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { return c.IupGetFloatId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { return c.IupGetFloatId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } } pub inline fn setFloatAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: f32) void { validateIds(ids_tuple); if (ids_tuple.len == 0) { c.IupSetFloat(getHandle(handle), getAttribute(attribute), value); } else if (ids_tuple.len == 1) { c.IupSetFloatId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", value); } else { c.IupSetFloatId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", value); } } pub inline fn getDoubleAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) f64 { validateIds(ids_tuple); if (ids_tuple.len == 0) { return c.IupGetDouble(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { return c.IupGetDouble(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { return c.IupGetDoubleId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } } pub inline fn setDoubleAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: f64) void { validateIds(ids_tuple); if (ids_tuple.len == 0) { c.IupSetDouble(getHandle(handle), getAttribute(attribute), value); } else if (ids_tuple.len == 1) { c.IupSetDoubleId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", value); } else { c.IupSetDoubleId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", value); } } pub inline fn getHandleAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) ?*Handle { validateIds(ids_tuple); if (ids_tuple.len == 0) { return c.IupGetAttributeHandle(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { return c.IupGetAttributeHandleId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { return c.IupGetAttributeHandleId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } } pub inline fn setHandleAttribute(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: anytype) void { if (ids_tuple.len == 0) { c.IupSetAttributeHandle(getHandle(handle), getAttribute(attribute), getHandle(value)); } else if (ids_tuple.len == 1) { c.IupSetAttributeHandleId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", getHandle(value)); } else { c.IupSetAttributeHandleId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", getHandle(value)); } } pub inline fn getPtrAttribute(comptime T: type, handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) ?*T { validateIds(ids_tuple); var ret = blk: { if (ids_tuple.len == 0) { break :blk c.IupGetAttribute(getHandle(handle), getAttribute(attribute)); } else if (ids_tuple.len == 1) { break :blk c.IupGetAttributeId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0"); } else { break :blk c.IupGetAttributeId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1"); } }; if (ret == null) return null; return @ptrCast(*T, ret); } pub inline fn setPtrAttribute(comptime T: type, handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, value: ?*T) void { validateIds(ids_tuple); if (value) |ptr| { if (ids_tuple.len == 0) { c.IupSetAttribute(getHandle(handle), getAttribute(attribute), @ptrCast([*c]const u8, ptr)); } else if (ids_tuple.len == 1) { c.IupSetAttributeId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", @ptrCast([*c]const u8, ptr)); } else { c.IupSetAttributeId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", @ptrCast([*c]const u8, ptr)); } } else { clearAttribute(handle, attribute, ids_tuple); } } pub inline fn validateHandle(native_type: iup.NativeType, handle: anytype) !void { const ElementType = std.meta.Child(@TypeOf(handle)); if (ElementType.NATIVE_TYPE != native_type) return iup.Error.InvalidElement; } pub fn getRgb(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype) iup.Rgb { validateIds(ids_tuple); var r: u8 = 0; var g: u8 = 0; var b: u8 = 0; var a: u8 = 0; if (ids_tuple.len == 0) { c.IupGetRGBA(getHandle(handle), getAttribute(attribute), &r, &g, &b, &a); } else if (ids_tuple.len == 1) { c.IupGetRGBId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", &r, &g, &b); a = 255; } else { c.IupGetRGBId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", &r, &g, &b); a = 255; } return .{ .r = r, .g = g, .b = b, .a = if (a == 255) null else a, }; } pub inline fn setRgb(handle: anytype, attribute: [:0]const u8, ids_tuple: anytype, arg: iup.Rgb) void { validateIds(ids_tuple); if (arg.alias) |alias| { setStrAttribute(handle, attribute, ids_tuple, alias); } else { if (ids_tuple.len == 0) { if (arg.a == null) { c.IupSetRGB(getHandle(handle), getAttribute(attribute), arg.r, arg.g, arg.b); } else { c.IupSetRGBA(getHandle(handle), getAttribute(attribute), arg.r, arg.g, arg.b, arg.a.?); } } else if (ids_tuple.len == 1) { c.IupSetRGBId(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", arg.r, arg.g, arg.b); } else { c.IupSetRGBId2(getHandle(handle), getAttribute(attribute), ids_tuple.@"0", ids_tuple.@"1", arg.r, arg.g, arg.b); } } } pub inline fn setNativeCallback(handle: anytype, attribute: [:0]const u8, callback: NativeCallbackFn) void { if (@TypeOf(handle) == void) { // Global callback _ = c.IupSetFunction(attribute, callback); } else { _ = c.IupSetCallback(getHandle(handle), attribute, callback); } } pub inline fn setCallbackStoreAttribute(comptime TCallback: type, handle: anytype, attribute: [:0]const u8, value: ?TCallback) void { if (value) |ptr| { // Global callbacks have null handler const handlePtr: ?*Handle = if (@TypeOf(handle) == void) null else getHandle(handle); c.IupSetAttribute(handlePtr, toCStr(attribute), @ptrCast([*c]const u8, ptr)); } else { clearAttribute(handle, attribute, .{}); } } pub inline fn getCallbackStoreAttribute(comptime TCallback: type, handle: anytype, attribute: [:0]const u8) ?TCallback { // Global callbacks have null handler const handlePtr: ?*Handle = if (@TypeOf(handle) == void) null else getHandle(handle); var ret = c.IupGetAttribute(handlePtr, toCStr(attribute)); if (ret == null) return null; return @ptrCast(TCallback, ret); } pub inline fn showXY(handle: anytype, x: iup.DialogPosX, y: iup.DialogPosY) iup.Error!void { const ret = c.IupShowXY(getHandle(handle), @enumToInt(x), @enumToInt(y)); if (ret == c.IUP_ERROR) return iup.Error.InvalidAction; } pub inline fn show(handle: anytype) iup.Error!void { const ret = c.IupShow(getHandle(handle)); if (ret == c.IUP_ERROR) return iup.Error.InvalidAction; } pub inline fn map(handle: anytype) iup.Error!void { const ret = c.IupMap(getHandle(handle)); if (ret == c.IUP_ERROR) return iup.Error.InvalidAction; } pub inline fn popup(handle: anytype, x: iup.DialogPosX, y: iup.DialogPosY) iup.Error!void { const ret = c.IupPopup(getHandle(handle), @enumToInt(x), @enumToInt(y)); if (ret == c.IUP_ERROR) return iup.Error.InvalidAction; } pub inline fn hide(handle: anytype) void { //Returns: IUP_NOERROR always. _ = c.IupHide(getHandle(handle)); } pub inline fn getDialog(handle: anytype) ?*iup.Dialog { if (c.IupGetDialog(getHandle(handle))) |value| { return fromHandle(iup.Dialog, value); } else { return null; } } pub inline fn getDialogChild(handle: anytype, byName: [:0]const u8) ?iup.Element { var child = c.IupGetDialogChild(getHandle(handle), toCStr(byName)) orelse return null; const className = c.IupGetClassName(child); return iup.Element.fromClassName(fromCStr(className), child); } pub inline fn append(parent: anytype, element: anytype) iup.Error!void { const ret = c.IupAppend(getHandle(parent), getHandle(element)); if (ret == null) return iup.Error.InvalidChild; } pub inline fn refresh(handle: anytype) void { c.IupRefresh(getHandle(handle)); } pub inline fn getChildCount(handle: anytype) i32 { return c.IupGetChildCount(getHandle(handle)); } pub inline fn getChild(handle: anytype, index: i32) ?*Handle { return c.IupGetChild(getHandle(handle), index); } pub inline fn getClassName(handle: anytype) [:0]const u8 { return fromCStr(c.IupGetClassName(getHandle(handle))); } pub fn intIntToString(buffer: []u8, x: i32, y: i32, comptime separator: u8) [:0]const u8 { var fbs = std.io.fixedBufferStream(buffer); std.fmt.format(fbs.writer(), "{}{c}{}\x00", .{ x, separator, y }) catch unreachable; return buffer[0 .. fbs.pos - 1 :0]; } pub fn strToIntInt(value: []const u8, separator: u8, a: *?i32, b: *?i32) void { const delimiter = [_]u8{separator}; var iterator = std.mem.split(u8, value, delimiter[0..]); if (iterator.next()) |part| { if (std.fmt.parseInt(i32, part, 10)) |int| { a.* = int; } else |_| {} } if (iterator.next()) |part| { if (std.fmt.parseInt(i32, part, 10)) |int| { b.* = int; } else |_| {} } } pub fn convertLinColToPos(handle: anytype, lin: i32, col: i32) ?i32 { const UNINITALIZED = std.math.minInt(i32); var pos: i32 = UNINITALIZED; c.IupTextConvertLinColToPos(getHandle(handle), lin, col, &pos); if (pos == UNINITALIZED) { return null; } else { return pos; } } pub fn convertPosToLinCol(handle: anytype, pos: i32) ?iup.LinColPos { const UNDEFINED = std.math.minInt(i32); var lin: i32 = UNDEFINED; var col: i32 = UNDEFINED; c.IupTextConvertPosToLinCol(getHandle(handle), pos, &lin, &col); if (lin == UNDEFINED or col == UNDEFINED) { return null; } else { return iup.LinColPos{ .lin = lin, .col = col }; } } fn validateIds(ids_tuple: anytype) void { if (comptime !trait.isTuple(@TypeOf(ids_tuple)) or ids_tuple.len > 2) @compileError("Expected a tuple with 0, 1 or 2 values"); } inline fn getAttribute(value: [:0]const u8) [*c]const u8 { //pure numbers are used as attributes in IupList and IupMatrix //translate them into IDVALUE. const IDVALUE = "IDVALUE"; const EMPTY = ""; if (std.mem.eql(u8, value, IDVALUE)) { return @ptrCast([*c]const u8, EMPTY); } else { return toCStr(value); } }
src/interop.zig
const std = @import("std"); const sqlite = @import("sqlite"); const manage_main = @import("main.zig"); const libpcre = @import("libpcre"); const Context = manage_main.Context; const log = std.log.scoped(.afind); const VERSION = "0.0.1"; const HELPTEXT = \\ afind: execute queries on the awtfdb index \\ \\ usage: \\ afind [options...] query \\ \\ options: \\ -h prints this help and exits \\ -V prints version and exits \\ -L, --link creates a temporary folder with \\ symlinks to the resulting files from \\ the query. deletes the folder on \\ CTRL-C. \\ (linux only) \\ \\ query examples: \\ afind 'mytag1' \\ search all files with mytag1 \\ afind 'mytag1 mytag2' \\ search all files with mytag1 AND mytag2 \\ afind 'mytag1 | mytag2' \\ search all files with mytag1 OR mytag2 \\ afind '"mytag1" | "mytag2"' \\ search all files with mytag1 OR mytag2 (raw tag syntax) \\ not all characters are allowed in non-raw tag syntax \\ afind '"mytag1" -"mytag2"' \\ afind 'mytag1 -mytag2' \\ search all files with mytag1 but they do NOT have mytag2 ; pub fn main() anyerror!void { const rc = sqlite.c.sqlite3_config(sqlite.c.SQLITE_CONFIG_LOG, manage_main.sqliteLog, @as(?*anyopaque, null)); if (rc != sqlite.c.SQLITE_OK) { std.log.err("failed to configure: {d} '{s}'", .{ rc, sqlite.c.sqlite3_errstr(rc), }); return error.ConfigFail; } var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var allocator = gpa.allocator(); var args_it = std.process.args(); _ = args_it.skip(); const StringList = std.ArrayList([]const u8); const Args = struct { help: bool = false, version: bool = false, link: bool = false, query: StringList, pub fn deinit(self: *@This()) void { self.query.deinit(); } }; var given_args = Args{ .query = StringList.init(allocator) }; defer given_args.deinit(); var arg_state: enum { None, MoreTags } = .None; while (args_it.next()) |arg| { switch (arg_state) { .None => {}, .MoreTags => { try given_args.query.append(arg); // once in MoreTags state, all next arguments are part // of the query. continue; }, } if (std.mem.eql(u8, arg, "-h")) { given_args.help = true; } else if (std.mem.eql(u8, arg, "-V")) { given_args.version = true; } else if (std.mem.eql(u8, arg, "-L") or std.mem.eql(u8, arg, "--link")) { given_args.link = true; } else { arg_state = .MoreTags; try given_args.query.append(arg); } } if (given_args.help) { std.debug.print(HELPTEXT, .{}); return; } else if (given_args.version) { std.debug.print("ainclude {s}\n", .{VERSION}); return; } if (given_args.query.items.len == 0) { std.log.err("query is a required argument", .{}); return error.MissingQuery; } const query = try std.mem.join(allocator, " ", given_args.query.items); defer allocator.free(query); var ctx = Context{ .home_path = null, .args_it = undefined, .stdout = undefined, .db = null, .allocator = allocator, }; defer ctx.deinit(); try ctx.loadDatabase(.{}); // afind tag (all files with tag) // afind 'tag1 tag2' (tag1 AND tag2) // afind 'tag1 | tag2' (tag1 OR tag2) // afind '(tag1 | tag2) tag3' (tag1 OR tag2, AND tag3) // afind '"tag3 2"' ("tag3 2" is a tag, actually) var giver = try SqlGiver.init(); defer giver.deinit(); const wrapped_result = try giver.giveMeSql(allocator, query); defer wrapped_result.deinit(); const result = switch (wrapped_result) { .Ok => |ok_body| ok_body, .Error => |error_body| { log.err("error at character {d}: {s}", .{ error_body.character, error_body.error_type }); return error.ParseErrorHappened; }, }; var resolved_tag_cores = std.ArrayList(i64).init(allocator); defer resolved_tag_cores.deinit(); for (result.tags) |tag_text| { const maybe_tag = try ctx.fetchNamedTag(tag_text, "en"); if (maybe_tag) |tag| { try resolved_tag_cores.append(tag.core.id); } else { log.err("unknown tag '{s}'", .{tag_text}); return error.UnknownTag; } } var stmt = try ctx.db.?.prepareDynamic(result.query); defer stmt.deinit(); log.debug("generated query: {s}", .{result.query}); log.debug("found tag cores: {any}", .{resolved_tag_cores.items}); var it = try stmt.iterator(i64, resolved_tag_cores.items); var stdout = std.io.getStdOut(); var stderr = std.io.getStdErr(); var returned_files = std.ArrayList(Context.File).init(allocator); defer { for (returned_files.items) |file| file.deinit(); returned_files.deinit(); } while (try it.next(.{})) |file_hash| { var file = (try ctx.fetchFile(file_hash)).?; // if we use --link, we need the full list of files to make // symlinks out of, so this block doesn't own the lifetime of the // file entity anymore. try returned_files.append(file); try stdout.writer().print("{s}", .{file.local_path}); try file.printTagsTo(allocator, stderr.writer()); try stdout.writer().print("\n", .{}); } log.info("found {d} files", .{returned_files.items.len}); if (given_args.link) { var PREFIX = "/tmp/awtf/afind-"; var template = "/tmp/awtf/afind-XXXXXXXXXX"; var tmp_path: [template.len]u8 = undefined; std.mem.copy(u8, &tmp_path, PREFIX); var fill_here = tmp_path[PREFIX.len..]; const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp())); var r = std.rand.DefaultPrng.init(seed); for (fill_here) |*el| { const ascii_idx = @intCast(u8, r.random().uintLessThan(u5, 24)); const letter: u8 = @as(u8, 65) + ascii_idx; el.* = letter; } log.debug("attempting to create folder '{s}'", .{tmp_path}); std.fs.makeDirAbsolute("/tmp/awtf") catch |err| if (err != error.PathAlreadyExists) return err else {}; try std.fs.makeDirAbsolute(&tmp_path); var tmp = try std.fs.openDirAbsolute(&tmp_path, .{}); defer { tmp.deleteTree(&tmp_path) catch |err| { log.err( "error happened while deleting '{s}': {s}, ignoring.", .{ &tmp_path, @errorName(err) }, ); }; tmp.close(); } for (returned_files.items) |file| { const joined_symlink_path = try std.fs.path.join(allocator, &[_][]const u8{ &tmp_path, std.fs.path.basename(file.local_path), }); defer allocator.free(joined_symlink_path); log.info("symlink '{s}' to '{s}'", .{ file.local_path, joined_symlink_path }); try tmp.symLink(file.local_path, joined_symlink_path, .{}); } log.info("successfully created symlinked folder at", .{}); try stdout.writer().print("{s}\n", .{tmp_path}); const self_pipe_fds = try std.os.pipe(); maybe_self_pipe = .{ .reader = .{ .handle = self_pipe_fds[0] }, .writer = .{ .handle = self_pipe_fds[1] }, }; defer { maybe_self_pipe.?.reader.close(); maybe_self_pipe.?.writer.close(); } // configure signal handler that's going to push data to the selfpipe var mask = std.os.empty_sigset; std.os.linux.sigaddset(&mask, std.os.SIG.TERM); std.os.linux.sigaddset(&mask, std.os.SIG.INT); var sa = std.os.Sigaction{ .handler = .{ .sigaction = signal_handler }, .mask = mask, .flags = 0, }; try std.os.sigaction(std.os.SIG.TERM, &sa, null); try std.os.sigaction(std.os.SIG.INT, &sa, null); const PollFdList = std.ArrayList(std.os.pollfd); var sockets = PollFdList.init(allocator); defer sockets.deinit(); try sockets.append(std.os.pollfd{ .fd = maybe_self_pipe.?.reader.handle, .events = std.os.POLL.IN, .revents = 0, }); // we don't need to do 'while (true) { sleep(1000); }' because // we can poll on the selfpipe trick! log.info("press ctrl-c to delete the temporary folder...", .{}); var run: bool = true; while (run) { log.debug("polling for signals...", .{}); const available = try std.os.poll(sockets.items, -1); try std.testing.expect(available > 0); for (sockets.items) |pollfd| { log.debug("fd {d} has revents {d}", .{ pollfd.fd, pollfd.revents }); if (pollfd.revents == 0) continue; if (pollfd.fd == maybe_self_pipe.?.reader.handle) { while (run) { const signal_data = maybe_self_pipe.?.reader.reader().readStruct(SignalData) catch |err| switch (err) { error.EndOfStream => break, else => return err, }; log.info("exiting! with signal {d}", .{signal_data.signal}); run = false; } } } } } } const Pipe = struct { reader: std.fs.File, writer: std.fs.File, }; var zig_segfault_handler: fn (i32, *const std.os.siginfo_t, ?*const anyopaque) callconv(.C) void = undefined; var maybe_self_pipe: ?Pipe = null; const SignalData = extern struct { signal: c_int, info: std.os.siginfo_t, uctx: ?*const anyopaque, }; const SignalList = std.ArrayList(SignalData); fn signal_handler( signal: c_int, info: *const std.os.siginfo_t, uctx: ?*const anyopaque, ) callconv(.C) void { if (maybe_self_pipe) |self_pipe| { const signal_data = SignalData{ .signal = signal, .info = info.*, .uctx = uctx, }; self_pipe.writer.writer().writeStruct(signal_data) catch return; } } pub const SqlGiver = struct { pub const ErrorType = enum { UnexpectedCharacter, }; const Result = union(enum) { Error: struct { character: usize, error_type: ErrorType, }, Ok: struct { allocator: std.mem.Allocator, query: []const u8, tags: [][]const u8, }, pub fn deinit(self: @This()) void { switch (self) { .Ok => |ok_body| { ok_body.allocator.free(ok_body.query); ok_body.allocator.free(ok_body.tags); }, .Error => {}, } } }; operators: [5]libpcre.Regex, const Self = @This(); pub const CaptureType = enum(usize) { Or = 0, Not, And, Tag, RawTag }; pub fn init() !Self { var or_operator = try libpcre.Regex.compile("( +)?\\|( +)?", .{}); var not_operator = try libpcre.Regex.compile("( +)?-( +)?", .{}); var and_operator = try libpcre.Regex.compile(" +", .{}); var tag_regex = try libpcre.Regex.compile("[a-zA-Z-_0-9:;&\\*]+", .{}); var raw_tag_regex = try libpcre.Regex.compile("\".*?\"", .{}); return Self{ .operators = [_]libpcre.Regex{ or_operator, not_operator, and_operator, tag_regex, raw_tag_regex, } }; } pub fn deinit(self: Self) void { for (self.operators) |regex| regex.deinit(); } pub fn giveMeSql( self: Self, allocator: std.mem.Allocator, query: []const u8, ) (libpcre.Regex.CompileError || libpcre.Regex.ExecError)!Result { var index: usize = 0; var list = std.ArrayList(u8).init(allocator); defer list.deinit(); var tags = std.ArrayList([]const u8).init(allocator); defer tags.deinit(); if (query.len == 0) { try list.writer().print("select distinct file_hash from tag_files", .{}); } else { try list.writer().print("select file_hash from tag_files where", .{}); } while (true) { // try to match on every regex with that same order: // tag_regex, raw_tag_regex, or_operator, and_operator // if any of those match first, emit the relevant SQL for that // type of tag. // TODO paren support "(" and ")" const query_slice = query[index..]; if (query_slice.len == 0) break; var maybe_captures: ?[]?libpcre.Capture = null; var captured_regex_index: ?CaptureType = null; for (self.operators) |regex, current_regex_index| { log.debug("try regex {d} on query '{s}'", .{ current_regex_index, query_slice }); maybe_captures = try regex.captures(allocator, query_slice, .{}); captured_regex_index = @intToEnum(CaptureType, current_regex_index); log.debug("raw capture? {any}", .{maybe_captures}); if (maybe_captures) |captures| { const capture = captures[0].?; if (capture.start != 0) { allocator.free(captures); maybe_captures = null; } else { log.debug("captured!!! {any}", .{maybe_captures}); break; } } } if (maybe_captures) |captures| { defer allocator.free(captures); const full_match = captures[0].?; var match_text = query[index + full_match.start .. index + full_match.end]; index += full_match.end; switch (captured_regex_index.?) { .Or => try list.writer().print(" or", .{}), .Not => { // this edge case is hit when queries start with '-TAG' // since we already printed a select, we need to add // some kind of condition before it's a syntax error if (tags.items.len == 0) { try list.writer().print(" true", .{}); } try list.writer().print(" except", .{}); try list.writer().print(" select file_hash from tag_files where", .{}); }, .And => { try list.writer().print(" intersect", .{}); try list.writer().print(" select file_hash from tag_files where", .{}); }, .Tag, .RawTag => { try list.writer().print(" core_hash = ?", .{}); // if we're matching raw_tag_regex (tags that have // quotemarks around them), index forward and backward // so that we don't pass those quotemarks to query // processors. if (captured_regex_index.? == .RawTag) { match_text = match_text[1 .. match_text.len - 1]; } try tags.append(match_text); }, } } else { return Result{ .Error = .{ .character = index, .error_type = .UnexpectedCharacter } }; } } return Result{ .Ok = .{ .allocator = allocator, .query = list.toOwnedSlice(), .tags = tags.toOwnedSlice(), } }; } }; test "sql parser" { const allocator = std.testing.allocator; var giver = try SqlGiver.init(); defer giver.deinit(); const wrapped_result = try giver.giveMeSql(allocator, "a b | \"cd\"|e"); defer wrapped_result.deinit(); const result = wrapped_result.Ok; try std.testing.expectEqualStrings( "select file_hash from tag_files where core_hash = ? intersect select file_hash from tag_files where core_hash = ? or core_hash = ? or core_hash = ?", result.query, ); try std.testing.expectEqual(@as(usize, 4), result.tags.len); const expected_tags = .{ "a", "b", "cd", "e" }; inline for (expected_tags) |expected_tag, index| { try std.testing.expectEqualStrings(expected_tag, result.tags[index]); } } test "sql parser errors" { const allocator = std.testing.allocator; var giver = try SqlGiver.init(); defer giver.deinit(); const wrapped_result = try giver.giveMeSql(allocator, "a \"cd"); defer wrapped_result.deinit(); const error_data = wrapped_result.Error; try std.testing.expectEqual(@as(usize, 2), error_data.character); try std.testing.expectEqual(SqlGiver.ErrorType.UnexpectedCharacter, error_data.error_type); } test "sql parser batch test" { const allocator = std.testing.allocator; var ctx = try manage_main.makeTestContext(); defer ctx.deinit(); var giver = try SqlGiver.init(); defer giver.deinit(); const TEST_DATA = .{ .{ "a b c", .{ "a", "b", "c" } }, .{ "a bc d", .{ "a", "bc", "d" } }, .{ "a \"bc\" d", .{ "a", "bc", "d" } }, .{ "a \"b c\" d", .{ "a", "b c", "d" } }, .{ "a \"b c\" -d", .{ "a", "b c", "d" } }, .{ "-a \"b c\" d", .{ "a", "b c", "d" } }, .{ "-a -\"b c\" -d", .{ "a", "b c", "d" } }, .{ "-d", .{"d"} }, }; inline for (TEST_DATA) |test_case, test_case_index| { const input_text = test_case.@"0"; const expected_tags = test_case.@"1"; const wrapped_result = try giver.giveMeSql(allocator, input_text); defer wrapped_result.deinit(); const result = wrapped_result.Ok; var stmt = ctx.db.?.prepareDynamic(result.query) catch |err| { const detailed_error = ctx.db.?.getDetailedError(); std.debug.panic( "unable to prepare statement test case {d} '{s}', error: {}, message: {s}\n", .{ test_case_index, result.query, err, detailed_error }, ); }; defer stmt.deinit(); try std.testing.expectEqual(@as(usize, expected_tags.len), result.tags.len); inline for (expected_tags) |expected_tag, index| { try std.testing.expectEqualStrings(expected_tag, result.tags[index]); } } }
src/find_main.zig
//-------------------------------------------------------------------------------- // Section: Types (1) //-------------------------------------------------------------------------------- pub const WSL_DISTRIBUTION_FLAGS = enum(u32) { NONE = 0, ENABLE_INTEROP = 1, APPEND_NT_PATH = 2, ENABLE_DRIVE_MOUNTING = 4, _, pub fn initFlags(o: struct { NONE: u1 = 0, ENABLE_INTEROP: u1 = 0, APPEND_NT_PATH: u1 = 0, ENABLE_DRIVE_MOUNTING: u1 = 0, }) WSL_DISTRIBUTION_FLAGS { return @intToEnum(WSL_DISTRIBUTION_FLAGS, (if (o.NONE == 1) @enumToInt(WSL_DISTRIBUTION_FLAGS.NONE) else 0) | (if (o.ENABLE_INTEROP == 1) @enumToInt(WSL_DISTRIBUTION_FLAGS.ENABLE_INTEROP) else 0) | (if (o.APPEND_NT_PATH == 1) @enumToInt(WSL_DISTRIBUTION_FLAGS.APPEND_NT_PATH) else 0) | (if (o.ENABLE_DRIVE_MOUNTING == 1) @enumToInt(WSL_DISTRIBUTION_FLAGS.ENABLE_DRIVE_MOUNTING) else 0) ); } }; pub const WSL_DISTRIBUTION_FLAGS_NONE = WSL_DISTRIBUTION_FLAGS.NONE; pub const WSL_DISTRIBUTION_FLAGS_ENABLE_INTEROP = WSL_DISTRIBUTION_FLAGS.ENABLE_INTEROP; pub const WSL_DISTRIBUTION_FLAGS_APPEND_NT_PATH = WSL_DISTRIBUTION_FLAGS.APPEND_NT_PATH; pub const WSL_DISTRIBUTION_FLAGS_ENABLE_DRIVE_MOUNTING = WSL_DISTRIBUTION_FLAGS.ENABLE_DRIVE_MOUNTING; //-------------------------------------------------------------------------------- // Section: Functions (7) //-------------------------------------------------------------------------------- pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslIsDistributionRegistered( distributionName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslRegisterDistribution( distributionName: ?[*:0]const u16, tarGzFilename: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslUnregisterDistribution( distributionName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslConfigureDistribution( distributionName: ?[*:0]const u16, defaultUID: u32, wslDistributionFlags: WSL_DISTRIBUTION_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslGetDistributionConfiguration( distributionName: ?[*:0]const u16, distributionVersion: ?*u32, defaultUID: ?*u32, wslDistributionFlags: ?*WSL_DISTRIBUTION_FLAGS, defaultEnvironmentVariables: ?*?*?PSTR, defaultEnvironmentVariableCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslLaunchInteractive( distributionName: ?[*:0]const u16, command: ?[*:0]const u16, useCurrentWorkingDirectory: BOOL, exitCode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "Api-ms-win-wsl-api-l1-1-0" fn WslLaunch( distributionName: ?[*:0]const u16, command: ?[*:0]const u16, useCurrentWorkingDirectory: BOOL, stdIn: ?HANDLE, stdOut: ?HANDLE, stdErr: ?HANDLE, process: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // 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 BOOL = @import("../foundation.zig").BOOL; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/subsystem_for_linux.zig
const std = @import("std"); const alka = @import("alka"); const gui = @import("gui.zig"); const game = @import("game.zig"); usingnamespace alka.log; pub const mlog = std.log.scoped(.app); pub const log_level: std.log.Level = .debug; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const callbacks = alka.Callbacks{ .update = game.update, .fixed = game.fupdate, .draw = game.draw, .close = game.close, }; try alka.init(&gpa.allocator, callbacks, 1024, 768, "App", 0, false); alka.setBackgroundColour(0.18, 0.18, 0.18); { try alka.getAssetManager().loadTexture(1, "assets/kenney_simplespace/ship_F.png"); const texture = try alka.getAssetManager().getTexture(1); texture.setFilter(.filter_nearest, .filter_nearest); } { try alka.getAssetManager().loadTexture(2, "assets/kenney_simplespace/enemy_A.png"); const texture = try alka.getAssetManager().getTexture(2); texture.setFilter(.filter_nearest, .filter_nearest); } { try alka.getAssetManager().loadTexture(3, "assets/kenney_simplespace/station_B.png"); const texture = try alka.getAssetManager().getTexture(3); texture.setFilter(.filter_nearest, .filter_nearest); } { try alka.getAssetManager().loadTexture(10, "assets/station_heart.png"); const texture = try alka.getAssetManager().getTexture(10); texture.setFilter(.filter_nearest, .filter_nearest); } try alka.getAssetManager().loadFont(0, "assets/VCR_OSD_MONO.ttf", 128); const font = try alka.getAssetManager().getFont(0); font.texture.setFilter(.filter_nearest, .filter_nearest); var input = alka.getInput(); try input.bindMouse(.ButtonLeft); try input.bindKey(.A); try input.bindKey(.D); try input.bindKey(.W); try input.bindKey(.S); try input.bindKey(.LeftShift); try gui.init(); try game.open(); try game.run(); try gui.deinit(); try alka.deinit(); const leaked = gpa.deinit(); if (leaked) return error.Leak; }
examples/example_shooter_game/src/main.zig
const gllparser = @import("../gllparser/gllparser.zig"); const Error = gllparser.Error; const Parser = gllparser.Parser; const ParserContext = gllparser.Context; const Result = gllparser.Result; const NodeName = gllparser.NodeName; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const Context = []const u8; pub const Value = struct { /// The `input` string itself. value: []const u8, pub fn deinit(self: *const @This(), allocator: mem.Allocator) void { _ = self; _ = allocator; } }; /// Matches the literal `input` string. /// /// The `input` string must remain alive for as long as the `Literal` parser will be used. pub fn Literal(comptime Payload: type) type { return struct { parser: Parser(Payload, Value) = Parser(Payload, Value).init(parse, nodeName, null, null), input: Context, const Self = @This(); pub fn init(allocator: mem.Allocator, input: Context) !*Parser(Payload, Value) { const self = Self{ .input = input }; return try self.parser.heapAlloc(allocator, self); } pub fn initStack(input: Context) Self { return Self{ .input = input }; } pub fn nodeName(parser: *const Parser(Payload, Value), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 { _ = node_name_cache; const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("Literal"); v +%= std.hash_map.hashString(self.input); return v; } pub fn parse(parser: *const Parser(Payload, Value), in_ctx: *const ParserContext(Payload, Value)) callconv(.Async) !void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); if (ctx.offset >= ctx.src.len or !mem.startsWith(u8, ctx.src[ctx.offset..], ctx.input)) { // TODO(slimsag): include what literal was expected try ctx.results.add(Result(Value).initError(ctx.offset + 1, "expected literal")); return; } try ctx.results.add(Result(Value).init(ctx.offset + ctx.input.len, .{ .value = self.input })); return; } }; } test "literal" { nosuspend { const allocator = testing.allocator; const Payload = void; var ctx = try ParserContext(Payload, Value).init(allocator, "hello world", {}); defer ctx.deinit(); var want = "hello"; var l = try Literal(Payload).init(allocator, want); defer l.deinit(allocator, null); try l.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; defer first.deinit(ctx.allocator); try testing.expectEqual(Result(Value).init(want.len, .{ .value = "hello" }), first); try testing.expect(sub.next() == null); } }
src/combn/parser/literal.zig