code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const Blake = crypto.hash.blake2.Blake2b512; /// Blake2b variation of Ed25519 (EdDSA) signatures. pub const Ed25519Blake2b = struct { /// The underlying elliptic curve. pub const Curve = crypto.sign.Ed25519.Curve; /// Length (in bytes) of a seed required to create a key pair. pub const seed_length = 32; /// Length (in bytes) of a compressed secret key. pub const secret_length = 64; /// Length (in bytes) of a compressed public key. pub const public_length = 32; /// Length (in bytes) of a signature. pub const signature_length = 64; /// Length (in bytes) of optional random bytes, for non-deterministic signatures. pub const noise_length = 32; /// An Ed25519 key pair. pub const KeyPair = struct { /// Public part. public_key: [public_length]u8, /// Secret part. What we expose as a secret key is, under the hood, the concatenation of the seed and the public key. secret_key: [secret_length]u8, /// Derive a key pair from an optional secret seed. /// /// As in RFC 8032, an Ed25519 public key is generated by hashing /// the secret key using the Blake2b function, and interpreting the /// bit-swapped, clamped lower-half of the output as the secret scalar. /// /// For this reason, an EdDSA secret key is commonly called a seed, /// from which the actual secret is derived. pub fn create(seed: ?[seed_length]u8) !KeyPair { const ss = seed orelse ss: { var random_seed: [seed_length]u8 = undefined; crypto.random.bytes(&random_seed); break :ss random_seed; }; var az: [Blake.digest_length]u8 = undefined; var h = Blake.init(.{}); h.update(&ss); h.final(&az); const p = try Curve.basePoint.clampedMul(az[0..32].*); var sk: [secret_length]u8 = undefined; mem.copy(u8, &sk, &ss); const pk = p.toBytes(); mem.copy(u8, sk[seed_length..], &pk); return KeyPair{ .public_key = pk, .secret_key = sk }; } /// Create a KeyPair from a secret key. pub fn fromSecretKey(secret_key: [secret_length]u8) KeyPair { return KeyPair{ .secret_key = secret_key, .public_key = secret_key[seed_length..].*, }; } }; /// Sign a message using a key pair, and optional random noise. /// Having noise creates non-standard, non-deterministic signatures, /// but has been proven to increase resilience against fault attacks. pub fn sign(msg: []const u8, key_pair: KeyPair, noise: ?[noise_length]u8) ![signature_length]u8 { const seed = key_pair.secret_key[0..seed_length]; const public_key = key_pair.secret_key[seed_length..]; if (!mem.eql(u8, public_key, &key_pair.public_key)) { return error.KeyMismatch; } var az: [Blake.digest_length]u8 = undefined; var h = Blake.init(.{}); h.update(seed); h.final(&az); h = Blake.init(.{}); if (noise) |*z| { h.update(z); } h.update(az[32..]); h.update(msg); var nonce64: [64]u8 = undefined; h.final(&nonce64); const nonce = Curve.scalar.reduce64(nonce64); const r = try Curve.basePoint.mul(nonce); var sig: [signature_length]u8 = undefined; mem.copy(u8, sig[0..32], &r.toBytes()); mem.copy(u8, sig[32..], public_key); h = Blake.init(.{}); h.update(&sig); h.update(msg); var hram64: [Blake.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); var x = az[0..32]; Curve.scalar.clamp(x); const s = Curve.scalar.mulAdd(hram, x.*, nonce); mem.copy(u8, sig[32..], s[0..]); return sig; } /// Verify an Ed25519 signature given a message and a public key. /// Returns error.InvalidSignature is the signature verification failed. pub fn verify(sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8) !void { const r = sig[0..32]; const s = sig[32..64]; try Curve.scalar.rejectNonCanonical(s.*); try Curve.rejectNonCanonical(public_key); const a = try Curve.fromBytes(public_key); try a.rejectIdentity(); try Curve.rejectNonCanonical(r.*); const expected_r = try Curve.fromBytes(r.*); var h = Blake.init(.{}); h.update(r); h.update(&public_key); h.update(msg); var hram64: [Blake.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); const ah = try a.neg().mulPublic(hram); const sb_ah = (try Curve.basePoint.mulPublic(s.*)).add(ah); if (expected_r.sub(sb_ah).clearCofactor().rejectIdentity()) |_| { return error.InvalidSignature; } else |_| {} } /// A (signature, message, public_key) tuple for batch verification pub const BatchElement = struct { sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8, }; /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one pub fn verifyBatch(comptime count: usize, signature_batch: [count]BatchElement) !void { var r_batch: [count][32]u8 = undefined; var s_batch: [count][32]u8 = undefined; var a_batch: [count]Curve = undefined; var expected_r_batch: [count]Curve = undefined; for (signature_batch) |signature, i| { const r = signature.sig[0..32]; const s = signature.sig[32..64]; try Curve.scalar.rejectNonCanonical(s.*); try Curve.rejectNonCanonical(signature.public_key); const a = try Curve.fromBytes(signature.public_key); try a.rejectIdentity(); try Curve.rejectNonCanonical(r.*); const expected_r = try Curve.fromBytes(r.*); expected_r_batch[i] = expected_r; r_batch[i] = r.*; s_batch[i] = s.*; a_batch[i] = a; } var hram_batch: [count]Curve.scalar.CompressedScalar = undefined; for (signature_batch) |signature, i| { var h = Blake.init(.{}); h.update(&r_batch[i]); h.update(&signature.public_key); h.update(signature.msg); var hram64: [Blake.digest_length]u8 = undefined; h.final(&hram64); hram_batch[i] = Curve.scalar.reduce64(hram64); } var z_batch: [count]Curve.scalar.CompressedScalar = undefined; for (z_batch) |*z| { std.crypto.random.bytes(z[0..16]); mem.set(u8, z[16..], 0); } var zs_sum = Curve.scalar.zero; for (z_batch) |z, i| { const zs = Curve.scalar.mul(z, s_batch[i]); zs_sum = Curve.scalar.add(zs_sum, zs); } zs_sum = Curve.scalar.mul8(zs_sum); var zhs: [count]Curve.scalar.CompressedScalar = undefined; for (z_batch) |z, i| { zhs[i] = Curve.scalar.mul(z, hram_batch[i]); } const zr = (try Curve.mulMulti(count, expected_r_batch, z_batch)).clearCofactor(); const zah = (try Curve.mulMulti(count, a_batch, zhs)).clearCofactor(); const zsb = try Curve.basePoint.mulPublic(zs_sum); if (zr.add(zah).sub(zsb).rejectIdentity()) |_| { return error.InvalidSignature; } else |_| {} } }; test "ed25519 key pair creation" { var seed: [32]u8 = undefined; try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519Blake2b.KeyPair.create(seed); var buf: [256]u8 = undefined; // Note that pubkey is concatenated to the private key (32 bytes); a lot of libraries do this std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{key_pair.secret_key}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1668BAB533F9F9786AD39013BF53CEEFD27691A369C383D0FE571540EFF7367CD1A"); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{key_pair.public_key}), "8BAB533F9F9786AD39013BF53CEEFD27691A369C383D0FE571540EFF7367CD1A"); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{key_pair.secret_key}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1668BAB533F9F9786AD39013BF53CEEFD27691A369C383D0FE571540EFF7367CD1A"); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{key_pair.public_key}), "8BAB533F9F9786AD39013BF53CEEFD27691A369C383D0FE571540EFF7367CD1A"); } test "ed25519 signature" { var seed: [32]u8 = undefined; try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519Blake2b.KeyPair.create(seed); const sig = try Ed25519Blake2b.sign("test", key_pair, null); var buf: [128]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{sig}), "DC91FB77E0BB1EFC65AC147D0E25C6B0EE87B01CFF21B5A001584DA43C942B7C922DBBB6945DAFE42C722F7E7665241A0B2826F8B91E25FC7A9A541ECDC1C606"); try Ed25519Blake2b.verify(sig, "test", key_pair.public_key); std.testing.expectError(error.InvalidSignature, Ed25519Blake2b.verify(sig, "TEST", key_pair.public_key)); } test "ed25519 batch verification" { var i: usize = 0; while (i < 100) : (i += 1) { const key_pair = try Ed25519Blake2b.KeyPair.create(null); var msg1: [32]u8 = undefined; var msg2: [32]u8 = undefined; std.crypto.random.bytes(&msg1); std.crypto.random.bytes(&msg2); const sig1 = try Ed25519Blake2b.sign(&msg1, key_pair, null); const sig2 = try Ed25519Blake2b.sign(&msg2, key_pair, null); var signature_batch = [_]Ed25519Blake2b.BatchElement{ Ed25519Blake2b.BatchElement{ .sig = sig1, .msg = &msg1, .public_key = key_pair.public_key, }, Ed25519Blake2b.BatchElement{ .sig = sig2, .msg = &msg2, .public_key = key_pair.public_key, }, }; try Ed25519Blake2b.verifyBatch(2, signature_batch); signature_batch[1].sig = sig1; std.testing.expectError(error.InvalidSignature, Ed25519Blake2b.verifyBatch(signature_batch.len, signature_batch)); } }
ed25519-blake2b.zig
const std = @import("std"); const mem = std.mem; const fmt = std.fmt; const zig = std.zig; const fs = std.fs; const stdlib_renames = std.ComptimeStringMap([]const u8, .{ // Most 64-bit archs. .{ "newfstatat", "fstatat64" }, // POWER. .{ "sync_file_range2", "sync_file_range" }, // ARM EABI/Thumb. .{ "arm_sync_file_range", "sync_file_range" }, .{ "arm_fadvise64_64", "fadvise64_64" }, }); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); if (args.len < 3 or mem.eql(u8, args[1], "--help")) usageAndExit(std.io.getStdErr(), args[0], 1); const zig_exe = args[1]; const linux_path = args[2]; var buf_out = std.io.bufferedWriter(std.io.getStdOut().writer()); const writer = buf_out.writer(); // As of 5.17.1, the largest table is 23467 bytes. // 32k should be enough for now. var buf = try allocator.alloc(u8, 1 << 15); const linux_dir = try std.fs.openDirAbsolute(linux_path, .{}); try writer.writeAll( \\// This file is automatically generated. \\// See tools/generate_linux_syscalls.zig for more info. \\ \\ ); // These architectures have their syscall definitions generated from a TSV // file, processed via scripts/syscallhdr.sh. { try writer.writeAll("pub const X86 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/x86/entry/syscalls/syscall_32.tbl", buf); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; // abi is always i386 _ = fields.next() orelse return error.Incomplete; const name = fields.next() orelse return error.Incomplete; try writer.print(" {s} = {s},\n", .{ zig.fmtId(name), number }); } try writer.writeAll("};\n\n"); } { try writer.writeAll("pub const X64 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/x86/entry/syscalls/syscall_64.tbl", buf); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; // The x32 abi syscalls are always at the end. if (mem.eql(u8, abi, "x32")) break; const name = fields.next() orelse return error.Incomplete; const fixed_name = if (stdlib_renames.get(name)) |fixed| fixed else name; try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } try writer.writeAll("};\n\n"); } { try writer.writeAll( \\pub const Arm = enum(usize) { \\ const arm_base = 0x0f0000; \\ \\ ); const table = try linux_dir.readFile("arch/arm/tools/syscall.tbl", buf); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; if (mem.eql(u8, abi, "oabi")) continue; const name = fields.next() orelse return error.Incomplete; const fixed_name = if (stdlib_renames.get(name)) |fixed| fixed else name; try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } // TODO: maybe extract these from arch/arm/include/uapi/asm/unistd.h try writer.writeAll( \\ \\ 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, \\}; \\ \\ ); } { try writer.writeAll("pub const Sparc64 = enum(usize) {\n"); const table = try linux_dir.readFile("arch/sparc/kernel/syscalls/syscall.tbl", buf); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; if (mem.eql(u8, abi, "32")) continue; const name = fields.next() orelse return error.Incomplete; try writer.print(" {s} = {s},\n", .{ zig.fmtId(name), number }); } try writer.writeAll("};\n\n"); } { try writer.writeAll( \\pub const Mips = enum(usize) { \\ pub const Linux = 4000; \\ \\ ); const table = try linux_dir.readFile("arch/mips/kernel/syscalls/syscall_o32.tbl", buf); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; // abi is always o32 _ = fields.next() orelse return error.Incomplete; const name = fields.next() orelse return error.Incomplete; if (mem.startsWith(u8, name, "unused")) continue; try writer.print(" {s} = Linux + {s},\n", .{ zig.fmtId(name), number }); } try writer.writeAll("};\n\n"); } { try writer.writeAll("pub const PowerPC = enum(usize) {\n"); const table = try linux_dir.readFile("arch/powerpc/kernel/syscalls/syscall.tbl", buf); var list_64 = std.ArrayList(u8).init(allocator); var lines = mem.tokenize(u8, table, "\n"); while (lines.next()) |line| { if (line[0] == '#') continue; var fields = mem.tokenize(u8, line, " \t"); const number = fields.next() orelse return error.Incomplete; const abi = fields.next() orelse return error.Incomplete; const name = fields.next() orelse return error.Incomplete; const fixed_name = if (stdlib_renames.get(name)) |fixed| fixed else name; if (mem.eql(u8, abi, "spu")) { continue; } else if (mem.eql(u8, abi, "32")) { try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } else if (mem.eql(u8, abi, "64")) { try list_64.writer().print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } else { // common/nospu try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); try list_64.writer().print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } } try writer.writeAll( \\}; \\ \\pub const PowerPC64 = enum(usize) { \\ ); try writer.writeAll(list_64.items); try writer.writeAll("};\n\n"); } // Newer architectures (starting with aarch64 c. 2012) now use the same C // header file for their syscall numbers. Arch-specific headers are used to // define pre-proc. vars that add additional (usually obsolete) syscalls. // // TODO: // - It would be better to use libclang/translate-c directly to extract the definitions. // - The `-dD` option only does minimal pre-processing and doesn't resolve addition, // so arch specific syscalls are dealt with manually. { try writer.writeAll("pub const Arm64 = enum(usize) {\n"); const child_args = [_][]const u8{ zig_exe, "cc", "-target", "aarch64-linux-gnu", "-E", // -dM is cleaner, but -dD preserves iteration order. "-dD", // No need for line-markers. "-P", "-nostdinc", // Using -I=[dir] includes the zig linux headers, which we don't want. "-Iinclude", "-Iinclude/uapi", "arch/arm64/include/uapi/asm/unistd.h", }; const child_result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &child_args, .cwd = linux_path, .cwd_dir = linux_dir, .max_output_bytes = 20 * 1024, }); if (child_result.stderr.len > 0) std.debug.print("{s}\n", .{child_result.stderr}); const defines = switch (child_result.term) { .Exited => |code| if (code == 0) child_result.stdout else { std.debug.print("zig cc exited with code {d}\n", .{code}); std.process.exit(1); }, else => { std.debug.print("zig cc crashed\n", .{}); std.process.exit(1); }, }; var lines = mem.tokenize(u8, defines, "\n"); loop: while (lines.next()) |line| { var fields = mem.tokenize(u8, line, " \t"); const cmd = fields.next() orelse return error.Incomplete; if (!mem.eql(u8, cmd, "#define")) continue; const define = fields.next() orelse return error.Incomplete; const number = fields.next() orelse continue; if (!std.ascii.isDigit(number[0])) continue; if (!mem.startsWith(u8, define, "__NR")) continue; const name = mem.trimLeft(u8, mem.trimLeft(u8, define, "__NR3264_"), "__NR_"); if (mem.eql(u8, name, "arch_specific_syscall")) continue; if (mem.eql(u8, name, "syscalls")) break :loop; const fixed_name = if (stdlib_renames.get(name)) |fixed| fixed else name; try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } try writer.writeAll("};\n\n"); } { try writer.writeAll( \\pub const RiscV64 = enum(usize) { \\ pub const arch_specific_syscall = 244; \\ \\ ); const child_args = [_][]const u8{ zig_exe, "cc", "-target", "riscv64-linux-gnu", "-E", "-dD", "-P", "-nostdinc", "-Iinclude", "-Iinclude/uapi", "arch/riscv/include/uapi/asm/unistd.h", }; const child_result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &child_args, .cwd = linux_path, .cwd_dir = linux_dir, .max_output_bytes = 20 * 1024, }); if (child_result.stderr.len > 0) std.debug.print("{s}\n", .{child_result.stderr}); const defines = switch (child_result.term) { .Exited => |code| if (code == 0) child_result.stdout else { std.debug.print("zig cc exited with code {d}\n", .{code}); std.process.exit(1); }, else => { std.debug.print("zig cc crashed\n", .{}); std.process.exit(1); }, }; var lines = mem.tokenize(u8, defines, "\n"); loop: while (lines.next()) |line| { var fields = mem.tokenize(u8, line, " \t"); const cmd = fields.next() orelse return error.Incomplete; if (!mem.eql(u8, cmd, "#define")) continue; const define = fields.next() orelse return error.Incomplete; const number = fields.next() orelse continue; if (!std.ascii.isDigit(number[0])) continue; if (!mem.startsWith(u8, define, "__NR")) continue; const name = mem.trimLeft(u8, mem.trimLeft(u8, define, "__NR3264_"), "__NR_"); if (mem.eql(u8, name, "arch_specific_syscall")) continue; if (mem.eql(u8, name, "syscalls")) break :loop; const fixed_name = if (stdlib_renames.get(name)) |fixed| fixed else name; try writer.print(" {s} = {s},\n", .{ zig.fmtId(fixed_name), number }); } try writer.writeAll( \\ \\ riscv_flush_icache = arch_specific_syscall + 15, \\}; \\ ); } try buf_out.flush(); } fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { file.writer().print( \\Usage: {s} /path/to/zig /path/to/linux \\Alternative Usage: zig run /path/to/git/zig/tools/generate_linux_syscalls.zig -- /path/to/zig /path/to/linux \\ \\Generates the list of Linux syscalls for each supported cpu arch, using the Linux development tree. \\Prints to stdout Zig code which you can use to replace the file lib/std/os/linux/syscalls.zig. \\ , .{arg0}) catch std.process.exit(1); std.process.exit(code); }
tools/generate_linux_syscalls.zig
const std = @import("std"); const bcrypt = std.crypto.pwhash.bcrypt; const clap = @import("clap.zig"); const debug = std.debug; const Allocator = std.mem.Allocator; const windows = std.os.windows; const WINAPI = std.os.windows.WINAPI; const HANDLE = std.os.windows.HANDLE; const DWORD = std.os.windows.DWORD; const LPDWORD = std.os.windows.LPDWORD; const BOOL = std.os.windows.BOOL; const bits = std.os; const linux = std.os.linux; const TCSA = bits.TCSA; const DEFAULT_ROUNDS: u6 = 10; const Mode = enum { encrypt, check }; pub fn main() !void { const allocator = std.heap.page_allocator; // First we specify what parameters our program can take. // We can use `parseParam` to parse a string to a `Param(Help)` const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit. ") catch unreachable, clap.parseParam("-r, --rounds <NUM> Indicates the log number of rounds, 1<= rounds <= 31. Default value is 10.") catch unreachable, clap.parseParam("-c, --check <HASH> Prompts for a password. 'true' or 'false' will be returned whether the password matches the hash. Cannot be combined with -er.") catch unreachable, clap.parseParam("-e, --encrypt Prompts for a password. The result will be a bcrypt hash of the password. Cannot be combined with -c. Default option.") catch unreachable, }; // We then initialize an argument iterator. We will use the OsIterator as it nicely // wraps iterating over arguments the most efficient way on each os. var iter = try clap.args.OsIterator.init(allocator); defer iter.deinit(); // Initalize our diagnostics, which can be used for reporting useful errors. // This is optional. You can also just pass `null` to `parser.next` if you // don't care about the extra information `Diagnostics` provides. var diag = clap.Diagnostic{}; var args = clap.parse(clap.Help, &params, .{ .diagnostic = &diag }) catch |err| { // Report 'Invalid argument [arg]' diag.report(std.io.getStdOut().writer(), err) catch {}; return; }; defer args.deinit(); var rounds: ?u6 = null; var mode = Mode.encrypt; if (args.flag("--help")) { var buf: [1024]u8 = undefined; var slice_stream = std.io.fixedBufferStream(&buf); try clap.help(std.io.getStdOut().writer(), &params); debug.warn("Usage: bcrypt-encoder [OPTION] \n Hashes password with the bcrypt algorithm. Also allows checking if a password matches a provided hash.\n\n If arguments are possible, they are mandatory unless specified otherwise.\n", .{}); debug.warn("{s}\n", .{slice_stream.getWritten()}); return; } if (args.option("--rounds")) |n| { var temp: u32 = 0; if (std.fmt.parseInt(u32, n[0..], 10)) |num| { temp = num; } else |err| { debug.warn("Round number is not a valid number\n", .{}); return; } if (temp < 1 or temp > 31) { debug.warn("Rounds must be >=1 and <=31\n", .{}); return; } else { rounds = @intCast(u6, temp); } } const encrypt = args.flag("-e"); var hash: [60]u8 = undefined; if (args.option("-c")) |n| { if (encrypt) { debug.warn("-c conflicts with -e\n", .{}); return; } if (n.len != 60) { debug.warn("Invalid hash length. Expected length 60, got length {d}\n", .{n.len}); return; } mode = Mode.check; for (n) |char, i| { hash[i] = char; } } var read_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer read_allocator.deinit(); errdefer read_allocator.deinit(); if (mode == Mode.encrypt) { var password: []u8 = try read_string_silently(&read_allocator.allocator); try std.io.getStdOut().writer().print("{s}\n", .{bcrypt_string(password[0..], rounds)}); zero_password(password); return; } else if (mode == Mode.check) { var password = try read_string_silently(&read_allocator.allocator); try std.io.getStdOut().writer().print("{s}\n", .{verify_password(hash, password[0..])}); zero_password(password); return; } else { unreachable; } } fn zero_password(password: []u8) void { for (password) |*char| { char.* = 0; } } fn bcrypt_string(password: []const u8, rounds: ?u6) ![60]u8 { return bcrypt.strHash(password, rounds orelse DEFAULT_ROUNDS); } fn verify_password(hash: [60]u8, password: []const u8) bool { bcrypt.strVerify(hash, password) catch |err| return false; return true; } pub extern "kernel32" fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) callconv(WINAPI) BOOL; pub extern "kernel32" fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) BOOL; fn read_string_silently(allocator: *std.mem.Allocator) ![]u8 { const os = std.builtin.os.tag; var hidden_input: bool = false; if (os == .windows) { const ENABLE_ECHO_INPUT: u32 = 4; var handle = try windows.GetStdHandle(std.os.windows.STD_INPUT_HANDLE); var my_val: u32 = 0; var current_mode: LPDWORD = &my_val; _ = GetConsoleMode(handle, current_mode); _ = SetConsoleMode(handle, current_mode.* & ~ENABLE_ECHO_INPUT); hidden_input = true; } else if (os == .linux) { var import_termios = try bits.tcgetattr(bits.STDIN_FILENO); import_termios.lflag = import_termios.lflag & ~@as(u32, linux.ECHO); try bits.tcsetattr(bits.STDIN_FILENO, TCSA.NOW, import_termios); hidden_input = true; } if (hidden_input) { try std.io.getStdOut().writer().print("Please enter password:\n", .{}); } else { try std.io.getStdOut().writer().print("Please enter password(Password will be visible!):\n", .{}); } var newline: u8 = 13; if (os == .linux) newline = 10; const max_size: usize = 1000; // Deallocation at end of program const read = try std.io.getStdIn().reader().readUntilDelimiterAlloc(allocator, newline, max_size); if (os == .windows) { // Echo re-enables automatically } else if (os == .linux) { var import_termios = try bits.tcgetattr(bits.STDIN_FILENO); import_termios.lflag = import_termios.lflag | @as(u32, linux.ECHO); try bits.tcsetattr(bits.STDIN_FILENO, TCSA.NOW, import_termios); } return read; }
main.zig
const DragIcon = @This(); const std = @import("std"); const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const Seat = @import("Seat.zig"); const Subsurface = @import("Subsurface.zig"); seat: *Seat, wlr_drag_icon: *wlr.Drag.Icon, // Always active destroy: wl.Listener(*wlr.Drag.Icon) = wl.Listener(*wlr.Drag.Icon).init(handleDestroy), map: wl.Listener(*wlr.Drag.Icon) = wl.Listener(*wlr.Drag.Icon).init(handleMap), unmap: wl.Listener(*wlr.Drag.Icon) = wl.Listener(*wlr.Drag.Icon).init(handleUnmap), new_subsurface: wl.Listener(*wlr.Subsurface) = wl.Listener(*wlr.Subsurface).init(handleNewSubsurface), // Only active while mapped commit: wl.Listener(*wlr.Surface) = wl.Listener(*wlr.Surface).init(handleCommit), pub fn init(drag_icon: *DragIcon, seat: *Seat, wlr_drag_icon: *wlr.Drag.Icon) void { drag_icon.* = .{ .seat = seat, .wlr_drag_icon = wlr_drag_icon }; wlr_drag_icon.events.destroy.add(&drag_icon.destroy); wlr_drag_icon.events.map.add(&drag_icon.map); wlr_drag_icon.events.unmap.add(&drag_icon.unmap); wlr_drag_icon.surface.events.new_subsurface.add(&drag_icon.new_subsurface); Subsurface.handleExisting(wlr_drag_icon.surface, .{ .drag_icon = drag_icon }); } fn handleDestroy(listener: *wl.Listener(*wlr.Drag.Icon), wlr_drag_icon: *wlr.Drag.Icon) void { const drag_icon = @fieldParentPtr(DragIcon, "destroy", listener); const node = @fieldParentPtr(std.SinglyLinkedList(DragIcon).Node, "data", drag_icon); server.root.drag_icons.remove(node); drag_icon.destroy.link.remove(); drag_icon.map.link.remove(); drag_icon.unmap.link.remove(); drag_icon.new_subsurface.link.remove(); Subsurface.destroySubsurfaces(wlr_drag_icon.surface); util.gpa.destroy(node); } fn handleMap(listener: *wl.Listener(*wlr.Drag.Icon), wlr_drag_icon: *wlr.Drag.Icon) void { const drag_icon = @fieldParentPtr(DragIcon, "map", listener); wlr_drag_icon.surface.events.commit.add(&drag_icon.commit); var it = server.root.outputs.first; while (it) |node| : (it = node.next) node.data.damage.addWhole(); } fn handleUnmap(listener: *wl.Listener(*wlr.Drag.Icon), wlr_drag_icon: *wlr.Drag.Icon) void { const drag_icon = @fieldParentPtr(DragIcon, "unmap", listener); drag_icon.commit.link.remove(); var it = server.root.outputs.first; while (it) |node| : (it = node.next) node.data.damage.addWhole(); } fn handleCommit(listener: *wl.Listener(*wlr.Surface), surface: *wlr.Surface) void { const drag_icon = @fieldParentPtr(DragIcon, "commit", listener); var it = server.root.outputs.first; while (it) |node| : (it = node.next) node.data.damage.addWhole(); } fn handleNewSubsurface(listener: *wl.Listener(*wlr.Subsurface), wlr_subsurface: *wlr.Subsurface) void { const drag_icon = @fieldParentPtr(DragIcon, "new_subsurface", listener); Subsurface.create(wlr_subsurface, .{ .drag_icon = drag_icon }); }
source/river-0.1.0/river/DragIcon.zig
const Self = @This(); const build_options = @import("build_options"); const std = @import("std"); const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const xkb = @import("xkbcommon"); const command = @import("command.zig"); const server = &@import("main.zig").server; const util = @import("util.zig"); const DragIcon = @import("DragIcon.zig"); const Cursor = @import("Cursor.zig"); const InputManager = @import("InputManager.zig"); const Keyboard = @import("Keyboard.zig"); const Mapping = @import("Mapping.zig"); const LayerSurface = @import("LayerSurface.zig"); const Output = @import("Output.zig"); const SeatStatus = @import("SeatStatus.zig"); const View = @import("View.zig"); const ViewStack = @import("view_stack.zig").ViewStack; const log = std.log.scoped(.seat); const PointerConstraint = @import("PointerConstraint.zig"); const FocusTarget = union(enum) { view: *View, layer: *LayerSurface, none: void, }; wlr_seat: *wlr.Seat, /// Multiple mice are handled by the same Cursor cursor: Cursor = undefined, /// Mulitple keyboards are handled separately keyboards: std.TailQueue(Keyboard) = .{}, /// ID of the current keymap mode mode_id: usize = 0, /// ID of previous keymap mode, used when returning from "locked" mode prev_mode_id: usize = 0, /// Timer for repeating keyboard mappings mapping_repeat_timer: *wl.EventSource, /// Currently repeating mapping, if any repeating_mapping: ?*const Mapping = null, /// Currently focused output, may be the noop output if no real output /// is currently available for focus. focused_output: *Output, /// Currently focused view/layer surface if any focused: FocusTarget = .none, /// Stack of views in most recently focused order /// If there is a currently focused view, it is on top. focus_stack: ViewStack(*View) = .{}, /// List of status tracking objects relaying changes to this seat to clients. status_trackers: std.SinglyLinkedList(SeatStatus) = .{}, request_set_selection: wl.Listener(*wlr.Seat.event.RequestSetSelection) = wl.Listener(*wlr.Seat.event.RequestSetSelection).init(handleRequestSetSelection), request_start_drag: wl.Listener(*wlr.Seat.event.RequestStartDrag) = wl.Listener(*wlr.Seat.event.RequestStartDrag).init(handleRequestStartDrag), start_drag: wl.Listener(*wlr.Drag) = wl.Listener(*wlr.Drag).init(handleStartDrag), request_set_primary_selection: wl.Listener(*wlr.Seat.event.RequestSetPrimarySelection) = wl.Listener(*wlr.Seat.event.RequestSetPrimarySelection).init(handleRequestSetPrimarySelection), pub fn init(self: *Self, name: [*:0]const u8) !void { const event_loop = server.wl_server.getEventLoop(); const mapping_repeat_timer = try event_loop.addTimer(*Self, handleMappingRepeatTimeout, self); errdefer mapping_repeat_timer.remove(); self.* = .{ // This will be automatically destroyed when the display is destroyed .wlr_seat = try wlr.Seat.create(server.wl_server, name), .focused_output = &server.root.noop_output, .mapping_repeat_timer = mapping_repeat_timer, }; self.wlr_seat.data = @ptrToInt(self); try self.cursor.init(self); self.wlr_seat.events.request_set_selection.add(&self.request_set_selection); self.wlr_seat.events.request_start_drag.add(&self.request_start_drag); self.wlr_seat.events.start_drag.add(&self.start_drag); self.wlr_seat.events.request_set_primary_selection.add(&self.request_set_primary_selection); } pub fn deinit(self: *Self) void { self.cursor.deinit(); self.mapping_repeat_timer.remove(); while (self.keyboards.pop()) |node| { node.data.deinit(); util.gpa.destroy(node); } while (self.focus_stack.first) |node| { self.focus_stack.remove(node); util.gpa.destroy(node); } } /// Set the current focus. If a visible view is passed it will be focused. /// If null is passed, the first visible view in the focus stack will be focused. pub fn focus(self: *Self, _target: ?*View) void { var target = _target; // While a layer surface is focused, views may not recieve focus if (self.focused == .layer) return; if (target) |view| { // If the view is not currently visible, behave as if null was passed if (view.pending.tags & view.output.pending.tags == 0) { target = null; } else { // If the view is not on the currently focused output, focus it if (view.output != self.focused_output) self.focusOutput(view.output); } } // If the target view is not fullscreen or null, then a fullscreen view // will grab focus if visible. if (if (target) |v| !v.pending.fullscreen else true) { const tags = self.focused_output.pending.tags; var it = ViewStack(*View).iter(self.focus_stack.first, .forward, tags, pendingFilter); target = while (it.next()) |view| { if (view.output == self.focused_output and view.pending.fullscreen) break view; } else target; } if (target == null) { // Set view to the first currently visible view in the focus stack if any const tags = self.focused_output.pending.tags; var it = ViewStack(*View).iter(self.focus_stack.first, .forward, tags, pendingFilter); target = while (it.next()) |view| { if (view.output == self.focused_output) break view; } else null; } // Focus the target view or clear the focus if target is null if (target) |view| { // Find the node for this view in the focus stack and move it to the top. var it = self.focus_stack.first; while (it) |node| : (it = node.next) { if (node.view == view) { const new_focus_node = self.focus_stack.remove(node); self.focus_stack.push(node); break; } } else { // A node is added when new Views are mapped in Seat.handleViewMap() unreachable; } self.setFocusRaw(.{ .view = view }); } else { self.setFocusRaw(.{ .none = {} }); } } fn pendingFilter(view: *View, filter_tags: u32) bool { return view.surface != null and view.pending.tags & filter_tags != 0; } /// Switch focus to the target, handling unfocus and input inhibition /// properly. This should only be called directly if dealing with layers. pub fn setFocusRaw(self: *Self, new_focus: FocusTarget) void { // If the target is already focused, do nothing if (std.meta.eql(new_focus, self.focused)) return; // Obtain the target surface const target_surface = switch (new_focus) { .view => |target_view| target_view.surface.?, .layer => |target_layer| target_layer.wlr_layer_surface.surface, .none => null, }; // If input is not allowed on the target surface (e.g. due to an active // input inhibitor) do not set focus. If there is no target surface we // still clear the focus. if (if (target_surface) |wlr_surface| server.input_manager.inputAllowed(wlr_surface) else true) { // First clear the current focus switch (self.focused) { .view => |view| { view.pending.focus -= 1; if (view.pending.focus == 0) view.setActivated(false); }, .layer, .none => {}, } // Set the new focus switch (new_focus) { .view => |target_view| { std.debug.assert(self.focused_output == target_view.output); if (target_view.pending.focus == 0) target_view.setActivated(true); target_view.pending.focus += 1; target_view.pending.urgent = false; }, .layer => |target_layer| std.debug.assert(self.focused_output == target_layer.output), .none => {}, } self.focused = new_focus; // Send keyboard enter/leave events and handle pointer constraints if (target_surface) |wlr_surface| { if (self.wlr_seat.getKeyboard()) |keyboard| { self.wlr_seat.keyboardNotifyEnter( wlr_surface, &keyboard.keycodes, keyboard.num_keycodes, &keyboard.modifiers, ); } else { self.wlr_seat.keyboardNotifyEnter(wlr_surface, null, 0, null); } if (server.input_manager.pointer_constraints.constraintForSurface(wlr_surface, self.wlr_seat)) |constraint| { @intToPtr(*PointerConstraint, constraint.data).setAsActive(); } else if (self.cursor.constraint) |constraint| { PointerConstraint.warpToHint(&self.cursor); constraint.sendDeactivated(); self.cursor.constraint = null; } } else { self.wlr_seat.keyboardClearFocus(); if (self.cursor.constraint) |constraint| { PointerConstraint.warpToHint(&self.cursor); constraint.sendDeactivated(); self.cursor.constraint = null; } } } // Inform any clients tracking status of the change var it = self.status_trackers.first; while (it) |node| : (it = node.next) node.data.sendFocusedView(); } /// Focus the given output, notifying any listening clients of the change. pub fn focusOutput(self: *Self, output: *Output) void { if (self.focused_output == output) return; var it = self.status_trackers.first; while (it) |node| : (it = node.next) node.data.sendOutput(.unfocused); self.focused_output = output; it = self.status_trackers.first; while (it) |node| : (it = node.next) node.data.sendOutput(.focused); if (self.focused_output == &server.root.noop_output) return; // Warp pointer to center of newly focused output (In layout coordinates), // but only if cursor is not already on the output and this feature is enabled. switch (server.config.warp_cursor) { .disabled => {}, .@"on-output-change" => { const layout_box = server.root.output_layout.getBox(output.wlr_output).?; if (!layout_box.containsPoint(self.cursor.wlr_cursor.x, self.cursor.wlr_cursor.y)) { const eff_res = output.getEffectiveResolution(); const lx = @intToFloat(f32, layout_box.x + @intCast(i32, eff_res.width / 2)); const ly = @intToFloat(f32, layout_box.y + @intCast(i32, eff_res.height / 2)); if (!self.cursor.wlr_cursor.warp(null, lx, ly)) { log.err("failed to warp cursor on output change", .{}); } } }, } } pub fn handleActivity(self: Self) void { server.input_manager.idle.notifyActivity(self.wlr_seat); } pub fn handleViewMap(self: *Self, view: *View) !void { const new_focus_node = try util.gpa.create(ViewStack(*View).Node); new_focus_node.view = view; self.focus_stack.append(new_focus_node); self.focus(view); } /// Handle the unmapping of a view, removing it from the focus stack and /// setting the focus if needed. pub fn handleViewUnmap(self: *Self, view: *View) void { // Remove the node from the focus stack and destroy it. var it = self.focus_stack.first; while (it) |node| : (it = node.next) { if (node.view == view) { self.focus_stack.remove(node); util.gpa.destroy(node); break; } } self.cursor.handleViewUnmap(view); // If the unmapped view is focused, choose a new focus if (self.focused == .view and self.focused.view == view) self.focus(null); } /// Handle any user-defined mapping for the passed keysym and modifiers /// Returns true if the key was handled pub fn handleMapping( self: *Self, keysym: xkb.Keysym, modifiers: wlr.Keyboard.ModifierMask, released: bool, ) bool { const modes = &server.config.modes; for (modes.items[self.mode_id].mappings.items) |*mapping| { if (std.meta.eql(modifiers, mapping.modifiers) and keysym == mapping.keysym and released == mapping.release) { if (mapping.repeat) { self.repeating_mapping = mapping; self.mapping_repeat_timer.timerUpdate(server.config.repeat_delay) catch { log.err("failed to update mapping repeat timer", .{}); }; } self.runMappedCommand(mapping); return true; } } return false; } fn runMappedCommand(self: *Self, mapping: *const Mapping) void { var out: ?[]const u8 = null; defer if (out) |s| util.gpa.free(s); const args = mapping.command_args; command.run(util.gpa, self, args, &out) catch |err| { const failure_message = switch (err) { command.Error.Other => out.?, else => command.errToMsg(err), }; std.log.scoped(.command).err("{s}: {s}", .{ args[0], failure_message }); return; }; if (out) |s| { const stdout = std.io.getStdOut().writer(); stdout.print("{s}", .{s}) catch |err| { std.log.scoped(.command).err("{s}: write to stdout failed {}", .{ args[0], err }); }; } } pub fn clearRepeatingMapping(self: *Self) void { self.mapping_repeat_timer.timerUpdate(0) catch { log.err("failed to clear mapping repeat timer", .{}); }; self.repeating_mapping = null; } /// Repeat key mapping fn handleMappingRepeatTimeout(self: *Self) callconv(.C) c_int { if (self.repeating_mapping) |mapping| { const rate = server.config.repeat_rate; const ms_delay = if (rate > 0) 1000 / rate else 0; self.mapping_repeat_timer.timerUpdate(ms_delay) catch { log.err("failed to update mapping repeat timer", .{}); }; self.runMappedCommand(mapping); } return 0; } /// Add a newly created input device to the seat and update the reported /// capabilities. pub fn addDevice(self: *Self, device: *wlr.InputDevice) void { switch (device.type) { .keyboard => self.addKeyboard(device) catch return, .pointer => self.addPointer(device), else => return, } // We need to let the wlr_seat know what our capabilities are, which is // communiciated to the client. We always have a cursor, even if // there are no pointer devices, so we always include that capability. self.wlr_seat.setCapabilities(.{ .pointer = true, .keyboard = self.keyboards.len > 0, }); } fn addKeyboard(self: *Self, device: *wlr.InputDevice) !void { const node = try util.gpa.create(std.TailQueue(Keyboard).Node); node.data.init(self, device) catch |err| { const log_keyboard = std.log.scoped(.keyboard); switch (err) { error.XkbContextFailed => log_keyboard.err("Failed to create XKB context", .{}), error.XkbKeymapFailed => log_keyboard.err("Failed to create XKB keymap", .{}), error.SetKeymapFailed => log_keyboard.err("Failed to set wlr keyboard keymap", .{}), } return; }; self.keyboards.append(node); self.wlr_seat.setKeyboard(device); } fn addPointer(self: Self, device: *wlr.InputDevice) void { // We don't do anything special with pointers. All of our pointer handling // is proxied through wlr_cursor. On another compositor, you might take this // opportunity to do libinput configuration on the device to set // acceleration, etc. self.cursor.wlr_cursor.attachInputDevice(device); } fn handleRequestSetSelection( listener: *wl.Listener(*wlr.Seat.event.RequestSetSelection), event: *wlr.Seat.event.RequestSetSelection, ) void { const self = @fieldParentPtr(Self, "request_set_selection", listener); self.wlr_seat.setSelection(event.source, event.serial); } fn handleRequestStartDrag( listener: *wl.Listener(*wlr.Seat.event.RequestStartDrag), event: *wlr.Seat.event.RequestStartDrag, ) void { const self = @fieldParentPtr(Self, "request_start_drag", listener); if (!self.wlr_seat.validatePointerGrabSerial(event.origin, event.serial)) { log.debug("ignoring request to start drag, failed to validate serial {}", .{event.serial}); if (event.drag.source) |source| source.destroy(); return; } log.debug("starting pointer drag", .{}); self.wlr_seat.startPointerDrag(event.drag, event.serial); } fn handleStartDrag( listener: *wl.Listener(*wlr.Drag), wlr_drag: *wlr.Drag, ) void { const self = @fieldParentPtr(Self, "start_drag", listener); if (wlr_drag.icon) |wlr_drag_icon| { const node = util.gpa.create(std.SinglyLinkedList(DragIcon).Node) catch { log.crit("out of memory", .{}); return; }; node.data.init(self, wlr_drag_icon); server.root.drag_icons.prepend(node); } self.cursor.mode = .passthrough; } fn handleRequestSetPrimarySelection( listener: *wl.Listener(*wlr.Seat.event.RequestSetPrimarySelection), event: *wlr.Seat.event.RequestSetPrimarySelection, ) void { const self = @fieldParentPtr(Self, "request_set_primary_selection", listener); self.wlr_seat.setPrimarySelection(event.source, event.serial); }
source/river-0.1.0/river/Seat.zig
const std = @import("std"); const print = std.debug.print; const List = std.ArrayList; const StrMap = std.StringHashMap; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day12.txt"); const Edge = struct { a: []const u8, b: []const u8, }; const Node = struct { is_start: bool = false, small: bool = true, visited: u8 = 0, neighbors: List(*Node), }; pub fn main() !void { var num_paths: usize = 0; var nodes = StrMap(Node).init(gpa); defer nodes.deinit(); // list nodes var edges = try util.toSliceOf(Edge, data, "-"); defer gpa.free(edges); for (edges) |edge| { var gop = try nodes.getOrPut(edge.a); if (!gop.found_existing) { gop.value_ptr.*.small = std.ascii.isLower(edge.a[0]); gop.value_ptr.*.visited = 0; gop.value_ptr.*.neighbors = List(*Node).init(gpa); } gop = try nodes.getOrPut(edge.b); if (!gop.found_existing) { gop.value_ptr.*.small = std.ascii.isLower(edge.b[0]); gop.value_ptr.*.visited = 0; gop.value_ptr.*.neighbors = List(*Node).init(gpa); } } // connect nodes var start: *Node = undefined; var end: *Node = undefined; for (edges) |edge| { var a = nodes.getPtr(edge.a).?; try a.*.neighbors.append(nodes.getPtr(edge.b).?); var b = nodes.getPtr(edge.b).?; try b.*.neighbors.append(nodes.getPtr(edge.a).?); if (util.streq(edge.a, "start")) start = nodes.getPtr(edge.a).?; if (util.streq(edge.b, "start")) start = nodes.getPtr(edge.b).?; if (util.streq(edge.a, "end")) end = nodes.getPtr(edge.a).?; if (util.streq(edge.b, "end")) end = nodes.getPtr(edge.b).?; } start.is_start = true; // find routes visit1(start, end, &num_paths); print("{}\n", .{num_paths}); num_paths = 0; var any_twice = false; visit2(start, end, &num_paths, &any_twice); print("{}\n", .{num_paths}); // free neighbors var it = nodes.iterator(); while (it.next()) |node| { node.value_ptr.*.neighbors.deinit(); } } fn visit1(node: *Node, end: *Node, num_paths: *usize) void { if (node.small and node.visited > 0) return; if (node == end) { num_paths.* += 1; return; } if (node.small) node.visited += 1; for (node.neighbors.items) |n| { visit1(n, end, num_paths); } if (node.small) node.visited -= 1; } fn visit2(node: *Node, end: *Node, num_paths: *usize, any_twice: *bool) void { if (node.small and node.visited > 2) return; if (node.small and any_twice.* and node.visited > 0) return; if (node.is_start and node.visited > 0) return; if (node == end) { num_paths.* += 1; return; } if (node.small) node.visited += 1; if (node.visited == 2) any_twice.* = true; for (node.neighbors.items) |n| { visit2(n, end, num_paths, any_twice); } if (node.visited == 2) any_twice.* = false; if (node.small) node.visited -= 1; }
2021/src/day12.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../inputs/day07.txt"); pub fn main() anyerror!void { var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_impl.deinit(); const gpa = gpa_impl.allocator(); return main_with_allocator(gpa); } pub fn main_with_allocator(allocator: Allocator) anyerror!void { var positions = std.ArrayList(isize).init(allocator); defer positions.deinit(); { var it = std.mem.split(u8, std.mem.trimRight(u8, data[0..], "\n"), ","); while (it.next()) |n| { const x = try std.fmt.parseInt(isize, n, 10); try positions.append(x); } } print("Part 1: {d}\n", .{try solve(positions.items, cost1)}); print("Part 2: {d}\n", .{try solve(positions.items, cost2)}); } fn solve(positions: []const isize, cost: fn ([]const isize, isize) anyerror!isize) anyerror!isize { var offset = averageInt(positions); const cur_cost = try cost(positions, offset); const next_cost = try cost(positions, offset + 1); var dir: isize = undefined; var best_cost: isize = undefined; if (next_cost < cur_cost) { dir = 1; best_cost = next_cost; offset = offset + 1; } else { dir = -1; best_cost = cur_cost; } var step_size: isize = 32; while (step_size > 1) { while (true) { const off = offset + step_size * dir; const new_cost = try cost(positions, off); if (new_cost >= best_cost) { break; } best_cost = new_cost; offset = off; } step_size >>= 1; } return best_cost; } fn cost1(positions: []const isize, offset: isize) anyerror!isize { var out: isize = 0; for (positions) |p| { out += try std.math.absInt(p - offset); } return out; } fn cost2(positions: []const isize, offset: isize) anyerror!isize { var out: isize = 0; for (positions) |p| { out += triangle(try std.math.absInt(p - offset)); } return out; } fn triangle(x: isize) isize { return @divTrunc((1 + x) * x, 2); } fn sum(xs: []const isize) isize { var out: isize = 0; for (xs) |x| { out += x; } return out; } fn averageInt(xs: []const isize) isize { const s: isize = sum(xs[0..]); return @divTrunc(s, @intCast(isize, xs.len)); } test "crabs" { const positions = [_]isize{ 16, 1, 2, 0, 4, 2, 7, 1, 2, 14 }; const part1 = try solve(positions[0..], cost1); try std.testing.expectEqual(@as(isize, 37), part1); const part2 = try solve(positions[0..], cost2); try std.testing.expectEqual(@as(isize, 168), part2); }
src/day07.zig
const std = @import("std"); pub usingnamespace std.os.windows; pub const WS_VISIBLE = 0x10000000; pub const VK_ESCAPE = 0x001B; pub const VK_LBUTTON = 0x01; pub const VK_RBUTTON = 0x02; pub const POINT = extern struct { x: LONG, y: LONG, }; pub const RECT = extern struct { left: LONG, top: LONG, right: LONG, bottom: LONG, }; pub extern "kernel32" fn AdjustWindowRect( lpRect: ?*RECT, dwStyle: DWORD, bMenu: BOOL, ) callconv(.C) BOOL; pub extern "kernel32" fn LoadLibraryA(lpLibFileName: [*:0]const u8) callconv(.C) ?HMODULE; pub extern "user32" fn SetProcessDPIAware() callconv(.C) BOOL; pub extern "user32" fn SetWindowTextA(hWnd: ?HWND, lpString: LPCSTR) callconv(.C) BOOL; pub extern "user32" fn GetCursorPos(lpPoint: *POINT) callconv(.C) BOOL; pub extern "user32" fn GetAsyncKeyState(vKey: c_int) callconv(.C) SHORT; pub extern "user32" fn LoadCursorA( hInstance: ?HINSTANCE, lpCursorName: LPCSTR, ) callconv(.C) HCURSOR; pub extern "user32" fn GetClientRect(HWND, *RECT) callconv(.C) BOOL; pub const IUnknown = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, }, usingnamespace IUnknown.Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn QueryInterface(self: *T, guid: *const GUID, outobj: **c_void) HRESULT { return self.vtbl.QueryInterface(self, guid, outobj); } pub inline fn AddRef(self: *T) u32 { return self.vtbl.AddRef(self); } pub inline fn Release(self: *T) u32 { return self.vtbl.Release(self); } }; } }; pub const CLSCTX_INPROC_SERVER = 0x1; pub extern "ole32" fn CoInitialize(reserved: ?*c_void) callconv(.C) HRESULT; pub extern "ole32" fn CoCreateInstance( rclsid: *const GUID, pUnkOuter: ?*IUnknown, dwClsContext: DWORD, riid: *const GUID, ppv: **c_void, ) callconv(.C) HRESULT; pub inline fn vhr(hr: HRESULT) void { if (hr != 0) { std.debug.panic("HRESULT function failed ({}).", .{hr}); } } pub inline fn releaseCom(obj: anytype) void { comptime std.debug.assert(@hasDecl(@TypeOf(obj.*.*), "Release")); _ = obj.*.Release(); obj.* = undefined; }
src/windows/windows.zig
const std = @import("std"); const os = std.os; const warn = std.debug.warn; const syspect = @import("syspect"); pub fn main() !void { const allocator = std.heap.c_allocator; const syscalls = &[_]os.SYS{ .open, .openat, }; var inspector = syspect.Inspector.init(allocator, syscalls, .{ .multithread = true }); defer inspector.deinit(); try init(allocator, &inspector); while (try next_syscall(&inspector)) |position_context| { // Here we are unwrapping a tagged union, which tells us if the syscall has been executed or not. switch (position_context) { // The syscall will be executed after we resume the tracee. // Now is our chance to inspect and even modify the arguments or tracee's memory. .pre_call => |context| { var buffer = [_]u8{0} ** std.fs.MAX_PATH_BYTES; // openat(2) and open(2) share all arguments/argument positions, except for openat(2)'s first argument. const pathname = switch (@intToEnum(os.SYS, context.registers.syscall)) { .open, .creat => try readString(context.pid, context.registers.arg1, buffer[0..]), .openat => try readString(context.pid, context.registers.arg2, buffer[0..]), else => unreachable, }; warn("pid = {}, '{}' path = '{}'\n", .{ context.pid, @tagName(@intToEnum(os.SYS, context.registers.syscall)), pathname }); try inspector.resume_tracee(context.pid); }, // The syscall has finished and the result will be returned to the tracee when resumed. // Here we can view the result as well as modify what the tracee will see as the return value. .post_call => |context| { warn("pid = {}, '{}' = {}\n\n", .{ context.pid, @tagName(@intToEnum(os.SYS, context.registers.syscall)), @intCast(isize, context.registers.result) }); try inspector.resume_tracee(context.pid); }, } } } // Currently Steam returns error.NoSuchProcess when we call ptrace.getRegister during a ptrace syscall trap. // We are unsure why this happens. However, this is a working bandaid, for now. fn next_syscall(inspector: *syspect.Inspector) anyerror!?syspect.Inspector.SyscallContext { return inspector.next_syscall() catch |err| { return switch (err) { error.NoSuchProcess => next_syscall(inspector), else => err, }; }; } /// Reads data as a string until we reach a null termination character. /// Takes a pointer to a string. The pointer does not have to point to our memory space. /// Can read data from other processes by utilizing "syspect.interprocess_rw" pub fn readString(pid: os.pid_t, ptr: usize, buffer: []u8) ![]u8 { const vmreadv_result = try syspect.interprocess_rw.readv(pid, buffer[0..], ptr); for (buffer) |i, index| { if (i == 0) return buffer[0..index]; } return error.FilenameEndNotFound; } /// Handles argument parsing. /// Can either spawn a new process or attach to a running process, given the PID. fn init(allocator: *std.mem.Allocator, inspector: *syspect.Inspector) !void { if (os.argv.len <= 1) { usage(os.argv[0]); os.exit(1); } const maybe_pid: ?os.pid_t = std.fmt.parseInt(os.pid_t, std.mem.span(os.argv[1]), 10) catch null; if (maybe_pid) |pid| { inspector.attach_to_process(pid) catch |err| { switch (err) { error.OperationNotPermitted => { warn("Operation not permitted. Usually caused by insufficient privileges. Try running the program as sudo!\n", .{}); os.exit(1); }, else => return err, } }; warn("Attached to pid: {}\n", .{pid}); } else { var target_argv = try allocator.alloc([]u8, os.argv.len - 1); defer allocator.free(target_argv); for (os.argv[1..os.argv.len]) |arg, index| { target_argv[index] = std.mem.span(arg); } // Spawns the process with associated arguments; immediately begins tracing the process. const tracee_pid = try inspector.spawn_process(allocator, target_argv); } } fn usage(our_name: [*:0]u8) void { warn("To use {}, call it with either: another program's path, or a running process' PID\n", .{our_name}); }
examples/print_pathname.zig
const std = @import("std"); const zap = @import("zap"); const hyperia = @import("hyperia.zig"); const os = std.os; const mem = std.mem; const builtin = std.builtin; const testing = std.testing; const assert = std.debug.assert; pub const cache_line_length = switch (builtin.cpu.arch) { .x86_64, .aarch64, .powerpc64 => 128, .arm, .mips, .mips64, .riscv64 => 32, .s390x => 256, else => 64, }; pub fn AsyncAutoResetEvent(comptime T: type) type { return struct { const Self = @This(); const Node = struct { runnable: zap.Pool.Runnable = .{ .runFn = run }, token: T = undefined, frame: anyframe, pub fn run(runnable: *zap.Pool.Runnable) void { const self = @fieldParentPtr(Node, "runnable", runnable); resume self.frame; } }; const EMPTY = 0; const NOTIFIED = 1; state: usize = EMPTY, pub usingnamespace if (@sizeOf(T) == 0) struct { pub fn set(self: *Self) ?*zap.Pool.Runnable { var state = @atomicLoad(usize, &self.state, .Monotonic); while (state != NOTIFIED) { if (state != EMPTY) { state = @cmpxchgWeak(usize, &self.state, state, NOTIFIED, .Acquire, .Monotonic) orelse { const node = @intToPtr(*Node, state); return &node.runnable; }; } else { state = @cmpxchgWeak(usize, &self.state, state, NOTIFIED, .Monotonic, .Monotonic) orelse { return null; }; } } return null; } pub fn wait(self: *Self) void { var state = @atomicLoad(usize, &self.state, .Monotonic); defer @atomicStore(usize, &self.state, EMPTY, .Monotonic); if (state != NOTIFIED) { var node: Node = .{ .frame = @frame() }; suspend { // This CMPXCHG can only fail if state is NOTIFIED. if (@cmpxchgStrong(usize, &self.state, state, @ptrToInt(&node), .Release, .Monotonic) != null) { hyperia.pool.schedule(.{}, &node.runnable); } } } } } else struct { pub fn set(self: *Self, token: T) ?*zap.Pool.Runnable { var state = @atomicLoad(usize, &self.state, .Monotonic); while (state != NOTIFIED) { if (state != EMPTY) { state = @cmpxchgWeak(usize, &self.state, state, NOTIFIED, .Acquire, .Monotonic) orelse { const node = @intToPtr(*Node, state); node.token = token; @fence(.Release); return &node.runnable; }; } else { state = @cmpxchgWeak(usize, &self.state, state, NOTIFIED, .Monotonic, .Monotonic) orelse { return null; }; } } return null; } pub fn wait(self: *Self) T { var state = @atomicLoad(usize, &self.state, .Monotonic); defer @atomicStore(usize, &self.state, EMPTY, .Monotonic); if (state != NOTIFIED) { var node: Node = .{ .token = mem.zeroes(T), .frame = @frame() }; suspend { // This CMPXCHG can only fail if state is NOTIFIED. if (@cmpxchgStrong(usize, &self.state, state, @ptrToInt(&node), .Release, .Monotonic) != null) { hyperia.pool.schedule(.{}, &node.runnable); } } @fence(.Acquire); return node.token; } return mem.zeroes(T); } }; }; } pub fn AsyncQueue(comptime T: type) type { return struct { const Self = @This(); queue: Queue(T) = .{}, closed: bool = false, event: AsyncAutoResetEvent(void) = .{}, pub fn close(self: *Self) void { @atomicStore(bool, &self.closed, true, .Monotonic); while (true) { const runnable = self.event.set() orelse break; hyperia.pool.schedule(.{}, runnable); } } pub fn peek(self: *const Self) usize { return self.queue.peek(); } pub fn push(self: *Self, src: *Queue(T).Node) void { self.queue.tryPush(src); if (self.event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } } pub fn pushBatch(self: *Self, first: *Queue(T).Node, last: *Queue(T).Node, count: usize) void { self.queue.tryPushBatch(first, last, count); if (self.event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } } pub fn tryPop(self: *Self) ?*Queue(T).Node { return self.queue.tryPop(); } pub fn tryPopBatch(self: *Self, b_first: **Queue(T).Node, b_last: **Queue(T).Node) usize { return self.queue.tryPopBatch(b_first, b_last); } pub fn pop(self: *Self) ?*Queue(T).Node { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { return self.tryPop() orelse { self.event.wait(); continue; }; } return null; } pub fn popBatch(self: *Self, b_first: **Queue(T).Node, b_last: **Queue(T).Node) callconv(.Async) usize { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { const num_items = self.tryPopBatch(b_first, b_last); if (num_items == 0) { self.event.wait(); continue; } return num_items; } return 0; } }; } pub fn AsyncSink(comptime T: type) type { return struct { const Self = @This(); sink: Sink(T) = .{}, closed: bool = false, event: AsyncAutoResetEvent(void) = .{}, pub fn close(self: *Self) void { @atomicStore(bool, &self.closed, true, .Monotonic); while (true) { const runnable = self.event.set() orelse break; hyperia.pool.schedule(.{}, runnable); } } pub fn push(self: *Self, src: *Sink(T).Node) void { self.sink.tryPush(src); if (self.event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } } pub fn pushBatch(self: *Self, first: *Sink(T).Node, last: *Sink(T).Node) void { self.sink.tryPushBatch(first, last); if (self.event.set()) |runnable| { hyperia.pool.schedule(.{}, runnable); } } pub fn tryPop(self: *Self) ?*Sink(T).Node { return self.sink.tryPop(); } pub fn tryPopBatch(self: *Self, b_first: **Sink(T).Node, b_last: **Sink(T).Node) usize { return self.sink.tryPopBatch(b_first, b_last); } pub fn pop(self: *Self) ?*Sink(T).Node { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { return self.tryPop() orelse { self.event.wait(); continue; }; } return null; } pub fn popBatch(self: *Self, b_first: **Sink(T).Node, b_last: **Sink(T).Node) usize { while (!@atomicLoad(bool, &self.closed, .Monotonic)) { const num_items = self.tryPopBatch(b_first, b_last); if (num_items == 0) { self.event.wait(); continue; } return num_items; } return 0; } }; } /// Unbounded MPSC queue supporting batching operations that keeps track of the number of items queued. pub fn Queue(comptime T: type) type { return struct { pub const Node = struct { next: ?*Node = null, value: T, }; const Self = @This(); front: Node align(cache_line_length) = .{ .value = undefined }, count: usize align(cache_line_length) = 0, back: ?*Node align(cache_line_length) = null, pub fn peek(self: *const Self) usize { const count = @atomicLoad(usize, &self.count, .Monotonic); assert(count >= 0); return count; } pub fn tryPush(self: *Self, src: *Node) void { assert(@atomicRmw(usize, &self.count, .Add, 1, .Monotonic) >= 0); src.next = null; const old_back = @atomicRmw(?*Node, &self.back, .Xchg, src, .AcqRel) orelse &self.front; @atomicStore(?*Node, &old_back.next, src, .Release); } pub fn tryPushBatch(self: *Self, first: *Node, last: *Node, count: usize) void { assert(@atomicRmw(usize, &self.count, .Add, count, .Monotonic) >= 0); last.next = null; const old_back = @atomicRmw(?*Node, &self.back, .Xchg, last, .AcqRel) orelse &self.front; @atomicStore(?*Node, &old_back.next, first, .Release); } pub fn tryPop(self: *Self) ?*Node { var first = @atomicLoad(?*Node, &self.front.next, .Acquire) orelse return null; if (@atomicLoad(?*Node, &first.next, .Acquire)) |next| { self.front.next = next; assert(@atomicRmw(usize, &self.count, .Sub, 1, .Monotonic) >= 1); return first; } var last = @atomicLoad(?*Node, &self.back, .Acquire) orelse &self.front; if (first != last) return null; self.front.next = null; if (@cmpxchgStrong(?*Node, &self.back, last, &self.front, .AcqRel, .Acquire) == null) { assert(@atomicRmw(usize, &self.count, .Sub, 1, .Monotonic) >= 1); return first; } var maybe_next = @atomicLoad(?*Node, &first.next, .Acquire); while (maybe_next == null) : (os.sched_yield() catch {}) { maybe_next = @atomicLoad(?*Node, &first.next, .Acquire); } self.front.next = maybe_next; assert(@atomicRmw(usize, &self.count, .Sub, 1, .Monotonic) >= 1); return first; } pub fn tryPopBatch(self: *Self, b_first: **Node, b_last: **Node) usize { var front = @atomicLoad(?*Node, &self.front.next, .Acquire) orelse return 0; b_first.* = front; var maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); var count: usize = 0; while (maybe_next) |next| { count += 1; b_last.* = front; front = next; maybe_next = @atomicLoad(?*Node, &next.next, .Acquire); } var last = @atomicLoad(?*Node, &self.back, .Acquire) orelse &self.front; if (front != last) { self.front.next = front; assert(@atomicRmw(usize, &self.count, .Sub, count, .Monotonic) >= count); return count; } self.front.next = null; if (@cmpxchgStrong(?*Node, &self.back, last, &self.front, .AcqRel, .Acquire) == null) { count += 1; b_last.* = front; assert(@atomicRmw(usize, &self.count, .Sub, count, .Monotonic) >= count); return count; } maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); while (maybe_next == null) : (os.sched_yield() catch {}) { maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); } count += 1; self.front.next = maybe_next; b_last.* = front; assert(@atomicRmw(usize, &self.count, .Sub, count, .Monotonic) >= count); return count; } }; } /// Unbounded MPSC queue supporting batching operations. pub fn Sink(comptime T: type) type { return struct { pub const Node = struct { next: ?*Node = null, value: T, }; const Self = @This(); front: Node align(cache_line_length) = .{ .value = undefined }, back: ?*Node align(cache_line_length) = null, pub fn tryPush(self: *Self, src: *Node) void { src.next = null; const old_back = @atomicRmw(?*Node, &self.back, .Xchg, src, .AcqRel) orelse &self.front; @atomicStore(?*Node, &old_back.next, src, .Release); } pub fn tryPushBatch(self: *Self, first: *Node, last: *Node) void { last.next = null; const old_back = @atomicRmw(?*Node, &self.back, .Xchg, last, .AcqRel) orelse &self.front; @atomicStore(?*Node, &old_back.next, first, .Release); } pub fn tryPop(self: *Self) ?*Node { var first = @atomicLoad(?*Node, &self.front.next, .Acquire) orelse return null; if (@atomicLoad(?*Node, &first.next, .Acquire)) |next| { self.front.next = next; return first; } var last = @atomicLoad(?*Node, &self.back, .Acquire) orelse &self.front; if (first != last) return null; self.front.next = null; if (@cmpxchgStrong(?*Node, &self.back, last, &self.front, .AcqRel, .Acquire) == null) { return first; } var maybe_next = @atomicLoad(?*Node, &first.next, .Acquire); while (maybe_next == null) : (os.sched_yield() catch {}) { maybe_next = @atomicLoad(?*Node, &first.next, .Acquire); } self.front.next = maybe_next; return first; } pub fn tryPopBatch(self: *Self, b_first: **Node, b_last: **Node) usize { var front = @atomicLoad(?*Node, &self.front.next, .Acquire) orelse return 0; b_first.* = front; var maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); var count: usize = 0; while (maybe_next) |next| { count += 1; b_last.* = front; front = next; maybe_next = @atomicLoad(?*Node, &next.next, .Acquire); } var last = @atomicLoad(?*Node, &self.back, .Acquire) orelse &self.front; if (front != last) { self.front.next = front; return count; } self.front.next = null; if (@cmpxchgStrong(?*Node, &self.back, last, &self.front, .AcqRel, .Acquire) == null) { count += 1; b_last.* = front; return count; } maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); while (maybe_next == null) : (os.sched_yield() catch {}) { maybe_next = @atomicLoad(?*Node, &front.next, .Acquire); } count += 1; self.front.next = maybe_next; b_last.* = front; return count; } }; } test { testing.refAllDecls(Queue(u64)); testing.refAllDecls(AsyncQueue(u64)); testing.refAllDecls(Sink(u64)); testing.refAllDecls(AsyncSink(u64)); testing.refAllDecls(AsyncAutoResetEvent(void)); testing.refAllDecls(AsyncAutoResetEvent(usize)); } test "mpsc/sink: push and pop 60,000 u64s with 15 producers" { const NUM_ITEMS = 60_000; const NUM_PRODUCERS = 15; const TestSink = Sink(u64); const Context = struct { allocator: *mem.Allocator, sink: *TestSink, fn runProducer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_PRODUCERS) : (i += 1) { const node = try self.allocator.create(TestSink.Node); node.* = .{ .value = @intCast(u64, i) }; self.sink.tryPush(node); } } fn runConsumer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS) : (i += 1) { self.allocator.destroy(while (true) { if (self.sink.tryPop()) |node| { break node; } } else unreachable); } } }; const allocator = testing.allocator; var sink: TestSink = .{}; const consumer = try std.Thread.spawn(Context.runConsumer, Context{ .allocator = allocator, .sink = &sink, }); defer consumer.wait(); var producers: [NUM_PRODUCERS]*std.Thread = undefined; defer for (producers) |producer| producer.wait(); for (producers) |*producer| { producer.* = try std.Thread.spawn(Context.runProducer, Context{ .allocator = allocator, .sink = &sink, }); } } test "mpsc/sink: batch push and pop 60,000 u64s with 15 producers" { const NUM_ITEMS = 60_000; const NUM_ITEMS_PER_BATCH = 100; const NUM_PRODUCERS = 15; const TestSink = Sink(u64); const Context = struct { allocator: *mem.Allocator, sink: *TestSink, fn runBatchProducer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_PRODUCERS) : (i += NUM_ITEMS_PER_BATCH) { var first = try self.allocator.create(TestSink.Node); first.* = .{ .value = @intCast(u64, i) }; const last = first; var j: usize = 0; while (j < NUM_ITEMS_PER_BATCH - 1) : (j += 1) { const node = try self.allocator.create(TestSink.Node); node.* = .{ .next = first, .value = @intCast(u64, i) + 1 + @intCast(u64, j), }; first = node; } self.sink.tryPushBatch(first, last); } } fn runBatchConsumer(self: @This()) !void { var first: *TestSink.Node = undefined; var last: *TestSink.Node = undefined; var i: usize = 0; while (i < NUM_ITEMS) { var j = self.sink.tryPopBatch(&first, &last); i += j; while (j > 0) : (j -= 1) { const next = first.next; self.allocator.destroy(first); first = next orelse continue; } } } }; const allocator = testing.allocator; var sink: TestSink = .{}; const consumer = try std.Thread.spawn(Context.runBatchConsumer, Context{ .allocator = allocator, .sink = &sink, }); defer consumer.wait(); var producers: [NUM_PRODUCERS]*std.Thread = undefined; defer for (producers) |producer| producer.wait(); for (producers) |*producer| { producer.* = try std.Thread.spawn(Context.runBatchProducer, Context{ .allocator = allocator, .sink = &sink, }); } } test "mpsc/queue: push and pop 60,000 u64s with 15 producers" { const NUM_ITEMS = 60_000; const NUM_PRODUCERS = 15; const TestQueue = Queue(u64); const Context = struct { allocator: *mem.Allocator, queue: *TestQueue, fn runProducer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_PRODUCERS) : (i += 1) { const node = try self.allocator.create(TestQueue.Node); node.* = .{ .value = @intCast(u64, i) }; self.queue.tryPush(node); } } fn runConsumer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS) : (i += 1) { self.allocator.destroy(while (true) { if (self.queue.tryPop()) |node| { break node; } } else unreachable); } } }; const allocator = testing.allocator; var queue: TestQueue = .{}; defer testing.expect(queue.peek() == 0); const consumer = try std.Thread.spawn(Context.runConsumer, Context{ .allocator = allocator, .queue = &queue, }); defer consumer.wait(); var producers: [NUM_PRODUCERS]*std.Thread = undefined; defer for (producers) |producer| producer.wait(); for (producers) |*producer| { producer.* = try std.Thread.spawn(Context.runProducer, Context{ .allocator = allocator, .queue = &queue, }); } } test "mpsc/queue: batch push and pop 60,000 u64s with 15 producers" { const NUM_ITEMS = 60_000; const NUM_ITEMS_PER_BATCH = 100; const NUM_PRODUCERS = 15; const TestQueue = Queue(u64); const Context = struct { allocator: *mem.Allocator, queue: *TestQueue, fn runBatchProducer(self: @This()) !void { var i: usize = 0; while (i < NUM_ITEMS / NUM_PRODUCERS) : (i += NUM_ITEMS_PER_BATCH) { var first = try self.allocator.create(TestQueue.Node); first.* = .{ .value = @intCast(u64, i) }; const last = first; var j: usize = 0; while (j < NUM_ITEMS_PER_BATCH - 1) : (j += 1) { const node = try self.allocator.create(TestQueue.Node); node.* = .{ .next = first, .value = @intCast(u64, i) + 1 + @intCast(u64, j), }; first = node; } self.queue.tryPushBatch(first, last, NUM_ITEMS_PER_BATCH); } } fn runBatchConsumer(self: @This()) !void { var first: *TestQueue.Node = undefined; var last: *TestQueue.Node = undefined; var i: usize = 0; while (i < NUM_ITEMS) { var j = self.queue.tryPopBatch(&first, &last); i += j; while (j > 0) : (j -= 1) { const next = first.next; self.allocator.destroy(first); first = next orelse continue; } } } }; const allocator = testing.allocator; var queue: TestQueue = .{}; defer testing.expect(queue.peek() == 0); const consumer = try std.Thread.spawn(Context.runBatchConsumer, Context{ .allocator = allocator, .queue = &queue, }); defer consumer.wait(); var producers: [NUM_PRODUCERS]*std.Thread = undefined; defer for (producers) |producer| producer.wait(); for (producers) |*producer| { producer.* = try std.Thread.spawn(Context.runBatchProducer, Context{ .allocator = allocator, .queue = &queue, }); } }
mpsc.zig
const std = @import("std"); const int = @import("int.zig"); pub const blz = @import("nds/blz.zig"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const testing = std.testing; const lu16 = int.lu16; const lu32 = int.lu32; pub const formats = @import("nds/formats.zig"); pub const fs = @import("nds/fs.zig"); pub const Banner = @import("nds/banner.zig").Banner; pub const Header = @import("nds/header.zig").Header; comptime { std.testing.refAllDecls(@This()); } pub const Range = extern struct { start: lu32, end: lu32, pub fn init(start: usize, end: usize) Range { return .{ .start = lu32.init(@intCast(u32, start)), .end = lu32.init(@intCast(u32, end)), }; } pub fn len(r: Range) u32 { return r.end.value() - r.start.value(); } pub fn slice(r: Range, s: anytype) mem.Span(@TypeOf(s)) { return s[r.start.value()..r.end.value()]; } }; pub const Slice = extern struct { start: lu32, len: lu32, pub fn fromSlice(data: []const u8, s: []const u8) Slice { const start = @ptrToInt(s.ptr) - @ptrToInt(data.ptr); return init(start, s.len); } pub fn init(start: usize, len: usize) Slice { return .{ .start = lu32.init(@intCast(u32, start)), .len = lu32.init(@intCast(u32, len)), }; } pub fn end(s: Slice) u32 { return s.start.value() + s.len.value(); } pub fn slice(sl: Slice, s: anytype) mem.Span(@TypeOf(s)) { return s[sl.start.value()..sl.end()]; } }; pub const Overlay = extern struct { overlay_id: lu32, ram_address: lu32, ram_size: lu32, bss_size: lu32, static_initialiser_start_address: lu32, static_initialiser_end_address: lu32, file_id: lu32, reserved: [4]u8, }; pub const Rom = struct { data: std.ArrayList(u8), pub fn new(allocator: mem.Allocator, game_title: []const u8, gamecode: []const u8, opts: struct { arm9_size: u32 = 0, arm7_size: u32 = 0, files: u32 = 0, }) !Rom { var res = Rom{ .data = std.ArrayList(u8).init(allocator) }; var writer = res.data.writer(); errdefer res.deinit(); var h = mem.zeroes(Header); mem.copy(u8, &h.game_title, game_title); mem.copy(u8, &h.gamecode, gamecode); h.secure_area_delay = lu16.init(0x051E); h.rom_header_size = lu32.init(0x4000); h.digest_ntr_region_offset = lu32.init(0x4000); h.title_id_rest = "\x00\x03\x00".*; try writer.writeAll(mem.asBytes(&h)); try writer.writeAll("\x00" ** (0x4000 - @sizeOf(Header))); h.arm9.entry_address = lu32.init(0x2000000); h.arm9.ram_address = lu32.init(0x2000000); h.arm9.offset = lu32.init(@intCast(u32, res.data.len)); h.arm9.size = lu32.init(opts.arm9_size); try writer.writeByteNTimes(0, h.arm9.size.value()); try writer.writeByteNTimes(0, 0x8000 -| res.data.len); h.arm7.ram_address = lu32.init(0x2000000); h.arm7.entry_address = lu32.init(0x2000000); h.arm7.offset = lu32.init(@intCast(u32, res.data.len)); h.arm7.size = lu32.init(opts.arm7_size); try writer.writeByteNTimes(0, h.arm7.size.value()); h.fat.start = lu32.init(@intCast(u32, res.data.len)); h.fat.len = lu32.init(opts.files * @sizeOf(Range)); try writer.writeByteNTimes(0, h.fat.len.value()); return res; } pub fn header(rom: Rom) *Header { return mem.bytesAsValue(Header, rom.data.items[0..@sizeOf(Header)]); } pub fn banner(rom: Rom) ?*Banner { const h = rom.header(); const offset = h.banner_offset.value(); if (offset == 0) return null; const bytes = rom.data.items[offset..][0..@sizeOf(Banner)]; return mem.bytesAsValue(Banner, bytes); } /// Returns the arm9 section of the rom. Note here that this section could /// be encoded and therefor not very useful. pub fn arm9(rom: Rom) []u8 { const h = rom.header(); const offset = h.arm9.offset.value(); return rom.data.items[offset..][0..h.arm9.size.value()]; } pub fn nitroFooter(rom: Rom) []u8 { const h = rom.header(); const offset = h.arm9.offset.value() + h.arm9.size.value(); const footer = rom.data.items[offset..][0..12]; if (@bitCast(lu32, footer[0..4].*).value() != 0xDEC00621) return footer[0..0]; return footer; } pub fn arm7(rom: Rom) []u8 { const h = rom.header(); const offset = h.arm7.offset.value(); return rom.data.items[offset..][0..h.arm7.size.value()]; } pub fn arm9OverlayTable(rom: Rom) []Overlay { const h = rom.header(); const bytes = h.arm9_overlay.slice(rom.data.items); return mem.bytesAsSlice(Overlay, bytes); } pub fn arm7OverlayTable(rom: Rom) []Overlay { const h = rom.header(); const bytes = h.arm7_overlay.slice(rom.data.items); return mem.bytesAsSlice(Overlay, bytes); } pub fn fileSystem(rom: Rom) fs.Fs { const h = rom.header(); const fnt_bytes = h.fnt.slice(rom.data.items); const fat_bytes = h.fat.slice(rom.data.items); return fs.Fs.fromFnt( fnt_bytes, mem.bytesAsSlice(Range, fat_bytes), rom.data.items, ); } pub fn resizeSection(rom: *Rom, old: []const u8, new_size: usize) ![]u8 { const data = &rom.data; var buf: [1 * (1024 * 1024)]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buf); const sections = try rom.buildSectionTable(fba.allocator()); const old_slice = Slice.fromSlice(data.items, old); const old_start = old_slice.start.value(); const old_len = old_slice.len.value(); const section_index = for (sections) |s, i| { const slice = s.toSlice(data.items); if (slice.start.value() == old_start and slice.len.value() == old_len) { break i; } } else unreachable; const is_last_section = section_index == sections.len - 1; const following_section_start = if (is_last_section) math.maxInt(u32) else sections[section_index + 1].toSlice(data.items).start.value(); const potential_new_end = old_start + new_size; const can_perform_in_place_resize = potential_new_end <= following_section_start; if (can_perform_in_place_resize) { // If there is room, we can beform the resize of the section inline in memory. // This only requires modifying the section offset in the rom. No copy required. const section = sections[section_index]; section.set(data.items, Slice.init(old_start, new_size)); const h = rom.header(); h.header_checksum = lu16.init(h.calcChecksum()); return data.items[old_start..][0..new_size]; } const arm9_section = rom.arm9(); const can_move_to_end_of_file = old.ptr != arm9_section.ptr; const new_start = if (can_move_to_end_of_file) blk: { // Most sections can be moved to the end of the rom. This is more efficient // than making room for the section where it is currently located. It will // fragment the rom a little, but we don't have to perform massive copies // using this method. const last_section = sections[sections.len - 1].toSlice(data.items); const last_section_end = last_section.end(); const new_start = mem.alignForward(last_section_end, 128); if (new_start + new_size > data.items.len) try data.resize(data.items.len * 2); mem.copy( u8, data.items[new_start..][0..new_size], data.items[old_start..][0..old.len], ); const section = sections[section_index]; section.set(data.items, Slice.init(new_start, new_size)); break :blk new_start; } else blk: { // Some sections (arm9) are not allowed to be moved, so we have to make room // for it where it is currently stored. This is expensive, but there is really // no other option. const extra_bytes = new_size - old.len; const old_sec_end = old_slice.end(); const old_rom_end = sections[sections.len - 1].toSlice(data.items).end(); for (sections[section_index + 1 ..]) |section| { const section_slice = section.toSlice(data.items); section.set(data.items, Slice.init( section_slice.start.value() + extra_bytes, section_slice.len.value(), )); } const section = sections[section_index]; section.set(data.items, Slice.init(old_start, new_size)); const new_rom_end = sections[sections.len - 1].toSlice(data.items).end(); if (new_rom_end > data.items.len) try data.resize(data.items.len * 2); mem.copyBackwards( u8, data.items[old_sec_end + extra_bytes ..], data.items[old_sec_end..old_rom_end], ); break :blk old_start; }; const last_section = sections[sections.len - 1]; const end = last_section.toSlice(data.items).end(); // Update header after resize const h = rom.header(); h.total_used_rom_size = lu32.init(@intCast(u32, end)); h.device_capacity = blk: { // Devicecapacity (Chipsize = 128KB SHL nn) (eg. 7 = 16MB) const size = data.items.len; var device_cap: u6 = 0; while (@shlExact(@as(u64, 128 * 1024), device_cap) < size) : (device_cap += 1) {} break :blk device_cap; }; h.header_checksum = lu16.init(h.calcChecksum()); return data.items[new_start..][0..new_size]; } /// A generic structure for pointing to memory in the nds rom. The memory /// pointed to is the memory for a `start/end` or `start/len` pair. This /// structure does NOT point to the memory that these `start/X` pairs /// refer to, but to the pairs them self. The reason for this is /// so that we can modify this `start/X` indexes as we move sections /// around the rom during a resize. const Section = struct { start_index: u32, other_index: u32, kind: Kind, const Kind = enum { range, slice, }; fn fromRange(data: []const u8, range: *const Range) Section { return fromStartEnd(data, &range.start, &range.end); } fn fromSlice(data: []const u8, slice: *const Slice) Section { return fromStartLen(data, &slice.start, &slice.len); } fn fromArm(data: []const u8, arm: *const Header.Arm) Section { return fromStartLen(data, &arm.offset, &arm.size); } fn fromStartEnd(data: []const u8, start: *const lu32, end: *const lu32) Section { return fromAny(data, .range, start, end); } fn fromStartLen(data: []const u8, start: *const lu32, len: *const lu32) Section { return fromAny(data, .slice, start, len); } fn fromAny(data: []const u8, kind: Kind, start: *const lu32, other: *const lu32) Section { const data_end = @ptrToInt(data.ptr) + data.len; const start_index = @ptrToInt(start) - @ptrToInt(data.ptr); const other_index = @ptrToInt(other) - @ptrToInt(data.ptr); debug.assert(start_index + @sizeOf(lu32) <= data_end); debug.assert(other_index + @sizeOf(lu32) <= data_end); return .{ .start_index = @intCast(u32, start_index), .other_index = @intCast(u32, other_index), .kind = kind, }; } fn toSlice(section: Section, data: []const u8) Slice { // We discard const here, so that we can call `getPtr`. This // is safe, as `getPtr` only needs a mutable pointer so that // it can return one. We don't modify the pointee, so there // is nothing unsafe about this discard. const const_discarded = @intToPtr([*]u8, @ptrToInt(data.ptr))[0..data.len]; const start = section.getPtr(const_discarded, .start).value(); const other = section.getPtr(const_discarded, .other).value(); const len = other - start * @boolToInt(section.kind == .range); return Slice.init(start, len); } fn getPtr(section: Section, data: []u8, field: enum { start, other }) *lu32 { const index = switch (field) { .start => section.start_index, .other => section.other_index, }; const bytes = data[index..][0..@sizeOf(lu32)]; return mem.bytesAsValue(lu32, bytes); } fn set(section: Section, data: []u8, slice: Slice) void { section.getPtr(data, .start).* = slice.start; switch (section.kind) { .slice => section.getPtr(data, .other).* = slice.len, .range => section.getPtr(data, .other).* = lu32.init(slice.end()), } } fn before(data: []const u8, a: Section, b: Section) bool { const a_slice = a.toSlice(data); const b_slice = b.toSlice(data); return a_slice.start.value() < b_slice.start.value(); } }; fn buildSectionTable(rom: Rom, allocator: mem.Allocator) ![]Section { const h = rom.header(); const file_system = rom.fileSystem(); const fat = file_system.fat; var sections = std.ArrayList(Section).init(allocator); try sections.ensureTotalCapacity(7 + fat.len); const data = &rom.data; sections.appendAssumeCapacity(Section.fromStartLen( data.items, &h.banner_offset, &h.banner_size, )); sections.appendAssumeCapacity(Section.fromArm(data.items, &h.arm9)); sections.appendAssumeCapacity(Section.fromArm(data.items, &h.arm7)); sections.appendAssumeCapacity(Section.fromSlice(data.items, &h.arm9_overlay)); sections.appendAssumeCapacity(Section.fromSlice(data.items, &h.arm7_overlay)); sections.appendAssumeCapacity(Section.fromSlice(data.items, &h.fat)); sections.appendAssumeCapacity(Section.fromSlice(data.items, &h.fnt)); for (fat) |*f| sections.appendAssumeCapacity(Section.fromRange(data.items, f)); // Sort sections by where they appear in the rom. std.sort.sort(Section, sections.items, data.items, Section.before); return sections.toOwnedSlice(); } pub fn fromFile(file: std.fs.File, allocator: mem.Allocator) !Rom { const reader = file.reader(); const size = try file.getEndPos(); try file.seekTo(0); if (size < @sizeOf(Header)) return error.InvalidRom; var data = std.ArrayList(u8).init(allocator); errdefer data.deinit(); try data.resize(size); try reader.readNoEof(data.items); const res = Rom{ .data = data }; try res.header().validate(); // TODO: we should validate that all the offsets and sizes are not // out of bounds of the rom.data.items. return res; } pub fn write(rom: Rom, writer: anytype) !void { // The contract here is that once you have an `nds.Rom`, it should // always be a valid rom, so we just assert that this is true here // for sanity. rom.header().validate() catch unreachable; try writer.writeAll(rom.data.items); } pub fn deinit(rom: Rom) void { rom.data.deinit(); } };
src/core/rom/nds.zig
const peripherals = @import("peripherals.zig"); const AddressRange = peripherals.AddressRange; const std = @import("std"); /// A structure containin info about the BCM2835 chip /// see this website which does a brilliant job of explaining everything /// https://www.pieter-jan.com/node/15 /// The most important thing is to look at the BCM2835 peripheral manual (pi1 / p2) /// and then see in section 1.2.3 how the register addresses in the manual relate with /// the physical memory. Then see the Gpio section for an explanation of how to /// operate the Gpio pins using the registers. /// The primary source for all of this is the Broadcom BCM2835 ARM Peripherals Manual pub const BoardInfo = struct { /// the *physical* address space of all peripherals pub const peripheral_addresses: AddressRange = .{ .start = 0x20000000, .len = 0xFFFFFF }; // address space of the GPIO registers pub const gpio_registers = .{ .start = peripheral_addresses.start + 0x200000, .len = 0xB4 }; // /// physical address space of the gpio registers GPFSEL{n} (function select) pub const gpfsel_registers: AddressRange = .{ .start = peripheral_addresses.start + 0x200000, .len = 6 * 4 }; /// physical address space of the gpio registers GPSET{n} (output setting) pub const gpset_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x1C, .len = 2 * 4 }; /// physical address space of the gpio registers GPCLR{n} (clearing pin output) pub const gpclr_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x28, .len = 2 * 4 }; /// physical address space of the gpio registers GPLEV{n} (reading pin levels) pub const gplev_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x34, .len = 2 * 4 }; /// phys address space of the gpio register GPPUD (pull up / pull down) pub const gppud_register: AddressRange = .{ .start = gpfsel_registers.start + 0x94, .len = 1 * 4 }; /// phys address space of the gpio register GPPUDCLK{n} (pull up / down clocks) pub const gppudclk_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x98, .len = 2 * 4 }; /// the number of GPIO pins. Pin indices start at 0. pub const NUM_GPIO_PINS = 53; }; pub const Bcm2385GpioMemoryMapper = struct { const Self: type = @This(); /// the GpioMemMapper interface memory_mapper: peripherals.GpioMemMapper, /// the raw bytes representing the memory mapping devgpiomem: []align(std.mem.page_size) u8, pub fn init() !Self { const devgpiomem = try std.fs.openFileAbsolute("/dev/gpiomem", std.fs.File.OpenFlags{ .read = true, .write = true }); defer devgpiomem.close(); return Self{ .devgpiomem = try std.os.mmap(null, BoardInfo.gpio_registers.len, std.os.PROT.READ | std.os.PROT.WRITE, std.os.MAP.SHARED, devgpiomem.handle, 0), .memory_mapper = .{ .map_fn = Self.memoryMap } }; } /// unmap the mapped memory pub fn deinit(self: Self) void { std.os.munmap(self.devgpiomem); } pub fn memoryMap(interface: *peripherals.GpioMemMapper) !peripherals.GpioRegisterMemory { var self = @fieldParentPtr(Self, "memory_mapper", interface); return std.mem.bytesAsSlice(u32, self.devgpiomem); } };
src/bcm2835.zig
usingnamespace @import("root").preamble; /// Allocator used to allocate memory for new tasks const task_alloc = os.memory.pmm.phys_heap; /// Load balancer lock. Locked when scheduler finds the best CPU for the task /// or when task terminates var balancer_lock = os.thread.Spinlock{}; /// Move to the next task. /// NOTE: Should be called in interrupt disabled context if its /// not the last time task runs pub fn wait() void { const waitCallback = struct { fn waitCallback(frame: *os.platform.InterruptFrame, _: usize) void { os.thread.preemption.saveCurrentState(frame); os.thread.preemption.awaitForTaskAndYield(frame); } }.waitCallback; os.platform.sched_call(waitCallback, undefined); } /// Equivalent to wait(), but allows to run custom callback on sched_stack. /// If callback returns true, task should be suspended pub fn waitWithCallback(params: struct { callback: fn (*os.platform.InterruptFrame, usize) bool, ctx: usize = undefined, }) void { const ParamsType = @TypeOf(params); const paramsAddr = @ptrToInt(&params); const waitCallback = struct { fn waitCallback(frame: *os.platform.InterruptFrame, ctx: usize) void { const passed = @intToPtr(*ParamsType, ctx); os.thread.preemption.saveCurrentState(frame); if (!passed.callback(frame, passed.ctx)) { return; } os.thread.preemption.awaitForTaskAndYield(frame); } }.waitCallback; os.platform.sched_call(waitCallback, paramsAddr); } /// Sleep + release spinlock pub fn waitReleaseSpinlock(spinlock: *os.thread.Spinlock) void { const callback = struct { fn callback(frame: *os.platform.InterruptFrame, ctx: usize) bool { const lock = @intToPtr(*os.thread.Spinlock, ctx); lock.ungrab(); return true; } }.callback; waitWithCallback(.{.callback = callback, .ctx = @ptrToInt(spinlock)}); } /// Terminate current task to never run it again pub fn leave() noreturn { const leaveCallback = struct { fn leaveCallback(frame: *os.platform.InterruptFrame, _: usize) void { os.thread.preemption.awaitForTaskAndYield(frame); } }.leaveCallback; os.platform.sched_call(leaveCallback, undefined); unreachable; } /// Preempt to the next task pub fn yield() void { const state = os.platform.get_and_disable_interrupts(); os.platform.thread.get_current_cpu().executable_tasks.enqueue(os.platform.get_current_task()); wait(); os.platform.set_interrupts(state); } /// Wake a task that has called `wait` pub fn wake(task: *os.thread.Task) void { os.platform.smp.cpus[task.allocated_core_id].executable_tasks.enqueue(task); } /// Initialize a task for usage, must call destroyTask to clean up /// You still have to initialize: /// * Paging context /// * Register state pub fn initTask(task: *os.thread.Task) !void { try task.allocStack(); errdefer task.freeStack(); // Find the best CPU for the task var best_cpu_idx: usize = 0; { const state = balancer_lock.lock(); // TODO: maybe something more sophisticated? for (os.platform.smp.cpus) |*cpu, i| { if (cpu.tasks_count < os.platform.smp.cpus[best_cpu_idx].tasks_count) { best_cpu_idx = i; } } task.allocated_core_id = best_cpu_idx; os.platform.smp.cpus[best_cpu_idx].tasks_count += 1; balancer_lock.unlock(state); } } /// Creates a new task on the heap and calls initTask() on it pub fn createTask(name: []const u8) !*os.thread.Task { const task = try task_alloc.create(os.thread.Task); errdefer task_alloc.destroy(task); task.name = name; try initTask(task); return task; } /// Create and start a new kernel task that calls a function with given arguments. /// Paging context is copied from the current one, task is automatically enqueued pub fn spawnTask(name: []const u8, func: anytype, args: anytype) !void { const task = try createTask(name); errdefer destroyTask(task); task.paging_context = os.platform.get_current_task().paging_context; // Initialize task in a way that it will execute func with args on the startup const entry = os.thread.NewTaskEntry.alloc(task, func, args); try os.platform.thread.init_task_call(task, entry); task.enqueue(); } /// Effectively destroy a task (cleanup after initTask() or createTask()) pub fn destroyTask(task: ?*os.thread.Task) void { const id = if (task) |t| t.allocated_core_id else 0; const state = balancer_lock.lock(); os.platform.smp.cpus[id].tasks_count -= 1; balancer_lock.unlock(state); if (task) |t| { task_alloc.destroy(t); } // TODO: Delete stacks in such a way that we can return from the current interrupt // in case it still is in use } /// Exit current task /// TODO: Should be reimplemented with URM pub fn exitTask() noreturn { destroyTask(os.platform.thread.self_exited()); leave(); } /// Initialize scheduler pub fn init(task: *os.thread.Task) void { const bsp = &os.platform.smp.cpus[0]; bsp.bootstrap_stacks(); os.platform.bsp_pre_scheduler_init(); os.platform.set_current_task(task); bsp.executable_tasks.init(bsp); }
subprojects/flork/src/thread/scheduler.zig
pub const LOCATION_API_VERSION = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (23) //-------------------------------------------------------------------------------- const CLSID_Location_Value = @import("../zig.zig").Guid.initString("e5b8e079-ee6d-4e33-a438-c87f2e959254"); pub const CLSID_Location = &CLSID_Location_Value; const CLSID_DefaultLocation_Value = @import("../zig.zig").Guid.initString("8b7fbfe0-5cd7-494a-af8c-283a65707506"); pub const CLSID_DefaultLocation = &CLSID_DefaultLocation_Value; const CLSID_LatLongReport_Value = @import("../zig.zig").Guid.initString("ed81c073-1f84-4ca8-a161-183c776bc651"); pub const CLSID_LatLongReport = &CLSID_LatLongReport_Value; const CLSID_CivicAddressReport_Value = @import("../zig.zig").Guid.initString("d39e7bdd-7d05-46b8-8721-80cf035f57d7"); pub const CLSID_CivicAddressReport = &CLSID_CivicAddressReport_Value; const CLSID_LatLongReportFactory_Value = @import("../zig.zig").Guid.initString("9dcc3cc8-8609-4863-bad4-03601f4c65e8"); pub const CLSID_LatLongReportFactory = &CLSID_LatLongReportFactory_Value; const CLSID_CivicAddressReportFactory_Value = @import("../zig.zig").Guid.initString("2a11f42c-3e81-4ad4-9cbe-45579d89671a"); pub const CLSID_CivicAddressReportFactory = &CLSID_CivicAddressReportFactory_Value; const CLSID_DispLatLongReport_Value = @import("../zig.zig").Guid.initString("7a7c3277-8f84-4636-95b2-ebb5507ff77e"); pub const CLSID_DispLatLongReport = &CLSID_DispLatLongReport_Value; const CLSID_DispCivicAddressReport_Value = @import("../zig.zig").Guid.initString("4c596aec-8544-4082-ba9f-eb0a7d8e65c6"); pub const CLSID_DispCivicAddressReport = &CLSID_DispCivicAddressReport_Value; pub const LOCATION_REPORT_STATUS = enum(i32) { NOT_SUPPORTED = 0, ERROR = 1, ACCESS_DENIED = 2, INITIALIZING = 3, RUNNING = 4, }; pub const REPORT_NOT_SUPPORTED = LOCATION_REPORT_STATUS.NOT_SUPPORTED; pub const REPORT_ERROR = LOCATION_REPORT_STATUS.ERROR; pub const REPORT_ACCESS_DENIED = LOCATION_REPORT_STATUS.ACCESS_DENIED; pub const REPORT_INITIALIZING = LOCATION_REPORT_STATUS.INITIALIZING; pub const REPORT_RUNNING = LOCATION_REPORT_STATUS.RUNNING; // TODO: this type is limited to platform 'windows6.1' const IID_ILocationReport_Value = @import("../zig.zig").Guid.initString("c8b7f7ee-75d0-4db9-b62d-7a0f369ca456"); pub const IID_ILocationReport = &IID_ILocationReport_Value; pub const ILocationReport = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSensorID: fn( self: *const ILocationReport, pSensorID: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTimestamp: fn( self: *const ILocationReport, pCreationTime: ?*SYSTEMTIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const ILocationReport, pKey: ?*const PROPERTYKEY, pValue: ?*PROPVARIANT, ) 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 ILocationReport_GetSensorID(self: *const T, pSensorID: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetSensorID(@ptrCast(*const ILocationReport, self), pSensorID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReport_GetTimestamp(self: *const T, pCreationTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetTimestamp(@ptrCast(*const ILocationReport, self), pCreationTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReport_GetValue(self: *const T, pKey: ?*const PROPERTYKEY, pValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReport.VTable, self.vtable).GetValue(@ptrCast(*const ILocationReport, self), pKey, pValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILatLongReport_Value = @import("../zig.zig").Guid.initString("7fed806d-0ef8-4f07-80ac-36a0beae3134"); pub const IID_ILatLongReport = &IID_ILatLongReport_Value; pub const ILatLongReport = extern struct { pub const VTable = extern struct { base: ILocationReport.VTable, GetLatitude: fn( self: *const ILatLongReport, pLatitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLongitude: fn( self: *const ILatLongReport, pLongitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorRadius: fn( self: *const ILatLongReport, pErrorRadius: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAltitude: fn( self: *const ILatLongReport, pAltitude: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAltitudeError: fn( self: *const ILatLongReport, pAltitudeError: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReport.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetLatitude(self: *const T, pLatitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetLatitude(@ptrCast(*const ILatLongReport, self), pLatitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetLongitude(self: *const T, pLongitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetLongitude(@ptrCast(*const ILatLongReport, self), pLongitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetErrorRadius(self: *const T, pErrorRadius: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetErrorRadius(@ptrCast(*const ILatLongReport, self), pErrorRadius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetAltitude(self: *const T, pAltitude: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetAltitude(@ptrCast(*const ILatLongReport, self), pAltitude); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReport_GetAltitudeError(self: *const T, pAltitudeError: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReport.VTable, self.vtable).GetAltitudeError(@ptrCast(*const ILatLongReport, self), pAltitudeError); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ICivicAddressReport_Value = @import("../zig.zig").Guid.initString("c0b19f70-4adf-445d-87f2-cad8fd711792"); pub const IID_ICivicAddressReport = &IID_ICivicAddressReport_Value; pub const ICivicAddressReport = extern struct { pub const VTable = extern struct { base: ILocationReport.VTable, GetAddressLine1: fn( self: *const ICivicAddressReport, pbstrAddress1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAddressLine2: fn( self: *const ICivicAddressReport, pbstrAddress2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCity: fn( self: *const ICivicAddressReport, pbstrCity: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStateProvince: fn( self: *const ICivicAddressReport, pbstrStateProvince: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPostalCode: fn( self: *const ICivicAddressReport, pbstrPostalCode: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCountryRegion: fn( self: *const ICivicAddressReport, pbstrCountryRegion: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDetailLevel: fn( self: *const ICivicAddressReport, pDetailLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReport.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetAddressLine1(self: *const T, pbstrAddress1: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetAddressLine1(@ptrCast(*const ICivicAddressReport, self), pbstrAddress1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetAddressLine2(self: *const T, pbstrAddress2: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetAddressLine2(@ptrCast(*const ICivicAddressReport, self), pbstrAddress2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetCity(self: *const T, pbstrCity: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetCity(@ptrCast(*const ICivicAddressReport, self), pbstrCity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetStateProvince(self: *const T, pbstrStateProvince: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetStateProvince(@ptrCast(*const ICivicAddressReport, self), pbstrStateProvince); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetPostalCode(self: *const T, pbstrPostalCode: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetPostalCode(@ptrCast(*const ICivicAddressReport, self), pbstrPostalCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetCountryRegion(self: *const T, pbstrCountryRegion: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetCountryRegion(@ptrCast(*const ICivicAddressReport, self), pbstrCountryRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReport_GetDetailLevel(self: *const T, pDetailLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReport.VTable, self.vtable).GetDetailLevel(@ptrCast(*const ICivicAddressReport, self), pDetailLevel); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILocation_Value = @import("../zig.zig").Guid.initString("ab2ece69-56d9-4f28-b525-de1b0ee44237"); pub const IID_ILocation = &IID_ILocation_Value; pub const ILocation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterForReport: fn( self: *const ILocation, pEvents: ?*ILocationEvents, reportType: ?*const Guid, dwRequestedReportInterval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterForReport: fn( self: *const ILocation, reportType: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReport: fn( self: *const ILocation, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReportStatus: fn( self: *const ILocation, reportType: ?*const Guid, pStatus: ?*LOCATION_REPORT_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReportInterval: fn( self: *const ILocation, reportType: ?*const Guid, pMilliseconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetReportInterval: fn( self: *const ILocation, reportType: ?*const Guid, millisecondsRequested: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDesiredAccuracy: fn( self: *const ILocation, reportType: ?*const Guid, pDesiredAccuracy: ?*LOCATION_DESIRED_ACCURACY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDesiredAccuracy: fn( self: *const ILocation, reportType: ?*const Guid, desiredAccuracy: LOCATION_DESIRED_ACCURACY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestPermissions: fn( self: *const ILocation, hParent: ?HWND, pReportTypes: [*]Guid, count: u32, fModal: 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 ILocation_RegisterForReport(self: *const T, pEvents: ?*ILocationEvents, reportType: ?*const Guid, dwRequestedReportInterval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).RegisterForReport(@ptrCast(*const ILocation, self), pEvents, reportType, dwRequestedReportInterval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_UnregisterForReport(self: *const T, reportType: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).UnregisterForReport(@ptrCast(*const ILocation, self), reportType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReport(self: *const T, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReport(@ptrCast(*const ILocation, self), reportType, ppLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReportStatus(self: *const T, reportType: ?*const Guid, pStatus: ?*LOCATION_REPORT_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReportStatus(@ptrCast(*const ILocation, self), reportType, pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetReportInterval(self: *const T, reportType: ?*const Guid, pMilliseconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetReportInterval(@ptrCast(*const ILocation, self), reportType, pMilliseconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_SetReportInterval(self: *const T, reportType: ?*const Guid, millisecondsRequested: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).SetReportInterval(@ptrCast(*const ILocation, self), reportType, millisecondsRequested); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_GetDesiredAccuracy(self: *const T, reportType: ?*const Guid, pDesiredAccuracy: ?*LOCATION_DESIRED_ACCURACY) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).GetDesiredAccuracy(@ptrCast(*const ILocation, self), reportType, pDesiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_SetDesiredAccuracy(self: *const T, reportType: ?*const Guid, desiredAccuracy: LOCATION_DESIRED_ACCURACY) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).SetDesiredAccuracy(@ptrCast(*const ILocation, self), reportType, desiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocation_RequestPermissions(self: *const T, hParent: ?HWND, pReportTypes: [*]Guid, count: u32, fModal: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ILocation.VTable, self.vtable).RequestPermissions(@ptrCast(*const ILocation, self), hParent, pReportTypes, count, fModal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_ILocationPower_Value = @import("../zig.zig").Guid.initString("193e7729-ab6b-4b12-8617-7596e1bb191c"); pub const IID_ILocationPower = &IID_ILocationPower_Value; pub const ILocationPower = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Connect: fn( self: *const ILocationPower, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const ILocationPower, ) 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 ILocationPower_Connect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationPower.VTable, self.vtable).Connect(@ptrCast(*const ILocationPower, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationPower_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationPower.VTable, self.vtable).Disconnect(@ptrCast(*const ILocationPower, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IDefaultLocation_Value = @import("../zig.zig").Guid.initString("a65af77e-969a-4a2e-8aca-33bb7cbb1235"); pub const IID_IDefaultLocation = &IID_IDefaultLocation_Value; pub const IDefaultLocation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetReport: fn( self: *const IDefaultLocation, reportType: ?*const Guid, pLocationReport: ?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReport: fn( self: *const IDefaultLocation, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport, ) 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 IDefaultLocation_SetReport(self: *const T, reportType: ?*const Guid, pLocationReport: ?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const IDefaultLocation.VTable, self.vtable).SetReport(@ptrCast(*const IDefaultLocation, self), reportType, pLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDefaultLocation_GetReport(self: *const T, reportType: ?*const Guid, ppLocationReport: ?*?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const IDefaultLocation.VTable, self.vtable).GetReport(@ptrCast(*const IDefaultLocation, self), reportType, ppLocationReport); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ILocationEvents_Value = @import("../zig.zig").Guid.initString("cae02bbf-798b-4508-a207-35a7906dc73d"); pub const IID_ILocationEvents = &IID_ILocationEvents_Value; pub const ILocationEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnLocationChanged: fn( self: *const ILocationEvents, reportType: ?*const Guid, pLocationReport: ?*ILocationReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStatusChanged: fn( self: *const ILocationEvents, reportType: ?*const Guid, newStatus: LOCATION_REPORT_STATUS, ) 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 ILocationEvents_OnLocationChanged(self: *const T, reportType: ?*const Guid, pLocationReport: ?*ILocationReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationEvents.VTable, self.vtable).OnLocationChanged(@ptrCast(*const ILocationEvents, self), reportType, pLocationReport); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationEvents_OnStatusChanged(self: *const T, reportType: ?*const Guid, newStatus: LOCATION_REPORT_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationEvents.VTable, self.vtable).OnStatusChanged(@ptrCast(*const ILocationEvents, self), reportType, newStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispLatLongReport_Value = @import("../zig.zig").Guid.initString("8ae32723-389b-4a11-9957-5bdd48fc9617"); pub const IID_IDispLatLongReport = &IID_IDispLatLongReport_Value; pub const IDispLatLongReport = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Latitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Longitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ErrorRadius: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Altitude: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AltitudeError: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IDispLatLongReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Latitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Latitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Longitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Longitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_ErrorRadius(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_ErrorRadius(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Altitude(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Altitude(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_AltitudeError(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_AltitudeError(@ptrCast(*const IDispLatLongReport, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispLatLongReport_get_Timestamp(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispLatLongReport.VTable, self.vtable).get_Timestamp(@ptrCast(*const IDispLatLongReport, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDispCivicAddressReport_Value = @import("../zig.zig").Guid.initString("16ff1a34-9e30-42c3-b44d-e22513b5767a"); pub const IID_IDispCivicAddressReport = &IID_IDispCivicAddressReport_Value; pub const IDispCivicAddressReport = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AddressLine1: fn( self: *const IDispCivicAddressReport, pAddress1: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AddressLine2: fn( self: *const IDispCivicAddressReport, pAddress2: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_City: fn( self: *const IDispCivicAddressReport, pCity: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StateProvince: fn( self: *const IDispCivicAddressReport, pStateProvince: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalCode: fn( self: *const IDispCivicAddressReport, pPostalCode: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CountryRegion: fn( self: *const IDispCivicAddressReport, pCountryRegion: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DetailLevel: fn( self: *const IDispCivicAddressReport, pDetailLevel: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timestamp: fn( self: *const IDispCivicAddressReport, pVal: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_AddressLine1(self: *const T, pAddress1: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_AddressLine1(@ptrCast(*const IDispCivicAddressReport, self), pAddress1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_AddressLine2(self: *const T, pAddress2: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_AddressLine2(@ptrCast(*const IDispCivicAddressReport, self), pAddress2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_City(self: *const T, pCity: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_City(@ptrCast(*const IDispCivicAddressReport, self), pCity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_StateProvince(self: *const T, pStateProvince: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_StateProvince(@ptrCast(*const IDispCivicAddressReport, self), pStateProvince); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_PostalCode(self: *const T, pPostalCode: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_PostalCode(@ptrCast(*const IDispCivicAddressReport, self), pPostalCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_CountryRegion(self: *const T, pCountryRegion: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_CountryRegion(@ptrCast(*const IDispCivicAddressReport, self), pCountryRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_DetailLevel(self: *const T, pDetailLevel: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_DetailLevel(@ptrCast(*const IDispCivicAddressReport, self), pDetailLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDispCivicAddressReport_get_Timestamp(self: *const T, pVal: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IDispCivicAddressReport.VTable, self.vtable).get_Timestamp(@ptrCast(*const IDispCivicAddressReport, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ILocationReportFactory_Value = @import("../zig.zig").Guid.initString("2daec322-90b2-47e4-bb08-0da841935a6b"); pub const IID_ILocationReportFactory = &IID_ILocationReportFactory_Value; pub const ILocationReportFactory = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ListenForReports: fn( self: *const ILocationReportFactory, requestedReportInterval: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopListeningForReports: fn( self: *const ILocationReportFactory, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const ILocationReportFactory, pVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReportInterval: fn( self: *const ILocationReportFactory, pMilliseconds: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReportInterval: fn( self: *const ILocationReportFactory, millisecondsRequested: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredAccuracy: fn( self: *const ILocationReportFactory, pDesiredAccuracy: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredAccuracy: fn( self: *const ILocationReportFactory, desiredAccuracy: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestPermissions: fn( self: *const ILocationReportFactory, hWnd: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_ListenForReports(self: *const T, requestedReportInterval: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).ListenForReports(@ptrCast(*const ILocationReportFactory, self), requestedReportInterval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_StopListeningForReports(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).StopListeningForReports(@ptrCast(*const ILocationReportFactory, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_Status(self: *const T, pVal: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_Status(@ptrCast(*const ILocationReportFactory, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_ReportInterval(self: *const T, pMilliseconds: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_ReportInterval(@ptrCast(*const ILocationReportFactory, self), pMilliseconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_put_ReportInterval(self: *const T, millisecondsRequested: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).put_ReportInterval(@ptrCast(*const ILocationReportFactory, self), millisecondsRequested); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_get_DesiredAccuracy(self: *const T, pDesiredAccuracy: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).get_DesiredAccuracy(@ptrCast(*const ILocationReportFactory, self), pDesiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_put_DesiredAccuracy(self: *const T, desiredAccuracy: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).put_DesiredAccuracy(@ptrCast(*const ILocationReportFactory, self), desiredAccuracy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILocationReportFactory_RequestPermissions(self: *const T, hWnd: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ILocationReportFactory.VTable, self.vtable).RequestPermissions(@ptrCast(*const ILocationReportFactory, self), hWnd); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ILatLongReportFactory_Value = @import("../zig.zig").Guid.initString("3f0804cb-b114-447d-83dd-390174ebb082"); pub const IID_ILatLongReportFactory = &IID_ILatLongReportFactory_Value; pub const ILatLongReportFactory = extern struct { pub const VTable = extern struct { base: ILocationReportFactory.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LatLongReport: fn( self: *const ILatLongReportFactory, pVal: ?*?*IDispLatLongReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReportFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ILatLongReportFactory_get_LatLongReport(self: *const T, pVal: ?*?*IDispLatLongReport) callconv(.Inline) HRESULT { return @ptrCast(*const ILatLongReportFactory.VTable, self.vtable).get_LatLongReport(@ptrCast(*const ILatLongReportFactory, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ICivicAddressReportFactory_Value = @import("../zig.zig").Guid.initString("bf773b93-c64f-4bee-beb2-67c0b8df66e0"); pub const IID_ICivicAddressReportFactory = &IID_ICivicAddressReportFactory_Value; pub const ICivicAddressReportFactory = extern struct { pub const VTable = extern struct { base: ILocationReportFactory.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CivicAddressReport: fn( self: *const ICivicAddressReportFactory, pVal: ?*?*IDispCivicAddressReport, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ILocationReportFactory.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICivicAddressReportFactory_get_CivicAddressReport(self: *const T, pVal: ?*?*IDispCivicAddressReport) callconv(.Inline) HRESULT { return @ptrCast(*const ICivicAddressReportFactory.VTable, self.vtable).get_CivicAddressReport(@ptrCast(*const ICivicAddressReportFactory, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; const IID__ILatLongReportFactoryEvents_Value = @import("../zig.zig").Guid.initString("16ee6cb7-ab3c-424b-849f-269be551fcbc"); pub const IID__ILatLongReportFactoryEvents = &IID__ILatLongReportFactoryEvents_Value; pub const _ILatLongReportFactoryEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID__ICivicAddressReportFactoryEvents_Value = @import("../zig.zig").Guid.initString("c96039ff-72ec-4617-89bd-84d88bedc722"); pub const IID__ICivicAddressReportFactoryEvents = &IID__ICivicAddressReportFactoryEvents_Value; pub const _ICivicAddressReportFactoryEvents = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (11) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/ole_automation.zig").IDispatch; const IUnknown = @import("../system/com.zig").IUnknown; const LOCATION_DESIRED_ACCURACY = @import("../devices/sensors.zig").LOCATION_DESIRED_ACCURACY; const PROPERTYKEY = @import("../system/properties_system.zig").PROPERTYKEY; const PROPVARIANT = @import("../storage/structured_storage.zig").PROPVARIANT; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/devices/geolocation.zig
const std = @import("std"); const objc = @import("objc.zig"); const Class = objc.Class; const object = objc.object; const id = objc.id; const SEL = objc.SEL; const IMP = objc.IMP; const c = @import("c.zig"); pub const Error = error{ FailedToGetClassForObject, FailedToGetInstanceVariable, ClassNotRegisteredWithRuntime, FailedToGetClassVariable, FailedToAllocateClassPair, NoSuchProtocol, }; // ----- Types ----- /// An opaque type that represents a method in a class definition. pub const Method = *c.objc_method; /// An opaque type that represents an instance variable. pub const Ivar = *c.objc_ivar; /// An opaque type that represents a category. pub const Category = *c.objc_category; /// An opaque type that represents an Objective-C declared property. pub const Property = *c.objc_property; pub const Protocol = c.objc_object; // ----- Working with Instances ----- /// Returns the class of an object. /// /// @param obj An id of the object you want to inspect. /// /// @return The class object of which object is an instance pub fn object_getClass(obj: id) Error!Class { return c.object_getClass(obj) orelse Error.FailedToGetClassForObject; } /// Obtains the value of an instance variable and the assosciated `Ivar` of a class instance. /// /// @param obj An instance of the class containing the instance variable whose value you wish to obtain. /// @param name The name of the instance variable whose value you wish to obtain. /// @param outValue On return, contains a pointer to the value of the instance variable. /// /// Returns a struct containing an `Ivar` that defines the type and name of the instance /// variable specified by `name` and the pub fn object_getInstanceVariable(comptime ValueType: type, obj: id, name: [:0]const u8) Error!struct { ivar: Ivar, value: ValueType } { var value_ptr: *ValueType = undefined; const maybe_ivar = c.object_getInstanceVariable(obj, name, @ptrCast([*c]?*anyopaque, &value_ptr)); return if (maybe_ivar) |ivar| .{ .ivar = ivar, .value = value_ptr.* } else Error.FailedToGetInstanceVariable; } // ----- Obtaining Class Definitions ---- /// Returns the class definition of a specified class, or an error if the class is not registered /// with the Objective-C runtime. /// /// @param name The name of the class to look up. /// /// @note getClass is different from lookUpClass in that if the class /// is not registered, getClass calls the class handler callback and then checks /// a second time to see whether the class is registered. lookUpClass does /// not call the class handler callback. /// /// @warning Earlier implementations of this function (prior to OS X v10.0) /// terminate the program if the class does not exist. pub fn getClass(class_name: [:0]const u8) Error!Class { return c.objc_getClass(class_name) orelse Error.ClassNotRegisteredWithRuntime; } /// Returns the metaclass definition of a specified class, or an error if the class is not registered /// with the Objective-C runtime. /// /// @param name The name of the class to look up. /// /// @note If the definition for the named class is not registered, this function calls the class handler /// callback and then checks a second time to see if the class is registered. However, every class /// definition must have a valid metaclass definition, and so the metaclass definition is always returned, /// whether it’s valid or not. pub fn getMetaClass(class_name: [:0]const u8) Error!Class { return c.objc_getMetaClass(class_name) orelse Error.ClassNotRegisteredWithRuntime; } /// Returns the class definition of a specified class, or null if the class is not registered /// with the Objective-C runtime /// /// @param name The name of the class to look up. /// /// @note getClass is different from this function in that if the class is not /// registered, getClass calls the class handler callback and then checks a second /// time to see whether the class is registered. This function does not call the class handler callback. pub fn lookUpClass(class_name: [:0]const u8) ?Class { return c.objc_lookUpClass(class_name); } /// Returns the Ivar for a specified class variable of a given class. /// /// @param cls The class definition whose class variable you wish to obtain. /// @param name The name of the class variable definition to obtain. pub fn class_getClassVariable(class: Class, name: [:0]const u8) Error!Ivar { return c.class_getClassVariable(class, name) orelse Error.FailedToGetClassVariable; } /// Returns an instance method corresponding to the implementation of a given selector for given class /// null if the specified class or its superclasses do not contain an instance method with the specified selector. /// NOTE: This function searches superclasses for implementations, whereas `class_copyMethodList` does not. pub fn class_getInstanceMethod(class: Class, selector: SEL) ?Method { return c.class_getInstanceMethod(class, selector); } /// Returns an class method corresponding to the implementation of a given selector for given class /// null if the specified class or its superclasses do not contain an class method with the specified selector. /// NOTE: This function searches superclasses for implementations, whereas `class_copyMethodList` does not. pub fn class_getClassMethod(class: Class, selector: SEL) ?Method { return c.class_getClassMethod(class, selector); } /// Returns a Boolean value that indicates whether instances of a class respond to a particular selector. pub fn class_respondsToSelector(class: Class, selector: SEL) bool { return (c.class_respondsToSelector(class, selector) != 0); } /// Returns a bool that indicates whether a class conforms to a given protocol. pub fn class_conformsToProtocol(class: Class, protocol: *Protocol) bool { return (c.class_conformsToProtocol(class, protocol) != 0); } // ----- Working with Classes ----- /// Adds a new method to a class with a given name and implementation. /// /// @param class The class to which to add a method. /// @param selector A selector that specifies the name of the method being added. /// @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. /// @param types An array of characters that describe the types of the arguments to the method. /// /// @return `true` if the method was added successfully, otherwise `false` /// (for example, the class already contains a method implementation with that name). /// @note `class_addMethod` will add an override of a superclass's implementation, /// but will not replace an existing implementation in this class. /// To change an existing implementation, use `method_setImplementation`. pub fn class_addMethod(class: Class, selector: SEL, imp: IMP, types: [:0]const u8) bool { return (c.class_addMethod(class, selector, @ptrCast(fn () callconv(.C) void, imp), types) != 0); } /// Replaces the implementation of a method for a given class. /// /// @param class The class you want to modify. /// @param selector A selector that identifies the method whose implementation you want to replace. /// @param imp The new implementation for the method identified by name for the class identified by cls. /// @param types An array of characters that describe the types of the arguments to the method. /// Since the function must take at least two arguments—self and _cmd, the second and third characters /// must be “@:” (the first character is the return type). /// /// @return The previous implementation of the method identified by `name` for the class identified by `class`. /// /// @note This function behaves in two different ways: /// - If the method identified by `name` does not yet exist, it is added as if `class_addMethod` were called. /// The type encoding specified by `types` is used as given. /// - If the method identified by `name` does exist, its `IMP` is replaced as if `method_setImplementation` were called. /// The type encoding specified by `types` is ignored. pub fn class_replaceMethod(class: Class, selector: SEL, imp: IMP, types: [:0]const u8) ?IMP { return c.class_replaceMethod(class, selector, @ptrCast(fn () callconv(.C) void, imp), types); } /// Adds a new instance variable to a class. /// /// @return `true` if the instance variable was added successfully, otherwise `false` /// (for example, the class already contains an instance variable with that name). /// /// @note This function may only be called after `objc_allocateClassPair` and before `objc_registerClassPair`. /// Adding an instance variable to an existing class is not supported. /// @note The class must not be a metaclass. Adding an instance variable to a metaclass is not supported. /// @note The instance variable's minimum alignment in bytes is 1<<align. The minimum alignment of an instance /// variable depends on the ivar's type and the machine architecture. /// For variables of any pointer type, pass log2(sizeof(pointer_type)). pub fn class_addIvar(class: Class, name: [:0]const u8, size: usize, alignment: u8, types: [:0]const u8) bool { return (c.class_addIvar(class, name, size, alignment, types) != 0); } // ----- Adding Classes ----- /// Creates a new class and metaclass. /// /// @param superclass The class to use as the new class's superclass, or nulll to create a new root class. /// @param name The string to use as the new class's name. The string will be copied. /// @param extraBytes The number of bytes to allocate for indexed ivars at the end of /// the class and metaclass objects. This should usually be 0. /// /// @return The new class, or an error if the class could not be created (for example, the desired name is already in use). /// /// @note You can get a pointer to the new metaclass by calling object_getClass(newClass). /// @note To create a new class, start by calling allocateClassPair. /// Then set the class's attributes with functions like class_addMethod and class_addIvar. /// When you are done building the class, call registerClassPair. The new class is now ready for use. /// @note Instance methods and instance variables should be added to the class itself. /// Class methods should be added to the metaclass. pub fn allocateClassPair(superclass: ?Class, class_name: [:0]const u8, extra_bytes: usize) Error!Class { return c.objc_allocateClassPair(superclass, class_name, extra_bytes) orelse Error.FailedToAllocateClassPair; } /// Registers a class that was allocated using allocateClassPair. /// /// @param cls The class you want to register. pub fn registerClassPair(class: Class) void { c.objc_registerClassPair(class); } /// Destroy a class and its associated metaclass. /// /// @param cls The class to be destroyed. It must have been allocated with objc_allocateClassPair /// /// @warning Do not call if instances of this class or a subclass exist. pub fn disposeClassPair(class: Class) void { c.objc_disposeClassPair(class); } // ----- Working with Methods ----- /// Sets the implementation of a method. /// /// @param m The method for which to set an implementation. /// @param imp The implemention to set to this method. /// /// @return The previous implementation of the method. pub fn method_setImplementation(m: Method, imp: IMP) ?IMP { return c.method_setImplementation(m, @ptrCast(fn () callconv(.C) void, imp)); } // ----- Working with Protocols ----- /// Returns a protocol specified by name pub fn getProtocol(name: [:0]const u8) Error!*Protocol { return c.objc_getProtocol(name) orelse Error.NoSuchProtocol; }
modules/platform/vendored/zig-objcrt/src/runtime.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const fmt = std.fmt; const util = @import("utils.zig"); const input = @embedFile("../in/day04.txt"); const PassportField = enum(usize) { byr, iyr, eyr, hgt, hcl, ecl, pid, cid }; fn part1(comptime n_fields: usize, comptime map: anytype) void { var valid: u16 = 0; var it = std.mem.split(input, "\n\n"); while (it.next()) |passport| { var is_present = [_]bool{false} ** n_fields; var fields_present: u8 = 0; var field_it = std.mem.tokenize(passport, ": \n"); while (field_it.next()) |field| { if (map.get(field)) |field_tag| { if (is_present[@enumToInt(field_tag)] == false) { is_present[@enumToInt(field_tag)] = true; fields_present += 1; } } _ = field_it.next(); // skip rhs of colon for this field. } if (fields_present == n_fields or (fields_present == (n_fields-1) and is_present[@enumToInt(PassportField.cid)] == false)) { valid += 1; } } print("part1: {}\n", .{valid}); } fn part2(comptime n_fields: usize, comptime map: anytype) void { var valid: u16 = 0; var it = mem.split(input, "\n\n"); while (it.next()) |passport| { var is_present = [_]bool{false} ** n_fields; var field_it = mem.tokenize(passport, " :\n"); while (field_it.next()) |field| { const field_value = field_it.next().?; if (map.get(field)) |field_tag| { switch (field_tag) { .byr => if (isValidYear(field_value, 1920, 2002)) markPresent(field_tag, &is_present), .iyr => if (isValidYear(field_value, 2010, 2020)) markPresent(field_tag, &is_present), .eyr => if (isValidYear(field_value, 2020, 2030)) markPresent(field_tag, &is_present), .hgt => if (isValidHeight(field_value)) markPresent(field_tag, &is_present), .hcl => if (isValidHairColor(field_value)) markPresent(field_tag, &is_present), .ecl => if (isValidEyeColor(field_value)) markPresent(field_tag, &is_present), .pid => if (isValidPid(field_value)) markPresent(field_tag, &is_present), .cid => continue } } } // count all fields marked present (except for cid which we're ignoring) const fields_present = blk: { var n: u8 = 0; for (is_present[0..@enumToInt(PassportField.cid)]) |s| { if (s) n += 1; } break :blk n; }; // if all fields but cid (which we didn't check for) are present, this is a valid passport. if (fields_present == (n_fields - 1)) { valid += 1; } } print("part2: {}\n", .{valid}); } pub fn main() !void { const n_fields = std.meta.fields(PassportField).len; const map = std.ComptimeStringMap(PassportField, .{ .{"byr", .byr}, .{"iyr", .iyr}, .{"eyr", .eyr}, .{"hgt", .hgt}, .{"hcl", .hcl}, .{"ecl", .ecl}, .{"pid", .pid}, .{"cid", .cid}} ); part1(n_fields, map); part2(n_fields, map); } inline fn markPresent(field: PassportField, is_present: []bool) void { is_present[@enumToInt(field)] = true; } fn isValidYear(buf: []const u8, min: u16, max: u16) bool { if (buf.len != 4) return false; if (fmt.parseUnsigned(u16, buf, 10)) |year| { return (min <= year and year <= max); } else |err| { return false; } } fn isValidHeight(buf: []const u8) bool { if (buf.len < 4) return false; switch (buf[3]) { 'c' => if (std.fmt.parseUnsigned(u16, buf[0..3], 10)) |height| { return (150 <= height and height <= 193); } else |err| return false, 'n' => if (std.fmt.parseUnsigned(u16, buf[0..2], 10)) |height| { return (59 <= height and height <= 76); } else |err| return false, else => return false } } fn isValidHairColor(buf: []const u8) bool { if (buf.len != 7 or buf[0] != '#') return false; for (buf[1..]) |char| { if (!(('0' <= char and char <= '9') or ('a' <= char and char <= 'f'))) { return false; } } return true; } fn isValidEyeColor(buf: []const u8) bool { if (buf.len != 3) return false; if (mem.eql(u8, buf, "amb") or mem.eql(u8, buf, "blu") or mem.eql(u8, buf, "brn") or mem.eql(u8, buf, "gry") or mem.eql(u8, buf, "grn") or mem.eql(u8, buf, "hzl") or mem.eql(u8, buf, "oth")) { return true; } return false; } fn isValidPid(buf: []const u8) bool { if (buf.len != 9) return false; for (buf) |char| { if (!std.ascii.isDigit(char)) return false; } return true; }
src/day04.zig
const std = @import("std"); const expect = std.testing.expect; const io = std.io; const mem = std.mem; const testing = std.testing; const ArrayList = std.ArrayList; const deflate = @import("compressor.zig"); const inflate = @import("decompressor.zig"); const deflate_const = @import("deflate_const.zig"); test "best speed" { // Tests that round-tripping through deflate and then inflate recovers the original input. // The Write sizes are near the thresholds in the compressor.encSpeed method (0, 16, 128), as well // as near `deflate_const.max_store_block_size` (65535). var abcabc = try testing.allocator.alloc(u8, 131_072); defer testing.allocator.free(abcabc); for (abcabc) |_, i| { abcabc[i] = @intCast(u8, i % 128); } var tc_01 = [_]u32{ 65536, 0 }; var tc_02 = [_]u32{ 65536, 1 }; var tc_03 = [_]u32{ 65536, 1, 256 }; var tc_04 = [_]u32{ 65536, 1, 65536 }; var tc_05 = [_]u32{ 65536, 14 }; var tc_06 = [_]u32{ 65536, 15 }; var tc_07 = [_]u32{ 65536, 16 }; var tc_08 = [_]u32{ 65536, 16, 256 }; var tc_09 = [_]u32{ 65536, 16, 65536 }; var tc_10 = [_]u32{ 65536, 127 }; var tc_11 = [_]u32{ 65536, 127 }; var tc_12 = [_]u32{ 65536, 128 }; var tc_13 = [_]u32{ 65536, 128, 256 }; var tc_14 = [_]u32{ 65536, 128, 65536 }; var tc_15 = [_]u32{ 65536, 129 }; var tc_16 = [_]u32{ 65536, 65536, 256 }; var tc_17 = [_]u32{ 65536, 65536, 65536 }; var test_cases = [_][]u32{ &tc_01, &tc_02, &tc_03, &tc_04, &tc_05, &tc_06, &tc_07, &tc_08, &tc_09, &tc_10, &tc_11, &tc_12, &tc_13, &tc_14, &tc_15, &tc_16, &tc_17, }; for (test_cases) |tc| { var firsts = [_]u32{ 1, 65534, 65535, 65536, 65537, 131072 }; for (firsts) |first_n| { tc[0] = first_n; var to_flush = [_]bool{ false, true }; for (to_flush) |flush| { var compressed = ArrayList(u8).init(testing.allocator); defer compressed.deinit(); var want = ArrayList(u8).init(testing.allocator); defer want.deinit(); var comp = try deflate.compressor( testing.allocator, compressed.writer(), .{ .level = .best_speed }, ); defer comp.deinit(); for (tc) |n| { try want.appendSlice(abcabc[0..n]); try comp.writer().writeAll(abcabc[0..n]); if (flush) { try comp.flush(); } } try comp.close(); var decompressed = try testing.allocator.alloc(u8, want.items.len); defer testing.allocator.free(decompressed); var fib = io.fixedBufferStream(compressed.items); var decomp = try inflate.decompressor(testing.allocator, fib.reader(), null); defer decomp.deinit(); var read = try decomp.reader().readAll(decompressed); _ = decomp.close(); try expect(read == want.items.len); try expect(mem.eql(u8, want.items, decompressed)); } } } } test "best speed max match offset" { const abc = "abcdefgh"; const xyz = "stuvwxyz"; const input_margin = 16 - 1; const match_before = [_]bool{ false, true }; for (match_before) |do_match_before| { const extras = [_]u32{ 0, input_margin - 1, input_margin, input_margin + 1, 2 * input_margin, }; for (extras) |extra| { var offset_adj: i32 = -5; while (offset_adj <= 5) : (offset_adj += 1) { var offset = deflate_const.max_match_offset + offset_adj; // Make src to be a []u8 of the form // fmt("{s}{s}{s}{s}{s}", .{abc, zeros0, xyzMaybe, abc, zeros1}) // where: // zeros0 is approximately max_match_offset zeros. // xyzMaybe is either xyz or the empty string. // zeros1 is between 0 and 30 zeros. // The difference between the two abc's will be offset, which // is max_match_offset plus or minus a small adjustment. var src_len: usize = @intCast(usize, offset + @as(i32, abc.len) + @intCast(i32, extra)); var src = try testing.allocator.alloc(u8, src_len); defer testing.allocator.free(src); mem.copy(u8, src, abc); if (!do_match_before) { var src_offset: usize = @intCast(usize, offset - @as(i32, xyz.len)); mem.copy(u8, src[src_offset..], xyz); } var src_offset: usize = @intCast(usize, offset); mem.copy(u8, src[src_offset..], abc); var compressed = ArrayList(u8).init(testing.allocator); defer compressed.deinit(); var comp = try deflate.compressor( testing.allocator, compressed.writer(), .{ .level = .best_speed }, ); defer comp.deinit(); try comp.writer().writeAll(src); _ = try comp.close(); var decompressed = try testing.allocator.alloc(u8, src.len); defer testing.allocator.free(decompressed); var fib = io.fixedBufferStream(compressed.items); var decomp = try inflate.decompressor(testing.allocator, fib.reader(), null); defer decomp.deinit(); var read = try decomp.reader().readAll(decompressed); _ = decomp.close(); try expect(read == src.len); try expect(mem.eql(u8, decompressed, src)); } } } }
lib/std/compress/deflate/deflate_fast_test.zig
const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("libui-test", "main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.linkLibC(); exe.addIncludeDir("./"); exe.linkSystemLibrary("gtk+-3.0"); for (common_c_files) |c_file| { exe.addCSourceFile(c_file, &[_][]const u8{}); } if (target.isWindows()) { exe.linkSystemLibrary("c++"); for (windows_c_files) |c_file| { exe.addCSourceFile(c_file, &[_][]const u8{}); } } else if (target.isLinux()) { exe.addLibPath("/usr/lib/x86_64-linux-gnu/"); for (unix_c_files) |c_file| { exe.addCSourceFile(c_file, &[_][]const u8{}); } } 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 common_c_files = &[_][]const u8{ "common/attribute.c", "common/attrlist.c", "common/attrstr.c", "common/areaevents.c", "common/control.c", "common/debug.c", "common/matrix.c", "common/opentype.c", "common/shouldquit.c", "common/tablemodel.c", "common/tablevalue.c", "common/userbugs.c", "common/utf.c", }; const unix_c_files = &[_][]const u8{ "unix/alloc.c", "unix/area.c", "unix/attrstr.c", "unix/box.c", "unix/button.c", "unix/cellrendererbutton.c", "unix/checkbox.c", "unix/child.c", "unix/colorbutton.c", "unix/combobox.c", "unix/control.c", "unix/datetimepicker.c", "unix/debug.c", "unix/draw.c", "unix/drawmatrix.c", "unix/drawpath.c", "unix/drawtext.c", "unix/editablecombo.c", "unix/entry.c", "unix/fontbutton.c", "unix/fontmatch.c", "unix/form.c", "unix/future.c", "unix/graphemes.c", "unix/grid.c", "unix/group.c", "unix/image.c", "unix/label.c", "unix/main.c", "unix/menu.c", "unix/multilineentry.c", "unix/opentype.c", "unix/progressbar.c", "unix/radiobuttons.c", "unix/separator.c", "unix/slider.c", "unix/spinbox.c", "unix/stddialogs.c", "unix/tab.c", "unix/table.c", "unix/tablemodel.c", "unix/text.c", "unix/util.c", "unix/window.c", }; const windows_libs = &[_][]const u8{ "user32", "kernel32", "gdi32", "comctl32", "uxtheme", "msimg32", "comdlg32", "d2d1", "dwrite", "ole32", "oleaut32", "oleacc", "uuid", "windowscodecs", }; const windows_c_files = &[_][]const u8{ "windows/alloc.cpp", "windows/area.cpp", "windows/areadraw.cpp", "windows/areaevents.cpp", "windows/areascroll.cpp", "windows/areautil.cpp", "windows/attrstr.cpp", "windows/box.cpp", "windows/button.cpp", "windows/checkbox.cpp", "windows/colorbutton.cpp", "windows/colordialog.cpp", "windows/combobox.cpp", "windows/container.cpp", "windows/control.cpp", "windows/d2dscratch.cpp", "windows/datetimepicker.cpp", "windows/debug.cpp", "windows/draw.cpp", "windows/drawmatrix.cpp", "windows/drawpath.cpp", "windows/drawtext.cpp", "windows/dwrite.cpp", "windows/editablecombo.cpp", "windows/entry.cpp", "windows/events.cpp", "windows/fontbutton.cpp", "windows/fontdialog.cpp", "windows/fontmatch.cpp", "windows/form.cpp", "windows/graphemes.cpp", "windows/grid.cpp", "windows/group.cpp", "windows/image.cpp", "windows/init.cpp", "windows/label.cpp", "windows/main.cpp", "windows/menu.cpp", "windows/multilineentry.cpp", "windows/opentype.cpp", "windows/parent.cpp", "windows/progressbar.cpp", "windows/radiobuttons.cpp", "windows/separator.cpp", "windows/sizing.cpp", "windows/slider.cpp", "windows/spinbox.cpp", "windows/stddialogs.cpp", "windows/tab.cpp", "windows/table.cpp", "windows/tabledispinfo.cpp", "windows/tabledraw.cpp", "windows/tableediting.cpp", "windows/tablemetrics.cpp", "windows/tabpage.cpp", "windows/text.cpp", "windows/utf16.cpp", "windows/utilwin.cpp", "windows/window.cpp", "windows/winpublic.cpp", "windows/winutil.cpp", };
build.zig
const std = @import("std"); const testing = std.testing; const mem = std.mem; const KV = @import("kv.zig").KV; const Link = @import("link.zig").Link; const LinkTag = @import("link.zig").LinkTag; const Pruned = @import("link.zig").Pruned; const Stored = @import("link.zig").Stored; const Hash = @import("hash.zig").H; const o = @import("ops.zig"); const Commiter = @import("commit.zig").Commiter; const DB = @import("db.zig").RocksDataBbase; const Merk = @import("merk.zig").Merk; pub const Tree = struct { kv: KV, left: ?Link, right: ?Link, pub fn init(k: []const u8, v: []const u8) !*Tree { var tree = try Merk.stack_allocator.create(Tree); errdefer allocator.destroy(tree); tree.kv = KV.init(k, v); tree.left = null; tree.right = null; return tree; } pub fn key(self: Tree) []const u8 { return self.kv.key; } pub fn value(self: Tree) []const u8 { return self.kv.val; } pub fn updateVal(self: *Tree, val: []const u8) void { self.kv.hash = KV.kvHash(self.kv.key, self.kv.val); } pub fn hash(self: Tree) Hash { return KV.nodeHash(self.kvHash(), self.childHash(true), self.childHash(false)); } pub fn childHash(self: Tree, is_left: bool) Hash { return if (self.link(is_left)) |l| l.hash().? else Hash.zeroHash(); } pub fn kvHash(self: Tree) Hash { return self.kv.hash; } pub fn height(self: Tree) u8 { return 1 + mem.max(u8, self.childHeights()[0..]); } pub fn childHeights(self: Tree) [2]u8 { return [2]u8{ self.childHeight(true), self.childHeight(false) }; } pub fn childHeight(self: Tree, is_left: bool) u8 { return if (self.link(is_left)) |l| l.height() else 0; } pub fn child(self: *Tree, is_left: bool) ?*Tree { if (self.link(is_left)) |l| { if (@as(LinkTag, l) == .Pruned) return Tree.fetchTree(null, l.key()); return l.tree(); } return null; } pub fn link(self: Tree, is_left: bool) ?Link { return if (is_left) self.left else self.right; } pub fn setLink(self: *Tree, is_left: bool, l: ?Link) void { if (is_left) self.left = l else self.right = l; } pub fn balanceFactor(self: *Tree) i16 { return @as(i16, self.childHeight(false)) - @as(i16, self.childHeight(true)); } pub fn attach(self: *Tree, is_left: bool, tree: ?*Tree) void { if (tree) |t| { if (mem.eql(u8, t.key(), self.key())) @panic("BUG: tried to attach tree with same key"); if (self.link(is_left)) |l| @panic("BUG: tried to attach to tree slot, but it is already some"); self.setLink(is_left, Link.fromModifiedTree(t)); } } pub fn detach(self: *Tree, is_left: bool) ?*Tree { if (self.link(is_left)) |l| { self.setLink(is_left, null); if (@as(LinkTag, l) == .Pruned) { return Tree.fetchTree(null, l.key()); } return l.tree(); } return null; } pub fn commit(self: *Tree, c: *Commiter) void { if (self.link(true)) |l| { if (@as(LinkTag, l) == .Modified) { l.tree().?.commit(c); self.setLink(true, l.intoStored(undefined)); } } if (self.link(false)) |l| { if (@as(LinkTag, l) == .Modified) { l.tree().?.commit(c); self.setLink(false, l.intoStored(undefined)); } } c.write(self); // Note: disable pruning, but keep this for future use case // if (c.prune(self)) { // if (self.link(true)) |l| { // defer Merk.stack_allocator.destroy(l.tree()); // self.setLink(true, l.intoPruned()); // } // if (self.link(false)) |l| { // defer Merk.stack_allocator.destroy(l.tree()); // self.setLink(false, l.intoPruned()); // } // } } pub fn fetchTree(db: ?DB, k: []const u8) *Tree { var _allocator = if (Merk.heap_allocator) |_| &Merk.heap_allocator.?.allocator else Merk.stack_allocator; var buf = std.ArrayList(u8).init(_allocator); const _db = if (db) |d| d else Merk.db.?; _ = _db.read(k, buf.writer()) catch unreachable; defer buf.deinit(); return Tree.unmarshal(buf.toOwnedSlice()) catch unreachable; } pub fn fetchTrees(db: ?DB, k: []const u8, level: u8) *Tree { const self = Tree.fetchTree(db, k); if (level > 0) { if (self.link(true)) |l| { var t = Tree.fetchTrees(db, l.key(), level - 1); self.setLink(true, l.intoStored(t)); } if (self.link(false)) |l| { var t = Tree.fetchTrees(db, l.key(), level - 1); self.setLink(false, l.intoStored(t)); } } return self; } pub fn marshal(self: *Tree, w: anytype) !void { @setRuntimeSafety(false); try w.writeIntBig(u32, @truncate(u32, self.key().len)); try w.writeAll(self.key()); try w.writeIntBig(u32, @truncate(u32, self.value().len)); try w.writeAll(self.value()); if (self.link(true)) |l| { try w.writeByte(0x01); try w.writeAll(&l.hash().?.inner); try w.writeIntBig(u32, @truncate(u32, l.key().len)); try w.writeAll(l.key()); } else { try w.writeByte(0x00); } if (self.link(false)) |l| { try w.writeByte(0x01); try w.writeAll(&l.hash().?.inner); try w.writeIntBig(u32, @truncate(u32, l.key().len)); try w.writeAll(l.key()); } else { try w.writeByte(0x00); } } pub fn unmarshal(buf: []const u8) !*Tree { @setRuntimeSafety(false); var ptr: usize = 0; var bytes: [4]u8 = undefined; const hash_len = Hash.len(); if (ptr + 4 + 4 + 1 + 1 > buf.len) return error.EndOfFile; // key mem.copy(u8, &bytes, buf[ptr .. ptr + 4]); ptr += 4; const key_len = mem.readIntBig(u32, &bytes); const k = buf[ptr .. ptr + key_len]; ptr += key_len; // val mem.copy(u8, &bytes, buf[ptr .. ptr + 4]); ptr += 4; const val_len = mem.readIntBig(u32, &bytes); const v = buf[ptr .. ptr + val_len]; ptr += val_len; var self = try Tree.init(k, v); // left const left_flg = buf[ptr]; ptr += 1; if (left_flg == 0x01) { const hash_buf = buf[ptr .. ptr + hash_len]; ptr += hash_len; mem.copy(u8, &bytes, buf[ptr .. ptr + 4]); ptr += 4; const val_left_len = mem.readIntBig(u32, &bytes); const val_left = buf[ptr .. ptr + val_left_len]; ptr += val_left_len; self.left = Link.fromMarshal(hash_buf, val_left); } // right const right_flg = buf[ptr]; ptr += 1; if (right_flg == 0x01) { const hash_buf = buf[ptr .. ptr + hash_len]; ptr += hash_len; mem.copy(u8, &bytes, buf[ptr .. ptr + 4]); ptr += 4; const val_right_len = mem.readIntBig(u32, &bytes); const val_right = buf[ptr .. ptr + val_right_len]; ptr += val_right_len; self.right = Link.fromMarshal(hash_buf, val_right); } return self; } pub fn verify(self: *Tree) bool { if (self.link(true)) |l| { if (@as(LinkTag, l) != .Pruned) { if (mem.lessThan(u8, self.key(), l.key())) @panic("unbalanced tree"); _ = l.tree().?.verify(); } } if (self.link(false)) |l| { if (@as(LinkTag, l) != .Pruned) { if (!mem.lessThan(u8, self.key(), l.key())) @panic("unbalanced tree"); _ = l.tree().?.verify(); } } return true; } }; test "check size" { std.debug.print("size of tree: {}\n", .{@sizeOf(Tree)}); } test "init" { const key = "key"; const val = "value"; const tree = try Tree.init(key, val); defer Merk.stack_allocator.destroy(tree); testing.expectEqualSlices(u8, tree.kv.key, key); } test "key" { testing.expectEqualSlices(u8, Tree.key(Tree{ .kv = KV.init("key", "value"), .left = null, .right = null }), "key"); } test "value" { testing.expectEqualSlices(u8, Tree.value(Tree{ .kv = KV.init("key", "value"), .left = null, .right = null }), "value"); } test "childHash" { var hash = KV.kvHash("key", "value"); var left: Link = Link{ .Pruned = Pruned{ .hash = hash, .child_heights = .{ 0, 0 }, .key = undefined } }; var tree: Tree = Tree{ .kv = KV.init("key", "value"), .left = left, .right = null }; testing.expectEqualSlices(u8, &tree.childHash(true).inner, &hash.inner); testing.expectEqualSlices(u8, &tree.childHash(false).inner, &Hash.zeroHash().inner); } test "height" { var left: Link = Link{ .Pruned = Pruned{ .hash = undefined, .child_heights = .{ 0, 2 }, .key = undefined } }; testing.expectEqual(Tree.height(Tree{ .kv = undefined, .left = left, .right = null }), 4); } test "attach" { var tree1 = try Tree.init("key1", "value1"); defer testing.allocator.destroy(tree1); var tree2 = try Tree.init("key2", "value2"); defer testing.allocator.destroy(tree2); tree1.attach(false, tree2); testing.expectEqualSlices(u8, tree1.right.?.tree().?.key()[0..], tree2.key()[0..]); } test "detach" { var tree1 = try Tree.init("key1", "value1"); defer Merk.stack_allocator.destroy(tree1); var tree2 = try Tree.init("key2", "value2"); defer Merk.stack_allocator.destroy(tree2); tree1.attach(false, tree2); var tree3 = tree1.detach(false); testing.expectEqual(tree3, tree2); testing.expectEqual(tree1.link(true), null); testing.expectEqual(tree1.link(false), null); } test "marshal and unmarshal" { // marshal var hash_l = KV.kvHash("leftkey", "leftvalue"); var hash_r = KV.kvHash("rightkey", "rightvalue"); var tree_l = Tree{ .kv = KV.init("keylefttree", "value"), .left = undefined, .right = undefined }; var tree_r = Tree{ .kv = KV.init("keyrighttree", "value"), .left = undefined, .right = undefined }; var left = Link{ .Stored = Stored{ .hash = hash_l, .child_heights = undefined, .tree = &tree_l } }; var right = Link{ .Stored = Stored{ .hash = hash_r, .child_heights = undefined, .tree = &tree_r } }; var tree: Tree = Tree{ .kv = KV.init("key", "value"), .left = left, .right = right }; var buf: [255]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); try tree.marshal(fbs.writer()); var marshaled: []const u8 = fbs.getWritten(); // unmarshal Merk.stack_allocator = testing.allocator; var unmarshaled = try Tree.unmarshal(marshaled); defer Merk.stack_allocator.destroy(unmarshaled); testing.expectEqualSlices(u8, unmarshaled.key(), "key"); testing.expectEqualSlices(u8, unmarshaled.value(), "value"); testing.expectEqualSlices(u8, unmarshaled.link(true).?.hash().?.inner[0..], &hash_l.inner); testing.expectEqualSlices(u8, unmarshaled.link(true).?.key(), tree_l.key()); testing.expectEqualSlices(u8, unmarshaled.link(false).?.hash().?.inner[0..], hash_r.inner[0..]); testing.expectEqualSlices(u8, unmarshaled.link(false).?.key(), tree_r.key()); }
src/tree.zig
const std = @import("std"); const log = std.log; const utils = @import("utils.zig"); const tokenizer = @import("tokenizer.zig"); const Tokenizer = tokenizer.Tokenizer; const Token = tokenizer.Token; const TokenKind = tokenizer.TokenKind; const ast = @import("ast.zig"); const Node = ast.Node; const NodeKind = ast.NodeKind; const code_chunks = @import("code_chunks.zig"); const Language = code_chunks.Language; const csl = @import("csl_json.zig"); const bic = @import("builtin.zig"); const BuiltinCall = bic.BuiltinCall; const builtin_call_info = bic.builtin_call_info; pub const Parser = struct { allocator: *std.mem.Allocator, node_arena: std.heap.ArenaAllocator, string_arena: std.heap.ArenaAllocator, label_node_map: std.StringHashMap(*Node.NodeData), citations: std.ArrayList(*Node), run_languages: LangSet, tokenizer: Tokenizer, // NOTE: ArrayList: pointers to items are __invalid__ after resizing operations!! // so it doesn't make sense to keep a ptr to the current token token_buf: std.ArrayList(Token), tk_index: u32, current_document: *Node, // keep track of last text node so we don't have to create a new one for at least // every word // opening or closing of blocks sets this to null last_text_node: ?*Node, /// these are not blocks in the markdown sense but rather parent nodes /// in general /// first open_block is always current_document // TODO use an ArrayList instead? open_blocks: [50]*Node, open_block_idx: u8, bibliography: ?*Node = null, // each error name across the entire compilation gets assigned an unsigned // integer greater than 0. You are allowed to declare the same error name // more than once, and if you do, it gets assigned the same integer value // // inferred error sets: // When a function has an inferred error set, that function becomes generic // and thus it becomes trickier to do certain things with it, such as // obtain a function pointer, or have an error set that is consistent // across different build targets. Additionally, inferred error sets are // incompatible with recursion. // In these situations, it is recommended to use an explicit error set. You // can generally start with an empty error set and let compile errors guide // you toward completing the set. // e.g. changing !void to ParseError!void gives the error msg: // not a member of destination error set error{OutOfMemory} // TODO go over use of SyntaxError and specific ones const ParseError = error { OutOfMemory, SyntaxError, ExceededOrderedListDigits, BuiltinCallFailed, }; const LangSet = std.enums.EnumSet(code_chunks.Language); pub fn init(allocator: *std.mem.Allocator, filename: []const u8) !Parser { var parser = Parser{ .allocator = allocator, .node_arena = std.heap.ArenaAllocator.init(allocator), .string_arena = std.heap.ArenaAllocator.init(allocator), .label_node_map = std.StringHashMap(*Node.NodeData).init(allocator), .citations = std.ArrayList(*Node).init(allocator), .run_languages = LangSet.init(.{}), .tokenizer = try Tokenizer.init(allocator, filename), // TODO allocate a capacity for tokens with ensureCapacity based on filesize .token_buf = std.ArrayList(Token).init(allocator), .tk_index = 0, .current_document = undefined, .last_text_node = null, .open_blocks = undefined, .open_block_idx = 0, }; // manually get the first token try parser.token_buf.append(try parser.tokenizer.get_token()); // create() returns ptr to undefined memory var current_document = try Node.create(&parser.node_arena.allocator); current_document.data = .Document; parser.current_document = current_document; parser.open_blocks[0] = current_document; return parser; } pub fn deinit(self: *Parser) void { // free code string buffers from .FencedCode nodes self.string_arena.deinit(); self.node_arena.deinit(); self.tokenizer.deinit(); self.token_buf.deinit(); self.label_node_map.deinit(); self.citations.deinit(); } inline fn new_node(self: *Parser, parent: *Node) !*Node { std.debug.assert(ast.children_allowed(parent.data)); const node = try Node.create(&self.node_arena.allocator); parent.append_child(node); // invalidate last text block; doing this manually was too error prone self.last_text_node = null; return node; } inline fn open_block(self: *Parser, block: *Node) void { self.open_block_idx += 1; self.open_blocks[self.open_block_idx] = block; self.last_text_node = null; } /// does no bounds checking inline fn get_last_block(self: *Parser) *Node { return self.open_blocks[self.open_block_idx]; } inline fn get_last_container_block(self: *Parser) *Node { var i: u8 = self.open_block_idx; while (i > 0) : (i -= 1) { if (ast.is_container_block(self.open_blocks[i].data)) { return self.open_blocks[i]; } } // return current_document which is open_blocks[0] return self.current_document; } inline fn get_last_leaf_block(self: *Parser) ?*Node { var i: u8 = self.open_block_idx; while (i > 0) : (i -= 1) { if (ast.is_leaf_block(self.open_blocks[i].data)) { return self.open_blocks[i]; } } return null; } inline fn close_blocks_until( self: *Parser, comptime match: fn (kind: NodeKind) bool, comptime close_first_match: bool ) void { var i: u8 = self.open_block_idx; while (i > 0) : (i -= 1) { if (match(self.open_blocks[i].data)) { self.open_block_idx = if (!close_first_match) i else i - 1; break; } } } inline fn close_blocks_until_kind( self: *Parser, comptime kind: NodeKind, comptime close_first_match: bool ) void { var i: u8 = self.open_block_idx; while (i > 0) : (i -= 1) { if (self.open_blocks[i].data == kind) { self.open_block_idx = if (!close_first_match) i else i - 1; break; } } } inline fn close_last_block(self: *Parser) void { std.debug.assert(self.open_block_idx > 0); self.open_block_idx -= 1; self.last_text_node = null; } pub fn parse(self: *Parser) ParseError!void { // tokenize the whole file first so we can use ptrs that don't get invalidated // due to resizing; maybe also faster for successful compiles since // better cache friendlyness? var token: Token = undefined; token.token_kind = TokenKind.Invalid; while (token.token_kind != TokenKind.Eof) { token = self.tokenizer.get_token() catch return ParseError.SyntaxError; try self.token_buf.append(token); } while (self.peek_token().token_kind != TokenKind.Eof) { try self.parse_block(0, false); } } /// does no bounds checking beyond which is integrated with zig up to ReleaseSafe mode /// assumes caller doesn't call peek_next_token after receiving TokenKind.Eof inline fn eat_token(self: *Parser) void { std.debug.assert((self.tk_index + 1) < self.token_buf.items.len); self.tk_index += 1; } inline fn put_back(self: *Parser) void { self.tk_index -= 1; } inline fn peek_token(self: *Parser) *Token { return &self.token_buf.items[self.tk_index]; } /// does no bounds checking beyond which is integrated with zig up to ReleaseSafe mode /// assumes caller doesn't call peek_next_token after receiving TokenKind.Eof inline fn peek_next_token(self: *Parser) *Token { return &self.token_buf.items[self.tk_index + 1]; } inline fn require_token(self: *Parser, comptime token_kind: TokenKind, comptime expl_msg: []const u8) ParseError!void { const token = self.peek_token(); if (token.token_kind != token_kind) { Parser.report_error("ln:{}: Expected token '{s}' found '{s}'" ++ expl_msg ++ "\n", .{ token.line_nr, token_kind.name(), token.token_kind.name() }); return ParseError.SyntaxError; } } inline fn report_error(comptime err_msg: []const u8, args: anytype) void { log.err(err_msg, args); } inline fn skip_whitespace(self: *@This(), comptime skip_newline: bool) u32 { var tok = self.peek_token(); var skipped: u32 = 0; while (true) : (tok = self.peek_token()) { switch (tok.token_kind) { .Space, .Tab =>{ skipped += 1; self.eat_token(); }, .Newline => { if (skip_newline) { skipped += 1; self.eat_token(); continue; } }, else => break, } } return skipped; } fn parse_block(self: *Parser, indent_change: i8, prev_line_blank: bool) ParseError!void { switch (self.peek_token().token_kind) { TokenKind.Comment => { self.eat_token(); // eat \n since the comment started the line self.eat_token(); // eat \n // @CleanUp don't emit .Comment at all? // comments are completely ignored so we need to pass along the // previous values for indent/blank lines return self.parse_block(indent_change, prev_line_blank); }, TokenKind.Eof => { try self.handle_open_blocks(NodeKind.Undefined, 0, prev_line_blank); }, TokenKind.Newline => { // close block on blank line otherwise ignore // blank lines are ignored // two \n (blank line) end a paragraph // self.current_document is always open_blocks[0] // container blocks can contain blank lines so we don't close them here if (self.open_block_idx > 0) { if (self.peek_next_token().token_kind == TokenKind.Newline) { log.debug("ln:{}: Close block (all): {s}\n", .{ self.peek_token().line_nr, @tagName(self.get_last_block().data) }); // close ALL open blocks except blockquote var idx = self.open_block_idx; while (idx > 0) : (idx -= 1) { if (self.open_blocks[idx].data == .BlockQuote) { break; } } self.open_block_idx = idx; self.eat_token(); self.eat_token(); // eat both \n } else { if (!ast.is_container_block(self.get_last_block().data)) { log.debug("ln:{}: Close block: {s}\n", .{ self.peek_token().line_nr, @tagName(self.get_last_block().data) }); self.close_last_block(); } // blank line in list -> loose list // here we could also count the last blankline at the end of the list // (list getting ended by another block not 2 blank lines) // so count the lines const last_container = self.get_last_container_block(); switch (last_container.data) { .OrderedListItem => last_container.parent.?.data.OrderedList.blank_lines += 1, .UnorderedListItem => last_container.parent.?.data.UnorderedList.blank_lines += 1, else => {}, } self.eat_token(); return self.parse_block(indent_change, true); } } else { self.eat_token(); } }, TokenKind.Decrease_indent => { self.eat_token(); return self.parse_block(indent_change - 1, prev_line_blank); }, TokenKind.Increase_indent => { self.eat_token(); return self.parse_block(1, prev_line_blank); // can't get more than on +Indent }, TokenKind.Double_quote_triple => { const start_tok_col = self.peek_token().column; self.eat_token(); if (indent_change > 0) { try self.require_token(TokenKind.Newline, " after blockquote opener '\"\"\"'!"); self.eat_token(); // start blockquote try self.handle_open_blocks(NodeKind.BlockQuote, start_tok_col, prev_line_blank); var blockquote_node: *Node = try self.new_node(self.get_last_block()); blockquote_node.data = .BlockQuote; self.open_block(blockquote_node); } else if (self.peek_token().token_kind == TokenKind.Newline) { self.eat_token(); // """ then blank line closes blockquote try self.require_token( TokenKind.Decrease_indent, " after '\"\"\"\\n' when closing a blockquote!"); self.eat_token(); // eat -Indent // end blockquote switch (self.get_last_block().data) { .Paragraph => { try self.close_paragraph(); // close everything up to and including the blockquote // (needed so open lists are also closed) self.close_blocks_until_kind(NodeKind.BlockQuote, true); }, .BlockQuote => { self.close_last_block(); }, else => { Parser.report_error( "ln:{}: Unclosed block of type '{s}' prevented closing a blockquote!\n", .{ self.peek_token().line_nr - 1, @tagName(self.get_last_block().data) }); return ParseError.SyntaxError; }, } } }, TokenKind.Hash => { // atx heading // 1-6 unescaped # followed by ' ' or end-of-line // not doing: optional closing # that don't have to match the number of opening # try self.handle_open_blocks(NodeKind.Heading, self.peek_token().column, prev_line_blank); var heading_lvl: u8 = 1; self.eat_token(); while (self.peek_token().token_kind == TokenKind.Hash) { heading_lvl += 1; self.eat_token(); } const tok_after_hashes = self.peek_token(); if (heading_lvl > 6 or tok_after_hashes.token_kind != TokenKind.Space) { // can't use self. otherwise self *Parser gets passed Parser.report_error( "ln:{}: Headings can only go up to level 6 and have to be followed by a" ++ " space and heading text! If you didn't want to create a heading" ++ " escape the first '#' with a '\\'", .{ tok_after_hashes.line_nr }); return ParseError.SyntaxError; } else { self.eat_token(); // eat space // TODO make sure we account for sudden Eof everywhere if (self.peek_token().token_kind.ends_line()) { Parser.report_error("ln:{}: Empty heading name!", .{ self.peek_token().line_nr }); return ParseError.SyntaxError; } var heading_node: *Node = try self.new_node(self.get_last_block()); heading_node.data = .{ .Heading = .{ .level = heading_lvl }, }; self.open_block(heading_node); log.debug("Heading: level {}\n", .{ heading_node.data.Heading.level }); try self.parse_inline_until(TokenKind.Newline); self.close_last_block(); } }, TokenKind.Dash, TokenKind.Plus => { // maybe thematic break: the same 3 or more *, - or _ followed by optional spaces // bullet list/list item // remove _ and * from being able to start a thematic break/unordered list // so we don't have to backtrack if parsing doesn't succeed when it was just // being used as emphasis const start_token = self.peek_token(); const start_token_kind = start_token.token_kind; self.eat_token(); const next_token = self.peek_token(); log.debug("Start {} Next {} 3rd {}\n", .{ start_token_kind, next_token.token_kind, self.peek_next_token().token_kind }); if (next_token.token_kind == TokenKind.Space) { // unordered list (can be started while in a container block) try self.require_token(TokenKind.Space, " after unordered list item starter!"); self.eat_token(); const skipped = self.skip_whitespace(false); // 2 -> 1 for '-' or '+' and 1 for first space const li_starter_offset = @intCast(u8, 2 + skipped); try self.parse_unordered_list( start_token_kind, start_token.column, li_starter_offset, prev_line_blank); } else if (start_token_kind == TokenKind.Dash and next_token.token_kind == TokenKind.Dash and self.peek_next_token().token_kind == TokenKind.Dash) { try self.handle_open_blocks(NodeKind.ThematicBreak, start_token.column, prev_line_blank); self.eat_token(); self.eat_token(); // thematic break var token_kind = self.peek_token().token_kind; while (token_kind == TokenKind.Dash or token_kind == TokenKind.Comment or token_kind == TokenKind.Space) { self.eat_token(); token_kind = self.peek_token().token_kind; } // CommonMark allows optional spaces after a thematic break - we don't! // so the line the thematic break is in has to end in a newline right // after the thematic break (---) if (!self.peek_token().token_kind.ends_line()) { // \\ starts a zig multiline string-literal that goes until the end // of the line, \n is only added if the next line starts with a \\ // alternatively you could use ++ at the end of the line to concat // the arrays // recognizes --- of table sep as invalid thematic break // -> always require table rows to start with | log.err("Line {}: " ++ "A line with a thematic break (consisting of at least 3 '-'" ++ " can only contain whitespace, comments or the " ++ "character that started the break and has to end in a new line!\n", .{ self.peek_token().line_nr }); return ParseError.SyntaxError; } else { var thematic_break = try self.new_node(self.get_last_block()); thematic_break.data = .ThematicBreak; log.debug("Found valid thematic break! starting with: '{}'\n", .{start_token_kind}); } } else { // error here otherwise we'd have to backtrack - how often do you // really want to start a paragraph with *-+_ without wanting // a thematic break / list? // still on 2nd #/-/_ Parser.report_error( "ln:{}: Characters '-' and '+' that start a new paragraph need to " ++ "either be part of an unordered list ('- Text') or a thematic break " ++ "(at least three '-')!\n", .{ self.peek_token().line_nr }); return ParseError.SyntaxError; } }, TokenKind.Digits => { // maybe ordered list // 1-9 digits (0-9) ending in a '.' or ')' const start_token = self.peek_token(); const next_token_kind = self.peek_next_token().token_kind; if (next_token_kind == TokenKind.Period or next_token_kind == TokenKind.Close_paren) { self.eat_token(); // digits self.eat_token(); // . or ) const start_num = std.fmt.parseUnsigned( u16, start_token.text(self.tokenizer.bytes), 10) catch { Parser.report_error( "ln:{}: Numbers that start an ordered list need to be in base 10, " ++ "number was '{s}'\n", .{ start_token.line_nr, start_token.text(self.tokenizer.bytes) }); return ParseError.SyntaxError; }; try self.require_token(TokenKind.Space, " after ordered list item starter!"); self.eat_token(); const skipped = self.skip_whitespace(false); // 2 -> 1 for '.' or ')' and 1 for first ' ' const li_starter_offset = @intCast(u8, start_token.len() + 2 + skipped); try self.parse_ordered_list( next_token_kind, start_token.column, prev_line_blank, start_num, '1', li_starter_offset); } else { try self.parse_paragraph(prev_line_blank); } }, TokenKind.Backtick_triple => { try self.handle_open_blocks(NodeKind.FencedCode, self.peek_token().column, prev_line_blank); self.eat_token(); // language name or newline const lang_name_start = self.peek_token().start; while (true) { switch (self.peek_token().token_kind) { .Newline, .Eof => break, else => self.eat_token(), } } const lang_name_end = self.peek_token().start; try self.require_token(.Newline, " after FencedCode block starter!"); self.eat_token(); var code_node = try self.new_node(self.get_last_block()); code_node.data = .{ .FencedCode = .{ .language = Language.match( self.tokenizer.bytes[lang_name_start..lang_name_end]), .code = undefined, .run = true, }, }; self.open_block(code_node); // mark language for running it later self.run_languages.insert(code_node.data.FencedCode.language); // allow builtin calls immediately after the first newline with each // builtin being separated by exactly one newline var tok_kind = self.peek_token().token_kind; const require_extra_newline = if (tok_kind == .Builtin_call) true else false; while (true) : ( tok_kind = self.peek_token().token_kind ) { if (tok_kind == .Builtin_call) { try self.parse_builtin(self.peek_token()); try self.require_token( .Newline, " after builtin call before the code of a FencedCode block!"); self.eat_token(); } else { if (require_extra_newline) { // require two newlines after the last builtin call try self.require_token( .Newline, " after the last builtin call inside of a FencedCode block!"); self.eat_token(); } break; } } log.debug("Found code block ln{}: lang_name {s}\n", .{ self.peek_token().line_nr, @tagName(code_node.data.FencedCode.language) }); try self.parse_code_block(); }, TokenKind.Dollar_double => { try self.handle_open_blocks( NodeKind.MathMultiline, self.peek_token().column, prev_line_blank); self.eat_token(); var ctoken = self.peek_token(); const math_start = ctoken; while (ctoken.token_kind != TokenKind.Dollar_double) : ({ self.eat_token(); ctoken = self.peek_token(); }) { if (ctoken.token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end of file inside math environment ($$...$$)", .{ math_start.line_nr }); return ParseError.SyntaxError; } } const math_node = try self.new_node(self.get_last_block()); math_node.data = .{ .MathMultiline = .{ .text = self.tokenizer.bytes[math_start.start..self.peek_token().start] } }; self.eat_token(); // eat closing $$ log.debug("ln:{}: Math env: $${s}$$\n", .{ math_start.line_nr, math_node.data.MathMultiline.text }); }, TokenKind.Colon_open_bracket => { try self.handle_open_blocks(NodeKind.LinkRef, self.peek_token().column, prev_line_blank); // link reference definition if (self.open_block_idx > 0) { Parser.report_error( "ln:{}: References must be defined at the document level! " ++ "Definition found in '{s}' instead.\n", .{ self.peek_token().line_nr, @tagName(self.get_last_block().data) }); return ParseError.SyntaxError; } self.eat_token(); var token = self.peek_token(); const ref_name_start = token.start; // CommonMark allows one \n inside a reference label // don't allow any for now! while (token.token_kind != TokenKind.Close_bracket_colon and !token.token_kind.ends_line()) { self.eat_token(); token = self.peek_token(); } const ref_name_end = self.peek_token().start; if (token.token_kind != TokenKind.Close_bracket_colon) { Parser.report_error("ln:{}: Missing closing ']:' from reference label!\n", .{ self.peek_token().line_nr }); return ParseError.SyntaxError; } self.eat_token(); if (ref_name_start == ref_name_end) { Parser.report_error("ln:{}: Empty reference label!\n", .{ self.peek_token().line_nr }); return ParseError.SyntaxError; } log.debug( "ln:{}: Ref with label: '{s}'\n", .{ self.peek_token().line_nr, self.tokenizer.bytes[ref_name_start..ref_name_end] }); try self.require_token( TokenKind.Space, ". A space is required between reference label and reference content!"); self.eat_token(); // reference definitions are alywas direct children of the document var reference_def = try self.new_node(self.current_document); reference_def.data = .{ .LinkRef = .{ .label = self.tokenizer.bytes[ref_name_start..ref_name_end], .url = undefined, .title = null, }, }; self.open_block(reference_def); // store entry in label_node_map with the label as key and the *Node as value // make sure we don't have a duplicate label! const entry_found = try self.label_node_map.getOrPut(reference_def.data.LinkRef.label.?); // ^ result will be a struct with a pointer to the HashMap.Entry and a bool // whether an existing value was found if (entry_found.found_existing) { Parser.report_error("ln:{}: Duplicate reference label '{s}'!\n", .{ self.peek_token().line_nr, reference_def.data.LinkRef.label.? }); return ParseError.SyntaxError; } else { // actually write entry value (key was already written by getOrPut) entry_found.value_ptr.* = &reference_def.data; } try self.parse_link_destination(); self.close_last_block(); }, TokenKind.Exclamation_open_bracket => { try self.handle_open_blocks(NodeKind.Image, self.peek_token().column, prev_line_blank); self.eat_token(); var img_node = try self.new_node(self.get_last_block()); img_node.data = .{ .Image = .{ .alt = undefined, .label = null, .url = null, .title = null, }, }; self.open_block(img_node); var token = self.peek_token(); const alt_start = token; while (token.token_kind != TokenKind.Close_bracket) { if (token.token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end of file inside image alt text block '[...]'!\n", .{ alt_start.line_nr }); return ParseError.SyntaxError; } self.eat_token(); token = self.peek_token(); } self.eat_token(); const alt_end = token; img_node.data.Image.alt = self.tokenizer.bytes[alt_start.start .. alt_end.start]; switch (self.peek_token().token_kind) { .Open_bracket => { img_node.data.Image.label = try self.parse_link_ref_label(NodeKind.Image); }, .Open_paren => try self.parse_link_destination(), else => { Parser.report_error( "ln:{}: Expected image label '[' or image destination '(' starter, " ++ "got '{s}' instead!\n", .{ self.peek_token().line_nr, self.peek_token().token_kind.name() }); return ParseError.SyntaxError; }, } }, .Text => { switch (self.peek_next_token().token_kind) { .Period, .Close_paren => { const start_token = self.peek_token(); const start = start_token.text(self.tokenizer.bytes); // allow single lower or uppercase ascii letters followed by '.' or ')' // to start a list as well if (start.len == 1) { var ol_type: u8 = undefined; var start_num: u16 = undefined; switch (start[0]) { 'a'...'z' => { ol_type = 'a'; start_num = start[0] - 'a' + 1; }, 'A'...'Z' => { ol_type = 'A'; start_num = start[0] - 'A' + 1; }, else => return try self.parse_paragraph(prev_line_blank), } self.eat_token(); const next_token = self.peek_token(); self.eat_token(); try self.require_token(TokenKind.Space, " after ordered (alt) list item starter!"); self.eat_token(); const skipped = self.skip_whitespace(false); // 3 -> 1 for letter, 1 for '.' or ')' and 1 for first space const li_starter_offset = @intCast(u8, 3 + skipped); try self.parse_ordered_list( next_token.token_kind, start_token.column, prev_line_blank, start_num, ol_type, li_starter_offset); } else { try self.parse_paragraph(prev_line_blank); } }, else => try self.parse_paragraph(prev_line_blank), } }, else => { try self.parse_paragraph(prev_line_blank); }, } } /// closes lists that don't match the current token's ident level /// (token.column == list.indent + list.li_starter_offset fn close_lists_not_matching_indent( self: *Parser, initial_last_container: Node.NodeData, starter_column: u32, initial_prev_line_blank: bool ) void { var last_container: Node.NodeData = initial_last_container; var prev_line_blank = initial_prev_line_blank; // close __all__ lists that don't match our indent! // (col __after__ list item starter + space) while (true) { switch (last_container) { .UnorderedListItem => |item| { if (item.indent + item.li_starter_offset != starter_column) { self.close_blocks_until_kind(.UnorderedListItem, false); self.close_list(prev_line_blank); // prev_line_blank gets "used up" by the first list prev_line_blank = false; } else { break; } }, .OrderedListItem => |item| { if (item.indent + item.li_starter_offset != starter_column) { self.close_blocks_until_kind(.OrderedListItem, false); self.close_list(prev_line_blank); // prev_line_blank gets "used up" by the first list prev_line_blank = false; } else { break; } }, else => break, } last_container = self.get_last_block().data; } } fn handle_open_blocks( self: *Parser, comptime new_block: NodeKind, starter_column: u32, // column of the token that starts the block initial_prev_line_blank: bool ) ParseError!void { std.debug.assert(new_block != .Paragraph); var last_block_kind: NodeKind = self.get_last_block().data; // there should be no remaining open inline elements // when opening new leaf/container blocks if (!ast.is_inline(new_block)) { if (ast.is_inline(last_block_kind)) { Parser.report_error( "ln:{}: There was at least one unclosed inline element of type '{s}'\n", .{ self.peek_token().line_nr, @tagName(last_block_kind) }); return ParseError.SyntaxError; } } if (last_block_kind == NodeKind.Paragraph) { try self.close_paragraph(); last_block_kind = self.get_last_block().data; } switch (new_block) { // not necessary for lists, that is handled by can_list_continue // since new_block is comptime this switch should not incur any runtime cost .UnorderedListItem, .OrderedListItem, .OrderedList, .UnorderedList => {}, else => { var last_container: Node.NodeData = self.get_last_container_block().data; if (last_container != new_block) { self.close_lists_not_matching_indent(last_container, starter_column, initial_prev_line_blank); last_block_kind = self.get_last_block().data; } } } // otherwise check that old can hold new block kind if (!ast.can_hold(last_block_kind, new_block)) { Parser.report_error( "ln:{}: Previous block of type '{s}' can't hold new block of type '{s}'\n", .{ self.peek_token().line_nr, @tagName(last_block_kind), @tagName(new_block) }); return ParseError.SyntaxError; } } fn close_list(self: *Parser, prev_line_blank: bool) void { self.close_last_block(); if (prev_line_blank) { // don't count a blank line if it occured before ending a list // // TODO OrderedList and UnorderedList have the same payload type // is there a way to access that without a switch? log.debug("ln:{}: One less blank!\n", .{ self.peek_token().line_nr}); switch (self.get_last_block().data) { .OrderedList, .UnorderedList => |*list| { list.*.blank_lines -= 1; }, else => unreachable, } } log.debug("ln:{}: Same blank!\n", .{ self.peek_token().line_nr}); self.close_last_block(); } fn can_list_continue( self: *Parser, comptime new_list: NodeKind, start_token_kind: TokenKind, start_column: u16, // column the list item itself (not the content starts on): ->1. or ->- prev_line_blank: bool, ol_type: u8, ) bool { const last_block = self.get_last_block(); const last_block_kind: NodeKind = last_block.data; var list_data: Node.ListItemData = undefined; switch (last_block.data) { .OrderedListItem, .UnorderedListItem => |data| { list_data = data; }, else => return false, } // const union_field_name = @tagName(new_list); var other_list_type = switch (new_list) { .OrderedListItem => NodeKind.UnorderedListItem, .UnorderedListItem => NodeKind.OrderedListItem, else => unreachable, }; // NOTE: list's loose status should already have been determined // before closing the list so we only have to check when we continue if (start_column == list_data.indent) { if (last_block_kind == new_list) { if (list_data.list_item_starter == start_token_kind and list_data.ol_type == ol_type) { // if (last_block_kind == .OrderedListItem and list_data.ol_type != ol_type) { // // same list type, same indent, same 2nd list starter, different ol type // self.close_list(prev_line_blank); // return false; // } // same list type, same indent, same list starter self.close_last_block(); return true; } else { // same list type, same indent, __different__ list starter self.close_list(prev_line_blank); return false; } } else if (last_block_kind == other_list_type) { // diff list type, same indent // close previous list self.close_list(prev_line_blank); return false; } } else if (start_column < list_data.indent) { // previous list was on a farther indent // => close it self.close_list(prev_line_blank); // test again return self.can_list_continue(new_list, start_token_kind, start_column, prev_line_blank, ol_type); } else { // start_column > indent // increased indent -> don't close anything return false; } unreachable; } fn parse_ordered_list( self: *Parser, start_token_kind: TokenKind, // list_item_starter e.g. '.', ')' start_column: u16, // column the list item starts on (not content): here ->1. prev_line_blank: bool, start_num: u16, ol_type: u8, // 1, a, A, i or I li_starter_offset: u8, ) ParseError!void { try self.handle_open_blocks(NodeKind.OrderedListItem, start_column, prev_line_blank); var list_node: *Node = undefined; // create new list if it can't continue if (!self.can_list_continue( NodeKind.OrderedListItem, start_token_kind, start_column, prev_line_blank, ol_type)) { list_node = try self.new_node(self.get_last_block()); list_node.data = .{ .OrderedList = .{ .blank_lines = 0, .start_num = start_num, .ol_type = ol_type }, }; self.open_block(list_node); } else { list_node = self.get_last_block(); std.debug.assert(list_node.data == NodeKind.OrderedList); } var list_item_node = try self.new_node(list_node); list_item_node.data = .{ .OrderedListItem = .{ .list_item_starter = start_token_kind, .indent = start_column, .ol_type = ol_type, .li_starter_offset = li_starter_offset, }, }; self.open_block(list_item_node); } fn parse_unordered_list( self: *Parser, start_token_kind: TokenKind, start_column: u16, li_starter_offset: u8, prev_line_blank: bool ) ParseError!void { try self.handle_open_blocks(NodeKind.UnorderedListItem, start_column, prev_line_blank); // if one blank line is present in the contents of any of the list items // the list will be loose var list_node: *Node = undefined; // create new list if it can't continue if (!self.can_list_continue( NodeKind.UnorderedListItem, start_token_kind, start_column, prev_line_blank, 0)) { list_node = try self.new_node(self.get_last_container_block()); list_node.data = .{ .UnorderedList = .{ .blank_lines = 0, .start_num = 0, .ol_type = 0 }, }; self.open_block(list_node); } else { list_node = self.get_last_block(); std.debug.assert(list_node.data == NodeKind.UnorderedList); } var list_node_item = try self.new_node(list_node); list_node_item.data = .{ .UnorderedListItem = .{ .list_item_starter = start_token_kind, .indent = start_column, .ol_type = 0, .li_starter_offset = li_starter_offset, }, }; self.open_block(list_node_item); } fn parse_paragraph(self: *Parser, prev_line_blank: bool) ParseError!void { // might have an open list that was not closed by two \n self.close_lists_not_matching_indent( self.get_last_container_block().data, self.peek_token().column, prev_line_blank); // parse_inline stops on Increase_indent after first list item // even though we could continue (unless next line starts another block) // -> check last block and contiue paragraph if we can const last_leaf_block = self.get_last_leaf_block(); if (last_leaf_block != null) log.debug("ln:{}: Last leaf block {s}\n", .{ self.peek_token().line_nr, @tagName(last_leaf_block.?.data) }); if (last_leaf_block == null or last_leaf_block.?.data != NodeKind.Paragraph) { var paragraph = try self.new_node(self.get_last_block()); paragraph.data = NodeKind.Paragraph; self.open_block(paragraph); } // stops on newline, eof, increase_indent, dedent while (try self.parse_inline(true)) {} switch (self.peek_token().token_kind) { .Newline => { // we need the soft line break here to output a space (or w/e) // between lines of the same paragraph that will end up being // printed on the same line var soft_line_break = try self.new_node(self.get_last_block()); soft_line_break.data = NodeKind.SoftLineBreak; // text_node now can't continue anymore self.last_text_node = null; self.eat_token(); // \n }, .Eof => try self.close_paragraph(), else => {}, } } fn close_paragraph(self: *Parser) ParseError!void { if (self.get_last_block().data != NodeKind.Paragraph) { Parser.report_error( "ln:{}: There was at least one unclosed inline element of type '{s}'\n", .{ self.peek_token().line_nr, @tagName(self.get_last_block().data) }); return ParseError.SyntaxError; } self.close_last_block(); } /// eats the token_kind token; EOF is not consumed fn parse_inline_until(self: *Parser, token_kind: TokenKind) ParseError!void { while (try self.parse_inline(false)) { if(self.peek_token().token_kind == token_kind) { self.eat_token(); return; } } } fn parse_code_span(self: *Parser, delimiter: TokenKind, comptime run: bool) ParseError!void { // delimiter -> if code span contains a ` you can use `` to start/end a code span self.eat_token(); const code_span = try self.new_node(self.get_last_block()); const maybe_lang_tok = self.peek_token(); const lang = Language.match(self.tokenizer.bytes[maybe_lang_tok.start..maybe_lang_tok.end]); code_span.data = .{ .CodeSpan = .{ .language = lang, .code = undefined, .run = run, } }; // eat lang name if it could be matched if (lang != .Unknown) { self.eat_token(); self.eat_token(); // eat ' ' } if (run) { // mark language for running it later self.run_languages.insert(lang); } var ctoken = self.peek_token(); const code_span_start = ctoken; while (ctoken.token_kind != delimiter) : ({ // while continue expression (executed on every loop as well as when a // continue happens) self.eat_token(); ctoken = self.peek_token(); }) { if (ctoken.token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end of file inside code span (`...`)", .{ code_span_start.line_nr }); return ParseError.SyntaxError; } } code_span.data.CodeSpan.code = self.tokenizer.bytes[code_span_start.start..self.peek_token().start]; self.eat_token(); // eat closing ` or `` log.debug("ln:{}: Code span {}\n", .{ code_span_start.line_nr, code_span.data }); } /// returns bool determining whether inline parsing should continue /// NOTE(m): no .SoftLineBreak node will be created for the end_on_newline case! fn parse_inline(self: *Parser, comptime end_on_newline: bool) ParseError!bool { const token = self.peek_token(); switch (token.token_kind) { TokenKind.Newline => { if (end_on_newline) { return false; } else { // NOTE(m): no .SoftLineBreak node will be created for the end_on_newline case! self.eat_token(); return true; } }, TokenKind.Eof, TokenKind.Increase_indent, TokenKind.Decrease_indent => return false, TokenKind.Comment => self.eat_token(), TokenKind.Hard_line_break => { self.eat_token(); var line_break = try self.new_node(self.get_last_block()); line_break.data = NodeKind.HardLineBreak; }, TokenKind.Asterisk, TokenKind.Underscore => { // check if we close the last emph block or open one // **fat _also cursive_** // ^ closes _ // ** fat _also cursive** also cursive_ <- not allowed! // NOTE: technichally not a block in the markdown sense but since it can // have children as an AST node we treat it as one const last_block = self.get_last_block(); const current_token_kind = self.peek_token().token_kind; if (last_block.data == NodeKind.Emphasis) { const opener_token_kind = last_block.data.Emphasis.opener_token_kind; if (last_block.data.Emphasis.opener_token_kind != current_token_kind) { Parser.report_error( "ln:{}: Wrong emphasis closer (expected '{}' got '{}')!\n", .{ self.peek_token().line_nr, opener_token_kind, current_token_kind }); return ParseError.SyntaxError; } log.debug("Close emphasis ln:{}: token: {}\n", .{ self.peek_token().line_nr, current_token_kind }); self.close_last_block(); } else { var emph_node = try self.new_node(self.get_last_block()); emph_node.data = .{ .Emphasis = .{ .opener_token_kind = current_token_kind }, }; log.debug("Open emphasis ln:{}: token: {} last block: {}\n", .{ self.peek_token().line_nr, current_token_kind, last_block.data }); self.open_block(emph_node); } self.eat_token(); }, TokenKind.Asterisk_double, TokenKind.Underscore_double => { const last_block = self.get_last_block(); const current_token_kind = self.peek_token().token_kind; if (last_block.data == NodeKind.StrongEmphasis) { const opener_token_kind = last_block.data.StrongEmphasis.opener_token_kind; if (last_block.data.StrongEmphasis.opener_token_kind != current_token_kind) { Parser.report_error( "ln:{}: Wrong strong emphasis closer (expected '{}' got '{}')!\n", .{ self.peek_token().line_nr, opener_token_kind, current_token_kind }); return ParseError.SyntaxError; } log.debug("Close strong emphasis ln:{}: token: {}\n", .{ self.peek_token().line_nr, current_token_kind }); self.close_last_block(); } else { var emph_node = try self.new_node(self.get_last_block()); emph_node.data = .{ .StrongEmphasis = .{ .opener_token_kind = current_token_kind }, }; log.debug("Open strong emphasis ln:{}: token: {}\n", .{ self.peek_token().line_nr, current_token_kind }); self.open_block(emph_node); } self.eat_token(); }, TokenKind.Tilde_double => { const last_block = self.get_last_block(); if (last_block.data == NodeKind.Strikethrough) { log.debug("ln:{}: Close Strikethrough\n", .{ self.peek_token().line_nr }); self.close_last_block(); } else { var strike_node = try self.new_node(self.get_last_block()); strike_node.data = .Strikethrough; log.debug("ln:{}: Open strikethrough\n", .{ self.peek_token().line_nr }); self.open_block(strike_node); } self.eat_token(); }, TokenKind.Caret => { // TODO pandoc doesn't allow spaces/newlines inside super/subscript blocks // but they can be backslash escaped // do this as well? or just make ppl escape the ^/~ instead of spaces inside? const last_block = self.get_last_block(); if (last_block.data == NodeKind.Superscript) { log.debug("ln:{}: Close Superscript\n", .{ self.peek_token().line_nr }); self.close_last_block(); } else { var superscript_node = try self.new_node(self.get_last_block()); superscript_node.data = .Superscript; log.debug("ln:{}: Open superscript\n", .{ self.peek_token().line_nr }); self.open_block(superscript_node); } self.eat_token(); }, TokenKind.Tilde => { const last_block = self.get_last_block(); if (last_block.data == NodeKind.Subscript) { log.debug("ln:{}: Close Subscript\n", .{ self.peek_token().line_nr }); self.close_last_block(); } else { var subscript_node = try self.new_node(self.get_last_block()); subscript_node.data = .Subscript; log.debug("ln:{}: Open subscript\n", .{ self.peek_token().line_nr }); self.open_block(subscript_node); } self.eat_token(); }, .Run_codespan => { try self.parse_code_span(.Backtick, true); }, .Run_codespan_alt => { try self.parse_code_span(.Backtick_double, true); }, TokenKind.Backtick, TokenKind.Backtick_double => { try self.parse_code_span(token.token_kind, false); }, TokenKind.Dollar => { // check if a digit follows immediately after and then just parse it as text // so often used $xx for prices doesn't need to be escaped (how pandoc does it) if (self.peek_next_token().token_kind == TokenKind.Digits) { try self.parse_text(token, self.get_last_block()); return true; } self.eat_token(); var ctoken = self.peek_token(); const inline_math_start = ctoken; while (ctoken.token_kind != TokenKind.Dollar) : ({ // while continue expression (executed on every loop as well as when a // continue happens) self.eat_token(); ctoken = self.peek_token(); }) { if (ctoken.token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end of file inside inline math ($...$)", .{ inline_math_start.line_nr }); return ParseError.SyntaxError; } } const math_node = try self.new_node(self.get_last_block()); math_node.data = .{ .MathInline = .{ .text = self.tokenizer.bytes[inline_math_start.start..self.peek_token().start] } }; self.eat_token(); // eat closing $ log.debug("ln:{}: Math span: `{s}`\n", .{ inline_math_start.line_nr, math_node.data.MathInline.text }); }, TokenKind.Open_bracket => { try self.parse_link(); }, TokenKind.Builtin_call => { try self.parse_builtin(token); }, else => { try self.parse_text(token, self.get_last_block()); }, } return true; } inline fn parse_text(self: *Parser, token: *const Token, parent: *Node) ParseError!void { if (self.last_text_node) |continue_text| { // enlarge slice by directly manipulating the length (which is allowed in zig) // TODO backslash escaped text will result in faulty text, since the // backslash is included but the escaped text isn't and this as a whole ends // up making the text buffer too narrow continue_text.data.Text.text.len += token.end - token.start; } else { var text_node = try self.new_node(parent); text_node.data = .{ .Text = .{ .text = self.tokenizer.bytes[token.start..token.end] }, }; self.last_text_node = text_node; } self.eat_token(); // TODO @Robustness? invalidate last_text_node since Newline will // be consumed by caller and will most likely never reach parse_inline // the swallowed newline will thus not be added to the text slice // and following continuation texts that get added will be off by one // alternative is to add the newline here instead but that might not be // wanted all the time if (self.peek_token().token_kind == TokenKind.Newline) { self.last_text_node = null; } } fn parse_link(self: *Parser) ParseError!void { // still on [ token self.eat_token(); var link_node = try self.new_node(self.get_last_block()); link_node.data = .{ .Link = .{ .label = null, .url = null, .title = null, }, }; self.open_block(link_node); const link_text_start_token = self.peek_token(); // TODO @CleanUp handle +-Indent while (try self.parse_inline(false)) { if (self.peek_token().token_kind == TokenKind.Close_bracket) { const last_block = self.get_last_block(); if (last_block.data != NodeKind.Link) { Parser.report_error( "ln:{}: Unclosed {s} in Link text (first [] of a link definition)\n", .{ self.peek_token().line_nr, @tagName(last_block.data) }); return ParseError.SyntaxError; } break; } } if (self.peek_token().token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end of file inside link text\n", .{ link_text_start_token.line_nr }); return ParseError.SyntaxError; } const link_text_end = self.peek_token().start; self.eat_token(); // eat ] var token = self.peek_token(); if (token.token_kind == TokenKind.Open_bracket) { link_node.data.Link.label = try self.parse_link_ref_label(NodeKind.Link); } else if (token.token_kind == TokenKind.Open_paren) { // start of url try self.parse_link_destination(); // expects to start on ( } else { // use link text as link label referring to a reference definition link_node.data.Link.label = self.tokenizer.bytes[link_text_start_token.start..link_text_end]; } self.close_last_block(); log.debug("ln:{}: Link: {}\n", .{ link_text_start_token.line_nr, link_node.data }); } fn parse_link_ref_label(self: *Parser, comptime kind: NodeKind) ParseError![]const u8 { // TODO compiler bug: expected token '}', found 'DocComment' // if function starts with a /// // /// expects to start on [ // start of link label referring to a reference definition self.eat_token(); var token = self.peek_token(); const start_token = token; while (true) { if (token.token_kind == TokenKind.Close_bracket) { self.eat_token(); break; } else if (token.token_kind == TokenKind.Eof) { Parser.report_error( "ln:{}: Encountered end-of-file inside {s} label brackets\n", .{ token.line_nr, @tagName(kind) }); return ParseError.SyntaxError; } self.eat_token(); token = self.peek_token(); } const label_end = token.start; return self.tokenizer.bytes[start_token.start..label_end]; } fn parse_code_block(self: *Parser) ParseError!void { // ArrayList doesn't accept ArenaAllocator directly so we need to // pass string_arena.allocator which is the proper mem.Allocator var string_buf = std.ArrayList(u8).init(&self.string_arena.allocator); var current_indent_lvl: u16 = 0; // TODO switch this to using spaces instead of "levels"? const indent = " " ** tokenizer.SPACES_PER_INDENT; var current_token: *Token = self.peek_token(); var line_start = false; while (true) { if (current_token.token_kind == TokenKind.Backtick_triple) { self.eat_token(); break; } else if (current_token.token_kind == TokenKind.Newline) { try string_buf.append('\n'); line_start = true; } else if (current_token.token_kind == TokenKind.Increase_indent) { current_indent_lvl += 1; } else if (current_token.token_kind == TokenKind.Decrease_indent) { current_indent_lvl -= 1; if (current_indent_lvl < 0) { self.report_error( "ln:{}: Code block's indent decreased beyond it's starting level!", .{ current_token.line_nr }); return ParseError.SyntaxError; } } else { if (line_start) { // indent to correct level at line start var i: u32 = 0; while (i < current_indent_lvl) : (i += 1) { try string_buf.appendSlice(indent); } line_start = false; } try string_buf.appendSlice(current_token.text(self.tokenizer.bytes)); } self.eat_token(); current_token = self.peek_token(); } const code_block = self.get_last_block(); // string_buf.toOwnedSlice() -> caller owns the returned memory (remaining capacity is free'd) code_block.data.FencedCode.code = string_buf.toOwnedSlice(); self.close_last_block(); // close code block log.debug("Code block:\n{s}", .{ code_block.data.FencedCode.code }); } /// when this method is called we're still on the first '(' fn parse_link_destination(self: *Parser) ParseError!void { try self.require_token(TokenKind.Open_paren, ". Link destinations need to be wrapped in parentheses!"); self.eat_token(); // eat ( var token = self.peek_token(); const token_url_start = token; var ended_on_link_title = false; while (token.token_kind != TokenKind.Close_paren) { if (token.token_kind == TokenKind.Eof) { Parser.report_error("ln:{}: Missing closing ')' in link destination\n", .{ token_url_start.line_nr }); return ParseError.SyntaxError; } else if (token.token_kind == TokenKind.Space and self.peek_next_token().token_kind == TokenKind.Double_quote) { // TODO allow title to start at next line // start of link title self.eat_token(); ended_on_link_title = true; break; } self.eat_token(); token = self.peek_token(); } const token_url_end = token; if (token_url_start.start == token_url_end.start) { Parser.report_error("ln:{}: Empty link destination\n", .{ token_url_end.line_nr }); return ParseError.SyntaxError; } const link_or_ref = self.get_last_block(); log.debug("ln:{}: Parse destination -> Link or ref: {s}\n", .{ self.peek_token().line_nr , @tagName(self.get_last_block().data) }); if (ended_on_link_title) { self.eat_token(); // eat " token = self.peek_token(); const link_title_start = token; while (token.token_kind != TokenKind.Double_quote) { if (token.token_kind == TokenKind.Eof) { Parser.report_error("ln:{}: Missing closing '\"' in link title\n", .{ link_title_start.line_nr }); return ParseError.SyntaxError; } self.eat_token(); token = self.peek_token(); } const link_title_end = token; self.eat_token(); // eat " try self.require_token(TokenKind.Close_paren, ". Link destination needs to be enclosed in parentheses!"); self.eat_token(); // eat ) if (link_title_start.start == link_title_end.start) { Parser.report_error("ln:{}: Empty link title\n", .{ token_url_end.line_nr }); return ParseError.SyntaxError; } switch (link_or_ref.data) { // payload of this switch prong is the assigned NodeData type // |value| is just a copy so we need to capture the ptr to modify it .Link, .LinkRef => |*value| { value.*.url = self.tokenizer.bytes[token_url_start.start..token_url_end.start]; value.*.title = self.tokenizer.bytes[link_title_start.start..link_title_end.start]; }, .Image => |*value| { value.*.url = self.tokenizer.bytes[token_url_start.start..token_url_end.start]; value.*.title = self.tokenizer.bytes[link_title_start.start..link_title_end.start]; }, else => unreachable, } } else { self.eat_token(); // eat ) switch (link_or_ref.data) { .Link, .LinkRef => |*value| { value.*.url = self.tokenizer.bytes[token_url_start.start..token_url_end.start]; value.*.title = null; }, .Image => |*value| { value.*.url = self.tokenizer.bytes[token_url_start.start..token_url_end.start]; value.*.title = null; }, else => unreachable, } } log.debug("Link dest: {}\n", .{ link_or_ref.data }); } inline fn skip_after_param(self: *Parser) !void { // we either need a after_pos_param state (which would mean // after_kw_param is needed as well) or we can skip all whitespace // till we hit the comma // TODO iterator? that erros on eof while (true) { tok = self.peek_token(); switch (tok.token_kind) { .Comma, .Close_paren => { state = .in_pos_param; // so ',' gets treated as finisher break; }, .Space, .Tab => {}, else => { Parser.report_error( "ln:{}: Hit '{s}' while waiting for param delimiter ','" ++ " or call closer ')' when parsing a builtin call!\n", .{ start_token.line_nr, tok.token_kind.name() }); return ParseError.SyntaxError; }, } self.eat_token(); } } fn parse_builtin(self: *Parser, start_token: *const Token) ParseError!void { self.eat_token(); // eat start_token try self.require_token( .Open_paren, ". Calling a builtin should look like: @builtin(arg, kwarg=..)\n"); self.eat_token(); var builtin = try self.new_node(self.get_last_block()); // start + 1 since the @ is included const keyword = self.tokenizer.bytes[start_token.start + 1..start_token.end]; const mb_builtin_type = std.meta.stringToEnum(BuiltinCall, keyword); log.debug("Builtin type: {}", .{ mb_builtin_type }); if (mb_builtin_type) |bi_type| { builtin.data = .{ .BuiltinCall = .{ .builtin_type = bi_type } }; } else { Parser.report_error( "ln:{}: Unrecognized builtin: '{s}'\n", .{ start_token.line_nr, keyword }); return ParseError.SyntaxError; } self.open_block(builtin); var current_arg = try self.new_node(builtin); current_arg.data = .PostionalArg; self.open_block(current_arg); const State = enum { next_pos_param, in_pos_param, // only expect kw_params after the first one next_kw, in_kw, after_kw, next_kw_param, in_kw_param, }; var state = State.next_pos_param; var tok = self.peek_token(); var last_end = tok.start; // exclusive // needed for switching to kwargs in the middle of in_pos_param // so we only need to set this in .next_pos_param and .in_pos_param var last_non_space = last_end; // exclusive var pos_params: u16 = 0; var kw_params: u16 = 0; while (tok.token_kind != .Close_paren) : ({ tok = self.peek_token(); }) { switch (state) { .next_pos_param => { switch (tok.token_kind) { .Space, .Tab, .Newline => { last_end += 1; self.eat_token(); }, else => { state = .in_pos_param; _ = try self.parse_inline(true); // eats the tok last_non_space = tok.end; }, } }, .next_kw_param => { switch (tok.token_kind) { .Space, .Tab, .Newline => { last_end += 1; self.eat_token(); }, else => { state = .in_kw_param; _ = try self.parse_inline(true); // eats the tok }, } }, .in_pos_param => { switch (tok.token_kind) { .Equals => { current_arg.data = .{ .KeywordArg = .{ .keyword = self.tokenizer.bytes[last_end..last_non_space], }, }; state = State.next_kw_param; last_end = tok.end; // delete text node that was created as the first param // TODO maybe force to use double quotes? // TODO this is error prone @Improve // (additionally make new_node set this to null?) self.last_text_node = null; current_arg.delete_direct_children(&self.node_arena.allocator); self.eat_token(); }, .Comma => { log.debug( "ln:{}: Finished arg: {s}", .{ start_token.line_nr, current_arg.data }); self.close_last_block(); state = .next_pos_param; self.last_text_node = null; last_end = tok.end; pos_params += 1; current_arg = try self.new_node(builtin); current_arg.data = .PostionalArg; self.open_block(current_arg); self.eat_token(); }, .Newline => { Parser.report_error( "ln:{}: Newlines are not allowed inside parameter values!\n", .{ tok.line_nr }); return ParseError.SyntaxError; }, .Space, .Tab => { // treat this as a special case since we might encounter an // = which would make this a kw param meaning we'd have to remember // the last_non_space properly _ = try self.parse_inline(true); // eats the tok }, else => { _ = try self.parse_inline(true); // eats the tok last_non_space = tok.end; } } }, .next_kw => { switch (tok.token_kind) { .Space, .Tab, .Newline => { last_end += 1; self.eat_token(); }, .Text, .Underscore => { state = .in_kw; // TODO is this needed? try self.parse_text(tok, current_arg); // eats the tok self.eat_token(); }, else => { Parser.report_error( "ln:{}: Expected keyword got {s}!\n", .{ start_token.line_nr, tok.token_kind.name() }); return ParseError.SyntaxError; }, } }, .in_kw => { switch (tok.token_kind) { .Space, .Tab, .Newline => { state = .after_kw; current_arg.data.KeywordArg.keyword = self.tokenizer.bytes[last_end..tok.start]; last_end = tok.end; self.eat_token(); }, .Equals => { state = .next_kw_param; current_arg.data.KeywordArg.keyword = self.tokenizer.bytes[last_end..tok.start]; last_end = tok.end; self.eat_token(); }, .Builtin_call => return ParseError.SyntaxError, else => { self.eat_token(); }, } }, .after_kw => { switch (tok.token_kind) { .Space, .Tab, .Newline => { self.eat_token(); }, .Builtin_call => return ParseError.SyntaxError, .Equals => { state = .next_kw_param; last_end = tok.end; self.eat_token(); }, else => { Parser.report_error( "ln:{}: Expected '=' got {s}!\n", .{ start_token.line_nr, tok.token_kind.name() }); return ParseError.SyntaxError; }, } }, .in_kw_param => { switch (tok.token_kind) { .Comma => { log.debug( "ln:{}: Finished arg: {}", .{ start_token.line_nr, current_arg.data }); self.close_last_block(); state = .next_kw; last_end = tok.end; kw_params += 1; self.last_text_node = null; current_arg = try self.new_node(builtin); self.open_block(current_arg); current_arg.data = .{ .KeywordArg = .{ .keyword = undefined, }, }; self.eat_token(); }, .Newline => { Parser.report_error( "ln:{}: Newlines are not allowed inside parameter values!\n", .{ tok.line_nr }); return ParseError.SyntaxError; }, else => _ = try self.parse_inline(true), // eats the tok } }, } } switch (state) { .in_kw, .after_kw, => { Parser.report_error( "ln:{}: Encountered postional argument after keyword argument!\n", .{ start_token.line_nr }); return ParseError.SyntaxError; }, .next_kw_param => { Parser.report_error( "ln:{}: Missing keyword parameter value!\n", .{ start_token.line_nr }); return ParseError.SyntaxError; }, .next_kw, .next_pos_param, // ignore extra comma e.g. @kw(abc, def,) .in_pos_param, .in_kw_param => { self.last_text_node = null; self.close_last_block(); // arg std.debug.assert(self.get_last_block().data == .BuiltinCall); self.close_last_block(); // builtin node switch (state) { .in_pos_param => pos_params += 1, .in_kw_param => kw_params += 1, else => {}, } log.debug("ln:{}: LAST Finished arg: {}", .{ start_token.line_nr, current_arg.data }); }, } // TODO inline blocks now allowed as arguments, when they're used with cite builtins // or with nested builtins they won't be respected / or we will crash // @CleanUp self.eat_token(); // eat ) log.debug( "ln:{}: Finished builtin: {s} pos: {}, kw: {}", .{ start_token.line_nr, self.tokenizer.bytes[start_token.start..start_token.end], pos_params, kw_params }); builtin.print_tree(); const bc_info = builtin_call_info[@enumToInt(mb_builtin_type.?)]; if (bc_info.pos_params >= 0 and pos_params != bc_info.pos_params) { Parser.report_error( "ln:{}: Expected {} positional arguments, found {} for builtin '{s}'\n", .{ start_token.line_nr, bc_info.pos_params, pos_params, keyword }); return ParseError.SyntaxError; } else if (kw_params > bc_info.kw_params) { Parser.report_error( "ln:{}: Expected a maximum of {} keyword arguments, found {} for builtin '{s}'\n", .{ start_token.line_nr, bc_info.kw_params, kw_params, keyword }); return ParseError.SyntaxError; } try self.execute_builtin(builtin, mb_builtin_type.?, .{}); } fn execute_builtin( self: *Parser, builtin_node: *ast.Node, builtin_type: BuiltinCall, data: anytype, ) ParseError!void { const allocator = &self.node_arena.allocator; const result = bic.evaluate_builtin(allocator, builtin_node, builtin_type, .{}) catch { return ParseError.BuiltinCallFailed; }; if (bic.builtin_call_info[@enumToInt(builtin_type)].persistent) { const persistent = try allocator.create(bic.BuiltinResult); persistent.* = result; builtin_node.data.BuiltinCall.result = persistent; } switch (result) { .cite, .textcite, .cites => { // store citation nodes for passing them to citeproc and replacing them // with actual citation nodes // NOTE: only store top-level citation calls (otherwise we get duplicate // output for .cites etc.) switch (self.get_last_block().data) { .BuiltinCall, .PostionalArg, .KeywordArg => {}, else => try self.citations.append(builtin_node), } }, .bibliography => { if (self.bibliography) |bib_node| { Parser.report_error("Only one bibliography allowed currently!\n", .{}); return ParseError.SyntaxError; } self.bibliography = result.bibliography; }, // TODO should these (or all builtin results?) be their own NodeData? .label => { const entry_found = try self.label_node_map.getOrPut(result.label); // ^ result will be a struct with a pointer to the HashMap.Entry and a bool // whether an existing value was found if (entry_found.found_existing) { Parser.report_error("ln:{d}: Duplicate label '{s}'!\n", .{ self.peek_token().line_nr, result.label }); return ParseError.SyntaxError; } else { // actually write entry value (key was already written by getOrPut) const parent = self.get_last_block(); std.debug.assert(parent.data != .BuiltinCall and parent.data != .PostionalArg and parent.data != .KeywordArg); entry_found.value_ptr.* = &parent.data; } }, else => {}, } } };
src/parser.zig
const std = @import("std"); const debug = std.debug; const mem = std.mem; const grid_serial_number: u32 = 5791; const grid_side_len = 300; pub fn main() void { const result1 = regionOfHighestTotalPower(grid_serial_number); debug.assert(V2.eq(V2.init(20, 68), result1)); debug.warn("11-1: {}\n", result1); const result2 = regionOfHighestTotalPowerOfAnySize(grid_serial_number); debug.assert(V2.eq(V2.init(231, 273), result2.region)); debug.assert(16 == result2.square_side_len); debug.warn("11-2: {},{}\n", result2.region, result2.square_side_len); } fn regionOfHighestTotalPowerOfAnySize(gsn: u32) RegionInfo { var grid = []i32{0} ** (grid_side_len * grid_side_len); for (grid) |*cell, i| { var coord = point_from_index(i, grid_side_len); // grid is 1 based, though array is 0 based cell.* = getFuelCellPower(coord.x + 1, coord.y + 1, gsn); } // https://en.wikipedia.org/wiki/Summed-area_table var sat = []i32{0} ** grid.len; for (grid) |cell, i| { const c = point_from_index(i, grid_side_len); sat[i] = grid[index_from_point(c.x, c.y, grid_side_len)]; if (c.x > 0) { sat[i] += sat[index_from_point(c.x - 1, c.y, grid_side_len)]; } if (c.y > 0) { sat[i] += sat[index_from_point(c.x, c.y - 1, grid_side_len)]; } if (c.x > 0 and c.y > 0) { sat[i] -= sat[index_from_point(c.x - 1, c.y - 1, grid_side_len)]; } } var highest_highest_power: i32 = grid[0]; var highest_highest_power_region = V2.init(0, 0); var highest_square_side_len: u32 = 1; var square_side_len: u32 = 1; while (square_side_len <= grid_side_len) : (square_side_len += 1) { var highest_power: i32 = @minValue(i32); var highest_power_region = V2.init(1, 1); for (grid) |cell, i| { const array_coord = point_from_index(i, grid_side_len); // cells start at (1, 1) const cell_coord = V2.init(array_coord.x + 1, array_coord.y + 1); const search_threshold = (grid_side_len - square_side_len) + 1; if (cell_coord.x > search_threshold or cell_coord.y > search_threshold) { continue; } const ssl = square_side_len - 1; // +----------------------+ // | | | | // | A| B| | // |------+-----------+ | // | | | | // | | | | // | | | | // | C| D| | // |------+-----------+ | // | | // +----------------------+ // sum = D - B - C + A // D var sum: i32 = sat[index_from_point(array_coord.x + ssl, array_coord.y + ssl, grid_side_len)]; if (array_coord.x > 0) { // - C sum -= sat[index_from_point(array_coord.x - 1, array_coord.y + ssl, grid_side_len)]; } if (array_coord.y > 0) { // - B sum -= sat[index_from_point(array_coord.x + ssl, array_coord.y - 1, grid_side_len)]; } if (array_coord.x > 0 and array_coord.y > 0) { // + A sum += sat[index_from_point(array_coord.x - 1, array_coord.y - 1, grid_side_len)]; } if (sum > highest_power) { highest_power = sum; highest_power_region = cell_coord; } } if (highest_power > highest_highest_power) { highest_highest_power = highest_power; highest_highest_power_region = highest_power_region; highest_square_side_len = square_side_len; } } return RegionInfo { .region = highest_highest_power_region, .square_side_len = highest_square_side_len, }; } const RegionInfo = struct { region: V2, square_side_len: u32, }; test "region of highest total power of any size" { const r18 = regionOfHighestTotalPowerOfAnySize(18); debug.assert(V2.eq(V2.init(90, 269), r18.region)); debug.assert(16 == r18.square_side_len); const r42 = regionOfHighestTotalPowerOfAnySize(42); debug.assert(V2.eq(V2.init(232, 251), r42.region)); debug.assert(12 == r42.square_side_len); } fn regionOfHighestTotalPower(gsn: u32) V2{ var grid = []i32{0} ** (grid_side_len * grid_side_len); for (grid) |*cell, i| { var coord = point_from_index(i, grid_side_len); // grid is 1 based, though array is 0 based coord.x += 1; coord.y += 1; cell.* = getFuelCellPower(coord.x, coord.y, gsn); } var square_side_len: u32 = 3; var highest_power: i32 = 0; var highest_power_region = V2.init(1, 1); for (grid) |cell, i| { const array_coord = point_from_index(i, grid_side_len); const cell_coord = V2.init(array_coord.x + 1, array_coord.y + 1); const search_threshold = grid_side_len - square_side_len; if (cell_coord.x >= search_threshold or cell_coord.y >= search_threshold) { continue; } var sum: i32 = 0; var square_x: u32 = 0; while (square_x < square_side_len) : (square_x += 1) { var square_y: u32 = 0; while (square_y < square_side_len) : (square_y += 1) { sum += grid[index_from_point(array_coord.x + square_x, array_coord.y + square_y, grid_side_len)]; } } if (sum > highest_power) { highest_power = sum; highest_power_region = cell_coord; } } return highest_power_region; } test "region of highest total power" { debug.assert(V2.eq(V2.init(33, 45), regionOfHighestTotalPower(18))); debug.assert(V2.eq(V2.init(21, 61), regionOfHighestTotalPower(42))); } fn getFuelCellPower(cell_x: u32, cell_y: u32, gsn: u32) i32 { const rack_id = cell_x + 10; var power_level: i32 = @intCast(i32, rack_id * cell_y); power_level += @intCast(i32, gsn); power_level *= @intCast(i32, rack_id); power_level = hundredsDigit(power_level); power_level -= 5; return power_level; } test "get fuel cell power" { debug.assert(4 == getFuelCellPower(3, 5, 8)); debug.assert(-5 == getFuelCellPower(122, 79, 57)); debug.assert(0 == getFuelCellPower(217, 196, 39)); debug.assert(4 == getFuelCellPower(101, 153, 71)); } inline fn hundredsDigit(n: i32) i32 { return @mod(@divTrunc(n, 100), 10); } test "hundreds digit" { debug.assert(0 == hundredsDigit(0)); debug.assert(0 == hundredsDigit(10)); debug.assert(1 == hundredsDigit(100)); debug.assert(0 == hundredsDigit(1000)); debug.assert(3 == hundredsDigit(12345)); } fn point_from_index(i: usize, stride: usize) V2 { var x: u32 = @intCast(u32, i % stride); var y: u32 = @intCast(u32, @divTrunc(i, stride)); return V2.init(x, y); } test "point from index" { debug.assert(V2.eq(V2.init(0, 0), point_from_index(0, 5))); debug.assert(V2.eq(V2.init(1, 1), point_from_index(6, 5))); debug.assert(V2.eq(V2.init(2, 1), point_from_index(7, 5))); debug.assert(V2.eq(V2.init(4, 2), point_from_index(14, 5))); debug.assert(V2.eq(V2.init(4, 4), point_from_index(24, 5))); } inline fn index_from_point(x: u32, y: u32, stride: usize) usize { return y * stride + x; } test "index from point" { debug.assert(0 == index_from_point(0, 0, 5)); debug.assert(6 == index_from_point(1, 1, 5)); debug.assert(7 == index_from_point(2, 1, 5)); debug.assert(14 == index_from_point(4, 2, 5)); debug.assert(24 == index_from_point(4, 4, 5)); } const V2 = struct { x: u32, y: u32, pub fn init(x: u32, y: u32) V2 { return V2 { .x = x, .y = y, }; } pub fn eq(vec1: V2, vec2: V2) bool { return vec1.x == vec2.x and vec1.y == vec2.y; } };
2018/day_11.zig
const std = @import("std"); const maxIgnorePatternLength: u32 = 1024; const maxIgnoreFilenameLength: u32 = 1024; fn trim(str: []u8) []u8 { var first: u64 = 0; while (first < str.len and str[first] == ' ') { first += 1; } var last: u64 = str.len; while (last > 0 and str[last - 1] == ' ') { last -= 1; } return str[first..last]; } pub fn main() anyerror!u8 { const fs = std.fs; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(&arena.allocator, args); const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); if (args.len != 2) { try stderr.print("Usage: {s} <root of path to sync>\n", .{args[0]}); return 1; } const rootPath = args[1]; const stdin = std.io.getStdIn().reader(); var buffer: [maxIgnoreFilenameLength]u8 = undefined; while (try stdin.readUntilDelimiterOrEof(&buffer, '\n')) |arg| { const realPath = fs.realpathAlloc(allocator, arg) catch |err| switch (err) { error.FileNotFound => { try stderr.print("Failed to find file {s}\n", .{arg}); return err; }, else => { return err; }, }; defer allocator.free(realPath); const absDir = fs.path.dirname(realPath) orelse { try stderr.print("Could not get directory of file {s}\n", .{realPath}); return error.DirNotFound; }; const file = fs.openFileAbsolute(realPath, .{ .read = true }) catch |err| switch (err) { error.FileNotFound => { try stderr.print("Failed to read file {s}\n", .{realPath}); return err; }, else => { return err; }, }; defer file.close(); const reader = file.reader(); while (true) { var line: []u8 = reader.readUntilDelimiterOrEofAlloc(allocator, '\n', maxIgnorePatternLength) catch |err| switch (err) { error.StreamTooLong => { try stderr.print("File '{s}'' has lines which are too long\n", .{realPath}); break; }, else => { try stdout.print("Error during read of file '{s}'\n", .{err}); return err; }, } orelse { break; }; if (line.len == 0) { continue; } line = trim(line); // .gitignore comment or inverted pattern if (line[0] == '#' or line[0] == '!') { continue; } var joined: []u8 = &.{}; if (line[0] == '/') { joined = try fs.path.join(allocator, &.{ absDir, line }); } else { joined = try fs.path.join(allocator, &.{ absDir, "**", line }); } defer allocator.free(joined); const relative = try fs.path.relative(allocator, rootPath, joined); defer allocator.free(relative); if (joined[joined.len - 1] != '/') { try stdout.print("{s}\n", .{relative}); } const globJoined = try fs.path.join(allocator, &.{ relative, "**" }); defer allocator.free(globJoined); try stdout.print("{s}\n", .{globJoined}); } } return 0; }
src/main.zig
pub const DescIter = struct { drv: *Driver, i: u8, curr: Descriptor, next: Descriptor, /// Put the head of a descriptor chain on the available ring pub fn begin(iter: *DescIter) void { var i = &iter.drv.queues[iter.i]; iter.next = iter.drv.descr(iter.i); i.avail.rings(i.wrap(i.avail.idx +% i.pending)).* = iter.next; i.pending += 1; } /// Put a descriptor to be part of the descriptor chain pub fn put(iter: *DescIter, a: anytype, len: u32, flags: u16) void { iter.curr = iter.next; iter.next = if ((flags & VRING_DESC_F_NEXT) != 0) iter.drv.descr(iter.i) else 0xFFFF; assert(len <= 0x1000); const addr = paging.translate_virt(.{.virt = @ptrToInt(a)}) catch |err| { @panic("virtio-pci: can't get the physical address"); }; iter.drv.queues[iter.i].desc[iter.curr] = .{ .addr = addr, .len = len, .flags = flags, .next = iter.next }; } }; /// The actual driver structure for the modern virtio-pci transport. /// It expects already-initialized BARs. There is no support for the legacy PIO-only interface. pub const Driver = struct { /// Find PCI BARs and initialize device pub fn init(a: pci.Addr, reqFeatures: u64, optFeatures: u64) !Driver { var drv: Driver = detectbars(a); drv.cfg.device_status = 0; // reset drv.cfg.device_status |= VIRTIO_ACKNOWLEDGE; // guest acknowledged device drv.cfg.device_status |= VIRTIO_DRIVER; // driver has been loaded errdefer drv.cfg.device_status |= VIRTIO_FAILED; // set the failed bit on unrecoverable errors // negotiate features var req = reqFeatures | (1 << VIRTIO_F_VERSION_1); // legacy devices aren't supported try drv.feature(0, @truncate(u32, req), @truncate(u32, optFeatures)); try drv.feature(1, @truncate(u32, req >> 32), @truncate(u32, optFeatures >> 32)); drv.cfg.device_status |= VIRTIO_FEATURES_OK; // features acknowledged if ((drv.cfg.device_status & VIRTIO_FEATURES_OK) == 0) return error.FeaturesNotAccepted; for (drv.queues) |_, i| drv.setupqueue(@truncate(u16, i)); drv.cfg.device_status |= VIRTIO_DRIVER_OK; // driver initialized, start normal operation return drv; } /// Create descriptor iterator pub fn iter(drv: *Driver, i: u8) DescIter { return .{ .drv = drv, .i = i, .curr = 0xFFFF, .next = 0xFFFF }; } /// Free the chain which starts at `head` pub fn freechain(drv: *Driver, i: u8, head: Descriptor) void { var q: *VirtQueue = &drv.queues[i]; var last = &q.desc[head]; while ((last.flags & VRING_DESC_F_NEXT) != 0) { // follow descriptor chain q.num_unused += 1; last = &q.desc[last.next]; } // last is now the descriptor *after* the chain q.num_unused += 1; last.next = q.first_unused; last.flags = if (q.first_unused != 0xFFFF) VRING_DESC_F_NEXT else 0; // add the freed chain before the current freelist q.first_unused = head; } /// Process incoming events. NOTE: this does not acknowledge the interrupt, to do that, use acknowledge() pub fn process(drv: *Driver, i: u8, cb: anytype, ctx: anytype) void { var q = &drv.queues[i]; while (q.last_in_used != q.used.idx) { var elem = q.used.rings(q.wrap(q.last_in_used)); q.last_in_used = q.last_in_used +% 1; cb(ctx, i, @truncate(u16, elem.id)); } } /// Make the descriptors available to the device and notify it. pub fn start(drv: *Driver, i: u8) void { // The virtio spec requires me to send values modulo 2^16, and not modulo size // This explains the ugly overflowing-adds drv.queues[i].avail.idx = drv.queues[i].avail.idx +% drv.queues[i].pending; drv.queues[i].pending = 0; drv.notify[i * drv.notify_mul] = drv.queues[i].avail.idx; } /// Acknowledge virtio interrupt pub fn acknowledge(drv: *Driver) void { var result = drv.isr.*; // Doesn't look very robust, but it works. Definitively look here if something breaks. } /// Allocate a descriptor pub fn descr(drv: *Driver, i: u8) Descriptor { var q = &drv.queues[i]; var first_un = q.first_unused; if ((first_un == 0xFFFF) or (q.num_unused == 0)) @panic("virtio-pci: not enough descriptors"); q.first_unused = q.desc[first_un].next; drv.queues[i].num_unused -= 1; return first_un; } /// Negotiate feature bitmask with device fn feature(drv: *Driver, i: u32, req: u32, opt: u32) !void { drv.cfg.device_feature_select = i; const f = drv.cfg.device_feature & (req | opt); if ((f & req) != req) return error.FeatureNotAvailable; drv.cfg.guest_feature_select = i; drv.cfg.guest_feature = f; } /// Detect BARs and capabilities and set up the cfg/notify/isr/dev structures fn detectbars(a: pci.Addr) Driver { var drv: Driver = undefined; var cap = a.cap(); while (cap.off != 0) { const vndr = cap.vndr(); if (vndr == 0x09) { const cfg_typ = cap.read(u8, VIRTIO_PCI_CAP_CFG_TYPE); const bar = cap.read(u8, VIRTIO_PCI_CAP_BAR); const off = cap.read(u32, VIRTIO_PCI_CAP_OFFSET); const len = cap.read(u32, VIRTIO_PCI_CAP_LENGTH); const phy = a.barinfo(bar).phy + off; switch (cfg_typ) { VIRTIO_PCI_CAP_COMMON_CFG => { drv.cfg = os.platform.phys_ptr(*volatile CommonCfg).from_int(phy).get_uncached(); }, VIRTIO_PCI_CAP_NOTIFY_CFG => { drv.notify_mul = cap.read(u32, VIRTIO_PCI_NOTIFY_CAP_MULT) / 2; // VIRTIO_PCI_NOTIFY_CAP_MULT is a byte offset, each field is u16 drv.notify = os.platform.phys_ptr([*]volatile u16).from_int(phy).get_uncached(); }, VIRTIO_PCI_CAP_ISR_CFG => { drv.isr = os.platform.phys_ptr(*volatile u32).from_int(phy).get_uncached(); }, VIRTIO_PCI_CAP_DEVICE_CFG => { drv.dev = os.platform.phys_ptr([*]volatile u8).from_int(phy).get_uncached(); }, VIRTIO_PCI_CAP_PCI_CFG => { }, else => {}, // ignore } } cap.next(); } return drv; } /// Set up a specific queue fn setupqueue(drv: *Driver, i: u16) void { drv.cfg.queue_select = i; const size = drv.cfg.queue_size; if (size == 0) return; const desc_siz: u32 = @sizeOf(VirtqDesc) * size; const avail_siz: u32 = @sizeOf(VirtqAvail) + 2 + 2 * size; const used_siz: u32 = @sizeOf(VirtqUsed) + 2 + @sizeOf(VirtqUsedItem) * size; const total_siz = desc_siz + avail_siz + used_siz; const phys = os.memory.pmm.alloc_phys(size) catch unreachable; const virt = os.platform.phys_ptr([*]volatile u8).from_int(phys).get_uncached(); @memset(virt, 0x00, total_siz); drv.queues[i] = .{ .desc = @ptrCast([*]VirtqDesc, virt), .avail = @ptrCast(*VirtqAvail, virt + desc_siz), .used = @ptrCast(*VirtqUsed, virt + desc_siz + avail_siz), .size = size, .num_unused = size, .first_unused = 0, .last_in_used = 0, .pending = 0, }; var m: u16 = 0; while (m < size - 1) : (m += 1) { drv.queues[i].desc[m] = .{ .flags = VRING_DESC_F_NEXT, .next = m + 1, .addr = 0, .len = 0 }; } drv.queues[i].desc[m].next = 0xFFFF; drv.cfg.queue_desc = phys; drv.cfg.queue_avail = phys + desc_siz; drv.cfg.queue_used = phys + desc_siz + avail_siz; drv.cfg.queue_enable = 1; // important: this enables the queue } cfg: *volatile CommonCfg, notify: [*]volatile Descriptor, notify_mul: u32, isr: *volatile u32, dev: [*]volatile u8, queues: [16]VirtQueue = undefined, }; pub const Descriptor = u16; // descriptor id const os = @import("root").os; const libalign = os.lib.libalign; const allocator = os.memory.vmm.backed(.Ephemeral); const pmm = os.memory.pmm; const paging = os.memory.paging; const pci = os.platform.pci; const assert = @import("std").debug.assert; /// Ring descriptor, actual structure (`Descriptor` is only its id) const VirtqDesc = packed struct { addr: u64, // guest phyaddr len: u32, flags: u16, next: Descriptor, }; // ring flags pub const VRING_DESC_F_NEXT: u32 = 1; pub const VRING_DESC_F_WRITE: u32 = 2; pub const VRING_DESC_F_INDIRECT: u32 = 4; const VirtqAvail = packed struct { flags: u16, idx: Descriptor, // important: virtio requires this field to have the index without wraparound pub fn rings(self: *volatile VirtqAvail, desc: Descriptor) *volatile u16 { return @intToPtr(*volatile u16, @ptrToInt(self) + @sizeOf(VirtqAvail) + desc * 2); } }; const VirtqUsedItem = packed struct { id: u32, // descriptor chain head len: u32, }; const VirtqUsed = packed struct { flags: u16, idx: u16, // last used idx, the driver keeps the first in last_in_used pub fn rings(self: *volatile VirtqUsed, desc: Descriptor) *volatile VirtqUsedItem { return @intToPtr(*volatile VirtqUsedItem, @ptrToInt(self) + @sizeOf(VirtqUsed) + desc * @sizeOf(VirtqUsedItem)); } }; const VirtQueue = struct { desc: [*]volatile VirtqDesc, avail: *volatile VirtqAvail, used: *volatile VirtqUsed, size: u16, first_unused: Descriptor, last_in_used: u16, // index into used.rings() num_unused: u16, pending: u16, // the size of a queue is guaranteed to be a power of two, so it's possible to save on a modulo // and instead get the mask to AND pub fn wrap(self: *@This(), val: u16) u16 { return val & (self.size - 1); } }; const CommonCfg = packed struct { device_feature_select: u32, device_feature: u32, guest_feature_select: u32, guest_feature: u32, msix_config: u16, num_queues: u16, device_status: u8, config_generation: u8, queue_select: u16, queue_size: u16, queue_msix_vector: u16, queue_enable: u16, queue_notify_off: u16, queue_desc: u64, queue_avail: u64, queue_used: u64, }; const VIRTIO_ACKNOWLEDGE: u8 = 1; const VIRTIO_DRIVER: u8 = 2; const VIRTIO_FAILED: u8 = 128; const VIRTIO_FEATURES_OK: u8 = 8; const VIRTIO_DRIVER_OK: u8 = 4; const VIRTIO_DEVICE_NEEDS_RESET: u8 = 64; // Capability config types const VIRTIO_PCI_CAP_COMMON_CFG = 1; const VIRTIO_PCI_CAP_NOTIFY_CFG = 2; const VIRTIO_PCI_CAP_ISR_CFG = 3; const VIRTIO_PCI_CAP_DEVICE_CFG = 4; const VIRTIO_PCI_CAP_PCI_CFG = 5; // PCI capability list record offsets const VIRTIO_PCI_CAP_LEN = 2; const VIRTIO_PCI_CAP_CFG_TYPE = 3; const VIRTIO_PCI_CAP_BAR = 4; const VIRTIO_PCI_CAP_OFFSET = 8; const VIRTIO_PCI_CAP_LENGTH = 12; const VIRTIO_PCI_NOTIFY_CAP_MULT = 16; // Feature bits const VIRTIO_F_VERSION_1 = 32; const VIRTIO_F_ACCESS_PLATFORM = 33; const VIRTIO_F_RING_PACKED = 34; const VIRTIO_F_ORDER_PLATFORM = 36; const VIRTIO_F_SR_IOV = 37;
src/drivers/virtio/virtio-pci.zig
const std = @import("std"); const print = std.debug.print; const List = std.ArrayList; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day09.txt"); const desc = std.sort.desc(usize); pub fn main() !void { var lines = try util.toStrSlice(data, "\n"); const rows = lines.len; const cols = lines[0].len; var basins = List(usize).init(gpa); var visited = try List(bool).initCapacity(gpa, rows * cols); try visited.appendNTimes(false, rows * cols); var sum: usize = 0; for (lines) |line, row| { for (line) |point, col| { var low = false; var val = point - '0'; if (row == 0) { // corners if (col == 0) { if (val < lines[row][col + 1] - '0' and val < lines[row + 1][col] - '0') { sum += val + 1; low = true; } } else if (col == cols - 1) { if (val < lines[row][col - 1] - '0' and val < lines[row + 1][col] - '0') { sum += val + 1; low = true; } } else { if (val < lines[row][col + 1] - '0' and val < lines[row][col - 1] - '0' and val < lines[row + 1][col] - '0') { sum += val + 1; low = true; } } } else if (row == rows - 1) { // corners if (col == 0) { if (val < lines[row][col + 1] - '0' and val < lines[row - 1][col] - '0') { sum += val + 1; low = true; } } else if (col == cols - 1) { if (val < lines[row][col - 1] - '0' and val < lines[row - 1][col] - '0') { sum += val + 1; low = true; } } else { if (val < lines[row][col + 1] - '0' and val < lines[row][col - 1] - '0' and val < lines[row - 1][col] - '0') { sum += val + 1; low = true; } } } else if (col == 0) { if (val < lines[row][col + 1] - '0' and val < lines[row - 1][col] - '0' and val < lines[row + 1][col] - '0') { sum += val + 1; low = true; } } else if (col == cols - 1) { if (val < lines[row][col - 1] - '0' and val < lines[row - 1][col] - '0' and val < lines[row + 1][col] - '0') { sum += val + 1; low = true; } } else { // inner if (val < lines[row - 1][col] - '0' and val < lines[row + 1][col] - '0' and val < lines[row][col - 1] - '0' and val < lines[row][col + 1] - '0') { sum += val + 1; low = true; } } if (low) { try basins.append(getBasinSize(lines, visited.items, row, col)); } } } std.sort.sort(usize, basins.items, {}, desc); print("{}\n", .{sum}); print("{}\n", .{basins.items[0] * basins.items[1] * basins.items[2]}); } fn getBasinSize(lines: [][]const u8, visited: []bool, row: usize, col: usize) usize { const rows = lines.len; const cols = lines[0].len; if (visited[row * cols + col]) return 0; if (lines[row][col] == '9') return 0; visited[row * cols + col] = true; var size: usize = 0; if (row > 0) size += getBasinSize(lines, visited, row - 1, col); if (col > 0) size += getBasinSize(lines, visited, row, col - 1); if (row < rows - 1) size += getBasinSize(lines, visited, row + 1, col); if (col < cols - 1) size += getBasinSize(lines, visited, row, col + 1); return size + 1; }
2021/src/day09.zig
const std = @import("std"); const os = std.os; const builtin = @import("builtin"); fn no_op_print(fmt: []const u8, args: var) void {} const print = if (builtin.is_test or builtin.mode != .Debug) no_op_print else std.debug.warn; const waitpid_file = @import("waitpid.zig"); const waitpid = waitpid_file.waitpid; const WIFSTOPPED = waitpid_file.WIFSTOPPED; const index = @import("index.zig"); const ptrace = index.ptrace; const c = index.c; const ProcState = enum { RUNNING, EXECUTING_CALL, }; const Tracee = struct { pid: os.pid_t, state: ProcState, }; pub const EventAction = enum { // Syscall was not made. CONT, // All child processes died. EXIT, // Syscall may be inspected and *should be resumed*. INSPECT, // Syscall has finished, results may be inspected. INSPECT_RESULT, // INSPECT_RESULT, except the syscall id is -1. Intended for use in nullifying syscalls. INSPECT_RESULT_UNKNOWN_SYSCALL, // Syscall started or ended normally. NORMAL, }; /// Used to encapsulate and share information to /// the caller of next_event. pub const Context = struct { pid: os.pid_t, registers: c.registers, }; pub const TraceeMap = std.AutoHashMap(os.pid_t, Tracee); pub const Inspections = struct { /// If inverse is true, any syscalls outside of .calls will be inspected /// Inverse turns .calls into a do-not-inspect list. inverse: bool = false, /// Syscalls to be inspected calls: []const os.SYS, }; pub fn next_event(pid: ?os.pid_t, tracee_map: *TraceeMap, ctx: *Context, inspections: Inspections) !EventAction { // This allows a caller to wait for the result of a syscall on a specific pid, // defaults to -1 (any pid available) const waiton: os.pid_t = if (pid) |p| p else -1; const wr = waitpid(waiton, 0) catch |err| { if (tracee_map.count() == 0) return EventAction.EXIT; return EventAction.CONT; }; return try handle_wait_result(wr, tracee_map, ctx, inspections); } pub fn handle_wait_result(wr: waitpid_file.WaitResult, tracee_map: *TraceeMap, ctx: *Context, inspections: Inspections) !EventAction { const tracee: *Tracee = try get_or_make_tracee(tracee_map, wr.pid); std.debug.assert(tracee.pid == wr.pid); ctx.pid = tracee.pid; switch (wr.status) { // Process exited normally .exit => |signal| { print("> {} exit signal: {}\n", .{ tracee.pid, signal }); return handle_dying_process(tracee, tracee_map); }, // Process was terminated by a signal .kill => |signal| { print("> {} kill signal: {}\n", .{ tracee.pid, signal }); return handle_dying_process(tracee, tracee_map); }, // Ptrace has stopped the process .ptrace => |signal| { switch (signal) { .syscall_trap => { // Continue through to the typical next step errdefer print("> [{}] error while handling syscall trap for syscall: {}\n", .{ tracee.pid, ctx.registers }); return try handle_event(tracee, tracee_map, ctx, inspections); }, // Is there any scenario where we receive this event and the tracee survives? Should we check for that? else => { // We have received a PTRACE event. // We want to continue the process as normal and ignore the event. print("> [{}] has received PTRACE signal {}\n", .{ tracee.pid, signal }); try ptrace.syscall(tracee.pid); return EventAction.CONT; }, } }, // Process was stopped by the delivery of a signal. .stop => |signal| { print("> [{}] has received linux signal: {}\n", .{ tracee.pid, @tagName(signal) }); switch (signal) { // These signals are associated with the death of the tracee process. .quit, .segv => { print("> {} quitting because of signal: {}\n", .{ tracee.pid, signal }); // Is this neccessary to be called? try ptrace.syscall(tracee.pid); return handle_dying_process(tracee, tracee_map); }, // The remaining signals should be effectively ignored. else => { try ptrace.syscall(tracee.pid); return EventAction.CONT; }, } }, } } fn handle_dying_process(tracee: *Tracee, tracee_map: *TraceeMap) EventAction { _ = tracee_map.remove(tracee.pid); return if (tracee_map.count() == 0) .EXIT else .CONT; } pub fn handle_event(tracee: *Tracee, tracee_map: *TraceeMap, ctx: *Context, inspections: Inspections) !EventAction { switch (tracee.state) { .RUNNING => { // Collect syscall arguments. ctx.registers = try ptrace.getregs(tracee.pid); if (in(ctx.registers.syscall, inspections.calls) != inspections.inverse) { return EventAction.INSPECT; } try begin_syscall(tracee); }, .EXECUTING_CALL => { // Collect syscall result. ctx.registers = try ptrace.getregs(tracee.pid); // Allows inspecting syscall results without resorting to blocking. const sc = ctx.registers.syscall; // TODO Replace usize and isize with proper Type if (sc == @bitCast(c.regT, @as(c.sregT, -1))) { return EventAction.INSPECT_RESULT_UNKNOWN_SYSCALL; } if (in(sc, inspections.calls) != inspections.inverse) { return EventAction.INSPECT_RESULT; } try end_syscall(tracee); }, } return EventAction.NORMAL; } fn in(needle: var, haystack: []const os.SYS) bool { for (haystack) |hay| { if (needle == @enumToInt(hay)) return true; } return false; } // TODO replace this with @suspend and resume in handle_event and caller code respectively /// Must be called after next_event returns INSPECT or INSPECT_RESULT /// Resumes tracee before or after the system call, as would normally happen in handle_event() with non-inspected calls. pub fn resume_from_inspection(tracee_map: *TraceeMap, pid: os.pid_t) !void { const tracee: *Tracee = try get_or_make_tracee(tracee_map, pid); switch (tracee.state) { .RUNNING => try begin_syscall(tracee), .EXECUTING_CALL => try end_syscall(tracee), } } /// Tracee has stopped execution right before /// executing a syscall. fn begin_syscall(tracee: *Tracee) !void { // Tracee will now conduct the syscall try ptrace.syscall(tracee.pid); tracee.state = .EXECUTING_CALL; } /// Tracee has finished its syscall fn end_syscall(tracee: *Tracee) !void { // Resume tracee try ptrace.syscall(tracee.pid); tracee.state = .RUNNING; } pub fn get_or_make_tracee(tracee_map: *TraceeMap, pid: os.pid_t) !*Tracee { if (tracee_map.get(pid)) |kv| { return &kv.value; } else { const tracee = Tracee{ .pid = pid, .state = .RUNNING }; _ = try tracee_map.put(pid, tracee); if (tracee_map.get(pid)) |kv| { return &kv.value; } else @panic("Very unexpected event. Could not get value we just placed in a hashmap"); } @panic("Very unexpected event. This should never happen"); }
src/events.zig
const main = @import("main.zig"); const vectors = @import("vectors.zig"); pub export fn _start() callconv(.Naked) noreturn { // At startup the stack pointer is at the end of RAM // so, no need to set it manually! // Reference this such that the file is analyzed and the vectors // are added. _ = vectors; copy_data_to_ram(); clear_bss(); { const MCUCR = @import("mmio.zig").MMIO(0x55, u8, u8); MCUCR.write(MCUCR.read() & ~@as(u8, 1 << 4)); //disable PUD, for pullup resistors } main.main(); while (true) {} } fn copy_data_to_ram() void { asm volatile ( \\ ; load Z register with the address of the data in flash \\ ldi r30, lo8(__data_load_start) \\ ldi r31, hi8(__data_load_start) \\ ; load X register with address of the data in ram \\ ldi r26, lo8(__data_start) \\ ldi r27, hi8(__data_start) \\ ; load address of end of the data in ram \\ ldi r24, lo8(__data_end) \\ ldi r25, hi8(__data_end) \\ rjmp .L2 \\ \\.L1: \\ lpm r18, Z+ ; copy from Z into r18 and increment Z \\ st X+, r18 ; store r18 at location X and increment X \\ \\.L2: \\ cp r26, r24 \\ cpc r27, r25 ; check and branch if we are at the end of data \\ brne .L1 ); // Probably a good idea to add clobbers here, but compiler doesn't seem to care } fn clear_bss() void { asm volatile ( \\ ; load X register with the beginning of bss section \\ ldi r26, lo8(__bss_start) \\ ldi r27, hi8(__bss_start) \\ ; load end of the bss in registers \\ ldi r24, lo8(__bss_end) \\ ldi r25, hi8(__bss_end) \\ ldi r18, 0x00 \\ rjmp .L4 \\ \\.L3: \\ st X+, r18 \\ \\.L4: \\ cp r26, r24 \\ cpc r27, r25 ; check and branch if we are at the end of bss \\ brne .L3 ); // Probably a good idea to add clobbers here, but compiler doesn't seem to care } pub fn panic(msg: []const u8, error_return_trace: ?*@import("builtin").StackTrace) noreturn { @import("liquid_crystal.zig").writePanic(msg); const gpio = @import("gpio.zig"); gpio.pinMode(13, .output); while (true) { delayMilliseconds(50); gpio.digitalWrite(13, .high); delayMilliseconds(100); gpio.digitalWrite(13, .low); } } fn delayMilliseconds(comptime ms: comptime_int) void { delayCycles(ms * 1600); } fn delayCycles(comptime cycles: comptime_int) void { var count: u32 = 0; while (count < cycles) : (count += 1) { asm volatile ("nop"); } }
src/start.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const net = std.net; const time = std.time; const testing = std.testing; const print = std.debug.print; pub const Socket = struct { fd: os.socket_t, pub fn init(domain: u32, socket_type: u32, protocol: u32) !Socket { return Socket{ .fd = try os.socket(domain, socket_type, protocol) }; } pub fn deinit(self: Socket) void { os.close(self.fd); } pub fn shutdown(self: Socket, how: os.ShutdownHow) !void { try os.shutdown(self.fd, how); } pub fn bind(self: Socket, address: net.Address) !void { try os.bind(self.fd, &address.any, address.getOsSockLen()); } pub fn listen(self: Socket, max_backlog_size: usize) !void { try os.listen(self.fd, @truncate(u31, max_backlog_size)); } pub fn setReuseAddress(self: Socket, enabled: bool) !void { if (@hasDecl(os, "SO_REUSEADDR")) { try os.setsockopt(self.fd, os.SOL_SOCKET, os.SO_REUSEADDR, mem.asBytes(&@as(usize, @boolToInt(enabled)))); } } pub fn setReusePort(self: Socket, enabled: bool) !void { if (@hasDecl(os, "SO_REUSEPORT")) { try os.setsockopt(self.fd, os.SOL_SOCKET, os.SO_REUSEPORT, mem.asBytes(&@as(usize, @boolToInt(enabled)))); } } pub fn setNoDelay(self: Socket, enabled: bool) !void { if (@hasDecl(os, "TCP_NODELAY")) { try os.setsockopt(self.fd, os.IPPROTO_TCP, os.TCP_NODELAY, mem.asBytes(&@as(usize, @boolToInt(enabled)))); } } pub fn setFastOpen(self: Socket, enabled: bool) !void { if (@hasDecl(os, "TCP_FASTOPEN")) { try os.setsockopt(self.fd, os.IPPROTO_TCP, os.TCP_FASTOPEN, mem.asBytes(&@as(usize, @boolToInt(enabled)))); } } pub fn setQuickAck(self: Socket, enabled: bool) !void { if (@hasDecl(os, "TCP_QUICKACK")) { try os.setsockopt(self.fd, os.IPPROTO_TCP, os.TCP_QUICKACK, mem.asBytes(&@as(usize, @boolToInt(enabled)))); } } pub fn getName(self: Socket) !net.Address { var binded_address: os.sockaddr = undefined; var binded_address_len: u32 = @sizeOf(os.sockaddr); try os.getsockname(self.fd, &binded_address, &binded_address_len); return net.Address.initPosix(@alignCast(4, &binded_address)); } pub fn connect(self: Socket, address: net.Address) !void { try os.connect(self.fd, &address.any, address.getOsSockLen()); } pub fn getError(self: Socket) !void { try os.getsockoptError(self.fd); } pub fn getReadBufferSize(self: Socket) !u32 { var value: u32 = undefined; var value_len: u32 = @sizeOf(u32); const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVBUF, mem.asBytes(&value), &value_len); return switch (os.errno(rc)) { 0 => value, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub fn getWriteBufferSize(self: Socket) !u32 { var value: u32 = undefined; var value_len: u32 = @sizeOf(u32); const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDBUF, mem.asBytes(&value), &value_len); return switch (os.errno(rc)) { 0 => value, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub fn setReadBufferSize(self: Socket, size: u32) !void { const rc = os.system.setsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVBUF, mem.asBytes(&size), @sizeOf(u32)); return switch (os.errno(rc)) { 0 => {}, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub fn setWriteBufferSize(self: Socket, size: u32) !void { const rc = os.system.setsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDBUF, mem.asBytes(&size), @sizeOf(u32)); return switch (os.errno(rc)) { 0 => {}, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub fn setReadTimeout(self: Socket, milliseconds: usize) !void { const timeout = os.timeval{ .tv_sec = @intCast(isize, milliseconds / time.ms_per_s), .tv_usec = @intCast(isize, (milliseconds % time.ms_per_s) * time.us_per_ms), }; const rc = os.system.setsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVTIMEO, mem.asBytes(&timeout), @sizeOf(os.timeval)); return switch (os.errno(rc)) { 0 => {}, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub fn setWriteTimeout(self: Socket, milliseconds: usize) !void { const timeout = os.timeval{ .tv_sec = @intCast(isize, milliseconds / time.ms_per_s), .tv_usec = @intCast(isize, (milliseconds % time.ms_per_s) * time.us_per_ms), }; const rc = os.system.setsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDTIMEO, mem.asBytes(&timeout), @sizeOf(os.timeval)); return switch (os.errno(rc)) { 0 => {}, os.EBADF => error.BadFileDescriptor, os.EFAULT => error.InvalidAddressSpace, os.EINVAL => error.InvalidSocketOption, os.ENOPROTOOPT => error.UnknownSocketOption, os.ENOTSOCK => error.NotASocket, else => |err| os.unexpectedErrno(err), }; } pub const Connection = struct { socket: Socket, address: net.Address, }; pub fn accept(self: Socket, flags: u32) !Connection { var address: os.sockaddr = undefined; var address_len: u32 = @sizeOf(os.sockaddr); const fd = try os.accept(self.fd, &address, &address_len, flags); return Connection{ .socket = Socket{ .fd = fd }, .address = net.Address.initPosix(@alignCast(4, &address)), }; } pub fn read(self: Socket, buf: []u8) !usize { return try os.read(self.fd, buf); } pub fn recv(self: Socket, buf: []u8, flags: u32) !usize { return try os.recv(self.fd, buf, flags); } pub fn write(self: Socket, buf: []const u8) !usize { return try os.write(self.fd, buf); } pub fn send(self: Socket, buf: []const u8, flags: u32) !usize { return try os.send(self.fd, buf, flags); } }; test { testing.refAllDecls(Socket); } test "socket/linux: set write timeout" { const a = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer a.deinit(); try a.bind(net.Address.initIp4([_]u8{ 0, 0, 0, 0 }, 0)); try a.listen(128); const binded_address = try a.getName(); print("Binded to address: {}\n", .{binded_address}); const b = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer b.deinit(); try b.connect(binded_address); const ab = try a.accept(os.SOCK_CLOEXEC); defer ab.socket.deinit(); // The minimum read buffer size is 128. // The minimum write buffer size is 1024. // All buffer sizes are doubled when they are passed in. // After taking into account book-keeping for buffer sizes, the minimum // buffer size before writes start to block the main thread is 65,483 bytes. var buf: [65_483]u8 = undefined; try ab.socket.setReadBufferSize(128); try b.setWriteBufferSize(1024); try b.setWriteTimeout(10); testing.expectEqual(buf.len - 1, try b.write(&buf)); } test "socket/linux: set read timeout" { const a = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer a.deinit(); try a.bind(net.Address.initIp4([_]u8{ 0, 0, 0, 0 }, 0)); try a.listen(128); const binded_address = try a.getName(); print("Binded to address: {}\n", .{binded_address}); const b = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer b.deinit(); try b.connect(binded_address); try b.setReadTimeout(10); const ab = try a.accept(os.SOCK_CLOEXEC); defer ab.socket.deinit(); var buf: [1]u8 = undefined; testing.expectError(error.WouldBlock, b.read(&buf)); } test "socket/linux: create socket pair" { const a = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_NONBLOCK | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer a.deinit(); try a.bind(net.Address.initIp4([_]u8{ 0, 0, 0, 0 }, 0)); try a.listen(128); const binded_address = try a.getName(); print("Binded to address: {}\n", .{binded_address}); const b = try Socket.init(os.AF_INET, os.SOCK_STREAM | os.SOCK_NONBLOCK | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer b.deinit(); testing.expectError(error.WouldBlock, b.connect(binded_address)); try b.getError(); const ab = try a.accept(os.SOCK_NONBLOCK | os.SOCK_CLOEXEC); defer ab.socket.deinit(); } test "raw_socket/linux: create socket pair" { const empty_ip4_address = os.sockaddr_in{ .port = 0, .addr = 0 }; const a = try os.socket(os.AF_INET, os.SOCK_STREAM | os.SOCK_NONBLOCK | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer os.close(a); try os.bind(a, @ptrCast(*const os.sockaddr, &empty_ip4_address), @sizeOf(os.sockaddr_in)); try os.listen(a, 128); var binded_address: os.sockaddr = undefined; var binded_address_len: u32 = @sizeOf(os.sockaddr); try os.getsockname(a, &binded_address, &binded_address_len); switch (binded_address.family) { os.AF_INET => print("Binded to IPv4 address: {}", .{@ptrCast(*align(1) os.sockaddr_in, &binded_address)}), os.AF_INET6 => print("Binded to IPv6 address: {}", .{@ptrCast(*align(1) os.sockaddr_in6, &binded_address)}), else => return error.UnexpectedAddressFamily, } const b = try os.socket(os.AF_INET, os.SOCK_STREAM | os.SOCK_NONBLOCK | os.SOCK_CLOEXEC, os.IPPROTO_TCP); defer os.close(b); testing.expectError(error.WouldBlock, os.connect(b, &binded_address, binded_address_len)); try os.getsockoptError(b); }
socket.zig
// SPDX-License-Identifier: MIT // This file is part of the Termelot project under the MIT license. const std = @import("std"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const Pkg = std.build.Pkg; const fs = std.fs; const BackendName = @import("src/backend.zig").BackendName; const backends = @typeInfo(BackendName).Enum.fields; // pub fn targetRequiresLibC(target: std.zig.CrossTarget) bool { // switch (target.getOsTag()) { // .linux => switch (target.getCpuArch()) { // .x86_64 => return false, // .aarch64 => return false, // .mipsel => return false, // else => return true, // }, // else => return true, // } // } pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const output_path = fs.path.join(b.allocator, &[_][]const u8{ b.build_root, "build", }) catch unreachable; // TODO: Wrap library with public C interface const lib = b.addStaticLibrary("termelot", "src/termelot.zig"); lib.setBuildMode(mode); lib.setTarget(target); lib.setOutputDir(output_path); lib.emit_h = true; const backend = try getBackend(b); const backend_path = backendNameToPath(backend); std.log.info("Selected {s} for backend at {s}.", .{ @tagName(backend), backend_path }); // NOTE: make Pkg of backend and use it EVERYWHERE const backend_pkg = backendAsPkg(backend); lib.addPackage(backend_pkg); try applyBuildOptions(lib, backend); b.default_step.dependOn(&lib.step); const lib_tests = b.addTest("src/termelot.zig"); lib_tests.setBuildMode(mode); // lib_tests.linkLibrary(lib); lib_tests.addPackage(backend_pkg); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&lib_tests.step); // Examples const lib_pkg = Pkg{ .name = "termelot", .path = .{ .path = "src/termelot.zig" }, .dependencies = &[1]Pkg{backend_pkg}, }; addExample(b, lib_pkg, "init", "examples/init.zig", target, mode); addExample(b, lib_pkg, "donut", "examples/donut.zig", target, mode); addExample(b, lib_pkg, "castle", "examples/castle.zig", target, mode); addExample(b, lib_pkg, "ziro", "examples/ziro.zig", target, mode); } pub fn backendAsPkg(backend: BackendName) Pkg { return std.build.Pkg{ .name = "backend", .path = .{ .path = backendNameToPath(backend) }, .dependencies = null, }; } pub fn backendNameToPath(backend: BackendName) []const u8 { return switch (backend) { .termios => "src/backend/termios.zig", .windows => "src/backend/windows.zig", .ncurses => "src/backend/ncurses.zig", .unimplemented => "src/backend/unimplemented.zig", }; } /// Combines target info and build options to determine the name of the backend to be compiled /// into the library. pub fn getBackend(b: *Builder) !BackendName { if (b.option([]const u8, "backend", "Override included backend")) |val| { inline for (backends) |backend| { if (std.mem.eql(u8, backend.name, val)) { return @intToEnum(BackendName, backend.value); } } std.log.crit("'{s}' is not a backend choice. Possible backends include:", .{val}); inline for (backends) |backend| { std.log.crit("{s}", .{backend.name}); return error.NoBackend; } } else { // Automatic backend selector return switch (std.builtin.os.tag) { .linux, .macos, .dragonfly, .freebsd, .openbsd => .termios, .windows => .windows, else => .unimplemented, }; } } /// For a given backend, apply all build options and functions required. pub fn applyBuildOptions(lib: *LibExeObjStep, backend: BackendName) !void { switch (backend) { .termios => lib.linkLibC(), .windows => lib.linkLibC(), .ncurses => { lib.linkLibC(); lib.linkSystemLibrary("ncurses"); // TODO: some systems name this library "curses" or "ncursesw" }, else => {}, } } /// Add an example to the list of build options. fn addExample(b: *Builder, lib_pkg: Pkg, comptime name: []const u8, root_src: []const u8, target: std.zig.CrossTarget, mode: std.builtin.Mode) void { const examples_output_path = fs.path.join(b.allocator, &[_][]const u8{ b.build_root, "build", "examples", }) catch unreachable; const exe = b.addExecutable(name, root_src); exe.setTarget(target); exe.setBuildMode(mode); exe.setOutputDir(examples_output_path); // Resolve imports for "termelot" and "backend" exe.addPackage(lib_pkg); const run_cmd = exe.run(); const run_step = b.step(name, "Run the '" ++ name ++ "' example"); run_step.dependOn(&run_cmd.step); }
build.zig
const std = @import("std"); const fs = std.fs; const os = std.os; const Connector = @import("connector.zig").Connector; const WireBuffer = @import("wire.zig").WireBuffer; const Table = @import("table.zig").Table; pub const FRAME_METHOD = 1; pub const FRAME_HEADER = 2; pub const FRAME_BODY = 3; pub const FRAME_HEARTBEAT = 8; pub const FRAME_MIN_SIZE = 4096; pub const FRAME_END = 206; pub const REPLY_SUCCESS = 200; pub const CONTENT_TOO_LARGE = 311; pub const NO_CONSUMERS = 313; pub const CONNECTION_FORCED = 320; pub const INVALID_PATH = 402; pub const ACCESS_REFUSED = 403; pub const NOT_FOUND = 404; pub const RESOURCE_LOCKED = 405; pub const PRECONDITION_FAILED = 406; pub const FRAME_ERROR = 501; pub const SYNTAX_ERROR = 502; pub const COMMAND_INVALID = 503; pub const CHANNEL_ERROR = 504; pub const UNEXPECTED_FRAME = 505; pub const RESOURCE_ERROR = 506; pub const NOT_ALLOWED = 530; pub const NOT_IMPLEMENTED = 540; pub const INTERNAL_ERROR = 541; // connection pub const Connection = struct { pub const CONNECTION_CLASS = 10; // start pub const Start = struct { pub const CLASS = 10; pub const METHOD = 10; version_major: u8, version_minor: u8, server_properties: Table, mechanisms: []const u8, locales: []const u8, pub fn read(conn: *Connector) !Start { const version_major = conn.rx_buffer.readU8(); const version_minor = conn.rx_buffer.readU8(); var server_properties = conn.rx_buffer.readTable(); const mechanisms = conn.rx_buffer.readLongString(); const locales = conn.rx_buffer.readLongString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Start", .{conn.channel}); return Start{ .version_major = version_major, .version_minor = version_minor, .server_properties = server_properties, .mechanisms = mechanisms, .locales = locales, }; } }; pub const START_METHOD = 10; pub fn startSync( conn: *Connector, version_major: u8, version_minor: u8, server_properties: ?*Table, mechanisms: []const u8, locales: []const u8, ) !StartOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, START_METHOD); conn.tx_buffer.writeU8(version_major); conn.tx_buffer.writeU8(version_minor); conn.tx_buffer.writeTable(server_properties); conn.tx_buffer.writeLongString(mechanisms); conn.tx_buffer.writeLongString(locales); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Start ->", .{conn.channel}); return awaitStartOk(conn); } // start pub fn awaitStart(conn: *Connector) !Start { return conn.awaitMethod(Start); } // start-ok pub const StartOk = struct { pub const CLASS = 10; pub const METHOD = 11; client_properties: Table, mechanism: []const u8, response: []const u8, locale: []const u8, pub fn read(conn: *Connector) !StartOk { var client_properties = conn.rx_buffer.readTable(); const mechanism = conn.rx_buffer.readShortString(); const response = conn.rx_buffer.readLongString(); const locale = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Start_ok", .{conn.channel}); return StartOk{ .client_properties = client_properties, .mechanism = mechanism, .response = response, .locale = locale, }; } }; pub const START_OK_METHOD = 11; pub fn startOkAsync( conn: *Connector, client_properties: ?*Table, mechanism: []const u8, response: []const u8, locale: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.START_OK_METHOD); conn.tx_buffer.writeTable(client_properties); conn.tx_buffer.writeShortString(mechanism); conn.tx_buffer.writeLongString(response); conn.tx_buffer.writeShortString(locale); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Start_ok ->", .{conn.channel}); } // start_ok pub fn awaitStartOk(conn: *Connector) !StartOk { return conn.awaitMethod(StartOk); } // secure pub const Secure = struct { pub const CLASS = 10; pub const METHOD = 20; challenge: []const u8, pub fn read(conn: *Connector) !Secure { const challenge = conn.rx_buffer.readLongString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Secure", .{conn.channel}); return Secure{ .challenge = challenge, }; } }; pub const SECURE_METHOD = 20; pub fn secureSync( conn: *Connector, challenge: []const u8, ) !SecureOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, SECURE_METHOD); conn.tx_buffer.writeLongString(challenge); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Secure ->", .{conn.channel}); return awaitSecureOk(conn); } // secure pub fn awaitSecure(conn: *Connector) !Secure { return conn.awaitMethod(Secure); } // secure-ok pub const SecureOk = struct { pub const CLASS = 10; pub const METHOD = 21; response: []const u8, pub fn read(conn: *Connector) !SecureOk { const response = conn.rx_buffer.readLongString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Secure_ok", .{conn.channel}); return SecureOk{ .response = response, }; } }; pub const SECURE_OK_METHOD = 21; pub fn secureOkAsync( conn: *Connector, response: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.SECURE_OK_METHOD); conn.tx_buffer.writeLongString(response); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Secure_ok ->", .{conn.channel}); } // secure_ok pub fn awaitSecureOk(conn: *Connector) !SecureOk { return conn.awaitMethod(SecureOk); } // tune pub const Tune = struct { pub const CLASS = 10; pub const METHOD = 30; channel_max: u16, frame_max: u32, heartbeat: u16, pub fn read(conn: *Connector) !Tune { const channel_max = conn.rx_buffer.readU16(); const frame_max = conn.rx_buffer.readU32(); const heartbeat = conn.rx_buffer.readU16(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Tune", .{conn.channel}); return Tune{ .channel_max = channel_max, .frame_max = frame_max, .heartbeat = heartbeat, }; } }; pub const TUNE_METHOD = 30; pub fn tuneSync( conn: *Connector, channel_max: u16, frame_max: u32, heartbeat: u16, ) !TuneOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, TUNE_METHOD); conn.tx_buffer.writeU16(channel_max); conn.tx_buffer.writeU32(frame_max); conn.tx_buffer.writeU16(heartbeat); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Tune ->", .{conn.channel}); return awaitTuneOk(conn); } // tune pub fn awaitTune(conn: *Connector) !Tune { return conn.awaitMethod(Tune); } // tune-ok pub const TuneOk = struct { pub const CLASS = 10; pub const METHOD = 31; channel_max: u16, frame_max: u32, heartbeat: u16, pub fn read(conn: *Connector) !TuneOk { const channel_max = conn.rx_buffer.readU16(); const frame_max = conn.rx_buffer.readU32(); const heartbeat = conn.rx_buffer.readU16(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Tune_ok", .{conn.channel}); return TuneOk{ .channel_max = channel_max, .frame_max = frame_max, .heartbeat = heartbeat, }; } }; pub const TUNE_OK_METHOD = 31; pub fn tuneOkAsync( conn: *Connector, channel_max: u16, frame_max: u32, heartbeat: u16, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.TUNE_OK_METHOD); conn.tx_buffer.writeU16(channel_max); conn.tx_buffer.writeU32(frame_max); conn.tx_buffer.writeU16(heartbeat); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Tune_ok ->", .{conn.channel}); } // tune_ok pub fn awaitTuneOk(conn: *Connector) !TuneOk { return conn.awaitMethod(TuneOk); } // open pub const Open = struct { pub const CLASS = 10; pub const METHOD = 40; virtual_host: []const u8, reserved_1: []const u8, reserved_2: bool, pub fn read(conn: *Connector) !Open { const virtual_host = conn.rx_buffer.readShortString(); const reserved_1 = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const reserved_2 = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Open", .{conn.channel}); return Open{ .virtual_host = virtual_host, .reserved_1 = reserved_1, .reserved_2 = reserved_2, }; } }; pub const OPEN_METHOD = 40; pub fn openSync( conn: *Connector, virtual_host: []const u8, ) !OpenOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, OPEN_METHOD); conn.tx_buffer.writeShortString(virtual_host); const reserved_1 = ""; conn.tx_buffer.writeShortString(reserved_1); const reserved_2 = false; var bitset0: u8 = 0; const _bit: u8 = 1; if (reserved_2) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Open ->", .{conn.channel}); return awaitOpenOk(conn); } // open pub fn awaitOpen(conn: *Connector) !Open { return conn.awaitMethod(Open); } // open-ok pub const OpenOk = struct { pub const CLASS = 10; pub const METHOD = 41; reserved_1: []const u8, pub fn read(conn: *Connector) !OpenOk { const reserved_1 = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Open_ok", .{conn.channel}); return OpenOk{ .reserved_1 = reserved_1, }; } }; pub const OPEN_OK_METHOD = 41; pub fn openOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.OPEN_OK_METHOD); const reserved_1 = ""; conn.tx_buffer.writeShortString(reserved_1); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Open_ok ->", .{conn.channel}); } // open_ok pub fn awaitOpenOk(conn: *Connector) !OpenOk { return conn.awaitMethod(OpenOk); } // close pub const Close = struct { pub const CLASS = 10; pub const METHOD = 50; reply_code: u16, reply_text: []const u8, class_id: u16, method_id: u16, pub fn read(conn: *Connector) !Close { const reply_code = conn.rx_buffer.readU16(); const reply_text = conn.rx_buffer.readShortString(); const class_id = conn.rx_buffer.readU16(); const method_id = conn.rx_buffer.readU16(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Close", .{conn.channel}); return Close{ .reply_code = reply_code, .reply_text = reply_text, .class_id = class_id, .method_id = method_id, }; } }; pub const CLOSE_METHOD = 50; pub fn closeSync( conn: *Connector, reply_code: u16, reply_text: []const u8, class_id: u16, method_id: u16, ) !CloseOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, CLOSE_METHOD); conn.tx_buffer.writeU16(reply_code); conn.tx_buffer.writeShortString(reply_text); conn.tx_buffer.writeU16(class_id); conn.tx_buffer.writeU16(method_id); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Close ->", .{conn.channel}); return awaitCloseOk(conn); } // close pub fn awaitClose(conn: *Connector) !Close { return conn.awaitMethod(Close); } // close-ok pub const CloseOk = struct { pub const CLASS = 10; pub const METHOD = 51; pub fn read(conn: *Connector) !CloseOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Close_ok", .{conn.channel}); return CloseOk{}; } }; pub const CLOSE_OK_METHOD = 51; pub fn closeOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.CLOSE_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Close_ok ->", .{conn.channel}); } // close_ok pub fn awaitCloseOk(conn: *Connector) !CloseOk { return conn.awaitMethod(CloseOk); } // blocked pub const Blocked = struct { pub const CLASS = 10; pub const METHOD = 60; reason: []const u8, pub fn read(conn: *Connector) !Blocked { const reason = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Blocked", .{conn.channel}); return Blocked{ .reason = reason, }; } }; pub const BLOCKED_METHOD = 60; pub fn blockedAsync( conn: *Connector, reason: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.BLOCKED_METHOD); conn.tx_buffer.writeShortString(reason); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Blocked ->", .{conn.channel}); } // blocked pub fn awaitBlocked(conn: *Connector) !Blocked { return conn.awaitMethod(Blocked); } // unblocked pub const Unblocked = struct { pub const CLASS = 10; pub const METHOD = 61; pub fn read(conn: *Connector) !Unblocked { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Connection@{}.Unblocked", .{conn.channel}); return Unblocked{}; } }; pub const UNBLOCKED_METHOD = 61; pub fn unblockedAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CONNECTION_CLASS, Connection.UNBLOCKED_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Connection@{}.Unblocked ->", .{conn.channel}); } // unblocked pub fn awaitUnblocked(conn: *Connector) !Unblocked { return conn.awaitMethod(Unblocked); } }; // channel pub const Channel = struct { pub const CHANNEL_CLASS = 20; // open pub const Open = struct { pub const CLASS = 20; pub const METHOD = 10; reserved_1: []const u8, pub fn read(conn: *Connector) !Open { const reserved_1 = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Open", .{conn.channel}); return Open{ .reserved_1 = reserved_1, }; } }; pub const OPEN_METHOD = 10; pub fn openSync( conn: *Connector, ) !OpenOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, OPEN_METHOD); const reserved_1 = ""; conn.tx_buffer.writeShortString(reserved_1); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Open ->", .{conn.channel}); return awaitOpenOk(conn); } // open pub fn awaitOpen(conn: *Connector) !Open { return conn.awaitMethod(Open); } // open-ok pub const OpenOk = struct { pub const CLASS = 20; pub const METHOD = 11; reserved_1: []const u8, pub fn read(conn: *Connector) !OpenOk { const reserved_1 = conn.rx_buffer.readLongString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Open_ok", .{conn.channel}); return OpenOk{ .reserved_1 = reserved_1, }; } }; pub const OPEN_OK_METHOD = 11; pub fn openOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, Channel.OPEN_OK_METHOD); const reserved_1 = ""; conn.tx_buffer.writeLongString(reserved_1); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Open_ok ->", .{conn.channel}); } // open_ok pub fn awaitOpenOk(conn: *Connector) !OpenOk { return conn.awaitMethod(OpenOk); } // flow pub const Flow = struct { pub const CLASS = 20; pub const METHOD = 20; active: bool, pub fn read(conn: *Connector) !Flow { const bitset0 = conn.rx_buffer.readU8(); const active = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Flow", .{conn.channel}); return Flow{ .active = active, }; } }; pub const FLOW_METHOD = 20; pub fn flowSync( conn: *Connector, active: bool, ) !FlowOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, FLOW_METHOD); var bitset0: u8 = 0; const _bit: u8 = 1; if (active) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Flow ->", .{conn.channel}); return awaitFlowOk(conn); } // flow pub fn awaitFlow(conn: *Connector) !Flow { return conn.awaitMethod(Flow); } // flow-ok pub const FlowOk = struct { pub const CLASS = 20; pub const METHOD = 21; active: bool, pub fn read(conn: *Connector) !FlowOk { const bitset0 = conn.rx_buffer.readU8(); const active = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Flow_ok", .{conn.channel}); return FlowOk{ .active = active, }; } }; pub const FLOW_OK_METHOD = 21; pub fn flowOkAsync( conn: *Connector, active: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, Channel.FLOW_OK_METHOD); var bitset0: u8 = 0; const _bit: u8 = 1; if (active) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Flow_ok ->", .{conn.channel}); } // flow_ok pub fn awaitFlowOk(conn: *Connector) !FlowOk { return conn.awaitMethod(FlowOk); } // close pub const Close = struct { pub const CLASS = 20; pub const METHOD = 40; reply_code: u16, reply_text: []const u8, class_id: u16, method_id: u16, pub fn read(conn: *Connector) !Close { const reply_code = conn.rx_buffer.readU16(); const reply_text = conn.rx_buffer.readShortString(); const class_id = conn.rx_buffer.readU16(); const method_id = conn.rx_buffer.readU16(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Close", .{conn.channel}); return Close{ .reply_code = reply_code, .reply_text = reply_text, .class_id = class_id, .method_id = method_id, }; } }; pub const CLOSE_METHOD = 40; pub fn closeSync( conn: *Connector, reply_code: u16, reply_text: []const u8, class_id: u16, method_id: u16, ) !CloseOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, CLOSE_METHOD); conn.tx_buffer.writeU16(reply_code); conn.tx_buffer.writeShortString(reply_text); conn.tx_buffer.writeU16(class_id); conn.tx_buffer.writeU16(method_id); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Close ->", .{conn.channel}); return awaitCloseOk(conn); } // close pub fn awaitClose(conn: *Connector) !Close { return conn.awaitMethod(Close); } // close-ok pub const CloseOk = struct { pub const CLASS = 20; pub const METHOD = 41; pub fn read(conn: *Connector) !CloseOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Channel@{}.Close_ok", .{conn.channel}); return CloseOk{}; } }; pub const CLOSE_OK_METHOD = 41; pub fn closeOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(CHANNEL_CLASS, Channel.CLOSE_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Channel@{}.Close_ok ->", .{conn.channel}); } // close_ok pub fn awaitCloseOk(conn: *Connector) !CloseOk { return conn.awaitMethod(CloseOk); } }; // exchange pub const Exchange = struct { pub const EXCHANGE_CLASS = 40; // declare pub const Declare = struct { pub const CLASS = 40; pub const METHOD = 10; reserved_1: u16, exchange: []const u8, tipe: []const u8, passive: bool, durable: bool, reserved_2: bool, reserved_3: bool, no_wait: bool, arguments: Table, pub fn read(conn: *Connector) !Declare { const reserved_1 = conn.rx_buffer.readU16(); const exchange = conn.rx_buffer.readShortString(); const tipe = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const passive = if (bitset0 & (1 << 0) == 0) true else false; const durable = if (bitset0 & (1 << 1) == 0) true else false; const reserved_2 = if (bitset0 & (1 << 2) == 0) true else false; const reserved_3 = if (bitset0 & (1 << 3) == 0) true else false; const no_wait = if (bitset0 & (1 << 4) == 0) true else false; var arguments = conn.rx_buffer.readTable(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Exchange@{}.Declare", .{conn.channel}); return Declare{ .reserved_1 = reserved_1, .exchange = exchange, .tipe = tipe, .passive = passive, .durable = durable, .reserved_2 = reserved_2, .reserved_3 = reserved_3, .no_wait = no_wait, .arguments = arguments, }; } }; pub const DECLARE_METHOD = 10; pub fn declareSync( conn: *Connector, exchange: []const u8, tipe: []const u8, passive: bool, durable: bool, no_wait: bool, arguments: ?*Table, ) !DeclareOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(EXCHANGE_CLASS, DECLARE_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(tipe); var bitset0: u8 = 0; const _bit: u8 = 1; if (passive) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (durable) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); const reserved_2 = false; if (reserved_2) bitset0 |= (_bit << 2) else bitset0 &= ~(_bit << 2); const reserved_3 = false; if (reserved_3) bitset0 |= (_bit << 3) else bitset0 &= ~(_bit << 3); if (no_wait) bitset0 |= (_bit << 4) else bitset0 &= ~(_bit << 4); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeTable(arguments); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Exchange@{}.Declare ->", .{conn.channel}); return awaitDeclareOk(conn); } // declare pub fn awaitDeclare(conn: *Connector) !Declare { return conn.awaitMethod(Declare); } // declare-ok pub const DeclareOk = struct { pub const CLASS = 40; pub const METHOD = 11; pub fn read(conn: *Connector) !DeclareOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Exchange@{}.Declare_ok", .{conn.channel}); return DeclareOk{}; } }; pub const DECLARE_OK_METHOD = 11; pub fn declareOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(EXCHANGE_CLASS, Exchange.DECLARE_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Exchange@{}.Declare_ok ->", .{conn.channel}); } // declare_ok pub fn awaitDeclareOk(conn: *Connector) !DeclareOk { return conn.awaitMethod(DeclareOk); } // delete pub const Delete = struct { pub const CLASS = 40; pub const METHOD = 20; reserved_1: u16, exchange: []const u8, if_unused: bool, no_wait: bool, pub fn read(conn: *Connector) !Delete { const reserved_1 = conn.rx_buffer.readU16(); const exchange = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const if_unused = if (bitset0 & (1 << 0) == 0) true else false; const no_wait = if (bitset0 & (1 << 1) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Exchange@{}.Delete", .{conn.channel}); return Delete{ .reserved_1 = reserved_1, .exchange = exchange, .if_unused = if_unused, .no_wait = no_wait, }; } }; pub const DELETE_METHOD = 20; pub fn deleteSync( conn: *Connector, exchange: []const u8, if_unused: bool, no_wait: bool, ) !DeleteOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(EXCHANGE_CLASS, DELETE_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(exchange); var bitset0: u8 = 0; const _bit: u8 = 1; if (if_unused) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (no_wait) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Exchange@{}.Delete ->", .{conn.channel}); return awaitDeleteOk(conn); } // delete pub fn awaitDelete(conn: *Connector) !Delete { return conn.awaitMethod(Delete); } // delete-ok pub const DeleteOk = struct { pub const CLASS = 40; pub const METHOD = 21; pub fn read(conn: *Connector) !DeleteOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Exchange@{}.Delete_ok", .{conn.channel}); return DeleteOk{}; } }; pub const DELETE_OK_METHOD = 21; pub fn deleteOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(EXCHANGE_CLASS, Exchange.DELETE_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Exchange@{}.Delete_ok ->", .{conn.channel}); } // delete_ok pub fn awaitDeleteOk(conn: *Connector) !DeleteOk { return conn.awaitMethod(DeleteOk); } }; // queue pub const Queue = struct { pub const QUEUE_CLASS = 50; // declare pub const Declare = struct { pub const CLASS = 50; pub const METHOD = 10; reserved_1: u16, queue: []const u8, passive: bool, durable: bool, exclusive: bool, auto_delete: bool, no_wait: bool, arguments: Table, pub fn read(conn: *Connector) !Declare { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const passive = if (bitset0 & (1 << 0) == 0) true else false; const durable = if (bitset0 & (1 << 1) == 0) true else false; const exclusive = if (bitset0 & (1 << 2) == 0) true else false; const auto_delete = if (bitset0 & (1 << 3) == 0) true else false; const no_wait = if (bitset0 & (1 << 4) == 0) true else false; var arguments = conn.rx_buffer.readTable(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Declare", .{conn.channel}); return Declare{ .reserved_1 = reserved_1, .queue = queue, .passive = passive, .durable = durable, .exclusive = exclusive, .auto_delete = auto_delete, .no_wait = no_wait, .arguments = arguments, }; } }; pub const DECLARE_METHOD = 10; pub fn declareSync( conn: *Connector, queue: []const u8, passive: bool, durable: bool, exclusive: bool, auto_delete: bool, no_wait: bool, arguments: ?*Table, ) !DeclareOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, DECLARE_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); var bitset0: u8 = 0; const _bit: u8 = 1; if (passive) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (durable) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); if (exclusive) bitset0 |= (_bit << 2) else bitset0 &= ~(_bit << 2); if (auto_delete) bitset0 |= (_bit << 3) else bitset0 &= ~(_bit << 3); if (no_wait) bitset0 |= (_bit << 4) else bitset0 &= ~(_bit << 4); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeTable(arguments); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Declare ->", .{conn.channel}); return awaitDeclareOk(conn); } // declare pub fn awaitDeclare(conn: *Connector) !Declare { return conn.awaitMethod(Declare); } // declare-ok pub const DeclareOk = struct { pub const CLASS = 50; pub const METHOD = 11; queue: []const u8, message_count: u32, consumer_count: u32, pub fn read(conn: *Connector) !DeclareOk { const queue = conn.rx_buffer.readShortString(); const message_count = conn.rx_buffer.readU32(); const consumer_count = conn.rx_buffer.readU32(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Declare_ok", .{conn.channel}); return DeclareOk{ .queue = queue, .message_count = message_count, .consumer_count = consumer_count, }; } }; pub const DECLARE_OK_METHOD = 11; pub fn declareOkAsync( conn: *Connector, queue: []const u8, message_count: u32, consumer_count: u32, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, Queue.DECLARE_OK_METHOD); conn.tx_buffer.writeShortString(queue); conn.tx_buffer.writeU32(message_count); conn.tx_buffer.writeU32(consumer_count); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Declare_ok ->", .{conn.channel}); } // declare_ok pub fn awaitDeclareOk(conn: *Connector) !DeclareOk { return conn.awaitMethod(DeclareOk); } // bind pub const Bind = struct { pub const CLASS = 50; pub const METHOD = 20; reserved_1: u16, queue: []const u8, exchange: []const u8, routing_key: []const u8, no_wait: bool, arguments: Table, pub fn read(conn: *Connector) !Bind { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const no_wait = if (bitset0 & (1 << 0) == 0) true else false; var arguments = conn.rx_buffer.readTable(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Bind", .{conn.channel}); return Bind{ .reserved_1 = reserved_1, .queue = queue, .exchange = exchange, .routing_key = routing_key, .no_wait = no_wait, .arguments = arguments, }; } }; pub const BIND_METHOD = 20; pub fn bindSync( conn: *Connector, queue: []const u8, exchange: []const u8, routing_key: []const u8, no_wait: bool, arguments: ?*Table, ) !BindOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, BIND_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); var bitset0: u8 = 0; const _bit: u8 = 1; if (no_wait) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeTable(arguments); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Bind ->", .{conn.channel}); return awaitBindOk(conn); } // bind pub fn awaitBind(conn: *Connector) !Bind { return conn.awaitMethod(Bind); } // bind-ok pub const BindOk = struct { pub const CLASS = 50; pub const METHOD = 21; pub fn read(conn: *Connector) !BindOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Bind_ok", .{conn.channel}); return BindOk{}; } }; pub const BIND_OK_METHOD = 21; pub fn bindOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, Queue.BIND_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Bind_ok ->", .{conn.channel}); } // bind_ok pub fn awaitBindOk(conn: *Connector) !BindOk { return conn.awaitMethod(BindOk); } // unbind pub const Unbind = struct { pub const CLASS = 50; pub const METHOD = 50; reserved_1: u16, queue: []const u8, exchange: []const u8, routing_key: []const u8, arguments: Table, pub fn read(conn: *Connector) !Unbind { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); var arguments = conn.rx_buffer.readTable(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Unbind", .{conn.channel}); return Unbind{ .reserved_1 = reserved_1, .queue = queue, .exchange = exchange, .routing_key = routing_key, .arguments = arguments, }; } }; pub const UNBIND_METHOD = 50; pub fn unbindSync( conn: *Connector, queue: []const u8, exchange: []const u8, routing_key: []const u8, arguments: ?*Table, ) !UnbindOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, UNBIND_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); conn.tx_buffer.writeTable(arguments); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Unbind ->", .{conn.channel}); return awaitUnbindOk(conn); } // unbind pub fn awaitUnbind(conn: *Connector) !Unbind { return conn.awaitMethod(Unbind); } // unbind-ok pub const UnbindOk = struct { pub const CLASS = 50; pub const METHOD = 51; pub fn read(conn: *Connector) !UnbindOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Unbind_ok", .{conn.channel}); return UnbindOk{}; } }; pub const UNBIND_OK_METHOD = 51; pub fn unbindOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, Queue.UNBIND_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Unbind_ok ->", .{conn.channel}); } // unbind_ok pub fn awaitUnbindOk(conn: *Connector) !UnbindOk { return conn.awaitMethod(UnbindOk); } // purge pub const Purge = struct { pub const CLASS = 50; pub const METHOD = 30; reserved_1: u16, queue: []const u8, no_wait: bool, pub fn read(conn: *Connector) !Purge { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const no_wait = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Purge", .{conn.channel}); return Purge{ .reserved_1 = reserved_1, .queue = queue, .no_wait = no_wait, }; } }; pub const PURGE_METHOD = 30; pub fn purgeSync( conn: *Connector, queue: []const u8, no_wait: bool, ) !PurgeOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, PURGE_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); var bitset0: u8 = 0; const _bit: u8 = 1; if (no_wait) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Purge ->", .{conn.channel}); return awaitPurgeOk(conn); } // purge pub fn awaitPurge(conn: *Connector) !Purge { return conn.awaitMethod(Purge); } // purge-ok pub const PurgeOk = struct { pub const CLASS = 50; pub const METHOD = 31; message_count: u32, pub fn read(conn: *Connector) !PurgeOk { const message_count = conn.rx_buffer.readU32(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Purge_ok", .{conn.channel}); return PurgeOk{ .message_count = message_count, }; } }; pub const PURGE_OK_METHOD = 31; pub fn purgeOkAsync( conn: *Connector, message_count: u32, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, Queue.PURGE_OK_METHOD); conn.tx_buffer.writeU32(message_count); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Purge_ok ->", .{conn.channel}); } // purge_ok pub fn awaitPurgeOk(conn: *Connector) !PurgeOk { return conn.awaitMethod(PurgeOk); } // delete pub const Delete = struct { pub const CLASS = 50; pub const METHOD = 40; reserved_1: u16, queue: []const u8, if_unused: bool, if_empty: bool, no_wait: bool, pub fn read(conn: *Connector) !Delete { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const if_unused = if (bitset0 & (1 << 0) == 0) true else false; const if_empty = if (bitset0 & (1 << 1) == 0) true else false; const no_wait = if (bitset0 & (1 << 2) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Delete", .{conn.channel}); return Delete{ .reserved_1 = reserved_1, .queue = queue, .if_unused = if_unused, .if_empty = if_empty, .no_wait = no_wait, }; } }; pub const DELETE_METHOD = 40; pub fn deleteSync( conn: *Connector, queue: []const u8, if_unused: bool, if_empty: bool, no_wait: bool, ) !DeleteOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, DELETE_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); var bitset0: u8 = 0; const _bit: u8 = 1; if (if_unused) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (if_empty) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); if (no_wait) bitset0 |= (_bit << 2) else bitset0 &= ~(_bit << 2); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Delete ->", .{conn.channel}); return awaitDeleteOk(conn); } // delete pub fn awaitDelete(conn: *Connector) !Delete { return conn.awaitMethod(Delete); } // delete-ok pub const DeleteOk = struct { pub const CLASS = 50; pub const METHOD = 41; message_count: u32, pub fn read(conn: *Connector) !DeleteOk { const message_count = conn.rx_buffer.readU32(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Queue@{}.Delete_ok", .{conn.channel}); return DeleteOk{ .message_count = message_count, }; } }; pub const DELETE_OK_METHOD = 41; pub fn deleteOkAsync( conn: *Connector, message_count: u32, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(QUEUE_CLASS, Queue.DELETE_OK_METHOD); conn.tx_buffer.writeU32(message_count); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Queue@{}.Delete_ok ->", .{conn.channel}); } // delete_ok pub fn awaitDeleteOk(conn: *Connector) !DeleteOk { return conn.awaitMethod(DeleteOk); } }; // basic pub const Basic = struct { pub const BASIC_CLASS = 60; // qos pub const Qos = struct { pub const CLASS = 60; pub const METHOD = 10; prefetch_size: u32, prefetch_count: u16, global: bool, pub fn read(conn: *Connector) !Qos { const prefetch_size = conn.rx_buffer.readU32(); const prefetch_count = conn.rx_buffer.readU16(); const bitset0 = conn.rx_buffer.readU8(); const global = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Qos", .{conn.channel}); return Qos{ .prefetch_size = prefetch_size, .prefetch_count = prefetch_count, .global = global, }; } }; pub const QOS_METHOD = 10; pub fn qosSync( conn: *Connector, prefetch_size: u32, prefetch_count: u16, global: bool, ) !QosOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, QOS_METHOD); conn.tx_buffer.writeU32(prefetch_size); conn.tx_buffer.writeU16(prefetch_count); var bitset0: u8 = 0; const _bit: u8 = 1; if (global) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Qos ->", .{conn.channel}); return awaitQosOk(conn); } // qos pub fn awaitQos(conn: *Connector) !Qos { return conn.awaitMethod(Qos); } // qos-ok pub const QosOk = struct { pub const CLASS = 60; pub const METHOD = 11; pub fn read(conn: *Connector) !QosOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Qos_ok", .{conn.channel}); return QosOk{}; } }; pub const QOS_OK_METHOD = 11; pub fn qosOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.QOS_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Qos_ok ->", .{conn.channel}); } // qos_ok pub fn awaitQosOk(conn: *Connector) !QosOk { return conn.awaitMethod(QosOk); } // consume pub const Consume = struct { pub const CLASS = 60; pub const METHOD = 20; reserved_1: u16, queue: []const u8, consumer_tag: []const u8, no_local: bool, no_ack: bool, exclusive: bool, no_wait: bool, arguments: Table, pub fn read(conn: *Connector) !Consume { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const consumer_tag = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const no_local = if (bitset0 & (1 << 0) == 0) true else false; const no_ack = if (bitset0 & (1 << 1) == 0) true else false; const exclusive = if (bitset0 & (1 << 2) == 0) true else false; const no_wait = if (bitset0 & (1 << 3) == 0) true else false; var arguments = conn.rx_buffer.readTable(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Consume", .{conn.channel}); return Consume{ .reserved_1 = reserved_1, .queue = queue, .consumer_tag = consumer_tag, .no_local = no_local, .no_ack = no_ack, .exclusive = exclusive, .no_wait = no_wait, .arguments = arguments, }; } }; pub const CONSUME_METHOD = 20; pub fn consumeSync( conn: *Connector, queue: []const u8, consumer_tag: []const u8, no_local: bool, no_ack: bool, exclusive: bool, no_wait: bool, arguments: ?*Table, ) !ConsumeOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, CONSUME_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); conn.tx_buffer.writeShortString(consumer_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (no_local) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (no_ack) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); if (exclusive) bitset0 |= (_bit << 2) else bitset0 &= ~(_bit << 2); if (no_wait) bitset0 |= (_bit << 3) else bitset0 &= ~(_bit << 3); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeTable(arguments); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Consume ->", .{conn.channel}); return awaitConsumeOk(conn); } // consume pub fn awaitConsume(conn: *Connector) !Consume { return conn.awaitMethod(Consume); } // consume-ok pub const ConsumeOk = struct { pub const CLASS = 60; pub const METHOD = 21; consumer_tag: []const u8, pub fn read(conn: *Connector) !ConsumeOk { const consumer_tag = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Consume_ok", .{conn.channel}); return ConsumeOk{ .consumer_tag = consumer_tag, }; } }; pub const CONSUME_OK_METHOD = 21; pub fn consumeOkAsync( conn: *Connector, consumer_tag: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.CONSUME_OK_METHOD); conn.tx_buffer.writeShortString(consumer_tag); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Consume_ok ->", .{conn.channel}); } // consume_ok pub fn awaitConsumeOk(conn: *Connector) !ConsumeOk { return conn.awaitMethod(ConsumeOk); } // cancel pub const Cancel = struct { pub const CLASS = 60; pub const METHOD = 30; consumer_tag: []const u8, no_wait: bool, pub fn read(conn: *Connector) !Cancel { const consumer_tag = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const no_wait = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Cancel", .{conn.channel}); return Cancel{ .consumer_tag = consumer_tag, .no_wait = no_wait, }; } }; pub const CANCEL_METHOD = 30; pub fn cancelSync( conn: *Connector, consumer_tag: []const u8, no_wait: bool, ) !CancelOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, CANCEL_METHOD); conn.tx_buffer.writeShortString(consumer_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (no_wait) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Cancel ->", .{conn.channel}); return awaitCancelOk(conn); } // cancel pub fn awaitCancel(conn: *Connector) !Cancel { return conn.awaitMethod(Cancel); } // cancel-ok pub const CancelOk = struct { pub const CLASS = 60; pub const METHOD = 31; consumer_tag: []const u8, pub fn read(conn: *Connector) !CancelOk { const consumer_tag = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Cancel_ok", .{conn.channel}); return CancelOk{ .consumer_tag = consumer_tag, }; } }; pub const CANCEL_OK_METHOD = 31; pub fn cancelOkAsync( conn: *Connector, consumer_tag: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.CANCEL_OK_METHOD); conn.tx_buffer.writeShortString(consumer_tag); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Cancel_ok ->", .{conn.channel}); } // cancel_ok pub fn awaitCancelOk(conn: *Connector) !CancelOk { return conn.awaitMethod(CancelOk); } // publish pub const Publish = struct { pub const CLASS = 60; pub const METHOD = 40; reserved_1: u16, exchange: []const u8, routing_key: []const u8, mandatory: bool, immediate: bool, pub fn read(conn: *Connector) !Publish { const reserved_1 = conn.rx_buffer.readU16(); const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const mandatory = if (bitset0 & (1 << 0) == 0) true else false; const immediate = if (bitset0 & (1 << 1) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Publish", .{conn.channel}); return Publish{ .reserved_1 = reserved_1, .exchange = exchange, .routing_key = routing_key, .mandatory = mandatory, .immediate = immediate, }; } }; pub const PUBLISH_METHOD = 40; pub fn publishAsync( conn: *Connector, exchange: []const u8, routing_key: []const u8, mandatory: bool, immediate: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.PUBLISH_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); var bitset0: u8 = 0; const _bit: u8 = 1; if (mandatory) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); if (immediate) bitset0 |= (_bit << 1) else bitset0 &= ~(_bit << 1); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Publish ->", .{conn.channel}); } // publish pub fn awaitPublish(conn: *Connector) !Publish { return conn.awaitMethod(Publish); } // return pub const Return = struct { pub const CLASS = 60; pub const METHOD = 50; reply_code: u16, reply_text: []const u8, exchange: []const u8, routing_key: []const u8, pub fn read(conn: *Connector) !Return { const reply_code = conn.rx_buffer.readU16(); const reply_text = conn.rx_buffer.readShortString(); const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Return", .{conn.channel}); return Return{ .reply_code = reply_code, .reply_text = reply_text, .exchange = exchange, .routing_key = routing_key, }; } }; pub const RETURN_METHOD = 50; pub fn returnAsync( conn: *Connector, reply_code: u16, reply_text: []const u8, exchange: []const u8, routing_key: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.RETURN_METHOD); conn.tx_buffer.writeU16(reply_code); conn.tx_buffer.writeShortString(reply_text); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Return ->", .{conn.channel}); } // @"return" pub fn awaitReturn(conn: *Connector) !Return { return conn.awaitMethod(Return); } // deliver pub const Deliver = struct { pub const CLASS = 60; pub const METHOD = 60; consumer_tag: []const u8, delivery_tag: u64, redelivered: bool, exchange: []const u8, routing_key: []const u8, pub fn read(conn: *Connector) !Deliver { const consumer_tag = conn.rx_buffer.readShortString(); const delivery_tag = conn.rx_buffer.readU64(); const bitset0 = conn.rx_buffer.readU8(); const redelivered = if (bitset0 & (1 << 0) == 0) true else false; const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Deliver", .{conn.channel}); return Deliver{ .consumer_tag = consumer_tag, .delivery_tag = delivery_tag, .redelivered = redelivered, .exchange = exchange, .routing_key = routing_key, }; } }; pub const DELIVER_METHOD = 60; pub fn deliverAsync( conn: *Connector, consumer_tag: []const u8, delivery_tag: u64, redelivered: bool, exchange: []const u8, routing_key: []const u8, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.DELIVER_METHOD); conn.tx_buffer.writeShortString(consumer_tag); conn.tx_buffer.writeU64(delivery_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (redelivered) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Deliver ->", .{conn.channel}); } // deliver pub fn awaitDeliver(conn: *Connector) !Deliver { return conn.awaitMethod(Deliver); } // get pub const Get = struct { pub const CLASS = 60; pub const METHOD = 70; reserved_1: u16, queue: []const u8, no_ack: bool, pub fn read(conn: *Connector) !Get { const reserved_1 = conn.rx_buffer.readU16(); const queue = conn.rx_buffer.readShortString(); const bitset0 = conn.rx_buffer.readU8(); const no_ack = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Get", .{conn.channel}); return Get{ .reserved_1 = reserved_1, .queue = queue, .no_ack = no_ack, }; } }; pub const GET_METHOD = 70; pub fn getSync( conn: *Connector, queue: []const u8, no_ack: bool, ) !GetEmpty { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, GET_METHOD); const reserved_1 = 0; conn.tx_buffer.writeU16(reserved_1); conn.tx_buffer.writeShortString(queue); var bitset0: u8 = 0; const _bit: u8 = 1; if (no_ack) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Get ->", .{conn.channel}); return awaitGetEmpty(conn); } // get pub fn awaitGet(conn: *Connector) !Get { return conn.awaitMethod(Get); } // get-ok pub const GetOk = struct { pub const CLASS = 60; pub const METHOD = 71; delivery_tag: u64, redelivered: bool, exchange: []const u8, routing_key: []const u8, message_count: u32, pub fn read(conn: *Connector) !GetOk { const delivery_tag = conn.rx_buffer.readU64(); const bitset0 = conn.rx_buffer.readU8(); const redelivered = if (bitset0 & (1 << 0) == 0) true else false; const exchange = conn.rx_buffer.readShortString(); const routing_key = conn.rx_buffer.readShortString(); const message_count = conn.rx_buffer.readU32(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Get_ok", .{conn.channel}); return GetOk{ .delivery_tag = delivery_tag, .redelivered = redelivered, .exchange = exchange, .routing_key = routing_key, .message_count = message_count, }; } }; pub const GET_OK_METHOD = 71; pub fn getOkAsync( conn: *Connector, delivery_tag: u64, redelivered: bool, exchange: []const u8, routing_key: []const u8, message_count: u32, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.GET_OK_METHOD); conn.tx_buffer.writeU64(delivery_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (redelivered) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.writeShortString(exchange); conn.tx_buffer.writeShortString(routing_key); conn.tx_buffer.writeU32(message_count); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Get_ok ->", .{conn.channel}); } // get_ok pub fn awaitGetOk(conn: *Connector) !GetOk { return conn.awaitMethod(GetOk); } // get-empty pub const GetEmpty = struct { pub const CLASS = 60; pub const METHOD = 72; reserved_1: []const u8, pub fn read(conn: *Connector) !GetEmpty { const reserved_1 = conn.rx_buffer.readShortString(); try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Get_empty", .{conn.channel}); return GetEmpty{ .reserved_1 = reserved_1, }; } }; pub const GET_EMPTY_METHOD = 72; pub fn getEmptyAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.GET_EMPTY_METHOD); const reserved_1 = ""; conn.tx_buffer.writeShortString(reserved_1); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Get_empty ->", .{conn.channel}); } // get_empty pub fn awaitGetEmpty(conn: *Connector) !GetEmpty { return conn.awaitMethod(GetEmpty); } // ack pub const Ack = struct { pub const CLASS = 60; pub const METHOD = 80; delivery_tag: u64, multiple: bool, pub fn read(conn: *Connector) !Ack { const delivery_tag = conn.rx_buffer.readU64(); const bitset0 = conn.rx_buffer.readU8(); const multiple = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Ack", .{conn.channel}); return Ack{ .delivery_tag = delivery_tag, .multiple = multiple, }; } }; pub const ACK_METHOD = 80; pub fn ackAsync( conn: *Connector, delivery_tag: u64, multiple: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.ACK_METHOD); conn.tx_buffer.writeU64(delivery_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (multiple) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Ack ->", .{conn.channel}); } // ack pub fn awaitAck(conn: *Connector) !Ack { return conn.awaitMethod(Ack); } // reject pub const Reject = struct { pub const CLASS = 60; pub const METHOD = 90; delivery_tag: u64, requeue: bool, pub fn read(conn: *Connector) !Reject { const delivery_tag = conn.rx_buffer.readU64(); const bitset0 = conn.rx_buffer.readU8(); const requeue = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Reject", .{conn.channel}); return Reject{ .delivery_tag = delivery_tag, .requeue = requeue, }; } }; pub const REJECT_METHOD = 90; pub fn rejectAsync( conn: *Connector, delivery_tag: u64, requeue: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.REJECT_METHOD); conn.tx_buffer.writeU64(delivery_tag); var bitset0: u8 = 0; const _bit: u8 = 1; if (requeue) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Reject ->", .{conn.channel}); } // reject pub fn awaitReject(conn: *Connector) !Reject { return conn.awaitMethod(Reject); } // recover-async pub const RecoverAsync = struct { pub const CLASS = 60; pub const METHOD = 100; requeue: bool, pub fn read(conn: *Connector) !RecoverAsync { const bitset0 = conn.rx_buffer.readU8(); const requeue = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Recover_async", .{conn.channel}); return RecoverAsync{ .requeue = requeue, }; } }; pub const RECOVER_ASYNC_METHOD = 100; pub fn recoverAsyncAsync( conn: *Connector, requeue: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.RECOVER_ASYNC_METHOD); var bitset0: u8 = 0; const _bit: u8 = 1; if (requeue) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Recover_async ->", .{conn.channel}); } // recover_async pub fn awaitRecoverAsync(conn: *Connector) !RecoverAsync { return conn.awaitMethod(RecoverAsync); } // recover pub const Recover = struct { pub const CLASS = 60; pub const METHOD = 110; requeue: bool, pub fn read(conn: *Connector) !Recover { const bitset0 = conn.rx_buffer.readU8(); const requeue = if (bitset0 & (1 << 0) == 0) true else false; try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Recover", .{conn.channel}); return Recover{ .requeue = requeue, }; } }; pub const RECOVER_METHOD = 110; pub fn recoverAsync( conn: *Connector, requeue: bool, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.RECOVER_METHOD); var bitset0: u8 = 0; const _bit: u8 = 1; if (requeue) bitset0 |= (_bit << 0) else bitset0 &= ~(_bit << 0); conn.tx_buffer.writeU8(bitset0); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Recover ->", .{conn.channel}); } // recover pub fn awaitRecover(conn: *Connector) !Recover { return conn.awaitMethod(Recover); } // recover-ok pub const RecoverOk = struct { pub const CLASS = 60; pub const METHOD = 111; pub fn read(conn: *Connector) !RecoverOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Basic@{}.Recover_ok", .{conn.channel}); return RecoverOk{}; } }; pub const RECOVER_OK_METHOD = 111; pub fn recoverOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(BASIC_CLASS, Basic.RECOVER_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Basic@{}.Recover_ok ->", .{conn.channel}); } // recover_ok pub fn awaitRecoverOk(conn: *Connector) !RecoverOk { return conn.awaitMethod(RecoverOk); } }; // tx pub const Tx = struct { pub const TX_CLASS = 90; // select pub const Select = struct { pub const CLASS = 90; pub const METHOD = 10; pub fn read(conn: *Connector) !Select { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Select", .{conn.channel}); return Select{}; } }; pub const SELECT_METHOD = 10; pub fn selectSync( conn: *Connector, ) !SelectOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, SELECT_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Select ->", .{conn.channel}); return awaitSelectOk(conn); } // select pub fn awaitSelect(conn: *Connector) !Select { return conn.awaitMethod(Select); } // select-ok pub const SelectOk = struct { pub const CLASS = 90; pub const METHOD = 11; pub fn read(conn: *Connector) !SelectOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Select_ok", .{conn.channel}); return SelectOk{}; } }; pub const SELECT_OK_METHOD = 11; pub fn selectOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, Tx.SELECT_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Select_ok ->", .{conn.channel}); } // select_ok pub fn awaitSelectOk(conn: *Connector) !SelectOk { return conn.awaitMethod(SelectOk); } // commit pub const Commit = struct { pub const CLASS = 90; pub const METHOD = 20; pub fn read(conn: *Connector) !Commit { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Commit", .{conn.channel}); return Commit{}; } }; pub const COMMIT_METHOD = 20; pub fn commitSync( conn: *Connector, ) !CommitOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, COMMIT_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Commit ->", .{conn.channel}); return awaitCommitOk(conn); } // commit pub fn awaitCommit(conn: *Connector) !Commit { return conn.awaitMethod(Commit); } // commit-ok pub const CommitOk = struct { pub const CLASS = 90; pub const METHOD = 21; pub fn read(conn: *Connector) !CommitOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Commit_ok", .{conn.channel}); return CommitOk{}; } }; pub const COMMIT_OK_METHOD = 21; pub fn commitOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, Tx.COMMIT_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Commit_ok ->", .{conn.channel}); } // commit_ok pub fn awaitCommitOk(conn: *Connector) !CommitOk { return conn.awaitMethod(CommitOk); } // rollback pub const Rollback = struct { pub const CLASS = 90; pub const METHOD = 30; pub fn read(conn: *Connector) !Rollback { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Rollback", .{conn.channel}); return Rollback{}; } }; pub const ROLLBACK_METHOD = 30; pub fn rollbackSync( conn: *Connector, ) !RollbackOk { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, ROLLBACK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Rollback ->", .{conn.channel}); return awaitRollbackOk(conn); } // rollback pub fn awaitRollback(conn: *Connector) !Rollback { return conn.awaitMethod(Rollback); } // rollback-ok pub const RollbackOk = struct { pub const CLASS = 90; pub const METHOD = 31; pub fn read(conn: *Connector) !RollbackOk { try conn.rx_buffer.readEOF(); std.log.debug("\t<- Tx@{}.Rollback_ok", .{conn.channel}); return RollbackOk{}; } }; pub const ROLLBACK_OK_METHOD = 31; pub fn rollbackOkAsync( conn: *Connector, ) !void { conn.tx_buffer.writeFrameHeader(.Method, conn.channel, 0); conn.tx_buffer.writeMethodHeader(TX_CLASS, Tx.ROLLBACK_OK_METHOD); conn.tx_buffer.updateFrameLength(); // TODO: do we need to retry write (if n isn't as high as we expect)? const n = try std.os.write(conn.file.handle, conn.tx_buffer.extent()); conn.tx_buffer.reset(); std.log.debug("Tx@{}.Rollback_ok ->", .{conn.channel}); } // rollback_ok pub fn awaitRollbackOk(conn: *Connector) !RollbackOk { return conn.awaitMethod(RollbackOk); } };
src/protocol.zig
const std = @import("std"); const stdx = @import("stdx"); const t = stdx.testing; const log = stdx.log.scoped(.incremental_test); const _parser = @import("parser.zig"); const Parser = _parser.Parser; const ParseConfig = _parser.ParseConfig; const DebugInfo = _parser.DebugInfo; const grammar = @import("grammar.zig"); const Grammar = grammar.Grammar; const builder = @import("builder.zig"); const grammars = @import("grammars.zig"); const document = stdx.textbuf.document; const Document = document.Document; const TokenId = @import("ast.zig").TokenId; const NullToken = stdx.ds.CompactNull(TokenId); test "Parser is_incremental=true" { const src = \\const std = @import("std"); \\ \\pub fn main() !void { \\ const stdout = std.io.getStdOut().writer(); \\ try stdout.print("Hello, {s}!\n", .{"world"}); \\} ; var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); var doc: Document = undefined; doc.init(t.alloc); defer doc.deinit(); doc.loadSource(src); var gram: Grammar = undefined; try builder.initGrammar(&gram, t.alloc, grammars.ZigGrammar); defer gram.deinit(); const Config: ParseConfig = .{ .is_incremental = true }; var parser = Parser.init(t.alloc, &gram); defer parser.deinit(); var res = parser.parse(Config, &doc); defer res.deinit(); var ast = &res.ast; const tokens = &ast.tokens.tokens; const lines = &ast.tokens.lines; // Verify token lists per document line. try t.eq(doc.numLines(), @intCast(u32, lines.items.len)); var token_id = tokens.getListHead(lines.items[doc.getLineId(0)].?).?; try t.eqStr(ast.getTokenString(&doc, 0, token_id), "const"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), "std"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), "="); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), "@import"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), "("); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), "\"std\""); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), ")"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 0, token_id), ";"); token_id = tokens.getNextIdNoCheck(token_id); try t.eq(token_id, NullToken); // Empty line so no token list. try t.eq(lines.items[doc.getLineId(1)], null); token_id = tokens.getListHead(lines.items[doc.getLineId(2)].?).?; try t.eqStr(ast.getTokenString(&doc, 2, token_id), "pub"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "fn"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "main"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "("); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), ")"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "!"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "void"); token_id = tokens.getNextIdNoCheck(token_id); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "{"); token_id = tokens.getNextIdNoCheck(token_id); try t.eq(token_id, NullToken); // Skip to end. token_id = tokens.getListHead(lines.items[doc.getLineId(5)].?).?; try t.eqStr(ast.getTokenString(&doc, 5, token_id), "}"); token_id = tokens.getNextIdNoCheck(token_id); try t.eq(token_id, NullToken); // str_buf.clearRetainingCapacity(); // ast.formatTree(str_buf.writer()); // log.warn("{s}", .{str_buf.items}); // Verify ast nodes. const stmts = ast.getChildNodeList(ast.mb_root.?, 0); try t.eq(stmts.len, 2); try t.eqStr(ast.getNodeTagName(stmts[0]), "VariableDecl"); try t.eqStr(ast.getNodeTagName(stmts[1]), "FunctionDecl"); const func_stmts = ast.getChildNodeList(stmts[1], 4); try t.eq(func_stmts.len, 2); try t.eqStr(ast.getNodeTagName(func_stmts[0]), "VariableDecl"); try t.eqStr(ast.getNodeTagName(func_stmts[1]), "TryExpr"); } test "Insert text" { const src = \\const std = @import("std"); \\ \\pub fn main() !void { \\ const stdout = std.io.getStdOut().writer(); \\ try stdout.print("Hello, {s}!\n", .{"world"}); \\} ; var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); var doc: Document = undefined; doc.init(t.alloc); defer doc.deinit(); var gram: Grammar = undefined; try builder.initGrammar(&gram, t.alloc, grammars.ZigGrammar); defer gram.deinit(); const Config: ParseConfig = .{ .is_incremental = true }; var parser = Parser.init(t.alloc, &gram); defer parser.deinit(); var debug: DebugInfo = undefined; debug.init(t.alloc); defer debug.deinit(); { // Insert before existing token that reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; // str_buf.clearRetainingCapacity(); // ast.formatTree(str_buf.writer()); // log.warn("{s}", .{str_buf.items}); doc.insertIntoLine(2, 7, "_insert_"); parser.reparseChangeDebug(Config, &doc, ast, 2, 7, "_insert_".len, &debug); try t.eq(debug.stats.inc_tokens_added, 2); try t.eq(debug.stats.inc_tokens_removed, 2); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "_insert_main"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } { // Insert in existing token reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; doc.insertIntoLine(2, 8, "_insert_"); parser.reparseChangeDebug(Config, &doc, ast, 2, 8, "_insert_".len, &debug); try t.eq(debug.stats.inc_tokens_added, 1); try t.eq(debug.stats.inc_tokens_removed, 1); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "m_insert_ain"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } { // Insert after existing token reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; doc.insertIntoLine(2, 11, "_insert_"); parser.reparseChangeDebug(Config, &doc, ast, 2, 11, "_insert_".len, &debug); try t.eq(debug.stats.inc_tokens_added, 1); try t.eq(debug.stats.inc_tokens_removed, 1); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "main_insert_"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } } test "Delete text" { const src = \\const std = @import("std"); \\ \\pub fn main() !void { \\ const stdout = std.io.getStdOut().writer(); \\ try stdout.print("Hello, {s}!\n", .{"world"}); \\} ; var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); var doc: Document = undefined; doc.init(t.alloc); defer doc.deinit(); var gram: Grammar = undefined; try builder.initGrammar(&gram, t.alloc, grammars.ZigGrammar); defer gram.deinit(); const Config: ParseConfig = .{ .is_incremental = true }; var parser = Parser.init(t.alloc, &gram); defer parser.deinit(); var debug: DebugInfo = undefined; debug.init(t.alloc); defer debug.deinit(); { // Delete beginning of existing token that reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; // str_buf.clearRetainingCapacity(); // ast.formatTree(str_buf.writer()); // log.warn("{s}", .{str_buf.items}); doc.removeRangeInLine(2, 7, 9); parser.reparseChangeDebug(Config, &doc, ast, 2, 7, -2, &debug); try t.eq(debug.stats.inc_tokens_added, 2); try t.eq(debug.stats.inc_tokens_removed, 2); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "in"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } { // Delete in existing token that reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; doc.removeRangeInLine(2, 8, 10); parser.reparseChangeDebug(Config, &doc, ast, 2, 8, -2, &debug); try t.eq(debug.stats.inc_tokens_added, 1); try t.eq(debug.stats.inc_tokens_removed, 1); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "mn"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } { // Delete ending of existing token that reparses as the same token tag. doc.loadSource(src); var res = parser.parse(Config, &doc); defer res.deinit(); const ast = &res.ast; doc.removeRangeInLine(2, 9, 11); parser.reparseChangeDebug(Config, &doc, ast, 2, 9, -2, &debug); try t.eq(debug.stats.inc_tokens_added, 1); try t.eq(debug.stats.inc_tokens_removed, 1); const list_id = ast.getTokenList(&doc, 2); const token_id = ast.tokens.tokens.getIdAt(list_id, 2); try t.eqStr(ast.getTokenString(&doc, 2, token_id), "ma"); try t.eqStr(ast.getTokenName(token_id), "IdentifierToken"); } }
parser/incremental.test.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const math = std.math; const expo2 = @import("expo2.zig").expo2; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the hyperbolic cosine of x. /// /// Special Cases: /// - cosh(+-0) = 1 /// - cosh(+-inf) = +inf /// - cosh(nan) = nan pub fn cosh(x: var) @typeOf(x) { const T = @typeOf(x); return switch (T) { f32 => cosh32(x), f64 => cosh64(x), else => @compileError("cosh not implemented for " ++ @typeName(T)), }; } // cosh(x) = (exp(x) + 1 / exp(x)) / 2 // = 1 + 0.5 * (exp(x) - 1) * (exp(x) - 1) / exp(x) // = 1 + (x * x) / 2 + o(x^4) fn cosh32(x: f32) f32 { const u = @bitCast(u32, x); const ux = u & 0x7FFFFFFF; const ax = @bitCast(f32, ux); // |x| < log(2) if (ux < 0x3F317217) { if (ux < 0x3F800000 - (12 << 23)) { math.raiseOverflow(); return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = math.exp(ax); return 0.5 * (t + 1 / t); } // |x| > log(FLT_MAX) or nan return expo2(ax); } fn cosh64(x: f64) f64 { const u = @bitCast(u64, x); const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (maxInt(u64) >> 1)); // TODO: Shouldn't need this explicit check. if (x == 0.0) { return 1.0; } // |x| < log(2) if (w < 0x3FE62E42) { if (w < 0x3FF00000 - (26 << 20)) { if (x != 0) { math.raiseInexact(); } return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(DBL_MAX) if (w < 0x40862E42) { const t = math.exp(ax); // NOTE: If x > log(0x1p26) then 1/t is not required. return 0.5 * (t + 1 / t); } // |x| > log(CBL_MAX) or nan return expo2(ax); } test "math.cosh" { expect(cosh(@as(f32, 1.5)) == cosh32(1.5)); expect(cosh(@as(f64, 1.5)) == cosh64(1.5)); } test "math.cosh32" { const epsilon = 0.000001; expect(math.approxEq(f32, cosh32(0.0), 1.0, epsilon)); expect(math.approxEq(f32, cosh32(0.2), 1.020067, epsilon)); expect(math.approxEq(f32, cosh32(0.8923), 1.425225, epsilon)); expect(math.approxEq(f32, cosh32(1.5), 2.352410, epsilon)); } test "math.cosh64" { const epsilon = 0.000001; expect(math.approxEq(f64, cosh64(0.0), 1.0, epsilon)); expect(math.approxEq(f64, cosh64(0.2), 1.020067, epsilon)); expect(math.approxEq(f64, cosh64(0.8923), 1.425225, epsilon)); expect(math.approxEq(f64, cosh64(1.5), 2.352410, epsilon)); } test "math.cosh32.special" { expect(cosh32(0.0) == 1.0); expect(cosh32(-0.0) == 1.0); expect(math.isPositiveInf(cosh32(math.inf(f32)))); expect(math.isPositiveInf(cosh32(-math.inf(f32)))); expect(math.isNan(cosh32(math.nan(f32)))); } test "math.cosh64.special" { expect(cosh64(0.0) == 1.0); expect(cosh64(-0.0) == 1.0); expect(math.isPositiveInf(cosh64(math.inf(f64)))); expect(math.isPositiveInf(cosh64(-math.inf(f64)))); expect(math.isNan(cosh64(math.nan(f64)))); }
lib/std/math/cosh.zig
const std = @import("../../../std.zig"); const linux = std.os.linux; const socklen_t = linux.socklen_t; const iovec = linux.iovec; const iovec_const = linux.iovec_const; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; const uid_t = linux.uid_t; const gid_t = linux.gid_t; const pid_t = linux.pid_t; pub const SYS = extern enum(usize) { 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, arm_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_range2 = 341, arm_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, breakpoint = 0x0f0001, cacheflush = 0x0f0002, usr26 = 0x0f0003, usr32 = 0x0f0004, set_tls = 0x0f0005, get_tls = 0x0f0006, _, }; pub const MMAP2_UNIT = 4096; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; pub const O_NOCTTY = 0o400; pub const O_TRUNC = 0o1000; pub const O_APPEND = 0o2000; pub const O_NONBLOCK = 0o4000; pub const O_DSYNC = 0o10000; pub const O_SYNC = 0o4010000; pub const O_RSYNC = 0o4010000; pub const O_DIRECTORY = 0o40000; pub const O_NOFOLLOW = 0o100000; pub const O_CLOEXEC = 0o2000000; pub const O_ASYNC = 0o20000; pub const O_DIRECT = 0o200000; pub const O_LARGEFILE = 0o400000; pub const O_NOATIME = 0o1000000; pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20040000; pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; pub const F_SETFD = 2; pub const F_GETFL = 3; pub const F_SETFL = 4; pub const F_SETOWN = 8; pub const F_GETOWN = 9; pub const F_SETSIG = 10; pub const F_GETSIG = 11; pub const F_GETLK = 12; pub const F_SETLK = 13; pub const F_SETLKW = 14; pub const F_RDLCK = 0; pub const F_WRLCK = 1; pub const F_UNLCK = 2; pub const F_SETOWN_EX = 15; pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; pub const LOCK_SH = 1; pub const LOCK_EX = 2; pub const LOCK_UN = 8; pub const LOCK_NB = 4; /// stack-like segment pub const MAP_GROWSDOWN = 0x0100; /// ETXTBSY pub const MAP_DENYWRITE = 0x0800; /// mark it as an executable pub const MAP_EXECUTABLE = 0x1000; /// pages are locked pub const MAP_LOCKED = 0x2000; /// don't check for reservations pub const MAP_NORESERVE = 0x4000; pub const VDSO_CGT_SYM = "__vdso_clock_gettime"; pub const VDSO_CGT_VER = "LINUX_2.6"; pub const HWCAP_SWP = 1 << 0; pub const HWCAP_HALF = 1 << 1; pub const HWCAP_THUMB = 1 << 2; pub const HWCAP_26BIT = 1 << 3; pub const HWCAP_FAST_MULT = 1 << 4; pub const HWCAP_FPA = 1 << 5; pub const HWCAP_VFP = 1 << 6; pub const HWCAP_EDSP = 1 << 7; pub const HWCAP_JAVA = 1 << 8; pub const HWCAP_IWMMXT = 1 << 9; pub const HWCAP_CRUNCH = 1 << 10; pub const HWCAP_THUMBEE = 1 << 11; pub const HWCAP_NEON = 1 << 12; pub const HWCAP_VFPv3 = 1 << 13; pub const HWCAP_VFPv3D16 = 1 << 14; pub const HWCAP_TLS = 1 << 15; pub const HWCAP_VFPv4 = 1 << 16; pub const HWCAP_IDIVA = 1 << 17; pub const HWCAP_IDIVT = 1 << 18; pub const HWCAP_VFPD32 = 1 << 19; pub const HWCAP_IDIV = HWCAP_IDIVA | HWCAP_IDIVT; pub const HWCAP_LPAE = 1 << 20; pub const HWCAP_EVTSTRM = 1 << 21; pub const Flock = extern struct { l_type: i16, l_whence: i16, __pad0: [4]u8, l_start: off_t, l_len: off_t, l_pid: pid_t, __unused: [4]u8, }; pub const msghdr = extern struct { msg_name: ?*sockaddr, msg_namelen: socklen_t, msg_iov: [*]iovec, msg_iovlen: i32, msg_control: ?*c_void, msg_controllen: socklen_t, msg_flags: i32, }; pub const msghdr_const = extern struct { msg_name: ?*const sockaddr, msg_namelen: socklen_t, msg_iov: [*]iovec_const, msg_iovlen: i32, msg_control: ?*c_void, msg_controllen: socklen_t, msg_flags: i32, }; pub const blksize_t = i32; pub const nlink_t = u32; pub const time_t = isize; pub const mode_t = u32; pub const off_t = i64; pub const ino_t = u64; pub const dev_t = u64; pub const blkcnt_t = i64; // The `stat` definition used by the Linux kernel. pub const kernel_stat = extern struct { dev: dev_t, __dev_padding: u32, __ino_truncated: u32, mode: mode_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, __rdev_padding: u32, size: off_t, blksize: blksize_t, blocks: blkcnt_t, atim: timespec, mtim: timespec, ctim: timespec, ino: ino_t, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; // The `stat64` definition used by the libc. pub const libc_stat = kernel_stat; pub const timespec = extern struct { tv_sec: i32, tv_nsec: i32, }; pub const timeval = extern struct { tv_sec: i32, tv_usec: i32, }; pub const timezone = extern struct { tz_minuteswest: i32, tz_dsttime: i32, }; pub const mcontext_t = extern struct { trap_no: usize, error_code: usize, oldmask: usize, arm_r0: usize, arm_r1: usize, arm_r2: usize, arm_r3: usize, arm_r4: usize, arm_r5: usize, arm_r6: usize, arm_r7: usize, arm_r8: usize, arm_r9: usize, arm_r10: usize, arm_fp: usize, arm_ip: usize, arm_sp: usize, arm_lr: usize, arm_pc: usize, arm_cpsr: usize, fault_address: usize, }; pub const ucontext_t = extern struct { flags: usize, link: *ucontext_t, stack: stack_t, mcontext: mcontext_t, sigmask: sigset_t, regspace: [64]u64, }; pub const Elf_Symndx = u32;
lib/std/os/bits/linux/arm-eabi.zig
const std = @import("std"); const lola = @import("../main.zig"); const whitespace = [_]u8{ 0x09, // horizontal tab 0x0A, // line feed 0x0B, // vertical tab 0x0C, // form feed 0x0D, // carriage return 0x20, // space }; const root = @import("root"); const milliTimestamp = if (std.builtin.os.tag == .freestanding) if (@hasDecl(root, "milliTimestamp")) root.milliTimestamp else @compileError("Please provide milliTimestamp in the root file for freestanding targets!") else std.time.milliTimestamp; /// Installs the LoLa standard library into the given environment, /// providing it with a basic set of functions. /// `allocator` will be used to perform new allocations for the environment. pub fn install(environment: *lola.runtime.Environment, allocator: *std.mem.Allocator) !void { // Install all functions from the namespace "functions": inline for (std.meta.declarations(sync_functions)) |decl| { try environment.installFunction(decl.name, lola.runtime.Function{ .syncUser = lola.runtime.UserFunction{ .context = lola.runtime.Context.init(std.mem.Allocator, allocator), .destructor = null, .call = @field(sync_functions, decl.name), }, }); } inline for (std.meta.declarations(async_functions)) |decl| { try environment.installFunction(decl.name, lola.runtime.Function{ .asyncUser = lola.runtime.AsyncUserFunction{ .context = lola.runtime.Context.init(std.mem.Allocator, allocator), .destructor = null, .call = @field(async_functions, decl.name), }, }); } } /// empty compile unit for testing purposes const empty_compile_unit = lola.CompileUnit{ .arena = std.heap.ArenaAllocator.init(std.testing.failing_allocator), .comment = "empty compile unit", .globalCount = 0, .temporaryCount = 0, .code = "", .functions = &[0]lola.CompileUnit.Function{}, .debugSymbols = &[0]lola.CompileUnit.DebugSymbol{}, }; test "stdlib.install" { var pool = lola.runtime.ObjectPool([_]type{}).init(std.testing.allocator); defer pool.deinit(); var env = try lola.runtime.Environment.init(std.testing.allocator, &empty_compile_unit, pool.interface()); defer env.deinit(); // TODO: Reinsert this try install(&env, std.testing.allocator); } const async_functions = struct { fn Sleep(env: *lola.runtime.Environment, call_context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.AsyncFunctionCall { const allocator = call_context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; const seconds = try args[0].toNumber(); const Context = struct { allocator: *std.mem.Allocator, end_time: f64, }; const ptr = try allocator.create(Context); ptr.* = Context{ .allocator = allocator, .end_time = @intToFloat(f64, milliTimestamp()) + 1000.0 * seconds, }; return lola.runtime.AsyncFunctionCall{ .context = lola.runtime.Context.init(Context, ptr), .destructor = struct { fn dtor(exec_context: lola.runtime.Context) void { const ctx = exec_context.get(Context); ctx.allocator.destroy(ctx); } }.dtor, .execute = struct { fn execute(exec_context: lola.runtime.Context) anyerror!?lola.runtime.Value { const ctx = exec_context.get(Context); if (ctx.end_time < @intToFloat(f64, milliTimestamp())) { return .void; } else { return null; } } }.execute, }; } fn Yield(env: *lola.runtime.Environment, call_context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.AsyncFunctionCall { const allocator = call_context.get(std.mem.Allocator); if (args.len != 0) return error.InvalidArgs; const Context = struct { allocator: *std.mem.Allocator, end: bool, }; const ptr = try allocator.create(Context); ptr.* = Context{ .allocator = allocator, .end = false, }; return lola.runtime.AsyncFunctionCall{ .context = lola.runtime.Context.init(Context, ptr), .destructor = struct { fn dtor(exec_context: lola.runtime.Context) void { const ctx = exec_context.get(Context); ctx.allocator.destroy(ctx); } }.dtor, .execute = struct { fn execute(exec_context: lola.runtime.Context) anyerror!?lola.runtime.Value { const ctx = exec_context.get(Context); if (ctx.end) { return .void; } else { ctx.end = true; return null; } } }.execute, }; } }; const sync_functions = struct { fn Length(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return switch (args[0]) { .string => |str| lola.runtime.Value.initNumber(@intToFloat(f64, str.contents.len)), .array => |arr| lola.runtime.Value.initNumber(@intToFloat(f64, arr.contents.len)), else => error.TypeMismatch, }; } fn SubString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 2 or args.len > 3) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; if (args[1] != .number) return error.TypeMismatch; if (args.len == 3 and args[2] != .number) return error.TypeMismatch; const str = args[0].string; const start = try args[1].toInteger(usize); if (start >= str.contents.len) return lola.runtime.Value.initString(allocator, ""); const sliced = if (args.len == 3) str.contents[start..][0..std.math.min(str.contents.len - start, try args[2].toInteger(usize))] else str.contents[start..]; return try lola.runtime.Value.initString(allocator, sliced); } fn Trim(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( allocator, std.mem.trim(u8, str.contents, &whitespace), ); } fn TrimLeft(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( allocator, std.mem.trimLeft(u8, str.contents, &whitespace), ); } fn TrimRight(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const str = args[0].string; return try lola.runtime.Value.initString( allocator, std.mem.trimRight(u8, str.contents, &whitespace), ); } fn IndexOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 2) return error.InvalidArgs; if (args[0] == .string) { if (args[1] != .string) return error.TypeMismatch; const haystack = args[0].string.contents; const needle = args[1].string.contents; return if (std.mem.indexOf(u8, haystack, needle)) |index| lola.runtime.Value.initNumber(@intToFloat(f64, index)) else .void; } else if (args[0] == .array) { const haystack = args[0].array.contents; for (haystack) |val, i| { if (val.eql(args[1])) return lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return .void; } else { return error.TypeMismatch; } } fn LastIndexOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 2) return error.InvalidArgs; if (args[0] == .string) { if (args[1] != .string) return error.TypeMismatch; const haystack = args[0].string.contents; const needle = args[1].string.contents; return if (std.mem.lastIndexOf(u8, haystack, needle)) |index| lola.runtime.Value.initNumber(@intToFloat(f64, index)) else .void; } else if (args[0] == .array) { const haystack = args[0].array.contents; var i: usize = haystack.len; while (i > 0) { i -= 1; if (haystack[i].eql(args[1])) return lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return .void; } else { return error.TypeMismatch; } } fn Byte(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; if (args[0] != .string) return error.TypeMismatch; const value = args[0].string.contents; if (value.len > 0) return lola.runtime.Value.initNumber(@intToFloat(f64, value[0])) else return .void; } fn Chr(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; const val = try args[0].toInteger(u8); return try lola.runtime.Value.initString( allocator, &[_]u8{val}, ); } fn NumToString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 1 or args.len > 2) return error.InvalidArgs; var buffer: [256]u8 = undefined; const slice = if (args.len == 2) blk: { const base = try args[1].toInteger(u8); const val = try args[0].toInteger(isize); const len = std.fmt.formatIntBuf(&buffer, val, base, true, std.fmt.FormatOptions{}); break :blk buffer[0..len]; } else blk: { var stream = std.io.fixedBufferStream(&buffer); const val = try args[0].toNumber(); try std.fmt.formatFloatDecimal(val, .{}, stream.writer()); break :blk stream.getWritten(); }; return try lola.runtime.Value.initString(allocator, slice); } fn StringToNum(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 1 or args.len > 2) return error.InvalidArgs; const str = try args[0].toString(); if (args.len == 2) { const base = try args[1].toInteger(u8); const text = if (base == 16) blk: { var tmp = str; if (std.mem.startsWith(u8, tmp, "0x")) tmp = tmp[2..]; if (std.mem.endsWith(u8, tmp, "h")) tmp = tmp[0 .. tmp.len - 1]; break :blk tmp; } else str; const val = try std.fmt.parseInt(isize, text, base); // return .void; return lola.runtime.Value.initNumber(@intToFloat(f64, val)); } else { const val = std.fmt.parseFloat(f64, str) catch return .void; return lola.runtime.Value.initNumber(val); } } fn Split(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 2 or args.len > 3) return error.InvalidArgs; const input = try args[0].toString(); const separator = try args[1].toString(); const removeEmpty = if (args.len == 3) try args[2].toBoolean() else false; var items = std.ArrayList(lola.runtime.Value).init(allocator); defer { for (items.items) |*i| { i.deinit(); } items.deinit(); } var iter = std.mem.split(input, separator); while (iter.next()) |slice| { if (!removeEmpty or slice.len > 0) { var val = try lola.runtime.Value.initString(allocator, slice); errdefer val.deinit(); try items.append(val); } } return lola.runtime.Value.fromArray(lola.runtime.Array{ .allocator = allocator, .contents = items.toOwnedSlice(), }); } fn Join(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 1 or args.len > 2) return error.InvalidArgs; const array = try args[0].toArray(); const separator = if (args.len == 2) try args[1].toString() else ""; for (array.contents) |item| { if (item != .string) return error.TypeMismatch; } var result = std.ArrayList(u8).init(allocator); defer result.deinit(); for (array.contents) |item, i| { if (i > 0) { try result.appendSlice(separator); } try result.appendSlice(try item.toString()); } return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned( allocator, result.toOwnedSlice(), )); } fn Range(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len < 1 or args.len > 2) return error.InvalidArgs; if (args.len == 2) { const start = try args[0].toInteger(usize); const length = try args[1].toInteger(usize); var arr = try lola.runtime.Array.init(allocator, length); for (arr.contents) |*item, i| { item.* = lola.runtime.Value.initNumber(@intToFloat(f64, start + i)); } return lola.runtime.Value.fromArray(arr); } else { const length = try args[0].toInteger(usize); var arr = try lola.runtime.Array.init(allocator, length); for (arr.contents) |*item, i| { item.* = lola.runtime.Value.initNumber(@intToFloat(f64, i)); } return lola.runtime.Value.fromArray(arr); } } fn Slice(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 3) return error.InvalidArgs; const array = try args[0].toArray(); const start = try args[1].toInteger(usize); const length = try args[2].toInteger(usize); // Out of bounds if (start >= array.contents.len) return lola.runtime.Value.fromArray(try lola.runtime.Array.init(allocator, 0)); const actual_length = std.math.min(length, array.contents.len - start); var arr = try lola.runtime.Array.init(allocator, actual_length); errdefer arr.deinit(); for (arr.contents) |*item, i| { item.* = try array.contents[start + i].clone(); } return lola.runtime.Value.fromArray(arr); } fn DeltaEqual(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 3) return error.InvalidArgs; const a = try args[0].toNumber(); const b = try args[1].toNumber(); const delta = try args[2].toNumber(); return lola.runtime.Value.initBoolean(std.math.fabs(a - b) < delta); } fn Sin(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.sin(try args[0].toNumber())); } fn Cos(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.cos(try args[0].toNumber())); } fn Tan(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.tan(try args[0].toNumber())); } fn Atan(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len == 1) { return lola.runtime.Value.initNumber( std.math.atan(try args[0].toNumber()), ); } else if (args.len == 2) { return lola.runtime.Value.initNumber(std.math.atan2( f64, try args[0].toNumber(), try args[1].toNumber(), )); } else { return error.InvalidArgs; } } fn Sqrt(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.sqrt(try args[0].toNumber())); } fn Pow(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 2) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.pow( f64, try args[0].toNumber(), try args[1].toNumber(), )); } fn Log(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len == 1) { return lola.runtime.Value.initNumber( std.math.log10(try args[0].toNumber()), ); } else if (args.len == 2) { return lola.runtime.Value.initNumber(std.math.log( f64, try args[1].toNumber(), try args[0].toNumber(), )); } else { return error.InvalidArgs; } } fn Exp(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initNumber(std.math.exp(try args[0].toNumber())); } fn Timestamp(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 0) return error.InvalidArgs; return lola.runtime.Value.initNumber(@intToFloat(f64, milliTimestamp()) / 1000.0); } fn TypeOf(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; return lola.runtime.Value.initString(allocator, switch (args[0]) { .void => "void", .boolean => "boolean", .string => "string", .number => "number", .object => "object", .array => "array", .enumerator => "enumerator", }); } fn ToString(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; var str = try std.fmt.allocPrint(allocator, "{}", .{args[0]}); return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned(allocator, str)); } fn HasFunction(env: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); switch (args.len) { 1 => { var name = try args[0].toString(); return lola.runtime.Value.initBoolean(env.functions.get(name) != null); }, 2 => { var obj = try args[0].toObject(); var name = try args[1].toString(); const maybe_method = try env.objectPool.getMethod(obj, name); return lola.runtime.Value.initBoolean(maybe_method != null); }, else => return error.InvalidArgs, } } fn Serialize(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; const value = args[0]; var string_buffer = std.ArrayList(u8).init(allocator); defer string_buffer.deinit(); try value.serialize(string_buffer.writer()); return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned(allocator, string_buffer.toOwnedSlice())); } fn Deserialize(env: *lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) !lola.runtime.Value { const allocator = context.get(std.mem.Allocator); if (args.len != 1) return error.InvalidArgs; const serialized_string = try args[0].toString(); var stream = std.io.fixedBufferStream(serialized_string); return try lola.runtime.Value.deserialize(stream.reader(), allocator); } };
src/library/libraries/stdlib.zig
const std = @import("std"); // Compile time regular expressions for zig // by alexnask // https://github.com/alexnask/ctregex.zig fn utf16leCharSequenceLength(first_char: u16) !u2 { const c0: u21 = first_char; if (first_char & ~@as(u21, 0x03ff) == 0xd800) { return 2; } else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) { return error.UnexpectedSecondSurrogateHalf; } return 1; } fn utf16leDecode(chars: []const u16) !u21 { const c0: u21 = chars[0]; if (c0 & ~@as(u21, 0x03ff) == 0xd800) { const c1: u21 = chars[1]; if (c1 & ~@as(u21, 0x03ff) != 0xdc00) return error.ExpectedSecondSurrogateHalf; return 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff)); } else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) { return error.UnexpectedSecondSurrogateHalf; } else { return c0; } } fn ctUtf8EncodeChar(comptime codepoint: u21) []const u8 { var buf: [4]u8 = undefined; return buf[0 .. std.unicode.utf8Encode(codepoint, &buf) catch unreachable]; } fn checkAscii(comptime codepoint: u21) void { if (codepoint > 127) @compileError("Cannot match character '" ++ ctUtf8EncodeChar(codepoint) ++ "' in ascii mode."); } fn charLenInEncoding(comptime codepoint: u21, comptime encoding: Encoding) usize { switch (encoding) { .ascii => { checkAscii(codepoint); return 1; }, .utf8 => return std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable, .utf16le => return if (codepoint < 0x10000) 1 else 2, .codepoint => return 1, } } fn ctEncode(comptime str: []const u21, comptime encoding: Encoding) []const encoding.CharT() { if (encoding == .codepoint) return str; var len: usize = 0; for (str) |c| len += charLenInEncoding(c, encoding); var result: [len]encoding.CharT() = undefined; var idx: usize = 0; for (str) |c| { switch (encoding) { .ascii => { result[idx] = @truncate(u8, c); idx += 1; }, .utf8 => idx += std.unicode.utf8Encode(c, result[idx..]) catch unreachable, .utf16le => { const utf8_c = ctUtf8EncodeChar(c); idx += std.unicode.utf8ToUtf16Le(result[idx..], utf8_c) catch unreachable; }, .codepoint => unreachable, } } return &result; } fn ctIntStr(comptime int: anytype) []const u8 { var buf: [16]u8 = undefined; return std.fmt.bufPrint(&buf, "{}", .{int}) catch unreachable; } /// Regex grammar /// ``` /// root ::= expr? /// expr ::= subexpr ('|' expr)? /// subexpr ::= atom ('*' | '+' | '?' | ('{' digit+ (',' (digit+)?)? '}'))? subexpr? /// atom ::= grouped | brackets | '.' | char_class | '\' special | '\' | rest_char /// grouped ::= '(' ('?' (':' | ('<' ascii_ident '>'))? expr ')' /// brackets ::= '[' '^'? (brackets_rule)+ ']' /// brackets_rule ::= brackets_atom | brackets_atom '-' brackets_atom /// brackets_atom ::= ('\' special_brackets | '\' | rest_brackets)+ /// special_brackets ::= '-' | ']' | '^' /// rest_brackets ::= <char>-special_brackets /// special ::= '.' | '[' | ']'| '(' | ')' | '|' | '*' | '+' | '?' | '^' | '{' | '}' /// rest_char ::= <char>-special /// char_class ::= '\d' | '\s' /// ``` const RegexParser = struct { iterator: std.unicode.Utf8Iterator, captures: []const *const Grouped = &[0]*const Grouped{}, curr_capture: usize = 0, fn init(comptime source: []const u8) RegexParser { const view = comptime std.unicode.Utf8View.initComptime(source); return .{ .iterator = comptime view.iterator(), }; } fn parse(comptime source: []const u8) ?ParseResult { var parser = RegexParser.init(source); return parser.parseRoot(); } fn skipWhitespace(comptime parser: *RegexParser) void { while (parser.iterator.i < parser.iterator.bytes.len and (parser.iterator.bytes[parser.iterator.i] == ' ' or parser.iterator.bytes[parser.iterator.i] == '\t')) : (parser.iterator.i += 1) {} } fn peek(comptime parser: *RegexParser) ?u21 { if (parser.atEnd()) return null; const curr_i = parser.iterator.i; const next = parser.iterator.nextCodepoint() orelse @compileError("Incomplete codepoint at the end of the regex string"); parser.iterator.i = curr_i; return next; } fn peekOneOf(comptime parser: *RegexParser, chars: anytype) ?u21 { const c = parser.peek() orelse return null; for (chars) |candidate| { if (c == candidate) return c; } return null; } fn atEnd(comptime parser: RegexParser) bool { return parser.iterator.i >= parser.iterator.bytes.len; } fn consumeNotOneOf(comptime parser: *RegexParser, chars: anytype) ?u21 { const c = parser.peek() orelse return null; for (chars) |candidate| { if (c == candidate) return null; } return parser.iterator.nextCodepoint().?; } fn consumeOneOf(comptime parser: *RegexParser, chars: anytype) ?u21 { const c = parser.peek() orelse return null; for (chars) |candidate| { if (c == candidate) { return parser.iterator.nextCodepoint().?; } } return null; } fn consumeChar(comptime parser: *RegexParser, char: u21) bool { const c = parser.peek() orelse return false; if (c == char) { _ = parser.iterator.nextCodepoint().?; return true; } return false; } fn raiseError(comptime parser: *RegexParser, comptime fmt: []const u8, args: anytype) void { var start_idx: usize = 0; while (parser.iterator.i - start_idx >= 40) { start_idx += std.unicode.utf8ByteSequenceLength(parser.iterator.bytes[start_idx]) catch unreachable; } var start_spaces: usize = 0; { var idx: usize = start_idx; while (idx < parser.iterator.i) { const n = std.unicode.utf8ByteSequenceLength(parser.iterator.bytes[idx]) catch unreachable; idx += n; if (n > 1) { start_spaces += 2; } else { start_spaces += 1; } } } var end_idx: usize = parser.iterator.i; while (end_idx - parser.iterator.i <= 40 and end_idx < parser.iterator.bytes.len) { end_idx += std.unicode.utf8ByteSequenceLength(parser.iterator.bytes[end_idx]) catch unreachable; } const line_prefix = if (start_idx == 0) "\n" else "\n[...] "; const line_suffix = if (end_idx == parser.iterator.bytes.len) "\n" else " [...]\n"; const ArgTuple = struct { tuple: anytype = .{}, }; var arg_list = ArgTuple{}; for (args) |arg| { if (@TypeOf(arg) == ?u21) { if (arg) |cp| { arg_list.tuple = arg_list.tuple ++ .{ctUtf8EncodeChar(cp)}; } else { arg_list.tuple = arg_list.tuple ++ .{"null"}; } } else if (@TypeOf(arg) == u21) { arg_list.tuple = arg_list.tuple ++ .{ctUtf8EncodeChar(arg)}; } else { arg_list.tuple = arg_list.tuple ++ .{arg}; } } var error_buf: [128]u8 = undefined; const error_slice = std.fmt.bufPrint(&error_buf, "error: {}: " ++ fmt, .{parser.iterator.i - 1} ++ arg_list.tuple) catch unreachable; @compileError("\n" ++ error_slice ++ line_prefix ++ parser.iterator.bytes[start_idx..end_idx] ++ line_suffix ++ " " ** (start_spaces + line_prefix.len - 2) ++ "^"); } const ParseResult = struct { root: Expr, captures: []const *const Grouped, }; // root ::= expr? fn parseRoot(comptime parser: *RegexParser) ?ParseResult { comptime { if (parser.parseExpr()) |expr| { if (!parser.atEnd()) parser.raiseError("Invalid regex, stopped parsing here", .{}); return ParseResult{ .root = expr, .captures = parser.captures }; } return null; } } // expr ::= subexpr ('|' expr)? fn parseExpr(comptime parser: *RegexParser) ?Expr { const sub_expr = parser.parseSubExpr() orelse return null; parser.skipWhitespace(); if (parser.consumeChar('|')) { const rhs = parser.parseExpr() orelse parser.raiseError("Expected expression after '|'", .{}); return Expr{ .lhs = sub_expr, .rhs = &rhs }; } return Expr{ .lhs = sub_expr, .rhs = null }; } const modifiers = .{ '*', '+', '?' }; const special_chars = .{ '.', '[', ']', '(', ')', '|', '*', '+', '?', '^', '{', '}' }; // subexpr ::= atom ('*' | '+' | '?' | ('{' digit+ (',' (digit+)?)? '}'))? subexpr? fn parseSubExpr(comptime parser: *RegexParser) ?SubExpr { const atom = parser.parseAtom() orelse return null; parser.skipWhitespace(); var lhs = SubExpr{ .atom = .{ .data = atom } }; if (parser.consumeOneOf(modifiers)) |mod| { lhs.atom.mod = .{ .char = mod }; parser.skipWhitespace(); } else if (parser.consumeChar('{')) { parser.skipWhitespace(); const min_reps = parser.parseNaturalNum(); parser.skipWhitespace(); if (parser.consumeChar(',')) { parser.skipWhitespace(); const max_reps = if (parser.maybeParseNaturalNum()) |reps| block: { if (reps <= min_reps) parser.raiseError("Expected repetition upper bound to be greater or equal to {}", .{min_reps}); break :block reps; } else 0; lhs.atom.mod = .{ .repetitions_range = .{ .min = min_reps, .max = max_reps, }, }; } else { if (min_reps == 0) parser.raiseError("Exactly zero repetitions requested...", .{}); lhs.atom.mod = .{ .exact_repetitions = min_reps, }; } parser.skipWhitespace(); if (!parser.consumeChar('}')) parser.raiseError("Expected closing '}' after repetition modifier", .{}); } if (parser.parseSubExpr()) |rhs| { const old_lhs = lhs; return SubExpr{ .concat = .{ .lhs = &old_lhs, .rhs = &rhs } }; } return lhs; } // atom ::= grouped | brackets | '.' | char_class | '\' special | '\' | rest_char fn parseAtom(comptime parser: *RegexParser) ?Atom { parser.skipWhitespace(); if (parser.parseGrouped()) |grouped| { return Atom{ .grouped = grouped }; } if (parser.parseBrackets()) |brackets| { return Atom{ .brackets = brackets }; } if (parser.consumeChar('.')) { return Atom.any; } var str: []const u21 = &[0]u21{}; // char_class | ('\' special | '\\' | rest_char)+ if (parser.consumeChar('\\')) block: { // char_class := '\d' | '\s' if (parser.consumeOneOf(char_classes)) |class| { return Atom{ .char_class = class }; } // special := '.' | '[' | ']'| '(' | ')' | '|' | '*' | '+' | '?' | '^' | '{' | '}' if (parser.consumeOneOf(special_chars ++ .{ ' ', '\t', '\\' })) |c| { str = str ++ &[1]u21{c}; break :block; } parser.raiseError("Invalid character '{}' after escape \\", .{parser.peek()}); } charLoop: while (true) { parser.skipWhitespace(); if (parser.consumeChar('\\')) { if (parser.consumeOneOf(special_chars ++ .{ ' ', '\t', '\\' })) |c| { str = str ++ &[1]u21{c}; continue :charLoop; } if (parser.peekOneOf(char_classes) != null) { // We know the backslash is 1 byte long // So we can safely do this parser.iterator.i -= 1; break :charLoop; } parser.raiseError("Invalid character '{}' after escape \\", .{parser.peek()}); } else if (parser.peekOneOf(modifiers ++ .{'{'}) != null) { if (str.len == 1) return Atom{ .literal = str }; if (str.len == 0) parser.raiseError("Stray modifier character '{}' applies to no expression", .{parser.peek()}); parser.iterator.i -= std.unicode.utf8CodepointSequenceLength(str[str.len - 1]) catch unreachable; return Atom{ .literal = str[0 .. str.len - 1] }; } // rest_char := <char>-special str = str ++ &[1]u21{parser.consumeNotOneOf(special_chars) orelse break :charLoop}; } if (str.len == 0) return null; return Atom{ .literal = str }; } fn parseAsciiIdent(comptime parser: *RegexParser) []const u8 { var c = parser.peek() orelse parser.raiseError("Expected ascii identifier", .{}); if (c > 127) parser.raiseError("Expected ascii character in identifier, got '{}'", .{c}); if (c != '_' and !std.ascii.isAlpha(@truncate(u8, c))) { parser.raiseError("Identifier must start with '_' or a letter, got '{}''", .{c}); } var res: []const u8 = &[1]u8{@truncate(u8, parser.iterator.nextCodepoint() orelse unreachable)}; readChars: while (true) { c = parser.peek() orelse break :readChars; if (c > 127 or (c != '_' and !std.ascii.isAlNum(@truncate(u8, c)))) break :readChars; res = res ++ &[1]u8{@truncate(u8, parser.iterator.nextCodepoint() orelse unreachable)}; } return res; } fn parseNaturalNum(comptime parser: *RegexParser) usize { return parser.maybeParseNaturalNum() orelse parser.raiseError("Expected natural number", .{}); } fn maybeParseNaturalNum(comptime parser: *RegexParser) ?usize { var c = parser.peek() orelse return null; if (c > 127 or !std.ascii.isDigit(@truncate(u8, c))) return null; var res: usize = (parser.iterator.nextCodepoint() orelse unreachable) - '0'; readChars: while (true) { c = parser.peek() orelse break :readChars; if (c > 127 or !std.ascii.isDigit(@truncate(u8, c))) break :readChars; res = res * 10 + ((parser.iterator.nextCodepoint() orelse unreachable) - '0'); } return res; } // grouped := '(' expr ')' fn parseGrouped(comptime parser: *RegexParser) ?Grouped { if (!parser.consumeChar('(')) return null; parser.skipWhitespace(); var grouped_expr = Grouped{ .capture_info = .{ .idx = parser.curr_capture, .name = null }, .expr = undefined }; if (parser.consumeChar('?')) { parser.skipWhitespace(); if (parser.consumeChar(':')) { grouped_expr.capture_info = null; } else if (parser.consumeChar('<')) { // TODO Support unicode names? // TODO Check for name redefinition grouped_expr.capture_info.?.name = parser.parseAsciiIdent(); if (!parser.consumeChar('>')) parser.raiseError("Expected > after grouped expression name", .{}); } else { parser.raiseError("Expected : or < after ? at the start of a grouped expression.", .{}); } } const expr = parser.parseExpr() orelse parser.raiseError("Expected expression after '('", .{}); parser.skipWhitespace(); if (!parser.consumeChar(')')) parser.raiseError("Expected ')' after expression", .{}); grouped_expr.expr = &expr; if (grouped_expr.capture_info != null) { parser.captures = parser.captures ++ &[1]*const Grouped{&grouped_expr}; parser.curr_capture += 1; } return grouped_expr; } // brackets ::= '[' '^'? (brackets_rule)+ ']' fn parseBrackets(comptime parser: *RegexParser) ?Brackets { if (!parser.consumeChar('[')) return null; parser.skipWhitespace(); const is_exclusive = parser.consumeChar('^'); if (is_exclusive) parser.skipWhitespace(); var brackets = Brackets{ .rules = &[1]Brackets.Rule{ parser.parseBracketsRule() orelse parser.raiseError("Expected at least one bracket rule", .{}), }, .is_exclusive = is_exclusive, }; while (parser.parseBracketsRule()) |rule| { brackets.rules = brackets.rules ++ &[1]Brackets.Rule{rule}; parser.skipWhitespace(); } if (!parser.consumeChar(']')) parser.raiseError("Missing matching closing bracket", .{}); return brackets; } // brackets_rule ::= brackets_atom | brackets_atom '-' brackets_atom // brackets_atom := '\' special_brackets | '\\' | rest_brackets // special_brackets := '-' | ']' // rest_brackets := <char>-special_brackets fn parseBracketsRule(comptime parser: *RegexParser) ?Brackets.Rule { const special_brackets = .{ '-', ']', '^' }; const first_char = if (parser.consumeChar('\\')) block: { if (parser.consumeOneOf(special_brackets ++ .{ ' ', '\t', '\\' })) |char| { break :block char; } else if (parser.consumeOneOf(char_classes)) |char| { return Brackets.Rule{ .char_class = char }; } parser.raiseError("Invalid character '{}' after escape \\", .{parser.peek()}); } else parser.consumeNotOneOf(special_brackets) orelse return null; parser.skipWhitespace(); if (parser.consumeChar('-')) { parser.skipWhitespace(); const second_char = if (parser.consumeChar('\\')) block: { if (parser.consumeOneOf(special_brackets ++ .{ ' ', '\t', '\\' })) |char| { break :block char; } parser.raiseError("Invalid character '{}' after escape \\", .{parser.peek()}); } else parser.consumeNotOneOf(special_brackets) orelse parser.raiseError("Expected a valid character after - in bracket rule, got character '{}'", .{c}); if (first_char >= second_char) { parser.raiseError("Invalid range '{}-{}', start should be smaller than end", .{ first_char, second_char }); } // TODO Check if the char is already in some other rule and error? return Brackets.Rule{ .range = .{ .start = first_char, .end = second_char } }; } return Brackets.Rule{ .char = first_char }; } const SubExpr = union(enum) { atom: struct { data: Atom, mod: union(enum) { char: u8, exact_repetitions: usize, repetitions_range: struct { min: usize, /// Zero for max means unbounded max: usize, }, none, } = .none, }, concat: struct { lhs: *const SubExpr, rhs: *const SubExpr, }, fn ctStr(comptime self: SubExpr) []const u8 { switch (self) { .atom => |atom| { const atom_str = atom.data.ctStr(); switch (atom.mod) { .none => {}, .exact_repetitions => |reps| return atom_str ++ "{" ++ ctIntStr(reps) ++ "}", .repetitions_range => |range| return atom_str ++ "{" ++ ctIntStr(range.min) ++ if (range.max == 0) ",<inf>}" else (", " ++ ctIntStr(range.max) ++ "}"), .char => |c| return atom_str ++ &[1]u8{c}, } return atom_str; }, .concat => |concat| { return concat.lhs.ctStr() ++ " " ++ concat.rhs.ctStr(); }, } return ""; } fn minLen(comptime self: SubExpr, comptime encoding: Encoding) usize { switch (self) { .atom => |atom| { const atom_min_len = atom.data.minLen(encoding); switch (atom.mod) { .char => |c| if (c == '*' or c == '?') return 0, .exact_repetitions => |reps| return reps * atom_min_len, .repetitions_range => |range| return range.min * atom_min_len, .none => {}, } return atom_min_len; }, .concat => |concat| return concat.lhs.minLen(encoding) + concat.rhs.minLen(encoding), } } }; const char_classes = .{ 'd', 's' }; fn charClassToString(class: u21) []const u8 { return switch (class) { 'd' => "<digit>", 's' => "<whitespace>", else => unreachable, }; } fn charClassMinLen(comptime class: u21, comptime encoding: Encoding) usize { _ = class; _ = encoding; return 1; } const Expr = struct { lhs: SubExpr, rhs: ?*const Expr, fn ctStr(comptime self: Expr) []const u8 { var str: []const u8 = self.lhs.ctStr(); if (self.rhs) |rhs| { str = str ++ " | " ++ rhs.ctStr(); } return str; } fn minLen(comptime self: Expr, comptime encoding: Encoding) usize { const lhs_len = self.lhs.minLen(encoding); if (self.rhs) |rhs| { const rhs_len = rhs.minLen(encoding); return std.math.min(lhs_len, rhs_len); } return lhs_len; } }; const Atom = union(enum) { grouped: Grouped, brackets: Brackets, any, char_class: u21, literal: []const u21, fn ctStr(comptime self: Atom) []const u8 { return switch (self) { .grouped => |grouped| grouped.ctStr(), .brackets => |bracks| bracks.ctStr(), .any => "<any_char>", .char_class => |class| charClassToString(class), .literal => |codepoint_str| block: { var str: []const u8 = "literal<"; for (codepoint_str) |codepoint| { str = str ++ ctUtf8EncodeChar(codepoint); } break :block str ++ ">"; }, }; } fn minLen(comptime self: Atom, comptime encoding: Encoding) usize { return switch (self) { .grouped => |grouped| grouped.minLen(encoding), .brackets => |brackets| brackets.minLen(encoding), .any => 1, .char_class => |class| charClassMinLen(class, encoding), .literal => |codepoint_str| block: { var len: usize = 0; for (codepoint_str) |cp| { len += charLenInEncoding(cp, encoding); } break :block len; }, }; } }; const Grouped = struct { expr: *const Expr, capture_info: ?struct { idx: usize, name: ?[]const u8, }, fn ctStr(comptime self: Grouped) []const u8 { const str = "(" ++ self.expr.ctStr() ++ ")"; if (self.capture_info) |info| { return "capture<" ++ (if (info.name) |n| n ++ ", " else "") ++ str ++ ">"; } return str; } fn minLen(comptime self: Grouped, comptime encoding: Encoding) usize { return self.expr.minLen(encoding); } }; const Brackets = struct { is_exclusive: bool, rules: []const Rule, const Rule = union(enum) { char: u21, range: struct { start: u21, end: u21, }, char_class: u21, }; fn ctStr(comptime self: Brackets) []const u8 { var str: []const u8 = "["; if (self.is_exclusive) str = str ++ "<not> "; for (self.rules) |rule, idx| { if (idx > 0) str = str ++ " "; str = str ++ switch (rule) { .char => |c| ctUtf8EncodeChar(c), .range => |r| ctUtf8EncodeChar(r.start) ++ "-" ++ ctUtf8EncodeChar(r.end), .char_class => |class| charClassToString(class), }; } return str ++ "]"; } fn minLen(comptime self: Brackets, comptime encoding: Encoding) usize { if (self.is_exclusive) return 1; var min_len: usize = std.math.maxInt(usize); for (self.rules) |rule| { var curr_len: usize = switch (rule) { .char => |c| charLenInEncoding(c, encoding), .range => |range| charLenInEncoding(range.start, encoding), .char_class => |class| charClassMinLen(class, encoding), }; if (curr_len < min_len) min_len = curr_len; if (min_len == 1) return 1; } return min_len; } }; }; pub const Encoding = enum { ascii, utf8, utf16le, codepoint, pub fn CharT(self: Encoding) type { return switch (self) { .ascii, .utf8 => u8, .utf16le => u16, .codepoint => u21, }; } }; inline fn readOneChar(comptime options: MatchOptions, str: []const options.encoding.CharT()) !@TypeOf(str) { switch (options.encoding) { .ascii, .codepoint => return str[0..1], .utf8 => return str[0..try std.unicode.utf8ByteSequenceLength(str[0])], .utf16le => return str[0..try utf16leCharSequenceLength(str[0])], } } inline fn inCharClass(comptime class: u21, cp: u21) bool { switch (class) { 'd' => return cp >= '0' and cp <= '9', 's' => { // TODO Include same chars as PCRE return cp == ' ' or cp == '\t'; }, else => unreachable, } } inline fn readCharClass(comptime class: u21, comptime options: MatchOptions, str: []const options.encoding.CharT()) ?@TypeOf(str) { switch (class) { 'd' => { switch (options.encoding) { .ascii, .utf8 => return if (std.ascii.isDigit(str[0])) str[0..1] else null, .codepoint, .utf16le => return if (str[0] >= '0' and str[0] <= '9') str[0..1] else null, } }, 's' => { // TODO Include same chars as PCRE return if (str[0] == ' ' or str[0] == '\t') str[0..1] else null; }, else => unreachable, } } inline fn matchAtom(comptime atom: RegexParser.Atom, comptime options: MatchOptions, str: []const options.encoding.CharT(), result: anytype) !?@TypeOf(str) { const min_len = comptime atom.minLen(options.encoding); if (str.len < min_len) return null; switch (atom) { .grouped => |grouped| { const ret = (try matchExpr(grouped.expr.*, options, str, result)) orelse return null; if (grouped.capture_info) |info| { result.captures[info.idx] = ret; } return ret; }, .any => return try readOneChar(options, str), .char_class => |class| return readCharClass(class, options, str), .literal => |lit| { const encoded_lit = comptime ctEncode(lit, options.encoding); if (std.mem.eql(options.encoding.CharT(), encoded_lit, str[0..encoded_lit.len])) { return str[0..encoded_lit.len]; } return null; }, .brackets => |brackets| { var this_slice: @TypeOf(str) = undefined; const this_cp: u21 = switch (options.encoding) { .codepoint, .ascii => block: { this_slice = str[0..1]; break :block str[0]; }, .utf8 => block: { this_slice = str[0..try std.unicode.utf8ByteSequenceLength(str[0])]; break :block try std.unicode.utf8Decode(this_slice); }, .utf16le => block: { this_slice = str[0..try utf16leCharSequenceLength(str[0])]; break :block try utf16leDecode(this_slice); }, }; inline for (brackets.rules) |rule| { switch (rule) { .char => |c| { if (c == this_cp) return if (brackets.is_exclusive) null else this_slice; }, .range => |range| { if (options.encoding == .ascii) { checkAscii(range.start); checkAscii(range.end); } if (this_cp >= range.start and this_cp <= range.end) return if (brackets.is_exclusive) null else this_slice; }, .char_class => |class| if (inCharClass(class, this_cp)) return if (brackets.is_exclusive) null else this_slice, } } return if (brackets.is_exclusive) try readOneChar(options, str) else null; }, } } inline fn matchSubExpr(comptime sub_expr: RegexParser.SubExpr, comptime options: MatchOptions, str: []const options.encoding.CharT(), result: anytype) !?@TypeOf(str) { const min_len = comptime sub_expr.minLen(options.encoding); if (str.len < min_len) return null; switch (sub_expr) { .atom => |atom| { switch (atom.mod) { .none => return try matchAtom(atom.data, options, str, result), .char => |c| switch (c) { // TODO Abstract this somehow? '*' => { if (try matchAtom(atom.data, options, str, result)) |ret_slice| { var curr_slice: @TypeOf(str) = str[0..ret_slice.len]; while (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } return curr_slice; } else { return str[0..0]; } }, '+' => { const ret_slice = (try matchAtom(atom.data, options, str, result)) orelse return null; var curr_slice: @TypeOf(str) = str[0..ret_slice.len]; while (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } return curr_slice; }, '?' => { return (try matchAtom(atom.data, options, str, result)) orelse str[0..0]; }, else => unreachable, }, .exact_repetitions => |reps| { var curr_slice: @TypeOf(str) = str[0..0]; // TODO Using an inline while here crashes the compiler in codegen var curr_rep: usize = reps; while (curr_rep > 0) : (curr_rep -= 1) { if (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } else return null; } return curr_slice; }, .repetitions_range => |range| { var curr_slice: @TypeOf(str) = str[0..0]; // Do minimum reps // TODO Using an inline while here crashes the compiler in codegen var curr_rep: usize = 0; while (curr_rep < range.min) : (curr_rep += 1) { if (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } else return null; } // 0 maximum reps means keep going on forever if (range.max == 0) { while (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } } else { // TODO Using an inline while here crashes the compiler in codegen var curr_additional_rep: usize = 0; _ = curr_additional_rep; // ??? while (curr_rep < range.max) : (curr_rep += 1) { if (try matchAtom(atom.data, options, str[curr_slice.len..], result)) |matched_slice| { curr_slice = str[0 .. matched_slice.len + curr_slice.len]; } else return curr_slice; } } return curr_slice; }, } }, .concat => |concat| { if (try matchSubExpr(concat.lhs.*, options, str, result)) |lhs_slice| { if (try matchSubExpr(concat.rhs.*, options, str[lhs_slice.len..], result)) |rhs_slice| { return str[0 .. lhs_slice.len + rhs_slice.len]; } } return null; }, } return null; } inline fn matchExpr(comptime expr: RegexParser.Expr, comptime options: MatchOptions, str: []const options.encoding.CharT(), result: anytype) !?@TypeOf(str) { const min_len = comptime expr.minLen(options.encoding); if (str.len < min_len) return null; if (try matchSubExpr(expr.lhs, options, str, result)) |lhs_slice| { return lhs_slice; } if (expr.rhs) |rhs| { if (try matchExpr(rhs.*, options, str, result)) |rhs_slice| { return rhs_slice; } } return null; } pub const MatchOptions = struct { encoding: Encoding = .utf8, }; pub fn MatchResult(comptime regex: []const u8, comptime options: MatchOptions) type { const CharT = options.encoding.CharT(); if (comptime RegexParser.parse(regex)) |parsed| { const capture_len = parsed.captures.len; comptime var capture_names: [capture_len]?[]const u8 = undefined; for (parsed.captures) |capt, idx| { if (capt.capture_info) |info| { capture_names[idx] = info.name; } } return struct { const Self = @This(); slice: []const CharT, captures: [capture_len]?[]const CharT = [1]?[]const CharT{null} ** capture_len, inline fn resetCaptures(self: *Self) void { self.captures = [1]?[]const CharT{null} ** capture_len; } pub usingnamespace if (capture_len != 0) struct { pub fn capture(self: Self, comptime name: []const u8) ?[]const CharT { inline for (capture_names) |maybe_name, curr_idx| { if (maybe_name) |curr_name| { if (comptime std.mem.eql(u8, name, curr_name)) return self.captures[curr_idx]; } } @compileError("No capture named '" ++ name ++ "'"); } } else struct {}; }; } return void; } pub fn match(comptime regex: []const u8, comptime options: MatchOptions, str: []const options.encoding.CharT()) !?MatchResult(regex, options) { if (comptime RegexParser.parse(regex)) |parsed| { var result: MatchResult(regex, options) = .{ .slice = undefined, }; if (try matchExpr(parsed.root, options, str, &result)) |slice| { // TODO More than just complete matches. if (slice.len != str.len) return null; result.slice = slice; return result; } return null; } return {}; } pub fn search(comptime regex: []const u8, comptime options: MatchOptions, str: []const options.encoding.CharT()) !?MatchResult(regex, options) { if (comptime RegexParser.parse(regex)) |parsed| { var result: MatchResult(regex, options) = .{ .slice = undefined, }; const min_len = comptime parsed.root.minLen(options.encoding); if (str.len < min_len) return null; // TODO Better strategy. var start_idx: usize = 0; while (start_idx <= (str.len - min_len)) : (start_idx += 1) { if (matchExpr(parsed.root, options, str[start_idx..], &result) catch |err| { if (options.encoding == .utf8 and err == error.Utf8InvalidStartByte) continue; if (options.encoding == .utf16le and err == error.UnexpectedSecondSurrogateHalf) continue; return err; }) |slice| { result.slice = slice; return result; } result.resetCaptures(); } return null; } return {}; } // TODO findAll, etc. // TODO Convert to DFA when we can (otherwise some mix of DFA + DFS?) // TODO More features, aim for PCRE compatibility // TODO Add an ignoreUnicodeErrros option
src/ctregex.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const common = @import("common.zig"); const instruction_ = @import("../instruction.zig"); const Op = instruction_.Op; const Addressing = instruction_.Addressing; const Instruction = instruction_.Instruction; const opToString = instruction_.opToString; const console_ = @import("../console.zig"); const Config = console_.Config; const Console = console_.Console; const Cart = @import("../cart.zig").Cart; const Ppu = @import("../ppu.zig").Ppu; const Apu = @import("../apu.zig").Apu; const Controller = @import("../controller.zig").Controller; pub fn Cpu(comptime config: Config) type { return struct { const Self = @This(); reg: common.Registers, mem: Memory(config), ppu: *Ppu(config), apu: *Apu(config), cycles: usize = 0, pub fn init(console: *Console(config)) Self { return Self{ .reg = common.Registers.startup(), .mem = Memory(config).zeroes(&console.cart, &console.ppu, &console.apu, &console.controller), .ppu = &console.ppu, .apu = &console.apu, }; } pub fn deinit(_: Self) void {} pub fn reset(self: *Self) void { self.reg.pc = self.mem.readWord(0xfffc); std.log.debug("PC set to {x:0>4}", .{self.reg.pc}); } pub fn setIrqSource(self: *Self, comptime _: []const u8) void { if (self.reg.getFlag("I")) { return; } self.pushStack(@truncate(u8, self.reg.pc >> 8)); self.pushStack(@truncate(u8, self.reg.pc)); self.pushStack(self.reg.p | 0b0010_0000); self.reg.setFlag("I", true); self.reg.pc = self.mem.readWord(0xfffe); } pub fn clearIrqSource(_: *Self, comptime _: []const u8) void {} pub fn setNmi(self: *Self) void { self.pushStack(@truncate(u8, self.reg.pc >> 8)); self.pushStack(@truncate(u8, self.reg.pc)); self.pushStack(self.reg.p | 0b0010_0000); self.reg.setFlag("I", true); self.reg.pc = self.mem.readWord(0xfffa); } fn dma(self: *Self, addr_high: u8) void { const oam_addr = self.ppu.reg.oam_addr; var i: usize = 0; while (i < 256) : (i += 1) { const oam_i: u8 = oam_addr +% @truncate(u8, i); self.ppu.mem.oam[oam_i] = self.mem.read((@as(u16, addr_high) << 8) | @truncate(u8, i)); self.apu.runCycle(); self.ppu.runCycle(); self.ppu.runCycle(); self.ppu.runCycle(); self.apu.runCycle(); self.ppu.runCycle(); self.ppu.runCycle(); self.ppu.runCycle(); } } fn pushStack(self: *Self, val: u8) void { self.mem.write(@as(u9, self.reg.s) | 0x100, val); self.reg.s -%= 1; } fn popStack(self: *Self) u8 { self.reg.s +%= 1; return self.mem.read(@as(u9, self.reg.s) | 0x100); } fn branchRelative(self: *Self, condition: bool, jump: u8) void { if (condition) { const prev_pc = self.reg.pc; self.reg.pc = @bitCast(u16, @bitCast(i16, self.reg.pc) +% @bitCast(i8, jump)); self.cycles += @as(usize, 1) + @boolToInt(self.reg.pc & 0xff00 != prev_pc & 0xff00); } } const ValueReference = union(enum) { none, register: *u8, memory: u16, fn peek(ref: @This(), cpu: Cpu(config)) u8 { return switch (ref) { .none => unreachable, .register => |ptr| ptr.*, .memory => |addr| cpu.mem.peek(addr), }; } fn read(ref: @This(), cpu: *Cpu(config)) u8 { return switch (ref) { .none => unreachable, .register => |ptr| ptr.*, .memory => |addr| cpu.mem.read(addr), }; } fn write(ref: @This(), cpu: *Cpu(config), val: u8) void { switch (ref) { .none => unreachable, .register => |ptr| ptr.* = val, .memory => |addr| cpu.mem.write(addr, val), } } }; /// Runs an instruction pub fn runStep(self: *Self) void { const opcode = self.mem.read(self.reg.pc); const instruction = Instruction(.fast).decode(opcode); self.reg.pc +%= 1; const value: ValueReference = blk: { switch (instruction.addressing) { .accumulator => break :blk ValueReference{ .register = &self.reg.a }, .absolute => { break :blk ValueReference{ .memory = self.mem.readWord(self.reg.pc) }; }, .absoluteX => { const val = self.mem.readWord(self.reg.pc); self.cycles += @boolToInt(instruction.var_cycles and (val +% self.reg.x) & 0xff < val & 0xff); break :blk ValueReference{ .memory = val +% self.reg.x }; }, .absoluteY => { const val = self.mem.readWord(self.reg.pc); self.cycles += @boolToInt(instruction.var_cycles and (val +% self.reg.y) & 0xff < val & 0xff); break :blk ValueReference{ .memory = val +% self.reg.y }; }, .immediate => break :blk ValueReference{ .memory = self.reg.pc }, .implied => break :blk .none, .indirect => { const addr_low = self.mem.read(self.reg.pc); const addr_high = @as(u16, self.mem.read(self.reg.pc +% 1)) << 8; const val_low = self.mem.read(addr_high | addr_low); const val_high = self.mem.read(addr_high | (addr_low +% 1)); break :blk ValueReference{ .memory = (@as(u16, val_high) << 8) | val_low }; }, .indirectX => { const zero_page = self.mem.read(self.reg.pc); const val_low = self.mem.read(zero_page +% self.reg.x); const val_high = self.mem.read(zero_page +% self.reg.x +% 1); break :blk ValueReference{ .memory = (@as(u16, val_high) << 8) | val_low }; }, .indirectY => { const zero_page = self.mem.read(self.reg.pc); const val_low = self.mem.read(zero_page); const val_high = self.mem.read(zero_page +% 1); self.cycles += @boolToInt(instruction.var_cycles and (val_low +% self.reg.y) < val_low); break :blk ValueReference{ .memory = ((@as(u16, val_high) << 8) | val_low) +% self.reg.y }; }, .relative => break :blk ValueReference{ .memory = self.reg.pc }, .zeroPage => { const zero_page = self.mem.read(self.reg.pc); break :blk ValueReference{ .memory = zero_page }; }, .zeroPageX => { const zero_page = self.mem.read(self.reg.pc); break :blk ValueReference{ .memory = zero_page +% self.reg.x }; }, .zeroPageY => { const zero_page = self.mem.read(self.reg.pc); break :blk ValueReference{ .memory = zero_page +% self.reg.y }; }, } }; if (@import("build_options").log_step) { self.logInstruction(instruction, value); } switch (instruction.op) { .op_ill => {}, .op_adc => { const original: u8 = value.read(self); const sum: u9 = @as(u9, self.reg.a) + @as(u9, original) + @as(u9, self.reg.getFlags("C")); const sum_u8: u8 = @truncate(u8, sum); const n_flag = sum_u8 & 0x80; const v_flag = (((self.reg.a ^ sum_u8) & (original ^ sum_u8)) & 0x80) >> 1; const z_flag = @as(u8, @boolToInt(sum_u8 == 0)) << 1; const c_flag = @truncate(u8, (sum & 0x100) >> 8); self.reg.setFlags("NVZC", n_flag | v_flag | z_flag | c_flag); self.reg.a = sum_u8; }, .op_and => { self.reg.a &= value.read(self); self.reg.setFlagsNZ(self.reg.a); }, .op_asl => { const val = value.read(self); const new = val << 1; value.write(self, new); self.reg.setFlagsNZ(new); self.reg.setFlag("C", (val & 0x80) != 0); }, .op_bpl => self.branchRelative(!self.reg.getFlag("N"), value.read(self)), .op_bmi => self.branchRelative(self.reg.getFlag("N"), value.read(self)), .op_bvc => self.branchRelative(!self.reg.getFlag("V"), value.read(self)), .op_bvs => self.branchRelative(self.reg.getFlag("V"), value.read(self)), .op_bcc => self.branchRelative(!self.reg.getFlag("C"), value.read(self)), .op_bcs => self.branchRelative(self.reg.getFlag("C"), value.read(self)), .op_bne => self.branchRelative(!self.reg.getFlag("Z"), value.read(self)), .op_beq => self.branchRelative(self.reg.getFlag("Z"), value.read(self)), .op_bit => { const mem = value.read(self); const val = self.reg.a & mem; self.reg.setFlags("NVZ", (mem & 0xc0) | @as(u8, @boolToInt(val == 0)) << 1); }, .op_brk => { var push_sp = self.reg.pc +% 1; self.pushStack(@truncate(u8, push_sp >> 8)); self.pushStack(@truncate(u8, push_sp)); self.pushStack(self.reg.p | 0b0011_0000); self.reg.pc = self.mem.readWord(0xfffe); }, .op_clc => self.reg.setFlag("C", false), .op_cld => self.reg.setFlag("D", false), .op_cli => self.reg.setFlag("I", false), .op_clv => self.reg.setFlag("V", false), .op_cmp => { const val = value.read(self); self.reg.setFlagsNZ(self.reg.a -% val); self.reg.setFlag("C", self.reg.a >= val); }, .op_cpx => { const val = value.read(self); self.reg.setFlagsNZ(self.reg.x -% val); self.reg.setFlag("C", self.reg.x >= val); }, .op_cpy => { const val = value.read(self); self.reg.setFlagsNZ(self.reg.y -% val); self.reg.setFlag("C", self.reg.y >= val); }, .op_dec => { const val = value.read(self) -% 1; value.write(self, val); self.reg.setFlagsNZ(val); }, .op_dex => { self.reg.x -%= 1; self.reg.setFlagsNZ(self.reg.x); }, .op_dey => { self.reg.y -%= 1; self.reg.setFlagsNZ(self.reg.y); }, .op_eor => { self.reg.a ^= value.read(self); self.reg.setFlagsNZ(self.reg.a); }, .op_inc => { const val = value.read(self) +% 1; value.write(self, val); self.reg.setFlagsNZ(val); }, .op_inx => { self.reg.x +%= 1; self.reg.setFlagsNZ(self.reg.x); }, .op_iny => { self.reg.y +%= 1; self.reg.setFlagsNZ(self.reg.y); }, .op_jmp => self.reg.pc = value.memory -% 2, .op_jsr => { var push_sp = self.reg.pc +% 1; self.pushStack(@truncate(u8, push_sp >> 8)); self.pushStack(@truncate(u8, push_sp)); self.reg.pc = value.memory -% 2; }, .op_lda => { self.reg.a = value.read(self); self.reg.setFlagsNZ(self.reg.a); }, .op_ldx => { self.reg.x = value.read(self); self.reg.setFlagsNZ(self.reg.x); }, .op_ldy => { self.reg.y = value.read(self); self.reg.setFlagsNZ(self.reg.y); }, .op_lsr => { const val = value.read(self); const new = val >> 1; value.write(self, new); self.reg.setFlagsNZ(new); self.reg.setFlags("C", val & 1); }, .op_nop => {}, .op_ora => { self.reg.a |= value.read(self); self.reg.setFlagsNZ(self.reg.a); }, .op_pha => self.pushStack(self.reg.a), .op_php => self.pushStack(self.reg.p | 0b0011_0000), .op_pla => { self.reg.a = self.popStack(); self.reg.setFlagsNZ(self.reg.a); }, .op_plp => self.reg.p = self.popStack(), .op_rol => { const val = value.read(self); const new = (val << 1) | self.reg.getFlags("C"); value.write(self, new); self.reg.setFlagsNZ(new); self.reg.setFlags("C", (val & 0x80) >> 7); }, .op_ror => { const val = value.read(self); const new = (val >> 1) | (self.reg.getFlags("C") << 7); value.write(self, new); self.reg.setFlagsNZ(new); self.reg.setFlags("C", val & 1); }, .op_rti => { self.reg.p = self.popStack(); const low = self.popStack(); const high = @as(u16, self.popStack()); self.reg.pc = (high << 8) | low; }, .op_rts => { const low = self.popStack(); const high = @as(u16, self.popStack()); self.reg.pc = ((high << 8) | low) +% 1; }, .op_sbc => { const original: u8 = value.read(self); const dif: u9 = @as(u9, self.reg.a) -% @as(u9, original) -% @as(u9, @boolToInt(!self.reg.getFlag("C"))); const dif_u8: u8 = @truncate(u8, dif); const n_flag = dif_u8 & 0x80; const v_flag = (((self.reg.a ^ dif_u8) & (~original ^ dif_u8)) & 0x80) >> 1; const z_flag = @as(u8, @boolToInt(dif_u8 == 0)) << 1; const c_flag = ~@truncate(u1, (dif & 0x100) >> 8); self.reg.setFlags("NVZC", n_flag | v_flag | z_flag | c_flag); self.reg.a = dif_u8; }, .op_sec => self.reg.setFlag("C", true), .op_sed => self.reg.setFlag("D", true), .op_sei => self.reg.setFlag("I", true), .op_sta => value.write(self, self.reg.a), .op_stx => value.write(self, self.reg.x), .op_sty => value.write(self, self.reg.y), .op_tax => { self.reg.x = self.reg.a; self.reg.setFlagsNZ(self.reg.x); }, .op_tay => { self.reg.y = self.reg.a; self.reg.setFlagsNZ(self.reg.y); }, .op_tsx => { self.reg.x = self.reg.s; self.reg.setFlagsNZ(self.reg.x); }, .op_txa => { self.reg.a = self.reg.x; self.reg.setFlagsNZ(self.reg.a); }, .op_txs => self.reg.s = self.reg.x, .op_tya => { self.reg.a = self.reg.y; self.reg.setFlagsNZ(self.reg.a); }, } self.reg.pc +%= instruction.addressing.op_size() - 1; self.cycles += instruction.cycles; var i: usize = 0; while (i < @as(usize, instruction.cycles)) : (i += 1) { common.cpuCycled(self); } } fn logInstruction(self: Self, instruction: Instruction(.fast), value: ValueReference) void { const op_str = opToString(instruction.op); const opcode = self.mem.peek(self.reg.pc -% 1); const low = self.mem.peek(self.reg.pc); const high = self.mem.peek(self.reg.pc +% 1); const address = (@as(u16, high) << 8) | low; std.debug.print("Cycles: {} ", .{self.cycles}); std.debug.print("A: {x:0>2} X: {x:0>2} Y: {x:0>2} P: {x:0>2} S: {x:0>2} PC: {x:0>4}\t", .{ self.reg.a, self.reg.x, self.reg.y, self.reg.p | 0x20, self.reg.s, self.reg.pc -% 1, }); std.debug.print("{x:0>2} {x:0>2} {x:0>2}\t{s} ", .{ opcode, low, high, op_str }); switch (instruction.addressing) { .accumulator => std.debug.print("A", .{}), .absolute => { std.debug.print("${x:0>4} \t; ${0x:0>4} = #${x:0>2}", .{ value.memory, value.peek(self) }); }, .absoluteX => { std.debug.print("${x:0>4},x \t; ${0x:0>4} = #${x:0>2}\tx = #${x:0>2}", .{ value.memory, value.peek(self), self.reg.x, }); }, .absoluteY => { std.debug.print("${x:0>4},y \t; ${0x:0>4} = #${x:0>2}\ty = #${x:0>2}", .{ value.memory, value.peek(self), self.reg.y, }); }, .immediate => std.debug.print("#${x:0>2}", .{low}), .implied => {}, .indirect => { std.debug.print("(${x:0>4}) \t; (${0x:0>4}) = ${x:0>4}", .{ address, value.memory }); }, .indirectX => { std.debug.print("(${x:0>2},x)\t; (${0x:0>4},{x:0>2}) = ${x:0>4} = #${x:0>2}", .{ low, self.reg.x, value.memory, value.peek(self), }); }, .indirectY => { std.debug.print("(${x:0>2}),y\t; (${0x:0>4}),{x:0>2} = ${x:0>4} = #${x:0>2}", .{ low, self.reg.y, value.memory, value.peek(self), }); }, .relative => { const val = value.peek(self); const new_pc = @bitCast(u16, @bitCast(i16, self.reg.pc) +% @bitCast(i8, val) +% 1); std.debug.print("${x:0>2} \t; PC ?= ${x:0>4}", .{ val, new_pc }); }, .zeroPage => { std.debug.print("${x:0>2} \t; ${0x:0>2} = #${x:0>2}", .{ value.memory, value.peek(self) }); }, .zeroPageX => { std.debug.print("${x:0>2},x \t; ${0x:0>2} = #${x:0>2}", .{ value.memory, value.peek(self) }); }, .zeroPageY => { std.debug.print("${x:0>2},y \t; ${0x:0>2} = #${x:0>2}", .{ value.memory, value.peek(self) }); }, } std.debug.print("\n", .{}); } }; } pub fn Memory(comptime config: Config) type { return struct { const Self = @This(); cart: *Cart(config), ppu: *Ppu(config), apu: *Apu(config), controller: *Controller(config.method), ram: [0x800]u8, // TODO: implement non-zero pattern? pub fn zeroes( cart: *Cart(config), ppu: *Ppu(config), apu: *Apu(config), controller: *Controller(config.method), ) Self { return Self{ .cart = cart, .ppu = ppu, .apu = apu, .controller = controller, .ram = [_]u8{0} ** 0x800, }; } pub fn peek(self: Self, addr: u16) u8 { switch (addr) { 0x0000...0x1fff => return self.ram[addr & 0x7ff], 0x2000...0x3fff => return self.ppu.reg.peek(@truncate(u3, addr)), 0x8000...0xffff => return self.cart.peekPrg(addr) orelse 0, else => return 0, } } pub fn read(self: Self, addr: u16) u8 { switch (addr) { 0x0000...0x1fff => return self.ram[addr & 0x7ff], 0x2000...0x3fff => return self.ppu.reg.read(@truncate(u3, addr)), 0x4000...0x4013, 0x4015, 0x4017 => return self.apu.read(@truncate(u5, addr)), 0x4016 => return self.controller.getNextButton(), 0x4020...0xffff => return self.cart.readPrg(addr) orelse 0, else => { //std.log.err("CPU: Unimplemented read memory address ({x:0>4})", .{addr}); return 0; }, } } pub fn readWord(self: Self, addr: u16) u16 { var low = self.read(addr); return (@as(u16, self.read(addr +% 1)) << 8) | low; } pub fn write(self: *Self, addr: u16, val: u8) void { switch (addr) { 0x0000...0x1fff => self.ram[addr & 0x7ff] = val, 0x2000...0x3fff => self.ppu.reg.write(@truncate(u3, addr), val), 0x4000...0x4013, 0x4015, 0x4017 => self.apu.write(@truncate(u5, addr), val), 0x4014 => @fieldParentPtr(Cpu(config), "mem", self).dma(val), 0x4016 => if (val & 1 == 1) { self.controller.strobe(); }, 0x4020...0xffff => return self.cart.writePrg(addr, val), else => { //std.log.err("CPU: Unimplemented write memory address ({x:0>4})", .{addr}); }, } } }; }
src/cpu/fast.zig
const std = @import("std"); const testing = std.testing; const math = std.math; const mem = std.mem; /// Given a type and value, cast the value to the type as c would. pub fn cast(comptime DestType: type, target: anytype) DestType { // this function should behave like transCCast in translate-c, except it's for macros const SourceType = @TypeOf(target); switch (@typeInfo(DestType)) { .Fn => if (@import("builtin").zig_backend == .stage1) return castToPtr(DestType, SourceType, target) else return castToPtr(*const DestType, SourceType, target), .Pointer => return castToPtr(DestType, SourceType, target), .Optional => |dest_opt| { if (@typeInfo(dest_opt.child) == .Pointer) { return castToPtr(DestType, SourceType, target); } else if (@typeInfo(dest_opt.child) == .Fn) { if (@import("builtin").zig_backend == .stage1) return castToPtr(DestType, SourceType, target) else return castToPtr(?*const dest_opt.child, SourceType, target); } }, .Int => { switch (@typeInfo(SourceType)) { .Pointer => { return castInt(DestType, @ptrToInt(target)); }, .Optional => |opt| { if (@typeInfo(opt.child) == .Pointer) { return castInt(DestType, @ptrToInt(target)); } }, .Int => { return castInt(DestType, target); }, else => {}, } }, .Union => |info| { inline for (info.fields) |field| { if (field.field_type == SourceType) return @unionInit(DestType, field.name, target); } @compileError("cast to union type '" ++ @typeName(DestType) ++ "' from type '" ++ @typeName(SourceType) ++ "' which is not present in union"); }, else => {}, } return @as(DestType, target); } fn castInt(comptime DestType: type, target: anytype) DestType { const dest = @typeInfo(DestType).Int; const source = @typeInfo(@TypeOf(target)).Int; if (dest.bits < source.bits) return @bitCast(DestType, @truncate(std.meta.Int(source.signedness, dest.bits), target)) else return @bitCast(DestType, @as(std.meta.Int(source.signedness, dest.bits), target)); } fn castPtr(comptime DestType: type, target: anytype) DestType { const dest = ptrInfo(DestType); const source = ptrInfo(@TypeOf(target)); if (source.is_const and !dest.is_const or source.is_volatile and !dest.is_volatile) return @intToPtr(DestType, @ptrToInt(target)) else if (@typeInfo(dest.child) == .Opaque) // dest.alignment would error out return @ptrCast(DestType, target) else return @ptrCast(DestType, @alignCast(dest.alignment, target)); } fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType { switch (@typeInfo(SourceType)) { .Int => { return @intToPtr(DestType, castInt(usize, target)); }, .ComptimeInt => { if (target < 0) return @intToPtr(DestType, @bitCast(usize, @intCast(isize, target))) else return @intToPtr(DestType, @intCast(usize, target)); }, .Pointer => { return castPtr(DestType, target); }, .Optional => |target_opt| { if (@typeInfo(target_opt.child) == .Pointer) { return castPtr(DestType, target); } }, else => {}, } return @as(DestType, target); } fn ptrInfo(comptime PtrType: type) std.builtin.Type.Pointer { return switch (@typeInfo(PtrType)) { .Optional => |opt_info| @typeInfo(opt_info.child).Pointer, .Pointer => |ptr_info| ptr_info, else => unreachable, }; } test "cast" { var i = @as(i64, 10); try testing.expect(cast(*u8, 16) == @intToPtr(*u8, 16)); try testing.expect(cast(*u64, &i).* == @as(u64, 10)); try testing.expect(cast(*i64, @as(?*align(1) i64, &i)) == &i); try testing.expect(cast(?*u8, 2) == @intToPtr(*u8, 2)); try testing.expect(cast(?*i64, @as(*align(1) i64, &i)) == &i); try testing.expect(cast(?*i64, @as(?*align(1) i64, &i)) == &i); try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(*u32, 4))); try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(?*u32, 4))); try testing.expectEqual(@as(u32, 10), cast(u32, @as(u64, 10))); try testing.expectEqual(@bitCast(i32, @as(u32, 0x8000_0000)), cast(i32, @as(u32, 0x8000_0000))); try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*const u8, 2))); try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*volatile u8, 2))); try testing.expectEqual(@intToPtr(?*anyopaque, 2), cast(?*anyopaque, @intToPtr(*u8, 2))); var foo: c_int = -1; try testing.expect(cast(*anyopaque, -1) == @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -1)))); try testing.expect(cast(*anyopaque, foo) == @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -1)))); try testing.expect(cast(?*anyopaque, -1) == @intToPtr(?*anyopaque, @bitCast(usize, @as(isize, -1)))); try testing.expect(cast(?*anyopaque, foo) == @intToPtr(?*anyopaque, @bitCast(usize, @as(isize, -1)))); const FnPtr = if (@import("builtin").zig_backend == .stage1) ?fn (*anyopaque) void else ?*const fn (*anyopaque) void; try testing.expect(cast(FnPtr, 0) == @intToPtr(FnPtr, @as(usize, 0))); try testing.expect(cast(FnPtr, foo) == @intToPtr(FnPtr, @bitCast(usize, @as(isize, -1)))); } /// Given a value returns its size as C's sizeof operator would. pub fn sizeof(target: anytype) usize { const T: type = if (@TypeOf(target) == type) target else @TypeOf(target); switch (@typeInfo(T)) { .Float, .Int, .Struct, .Union, .Array, .Bool, .Vector => return @sizeOf(T), .Fn => { if (@import("builtin").zig_backend == .stage1) { // sizeof(main) returns 1, sizeof(&main) returns pointer size. // We cannot distinguish those types in Zig, so use pointer size. return @sizeOf(T); } // sizeof(main) in C returns 1 return 1; }, .Null => return @sizeOf(*anyopaque), .Void => { // Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC. return 1; }, .Opaque => { if (T == anyopaque) { // Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC. return 1; } else { @compileError("Cannot use C sizeof on opaque type " ++ @typeName(T)); } }, .Optional => |opt| { if (@typeInfo(opt.child) == .Pointer) { return sizeof(opt.child); } else { @compileError("Cannot use C sizeof on non-pointer optional " ++ @typeName(T)); } }, .Pointer => |ptr| { if (ptr.size == .Slice) { @compileError("Cannot use C sizeof on slice type " ++ @typeName(T)); } // for strings, sizeof("a") returns 2. // normal pointer decay scenarios from C are handled // in the .Array case above, but strings remain literals // and are therefore always pointers, so they need to be // specially handled here. if (ptr.size == .One and ptr.is_const and @typeInfo(ptr.child) == .Array) { const array_info = @typeInfo(ptr.child).Array; if ((array_info.child == u8 or array_info.child == u16) and array_info.sentinel != null and @ptrCast(*const array_info.child, array_info.sentinel.?).* == 0) { // length of the string plus one for the null terminator. return (array_info.len + 1) * @sizeOf(array_info.child); } } // When zero sized pointers are removed, this case will no // longer be reachable and can be deleted. if (@sizeOf(T) == 0) { return @sizeOf(*anyopaque); } return @sizeOf(T); }, .ComptimeFloat => return @sizeOf(f64), // TODO c_double #3999 .ComptimeInt => { // TODO to get the correct result we have to translate // `1073741824 * 4` as `int(1073741824) *% int(4)` since // sizeof(1073741824 * 4) != sizeof(4294967296). // TODO test if target fits in int, long or long long return @sizeOf(c_int); }, else => @compileError("std.meta.sizeof does not support type " ++ @typeName(T)), } } test "sizeof" { const S = extern struct { a: u32 }; const ptr_size = @sizeOf(*anyopaque); try testing.expect(sizeof(u32) == 4); try testing.expect(sizeof(@as(u32, 2)) == 4); try testing.expect(sizeof(2) == @sizeOf(c_int)); try testing.expect(sizeof(2.0) == @sizeOf(f64)); try testing.expect(sizeof(S) == 4); try testing.expect(sizeof([_]u32{ 4, 5, 6 }) == 12); try testing.expect(sizeof([3]u32) == 12); try testing.expect(sizeof([3:0]u32) == 16); try testing.expect(sizeof(&[_]u32{ 4, 5, 6 }) == ptr_size); try testing.expect(sizeof(*u32) == ptr_size); try testing.expect(sizeof([*]u32) == ptr_size); try testing.expect(sizeof([*c]u32) == ptr_size); try testing.expect(sizeof(?*u32) == ptr_size); try testing.expect(sizeof(?[*]u32) == ptr_size); try testing.expect(sizeof(*anyopaque) == ptr_size); try testing.expect(sizeof(*void) == ptr_size); try testing.expect(sizeof(null) == ptr_size); try testing.expect(sizeof("foobar") == 7); try testing.expect(sizeof(&[_:0]u16{ 'f', 'o', 'o', 'b', 'a', 'r' }) == 14); try testing.expect(sizeof(*const [4:0]u8) == 5); try testing.expect(sizeof(*[4:0]u8) == ptr_size); try testing.expect(sizeof([*]const [4:0]u8) == ptr_size); try testing.expect(sizeof(*const *const [4:0]u8) == ptr_size); try testing.expect(sizeof(*const [4]u8) == ptr_size); if (@import("builtin").zig_backend == .stage1) { try testing.expect(sizeof(sizeof) == @sizeOf(@TypeOf(sizeof))); } else if (false) { // TODO try testing.expect(sizeof(&sizeof) == @sizeOf(@TypeOf(&sizeof))); try testing.expect(sizeof(sizeof) == 1); } try testing.expect(sizeof(void) == 1); try testing.expect(sizeof(anyopaque) == 1); } pub const CIntLiteralRadix = enum { decimal, octal, hexadecimal }; fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime radix: CIntLiteralRadix) type { const signed_decimal = [_]type{ c_int, c_long, c_longlong }; const signed_oct_hex = [_]type{ c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong }; const unsigned = [_]type{ c_uint, c_ulong, c_ulonglong }; const list: []const type = if (@typeInfo(SuffixType).Int.signedness == .unsigned) &unsigned else if (radix == .decimal) &signed_decimal else &signed_oct_hex; var pos = mem.indexOfScalar(type, list, SuffixType).?; while (pos < list.len) : (pos += 1) { if (number >= math.minInt(list[pos]) and number <= math.maxInt(list[pos])) { return list[pos]; } } @compileError("Integer literal is too large"); } /// Promote the type of an integer literal until it fits as C would. pub fn promoteIntLiteral( comptime SuffixType: type, comptime number: comptime_int, comptime radix: CIntLiteralRadix, ) PromoteIntLiteralReturnType(SuffixType, number, radix) { return number; } test "promoteIntLiteral" { const signed_hex = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .hexadecimal); try testing.expectEqual(c_uint, @TypeOf(signed_hex)); if (math.maxInt(c_longlong) == math.maxInt(c_int)) return; const signed_decimal = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .decimal); const unsigned = promoteIntLiteral(c_uint, math.maxInt(c_uint) + 1, .hexadecimal); if (math.maxInt(c_long) > math.maxInt(c_int)) { try testing.expectEqual(c_long, @TypeOf(signed_decimal)); try testing.expectEqual(c_ulong, @TypeOf(unsigned)); } else { try testing.expectEqual(c_longlong, @TypeOf(signed_decimal)); try testing.expectEqual(c_ulonglong, @TypeOf(unsigned)); } } /// Convert from clang __builtin_shufflevector index to Zig @shuffle index /// clang requires __builtin_shufflevector index arguments to be integer constants. /// negative values for `this_index` indicate "don't care" so we arbitrarily choose 0 /// clang enforces that `this_index` is less than the total number of vector elements /// See https://ziglang.org/documentation/master/#shuffle /// See https://clang.llvm.org/docs/LanguageExtensions.html#langext-builtin-shufflevector pub fn shuffleVectorIndex(comptime this_index: c_int, comptime source_vector_len: usize) i32 { if (this_index <= 0) return 0; const positive_index = @intCast(usize, this_index); if (positive_index < source_vector_len) return @intCast(i32, this_index); const b_index = positive_index - source_vector_len; return ~@intCast(i32, b_index); } test "shuffleVectorIndex" { const vector_len: usize = 4; try testing.expect(shuffleVectorIndex(-1, vector_len) == 0); try testing.expect(shuffleVectorIndex(0, vector_len) == 0); try testing.expect(shuffleVectorIndex(1, vector_len) == 1); try testing.expect(shuffleVectorIndex(2, vector_len) == 2); try testing.expect(shuffleVectorIndex(3, vector_len) == 3); try testing.expect(shuffleVectorIndex(4, vector_len) == -1); try testing.expect(shuffleVectorIndex(5, vector_len) == -2); try testing.expect(shuffleVectorIndex(6, vector_len) == -3); try testing.expect(shuffleVectorIndex(7, vector_len) == -4); } /// Constructs a [*c] pointer with the const and volatile annotations /// from SelfType for pointing to a C flexible array of ElementType. pub fn FlexibleArrayType(comptime SelfType: type, ElementType: type) type { switch (@typeInfo(SelfType)) { .Pointer => |ptr| { return @Type(.{ .Pointer = .{ .size = .C, .is_const = ptr.is_const, .is_volatile = ptr.is_volatile, .alignment = @alignOf(ElementType), .address_space = .generic, .child = ElementType, .is_allowzero = true, .sentinel = null, } }); }, else => |info| @compileError("Invalid self type \"" ++ @tagName(info) ++ "\" for flexible array getter: " ++ @typeName(SelfType)), } } test "Flexible Array Type" { const Container = extern struct { size: usize, }; try testing.expectEqual(FlexibleArrayType(*Container, c_int), [*c]c_int); try testing.expectEqual(FlexibleArrayType(*const Container, c_int), [*c]const c_int); try testing.expectEqual(FlexibleArrayType(*volatile Container, c_int), [*c]volatile c_int); try testing.expectEqual(FlexibleArrayType(*const volatile Container, c_int), [*c]const volatile c_int); } /// C `%` operator for signed integers /// C standard states: "If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a" /// The quotient is not representable if denominator is zero, or if numerator is the minimum integer for /// the type and denominator is -1. C has undefined behavior for those two cases; this function has safety /// checked undefined behavior pub fn signedRemainder(numerator: anytype, denominator: anytype) @TypeOf(numerator, denominator) { std.debug.assert(@typeInfo(@TypeOf(numerator, denominator)).Int.signedness == .signed); if (denominator > 0) return @rem(numerator, denominator); return numerator - @divTrunc(numerator, denominator) * denominator; } pub const Macros = struct { pub fn U_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_uint, n, .decimal)) { return promoteIntLiteral(c_uint, n, .decimal); } fn L_SUFFIX_ReturnType(comptime number: anytype) type { switch (@TypeOf(number)) { comptime_int => return @TypeOf(promoteIntLiteral(c_long, number, .decimal)), comptime_float => return c_longdouble, else => @compileError("Invalid value for L suffix"), } } pub fn L_SUFFIX(comptime number: anytype) L_SUFFIX_ReturnType(number) { switch (@TypeOf(number)) { comptime_int => return promoteIntLiteral(c_long, number, .decimal), comptime_float => @compileError("TODO: c_longdouble initialization from comptime_float not supported"), else => @compileError("Invalid value for L suffix"), } } pub fn UL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulong, n, .decimal)) { return promoteIntLiteral(c_ulong, n, .decimal); } pub fn LL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_longlong, n, .decimal)) { return promoteIntLiteral(c_longlong, n, .decimal); } pub fn ULL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulonglong, n, .decimal)) { return promoteIntLiteral(c_ulonglong, n, .decimal); } pub fn F_SUFFIX(comptime f: comptime_float) f32 { return @as(f32, f); } pub fn WL_CONTAINER_OF(ptr: anytype, sample: anytype, comptime member: []const u8) @TypeOf(sample) { return @fieldParentPtr(@TypeOf(sample.*), member, ptr); } /// A 2-argument function-like macro defined as #define FOO(A, B) (A)(B) /// could be either: cast B to A, or call A with the value B. pub fn CAST_OR_CALL(a: anytype, b: anytype) switch (@typeInfo(@TypeOf(a))) { .Type => a, .Fn => |fn_info| fn_info.return_type orelse void, else => |info| @compileError("Unexpected argument type: " ++ @tagName(info)), } { switch (@typeInfo(@TypeOf(a))) { .Type => return cast(a, b), .Fn => return a(b), else => unreachable, // return type will be a compile error otherwise } } pub inline fn DISCARD(x: anytype) void { _ = x; } }; test "Macro suffix functions" { try testing.expect(@TypeOf(Macros.F_SUFFIX(1)) == f32); try testing.expect(@TypeOf(Macros.U_SUFFIX(1)) == c_uint); if (math.maxInt(c_ulong) > math.maxInt(c_uint)) { try testing.expect(@TypeOf(Macros.U_SUFFIX(math.maxInt(c_uint) + 1)) == c_ulong); } if (math.maxInt(c_ulonglong) > math.maxInt(c_ulong)) { try testing.expect(@TypeOf(Macros.U_SUFFIX(math.maxInt(c_ulong) + 1)) == c_ulonglong); } try testing.expect(@TypeOf(Macros.L_SUFFIX(1)) == c_long); if (math.maxInt(c_long) > math.maxInt(c_int)) { try testing.expect(@TypeOf(Macros.L_SUFFIX(math.maxInt(c_int) + 1)) == c_long); } if (math.maxInt(c_longlong) > math.maxInt(c_long)) { try testing.expect(@TypeOf(Macros.L_SUFFIX(math.maxInt(c_long) + 1)) == c_longlong); } try testing.expect(@TypeOf(Macros.UL_SUFFIX(1)) == c_ulong); if (math.maxInt(c_ulonglong) > math.maxInt(c_ulong)) { try testing.expect(@TypeOf(Macros.UL_SUFFIX(math.maxInt(c_ulong) + 1)) == c_ulonglong); } try testing.expect(@TypeOf(Macros.LL_SUFFIX(1)) == c_longlong); try testing.expect(@TypeOf(Macros.ULL_SUFFIX(1)) == c_ulonglong); } test "WL_CONTAINER_OF" { const S = struct { a: u32 = 0, b: u32 = 0, }; var x = S{}; var y = S{}; var ptr = Macros.WL_CONTAINER_OF(&x.b, &y, "b"); try testing.expectEqual(&x, ptr); } test "CAST_OR_CALL casting" { var arg = @as(c_int, 1000); var casted = Macros.CAST_OR_CALL(u8, arg); try testing.expectEqual(cast(u8, arg), casted); const S = struct { x: u32 = 0, }; var s = S{}; var casted_ptr = Macros.CAST_OR_CALL(*u8, &s); try testing.expectEqual(cast(*u8, &s), casted_ptr); } test "CAST_OR_CALL calling" { const Helper = struct { var last_val: bool = false; fn returnsVoid(val: bool) void { last_val = val; } fn returnsBool(f: f32) bool { return f > 0; } fn identity(self: c_uint) c_uint { return self; } }; Macros.CAST_OR_CALL(Helper.returnsVoid, true); try testing.expectEqual(true, Helper.last_val); Macros.CAST_OR_CALL(Helper.returnsVoid, false); try testing.expectEqual(false, Helper.last_val); try testing.expectEqual(Helper.returnsBool(1), Macros.CAST_OR_CALL(Helper.returnsBool, @as(f32, 1))); try testing.expectEqual(Helper.returnsBool(-1), Macros.CAST_OR_CALL(Helper.returnsBool, @as(f32, -1))); try testing.expectEqual(Helper.identity(@as(c_uint, 100)), Macros.CAST_OR_CALL(Helper.identity, @as(c_uint, 100))); }
lib/std/zig/c_translation.zig
const std = @import("std"); const Builder = std.build.Builder; const Pkg = std.build.Pkg; const string = []const u8; const alloc = std.heap.page_allocator; const fmt_description = "Run the {s} example"; const Pkgs = struct { const QObject: Pkg = .{ .name = "QObject", .path = "src/QObject.zig", }; const QMetaObject: Pkg = .{ .name = "QMetaObject", .path = "src/QMetaObject.zig", }; const QVariant: Pkg = .{ .name = "QVariant", .path = "src/QVariant.zig", }; const QQmlContext: Pkg = .{ .name = "QQmlContext", .path = "src/QQmlContext.zig", }; const QMetaType: Pkg = .{ .name = "QMetaType", .path = "src/QMetaType.zig", }; const QUrl: Pkg = .{ .name = "QUrl", .path = "src/QUrl.zig", }; const QQmlApplicationEngine: Pkg = .{ .name = "QQmlApplicationEngine", .path = "src/QQmlApplicationEngine.zig", }; const QGuiApplication: Pkg = .{ .name = "QGuiApplication", .path = "src/QGuiApplication.zig", }; const DOtherSide: Pkg = .{ .name = "DOtherSide", .path = "src/DOtherSide.zig", }; }; pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); try cmakeBuild(b); // Original examples try makeExample(b, mode, target, "examples/animated.zig", "Animated"); try makeExample(b, mode, target, "examples/hello.zig", "Hello"); // More examples try makeExample(b, mode, target, "examples/button.zig", "Button"); // Copypasta from the Go QML eamples https://github.com/go-qml/qml/tree/v1/examples try makeExample(b, mode, target, "examples/particle.zig", "Particle"); try makeExample(b, mode, target, "examples/layouts.zig", "Layouts"); try makeExample(b, mode, target, "examples/splitview.zig", "Splits"); try makeExample(b, mode, target, "examples/tableview.zig", "Tables"); // Cloned simple examples from the Qml doco try makeExample(b, mode, target, "examples/cells.zig", "Cells"); } fn makeExample(b: *Builder, mode: std.builtin.Mode, target: std.zig.CrossTarget, src: string, name: string) !void { //Example 1 const example = b.addExecutable(name, src); if (mode != .Debug) { example.strip = true; } example.setBuildMode(mode); example.setTarget(target); example.addPackage(Pkgs.QObject); example.addPackage(Pkgs.QVariant); example.addPackage(Pkgs.QUrl); example.addPackage(Pkgs.QMetaType); example.addPackage(Pkgs.QMetaObject); example.addPackage(Pkgs.QQmlContext); example.addPackage(Pkgs.QGuiApplication); example.addPackage(Pkgs.QQmlApplicationEngine); example.addPackage(Pkgs.DOtherSide); example.addLibPath("deps/dotherside/build/lib"); example.linkSystemLibraryName("DOtherSide"); example.linkLibC(); example.install(); const run_cmd = example.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } var descr = std.fmt.allocPrintZ(alloc, fmt_description, .{name}) catch unreachable; const run_step = b.step(name, descr); run_step.dependOn(&run_cmd.step); } fn cmakeBuild(b: *Builder) !void { //CMake builds - DOtherSide build const DOtherSide_configure = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", "deps/dotherside/build", "-S", "deps/dotherside", "-DCMAKE_BUILD_TYPE=Release", }); const DOtherSide_build = b.addSystemCommand(&[_][]const u8{ "cmake", "--build", "deps/dotherside/build", "-j", }); // Note: If it is not necessary to compile DOtherSide library, please comment on these two lines. try DOtherSide_configure.step.make(); try DOtherSide_build.step.make(); }
build.zig
const std = @import("std"); usingnamespace @import("vector3.zig"); usingnamespace @import("quaternion.zig"); pub fn Matrix4Fn(comptime T: type) type { if (@typeInfo(T) != .Float) { @compileError("Matrix4 not implemented for " ++ @typeName(T) ++ " must use float type"); } return struct { const Self = @This(); const Vec3Type = Vector3Fn(T); const QuatType = QuaternionFn(T); data: [4]std.meta.Vector(4, T), pub const zero = Self{ .data = .{ .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, }, }; pub const identity = Self{ .data = .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 0, 0, 0, 1 }, }, }; pub fn translation(vec: Vec3Type) Self { return Self{ .data = .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ vec.data[0], vec.data[1], vec.data[2], 1 }, }, }; } pub fn rotation(quat: QuatType) Self { var data = quat.data; var qxx = data[1] * data[1]; var qyy = data[2] * data[2]; var qzz = data[3] * data[3]; var qxz = data[1] * data[3]; var qxy = data[1] * data[2]; var qyz = data[2] * data[3]; var qwx = data[0] * data[1]; var qwy = data[0] * data[2]; var qwz = data[0] * data[3]; var result = Self.identity; //TODO: transpose this? result.data[0][0] = 1 - 2 * (qyy + qzz); result.data[0][1] = 2 * (qxy + qwz); result.data[0][2] = 2 * (qxz - qwy); result.data[1][0] = 2 * (qxy - qwz); result.data[1][1] = 1 - 2 * (qxx + qzz); result.data[1][2] = 2 * (qyz + qwx); result.data[2][0] = 2 * (qxz + qwy); result.data[2][1] = 2 * (qyz - qwx); result.data[2][2] = 1 - 2 * (qxx + qyy); return result; } pub fn scale(vec: Vec3Type) Self { return Self{ .data = .{ .{ vec.data[0], 0, 0, 0 }, .{ 0, vec.data[1], 0, 0 }, .{ 0, 0, vec.data[2], 0 }, .{ 0, 0, 0, 1 }, }, }; } pub fn model(p: Vec3Type, r: QuatType, s: Vec3Type) Self { return Self.translation(p).mul(Self.rotation(r)).mul(Self.scale(s)); } pub fn orthographic_lh_zo(left: T, right: T, bottom: T, top: T, near: T, far: T) Self { return Self{ .data = .{ .{ 2 / (right - left), 0, 0, 0 }, .{ 0, 2 / (top - bottom), 0, 0 }, .{ 0, 0, 1 / (far - near), 0 }, .{ -(right + left) / (right - left), -(top + bottom) / (top - bottom), -near / (far - near), 1, }, }, }; } pub fn perspective_lh_zo(fovy: T, aspect_ratio: T, near: T, far: T) Self { var tan_half_fov = std.math.tan(fovy / 2); return Self{ .data = .{ .{ 1 / (aspect_ratio * tan_half_fov), 0, 0, 0 }, .{ 0, 1 / tan_half_fov, 0, 0 }, .{ 0, 0, far / (far - near), 1 }, .{ 0, 0, -(far * near) / (far - near), 1 }, }, }; } pub fn view_lh(pos: Vec3Type, rot: QuatType) Self { var r = rot.rotate(Vec3Type.xaxis).normalize(); var u = rot.rotate(Vec3Type.yaxis).normalize(); var f = rot.rotate(Vec3Type.zaxis).normalize(); return Self{ .data = .{ .{ r.data[0], u.data[0], f.data[0], 0 }, .{ r.data[1], u.data[1], f.data[1], 0 }, .{ r.data[2], u.data[2], f.data[2], 0 }, .{ -r.dot(pos), -u.dot(pos), -f.dot(pos), 1 }, }, }; } pub fn transpose(mat: Self) Self { var m = mat.data; return Self{ .data = .{ .{ m[0][0], m[1][0], m[2][0], m[3][0] }, .{ m[0][1], m[1][1], m[2][1], m[3][1] }, .{ m[0][2], m[1][2], m[2][2], m[3][2] }, .{ m[0][3], m[1][3], m[2][3], m[3][3] }, }, }; } pub fn mul(left: Self, right: Self) Self { var mat = Self.zero; var columns: usize = 0; while (columns < 4) : (columns += 1) { var rows: usize = 0; while (rows < 4) : (rows += 1) { var sum: T = 0.0; var current_mat: usize = 0; while (current_mat < 4) : (current_mat += 1) { sum += left.data[current_mat][rows] * right.data[columns][current_mat]; } mat.data[columns][rows] = sum; } } return mat; //TODO: fix this // var lhs = self.data; // var rhs = other.transpose().data; // var result = Self.zero; // var row: u8 = 0; // while (row < 4) : (row += 1) { // var column: u8 = 0; // while (column < 4) : (column += 1) { // //Force to product to slice // var products: [4]f32 = lhs[row] * rhs[column]; // //TODO: unroll or use SIMD? // for (products) |value| { // result.data[row][column] += value; // } // } // } // return result; } }; } //TODO: Make tests for these? // var identity = Matrix4.identity; // var scale = Matrix4.scale(Vector3.new(1, 2, 3)); // var translation = Matrix4.translation(Vector3.new(1, 2, 3)); // var rotation = Matrix4.rotation(Quaternion.axisAngle(Vector3.yaxis, 3.1415926 / 4.0)); // var multiply = translation.mul(scale).mul(rotation); // std.log.info("Identity : {d:0.2}", .{identity.data}); // std.log.info("scale : {d:0.2}", .{scale.data}); // std.log.info("translation: {d:0.2}", .{translation.data}); // std.log.info("rotation : {d:0.2}", .{rotation.data}); // std.log.info("multiply : {d:0.2}", .{multiply.data});
src/linear_math/matrix4.zig
const std = @import("std"); const Tokenizer = @import("tokenizer.zig"); pub const Token = Tokenizer.Token; const TokenIterator = Tokenizer.TokenList.Iterator; const OOMhandler = Tokenizer.OOMhandler; const algods = @import("algods"); const compiler = @import("main.zig"); const types = @import("type.zig"); const Type = types.Type; pub const Parser = @This(); const AstNodeKind = enum { NK_ADD, // + NK_SUB, // - NK_MUL, // * NK_DIV, // / NK_NEG, // Negative -Num NK_NUM, // Integer NK_EQ, // == NK_NE, // != NK_LT, // < NK_GT, // > NK_LE, // <= NK_GE, // >= NK_EXPR_STMT, // Expression statement .ie stmt separated by commas NK_ASSIGN, // = NK_VAR, // Variable NK_RETURN, // return statement NK_BLOCK, // { block } NK_IF, // if NK_LOOP, // for or while NK_ADDR, // unary & operator .ie address operator NK_DEREF, //unary * operator .ie pointer dereference }; // Local variable pub const Variable = struct { name: []const u8, // Variable name rbp_offset: usize, // Offset from RBP }; //I use a SinglyCircularList because appending doesn't require node traversal pub const ExprList = algods.linked_list.SinglyCircularList(*AstTree.AstNode); pub const VarList = algods.linked_list.SinglyCircularList(Variable); pub const Function = struct { body: ExprList, local_variables: VarList, stack_size: usize, }; //if statement const Conditonal = struct { if_expr: *AstTree.AstNode, then_branch: *AstTree.AstNode, else_branch: ?*AstTree.AstNode = null, }; //for or while loop const Loop = struct { init: ?*AstTree.AstNode = null, condition: ?*AstTree.AstNode = null, increment: ?*AstTree.AstNode = null, body: *AstTree.AstNode, }; pub const AstTree = struct { // AST node type pub const AstNode = struct { kind: AstNodeKind, // AstNode kind lhs: ?*AstNode = null, // Left-hand side rhs: ?*AstNode = null, // Right-hand side token: Token, //A representative Token of the Node to improve error messages type: ?Type = null, //Type, e.g. int or pointer to int value: Value = .{ .no_value = true }, const Value = union(enum) { number: u64, // value of integer if kind == NK_NUM identifier: Variable, // Used if node is an Identifier Token .ie kind == ND_VAR block: ExprList, // Block { ... } if_statement: Conditonal, //if statement loop: Loop, //for or while loop no_value: bool, }; }; allocator: std.mem.Allocator, // All local variable instances created during parsing are accumulated to this list. local_variables: VarList, local_variables_rbp_offset: usize = 0, pub fn init(allocator: std.mem.Allocator) AstTree { return .{ .allocator = allocator, .local_variables = VarList.init(allocator) }; } fn createAstNode(self: *AstTree, kind: AstNodeKind, token: Token) *AstNode { var new_ast_node = self.allocator.create(AstNode) catch OOMhandler(); //default initialize default fileds from undefined values new_ast_node.lhs = null; new_ast_node.rhs = null; new_ast_node.type = null; new_ast_node.value = AstNode.Value{ .no_value = true }; new_ast_node.kind = kind; new_ast_node.token = token; return new_ast_node; } // In C, `+` operator is overloaded to perform the pointer arithmetic. // If p is a pointer, p+n adds not n but sizeof(*p)*n to the value of p, // so that p+n points to the location n elements (not bytes) ahead of p. // In other words, we need to scale an integer value before adding to a // pointer value. This function takes care of the scaling. fn addExpression(self: *AstTree, lhs: *AstNode, rhs: *AstNode, token: Token) *AstNode { types.addType(lhs); types.addType(rhs); //num + num if (lhs.type.?.isInt() and rhs.type.?.isInt()) { return self.binaryExpression(.NK_ADD, lhs, rhs, token); } // Canonicalize `num + ptr` to `ptr + num`. if (!lhs.type.?.isPtr() and rhs.type.?.isPtr()) { std.mem.swap(AstNode, lhs, rhs); } if (lhs.type.?.isPtr() and rhs.type.?.isInt()) { //ptr + num //number is scaled by 8 .ie assuming 64bit const new_rhs = self.binaryExpression(.NK_MUL, rhs, self.number(8, token), token); //.NK_SUB because we need to subtract the scaled number for the stack pointer return self.binaryExpression(.NK_SUB, lhs, new_rhs, token); } //&num + &num is not allowed // if (lhs.type.?.isPtr() and rhs.type.?.isPtr()) reportParserError(token, "invalid operands. expected &lhs + num but found &lhs + &num", .{}); } // Like `+`, `-` is overloaded for the pointer type. fn subExpression(self: *AstTree, lhs: *AstNode, rhs: *AstNode, token: Token) *AstNode { types.addType(lhs); types.addType(rhs); //num - num if (lhs.type.?.isInt() and rhs.type.?.isInt()) { return self.binaryExpression(.NK_SUB, lhs, rhs, token); } //ptr - num if (lhs.type.?.isPtr() and rhs.type.?.isInt()) { var scaled_rhs = self.binaryExpression(.NK_MUL, rhs, self.number(8, token), token); types.addType(scaled_rhs); var current_lhs = self.binaryExpression(.NK_ADD, lhs, scaled_rhs, token); current_lhs.type = lhs.type; return current_lhs; } // ptr - ptr, which returns how many elements are between the two. if (lhs.type.?.isPtr() and rhs.type.?.isPtr()) { //sub rhs from lhs because rhs is usually at a higher address than lhs //so we don't get negative values var bytes_btw_lhs_rhs = self.binaryExpression(.NK_SUB, rhs, lhs, token); bytes_btw_lhs_rhs.type = types.int_ty; return self.binaryExpression(.NK_DIV, bytes_btw_lhs_rhs, self.number(8, token), token); } reportParserError(token, "invalid subtraction operands", .{}); } fn binaryExpression(self: *AstTree, kind: AstNodeKind, lhs: *AstNode, rhs: *AstNode, token: Token) *AstNode { var binaray_node = self.createAstNode(kind, token); binaray_node.rhs = rhs; binaray_node.lhs = lhs; return binaray_node; } fn number(self: *AstTree, value: u64, token: Token) *AstNode { var num_terminal_node = self.createAstNode(.NK_NUM, token); num_terminal_node.value = AstNode.Value{ .number = value }; return num_terminal_node; } fn unaryExpression(self: *AstTree, kind: AstNodeKind, unary_expr: *AstNode, token: Token) *AstNode { var unary_node = self.createAstNode(kind, token); unary_node.rhs = unary_expr; return unary_node; } fn blockExpression(self: *AstTree, kind: AstNodeKind, expression_list: ExprList, token: Token) *AstNode { var compound_node = self.createAstNode(kind, token); compound_node.value = AstNode.Value{ .block = expression_list }; return compound_node; } fn conditionExpression(self: *AstTree, kind: AstNodeKind, conditional_expression: Conditonal, token: Token) *AstNode { var if_statement = self.createAstNode(kind, token); if_statement.value = AstNode.Value{ .if_statement = conditional_expression }; return if_statement; } fn loopExpression(self: *AstTree, kind: AstNodeKind, loop: Loop, token: Token) *AstNode { var loop_statment = self.createAstNode(kind, token); loop_statment.value = AstNode.Value{ .loop = loop }; return loop_statment; } fn nullBlock(self: *AstTree, token: Token) *AstNode { var null_block = self.createAstNode(.NK_BLOCK, token); null_block.value = AstNode.Value{ .block = ExprList.init(self.allocator) }; return null_block; } // Assign offsets to local variables. fn nextlvarOffsets(self: *AstTree) usize { const byte_size = 8; const offset = new_offset: { self.local_variables_rbp_offset += byte_size; break :new_offset self.local_variables_rbp_offset; }; return offset; } fn findVariable(self: AstTree, variable_name: []const u8) ?Variable { // Traverse forwards. var it = self.local_variables.iterator(); while (it.next()) |variable| { if (std.mem.eql(u8, variable_name, variable.name)) { return variable; } } return null; } fn createVariable(self: *AstTree, name: []const u8) Variable { return Variable{ .name = name, .rbp_offset = offset: { if (self.findVariable(name)) |variable_exist| { break :offset variable_exist.rbp_offset; } else { break :offset self.nextlvarOffsets(); } } }; } fn variableAssignment(self: *AstTree, variable: Variable, token: Token) *AstNode { var variable_node = self.createAstNode(.NK_VAR, token); variable_node.value = AstNode.Value{ .identifier = variable }; return variable_node; } }; nodes: AstTree, tokenizer: TokenIterator, statements: ExprList, pub fn init(allocator: std.mem.Allocator, tokens: TokenIterator) Parser { return .{ .nodes = AstTree.init(allocator), .tokenizer = tokens, .statements = ExprList.init(allocator), }; } // Round up `num` to the nearest multiple of `alignment`. For instance, // align_to(5, 8) returns 8 and align_to(11, 8) returns 16. fn alignTo(num: usize, alignment: usize) usize { // return (num + alignment - 1) / alignment * alignment; return std.mem.alignForward(num, alignment); } //program = stmt pub fn parse(self: *Parser) Function { //we call nextToken to move from end to first token if (self.expectToken(self.nextToken(), "{")) { self.statements = self.compoundStmt(self.currentToken()); } else { reportParserError(self.currentToken(), "expected program to start with {{ but found {s}", .{self.currentToken().value.ident_name}); } //After parsing the stream of tokens EOF must be the last token std.debug.assert(self.currentToken().kind == .TK_EOF); return .{ .body = self.statements, .local_variables = self.nodes.local_variables, .stack_size = alignTo(self.nodes.local_variables_rbp_offset, 16), }; } //compound-stmt = stmt* "}" fn compoundStmt(self: *Parser, token: Token) ExprList { var compound_stmt = ExprList.init(self.nodes.allocator); _ = token; while (!isEqual(self.currentToken(), "}")) { const statement = self.stmt(self.currentToken()); compound_stmt.append(statement) catch OOMhandler(); } if (!self.expectToken(self.currentToken(), "}")) { reportParserError(self.currentToken(), "expected block to end with }} but found {s}", .{self.currentToken().value.ident_name}); } return compound_stmt; } /// stmt = "return" expr ";" | "{" compound-stmt | /// | "if" "(" expr ")" stmt ("else" stmt )? /// | "for" "(" expr_stmt expr? ";" expr ")" stmt /// | "while" "(" expr ")" stmt /// | expr_stmt fn stmt(self: *Parser, token: Token) *AstTree.AstNode { const start = token; if (isEqual(token, "return")) { const return_statement = self.nodes.unaryExpression(.NK_RETURN, self.expr(self.nextToken()), start); if (!self.expectToken(self.currentToken(), ";")) { reportParserError(self.currentToken(), "expected statement to end with ';' but found {s}", .{self.currentToken().value.ident_name}); } return return_statement; } if (isEqual(token, "{")) { const compound_stmt = self.nodes.blockExpression(.NK_BLOCK, self.compoundStmt(self.nextToken()), start); return compound_stmt; } if (isEqual(token, "if")) { if (self.expectToken(self.nextToken(), "(")) { const if_expr = self.expr(self.currentToken()); if (self.expectToken(self.currentToken(), ")")) { const then_branch = self.stmt(self.currentToken()); if (isEqual(self.currentToken(), "else")) { const else_branch = self.stmt(self.nextToken()); const if_statement = self.nodes.conditionExpression(.NK_IF, .{ .if_expr = if_expr, .then_branch = then_branch, .else_branch = else_branch }, start); return if_statement; } else { const if_statement = self.nodes.conditionExpression(.NK_IF, .{ .if_expr = if_expr, .then_branch = then_branch }, start); return if_statement; } } else { reportParserError(self.currentToken(), "expected ) after if ( expr but found {s}", .{self.currentToken().value.ident_name}); } } else { reportParserError(self.currentToken(), "expected ( after if keyword but found {s}", .{self.currentToken().value.ident_name}); } } if (isEqual(token, "for")) { var for_loop: Loop = Loop{ .init = undefined, .body = undefined }; if (self.expectToken(self.nextToken(), "(")) { const init_statment = self.exprStmt(self.currentToken()); for_loop.init = init_statment; } else { reportParserError(self.currentToken(), "expected '(' after 'for' like 'for (' but found 'for {s}'", .{self.currentToken().value.ident_name}); } //if not for(init;;) .ie for (init;expr;) if (!isEqual(self.currentToken(), ";")) { const conditon_expr = self.expr(self.currentToken()); for_loop.condition = conditon_expr; } if (!self.expectToken(self.currentToken(), ";")) { reportParserError(self.currentToken(), "expected ';' after 'condition' like 'for (init; condition ;' but found 'for (init; condition {s}'", .{self.currentToken().value.ident_name}); } if (!isEqual(self.currentToken(), ")")) { const increment_expr = self.expr(self.currentToken()); for_loop.increment = increment_expr; } if (!self.expectToken(self.currentToken(), ")")) { reportParserError(self.currentToken(), "expected ')' after 'inc' like 'for (init; condition ; inc )' but found 'for (init; condition ; inc {s}'", .{self.currentToken().value.ident_name}); } const loop_body = self.stmt(self.currentToken()); for_loop.body = loop_body; return self.nodes.loopExpression(.NK_LOOP, for_loop, start); } if (isEqual(token, "while")) { var while_loop: Loop = Loop{ .condition = undefined, .body = undefined }; if (self.expectToken(self.nextToken(), "(")) { const conditon_expr = self.expr(self.currentToken()); while_loop.condition = conditon_expr; } else { reportParserError(self.currentToken(), "expected '(' after 'while' like 'while (' but found 'while {s}'", .{self.currentToken().value.ident_name}); } if (!self.expectToken(self.currentToken(), ")")) { reportParserError(self.currentToken(), "expected ')' after 'condition' like 'while ( condition )' but found 'while (condition {s}'", .{self.currentToken().value.ident_name}); } const while_body = self.stmt(self.currentToken()); while_loop.body = while_body; return self.nodes.loopExpression(.NK_LOOP, while_loop, start); } return self.exprStmt(token); } // expr_stmt = expr? ";" fn exprStmt(self: *Parser, token: Token) *AstTree.AstNode { const start = token; //.ie there is no expr //null block are used in for (;;){stmt} if (isEqual(token, ";")) { //skip the current Token _ = self.nextToken(); return self.nodes.nullBlock(start); } const expr_stmt_node = self.nodes.unaryExpression(.NK_EXPR_STMT, self.expr(token), start); if (!self.expectToken(self.currentToken(), ";")) { reportParserError(self.currentToken(), "expected statement to end with ';' but found {s}", .{self.currentToken().value.ident_name}); } return expr_stmt_node; } // expr = assign fn expr(self: *Parser, token: Token) *AstTree.AstNode { return self.assign(token); } //assign = equality ('=' assign)? fn assign(self: *Parser, token: Token) *AstTree.AstNode { const start = token; const equality_lhs_node = self.equality(token); var assignment_tree_node = equality_lhs_node; if (isEqual(self.currentToken(), "=")) { const assignment_rhs_node = self.assign(self.nextToken()); assignment_tree_node = self.nodes.binaryExpression(.NK_ASSIGN, equality_lhs_node, assignment_rhs_node, start); } return assignment_tree_node; } //equality = relational ("==" relational | "!=" relational)* fn equality(self: *Parser, token: Token) *AstTree.AstNode { const start = token; const equality_lhs_node = self.relational(token); var equality_tree_node = equality_lhs_node; while (true) { if (isEqual(self.currentToken(), "==")) { const equality_rhs_node = self.relational(self.nextToken()); equality_tree_node = self.nodes.binaryExpression(.NK_EQ, equality_lhs_node, equality_rhs_node, start); continue; } if (isEqual(self.currentToken(), "!=")) { const equality_rhs_node = self.relational(self.nextToken()); equality_tree_node = self.nodes.binaryExpression(.NK_NE, equality_lhs_node, equality_rhs_node, start); continue; } return equality_tree_node; } } //relational = add ("<" add | "<=" add | ">" add | ">=" add)* fn relational(self: *Parser, token: Token) *AstTree.AstNode { const start = token; const relational_lhs_node = self.add(token); var relational_tree_node = relational_lhs_node; while (true) { if (isEqual(self.currentToken(), "<")) { const relational_rhs_node = self.add(self.nextToken()); relational_tree_node = self.nodes.binaryExpression(.NK_LT, relational_lhs_node, relational_rhs_node, start); continue; } if (isEqual(self.currentToken(), "<=")) { const relational_rhs_node = self.add(self.nextToken()); relational_tree_node = self.nodes.binaryExpression(.NK_LE, relational_lhs_node, relational_rhs_node, start); continue; } if (isEqual(self.currentToken(), ">")) { const relational_rhs_node = self.add(self.nextToken()); relational_tree_node = self.nodes.binaryExpression(.NK_GT, relational_lhs_node, relational_rhs_node, start); continue; } if (isEqual(self.currentToken(), ">=")) { const relational_rhs_node = self.add(self.nextToken()); relational_tree_node = self.nodes.binaryExpression(.NK_GE, relational_lhs_node, relational_rhs_node, start); continue; } return relational_tree_node; } } /// add = mul ("+" mul | "-" mul) fn add(self: *Parser, token: Token) *AstTree.AstNode { const start = token; const lhs_node = self.mul(token); var next_lhs_node = lhs_node; while (true) { if (isEqual(self.currentToken(), "+")) { const rhs_node = self.mul(self.nextToken()); next_lhs_node = self.nodes.addExpression(next_lhs_node, rhs_node, start); continue; } if (isEqual(self.currentToken(), "-")) { const rhs_node = self.mul(self.nextToken()); next_lhs_node = self.nodes.subExpression(next_lhs_node, rhs_node, start); continue; } return next_lhs_node; } } /// mul = unary ("*" unary | "/" unary)* fn mul(self: *Parser, token: Token) *AstTree.AstNode { const start = token; const lhs_node = self.unary(token); var next_lhs_node = lhs_node; while (true) { if (isEqual(self.currentToken(), "*")) { const rhs_node = self.unary(self.nextToken()); next_lhs_node = self.nodes.binaryExpression(.NK_MUL, next_lhs_node, rhs_node, start); continue; } if (isEqual(self.currentToken(), "/")) { const rhs_node = self.unary(self.nextToken()); next_lhs_node = self.nodes.binaryExpression(.NK_DIV, next_lhs_node, rhs_node, start); continue; } return next_lhs_node; } } /// unary = ('+'|'-'|'*'|'&') unary | primary fn unary(self: *Parser, token: Token) *AstTree.AstNode { const start = token; if (isEqual(token, "+")) { return self.unary(self.nextToken()); } if (isEqual(token, "-")) { return self.nodes.unaryExpression(.NK_NEG, self.unary(self.nextToken()), start); } if (isEqual(token, "*")) { return self.nodes.unaryExpression(.NK_DEREF, self.unary(self.nextToken()), start); } if (isEqual(token, "&")) { return self.nodes.unaryExpression(.NK_ADDR, self.unary(self.nextToken()), start); } return self.primary(token); } // primary = "(" expr ")" | IDENTIFIER | NUM fn primary(self: *Parser, token: Token) *AstTree.AstNode { const start = token; if (isEqual(token, "(")) { const expr_node = self.expr(self.nextToken()); if (!self.expectToken(self.currentToken(), ")")) { reportParserError(self.currentToken(), "expected ) after 'expr' like '( expr )' but found '( expr {}'", .{self.currentToken().value}); } return expr_node; } if (token.kind == .TK_IDENT) { const variable = self.nodes.findVariable(token.value.ident_name) orelse new_variable: { const new_identifier = self.nodes.createVariable(token.value.ident_name); self.nodes.local_variables.append(new_identifier) catch OOMhandler(); break :new_variable new_identifier; }; const identifier_node = self.nodes.variableAssignment(variable, start); _ = self.nextToken(); return identifier_node; } if (token.kind == .TK_NUM) { const num_node = self.nodes.number(token.value.num_value, start); _ = self.nextToken(); return num_node; } reportParserError(token, "Expected an ( expression ) , variable assignment or a number", .{}); } fn reportParserError(token: Token, comptime msg: []const u8, args: anytype) noreturn { const error_msg = "\nInvalid Parse Token '{[token_name]s}' in '{[token_stream]s}' at {[token_location]d}"; const identifier_name = token.value.ident_name; std.log.err(error_msg, .{ .token_name = identifier_name, .token_stream = compiler.TOKEN_STREAM, .token_location = token.location, }); const location_offset = 27; const token_location = location_offset + identifier_name.len + token.location; //add empty spaces till the character where the error starts std.debug.print("{[spaces]s:>[width]}", .{ .spaces = " ", .width = token_location }); const format_msg = "^ " ++ msg ++ "\n"; std.debug.print(format_msg, args); std.process.exit(3); } ///check if current token matches terminal fn isEqual(token: Token, terminal: []const u8) bool { if (token.kind != .TK_NUM) { return std.mem.eql(u8, token.value.ident_name, terminal); } const digit = std.fmt.charToDigit(terminal[0], 10) catch undefined; if (digit == token.value.num_value) { return true; } else { return false; } } ///consumes token if it matches terminal. fn expectToken(self: *Parser, token: Token, terminal: []const u8) bool { if (token.kind != .TK_NUM) { const match = std.mem.eql(u8, token.value.ident_name, terminal); if (match) { _ = self.nextToken(); return true; } else { return false; } } const digit = std.fmt.charToDigit(terminal[0], 10) catch undefined; if (digit == token.value.num_value) { _ = self.nextToken(); return true; } else { return false; } } //look at current token pub fn currentToken(self: *Parser) Token { return self.tokenizer.current(); } //consume next token in the input stream fn nextToken(self: *Parser) Token { return self.tokenizer.next().?; }
src/parser.zig
const std = @import("std"); fn ok(comptime s: []const u8) void { std.debug.assert(std.json.validate(s)); } fn err(comptime s: []const u8) void { std.debug.assert(!std.json.validate(s)); } fn any(comptime s: []const u8) void { std.debug.assert(true); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // Additional tests not part of test JSONTestSuite. test "json.y_trailing_comma_after_empty" { ok( \\{"1":[],"2":{},"3":"4"} ); } //////////////////////////////////////////////////////////////////////////////////////////////////// test "json.y_array_arraysWithSpaces" { ok( \\[[] ] ); } test "json.y_array_empty" { ok( \\[] ); } test "json.y_array_empty-string" { ok( \\[""] ); } test "json.y_array_ending_with_newline" { ok( \\["a"] ); } test "json.y_array_false" { ok( \\[false] ); } test "json.y_array_heterogeneous" { ok( \\[null, 1, "1", {}] ); } test "json.y_array_null" { ok( \\[null] ); } test "json.y_array_with_1_and_newline" { ok( \\[1 \\] ); } test "json.y_array_with_leading_space" { ok( \\ [1] ); } test "json.y_array_with_several_null" { ok( \\[1,null,null,null,2] ); } test "json.y_array_with_trailing_space" { ok("[2] "); } test "json.y_number_0e+1" { ok( \\[0e+1] ); } test "json.y_number_0e1" { ok( \\[0e1] ); } test "json.y_number_after_space" { ok( \\[ 4] ); } test "json.y_number_double_close_to_zero" { ok( \\[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001] ); } test "json.y_number_int_with_exp" { ok( \\[20e1] ); } test "json.y_number" { ok( \\[123e65] ); } test "json.y_number_minus_zero" { ok( \\[-0] ); } test "json.y_number_negative_int" { ok( \\[-123] ); } test "json.y_number_negative_one" { ok( \\[-1] ); } test "json.y_number_negative_zero" { ok( \\[-0] ); } test "json.y_number_real_capital_e" { ok( \\[1E22] ); } test "json.y_number_real_capital_e_neg_exp" { ok( \\[1E-2] ); } test "json.y_number_real_capital_e_pos_exp" { ok( \\[1E+2] ); } test "json.y_number_real_exponent" { ok( \\[123e45] ); } test "json.y_number_real_fraction_exponent" { ok( \\[123.456e78] ); } test "json.y_number_real_neg_exp" { ok( \\[1e-2] ); } test "json.y_number_real_pos_exponent" { ok( \\[1e+2] ); } test "json.y_number_simple_int" { ok( \\[123] ); } test "json.y_number_simple_real" { ok( \\[123.456789] ); } test "json.y_object_basic" { ok( \\{"asd":"sdf"} ); } test "json.y_object_duplicated_key_and_value" { ok( \\{"a":"b","a":"b"} ); } test "json.y_object_duplicated_key" { ok( \\{"a":"b","a":"c"} ); } test "json.y_object_empty" { ok( \\{} ); } test "json.y_object_empty_key" { ok( \\{"":0} ); } test "json.y_object_escaped_null_in_key" { ok( \\{"foo\u0000bar": 42} ); } test "json.y_object_extreme_numbers" { ok( \\{ "min": -1.0e+28, "max": 1.0e+28 } ); } test "json.y_object" { ok( \\{"asd":"sdf", "dfg":"fgh"} ); } test "json.y_object_long_strings" { ok( \\{"x":[{"id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}], "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"} ); } test "json.y_object_simple" { ok( \\{"a":[]} ); } test "json.y_object_string_unicode" { ok( \\{"title":"\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" } ); } test "json.y_object_with_newlines" { ok( \\{ \\"a": "b" \\} ); } test "json.y_string_1_2_3_bytes_UTF-8_sequences" { ok( \\["\u0060\u012a\u12AB"] ); } test "json.y_string_accepted_surrogate_pair" { ok( \\["\uD801\udc37"] ); } test "json.y_string_accepted_surrogate_pairs" { ok( \\["\ud83d\ude39\ud83d\udc8d"] ); } test "json.y_string_allowed_escapes" { ok( \\["\"\\\/\b\f\n\r\t"] ); } test "json.y_string_backslash_and_u_escaped_zero" { ok( \\["\\u0000"] ); } test "json.y_string_backslash_doublequotes" { ok( \\["\""] ); } test "json.y_string_comments" { ok( \\["a/*b*/c/*d//e"] ); } test "json.y_string_double_escape_a" { ok( \\["\\a"] ); } test "json.y_string_double_escape_n" { ok( \\["\\n"] ); } test "json.y_string_escaped_control_character" { ok( \\["\u0012"] ); } test "json.y_string_escaped_noncharacter" { ok( \\["\uFFFF"] ); } test "json.y_string_in_array" { ok( \\["asd"] ); } test "json.y_string_in_array_with_leading_space" { ok( \\[ "asd"] ); } test "json.y_string_last_surrogates_1_and_2" { ok( \\["\uDBFF\uDFFF"] ); } test "json.y_string_nbsp_uescaped" { ok( \\["new\u00A0line"] ); } test "json.y_string_nonCharacterInUTF-8_U+10FFFF" { ok( \\["􏿿"] ); } test "json.y_string_nonCharacterInUTF-8_U+FFFF" { ok( \\["￿"] ); } test "json.y_string_null_escape" { ok( \\["\u0000"] ); } test "json.y_string_one-byte-utf-8" { ok( \\["\u002c"] ); } test "json.y_string_pi" { ok( \\["π"] ); } test "json.y_string_reservedCharacterInUTF-8_U+1BFFF" { ok( \\["𛿿"] ); } test "json.y_string_simple_ascii" { ok( \\["asd "] ); } test "json.y_string_space" { ok( \\" " ); } test "json.y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF" { ok( \\["\uD834\uDd1e"] ); } test "json.y_string_three-byte-utf-8" { ok( \\["\u0821"] ); } test "json.y_string_two-byte-utf-8" { ok( \\["\u0123"] ); } test "json.y_string_u+2028_line_sep" { ok("[\"\xe2\x80\xa8\"]"); } test "json.y_string_u+2029_par_sep" { ok("[\"\xe2\x80\xa9\"]"); } test "json.y_string_uescaped_newline" { ok( \\["new\u000Aline"] ); } test "json.y_string_uEscape" { ok( \\["\u0061\u30af\u30EA\u30b9"] ); } test "json.y_string_unescaped_char_delete" { ok("[\"\x7f\"]"); } test "json.y_string_unicode_2" { ok( \\["⍂㈴⍂"] ); } test "json.y_string_unicodeEscapedBackslash" { ok( \\["\u005C"] ); } test "json.y_string_unicode_escaped_double_quote" { ok( \\["\u0022"] ); } test "json.y_string_unicode" { ok( \\["\uA66D"] ); } test "json.y_string_unicode_U+10FFFE_nonchar" { ok( \\["\uDBFF\uDFFE"] ); } test "json.y_string_unicode_U+1FFFE_nonchar" { ok( \\["\uD83F\uDFFE"] ); } test "json.y_string_unicode_U+200B_ZERO_WIDTH_SPACE" { ok( \\["\u200B"] ); } test "json.y_string_unicode_U+2064_invisible_plus" { ok( \\["\u2064"] ); } test "json.y_string_unicode_U+FDD0_nonchar" { ok( \\["\uFDD0"] ); } test "json.y_string_unicode_U+FFFE_nonchar" { ok( \\["\uFFFE"] ); } test "json.y_string_utf8" { ok( \\["€𝄞"] ); } test "json.y_string_with_del_character" { ok("[\"a\x7fa\"]"); } test "json.y_structure_lonely_false" { ok( \\false ); } test "json.y_structure_lonely_int" { ok( \\42 ); } test "json.y_structure_lonely_negative_real" { ok( \\-0.1 ); } test "json.y_structure_lonely_null" { ok( \\null ); } test "json.y_structure_lonely_string" { ok( \\"asd" ); } test "json.y_structure_lonely_true" { ok( \\true ); } test "json.y_structure_string_empty" { ok( \\"" ); } test "json.y_structure_trailing_newline" { ok( \\["a"] ); } test "json.y_structure_true_in_array" { ok( \\[true] ); } test "json.y_structure_whitespace_array" { ok(" [] "); } //////////////////////////////////////////////////////////////////////////////////////////////////// test "json.n_array_1_true_without_comma" { err( \\[1 true] ); } test "json.n_array_a_invalid_utf8" { err( \\[aå] ); } test "json.n_array_colon_instead_of_comma" { err( \\["": 1] ); } test "json.n_array_comma_after_close" { //err( // \\[""], //); } test "json.n_array_comma_and_number" { err( \\[,1] ); } test "json.n_array_double_comma" { err( \\[1,,2] ); } test "json.n_array_double_extra_comma" { err( \\["x",,] ); } test "json.n_array_extra_close" { err( \\["x"]] ); } test "json.n_array_extra_comma" { //err( // \\["",] //); } test "json.n_array_incomplete_invalid_value" { err( \\[x ); } test "json.n_array_incomplete" { err( \\["x" ); } test "json.n_array_inner_array_no_comma" { err( \\[3[4]] ); } test "json.n_array_invalid_utf8" { err( \\[ÿ] ); } test "json.n_array_items_separated_by_semicolon" { err( \\[1:2] ); } test "json.n_array_just_comma" { err( \\[,] ); } test "json.n_array_just_minus" { err( \\[-] ); } test "json.n_array_missing_value" { err( \\[ , ""] ); } test "json.n_array_newlines_unclosed" { err( \\["a", \\4 \\,1, ); } test "json.n_array_number_and_comma" { err( \\[1,] ); } test "json.n_array_number_and_several_commas" { err( \\[1,,] ); } test "json.n_array_spaces_vertical_tab_formfeed" { err("[\"\x0aa\"\\f]"); } test "json.n_array_star_inside" { err( \\[*] ); } test "json.n_array_unclosed" { err( \\["" ); } test "json.n_array_unclosed_trailing_comma" { err( \\[1, ); } test "json.n_array_unclosed_with_new_lines" { err( \\[1, \\1 \\,1 ); } test "json.n_array_unclosed_with_object_inside" { err( \\[{} ); } test "json.n_incomplete_false" { err( \\[fals] ); } test "json.n_incomplete_null" { err( \\[nul] ); } test "json.n_incomplete_true" { err( \\[tru] ); } test "json.n_multidigit_number_then_00" { err("123\x00"); } test "json.n_number_0.1.2" { err( \\[0.1.2] ); } test "json.n_number_-01" { err( \\[-01] ); } test "json.n_number_0.3e" { err( \\[0.3e] ); } test "json.n_number_0.3e+" { err( \\[0.3e+] ); } test "json.n_number_0_capital_E" { err( \\[0E] ); } test "json.n_number_0_capital_E+" { err( \\[0E+] ); } test "json.n_number_0.e1" { err( \\[0.e1] ); } test "json.n_number_0e" { err( \\[0e] ); } test "json.n_number_0e+" { err( \\[0e+] ); } test "json.n_number_1_000" { err( \\[1 000.0] ); } test "json.n_number_1.0e-" { err( \\[1.0e-] ); } test "json.n_number_1.0e" { err( \\[1.0e] ); } test "json.n_number_1.0e+" { err( \\[1.0e+] ); } test "json.n_number_-1.0." { err( \\[-1.0.] ); } test "json.n_number_1eE2" { err( \\[1eE2] ); } test "json.n_number_.-1" { err( \\[.-1] ); } test "json.n_number_+1" { err( \\[+1] ); } test "json.n_number_.2e-3" { err( \\[.2e-3] ); } test "json.n_number_2.e-3" { err( \\[2.e-3] ); } test "json.n_number_2.e+3" { err( \\[2.e+3] ); } test "json.n_number_2.e3" { err( \\[2.e3] ); } test "json.n_number_-2." { err( \\[-2.] ); } test "json.n_number_9.e+" { err( \\[9.e+] ); } test "json.n_number_expression" { err( \\[1+2] ); } test "json.n_number_hex_1_digit" { err( \\[0x1] ); } test "json.n_number_hex_2_digits" { err( \\[0x42] ); } test "json.n_number_infinity" { err( \\[Infinity] ); } test "json.n_number_+Inf" { err( \\[+Inf] ); } test "json.n_number_Inf" { err( \\[Inf] ); } test "json.n_number_invalid+-" { err( \\[0e+-1] ); } test "json.n_number_invalid-negative-real" { err( \\[-123.123foo] ); } test "json.n_number_invalid-utf-8-in-bigger-int" { err( \\[123å] ); } test "json.n_number_invalid-utf-8-in-exponent" { err( \\[1e1å] ); } test "json.n_number_invalid-utf-8-in-int" { err( \\[0å] ); } test "json.n_number_++" { err( \\[++1234] ); } test "json.n_number_minus_infinity" { err( \\[-Infinity] ); } test "json.n_number_minus_sign_with_trailing_garbage" { err( \\[-foo] ); } test "json.n_number_minus_space_1" { err( \\[- 1] ); } test "json.n_number_-NaN" { err( \\[-NaN] ); } test "json.n_number_NaN" { err( \\[NaN] ); } test "json.n_number_neg_int_starting_with_zero" { err( \\[-012] ); } test "json.n_number_neg_real_without_int_part" { err( \\[-.123] ); } test "json.n_number_neg_with_garbage_at_end" { err( \\[-1x] ); } test "json.n_number_real_garbage_after_e" { err( \\[1ea] ); } test "json.n_number_real_with_invalid_utf8_after_e" { err( \\[1eå] ); } test "json.n_number_real_without_fractional_part" { err( \\[1.] ); } test "json.n_number_starting_with_dot" { err( \\[.123] ); } test "json.n_number_U+FF11_fullwidth_digit_one" { err( \\[1] ); } test "json.n_number_with_alpha_char" { err( \\[1.8011670033376514H-308] ); } test "json.n_number_with_alpha" { err( \\[1.2a-3] ); } test "json.n_number_with_leading_zero" { err( \\[012] ); } test "json.n_object_bad_value" { err( \\["x", truth] ); } test "json.n_object_bracket_key" { err( \\{[: "x"} ); } test "json.n_object_comma_instead_of_colon" { err( \\{"x", null} ); } test "json.n_object_double_colon" { err( \\{"x"::"b"} ); } test "json.n_object_emoji" { err( \\{🇨🇭} ); } test "json.n_object_garbage_at_end" { err( \\{"a":"a" 123} ); } test "json.n_object_key_with_single_quotes" { err( \\{key: 'value'} ); } test "json.n_object_lone_continuation_byte_in_key_and_trailing_comma" { err( \\{"¹":"0",} ); } test "json.n_object_missing_colon" { err( \\{"a" b} ); } test "json.n_object_missing_key" { err( \\{:"b"} ); } test "json.n_object_missing_semicolon" { err( \\{"a" "b"} ); } test "json.n_object_missing_value" { err( \\{"a": ); } test "json.n_object_no-colon" { err( \\{"a" ); } test "json.n_object_non_string_key_but_huge_number_instead" { err( \\{9999E9999:1} ); } test "json.n_object_non_string_key" { err( \\{1:1} ); } test "json.n_object_repeated_null_null" { err( \\{null:null,null:null} ); } test "json.n_object_several_trailing_commas" { err( \\{"id":0,,,,,} ); } test "json.n_object_single_quote" { err( \\{'a':0} ); } test "json.n_object_trailing_comma" { err( \\{"id":0,} ); } test "json.n_object_trailing_comment" { err( \\{"a":"b"}/**/ ); } test "json.n_object_trailing_comment_open" { err( \\{"a":"b"}/**// ); } test "json.n_object_trailing_comment_slash_open_incomplete" { err( \\{"a":"b"}/ ); } test "json.n_object_trailing_comment_slash_open" { err( \\{"a":"b"}// ); } test "json.n_object_two_commas_in_a_row" { err( \\{"a":"b",,"c":"d"} ); } test "json.n_object_unquoted_key" { err( \\{a: "b"} ); } test "json.n_object_unterminated-value" { err( \\{"a":"a ); } test "json.n_object_with_single_string" { err( \\{ "foo" : "bar", "a" } ); } test "json.n_object_with_trailing_garbage" { err( \\{"a":"b"}# ); } test "json.n_single_space" { err(" "); } test "json.n_string_1_surrogate_then_escape" { err( \\["\uD800\"] ); } test "json.n_string_1_surrogate_then_escape_u1" { err( \\["\uD800\u1"] ); } test "json.n_string_1_surrogate_then_escape_u1x" { err( \\["\uD800\u1x"] ); } test "json.n_string_1_surrogate_then_escape_u" { err( \\["\uD800\u"] ); } test "json.n_string_accentuated_char_no_quotes" { err( \\[é] ); } test "json.n_string_backslash_00" { err("[\"\x00\"]"); } test "json.n_string_escaped_backslash_bad" { err( \\["\\\"] ); } test "json.n_string_escaped_ctrl_char_tab" { err("\x5b\x22\x5c\x09\x22\x5d"); } test "json.n_string_escaped_emoji" { err("[\"\x5c\xc3\xb0\xc2\x9f\xc2\x8c\xc2\x80\"]"); } test "json.n_string_escape_x" { err( \\["\x00"] ); } test "json.n_string_incomplete_escaped_character" { err( \\["\u00A"] ); } test "json.n_string_incomplete_escape" { err( \\["\"] ); } test "json.n_string_incomplete_surrogate_escape_invalid" { err( \\["\uD800\uD800\x"] ); } test "json.n_string_incomplete_surrogate" { err( \\["\uD834\uDd"] ); } test "json.n_string_invalid_backslash_esc" { err( \\["\a"] ); } test "json.n_string_invalid_unicode_escape" { err( \\["\uqqqq"] ); } test "json.n_string_invalid_utf8_after_escape" { err("[\"\\\x75\xc3\xa5\"]"); } test "json.n_string_invalid-utf-8-in-escape" { err( \\["\uå"] ); } test "json.n_string_leading_uescaped_thinspace" { err( \\[\u0020"asd"] ); } test "json.n_string_no_quotes_with_bad_escape" { err( \\[\n] ); } test "json.n_string_single_doublequote" { err( \\" ); } test "json.n_string_single_quote" { err( \\['single quote'] ); } test "json.n_string_single_string_no_double_quotes" { err( \\abc ); } test "json.n_string_start_escape_unclosed" { err( \\["\ ); } test "json.n_string_unescaped_crtl_char" { err("[\"a\x00a\"]"); } test "json.n_string_unescaped_newline" { err( \\["new \\line"] ); } test "json.n_string_unescaped_tab" { err("[\"\t\"]"); } test "json.n_string_unicode_CapitalU" { err( \\"\UA66D" ); } test "json.n_string_with_trailing_garbage" { err( \\""x ); } test "json.n_structure_100000_opening_arrays" { err("[" ** 100000); } test "json.n_structure_angle_bracket_." { err( \\<.> ); } test "json.n_structure_angle_bracket_null" { err( \\[<null>] ); } test "json.n_structure_array_trailing_garbage" { err( \\[1]x ); } test "json.n_structure_array_with_extra_array_close" { err( \\[1]] ); } test "json.n_structure_array_with_unclosed_string" { err( \\["asd] ); } test "json.n_structure_ascii-unicode-identifier" { err( \\aÃ¥ ); } test "json.n_structure_capitalized_True" { err( \\[True] ); } test "json.n_structure_close_unopened_array" { err( \\1] ); } test "json.n_structure_comma_instead_of_closing_brace" { err( \\{"x": true, ); } test "json.n_structure_double_array" { err( \\[][] ); } test "json.n_structure_end_array" { err( \\] ); } test "json.n_structure_incomplete_UTF8_BOM" { err( \\ï»{} ); } test "json.n_structure_lone-invalid-utf-8" { err( \\å ); } test "json.n_structure_lone-open-bracket" { err( \\[ ); } test "json.n_structure_no_data" { err( \\ ); } test "json.n_structure_null-byte-outside-string" { err("[\x00]"); } test "json.n_structure_number_with_trailing_garbage" { err( \\2@ ); } test "json.n_structure_object_followed_by_closing_object" { err( \\{}} ); } test "json.n_structure_object_unclosed_no_value" { err( \\{"": ); } test "json.n_structure_object_with_comment" { err( \\{"a":/*comment*/"b"} ); } test "json.n_structure_object_with_trailing_garbage" { err( \\{"a": true} "x" ); } test "json.n_structure_open_array_apostrophe" { err( \\[' ); } test "json.n_structure_open_array_comma" { err( \\[, ); } test "json.n_structure_open_array_object" { err("[{\"\":" ** 50000); } test "json.n_structure_open_array_open_object" { err( \\[{ ); } test "json.n_structure_open_array_open_string" { err( \\["a ); } test "json.n_structure_open_array_string" { err( \\["a" ); } test "json.n_structure_open_object_close_array" { err( \\{] ); } test "json.n_structure_open_object_comma" { err( \\{, ); } test "json.n_structure_open_object" { err( \\{ ); } test "json.n_structure_open_object_open_array" { err( \\{[ ); } test "json.n_structure_open_object_open_string" { err( \\{"a ); } test "json.n_structure_open_object_string_with_apostrophes" { err( \\{'a' ); } test "json.n_structure_open_open" { err( \\["\{["\{["\{["\{ ); } test "json.n_structure_single_eacute" { err( \\é ); } test "json.n_structure_single_star" { err( \\* ); } test "json.n_structure_trailing_#" { err( \\{"a":"b"}#{} ); } test "json.n_structure_U+2060_word_joined" { err( \\[⁠] ); } test "json.n_structure_uescaped_LF_before_string" { err( \\[\u000A""] ); } test "json.n_structure_unclosed_array" { err( \\[1 ); } test "json.n_structure_unclosed_array_partial_null" { err( \\[ false, nul ); } test "json.n_structure_unclosed_array_unfinished_false" { err( \\[ true, fals ); } test "json.n_structure_unclosed_array_unfinished_true" { err( \\[ false, tru ); } test "json.n_structure_unclosed_object" { err( \\{"asd":"asd" ); } test "json.n_structure_unicode-identifier" { err( \\Ã¥ ); } test "json.n_structure_UTF8_BOM_no_data" { err( \\ ); } test "json.n_structure_whitespace_formfeed" { err("[\x0c]"); } test "json.n_structure_whitespace_U+2060_word_joiner" { err( \\[⁠] ); } //////////////////////////////////////////////////////////////////////////////////////////////////// test "json.i_number_double_huge_neg_exp" { any( \\[123.456e-789] ); } test "json.i_number_huge_exp" { any( \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006] ); } test "json.i_number_neg_int_huge_exp" { any( \\[-1e+9999] ); } test "json.i_number_pos_double_huge_exp" { any( \\[1.5e+9999] ); } test "json.i_number_real_neg_overflow" { any( \\[-123123e100000] ); } test "json.i_number_real_pos_overflow" { any( \\[123123e100000] ); } test "json.i_number_real_underflow" { any( \\[123e-10000000] ); } test "json.i_number_too_big_neg_int" { any( \\[-123123123123123123123123123123] ); } test "json.i_number_too_big_pos_int" { any( \\[100000000000000000000] ); } test "json.i_number_very_big_negative_int" { any( \\[-237462374673276894279832749832423479823246327846] ); } test "json.i_object_key_lone_2nd_surrogate" { any( \\{"\uDFAA":0} ); } test "json.i_string_1st_surrogate_but_2nd_missing" { any( \\["\uDADA"] ); } test "json.i_string_1st_valid_surrogate_2nd_invalid" { any( \\["\uD888\u1234"] ); } test "json.i_string_incomplete_surrogate_and_escape_valid" { any( \\["\uD800\n"] ); } test "json.i_string_incomplete_surrogate_pair" { any( \\["\uDd1ea"] ); } test "json.i_string_incomplete_surrogates_escape_valid" { any( \\["\uD800\uD800\n"] ); } test "json.i_string_invalid_lonely_surrogate" { any( \\["\ud800"] ); } test "json.i_string_invalid_surrogate" { any( \\["\ud800abc"] ); } test "json.i_string_invalid_utf-8" { any( \\["ÿ"] ); } test "json.i_string_inverted_surrogates_U+1D11E" { any( \\["\uDd1e\uD834"] ); } test "json.i_string_iso_latin_1" { any( \\["é"] ); } test "json.i_string_lone_second_surrogate" { any( \\["\uDFAA"] ); } test "json.i_string_lone_utf8_continuation_byte" { any( \\[""] ); } test "json.i_string_not_in_unicode_range" { any( \\["ô¿¿¿"] ); } test "json.i_string_overlong_sequence_2_bytes" { any( \\["À¯"] ); } test "json.i_string_overlong_sequence_6_bytes" { any( \\["üƒ¿¿¿¿"] ); } test "json.i_string_overlong_sequence_6_bytes_null" { any( \\["ü€€€€€"] ); } test "json.i_string_truncated-utf-8" { any( \\["àÿ"] ); } test "json.i_string_utf16BE_no_BOM" { any("\x00\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d"); } test "json.i_string_utf16LE_no_BOM" { any("\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00"); } test "json.i_string_UTF-16LE_with_BOM" { any("\xc3\xbf\xc3\xbe\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00"); } test "json.i_string_UTF-8_invalid_sequence" { any( \\["日шú"] ); } test "json.i_string_UTF8_surrogate_U+D800" { any( \\["í €"] ); } test "json.i_structure_500_nested_arrays" { any(("[" ** 500) ++ ("]" ** 500)); } test "json.i_structure_UTF-8_BOM_empty_object" { any( \\{} ); }
json_test.zig
const std = @import("std"); 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 Vec3 = [3]i32; fn abs(x: i32) u32 { return if (x >= 0) @intCast(u32, x) else @intCast(u32, -x); } fn length(d: Vec3) u32 { return abs(d[0]) + abs(d[1]) + abs(d[2]); } fn pgcd(_a: u64, _b: u64) u64 { var a = _a; var b = _b; while (b != 0) { var t = b; b = a % b; a = t; } return a; } fn ppcm(a: u64, b: u64) u64 { return (a * b) / pgcd(a, b); } const Body = struct { pos: Vec3, vel: Vec3, energy: u32, }; const Axis = struct { pos: [4]i32, vel: [4]i32, }; const Hash = std.AutoHashMap(Axis, void); pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { _ = input; const initial_state = [_]Body{ .{ .pos = .{ -7, -1, 6 }, .vel = .{ 0, 0, 0 }, .energy = 0, }, .{ .pos = .{ 6, -9, -9 }, .vel = .{ 0, 0, 0 }, .energy = 0, }, .{ .pos = .{ -12, 2, -7 }, .vel = .{ 0, 0, 0 }, .energy = 0, }, .{ .pos = .{ 4, -17, -12 }, .vel = .{ 0, 0, 0 }, .energy = 0, }, }; const part1_steps = 1000; var center = Vec3{ 0, 0, 0 }; { var total: u32 = 0; for (initial_state) |it| { for (center) |*p, j| { p.* += it.pos[j]; } total += length(it.pos) * length(it.vel); } trace("start: {}, {}\n", .{ total, center }); } var tables = [_]Hash{ Hash.init(allocator), Hash.init(allocator), Hash.init(allocator) }; defer { for (tables) |*t| { t.deinit(); } } { for (center) |_, a| { const axis = Axis{ .pos = .{ initial_state[0].pos[a], initial_state[1].pos[a], initial_state[2].pos[a], initial_state[3].pos[a] }, .vel = .{ initial_state[0].vel[a], initial_state[1].vel[a], initial_state[2].vel[a], initial_state[3].vel[a] }, }; _ = try tables[a].put(axis, .{}); } } var axis_repeat = [3]?u32{ null, null, null }; var total_energy_at_1000: u32 = 0; var cur = initial_state; var next: [4]Body = undefined; var step: u32 = 1; while (axis_repeat[0] == null or axis_repeat[1] == null or axis_repeat[2] == null) : (step += 1) { var total: u32 = 0; for (next) |*this, i| { const pos = cur[i].pos; var vel = cur[i].vel; for (cur) |other| { for (vel) |*v, j| { if (other.pos[j] > pos[j]) v.* += 1; if (other.pos[j] < pos[j]) v.* -= 1; } } for (this.pos) |*p, j| { p.* = pos[j] + vel[j]; } this.vel = vel; this.energy = length(this.pos) * length(this.vel); total += this.energy; } if (step == part1_steps) { total_energy_at_1000 = total; } for (axis_repeat) |*axr, a| { if (axr.*) |_| continue; const axis = Axis{ .pos = .{ next[0].pos[a], next[1].pos[a], next[2].pos[a], next[3].pos[a] }, .vel = .{ next[0].vel[a], next[1].vel[a], next[2].vel[a], next[3].vel[a] }, }; if (try tables[a].fetchPut(axis, .{})) |_| { axr.* = step; trace("REPEAT{} step n°{} {},{},{},{}\n", .{ a, step, next[0].pos[a], next[1].pos[a], next[2].pos[a], next[3].pos[a] }); // next[0] } } cur = next; } const rpt_x = @as(u64, axis_repeat[0].?); const rpt_y = @as(u64, axis_repeat[1].?); const rpt_z = @as(u64, axis_repeat[2].?); trace("repeats: {},{},{}\n", .{ rpt_x, rpt_y, rpt_z }); const ppcm1 = ppcm(rpt_x, rpt_y); const ppcm2 = ppcm(ppcm1, rpt_z); trace("repeat ppcm={} -> {}\n", .{ ppcm1, ppcm2 }); return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{total_energy_at_1000}), try std.fmt.allocPrint(allocator, "{}", .{ppcm2}), }; } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const ans = try run("", allocator); defer allocator.free(ans[0]); defer allocator.free(ans[1]); try stdout.print("PART 1: {s}\nPART 2: {s}\n", .{ ans[0], ans[1] }); }
2019/day12.zig
const std = @import("std"); const tvg = @import("tvg"); pub fn main() !void { try std.fs.cwd().writeFile("examples/app_menu.tvg", &app_menu); try std.fs.cwd().writeFile("examples/workspace.tvg", &workspace); try std.fs.cwd().writeFile("examples/workspace_add.tvg", &workspace_add); try std.fs.cwd().writeFile("examples/shield.tvg", &shield); try std.fs.cwd().writeFile("examples/feature-showcase.tvg", &feature_showcase); } const builder = tvg.builder(.@"1/256"); const builder_16 = tvg.builder(.@"1/16"); pub const app_menu = blk: { @setEvalBranchQuota(10_000); break :blk builder.header(48, 48) ++ builder.colorTable(&[_]tvg.Color{ tvg.Color.fromString("000000") catch unreachable, }) ++ builder.fillRectangles(3, .flat, 0) ++ builder.rectangle(6, 12, 36, 4) ++ builder.rectangle(6, 22, 36, 4) ++ builder.rectangle(6, 32, 36, 4) ++ builder.end_of_document; }; pub const workspace = blk: { @setEvalBranchQuota(10_000); break :blk builder.header(48, 48) ++ builder.colorTable(&[_]tvg.Color{ tvg.Color.fromString("008751") catch unreachable, tvg.Color.fromString("83769c") catch unreachable, tvg.Color.fromString("1d2b53") catch unreachable, }) ++ builder.fillRectangles(1, .flat, 0) ++ builder.rectangle(6, 6, 16, 36) ++ builder.fillRectangles(1, .flat, 1) ++ builder.rectangle(26, 6, 16, 16) ++ builder.fillRectangles(1, .flat, 2) ++ builder.rectangle(26, 26, 16, 16) ++ builder.end_of_document; }; pub const workspace_add = blk: { @setEvalBranchQuota(10_000); break :blk builder.header(48, 48) ++ builder.colorTable(&[_]tvg.Color{ tvg.Color.fromString("008751") catch unreachable, tvg.Color.fromString("83769c") catch unreachable, tvg.Color.fromString("ff004d") catch unreachable, }) ++ builder.fillRectangles(1, .flat, 0) ++ builder.rectangle(6, 6, 16, 36) ++ builder.fillRectangles(1, .flat, 1) ++ builder.rectangle(26, 6, 16, 16) ++ builder.fillPath(11, .flat, 2) ++ builder.point(26, 32) ++ builder.path.horiz(32) ++ builder.path.vert(26) ++ builder.path.horiz(36) ++ builder.path.vert(32) ++ builder.path.horiz(42) ++ builder.path.vert(36) ++ builder.path.horiz(36) ++ builder.path.vert(42) ++ builder.path.horiz(32) ++ builder.path.vert(36) ++ builder.path.horiz(26) ++ builder.end_of_document; }; pub const shield = blk: { @setEvalBranchQuota(10_000); break :blk builder.header(24, 24) ++ builder.colorTable(&[_]tvg.Color{ tvg.Color.fromString("29adff") catch unreachable, tvg.Color.fromString("fff1e8") catch unreachable, }) ++ builder.fillPath(5, .flat, 0) ++ builder.point(12, 1) ++ // M 12 1 builder.path.line(3, 5) ++ // L 3 5 builder.path.vert(11) ++ // V 11 builder.path.bezier(3, 16.55, 6.84, 21.74, 12, 23) ++ // C 3 16.55 6.84 21.74 12 23 builder.path.bezier(17.16, 21.74, 21, 16.55, 21, 11) ++ // C 17.16 21.74 21 16.55 21 11 builder.path.vert(5) ++ // V 5 builder.fillPath(6, .flat, 1) ++ builder.point(17.13, 17) ++ // M 12 1 builder.path.bezier(15.92, 18.85, 14.11, 20.24, 12, 20.92) ++ builder.path.bezier(9.89, 20.24, 8.08, 18.85, 6.87, 17) ++ builder.path.bezier(6.53, 16.5, 6.24, 16, 6, 15.47) ++ builder.path.bezier(6, 13.82, 8.71, 12.47, 12, 12.47) ++ builder.path.bezier(15.29, 12.47, 18, 13.79, 18, 15.47) ++ builder.path.bezier(17.76, 16, 17.47, 16.5, 17.13, 17) ++ builder.fillPath(4, .flat, 1) ++ builder.point(12, 5) ++ builder.path.bezier(13.5, 5, 15, 6.2, 15, 8) ++ builder.path.bezier(15, 9.5, 13.8, 10.998, 12, 11) ++ builder.path.bezier(10.5, 11, 9, 9.8, 9, 8) ++ builder.path.bezier(9, 6.4, 10.2, 5, 12, 5) ++ builder.end_of_document; }; pub const feature_showcase = blk: { @setEvalBranchQuota(20_000); break :blk builder_16.header(1024, 1024) ++ builder_16.colorTable(&[_]tvg.Color{ tvg.Color.fromString("e7a915") catch unreachable, // 0 yellow tvg.Color.fromString("ff7800") catch unreachable, // 1 orange tvg.Color.fromString("40ff00") catch unreachable, // 2 green tvg.Color.fromString("ba004d") catch unreachable, // 3 reddish purple tvg.Color.fromString("62009e") catch unreachable, // 4 blueish purple tvg.Color.fromString("94e538") catch unreachable, // 5 grass green }) ++ // FILL RECTANGLE builder_16.fillRectangles(2, .flat, 0) ++ builder_16.rectangle(16, 16, 64, 48) ++ builder_16.rectangle(96, 16, 64, 48) ++ builder_16.fillRectangles(2, .linear, .{ .point_0 = .{ .x = 32, .y = 80 }, .point_1 = .{ .x = 144, .y = 128 }, .color_0 = 1, .color_1 = 2, }) ++ builder_16.rectangle(16, 80, 64, 48) ++ builder_16.rectangle(96, 80, 64, 48) ++ builder_16.fillRectangles(2, .radial, .{ .point_0 = .{ .x = 80, .y = 144 }, .point_1 = .{ .x = 48, .y = 176 }, .color_0 = 1, .color_1 = 2, }) ++ builder_16.rectangle(16, 144, 64, 48) ++ builder_16.rectangle(96, 144, 64, 48) ++ // FILL POLYGON builder_16.fillPolygon(7, .flat, 3) ++ builder_16.point(192, 32) ++ builder_16.point(208, 16) ++ builder_16.point(240, 16) ++ builder_16.point(256, 32) ++ builder_16.point(256, 64) ++ builder_16.point(224, 48) ++ builder_16.point(192, 64) ++ builder_16.fillPolygon(7, .linear, .{ .point_0 = .{ .x = 224, .y = 80 }, .point_1 = .{ .x = 224, .y = 128 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(192, 96) ++ builder_16.point(208, 80) ++ builder_16.point(240, 80) ++ builder_16.point(256, 96) ++ builder_16.point(256, 128) ++ builder_16.point(224, 112) ++ builder_16.point(192, 128) ++ builder_16.fillPolygon(7, .radial, .{ .point_0 = .{ .x = 224, .y = 144 }, .point_1 = .{ .x = 224, .y = 192 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(192, 160) ++ builder_16.point(208, 144) ++ builder_16.point(240, 144) ++ builder_16.point(256, 160) ++ builder_16.point(256, 192) ++ builder_16.point(224, 176) ++ builder_16.point(192, 192) ++ // FILL PATH builder_16.fillPath(10, .flat, 5) ++ builder_16.point(288, 64) ++ builder_16.path.vert(32) ++ builder_16.path.bezier(288, 24, 288, 16, 304, 16) ++ builder_16.path.horiz(336) ++ builder_16.path.bezier(352, 16, 352, 24, 352, 32) ++ builder_16.path.vert(64) ++ builder_16.path.line(336, 48) ++ // this should be an arc segment builder_16.path.line(320, 32) ++ builder_16.path.line(312, 48) ++ builder_16.path.line(304, 64) ++ // this should be an arc segment builder_16.path.close() ++ builder_16.fillPath(10, .linear, .{ .point_0 = .{ .x = 320, .y = 80 }, .point_1 = .{ .x = 320, .y = 128 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(288, 64 + 64) ++ builder_16.path.vert(64 + 32) ++ builder_16.path.bezier(288, 64 + 24, 288, 64 + 16, 304, 64 + 16) ++ builder_16.path.horiz(336) ++ builder_16.path.bezier(352, 64 + 16, 352, 64 + 24, 352, 64 + 32) ++ builder_16.path.vert(64 + 64) ++ builder_16.path.line(336, 64 + 48) ++ // this should be an arc segment builder_16.path.line(320, 64 + 32) ++ builder_16.path.line(312, 64 + 48) ++ builder_16.path.line(304, 64 + 64) ++ // this should be an arc segment builder_16.path.close() ++ builder_16.fillPath(10, .radial, .{ .point_0 = .{ .x = 320, .y = 144 }, .point_1 = .{ .x = 320, .y = 192 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(288, 128 + 64) ++ builder_16.path.vert(128 + 32) ++ builder_16.path.bezier(288, 128 + 24, 288, 128 + 16, 304, 128 + 16) ++ builder_16.path.horiz(336) ++ builder_16.path.bezier(352, 128 + 16, 352, 128 + 24, 352, 128 + 32) ++ builder_16.path.vert(128 + 64) ++ builder_16.path.line(336, 128 + 48) ++ // this should be an arc segment builder_16.path.line(320, 128 + 32) ++ builder_16.path.line(312, 128 + 48) ++ builder_16.path.line(304, 128 + 64) ++ // this should be an arc segment builder_16.path.close() ++ // DRAW LINES builder_16.drawLines(4, 0.0, .flat, 1) ++ builder_16.point(16 + 0, 224 + 0) ++ builder_16.point(16 + 64, 224 + 0) ++ builder_16.point(16 + 0, 224 + 16) ++ builder_16.point(16 + 64, 224 + 16) ++ builder_16.point(16 + 0, 224 + 32) ++ builder_16.point(16 + 64, 224 + 32) ++ builder_16.point(16 + 0, 224 + 48) ++ builder_16.point(16 + 64, 224 + 48) ++ builder_16.drawLines(4, 3.0, .linear, .{ .point_0 = .{ .x = 48, .y = 304 }, .point_1 = .{ .x = 48, .y = 352 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(16 + 0, 304 + 0) ++ builder_16.point(16 + 64, 304 + 0) ++ builder_16.point(16 + 0, 304 + 16) ++ builder_16.point(16 + 64, 304 + 16) ++ builder_16.point(16 + 0, 304 + 32) ++ builder_16.point(16 + 64, 304 + 32) ++ builder_16.point(16 + 0, 304 + 48) ++ builder_16.point(16 + 64, 304 + 48) ++ builder_16.drawLines(4, 6.0, .radial, .{ .point_0 = .{ .x = 48, .y = 408 }, .point_1 = .{ .x = 48, .y = 432 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(16 + 0, 384 + 0) ++ builder_16.point(16 + 64, 384 + 0) ++ builder_16.point(16 + 0, 384 + 16) ++ builder_16.point(16 + 64, 384 + 16) ++ builder_16.point(16 + 0, 384 + 32) ++ builder_16.point(16 + 64, 384 + 32) ++ builder_16.point(16 + 0, 384 + 48) ++ builder_16.point(16 + 64, 384 + 48) ++ // DRAW LINE STRIP builder_16.drawLineStrip(8, 3.0, .flat, 1) ++ builder_16.point(96 + 0, 224 + 0) ++ builder_16.point(96 + 64, 224 + 0) ++ builder_16.point(96 + 64, 224 + 16) ++ builder_16.point(96 + 0, 224 + 16) ++ builder_16.point(96 + 0, 224 + 32) ++ builder_16.point(96 + 64, 224 + 32) ++ builder_16.point(96 + 64, 224 + 48) ++ builder_16.point(96 + 0, 224 + 48) ++ builder_16.drawLineStrip(8, 6.0, .linear, .{ .point_0 = .{ .x = 128, .y = 304 }, .point_1 = .{ .x = 128, .y = 352 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(96 + 0, 304 + 0) ++ builder_16.point(96 + 64, 304 + 0) ++ builder_16.point(96 + 64, 304 + 16) ++ builder_16.point(96 + 0, 304 + 16) ++ builder_16.point(96 + 0, 304 + 32) ++ builder_16.point(96 + 64, 304 + 32) ++ builder_16.point(96 + 64, 304 + 48) ++ builder_16.point(96 + 0, 304 + 48) ++ builder_16.drawLineStrip(8, 0.0, .radial, .{ .point_0 = .{ .x = 128, .y = 408 }, .point_1 = .{ .x = 128, .y = 432 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(96 + 0, 384 + 0) ++ builder_16.point(96 + 64, 384 + 0) ++ builder_16.point(96 + 64, 384 + 16) ++ builder_16.point(96 + 0, 384 + 16) ++ builder_16.point(96 + 0, 384 + 32) ++ builder_16.point(96 + 64, 384 + 32) ++ builder_16.point(96 + 64, 384 + 48) ++ builder_16.point(96 + 0, 384 + 48) ++ // DRAW LINE LOOP builder_16.drawLineLoop(8, 6.0, .flat, 1) ++ builder_16.point(176 + 0, 224 + 0) ++ builder_16.point(176 + 64, 224 + 0) ++ builder_16.point(176 + 64, 224 + 16) ++ builder_16.point(176 + 16, 224 + 16) ++ builder_16.point(176 + 16, 224 + 32) ++ builder_16.point(176 + 64, 224 + 32) ++ builder_16.point(176 + 64, 224 + 48) ++ builder_16.point(176 + 0, 224 + 48) ++ builder_16.drawLineLoop(8, 0.0, .linear, .{ .point_0 = .{ .x = 208, .y = 304 }, .point_1 = .{ .x = 208, .y = 352 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(176 + 0, 304 + 0) ++ builder_16.point(176 + 64, 304 + 0) ++ builder_16.point(176 + 64, 304 + 16) ++ builder_16.point(176 + 16, 304 + 16) ++ builder_16.point(176 + 16, 304 + 32) ++ builder_16.point(176 + 64, 304 + 32) ++ builder_16.point(176 + 64, 304 + 48) ++ builder_16.point(176 + 0, 304 + 48) ++ builder_16.drawLineLoop(8, 3.0, .radial, .{ .point_0 = .{ .x = 208, .y = 408 }, .point_1 = .{ .x = 208, .y = 432 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(176 + 0, 384 + 0) ++ builder_16.point(176 + 64, 384 + 0) ++ builder_16.point(176 + 64, 384 + 16) ++ builder_16.point(176 + 16, 384 + 16) ++ builder_16.point(176 + 16, 384 + 32) ++ builder_16.point(176 + 64, 384 + 32) ++ builder_16.point(176 + 64, 384 + 48) ++ builder_16.point(176 + 0, 384 + 48) ++ // DRAW LINE PATH builder_16.drawPath(10, 0.0, .flat, 1) ++ builder_16.point(256 + 0, 224 + 0) ++ builder_16.path.horiz(256 + 48) ++ builder_16.path.bezier(256 + 64, 224 + 0, 256 + 64, 224 + 16, 256 + 48, 224 + 16) ++ builder_16.path.horiz(256 + 32) ++ builder_16.path.line(256 + 16, 224 + 24) ++ builder_16.path.line(256 + 32, 224 + 32) ++ builder_16.path.line(256 + 64, 224 + 32) ++ // this is arc-ellipse later builder_16.path.line(256 + 48, 224 + 48) ++ // this is arc-circle later builder_16.path.horiz(256 + 16) ++ builder_16.path.line(256 + 0, 224 + 32) ++ // this is arc-circle later builder_16.path.close() ++ builder_16.drawPath(10, 6.0, .linear, .{ .point_0 = .{ .x = 288, .y = 408 }, .point_1 = .{ .x = 288, .y = 432 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(256 + 0, 304 + 0) ++ builder_16.path.horiz(256 + 48) ++ builder_16.path.bezier(256 + 64, 304 + 0, 256 + 64, 304 + 16, 256 + 48, 304 + 16) ++ builder_16.path.horiz(256 + 32) ++ builder_16.path.line(256 + 16, 304 + 24) ++ builder_16.path.line(256 + 32, 304 + 32) ++ builder_16.path.line(256 + 64, 304 + 32) ++ // this is arc-ellipse later builder_16.path.line(256 + 48, 304 + 48) ++ // this is arc-circle later builder_16.path.horiz(256 + 16) ++ builder_16.path.line(256 + 0, 304 + 32) ++ // this is arc-circle later builder_16.path.close() ++ builder_16.drawPath(10, 3.0, .radial, .{ .point_0 = .{ .x = 288, .y = 408 }, .point_1 = .{ .x = 288, .y = 432 }, .color_0 = 3, .color_1 = 4, }) ++ builder_16.point(256 + 0, 384 + 0) ++ builder_16.path.horiz(256 + 48) ++ builder_16.path.bezier(256 + 64, 384 + 0, 256 + 64, 384 + 16, 256 + 48, 384 + 16) ++ builder_16.path.horiz(256 + 32) ++ builder_16.path.line(256 + 16, 384 + 24) ++ builder_16.path.line(256 + 32, 384 + 32) ++ builder_16.path.line(256 + 64, 384 + 32) ++ // this is arc-ellipse later builder_16.path.line(256 + 48, 384 + 48) ++ // this is arc-circle later builder_16.path.horiz(256 + 16) ++ builder_16.path.line(256 + 0, 384 + 32) ++ // this is arc-circle later builder_16.path.close() ++ // Outline Fill Rectangle builder_16.outlineFillRectangles(1, 0.0, .flat, 0, .flat, 3) ++ builder_16.rectangle(384, 16, 64, 48) ++ builder_16.outlineFillRectangles(1, 1.0, .flat, 0, .linear, .{ .point_0 = .{ .x = 416, .y = 80 }, .point_1 = .{ .x = 416, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(384, 80, 64, 48) ++ builder_16.outlineFillRectangles(1, 2.0, .flat, 0, .radial, .{ .point_0 = .{ .x = 416, .y = 168 }, .point_1 = .{ .x = 416, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(384, 144, 64, 48) ++ builder_16.outlineFillRectangles(1, 3.0, .linear, .{ .point_0 = .{ .x = 496, .y = 16 }, .point_1 = .{ .x = 496, .y = 64 }, .color_0 = 1, .color_1 = 2 }, .flat, 3) ++ builder_16.rectangle(464, 16, 64, 48) ++ builder_16.outlineFillRectangles(1, 4.0, .linear, .{ .point_0 = .{ .x = 496, .y = 80 }, .point_1 = .{ .x = 496, .y = 128 }, .color_0 = 1, .color_1 = 2 }, .linear, .{ .point_0 = .{ .x = 496, .y = 80 }, .point_1 = .{ .x = 496, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(464, 80, 64, 48) ++ builder_16.outlineFillRectangles(1, 5.0, .linear, .{ .point_0 = .{ .x = 496, .y = 144 }, .point_1 = .{ .x = 496, .y = 192 }, .color_0 = 1, .color_1 = 2 }, .radial, .{ .point_0 = .{ .x = 496, .y = 168 }, .point_1 = .{ .x = 496, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(464, 144, 64, 48) ++ builder_16.outlineFillRectangles(1, 6.0, .radial, .{ .point_0 = .{ .x = 576, .y = 40 }, .point_1 = .{ .x = 576, .y = 88 }, .color_0 = 1, .color_1 = 2 }, .flat, 3) ++ builder_16.rectangle(544, 16, 64, 48) ++ builder_16.outlineFillRectangles(1, 7.0, .radial, .{ .point_0 = .{ .x = 576, .y = 104 }, .point_1 = .{ .x = 576, .y = 150 }, .color_0 = 1, .color_1 = 2 }, .linear, .{ .point_0 = .{ .x = 576, .y = 80 }, .point_1 = .{ .x = 576, .y = 128 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(544, 80, 64, 48) ++ builder_16.outlineFillRectangles(1, 8.0, .radial, .{ .point_0 = .{ .x = 576, .y = 168 }, .point_1 = .{ .x = 576, .y = 216 }, .color_0 = 1, .color_1 = 2 }, .radial, .{ .point_0 = .{ .x = 576, .y = 168 }, .point_1 = .{ .x = 576, .y = 216 }, .color_0 = 3, .color_1 = 4 }) ++ builder_16.rectangle(544, 144, 64, 48) ++ // Outline Fill Polygon // TODO // PATH WITH ARC (ELLIPSE) builder_16.drawPath(3, 2.0, .flat, 1) ++ builder_16.point(16 + 0, 464 + 0) ++ builder_16.path.line(16 + 16, 464 + 16) ++ builder_16.path.arc_ellipse(25, 45, 15, false, false, 16 + 48, 464 + 48) ++ builder_16.path.line(16 + 64, 464 + 64) ++ builder_16.drawPath(3, 2.0, .flat, 1) ++ builder_16.point(96 + 0, 464 + 0) ++ builder_16.path.line(96 + 16, 464 + 16) ++ builder_16.path.arc_ellipse(25, 45, 15, false, true, 96 + 48, 464 + 48) ++ builder_16.path.line(96 + 64, 464 + 64) ++ builder_16.drawPath(3, 2.0, .flat, 1) ++ builder_16.point(176 + 0, 464 + 0) ++ builder_16.path.line(176 + 16, 464 + 16) ++ builder_16.path.arc_ellipse(25, 45, -35, true, true, 176 + 48, 464 + 48) ++ builder_16.path.line(176 + 64, 464 + 64) ++ builder_16.drawPath(3, 2.0, .flat, 1) ++ builder_16.point(256 + 0, 464 + 0) ++ builder_16.path.line(256 + 16, 464 + 16) ++ builder_16.path.arc_ellipse(25, 45, -35, true, false, 256 + 48, 464 + 48) ++ builder_16.path.line(256 + 64, 464 + 64) ++ builder_16.end_of_document; };
src/data/ground-truth.zig
const std = @import("std"); const Builder = std.build.Builder; pub fn build(b: *Builder) void { const fmt = b.addFmt(&[_][]const u8{ "src", "build.zig" }); { const panel = b.step("panel", "Build panel"); const mode = b.standardReleaseOptions(); const lib = b.addSharedLibrary("tenhourtime", "src/panel.zig", b.version(1, 0, 0)); lib.setBuildMode(mode); lib.linkLibC(); lib.linkSystemLibrary("gtk+-3.0"); lib.linkSystemLibrary("libxfce4panel-1.0"); lib.install(); panel.dependOn(&fmt.step); panel.dependOn(&lib.step); panel.dependOn(&lib.install_step.?.step); } { var cli = b.step("cli", "Build cli"); const mode = b.standardReleaseOptions(); const exe = b.addExecutable("tenhourtime", "src/cli.zig"); exe.setBuildMode(mode); exe.linkLibC(); exe.install(); cli.dependOn(&fmt.step); cli.dependOn(&exe.step); cli.dependOn(&exe.install_step.?.step); const runCmd = exe.run(); const runCli = b.step("run-cli", "Run cli"); runCli.dependOn(cli); runCli.dependOn(&runCmd.step); } { var testc = b.step("test", "Test code"); const mode = b.standardReleaseOptions(); const t = b.addTest("src/tenhourtime.zig"); t.setBuildMode(mode); t.linkLibC(); testc.dependOn(&t.step); } } //// Run a test //// b.addTest("src/file.zig") // pub fn addTest( //// Create a custom build step for the `zig build` command //// Example: //// ```zig //// const fmtStep = b.step("fmt", "Format code"); //// const fmt = builder.addFmt(&[_][]const u8{"src"}); //// fmtStep.dependOn(&fmt.step); //// ``` //// `zig build --help` will now show the fmt step and it can be used with `zig build fmt` // pub fn step( //// Create a step to format code with `zig fmt`. //// Example: //// ```zig //// const fmtStep = b.step("fmt", "Format code"); //// const fmt = builder.addFmt(&[_][]const u8{"src"}); //// fmtStep.dependOn(&fmt.step); //// ``` //// `zig build fmt` will now format all the code in src/ // pub fn addFmt(
build.zig
const std = @import("std"); const analysis = @import("./analysis.zig"); const types = @import("./types.zig"); const offsets = @import("./offsets.zig"); const URI = @import("./uri.zig"); const allocator = std.testing.allocator; fn makeDocument(uri: []const u8, text: []const u8) !types.TextDocument { const mem = try allocator.alloc(u8, text.len + 1); std.mem.copy(u8, mem, text); mem[text.len] = 0; return types.TextDocument{ .uri = uri, .mem = mem, .text = mem[0..text.len :0], }; } fn freeDocument(doc: types.TextDocument) void { allocator.free(doc.text); } fn makeUnnamedDocument(text: []const u8) !types.TextDocument { return try makeDocument("test", text); } fn testContext(comptime line: []const u8, comptime tag: anytype, comptime range: ?[]const u8) !void { const cursor_idx = comptime std.mem.indexOf(u8, line, "<cursor>").?; const final_line = line[0..cursor_idx] ++ line[cursor_idx + "<cursor>".len ..]; const doc = try makeUnnamedDocument(final_line); defer freeDocument(doc); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const p = try offsets.documentPosition(doc, .{ .line = 0, .character = @intCast(i64, cursor_idx) }, .utf8); const ctx = try analysis.documentPositionContext(&arena, doc, p); if (std.meta.activeTag(ctx) != tag) { std.debug.print("Expected tag {}, got {}\n", .{ tag, std.meta.activeTag(ctx) }); return error.DifferentTag; } if (ctx.range()) |ctx_range| { if (range == null) { std.debug.print("Expected null range, got `{s}`\n", .{ doc.text[ctx_range.start..ctx_range.end], }); } else { const range_start = comptime std.mem.indexOf(u8, final_line, range.?).?; const range_end = range_start + range.?.len; if (range_start != ctx_range.start or range_end != ctx_range.end) { std.debug.print("Expected range `{s}` ({}..{}), got `{s}` ({}..{})\n", .{ doc.text[range_start..range_end], range_start, range_end, doc.text[ctx_range.start..ctx_range.end], ctx_range.start, ctx_range.end, }); return error.DifferentRange; } } } else if (range != null) { std.debug.print("Unexpected null range\n", .{}); return error.DifferentRange; } } test "documentPositionContext" { try testContext( \\const this_var = id<cursor>entifier; , .var_access, "id", ); try testContext( \\if (displ.*.?.c.*[0].<cursor>@"a" == foo) { , .field_access, "displ.*.?.c.*[0].", ); try testContext( \\const arr = std.ArrayList(SomeStruct(a, b, c, d)).in<cursor>it(allocator); , .field_access, "std.ArrayList(SomeStruct(a, b, c, d)).in", ); try testContext( \\try erroringFn(the_first[arg], second[a..<cursor>]); , .empty, null, ); try testContext( \\ fn add(lhf: lself, rhs: rself) !Se<cursor> { , .var_access, "Se", ); } test "pathRelative and escapes" { const join1 = try URI.pathRelative(allocator, "file://project/zig", "/src/main+.zig"); defer allocator.free(join1); try std.testing.expectEqualStrings("file://project/zig/src/main%2B.zig", join1); const join2 = try URI.pathRelative(allocator, "file://project/zig/wow", "../]src]/]main.zig"); defer allocator.free(join2); try std.testing.expectEqualStrings("file://project/zig/%5Dsrc%5D/%5Dmain.zig", join2); }
src/unit_tests.zig
const std = @import("std"); const printf = std.io.stdout.printf; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Buffer = std.Buffer; const MdState = enum { Normal, FencedCodeBlock, }; const HeaderWeight = enum { H1, H2, H3, H4, H5, H6, }; const MdTextAttribute = enum { None, Italic, Bold, Code, }; const MdTextItem = enum { Buf: Buffer, Attr: MdTextAttribute, pub fn print(self: &const MdTextItem) -> %void { switch (*self) { MdTextItem.Buf => |b| { %return printf("'{}'", b.toSliceConst()); }, MdTextItem.Attr => |a| { %return printf("'{}'", @enumTagName(a)); } } } }; const MdText = ArrayList(MdTextItem); const MdHeader = struct { text: MdText, weight: HeaderWeight, }; const MdNode = enum { Header: MdHeader, Paragraph: MdText, pub fn print(self: &const MdNode) -> %void { switch (*self) { MdNode.Header => |header| { %return printf( \\Header {{ \\ text: ); for (header.text.toSliceConst()) |text| { %return text.print(); %return printf(", "); } %%printf( \\ \\ weight: {} \\}} \\ , @enumTagName(header.weight) ); }, MdNode.Paragraph => |para| { %return printf( \\Paragraph {{ \\ text: ); for (para.toSliceConst()) |text| { %return text.print(); %return printf(", "); } %return printf( \\ \\}} \\ ); }, } } }; error BadHeaderWeightValue; const MdParser = struct { const Self = this; allocator: &Allocator, nodes: ArrayList(MdNode), state: MdState, line_state: MdText, pub fn init(allocator: &Allocator) -> %Self { Self { .allocator = allocator, .nodes = ArrayList(MdNode).init(allocator), .state = MdState.Normal, .line_state = ArrayList(MdTextItem).init(allocator), } } fn parseText(self: &Self, line: []const u8) -> %MdText { var text = MdText.init(self.allocator); %defer text.deinit(); // For now, don't handle styles %return text.append(MdTextItem.Buf { %return Buffer.init(self.allocator, line), }); text } fn parseHeader(self: &Self, line: []const u8) -> %MdNode { var i: usize = 0; var weight: usize = 0; while (i < line.len) : (i += 1) { if (line[i] == '#') { weight += 1; } else { break; } } if (weight < @memberCount(HeaderWeight)) { // NOTE: Could we infer the inner types better for enums? const header = MdHeader { .text = %return self.parseText(line[i..]), .weight = HeaderWeight(weight - 1), }; MdNode.Header { header } } else { error.BadHeaderWeightValue } } pub fn parseLine(self: &Self, line: []const u8) -> %?MdNode { switch (self.state) { MdState.Normal => { if (line.len > 0 and line[0] == '#') { // NOTE: This is required else the return value is seen as %MdNode const header = %return self.parseHeader(line); header } else { if (line.len == 0) { // TODO: This implies we always follow paragraphs with an empty line. if (self.line_state.len != 0) { var pg = MdText.init(self.allocator); %defer pg.deinit(); %return pg.appendSlice(self.line_state.toSliceConst()); self.line_state.resizeDown(0); var paragraph = MdNode.Paragraph { pg }; paragraph } else { null } } else { var text = %return self.parseText(line); %return self.line_state.appendSlice(text.toSliceConst()); null } } }, MdState.FencedCodeBlock => { unreachable; }, } } pub fn parse(self: &Self, markdown: []const u8) -> %ArrayList(MdNode) { // The split iterator does not show new lines which we are interested in. var lines = iterateLines(markdown); while (lines.next()) |line| { if (self.parseLine(line)) |ok| { if (ok) |node| { %return self.nodes.append(node); } } else |err| { %return std.io.stderr.printf("{}\n", @errorName(err)); } } self.nodes } }; fn iterateLines(s: []const u8) -> LineIterator { LineIterator { .index = 0, .s = s, } } const LineIterator = struct { s: []const u8, index: usize, pub fn next(self: &LineIterator) -> ?[]const u8 { const start = self.index; if (start >= self.s.len) { return null; } self.index += 1; while (self.index < self.s.len and self.s[self.index] != '\n') { self.index += 1; } const end = self.index; if (start == 0) { self.s[start .. end] } else { self.s[start + 1 .. end] } } }; test "markdown" { const md1 = \\# Here is a title \\## Title 2 \\ \\Here is a paragraph, \\ followed on the same line \\ \\and a new paragraph \\ \\##### Following title ; var md = %%MdParser.init(&std.debug.global_allocator); const nodes = %%md.parse(md1); for (nodes.toSliceConst()) |node| { %%node.print(); } }
src/markdown.zig
const std = @import("std"); fn calculateChecksum(packet_data: []const u8) u8 { var result: u8 = 0; for (packet_data) |c| result +%= c; return result; } fn verifyChecksum(packet_data: []const u8, checksum: u8) !void { if (calculateChecksum(packet_data) != checksum) return error.BadChecksum; return; } pub const Stream = struct { reader: std.net.Stream.Reader, writer: std.net.Stream.Writer, pub fn init(stream: std.net.Stream) @This() { return .{ .reader = stream.reader(), .writer = stream.writer(), }; } pub const ReadSession = struct {}; pub fn readInto(self: @This(), buffer: []u8) ![]u8 { errdefer self.writer.writeByte('-') catch @panic("Couldn't send NAK!"); var first_byte = try self.reader.readByte(); while (first_byte != '$') { switch (first_byte) { '-' => std.log.err("Whoops, must have sent something valid bcuz gdb be mad bro", .{}), '+' => {}, else => std.log.err("Bad packet byte: 0x{X}", .{first_byte}), } first_byte = try self.reader.readByte(); } var used_size: usize = 0; while (true) { const b = try self.reader.readByte(); if (b == '#') { const cs = try std.fmt.parseUnsigned(u8, &try self.reader.readBytesNoEof(2), 16); const result = buffer[0..used_size]; try verifyChecksum(result, cs); try self.writer.writeByte('+'); std.log.info("->'{s}'", .{result}); //std.log.info("<-'+'", .{}); return result; } if (used_size == buffer.len) { return error.BufferFull; } buffer[used_size] = if (b == 0x7D) (try self.reader.readByte()) ^ 0x20 else b; used_size += 1; } } /// Send `data` as a gdb packet, retries until you probably should treat it as a fatal error. pub fn send(self: *@This(), data: []const u8) !void { var tries: usize = 0; while (tries < 1000) : (tries += 1) { var session = try self.startSendSession(); session.send(data) catch |err| { session.trash() catch {}; // Try to trash but don't care if it fails return err; }; session.finalize() catch |err| { switch (err) { //error.GdbDeniedPacket => continue, // Try sending the packet again else => return err, } }; return; } } pub const SendSession = struct { stream: *Stream, checksum: u8 = 0, fn doSendByte(self: *@This(), b: u8) callconv(.Inline) !void { try self.stream.writer.writeByte(b); self.checksum +%= b; } /// Add some bytes to this packet pub fn send(self: *@This(), data: []const u8) !void { std.log.info("<- Continue: '{s}'", .{data}); for (data) |b| { switch (b) { // Check if the byte needs escaping // https://sourceware.org/gdb/onlinedocs/gdb/Overview.html#Binary-Data 0x23, 0x24, 0x2A, 0x7D => { try self.doSendByte(0x7D); try self.doSendByte(b ^ 0x20); }, else => { try self.doSendByte(b); }, } } } fn sendChecksum(self: @This(), checksum: u8) callconv(.Inline) !void { try self.stream.writer.writeByte('#'); var checksum_buffer: [2]u8 = undefined; _ = std.fmt.bufPrint(&checksum_buffer, "{X:0>2}", .{checksum}) catch unreachable; try self.stream.writer.writeAll(&checksum_buffer); } /// Finish sending a packet pub fn finalize(self: @This()) !void { try self.sendChecksum(self.checksum); std.log.info("<- Finish", .{}); // We can't do the response reading yet, we need a "reader thread" or something similar to make sure // we can grab a byte here when there's another packet waiting, since we have to read that first. // const reply = try self.stream.reader.readByte(); // switch(reply) { // '-' => return error.GdbDeniedPacket, // '+' => return, // else => { // @panic("Bad GDB reply byte!"); // }, // } } /// Cancel sending a packet, GDB _should_ reject it since it has an invalid checksum /// A session is no longer valid after this. pub fn trash(self: @This()) !void { try self.sendChecksum(~self.checksum); // Send invalid checksum std.log.info("<- Cancel", .{}); // We should recieve a reply here too later } }; /// Session to send multiple slices of data in one gdb packet. Sending may fail. pub fn startSendSession(self: *@This()) !SendSession { std.log.info("<- Start", .{}); try self.writer.writeByte('$'); return SendSession{ .stream = self, }; } }; // pub fn sendPacket(data: []const u8, reader: *std.net.Stream.Reader, writer: *std.net.Stream.Writer) !void { // var tries: usize = 0; // while (tries < 10000) : (tries += 1) { // try writer.writeByte('$'); // try writer.writeAll(data); // try writer.writeByte('#'); // try writer.writeAll(&checksum_buffer); // std.log.info("<-'{s}'", .{data}); // _ = reader; // return; // // const reply = try reader.readByte(); // // switch(reply) { // // '-' => continue, // // '+' => { // // // // return; // // }, // // else => unreachable, // // } // } // return error.TooManyRetries; // }
src/lib/gdb.zig
const std = @import("std"); const testing = std.testing; const binary_search = @import("binary_search.zig"); const SearchError = binary_search.SearchError; test "finds a value in an array with one element" { comptime try testing.expectEqual(0, try binary_search.binarySearch(i4, 6, &[_]i4{6})); } test "finds a value in the middle of an array" { comptime try testing.expectEqual(3, try binary_search.binarySearch(u4, 6, &[_]u4{1, 3, 4, 6, 8, 9, 11})); } test "finds a value at the beginning of an array" { comptime try testing.expectEqual(0, try binary_search.binarySearch(i8, 1, &[_]i8{1, 3, 4, 6, 8, 9, 11})); } test "finds a value at the end of an array" { comptime try testing.expectEqual(6, try binary_search.binarySearch(u8, 11, &[_]u8{1, 3, 4, 6, 8, 9, 11})); } test "finds a value in an array of odd length" { comptime try testing.expectEqual(5, try binary_search.binarySearch(i16, 21, &[_]i16{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634})); } test "finds a value in an array of even length" { comptime try testing.expectEqual(5, try binary_search.binarySearch(u16, 21, &[_]u16{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377})); } test "identifies that a value is not included in the array" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(i32, 7, &[_]i32{1, 3, 4, 6, 8, 9, 11})); } test "a value smaller than the arrays smallest value is not found" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(u32, 0, &[_]u32{1, 3, 4, 6, 8, 9, 11})); } test "a value larger than the arrays largest value is not found" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(i64, 13, &[_]i64{1, 3, 4, 6, 8, 9, 11})); } test "nothing is found in an empty array" { try testing.expectError(SearchError.EmptyBuffer, binary_search.binarySearch(u64, 13, &[_]u64{})); } test "nothing is found when the left and right bounds cross" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(isize, 13, &[_]isize{1, 2})); }
exercises/practice/binary-search/test_binary_search.zig
pub extern "LALR" const zig_grammar = struct { const Precedence = struct { right: enum { Precedence_enumlit, }, left: enum { // AssignOp Equal, AsteriskEqual, SlashEqual, PercentEqual, PlusEqual, MinusEqual, AngleBracketAngleBracketLeftEqual, AngleBracketAngleBracketRightEqual, AmpersandEqual, CaretEqual, PipeEqual, AsteriskPercentEqual, PlusPercentEqual, MinusPercentEqual, }, right: enum { Keyword_break, Keyword_return, Keyword_continue, Keyword_resume, Keyword_cancel, Keyword_comptime, Keyword_promise, }, left: enum { Keyword_or, }, left: enum { Keyword_and, AmpersandAmpersand, }, left: enum { // CompareOp EqualEqual, BangEqual, AngleBracketLeft, AngleBracketRight, AngleBracketLeftEqual, AngleBracketRightEqual, }, left: enum { Keyword_orelse, Keyword_catch, }, left: enum { // Bitwise OR Pipe, }, left: enum { // Bitwise XOR Caret, }, left: enum { // Bitwise AND Ampersand, }, left: enum { AngleBracketAngleBracketLeft, AngleBracketAngleBracketRight, }, left: enum { Plus, Minus, PlusPlus, PlusPercent, MinusPercent, }, left: enum { Asterisk, Slash, Percent, AsteriskAsterisk, AsteriskPercent, PipePipe, }, right: enum { Keyword_try, Keyword_await, Precedence_not, Precedence_neg, Tilde, Precedence_ref, QuestionMark, }, right: enum { // x{} initializer LCurly, LBrace, // x.* x.? PeriodAsterisk, PeriodQuestionMark, }, left: enum { // a!b Bang, }, left: enum { LParen, LBracket, Period, }, left: enum { Precedence_async, }, }; fn Root(MaybeRootDocComment: ?*Node.DocComment, MaybeContainerMembers: ?*NodeList) *Node { const node = try parser.createNode(Node.Root); node.doc_comments = arg1; node.decls = if (arg2) |p| p.* else NodeList.init(parser.allocator); result = &node.base; } // DocComments fn MaybeDocComment() ?*Node.DocComment; fn MaybeDocComment(DocCommentLines: *TokenList) ?*Node.DocComment { const node = try parser.createNode(Node.DocComment); node.lines = arg1.*; result = node; } fn DocCommentLines(DocCommentLines: *TokenList, DocComment: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn DocCommentLines(DocComment: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MaybeRootDocComment() ?*Node.DocComment; fn MaybeRootDocComment(RootDocCommentLines: *TokenList) ?*Node.DocComment { const node = try parser.createNode(Node.DocComment); node.lines = arg1.*; result = node; } fn RootDocCommentLines(RootDocCommentLines: *TokenList, RootDocComment: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn RootDocCommentLines(RootDocComment: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } // Containers fn MaybeContainerMembers() ?*NodeList; fn MaybeContainerMembers(ContainerMembers: *NodeList) ?*NodeList; fn ContainerMembers(ContainerMembers: *NodeList, ContainerMember: *Node) *NodeList { result = arg1; try arg1.append(arg2); } fn ContainerMembers(ContainerMember: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, TestDecl: *Node.TestDecl) *Node { result = &arg2.base; arg2.doc_comments = arg1; } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, TopLevelComptime: *Node.Comptime) *Node { result = &arg2.base; arg2.doc_comments = arg1; } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, MaybePub: ?*Token, TopLevelDecl: *Node) *Node { result = arg3; if (arg3.cast(Node.VarDecl)) |node| { node.doc_comments = arg1; node.visib_token = arg2; } else if (arg3.cast(Node.FnProto)) |node| { node.doc_comments = arg1; node.visib_token = arg2; } else { const node = arg3.unsafe_cast(Node.Use); node.doc_comments = arg1; node.visib_token = arg2; } } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, MaybePub: ?*Token, ContainerField: *Node, Comma: *Token) *Node { result = arg3; const node = arg3.unsafe_cast(Node.ContainerField); node.doc_comments = arg1; node.visib_token = arg2; } // Test fn TestDecl(Keyword_test: *Token, StringLiteral: *Token, Block: *Node.Block) *Node.TestDecl { const name = try parser.createNode(Node.StringLiteral); name.token = arg2; const node = try parser.createNode(Node.TestDecl); node.test_token = arg1; node.name = &name.base; node.body_node = &arg3.base; result = node; } // Comptime fn TopLevelComptime(Keyword_comptime: *Token, BlockExpr: *Node) *Node.Comptime { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = node; } // TopLevel declarations fn TopLevelDecl(FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg1.base; } fn TopLevelDecl(FnProto: *Node.FnProto, Block: *Node.Block) *Node { arg1.body_node = &arg2.base; result = &arg1.base; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg3.base; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; arg3.extern_export_inline_token = arg1; arg3.lib_name = &lib_name.base; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg3.base; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; arg3.extern_export_inline_token = arg1; arg3.lib_name = &lib_name.base; arg3.body_node = &arg4.base; } fn TopLevelDecl(Keyword_export: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; } fn TopLevelDecl(Keyword_inline: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; } fn TopLevelDecl(Keyword_export: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; arg2.body_node = &arg3.base; } fn TopLevelDecl(Keyword_inline: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; arg2.body_node = &arg3.base; } fn TopLevelDecl(MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg2; const node = arg2.unsafe_cast(Node.VarDecl); node.thread_local_token = arg1; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg4; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; const node = arg4.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.lib_name = &lib_name.base; node.thread_local_token = arg3; } fn TopLevelDecl(Keyword_export: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg3; const node = arg3.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.thread_local_token = arg2; } fn TopLevelDecl(Keyword_extern: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg3; const node = arg3.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.thread_local_token = arg2; } fn TopLevelDecl(Keyword_usingnamespace: *Token, Expr: *Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Use); node.use_token = arg1; node.expr = arg2; node.semicolon_token = arg3; result = &node.base; } fn TopLevelDecl(Keyword_use: *Token, Expr: *Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Use); node.use_token = arg1; node.expr = arg2; node.semicolon_token = arg3; result = &node.base; } fn MaybeThreadlocal() ?*Token; fn MaybeThreadlocal(Keyword_threadlocal: *Token) ?*Token; // Functions fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .Explicit = arg8 }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .Explicit = arg9 }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg9 }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg10 }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg8; const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg9; const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg9; const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg10; const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base }; result = node; } // Variables fn VarDecl(Keyword_const: *Token, Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, MaybeEqualExpr: ?*Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.VarDecl); node.mut_token = arg1; node.name_token = arg2; node.type_node = arg3; node.align_node = arg4; node.section_node = arg5; node.init_node = arg6; node.semicolon_token = arg7; result = &node.base; } fn VarDecl(Keyword_var: *Token, Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, MaybeEqualExpr: ?*Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.VarDecl); node.mut_token = arg1; node.name_token = arg2; node.type_node = arg3; node.align_node = arg4; node.section_node = arg5; node.init_node = arg6; node.semicolon_token = arg7; result = &node.base; } // Container field fn ContainerField(Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeEqualExpr: ?*Node) *Node { const node = try parser.createNode(Node.ContainerField); node.name_token = arg1; node.type_expr = arg2; node.value_expr = arg3; result = &node.base; } // Statements fn MaybeStatements() ?*NodeList; fn MaybeStatements(Statements: *NodeList) ?*NodeList; fn Statements(Statement: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn Statements(Statements: *NodeList, Statement: *Node) *NodeList { result = arg1; try arg1.append(arg2); } fn Statement(Keyword_comptime: *Token, VarDecl: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(VarDecl: *Node) *Node; fn Statement(Keyword_comptime: *Token, BlockExpr: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(Keyword_suspend: *Token, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Suspend); node.suspend_token = arg1; result = &node.base; } fn Statement(Keyword_suspend: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Suspend); node.suspend_token = arg1; node.body = arg2; result = &node.base; } fn Statement(Keyword_defer: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Defer); node.defer_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(Keyword_errdefer: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Defer); node.defer_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(IfStatement: *Node) *Node; fn Statement(MaybeInline: ?*Token, ForStatement: *Node.For) *Node { result = &arg2.base; arg2.inline_token = arg1; } fn Statement(MaybeInline: ?*Token, WhileStatement: *Node.While) *Node { result = &arg2.base; arg2.inline_token = arg1; } fn Statement(LabeledStatement: *Node) *Node; fn Statement(SwitchExpr: *Node) *Node; fn Statement(AssignExpr: *Node, Semicolon: *Token) *Node { result = arg1; } fn IfStatement(IfPrefix: *Node.If, BlockExpr: *Node) *Node { result = &arg1.base; arg1.body = arg2; } fn IfStatement(IfPrefix: *Node.If, BlockExpr: *Node, ElseStatement: *Node.Else) *Node { result = &arg1.base; arg1.body = arg2; arg1.@"else" = arg3; } fn IfStatement(IfPrefix: *Node.If, AssignExpr: *Node, Semicolon: *Token) *Node { result = &arg1.base; arg1.body = arg2; } fn IfStatement(IfPrefix: *Node.If, AssignExpr: *Node, ElseStatement: *Node.Else) *Node { result = &arg1.base; arg1.body = arg2; arg1.@"else" = arg3; } fn ElseStatement(Keyword_else: *Token, MaybePayload: ?*Node, Statement: *Node) *Node.Else { const node = try parser.createNode(Node.Else); node.else_token = arg1; node.payload = arg2; node.body = arg3; result = node; } fn LabeledStatement(BlockLabel: *Token, MaybeInline: ?*Token, ForStatement: *Node.For) *Node { result = &arg3.base; arg3.label = arg1; arg3.inline_token = arg2; } fn LabeledStatement(BlockLabel: *Token, MaybeInline: ?*Token, WhileStatement: *Node.While) *Node { result = &arg3.base; arg3.label = arg1; arg3.inline_token = arg2; } fn LabeledStatement(BlockExpr: *Node) *Node; fn ForStatement(ForPrefix: *Node.For, BlockExpr: *Node) *Node.For { result = arg1; arg1.body = arg2; } fn ForStatement(ForPrefix: *Node.For, BlockExpr: *Node, ElseNoPayloadStatement: *Node.Else) *Node.For { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn ForStatement(ForPrefix: *Node.For, AssignExpr: *Node, Semicolon: *Token) *Node.For { result = arg1; arg1.body = arg2; } fn ForStatement(ForPrefix: *Node.For, AssignExpr: *Node, ElseNoPayloadStatement: *Node.Else) *Node.For { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn ElseNoPayloadStatement(Keyword_else: *Token, Statement: *Node) *Node.Else { const node = try parser.createNode(Node.Else); node.else_token = arg1; node.body = arg2; result = node; } fn WhileStatement(WhilePrefix: *Node.While, BlockExpr: *Node) *Node.While { result = arg1; arg1.body = arg2; } fn WhileStatement(WhilePrefix: *Node.While, BlockExpr: *Node, ElseStatement: *Node.Else) *Node.While { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn WhileStatement(WhilePrefix: *Node.While, AssignExpr: *Node, Semicolon: *Token) *Node.While { result = arg1; arg1.body = arg2; } fn WhileStatement(WhilePrefix: *Node.While, AssignExpr: *Node, ElseStatement: *Node.Else) *Node.While { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn BlockExprStatement(BlockExpr: *Node) *Node; fn BlockExprStatement(AssignExpr: *Node, Semicolon: *Token) *Node { result = arg1; } // Expression level fn AssignExpr(Expr: *Node, AsteriskEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignTimes; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, SlashEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignDiv; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMod; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PlusEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignPlus; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, MinusEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMinus; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AngleBracketAngleBracketLeftEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitShiftLeft; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AngleBracketAngleBracketRightEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitShiftRight; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AmpersandEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitAnd; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, CaretEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitXor; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PipeEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitOr; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AsteriskPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignTimesWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PlusPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignPlusWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, MinusPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMinusWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, Equal: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Assign; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node) *Node; fn MaybeEqualExpr() ?*Node; fn MaybeEqualExpr(Equal: *Token, Expr: *Node) ?*Node { result = arg2; } // Recovery fn Expr(Recovery: *Token) *Node { const node = try parser.createNode(Node.Recovery); node.token = arg1; result = &node.base; } // Grouped fn Expr(LParen: *Token, Expr: *Node, RParen: *Token) *Node { if (arg2.id != .GroupedExpression) { const node = try parser.createNode(Node.GroupedExpression); node.lparen = arg1; node.expr = arg2; node.rparen = arg3; result = &node.base; } else result = arg2; } // Infix fn Expr(Expr: *Node, Keyword_orelse: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .UnwrapOptional; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Keyword_catch: *Token, MaybePayload: ?*Node, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = Node.InfixOp.Op{ .Catch = arg3 }; node.rhs = arg4; result = &node.base; } fn Expr(Expr: *Node, Keyword_or: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolOr; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AmpersandAmpersand: *Token, Expr: *Node) *Node { try parser.reportError(ParseError.AmpersandAmpersand, arg2); const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Keyword_and: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, EqualEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .EqualEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, BangEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BangEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketLeft: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .LessThan; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .GreaterThan; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketLeftEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .LessOrEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketRightEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .GreaterOrEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Pipe: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitOr; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Caret: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitXor; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Ampersand: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketAngleBracketLeft: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitShiftLeft; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketAngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitShiftRight; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Plus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Add; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Minus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Sub; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PlusPlus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ArrayCat; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PlusPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AddWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, MinusPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .SubWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Asterisk: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Div; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Slash: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Div; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Percent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Mod; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AsteriskAsterisk: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ArrayMult; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AsteriskPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .MultWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PipePipe: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ErrorUnion; node.rhs = arg3; result = &node.base; } // Prefix fn Expr(Bang: Precedence_not(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .BoolNot; node.rhs = arg2; result = &node.base; } fn Expr(Minus: Precedence_neg(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Negation; node.rhs = arg2; result = &node.base; } fn Expr(MinusPercent: Precedence_neg(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .NegationWrap; node.rhs = arg2; result = &node.base; } fn Expr(Tilde: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .BitNot; node.rhs = arg2; result = &node.base; } fn Expr(Ampersand: Precedence_ref(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .AddressOf; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_async: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Async; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_try: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Try; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_await: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Await; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_comptime: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } // Primary fn Expr(AsmExpr: *Node) *Node; fn Expr(Keyword_resume: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Resume; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_cancel: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Cancel; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_break: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = null }; result = &node.base; } fn Expr(Keyword_break: *Token, BreakLabel: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 }; result = &node.base; } fn Expr(Keyword_break: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = null }; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_break: *Token, BreakLabel: *Node, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 }; node.rhs = arg3; result = &node.base; } fn Expr(Keyword_continue: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Continue = null }; result = &node.base; } fn Expr(Keyword_continue: *Token, BreakLabel: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Continue = arg2 }; result = &node.base; } fn Expr(Keyword_return: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = .Return; result = &node.base; } fn Expr(Keyword_return: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = .Return; node.rhs = arg2; result = &node.base; } // Initializer list fn Expr(Expr: *Node, LCurly: *Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .ArrayInitializer = NodeList.init(parser.allocator) }; node.rtoken = arg3; result = &node.base; } fn Expr(Expr: *Node, LCurly: *Token, InitList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = init: { if (arg3.at(0).cast(Node.InfixOp)) |infix| { switch (infix.op) { // StructInitializer .Assign => break :init Node.SuffixOp.Op{ .StructInitializer = arg3.* }, else => {}, } } // ArrayInitializer break :init Node.SuffixOp.Op{ .ArrayInitializer = arg3.* }; }; node.rtoken = arg5; result = &node.base; } // Prefix fn Expr(QuestionMark: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .OptionalType; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_promise: *Token) *Node { const node = try parser.createNode(Node.PromiseType); node.promise_token = arg1; result = &node.base; } fn Expr(Keyword_promise: *Token, MinusAngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PromiseType); node.promise_token = arg1; node.result = Node.PromiseType.Result{ .arrow_token = arg2, .return_type = arg3 }; result = &node.base; } // ArrayType fn Expr(LBracket: *Token, Expr: *Node, RBracket: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .ArrayType = arg2 }; node.rhs = arg4; result = &node.base; } // SliceType fn Expr(LBracket: *Token, RBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .SliceType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg3, .align_info = if (arg4) |p| p.* else null, .const_token = arg5, .volatile_token = arg6 } }; node.rhs = arg7; result = &node.base; } // PtrType fn Expr(Asterisk: Precedence_none(*Token), MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } fn Expr(AsteriskAsterisk: Precedence_none(*Token), MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { arg1.id = .Asterisk; const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; const outer = try parser.createNode(Node.PrefixOp); outer.op_token = arg1; outer.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = null, .align_info = null, .const_token = null, .volatile_token = null } }; outer.rhs = &node.base; result = &outer.base; } fn Expr(BracketStarBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } fn Expr(BracketStarCBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } // Block fn Expr(BlockExpr: Shadow(*Node)) *Node; fn BlockExpr(Block: *Node.Block) *Node { result = &arg1.base; } fn BlockExpr(BlockLabel: *Token, Block: *Node.Block) *Node { result = &arg2.base; arg2.label = arg1; } fn Block(LBrace: *Token, MaybeStatements: ?*NodeList, RBrace: *Token) *Node.Block { const node = try parser.createNode(Node.Block); node.lbrace = arg1; node.statements = if (arg2) |p| p.* else NodeList.init(parser.allocator); node.rbrace = arg3; result = node; } fn BlockLabel(Identifier: *Token, Colon: *Token) *Token { result = arg1; } // ErrorType fn Expr(Expr: *Node, Bang: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ErrorUnion; node.rhs = arg3; result = &node.base; } // Literals fn Expr(Identifier: *Token) *Node { const node = try parser.createNode(Node.Identifier); node.token = arg1; result = &node.base; } fn Expr(CharLiteral: *Token) *Node { const node = try parser.createNode(Node.CharLiteral); node.token = arg1; result = &node.base; } fn Expr(FloatLiteral: *Token) *Node { const node = try parser.createNode(Node.FloatLiteral); node.token = arg1; result = &node.base; } fn Expr(IntegerLiteral: *Token) *Node { const node = try parser.createNode(Node.IntegerLiteral); node.token = arg1; result = &node.base; } fn Expr(StringLiteral: *Token) *Node { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = &node.base; } fn Expr(MultilineStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn Expr(MultilineCStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn Expr(Period: Precedence_enumlit(*Token), Identifier: *Token) *Node { const node = try parser.createNode(Node.EnumLiteral); node.dot = arg1; node.name = arg2; result = &node.base; } // Simple types fn Expr(Keyword_error: *Token, Period: *Token, Identifier: *Token) *Node { const err = try parser.createNode(Node.ErrorType); err.token = arg1; const name = try parser.createNode(Node.Identifier); name.token = arg3; const infix = try parser.createNode(Node.InfixOp); infix.lhs = &err.base; infix.op_token = arg2; infix.op = .Period; infix.rhs = &name.base; result = &infix.base; } fn Expr(Keyword_error: *Token, LCurly: Precedence_none(*Token), RBrace: *Token) *Node { const error_set = try parser.createNode(Node.ErrorSetDecl); error_set.error_token = arg1; error_set.decls = NodeList.init(parser.allocator); error_set.rbrace_token = arg3; result = &error_set.base; } fn Expr(Keyword_error: *Token, LCurly: Precedence_none(*Token), ErrorTagList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const error_set = try parser.createNode(Node.ErrorSetDecl); error_set.error_token = arg1; error_set.decls = arg3.*; error_set.rbrace_token = arg5; result = &error_set.base; } fn Expr(Keyword_false: *Token) *Node { const node = try parser.createNode(Node.BoolLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_true: *Token) *Node { const node = try parser.createNode(Node.BoolLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_null: *Token) *Node { const node = try parser.createNode(Node.NullLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_undefined: *Token) *Node { const node = try parser.createNode(Node.UndefinedLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_unreachable: *Token) *Node { const node = try parser.createNode(Node.Unreachable); node.token = arg1; result = &node.base; } // Flow types fn Expr(SwitchExpr: Shadow(*Node)) *Node; // IfExpr fn Expr(IfPrefix: *Node.If, Expr: *Node) *Node { result = &arg1.base; arg1.body = arg2; } fn Expr(IfPrefix: *Node.If, Expr: *Node, Keyword_else: *Token, MaybePayload: ?*Node, Expr: *Node) *Node { result = &arg1.base; const node = try parser.createNode(Node.Else); node.else_token = arg3; node.payload = arg4; node.body = arg5; arg1.body = arg2; arg1.@"else" = node; } // Builtin calls fn Expr(Builtin: *Token, LParen: *Token, MaybeExprList: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.BuiltinCall); node.builtin_token = arg1; node.params = if (arg3) |p| p.* else NodeList.init(parser.allocator); node.rparen_token = arg4; result = &node.base; } // FunctionType fn Expr(FnProto: *Node.FnProto) *Node { result = &arg1.base; } // a[] fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .ArrayAccess = arg3 }; node.rtoken = arg4; result = &node.base; } fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, Ellipsis2: *Token, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = null } }; node.rtoken = arg5; result = &node.base; } fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, Ellipsis2: *Token, Expr: *Node, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = arg5 } }; node.rtoken = arg6; result = &node.base; } // a.b fn Expr(Expr: *Node, Period: *Token, Identifier: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const infix = try parser.createNode(Node.InfixOp); infix.lhs = arg1; infix.op_token = arg2; infix.op = .Period; infix.rhs = &name.base; result = &infix.base; } // a.* fn Expr(Expr: *Node, PeriodAsterisk: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = .Deref; node.rtoken = arg2; result = &node.base; } // a.? fn Expr(Expr: *Node, PeriodQuestionMark: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = .UnwrapOptional; node.rtoken = arg2; result = &node.base; } // a() fn Expr(Expr: *Node, LParen: *Token, MaybeExprList: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Call = Node.SuffixOp.Op.Call{ .params = if (arg3) |p| p.* else NodeList.init(parser.allocator) } }; node.rtoken = arg4; result = &node.base; } // Containers (struct/enum/union) fn Expr(ContainerDecl: *Node) *Node; fn ContainerDecl(ContainerDeclOp: *Token, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = .None; node.lbrace_token = arg2; node.fields_and_decls = if (arg3) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg4; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, ContainerDeclOp: *Token, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = .None; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(Keyword_enum: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_enum: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } fn ContainerDecl(Keyword_union: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_union: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } fn ContainerDecl(Keyword_union: *Token, ContainerDeclTypeEnum: ?*Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_union: *Token, ContainerDeclTypeEnum: ?*Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } // ContainerDecl helper fn ExternPacked(Keyword_extern: *Token) *Token; fn ExternPacked(Keyword_packed: *Token) *Token; fn SwitchExpr(Keyword_switch: *Token, LParen: *Token, Expr: *Node, RParen: *Token, LBrace: *Token, SwitchProngList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.Switch); node.switch_token = arg1; node.expr = arg3; node.cases = arg6.*; node.rbrace = arg8; result = &node.base; } // Assembly fn String(StringLiteral: *Token) *Node { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = &node.base; } fn String(MultilineStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn String(MultilineCStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = NodeList.init(parser.allocator); node.inputs = NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg5; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg6; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, AsmInput: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg7; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, AsmInput: ?*NodeList, AsmClobber: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator); node.clobbers = if (arg7) |p| p.* else NodeList.init(parser.allocator); node.rparen = arg8; result = &node.base; } fn AsmOutput(Colon: *Token) ?*NodeList { result = null; } fn AsmOutput(Colon: *Token, AsmOutputList: *NodeList) ?*NodeList { result = arg2; } fn AsmOutputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, Identifier: *Token, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const variable = try parser.createNode(Node.Identifier); variable.token = arg6; const node = try parser.createNode(Node.AsmOutput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.kind = Node.AsmOutput.Kind{ .Variable = variable }; node.rparen = arg7; result = &node.base; } fn AsmOutputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, MinusAngleBracketRight: *Token, Expr: *Node, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.AsmOutput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.kind = Node.AsmOutput.Kind{ .Return = arg7 }; node.rparen = arg8; result = &node.base; } fn AsmInput(Colon: *Token) ?*NodeList { result = null; } fn AsmInput(Colon: *Token, AsmInputList: *NodeList) ?*NodeList { result = arg2; } fn AsmInputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, Expr: *Node, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.AsmInput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.expr = arg6; node.rparen = arg7; result = &node.base; } fn AsmClobber(Colon: *Token) ?*NodeList { result = null; } fn AsmClobber(Colon: *Token, StringList: *NodeList) ?*NodeList { result = arg2; } // Helper grammar fn BreakLabel(Colon: *Token, Identifier: *Token) *Node { const node = try parser.createNode(Node.Identifier); node.token = arg2; result = &node.base; } fn MaybeLinkSection() ?*Node; fn MaybeLinkSection(Keyword_linksection: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node { result = arg3; } // Function specific fn FnCC(Keyword_nakedcc: *Token) *Token; fn FnCC(Keyword_stdcallcc: *Token) *Token; fn FnCC(Keyword_extern: *Token) *Token; fn FnCC(Keyword_async: *Token) *Token; fn ParamDecl(MaybeNoalias: ?*Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg2; arg2.noalias_token = arg1; } fn ParamDecl(MaybeNoalias: ?*Token, Identifier: *Token, Colon: *Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg4; arg4.noalias_token = arg1; arg4.name_token = arg2; } fn ParamDecl(MaybeNoalias: ?*Token, Keyword_comptime: *Token, Identifier: *Token, Colon: *Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg5; arg5.noalias_token = arg1; arg5.comptime_token = arg2; arg5.name_token = arg3; } fn ParamType(Keyword_var: *Token) *Node.ParamDecl { const vtype = try parser.createNode(Node.VarType); vtype.token = arg1; const node = try parser.createNode(Node.ParamDecl); node.type_node = &vtype.base; result = node; } fn ParamType(Ellipsis3: *Token) *Node.ParamDecl { const node = try parser.createNode(Node.ParamDecl); node.var_args_token = arg1; result = node; } fn ParamType(Expr: *Node) *Node.ParamDecl { const node = try parser.createNode(Node.ParamDecl); node.type_node = arg1; result = node; } // Control flow prefixes fn IfPrefix(Keyword_if: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node) *Node.If { const node = try parser.createNode(Node.If); node.if_token = arg1; node.condition = arg3; node.payload = arg5; result = node; } fn ForPrefix(Keyword_for: *Token, LParen: *Token, Expr: *Node, RParen: *Token, PtrIndexPayload: *Node) *Node.For { const node = try parser.createNode(Node.For); node.for_token = arg1; node.array_expr = arg3; node.payload = arg5; result = node; } fn WhilePrefix(Keyword_while: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node) *Node.While { const node = try parser.createNode(Node.While); node.while_token = arg1; node.condition = arg3; node.payload = arg5; result = node; } fn WhilePrefix(Keyword_while: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node, Colon: *Token, LParen: *Token, AssignExpr: *Node, RParen: *Token) *Node.While { const node = try parser.createNode(Node.While); node.while_token = arg1; node.condition = arg3; node.payload = arg5; node.continue_expr = arg8; result = node; } // Payloads fn MaybePayload() ?*Node; fn MaybePayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.Payload); node.lpipe = arg1; node.error_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn MaybePtrPayload() ?*Node; fn MaybePtrPayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.PointerPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn MaybePtrPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const node = try parser.createNode(Node.PointerPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.rpipe = arg4; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.rpipe = arg4; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Identifier: *Token, Comma: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const index = try parser.createNode(Node.Identifier); index.token = arg4; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.index_symbol = &index.base; node.rpipe = arg5; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Comma: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const index = try parser.createNode(Node.Identifier); index.token = arg5; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.index_symbol = &index.base; node.rpipe = arg6; result = &node.base; } // Switch specific fn SwitchProng(SwitchCase: *Node.SwitchCase, EqualAngleBracketRight: *Token, MaybePtrPayload: ?*Node, AssignExpr: *Node) *Node { result = &arg1.base; arg1.arrow_token = arg2; arg1.payload = arg3; arg1.expr = arg4; } fn SwitchCase(Keyword_else: *Token) *Node.SwitchCase { const else_node = try parser.createNode(Node.SwitchElse); else_node.token = arg1; const node = try parser.createNode(Node.SwitchCase); node.items = NodeList.init(parser.allocator); try node.items.append(&else_node.base); result = node; } fn SwitchCase(SwitchItems: *NodeList, MaybeComma: ?*Token) *Node.SwitchCase { const node = try parser.createNode(Node.SwitchCase); node.items = arg1.*; result = node; } fn SwitchItems(SwitchItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn SwitchItems(SwitchItems: *NodeList, Comma: *Token, SwitchItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn SwitchItem(Expr: *Node) *Node; fn SwitchItem(Expr: *Node, Ellipsis3: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Range; node.rhs = arg3; result = &node.base; } fn MaybeVolatile() ?*Token; fn MaybeVolatile(Keyword_volatile: *Token) ?*Token; fn MaybeAllowzero() ?*Token; fn MaybeAllowzero(Keyword_allowzero: *Token) ?*Token; // ContainerDecl specific fn ContainerDeclTypeEnum(LParen: *Token, Keyword_enum: *Token, RParen: *Token) ?*Node; fn ContainerDeclTypeEnum(LParen: *Token, Keyword_enum: *Token, LParen: *Token, Expr: *Node, RParen: *Token, RParen: *Token) ?*Node { result = arg4; } fn ContainerDeclTypeType(LParen: *Token, Expr: *Node, RParen: *Token) *Node { result = arg2; } fn ContainerDeclOp(Keyword_struct: *Token) *Token; fn ContainerDeclOp(Keyword_union: *Token) *Token; fn ContainerDeclOp(Keyword_enum: *Token) *Token; // Alignment fn MaybeByteAlign() ?*Node; fn MaybeByteAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node { result = arg3; } fn MaybeAlign() ?*Node.PrefixOp.PtrInfo.Align; fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = arg3; result = value; } fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, Colon: *Token, IntegerLiteral: *Token, Colon: *Token, IntegerLiteral: *Token, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const start = try parser.createNode(Node.IntegerLiteral); start.token = arg5; const end = try parser.createNode(Node.IntegerLiteral); end.token = arg7; const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = arg3; value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base }; result = value; } fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Identifier: *Token, Colon: *Token, IntegerLiteral: *Token, Colon: *Token, IntegerLiteral: *Token, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const node = try parser.createNode(Node.Identifier); node.token = arg3; const start = try parser.createNode(Node.IntegerLiteral); start.token = arg5; const end = try parser.createNode(Node.IntegerLiteral); end.token = arg7; const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = &node.base; value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base }; result = value; } // Lists fn ErrorTagList(MaybeDocComment: ?*Node.DocComment, Identifier: *Token) *NodeList { const node = try parser.createNode(Node.ErrorTag); node.doc_comments = arg1; node.name_token = arg2; result = try parser.createListWithNode(NodeList, &node.base); } fn ErrorTagList(ErrorTagList: *NodeList, Comma: *Token, MaybeDocComment: ?*Node.DocComment, Identifier: *Token) *NodeList { result = arg1; const node = try parser.createNode(Node.ErrorTag); node.doc_comments = arg3; node.name_token = arg4; try arg1.append(&node.base); } fn SwitchProngList(SwitchProng: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn SwitchProngList(SwitchProngList: *NodeList, Comma: *Token, SwitchProng: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn AsmOutputList(AsmOutputItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn AsmOutputList(AsmOutputList: *NodeList, Comma: *Token, AsmOutputItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn AsmInputList(AsmInputItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn AsmInputList(AsmInputList: *NodeList, Comma: *Token, AsmInputItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn StringList(StringLiteral: *Token) *NodeList { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = try parser.createListWithNode(NodeList, &node.base); } fn StringList(StringList: *NodeList, Comma: *Token, StringLiteral: *Token) *NodeList { result = arg1; const node = try parser.createNode(Node.StringLiteral); node.token = arg3; try arg1.append(&node.base); } fn MaybeParamDeclList() ?*NodeList; fn MaybeParamDeclList(ParamDeclList: *NodeList, MaybeComma: ?*Token) *NodeList { result = arg1; } fn ParamDeclList(MaybeDocComment: ?*Node.DocComment, ParamDecl: *Node.ParamDecl) *NodeList { arg2.doc_comments = arg1; result = try parser.createListWithNode(NodeList, &arg2.base); } fn ParamDeclList(ParamDeclList: *NodeList, Comma: *Token, MaybeDocComment: ?*Node.DocComment, ParamDecl: *Node.ParamDecl) *NodeList { result = arg1; arg4.doc_comments = arg3; try arg1.append(&arg4.base); } fn MaybeExprList() ?*NodeList {} fn MaybeExprList(ExprList: *NodeList, MaybeComma: ?*Token) ?*NodeList { result = arg1; } fn ExprList(Expr: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn ExprList(ExprList: *NodeList, Comma: *Token, Expr: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn InitList(Expr: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn InitList(Period: *Token, Identifier: *Token, Equal: *Token, Expr: *Node) *NodeList { const node = try parser.createNode(Node.FieldInitializer); node.period_token = arg1; node.name_token = arg2; node.expr = arg4; result = try parser.createListWithNode(NodeList, &node.base); } fn InitList(InitList: *NodeList, Comma: *Token, Expr: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn InitList(InitList: *NodeList, Comma: *Token, Period: *Token, Identifier: *Token, Equal: *Token, Expr: *Node) *NodeList { result = arg1; const node = try parser.createNode(Node.FieldInitializer); node.period_token = arg3; node.name_token = arg4; node.expr = arg6; try arg1.append(&node.base); } // Various helpers fn MaybePub() ?*Token; fn MaybePub(Keyword_pub: *Token) ?*Token; fn MaybeColonTypeExpr() ?*Node; fn MaybeColonTypeExpr(Colon: *Token, Expr: *Node) ?*Node { result = arg2; } fn MaybeExpr() ?*Node; fn MaybeExpr(Expr: *Node) ?*Node; fn MaybeNoalias() ?*Token; fn MaybeNoalias(Keyword_noalias: *Token) ?*Token; fn MaybeInline() ?*Token; fn MaybeInline(Keyword_inline: *Token) ?*Token; fn MaybeIdentifier() ?*Token; fn MaybeIdentifier(Identifier: *Token) ?*Token; fn MaybeComma() ?*Token; fn MaybeComma(Comma: *Token) ?*Token; fn MaybeConst() ?*Token; fn MaybeConst(Keyword_const: *Token) ?*Token; fn MultilineStringLiteral(LineString: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MultilineStringLiteral(MultilineStringLiteral: *TokenList, LineString: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn MultilineCStringLiteral(LineCString: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MultilineCStringLiteral(MultilineCStringLiteral: *TokenList, LineCString: *Token) *TokenList { result = arg1; try arg1.append(arg2); } };
zig/ziglang.zig
const stdm = @import("std").math; pub const colorsRGB8 = @import("ColorRGB8.zig"); pub const colorsRGBA8 = @import("ColorRGBA8.zig"); pub const colorsRGBA = @import("ColorRGBA.zig"); pub const colorsRGB = @import("ColorRGB.zig"); fn ColorEquals(comptime colorType: type, lhs: *const colorType, rhs: *const colorType) bool { const fieldNames = .{ "r", "g", "b", "a", "h", "s", "v", }; for (fieldNames) |fieldName| { if (@hasField(colorType, fieldName)) { if (@field(lhs, fieldName) != @field(rhs, fieldName)) return false; } } return true; } pub const ColorRGB = packed struct { r: f32, g: f32, b: f32, pub fn Equals(self: *const ColorRGB, other: *const ColorRGB) bool { return ColorEquals(ColorRGB, self, other); } }; pub const ColorRGB8 = packed struct { r: u8, g: u8, b: u8, pub fn Equals(self: *const ColorRGB8, other: *const ColorRGB8) bool { return ColorEquals(ColorRGB8, self, other); } }; pub const ColorRGBA = packed struct { r: f32, g: f32, b: f32, a: f32, pub fn Equals(self: *const ColorRGBA, other: *const ColorRGBA) bool { return ColorEquals(ColorRGBA, self, other); } }; pub const ColorRGBA8 = packed struct { r: u8, g: u8, b: u8, a: u8, pub fn Equals(self: *const ColorRGBA8, other: *const ColorRGBA8) bool { return ColorEquals(ColorRGBA8, self, other); } }; pub const ColorHSV = packed struct { h: f32, // angle in degrees s: f32, // 0 to 1 v: f32, // 0 to 1 pub fn Equals(self: *const ColorHSV, other: *const ColorHSV) bool { return ColorEquals(ColorHSV, self, other); } }; // FromHSV //TODO HSV8 / RGB8 version pub fn HSVToRGB(color: *const ColorHSV) ColorRGB { if (color.s == 0.0) { // grey-scale return ColorRGB{ .r = color.v, .g = color.v, .b = color.v }; } const hh = color.h / 60.0; const i = @floatToInt(u8, hh); const ff = hh - @intToFloat(f32, i); const p = color.v * (1.0 - color.s); const q = color.v * (1.0 - (color.s * ff)); const t = color.v * (1.0 - (color.s * (1.0 - ff))); return switch (i) { 0 => ColorRGB{ .r = color.v, .g = t, .b = p }, 1 => ColorRGB{ .r = q, .g = color.v, .b = p }, 2 => ColorRGB{ .r = p, .g = color.v, .b = t }, 3 => ColorRGB{ .r = p, .g = q, .b = color.v }, 4 => ColorRGB{ .r = t, .g = p, .b = color.v }, else => ColorRGB{ .r = color.v, .g = p, .b = q }, }; } // ToHSV //TODO HSV8 / RGB8 version pub fn RGBToHSV(color: *const ColorRGB) ColorHSV { const min = stdm.min(stdm.min(color.r, color.g), color.b); const max = stdm.max(stdm.max(color.r, color.g), color.b); const delta = max - min; var outHSV = ColorHSV{ .h = 0.0, .s = 0.0, .v = max }; if (delta < stdm.f32_epsilon) //grey-scale color { return outHSV; } else { outHSV.s = (delta / max); } if (color.r >= max) { outHSV.h = (color.g - color.b) / delta; // between magenta & yellow } else { if (color.g >= max) { outHSV.h = 2.0 + (color.b - color.r) / delta; // between cyan & yellow } else { outHSV.h = 4.0 + (color.r - color.g) / delta; // between magenta & cyan } } outHSV.h *= 60.0; // degrees if (outHSV.h < 0.0) outHSV.h += 360.0; return outHSV; } // ToRGB pub fn RGB8ToRGB(color: *const ColorRGB8) ColorRGB { return ColorRGB{ .r = @intToFloat(f32, color.r) / 255.0, .g = @intToFloat(f32, color.g) / 255.0, .b = @intToFloat(f32, color.b) / 255.0, }; } pub fn RGBAToRGB(color: *const ColorRGBA) ColorRGB { return ColorRGB{ .r = color.r, .g = color.g, .b = color.b, }; } pub fn RGBA8ToRGB(color: *const ColorRGBA8) ColorRGB { return ColorRGB{ .r = color.r, .g = color.g, .b = color.b, }; } // ToRGB8 pub fn RGBToRGB8(color: *const ColorRGB) ColorRGB8 { return ColorRGB8{ .r = @floatToInt(u8, stdm.round(color.r * 255.0)), .g = @floatToInt(u8, stdm.round(color.g * 255.0)), .b = @floatToInt(u8, stdm.round(color.b * 255.0)), }; } pub fn RGBAToRGB8(color: *const ColorRGBA) ColorRGB8 { return ColorRGB8{ .r = @floatToInt(u8, stdm.round(color.r * 255.0)), .g = @floatToInt(u8, stdm.round(color.g * 255.0)), .b = @floatToInt(u8, stdm.round(color.b * 255.0)), }; } pub fn RGBA8ToRGB8(color: *const ColorRGB) ColorRGB8 { return ColorRGB8{ .r = color.r, .g = color.g, .b = color.b, }; } // ToRGBA pub fn RGBToRGBA(color: *const ColorRGB) ColorRGBA { return ColorRGBA{ .r = color.r, .g = color.g, .b = color.b, .a = 1.0, }; } pub fn RGB8ToRGBA(color: *const ColorRGB8) ColorRGBA { return ColorRGBA{ .r = @intToFloat(f32, color.r) / 255.0, .g = @intToFloat(f32, color.g) / 255.0, .b = @intToFloat(f32, color.b) / 255.0, .a = 1.0, }; } pub fn RGBA8ToRGBA(color: *const ColorRGBA8) ColorRGBA { return ColorRGBA{ .r = @intToFloat(f32, color.r) / 255.0, .g = @intToFloat(f32, color.g) / 255.0, .b = @intToFloat(f32, color.b) / 255.0, .a = @intToFloat(f32, color.a) / 255.0, }; } // ToRGBA8 pub fn RGBToRGBA8(color: *const ColorRGB) ColorRGBA8 { return ColorRGBA8{ .r = @floatToInt(u8, stdm.round(color.r * 255.0)), .g = @floatToInt(u8, stdm.round(color.g * 255.0)), .b = @floatToInt(u8, stdm.round(color.b * 255.0)), .a = 255, }; } pub fn RGBAToRGBA8(color: *const ColorRGBA) ColorRGBA8 { return ColorRGBA8{ .r = @floatToInt(u8, stdm.round(color.r * 255.0)), .g = @floatToInt(u8, stdm.round(color.g * 255.0)), .b = @floatToInt(u8, stdm.round(color.b * 255.0)), .a = @floatToInt(u8, stdm.round(color.a * 255.0)), }; } pub fn RGB8ToRGBA8(color: *const ColorRGB8) ColorRGBA8 { return ColorRGBA8{ .r = color.r, .g = color.g, .b = color.b, .a = 255, }; } const std = @import("std"); const expect = std.testing.expect; test "Color 8bit to f32 conversion" { const testColors = [_]ColorRGB8{ colorsRGB8.Red, colorsRGB8.Green, colorsRGB8.Blue, colorsRGB8.Cyan, colorsRGB8.Yellow, colorsRGB8.Magenta, }; for (testColors) |color| { const colorConverted = RGB8ToRGB(&color); const colorConvertedBack = RGBToRGB8(&colorConverted); expect(color.Equals(&colorConvertedBack)); } } test "Color 8bit to f32 conversion with alpha" { const testColors = [_]ColorRGBA8{ colorsRGBA8.Red, colorsRGBA8.Green, colorsRGBA8.Blue, colorsRGBA8.Cyan, colorsRGBA8.Yellow, colorsRGBA8.Magenta, }; for (testColors) |color| { const colorConverted = RGBA8ToRGBA(&color); const colorConvertedBack = RGBAToRGBA8(&colorConverted); expect(color.Equals(&colorConvertedBack)); } } test "Color RGB to HSV and HSV to RGB" { const testColors = [_]ColorRGB{ colorsRGB.Red, colorsRGB.Green, colorsRGB.Blue, colorsRGB.Cyan, colorsRGB.Yellow, colorsRGB.Magenta, }; for (testColors) |color| { const colorConverted = RGBToHSV(&color); const colorConvertedBack = HSVToRGB(&colorConverted); expect(color.Equals(&colorConvertedBack)); } }
src/math/Color.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const Metric = @import("metric.zig").Metric; const Self = @This(); metric: Metric = Metric{ .getResultFn = getResult, }, value: std.atomic.Atomic(u64) = .{ .value = 0 }, pub fn init(allocator: mem.Allocator) !*Self { const self = try allocator.create(Self); self.* = .{}; return self; } pub fn inc(self: *Self) void { _ = self.value.fetchAdd(1, .SeqCst); } pub fn dec(self: *Self) void { _ = self.value.fetchSub(1, .SeqCst); } pub fn add(self: *Self, value: anytype) void { if (!comptime std.meta.trait.isNumber(@TypeOf(value))) { @compileError("can't add a non-number"); } _ = self.value.fetchAdd(@intCast(u64, value), .SeqCst); } pub fn get(self: *const Self) u64 { return self.value.load(.SeqCst); } pub fn set(self: *Self, value: anytype) void { if (!comptime std.meta.trait.isNumber(@TypeOf(value))) { @compileError("can't set a non-number"); } _ = self.value.store(@intCast(u64, value), .SeqCst); } fn getResult(metric: *Metric, allocator: mem.Allocator) Metric.Error!Metric.Result { _ = allocator; const self = @fieldParentPtr(Self, "metric", metric); return Metric.Result{ .counter = self.get() }; } test "counter: inc/add/dec/set/get" { var buffer = std.ArrayList(u8).init(testing.allocator); defer buffer.deinit(); var counter = try Self.init(testing.allocator); defer testing.allocator.destroy(counter); try testing.expectEqual(@as(u64, 0), counter.get()); counter.inc(); try testing.expectEqual(@as(u64, 1), counter.get()); counter.add(200); try testing.expectEqual(@as(u64, 201), counter.get()); counter.dec(); try testing.expectEqual(@as(u64, 200), counter.get()); counter.set(43); try testing.expectEqual(@as(u64, 43), counter.get()); } test "counter: concurrent" { var counter = try Self.init(testing.allocator); defer testing.allocator.destroy(counter); var threads: [4]std.Thread = undefined; for (threads) |*thread| { thread.* = try std.Thread.spawn( .{}, struct { fn run(c: *Self) void { var i: usize = 0; while (i < 20) : (i += 1) { c.inc(); } } }.run, .{counter}, ); } for (threads) |*thread| thread.join(); try testing.expectEqual(@as(u64, 80), counter.get()); } test "counter: write" { var counter = try Self.init(testing.allocator); defer testing.allocator.destroy(counter); counter.set(340); var buffer = std.ArrayList(u8).init(testing.allocator); defer buffer.deinit(); var metric = &counter.metric; try metric.write(testing.allocator, buffer.writer(), "mycounter"); try testing.expectEqualStrings("mycounter 340\n", buffer.items); }
src/Counter.zig
const std = @import("std"); const sdk = @import("sdk"); const log = @import("log.zig"); const hooks = @import("hooks.zig"); var ifaces_internal = blk: { // This is a workaround for a weird result location bug, will be fixed in stage2 var i: Ifaces = undefined; break :blk i; }; pub const ifaces = &ifaces_internal; var orig_internal = blk: { var i: Orig = undefined; break :blk i; }; pub const orig = &orig_internal; const locations = .{ .ICvar = "tier1:VEngineCvar007", .IEngineVGui = "engine:VEngineVGui001", .ISurface = "vguimatsurface:VGUI_Surface031", .IVEngineClient = "engine:VEngineClient015", .IServerTools = "server:VSERVERTOOLS001", .IServerGameDLL = "server:ServerGameDLL005", }; var allocator: std.mem.Allocator = undefined; const VtableEntry = ?*const opaque {}; var hooked_tables: std.ArrayList([]VtableEntry) = undefined; pub fn init(allocator1: std.mem.Allocator) !void { allocator = allocator1; hooked_tables = @TypeOf(hooked_tables).init(allocator); errdefer hooked_tables.deinit(); inline for (comptime getDescs()) |desc| { var library = if (std.mem.eql(u8, desc.module, "tier1")) switch (@import("builtin").os.tag) { .windows => "vstdlib.dll", .linux => "libvstdlib.so", .macos => "libvstdlib.dylib", else => @compileError("Unsupported OS"), } else desc.module ++ switch (@import("builtin").os.tag) { .windows => ".dll", .linux => ".so", .macos => ".dylib", else => @compileError("Unsupported OS"), }; log.info("Opening {s}\n", .{library}); if (std.mem.eql(u8, library, "server.so")) library = "portal2/bin/linux32/server.so"; var lib = try std.DynLib.open(library); const createInterface = lib.lookup(sdk.CreateInterfaceFn, "CreateInterface") orelse return error.SymbolNotFound; const iface = @ptrCast( @TypeOf(@field(ifaces, desc.name)), createInterface(desc.id.ptr, null) orelse return error.InterfaceNotFound, ); @field(ifaces_internal, desc.name) = iface; @field(orig_internal, desc.name) = iface.*.vtable; const new_vtable = try copyVtable(@TypeOf(iface.*.vtable.*), iface.*.vtable); inline for (@typeInfo(desc.hooks).Struct.decls) |decl| { const hooked = @field(desc.hooks, decl.name); // TODO: assert type @field(new_vtable.*, decl.name) = hooked; } iface.*.vtable = new_vtable; log.devInfo("Initialized interface {s}:{s}\n", .{ desc.module, desc.id }); } } pub fn deinit() void { inline for (comptime getDescs()) |desc| { var iface = @field(ifaces_internal, desc.name); iface.*.vtable = @field(orig_internal, desc.name); } for (hooked_tables.items) |vtable| { allocator.free(vtable); } hooked_tables.deinit(); } fn copyVtable(comptime T: type, vtable: *const T) !*T { // We don't necessarily know the full extent of vtables; not only could // our SDK definitions be incomplete, but also the subclass could // define extra virtual methods that we don't know about. That means // that in order to not completely fuck the vtable, we need to copy the // *whole* thing, including these extra bits. Luckily, there's a null // pointer at the end of the vtable, so we can use that as a sentinel! // Note that we also copy one pointer *before* the start of the vtable; // this is RTTI shit, I don't really understand it, but SAR does it and // I'm pretty sure it's a good idea. var vtable1 = std.mem.span(@ptrCast([*:null]const VtableEntry, vtable)); // Include the preceding typeinfo shit and the terminator vtable1.len += 2; vtable1.ptr -= 1; var new_vtable = try allocator.alloc(VtableEntry, vtable1.len); std.mem.copy(VtableEntry, new_vtable, vtable1); try hooked_tables.append(new_vtable); return @ptrCast(*T, new_vtable.ptr + 1); } pub const Ifaces = blk: { var fields: [getDescs().len]std.builtin.TypeInfo.StructField = undefined; for (getDescs()) |desc, i| { const T = @field(sdk, desc.name); fields[i] = .{ .name = desc.name, .field_type = *T, .default_value = null, .is_comptime = false, .alignment = @alignOf(*T), }; } break :blk @Type(.{ .Struct = .{ .layout = .Auto, .fields = &fields, .decls = &.{}, .is_tuple = false, } }); }; pub const Orig = blk: { var fields: [getDescs().len]std.builtin.TypeInfo.StructField = undefined; for (getDescs()) |desc, i| { const T = @field(sdk, desc.name).Vtable; fields[i] = .{ .name = desc.name, .field_type = *const T, .default_value = null, .is_comptime = false, .alignment = @alignOf(*T), }; } break :blk @Type(.{ .Struct = .{ .layout = .Auto, .fields = &fields, .decls = &.{}, .is_tuple = false, } }); }; const IfaceDesc = struct { name: []const u8, module: []const u8, id: [:0]const u8, hooks: type, }; fn getDescs() []const IfaceDesc { comptime var descs: [std.meta.fields(@TypeOf(locations)).len]IfaceDesc = undefined; inline for (comptime std.meta.fieldNames(@TypeOf(locations))) |name, i| { const desc = @field(locations, name); const idx = comptime std.mem.lastIndexOfScalar(u8, desc, ':') orelse { @compileError(std.fmt.comptimePrint( "Malformed interface location string \"{}\"", .{std.zig.fmtEscapes(desc)}, )); }; descs[i] = .{ .name = name, .module = desc[0..idx], .id = desc[idx + 1 ..], .hooks = struct {}, }; for (std.meta.fields(hooks)) |field| { if (std.mem.eql(u8, field.name, name)) { descs[i].hooks = field.field_type; } } } return &descs; }
src/interface.zig
const std = @import("std"); const c = @import("c.zig"); const ft = @import("ft.zig"); const msgpack = @import("msgpack.zig"); const shaderc = @import("shaderc.zig"); const util = @import("util.zig"); const paste = @import("paste.zig"); const Buffer = @import("buffer.zig").Buffer; const Debounce = @import("debounce.zig").Debounce(u32, 200); const Renderer = @import("renderer.zig").Renderer; const RPC = @import("rpc.zig").RPC; const Window = @import("window.zig").Window; const FONT_NAME = "font/Inconsolata-SemiBold.ttf"; const FONT_SIZE = 14; const SCROLL_THRESHOLD = 0.1; pub const Tui = struct { const Self = @This(); alloc: *std.mem.Allocator, // These are the three components to the Tui: // - The window holds the GLFW window and handles resizing // - The renderer handles all the WGPU stuff // - The RPC bridge talks to a subprocess window: Window, renderer: Renderer, rpc: RPC, font: ft.Atlas, buffers: std.AutoHashMap(u32, *Buffer), debounce: Debounce, // Persistent shader compiler to rebuild previews faster compiler: c.shaderc_compiler_t, char_grid: [512 * 512]u32, x_tiles: u32, y_tiles: u32, total_tiles: u32, mouse_tile_x: i32, mouse_tile_y: i32, mouse_scroll_y: f64, // Render state to pass into WGPU u: c.fpUniforms, uniforms_changed: bool, pixel_density: u32, pub fn deinit(self: *Self) void { self.rpc.deinit(); self.font.deinit(); self.window.deinit(); self.renderer.deinit(self.alloc); var itr = self.buffers.iterator(); while (itr.next()) |buf| { buf.value.deinit(); self.alloc.destroy(buf.value); } self.buffers.deinit(); c.shaderc_compiler_release(self.compiler); self.alloc.destroy(self); } fn attach_buffer(self: *Self, id: u32) !void { var options = msgpack.KeyValueMap.init(self.alloc); defer options.deinit(); try self.rpc.call_release("nvim_buf_attach", .{ id, true, options }); // Create a buffer on the heap and store it in the hash map. var buf = try self.alloc.create(Buffer); buf.* = try Buffer.init(self.alloc); try self.buffers.put(id, buf); } pub fn init(alloc: *std.mem.Allocator) !*Self { // We'll use an arena for transient CPU-side resources var arena = std.heap.ArenaAllocator.init(alloc); const tmp_alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); var width: c_int = 900; var height: c_int = 600; var window = try Window.init(width, height, "futureproof"); c.glfwGetFramebufferSize(window.window, &width, &height); const font = try ft.build_atlas( alloc, FONT_NAME, FONT_SIZE, 512, ); const renderer = try Renderer.init(tmp_alloc, window.window, &font); const x_tiles = @intCast(u32, width) / font.u.glyph_advance; const y_tiles = @intCast(u32, height) / font.u.glyph_height; // Start up the RPC subprocess, using the global allocator const nvim_cmd = [_][]const u8{ "nvim", "--embed", "--clean", "-u", "config/init.vim", }; var rpc = try RPC.init(&nvim_cmd, alloc); const out = try alloc.create(Self); out.* = .{ .alloc = alloc, .window = window, .renderer = renderer, .rpc = rpc, .font = font, .buffers = std.AutoHashMap(u32, *Buffer).init(alloc), .debounce = Debounce.init(), .compiler = c.shaderc_compiler_initialize(), .char_grid = undefined, .x_tiles = 0, .y_tiles = 0, .total_tiles = 0, .mouse_tile_x = 0, .mouse_tile_y = 0, .mouse_scroll_y = 0.0, .u = c.fpUniforms{ .width_px = @intCast(u32, width), .height_px = @intCast(u32, height), .font = font.u, .attrs = undefined, .modes = undefined, }, .uniforms_changed = true, .pixel_density = 1, }; window.set_callbacks( size_cb, key_cb, mouse_button_cb, mouse_pos_cb, scroll_cb, @ptrCast(?*c_void, out), ); { // Attach the UI via RPC var options = msgpack.KeyValueMap.init(alloc); try options.put( msgpack.Key{ .RawString = "ext_linegrid" }, msgpack.Value{ .Boolean = true }, ); defer options.deinit(); try rpc.call_release( "nvim_ui_attach", .{ x_tiles, y_tiles, options }, ); } { // Try to subscribe to Fp events var options = msgpack.KeyValueMap.init(alloc); defer options.deinit(); try rpc.call_release("nvim_subscribe", .{"Fp"}); } // Tell Vim to save the default undo levels in a variable, then // set them to -1 (so that loading the template doesn't end up // in the undo list) try rpc.call_release( "nvim_input", .{":let old_undolevels = &undolevels<Enter>:set undolevels=-1<Enter>"}, ); { // Send the template text to the first buffer const src = try util.file_contents( tmp_alloc, "shaders/preview.template.frag", ); var line_count: u32 = 1; for (src[0..(src.len - 2)]) |char| { if (char == '\n') { line_count += 1; } } var lines = try tmp_alloc.alloc([]const u8, line_count); var start: usize = 0; var i: u32 = 0; while (std.mem.indexOf(u8, src[start..], "\n")) |end| { lines[i] = src[start..(start + end)]; i += 1; start += end + 1; } // Encode the lines manually, as encoding nested structs // doesn't work right now (TODO). const encoded = try msgpack.Value.encode(tmp_alloc, lines); try rpc.call_release( "nvim_buf_set_lines", .{ 0, 0, 0, false, encoded }, ); } // Clean up and set the filetype try rpc.call_release( "nvim_input", .{"ddgg:set filetype=glsl<Enter>:setlocal nomodified<Enter>"}, ); // Re-enable undo by restoring default undo levels try rpc.call_release( "nvim_input", .{":let &undolevels = old_undolevels<Enter>:unlet old_undolevels<Enter>"}, ); out.update_size(width, height); return out; } fn char_at(self: *Self, x: usize, y: usize) *u32 { return &self.char_grid[x + y * self.x_tiles]; } fn api_grid_scroll(self: *Self, line: []const msgpack.Value) void { const grid = line[0].UInt; std.debug.assert(grid == 1); const top = line[1].UInt; const bot = line[2].UInt; const left = line[3].UInt; const right = line[4].UInt; const cols = line[6].UInt; std.debug.assert(cols == 0); // rows > 0 --> moving rows upwards if (line[5] == .UInt) { const rows = line[5].UInt; var y = top; while (y < bot - rows) : (y += 1) { var x = left; while (x < right) : (x += 1) { self.char_at(x, y).* = self.char_at(x, y + rows).*; } } // rows < 0 --> moving rows downwards } else if (line[5] == .Int) { const rows = @intCast(u32, -line[5].Int); var y = bot - 1; while (y >= top + rows) : (y -= 1) { var x = left; while (x < right) : (x += 1) { self.char_at(x, y).* = self.char_at(x, y - rows).*; } } } } fn decode_utf8(char: []const u8) u32 { if (char[0] >> 7 == 0) { std.debug.assert(char.len == 1); return char[0]; } else if (char[0] >> 5 == 0b110) { std.debug.assert(char.len == 2); return (@intCast(u32, char[0] & 0b00011111) << 6) | @intCast(u32, char[1] & 0b00111111); } else if (char[0] >> 4 == 0b1110) { std.debug.assert(char.len == 3); return (@intCast(u32, char[0] & 0b00001111) << 12) | (@intCast(u32, char[1] & 0b00111111) << 6) | @intCast(u32, char[2] & 0b00111111); } else if (char[0] >> 3 == 0b11110) { std.debug.assert(char.len == 4); return (@intCast(u32, char[0] & 0b00000111) << 18) | (@intCast(u32, char[1] & 0b00111111) << 12) | (@intCast(u32, char[2] & 0b00111111) << 6) | @intCast(u32, char[3] & 0b00111111); } return 0; } fn api_grid_line(self: *Self, line: []const msgpack.Value) void { const grid = line[0].UInt; std.debug.assert(grid == 1); var hl_attr: u16 = 0; const row = line[1].UInt; var col = line[2].UInt; for (line[3].Array) |cell_| { const cell = cell_.Array; const text = cell[0].RawString; if (cell.len >= 2) { hl_attr = @intCast(u16, cell[1].UInt); } const repeat = if (cell.len >= 3) cell[2].UInt else 1; const codepoint = decode_utf8(text); var char: u32 = undefined; if (self.font.get_glyph(codepoint)) |g| { char = g; } else { std.debug.print("Adding new codepoint: {x}\n", .{codepoint}); char = self.font.add_glyph(codepoint) catch |err| { std.debug.panic("Could not add glyph {}: {}\n", .{ codepoint, err }); }; // We've only added one glyph to the texture, so just copy // this one line over to our local uniforms: self.u.font.glyphs[char] = self.font.u.glyphs[char]; // Then send the updated atlas and texture to the GPU self.renderer.update_uniforms(&self.u); self.renderer.update_font_tex(&self.font); } std.debug.assert(char < self.u.font.glyphs.len); var i: usize = 0; while (i < repeat) : (i += 1) { self.char_at(col, row).* = char | (@intCast(u32, hl_attr) << 16); col += 1; // TODO: unicode?! } } } fn api_flush(self: *Self, cmd: []const msgpack.Value) void { // Send over the character grid, along with the extra three values // that mark cursor position and mode within the grid std.debug.assert(cmd.len == 0); self.renderer.update_grid(self.char_grid[0 .. self.total_tiles + 3]); } fn api_grid_clear(self: *Self, cmd: []const msgpack.Value) void { const grid = cmd[0].UInt; std.debug.assert(grid == 1); std.mem.set(u32, self.char_grid[0..], 0); } fn api_grid_cursor_goto(self: *Self, cmd: []const msgpack.Value) void { const grid = cmd[0].UInt; std.debug.assert(grid == 1); // Record the cursor position at the end of the grid self.char_grid[self.total_tiles] = @intCast(u32, cmd[2].UInt); self.char_grid[self.total_tiles + 1] = @intCast(u32, cmd[1].UInt); } fn decode_hl_attrs(attr: *const msgpack.KeyValueMap) c.fpHlAttrs { var out = (c.fpHlAttrs){ .foreground = 0xffffffff, .background = 0xffffffff, .special = 0xffffffff, .flags = 0, }; var itr = attr.iterator(); while (itr.next()) |entry| { if (std.mem.eql(u8, entry.key.RawString, "foreground")) { out.foreground = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "background")) { out.background = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "special")) { out.special = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "bold") and entry.value.Boolean) { out.flags |= c.FP_FLAG_BOLD; } else if (std.mem.eql(u8, entry.key.RawString, "italic") and entry.value.Boolean) { out.flags |= c.FP_FLAG_ITALIC; } else if (std.mem.eql(u8, entry.key.RawString, "undercurl") and entry.value.Boolean) { out.flags |= c.FP_FLAG_UNDERCURL; } else if (std.mem.eql(u8, entry.key.RawString, "reverse") and entry.value.Boolean) { out.flags |= c.FP_FLAG_REVERSE; } else if (std.mem.eql(u8, entry.key.RawString, "underline") and entry.value.Boolean) { out.flags |= c.FP_FLAG_UNDERLINE; } else if (std.mem.eql(u8, entry.key.RawString, "strikethrough") and entry.value.Boolean) { out.flags |= c.FP_FLAG_STRIKETHROUGH; } else if (std.mem.eql(u8, entry.key.RawString, "standout") and entry.value.Boolean) { out.flags |= c.FP_FLAG_STANDOUT; } else { std.debug.warn("Unknown hlAttr: {} {}\n", .{ entry.key, entry.value }); } } return out; } fn api_hl_attr_define(self: *Self, cmd: []const msgpack.Value) void { // Decode rgb_attrs into the appropriate slot const id = cmd[0].UInt; std.debug.assert(id < c.FP_MAX_ATTRS); self.u.attrs[id] = decode_hl_attrs(&cmd[1].Map); self.uniforms_changed = true; } fn decode_mode(mode: *const msgpack.KeyValueMap) c.fpMode { var out = (c.fpMode){ .cursor_shape = c.FP_CURSOR_BLOCK, .cell_percentage = 100, .blinkwait = 0, .blinkon = 0, .blinkoff = 0, .attr_id = 0, }; var itr = mode.iterator(); while (itr.next()) |entry| { if (std.mem.eql(u8, entry.key.RawString, "cursor_shape")) { if (std.mem.eql(u8, entry.value.RawString, "horizontal")) { out.cursor_shape = c.FP_CURSOR_HORIZONTAL; } else if (std.mem.eql(u8, entry.value.RawString, "vertical")) { out.cursor_shape = c.FP_CURSOR_VERTICAL; } else if (std.mem.eql(u8, entry.value.RawString, "block")) { out.cursor_shape = c.FP_CURSOR_BLOCK; } else { std.debug.panic("Unknown cursor shape: {}\n", .{entry.value}); } } else if (std.mem.eql(u8, entry.key.RawString, "cell_percentage")) { out.cell_percentage = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "blinkwait")) { out.blinkwait = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "blinkon")) { out.blinkon = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "blinkoff")) { out.blinkoff = @intCast(u32, entry.value.UInt); } else if (std.mem.eql(u8, entry.key.RawString, "attr_id")) { out.attr_id = @intCast(u32, entry.value.UInt); } else { // Ignore other elements for now } } return out; } fn api_mode_info_set(self: *Self, cmd: []const msgpack.Value) void { const cursor_style_enabled = cmd[0].Boolean; // unused for now? std.debug.assert(cmd[1].Array.len < c.FP_MAX_MODES); var i: u32 = 0; while (i < cmd[1].Array.len) : (i += 1) { self.u.modes[i] = decode_mode(&cmd[1].Array[i].Map); } } fn api_mode_change(self: *Self, cmd: []const msgpack.Value) void { self.char_grid[self.total_tiles + 2] = @intCast(u32, cmd[1].UInt); } fn api_default_colors_set(self: *Self, cmd: []const msgpack.Value) void { self.u.attrs[0] = (c.fpHlAttrs){ .foreground = @intCast(u32, cmd[0].UInt), .background = @intCast(u32, cmd[1].UInt), .special = @intCast(u32, cmd[2].UInt), .flags = 0, }; self.uniforms_changed = true; } fn call_method(self: *Self, event: []const msgpack.Value) !void { const target = event[2].Array[0].Ext; if (target.type == 0) { // Buffer const buf_num = try target.as_u32(); if (self.buffers.get(buf_num)) |buf| { const name = event[1].RawString; const args = event[2].Array[1..]; switch (try buf.rpc_method(name, args)) { .Changed => { try self.debounce.update(buf_num); }, .Done => { buf.deinit(); self.alloc.destroy(buf); _ = self.buffers.remove(buf_num); }, .Okay => {}, } } else { std.debug.warn("Invalid buffer: {}\n", .{buf_num}); } } else { std.debug.warn("Unknown method target: {}\n", .{target.type}); } } fn fp_buf_new(self: *Self, args: []const msgpack.Value) !void { try self.attach_buffer(@intCast(u32, args[0].UInt)); } fn call_fp(self: *Self, event: []const msgpack.Value) !void { const args_ = event[2].Array; const name = args_[0].RawString; const args = args_[1..]; // Work around issue #4639 by storing opts in a variable comptime const opts = std.builtin.CallOptions{}; inline for (@typeInfo(Self).Struct.decls) |s| { // Same trick as call_api comptime const is_fp = std.mem.startsWith(u8, s.name, "fp_"); if (is_fp) { if (std.mem.eql(u8, name, s.name[3..])) { return @call( opts, @field(Self, s.name), .{ self, args }, ); } } } std.debug.warn("[Tui] Unknown Fp event: {}\n", .{name}); } fn call_api(self: *Self, event: []const msgpack.Value) !void { // Work around issue #4639 by storing opts in a variable comptime const opts = std.builtin.CallOptions{}; // For each command in the incoming stream, try to match // it against a local api_XYZ declaration. for (event[2].Array) |cmd| { var matched = false; const api_name = cmd.Array[0].RawString; inline for (@typeInfo(Self).Struct.decls) |s| { // This conditional should be optimized out, since // it's known at comptime. comptime const is_api = std.mem.startsWith(u8, s.name, "api_"); if (is_api) { if (std.mem.eql(u8, api_name, s.name[4..])) { for (cmd.Array[1..]) |v| { @call( opts, @field(Self, s.name), .{ self, v.Array }, ); } matched = true; break; } } } if (!matched) { std.debug.warn("[Tui] Unimplemented API: {}\n", .{api_name}); } } } pub fn tick(self: *Self) !bool { while (self.rpc.get_event()) |event| { defer self.rpc.release(event); if (event == .Int) { return false; } // Methods are called on Ext objects (buffers, windows, etc) if (event.Array[2].Array[0] == .Ext) { try self.call_method(event.Array); } // We attach a few autocommands to rpcnotify(0, 'Fp', ...), which // are handled here. else if (std.mem.eql(u8, "Fp", event.Array[1].RawString)) { try self.call_fp(event.Array); } // Otherwise, we compare against a list of implemented APIs, by // doing a comptime unrolled loop that finds api_XYZ functions // and compares against them by name. else { try self.call_api(event.Array); } } if (self.uniforms_changed) { self.uniforms_changed = false; self.renderer.update_uniforms(&self.u); } // Work around a potential deadlock: if nvim is in a blocking mode, // then we can't use nvim_command, so we defer handling the shaders // until then. const mode = (try self.rpc.call("nvim_get_mode", .{})); defer self.rpc.release(mode); const key = msgpack.Key{ .RawString = "blocking" }; const blocking = mode.Map.get(key) orelse std.debug.panic("Could not get 'blocking'", .{}); if (!blocking.Boolean) { if (self.debounce.check()) |buf_num| { // Check that the target buffer hasn't been deleted during the // debouncing delay time. If it exists, then try to compile // it as a shader and load it into the preview pane. if (self.buffers.get(buf_num)) |buf| { const shader_text = try buf.to_buf(); defer self.alloc.free(shader_text); try self.rebuild_preview(buf_num, shader_text); } } } self.renderer.redraw(self.total_tiles); return true; } fn rebuild_preview(self: *Self, buf_num: u32, shader_text: []const u8) !void { const out = try shaderc.build_preview_shader( self.alloc, self.compiler, shader_text, ); defer out.deinit(self.alloc); // Clear all of the error markers before compiling the shader try self.rpc.call_release("nvim_command", .{":sign unplace *"}); // Clear the quick-fix list try self.rpc.call_release("nvim_command", .{":lexpr \"\""}); switch (out) { .Shader => |s| { try self.renderer.update_preview(self.alloc, s); try self.rpc.call_release("nvim_command", .{":lclose"}); }, .Error => |e| { var arena = std.heap.ArenaAllocator.init(self.alloc); const tmp_alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); self.renderer.clear_preview(self.alloc); for (e.errs) |line_err| { var line_num: u32 = 1; if (line_err.line) |n| { line_num = n; } const cmd = try std.fmt.allocPrint( tmp_alloc, ":sign place {} line={} name=fpErr buffer={}", .{ line_num, line_num, buf_num, }, ); try self.rpc.call_release("nvim_command", .{cmd}); const lexp = try std.fmt.allocPrint( tmp_alloc, ":ladd \"{}:{}\"", .{ line_num, line_err.msg }, ); try self.rpc.call_release("nvim_command", .{lexp}); } try self.rpc.call_release("nvim_command", .{":lopen"}); try self.rpc.call_release("nvim_command", .{":silent! wincmd p"}); }, } } pub fn run(self: *Self) !void { while (!self.window.should_close() and (try self.tick())) { c.glfwWaitEvents(); } // Halt the subprocess, then clean out any remaining items in the queue _ = try self.rpc.halt(); // Ignore return code } pub fn update_size(self: *Self, width: c_int, height: c_int) void { self.u.width_px = @intCast(u32, width); self.u.height_px = @intCast(u32, height); const density = self.u.width_px / self.window.get_window_width(); if (density != self.pixel_density) { self.pixel_density = density; self.font.deinit(); self.font = ft.build_atlas( self.alloc, FONT_NAME, FONT_SIZE * self.pixel_density, 512, ) catch |err| { std.debug.panic("Could not rebuild font: {}\n", .{err}); }; self.u.font = self.font.u; self.renderer.update_font_tex(&self.font); } const cursor_x = self.char_grid[self.total_tiles]; const cursor_y = self.char_grid[self.total_tiles + 1]; self.x_tiles = self.u.width_px / self.u.font.glyph_advance / 2; self.y_tiles = self.u.height_px / self.u.font.glyph_height; self.total_tiles = self.x_tiles * self.y_tiles; self.renderer.resize_swap_chain(self.u.width_px, self.u.height_px); self.renderer.update_uniforms(&self.u); self.rpc.call_release( "nvim_ui_try_resize", .{ self.x_tiles, self.y_tiles }, ) catch |err| { std.debug.panic("Failed to resize UI: {}\n", .{err}); }; self.char_grid[self.total_tiles] = cursor_x; self.char_grid[self.total_tiles + 1] = cursor_y; const r = self.tick() catch |err| { std.debug.panic("Failed to tick: {}\n", .{err}); }; // Resizing the window shouldn't ever cause the nvim process to exit std.debug.assert(r); } fn get_ascii_lower(key: c_int) ?u8 { if (key >= 1 and key <= 127) { const char = @intCast(u8, key); if (char >= 'A' and char <= 'Z') { return char + ('a' - 'A'); } else { return char; } } return null; } fn get_ascii(key: c_int, mods: c_int) ?u8 { if (get_ascii_lower(key)) |char| { return if ((mods & c.GLFW_MOD_SHIFT) != 0) to_upper(char) else char; } return null; } fn to_upper(key: u8) u8 { // This assumes a US-EN keyboard return switch (key) { 'a'...'z' => key - ('a' - 'A'), '`' => '~', '1' => '!', '2' => '@', '3' => '#', '4' => '$', '5' => '%', '6' => '^', '7' => '&', '8' => '*', '9' => '(', '0' => ')', '-' => '_', '=' => '+', '[' => '{', ']' => '}', '\\' => '|', ';' => ':', '\'' => '"', ',' => '<', '.' => '>', '/' => '?', else => key, }; } fn get_encoded(key: c_int) ?([]const u8) { return switch (key) { c.GLFW_KEY_ENTER => "Enter", c.GLFW_KEY_ESCAPE => "Esc", c.GLFW_KEY_TAB => "Tab", c.GLFW_KEY_BACKSPACE => "BS", c.GLFW_KEY_INSERT => "Insert", c.GLFW_KEY_DELETE => "Del", c.GLFW_KEY_RIGHT => "Right", c.GLFW_KEY_LEFT => "Left", c.GLFW_KEY_DOWN => "Down", c.GLFW_KEY_UP => "Up", c.GLFW_KEY_PAGE_UP => "PageUp", c.GLFW_KEY_PAGE_DOWN => "PageDown", c.GLFW_KEY_HOME => "Home", c.GLFW_KEY_END => "End", c.GLFW_KEY_F1 => "F1", c.GLFW_KEY_F2 => "F2", c.GLFW_KEY_F3 => "F3", c.GLFW_KEY_F4 => "F4", c.GLFW_KEY_F5 => "F5", c.GLFW_KEY_F6 => "F6", c.GLFW_KEY_F7 => "F7", c.GLFW_KEY_F8 => "F8", c.GLFW_KEY_F9 => "F9", c.GLFW_KEY_F10 => "F10", c.GLFW_KEY_F11 => "F11", c.GLFW_KEY_F12 => "F12", c.GLFW_KEY_KP_0 => "k0", c.GLFW_KEY_KP_1 => "k1", c.GLFW_KEY_KP_2 => "k2", c.GLFW_KEY_KP_3 => "k3", c.GLFW_KEY_KP_4 => "k4", c.GLFW_KEY_KP_5 => "k5", c.GLFW_KEY_KP_6 => "k6", c.GLFW_KEY_KP_7 => "k7", c.GLFW_KEY_KP_8 => "k8", c.GLFW_KEY_KP_9 => "k9", c.GLFW_KEY_KP_DECIMAL => "kPoint", c.GLFW_KEY_KP_DIVIDE => "kDivide", c.GLFW_KEY_KP_MULTIPLY => "kMultiply", c.GLFW_KEY_KP_SUBTRACT => "kSubtract", c.GLFW_KEY_KP_ADD => "kAdd", c.GLFW_KEY_KP_ENTER => "kEnter", c.GLFW_KEY_KP_EQUAL => "kEqual", else => null, }; } fn skip_key(key: c_int) bool { return switch (key) { c.GLFW_KEY_LEFT_SHIFT, c.GLFW_KEY_LEFT_CONTROL, c.GLFW_KEY_LEFT_ALT, c.GLFW_KEY_LEFT_SUPER, c.GLFW_KEY_RIGHT_SHIFT, c.GLFW_KEY_RIGHT_CONTROL, c.GLFW_KEY_RIGHT_ALT, c.GLFW_KEY_RIGHT_SUPER, => true, else => false, }; } // Helper function to convert a mod bitfield into a string // alloc must be an arena allocator, for ease of memory management fn encode_mods(alloc: *std.mem.Allocator, mods: c_int) ![]const u8 { var out = try std.fmt.allocPrint(alloc, "", .{}); std.debug.assert(out.len == 0); if ((mods & c.GLFW_MOD_SHIFT) != 0) { out = try std.fmt.allocPrint(alloc, "S-{}", .{out}); } if ((mods & c.GLFW_MOD_CONTROL) != 0) { out = try std.fmt.allocPrint(alloc, "C-{}", .{out}); } if ((mods & c.GLFW_MOD_ALT) != 0) { out = try std.fmt.allocPrint(alloc, "A-{}", .{out}); } if ((mods & c.GLFW_MOD_SUPER) != 0) { out = try std.fmt.allocPrint(alloc, "D-{}", .{out}); } return out; } fn shortcut(self: *Self, key: c_int, mods: c_int) !bool { if (key == c.GLFW_KEY_V and mods == c.GLFW_MOD_SUPER) { const s = paste.get_clipboard(); const i = std.mem.indexOfSentinel(u8, 0, s); try self.rpc.call_release("nvim_input", .{s[0..i]}); return true; } return false; } pub fn on_key(self: *Self, key: c_int, mods: c_int) !void { var arena = std.heap.ArenaAllocator.init(self.alloc); var alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); var char_str = [1]u8{0}; var str: ?[]const u8 = null; if (skip_key(key)) { // Nothing to do here } else if (try self.shortcut(key, mods)) { // Nothing to do here either } else if (get_ascii(key, mods)) |char| { if (char == '<') { str = "<LT>"; } else { char_str[0] = char; str = &char_str; } const mods_ = mods & (~@intCast(c_int, c.GLFW_MOD_SHIFT)); if (mods_ != 0) { const mod_str = try encode_mods(alloc, mods_); std.debug.assert(mod_str.len != 0); str = try std.fmt.allocPrint(alloc, "<{}{}>", .{ mod_str, str }); } } else if (get_encoded(key)) |enc| { if (mods == 0) { str = try std.fmt.allocPrint(alloc, "<{}>", .{enc}); } else { const mod_str = try encode_mods(alloc, mods); str = try std.fmt.allocPrint(alloc, "<{}{}>", .{ mod_str, enc }); } } else { std.debug.print("Got unknown key {} {}\n", .{ key, mods }); } if (str) |s| { try self.rpc.call_release("nvim_input", .{s}); } } pub fn on_mouse_pos(self: *Self, x: f64, y: f64) !void { self.mouse_tile_x = @floatToInt(i32, @intToFloat(f64, self.pixel_density) * x / @intToFloat(f64, self.u.font.glyph_advance)); self.mouse_tile_y = @floatToInt(i32, @intToFloat(f64, self.pixel_density) * y / @intToFloat(f64, self.u.font.glyph_height)); } pub fn on_scroll(self: *Self, dx: f64, dy: f64) !void { // Reset accumulator if we've changed directions if (self.mouse_scroll_y != 0 and std.math.signbit(dy) != std.math.signbit(self.mouse_scroll_y)) { self.mouse_scroll_y = 0; } self.mouse_scroll_y += dy; while (std.math.absFloat(self.mouse_scroll_y) >= SCROLL_THRESHOLD) { const dir = if (self.mouse_scroll_y > 0) "up" else "down"; if (self.mouse_scroll_y > 0) { self.mouse_scroll_y -= SCROLL_THRESHOLD; } else { self.mouse_scroll_y += SCROLL_THRESHOLD; } self.rpc.call_release("nvim_input_mouse", .{ "wheel", dir, "", // mods 0, // grid self.mouse_tile_y, // row self.mouse_tile_x, // col }) catch |err| { std.debug.panic("Failed to call nvim_input_mouse: {}", .{err}); }; } } pub fn on_mouse_button(self: *Self, button: c_int, action: c_int, mods: c_int) !void { var arena = std.heap.ArenaAllocator.init(self.alloc); var alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); const button_str = switch (button) { c.GLFW_MOUSE_BUTTON_LEFT => "left", c.GLFW_MOUSE_BUTTON_RIGHT => "right", c.GLFW_MOUSE_BUTTON_MIDDLE => "middle", else => |b| { std.debug.warn("Ignoring unknown mouse: {}\n", .{b}); return; }, }; const action_str = switch (action) { c.GLFW_PRESS => "press", c.GLFW_RELEASE => "release", else => |b| std.debug.panic("Invalid mouse action: {}\n", .{b}), }; const mods_str = try encode_mods(alloc, mods); try self.rpc.call_release("nvim_input_mouse", .{ button_str, action_str, mods_str, 0, // grid self.mouse_tile_y, // row self.mouse_tile_x, // col }); } }; export fn size_cb(w: ?*c.GLFWwindow, width: c_int, height: c_int) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var tui = @ptrCast(*Tui, @alignCast(8, ptr)); tui.update_size(width, height); } export fn key_cb(w: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var tui = @ptrCast(*Tui, @alignCast(8, ptr)); if (action == c.GLFW_PRESS or action == c.GLFW_REPEAT) { tui.on_key(key, mods) catch |err| { std.debug.panic("Failed on_key: {}\n", .{err}); }; } } export fn mouse_pos_cb(w: ?*c.GLFWwindow, x: f64, y: f64) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var tui = @ptrCast(*Tui, @alignCast(8, ptr)); tui.on_mouse_pos(x, y) catch |err| { std.debug.print("Failed on_mouse_pos: {}\n", .{err}); }; } export fn mouse_button_cb(w: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var tui = @ptrCast(*Tui, @alignCast(8, ptr)); tui.on_mouse_button(button, action, mods) catch |err| { std.debug.print("Failed on_mouse_button: {}\n", .{err}); }; } export fn scroll_cb(w: ?*c.GLFWwindow, dx: f64, dy: f64) void { const ptr = c.glfwGetWindowUserPointer(w) orelse std.debug.panic("Missing user pointer", .{}); var tui = @ptrCast(*Tui, @alignCast(8, ptr)); tui.on_scroll(dx, dy) catch |err| { std.debug.print("Failed on_scroll: {}\n", .{err}); }; }
src/tui.zig
const std = @import("std"); const fmt = std.fmt; const testing = std.testing; const Allocator = std.mem.Allocator; pub const Error = struct { _buf: [32]u8, end: usize, /// Get the error code. pub fn getCode(self: Error) []const u8 { return self._buf[0..self.end]; } }; pub const FullError = struct { _buf: [32]u8, end: usize, /// The full error message message: []u8, /// Get the error code. pub fn getCode(self: FullError) []const u8 { return self._buf[0..self.end]; } }; /// Creates a union over T that is capable of optionally parsing /// Redis Errors. It's the idiomatic way of parsing Redis errors /// as inspectable values. `OrErr` only captures the error code, /// use `OrFullErr` to also obtain the error message. /// /// You can also decode `nil` replies using this union. pub fn OrErr(comptime T: type) type { return union(enum) { Ok: T, Nil: void, /// Use `.getCode()` to obtain the error code as a `[]const u8` Err: Error, const Self = @This(); pub const Redis = struct { pub const Parser = struct { pub const NoOptionalWrapper = true; pub fn parse(tag: u8, comptime rootParser: type, msg: anytype) !Self { return switch (tag) { '_', '-', '!' => internalParse(tag, rootParser, msg), else => Self{ .Ok = try rootParser.parseFromTag(T, tag, msg) }, }; } pub fn destroy(self: Self, comptime rootParser: type, allocator: *Allocator) void { switch (self) { .Ok => |ok| rootParser.freeReply(ok, allocator), else => {}, } } pub fn parseAlloc(tag: u8, comptime rootParser: type, allocator: *Allocator, msg: anytype) !Self { return switch (tag) { '_', '-', '!' => internalParse(tag, rootParser, msg), else => return Self{ .Ok = try rootParser.parseAllocFromTag(T, tag, allocator, msg) }, }; } fn internalParse(tag: u8, comptime _: type, msg: anytype) !Self { switch (tag) { else => unreachable, '_' => { try msg.skipBytes(2, .{}); return Self{ .Nil = {} }; }, '!' => { // TODO: write real implementation var buf: [100]u8 = undefined; var end: usize = 0; for (buf) |*elem, i| { const ch = try msg.readByte(); elem.* = ch; if (ch == '\r') { end = i; break; } } try msg.skipBytes(1, .{}); var size = try fmt.parseInt(usize, buf[0..end], 10); var res = Self{ .Err = undefined }; // Parse the Code part var ch = try msg.readByte(); for (res.Err._buf) |*elem, i| { if (i == size) { elem.* = ch; res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; try msg.skipBytes(2, .{}); return res; } switch (ch) { ' ' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; break; }, else => { elem.* = ch; ch = try msg.readByte(); }, } } if (ch != ' ') return error.ErrorCodeBufTooSmall; const remainder = size - res.Err.end + 2; // +2 because of `\r\n` if (remainder > 0) try msg.skipBytes(remainder, .{}); return res; }, '-' => { var res = Self{ .Err = undefined }; // Parse the Code part var ch = try msg.readByte(); for (res.Err._buf) |*elem, i| { switch (ch) { ' ' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; break; }, '\r' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; try msg.skipBytes(1, .{}); return res; }, else => { elem.* = ch; ch = try msg.readByte(); }, } } if (ch != ' ') return error.ErrorCodeBufTooSmall; // Seek through the rest of the message, discarding it. while (ch != '\n') ch = try msg.readByte(); return res; }, } } }; }; }; } /// Like `OrErr`, but it uses an allocator to store the full error message. pub fn OrFullErr(comptime T: type) type { return union(enum) { Ok: T, Nil: void, /// Use `.getCode()` to obtain the error code as a `[]const u8`, /// and `.message` to obtain the full error message as a `[]const u8`. Err: FullError, const Self = @This(); pub const Redis = struct { pub const Parser = struct { pub const NoOptionalWrapper = true; pub fn parse(_: u8, comptime _: type, _: anytype) !Self { @compileError("OrFullErr requires an allocator, use `OrErr` to parse just the error code without the need of an allocator."); } pub fn destroy(self: Self, comptime rootParser: type, allocator: *Allocator) void { switch (self) { .Ok => |ok| rootParser.freeReply(ok, allocator), .Err => |err| allocator.free(err.message), .Nil => {}, } } pub fn parseAlloc(tag: u8, comptime rootParser: type, allocator: *Allocator, msg: anytype) !Self { switch (tag) { else => return Self{ .Ok = try rootParser.parseAllocFromTag(T, tag, allocator, msg) }, '_' => { try msg.skipBytes(2, .{}); return Self{ .Nil = {} }; }, '!' => { // TODO: write real implementation var buf: [100]u8 = undefined; var end: usize = 0; for (buf) |*elem, i| { const ch = try msg.readByte(); elem.* = ch; if (ch == '\r') { end = i; break; } } try msg.skipBytes(1, .{}); var size = try fmt.parseInt(usize, buf[0..end], 10); var res = Self{ .Err = undefined }; res.Err.message = &[0]u8{}; // Parse the Code part var ch = try msg.readByte(); for (res.Err._buf) |*elem, i| { if (i == size) { elem.* = ch; res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; try msg.skipBytes(2, .{}); return res; } switch (ch) { ' ' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; break; }, else => { elem.* = ch; ch = try msg.readByte(); }, } } if (ch != ' ') return error.ErrorCodeBufTooSmall; // Alloc difference: const remainder = size - res.Err.end; if (remainder == 0) return res; var slice = try allocator.alloc(u8, remainder); errdefer allocator.free(slice); try msg.readNoEof(slice); res.Err.message = slice; try msg.skipBytes(2, .{}); return res; }, '-' => { var res = Self{ .Err = undefined }; res.Err.message = &[0]u8{}; // Parse the Code part var ch = try msg.readByte(); for (res.Err._buf) |*elem, i| { switch (ch) { ' ' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; break; }, '\r' => { res.Err.end = i; // res.Err.code = res.Err._buf[0..i]; try msg.skipBytes(1, .{}); return res; }, else => { elem.* = ch; ch = try msg.readByte(); }, } } if (ch != ' ') return error.ErrorCodeBufTooSmall; // Seek through the rest of the message, // discarding it. res.Err.message = try msg.readUntilDelimiterAlloc(allocator, '\r', 4096); try msg.skipBytes(1, .{}); return res; }, } } }; }; }; } test "parse simple errors" { switch (try OrErr(u8).Redis.Parser.parse('_', fakeParser, MakeNil().reader())) { .Ok, .Err => unreachable, .Nil => try testing.expect(true), } switch (try OrErr(u8).Redis.Parser.parse('!', fakeParser, MakeBlobErr().reader())) { .Ok, .Nil => unreachable, .Err => |err| try testing.expectEqualSlices(u8, "ERRN\r\nOGOODFOOD", err.getCode()), } switch (try OrErr(u8).Redis.Parser.parse('-', fakeParser, MakeErr().reader())) { .Ok, .Nil => unreachable, .Err => |err| try testing.expectEqualSlices(u8, "ERRNOGOODFOOD", err.getCode()), } switch (try OrErr(u8).Redis.Parser.parse('-', fakeParser, MakeErroji().reader())) { .Ok, .Nil => unreachable, .Err => |err| try testing.expectEqualSlices(u8, "😈", err.getCode()), } switch (try OrErr(u8).Redis.Parser.parse('-', fakeParser, MakeShortErr().reader())) { .Ok, .Nil => unreachable, .Err => |err| try testing.expectEqualSlices(u8, "ABC", err.getCode()), } try testing.expectError(error.ErrorCodeBufTooSmall, OrErr(u8).Redis.Parser.parse('-', fakeParser, MakeBadErr().reader())); const allocator = std.heap.page_allocator; switch (try OrFullErr(u8).Redis.Parser.parseAlloc('-', fakeParser, allocator, MakeErroji().reader())) { .Ok, .Nil => unreachable, .Err => |err| { try testing.expectEqualSlices(u8, "😈", err.getCode()); try testing.expectEqualSlices(u8, "your Redis belongs to us", err.message); }, } switch (try OrFullErr(u8).Redis.Parser.parseAlloc('!', fakeParser, allocator, MakeBlobErr().reader())) { .Ok, .Nil => unreachable, .Err => |err| { try testing.expectEqualSlices(u8, "ERRN\r\nOGOODFOOD", err.getCode()); try testing.expectEqualSlices(u8, "redis \r\n\r\ncould not find any\r\n good food", err.message); }, } } const fakeParser = struct { pub inline fn parse(comptime T: type, rootParser: anytype) !T { _ = T; _ = rootParser; return error.Errror; } pub inline fn parseFromTag(comptime T: type, tag: u8, rootParser: anytype) !T { _ = T; _ = tag; _ = rootParser; return error.Errror; } pub inline fn parseAllocFromTag(comptime T: type, tag: u8, allocator: *Allocator, rootParser: anytype) !T { _ = T; _ = rootParser; _ = tag; _ = allocator; return error.Errror; } }; fn MakeErroji() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("-😈 your Redis belongs to us\r\n"[1..]); } fn MakeErr() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("-ERRNOGOODFOOD redis could not find any good food\r\n"[1..]); } fn MakeBadErr() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("-ARIARIARIARIARIARIARIARIARIARRIVEDERCI *golden wind music starts*\r\n"[1..]); } fn MakeShortErr() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("-ABC\r\n"[1..]); } fn MakeBlobErr() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("!55\r\nERRN\r\nOGOODFOOD redis \r\n\r\ncould not find any\r\n good food\r\n"[1..]); } fn MakeNil() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("_\r\n"[1..]); } test "docs" { @import("std").testing.refAllDecls(@This()); @import("std").testing.refAllDecls(Error); @import("std").testing.refAllDecls(FullError); }
src/types/error.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const nvg = @import("nanovg"); const gui = @import("../gui.zig"); const Rect = @import("../geometry.zig").Rect; const pad: f32 = 2; const Self = @This(); widget: gui.Widget, allocator: Allocator, has_grip: bool = false, separators: ArrayList(*gui.Widget), pub fn init(allocator: Allocator, rect: Rect(f32)) !*Self { var self = try allocator.create(Self); self.* = Self{ .widget = gui.Widget.init(allocator, rect), .allocator = allocator, .separators = ArrayList(*gui.Widget).init(allocator), }; self.widget.onResizeFn = onResize; self.widget.drawFn = draw; return self; } pub fn deinit(self: *Self) void { for (self.separators.items) |widget| { self.allocator.destroy(widget); } self.separators.deinit(); self.widget.deinit(); self.allocator.destroy(self); } fn onResize(widget: *gui.Widget, _: *gui.ResizeEvent) void { const self = @fieldParentPtr(Self, "widget", widget); self.updateLayout(); } fn updateLayout(self: Self) void { var rem = self.widget.relative_rect.w - pad; var grow_count: u32 = 0; for (self.widget.children.items) |child| { if (child.layout.grow) { grow_count += 1; } else { rem -= child.relative_rect.w + pad; } } if (rem < 0) rem = 0; var x = pad; for (self.widget.children.items) |child| { child.relative_rect.x = x; if (child.layout.grow) { child.relative_rect.w = @round(rem / @intToFloat(f32, grow_count) - pad); rem -= child.relative_rect.w + pad; grow_count -= 1; } x += child.relative_rect.w + pad; } } pub fn addButton(self: *Self, button: *gui.Button) !void { button.style = .toolbar; button.widget.focus_policy = gui.FocusPolicy.none(); button.widget.relative_rect.w = 20; button.widget.relative_rect.h = 20; try self.addWidget(&button.widget); } pub fn addSeparator(self: *Self) !void { var separator = try self.allocator.create(gui.Widget); separator.* = gui.Widget.init(self.allocator, Rect(f32).make(0, 0, 4, 20)); separator.drawFn = drawSeparator; try self.separators.append(separator); try self.addWidget(separator); } pub fn addWidget(self: *Self, widget: *gui.Widget) !void { widget.relative_rect.y = pad; try self.widget.addChild(widget); self.updateLayout(); } fn drawSeparator(widget: *gui.Widget, vg: nvg) void { const rect = widget.relative_rect; vg.beginPath(); vg.rect(rect.x + 1, rect.y + 1, 1, rect.h - 2); vg.fillColor(gui.theme_colors.shadow); vg.fill(); vg.beginPath(); vg.rect(rect.x + 2, rect.y + 1, 1, rect.h - 2); vg.fillColor(gui.theme_colors.light); vg.fill(); } fn draw(widget: *gui.Widget, vg: nvg) void { const self = @fieldParentPtr(Self, "widget", widget); const rect = widget.relative_rect; gui.drawPanel(vg, rect.x, rect.y, rect.w, rect.h, 1, false, false); if (self.has_grip) { drawGrip(vg, rect.x + rect.w - 16, rect.y + rect.h - 16); } widget.drawChildren(vg); } fn drawGrip(vg: nvg, x: f32, y: f32) void { vg.scissor(x, y, 14, 14); defer vg.resetScissor(); vg.beginPath(); vg.moveTo(x, y + 16); vg.lineTo(x + 16, y); vg.moveTo(x + 4, y + 16); vg.lineTo(x + 4 + 16, y); vg.moveTo(x + 8, y + 16); vg.lineTo(x + 8 + 16, y); vg.strokeColor(gui.theme_colors.light); vg.stroke(); vg.beginPath(); vg.moveTo(x + 1, y + 16); vg.lineTo(x + 1 + 16, y); vg.moveTo(x + 5, y + 16); vg.lineTo(x + 5 + 16, y); vg.moveTo(x + 9, y + 16); vg.lineTo(x + 9 + 16, y); vg.strokeColor(gui.theme_colors.shadow); vg.stroke(); }
src/gui/widgets/Toolbar.zig
const std = @import("std"); const Module = @import("module.zig"); const Instance = @import("instance.zig"); const Memory = @import("Memory.zig"); const Wasi = @This(); argv: [][]u8, environ: [][]u8 = &.{}, exit_code: ?Exitcode = null, const P = Memory.P; pub fn run(self: *Wasi, allocator: *std.mem.Allocator, reader: anytype) !Exitcode { var module = try Module.parse(allocator, reader); defer module.deinit(); var instance = try module.instantiate(allocator, self, struct { pub const wasi = imports; pub const wasi_snapshot_preview1 = imports; }); defer instance.deinit(); _ = instance.call("_start", .{}) catch |err| switch (err) { error.Unreachable => { if (self.exit_code) |code| return code; return err; }, else => return err, }; // TODO: what should we do if there is no explicit exit? return @intToEnum(Exitcode, 0); } pub const Size = u32; /// Non-negative file size or length of a region within a file. pub const Filesize: u64; /// Timestamp in nanoseconds. pub const Timestamp = u64; /// Identifiers for clocks. pub const ClockId = enum(u32) { /// The clock measuring real time. Time value zero corresponds with 1970-01-01T00:00:00Z. realtime = 0, /// The store-wide monotonic clock, which is defined as a clock measuring real time, whose value cannot be adjusted and which cannot have negative clock jumps. The epoch of this clock is undefined. The absolute time value of this clock therefore has no meaning. monotonic = 1, /// The CPU-time clock associated with the current process. process_cputime_id = 2, /// The CPU-time clock associated with the current thread. thread_cputime_id = 3, _, }; /// Exit code generated by a process when exiting. pub const Exitcode = enum(u32) { _ }; /// A file descriptor handle. const Fd = enum(u32) { stdin = 0, stdout = 1, stderr = 2, _, }; /// A region of memory for scatter/gather reads. const Iovec = extern struct { buf: P(u8), len: Size, }; /// Error codes returned by functions. Not all of these error codes are returned by the functions provided by this API; some are used in higher-level library layers, and others are provided merely for alignment with POSIX. pub const Errno = enum(u32) { /// No error occurred. System call completed successfully. success = 0, /// Permission denied. acces = 2, /// Resource unavailable, or operation would block. again = 6, /// Bad file descriptor. badf = 8, /// Connection aborted. connaborted = 13, /// Connection refused. connrefused = 14, /// Connection reset. connreset = 15, /// Reserved. dquot = 19, /// File too large. fbig = 22, /// Invalid argument. inval = 28, /// I/O error. io = 29, /// No buffer space available. nobufs = 42, /// No space left on device. nospc = 51, /// Function not supported. nosys = 52, /// Broken pipe. pipe = 64, unexpected = 0xAAAA, _, }; /// File descriptor rights, determining which actions may be performed. pub const Rights = packed struct { fd_datasync: bool, fd_read: bool, fd_seek: bool, fd_fdstat_set_flags: bool, fd_sync: bool, fd_tell: bool, fd_write: bool, fd_advise: bool, fd_allocate: bool, path_create_directory: bool, path_create_file: bool, path_link_source: bool, path_link_target: bool, path_open: bool, fd_readdir: bool, path_readlink: bool, path_rename_source: bool, path_rename_target: bool, path_filestat_get: bool, path_filestat_set_size: bool, path_filestat_set_times: bool, fd_filestat_get: bool, fd_filestat_set_size: bool, fd_filestat_set_times: bool, path_symlink: bool, path_remove_directory: bool, path_unlink_file: bool, poll_fd_readwrite: bool, sock_shutdown: bool, _pad: u3, _pad1: u32, }; const imports = struct { pub fn args_get(mem: *Memory, argv: P(P(u8)), argv_buf: P(u8)) !Errno { const wasi = mem.ext(Wasi); return strings_get(mem, wasi.argv, argv, argv_buf); } pub fn args_sizes_get(mem: *Memory, argc: P(Size), argv_buf_size: P(Size)) !Errno { const wasi = mem.ext(Wasi); return strings_sizes_get(mem, wasi.argv, argc, argv_buf_size); } pub fn environ_get(mem: *Memory, environ: P(P(u8)), environ_buf: P(u8)) !Errno { const wasi = mem.ext(Wasi); return strings_get(mem, wasi.environ, environ, environ_buf); } pub fn environ_sizes_get(mem: *Memory, environc: P(Size), environ_buf_size: P(Size)) !Errno { const wasi = mem.ext(Wasi); return strings_sizes_get(mem, wasi.environ, environc, environ_buf_size); } pub fn fd_write(mem: *Memory, fd: Fd, iovs: P(Iovec), iovs_len: Size, nread: P(Size)) !Errno { var os_vec: [128]std.os.iovec_const = undefined; var i: u32 = 0; var osi: u32 = 0; while (i < iovs_len) : (i += 1) { const iov = try mem.get(try iovs.add(i)); var iter = mem.iterBytes(iov.buf, iov.len); while (try iter.next()) |bytes| { os_vec[osi] = .{ .iov_base = bytes.ptr, .iov_len = bytes.len }; osi += 1; } } const handle = switch (fd) { .stdin => unreachable, .stdout => std.io.getStdOut().handle, .stderr => std.io.getStdErr().handle, else => unreachable, }; var written = std.os.writev(handle, os_vec[0..osi]) catch |err| return switch (err) { error.DiskQuota => Errno.dquot, error.FileTooBig => Errno.fbig, error.InputOutput => Errno.io, error.NoSpaceLeft => Errno.nospc, error.AccessDenied => Errno.acces, error.BrokenPipe => Errno.pipe, error.SystemResources => Errno.nobufs, error.OperationAborted => unreachable, error.NotOpenForWriting => Errno.badf, error.WouldBlock => Errno.again, error.ConnectionResetByPeer => Errno.connreset, error.Unexpected => Errno.unexpected, }; try mem.set(nread, @intCast(u32, written)); return Errno.success; } fn strings_get(mem: *Memory, strings: [][]u8, target: P(P(u8)), target_buf: P(u8)) !Errno { var target_ = target; var target_buf_ = target_buf; for (strings) |string| { try mem.set(target_, target_buf_); target_ = try target_.add(1); try mem.setMany(target_buf_, string); target_buf_ = try target_buf_.add(@intCast(u32, string.len)); try mem.set(target_buf_, 0); target_buf_ = try target_buf_.add(1); } return Errno.success; } fn strings_sizes_get(mem: *Memory, strings: [][]u8, targetc: P(Size), target_buf_size: P(Size)) !Errno { try mem.set(targetc, @intCast(Size, strings.len)); var buf_size: usize = 0; for (strings) |string| { buf_size += string.len + 1; } try mem.set(target_buf_size, @intCast(Size, buf_size)); return Errno.success; } pub fn clock_res_get(mem: *Memory, clock_id: ClockId, resolution: P(Timestamp)) !Errno { const clk: i32 = switch (clock_id) { .realtime => std.os.CLOCK_REALTIME, .monotonic => std.os.CLOCK_MONOTONIC, .process_cputime_id => std.os.CLOCK_PROCESS_CPUTIME_ID, .thread_cputime_id => std.os.CLOCK_THREAD_CPUTIME_ID, else => return Errno.inval, }; var result: std.os.timespec = undefined; std.os.clock_getres(clk, &result) catch |err| switch (err) { error.UnsupportedClock => return Errno.inval, error.Unexpected => return Errno.unexpected, }; try mem.set(resolution, @intCast(Timestamp, std.time.ns_per_s * result.tv_sec + result.tv_nsec)); return Errno.success; } pub fn clock_time_get(mem: *Memory, clock_id: ClockId, precision: Timestamp, time: P(Timestamp)) !Errno { const clk: i32 = switch (clock_id) { .realtime => std.os.CLOCK_REALTIME, .monotonic => std.os.CLOCK_MONOTONIC, .process_cputime_id => std.os.CLOCK_PROCESS_CPUTIME_ID, .thread_cputime_id => std.os.CLOCK_THREAD_CPUTIME_ID, else => return Errno.inval, }; var result: std.os.timespec = undefined; std.os.clock_gettime(clk, &result) catch |err| switch (err) { error.UnsupportedClock => return Errno.inval, error.Unexpected => return Errno.unexpected, }; try mem.set(time, @intCast(Timestamp, std.time.ns_per_s * result.tv_sec + result.tv_nsec)); return Errno.success; } pub fn proc_exit(mem: *Memory, rval: Exitcode) !void { const wasi = mem.ext(Wasi); wasi.exit_code = rval; return error.Unreachable; } pub fn sched_yield(mem: *Memory) Errno { std.os.sched_yield() catch |err| switch (err) { error.SystemCannotYield => return Errno.nosys, }; return Errno.success; } }; test "smoke" { _ = Instance.ImportManager(struct { pub const wasi = imports; }); }
src/wasi.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(.arm); const VERSION = "0.0.1"; const HELPTEXT = \\ arm: remove files from the index \\ \\ usage: \\ arm [options] path \\ \\ options: \\ -h prints this help and exits \\ -V prints version and exits \\ -f forcefully delete a path \\ (TODO support folder paths) \\ -r remove files recursively (in a folder) \\ --dry-run don't edit the index database \\ \\ examples: \\ arm path/to/file \\ arm -r path/to/folder ; 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 Args = struct { help: bool = false, version: bool = false, recursive: bool = false, force: bool = false, dry_run: bool = false, path: ?[]const u8 = null, }; var given_args = Args{}; while (args_it.next()) |arg| { 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, "-r")) { given_args.recursive = true; } else if (std.mem.eql(u8, arg, "-f")) { given_args.force = true; } else if (std.mem.eql(u8, arg, "--dry-run")) { given_args.dry_run = true; } else { given_args.path = 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.path == null) { std.log.err("path is a required argument", .{}); return error.MissingPath; } const path = given_args.path.?; var ctx = Context{ .home_path = null, .args_it = undefined, .stdout = undefined, .db = null, .allocator = allocator, }; defer ctx.deinit(); try ctx.loadDatabase(.{}); if (given_args.dry_run) try ctx.turnIntoMemoryDb(); var full_path_buffer: [std.os.PATH_MAX]u8 = undefined; // if forcing a deletion, do not give a shit about filesystem const full_path = if (given_args.force) path else try std.fs.cwd().realpath(path, &full_path_buffer); const maybe_file = try ctx.fetchFileByPath(full_path); var count: usize = 0; if (maybe_file) |file| { defer file.deinit(); try file.delete(); count += 1; } else { var dir = std.fs.cwd().openDir(full_path, .{ .iterate = true }) catch |err| switch (err) { std.fs.Dir.OpenError.FileNotFound => { log.err("path not found: {s}", .{full_path}); return err; }, else => return err, }; if (!given_args.recursive) { log.err("given path is a folder but -r is not set", .{}); return error.MissingRecursiveFlag; } var walker = try dir.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind != .File) continue; log.debug("checking path {s}", .{entry.path}); var inner_realpath_buffer: [std.os.PATH_MAX]u8 = undefined; const inner_full_path = try entry.dir.realpath(entry.basename, &inner_realpath_buffer); const maybe_inner_file = try ctx.fetchFileByPath(inner_full_path); if (maybe_inner_file) |file| { defer file.deinit(); log.info("removing path {s}", .{entry.path}); try file.delete(); count += 1; } } } log.info("deleted {d} files", .{count}); }
src/rm_main.zig
const root = @import("root"); const builtin = @import("builtin"); const std = @import("std"); const backend = @import("backend.zig"); const style = @import("style.zig"); const Widget = @import("widget.zig").Widget; const Class = @import("widget.zig").Class; const Size = @import("data.zig").Size; const DataWrapper = @import("data.zig").DataWrapper; const Container_Impl = @import("containers.zig").Container_Impl; const Layout = @import("containers.zig").Layout; /// Allocator used for small, short-lived and repetitive allocations. /// You can change this by setting the `zgtScratchAllocator` field in your main file /// or by setting the `zgtAllocator` field which will also apply as lasting allocator. pub const scratch_allocator = if (@hasDecl(root, "zgtScratchAllocator")) root.zgtScratchAllocator else if (@hasDecl(root, "zgtAllocator")) root.zgtAllocator else if (@import("builtin").is_test) std.testing.allocator else std.heap.page_allocator; /// Allocator used for bigger, longer-lived but rare allocations (example: widgets). /// You can change this by setting the `zgtLastingAllocator` field in your main file /// or by setting the `zgtAllocator` field which will also apply as scratch allocator. pub const lasting_allocator = if (@hasDecl(root, "zgtLastingAllocator")) root.zgtScratchAllocator else if (@hasDecl(root, "zgtAllocator")) root.zgtAllocator else if (@import("builtin").is_test) std.testing.allocator else std.heap.page_allocator; /// Convenience function for creating widgets pub fn All(comptime T: type) type { return struct { pub usingnamespace Events(T); pub usingnamespace Widgeting(T); }; } // Styling // pub fn Styling(comptime T: type) type { // return struct { // pub usingnamespace Measurement(T); // }; // } /// Convenience function for creating widgets pub fn Widgeting(comptime T: type) type { return struct { // zig fmt: off pub const WidgetClass = Class{ .typeName = @typeName(T), .showFn = showWidget, .deinitFn = deinitWidget, .preferredSizeFn = getPreferredSizeWidget, }; pub const DataWrappers = struct { opacity: DataWrapper(f64) = DataWrapper(f64).of(1.0), alignX: DataWrapper(f32) = DataWrapper(f32).of(0.5), alignY: DataWrapper(f32) = DataWrapper(f32).of(0.5), name: ?[]const u8 = null, /// The widget representing this component widget: ?*Widget = null, }; // zig fmt: on /// When alignX or alignY is changed, this will trigger a parent relayout fn alignChanged(new: f32, userdata: usize) void { _ = new; const widget = @intToPtr(*Widget, userdata); if (widget.parent) |parent| { const container = parent.as(@import("containers.zig").Container_Impl); container.relayout() catch {}; } } pub fn showWidget(widget: *Widget) anyerror!void { const component = @intToPtr(*T, widget.data); try component.show(); widget.peer = component.peer.?.peer; _ = try component.dataWrappers.alignX.addChangeListener(.{ .function = alignChanged, .userdata = @ptrToInt(widget) }); _ = try component.dataWrappers.alignY.addChangeListener(.{ .function = alignChanged, .userdata = @ptrToInt(widget) }); // if the widget wants to do some operations on showWidget if (@hasDecl(T, "_showWidget")) { try T._showWidget(widget, component); } } pub fn deinitWidget(widget: *Widget) void { const component = @intToPtr(*T, widget.data); component.deinit(); if (@hasDecl(T, "_deinit")) { T._deinit(component, widget); } if (widget.allocator) |allocator| allocator.destroy(component); } pub fn deinit(self: *T) void { std.log.info("deinit {s}", .{@typeName(T)}); std.log.info("a {}", .{self}); self.dataWrappers.widget = null; self.handlers.clickHandlers.deinit(); self.handlers.drawHandlers.deinit(); self.handlers.buttonHandlers.deinit(); self.handlers.scrollHandlers.deinit(); self.handlers.resizeHandlers.deinit(); self.handlers.keyTypeHandlers.deinit(); if (self.peer) |peer| peer.deinit(); } pub fn pointerMoved(self: *T) void { self.dataWrappers.opacity.updateBinders(); self.dataWrappers.alignX.updateBinders(); self.dataWrappers.alignY.updateBinders(); if (@hasDecl(T, "_pointerMoved")) { self._pointerMoved(); } } pub fn getPreferredSizeWidget(widget: *const Widget, available: Size) Size { const component = @intToPtr(*T, widget.data); return component.getPreferredSize(available); } pub fn getWidth(self: *T) u32 { if (self.peer == null) return 0; return @intCast(u32, self.peer.?.getWidth()); } pub fn getHeight(self: *T) u32 { if (self.peer == null) return 0; return @intCast(u32, self.peer.?.getHeight()); } pub fn asWidget(self: *T) anyerror!Widget { return try genericWidgetFrom(self); } // TODO: consider using something like https://github.com/MasterQ32/any-pointer for userdata // to get some safety pub fn setUserdata(self: *T, userdata: ?*anyopaque) T { if (comptime std.meta.trait.isIntegral(@TypeOf(userdata))) { self.handlers.userdata = userdata; } else { self.handlers.userdata = @ptrToInt(userdata); } return self.*; } pub fn getUserdata(self: *T, comptime U: type) U { return @intToPtr(U, self.handlers.userdata); } // Properties // TODO: pub usingnamespace Property(f64, "opacity"); pub fn setOpacity(self: *T, opacity: f64) void { self.dataWrappers.opacity.set(opacity); } pub fn getOpacity(self: *T) f64 { return self.dataWrappers.opacity.get(); } pub fn getName(self: *T) ?[]const u8 { return self.dataWrappers.name; } /// Bind the 'opacity' property to argument. pub fn bindOpacity(self: *T, other: *DataWrapper(f64)) T { self.dataWrappers.opacity.bind(other); self.dataWrappers.opacity.set(other.get()); return self.*; } pub fn setAlignX(self: *T, alignX: f32) T { self.dataWrappers.alignX.set(alignX); return self.*; } pub fn setAlignY(self: *T, alignY: f32) T { self.dataWrappers.alignY.set(alignY); return self.*; } pub fn setName(self: *T, name: ?[]const u8) T { self.dataWrappers.name = name; return self.*; } /// Bind the 'alignX' property to argument. pub fn bindAlignX(self: *T, other: *DataWrapper(f32)) T { self.dataWrappers.alignX.bind(other); self.dataWrappers.alignX.set(other.get()); return self.*; } /// Bind the 'alignY' property to argument. pub fn bindAlignY(self: *T, other: *DataWrapper(f32)) T { self.dataWrappers.alignY.bind(other); self.dataWrappers.alignY.set(other.get()); return self.*; } pub fn getWidget(self: *T) ?*Widget { return self.dataWrappers.widget; } // This can return a Container_Impl as parents are always a container pub fn getParent(self: *T) ?*Container_Impl { if (self.dataWrappers.widget) |widget| { if (widget.parent) |parent| { return parent.as(Container_Impl); } } return null; } /// Go up the widget tree until we find the root (which is the component /// put with window.set() /// Returns null if the component is unparented. pub fn getRoot(self: *T) ?*Container_Impl { var parent = self.getParent() orelse return null; while (true) { const ancester = parent.getParent(); if (ancester) |newParent| { parent = newParent; } else { break; } } return parent; } }; } /// Generate a config struct that allows with all the properties of the given type pub fn GenerateConfigStruct(comptime T: type) type { _ = T; unreachable; } pub fn DereferencedType(comptime T: type) type { return if (comptime std.meta.trait.isSingleItemPtr(T)) std.meta.Child(T) else T; } /// Create a generic Widget struct from the given component. pub fn genericWidgetFrom(component: anytype) anyerror!Widget { const ComponentType = @TypeOf(component); if (ComponentType == Widget) return component; if (component.dataWrappers.widget != null) { return error.ComponentAlreadyHasWidget; } var cp = if (comptime std.meta.trait.isSingleItemPtr(ComponentType)) component else blk: { var copy = try lasting_allocator.create(ComponentType); copy.* = component; break :blk copy; }; // used to update things like data wrappers, this happens once, at initialization, // after that the component isn't moved in memory anymore cp.pointerMoved(); const Dereferenced = DereferencedType(ComponentType); return Widget{ .data = @ptrToInt(cp), .class = &Dereferenced.WidgetClass, .name = &cp.dataWrappers.name, .alignX = &cp.dataWrappers.alignX, .alignY = &cp.dataWrappers.alignY, .allocator = if (comptime std.meta.trait.isSingleItemPtr(ComponentType)) null else lasting_allocator, }; } pub fn isErrorUnion(comptime T: type) bool { return switch (@typeInfo(T)) { .ErrorUnion => true, else => false, }; } pub fn convertTupleToWidgets(childrens: anytype) anyerror!std.ArrayList(Widget) { 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 list; } // pub fn Property(comptime T: type, comptime name: []const u8) type { // Depends on #6709 // return struct { // }; // } // Events pub const RedrawError = error{MissingPeer}; /// Convenience function for creating widgets pub fn Events(comptime T: type) type { return struct { pub const Callback = fn (widget: *T) anyerror!void; pub const DrawCallback = fn (widget: *T, ctx: *backend.Canvas.DrawContext) anyerror!void; pub const ButtonCallback = fn (widget: *T, button: backend.MouseButton, pressed: bool, x: u32, y: u32) anyerror!void; pub const MouseMoveCallback = fn(widget: *T, x: u32, y: u32) anyerror!void; pub const ScrollCallback = fn (widget: *T, dx: f32, dy: f32) anyerror!void; pub const ResizeCallback = fn (widget: *T, size: Size) anyerror!void; pub const KeyTypeCallback = fn (widget: *T, key: []const u8) anyerror!void; const HandlerList = std.ArrayList(Callback); const DrawHandlerList = std.ArrayList(DrawCallback); const ButtonHandlerList = std.ArrayList(ButtonCallback); const MouseMoveHandlerList = std.ArrayList(MouseMoveCallback); const ScrollHandlerList = std.ArrayList(ScrollCallback); const ResizeHandlerList = std.ArrayList(ResizeCallback); const KeyTypeHandlerList = std.ArrayList(KeyTypeCallback); pub const Handlers = struct { clickHandlers: HandlerList, drawHandlers: DrawHandlerList, buttonHandlers: ButtonHandlerList, mouseMoveHandlers: MouseMoveHandlerList, scrollHandlers: ScrollHandlerList, resizeHandlers: ResizeHandlerList, keyTypeHandlers: KeyTypeHandlerList, userdata: usize = 0, }; pub fn init_events(self: T) T { var obj = self; // zig fmt: off obj.handlers = .{ .clickHandlers = HandlerList.init(lasting_allocator), .drawHandlers = DrawHandlerList.init(lasting_allocator), .buttonHandlers = ButtonHandlerList.init(lasting_allocator), .mouseMoveHandlers = MouseMoveHandlerList.init(lasting_allocator), .scrollHandlers = ScrollHandlerList.init(lasting_allocator), .resizeHandlers = ResizeHandlerList.init(lasting_allocator), .keyTypeHandlers = KeyTypeHandlerList.init(lasting_allocator) }; // zig fmt: on return obj; } fn errorHandler(err: anyerror) void { std.log.err("{s}", .{@errorName(err)}); var streamBuf: [16384]u8 = undefined; var stream = std.io.fixedBufferStream(&streamBuf); var writer = stream.writer(); writer.print("Internal error: {s}.\n", .{@errorName(err)}) catch {}; if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); if (std.io.is_async) { // can't use writeStackTrace as it is async but errorHandler should not be async! } else { if (std.debug.getSelfDebugInfo()) |debug_info| { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); std.debug.writeStackTrace(trace.*, writer, arena.allocator(), debug_info, .no_color) catch {}; } else |_| {} } } writer.print("Please check the log.", .{}) catch {}; backend.showNativeMessageDialog(.Error, "{s}", .{stream.getWritten()}); } fn clickHandler(data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.clickHandlers.items) |func| { func(self) catch |err| errorHandler(err); } } fn drawHandler(ctx: *backend.Canvas.DrawContext, data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.drawHandlers.items) |func| { func(self, ctx) catch |err| errorHandler(err); } } fn buttonHandler(button: backend.MouseButton, pressed: bool, x: u32, y: u32, data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.buttonHandlers.items) |func| { func(self, button, pressed, x, y) catch |err| errorHandler(err); } } fn mouseMovedHandler(x: u32, y: u32, data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.mouseMoveHandlers.items) |func| { func(self, x, y) catch |err| errorHandler(err); } } fn keyTypeHandler(str: []const u8, data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.keyTypeHandlers.items) |func| { func(self, str) catch |err| errorHandler(err); } } fn scrollHandler(dx: f32, dy: f32, data: usize) void { const self = @intToPtr(*T, data); for (self.handlers.scrollHandlers.items) |func| { func(self, dx, dy) catch |err| errorHandler(err); } } fn resizeHandler(width: u32, height: u32, data: usize) void { const self = @intToPtr(*T, data); const size = Size{ .width = width, .height = height }; for (self.handlers.resizeHandlers.items) |func| { func(self, size) catch |err| errorHandler(err); } } /// When the value is changed in the opacity data wrapper fn opacityChanged(newValue: f64, userdata: usize) void { const widget = @intToPtr(*T, userdata); if (widget.peer) |*peer| { peer.setOpacity(newValue); } } pub fn show_events(self: *T) !void { self.peer.?.setUserData(self); try self.peer.?.setCallback(.Click, clickHandler); try self.peer.?.setCallback(.Draw, drawHandler); try self.peer.?.setCallback(.MouseButton, buttonHandler); try self.peer.?.setCallback(.MouseMotion, mouseMovedHandler); try self.peer.?.setCallback(.Scroll, scrollHandler); try self.peer.?.setCallback(.Resize, resizeHandler); try self.peer.?.setCallback(.KeyType, keyTypeHandler); _ = try self.dataWrappers.opacity.addChangeListener(.{ .function = opacityChanged, .userdata = @ptrToInt(self) }); opacityChanged(self.dataWrappers.opacity.get(), @ptrToInt(self)); // call it so it's updated } pub fn addClickHandler(self: *T, handler: Callback) !void { try self.handlers.clickHandlers.append(handler); } pub fn addDrawHandler(self: *T, handler: DrawCallback) !T { try self.handlers.drawHandlers.append(handler); return self.*; } pub fn addMouseButtonHandler(self: *T, handler: ButtonCallback) !void { try self.handlers.buttonHandlers.append(handler); } pub fn addMouseMotionHandler(self: *T, handler: MouseMoveCallback) !void { try self.handlers.mouseMoveHandlers.append(handler); } pub fn addScrollHandler(self: *T, handler: ScrollCallback) !void { try self.handlers.scrollHandlers.append(handler); } pub fn addResizeHandler(self: *T, handler: ResizeCallback) !void { try self.handlers.resizeHandlers.append(handler); } pub fn addKeyTypeHandler(self: *T, handler: KeyTypeCallback) !void { std.log.info("add", .{}); try self.handlers.keyTypeHandlers.append(handler); } pub fn requestDraw(self: *T) !void { if (self.peer) |*peer| { try peer.requestDraw(); } else { return RedrawError.MissingPeer; } } }; } pub fn milliTimestamp() i64 { if (@hasDecl(backend, "milliTimestamp")) { return backend.milliTimestamp(); } else { return std.time.milliTimestamp(); } }
src/internal.zig
const std = @import("std"); const string = []const u8; const input = @embedFile("../input/day03.txt"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // part 1 { var arena = std.heap.ArenaAllocator.init(&gpa.allocator); defer arena.deinit(); const alloc = &arena.allocator; var iter = std.mem.split(u8, input, "\n"); var line = iter.next().?; const len = line.len; // amount of 0s and 1s per digit var list = std.ArrayList([2]u32).init(alloc); try list.ensureTotalCapacity(line.len); for (line) |_| { try list.append([_]u32{ 0, 0 }); } // count 0s and 1s in each place while (true) { for (line) |c, i| { switch (c) { '0' => list.items[i][0] += 1, '1' => list.items[i][1] += 1, else => @panic("non-binary digit"), // trans rights } } if (iter.next()) |ll| { line = ll; continue; } break; } // create string based on whichever digit occured more var buf = try std.ArrayList(u8).initCapacity(alloc, len); for (list.toOwnedSlice()) |digits, i| { if (digits[0] > digits[1]) { try buf.append('0'); } if (digits[0] < digits[1]) { try buf.append('1'); } if (digits[0] == digits[1]) { @panic(try std.fmt.allocPrint(alloc, "same amount of 0s and 1s in {d}th place", .{i})); } } const gamma = try std.fmt.parseUnsigned(u32, buf.toOwnedSlice(), 2); const epsilon = ~gamma & (std.math.pow(u32, 2, @intCast(u32, len)) - 1); std.debug.print("{d}\n", .{gamma * epsilon}); } // part 2 { var arena = std.heap.ArenaAllocator.init(&gpa.allocator); defer arena.deinit(); const alloc = &arena.allocator; var iter = std.mem.split(u8, input, "\n"); var allnumbers = std.ArrayList(string).init(alloc); while (iter.next()) |line| { if (line.len == 0) continue; try allnumbers.append(line); } const oxygen_generator = blk: { var running = std.ArrayList(string).init(alloc); try running.appendSlice(allnumbers.items); // go over all digit places for (range(running.items.len)) |_, i| { var zeroes: u32 = 0; var ones: u32 = 0; // find which digit appears most often for (running.items) |item| { switch (item[i]) { '0' => zeroes += 1, '1' => ones += 1, else => @panic("non-binary digit"), } } // remove lower frequency items var j: usize = 0; while (j < running.items.len) { if (zeroes < ones and running.items[j][i] == '0') { _ = running.orderedRemove(j); continue; } if (ones < zeroes and running.items[j][i] == '1') { _ = running.orderedRemove(j); continue; } // oxygen preference for 1 if (zeroes == ones and running.items[j][i] == '0') { _ = running.orderedRemove(j); continue; } j += 1; } if (running.items.len == 1) { break :blk try std.fmt.parseUnsigned(u32, running.items[0], 2); } } @panic(""); }; const c02_scrubber = blk: { var running = std.ArrayList(string).init(alloc); try running.appendSlice(allnumbers.items); // go over all digit places for (range(running.items.len)) |_, i| { var zeroes: u32 = 0; var ones: u32 = 0; // find which digit appears most often for (running.items) |item| { switch (item[i]) { '0' => zeroes += 1, '1' => ones += 1, else => @panic("non-binary digit"), } } // remove higher frequency items var j: usize = 0; while (j < running.items.len) { if (zeroes < ones and running.items[j][i] == '1') { _ = running.orderedRemove(j); continue; } if (ones < zeroes and running.items[j][i] == '0') { _ = running.orderedRemove(j); continue; } // C02 preference for 1 if (zeroes == ones and running.items[j][i] == '1') { _ = running.orderedRemove(j); continue; } j += 1; } if (running.items.len == 1) { break :blk try std.fmt.parseUnsigned(u32, running.items[0], 2); } } @panic(""); }; std.debug.print("{d}\n", .{oxygen_generator * c02_scrubber}); } } pub fn range(len: usize) []const u0 { return @as([*]u0, undefined)[0..len]; }
src/day03.zig
const Scope = @import("scope.zig").Scope; pub const Instruction = struct { id: Id, scope: &Scope, pub const Id = enum { Br, CondBr, SwitchBr, SwitchVar, SwitchTarget, Phi, UnOp, BinOp, DeclVar, LoadPtr, StorePtr, FieldPtr, StructFieldPtr, UnionFieldPtr, ElemPtr, VarPtr, Call, Const, Return, Cast, ContainerInitList, ContainerInitFields, StructInit, UnionInit, Unreachable, TypeOf, ToPtrType, PtrTypeChild, SetRuntimeSafety, SetFloatMode, ArrayType, SliceType, Asm, SizeOf, TestNonNull, UnwrapMaybe, MaybeWrap, UnionTag, Clz, Ctz, Import, CImport, CInclude, CDefine, CUndef, ArrayLen, Ref, MinValue, MaxValue, CompileErr, CompileLog, ErrName, EmbedFile, Cmpxchg, Fence, Truncate, IntType, BoolNot, Memset, Memcpy, Slice, MemberCount, MemberType, MemberName, Breakpoint, ReturnAddress, FrameAddress, AlignOf, OverflowOp, TestErr, UnwrapErrCode, UnwrapErrPayload, ErrWrapCode, ErrWrapPayload, FnProto, TestComptime, PtrCast, BitCast, WidenOrShorten, IntToPtr, PtrToInt, IntToEnum, IntToErr, ErrToInt, CheckSwitchProngs, CheckStatementIsVoid, TypeName, CanImplicitCast, DeclRef, Panic, TagName, TagType, FieldParentPtr, OffsetOf, TypeId, SetEvalBranchQuota, PtrTypeOf, AlignCast, OpaqueType, SetAlignStack, ArgType, Export, }; };
src-self-hosted/ir.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day09.txt"); //const data = "2199943210\n3987894921\n9856789892\n8767896789\n9899965678"; pub fn main() !void { const input: [][]u4 = outer: { var iter = tokenize(u8, data, "\r\n"); var rows = std.ArrayList([]u4).init(gpa); while (iter.next()) |line| { const row: []u4 = inner: { var cols = std.ArrayList(u4).init(gpa); for (line) |c| { const n = try parseInt(u4, &[1]u8{c}, 10); try cols.append(n); } break :inner cols.toOwnedSlice(); }; try rows.append(row); } break :outer rows.toOwnedSlice(); }; { // part 1 var risk: u32 = 0; for (input) |line, row| { for (line) |cell, col| { const left = if (col == 0) 9 else line[col-1]; const right = if (col+1 == line.len) 9 else line[col+1]; const up = if (row == 0) 9 else input[row-1][col]; const down = if (row+1 == input.len) 9 else input[row+1][col]; if (cell<left and cell<right and cell<up and cell<down) { risk += cell + 1; } } } print("{}\n", .{risk}); } { // part 2 //const num_rows = input.len; //const num_cols = input[0].len; // Create an array of basins // The u16 is the basin number // Null means not in any basin var basins: [][]?u16 = blk: { var list = std.ArrayList([]?u16).init(gpa); var basin_number: u16 = 0; for (input) |line, row| { var list_cols = std.ArrayList(?u16).init(gpa); for (line) |cell, col| { const left = if (col == 0) 9 else line[col-1]; const right = if (col+1 == line.len) 9 else line[col+1]; const up = if (row == 0) 9 else input[row-1][col]; const down = if (row+1 == input.len) 9 else input[row+1][col]; if (cell!=9 and cell<left and cell<right and cell<up and cell<down) { try list_cols.append(basin_number); basin_number += 1; } else { try list_cols.append(null); } } try list.append(list_cols.toOwnedSlice()); } break :blk list.toOwnedSlice(); }; // Find each non-9 cell that is next to a basin and isn't a basin // Change that cell to be a basin with an adjacent basin number // Do this until all non-9 cells have a basin number var incomplete = true; while (incomplete) { incomplete = false; for (input) |line, row| { for (line) |cell, col| { if (cell == 9) continue; if (basins[row][col] != null) continue; const left = if (col==0) null else basins[row][col-1]; const right = if (col+1==line.len) null else basins[row][col+1]; const up = if (row==0) null else basins[row-1][col]; const down = if (row+1==input.len) null else basins[row+1][col]; if (left) |num| basins[row][col] = num; if (right) |num| basins[row][col] = num; if (up) |num| basins[row][col] = num; if (down) |num| basins[row][col] = num; if (basins[row][col] == null) incomplete = true; } } } // count how many cells are in each basin var counts = Map(u16,u32).init(gpa); for (basins) |line| { for (line) |cell| { if (cell) |num| { if (counts.get(num)) |count| { try counts.put(num, count+1); } else { try counts.put(num, 1); } } } } // put the count values into a list then sort it var counts_iter = counts.iterator(); var counts_list = std.ArrayList(u32).init(gpa); while (counts_iter.next()) |entry| { try counts_list.append(entry.value_ptr.*); } sort(u32, counts_list.items, {}, comptime desc(u32)); //for (counts_list.items) |item| { // print("{}\n", .{item}); //} const answer = counts_list.items[0] * counts_list.items[1] * counts_list.items[2]; print("{}\n", .{answer}); } } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day09.zig
pub const GUID_PROP_TEXTOWNER = Guid.initString("f1e2d520-0969-11d3-8df0-00105a2799b5"); pub const GUID_PROP_ATTRIBUTE = Guid.initString("34b45670-7526-11d2-a147-00105a2799b5"); pub const GUID_PROP_LANGID = Guid.initString("3280ce20-8032-11d2-b603-00105a2799b5"); pub const GUID_PROP_READING = Guid.initString("5463f7c0-8e31-11d2-bf46-00105a2799b5"); pub const GUID_PROP_COMPOSING = Guid.initString("e12ac060-af15-11d2-afc5-00105a2799b5"); pub const GUID_PROP_TKB_ALTERNATES = Guid.initString("70b2a803-968d-462e-b93b-2164c91517f7"); pub const GUID_SYSTEM_FUNCTIONPROVIDER = Guid.initString("9a698bb0-0f21-11d3-8df1-00105a2799b5"); pub const GUID_APP_FUNCTIONPROVIDER = Guid.initString("4caef01e-12af-4b0e-9db1-a6ec5b881208"); pub const GUID_TFCAT_CATEGORY_OF_TIP = Guid.initString("534c48c1-0607-4098-a521-4fc899c73e90"); pub const GUID_TFCAT_TIP_KEYBOARD = Guid.initString("34745c63-b2f0-4784-8b67-5e12c8701a31"); pub const GUID_TFCAT_TIP_SPEECH = Guid.initString("b5a73cd1-8355-426b-a161-259808f26b14"); pub const GUID_TFCAT_TIP_HANDWRITING = Guid.initString("246ecb87-c2f2-4abe-905b-c8b38add2c43"); pub const GUID_TFCAT_PROP_AUDIODATA = Guid.initString("9b7be3a9-e8ab-4d47-a8fe-254fa423436d"); pub const GUID_TFCAT_PROP_INKDATA = Guid.initString("7c6a82ae-b0d7-4f14-a745-14f28b009d61"); pub const GUID_COMPARTMENT_SAPI_AUDIO = Guid.initString("51af2086-cc6b-457d-b5aa-8b19dc290ab4"); pub const GUID_COMPARTMENT_KEYBOARD_DISABLED = Guid.initString("71a5b253-1951-466b-9fbc-9c8808fa84f2"); pub const GUID_COMPARTMENT_KEYBOARD_OPENCLOSE = Guid.initString("58273aad-01bb-4164-95c6-755ba0b5162d"); pub const GUID_COMPARTMENT_HANDWRITING_OPENCLOSE = Guid.initString("f9ae2c6b-1866-4361-af72-7aa30948890e"); pub const GUID_COMPARTMENT_SPEECH_DISABLED = Guid.initString("56c5c607-0703-4e59-8e52-cbc84e8bbe35"); pub const GUID_COMPARTMENT_SPEECH_OPENCLOSE = Guid.initString("544d6a63-e2e8-4752-bbd1-000960bca083"); pub const GUID_COMPARTMENT_SPEECH_GLOBALSTATE = Guid.initString("2a54fe8e-0d08-460c-a75d-87035ff436c5"); pub const GUID_COMPARTMENT_CONVERSIONMODEBIAS = Guid.initString("5497f516-ee91-436e-b946-aa2c05f1ac5b"); pub const GUID_PROP_MODEBIAS = Guid.initString("372e0716-974f-40ac-a088-08cdc92ebfbc"); pub const GUID_COMPARTMENT_KEYBOARD_INPUTMODE = Guid.initString("b6592511-bcee-4122-a7c4-09f4b3fa4396"); pub const GUID_MODEBIAS_NONE = Guid.initString("00000000-0000-0000-0000-000000000000"); pub const GUID_MODEBIAS_URLHISTORY = Guid.initString("8b0e54d9-63f2-4c68-84d4-79aee7a59f09"); pub const GUID_MODEBIAS_FILENAME = Guid.initString("d7f707fe-44c6-4fca-8e76-86ab50c7931b"); pub const GUID_MODEBIAS_READING = Guid.initString("e31643a3-6466-4cbf-8d8b-0bd4d8545461"); pub const GUID_MODEBIAS_DATETIME = Guid.initString("f2bdb372-7f61-4039-92ef-1c35599f0222"); pub const GUID_MODEBIAS_NAME = Guid.initString("fddc10f0-d239-49bf-b8fc-5410caaa427e"); pub const GUID_MODEBIAS_CONVERSATION = Guid.initString("0f4ec104-1790-443b-95f1-e10f939d6546"); pub const GUID_MODEBIAS_NUMERIC = Guid.initString("4021766c-e872-48fd-9cee-4ec5c75e16c3"); pub const GUID_MODEBIAS_HIRAGANA = Guid.initString("d73d316e-9b91-46f1-a280-31597f52c694"); pub const GUID_MODEBIAS_KATAKANA = Guid.initString("2e0eeddd-3a1a-499e-8543-3c7ee7949811"); pub const GUID_MODEBIAS_HANGUL = Guid.initString("76ef0541-23b3-4d77-a074-691801ccea17"); pub const GUID_MODEBIAS_CHINESE = Guid.initString("7add26de-4328-489b-83ae-6493750cad5c"); pub const GUID_MODEBIAS_HALFWIDTHKATAKANA = Guid.initString("005f6b63-78d4-41cc-8859-485ca821a795"); pub const GUID_MODEBIAS_FULLWIDTHALPHANUMERIC = Guid.initString("81489fb8-b36a-473d-8146-e4a2258b24ae"); pub const GUID_MODEBIAS_FULLWIDTHHANGUL = Guid.initString("c01ae6c9-45b5-4fd0-9cb1-9f4cebc39fea"); pub const GUID_TFCAT_PROPSTYLE_STATIC = Guid.initString("565fb8d8-6bd4-4ca1-b223-0f2ccb8f4f96"); pub const GUID_TFCAT_DISPLAYATTRIBUTEPROVIDER = Guid.initString("046b8c80-1647-40f7-9b21-b93b81aabc1b"); pub const GUID_TFCAT_DISPLAYATTRIBUTEPROPERTY = Guid.initString("b95f181b-ea4c-4af1-8056-7c321abbb091"); pub const GUID_COMPARTMENT_SPEECH_UI_STATUS = Guid.initString("d92016f0-9367-4fe7-9abf-bc59dacbe0e3"); pub const GUID_COMPARTMENT_EMPTYCONTEXT = Guid.initString("d7487dbf-804e-41c5-894d-ad96fd4eea13"); pub const GUID_COMPARTMENT_TIPUISTATUS = Guid.initString("148ca3ec-0366-401c-8d75-ed978d85fbc9"); pub const GUID_COMPARTMENT_SPEECH_CFGMENU = Guid.initString("fb6c5c2d-4e83-4bb6-91a2-e019bff6762d"); pub const GUID_LBI_SAPILAYR_CFGMENUBUTTON = Guid.initString("d02f24a1-942d-422e-8d99-b4f2addee999"); pub const GUID_TFCAT_TIPCAP_SECUREMODE = Guid.initString("49d2f9ce-1f5e-11d7-a6d3-00065b84435c"); pub const GUID_TFCAT_TIPCAP_UIELEMENTENABLED = Guid.initString("49d2f9cf-1f5e-11d7-a6d3-00065b84435c"); pub const GUID_TFCAT_TIPCAP_INPUTMODECOMPARTMENT = Guid.initString("ccf05dd7-4a87-11d7-a6e2-00065b84435c"); pub const GUID_TFCAT_TIPCAP_COMLESS = Guid.initString("364215d9-75bc-11d7-a6ef-00065b84435c"); pub const GUID_TFCAT_TIPCAP_WOW16 = Guid.initString("364215da-75bc-11d7-a6ef-00065b84435c"); pub const GUID_TFCAT_TIPCAP_IMMERSIVESUPPORT = Guid.initString("13a016df-560b-46cd-947a-4c3af1e0e35d"); pub const GUID_TFCAT_TIPCAP_IMMERSIVEONLY = Guid.initString("3a4259ac-640d-4ad4-89f7-1eb67e7c4ee8"); pub const GUID_TFCAT_TIPCAP_LOCALSERVER = Guid.initString("74769ee9-4a66-4f9d-90d6-bf8b7c3eb461"); pub const GUID_TFCAT_TIPCAP_TSF3 = Guid.initString("07dcb4af-98de-4548-bef7-25bd45979a1f"); pub const GUID_TFCAT_TIPCAP_DUALMODE = Guid.initString("3af314a2-d79f-4b1b-9992-15086d339b05"); pub const GUID_TFCAT_TIPCAP_SYSTRAYSUPPORT = Guid.initString("25504fb4-7bab-4bc1-9c69-cf81890f0ef5"); pub const GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION = Guid.initString("ccf05dd8-4a87-11d7-a6e2-00065b84435c"); pub const GUID_COMPARTMENT_KEYBOARD_INPUTMODE_SENTENCE = Guid.initString("ccf05dd9-4a87-11d7-a6e2-00065b84435c"); pub const GUID_COMPARTMENT_TRANSITORYEXTENSION = Guid.initString("8be347f5-c7a0-11d7-b408-00065b84435c"); pub const GUID_COMPARTMENT_TRANSITORYEXTENSION_DOCUMENTMANAGER = Guid.initString("8be347f7-c7a0-11d7-b408-00065b84435c"); pub const GUID_COMPARTMENT_TRANSITORYEXTENSION_PARENT = Guid.initString("8be347f8-c7a0-11d7-b408-00065b84435c"); pub const GUID_COMPARTMENT_ENABLED_PROFILES_UPDATED = Guid.initString("92c1fd48-a9ae-4a7c-be08-4329e4723817"); pub const GUID_TFCAT_TRANSITORYEXTENSIONUI = Guid.initString("6302de22-a5cf-4b02-bfe8-4d72b2bed3c6"); pub const GUID_LBI_INPUTMODE = Guid.initString("2c77a81e-41cc-4178-a3a7-5f8a987568e6"); pub const CLSID_TF_ThreadMgr = Guid.initString("529a9e6b-6587-4f23-ab9e-9c7d683e3c50"); pub const CLSID_TF_LangBarMgr = Guid.initString("ebb08c45-6c4a-4fdc-ae53-4eb8c4c7db8e"); pub const CLSID_TF_DisplayAttributeMgr = Guid.initString("3ce74de4-53d3-4d74-8b83-431b3828ba53"); pub const CLSID_TF_CategoryMgr = Guid.initString("a4b544a1-438d-4b41-9325-869523e2d6c7"); pub const CLSID_TF_InputProcessorProfiles = Guid.initString("33c53a50-f456-4884-b049-85fd643ecfed"); pub const CLSID_TF_LangBarItemMgr = Guid.initString("b9931692-a2b3-4fab-bf33-9ec6f9fb96ac"); pub const CLSID_TF_ClassicLangBar = Guid.initString("3318360c-1afc-4d09-a86b-9f9cb6dceb9c"); pub const CLSID_TF_TransitoryExtensionUIEntry = Guid.initString("ae6be008-07fb-400d-8beb-337a64f7051f"); pub const CLSID_TsfServices = Guid.initString("39aedc00-6b60-46db-8d31-3642be0e4373"); pub const GUID_TS_SERVICE_DATAOBJECT = Guid.initString("6086fbb5-e225-46ce-a770-c1bbd3e05d7b"); pub const GUID_TS_SERVICE_ACCESSIBLE = Guid.initString("f9786200-a5bf-4a0f-8c24-fb16f5d1aabb"); pub const GUID_TS_SERVICE_ACTIVEX = Guid.initString("ea937a50-c9a6-4b7d-894a-49d99b784834"); pub const TS_E_INVALIDPOS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220992)); pub const TS_E_NOLOCK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220991)); pub const TS_E_NOOBJECT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220990)); pub const TS_E_NOSERVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220989)); pub const TS_E_NOINTERFACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220988)); pub const TS_E_NOSELECTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220987)); pub const TS_E_NOLAYOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220986)); pub const TS_E_INVALIDPOINT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220985)); pub const TS_E_SYNCHRONOUS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220984)); pub const TS_E_READONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220983)); pub const TS_E_FORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220982)); pub const TS_S_ASYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, 262912)); pub const TS_AS_TEXT_CHANGE = @as(u32, 1); pub const TS_AS_SEL_CHANGE = @as(u32, 2); pub const TS_AS_LAYOUT_CHANGE = @as(u32, 4); pub const TS_AS_ATTR_CHANGE = @as(u32, 8); pub const TS_AS_STATUS_CHANGE = @as(u32, 16); pub const TS_LF_SYNC = @as(u32, 1); pub const TS_SD_READONLY = @as(u32, 1); pub const TS_SD_LOADING = @as(u32, 2); pub const TS_SD_RESERVED = @as(u32, 4); pub const TS_SD_TKBAUTOCORRECTENABLE = @as(u32, 8); pub const TS_SD_TKBPREDICTIONENABLE = @as(u32, 16); pub const TS_SD_UIINTEGRATIONENABLE = @as(u32, 32); pub const TS_SD_INPUTPANEMANUALDISPLAYENABLE = @as(u32, 64); pub const TS_SD_EMBEDDEDHANDWRITINGVIEW_ENABLED = @as(u32, 128); pub const TS_SD_EMBEDDEDHANDWRITINGVIEW_VISIBLE = @as(u32, 256); pub const TS_SS_DISJOINTSEL = @as(u32, 1); pub const TS_SS_REGIONS = @as(u32, 2); pub const TS_SS_TRANSITORY = @as(u32, 4); pub const TS_SS_NOHIDDENTEXT = @as(u32, 8); pub const TS_SS_TKBAUTOCORRECTENABLE = @as(u32, 16); pub const TS_SS_TKBPREDICTIONENABLE = @as(u32, 32); pub const TS_SS_UWPCONTROL = @as(u32, 64); pub const TS_IE_CORRECTION = @as(u32, 1); pub const TS_IE_COMPOSITION = @as(u32, 2); pub const TS_IAS_NOQUERY = @as(u32, 1); pub const TS_IAS_QUERYONLY = @as(u32, 2); pub const GXFPF_ROUND_NEAREST = @as(u32, 1); pub const GXFPF_NEAREST = @as(u32, 2); pub const TS_CHAR_EMBEDDED = @as(u32, 65532); pub const TS_CHAR_REGION = @as(u32, 0); pub const TS_CHAR_REPLACEMENT = @as(u32, 65533); pub const TS_ATTR_FIND_BACKWARDS = @as(u32, 1); pub const TS_ATTR_FIND_WANT_OFFSET = @as(u32, 2); pub const TS_ATTR_FIND_UPDATESTART = @as(u32, 4); pub const TS_ATTR_FIND_WANT_VALUE = @as(u32, 8); pub const TS_ATTR_FIND_WANT_END = @as(u32, 16); pub const TS_ATTR_FIND_HIDDEN = @as(u32, 32); pub const TS_VCOOKIE_NUL = @as(u32, 4294967295); pub const TS_SHIFT_COUNT_HIDDEN = @as(u32, 1); pub const TS_SHIFT_HALT_HIDDEN = @as(u32, 2); pub const TS_SHIFT_HALT_VISIBLE = @as(u32, 4); pub const TS_SHIFT_COUNT_ONLY = @as(u32, 8); pub const TS_GTA_HIDDEN = @as(u32, 1); pub const TS_GEA_HIDDEN = @as(u32, 1); pub const TF_E_LOCKED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220224)); pub const TF_E_STACKFULL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220223)); pub const TF_E_NOTOWNEDRANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220222)); pub const TF_E_NOPROVIDER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220221)); pub const TF_E_DISCONNECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220220)); pub const TF_E_INVALIDVIEW = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220219)); pub const TF_E_ALREADY_EXISTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220218)); pub const TF_E_RANGE_NOT_COVERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220217)); pub const TF_E_COMPOSITION_REJECTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220216)); pub const TF_E_EMPTYCONTEXT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220215)); pub const TF_E_INVALIDPOS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220992)); pub const TF_E_NOLOCK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220991)); pub const TF_E_NOOBJECT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220990)); pub const TF_E_NOSERVICE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220989)); pub const TF_E_NOINTERFACE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220988)); pub const TF_E_NOSELECTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220987)); pub const TF_E_NOLAYOUT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220986)); pub const TF_E_INVALIDPOINT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220985)); pub const TF_E_SYNCHRONOUS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220984)); pub const TF_E_READONLY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220983)); pub const TF_E_FORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147220982)); pub const TF_S_ASYNC = @import("../zig.zig").typedConst(HRESULT, @as(i32, 262912)); pub const TF_RCM_COMLESS = @as(u32, 1); pub const TF_RCM_VKEY = @as(u32, 2); pub const TF_RCM_HINT_READING_LENGTH = @as(u32, 4); pub const TF_RCM_HINT_COLLISION = @as(u32, 8); pub const TKB_ALTERNATES_STANDARD = @as(u32, 1); pub const TKB_ALTERNATES_FOR_AUTOCORRECTION = @as(u32, 2); pub const TKB_ALTERNATES_FOR_PREDICTION = @as(u32, 3); pub const TKB_ALTERNATES_AUTOCORRECTION_APPLIED = @as(u32, 4); pub const TF_TMAE_NOACTIVATETIP = @as(u32, 1); pub const TF_TMAE_SECUREMODE = @as(u32, 2); pub const TF_TMAE_UIELEMENTENABLEDONLY = @as(u32, 4); pub const TF_TMAE_COMLESS = @as(u32, 8); pub const TF_TMAE_WOW16 = @as(u32, 16); pub const TF_TMAE_NOACTIVATEKEYBOARDLAYOUT = @as(u32, 32); pub const TF_TMAE_CONSOLE = @as(u32, 64); pub const TF_TMF_NOACTIVATETIP = @as(u32, 1); pub const TF_TMF_SECUREMODE = @as(u32, 2); pub const TF_TMF_UIELEMENTENABLEDONLY = @as(u32, 4); pub const TF_TMF_COMLESS = @as(u32, 8); pub const TF_TMF_WOW16 = @as(u32, 16); pub const TF_TMF_CONSOLE = @as(u32, 64); pub const TF_TMF_IMMERSIVEMODE = @as(u32, 1073741824); pub const TF_TMF_ACTIVATED = @as(u32, 2147483648); pub const TF_MOD_ALT = @as(u32, 1); pub const TF_MOD_CONTROL = @as(u32, 2); pub const TF_MOD_SHIFT = @as(u32, 4); pub const TF_MOD_RALT = @as(u32, 8); pub const TF_MOD_RCONTROL = @as(u32, 16); pub const TF_MOD_RSHIFT = @as(u32, 32); pub const TF_MOD_LALT = @as(u32, 64); pub const TF_MOD_LCONTROL = @as(u32, 128); pub const TF_MOD_LSHIFT = @as(u32, 256); pub const TF_MOD_ON_KEYUP = @as(u32, 512); pub const TF_MOD_IGNORE_ALL_MODIFIER = @as(u32, 1024); pub const TF_US_HIDETIPUI = @as(u32, 1); pub const TF_DISABLE_SPEECH = @as(u32, 1); pub const TF_DISABLE_DICTATION = @as(u32, 2); pub const TF_DISABLE_COMMANDING = @as(u32, 4); pub const TF_CLUIE_DOCUMENTMGR = @as(u32, 1); pub const TF_CLUIE_COUNT = @as(u32, 2); pub const TF_CLUIE_SELECTION = @as(u32, 4); pub const TF_CLUIE_STRING = @as(u32, 8); pub const TF_CLUIE_PAGEINDEX = @as(u32, 16); pub const TF_CLUIE_CURRENTPAGE = @as(u32, 32); pub const TF_RIUIE_CONTEXT = @as(u32, 1); pub const TF_RIUIE_STRING = @as(u32, 2); pub const TF_RIUIE_MAXREADINGSTRINGLENGTH = @as(u32, 4); pub const TF_RIUIE_ERRORINDEX = @as(u32, 8); pub const TF_RIUIE_VERTICALORDER = @as(u32, 16); pub const TF_CONVERSIONMODE_ALPHANUMERIC = @as(u32, 0); pub const TF_CONVERSIONMODE_NATIVE = @as(u32, 1); pub const TF_CONVERSIONMODE_KATAKANA = @as(u32, 2); pub const TF_CONVERSIONMODE_FULLSHAPE = @as(u32, 8); pub const TF_CONVERSIONMODE_ROMAN = @as(u32, 16); pub const TF_CONVERSIONMODE_CHARCODE = @as(u32, 32); pub const TF_CONVERSIONMODE_SOFTKEYBOARD = @as(u32, 128); pub const TF_CONVERSIONMODE_NOCONVERSION = @as(u32, 256); pub const TF_CONVERSIONMODE_EUDC = @as(u32, 512); pub const TF_CONVERSIONMODE_SYMBOL = @as(u32, 1024); pub const TF_CONVERSIONMODE_FIXED = @as(u32, 2048); pub const TF_SENTENCEMODE_NONE = @as(u32, 0); pub const TF_SENTENCEMODE_PLAURALCLAUSE = @as(u32, 1); pub const TF_SENTENCEMODE_SINGLECONVERT = @as(u32, 2); pub const TF_SENTENCEMODE_AUTOMATIC = @as(u32, 4); pub const TF_SENTENCEMODE_PHRASEPREDICT = @as(u32, 8); pub const TF_SENTENCEMODE_CONVERSATION = @as(u32, 16); pub const TF_TRANSITORYEXTENSION_NONE = @as(u32, 0); pub const TF_TRANSITORYEXTENSION_FLOATING = @as(u32, 1); pub const TF_TRANSITORYEXTENSION_ATSELECTION = @as(u32, 2); pub const TF_PROFILETYPE_INPUTPROCESSOR = @as(u32, 1); pub const TF_PROFILETYPE_KEYBOARDLAYOUT = @as(u32, 2); pub const TF_RIP_FLAG_FREEUNUSEDLIBRARIES = @as(u32, 1); pub const TF_IPP_FLAG_ACTIVE = @as(u32, 1); pub const TF_IPP_FLAG_ENABLED = @as(u32, 2); pub const TF_IPP_FLAG_SUBSTITUTEDBYINPUTPROCESSOR = @as(u32, 4); pub const TF_IPP_CAPS_DISABLEONTRANSITORY = @as(u32, 1); pub const TF_IPP_CAPS_SECUREMODESUPPORT = @as(u32, 2); pub const TF_IPP_CAPS_UIELEMENTENABLED = @as(u32, 4); pub const TF_IPP_CAPS_COMLESSSUPPORT = @as(u32, 8); pub const TF_IPP_CAPS_WOW16SUPPORT = @as(u32, 16); pub const TF_IPP_CAPS_IMMERSIVESUPPORT = @as(u32, 65536); pub const TF_IPP_CAPS_SYSTRAYSUPPORT = @as(u32, 131072); pub const TF_IPPMF_FORPROCESS = @as(u32, 268435456); pub const TF_IPPMF_FORSESSION = @as(u32, 536870912); pub const TF_IPPMF_FORSYSTEMALL = @as(u32, 1073741824); pub const TF_IPPMF_ENABLEPROFILE = @as(u32, 1); pub const TF_IPPMF_DISABLEPROFILE = @as(u32, 2); pub const TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE = @as(u32, 4); pub const TF_RP_HIDDENINSETTINGUI = @as(u32, 2); pub const TF_RP_LOCALPROCESS = @as(u32, 4); pub const TF_RP_LOCALTHREAD = @as(u32, 8); pub const TF_RP_SUBITEMINSETTINGUI = @as(u32, 16); pub const TF_URP_ALLPROFILES = @as(u32, 2); pub const TF_URP_LOCALPROCESS = @as(u32, 4); pub const TF_URP_LOCALTHREAD = @as(u32, 8); pub const TF_IPSINK_FLAG_ACTIVE = @as(u32, 1); pub const TF_INVALID_EDIT_COOKIE = @as(u32, 0); pub const TF_POPF_ALL = @as(u32, 1); pub const TF_SD_READONLY = @as(u32, 1); pub const TF_SD_LOADING = @as(u32, 2); pub const TF_SS_DISJOINTSEL = @as(u32, 1); pub const TF_SS_REGIONS = @as(u32, 2); pub const TF_SS_TRANSITORY = @as(u32, 4); pub const TF_SS_TKBAUTOCORRECTENABLE = @as(u32, 16); pub const TF_SS_TKBPREDICTIONENABLE = @as(u32, 32); pub const TF_CHAR_EMBEDDED = @as(u32, 65532); pub const TF_HF_OBJECT = @as(u32, 1); pub const TF_TF_MOVESTART = @as(u32, 1); pub const TF_TF_IGNOREEND = @as(u32, 2); pub const TF_ST_CORRECTION = @as(u32, 1); pub const TF_IE_CORRECTION = @as(u32, 1); pub const TF_TU_CORRECTION = @as(u32, 1); pub const TF_INVALID_COOKIE = @as(u32, 4294967295); pub const TF_PROFILE_NEWPHONETIC = Guid.initString("b2f9c502-1742-11d4-9790-0080c882687e"); pub const TF_PROFILE_PHONETIC = Guid.initString("761309de-317a-11d4-9b5d-0080c882687e"); pub const TF_PROFILE_NEWCHANGJIE = Guid.initString("f3ba907a-6c7e-11d4-97fa-0080c882687e"); pub const TF_PROFILE_CHANGJIE = Guid.initString("4bdf9f03-c7d3-11d4-b2ab-0080c882687e"); pub const TF_PROFILE_NEWQUICK = Guid.initString("0b883ba0-c1c7-11d4-87f9-0080c882687e"); pub const TF_PROFILE_QUICK = Guid.initString("6024b45f-5c54-11d4-b921-0080c882687e"); pub const TF_PROFILE_CANTONESE = Guid.initString("0aec109c-7e96-11d4-b2ef-0080c882687e"); pub const TF_PROFILE_PINYIN = Guid.initString("f3ba9077-6c7e-11d4-97fa-0080c882687e"); pub const TF_PROFILE_SIMPLEFAST = Guid.initString("fa550b04-5ad7-411f-a5ac-ca038ec515d7"); pub const TF_PROFILE_WUBI = Guid.initString("82590c13-f4dd-44f4-ba1d-8667246fdf8e"); pub const TF_PROFILE_DAYI = Guid.initString("037b2c25-480c-4d7f-b027-d6ca6b69788a"); pub const TF_PROFILE_ARRAY = Guid.initString("d38eff65-aa46-4fd5-91a7-67845fb02f5b"); pub const TF_PROFILE_YI = Guid.initString("409c8376-007b-4357-ae8e-26316ee3fb0d"); pub const TF_PROFILE_TIGRINYA = Guid.initString("3cab88b7-cc3e-46a6-9765-b772ad7761ff"); pub const TF_E_NOCONVERSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147219968)); pub const TF_DICTATION_ON = @as(u32, 1); pub const TF_DICTATION_ENABLED = @as(u32, 2); pub const TF_COMMANDING_ENABLED = @as(u32, 4); pub const TF_COMMANDING_ON = @as(u32, 8); pub const TF_SPEECHUI_SHOWN = @as(u32, 16); pub const TF_SHOW_BALLOON = @as(u32, 1); pub const TF_DISABLE_BALLOON = @as(u32, 2); pub const TF_MENUREADY = @as(u32, 1); pub const TF_PROPUI_STATUS_SAVETOFILE = @as(u32, 1); pub const GUID_INTEGRATIONSTYLE_SEARCHBOX = Guid.initString("e6d1bd11-82f7-4903-ae21-1a6397cde2eb"); pub const TKBL_UNDEFINED = @as(u32, 0); pub const TKBL_CLASSIC_TRADITIONAL_CHINESE_PHONETIC = @as(u32, 1028); pub const TKBL_CLASSIC_TRADITIONAL_CHINESE_CHANGJIE = @as(u32, 61506); pub const TKBL_CLASSIC_TRADITIONAL_CHINESE_DAYI = @as(u32, 61507); pub const TKBL_OPT_JAPANESE_ABC = @as(u32, 1041); pub const TKBL_OPT_KOREAN_HANGUL_2_BULSIK = @as(u32, 1042); pub const TKBL_OPT_SIMPLIFIED_CHINESE_PINYIN = @as(u32, 2052); pub const TKBL_OPT_TRADITIONAL_CHINESE_PHONETIC = @as(u32, 1028); pub const TF_LBI_ICON = @as(u32, 1); pub const TF_LBI_TEXT = @as(u32, 2); pub const TF_LBI_TOOLTIP = @as(u32, 4); pub const TF_LBI_BITMAP = @as(u32, 8); pub const TF_LBI_BALLOON = @as(u32, 16); pub const TF_LBI_CUSTOMUI = @as(u32, 32); pub const TF_LBI_STATUS = @as(u32, 65536); pub const TF_LBI_STYLE_HIDDENSTATUSCONTROL = @as(u32, 1); pub const TF_LBI_STYLE_SHOWNINTRAY = @as(u32, 2); pub const TF_LBI_STYLE_HIDEONNOOTHERITEMS = @as(u32, 4); pub const TF_LBI_STYLE_SHOWNINTRAYONLY = @as(u32, 8); pub const TF_LBI_STYLE_HIDDENBYDEFAULT = @as(u32, 16); pub const TF_LBI_STYLE_TEXTCOLORICON = @as(u32, 32); pub const TF_LBI_STYLE_BTN_BUTTON = @as(u32, 65536); pub const TF_LBI_STYLE_BTN_MENU = @as(u32, 131072); pub const TF_LBI_STYLE_BTN_TOGGLE = @as(u32, 262144); pub const TF_LBI_STATUS_HIDDEN = @as(u32, 1); pub const TF_LBI_STATUS_DISABLED = @as(u32, 2); pub const TF_LBI_STATUS_BTN_TOGGLED = @as(u32, 65536); pub const TF_LBI_BMPF_VERTICAL = @as(u32, 1); pub const TF_SFT_SHOWNORMAL = @as(u32, 1); pub const TF_SFT_DOCK = @as(u32, 2); pub const TF_SFT_MINIMIZED = @as(u32, 4); pub const TF_SFT_HIDDEN = @as(u32, 8); pub const TF_SFT_NOTRANSPARENCY = @as(u32, 16); pub const TF_SFT_LOWTRANSPARENCY = @as(u32, 32); pub const TF_SFT_HIGHTRANSPARENCY = @as(u32, 64); pub const TF_SFT_LABELS = @as(u32, 128); pub const TF_SFT_NOLABELS = @as(u32, 256); pub const TF_SFT_EXTRAICONSONMINIMIZED = @as(u32, 512); pub const TF_SFT_NOEXTRAICONSONMINIMIZED = @as(u32, 1024); pub const TF_SFT_DESKBAND = @as(u32, 2048); pub const TF_LBI_DESC_MAXLEN = @as(u32, 32); pub const TF_LBMENUF_CHECKED = @as(u32, 1); pub const TF_LBMENUF_SUBMENU = @as(u32, 2); pub const TF_LBMENUF_SEPARATOR = @as(u32, 4); pub const TF_LBMENUF_RADIOCHECKED = @as(u32, 8); pub const TF_LBMENUF_GRAYED = @as(u32, 16); pub const GUID_PROP_INPUTSCOPE = Guid.initString("1713dd5a-68e7-4a5b-9af6-592a595c778d"); pub const DCM_FLAGS_TASKENG = @as(u32, 1); pub const DCM_FLAGS_CTFMON = @as(u32, 2); pub const DCM_FLAGS_LOCALTHREADTSF = @as(u32, 4); pub const ILMCM_CHECKLAYOUTANDTIPENABLED = @as(u32, 1); pub const ILMCM_LANGUAGEBAROFF = @as(u32, 2); pub const LIBID_MSAATEXTLib = Guid.initString("150e2d7a-dac1-4582-947d-2a8fd78b82cd"); pub const TS_STRF_START = @as(u32, 0); pub const TS_STRF_MID = @as(u32, 1); pub const TS_STRF_END = @as(u32, 2); pub const TSATTRID_OTHERS = Guid.initString("b3c32af9-57d0-46a9-bca8-dac238a13057"); pub const TSATTRID_Font = Guid.initString("573ea825-749b-4f8a-9cfd-21c3605ca828"); pub const TSATTRID_Font_FaceName = Guid.initString("b536aeb6-053b-4eb8-b65a-50da1e81e72e"); pub const TSATTRID_Font_SizePts = Guid.initString("c8493302-a5e9-456d-af04-8005e4130f03"); pub const TSATTRID_Font_Style = Guid.initString("68b2a77f-6b0e-4f28-8177-571c2f3a42b1"); pub const TSATTRID_Font_Style_Bold = Guid.initString("48813a43-8a20-4940-8e58-97823f7b268a"); pub const TSATTRID_Font_Style_Italic = Guid.initString("8740682a-a765-48e1-acfc-d22222b2f810"); pub const TSATTRID_Font_Style_SmallCaps = Guid.initString("facb6bc6-9100-4cc6-b969-11eea45a86b4"); pub const TSATTRID_Font_Style_Capitalize = Guid.initString("7d85a3ba-b4fd-43b3-befc-6b985c843141"); pub const TSATTRID_Font_Style_Uppercase = Guid.initString("33a300e8-e340-4937-b697-8f234045cd9a"); pub const TSATTRID_Font_Style_Lowercase = Guid.initString("76d8ccb5-ca7b-4498-8ee9-d5c4f6f74c60"); pub const TSATTRID_Font_Style_Animation = Guid.initString("dcf73d22-e029-47b7-bb36-f263a3d004cc"); pub const TSATTRID_Font_Style_Animation_LasVegasLights = Guid.initString("f40423d5-0f87-4f8f-bada-e6d60c25e152"); pub const TSATTRID_Font_Style_Animation_BlinkingBackground = Guid.initString("86e5b104-0104-4b10-b585-00f2527522b5"); pub const TSATTRID_Font_Style_Animation_SparkleText = Guid.initString("533aad20-962c-4e9f-8c09-b42ea4749711"); pub const TSATTRID_Font_Style_Animation_MarchingBlackAnts = Guid.initString("7644e067-f186-4902-bfc6-ec815aa20e9d"); pub const TSATTRID_Font_Style_Animation_MarchingRedAnts = Guid.initString("78368dad-50fb-4c6f-840b-d486bb6cf781"); pub const TSATTRID_Font_Style_Animation_Shimmer = Guid.initString("2ce31b58-5293-4c36-8809-bf8bb51a27b3"); pub const TSATTRID_Font_Style_Animation_WipeDown = Guid.initString("5872e874-367b-4803-b160-c90ff62569d0"); pub const TSATTRID_Font_Style_Animation_WipeRight = Guid.initString("b855cbe3-3d2c-4600-b1e9-e1c9ce02f842"); pub const TSATTRID_Font_Style_Emboss = Guid.initString("bd8ed742-349e-4e37-82fb-437979cb53a7"); pub const TSATTRID_Font_Style_Engrave = Guid.initString("9c3371de-8332-4897-be5d-89233223179a"); pub const TSATTRID_Font_Style_Hidden = Guid.initString("b1e28770-881c-475f-863f-887a647b1090"); pub const TSATTRID_Font_Style_Kerning = Guid.initString("cc26e1b4-2f9a-47c8-8bff-bf1eb7cce0dd"); pub const TSATTRID_Font_Style_Outlined = Guid.initString("10e6db31-db0d-4ac6-a7f5-9c9cff6f2ab4"); pub const TSATTRID_Font_Style_Position = Guid.initString("15cd26ab-f2fb-4062-b5a6-9a49e1a5cc0b"); pub const TSATTRID_Font_Style_Protected = Guid.initString("1c557cb2-14cf-4554-a574-ecb2f7e7efd4"); pub const TSATTRID_Font_Style_Shadow = Guid.initString("5f686d2f-c6cd-4c56-8a1a-994a4b9766be"); pub const TSATTRID_Font_Style_Spacing = Guid.initString("98c1200d-8f06-409a-8e49-6a554bf7c153"); pub const TSATTRID_Font_Style_Weight = Guid.initString("12f3189c-8bb0-461b-b1fa-eaf907047fe0"); pub const TSATTRID_Font_Style_Height = Guid.initString("7e937477-12e6-458b-926a-1fa44ee8f391"); pub const TSATTRID_Font_Style_Underline = Guid.initString("c3c9c9f3-7902-444b-9a7b-48e70f4b50f7"); pub const TSATTRID_Font_Style_Underline_Single = Guid.initString("1b6720e5-0f73-4951-a6b3-6f19e43c9461"); pub const TSATTRID_Font_Style_Underline_Double = Guid.initString("74d24aa6-1db3-4c69-a176-31120e7586d5"); pub const TSATTRID_Font_Style_Strikethrough = Guid.initString("0c562193-2d08-4668-9601-ced41309d7af"); pub const TSATTRID_Font_Style_Strikethrough_Single = Guid.initString("75d736b6-3c8f-4b97-ab78-1877cb990d31"); pub const TSATTRID_Font_Style_Strikethrough_Double = Guid.initString("62489b31-a3e7-4f94-ac43-ebaf8fcc7a9f"); pub const TSATTRID_Font_Style_Overline = Guid.initString("e3989f4a-992b-4301-8ce1-a5b7c6d1f3c8"); pub const TSATTRID_Font_Style_Overline_Single = Guid.initString("8440d94c-51ce-47b2-8d4c-15751e5f721b"); pub const TSATTRID_Font_Style_Overline_Double = Guid.initString("dc46063a-e115-46e3-bcd8-ca6772aa95b4"); pub const TSATTRID_Font_Style_Blink = Guid.initString("bfb2c036-7acf-4532-b720-b416dd7765a8"); pub const TSATTRID_Font_Style_Subscript = Guid.initString("5774fb84-389b-43bc-a74b-1568347cf0f4"); pub const TSATTRID_Font_Style_Superscript = Guid.initString("2ea4993c-563c-49aa-9372-0bef09a9255b"); pub const TSATTRID_Font_Style_Color = Guid.initString("857a7a37-b8af-4e9a-81b4-acf700c8411b"); pub const TSATTRID_Font_Style_BackgroundColor = Guid.initString("b50eaa4e-3091-4468-81db-d79ea190c7c7"); pub const TSATTRID_Text = Guid.initString("7edb8e68-81f9-449d-a15a-87a8388faac0"); pub const TSATTRID_Text_VerticalWriting = Guid.initString("6bba8195-046f-4ea9-b311-97fd66c4274b"); pub const TSATTRID_Text_RightToLeft = Guid.initString("ca666e71-1b08-453d-bfdd-28e08c8aaf7a"); pub const TSATTRID_Text_Orientation = Guid.initString("6bab707f-8785-4c39-8b52-96f878303ffb"); pub const TSATTRID_Text_Language = Guid.initString("d8c04ef1-5753-4c25-8887-85443fe5f819"); pub const TSATTRID_Text_ReadOnly = Guid.initString("85836617-de32-4afd-a50f-a2db110e6e4d"); pub const TSATTRID_Text_EmbeddedObject = Guid.initString("7edb8e68-81f9-449d-a15a-87a8388faac0"); pub const TSATTRID_Text_Alignment = Guid.initString("139941e6-1767-456d-938e-35ba568b5cd4"); pub const TSATTRID_Text_Alignment_Left = Guid.initString("16ae95d3-6361-43a2-8495-d00f397f1693"); pub const TSATTRID_Text_Alignment_Right = Guid.initString("b36f0f98-1b9e-4360-8616-03fb08a78456"); pub const TSATTRID_Text_Alignment_Center = Guid.initString("a4a95c16-53bf-4d55-8b87-4bdd8d4275fc"); pub const TSATTRID_Text_Alignment_Justify = Guid.initString("ed350740-a0f7-42d3-8ea8-f81b6488faf0"); pub const TSATTRID_Text_Link = Guid.initString("47cd9051-3722-4cd8-b7c8-4e17ca1759f5"); pub const TSATTRID_Text_Hyphenation = Guid.initString("dadf4525-618e-49eb-b1a8-3b68bd7648e3"); pub const TSATTRID_Text_Para = Guid.initString("5edc5822-99dc-4dd6-aec3-b62baa5b2e7c"); pub const TSATTRID_Text_Para_FirstLineIndent = Guid.initString("07c97a13-7472-4dd8-90a9-91e3d7e4f29c"); pub const TSATTRID_Text_Para_LeftIndent = Guid.initString("fb2848e9-7471-41c9-b6b3-8a1450e01897"); pub const TSATTRID_Text_Para_RightIndent = Guid.initString("2c7f26f9-a5e2-48da-b98a-520cb16513bf"); pub const TSATTRID_Text_Para_SpaceAfter = Guid.initString("7b0a3f55-22dc-425f-a411-93da1d8f9baa"); pub const TSATTRID_Text_Para_SpaceBefore = Guid.initString("8df98589-194a-4601-b251-9865a3e906dd"); pub const TSATTRID_Text_Para_LineSpacing = Guid.initString("699b380d-7f8c-46d6-a73b-dfe3d1538df3"); pub const TSATTRID_Text_Para_LineSpacing_Single = Guid.initString("ed350740-a0f7-42d3-8ea8-f81b6488faf0"); pub const TSATTRID_Text_Para_LineSpacing_OnePtFive = Guid.initString("0428a021-0397-4b57-9a17-0795994cd3c5"); pub const TSATTRID_Text_Para_LineSpacing_Double = Guid.initString("82fb1805-a6c4-4231-ac12-6260af2aba28"); pub const TSATTRID_Text_Para_LineSpacing_AtLeast = Guid.initString("adfedf31-2d44-4434-a5ff-7f4c4990a905"); pub const TSATTRID_Text_Para_LineSpacing_Exactly = Guid.initString("3d45ad40-23de-48d7-a6b3-765420c620cc"); pub const TSATTRID_Text_Para_LineSpacing_Multiple = Guid.initString("910f1e3c-d6d0-4f65-8a3c-42b4b31868c5"); pub const TSATTRID_List = Guid.initString("436d673b-26f1-4aee-9e65-8f83a4ed4884"); pub const TSATTRID_List_LevelIndel = Guid.initString("7f7cc899-311f-487b-ad5d-e2a459e12d42"); pub const TSATTRID_List_Type = Guid.initString("ae3e665e-4bce-49e3-a0fe-2db47d3a17ae"); pub const TSATTRID_List_Type_Bullet = Guid.initString("bccd77c5-4c4d-4ce2-b102-559f3b2bfcea"); pub const TSATTRID_List_Type_Arabic = Guid.initString("1338c5d6-98a3-4fa3-9bd1-7a60eef8e9e0"); pub const TSATTRID_List_Type_LowerLetter = Guid.initString("96372285-f3cf-491e-a925-3832347fd237"); pub const TSATTRID_List_Type_UpperLetter = Guid.initString("7987b7cd-ce52-428b-9b95-a357f6f10c45"); pub const TSATTRID_List_Type_LowerRoman = Guid.initString("90466262-3980-4b8e-9368-918bd1218a41"); pub const TSATTRID_List_Type_UpperRoman = Guid.initString("0f6ab552-4a80-467f-b2f1-127e2aa3ba9e"); pub const TSATTRID_App = Guid.initString("a80f77df-4237-40e5-849c-b5fa51c13ac7"); pub const TSATTRID_App_IncorrectSpelling = Guid.initString("f42de43c-ef12-430d-944c-9a08970a25d2"); pub const TSATTRID_App_IncorrectGrammar = Guid.initString("bd54e398-ad03-4b74-b6b3-5edb19996388"); //-------------------------------------------------------------------------------- // Section: Types (211) //-------------------------------------------------------------------------------- pub const LANG_BAR_ITEM_ICON_MODE_FLAGS = enum(u32) { NONE = 0, USEPROFILEICON = 1, }; pub const TF_DTLBI_NONE = LANG_BAR_ITEM_ICON_MODE_FLAGS.NONE; pub const TF_DTLBI_USEPROFILEICON = LANG_BAR_ITEM_ICON_MODE_FLAGS.USEPROFILEICON; pub const TEXT_STORE_TEXT_CHANGE_FLAGS = enum(u32) { NONE = 0, CORRECTION = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, CORRECTION: u1 = 0, }) TEXT_STORE_TEXT_CHANGE_FLAGS { return @intToEnum(TEXT_STORE_TEXT_CHANGE_FLAGS, (if (o.NONE == 1) @enumToInt(TEXT_STORE_TEXT_CHANGE_FLAGS.NONE) else 0) | (if (o.CORRECTION == 1) @enumToInt(TEXT_STORE_TEXT_CHANGE_FLAGS.CORRECTION) else 0) ); } }; pub const TS_ST_NONE = TEXT_STORE_TEXT_CHANGE_FLAGS.NONE; pub const TS_ST_CORRECTION = TEXT_STORE_TEXT_CHANGE_FLAGS.CORRECTION; pub const TEXT_STORE_CHANGE_FLAGS = enum(u32) { NONE = 0, CORRECTION = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, CORRECTION: u1 = 0, }) TEXT_STORE_CHANGE_FLAGS { return @intToEnum(TEXT_STORE_CHANGE_FLAGS, (if (o.NONE == 1) @enumToInt(TEXT_STORE_CHANGE_FLAGS.NONE) else 0) | (if (o.CORRECTION == 1) @enumToInt(TEXT_STORE_CHANGE_FLAGS.CORRECTION) else 0) ); } }; pub const TS_TC_NONE = TEXT_STORE_CHANGE_FLAGS.NONE; pub const TS_TC_CORRECTION = TEXT_STORE_CHANGE_FLAGS.CORRECTION; pub const INSERT_TEXT_AT_SELECTION_FLAGS = enum(u32) { NOQUERY = 1, QUERYONLY = 2, NO_DEFAULT_COMPOSITION = 2147483648, }; pub const TF_IAS_NOQUERY = INSERT_TEXT_AT_SELECTION_FLAGS.NOQUERY; pub const TF_IAS_QUERYONLY = INSERT_TEXT_AT_SELECTION_FLAGS.QUERYONLY; pub const TF_IAS_NO_DEFAULT_COMPOSITION = INSERT_TEXT_AT_SELECTION_FLAGS.NO_DEFAULT_COMPOSITION; pub const ANCHOR_CHANGE_HISTORY_FLAGS = enum(u32) { PRECEDING_DEL = 1, FOLLOWING_DEL = 2, _, pub fn initFlags(o: struct { PRECEDING_DEL: u1 = 0, FOLLOWING_DEL: u1 = 0, }) ANCHOR_CHANGE_HISTORY_FLAGS { return @intToEnum(ANCHOR_CHANGE_HISTORY_FLAGS, (if (o.PRECEDING_DEL == 1) @enumToInt(ANCHOR_CHANGE_HISTORY_FLAGS.PRECEDING_DEL) else 0) | (if (o.FOLLOWING_DEL == 1) @enumToInt(ANCHOR_CHANGE_HISTORY_FLAGS.FOLLOWING_DEL) else 0) ); } }; pub const TS_CH_PRECEDING_DEL = ANCHOR_CHANGE_HISTORY_FLAGS.PRECEDING_DEL; pub const TS_CH_FOLLOWING_DEL = ANCHOR_CHANGE_HISTORY_FLAGS.FOLLOWING_DEL; pub const TEXT_STORE_LOCK_FLAGS = enum(u32) { D = 2, WRITE = 6, }; pub const TS_LF_READ = TEXT_STORE_LOCK_FLAGS.D; pub const TS_LF_READWRITE = TEXT_STORE_LOCK_FLAGS.WRITE; pub const GET_TEXT_AND_PROPERTY_UPDATES_FLAGS = enum(u32) { NONE = 0, INCL_TEXT = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, INCL_TEXT: u1 = 0, }) GET_TEXT_AND_PROPERTY_UPDATES_FLAGS { return @intToEnum(GET_TEXT_AND_PROPERTY_UPDATES_FLAGS, (if (o.NONE == 1) @enumToInt(GET_TEXT_AND_PROPERTY_UPDATES_FLAGS.NONE) else 0) | (if (o.INCL_TEXT == 1) @enumToInt(GET_TEXT_AND_PROPERTY_UPDATES_FLAGS.INCL_TEXT) else 0) ); } }; pub const TF_GTP_NONE = GET_TEXT_AND_PROPERTY_UPDATES_FLAGS.NONE; pub const TF_GTP_INCL_TEXT = GET_TEXT_AND_PROPERTY_UPDATES_FLAGS.INCL_TEXT; pub const TF_CONTEXT_EDIT_CONTEXT_FLAGS = enum(u32) { ASYNCDONTCARE = 0, SYNC = 1, READ = 2, READWRITE = 6, ASYNC = 8, _, pub fn initFlags(o: struct { ASYNCDONTCARE: u1 = 0, SYNC: u1 = 0, READ: u1 = 0, READWRITE: u1 = 0, ASYNC: u1 = 0, }) TF_CONTEXT_EDIT_CONTEXT_FLAGS { return @intToEnum(TF_CONTEXT_EDIT_CONTEXT_FLAGS, (if (o.ASYNCDONTCARE == 1) @enumToInt(TF_CONTEXT_EDIT_CONTEXT_FLAGS.ASYNCDONTCARE) else 0) | (if (o.SYNC == 1) @enumToInt(TF_CONTEXT_EDIT_CONTEXT_FLAGS.SYNC) else 0) | (if (o.READ == 1) @enumToInt(TF_CONTEXT_EDIT_CONTEXT_FLAGS.READ) else 0) | (if (o.READWRITE == 1) @enumToInt(TF_CONTEXT_EDIT_CONTEXT_FLAGS.READWRITE) else 0) | (if (o.ASYNC == 1) @enumToInt(TF_CONTEXT_EDIT_CONTEXT_FLAGS.ASYNC) else 0) ); } }; pub const TF_ES_ASYNCDONTCARE = TF_CONTEXT_EDIT_CONTEXT_FLAGS.ASYNCDONTCARE; pub const TF_ES_SYNC = TF_CONTEXT_EDIT_CONTEXT_FLAGS.SYNC; pub const TF_ES_READ = TF_CONTEXT_EDIT_CONTEXT_FLAGS.READ; pub const TF_ES_READWRITE = TF_CONTEXT_EDIT_CONTEXT_FLAGS.READWRITE; pub const TF_ES_ASYNC = TF_CONTEXT_EDIT_CONTEXT_FLAGS.ASYNC; pub const HKL = *opaque{}; pub const TS_STATUS = extern struct { dwDynamicFlags: u32, dwStaticFlags: u32, }; pub const TS_TEXTCHANGE = extern struct { acpStart: i32, acpOldEnd: i32, acpNewEnd: i32, }; pub const TsActiveSelEnd = enum(i32) { NONE = 0, START = 1, END = 2, }; pub const TS_AE_NONE = TsActiveSelEnd.NONE; pub const TS_AE_START = TsActiveSelEnd.START; pub const TS_AE_END = TsActiveSelEnd.END; pub const TS_SELECTIONSTYLE = extern struct { ase: TsActiveSelEnd, fInterimChar: BOOL, }; pub const TS_SELECTION_ACP = extern struct { acpStart: i32, acpEnd: i32, style: TS_SELECTIONSTYLE, }; pub const TS_SELECTION_ANCHOR = extern struct { paStart: ?*IAnchor, paEnd: ?*IAnchor, style: TS_SELECTIONSTYLE, }; pub const TS_ATTRVAL = extern struct { idAttr: Guid, dwOverlapId: u32, varValue: VARIANT, }; pub const TsLayoutCode = enum(i32) { CREATE = 0, CHANGE = 1, DESTROY = 2, }; pub const TS_LC_CREATE = TsLayoutCode.CREATE; pub const TS_LC_CHANGE = TsLayoutCode.CHANGE; pub const TS_LC_DESTROY = TsLayoutCode.DESTROY; pub const TsRunType = enum(i32) { PLAIN = 0, HIDDEN = 1, OPAQUE = 2, }; pub const TS_RT_PLAIN = TsRunType.PLAIN; pub const TS_RT_HIDDEN = TsRunType.HIDDEN; pub const TS_RT_OPAQUE = TsRunType.OPAQUE; pub const TS_RUNINFO = extern struct { uCount: u32, type: TsRunType, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITextStoreACP_Value = Guid.initString("28888fe3-c2a0-483a-a3ea-8cb1ce51ff3d"); pub const IID_ITextStoreACP = &IID_ITextStoreACP_Value; pub const ITextStoreACP = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseSink: fn( self: *const ITextStoreACP, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseSink: fn( self: *const ITextStoreACP, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestLock: fn( self: *const ITextStoreACP, dwLockFlags: u32, phrSession: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITextStoreACP, pdcs: ?*TS_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsert: fn( self: *const ITextStoreACP, acpTestStart: i32, acpTestEnd: i32, cch: u32, pacpResultStart: ?*i32, pacpResultEnd: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelection: fn( self: *const ITextStoreACP, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ACP, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSelection: fn( self: *const ITextStoreACP, ulCount: u32, pSelection: [*]const TS_SELECTION_ACP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetText: fn( self: *const ITextStoreACP, acpStart: i32, acpEnd: i32, pchPlain: [*:0]u16, cchPlainReq: u32, pcchPlainRet: ?*u32, prgRunInfo: [*]TS_RUNINFO, cRunInfoReq: u32, pcRunInfoRet: ?*u32, pacpNext: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetText: fn( self: *const ITextStoreACP, dwFlags: u32, acpStart: i32, acpEnd: i32, pchText: [*:0]const u16, cch: u32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormattedText: fn( self: *const ITextStoreACP, acpStart: i32, acpEnd: i32, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEmbedded: fn( self: *const ITextStoreACP, acpPos: i32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsertEmbedded: fn( self: *const ITextStoreACP, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbedded: fn( self: *const ITextStoreACP, dwFlags: u32, acpStart: i32, acpEnd: i32, pDataObject: ?*IDataObject, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertTextAtSelection: fn( self: *const ITextStoreACP, dwFlags: u32, pchText: [*:0]const u16, cch: u32, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbeddedAtSelection: fn( self: *const ITextStoreACP, dwFlags: u32, pDataObject: ?*IDataObject, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestSupportedAttrs: fn( self: *const ITextStoreACP, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsAtPosition: fn( self: *const ITextStoreACP, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsTransitioningAtPosition: fn( self: *const ITextStoreACP, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindNextAttrTransition: fn( self: *const ITextStoreACP, acpStart: i32, acpHalt: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pacpNext: ?*i32, pfFound: ?*BOOL, plFoundOffset: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RetrieveRequestedAttrs: fn( self: *const ITextStoreACP, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndACP: fn( self: *const ITextStoreACP, pacp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveView: fn( self: *const ITextStoreACP, pvcView: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetACPFromPoint: fn( self: *const ITextStoreACP, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextExt: fn( self: *const ITextStoreACP, vcView: u32, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScreenExt: fn( self: *const ITextStoreACP, vcView: u32, prc: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWnd: fn( self: *const ITextStoreACP, vcView: u32, phwnd: ?*?HWND, ) 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 ITextStoreACP_AdviseSink(self: *const T, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).AdviseSink(@ptrCast(*const ITextStoreACP, self), riid, punk, dwMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_UnadviseSink(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).UnadviseSink(@ptrCast(*const ITextStoreACP, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_RequestLock(self: *const T, dwLockFlags: u32, phrSession: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).RequestLock(@ptrCast(*const ITextStoreACP, self), dwLockFlags, phrSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetStatus(self: *const T, pdcs: ?*TS_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetStatus(@ptrCast(*const ITextStoreACP, self), pdcs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_QueryInsert(self: *const T, acpTestStart: i32, acpTestEnd: i32, cch: u32, pacpResultStart: ?*i32, pacpResultEnd: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).QueryInsert(@ptrCast(*const ITextStoreACP, self), acpTestStart, acpTestEnd, cch, pacpResultStart, pacpResultEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetSelection(self: *const T, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ACP, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetSelection(@ptrCast(*const ITextStoreACP, self), ulIndex, ulCount, pSelection, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_SetSelection(self: *const T, ulCount: u32, pSelection: [*]const TS_SELECTION_ACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).SetSelection(@ptrCast(*const ITextStoreACP, self), ulCount, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetText(self: *const T, acpStart: i32, acpEnd: i32, pchPlain: [*:0]u16, cchPlainReq: u32, pcchPlainRet: ?*u32, prgRunInfo: [*]TS_RUNINFO, cRunInfoReq: u32, pcRunInfoRet: ?*u32, pacpNext: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetText(@ptrCast(*const ITextStoreACP, self), acpStart, acpEnd, pchPlain, cchPlainReq, pcchPlainRet, prgRunInfo, cRunInfoReq, pcRunInfoRet, pacpNext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_SetText(self: *const T, dwFlags: u32, acpStart: i32, acpEnd: i32, pchText: [*:0]const u16, cch: u32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).SetText(@ptrCast(*const ITextStoreACP, self), dwFlags, acpStart, acpEnd, pchText, cch, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetFormattedText(self: *const T, acpStart: i32, acpEnd: i32, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetFormattedText(@ptrCast(*const ITextStoreACP, self), acpStart, acpEnd, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetEmbedded(self: *const T, acpPos: i32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetEmbedded(@ptrCast(*const ITextStoreACP, self), acpPos, rguidService, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_QueryInsertEmbedded(self: *const T, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).QueryInsertEmbedded(@ptrCast(*const ITextStoreACP, self), pguidService, pFormatEtc, pfInsertable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_InsertEmbedded(self: *const T, dwFlags: u32, acpStart: i32, acpEnd: i32, pDataObject: ?*IDataObject, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).InsertEmbedded(@ptrCast(*const ITextStoreACP, self), dwFlags, acpStart, acpEnd, pDataObject, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_InsertTextAtSelection(self: *const T, dwFlags: u32, pchText: [*:0]const u16, cch: u32, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).InsertTextAtSelection(@ptrCast(*const ITextStoreACP, self), dwFlags, pchText, cch, pacpStart, pacpEnd, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_InsertEmbeddedAtSelection(self: *const T, dwFlags: u32, pDataObject: ?*IDataObject, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).InsertEmbeddedAtSelection(@ptrCast(*const ITextStoreACP, self), dwFlags, pDataObject, pacpStart, pacpEnd, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_RequestSupportedAttrs(self: *const T, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).RequestSupportedAttrs(@ptrCast(*const ITextStoreACP, self), dwFlags, cFilterAttrs, paFilterAttrs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_RequestAttrsAtPosition(self: *const T, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).RequestAttrsAtPosition(@ptrCast(*const ITextStoreACP, self), acpPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_RequestAttrsTransitioningAtPosition(self: *const T, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).RequestAttrsTransitioningAtPosition(@ptrCast(*const ITextStoreACP, self), acpPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_FindNextAttrTransition(self: *const T, acpStart: i32, acpHalt: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pacpNext: ?*i32, pfFound: ?*BOOL, plFoundOffset: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).FindNextAttrTransition(@ptrCast(*const ITextStoreACP, self), acpStart, acpHalt, cFilterAttrs, paFilterAttrs, dwFlags, pacpNext, pfFound, plFoundOffset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_RetrieveRequestedAttrs(self: *const T, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).RetrieveRequestedAttrs(@ptrCast(*const ITextStoreACP, self), ulCount, paAttrVals, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetEndACP(self: *const T, pacp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetEndACP(@ptrCast(*const ITextStoreACP, self), pacp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetActiveView(self: *const T, pvcView: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetActiveView(@ptrCast(*const ITextStoreACP, self), pvcView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetACPFromPoint(self: *const T, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetACPFromPoint(@ptrCast(*const ITextStoreACP, self), vcView, ptScreen, dwFlags, pacp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetTextExt(self: *const T, vcView: u32, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetTextExt(@ptrCast(*const ITextStoreACP, self), vcView, acpStart, acpEnd, prc, pfClipped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetScreenExt(self: *const T, vcView: u32, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetScreenExt(@ptrCast(*const ITextStoreACP, self), vcView, prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP_GetWnd(self: *const T, vcView: u32, phwnd: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP.VTable, self.vtable).GetWnd(@ptrCast(*const ITextStoreACP, self), vcView, phwnd); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_ITextStoreACP2_Value = Guid.initString("f86ad89f-5fe4-4b8d-bb9f-ef3797a84f1f"); pub const IID_ITextStoreACP2 = &IID_ITextStoreACP2_Value; pub const ITextStoreACP2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseSink: fn( self: *const ITextStoreACP2, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseSink: fn( self: *const ITextStoreACP2, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestLock: fn( self: *const ITextStoreACP2, dwLockFlags: u32, phrSession: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITextStoreACP2, pdcs: ?*TS_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsert: fn( self: *const ITextStoreACP2, acpTestStart: i32, acpTestEnd: i32, cch: u32, pacpResultStart: ?*i32, pacpResultEnd: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelection: fn( self: *const ITextStoreACP2, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ACP, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSelection: fn( self: *const ITextStoreACP2, ulCount: u32, pSelection: [*]const TS_SELECTION_ACP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetText: fn( self: *const ITextStoreACP2, acpStart: i32, acpEnd: i32, pchPlain: [*:0]u16, cchPlainReq: u32, pcchPlainRet: ?*u32, prgRunInfo: [*]TS_RUNINFO, cRunInfoReq: u32, pcRunInfoRet: ?*u32, pacpNext: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetText: fn( self: *const ITextStoreACP2, dwFlags: u32, acpStart: i32, acpEnd: i32, pchText: [*:0]const u16, cch: u32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormattedText: fn( self: *const ITextStoreACP2, acpStart: i32, acpEnd: i32, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEmbedded: fn( self: *const ITextStoreACP2, acpPos: i32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsertEmbedded: fn( self: *const ITextStoreACP2, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbedded: fn( self: *const ITextStoreACP2, dwFlags: u32, acpStart: i32, acpEnd: i32, pDataObject: ?*IDataObject, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertTextAtSelection: fn( self: *const ITextStoreACP2, dwFlags: u32, pchText: [*:0]const u16, cch: u32, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbeddedAtSelection: fn( self: *const ITextStoreACP2, dwFlags: u32, pDataObject: ?*IDataObject, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestSupportedAttrs: fn( self: *const ITextStoreACP2, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsAtPosition: fn( self: *const ITextStoreACP2, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsTransitioningAtPosition: fn( self: *const ITextStoreACP2, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindNextAttrTransition: fn( self: *const ITextStoreACP2, acpStart: i32, acpHalt: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pacpNext: ?*i32, pfFound: ?*BOOL, plFoundOffset: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RetrieveRequestedAttrs: fn( self: *const ITextStoreACP2, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEndACP: fn( self: *const ITextStoreACP2, pacp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveView: fn( self: *const ITextStoreACP2, pvcView: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetACPFromPoint: fn( self: *const ITextStoreACP2, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextExt: fn( self: *const ITextStoreACP2, vcView: u32, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScreenExt: fn( self: *const ITextStoreACP2, vcView: u32, prc: ?*RECT, ) 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 ITextStoreACP2_AdviseSink(self: *const T, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).AdviseSink(@ptrCast(*const ITextStoreACP2, self), riid, punk, dwMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_UnadviseSink(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).UnadviseSink(@ptrCast(*const ITextStoreACP2, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_RequestLock(self: *const T, dwLockFlags: u32, phrSession: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).RequestLock(@ptrCast(*const ITextStoreACP2, self), dwLockFlags, phrSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetStatus(self: *const T, pdcs: ?*TS_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetStatus(@ptrCast(*const ITextStoreACP2, self), pdcs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_QueryInsert(self: *const T, acpTestStart: i32, acpTestEnd: i32, cch: u32, pacpResultStart: ?*i32, pacpResultEnd: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).QueryInsert(@ptrCast(*const ITextStoreACP2, self), acpTestStart, acpTestEnd, cch, pacpResultStart, pacpResultEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetSelection(self: *const T, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ACP, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetSelection(@ptrCast(*const ITextStoreACP2, self), ulIndex, ulCount, pSelection, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_SetSelection(self: *const T, ulCount: u32, pSelection: [*]const TS_SELECTION_ACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).SetSelection(@ptrCast(*const ITextStoreACP2, self), ulCount, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetText(self: *const T, acpStart: i32, acpEnd: i32, pchPlain: [*:0]u16, cchPlainReq: u32, pcchPlainRet: ?*u32, prgRunInfo: [*]TS_RUNINFO, cRunInfoReq: u32, pcRunInfoRet: ?*u32, pacpNext: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetText(@ptrCast(*const ITextStoreACP2, self), acpStart, acpEnd, pchPlain, cchPlainReq, pcchPlainRet, prgRunInfo, cRunInfoReq, pcRunInfoRet, pacpNext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_SetText(self: *const T, dwFlags: u32, acpStart: i32, acpEnd: i32, pchText: [*:0]const u16, cch: u32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).SetText(@ptrCast(*const ITextStoreACP2, self), dwFlags, acpStart, acpEnd, pchText, cch, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetFormattedText(self: *const T, acpStart: i32, acpEnd: i32, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetFormattedText(@ptrCast(*const ITextStoreACP2, self), acpStart, acpEnd, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetEmbedded(self: *const T, acpPos: i32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetEmbedded(@ptrCast(*const ITextStoreACP2, self), acpPos, rguidService, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_QueryInsertEmbedded(self: *const T, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).QueryInsertEmbedded(@ptrCast(*const ITextStoreACP2, self), pguidService, pFormatEtc, pfInsertable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_InsertEmbedded(self: *const T, dwFlags: u32, acpStart: i32, acpEnd: i32, pDataObject: ?*IDataObject, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).InsertEmbedded(@ptrCast(*const ITextStoreACP2, self), dwFlags, acpStart, acpEnd, pDataObject, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_InsertTextAtSelection(self: *const T, dwFlags: u32, pchText: [*:0]const u16, cch: u32, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).InsertTextAtSelection(@ptrCast(*const ITextStoreACP2, self), dwFlags, pchText, cch, pacpStart, pacpEnd, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_InsertEmbeddedAtSelection(self: *const T, dwFlags: u32, pDataObject: ?*IDataObject, pacpStart: ?*i32, pacpEnd: ?*i32, pChange: ?*TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).InsertEmbeddedAtSelection(@ptrCast(*const ITextStoreACP2, self), dwFlags, pDataObject, pacpStart, pacpEnd, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_RequestSupportedAttrs(self: *const T, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).RequestSupportedAttrs(@ptrCast(*const ITextStoreACP2, self), dwFlags, cFilterAttrs, paFilterAttrs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_RequestAttrsAtPosition(self: *const T, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).RequestAttrsAtPosition(@ptrCast(*const ITextStoreACP2, self), acpPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_RequestAttrsTransitioningAtPosition(self: *const T, acpPos: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).RequestAttrsTransitioningAtPosition(@ptrCast(*const ITextStoreACP2, self), acpPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_FindNextAttrTransition(self: *const T, acpStart: i32, acpHalt: i32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pacpNext: ?*i32, pfFound: ?*BOOL, plFoundOffset: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).FindNextAttrTransition(@ptrCast(*const ITextStoreACP2, self), acpStart, acpHalt, cFilterAttrs, paFilterAttrs, dwFlags, pacpNext, pfFound, plFoundOffset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_RetrieveRequestedAttrs(self: *const T, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).RetrieveRequestedAttrs(@ptrCast(*const ITextStoreACP2, self), ulCount, paAttrVals, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetEndACP(self: *const T, pacp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetEndACP(@ptrCast(*const ITextStoreACP2, self), pacp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetActiveView(self: *const T, pvcView: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetActiveView(@ptrCast(*const ITextStoreACP2, self), pvcView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetACPFromPoint(self: *const T, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetACPFromPoint(@ptrCast(*const ITextStoreACP2, self), vcView, ptScreen, dwFlags, pacp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetTextExt(self: *const T, vcView: u32, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetTextExt(@ptrCast(*const ITextStoreACP2, self), vcView, acpStart, acpEnd, prc, pfClipped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACP2_GetScreenExt(self: *const T, vcView: u32, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACP2.VTable, self.vtable).GetScreenExt(@ptrCast(*const ITextStoreACP2, self), vcView, prc); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITextStoreACPSink_Value = Guid.initString("22d44c94-a419-4542-a272-ae26093ececf"); pub const IID_ITextStoreACPSink = &IID_ITextStoreACPSink_Value; pub const ITextStoreACPSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnTextChange: fn( self: *const ITextStoreACPSink, dwFlags: TEXT_STORE_TEXT_CHANGE_FLAGS, pChange: ?*const TS_TEXTCHANGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSelectionChange: fn( self: *const ITextStoreACPSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLayoutChange: fn( self: *const ITextStoreACPSink, lcode: TsLayoutCode, vcView: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStatusChange: fn( self: *const ITextStoreACPSink, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnAttrsChange: fn( self: *const ITextStoreACPSink, acpStart: i32, acpEnd: i32, cAttrs: u32, paAttrs: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLockGranted: fn( self: *const ITextStoreACPSink, dwLockFlags: TEXT_STORE_LOCK_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStartEditTransaction: fn( self: *const ITextStoreACPSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndEditTransaction: fn( self: *const ITextStoreACPSink, ) 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 ITextStoreACPSink_OnTextChange(self: *const T, dwFlags: TEXT_STORE_TEXT_CHANGE_FLAGS, pChange: ?*const TS_TEXTCHANGE) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnTextChange(@ptrCast(*const ITextStoreACPSink, self), dwFlags, pChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnSelectionChange(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnSelectionChange(@ptrCast(*const ITextStoreACPSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnLayoutChange(self: *const T, lcode: TsLayoutCode, vcView: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnLayoutChange(@ptrCast(*const ITextStoreACPSink, self), lcode, vcView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnStatusChange(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnStatusChange(@ptrCast(*const ITextStoreACPSink, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnAttrsChange(self: *const T, acpStart: i32, acpEnd: i32, cAttrs: u32, paAttrs: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnAttrsChange(@ptrCast(*const ITextStoreACPSink, self), acpStart, acpEnd, cAttrs, paAttrs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnLockGranted(self: *const T, dwLockFlags: TEXT_STORE_LOCK_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnLockGranted(@ptrCast(*const ITextStoreACPSink, self), dwLockFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnStartEditTransaction(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnStartEditTransaction(@ptrCast(*const ITextStoreACPSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSink_OnEndEditTransaction(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSink.VTable, self.vtable).OnEndEditTransaction(@ptrCast(*const ITextStoreACPSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const TsGravity = enum(i32) { BACKWARD = 0, FORWARD = 1, }; pub const TS_GR_BACKWARD = TsGravity.BACKWARD; pub const TS_GR_FORWARD = TsGravity.FORWARD; pub const TsShiftDir = enum(i32) { BACKWARD = 0, FORWARD = 1, }; pub const TS_SD_BACKWARD = TsShiftDir.BACKWARD; pub const TS_SD_FORWARD = TsShiftDir.FORWARD; // TODO: this type is limited to platform 'windows5.0' const IID_IAnchor_Value = Guid.initString("0feb7e34-5a60-4356-8ef7-abdec2ff7cf8"); pub const IID_IAnchor = &IID_IAnchor_Value; pub const IAnchor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetGravity: fn( self: *const IAnchor, gravity: TsGravity, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGravity: fn( self: *const IAnchor, pgravity: ?*TsGravity, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEqual: fn( self: *const IAnchor, paWith: ?*IAnchor, pfEqual: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Compare: fn( self: *const IAnchor, paWith: ?*IAnchor, plResult: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Shift: fn( self: *const IAnchor, dwFlags: u32, cchReq: i32, pcch: ?*i32, paHaltAnchor: ?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftTo: fn( self: *const IAnchor, paSite: ?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftRegion: fn( self: *const IAnchor, dwFlags: u32, dir: TsShiftDir, pfNoRegion: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetChangeHistoryMask: fn( self: *const IAnchor, dwMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChangeHistory: fn( self: *const IAnchor, pdwHistory: ?*ANCHOR_CHANGE_HISTORY_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearChangeHistory: fn( self: *const IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IAnchor, ppaClone: ?*?*IAnchor, ) 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 IAnchor_SetGravity(self: *const T, gravity: TsGravity) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).SetGravity(@ptrCast(*const IAnchor, self), gravity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_GetGravity(self: *const T, pgravity: ?*TsGravity) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).GetGravity(@ptrCast(*const IAnchor, self), pgravity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_IsEqual(self: *const T, paWith: ?*IAnchor, pfEqual: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).IsEqual(@ptrCast(*const IAnchor, self), paWith, pfEqual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_Compare(self: *const T, paWith: ?*IAnchor, plResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).Compare(@ptrCast(*const IAnchor, self), paWith, plResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_Shift(self: *const T, dwFlags: u32, cchReq: i32, pcch: ?*i32, paHaltAnchor: ?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).Shift(@ptrCast(*const IAnchor, self), dwFlags, cchReq, pcch, paHaltAnchor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_ShiftTo(self: *const T, paSite: ?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).ShiftTo(@ptrCast(*const IAnchor, self), paSite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_ShiftRegion(self: *const T, dwFlags: u32, dir: TsShiftDir, pfNoRegion: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).ShiftRegion(@ptrCast(*const IAnchor, self), dwFlags, dir, pfNoRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_SetChangeHistoryMask(self: *const T, dwMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).SetChangeHistoryMask(@ptrCast(*const IAnchor, self), dwMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_GetChangeHistory(self: *const T, pdwHistory: ?*ANCHOR_CHANGE_HISTORY_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).GetChangeHistory(@ptrCast(*const IAnchor, self), pdwHistory); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_ClearChangeHistory(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).ClearChangeHistory(@ptrCast(*const IAnchor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAnchor_Clone(self: *const T, ppaClone: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const IAnchor.VTable, self.vtable).Clone(@ptrCast(*const IAnchor, self), ppaClone); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITextStoreAnchor_Value = Guid.initString("9b2077b0-5f18-4dec-bee9-3cc722f5dfe0"); pub const IID_ITextStoreAnchor = &IID_ITextStoreAnchor_Value; pub const ITextStoreAnchor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseSink: fn( self: *const ITextStoreAnchor, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseSink: fn( self: *const ITextStoreAnchor, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestLock: fn( self: *const ITextStoreAnchor, dwLockFlags: u32, phrSession: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITextStoreAnchor, pdcs: ?*TS_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsert: fn( self: *const ITextStoreAnchor, paTestStart: ?*IAnchor, paTestEnd: ?*IAnchor, cch: u32, ppaResultStart: ?*?*IAnchor, ppaResultEnd: ?*?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelection: fn( self: *const ITextStoreAnchor, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ANCHOR, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSelection: fn( self: *const ITextStoreAnchor, ulCount: u32, pSelection: [*]const TS_SELECTION_ANCHOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetText: fn( self: *const ITextStoreAnchor, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pchText: [*:0]u16, cchReq: u32, pcch: ?*u32, fUpdateAnchor: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetText: fn( self: *const ITextStoreAnchor, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pchText: [*:0]const u16, cch: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormattedText: fn( self: *const ITextStoreAnchor, paStart: ?*IAnchor, paEnd: ?*IAnchor, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEmbedded: fn( self: *const ITextStoreAnchor, dwFlags: u32, paPos: ?*IAnchor, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbedded: fn( self: *const ITextStoreAnchor, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestSupportedAttrs: fn( self: *const ITextStoreAnchor, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsAtPosition: fn( self: *const ITextStoreAnchor, paPos: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestAttrsTransitioningAtPosition: fn( self: *const ITextStoreAnchor, paPos: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindNextAttrTransition: fn( self: *const ITextStoreAnchor, paStart: ?*IAnchor, paHalt: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pfFound: ?*BOOL, plFoundOffset: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RetrieveRequestedAttrs: fn( self: *const ITextStoreAnchor, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStart: fn( self: *const ITextStoreAnchor, ppaStart: ?*?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnd: fn( self: *const ITextStoreAnchor, ppaEnd: ?*?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveView: fn( self: *const ITextStoreAnchor, pvcView: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAnchorFromPoint: fn( self: *const ITextStoreAnchor, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, ppaSite: ?*?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextExt: fn( self: *const ITextStoreAnchor, vcView: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, prc: ?*RECT, pfClipped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScreenExt: fn( self: *const ITextStoreAnchor, vcView: u32, prc: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWnd: fn( self: *const ITextStoreAnchor, vcView: u32, phwnd: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryInsertEmbedded: fn( self: *const ITextStoreAnchor, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertTextAtSelection: fn( self: *const ITextStoreAnchor, dwFlags: u32, pchText: [*:0]const u16, cch: u32, ppaStart: ?*?*IAnchor, ppaEnd: ?*?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbeddedAtSelection: fn( self: *const ITextStoreAnchor, dwFlags: u32, pDataObject: ?*IDataObject, ppaStart: ?*?*IAnchor, ppaEnd: ?*?*IAnchor, ) 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 ITextStoreAnchor_AdviseSink(self: *const T, riid: ?*const Guid, punk: ?*IUnknown, dwMask: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).AdviseSink(@ptrCast(*const ITextStoreAnchor, self), riid, punk, dwMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_UnadviseSink(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).UnadviseSink(@ptrCast(*const ITextStoreAnchor, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_RequestLock(self: *const T, dwLockFlags: u32, phrSession: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).RequestLock(@ptrCast(*const ITextStoreAnchor, self), dwLockFlags, phrSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetStatus(self: *const T, pdcs: ?*TS_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetStatus(@ptrCast(*const ITextStoreAnchor, self), pdcs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_QueryInsert(self: *const T, paTestStart: ?*IAnchor, paTestEnd: ?*IAnchor, cch: u32, ppaResultStart: ?*?*IAnchor, ppaResultEnd: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).QueryInsert(@ptrCast(*const ITextStoreAnchor, self), paTestStart, paTestEnd, cch, ppaResultStart, ppaResultEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetSelection(self: *const T, ulIndex: u32, ulCount: u32, pSelection: [*]TS_SELECTION_ANCHOR, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetSelection(@ptrCast(*const ITextStoreAnchor, self), ulIndex, ulCount, pSelection, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_SetSelection(self: *const T, ulCount: u32, pSelection: [*]const TS_SELECTION_ANCHOR) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).SetSelection(@ptrCast(*const ITextStoreAnchor, self), ulCount, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetText(self: *const T, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pchText: [*:0]u16, cchReq: u32, pcch: ?*u32, fUpdateAnchor: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetText(@ptrCast(*const ITextStoreAnchor, self), dwFlags, paStart, paEnd, pchText, cchReq, pcch, fUpdateAnchor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_SetText(self: *const T, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pchText: [*:0]const u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).SetText(@ptrCast(*const ITextStoreAnchor, self), dwFlags, paStart, paEnd, pchText, cch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetFormattedText(self: *const T, paStart: ?*IAnchor, paEnd: ?*IAnchor, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetFormattedText(@ptrCast(*const ITextStoreAnchor, self), paStart, paEnd, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetEmbedded(self: *const T, dwFlags: u32, paPos: ?*IAnchor, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetEmbedded(@ptrCast(*const ITextStoreAnchor, self), dwFlags, paPos, rguidService, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_InsertEmbedded(self: *const T, dwFlags: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, pDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).InsertEmbedded(@ptrCast(*const ITextStoreAnchor, self), dwFlags, paStart, paEnd, pDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_RequestSupportedAttrs(self: *const T, dwFlags: u32, cFilterAttrs: u32, paFilterAttrs: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).RequestSupportedAttrs(@ptrCast(*const ITextStoreAnchor, self), dwFlags, cFilterAttrs, paFilterAttrs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_RequestAttrsAtPosition(self: *const T, paPos: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).RequestAttrsAtPosition(@ptrCast(*const ITextStoreAnchor, self), paPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_RequestAttrsTransitioningAtPosition(self: *const T, paPos: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).RequestAttrsTransitioningAtPosition(@ptrCast(*const ITextStoreAnchor, self), paPos, cFilterAttrs, paFilterAttrs, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_FindNextAttrTransition(self: *const T, paStart: ?*IAnchor, paHalt: ?*IAnchor, cFilterAttrs: u32, paFilterAttrs: [*]const Guid, dwFlags: u32, pfFound: ?*BOOL, plFoundOffset: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).FindNextAttrTransition(@ptrCast(*const ITextStoreAnchor, self), paStart, paHalt, cFilterAttrs, paFilterAttrs, dwFlags, pfFound, plFoundOffset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_RetrieveRequestedAttrs(self: *const T, ulCount: u32, paAttrVals: [*]TS_ATTRVAL, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).RetrieveRequestedAttrs(@ptrCast(*const ITextStoreAnchor, self), ulCount, paAttrVals, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetStart(self: *const T, ppaStart: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetStart(@ptrCast(*const ITextStoreAnchor, self), ppaStart); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetEnd(self: *const T, ppaEnd: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetEnd(@ptrCast(*const ITextStoreAnchor, self), ppaEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetActiveView(self: *const T, pvcView: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetActiveView(@ptrCast(*const ITextStoreAnchor, self), pvcView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetAnchorFromPoint(self: *const T, vcView: u32, ptScreen: ?*const POINT, dwFlags: u32, ppaSite: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetAnchorFromPoint(@ptrCast(*const ITextStoreAnchor, self), vcView, ptScreen, dwFlags, ppaSite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetTextExt(self: *const T, vcView: u32, paStart: ?*IAnchor, paEnd: ?*IAnchor, prc: ?*RECT, pfClipped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetTextExt(@ptrCast(*const ITextStoreAnchor, self), vcView, paStart, paEnd, prc, pfClipped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetScreenExt(self: *const T, vcView: u32, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetScreenExt(@ptrCast(*const ITextStoreAnchor, self), vcView, prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_GetWnd(self: *const T, vcView: u32, phwnd: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).GetWnd(@ptrCast(*const ITextStoreAnchor, self), vcView, phwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_QueryInsertEmbedded(self: *const T, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).QueryInsertEmbedded(@ptrCast(*const ITextStoreAnchor, self), pguidService, pFormatEtc, pfInsertable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_InsertTextAtSelection(self: *const T, dwFlags: u32, pchText: [*:0]const u16, cch: u32, ppaStart: ?*?*IAnchor, ppaEnd: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).InsertTextAtSelection(@ptrCast(*const ITextStoreAnchor, self), dwFlags, pchText, cch, ppaStart, ppaEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchor_InsertEmbeddedAtSelection(self: *const T, dwFlags: u32, pDataObject: ?*IDataObject, ppaStart: ?*?*IAnchor, ppaEnd: ?*?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchor.VTable, self.vtable).InsertEmbeddedAtSelection(@ptrCast(*const ITextStoreAnchor, self), dwFlags, pDataObject, ppaStart, ppaEnd); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITextStoreAnchorSink_Value = Guid.initString("aa80e905-2021-11d2-93e0-0060b067b86e"); pub const IID_ITextStoreAnchorSink = &IID_ITextStoreAnchorSink_Value; pub const ITextStoreAnchorSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnTextChange: fn( self: *const ITextStoreAnchorSink, dwFlags: TEXT_STORE_CHANGE_FLAGS, paStart: ?*IAnchor, paEnd: ?*IAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSelectionChange: fn( self: *const ITextStoreAnchorSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLayoutChange: fn( self: *const ITextStoreAnchorSink, lcode: TsLayoutCode, vcView: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStatusChange: fn( self: *const ITextStoreAnchorSink, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnAttrsChange: fn( self: *const ITextStoreAnchorSink, paStart: ?*IAnchor, paEnd: ?*IAnchor, cAttrs: u32, paAttrs: [*]const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLockGranted: fn( self: *const ITextStoreAnchorSink, dwLockFlags: TEXT_STORE_LOCK_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStartEditTransaction: fn( self: *const ITextStoreAnchorSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndEditTransaction: fn( self: *const ITextStoreAnchorSink, ) 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 ITextStoreAnchorSink_OnTextChange(self: *const T, dwFlags: TEXT_STORE_CHANGE_FLAGS, paStart: ?*IAnchor, paEnd: ?*IAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnTextChange(@ptrCast(*const ITextStoreAnchorSink, self), dwFlags, paStart, paEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnSelectionChange(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnSelectionChange(@ptrCast(*const ITextStoreAnchorSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnLayoutChange(self: *const T, lcode: TsLayoutCode, vcView: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnLayoutChange(@ptrCast(*const ITextStoreAnchorSink, self), lcode, vcView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnStatusChange(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnStatusChange(@ptrCast(*const ITextStoreAnchorSink, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnAttrsChange(self: *const T, paStart: ?*IAnchor, paEnd: ?*IAnchor, cAttrs: u32, paAttrs: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnAttrsChange(@ptrCast(*const ITextStoreAnchorSink, self), paStart, paEnd, cAttrs, paAttrs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnLockGranted(self: *const T, dwLockFlags: TEXT_STORE_LOCK_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnLockGranted(@ptrCast(*const ITextStoreAnchorSink, self), dwLockFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnStartEditTransaction(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnStartEditTransaction(@ptrCast(*const ITextStoreAnchorSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreAnchorSink_OnEndEditTransaction(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorSink.VTable, self.vtable).OnEndEditTransaction(@ptrCast(*const ITextStoreAnchorSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarMgr_Value = Guid.initString("87955690-e627-11d2-8ddb-00105a2799b5"); pub const IID_ITfLangBarMgr = &IID_ITfLangBarMgr_Value; pub const ITfLangBarMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseEventSink: fn( self: *const ITfLangBarMgr, pSink: ?*ITfLangBarEventSink, hwnd: ?HWND, dwFlags: u32, pdwCookie: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseEventSink: fn( self: *const ITfLangBarMgr, dwCookie: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThreadMarshalInterface: fn( self: *const ITfLangBarMgr, dwThreadId: u32, dwType: u32, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetThreadLangBarItemMgr: fn( self: *const ITfLangBarMgr, dwThreadId: u32, pplbi: ?*?*ITfLangBarItemMgr, pdwThreadid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputProcessorProfiles: fn( self: *const ITfLangBarMgr, dwThreadId: u32, ppaip: ?*?*ITfInputProcessorProfiles, pdwThreadid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreLastFocus: fn( self: *const ITfLangBarMgr, pdwThreadId: ?*u32, fPrev: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetModalInput: fn( self: *const ITfLangBarMgr, pSink: ?*ITfLangBarEventSink, dwThreadId: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowFloating: fn( self: *const ITfLangBarMgr, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetShowFloatingStatus: fn( self: *const ITfLangBarMgr, pdwFlags: ?*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 ITfLangBarMgr_AdviseEventSink(self: *const T, pSink: ?*ITfLangBarEventSink, hwnd: ?HWND, dwFlags: u32, pdwCookie: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).AdviseEventSink(@ptrCast(*const ITfLangBarMgr, self), pSink, hwnd, dwFlags, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_UnadviseEventSink(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).UnadviseEventSink(@ptrCast(*const ITfLangBarMgr, self), dwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_GetThreadMarshalInterface(self: *const T, dwThreadId: u32, dwType: u32, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).GetThreadMarshalInterface(@ptrCast(*const ITfLangBarMgr, self), dwThreadId, dwType, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_GetThreadLangBarItemMgr(self: *const T, dwThreadId: u32, pplbi: ?*?*ITfLangBarItemMgr, pdwThreadid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).GetThreadLangBarItemMgr(@ptrCast(*const ITfLangBarMgr, self), dwThreadId, pplbi, pdwThreadid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_GetInputProcessorProfiles(self: *const T, dwThreadId: u32, ppaip: ?*?*ITfInputProcessorProfiles, pdwThreadid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).GetInputProcessorProfiles(@ptrCast(*const ITfLangBarMgr, self), dwThreadId, ppaip, pdwThreadid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_RestoreLastFocus(self: *const T, pdwThreadId: ?*u32, fPrev: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).RestoreLastFocus(@ptrCast(*const ITfLangBarMgr, self), pdwThreadId, fPrev); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_SetModalInput(self: *const T, pSink: ?*ITfLangBarEventSink, dwThreadId: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).SetModalInput(@ptrCast(*const ITfLangBarMgr, self), pSink, dwThreadId, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_ShowFloating(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).ShowFloating(@ptrCast(*const ITfLangBarMgr, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarMgr_GetShowFloatingStatus(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarMgr.VTable, self.vtable).GetShowFloatingStatus(@ptrCast(*const ITfLangBarMgr, self), pdwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarEventSink_Value = Guid.initString("18a4e900-e0ae-11d2-afdd-00105a2799b5"); pub const IID_ITfLangBarEventSink = &IID_ITfLangBarEventSink_Value; pub const ITfLangBarEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnSetFocus: fn( self: *const ITfLangBarEventSink, dwThreadId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnThreadTerminate: fn( self: *const ITfLangBarEventSink, dwThreadId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnThreadItemChange: fn( self: *const ITfLangBarEventSink, dwThreadId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnModalInput: fn( self: *const ITfLangBarEventSink, dwThreadId: u32, uMsg: u32, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowFloating: fn( self: *const ITfLangBarEventSink, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItemFloatingRect: fn( self: *const ITfLangBarEventSink, dwThreadId: u32, rguid: ?*const Guid, prc: ?*RECT, ) 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 ITfLangBarEventSink_OnSetFocus(self: *const T, dwThreadId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).OnSetFocus(@ptrCast(*const ITfLangBarEventSink, self), dwThreadId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarEventSink_OnThreadTerminate(self: *const T, dwThreadId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).OnThreadTerminate(@ptrCast(*const ITfLangBarEventSink, self), dwThreadId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarEventSink_OnThreadItemChange(self: *const T, dwThreadId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).OnThreadItemChange(@ptrCast(*const ITfLangBarEventSink, self), dwThreadId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarEventSink_OnModalInput(self: *const T, dwThreadId: u32, uMsg: u32, wParam: WPARAM, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).OnModalInput(@ptrCast(*const ITfLangBarEventSink, self), dwThreadId, uMsg, wParam, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarEventSink_ShowFloating(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).ShowFloating(@ptrCast(*const ITfLangBarEventSink, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarEventSink_GetItemFloatingRect(self: *const T, dwThreadId: u32, rguid: ?*const Guid, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarEventSink.VTable, self.vtable).GetItemFloatingRect(@ptrCast(*const ITfLangBarEventSink, self), dwThreadId, rguid, prc); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemSink_Value = Guid.initString("57dbe1a0-de25-11d2-afdd-00105a2799b5"); pub const IID_ITfLangBarItemSink = &IID_ITfLangBarItemSink_Value; pub const ITfLangBarItemSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUpdate: fn( self: *const ITfLangBarItemSink, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemSink_OnUpdate(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemSink.VTable, self.vtable).OnUpdate(@ptrCast(*const ITfLangBarItemSink, self), dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfLangBarItems_Value = Guid.initString("583f34d0-de25-11d2-afdd-00105a2799b5"); pub const IID_IEnumTfLangBarItems = &IID_IEnumTfLangBarItems_Value; pub const IEnumTfLangBarItems = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfLangBarItems, ppEnum: ?*?*IEnumTfLangBarItems, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfLangBarItems, ulCount: u32, ppItem: [*]?*ITfLangBarItem, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfLangBarItems, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfLangBarItems, ulCount: 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 IEnumTfLangBarItems_Clone(self: *const T, ppEnum: ?*?*IEnumTfLangBarItems) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLangBarItems.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfLangBarItems, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLangBarItems_Next(self: *const T, ulCount: u32, ppItem: [*]?*ITfLangBarItem, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLangBarItems.VTable, self.vtable).Next(@ptrCast(*const IEnumTfLangBarItems, self), ulCount, ppItem, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLangBarItems_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLangBarItems.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfLangBarItems, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLangBarItems_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLangBarItems.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfLangBarItems, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_LANGBARITEMINFO = extern struct { clsidService: Guid, guidItem: Guid, dwStyle: u32, ulSort: u32, szDescription: [32]u16, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemMgr_Value = Guid.initString("ba468c55-9956-4fb1-a59d-52a7dd7cc6aa"); pub const IID_ITfLangBarItemMgr = &IID_ITfLangBarItemMgr_Value; pub const ITfLangBarItemMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumItems: fn( self: *const ITfLangBarItemMgr, ppEnum: ?*?*IEnumTfLangBarItems, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItem: fn( self: *const ITfLangBarItemMgr, rguid: ?*const Guid, ppItem: ?*?*ITfLangBarItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddItem: fn( self: *const ITfLangBarItemMgr, punk: ?*ITfLangBarItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveItem: fn( self: *const ITfLangBarItemMgr, punk: ?*ITfLangBarItem, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AdviseItemSink: fn( self: *const ITfLangBarItemMgr, punk: ?*ITfLangBarItemSink, pdwCookie: ?*u32, rguidItem: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseItemSink: fn( self: *const ITfLangBarItemMgr, dwCookie: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItemFloatingRect: fn( self: *const ITfLangBarItemMgr, dwThreadId: u32, rguid: ?*const Guid, prc: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItemsStatus: fn( self: *const ITfLangBarItemMgr, ulCount: u32, prgguid: [*]const Guid, pdwStatus: [*]u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItemNum: fn( self: *const ITfLangBarItemMgr, pulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItems: fn( self: *const ITfLangBarItemMgr, ulCount: u32, ppItem: [*]?*ITfLangBarItem, pInfo: [*]TF_LANGBARITEMINFO, pdwStatus: [*]u32, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AdviseItemsSink: fn( self: *const ITfLangBarItemMgr, ulCount: u32, ppunk: [*]?*ITfLangBarItemSink, pguidItem: [*]const Guid, pdwCookie: [*]u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseItemsSink: fn( self: *const ITfLangBarItemMgr, ulCount: u32, pdwCookie: [*]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 ITfLangBarItemMgr_EnumItems(self: *const T, ppEnum: ?*?*IEnumTfLangBarItems) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).EnumItems(@ptrCast(*const ITfLangBarItemMgr, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_GetItem(self: *const T, rguid: ?*const Guid, ppItem: ?*?*ITfLangBarItem) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).GetItem(@ptrCast(*const ITfLangBarItemMgr, self), rguid, ppItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_AddItem(self: *const T, punk: ?*ITfLangBarItem) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).AddItem(@ptrCast(*const ITfLangBarItemMgr, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_RemoveItem(self: *const T, punk: ?*ITfLangBarItem) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).RemoveItem(@ptrCast(*const ITfLangBarItemMgr, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_AdviseItemSink(self: *const T, punk: ?*ITfLangBarItemSink, pdwCookie: ?*u32, rguidItem: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).AdviseItemSink(@ptrCast(*const ITfLangBarItemMgr, self), punk, pdwCookie, rguidItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_UnadviseItemSink(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).UnadviseItemSink(@ptrCast(*const ITfLangBarItemMgr, self), dwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_GetItemFloatingRect(self: *const T, dwThreadId: u32, rguid: ?*const Guid, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).GetItemFloatingRect(@ptrCast(*const ITfLangBarItemMgr, self), dwThreadId, rguid, prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_GetItemsStatus(self: *const T, ulCount: u32, prgguid: [*]const Guid, pdwStatus: [*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).GetItemsStatus(@ptrCast(*const ITfLangBarItemMgr, self), ulCount, prgguid, pdwStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_GetItemNum(self: *const T, pulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).GetItemNum(@ptrCast(*const ITfLangBarItemMgr, self), pulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_GetItems(self: *const T, ulCount: u32, ppItem: [*]?*ITfLangBarItem, pInfo: [*]TF_LANGBARITEMINFO, pdwStatus: [*]u32, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).GetItems(@ptrCast(*const ITfLangBarItemMgr, self), ulCount, ppItem, pInfo, pdwStatus, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_AdviseItemsSink(self: *const T, ulCount: u32, ppunk: [*]?*ITfLangBarItemSink, pguidItem: [*]const Guid, pdwCookie: [*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).AdviseItemsSink(@ptrCast(*const ITfLangBarItemMgr, self), ulCount, ppunk, pguidItem, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemMgr_UnadviseItemsSink(self: *const T, ulCount: u32, pdwCookie: [*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemMgr.VTable, self.vtable).UnadviseItemsSink(@ptrCast(*const ITfLangBarItemMgr, self), ulCount, pdwCookie); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItem_Value = Guid.initString("73540d69-edeb-4ee9-96c9-23aa30b25916"); pub const IID_ITfLangBarItem = &IID_ITfLangBarItem_Value; pub const ITfLangBarItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInfo: fn( self: *const ITfLangBarItem, pInfo: ?*TF_LANGBARITEMINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITfLangBarItem, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Show: fn( self: *const ITfLangBarItem, fShow: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTooltipString: fn( self: *const ITfLangBarItem, pbstrToolTip: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItem_GetInfo(self: *const T, pInfo: ?*TF_LANGBARITEMINFO) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItem.VTable, self.vtable).GetInfo(@ptrCast(*const ITfLangBarItem, self), pInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItem_GetStatus(self: *const T, pdwStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItem.VTable, self.vtable).GetStatus(@ptrCast(*const ITfLangBarItem, self), pdwStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItem_Show(self: *const T, fShow: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItem.VTable, self.vtable).Show(@ptrCast(*const ITfLangBarItem, self), fShow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItem_GetTooltipString(self: *const T, pbstrToolTip: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItem.VTable, self.vtable).GetTooltipString(@ptrCast(*const ITfLangBarItem, self), pbstrToolTip); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSystemLangBarItemSink_Value = Guid.initString("1449d9ab-13cf-4687-aa3e-8d8b18574396"); pub const IID_ITfSystemLangBarItemSink = &IID_ITfSystemLangBarItemSink_Value; pub const ITfSystemLangBarItemSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InitMenu: fn( self: *const ITfSystemLangBarItemSink, pMenu: ?*ITfMenu, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnMenuSelect: fn( self: *const ITfSystemLangBarItemSink, wID: 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 ITfSystemLangBarItemSink_InitMenu(self: *const T, pMenu: ?*ITfMenu) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItemSink.VTable, self.vtable).InitMenu(@ptrCast(*const ITfSystemLangBarItemSink, self), pMenu); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSystemLangBarItemSink_OnMenuSelect(self: *const T, wID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItemSink.VTable, self.vtable).OnMenuSelect(@ptrCast(*const ITfSystemLangBarItemSink, self), wID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSystemLangBarItem_Value = Guid.initString("1e13e9ec-6b33-4d4a-b5eb-8a92f029f356"); pub const IID_ITfSystemLangBarItem = &IID_ITfSystemLangBarItem_Value; pub const ITfSystemLangBarItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetIcon: fn( self: *const ITfSystemLangBarItem, hIcon: ?HICON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTooltipString: fn( self: *const ITfSystemLangBarItem, pchToolTip: [*:0]u16, cch: 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 ITfSystemLangBarItem_SetIcon(self: *const T, hIcon: ?HICON) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItem.VTable, self.vtable).SetIcon(@ptrCast(*const ITfSystemLangBarItem, self), hIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSystemLangBarItem_SetTooltipString(self: *const T, pchToolTip: [*:0]u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItem.VTable, self.vtable).SetTooltipString(@ptrCast(*const ITfSystemLangBarItem, self), pchToolTip, cch); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSystemLangBarItemText_Value = Guid.initString("5c4ce0e5-ba49-4b52-ac6b-3b397b4f701f"); pub const IID_ITfSystemLangBarItemText = &IID_ITfSystemLangBarItemText_Value; pub const ITfSystemLangBarItemText = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetItemText: fn( self: *const ITfSystemLangBarItemText, pch: [*:0]const u16, cch: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItemText: fn( self: *const ITfSystemLangBarItemText, pbstrText: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSystemLangBarItemText_SetItemText(self: *const T, pch: [*:0]const u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItemText.VTable, self.vtable).SetItemText(@ptrCast(*const ITfSystemLangBarItemText, self), pch, cch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSystemLangBarItemText_GetItemText(self: *const T, pbstrText: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemLangBarItemText.VTable, self.vtable).GetItemText(@ptrCast(*const ITfSystemLangBarItemText, self), pbstrText); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSystemDeviceTypeLangBarItem_Value = Guid.initString("45672eb9-9059-46a2-838d-4530355f6a77"); pub const IID_ITfSystemDeviceTypeLangBarItem = &IID_ITfSystemDeviceTypeLangBarItem_Value; pub const ITfSystemDeviceTypeLangBarItem = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetIconMode: fn( self: *const ITfSystemDeviceTypeLangBarItem, dwFlags: LANG_BAR_ITEM_ICON_MODE_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIconMode: fn( self: *const ITfSystemDeviceTypeLangBarItem, pdwFlags: ?*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 ITfSystemDeviceTypeLangBarItem_SetIconMode(self: *const T, dwFlags: LANG_BAR_ITEM_ICON_MODE_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemDeviceTypeLangBarItem.VTable, self.vtable).SetIconMode(@ptrCast(*const ITfSystemDeviceTypeLangBarItem, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSystemDeviceTypeLangBarItem_GetIconMode(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSystemDeviceTypeLangBarItem.VTable, self.vtable).GetIconMode(@ptrCast(*const ITfSystemDeviceTypeLangBarItem, self), pdwFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfLBIClick = enum(i32) { RIGHT = 1, LEFT = 2, }; pub const TF_LBI_CLK_RIGHT = TfLBIClick.RIGHT; pub const TF_LBI_CLK_LEFT = TfLBIClick.LEFT; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemButton_Value = Guid.initString("28c7f1d0-de25-11d2-afdd-00105a2799b5"); pub const IID_ITfLangBarItemButton = &IID_ITfLangBarItemButton_Value; pub const ITfLangBarItemButton = extern struct { pub const VTable = extern struct { base: ITfLangBarItem.VTable, OnClick: fn( self: *const ITfLangBarItemButton, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitMenu: fn( self: *const ITfLangBarItemButton, pMenu: ?*ITfMenu, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnMenuSelect: fn( self: *const ITfLangBarItemButton, wID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIcon: fn( self: *const ITfLangBarItemButton, phIcon: ?*?HICON, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetText: fn( self: *const ITfLangBarItemButton, pbstrText: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfLangBarItem.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemButton_OnClick(self: *const T, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemButton.VTable, self.vtable).OnClick(@ptrCast(*const ITfLangBarItemButton, self), click, pt, prcArea); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemButton_InitMenu(self: *const T, pMenu: ?*ITfMenu) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemButton.VTable, self.vtable).InitMenu(@ptrCast(*const ITfLangBarItemButton, self), pMenu); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemButton_OnMenuSelect(self: *const T, wID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemButton.VTable, self.vtable).OnMenuSelect(@ptrCast(*const ITfLangBarItemButton, self), wID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemButton_GetIcon(self: *const T, phIcon: ?*?HICON) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemButton.VTable, self.vtable).GetIcon(@ptrCast(*const ITfLangBarItemButton, self), phIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemButton_GetText(self: *const T, pbstrText: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemButton.VTable, self.vtable).GetText(@ptrCast(*const ITfLangBarItemButton, self), pbstrText); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemBitmapButton_Value = Guid.initString("a26a0525-3fae-4fa0-89ee-88a964f9f1b5"); pub const IID_ITfLangBarItemBitmapButton = &IID_ITfLangBarItemBitmapButton_Value; pub const ITfLangBarItemBitmapButton = extern struct { pub const VTable = extern struct { base: ITfLangBarItem.VTable, OnClick: fn( self: *const ITfLangBarItemBitmapButton, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitMenu: fn( self: *const ITfLangBarItemBitmapButton, pMenu: ?*ITfMenu, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnMenuSelect: fn( self: *const ITfLangBarItemBitmapButton, wID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreferredSize: fn( self: *const ITfLangBarItemBitmapButton, pszDefault: ?*const SIZE, psz: ?*SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DrawBitmap: fn( self: *const ITfLangBarItemBitmapButton, bmWidth: i32, bmHeight: i32, dwFlags: u32, phbmp: ?*?HBITMAP, phbmpMask: ?*?HBITMAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetText: fn( self: *const ITfLangBarItemBitmapButton, pbstrText: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfLangBarItem.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_OnClick(self: *const T, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).OnClick(@ptrCast(*const ITfLangBarItemBitmapButton, self), click, pt, prcArea); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_InitMenu(self: *const T, pMenu: ?*ITfMenu) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).InitMenu(@ptrCast(*const ITfLangBarItemBitmapButton, self), pMenu); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_OnMenuSelect(self: *const T, wID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).OnMenuSelect(@ptrCast(*const ITfLangBarItemBitmapButton, self), wID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_GetPreferredSize(self: *const T, pszDefault: ?*const SIZE, psz: ?*SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).GetPreferredSize(@ptrCast(*const ITfLangBarItemBitmapButton, self), pszDefault, psz); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_DrawBitmap(self: *const T, bmWidth: i32, bmHeight: i32, dwFlags: u32, phbmp: ?*?HBITMAP, phbmpMask: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).DrawBitmap(@ptrCast(*const ITfLangBarItemBitmapButton, self), bmWidth, bmHeight, dwFlags, phbmp, phbmpMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmapButton_GetText(self: *const T, pbstrText: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmapButton.VTable, self.vtable).GetText(@ptrCast(*const ITfLangBarItemBitmapButton, self), pbstrText); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemBitmap_Value = Guid.initString("73830352-d722-4179-ada5-f045c98df355"); pub const IID_ITfLangBarItemBitmap = &IID_ITfLangBarItemBitmap_Value; pub const ITfLangBarItemBitmap = extern struct { pub const VTable = extern struct { base: ITfLangBarItem.VTable, OnClick: fn( self: *const ITfLangBarItemBitmap, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreferredSize: fn( self: *const ITfLangBarItemBitmap, pszDefault: ?*const SIZE, psz: ?*SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DrawBitmap: fn( self: *const ITfLangBarItemBitmap, bmWidth: i32, bmHeight: i32, dwFlags: u32, phbmp: ?*?HBITMAP, phbmpMask: ?*?HBITMAP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfLangBarItem.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmap_OnClick(self: *const T, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmap.VTable, self.vtable).OnClick(@ptrCast(*const ITfLangBarItemBitmap, self), click, pt, prcArea); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmap_GetPreferredSize(self: *const T, pszDefault: ?*const SIZE, psz: ?*SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmap.VTable, self.vtable).GetPreferredSize(@ptrCast(*const ITfLangBarItemBitmap, self), pszDefault, psz); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBitmap_DrawBitmap(self: *const T, bmWidth: i32, bmHeight: i32, dwFlags: u32, phbmp: ?*?HBITMAP, phbmpMask: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBitmap.VTable, self.vtable).DrawBitmap(@ptrCast(*const ITfLangBarItemBitmap, self), bmWidth, bmHeight, dwFlags, phbmp, phbmpMask); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfLBBalloonStyle = enum(i32) { RECO = 0, SHOW = 1, MISS = 2, }; pub const TF_LB_BALLOON_RECO = TfLBBalloonStyle.RECO; pub const TF_LB_BALLOON_SHOW = TfLBBalloonStyle.SHOW; pub const TF_LB_BALLOON_MISS = TfLBBalloonStyle.MISS; pub const TF_LBBALLOONINFO = extern struct { style: TfLBBalloonStyle, bstrText: ?BSTR, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLangBarItemBalloon_Value = Guid.initString("01c2d285-d3c7-4b7b-b5b5-d97411d0c283"); pub const IID_ITfLangBarItemBalloon = &IID_ITfLangBarItemBalloon_Value; pub const ITfLangBarItemBalloon = extern struct { pub const VTable = extern struct { base: ITfLangBarItem.VTable, OnClick: fn( self: *const ITfLangBarItemBalloon, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreferredSize: fn( self: *const ITfLangBarItemBalloon, pszDefault: ?*const SIZE, psz: ?*SIZE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBalloonInfo: fn( self: *const ITfLangBarItemBalloon, pInfo: ?*TF_LBBALLOONINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfLangBarItem.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBalloon_OnClick(self: *const T, click: TfLBIClick, pt: POINT, prcArea: ?*const RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBalloon.VTable, self.vtable).OnClick(@ptrCast(*const ITfLangBarItemBalloon, self), click, pt, prcArea); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBalloon_GetPreferredSize(self: *const T, pszDefault: ?*const SIZE, psz: ?*SIZE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBalloon.VTable, self.vtable).GetPreferredSize(@ptrCast(*const ITfLangBarItemBalloon, self), pszDefault, psz); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLangBarItemBalloon_GetBalloonInfo(self: *const T, pInfo: ?*TF_LBBALLOONINFO) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLangBarItemBalloon.VTable, self.vtable).GetBalloonInfo(@ptrCast(*const ITfLangBarItemBalloon, self), pInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMenu_Value = Guid.initString("6f8a98e4-aaa0-4f15-8c5b-07e0df0a3dd8"); pub const IID_ITfMenu = &IID_ITfMenu_Value; pub const ITfMenu = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddMenuItem: fn( self: *const ITfMenu, uId: u32, dwFlags: u32, hbmp: ?HBITMAP, hbmpMask: ?HBITMAP, pch: [*:0]const u16, cch: u32, ppMenu: ?*?*ITfMenu, ) 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 ITfMenu_AddMenuItem(self: *const T, uId: u32, dwFlags: u32, hbmp: ?HBITMAP, hbmpMask: ?HBITMAP, pch: [*:0]const u16, cch: u32, ppMenu: ?*?*ITfMenu) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMenu.VTable, self.vtable).AddMenuItem(@ptrCast(*const ITfMenu, self), uId, dwFlags, hbmp, hbmpMask, pch, cch, ppMenu); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_PERSISTENT_PROPERTY_HEADER_ACP = extern struct { guidType: Guid, ichStart: i32, cch: i32, cb: u32, dwPrivate: u32, clsidTIP: Guid, }; pub const TF_LANGUAGEPROFILE = extern struct { clsid: Guid, langid: u16, catid: Guid, fActive: BOOL, guidProfile: Guid, }; pub const TfAnchor = enum(i32) { START = 0, END = 1, }; pub const TF_ANCHOR_START = TfAnchor.START; pub const TF_ANCHOR_END = TfAnchor.END; // TODO: this type is limited to platform 'windows5.0' const IID_ITfThreadMgr_Value = Guid.initString("aa80e801-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfThreadMgr = &IID_ITfThreadMgr_Value; pub const ITfThreadMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Activate: fn( self: *const ITfThreadMgr, ptid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Deactivate: fn( self: *const ITfThreadMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDocumentMgr: fn( self: *const ITfThreadMgr, ppdim: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDocumentMgrs: fn( self: *const ITfThreadMgr, ppEnum: ?*?*IEnumTfDocumentMgrs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFocus: fn( self: *const ITfThreadMgr, ppdimFocus: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFocus: fn( self: *const ITfThreadMgr, pdimFocus: ?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AssociateFocus: fn( self: *const ITfThreadMgr, hwnd: ?HWND, pdimNew: ?*ITfDocumentMgr, ppdimPrev: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsThreadFocus: fn( self: *const ITfThreadMgr, pfThreadFocus: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFunctionProvider: fn( self: *const ITfThreadMgr, clsid: ?*const Guid, ppFuncProv: ?*?*ITfFunctionProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumFunctionProviders: fn( self: *const ITfThreadMgr, ppEnum: ?*?*IEnumTfFunctionProviders, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlobalCompartment: fn( self: *const ITfThreadMgr, ppCompMgr: ?*?*ITfCompartmentMgr, ) 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 ITfThreadMgr_Activate(self: *const T, ptid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).Activate(@ptrCast(*const ITfThreadMgr, self), ptid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_Deactivate(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).Deactivate(@ptrCast(*const ITfThreadMgr, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_CreateDocumentMgr(self: *const T, ppdim: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).CreateDocumentMgr(@ptrCast(*const ITfThreadMgr, self), ppdim); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_EnumDocumentMgrs(self: *const T, ppEnum: ?*?*IEnumTfDocumentMgrs) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).EnumDocumentMgrs(@ptrCast(*const ITfThreadMgr, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_GetFocus(self: *const T, ppdimFocus: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).GetFocus(@ptrCast(*const ITfThreadMgr, self), ppdimFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_SetFocus(self: *const T, pdimFocus: ?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).SetFocus(@ptrCast(*const ITfThreadMgr, self), pdimFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_AssociateFocus(self: *const T, hwnd: ?HWND, pdimNew: ?*ITfDocumentMgr, ppdimPrev: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).AssociateFocus(@ptrCast(*const ITfThreadMgr, self), hwnd, pdimNew, ppdimPrev); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_IsThreadFocus(self: *const T, pfThreadFocus: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).IsThreadFocus(@ptrCast(*const ITfThreadMgr, self), pfThreadFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_GetFunctionProvider(self: *const T, clsid: ?*const Guid, ppFuncProv: ?*?*ITfFunctionProvider) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).GetFunctionProvider(@ptrCast(*const ITfThreadMgr, self), clsid, ppFuncProv); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_EnumFunctionProviders(self: *const T, ppEnum: ?*?*IEnumTfFunctionProviders) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).EnumFunctionProviders(@ptrCast(*const ITfThreadMgr, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr_GetGlobalCompartment(self: *const T, ppCompMgr: ?*?*ITfCompartmentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr.VTable, self.vtable).GetGlobalCompartment(@ptrCast(*const ITfThreadMgr, self), ppCompMgr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfThreadMgrEx_Value = Guid.initString("3e90ade3-7594-4cb0-bb58-69628f5f458c"); pub const IID_ITfThreadMgrEx = &IID_ITfThreadMgrEx_Value; pub const ITfThreadMgrEx = extern struct { pub const VTable = extern struct { base: ITfThreadMgr.VTable, ActivateEx: fn( self: *const ITfThreadMgrEx, ptid: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveFlags: fn( self: *const ITfThreadMgrEx, lpdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfThreadMgr.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEx_ActivateEx(self: *const T, ptid: ?*u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEx.VTable, self.vtable).ActivateEx(@ptrCast(*const ITfThreadMgrEx, self), ptid, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEx_GetActiveFlags(self: *const T, lpdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEx.VTable, self.vtable).GetActiveFlags(@ptrCast(*const ITfThreadMgrEx, self), lpdwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_ITfThreadMgr2_Value = Guid.initString("0ab198ef-6477-4ee8-8812-6780edb82d5e"); pub const IID_ITfThreadMgr2 = &IID_ITfThreadMgr2_Value; pub const ITfThreadMgr2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Activate: fn( self: *const ITfThreadMgr2, ptid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Deactivate: fn( self: *const ITfThreadMgr2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDocumentMgr: fn( self: *const ITfThreadMgr2, ppdim: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDocumentMgrs: fn( self: *const ITfThreadMgr2, ppEnum: ?*?*IEnumTfDocumentMgrs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFocus: fn( self: *const ITfThreadMgr2, ppdimFocus: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFocus: fn( self: *const ITfThreadMgr2, pdimFocus: ?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsThreadFocus: fn( self: *const ITfThreadMgr2, pfThreadFocus: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFunctionProvider: fn( self: *const ITfThreadMgr2, clsid: ?*const Guid, ppFuncProv: ?*?*ITfFunctionProvider, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumFunctionProviders: fn( self: *const ITfThreadMgr2, ppEnum: ?*?*IEnumTfFunctionProviders, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlobalCompartment: fn( self: *const ITfThreadMgr2, ppCompMgr: ?*?*ITfCompartmentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ActivateEx: fn( self: *const ITfThreadMgr2, ptid: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveFlags: fn( self: *const ITfThreadMgr2, lpdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SuspendKeystrokeHandling: fn( self: *const ITfThreadMgr2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResumeKeystrokeHandling: fn( self: *const ITfThreadMgr2, ) 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 ITfThreadMgr2_Activate(self: *const T, ptid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).Activate(@ptrCast(*const ITfThreadMgr2, self), ptid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_Deactivate(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).Deactivate(@ptrCast(*const ITfThreadMgr2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_CreateDocumentMgr(self: *const T, ppdim: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).CreateDocumentMgr(@ptrCast(*const ITfThreadMgr2, self), ppdim); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_EnumDocumentMgrs(self: *const T, ppEnum: ?*?*IEnumTfDocumentMgrs) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).EnumDocumentMgrs(@ptrCast(*const ITfThreadMgr2, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_GetFocus(self: *const T, ppdimFocus: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).GetFocus(@ptrCast(*const ITfThreadMgr2, self), ppdimFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_SetFocus(self: *const T, pdimFocus: ?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).SetFocus(@ptrCast(*const ITfThreadMgr2, self), pdimFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_IsThreadFocus(self: *const T, pfThreadFocus: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).IsThreadFocus(@ptrCast(*const ITfThreadMgr2, self), pfThreadFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_GetFunctionProvider(self: *const T, clsid: ?*const Guid, ppFuncProv: ?*?*ITfFunctionProvider) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).GetFunctionProvider(@ptrCast(*const ITfThreadMgr2, self), clsid, ppFuncProv); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_EnumFunctionProviders(self: *const T, ppEnum: ?*?*IEnumTfFunctionProviders) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).EnumFunctionProviders(@ptrCast(*const ITfThreadMgr2, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_GetGlobalCompartment(self: *const T, ppCompMgr: ?*?*ITfCompartmentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).GetGlobalCompartment(@ptrCast(*const ITfThreadMgr2, self), ppCompMgr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_ActivateEx(self: *const T, ptid: ?*u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).ActivateEx(@ptrCast(*const ITfThreadMgr2, self), ptid, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_GetActiveFlags(self: *const T, lpdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).GetActiveFlags(@ptrCast(*const ITfThreadMgr2, self), lpdwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_SuspendKeystrokeHandling(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).SuspendKeystrokeHandling(@ptrCast(*const ITfThreadMgr2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgr2_ResumeKeystrokeHandling(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgr2.VTable, self.vtable).ResumeKeystrokeHandling(@ptrCast(*const ITfThreadMgr2, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfThreadMgrEventSink_Value = Guid.initString("aa80e80e-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfThreadMgrEventSink = &IID_ITfThreadMgrEventSink_Value; pub const ITfThreadMgrEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnInitDocumentMgr: fn( self: *const ITfThreadMgrEventSink, pdim: ?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnUninitDocumentMgr: fn( self: *const ITfThreadMgrEventSink, pdim: ?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnSetFocus: fn( self: *const ITfThreadMgrEventSink, pdimFocus: ?*ITfDocumentMgr, pdimPrevFocus: ?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnPushContext: fn( self: *const ITfThreadMgrEventSink, pic: ?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnPopContext: fn( self: *const ITfThreadMgrEventSink, pic: ?*ITfContext, ) 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 ITfThreadMgrEventSink_OnInitDocumentMgr(self: *const T, pdim: ?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEventSink.VTable, self.vtable).OnInitDocumentMgr(@ptrCast(*const ITfThreadMgrEventSink, self), pdim); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEventSink_OnUninitDocumentMgr(self: *const T, pdim: ?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEventSink.VTable, self.vtable).OnUninitDocumentMgr(@ptrCast(*const ITfThreadMgrEventSink, self), pdim); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEventSink_OnSetFocus(self: *const T, pdimFocus: ?*ITfDocumentMgr, pdimPrevFocus: ?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEventSink.VTable, self.vtable).OnSetFocus(@ptrCast(*const ITfThreadMgrEventSink, self), pdimFocus, pdimPrevFocus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEventSink_OnPushContext(self: *const T, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEventSink.VTable, self.vtable).OnPushContext(@ptrCast(*const ITfThreadMgrEventSink, self), pic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadMgrEventSink_OnPopContext(self: *const T, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadMgrEventSink.VTable, self.vtable).OnPopContext(@ptrCast(*const ITfThreadMgrEventSink, self), pic); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfConfigureSystemKeystrokeFeed_Value = Guid.initString("0d2c969a-bc9c-437c-84ee-951c49b1a764"); pub const IID_ITfConfigureSystemKeystrokeFeed = &IID_ITfConfigureSystemKeystrokeFeed_Value; pub const ITfConfigureSystemKeystrokeFeed = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DisableSystemKeystrokeFeed: fn( self: *const ITfConfigureSystemKeystrokeFeed, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableSystemKeystrokeFeed: fn( self: *const ITfConfigureSystemKeystrokeFeed, ) 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 ITfConfigureSystemKeystrokeFeed_DisableSystemKeystrokeFeed(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfConfigureSystemKeystrokeFeed.VTable, self.vtable).DisableSystemKeystrokeFeed(@ptrCast(*const ITfConfigureSystemKeystrokeFeed, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfConfigureSystemKeystrokeFeed_EnableSystemKeystrokeFeed(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfConfigureSystemKeystrokeFeed.VTable, self.vtable).EnableSystemKeystrokeFeed(@ptrCast(*const ITfConfigureSystemKeystrokeFeed, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfDocumentMgrs_Value = Guid.initString("aa80e808-2021-11d2-93e0-0060b067b86e"); pub const IID_IEnumTfDocumentMgrs = &IID_IEnumTfDocumentMgrs_Value; pub const IEnumTfDocumentMgrs = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfDocumentMgrs, ppEnum: ?*?*IEnumTfDocumentMgrs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfDocumentMgrs, ulCount: u32, rgDocumentMgr: [*]?*ITfDocumentMgr, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfDocumentMgrs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfDocumentMgrs, ulCount: 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 IEnumTfDocumentMgrs_Clone(self: *const T, ppEnum: ?*?*IEnumTfDocumentMgrs) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDocumentMgrs.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfDocumentMgrs, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDocumentMgrs_Next(self: *const T, ulCount: u32, rgDocumentMgr: [*]?*ITfDocumentMgr, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDocumentMgrs.VTable, self.vtable).Next(@ptrCast(*const IEnumTfDocumentMgrs, self), ulCount, rgDocumentMgr, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDocumentMgrs_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDocumentMgrs.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfDocumentMgrs, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDocumentMgrs_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDocumentMgrs.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfDocumentMgrs, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfDocumentMgr_Value = Guid.initString("aa80e7f4-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfDocumentMgr = &IID_ITfDocumentMgr_Value; pub const ITfDocumentMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateContext: fn( self: *const ITfDocumentMgr, tidOwner: u32, dwFlags: u32, punk: ?*IUnknown, ppic: ?*?*ITfContext, pecTextStore: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Push: fn( self: *const ITfDocumentMgr, pic: ?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pop: fn( self: *const ITfDocumentMgr, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTop: fn( self: *const ITfDocumentMgr, ppic: ?*?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBase: fn( self: *const ITfDocumentMgr, ppic: ?*?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumContexts: fn( self: *const ITfDocumentMgr, ppEnum: ?*?*IEnumTfContexts, ) 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 ITfDocumentMgr_CreateContext(self: *const T, tidOwner: u32, dwFlags: u32, punk: ?*IUnknown, ppic: ?*?*ITfContext, pecTextStore: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).CreateContext(@ptrCast(*const ITfDocumentMgr, self), tidOwner, dwFlags, punk, ppic, pecTextStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDocumentMgr_Push(self: *const T, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).Push(@ptrCast(*const ITfDocumentMgr, self), pic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDocumentMgr_Pop(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).Pop(@ptrCast(*const ITfDocumentMgr, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDocumentMgr_GetTop(self: *const T, ppic: ?*?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).GetTop(@ptrCast(*const ITfDocumentMgr, self), ppic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDocumentMgr_GetBase(self: *const T, ppic: ?*?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).GetBase(@ptrCast(*const ITfDocumentMgr, self), ppic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDocumentMgr_EnumContexts(self: *const T, ppEnum: ?*?*IEnumTfContexts) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDocumentMgr.VTable, self.vtable).EnumContexts(@ptrCast(*const ITfDocumentMgr, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfContexts_Value = Guid.initString("8f1a7ea6-1654-4502-a86e-b2902344d507"); pub const IID_IEnumTfContexts = &IID_IEnumTfContexts_Value; pub const IEnumTfContexts = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfContexts, ppEnum: ?*?*IEnumTfContexts, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfContexts, ulCount: u32, rgContext: [*]?*ITfContext, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfContexts, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfContexts, ulCount: 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 IEnumTfContexts_Clone(self: *const T, ppEnum: ?*?*IEnumTfContexts) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContexts.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfContexts, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContexts_Next(self: *const T, ulCount: u32, rgContext: [*]?*ITfContext, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContexts.VTable, self.vtable).Next(@ptrCast(*const IEnumTfContexts, self), ulCount, rgContext, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContexts_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContexts.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfContexts, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContexts_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContexts.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfContexts, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCompositionView_Value = Guid.initString("d7540241-f9a1-4364-befc-dbcd2c4395b7"); pub const IID_ITfCompositionView = &IID_ITfCompositionView_Value; pub const ITfCompositionView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOwnerClsid: fn( self: *const ITfCompositionView, pclsid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRange: fn( self: *const ITfCompositionView, ppRange: ?*?*ITfRange, ) 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 ITfCompositionView_GetOwnerClsid(self: *const T, pclsid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompositionView.VTable, self.vtable).GetOwnerClsid(@ptrCast(*const ITfCompositionView, self), pclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompositionView_GetRange(self: *const T, ppRange: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompositionView.VTable, self.vtable).GetRange(@ptrCast(*const ITfCompositionView, self), ppRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumITfCompositionView_Value = Guid.initString("5efd22ba-7838-46cb-88e2-cadb14124f8f"); pub const IID_IEnumITfCompositionView = &IID_IEnumITfCompositionView_Value; pub const IEnumITfCompositionView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumITfCompositionView, ppEnum: ?*?*IEnumITfCompositionView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumITfCompositionView, ulCount: u32, rgCompositionView: [*]?*ITfCompositionView, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumITfCompositionView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumITfCompositionView, ulCount: 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 IEnumITfCompositionView_Clone(self: *const T, ppEnum: ?*?*IEnumITfCompositionView) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumITfCompositionView.VTable, self.vtable).Clone(@ptrCast(*const IEnumITfCompositionView, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumITfCompositionView_Next(self: *const T, ulCount: u32, rgCompositionView: [*]?*ITfCompositionView, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumITfCompositionView.VTable, self.vtable).Next(@ptrCast(*const IEnumITfCompositionView, self), ulCount, rgCompositionView, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumITfCompositionView_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumITfCompositionView.VTable, self.vtable).Reset(@ptrCast(*const IEnumITfCompositionView, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumITfCompositionView_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumITfCompositionView.VTable, self.vtable).Skip(@ptrCast(*const IEnumITfCompositionView, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfComposition_Value = Guid.initString("20168d64-5a8f-4a5a-b7bd-cfa29f4d0fd9"); pub const IID_ITfComposition = &IID_ITfComposition_Value; pub const ITfComposition = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetRange: fn( self: *const ITfComposition, ppRange: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftStart: fn( self: *const ITfComposition, ecWrite: u32, pNewStart: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftEnd: fn( self: *const ITfComposition, ecWrite: u32, pNewEnd: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndComposition: fn( self: *const ITfComposition, ecWrite: 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 ITfComposition_GetRange(self: *const T, ppRange: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfComposition.VTable, self.vtable).GetRange(@ptrCast(*const ITfComposition, self), ppRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfComposition_ShiftStart(self: *const T, ecWrite: u32, pNewStart: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfComposition.VTable, self.vtable).ShiftStart(@ptrCast(*const ITfComposition, self), ecWrite, pNewStart); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfComposition_ShiftEnd(self: *const T, ecWrite: u32, pNewEnd: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfComposition.VTable, self.vtable).ShiftEnd(@ptrCast(*const ITfComposition, self), ecWrite, pNewEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfComposition_EndComposition(self: *const T, ecWrite: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfComposition.VTable, self.vtable).EndComposition(@ptrCast(*const ITfComposition, self), ecWrite); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCompositionSink_Value = Guid.initString("a781718c-579a-4b15-a280-32b8577acc5e"); pub const IID_ITfCompositionSink = &IID_ITfCompositionSink_Value; pub const ITfCompositionSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnCompositionTerminated: fn( self: *const ITfCompositionSink, ecWrite: u32, pComposition: ?*ITfComposition, ) 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 ITfCompositionSink_OnCompositionTerminated(self: *const T, ecWrite: u32, pComposition: ?*ITfComposition) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompositionSink.VTable, self.vtable).OnCompositionTerminated(@ptrCast(*const ITfCompositionSink, self), ecWrite, pComposition); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextComposition_Value = Guid.initString("d40c8aae-ac92-4fc7-9a11-0ee0e23aa39b"); pub const IID_ITfContextComposition = &IID_ITfContextComposition_Value; pub const ITfContextComposition = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartComposition: fn( self: *const ITfContextComposition, ecWrite: u32, pCompositionRange: ?*ITfRange, pSink: ?*ITfCompositionSink, ppComposition: ?*?*ITfComposition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumCompositions: fn( self: *const ITfContextComposition, ppEnum: ?*?*IEnumITfCompositionView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindComposition: fn( self: *const ITfContextComposition, ecRead: u32, pTestRange: ?*ITfRange, ppEnum: ?*?*IEnumITfCompositionView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TakeOwnership: fn( self: *const ITfContextComposition, ecWrite: u32, pComposition: ?*ITfCompositionView, pSink: ?*ITfCompositionSink, ppComposition: ?*?*ITfComposition, ) 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 ITfContextComposition_StartComposition(self: *const T, ecWrite: u32, pCompositionRange: ?*ITfRange, pSink: ?*ITfCompositionSink, ppComposition: ?*?*ITfComposition) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextComposition.VTable, self.vtable).StartComposition(@ptrCast(*const ITfContextComposition, self), ecWrite, pCompositionRange, pSink, ppComposition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextComposition_EnumCompositions(self: *const T, ppEnum: ?*?*IEnumITfCompositionView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextComposition.VTable, self.vtable).EnumCompositions(@ptrCast(*const ITfContextComposition, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextComposition_FindComposition(self: *const T, ecRead: u32, pTestRange: ?*ITfRange, ppEnum: ?*?*IEnumITfCompositionView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextComposition.VTable, self.vtable).FindComposition(@ptrCast(*const ITfContextComposition, self), ecRead, pTestRange, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextComposition_TakeOwnership(self: *const T, ecWrite: u32, pComposition: ?*ITfCompositionView, pSink: ?*ITfCompositionSink, ppComposition: ?*?*ITfComposition) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextComposition.VTable, self.vtable).TakeOwnership(@ptrCast(*const ITfContextComposition, self), ecWrite, pComposition, pSink, ppComposition); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextOwnerCompositionServices_Value = Guid.initString("86462810-593b-4916-9764-19c08e9ce110"); pub const IID_ITfContextOwnerCompositionServices = &IID_ITfContextOwnerCompositionServices_Value; pub const ITfContextOwnerCompositionServices = extern struct { pub const VTable = extern struct { base: ITfContextComposition.VTable, TerminateComposition: fn( self: *const ITfContextOwnerCompositionServices, pComposition: ?*ITfCompositionView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfContextComposition.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerCompositionServices_TerminateComposition(self: *const T, pComposition: ?*ITfCompositionView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerCompositionServices.VTable, self.vtable).TerminateComposition(@ptrCast(*const ITfContextOwnerCompositionServices, self), pComposition); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextOwnerCompositionSink_Value = Guid.initString("5f20aa40-b57a-4f34-96ab-3576f377cc79"); pub const IID_ITfContextOwnerCompositionSink = &IID_ITfContextOwnerCompositionSink_Value; pub const ITfContextOwnerCompositionSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStartComposition: fn( self: *const ITfContextOwnerCompositionSink, pComposition: ?*ITfCompositionView, pfOk: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnUpdateComposition: fn( self: *const ITfContextOwnerCompositionSink, pComposition: ?*ITfCompositionView, pRangeNew: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndComposition: fn( self: *const ITfContextOwnerCompositionSink, pComposition: ?*ITfCompositionView, ) 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 ITfContextOwnerCompositionSink_OnStartComposition(self: *const T, pComposition: ?*ITfCompositionView, pfOk: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerCompositionSink.VTable, self.vtable).OnStartComposition(@ptrCast(*const ITfContextOwnerCompositionSink, self), pComposition, pfOk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerCompositionSink_OnUpdateComposition(self: *const T, pComposition: ?*ITfCompositionView, pRangeNew: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerCompositionSink.VTable, self.vtable).OnUpdateComposition(@ptrCast(*const ITfContextOwnerCompositionSink, self), pComposition, pRangeNew); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerCompositionSink_OnEndComposition(self: *const T, pComposition: ?*ITfCompositionView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerCompositionSink.VTable, self.vtable).OnEndComposition(@ptrCast(*const ITfContextOwnerCompositionSink, self), pComposition); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextView_Value = Guid.initString("2433bf8e-0f9b-435c-ba2c-180611978c30"); pub const IID_ITfContextView = &IID_ITfContextView_Value; pub const ITfContextView = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetRangeFromPoint: fn( self: *const ITfContextView, ec: u32, ppt: ?*const POINT, dwFlags: u32, ppRange: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextExt: fn( self: *const ITfContextView, ec: u32, pRange: ?*ITfRange, prc: ?*RECT, pfClipped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScreenExt: fn( self: *const ITfContextView, prc: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWnd: fn( self: *const ITfContextView, phwnd: ?*?HWND, ) 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 ITfContextView_GetRangeFromPoint(self: *const T, ec: u32, ppt: ?*const POINT, dwFlags: u32, ppRange: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextView.VTable, self.vtable).GetRangeFromPoint(@ptrCast(*const ITfContextView, self), ec, ppt, dwFlags, ppRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextView_GetTextExt(self: *const T, ec: u32, pRange: ?*ITfRange, prc: ?*RECT, pfClipped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextView.VTable, self.vtable).GetTextExt(@ptrCast(*const ITfContextView, self), ec, pRange, prc, pfClipped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextView_GetScreenExt(self: *const T, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextView.VTable, self.vtable).GetScreenExt(@ptrCast(*const ITfContextView, self), prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextView_GetWnd(self: *const T, phwnd: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextView.VTable, self.vtable).GetWnd(@ptrCast(*const ITfContextView, self), phwnd); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IEnumTfContextViews_Value = Guid.initString("f0c0f8dd-cf38-44e1-bb0f-68cf0d551c78"); pub const IID_IEnumTfContextViews = &IID_IEnumTfContextViews_Value; pub const IEnumTfContextViews = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfContextViews, ppEnum: ?*?*IEnumTfContextViews, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfContextViews, ulCount: u32, rgViews: [*]?*ITfContextView, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfContextViews, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfContextViews, ulCount: 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 IEnumTfContextViews_Clone(self: *const T, ppEnum: ?*?*IEnumTfContextViews) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContextViews.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfContextViews, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContextViews_Next(self: *const T, ulCount: u32, rgViews: [*]?*ITfContextView, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContextViews.VTable, self.vtable).Next(@ptrCast(*const IEnumTfContextViews, self), ulCount, rgViews, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContextViews_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContextViews.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfContextViews, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfContextViews_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfContextViews.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfContextViews, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfActiveSelEnd = enum(i32) { NONE = 0, START = 1, END = 2, }; pub const TF_AE_NONE = TfActiveSelEnd.NONE; pub const TF_AE_START = TfActiveSelEnd.START; pub const TF_AE_END = TfActiveSelEnd.END; pub const TF_SELECTIONSTYLE = extern struct { ase: TfActiveSelEnd, fInterimChar: BOOL, }; pub const TF_SELECTION = extern struct { range: ?*ITfRange, style: TF_SELECTIONSTYLE, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContext_Value = Guid.initString("aa80e7fd-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfContext = &IID_ITfContext_Value; pub const ITfContext = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RequestEditSession: fn( self: *const ITfContext, tid: u32, pes: ?*ITfEditSession, dwFlags: TF_CONTEXT_EDIT_CONTEXT_FLAGS, phrSession: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InWriteSession: fn( self: *const ITfContext, tid: u32, pfWriteSession: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelection: fn( self: *const ITfContext, ec: u32, ulIndex: u32, ulCount: u32, pSelection: [*]TF_SELECTION, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSelection: fn( self: *const ITfContext, ec: u32, ulCount: u32, pSelection: [*]const TF_SELECTION, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStart: fn( self: *const ITfContext, ec: u32, ppStart: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnd: fn( self: *const ITfContext, ec: u32, ppEnd: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveView: fn( self: *const ITfContext, ppView: ?*?*ITfContextView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumViews: fn( self: *const ITfContext, ppEnum: ?*?*IEnumTfContextViews, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITfContext, pdcs: ?*TS_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperty: fn( self: *const ITfContext, guidProp: ?*const Guid, ppProp: ?*?*ITfProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAppProperty: fn( self: *const ITfContext, guidProp: ?*const Guid, ppProp: ?*?*ITfReadOnlyProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TrackProperties: fn( self: *const ITfContext, prgProp: [*]const ?*const Guid, cProp: u32, prgAppProp: [*]const ?*const Guid, cAppProp: u32, ppProperty: ?*?*ITfReadOnlyProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumProperties: fn( self: *const ITfContext, ppEnum: ?*?*IEnumTfProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentMgr: fn( self: *const ITfContext, ppDm: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRangeBackup: fn( self: *const ITfContext, ec: u32, pRange: ?*ITfRange, ppBackup: ?*?*ITfRangeBackup, ) 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 ITfContext_RequestEditSession(self: *const T, tid: u32, pes: ?*ITfEditSession, dwFlags: TF_CONTEXT_EDIT_CONTEXT_FLAGS, phrSession: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).RequestEditSession(@ptrCast(*const ITfContext, self), tid, pes, dwFlags, phrSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_InWriteSession(self: *const T, tid: u32, pfWriteSession: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).InWriteSession(@ptrCast(*const ITfContext, self), tid, pfWriteSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetSelection(self: *const T, ec: u32, ulIndex: u32, ulCount: u32, pSelection: [*]TF_SELECTION, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetSelection(@ptrCast(*const ITfContext, self), ec, ulIndex, ulCount, pSelection, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_SetSelection(self: *const T, ec: u32, ulCount: u32, pSelection: [*]const TF_SELECTION) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).SetSelection(@ptrCast(*const ITfContext, self), ec, ulCount, pSelection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetStart(self: *const T, ec: u32, ppStart: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetStart(@ptrCast(*const ITfContext, self), ec, ppStart); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetEnd(self: *const T, ec: u32, ppEnd: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetEnd(@ptrCast(*const ITfContext, self), ec, ppEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetActiveView(self: *const T, ppView: ?*?*ITfContextView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetActiveView(@ptrCast(*const ITfContext, self), ppView); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_EnumViews(self: *const T, ppEnum: ?*?*IEnumTfContextViews) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).EnumViews(@ptrCast(*const ITfContext, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetStatus(self: *const T, pdcs: ?*TS_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetStatus(@ptrCast(*const ITfContext, self), pdcs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetProperty(self: *const T, guidProp: ?*const Guid, ppProp: ?*?*ITfProperty) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetProperty(@ptrCast(*const ITfContext, self), guidProp, ppProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetAppProperty(self: *const T, guidProp: ?*const Guid, ppProp: ?*?*ITfReadOnlyProperty) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetAppProperty(@ptrCast(*const ITfContext, self), guidProp, ppProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_TrackProperties(self: *const T, prgProp: [*]const ?*const Guid, cProp: u32, prgAppProp: [*]const ?*const Guid, cAppProp: u32, ppProperty: ?*?*ITfReadOnlyProperty) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).TrackProperties(@ptrCast(*const ITfContext, self), prgProp, cProp, prgAppProp, cAppProp, ppProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_EnumProperties(self: *const T, ppEnum: ?*?*IEnumTfProperties) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).EnumProperties(@ptrCast(*const ITfContext, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_GetDocumentMgr(self: *const T, ppDm: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).GetDocumentMgr(@ptrCast(*const ITfContext, self), ppDm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContext_CreateRangeBackup(self: *const T, ec: u32, pRange: ?*ITfRange, ppBackup: ?*?*ITfRangeBackup) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContext.VTable, self.vtable).CreateRangeBackup(@ptrCast(*const ITfContext, self), ec, pRange, ppBackup); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfQueryEmbedded_Value = Guid.initString("0fab9bdb-d250-4169-84e5-6be118fdd7a8"); pub const IID_ITfQueryEmbedded = &IID_ITfQueryEmbedded_Value; pub const ITfQueryEmbedded = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryInsertEmbedded: fn( self: *const ITfQueryEmbedded, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*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 ITfQueryEmbedded_QueryInsertEmbedded(self: *const T, pguidService: ?*const Guid, pFormatEtc: ?*const FORMATETC, pfInsertable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfQueryEmbedded.VTable, self.vtable).QueryInsertEmbedded(@ptrCast(*const ITfQueryEmbedded, self), pguidService, pFormatEtc, pfInsertable); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfInsertAtSelection_Value = Guid.initString("55ce16ba-3014-41c1-9ceb-fade1446ac6c"); pub const IID_ITfInsertAtSelection = &IID_ITfInsertAtSelection_Value; pub const ITfInsertAtSelection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, InsertTextAtSelection: fn( self: *const ITfInsertAtSelection, ec: u32, dwFlags: INSERT_TEXT_AT_SELECTION_FLAGS, pchText: [*:0]const u16, cch: i32, ppRange: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbeddedAtSelection: fn( self: *const ITfInsertAtSelection, ec: u32, dwFlags: u32, pDataObject: ?*IDataObject, ppRange: ?*?*ITfRange, ) 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 ITfInsertAtSelection_InsertTextAtSelection(self: *const T, ec: u32, dwFlags: INSERT_TEXT_AT_SELECTION_FLAGS, pchText: [*:0]const u16, cch: i32, ppRange: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInsertAtSelection.VTable, self.vtable).InsertTextAtSelection(@ptrCast(*const ITfInsertAtSelection, self), ec, dwFlags, pchText, cch, ppRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInsertAtSelection_InsertEmbeddedAtSelection(self: *const T, ec: u32, dwFlags: u32, pDataObject: ?*IDataObject, ppRange: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInsertAtSelection.VTable, self.vtable).InsertEmbeddedAtSelection(@ptrCast(*const ITfInsertAtSelection, self), ec, dwFlags, pDataObject, ppRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCleanupContextSink_Value = Guid.initString("01689689-7acb-4e9b-ab7c-7ea46b12b522"); pub const IID_ITfCleanupContextSink = &IID_ITfCleanupContextSink_Value; pub const ITfCleanupContextSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnCleanupContext: fn( self: *const ITfCleanupContextSink, ecWrite: u32, pic: ?*ITfContext, ) 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 ITfCleanupContextSink_OnCleanupContext(self: *const T, ecWrite: u32, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCleanupContextSink.VTable, self.vtable).OnCleanupContext(@ptrCast(*const ITfCleanupContextSink, self), ecWrite, pic); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCleanupContextDurationSink_Value = Guid.initString("45c35144-154e-4797-bed8-d33ae7bf8794"); pub const IID_ITfCleanupContextDurationSink = &IID_ITfCleanupContextDurationSink_Value; pub const ITfCleanupContextDurationSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStartCleanupContext: fn( self: *const ITfCleanupContextDurationSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndCleanupContext: fn( self: *const ITfCleanupContextDurationSink, ) 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 ITfCleanupContextDurationSink_OnStartCleanupContext(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCleanupContextDurationSink.VTable, self.vtable).OnStartCleanupContext(@ptrCast(*const ITfCleanupContextDurationSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCleanupContextDurationSink_OnEndCleanupContext(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCleanupContextDurationSink.VTable, self.vtable).OnEndCleanupContext(@ptrCast(*const ITfCleanupContextDurationSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfReadOnlyProperty_Value = Guid.initString("17d49a3d-f8b8-4b2f-b254-52319dd64c53"); pub const IID_ITfReadOnlyProperty = &IID_ITfReadOnlyProperty_Value; pub const ITfReadOnlyProperty = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetType: fn( self: *const ITfReadOnlyProperty, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumRanges: fn( self: *const ITfReadOnlyProperty, ec: u32, ppEnum: ?*?*IEnumTfRanges, pTargetRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const ITfReadOnlyProperty, ec: u32, pRange: ?*ITfRange, pvarValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContext: fn( self: *const ITfReadOnlyProperty, ppContext: ?*?*ITfContext, ) 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 ITfReadOnlyProperty_GetType(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadOnlyProperty.VTable, self.vtable).GetType(@ptrCast(*const ITfReadOnlyProperty, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadOnlyProperty_EnumRanges(self: *const T, ec: u32, ppEnum: ?*?*IEnumTfRanges, pTargetRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadOnlyProperty.VTable, self.vtable).EnumRanges(@ptrCast(*const ITfReadOnlyProperty, self), ec, ppEnum, pTargetRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadOnlyProperty_GetValue(self: *const T, ec: u32, pRange: ?*ITfRange, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadOnlyProperty.VTable, self.vtable).GetValue(@ptrCast(*const ITfReadOnlyProperty, self), ec, pRange, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadOnlyProperty_GetContext(self: *const T, ppContext: ?*?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadOnlyProperty.VTable, self.vtable).GetContext(@ptrCast(*const ITfReadOnlyProperty, self), ppContext); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_PROPERTYVAL = extern struct { guidId: Guid, varValue: VARIANT, }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfPropertyValue_Value = Guid.initString("8ed8981b-7c10-4d7d-9fb3-ab72e9c75f72"); pub const IID_IEnumTfPropertyValue = &IID_IEnumTfPropertyValue_Value; pub const IEnumTfPropertyValue = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfPropertyValue, ppEnum: ?*?*IEnumTfPropertyValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfPropertyValue, ulCount: u32, rgValues: [*]TF_PROPERTYVAL, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfPropertyValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfPropertyValue, ulCount: 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 IEnumTfPropertyValue_Clone(self: *const T, ppEnum: ?*?*IEnumTfPropertyValue) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfPropertyValue.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfPropertyValue, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfPropertyValue_Next(self: *const T, ulCount: u32, rgValues: [*]TF_PROPERTYVAL, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfPropertyValue.VTable, self.vtable).Next(@ptrCast(*const IEnumTfPropertyValue, self), ulCount, rgValues, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfPropertyValue_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfPropertyValue.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfPropertyValue, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfPropertyValue_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfPropertyValue.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfPropertyValue, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMouseTracker_Value = Guid.initString("09d146cd-a544-4132-925b-7afa8ef322d0"); pub const IID_ITfMouseTracker = &IID_ITfMouseTracker_Value; pub const ITfMouseTracker = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseMouseSink: fn( self: *const ITfMouseTracker, range: ?*ITfRange, pSink: ?*ITfMouseSink, pdwCookie: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseMouseSink: fn( self: *const ITfMouseTracker, dwCookie: 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 ITfMouseTracker_AdviseMouseSink(self: *const T, range: ?*ITfRange, pSink: ?*ITfMouseSink, pdwCookie: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMouseTracker.VTable, self.vtable).AdviseMouseSink(@ptrCast(*const ITfMouseTracker, self), range, pSink, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMouseTracker_UnadviseMouseSink(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMouseTracker.VTable, self.vtable).UnadviseMouseSink(@ptrCast(*const ITfMouseTracker, self), dwCookie); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMouseTrackerACP_Value = Guid.initString("3bdd78e2-c16e-47fd-b883-ce6facc1a208"); pub const IID_ITfMouseTrackerACP = &IID_ITfMouseTrackerACP_Value; pub const ITfMouseTrackerACP = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseMouseSink: fn( self: *const ITfMouseTrackerACP, range: ?*ITfRangeACP, pSink: ?*ITfMouseSink, pdwCookie: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseMouseSink: fn( self: *const ITfMouseTrackerACP, dwCookie: 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 ITfMouseTrackerACP_AdviseMouseSink(self: *const T, range: ?*ITfRangeACP, pSink: ?*ITfMouseSink, pdwCookie: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMouseTrackerACP.VTable, self.vtable).AdviseMouseSink(@ptrCast(*const ITfMouseTrackerACP, self), range, pSink, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMouseTrackerACP_UnadviseMouseSink(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMouseTrackerACP.VTable, self.vtable).UnadviseMouseSink(@ptrCast(*const ITfMouseTrackerACP, self), dwCookie); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMouseSink_Value = Guid.initString("a1adaaa2-3a24-449d-ac96-5183e7f5c217"); pub const IID_ITfMouseSink = &IID_ITfMouseSink_Value; pub const ITfMouseSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnMouseEvent: fn( self: *const ITfMouseSink, uEdge: u32, uQuadrant: u32, dwBtnStatus: u32, pfEaten: ?*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 ITfMouseSink_OnMouseEvent(self: *const T, uEdge: u32, uQuadrant: u32, dwBtnStatus: u32, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMouseSink.VTable, self.vtable).OnMouseEvent(@ptrCast(*const ITfMouseSink, self), uEdge, uQuadrant, dwBtnStatus, pfEaten); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfEditRecord_Value = Guid.initString("42d4d099-7c1a-4a89-b836-6c6f22160df0"); pub const IID_ITfEditRecord = &IID_ITfEditRecord_Value; pub const ITfEditRecord = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSelectionStatus: fn( self: *const ITfEditRecord, pfChanged: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextAndPropertyUpdates: fn( self: *const ITfEditRecord, dwFlags: GET_TEXT_AND_PROPERTY_UPDATES_FLAGS, prgProperties: [*]const ?*const Guid, cProperties: u32, ppEnum: ?*?*IEnumTfRanges, ) 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 ITfEditRecord_GetSelectionStatus(self: *const T, pfChanged: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfEditRecord.VTable, self.vtable).GetSelectionStatus(@ptrCast(*const ITfEditRecord, self), pfChanged); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfEditRecord_GetTextAndPropertyUpdates(self: *const T, dwFlags: GET_TEXT_AND_PROPERTY_UPDATES_FLAGS, prgProperties: [*]const ?*const Guid, cProperties: u32, ppEnum: ?*?*IEnumTfRanges) callconv(.Inline) HRESULT { return @ptrCast(*const ITfEditRecord.VTable, self.vtable).GetTextAndPropertyUpdates(@ptrCast(*const ITfEditRecord, self), dwFlags, prgProperties, cProperties, ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTextEditSink_Value = Guid.initString("8127d409-ccd3-4683-967a-b43d5b482bf7"); pub const IID_ITfTextEditSink = &IID_ITfTextEditSink_Value; pub const ITfTextEditSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnEndEdit: fn( self: *const ITfTextEditSink, pic: ?*ITfContext, ecReadOnly: u32, pEditRecord: ?*ITfEditRecord, ) 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 ITfTextEditSink_OnEndEdit(self: *const T, pic: ?*ITfContext, ecReadOnly: u32, pEditRecord: ?*ITfEditRecord) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTextEditSink.VTable, self.vtable).OnEndEdit(@ptrCast(*const ITfTextEditSink, self), pic, ecReadOnly, pEditRecord); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfLayoutCode = enum(i32) { CREATE = 0, CHANGE = 1, DESTROY = 2, }; pub const TF_LC_CREATE = TfLayoutCode.CREATE; pub const TF_LC_CHANGE = TfLayoutCode.CHANGE; pub const TF_LC_DESTROY = TfLayoutCode.DESTROY; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTextLayoutSink_Value = Guid.initString("2af2d06a-dd5b-4927-a0b4-54f19c91fade"); pub const IID_ITfTextLayoutSink = &IID_ITfTextLayoutSink_Value; pub const ITfTextLayoutSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnLayoutChange: fn( self: *const ITfTextLayoutSink, pic: ?*ITfContext, lcode: TfLayoutCode, pView: ?*ITfContextView, ) 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 ITfTextLayoutSink_OnLayoutChange(self: *const T, pic: ?*ITfContext, lcode: TfLayoutCode, pView: ?*ITfContextView) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTextLayoutSink.VTable, self.vtable).OnLayoutChange(@ptrCast(*const ITfTextLayoutSink, self), pic, lcode, pView); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfStatusSink_Value = Guid.initString("6b7d8d73-b267-4f69-b32e-1ca321ce4f45"); pub const IID_ITfStatusSink = &IID_ITfStatusSink_Value; pub const ITfStatusSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStatusChange: fn( self: *const ITfStatusSink, pic: ?*ITfContext, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfStatusSink_OnStatusChange(self: *const T, pic: ?*ITfContext, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfStatusSink.VTable, self.vtable).OnStatusChange(@ptrCast(*const ITfStatusSink, self), pic, dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfEditTransactionSink_Value = Guid.initString("708fbf70-b520-416b-b06c-2c41ab44f8ba"); pub const IID_ITfEditTransactionSink = &IID_ITfEditTransactionSink_Value; pub const ITfEditTransactionSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStartEditTransaction: fn( self: *const ITfEditTransactionSink, pic: ?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEndEditTransaction: fn( self: *const ITfEditTransactionSink, pic: ?*ITfContext, ) 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 ITfEditTransactionSink_OnStartEditTransaction(self: *const T, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfEditTransactionSink.VTable, self.vtable).OnStartEditTransaction(@ptrCast(*const ITfEditTransactionSink, self), pic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfEditTransactionSink_OnEndEditTransaction(self: *const T, pic: ?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfEditTransactionSink.VTable, self.vtable).OnEndEditTransaction(@ptrCast(*const ITfEditTransactionSink, self), pic); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextOwner_Value = Guid.initString("aa80e80c-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfContextOwner = &IID_ITfContextOwner_Value; pub const ITfContextOwner = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetACPFromPoint: fn( self: *const ITfContextOwner, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTextExt: fn( self: *const ITfContextOwner, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScreenExt: fn( self: *const ITfContextOwner, prc: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const ITfContextOwner, pdcs: ?*TS_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWnd: fn( self: *const ITfContextOwner, phwnd: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttribute: fn( self: *const ITfContextOwner, rguidAttribute: ?*const Guid, pvarValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetACPFromPoint(self: *const T, ptScreen: ?*const POINT, dwFlags: u32, pacp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetACPFromPoint(@ptrCast(*const ITfContextOwner, self), ptScreen, dwFlags, pacp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetTextExt(self: *const T, acpStart: i32, acpEnd: i32, prc: ?*RECT, pfClipped: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetTextExt(@ptrCast(*const ITfContextOwner, self), acpStart, acpEnd, prc, pfClipped); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetScreenExt(self: *const T, prc: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetScreenExt(@ptrCast(*const ITfContextOwner, self), prc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetStatus(self: *const T, pdcs: ?*TS_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetStatus(@ptrCast(*const ITfContextOwner, self), pdcs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetWnd(self: *const T, phwnd: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetWnd(@ptrCast(*const ITfContextOwner, self), phwnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwner_GetAttribute(self: *const T, rguidAttribute: ?*const Guid, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwner.VTable, self.vtable).GetAttribute(@ptrCast(*const ITfContextOwner, self), rguidAttribute, pvarValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextOwnerServices_Value = Guid.initString("b23eb630-3e1c-11d3-a745-0050040ab407"); pub const IID_ITfContextOwnerServices = &IID_ITfContextOwnerServices_Value; pub const ITfContextOwnerServices = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnLayoutChange: fn( self: *const ITfContextOwnerServices, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnStatusChange: fn( self: *const ITfContextOwnerServices, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnAttributeChange: fn( self: *const ITfContextOwnerServices, rguidAttribute: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Serialize: fn( self: *const ITfContextOwnerServices, pProp: ?*ITfProperty, pRange: ?*ITfRange, pHdr: ?*TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unserialize: fn( self: *const ITfContextOwnerServices, pProp: ?*ITfProperty, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, pLoader: ?*ITfPersistentPropertyLoaderACP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ForceLoadProperty: fn( self: *const ITfContextOwnerServices, pProp: ?*ITfProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRange: fn( self: *const ITfContextOwnerServices, acpStart: i32, acpEnd: i32, ppRange: ?*?*ITfRangeACP, ) 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 ITfContextOwnerServices_OnLayoutChange(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).OnLayoutChange(@ptrCast(*const ITfContextOwnerServices, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_OnStatusChange(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).OnStatusChange(@ptrCast(*const ITfContextOwnerServices, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_OnAttributeChange(self: *const T, rguidAttribute: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).OnAttributeChange(@ptrCast(*const ITfContextOwnerServices, self), rguidAttribute); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_Serialize(self: *const T, pProp: ?*ITfProperty, pRange: ?*ITfRange, pHdr: ?*TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).Serialize(@ptrCast(*const ITfContextOwnerServices, self), pProp, pRange, pHdr, pStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_Unserialize(self: *const T, pProp: ?*ITfProperty, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, pLoader: ?*ITfPersistentPropertyLoaderACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).Unserialize(@ptrCast(*const ITfContextOwnerServices, self), pProp, pHdr, pStream, pLoader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_ForceLoadProperty(self: *const T, pProp: ?*ITfProperty) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).ForceLoadProperty(@ptrCast(*const ITfContextOwnerServices, self), pProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextOwnerServices_CreateRange(self: *const T, acpStart: i32, acpEnd: i32, ppRange: ?*?*ITfRangeACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextOwnerServices.VTable, self.vtable).CreateRange(@ptrCast(*const ITfContextOwnerServices, self), acpStart, acpEnd, ppRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfContextKeyEventSink_Value = Guid.initString("0552ba5d-c835-4934-bf50-846aaa67432f"); pub const IID_ITfContextKeyEventSink = &IID_ITfContextKeyEventSink_Value; pub const ITfContextKeyEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnKeyDown: fn( self: *const ITfContextKeyEventSink, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKeyUp: fn( self: *const ITfContextKeyEventSink, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTestKeyDown: fn( self: *const ITfContextKeyEventSink, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTestKeyUp: fn( self: *const ITfContextKeyEventSink, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*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 ITfContextKeyEventSink_OnKeyDown(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextKeyEventSink.VTable, self.vtable).OnKeyDown(@ptrCast(*const ITfContextKeyEventSink, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextKeyEventSink_OnKeyUp(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextKeyEventSink.VTable, self.vtable).OnKeyUp(@ptrCast(*const ITfContextKeyEventSink, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextKeyEventSink_OnTestKeyDown(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextKeyEventSink.VTable, self.vtable).OnTestKeyDown(@ptrCast(*const ITfContextKeyEventSink, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfContextKeyEventSink_OnTestKeyUp(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfContextKeyEventSink.VTable, self.vtable).OnTestKeyUp(@ptrCast(*const ITfContextKeyEventSink, self), wParam, lParam, pfEaten); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfEditSession_Value = Guid.initString("aa80e803-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfEditSession = &IID_ITfEditSession_Value; pub const ITfEditSession = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DoEditSession: fn( self: *const ITfEditSession, ec: 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 ITfEditSession_DoEditSession(self: *const T, ec: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfEditSession.VTable, self.vtable).DoEditSession(@ptrCast(*const ITfEditSession, self), ec); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfGravity = enum(i32) { BACKWARD = 0, FORWARD = 1, }; pub const TF_GRAVITY_BACKWARD = TfGravity.BACKWARD; pub const TF_GRAVITY_FORWARD = TfGravity.FORWARD; pub const TfShiftDir = enum(i32) { BACKWARD = 0, FORWARD = 1, }; pub const TF_SD_BACKWARD = TfShiftDir.BACKWARD; pub const TF_SD_FORWARD = TfShiftDir.FORWARD; pub const TF_HALTCOND = extern struct { pHaltRange: ?*ITfRange, aHaltPos: TfAnchor, dwFlags: u32, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfRange_Value = Guid.initString("aa80e7ff-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfRange = &IID_ITfRange_Value; pub const ITfRange = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetText: fn( self: *const ITfRange, ec: u32, dwFlags: u32, pchText: [*:0]u16, cchMax: u32, pcch: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetText: fn( self: *const ITfRange, ec: u32, dwFlags: u32, pchText: [*:0]const u16, cch: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormattedText: fn( self: *const ITfRange, ec: u32, ppDataObject: ?*?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEmbedded: fn( self: *const ITfRange, ec: u32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InsertEmbedded: fn( self: *const ITfRange, ec: u32, dwFlags: u32, pDataObject: ?*IDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftStart: fn( self: *const ITfRange, ec: u32, cchReq: i32, pcch: ?*i32, pHalt: ?*const TF_HALTCOND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftEnd: fn( self: *const ITfRange, ec: u32, cchReq: i32, pcch: ?*i32, pHalt: ?*const TF_HALTCOND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftStartToRange: fn( self: *const ITfRange, ec: u32, pRange: ?*ITfRange, aPos: TfAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftEndToRange: fn( self: *const ITfRange, ec: u32, pRange: ?*ITfRange, aPos: TfAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftStartRegion: fn( self: *const ITfRange, ec: u32, dir: TfShiftDir, pfNoRegion: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShiftEndRegion: fn( self: *const ITfRange, ec: u32, dir: TfShiftDir, pfNoRegion: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEmpty: fn( self: *const ITfRange, ec: u32, pfEmpty: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Collapse: fn( self: *const ITfRange, ec: u32, aPos: TfAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEqualStart: fn( self: *const ITfRange, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, pfEqual: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEqualEnd: fn( self: *const ITfRange, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, pfEqual: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareStart: fn( self: *const ITfRange, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, plResult: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompareEnd: fn( self: *const ITfRange, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, plResult: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AdjustForInsert: fn( self: *const ITfRange, ec: u32, cchInsert: u32, pfInsertOk: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGravity: fn( self: *const ITfRange, pgStart: ?*TfGravity, pgEnd: ?*TfGravity, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGravity: fn( self: *const ITfRange, ec: u32, gStart: TfGravity, gEnd: TfGravity, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const ITfRange, ppClone: ?*?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContext: fn( self: *const ITfRange, ppContext: ?*?*ITfContext, ) 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 ITfRange_GetText(self: *const T, ec: u32, dwFlags: u32, pchText: [*:0]u16, cchMax: u32, pcch: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).GetText(@ptrCast(*const ITfRange, self), ec, dwFlags, pchText, cchMax, pcch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_SetText(self: *const T, ec: u32, dwFlags: u32, pchText: [*:0]const u16, cch: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).SetText(@ptrCast(*const ITfRange, self), ec, dwFlags, pchText, cch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_GetFormattedText(self: *const T, ec: u32, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).GetFormattedText(@ptrCast(*const ITfRange, self), ec, ppDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_GetEmbedded(self: *const T, ec: u32, rguidService: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).GetEmbedded(@ptrCast(*const ITfRange, self), ec, rguidService, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_InsertEmbedded(self: *const T, ec: u32, dwFlags: u32, pDataObject: ?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).InsertEmbedded(@ptrCast(*const ITfRange, self), ec, dwFlags, pDataObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftStart(self: *const T, ec: u32, cchReq: i32, pcch: ?*i32, pHalt: ?*const TF_HALTCOND) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftStart(@ptrCast(*const ITfRange, self), ec, cchReq, pcch, pHalt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftEnd(self: *const T, ec: u32, cchReq: i32, pcch: ?*i32, pHalt: ?*const TF_HALTCOND) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftEnd(@ptrCast(*const ITfRange, self), ec, cchReq, pcch, pHalt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftStartToRange(self: *const T, ec: u32, pRange: ?*ITfRange, aPos: TfAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftStartToRange(@ptrCast(*const ITfRange, self), ec, pRange, aPos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftEndToRange(self: *const T, ec: u32, pRange: ?*ITfRange, aPos: TfAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftEndToRange(@ptrCast(*const ITfRange, self), ec, pRange, aPos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftStartRegion(self: *const T, ec: u32, dir: TfShiftDir, pfNoRegion: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftStartRegion(@ptrCast(*const ITfRange, self), ec, dir, pfNoRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_ShiftEndRegion(self: *const T, ec: u32, dir: TfShiftDir, pfNoRegion: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).ShiftEndRegion(@ptrCast(*const ITfRange, self), ec, dir, pfNoRegion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_IsEmpty(self: *const T, ec: u32, pfEmpty: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).IsEmpty(@ptrCast(*const ITfRange, self), ec, pfEmpty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_Collapse(self: *const T, ec: u32, aPos: TfAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).Collapse(@ptrCast(*const ITfRange, self), ec, aPos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_IsEqualStart(self: *const T, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, pfEqual: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).IsEqualStart(@ptrCast(*const ITfRange, self), ec, pWith, aPos, pfEqual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_IsEqualEnd(self: *const T, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, pfEqual: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).IsEqualEnd(@ptrCast(*const ITfRange, self), ec, pWith, aPos, pfEqual); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_CompareStart(self: *const T, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, plResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).CompareStart(@ptrCast(*const ITfRange, self), ec, pWith, aPos, plResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_CompareEnd(self: *const T, ec: u32, pWith: ?*ITfRange, aPos: TfAnchor, plResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).CompareEnd(@ptrCast(*const ITfRange, self), ec, pWith, aPos, plResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_AdjustForInsert(self: *const T, ec: u32, cchInsert: u32, pfInsertOk: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).AdjustForInsert(@ptrCast(*const ITfRange, self), ec, cchInsert, pfInsertOk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_GetGravity(self: *const T, pgStart: ?*TfGravity, pgEnd: ?*TfGravity) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).GetGravity(@ptrCast(*const ITfRange, self), pgStart, pgEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_SetGravity(self: *const T, ec: u32, gStart: TfGravity, gEnd: TfGravity) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).SetGravity(@ptrCast(*const ITfRange, self), ec, gStart, gEnd); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_Clone(self: *const T, ppClone: ?*?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).Clone(@ptrCast(*const ITfRange, self), ppClone); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRange_GetContext(self: *const T, ppContext: ?*?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRange.VTable, self.vtable).GetContext(@ptrCast(*const ITfRange, self), ppContext); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfRangeACP_Value = Guid.initString("057a6296-029b-4154-b79a-0d461d4ea94c"); pub const IID_ITfRangeACP = &IID_ITfRangeACP_Value; pub const ITfRangeACP = extern struct { pub const VTable = extern struct { base: ITfRange.VTable, GetExtent: fn( self: *const ITfRangeACP, pacpAnchor: ?*i32, pcch: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetExtent: fn( self: *const ITfRangeACP, acpAnchor: i32, cch: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfRange.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRangeACP_GetExtent(self: *const T, pacpAnchor: ?*i32, pcch: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRangeACP.VTable, self.vtable).GetExtent(@ptrCast(*const ITfRangeACP, self), pacpAnchor, pcch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfRangeACP_SetExtent(self: *const T, acpAnchor: i32, cch: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRangeACP.VTable, self.vtable).SetExtent(@ptrCast(*const ITfRangeACP, self), acpAnchor, cch); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITextStoreACPServices_Value = Guid.initString("aa80e901-2021-11d2-93e0-0060b067b86e"); pub const IID_ITextStoreACPServices = &IID_ITextStoreACPServices_Value; pub const ITextStoreACPServices = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Serialize: fn( self: *const ITextStoreACPServices, pProp: ?*ITfProperty, pRange: ?*ITfRange, pHdr: ?*TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unserialize: fn( self: *const ITextStoreACPServices, pProp: ?*ITfProperty, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, pLoader: ?*ITfPersistentPropertyLoaderACP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ForceLoadProperty: fn( self: *const ITextStoreACPServices, pProp: ?*ITfProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateRange: fn( self: *const ITextStoreACPServices, acpStart: i32, acpEnd: i32, ppRange: ?*?*ITfRangeACP, ) 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 ITextStoreACPServices_Serialize(self: *const T, pProp: ?*ITfProperty, pRange: ?*ITfRange, pHdr: ?*TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPServices.VTable, self.vtable).Serialize(@ptrCast(*const ITextStoreACPServices, self), pProp, pRange, pHdr, pStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPServices_Unserialize(self: *const T, pProp: ?*ITfProperty, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, pStream: ?*IStream, pLoader: ?*ITfPersistentPropertyLoaderACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPServices.VTable, self.vtable).Unserialize(@ptrCast(*const ITextStoreACPServices, self), pProp, pHdr, pStream, pLoader); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPServices_ForceLoadProperty(self: *const T, pProp: ?*ITfProperty) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPServices.VTable, self.vtable).ForceLoadProperty(@ptrCast(*const ITextStoreACPServices, self), pProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPServices_CreateRange(self: *const T, acpStart: i32, acpEnd: i32, ppRange: ?*?*ITfRangeACP) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPServices.VTable, self.vtable).CreateRange(@ptrCast(*const ITextStoreACPServices, self), acpStart, acpEnd, ppRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfRangeBackup_Value = Guid.initString("463a506d-6992-49d2-9b88-93d55e70bb16"); pub const IID_ITfRangeBackup = &IID_ITfRangeBackup_Value; pub const ITfRangeBackup = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Restore: fn( self: *const ITfRangeBackup, ec: u32, pRange: ?*ITfRange, ) 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 ITfRangeBackup_Restore(self: *const T, ec: u32, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfRangeBackup.VTable, self.vtable).Restore(@ptrCast(*const ITfRangeBackup, self), ec, pRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfPropertyStore_Value = Guid.initString("6834b120-88cb-11d2-bf45-00105a2799b5"); pub const IID_ITfPropertyStore = &IID_ITfPropertyStore_Value; pub const ITfPropertyStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetType: fn( self: *const ITfPropertyStore, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataType: fn( self: *const ITfPropertyStore, pdwReserved: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetData: fn( self: *const ITfPropertyStore, pvarValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTextUpdated: fn( self: *const ITfPropertyStore, dwFlags: u32, pRangeNew: ?*ITfRange, pfAccept: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Shrink: fn( self: *const ITfPropertyStore, pRangeNew: ?*ITfRange, pfFree: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Divide: fn( self: *const ITfPropertyStore, pRangeThis: ?*ITfRange, pRangeNew: ?*ITfRange, ppPropStore: ?*?*ITfPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const ITfPropertyStore, pPropStore: ?*?*ITfPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyRangeCreator: fn( self: *const ITfPropertyStore, pclsid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Serialize: fn( self: *const ITfPropertyStore, pStream: ?*IStream, pcb: ?*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 ITfPropertyStore_GetType(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).GetType(@ptrCast(*const ITfPropertyStore, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_GetDataType(self: *const T, pdwReserved: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).GetDataType(@ptrCast(*const ITfPropertyStore, self), pdwReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_GetData(self: *const T, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).GetData(@ptrCast(*const ITfPropertyStore, self), pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_OnTextUpdated(self: *const T, dwFlags: u32, pRangeNew: ?*ITfRange, pfAccept: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).OnTextUpdated(@ptrCast(*const ITfPropertyStore, self), dwFlags, pRangeNew, pfAccept); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_Shrink(self: *const T, pRangeNew: ?*ITfRange, pfFree: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).Shrink(@ptrCast(*const ITfPropertyStore, self), pRangeNew, pfFree); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_Divide(self: *const T, pRangeThis: ?*ITfRange, pRangeNew: ?*ITfRange, ppPropStore: ?*?*ITfPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).Divide(@ptrCast(*const ITfPropertyStore, self), pRangeThis, pRangeNew, ppPropStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_Clone(self: *const T, pPropStore: ?*?*ITfPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).Clone(@ptrCast(*const ITfPropertyStore, self), pPropStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_GetPropertyRangeCreator(self: *const T, pclsid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).GetPropertyRangeCreator(@ptrCast(*const ITfPropertyStore, self), pclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfPropertyStore_Serialize(self: *const T, pStream: ?*IStream, pcb: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPropertyStore.VTable, self.vtable).Serialize(@ptrCast(*const ITfPropertyStore, self), pStream, pcb); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfRanges_Value = Guid.initString("f99d3f40-8e32-11d2-bf46-00105a2799b5"); pub const IID_IEnumTfRanges = &IID_IEnumTfRanges_Value; pub const IEnumTfRanges = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfRanges, ppEnum: ?*?*IEnumTfRanges, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfRanges, ulCount: u32, ppRange: [*]?*ITfRange, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfRanges, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfRanges, ulCount: 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 IEnumTfRanges_Clone(self: *const T, ppEnum: ?*?*IEnumTfRanges) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfRanges.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfRanges, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfRanges_Next(self: *const T, ulCount: u32, ppRange: [*]?*ITfRange, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfRanges.VTable, self.vtable).Next(@ptrCast(*const IEnumTfRanges, self), ulCount, ppRange, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfRanges_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfRanges.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfRanges, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfRanges_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfRanges.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfRanges, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCreatePropertyStore_Value = Guid.initString("2463fbf0-b0af-11d2-afc5-00105a2799b5"); pub const IID_ITfCreatePropertyStore = &IID_ITfCreatePropertyStore_Value; pub const ITfCreatePropertyStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, IsStoreSerializable: fn( self: *const ITfCreatePropertyStore, guidProp: ?*const Guid, pRange: ?*ITfRange, pPropStore: ?*ITfPropertyStore, pfSerializable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePropertyStore: fn( self: *const ITfCreatePropertyStore, guidProp: ?*const Guid, pRange: ?*ITfRange, cb: u32, pStream: ?*IStream, ppStore: ?*?*ITfPropertyStore, ) 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 ITfCreatePropertyStore_IsStoreSerializable(self: *const T, guidProp: ?*const Guid, pRange: ?*ITfRange, pPropStore: ?*ITfPropertyStore, pfSerializable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCreatePropertyStore.VTable, self.vtable).IsStoreSerializable(@ptrCast(*const ITfCreatePropertyStore, self), guidProp, pRange, pPropStore, pfSerializable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCreatePropertyStore_CreatePropertyStore(self: *const T, guidProp: ?*const Guid, pRange: ?*ITfRange, cb: u32, pStream: ?*IStream, ppStore: ?*?*ITfPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCreatePropertyStore.VTable, self.vtable).CreatePropertyStore(@ptrCast(*const ITfCreatePropertyStore, self), guidProp, pRange, cb, pStream, ppStore); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfPersistentPropertyLoaderACP_Value = Guid.initString("4ef89150-0807-11d3-8df0-00105a2799b5"); pub const IID_ITfPersistentPropertyLoaderACP = &IID_ITfPersistentPropertyLoaderACP_Value; pub const ITfPersistentPropertyLoaderACP = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, LoadProperty: fn( self: *const ITfPersistentPropertyLoaderACP, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, ppStream: ?*?*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 ITfPersistentPropertyLoaderACP_LoadProperty(self: *const T, pHdr: ?*const TF_PERSISTENT_PROPERTY_HEADER_ACP, ppStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPersistentPropertyLoaderACP.VTable, self.vtable).LoadProperty(@ptrCast(*const ITfPersistentPropertyLoaderACP, self), pHdr, ppStream); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfProperty_Value = Guid.initString("e2449660-9542-11d2-bf46-00105a2799b5"); pub const IID_ITfProperty = &IID_ITfProperty_Value; pub const ITfProperty = extern struct { pub const VTable = extern struct { base: ITfReadOnlyProperty.VTable, FindRange: fn( self: *const ITfProperty, ec: u32, pRange: ?*ITfRange, ppRange: ?*?*ITfRange, aPos: TfAnchor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetValueStore: fn( self: *const ITfProperty, ec: u32, pRange: ?*ITfRange, pPropStore: ?*ITfPropertyStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetValue: fn( self: *const ITfProperty, ec: u32, pRange: ?*ITfRange, pvarValue: ?*const VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const ITfProperty, ec: u32, pRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfReadOnlyProperty.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfProperty_FindRange(self: *const T, ec: u32, pRange: ?*ITfRange, ppRange: ?*?*ITfRange, aPos: TfAnchor) callconv(.Inline) HRESULT { return @ptrCast(*const ITfProperty.VTable, self.vtable).FindRange(@ptrCast(*const ITfProperty, self), ec, pRange, ppRange, aPos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfProperty_SetValueStore(self: *const T, ec: u32, pRange: ?*ITfRange, pPropStore: ?*ITfPropertyStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITfProperty.VTable, self.vtable).SetValueStore(@ptrCast(*const ITfProperty, self), ec, pRange, pPropStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfProperty_SetValue(self: *const T, ec: u32, pRange: ?*ITfRange, pvarValue: ?*const VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfProperty.VTable, self.vtable).SetValue(@ptrCast(*const ITfProperty, self), ec, pRange, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfProperty_Clear(self: *const T, ec: u32, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfProperty.VTable, self.vtable).Clear(@ptrCast(*const ITfProperty, self), ec, pRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfProperties_Value = Guid.initString("19188cb0-aca9-11d2-afc5-00105a2799b5"); pub const IID_IEnumTfProperties = &IID_IEnumTfProperties_Value; pub const IEnumTfProperties = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfProperties, ppEnum: ?*?*IEnumTfProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfProperties, ulCount: u32, ppProp: [*]?*ITfProperty, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfProperties, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfProperties, ulCount: 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 IEnumTfProperties_Clone(self: *const T, ppEnum: ?*?*IEnumTfProperties) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfProperties.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfProperties, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfProperties_Next(self: *const T, ulCount: u32, ppProp: [*]?*ITfProperty, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfProperties.VTable, self.vtable).Next(@ptrCast(*const IEnumTfProperties, self), ulCount, ppProp, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfProperties_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfProperties.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfProperties, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfProperties_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfProperties.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfProperties, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCompartment_Value = Guid.initString("bb08f7a9-607a-4384-8623-056892b64371"); pub const IID_ITfCompartment = &IID_ITfCompartment_Value; pub const ITfCompartment = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetValue: fn( self: *const ITfCompartment, tid: u32, pvarValue: ?*const VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetValue: fn( self: *const ITfCompartment, pvarValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompartment_SetValue(self: *const T, tid: u32, pvarValue: ?*const VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartment.VTable, self.vtable).SetValue(@ptrCast(*const ITfCompartment, self), tid, pvarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompartment_GetValue(self: *const T, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartment.VTable, self.vtable).GetValue(@ptrCast(*const ITfCompartment, self), pvarValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCompartmentEventSink_Value = Guid.initString("743abd5f-f26d-48df-8cc5-238492419b64"); pub const IID_ITfCompartmentEventSink = &IID_ITfCompartmentEventSink_Value; pub const ITfCompartmentEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnChange: fn( self: *const ITfCompartmentEventSink, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompartmentEventSink_OnChange(self: *const T, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartmentEventSink.VTable, self.vtable).OnChange(@ptrCast(*const ITfCompartmentEventSink, self), rguid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCompartmentMgr_Value = Guid.initString("7dcf57ac-18ad-438b-824d-979bffb74b7c"); pub const IID_ITfCompartmentMgr = &IID_ITfCompartmentMgr_Value; pub const ITfCompartmentMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCompartment: fn( self: *const ITfCompartmentMgr, rguid: ?*const Guid, ppcomp: ?*?*ITfCompartment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearCompartment: fn( self: *const ITfCompartmentMgr, tid: u32, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumCompartments: fn( self: *const ITfCompartmentMgr, ppEnum: ?*?*IEnumGUID, ) 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 ITfCompartmentMgr_GetCompartment(self: *const T, rguid: ?*const Guid, ppcomp: ?*?*ITfCompartment) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartmentMgr.VTable, self.vtable).GetCompartment(@ptrCast(*const ITfCompartmentMgr, self), rguid, ppcomp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompartmentMgr_ClearCompartment(self: *const T, tid: u32, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartmentMgr.VTable, self.vtable).ClearCompartment(@ptrCast(*const ITfCompartmentMgr, self), tid, rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCompartmentMgr_EnumCompartments(self: *const T, ppEnum: ?*?*IEnumGUID) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCompartmentMgr.VTable, self.vtable).EnumCompartments(@ptrCast(*const ITfCompartmentMgr, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFunction_Value = Guid.initString("db593490-098f-11d3-8df0-00105a2799b5"); pub const IID_ITfFunction = &IID_ITfFunction_Value; pub const ITfFunction = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDisplayName: fn( self: *const ITfFunction, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFunction_GetDisplayName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFunction.VTable, self.vtable).GetDisplayName(@ptrCast(*const ITfFunction, self), pbstrName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFunctionProvider_Value = Guid.initString("101d6610-0990-11d3-8df0-00105a2799b5"); pub const IID_ITfFunctionProvider = &IID_ITfFunctionProvider_Value; pub const ITfFunctionProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetType: fn( self: *const ITfFunctionProvider, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const ITfFunctionProvider, pbstrDesc: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFunction: fn( self: *const ITfFunctionProvider, rguid: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFunctionProvider_GetType(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFunctionProvider.VTable, self.vtable).GetType(@ptrCast(*const ITfFunctionProvider, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFunctionProvider_GetDescription(self: *const T, pbstrDesc: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFunctionProvider.VTable, self.vtable).GetDescription(@ptrCast(*const ITfFunctionProvider, self), pbstrDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFunctionProvider_GetFunction(self: *const T, rguid: ?*const Guid, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFunctionProvider.VTable, self.vtable).GetFunction(@ptrCast(*const ITfFunctionProvider, self), rguid, riid, ppunk); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfFunctionProviders_Value = Guid.initString("e4b24db0-0990-11d3-8df0-00105a2799b5"); pub const IID_IEnumTfFunctionProviders = &IID_IEnumTfFunctionProviders_Value; pub const IEnumTfFunctionProviders = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfFunctionProviders, ppEnum: ?*?*IEnumTfFunctionProviders, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfFunctionProviders, ulCount: u32, ppCmdobj: [*]?*ITfFunctionProvider, pcFetch: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfFunctionProviders, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfFunctionProviders, ulCount: 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 IEnumTfFunctionProviders_Clone(self: *const T, ppEnum: ?*?*IEnumTfFunctionProviders) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfFunctionProviders.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfFunctionProviders, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfFunctionProviders_Next(self: *const T, ulCount: u32, ppCmdobj: [*]?*ITfFunctionProvider, pcFetch: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfFunctionProviders.VTable, self.vtable).Next(@ptrCast(*const IEnumTfFunctionProviders, self), ulCount, ppCmdobj, pcFetch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfFunctionProviders_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfFunctionProviders.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfFunctionProviders, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfFunctionProviders_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfFunctionProviders.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfFunctionProviders, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfInputProcessorProfiles_Value = Guid.initString("1f02b6c5-7842-4ee6-8a0b-9a24183a95ca"); pub const IID_ITfInputProcessorProfiles = &IID_ITfInputProcessorProfiles_Value; pub const ITfInputProcessorProfiles = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Register: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unregister: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32, pchIconFile: [*:0]const u16, cchFile: u32, uIconIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumInputProcessorInfo: fn( self: *const ITfInputProcessorProfiles, ppEnum: ?*?*IEnumGUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDefaultLanguageProfile: fn( self: *const ITfInputProcessorProfiles, langid: u16, catid: ?*const Guid, pclsid: ?*Guid, pguidProfile: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDefaultLanguageProfile: fn( self: *const ITfInputProcessorProfiles, langid: u16, rclsid: ?*const Guid, guidProfiles: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ActivateLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfiles: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, plangid: ?*u16, pguidProfile: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguageProfileDescription: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pbstrProfile: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentLanguage: fn( self: *const ITfInputProcessorProfiles, plangid: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangeCurrentLanguage: fn( self: *const ITfInputProcessorProfiles, langid: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLanguageList: fn( self: *const ITfInputProcessorProfiles, ppLangId: [*]?*u16, pulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumLanguageProfiles: fn( self: *const ITfInputProcessorProfiles, langid: u16, ppEnum: ?*?*IEnumTfLanguageProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEnabledLanguageProfile: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pfEnable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableLanguageProfileByDefault: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SubstituteKeyboardLayout: fn( self: *const ITfInputProcessorProfiles, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, hKL: ?HKL, ) 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 ITfInputProcessorProfiles_Register(self: *const T, rclsid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).Register(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_Unregister(self: *const T, rclsid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).Unregister(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_AddLanguageProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32, pchIconFile: [*:0]const u16, cchFile: u32, uIconIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).AddLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, pchDesc, cchDesc, pchIconFile, cchFile, uIconIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_RemoveLanguageProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).RemoveLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_EnumInputProcessorInfo(self: *const T, ppEnum: ?*?*IEnumGUID) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).EnumInputProcessorInfo(@ptrCast(*const ITfInputProcessorProfiles, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_GetDefaultLanguageProfile(self: *const T, langid: u16, catid: ?*const Guid, pclsid: ?*Guid, pguidProfile: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).GetDefaultLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), langid, catid, pclsid, pguidProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_SetDefaultLanguageProfile(self: *const T, langid: u16, rclsid: ?*const Guid, guidProfiles: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).SetDefaultLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), langid, rclsid, guidProfiles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_ActivateLanguageProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfiles: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).ActivateLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfiles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_GetActiveLanguageProfile(self: *const T, rclsid: ?*const Guid, plangid: ?*u16, pguidProfile: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).GetActiveLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, plangid, pguidProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_GetLanguageProfileDescription(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pbstrProfile: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).GetLanguageProfileDescription(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, pbstrProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_GetCurrentLanguage(self: *const T, plangid: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).GetCurrentLanguage(@ptrCast(*const ITfInputProcessorProfiles, self), plangid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_ChangeCurrentLanguage(self: *const T, langid: u16) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).ChangeCurrentLanguage(@ptrCast(*const ITfInputProcessorProfiles, self), langid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_GetLanguageList(self: *const T, ppLangId: [*]?*u16, pulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).GetLanguageList(@ptrCast(*const ITfInputProcessorProfiles, self), ppLangId, pulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_EnumLanguageProfiles(self: *const T, langid: u16, ppEnum: ?*?*IEnumTfLanguageProfiles) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).EnumLanguageProfiles(@ptrCast(*const ITfInputProcessorProfiles, self), langid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_EnableLanguageProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).EnableLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_IsEnabledLanguageProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pfEnable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).IsEnabledLanguageProfile(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, pfEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_EnableLanguageProfileByDefault(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).EnableLanguageProfileByDefault(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfiles_SubstituteKeyboardLayout(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, hKL: ?HKL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfiles.VTable, self.vtable).SubstituteKeyboardLayout(@ptrCast(*const ITfInputProcessorProfiles, self), rclsid, langid, guidProfile, hKL); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfInputProcessorProfilesEx_Value = Guid.initString("892f230f-fe00-4a41-a98e-fcd6de0d35ef"); pub const IID_ITfInputProcessorProfilesEx = &IID_ITfInputProcessorProfilesEx_Value; pub const ITfInputProcessorProfilesEx = extern struct { pub const VTable = extern struct { base: ITfInputProcessorProfiles.VTable, SetLanguageProfileDisplayName: fn( self: *const ITfInputProcessorProfilesEx, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchFile: [*:0]const u16, cchFile: u32, uResId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfInputProcessorProfiles.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfilesEx_SetLanguageProfileDisplayName(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchFile: [*:0]const u16, cchFile: u32, uResId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfilesEx.VTable, self.vtable).SetLanguageProfileDisplayName(@ptrCast(*const ITfInputProcessorProfilesEx, self), rclsid, langid, guidProfile, pchFile, cchFile, uResId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfInputProcessorProfileSubstituteLayout_Value = Guid.initString("4fd67194-1002-4513-bff2-c0ddf6258552"); pub const IID_ITfInputProcessorProfileSubstituteLayout = &IID_ITfInputProcessorProfileSubstituteLayout_Value; pub const ITfInputProcessorProfileSubstituteLayout = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSubstituteKeyboardLayout: fn( self: *const ITfInputProcessorProfileSubstituteLayout, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, phKL: ?*?HKL, ) 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 ITfInputProcessorProfileSubstituteLayout_GetSubstituteKeyboardLayout(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, phKL: ?*?HKL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileSubstituteLayout.VTable, self.vtable).GetSubstituteKeyboardLayout(@ptrCast(*const ITfInputProcessorProfileSubstituteLayout, self), rclsid, langid, guidProfile, phKL); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfActiveLanguageProfileNotifySink_Value = Guid.initString("b246cb75-a93e-4652-bf8c-b3fe0cfd7e57"); pub const IID_ITfActiveLanguageProfileNotifySink = &IID_ITfActiveLanguageProfileNotifySink_Value; pub const ITfActiveLanguageProfileNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnActivated: fn( self: *const ITfActiveLanguageProfileNotifySink, clsid: ?*const Guid, guidProfile: ?*const Guid, fActivated: 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 ITfActiveLanguageProfileNotifySink_OnActivated(self: *const T, clsid: ?*const Guid, guidProfile: ?*const Guid, fActivated: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfActiveLanguageProfileNotifySink.VTable, self.vtable).OnActivated(@ptrCast(*const ITfActiveLanguageProfileNotifySink, self), clsid, guidProfile, fActivated); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfLanguageProfiles_Value = Guid.initString("3d61bf11-ac5f-42c8-a4cb-931bcc28c744"); pub const IID_IEnumTfLanguageProfiles = &IID_IEnumTfLanguageProfiles_Value; pub const IEnumTfLanguageProfiles = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfLanguageProfiles, ppEnum: ?*?*IEnumTfLanguageProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfLanguageProfiles, ulCount: u32, pProfile: [*]TF_LANGUAGEPROFILE, pcFetch: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfLanguageProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfLanguageProfiles, ulCount: 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 IEnumTfLanguageProfiles_Clone(self: *const T, ppEnum: ?*?*IEnumTfLanguageProfiles) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLanguageProfiles.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfLanguageProfiles, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLanguageProfiles_Next(self: *const T, ulCount: u32, pProfile: [*]TF_LANGUAGEPROFILE, pcFetch: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLanguageProfiles.VTable, self.vtable).Next(@ptrCast(*const IEnumTfLanguageProfiles, self), ulCount, pProfile, pcFetch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLanguageProfiles_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLanguageProfiles.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfLanguageProfiles, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLanguageProfiles_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLanguageProfiles.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfLanguageProfiles, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLanguageProfileNotifySink_Value = Guid.initString("43c9fe15-f494-4c17-9de2-b8a4ac350aa8"); pub const IID_ITfLanguageProfileNotifySink = &IID_ITfLanguageProfileNotifySink_Value; pub const ITfLanguageProfileNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnLanguageChange: fn( self: *const ITfLanguageProfileNotifySink, langid: u16, pfAccept: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLanguageChanged: fn( self: *const ITfLanguageProfileNotifySink, ) 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 ITfLanguageProfileNotifySink_OnLanguageChange(self: *const T, langid: u16, pfAccept: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLanguageProfileNotifySink.VTable, self.vtable).OnLanguageChange(@ptrCast(*const ITfLanguageProfileNotifySink, self), langid, pfAccept); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLanguageProfileNotifySink_OnLanguageChanged(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLanguageProfileNotifySink.VTable, self.vtable).OnLanguageChanged(@ptrCast(*const ITfLanguageProfileNotifySink, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_INPUTPROCESSORPROFILE = extern struct { dwProfileType: u32, langid: u16, clsid: Guid, guidProfile: Guid, catid: Guid, hklSubstitute: ?HKL, dwCaps: u32, hkl: ?HKL, dwFlags: u32, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITfInputProcessorProfileMgr_Value = Guid.initString("71c6e74c-0f28-11d8-a82a-00065b84435c"); pub const IID_ITfInputProcessorProfileMgr = &IID_ITfInputProcessorProfileMgr_Value; pub const ITfInputProcessorProfileMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ActivateProfile: fn( self: *const ITfInputProcessorProfileMgr, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeactivateProfile: fn( self: *const ITfInputProcessorProfileMgr, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProfile: fn( self: *const ITfInputProcessorProfileMgr, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, pProfile: ?*TF_INPUTPROCESSORPROFILE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumProfiles: fn( self: *const ITfInputProcessorProfileMgr, langid: u16, ppEnum: ?*?*IEnumTfInputProcessorProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseInputProcessor: fn( self: *const ITfInputProcessorProfileMgr, rclsid: ?*const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterProfile: fn( self: *const ITfInputProcessorProfileMgr, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32, pchIconFile: [*:0]const u16, cchFile: u32, uIconIndex: u32, hklsubstitute: ?HKL, dwPreferredLayout: u32, bEnabledByDefault: BOOL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterProfile: fn( self: *const ITfInputProcessorProfileMgr, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveProfile: fn( self: *const ITfInputProcessorProfileMgr, catid: ?*const Guid, pProfile: ?*TF_INPUTPROCESSORPROFILE, ) 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 ITfInputProcessorProfileMgr_ActivateProfile(self: *const T, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).ActivateProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), dwProfileType, langid, clsid, guidProfile, hkl, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_DeactivateProfile(self: *const T, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).DeactivateProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), dwProfileType, langid, clsid, guidProfile, hkl, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_GetProfile(self: *const T, dwProfileType: u32, langid: u16, clsid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, pProfile: ?*TF_INPUTPROCESSORPROFILE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).GetProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), dwProfileType, langid, clsid, guidProfile, hkl, pProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_EnumProfiles(self: *const T, langid: u16, ppEnum: ?*?*IEnumTfInputProcessorProfiles) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).EnumProfiles(@ptrCast(*const ITfInputProcessorProfileMgr, self), langid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_ReleaseInputProcessor(self: *const T, rclsid: ?*const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).ReleaseInputProcessor(@ptrCast(*const ITfInputProcessorProfileMgr, self), rclsid, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_RegisterProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32, pchIconFile: [*:0]const u16, cchFile: u32, uIconIndex: u32, hklsubstitute: ?HKL, dwPreferredLayout: u32, bEnabledByDefault: BOOL, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).RegisterProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), rclsid, langid, guidProfile, pchDesc, cchDesc, pchIconFile, cchFile, uIconIndex, hklsubstitute, dwPreferredLayout, bEnabledByDefault, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_UnregisterProfile(self: *const T, rclsid: ?*const Guid, langid: u16, guidProfile: ?*const Guid, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).UnregisterProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), rclsid, langid, guidProfile, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileMgr_GetActiveProfile(self: *const T, catid: ?*const Guid, pProfile: ?*TF_INPUTPROCESSORPROFILE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileMgr.VTable, self.vtable).GetActiveProfile(@ptrCast(*const ITfInputProcessorProfileMgr, self), catid, pProfile); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfInputProcessorProfiles_Value = Guid.initString("71c6e74d-0f28-11d8-a82a-00065b84435c"); pub const IID_IEnumTfInputProcessorProfiles = &IID_IEnumTfInputProcessorProfiles_Value; pub const IEnumTfInputProcessorProfiles = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfInputProcessorProfiles, ppEnum: ?*?*IEnumTfInputProcessorProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfInputProcessorProfiles, ulCount: u32, pProfile: [*]TF_INPUTPROCESSORPROFILE, pcFetch: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfInputProcessorProfiles, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfInputProcessorProfiles, ulCount: 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 IEnumTfInputProcessorProfiles_Clone(self: *const T, ppEnum: ?*?*IEnumTfInputProcessorProfiles) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfInputProcessorProfiles.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfInputProcessorProfiles, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfInputProcessorProfiles_Next(self: *const T, ulCount: u32, pProfile: [*]TF_INPUTPROCESSORPROFILE, pcFetch: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfInputProcessorProfiles.VTable, self.vtable).Next(@ptrCast(*const IEnumTfInputProcessorProfiles, self), ulCount, pProfile, pcFetch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfInputProcessorProfiles_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfInputProcessorProfiles.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfInputProcessorProfiles, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfInputProcessorProfiles_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfInputProcessorProfiles.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfInputProcessorProfiles, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfInputProcessorProfileActivationSink_Value = Guid.initString("71c6e74e-0f28-11d8-a82a-00065b84435c"); pub const IID_ITfInputProcessorProfileActivationSink = &IID_ITfInputProcessorProfileActivationSink_Value; pub const ITfInputProcessorProfileActivationSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnActivated: fn( self: *const ITfInputProcessorProfileActivationSink, dwProfileType: u32, langid: u16, clsid: ?*const Guid, catid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputProcessorProfileActivationSink_OnActivated(self: *const T, dwProfileType: u32, langid: u16, clsid: ?*const Guid, catid: ?*const Guid, guidProfile: ?*const Guid, hkl: ?HKL, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputProcessorProfileActivationSink.VTable, self.vtable).OnActivated(@ptrCast(*const ITfInputProcessorProfileActivationSink, self), dwProfileType, langid, clsid, catid, guidProfile, hkl, dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_PRESERVEDKEY = extern struct { uVKey: u32, uModifiers: u32, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfKeystrokeMgr_Value = Guid.initString("aa80e7f0-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfKeystrokeMgr = &IID_ITfKeystrokeMgr_Value; pub const ITfKeystrokeMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseKeyEventSink: fn( self: *const ITfKeystrokeMgr, tid: u32, pSink: ?*ITfKeyEventSink, fForeground: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseKeyEventSink: fn( self: *const ITfKeystrokeMgr, tid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetForeground: fn( self: *const ITfKeystrokeMgr, pclsid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TestKeyDown: fn( self: *const ITfKeystrokeMgr, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TestKeyUp: fn( self: *const ITfKeystrokeMgr, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, KeyDown: fn( self: *const ITfKeystrokeMgr, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, KeyUp: fn( self: *const ITfKeystrokeMgr, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreservedKey: fn( self: *const ITfKeystrokeMgr, pic: ?*ITfContext, pprekey: ?*const TF_PRESERVEDKEY, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsPreservedKey: fn( self: *const ITfKeystrokeMgr, rguid: ?*const Guid, pprekey: ?*const TF_PRESERVEDKEY, pfRegistered: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PreserveKey: fn( self: *const ITfKeystrokeMgr, tid: u32, rguid: ?*const Guid, prekey: ?*const TF_PRESERVEDKEY, pchDesc: [*:0]const u16, cchDesc: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnpreserveKey: fn( self: *const ITfKeystrokeMgr, rguid: ?*const Guid, pprekey: ?*const TF_PRESERVEDKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPreservedKeyDescription: fn( self: *const ITfKeystrokeMgr, rguid: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreservedKeyDescription: fn( self: *const ITfKeystrokeMgr, rguid: ?*const Guid, pbstrDesc: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SimulatePreservedKey: fn( self: *const ITfKeystrokeMgr, pic: ?*ITfContext, rguid: ?*const Guid, pfEaten: ?*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 ITfKeystrokeMgr_AdviseKeyEventSink(self: *const T, tid: u32, pSink: ?*ITfKeyEventSink, fForeground: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).AdviseKeyEventSink(@ptrCast(*const ITfKeystrokeMgr, self), tid, pSink, fForeground); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_UnadviseKeyEventSink(self: *const T, tid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).UnadviseKeyEventSink(@ptrCast(*const ITfKeystrokeMgr, self), tid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_GetForeground(self: *const T, pclsid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).GetForeground(@ptrCast(*const ITfKeystrokeMgr, self), pclsid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_TestKeyDown(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).TestKeyDown(@ptrCast(*const ITfKeystrokeMgr, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_TestKeyUp(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).TestKeyUp(@ptrCast(*const ITfKeystrokeMgr, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_KeyDown(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).KeyDown(@ptrCast(*const ITfKeystrokeMgr, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_KeyUp(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).KeyUp(@ptrCast(*const ITfKeystrokeMgr, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_GetPreservedKey(self: *const T, pic: ?*ITfContext, pprekey: ?*const TF_PRESERVEDKEY, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).GetPreservedKey(@ptrCast(*const ITfKeystrokeMgr, self), pic, pprekey, pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_IsPreservedKey(self: *const T, rguid: ?*const Guid, pprekey: ?*const TF_PRESERVEDKEY, pfRegistered: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).IsPreservedKey(@ptrCast(*const ITfKeystrokeMgr, self), rguid, pprekey, pfRegistered); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_PreserveKey(self: *const T, tid: u32, rguid: ?*const Guid, prekey: ?*const TF_PRESERVEDKEY, pchDesc: [*:0]const u16, cchDesc: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).PreserveKey(@ptrCast(*const ITfKeystrokeMgr, self), tid, rguid, prekey, pchDesc, cchDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_UnpreserveKey(self: *const T, rguid: ?*const Guid, pprekey: ?*const TF_PRESERVEDKEY) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).UnpreserveKey(@ptrCast(*const ITfKeystrokeMgr, self), rguid, pprekey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_SetPreservedKeyDescription(self: *const T, rguid: ?*const Guid, pchDesc: [*:0]const u16, cchDesc: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).SetPreservedKeyDescription(@ptrCast(*const ITfKeystrokeMgr, self), rguid, pchDesc, cchDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_GetPreservedKeyDescription(self: *const T, rguid: ?*const Guid, pbstrDesc: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).GetPreservedKeyDescription(@ptrCast(*const ITfKeystrokeMgr, self), rguid, pbstrDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeystrokeMgr_SimulatePreservedKey(self: *const T, pic: ?*ITfContext, rguid: ?*const Guid, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeystrokeMgr.VTable, self.vtable).SimulatePreservedKey(@ptrCast(*const ITfKeystrokeMgr, self), pic, rguid, pfEaten); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfKeyEventSink_Value = Guid.initString("aa80e7f5-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfKeyEventSink = &IID_ITfKeyEventSink_Value; pub const ITfKeyEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnSetFocus: fn( self: *const ITfKeyEventSink, fForeground: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTestKeyDown: fn( self: *const ITfKeyEventSink, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTestKeyUp: fn( self: *const ITfKeyEventSink, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKeyDown: fn( self: *const ITfKeyEventSink, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKeyUp: fn( self: *const ITfKeyEventSink, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnPreservedKey: fn( self: *const ITfKeyEventSink, pic: ?*ITfContext, rguid: ?*const Guid, pfEaten: ?*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 ITfKeyEventSink_OnSetFocus(self: *const T, fForeground: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnSetFocus(@ptrCast(*const ITfKeyEventSink, self), fForeground); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyEventSink_OnTestKeyDown(self: *const T, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnTestKeyDown(@ptrCast(*const ITfKeyEventSink, self), pic, wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyEventSink_OnTestKeyUp(self: *const T, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnTestKeyUp(@ptrCast(*const ITfKeyEventSink, self), pic, wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyEventSink_OnKeyDown(self: *const T, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnKeyDown(@ptrCast(*const ITfKeyEventSink, self), pic, wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyEventSink_OnKeyUp(self: *const T, pic: ?*ITfContext, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnKeyUp(@ptrCast(*const ITfKeyEventSink, self), pic, wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyEventSink_OnPreservedKey(self: *const T, pic: ?*ITfContext, rguid: ?*const Guid, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyEventSink.VTable, self.vtable).OnPreservedKey(@ptrCast(*const ITfKeyEventSink, self), pic, rguid, pfEaten); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfKeyTraceEventSink_Value = Guid.initString("1cd4c13b-1c36-4191-a70a-7f3e611f367d"); pub const IID_ITfKeyTraceEventSink = &IID_ITfKeyTraceEventSink_Value; pub const ITfKeyTraceEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnKeyTraceDown: fn( self: *const ITfKeyTraceEventSink, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKeyTraceUp: fn( self: *const ITfKeyTraceEventSink, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyTraceEventSink_OnKeyTraceDown(self: *const T, wParam: WPARAM, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyTraceEventSink.VTable, self.vtable).OnKeyTraceDown(@ptrCast(*const ITfKeyTraceEventSink, self), wParam, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfKeyTraceEventSink_OnKeyTraceUp(self: *const T, wParam: WPARAM, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const ITfKeyTraceEventSink.VTable, self.vtable).OnKeyTraceUp(@ptrCast(*const ITfKeyTraceEventSink, self), wParam, lParam); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfPreservedKeyNotifySink_Value = Guid.initString("6f77c993-d2b1-446e-853e-5912efc8a286"); pub const IID_ITfPreservedKeyNotifySink = &IID_ITfPreservedKeyNotifySink_Value; pub const ITfPreservedKeyNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUpdated: fn( self: *const ITfPreservedKeyNotifySink, pprekey: ?*const TF_PRESERVEDKEY, ) 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 ITfPreservedKeyNotifySink_OnUpdated(self: *const T, pprekey: ?*const TF_PRESERVEDKEY) callconv(.Inline) HRESULT { return @ptrCast(*const ITfPreservedKeyNotifySink.VTable, self.vtable).OnUpdated(@ptrCast(*const ITfPreservedKeyNotifySink, self), pprekey); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMessagePump_Value = Guid.initString("8f1b8ad8-0b6b-4874-90c5-bd76011e8f7c"); pub const IID_ITfMessagePump = &IID_ITfMessagePump_Value; pub const ITfMessagePump = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, PeekMessageA: fn( self: *const ITfMessagePump, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32, pfResult: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessageA: fn( self: *const ITfMessagePump, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, pfResult: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PeekMessageW: fn( self: *const ITfMessagePump, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32, pfResult: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessageW: fn( self: *const ITfMessagePump, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, pfResult: ?*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 ITfMessagePump_PeekMessageA(self: *const T, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32, pfResult: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMessagePump.VTable, self.vtable).PeekMessageA(@ptrCast(*const ITfMessagePump, self), pMsg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg, pfResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMessagePump_GetMessageA(self: *const T, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, pfResult: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMessagePump.VTable, self.vtable).GetMessageA(@ptrCast(*const ITfMessagePump, self), pMsg, hwnd, wMsgFilterMin, wMsgFilterMax, pfResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMessagePump_PeekMessageW(self: *const T, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32, pfResult: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMessagePump.VTable, self.vtable).PeekMessageW(@ptrCast(*const ITfMessagePump, self), pMsg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg, pfResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMessagePump_GetMessageW(self: *const T, pMsg: ?*MSG, hwnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, pfResult: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMessagePump.VTable, self.vtable).GetMessageW(@ptrCast(*const ITfMessagePump, self), pMsg, hwnd, wMsgFilterMin, wMsgFilterMax, pfResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfThreadFocusSink_Value = Guid.initString("c0f1db0c-3a20-405c-a303-96b6010a885f"); pub const IID_ITfThreadFocusSink = &IID_ITfThreadFocusSink_Value; pub const ITfThreadFocusSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnSetThreadFocus: fn( self: *const ITfThreadFocusSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKillThreadFocus: fn( self: *const ITfThreadFocusSink, ) 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 ITfThreadFocusSink_OnSetThreadFocus(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadFocusSink.VTable, self.vtable).OnSetThreadFocus(@ptrCast(*const ITfThreadFocusSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfThreadFocusSink_OnKillThreadFocus(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfThreadFocusSink.VTable, self.vtable).OnKillThreadFocus(@ptrCast(*const ITfThreadFocusSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTextInputProcessor_Value = Guid.initString("aa80e7f7-2021-11d2-93e0-0060b067b86e"); pub const IID_ITfTextInputProcessor = &IID_ITfTextInputProcessor_Value; pub const ITfTextInputProcessor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Activate: fn( self: *const ITfTextInputProcessor, ptim: ?*ITfThreadMgr, tid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Deactivate: fn( self: *const ITfTextInputProcessor, ) 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 ITfTextInputProcessor_Activate(self: *const T, ptim: ?*ITfThreadMgr, tid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTextInputProcessor.VTable, self.vtable).Activate(@ptrCast(*const ITfTextInputProcessor, self), ptim, tid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfTextInputProcessor_Deactivate(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTextInputProcessor.VTable, self.vtable).Deactivate(@ptrCast(*const ITfTextInputProcessor, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTextInputProcessorEx_Value = Guid.initString("6e4e2102-f9cd-433d-b496-303ce03a6507"); pub const IID_ITfTextInputProcessorEx = &IID_ITfTextInputProcessorEx_Value; pub const ITfTextInputProcessorEx = extern struct { pub const VTable = extern struct { base: ITfTextInputProcessor.VTable, ActivateEx: fn( self: *const ITfTextInputProcessorEx, ptim: ?*ITfThreadMgr, tid: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfTextInputProcessor.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfTextInputProcessorEx_ActivateEx(self: *const T, ptim: ?*ITfThreadMgr, tid: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTextInputProcessorEx.VTable, self.vtable).ActivateEx(@ptrCast(*const ITfTextInputProcessorEx, self), ptim, tid, dwFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfClientId_Value = Guid.initString("d60a7b49-1b9f-4be2-b702-47e9dc05dec3"); pub const IID_ITfClientId = &IID_ITfClientId_Value; pub const ITfClientId = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetClientId: fn( self: *const ITfClientId, rclsid: ?*const Guid, ptid: ?*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 ITfClientId_GetClientId(self: *const T, rclsid: ?*const Guid, ptid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfClientId.VTable, self.vtable).GetClientId(@ptrCast(*const ITfClientId, self), rclsid, ptid); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_DA_LINESTYLE = enum(i32) { NONE = 0, SOLID = 1, DOT = 2, DASH = 3, SQUIGGLE = 4, }; pub const TF_LS_NONE = TF_DA_LINESTYLE.NONE; pub const TF_LS_SOLID = TF_DA_LINESTYLE.SOLID; pub const TF_LS_DOT = TF_DA_LINESTYLE.DOT; pub const TF_LS_DASH = TF_DA_LINESTYLE.DASH; pub const TF_LS_SQUIGGLE = TF_DA_LINESTYLE.SQUIGGLE; pub const TF_DA_COLORTYPE = enum(i32) { NONE = 0, SYSCOLOR = 1, COLORREF = 2, }; pub const TF_CT_NONE = TF_DA_COLORTYPE.NONE; pub const TF_CT_SYSCOLOR = TF_DA_COLORTYPE.SYSCOLOR; pub const TF_CT_COLORREF = TF_DA_COLORTYPE.COLORREF; pub const TF_DA_COLOR = extern struct { type: TF_DA_COLORTYPE, Anonymous: extern union { nIndex: i32, cr: u32, }, }; pub const TF_DA_ATTR_INFO = enum(i32) { INPUT = 0, TARGET_CONVERTED = 1, CONVERTED = 2, TARGET_NOTCONVERTED = 3, INPUT_ERROR = 4, FIXEDCONVERTED = 5, OTHER = -1, }; pub const TF_ATTR_INPUT = TF_DA_ATTR_INFO.INPUT; pub const TF_ATTR_TARGET_CONVERTED = TF_DA_ATTR_INFO.TARGET_CONVERTED; pub const TF_ATTR_CONVERTED = TF_DA_ATTR_INFO.CONVERTED; pub const TF_ATTR_TARGET_NOTCONVERTED = TF_DA_ATTR_INFO.TARGET_NOTCONVERTED; pub const TF_ATTR_INPUT_ERROR = TF_DA_ATTR_INFO.INPUT_ERROR; pub const TF_ATTR_FIXEDCONVERTED = TF_DA_ATTR_INFO.FIXEDCONVERTED; pub const TF_ATTR_OTHER = TF_DA_ATTR_INFO.OTHER; pub const TF_DISPLAYATTRIBUTE = extern struct { crText: TF_DA_COLOR, crBk: TF_DA_COLOR, lsStyle: TF_DA_LINESTYLE, fBoldLine: BOOL, crLine: TF_DA_COLOR, bAttr: TF_DA_ATTR_INFO, }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfDisplayAttributeInfo_Value = Guid.initString("70528852-2f26-4aea-8c96-215150578932"); pub const IID_ITfDisplayAttributeInfo = &IID_ITfDisplayAttributeInfo_Value; pub const ITfDisplayAttributeInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetGUID: fn( self: *const ITfDisplayAttributeInfo, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDescription: fn( self: *const ITfDisplayAttributeInfo, pbstrDesc: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeInfo: fn( self: *const ITfDisplayAttributeInfo, pda: ?*TF_DISPLAYATTRIBUTE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAttributeInfo: fn( self: *const ITfDisplayAttributeInfo, pda: ?*const TF_DISPLAYATTRIBUTE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const ITfDisplayAttributeInfo, ) 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 ITfDisplayAttributeInfo_GetGUID(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeInfo.VTable, self.vtable).GetGUID(@ptrCast(*const ITfDisplayAttributeInfo, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeInfo_GetDescription(self: *const T, pbstrDesc: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeInfo.VTable, self.vtable).GetDescription(@ptrCast(*const ITfDisplayAttributeInfo, self), pbstrDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeInfo_GetAttributeInfo(self: *const T, pda: ?*TF_DISPLAYATTRIBUTE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeInfo.VTable, self.vtable).GetAttributeInfo(@ptrCast(*const ITfDisplayAttributeInfo, self), pda); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeInfo_SetAttributeInfo(self: *const T, pda: ?*const TF_DISPLAYATTRIBUTE) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeInfo.VTable, self.vtable).SetAttributeInfo(@ptrCast(*const ITfDisplayAttributeInfo, self), pda); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeInfo_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeInfo.VTable, self.vtable).Reset(@ptrCast(*const ITfDisplayAttributeInfo, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfDisplayAttributeInfo_Value = Guid.initString("7cef04d7-cb75-4e80-a7ab-5f5bc7d332de"); pub const IID_IEnumTfDisplayAttributeInfo = &IID_IEnumTfDisplayAttributeInfo_Value; pub const IEnumTfDisplayAttributeInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfDisplayAttributeInfo, ppEnum: ?*?*IEnumTfDisplayAttributeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfDisplayAttributeInfo, ulCount: u32, rgInfo: [*]?*ITfDisplayAttributeInfo, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfDisplayAttributeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfDisplayAttributeInfo, ulCount: 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 IEnumTfDisplayAttributeInfo_Clone(self: *const T, ppEnum: ?*?*IEnumTfDisplayAttributeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDisplayAttributeInfo.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfDisplayAttributeInfo, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDisplayAttributeInfo_Next(self: *const T, ulCount: u32, rgInfo: [*]?*ITfDisplayAttributeInfo, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDisplayAttributeInfo.VTable, self.vtable).Next(@ptrCast(*const IEnumTfDisplayAttributeInfo, self), ulCount, rgInfo, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDisplayAttributeInfo_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDisplayAttributeInfo.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfDisplayAttributeInfo, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfDisplayAttributeInfo_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfDisplayAttributeInfo.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfDisplayAttributeInfo, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfDisplayAttributeProvider_Value = Guid.initString("fee47777-163c-4769-996a-6e9c50ad8f54"); pub const IID_ITfDisplayAttributeProvider = &IID_ITfDisplayAttributeProvider_Value; pub const ITfDisplayAttributeProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumDisplayAttributeInfo: fn( self: *const ITfDisplayAttributeProvider, ppEnum: ?*?*IEnumTfDisplayAttributeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayAttributeInfo: fn( self: *const ITfDisplayAttributeProvider, guid: ?*const Guid, ppInfo: ?*?*ITfDisplayAttributeInfo, ) 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 ITfDisplayAttributeProvider_EnumDisplayAttributeInfo(self: *const T, ppEnum: ?*?*IEnumTfDisplayAttributeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeProvider.VTable, self.vtable).EnumDisplayAttributeInfo(@ptrCast(*const ITfDisplayAttributeProvider, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeProvider_GetDisplayAttributeInfo(self: *const T, guid: ?*const Guid, ppInfo: ?*?*ITfDisplayAttributeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeProvider.VTable, self.vtable).GetDisplayAttributeInfo(@ptrCast(*const ITfDisplayAttributeProvider, self), guid, ppInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfDisplayAttributeMgr_Value = Guid.initString("8ded7393-5db1-475c-9e71-a39111b0ff67"); pub const IID_ITfDisplayAttributeMgr = &IID_ITfDisplayAttributeMgr_Value; pub const ITfDisplayAttributeMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUpdateInfo: fn( self: *const ITfDisplayAttributeMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDisplayAttributeInfo: fn( self: *const ITfDisplayAttributeMgr, ppEnum: ?*?*IEnumTfDisplayAttributeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayAttributeInfo: fn( self: *const ITfDisplayAttributeMgr, guid: ?*const Guid, ppInfo: ?*?*ITfDisplayAttributeInfo, pclsidOwner: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeMgr_OnUpdateInfo(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeMgr.VTable, self.vtable).OnUpdateInfo(@ptrCast(*const ITfDisplayAttributeMgr, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeMgr_EnumDisplayAttributeInfo(self: *const T, ppEnum: ?*?*IEnumTfDisplayAttributeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeMgr.VTable, self.vtable).EnumDisplayAttributeInfo(@ptrCast(*const ITfDisplayAttributeMgr, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfDisplayAttributeMgr_GetDisplayAttributeInfo(self: *const T, guid: ?*const Guid, ppInfo: ?*?*ITfDisplayAttributeInfo, pclsidOwner: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeMgr.VTable, self.vtable).GetDisplayAttributeInfo(@ptrCast(*const ITfDisplayAttributeMgr, self), guid, ppInfo, pclsidOwner); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfDisplayAttributeNotifySink_Value = Guid.initString("ad56f402-e162-4f25-908f-7d577cf9bda9"); pub const IID_ITfDisplayAttributeNotifySink = &IID_ITfDisplayAttributeNotifySink_Value; pub const ITfDisplayAttributeNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUpdateInfo: fn( self: *const ITfDisplayAttributeNotifySink, ) 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 ITfDisplayAttributeNotifySink_OnUpdateInfo(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfDisplayAttributeNotifySink.VTable, self.vtable).OnUpdateInfo(@ptrCast(*const ITfDisplayAttributeNotifySink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCategoryMgr_Value = Guid.initString("c3acefb5-f69d-4905-938f-fcadcf4be830"); pub const IID_ITfCategoryMgr = &IID_ITfCategoryMgr_Value; pub const ITfCategoryMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterCategory: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rcatid: ?*const Guid, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterCategory: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rcatid: ?*const Guid, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumCategoriesInItem: fn( self: *const ITfCategoryMgr, rguid: ?*const Guid, ppEnum: ?*?*IEnumGUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumItemsInCategory: fn( self: *const ITfCategoryMgr, rcatid: ?*const Guid, ppEnum: ?*?*IEnumGUID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindClosestCategory: fn( self: *const ITfCategoryMgr, rguid: ?*const Guid, pcatid: ?*Guid, ppcatidList: [*]const ?*const Guid, ulCount: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterGUIDDescription: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rguid: ?*const Guid, pchDesc: [*:0]const u16, cch: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterGUIDDescription: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGUIDDescription: fn( self: *const ITfCategoryMgr, rguid: ?*const Guid, pbstrDesc: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterGUIDDWORD: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rguid: ?*const Guid, dw: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterGUIDDWORD: fn( self: *const ITfCategoryMgr, rclsid: ?*const Guid, rguid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGUIDDWORD: fn( self: *const ITfCategoryMgr, rguid: ?*const Guid, pdw: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterGUID: fn( self: *const ITfCategoryMgr, rguid: ?*const Guid, pguidatom: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGUID: fn( self: *const ITfCategoryMgr, guidatom: u32, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEqualTfGuidAtom: fn( self: *const ITfCategoryMgr, guidatom: u32, rguid: ?*const Guid, pfEqual: ?*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 ITfCategoryMgr_RegisterCategory(self: *const T, rclsid: ?*const Guid, rcatid: ?*const Guid, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).RegisterCategory(@ptrCast(*const ITfCategoryMgr, self), rclsid, rcatid, rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_UnregisterCategory(self: *const T, rclsid: ?*const Guid, rcatid: ?*const Guid, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).UnregisterCategory(@ptrCast(*const ITfCategoryMgr, self), rclsid, rcatid, rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_EnumCategoriesInItem(self: *const T, rguid: ?*const Guid, ppEnum: ?*?*IEnumGUID) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).EnumCategoriesInItem(@ptrCast(*const ITfCategoryMgr, self), rguid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_EnumItemsInCategory(self: *const T, rcatid: ?*const Guid, ppEnum: ?*?*IEnumGUID) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).EnumItemsInCategory(@ptrCast(*const ITfCategoryMgr, self), rcatid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_FindClosestCategory(self: *const T, rguid: ?*const Guid, pcatid: ?*Guid, ppcatidList: [*]const ?*const Guid, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).FindClosestCategory(@ptrCast(*const ITfCategoryMgr, self), rguid, pcatid, ppcatidList, ulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_RegisterGUIDDescription(self: *const T, rclsid: ?*const Guid, rguid: ?*const Guid, pchDesc: [*:0]const u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).RegisterGUIDDescription(@ptrCast(*const ITfCategoryMgr, self), rclsid, rguid, pchDesc, cch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_UnregisterGUIDDescription(self: *const T, rclsid: ?*const Guid, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).UnregisterGUIDDescription(@ptrCast(*const ITfCategoryMgr, self), rclsid, rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_GetGUIDDescription(self: *const T, rguid: ?*const Guid, pbstrDesc: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).GetGUIDDescription(@ptrCast(*const ITfCategoryMgr, self), rguid, pbstrDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_RegisterGUIDDWORD(self: *const T, rclsid: ?*const Guid, rguid: ?*const Guid, dw: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).RegisterGUIDDWORD(@ptrCast(*const ITfCategoryMgr, self), rclsid, rguid, dw); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_UnregisterGUIDDWORD(self: *const T, rclsid: ?*const Guid, rguid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).UnregisterGUIDDWORD(@ptrCast(*const ITfCategoryMgr, self), rclsid, rguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_GetGUIDDWORD(self: *const T, rguid: ?*const Guid, pdw: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).GetGUIDDWORD(@ptrCast(*const ITfCategoryMgr, self), rguid, pdw); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_RegisterGUID(self: *const T, rguid: ?*const Guid, pguidatom: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).RegisterGUID(@ptrCast(*const ITfCategoryMgr, self), rguid, pguidatom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_GetGUID(self: *const T, guidatom: u32, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).GetGUID(@ptrCast(*const ITfCategoryMgr, self), guidatom, pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCategoryMgr_IsEqualTfGuidAtom(self: *const T, guidatom: u32, rguid: ?*const Guid, pfEqual: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCategoryMgr.VTable, self.vtable).IsEqualTfGuidAtom(@ptrCast(*const ITfCategoryMgr, self), guidatom, rguid, pfEqual); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSource_Value = Guid.initString("4ea48a35-60ae-446f-8fd6-e6a8d82459f7"); pub const IID_ITfSource = &IID_ITfSource_Value; pub const ITfSource = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseSink: fn( self: *const ITfSource, riid: ?*const Guid, punk: ?*IUnknown, pdwCookie: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseSink: fn( self: *const ITfSource, dwCookie: 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 ITfSource_AdviseSink(self: *const T, riid: ?*const Guid, punk: ?*IUnknown, pdwCookie: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSource.VTable, self.vtable).AdviseSink(@ptrCast(*const ITfSource, self), riid, punk, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSource_UnadviseSink(self: *const T, dwCookie: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSource.VTable, self.vtable).UnadviseSink(@ptrCast(*const ITfSource, self), dwCookie); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSourceSingle_Value = Guid.initString("73131f9c-56a9-49dd-b0ee-d046633f7528"); pub const IID_ITfSourceSingle = &IID_ITfSourceSingle_Value; pub const ITfSourceSingle = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdviseSingleSink: fn( self: *const ITfSourceSingle, tid: u32, riid: ?*const Guid, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnadviseSingleSink: fn( self: *const ITfSourceSingle, tid: u32, riid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSourceSingle_AdviseSingleSink(self: *const T, tid: u32, riid: ?*const Guid, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSourceSingle.VTable, self.vtable).AdviseSingleSink(@ptrCast(*const ITfSourceSingle, self), tid, riid, punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSourceSingle_UnadviseSingleSink(self: *const T, tid: u32, riid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSourceSingle.VTable, self.vtable).UnadviseSingleSink(@ptrCast(*const ITfSourceSingle, self), tid, riid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfUIElementMgr_Value = Guid.initString("ea1ea135-19df-11d7-a6d2-00065b84435c"); pub const IID_ITfUIElementMgr = &IID_ITfUIElementMgr_Value; pub const ITfUIElementMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, BeginUIElement: fn( self: *const ITfUIElementMgr, pElement: ?*ITfUIElement, pbShow: ?*BOOL, pdwUIElementId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateUIElement: fn( self: *const ITfUIElementMgr, dwUIElementId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndUIElement: fn( self: *const ITfUIElementMgr, dwUIElementId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUIElement: fn( self: *const ITfUIElementMgr, dwUIELementId: u32, ppElement: ?*?*ITfUIElement, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumUIElements: fn( self: *const ITfUIElementMgr, ppEnum: ?*?*IEnumTfUIElements, ) 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 ITfUIElementMgr_BeginUIElement(self: *const T, pElement: ?*ITfUIElement, pbShow: ?*BOOL, pdwUIElementId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementMgr.VTable, self.vtable).BeginUIElement(@ptrCast(*const ITfUIElementMgr, self), pElement, pbShow, pdwUIElementId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementMgr_UpdateUIElement(self: *const T, dwUIElementId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementMgr.VTable, self.vtable).UpdateUIElement(@ptrCast(*const ITfUIElementMgr, self), dwUIElementId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementMgr_EndUIElement(self: *const T, dwUIElementId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementMgr.VTable, self.vtable).EndUIElement(@ptrCast(*const ITfUIElementMgr, self), dwUIElementId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementMgr_GetUIElement(self: *const T, dwUIELementId: u32, ppElement: ?*?*ITfUIElement) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementMgr.VTable, self.vtable).GetUIElement(@ptrCast(*const ITfUIElementMgr, self), dwUIELementId, ppElement); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementMgr_EnumUIElements(self: *const T, ppEnum: ?*?*IEnumTfUIElements) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementMgr.VTable, self.vtable).EnumUIElements(@ptrCast(*const ITfUIElementMgr, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfUIElements_Value = Guid.initString("887aa91e-acba-4931-84da-3c5208cf543f"); pub const IID_IEnumTfUIElements = &IID_IEnumTfUIElements_Value; pub const IEnumTfUIElements = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfUIElements, ppEnum: ?*?*IEnumTfUIElements, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfUIElements, ulCount: u32, ppElement: [*]?*ITfUIElement, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfUIElements, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfUIElements, ulCount: 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 IEnumTfUIElements_Clone(self: *const T, ppEnum: ?*?*IEnumTfUIElements) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfUIElements.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfUIElements, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfUIElements_Next(self: *const T, ulCount: u32, ppElement: [*]?*ITfUIElement, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfUIElements.VTable, self.vtable).Next(@ptrCast(*const IEnumTfUIElements, self), ulCount, ppElement, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfUIElements_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfUIElements.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfUIElements, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfUIElements_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfUIElements.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfUIElements, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfUIElementSink_Value = Guid.initString("ea1ea136-19df-11d7-a6d2-00065b84435c"); pub const IID_ITfUIElementSink = &IID_ITfUIElementSink_Value; pub const ITfUIElementSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, BeginUIElement: fn( self: *const ITfUIElementSink, dwUIElementId: u32, pbShow: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateUIElement: fn( self: *const ITfUIElementSink, dwUIElementId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EndUIElement: fn( self: *const ITfUIElementSink, dwUIElementId: 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 ITfUIElementSink_BeginUIElement(self: *const T, dwUIElementId: u32, pbShow: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementSink.VTable, self.vtable).BeginUIElement(@ptrCast(*const ITfUIElementSink, self), dwUIElementId, pbShow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementSink_UpdateUIElement(self: *const T, dwUIElementId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementSink.VTable, self.vtable).UpdateUIElement(@ptrCast(*const ITfUIElementSink, self), dwUIElementId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElementSink_EndUIElement(self: *const T, dwUIElementId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElementSink.VTable, self.vtable).EndUIElement(@ptrCast(*const ITfUIElementSink, self), dwUIElementId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfUIElement_Value = Guid.initString("ea1ea137-19df-11d7-a6d2-00065b84435c"); pub const IID_ITfUIElement = &IID_ITfUIElement_Value; pub const ITfUIElement = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDescription: fn( self: *const ITfUIElement, pbstrDescription: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGUID: fn( self: *const ITfUIElement, pguid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Show: fn( self: *const ITfUIElement, bShow: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsShown: fn( self: *const ITfUIElement, pbShow: ?*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 ITfUIElement_GetDescription(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElement.VTable, self.vtable).GetDescription(@ptrCast(*const ITfUIElement, self), pbstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElement_GetGUID(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElement.VTable, self.vtable).GetGUID(@ptrCast(*const ITfUIElement, self), pguid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElement_Show(self: *const T, bShow: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElement.VTable, self.vtable).Show(@ptrCast(*const ITfUIElement, self), bShow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfUIElement_IsShown(self: *const T, pbShow: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfUIElement.VTable, self.vtable).IsShown(@ptrCast(*const ITfUIElement, self), pbShow); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCandidateListUIElement_Value = Guid.initString("ea1ea138-19df-11d7-a6d2-00065b84435c"); pub const IID_ITfCandidateListUIElement = &IID_ITfCandidateListUIElement_Value; pub const ITfCandidateListUIElement = extern struct { pub const VTable = extern struct { base: ITfUIElement.VTable, GetUpdatedFlags: fn( self: *const ITfCandidateListUIElement, pdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocumentMgr: fn( self: *const ITfCandidateListUIElement, ppdim: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCount: fn( self: *const ITfCandidateListUIElement, puCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelection: fn( self: *const ITfCandidateListUIElement, puIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const ITfCandidateListUIElement, uIndex: u32, pstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPageIndex: fn( self: *const ITfCandidateListUIElement, pIndex: [*]u32, uSize: u32, puPageCnt: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPageIndex: fn( self: *const ITfCandidateListUIElement, pIndex: [*]u32, uPageCnt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentPage: fn( self: *const ITfCandidateListUIElement, puPage: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfUIElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetUpdatedFlags(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetUpdatedFlags(@ptrCast(*const ITfCandidateListUIElement, self), pdwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetDocumentMgr(self: *const T, ppdim: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetDocumentMgr(@ptrCast(*const ITfCandidateListUIElement, self), ppdim); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetCount(self: *const T, puCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetCount(@ptrCast(*const ITfCandidateListUIElement, self), puCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetSelection(self: *const T, puIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetSelection(@ptrCast(*const ITfCandidateListUIElement, self), puIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetString(self: *const T, uIndex: u32, pstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetString(@ptrCast(*const ITfCandidateListUIElement, self), uIndex, pstr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetPageIndex(self: *const T, pIndex: [*]u32, uSize: u32, puPageCnt: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetPageIndex(@ptrCast(*const ITfCandidateListUIElement, self), pIndex, uSize, puPageCnt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_SetPageIndex(self: *const T, pIndex: [*]u32, uPageCnt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).SetPageIndex(@ptrCast(*const ITfCandidateListUIElement, self), pIndex, uPageCnt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElement_GetCurrentPage(self: *const T, puPage: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElement.VTable, self.vtable).GetCurrentPage(@ptrCast(*const ITfCandidateListUIElement, self), puPage); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCandidateListUIElementBehavior_Value = Guid.initString("85fad185-58ce-497a-9460-355366b64b9a"); pub const IID_ITfCandidateListUIElementBehavior = &IID_ITfCandidateListUIElementBehavior_Value; pub const ITfCandidateListUIElementBehavior = extern struct { pub const VTable = extern struct { base: ITfCandidateListUIElement.VTable, SetSelection: fn( self: *const ITfCandidateListUIElementBehavior, nIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Finalize: fn( self: *const ITfCandidateListUIElementBehavior, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Abort: fn( self: *const ITfCandidateListUIElementBehavior, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfCandidateListUIElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElementBehavior_SetSelection(self: *const T, nIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElementBehavior.VTable, self.vtable).SetSelection(@ptrCast(*const ITfCandidateListUIElementBehavior, self), nIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElementBehavior_Finalize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElementBehavior.VTable, self.vtable).Finalize(@ptrCast(*const ITfCandidateListUIElementBehavior, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateListUIElementBehavior_Abort(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateListUIElementBehavior.VTable, self.vtable).Abort(@ptrCast(*const ITfCandidateListUIElementBehavior, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfReadingInformationUIElement_Value = Guid.initString("ea1ea139-19df-11d7-a6d2-00065b84435c"); pub const IID_ITfReadingInformationUIElement = &IID_ITfReadingInformationUIElement_Value; pub const ITfReadingInformationUIElement = extern struct { pub const VTable = extern struct { base: ITfUIElement.VTable, GetUpdatedFlags: fn( self: *const ITfReadingInformationUIElement, pdwFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContext: fn( self: *const ITfReadingInformationUIElement, ppic: ?*?*ITfContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const ITfReadingInformationUIElement, pstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxReadingStringLength: fn( self: *const ITfReadingInformationUIElement, pcchMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorIndex: fn( self: *const ITfReadingInformationUIElement, pErrorIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsVerticalOrderPreferred: fn( self: *const ITfReadingInformationUIElement, pfVertical: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfUIElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_GetUpdatedFlags(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).GetUpdatedFlags(@ptrCast(*const ITfReadingInformationUIElement, self), pdwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_GetContext(self: *const T, ppic: ?*?*ITfContext) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).GetContext(@ptrCast(*const ITfReadingInformationUIElement, self), ppic); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_GetString(self: *const T, pstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).GetString(@ptrCast(*const ITfReadingInformationUIElement, self), pstr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_GetMaxReadingStringLength(self: *const T, pcchMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).GetMaxReadingStringLength(@ptrCast(*const ITfReadingInformationUIElement, self), pcchMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_GetErrorIndex(self: *const T, pErrorIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).GetErrorIndex(@ptrCast(*const ITfReadingInformationUIElement, self), pErrorIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReadingInformationUIElement_IsVerticalOrderPreferred(self: *const T, pfVertical: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReadingInformationUIElement.VTable, self.vtable).IsVerticalOrderPreferred(@ptrCast(*const ITfReadingInformationUIElement, self), pfVertical); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTransitoryExtensionUIElement_Value = Guid.initString("858f956a-972f-42a2-a2f2-0321e1abe209"); pub const IID_ITfTransitoryExtensionUIElement = &IID_ITfTransitoryExtensionUIElement_Value; pub const ITfTransitoryExtensionUIElement = extern struct { pub const VTable = extern struct { base: ITfUIElement.VTable, GetDocumentMgr: fn( self: *const ITfTransitoryExtensionUIElement, ppdim: ?*?*ITfDocumentMgr, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfUIElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfTransitoryExtensionUIElement_GetDocumentMgr(self: *const T, ppdim: ?*?*ITfDocumentMgr) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTransitoryExtensionUIElement.VTable, self.vtable).GetDocumentMgr(@ptrCast(*const ITfTransitoryExtensionUIElement, self), ppdim); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfTransitoryExtensionSink_Value = Guid.initString("a615096f-1c57-4813-8a15-55ee6e5a839c"); pub const IID_ITfTransitoryExtensionSink = &IID_ITfTransitoryExtensionSink_Value; pub const ITfTransitoryExtensionSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnTransitoryExtensionUpdated: fn( self: *const ITfTransitoryExtensionSink, pic: ?*ITfContext, ecReadOnly: u32, pResultRange: ?*ITfRange, pCompositionRange: ?*ITfRange, pfDeleteResultRange: ?*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 ITfTransitoryExtensionSink_OnTransitoryExtensionUpdated(self: *const T, pic: ?*ITfContext, ecReadOnly: u32, pResultRange: ?*ITfRange, pCompositionRange: ?*ITfRange, pfDeleteResultRange: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfTransitoryExtensionSink.VTable, self.vtable).OnTransitoryExtensionUpdated(@ptrCast(*const ITfTransitoryExtensionSink, self), pic, ecReadOnly, pResultRange, pCompositionRange, pfDeleteResultRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfToolTipUIElement_Value = Guid.initString("52b18b5c-555d-46b2-b00a-fa680144fbdb"); pub const IID_ITfToolTipUIElement = &IID_ITfToolTipUIElement_Value; pub const ITfToolTipUIElement = extern struct { pub const VTable = extern struct { base: ITfUIElement.VTable, GetString: fn( self: *const ITfToolTipUIElement, pstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfUIElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfToolTipUIElement_GetString(self: *const T, pstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfToolTipUIElement.VTable, self.vtable).GetString(@ptrCast(*const ITfToolTipUIElement, self), pstr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITfReverseConversionList_Value = Guid.initString("151d69f0-86f4-4674-b721-56911e797f47"); pub const IID_ITfReverseConversionList = &IID_ITfReverseConversionList_Value; pub const ITfReverseConversionList = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLength: fn( self: *const ITfReverseConversionList, puIndex: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const ITfReverseConversionList, uIndex: u32, pbstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReverseConversionList_GetLength(self: *const T, puIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReverseConversionList.VTable, self.vtable).GetLength(@ptrCast(*const ITfReverseConversionList, self), puIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfReverseConversionList_GetString(self: *const T, uIndex: u32, pbstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReverseConversionList.VTable, self.vtable).GetString(@ptrCast(*const ITfReverseConversionList, self), uIndex, pbstr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITfReverseConversion_Value = Guid.initString("a415e162-157d-417d-8a8c-0ab26c7d2781"); pub const IID_ITfReverseConversion = &IID_ITfReverseConversion_Value; pub const ITfReverseConversion = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DoReverseConversion: fn( self: *const ITfReverseConversion, lpstr: ?[*:0]const u16, ppList: ?*?*ITfReverseConversionList, ) 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 ITfReverseConversion_DoReverseConversion(self: *const T, lpstr: ?[*:0]const u16, ppList: ?*?*ITfReverseConversionList) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReverseConversion.VTable, self.vtable).DoReverseConversion(@ptrCast(*const ITfReverseConversion, self), lpstr, ppList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ITfReverseConversionMgr_Value = Guid.initString("b643c236-c493-41b6-abb3-692412775cc4"); pub const IID_ITfReverseConversionMgr = &IID_ITfReverseConversionMgr_Value; pub const ITfReverseConversionMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetReverseConversion: fn( self: *const ITfReverseConversionMgr, langid: u16, guidProfile: ?*const Guid, dwflag: u32, ppReverseConversion: ?*?*ITfReverseConversion, ) 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 ITfReverseConversionMgr_GetReverseConversion(self: *const T, langid: u16, guidProfile: ?*const Guid, dwflag: u32, ppReverseConversion: ?*?*ITfReverseConversion) callconv(.Inline) HRESULT { return @ptrCast(*const ITfReverseConversionMgr.VTable, self.vtable).GetReverseConversion(@ptrCast(*const ITfReverseConversionMgr, self), langid, guidProfile, dwflag, ppReverseConversion); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCandidateString_Value = Guid.initString("581f317e-fd9d-443f-b972-ed00467c5d40"); pub const IID_ITfCandidateString = &IID_ITfCandidateString_Value; pub const ITfCandidateString = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetString: fn( self: *const ITfCandidateString, pbstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIndex: fn( self: *const ITfCandidateString, pnIndex: ?*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 ITfCandidateString_GetString(self: *const T, pbstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateString.VTable, self.vtable).GetString(@ptrCast(*const ITfCandidateString, self), pbstr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateString_GetIndex(self: *const T, pnIndex: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateString.VTable, self.vtable).GetIndex(@ptrCast(*const ITfCandidateString, self), pnIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfCandidates_Value = Guid.initString("defb1926-6c80-4ce8-87d4-d6b72b812bde"); pub const IID_IEnumTfCandidates = &IID_IEnumTfCandidates_Value; pub const IEnumTfCandidates = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfCandidates, ppEnum: ?*?*IEnumTfCandidates, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfCandidates, ulCount: u32, ppCand: [*]?*ITfCandidateString, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfCandidates, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfCandidates, ulCount: 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 IEnumTfCandidates_Clone(self: *const T, ppEnum: ?*?*IEnumTfCandidates) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfCandidates.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfCandidates, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfCandidates_Next(self: *const T, ulCount: u32, ppCand: [*]?*ITfCandidateString, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfCandidates.VTable, self.vtable).Next(@ptrCast(*const IEnumTfCandidates, self), ulCount, ppCand, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfCandidates_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfCandidates.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfCandidates, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfCandidates_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfCandidates.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfCandidates, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfCandidateResult = enum(i32) { FINALIZED = 0, SELECTED = 1, CANCELED = 2, }; pub const CAND_FINALIZED = TfCandidateResult.FINALIZED; pub const CAND_SELECTED = TfCandidateResult.SELECTED; pub const CAND_CANCELED = TfCandidateResult.CANCELED; // TODO: this type is limited to platform 'windows5.0' const IID_ITfCandidateList_Value = Guid.initString("a3ad50fb-9bdb-49e3-a843-6c76520fbf5d"); pub const IID_ITfCandidateList = &IID_ITfCandidateList_Value; pub const ITfCandidateList = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumCandidates: fn( self: *const ITfCandidateList, ppEnum: ?*?*IEnumTfCandidates, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCandidate: fn( self: *const ITfCandidateList, nIndex: u32, ppCand: ?*?*ITfCandidateString, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCandidateNum: fn( self: *const ITfCandidateList, pnCnt: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetResult: fn( self: *const ITfCandidateList, nIndex: u32, imcr: TfCandidateResult, ) 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 ITfCandidateList_EnumCandidates(self: *const T, ppEnum: ?*?*IEnumTfCandidates) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateList.VTable, self.vtable).EnumCandidates(@ptrCast(*const ITfCandidateList, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateList_GetCandidate(self: *const T, nIndex: u32, ppCand: ?*?*ITfCandidateString) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateList.VTable, self.vtable).GetCandidate(@ptrCast(*const ITfCandidateList, self), nIndex, ppCand); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateList_GetCandidateNum(self: *const T, pnCnt: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateList.VTable, self.vtable).GetCandidateNum(@ptrCast(*const ITfCandidateList, self), pnCnt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfCandidateList_SetResult(self: *const T, nIndex: u32, imcr: TfCandidateResult) callconv(.Inline) HRESULT { return @ptrCast(*const ITfCandidateList.VTable, self.vtable).SetResult(@ptrCast(*const ITfCandidateList, self), nIndex, imcr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnReconversion_Value = Guid.initString("4cea93c0-0a58-11d3-8df0-00105a2799b5"); pub const IID_ITfFnReconversion = &IID_ITfFnReconversion_Value; pub const ITfFnReconversion = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, QueryRange: fn( self: *const ITfFnReconversion, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfConvertable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReconversion: fn( self: *const ITfFnReconversion, pRange: ?*ITfRange, ppCandList: ?*?*ITfCandidateList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reconvert: fn( self: *const ITfFnReconversion, pRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnReconversion_QueryRange(self: *const T, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfConvertable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnReconversion.VTable, self.vtable).QueryRange(@ptrCast(*const ITfFnReconversion, self), pRange, ppNewRange, pfConvertable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnReconversion_GetReconversion(self: *const T, pRange: ?*ITfRange, ppCandList: ?*?*ITfCandidateList) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnReconversion.VTable, self.vtable).GetReconversion(@ptrCast(*const ITfFnReconversion, self), pRange, ppCandList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnReconversion_Reconvert(self: *const T, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnReconversion.VTable, self.vtable).Reconvert(@ptrCast(*const ITfFnReconversion, self), pRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnPlayBack_Value = Guid.initString("a3a416a4-0f64-11d3-b5b7-00c04fc324a1"); pub const IID_ITfFnPlayBack = &IID_ITfFnPlayBack_Value; pub const ITfFnPlayBack = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, QueryRange: fn( self: *const ITfFnPlayBack, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfPlayable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Play: fn( self: *const ITfFnPlayBack, pRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnPlayBack_QueryRange(self: *const T, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfPlayable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnPlayBack.VTable, self.vtable).QueryRange(@ptrCast(*const ITfFnPlayBack, self), pRange, ppNewRange, pfPlayable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnPlayBack_Play(self: *const T, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnPlayBack.VTable, self.vtable).Play(@ptrCast(*const ITfFnPlayBack, self), pRange); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnLangProfileUtil_Value = Guid.initString("a87a8574-a6c1-4e15-99f0-3d3965f548eb"); pub const IID_ITfFnLangProfileUtil = &IID_ITfFnLangProfileUtil_Value; pub const ITfFnLangProfileUtil = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, RegisterActiveProfiles: fn( self: *const ITfFnLangProfileUtil, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsProfileAvailableForLang: fn( self: *const ITfFnLangProfileUtil, langid: u16, pfAvailable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLangProfileUtil_RegisterActiveProfiles(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLangProfileUtil.VTable, self.vtable).RegisterActiveProfiles(@ptrCast(*const ITfFnLangProfileUtil, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLangProfileUtil_IsProfileAvailableForLang(self: *const T, langid: u16, pfAvailable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLangProfileUtil.VTable, self.vtable).IsProfileAvailableForLang(@ptrCast(*const ITfFnLangProfileUtil, self), langid, pfAvailable); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnConfigure_Value = Guid.initString("88f567c6-1757-49f8-a1b2-89234c1eeff9"); pub const IID_ITfFnConfigure = &IID_ITfFnConfigure_Value; pub const ITfFnConfigure = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, Show: fn( self: *const ITfFnConfigure, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnConfigure_Show(self: *const T, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnConfigure.VTable, self.vtable).Show(@ptrCast(*const ITfFnConfigure, self), hwndParent, langid, rguidProfile); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnConfigureRegisterWord_Value = Guid.initString("bb95808a-6d8f-4bca-8400-5390b586aedf"); pub const IID_ITfFnConfigureRegisterWord = &IID_ITfFnConfigureRegisterWord_Value; pub const ITfFnConfigureRegisterWord = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, Show: fn( self: *const ITfFnConfigureRegisterWord, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid, bstrRegistered: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnConfigureRegisterWord_Show(self: *const T, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid, bstrRegistered: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnConfigureRegisterWord.VTable, self.vtable).Show(@ptrCast(*const ITfFnConfigureRegisterWord, self), hwndParent, langid, rguidProfile, bstrRegistered); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnConfigureRegisterEudc_Value = Guid.initString("b5e26ff5-d7ad-4304-913f-21a2ed95a1b0"); pub const IID_ITfFnConfigureRegisterEudc = &IID_ITfFnConfigureRegisterEudc_Value; pub const ITfFnConfigureRegisterEudc = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, Show: fn( self: *const ITfFnConfigureRegisterEudc, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid, bstrRegistered: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnConfigureRegisterEudc_Show(self: *const T, hwndParent: ?HWND, langid: u16, rguidProfile: ?*const Guid, bstrRegistered: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnConfigureRegisterEudc.VTable, self.vtable).Show(@ptrCast(*const ITfFnConfigureRegisterEudc, self), hwndParent, langid, rguidProfile, bstrRegistered); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnShowHelp_Value = Guid.initString("5ab1d30c-094d-4c29-8ea5-0bf59be87bf3"); pub const IID_ITfFnShowHelp = &IID_ITfFnShowHelp_Value; pub const ITfFnShowHelp = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, Show: fn( self: *const ITfFnShowHelp, hwndParent: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnShowHelp_Show(self: *const T, hwndParent: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnShowHelp.VTable, self.vtable).Show(@ptrCast(*const ITfFnShowHelp, self), hwndParent); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnBalloon_Value = Guid.initString("3bab89e4-5fbe-45f4-a5bc-dca36ad225a8"); pub const IID_ITfFnBalloon = &IID_ITfFnBalloon_Value; pub const ITfFnBalloon = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, UpdateBalloon: fn( self: *const ITfFnBalloon, style: TfLBBalloonStyle, pch: [*:0]const u16, cch: 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 ITfFnBalloon_UpdateBalloon(self: *const T, style: TfLBBalloonStyle, pch: [*:0]const u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnBalloon.VTable, self.vtable).UpdateBalloon(@ptrCast(*const ITfFnBalloon, self), style, pch, cch); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfSapiObject = enum(i32) { RESMGR = 0, RECOCONTEXT = 1, RECOGNIZER = 2, VOICE = 3, DICTGRAM = 4, RECOGNIZERNOINIT = 5, }; pub const GETIF_RESMGR = TfSapiObject.RESMGR; pub const GETIF_RECOCONTEXT = TfSapiObject.RECOCONTEXT; pub const GETIF_RECOGNIZER = TfSapiObject.RECOGNIZER; pub const GETIF_VOICE = TfSapiObject.VOICE; pub const GETIF_DICTGRAM = TfSapiObject.DICTGRAM; pub const GETIF_RECOGNIZERNOINIT = TfSapiObject.RECOGNIZERNOINIT; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnGetSAPIObject_Value = Guid.initString("5c0ab7ea-167d-4f59-bfb5-4693755e90ca"); pub const IID_ITfFnGetSAPIObject = &IID_ITfFnGetSAPIObject_Value; pub const ITfFnGetSAPIObject = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, Get: fn( self: *const ITfFnGetSAPIObject, sObj: TfSapiObject, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnGetSAPIObject_Get(self: *const T, sObj: TfSapiObject, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnGetSAPIObject.VTable, self.vtable).Get(@ptrCast(*const ITfFnGetSAPIObject, self), sObj, ppunk); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnPropertyUIStatus_Value = Guid.initString("2338ac6e-2b9d-44c0-a75e-ee64f256b3bd"); pub const IID_ITfFnPropertyUIStatus = &IID_ITfFnPropertyUIStatus_Value; pub const ITfFnPropertyUIStatus = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, GetStatus: fn( self: *const ITfFnPropertyUIStatus, refguidProp: ?*const Guid, pdw: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStatus: fn( self: *const ITfFnPropertyUIStatus, refguidProp: ?*const Guid, dw: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnPropertyUIStatus_GetStatus(self: *const T, refguidProp: ?*const Guid, pdw: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnPropertyUIStatus.VTable, self.vtable).GetStatus(@ptrCast(*const ITfFnPropertyUIStatus, self), refguidProp, pdw); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnPropertyUIStatus_SetStatus(self: *const T, refguidProp: ?*const Guid, dw: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnPropertyUIStatus.VTable, self.vtable).SetStatus(@ptrCast(*const ITfFnPropertyUIStatus, self), refguidProp, dw); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IEnumSpeechCommands_Value = Guid.initString("8c5dac4f-083c-4b85-a4c9-71746048adca"); pub const IID_IEnumSpeechCommands = &IID_IEnumSpeechCommands_Value; pub const IEnumSpeechCommands = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumSpeechCommands, ppEnum: ?*?*IEnumSpeechCommands, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumSpeechCommands, ulCount: u32, pSpCmds: [*]?*u16, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumSpeechCommands, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumSpeechCommands, ulCount: 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 IEnumSpeechCommands_Clone(self: *const T, ppEnum: ?*?*IEnumSpeechCommands) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumSpeechCommands.VTable, self.vtable).Clone(@ptrCast(*const IEnumSpeechCommands, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumSpeechCommands_Next(self: *const T, ulCount: u32, pSpCmds: [*]?*u16, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumSpeechCommands.VTable, self.vtable).Next(@ptrCast(*const IEnumSpeechCommands, self), ulCount, pSpCmds, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumSpeechCommands_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumSpeechCommands.VTable, self.vtable).Reset(@ptrCast(*const IEnumSpeechCommands, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumSpeechCommands_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumSpeechCommands.VTable, self.vtable).Skip(@ptrCast(*const IEnumSpeechCommands, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ISpeechCommandProvider_Value = Guid.initString("38e09d4c-586d-435a-b592-c8a86691dec6"); pub const IID_ISpeechCommandProvider = &IID_ISpeechCommandProvider_Value; pub const ISpeechCommandProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumSpeechCommands: fn( self: *const ISpeechCommandProvider, langid: u16, ppEnum: ?*?*IEnumSpeechCommands, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessCommand: fn( self: *const ISpeechCommandProvider, pszCommand: [*:0]const u16, cch: u32, langid: 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 ISpeechCommandProvider_EnumSpeechCommands(self: *const T, langid: u16, ppEnum: ?*?*IEnumSpeechCommands) callconv(.Inline) HRESULT { return @ptrCast(*const ISpeechCommandProvider.VTable, self.vtable).EnumSpeechCommands(@ptrCast(*const ISpeechCommandProvider, self), langid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ISpeechCommandProvider_ProcessCommand(self: *const T, pszCommand: [*:0]const u16, cch: u32, langid: u16) callconv(.Inline) HRESULT { return @ptrCast(*const ISpeechCommandProvider.VTable, self.vtable).ProcessCommand(@ptrCast(*const ISpeechCommandProvider, self), pszCommand, cch, langid); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITfFnCustomSpeechCommand_Value = Guid.initString("fca6c349-a12f-43a3-8dd6-5a5a4282577b"); pub const IID_ITfFnCustomSpeechCommand = &IID_ITfFnCustomSpeechCommand_Value; pub const ITfFnCustomSpeechCommand = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, SetSpeechCommandProvider: fn( self: *const ITfFnCustomSpeechCommand, pspcmdProvider: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnCustomSpeechCommand_SetSpeechCommandProvider(self: *const T, pspcmdProvider: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnCustomSpeechCommand.VTable, self.vtable).SetSpeechCommandProvider(@ptrCast(*const ITfFnCustomSpeechCommand, self), pspcmdProvider); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnLMProcessor_Value = Guid.initString("7afbf8e7-ac4b-4082-b058-890899d3a010"); pub const IID_ITfFnLMProcessor = &IID_ITfFnLMProcessor_Value; pub const ITfFnLMProcessor = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, QueryRange: fn( self: *const ITfFnLMProcessor, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfAccepted: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryLangID: fn( self: *const ITfFnLMProcessor, langid: u16, pfAccepted: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReconversion: fn( self: *const ITfFnLMProcessor, pRange: ?*ITfRange, ppCandList: ?*?*ITfCandidateList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reconvert: fn( self: *const ITfFnLMProcessor, pRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryKey: fn( self: *const ITfFnLMProcessor, fUp: BOOL, vKey: WPARAM, lparamKeydata: LPARAM, pfInterested: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeKey: fn( self: *const ITfFnLMProcessor, fUp: BOOL, vKey: WPARAM, lparamKeyData: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeFunc: fn( self: *const ITfFnLMProcessor, pic: ?*ITfContext, refguidFunc: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_QueryRange(self: *const T, pRange: ?*ITfRange, ppNewRange: ?*?*ITfRange, pfAccepted: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).QueryRange(@ptrCast(*const ITfFnLMProcessor, self), pRange, ppNewRange, pfAccepted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_QueryLangID(self: *const T, langid: u16, pfAccepted: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).QueryLangID(@ptrCast(*const ITfFnLMProcessor, self), langid, pfAccepted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_GetReconversion(self: *const T, pRange: ?*ITfRange, ppCandList: ?*?*ITfCandidateList) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).GetReconversion(@ptrCast(*const ITfFnLMProcessor, self), pRange, ppCandList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_Reconvert(self: *const T, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).Reconvert(@ptrCast(*const ITfFnLMProcessor, self), pRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_QueryKey(self: *const T, fUp: BOOL, vKey: WPARAM, lparamKeydata: LPARAM, pfInterested: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).QueryKey(@ptrCast(*const ITfFnLMProcessor, self), fUp, vKey, lparamKeydata, pfInterested); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_InvokeKey(self: *const T, fUp: BOOL, vKey: WPARAM, lparamKeyData: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).InvokeKey(@ptrCast(*const ITfFnLMProcessor, self), fUp, vKey, lparamKeyData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMProcessor_InvokeFunc(self: *const T, pic: ?*ITfContext, refguidFunc: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMProcessor.VTable, self.vtable).InvokeFunc(@ptrCast(*const ITfFnLMProcessor, self), pic, refguidFunc); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnLMInternal_Value = Guid.initString("04b825b1-ac9a-4f7b-b5ad-c7168f1ee445"); pub const IID_ITfFnLMInternal = &IID_ITfFnLMInternal_Value; pub const ITfFnLMInternal = extern struct { pub const VTable = extern struct { base: ITfFnLMProcessor.VTable, ProcessLattice: fn( self: *const ITfFnLMInternal, pRange: ?*ITfRange, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFnLMProcessor.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnLMInternal_ProcessLattice(self: *const T, pRange: ?*ITfRange) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnLMInternal.VTable, self.vtable).ProcessLattice(@ptrCast(*const ITfFnLMInternal, self), pRange); } };} pub usingnamespace MethodMixin(@This()); }; pub const TF_LMLATTELEMENT = extern struct { dwFrameStart: u32, dwFrameLen: u32, dwFlags: u32, Anonymous: extern union { iCost: i32, }, bstrText: ?BSTR, }; // TODO: this type is limited to platform 'windows5.0' const IID_IEnumTfLatticeElements_Value = Guid.initString("56988052-47da-4a05-911a-e3d941f17145"); pub const IID_IEnumTfLatticeElements = &IID_IEnumTfLatticeElements_Value; pub const IEnumTfLatticeElements = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const IEnumTfLatticeElements, ppEnum: ?*?*IEnumTfLatticeElements, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IEnumTfLatticeElements, ulCount: u32, rgsElements: [*]TF_LMLATTELEMENT, pcFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumTfLatticeElements, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumTfLatticeElements, ulCount: 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 IEnumTfLatticeElements_Clone(self: *const T, ppEnum: ?*?*IEnumTfLatticeElements) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLatticeElements.VTable, self.vtable).Clone(@ptrCast(*const IEnumTfLatticeElements, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLatticeElements_Next(self: *const T, ulCount: u32, rgsElements: [*]TF_LMLATTELEMENT, pcFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLatticeElements.VTable, self.vtable).Next(@ptrCast(*const IEnumTfLatticeElements, self), ulCount, rgsElements, pcFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLatticeElements_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLatticeElements.VTable, self.vtable).Reset(@ptrCast(*const IEnumTfLatticeElements, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumTfLatticeElements_Skip(self: *const T, ulCount: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumTfLatticeElements.VTable, self.vtable).Skip(@ptrCast(*const IEnumTfLatticeElements, self), ulCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfLMLattice_Value = Guid.initString("d4236675-a5bf-4570-9d42-5d6d7b02d59b"); pub const IID_ITfLMLattice = &IID_ITfLMLattice_Value; pub const ITfLMLattice = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryType: fn( self: *const ITfLMLattice, rguidType: ?*const Guid, pfSupported: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumLatticeElements: fn( self: *const ITfLMLattice, dwFrameStart: u32, rguidType: ?*const Guid, ppEnum: ?*?*IEnumTfLatticeElements, ) 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 ITfLMLattice_QueryType(self: *const T, rguidType: ?*const Guid, pfSupported: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLMLattice.VTable, self.vtable).QueryType(@ptrCast(*const ITfLMLattice, self), rguidType, pfSupported); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfLMLattice_EnumLatticeElements(self: *const T, dwFrameStart: u32, rguidType: ?*const Guid, ppEnum: ?*?*IEnumTfLatticeElements) callconv(.Inline) HRESULT { return @ptrCast(*const ITfLMLattice.VTable, self.vtable).EnumLatticeElements(@ptrCast(*const ITfLMLattice, self), dwFrameStart, rguidType, ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfFnAdviseText_Value = Guid.initString("3527268b-7d53-4dd9-92b7-7296ae461249"); pub const IID_ITfFnAdviseText = &IID_ITfFnAdviseText_Value; pub const ITfFnAdviseText = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, OnTextUpdate: fn( self: *const ITfFnAdviseText, pRange: ?*ITfRange, pchText: [*:0]const u16, cch: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnLatticeUpdate: fn( self: *const ITfFnAdviseText, pRange: ?*ITfRange, pLattice: ?*ITfLMLattice, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnAdviseText_OnTextUpdate(self: *const T, pRange: ?*ITfRange, pchText: [*:0]const u16, cch: i32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnAdviseText.VTable, self.vtable).OnTextUpdate(@ptrCast(*const ITfFnAdviseText, self), pRange, pchText, cch); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnAdviseText_OnLatticeUpdate(self: *const T, pRange: ?*ITfRange, pLattice: ?*ITfLMLattice) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnAdviseText.VTable, self.vtable).OnLatticeUpdate(@ptrCast(*const ITfFnAdviseText, self), pRange, pLattice); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_ITfFnSearchCandidateProvider_Value = Guid.initString("87a2ad8f-f27b-4920-8501-67602280175d"); pub const IID_ITfFnSearchCandidateProvider = &IID_ITfFnSearchCandidateProvider_Value; pub const ITfFnSearchCandidateProvider = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, GetSearchCandidates: fn( self: *const ITfFnSearchCandidateProvider, bstrQuery: ?BSTR, bstrApplicationId: ?BSTR, pplist: ?*?*ITfCandidateList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetResult: fn( self: *const ITfFnSearchCandidateProvider, bstrQuery: ?BSTR, bstrApplicationID: ?BSTR, bstrResult: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnSearchCandidateProvider_GetSearchCandidates(self: *const T, bstrQuery: ?BSTR, bstrApplicationId: ?BSTR, pplist: ?*?*ITfCandidateList) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnSearchCandidateProvider.VTable, self.vtable).GetSearchCandidates(@ptrCast(*const ITfFnSearchCandidateProvider, self), bstrQuery, bstrApplicationId, pplist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnSearchCandidateProvider_SetResult(self: *const T, bstrQuery: ?BSTR, bstrApplicationID: ?BSTR, bstrResult: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnSearchCandidateProvider.VTable, self.vtable).SetResult(@ptrCast(*const ITfFnSearchCandidateProvider, self), bstrQuery, bstrApplicationID, bstrResult); } };} pub usingnamespace MethodMixin(@This()); }; pub const TfIntegratableCandidateListSelectionStyle = enum(i32) { ACTIVE_SELECTION = 0, IMPLIED_SELECTION = 1, }; pub const STYLE_ACTIVE_SELECTION = TfIntegratableCandidateListSelectionStyle.ACTIVE_SELECTION; pub const STYLE_IMPLIED_SELECTION = TfIntegratableCandidateListSelectionStyle.IMPLIED_SELECTION; // TODO: this type is limited to platform 'windows8.0' const IID_ITfIntegratableCandidateListUIElement_Value = Guid.initString("c7a6f54f-b180-416f-b2bf-7bf2e4683d7b"); pub const IID_ITfIntegratableCandidateListUIElement = &IID_ITfIntegratableCandidateListUIElement_Value; pub const ITfIntegratableCandidateListUIElement = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetIntegrationStyle: fn( self: *const ITfIntegratableCandidateListUIElement, guidIntegrationStyle: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelectionStyle: fn( self: *const ITfIntegratableCandidateListUIElement, ptfSelectionStyle: ?*TfIntegratableCandidateListSelectionStyle, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnKeyDown: fn( self: *const ITfIntegratableCandidateListUIElement, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowCandidateNumbers: fn( self: *const ITfIntegratableCandidateListUIElement, pfShow: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FinalizeExactCompositionString: fn( self: *const ITfIntegratableCandidateListUIElement, ) 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 ITfIntegratableCandidateListUIElement_SetIntegrationStyle(self: *const T, guidIntegrationStyle: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITfIntegratableCandidateListUIElement.VTable, self.vtable).SetIntegrationStyle(@ptrCast(*const ITfIntegratableCandidateListUIElement, self), guidIntegrationStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfIntegratableCandidateListUIElement_GetSelectionStyle(self: *const T, ptfSelectionStyle: ?*TfIntegratableCandidateListSelectionStyle) callconv(.Inline) HRESULT { return @ptrCast(*const ITfIntegratableCandidateListUIElement.VTable, self.vtable).GetSelectionStyle(@ptrCast(*const ITfIntegratableCandidateListUIElement, self), ptfSelectionStyle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfIntegratableCandidateListUIElement_OnKeyDown(self: *const T, wParam: WPARAM, lParam: LPARAM, pfEaten: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfIntegratableCandidateListUIElement.VTable, self.vtable).OnKeyDown(@ptrCast(*const ITfIntegratableCandidateListUIElement, self), wParam, lParam, pfEaten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfIntegratableCandidateListUIElement_ShowCandidateNumbers(self: *const T, pfShow: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfIntegratableCandidateListUIElement.VTable, self.vtable).ShowCandidateNumbers(@ptrCast(*const ITfIntegratableCandidateListUIElement, self), pfShow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfIntegratableCandidateListUIElement_FinalizeExactCompositionString(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfIntegratableCandidateListUIElement.VTable, self.vtable).FinalizeExactCompositionString(@ptrCast(*const ITfIntegratableCandidateListUIElement, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const TKBLayoutType = enum(i32) { UNDEFINED = 0, CLASSIC = 1, OPTIMIZED = 2, }; pub const TKBLT_UNDEFINED = TKBLayoutType.UNDEFINED; pub const TKBLT_CLASSIC = TKBLayoutType.CLASSIC; pub const TKBLT_OPTIMIZED = TKBLayoutType.OPTIMIZED; // TODO: this type is limited to platform 'windows8.0' const IID_ITfFnGetPreferredTouchKeyboardLayout_Value = Guid.initString("5f309a41-590a-4acc-a97f-d8efff13fdfc"); pub const IID_ITfFnGetPreferredTouchKeyboardLayout = &IID_ITfFnGetPreferredTouchKeyboardLayout_Value; pub const ITfFnGetPreferredTouchKeyboardLayout = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, GetLayout: fn( self: *const ITfFnGetPreferredTouchKeyboardLayout, pTKBLayoutType: ?*TKBLayoutType, pwPreferredLayoutId: ?*u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnGetPreferredTouchKeyboardLayout_GetLayout(self: *const T, pTKBLayoutType: ?*TKBLayoutType, pwPreferredLayoutId: ?*u16) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnGetPreferredTouchKeyboardLayout.VTable, self.vtable).GetLayout(@ptrCast(*const ITfFnGetPreferredTouchKeyboardLayout, self), pTKBLayoutType, pwPreferredLayoutId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_ITfFnGetLinguisticAlternates_Value = Guid.initString("ea163ce2-7a65-4506-82a3-c528215da64e"); pub const IID_ITfFnGetLinguisticAlternates = &IID_ITfFnGetLinguisticAlternates_Value; pub const ITfFnGetLinguisticAlternates = extern struct { pub const VTable = extern struct { base: ITfFunction.VTable, GetAlternates: fn( self: *const ITfFnGetLinguisticAlternates, pRange: ?*ITfRange, ppCandidateList: ?*?*ITfCandidateList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfFunction.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfFnGetLinguisticAlternates_GetAlternates(self: *const T, pRange: ?*ITfRange, ppCandidateList: ?*?*ITfCandidateList) callconv(.Inline) HRESULT { return @ptrCast(*const ITfFnGetLinguisticAlternates.VTable, self.vtable).GetAlternates(@ptrCast(*const ITfFnGetLinguisticAlternates, self), pRange, ppCandidateList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IUIManagerEventSink_Value = Guid.initString("cd91d690-a7e8-4265-9b38-8bb3bbaba7de"); pub const IID_IUIManagerEventSink = &IID_IUIManagerEventSink_Value; pub const IUIManagerEventSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnWindowOpening: fn( self: *const IUIManagerEventSink, prcBounds: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnWindowOpened: fn( self: *const IUIManagerEventSink, prcBounds: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnWindowUpdating: fn( self: *const IUIManagerEventSink, prcUpdatedBounds: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnWindowUpdated: fn( self: *const IUIManagerEventSink, prcUpdatedBounds: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnWindowClosing: fn( self: *const IUIManagerEventSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnWindowClosed: fn( self: *const IUIManagerEventSink, ) 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 IUIManagerEventSink_OnWindowOpening(self: *const T, prcBounds: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowOpening(@ptrCast(*const IUIManagerEventSink, self), prcBounds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIManagerEventSink_OnWindowOpened(self: *const T, prcBounds: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowOpened(@ptrCast(*const IUIManagerEventSink, self), prcBounds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIManagerEventSink_OnWindowUpdating(self: *const T, prcUpdatedBounds: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowUpdating(@ptrCast(*const IUIManagerEventSink, self), prcUpdatedBounds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIManagerEventSink_OnWindowUpdated(self: *const T, prcUpdatedBounds: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowUpdated(@ptrCast(*const IUIManagerEventSink, self), prcUpdatedBounds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIManagerEventSink_OnWindowClosing(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowClosing(@ptrCast(*const IUIManagerEventSink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIManagerEventSink_OnWindowClosed(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IUIManagerEventSink.VTable, self.vtable).OnWindowClosed(@ptrCast(*const IUIManagerEventSink, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const InputScope = enum(i32) { DEFAULT = 0, URL = 1, FILE_FULLFILEPATH = 2, FILE_FILENAME = 3, EMAIL_USERNAME = 4, EMAIL_SMTPEMAILADDRESS = 5, LOGINNAME = 6, PERSONALNAME_FULLNAME = 7, PERSONALNAME_PREFIX = 8, PERSONALNAME_GIVENNAME = 9, PERSONALNAME_MIDDLENAME = 10, PERSONALNAME_SURNAME = 11, PERSONALNAME_SUFFIX = 12, ADDRESS_FULLPOSTALADDRESS = 13, ADDRESS_POSTALCODE = 14, ADDRESS_STREET = 15, ADDRESS_STATEORPROVINCE = 16, ADDRESS_CITY = 17, ADDRESS_COUNTRYNAME = 18, ADDRESS_COUNTRYSHORTNAME = 19, CURRENCY_AMOUNTANDSYMBOL = 20, CURRENCY_AMOUNT = 21, DATE_FULLDATE = 22, DATE_MONTH = 23, DATE_DAY = 24, DATE_YEAR = 25, DATE_MONTHNAME = 26, DATE_DAYNAME = 27, DIGITS = 28, NUMBER = 29, ONECHAR = 30, PASSWORD = 31, TELEPHONE_FULLTELEPHONENUMBER = 32, TELEPHONE_COUNTRYCODE = 33, TELEPHONE_AREACODE = 34, TELEPHONE_LOCALNUMBER = 35, TIME_FULLTIME = 36, TIME_HOUR = 37, TIME_MINORSEC = 38, NUMBER_FULLWIDTH = 39, ALPHANUMERIC_HALFWIDTH = 40, ALPHANUMERIC_FULLWIDTH = 41, CURRENCY_CHINESE = 42, BOPOMOFO = 43, HIRAGANA = 44, KATAKANA_HALFWIDTH = 45, KATAKANA_FULLWIDTH = 46, HANJA = 47, HANGUL_HALFWIDTH = 48, HANGUL_FULLWIDTH = 49, SEARCH = 50, FORMULA = 51, SEARCH_INCREMENTAL = 52, CHINESE_HALFWIDTH = 53, CHINESE_FULLWIDTH = 54, NATIVE_SCRIPT = 55, YOMI = 56, TEXT = 57, CHAT = 58, NAME_OR_PHONENUMBER = 59, EMAILNAME_OR_ADDRESS = 60, PRIVATE = 61, MAPS = 62, NUMERIC_PASSWORD = 63, NUMERIC_PIN = 64, ALPHANUMERIC_PIN = 65, ALPHANUMERIC_PIN_SET = 66, FORMULA_NUMBER = 67, CHAT_WITHOUT_EMOJI = 68, PHRASELIST = -1, REGULAREXPRESSION = -2, SRGS = -3, XML = -4, ENUMSTRING = -5, }; pub const IS_DEFAULT = InputScope.DEFAULT; pub const IS_URL = InputScope.URL; pub const IS_FILE_FULLFILEPATH = InputScope.FILE_FULLFILEPATH; pub const IS_FILE_FILENAME = InputScope.FILE_FILENAME; pub const IS_EMAIL_USERNAME = InputScope.EMAIL_USERNAME; pub const IS_EMAIL_SMTPEMAILADDRESS = InputScope.EMAIL_SMTPEMAILADDRESS; pub const IS_LOGINNAME = InputScope.LOGINNAME; pub const IS_PERSONALNAME_FULLNAME = InputScope.PERSONALNAME_FULLNAME; pub const IS_PERSONALNAME_PREFIX = InputScope.PERSONALNAME_PREFIX; pub const IS_PERSONALNAME_GIVENNAME = InputScope.PERSONALNAME_GIVENNAME; pub const IS_PERSONALNAME_MIDDLENAME = InputScope.PERSONALNAME_MIDDLENAME; pub const IS_PERSONALNAME_SURNAME = InputScope.PERSONALNAME_SURNAME; pub const IS_PERSONALNAME_SUFFIX = InputScope.PERSONALNAME_SUFFIX; pub const IS_ADDRESS_FULLPOSTALADDRESS = InputScope.ADDRESS_FULLPOSTALADDRESS; pub const IS_ADDRESS_POSTALCODE = InputScope.ADDRESS_POSTALCODE; pub const IS_ADDRESS_STREET = InputScope.ADDRESS_STREET; pub const IS_ADDRESS_STATEORPROVINCE = InputScope.ADDRESS_STATEORPROVINCE; pub const IS_ADDRESS_CITY = InputScope.ADDRESS_CITY; pub const IS_ADDRESS_COUNTRYNAME = InputScope.ADDRESS_COUNTRYNAME; pub const IS_ADDRESS_COUNTRYSHORTNAME = InputScope.ADDRESS_COUNTRYSHORTNAME; pub const IS_CURRENCY_AMOUNTANDSYMBOL = InputScope.CURRENCY_AMOUNTANDSYMBOL; pub const IS_CURRENCY_AMOUNT = InputScope.CURRENCY_AMOUNT; pub const IS_DATE_FULLDATE = InputScope.DATE_FULLDATE; pub const IS_DATE_MONTH = InputScope.DATE_MONTH; pub const IS_DATE_DAY = InputScope.DATE_DAY; pub const IS_DATE_YEAR = InputScope.DATE_YEAR; pub const IS_DATE_MONTHNAME = InputScope.DATE_MONTHNAME; pub const IS_DATE_DAYNAME = InputScope.DATE_DAYNAME; pub const IS_DIGITS = InputScope.DIGITS; pub const IS_NUMBER = InputScope.NUMBER; pub const IS_ONECHAR = InputScope.ONECHAR; pub const IS_PASSWORD = InputScope.PASSWORD; pub const IS_TELEPHONE_FULLTELEPHONENUMBER = InputScope.TELEPHONE_FULLTELEPHONENUMBER; pub const IS_TELEPHONE_COUNTRYCODE = InputScope.TELEPHONE_COUNTRYCODE; pub const IS_TELEPHONE_AREACODE = InputScope.TELEPHONE_AREACODE; pub const IS_TELEPHONE_LOCALNUMBER = InputScope.TELEPHONE_LOCALNUMBER; pub const IS_TIME_FULLTIME = InputScope.TIME_FULLTIME; pub const IS_TIME_HOUR = InputScope.TIME_HOUR; pub const IS_TIME_MINORSEC = InputScope.TIME_MINORSEC; pub const IS_NUMBER_FULLWIDTH = InputScope.NUMBER_FULLWIDTH; pub const IS_ALPHANUMERIC_HALFWIDTH = InputScope.ALPHANUMERIC_HALFWIDTH; pub const IS_ALPHANUMERIC_FULLWIDTH = InputScope.ALPHANUMERIC_FULLWIDTH; pub const IS_CURRENCY_CHINESE = InputScope.CURRENCY_CHINESE; pub const IS_BOPOMOFO = InputScope.BOPOMOFO; pub const IS_HIRAGANA = InputScope.HIRAGANA; pub const IS_KATAKANA_HALFWIDTH = InputScope.KATAKANA_HALFWIDTH; pub const IS_KATAKANA_FULLWIDTH = InputScope.KATAKANA_FULLWIDTH; pub const IS_HANJA = InputScope.HANJA; pub const IS_HANGUL_HALFWIDTH = InputScope.HANGUL_HALFWIDTH; pub const IS_HANGUL_FULLWIDTH = InputScope.HANGUL_FULLWIDTH; pub const IS_SEARCH = InputScope.SEARCH; pub const IS_FORMULA = InputScope.FORMULA; pub const IS_SEARCH_INCREMENTAL = InputScope.SEARCH_INCREMENTAL; pub const IS_CHINESE_HALFWIDTH = InputScope.CHINESE_HALFWIDTH; pub const IS_CHINESE_FULLWIDTH = InputScope.CHINESE_FULLWIDTH; pub const IS_NATIVE_SCRIPT = InputScope.NATIVE_SCRIPT; pub const IS_YOMI = InputScope.YOMI; pub const IS_TEXT = InputScope.TEXT; pub const IS_CHAT = InputScope.CHAT; pub const IS_NAME_OR_PHONENUMBER = InputScope.NAME_OR_PHONENUMBER; pub const IS_EMAILNAME_OR_ADDRESS = InputScope.EMAILNAME_OR_ADDRESS; pub const IS_PRIVATE = InputScope.PRIVATE; pub const IS_MAPS = InputScope.MAPS; pub const IS_NUMERIC_PASSWORD = InputScope.NUMERIC_PASSWORD; pub const IS_NUMERIC_PIN = InputScope.NUMERIC_PIN; pub const IS_ALPHANUMERIC_PIN = InputScope.ALPHANUMERIC_PIN; pub const IS_ALPHANUMERIC_PIN_SET = InputScope.ALPHANUMERIC_PIN_SET; pub const IS_FORMULA_NUMBER = InputScope.FORMULA_NUMBER; pub const IS_CHAT_WITHOUT_EMOJI = InputScope.CHAT_WITHOUT_EMOJI; pub const IS_PHRASELIST = InputScope.PHRASELIST; pub const IS_REGULAREXPRESSION = InputScope.REGULAREXPRESSION; pub const IS_SRGS = InputScope.SRGS; pub const IS_XML = InputScope.XML; pub const IS_ENUMSTRING = InputScope.ENUMSTRING; // TODO: this type is limited to platform 'windows5.1.2600' const IID_ITfInputScope_Value = Guid.initString("fde1eaee-6924-4cdf-91e7-da38cff5559d"); pub const IID_ITfInputScope = &IID_ITfInputScope_Value; pub const ITfInputScope = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInputScopes: fn( self: *const ITfInputScope, pprgInputScopes: [*]?*InputScope, pcCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPhrase: fn( self: *const ITfInputScope, ppbstrPhrases: [*]?*?BSTR, pcCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegularExpression: fn( self: *const ITfInputScope, pbstrRegExp: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSRGS: fn( self: *const ITfInputScope, pbstrSRGS: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXML: fn( self: *const ITfInputScope, pbstrXML: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope_GetInputScopes(self: *const T, pprgInputScopes: [*]?*InputScope, pcCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope.VTable, self.vtable).GetInputScopes(@ptrCast(*const ITfInputScope, self), pprgInputScopes, pcCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope_GetPhrase(self: *const T, ppbstrPhrases: [*]?*?BSTR, pcCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope.VTable, self.vtable).GetPhrase(@ptrCast(*const ITfInputScope, self), ppbstrPhrases, pcCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope_GetRegularExpression(self: *const T, pbstrRegExp: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope.VTable, self.vtable).GetRegularExpression(@ptrCast(*const ITfInputScope, self), pbstrRegExp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope_GetSRGS(self: *const T, pbstrSRGS: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope.VTable, self.vtable).GetSRGS(@ptrCast(*const ITfInputScope, self), pbstrSRGS); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope_GetXML(self: *const T, pbstrXML: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope.VTable, self.vtable).GetXML(@ptrCast(*const ITfInputScope, self), pbstrXML); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_ITfInputScope2_Value = Guid.initString("5731eaa0-6bc2-4681-a532-92fbb74d7c41"); pub const IID_ITfInputScope2 = &IID_ITfInputScope2_Value; pub const ITfInputScope2 = extern struct { pub const VTable = extern struct { base: ITfInputScope.VTable, EnumWordList: fn( self: *const ITfInputScope2, ppEnumString: ?*?*IEnumString, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITfInputScope.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfInputScope2_EnumWordList(self: *const T, ppEnumString: ?*?*IEnumString) callconv(.Inline) HRESULT { return @ptrCast(*const ITfInputScope2.VTable, self.vtable).EnumWordList(@ptrCast(*const ITfInputScope2, self), ppEnumString); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_MSAAControl_Value = Guid.initString("08cd963f-7a3e-4f5c-9bd8-d692bb043c5b"); pub const CLSID_MSAAControl = &CLSID_MSAAControl_Value; const CLSID_AccStore_Value = Guid.initString("5440837f-4bff-4ae5-a1b1-7722ecc6332a"); pub const CLSID_AccStore = &CLSID_AccStore_Value; const CLSID_AccDictionary_Value = Guid.initString("6572ee16-5fe5-4331-bb6d-76a49c56e423"); pub const CLSID_AccDictionary = &CLSID_AccDictionary_Value; const CLSID_AccServerDocMgr_Value = Guid.initString("6089a37e-eb8a-482d-bd6f-f9f46904d16d"); pub const CLSID_AccServerDocMgr = &CLSID_AccServerDocMgr_Value; const CLSID_AccClientDocMgr_Value = Guid.initString("fc48cc30-4f3e-4fa1-803b-ad0e196a83b1"); pub const CLSID_AccClientDocMgr = &CLSID_AccClientDocMgr_Value; const CLSID_DocWrap_Value = Guid.initString("bf426f7e-7a5e-44d6-830c-a390ea9462a3"); pub const CLSID_DocWrap = &CLSID_DocWrap_Value; // TODO: this type is limited to platform 'windows5.0' const IID_ITfMSAAControl_Value = Guid.initString("b5f8fb3b-393f-4f7c-84cb-504924c2705a"); pub const IID_ITfMSAAControl = &IID_ITfMSAAControl_Value; pub const ITfMSAAControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SystemEnableMSAA: fn( self: *const ITfMSAAControl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SystemDisableMSAA: fn( self: *const ITfMSAAControl, ) 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 ITfMSAAControl_SystemEnableMSAA(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMSAAControl.VTable, self.vtable).SystemEnableMSAA(@ptrCast(*const ITfMSAAControl, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfMSAAControl_SystemDisableMSAA(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfMSAAControl.VTable, self.vtable).SystemDisableMSAA(@ptrCast(*const ITfMSAAControl, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IInternalDocWrap_Value = Guid.initString("e1aa6466-9db4-40ba-be03-77c38e8e60b2"); pub const IID_IInternalDocWrap = &IID_IInternalDocWrap_Value; pub const IInternalDocWrap = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NotifyRevoke: fn( self: *const IInternalDocWrap, ) 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 IInternalDocWrap_NotifyRevoke(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IInternalDocWrap.VTable, self.vtable).NotifyRevoke(@ptrCast(*const IInternalDocWrap, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITextStoreACPEx_Value = Guid.initString("a2de3bc2-3d8e-11d3-81a9-f753fbe61a00"); pub const IID_ITextStoreACPEx = &IID_ITextStoreACPEx_Value; pub const ITextStoreACPEx = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ScrollToRect: fn( self: *const ITextStoreACPEx, acpStart: i32, acpEnd: i32, rc: RECT, dwPosition: 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 ITextStoreACPEx_ScrollToRect(self: *const T, acpStart: i32, acpEnd: i32, rc: RECT, dwPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPEx.VTable, self.vtable).ScrollToRect(@ptrCast(*const ITextStoreACPEx, self), acpStart, acpEnd, rc, dwPosition); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITextStoreAnchorEx_Value = Guid.initString("a2de3bc1-3d8e-11d3-81a9-f753fbe61a00"); pub const IID_ITextStoreAnchorEx = &IID_ITextStoreAnchorEx_Value; pub const ITextStoreAnchorEx = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ScrollToRect: fn( self: *const ITextStoreAnchorEx, pStart: ?*IAnchor, pEnd: ?*IAnchor, rc: RECT, dwPosition: 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 ITextStoreAnchorEx_ScrollToRect(self: *const T, pStart: ?*IAnchor, pEnd: ?*IAnchor, rc: RECT, dwPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreAnchorEx.VTable, self.vtable).ScrollToRect(@ptrCast(*const ITextStoreAnchorEx, self), pStart, pEnd, rc, dwPosition); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITextStoreACPSinkEx_Value = Guid.initString("2bdf9464-41e2-43e3-950c-a6865ba25cd4"); pub const IID_ITextStoreACPSinkEx = &IID_ITextStoreACPSinkEx_Value; pub const ITextStoreACPSinkEx = extern struct { pub const VTable = extern struct { base: ITextStoreACPSink.VTable, OnDisconnect: fn( self: *const ITextStoreACPSinkEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITextStoreACPSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreACPSinkEx_OnDisconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreACPSinkEx.VTable, self.vtable).OnDisconnect(@ptrCast(*const ITextStoreACPSinkEx, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_ITextStoreSinkAnchorEx_Value = Guid.initString("25642426-028d-4474-977b-111bb114fe3e"); pub const IID_ITextStoreSinkAnchorEx = &IID_ITextStoreSinkAnchorEx_Value; pub const ITextStoreSinkAnchorEx = extern struct { pub const VTable = extern struct { base: ITextStoreAnchorSink.VTable, OnDisconnect: fn( self: *const ITextStoreSinkAnchorEx, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITextStoreAnchorSink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITextStoreSinkAnchorEx_OnDisconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITextStoreSinkAnchorEx.VTable, self.vtable).OnDisconnect(@ptrCast(*const ITextStoreSinkAnchorEx, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IAccDictionary_Value = Guid.initString("1dc4cb5f-d737-474d-ade9-5ccfc9bc1cc9"); pub const IID_IAccDictionary = &IID_IAccDictionary_Value; pub const IAccDictionary = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLocalizedString: fn( self: *const IAccDictionary, Term: ?*const Guid, lcid: u32, pResult: ?*?BSTR, plcid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetParentTerm: fn( self: *const IAccDictionary, Term: ?*const Guid, pParentTerm: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMnemonicString: fn( self: *const IAccDictionary, Term: ?*const Guid, pResult: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupMnemonicTerm: fn( self: *const IAccDictionary, bstrMnemonic: ?BSTR, pTerm: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertValueToString: fn( self: *const IAccDictionary, Term: ?*const Guid, lcid: u32, varValue: VARIANT, pbstrResult: ?*?BSTR, plcid: ?*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 IAccDictionary_GetLocalizedString(self: *const T, Term: ?*const Guid, lcid: u32, pResult: ?*?BSTR, plcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAccDictionary.VTable, self.vtable).GetLocalizedString(@ptrCast(*const IAccDictionary, self), Term, lcid, pResult, plcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccDictionary_GetParentTerm(self: *const T, Term: ?*const Guid, pParentTerm: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IAccDictionary.VTable, self.vtable).GetParentTerm(@ptrCast(*const IAccDictionary, self), Term, pParentTerm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccDictionary_GetMnemonicString(self: *const T, Term: ?*const Guid, pResult: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IAccDictionary.VTable, self.vtable).GetMnemonicString(@ptrCast(*const IAccDictionary, self), Term, pResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccDictionary_LookupMnemonicTerm(self: *const T, bstrMnemonic: ?BSTR, pTerm: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IAccDictionary.VTable, self.vtable).LookupMnemonicTerm(@ptrCast(*const IAccDictionary, self), bstrMnemonic, pTerm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccDictionary_ConvertValueToString(self: *const T, Term: ?*const Guid, lcid: u32, varValue: VARIANT, pbstrResult: ?*?BSTR, plcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAccDictionary.VTable, self.vtable).ConvertValueToString(@ptrCast(*const IAccDictionary, self), Term, lcid, varValue, pbstrResult, plcid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IVersionInfo_Value = Guid.initString("401518ec-db00-4611-9b29-2a0e4b9afa85"); pub const IID_IVersionInfo = &IID_IVersionInfo_Value; pub const IVersionInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSubcomponentCount: fn( self: *const IVersionInfo, ulSub: u32, ulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetImplementationID: fn( self: *const IVersionInfo, ulSub: u32, implid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBuildVersion: fn( self: *const IVersionInfo, ulSub: u32, pdwMajor: ?*u32, pdwMinor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetComponentDescription: fn( self: *const IVersionInfo, ulSub: u32, pImplStr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInstanceDescription: fn( self: *const IVersionInfo, ulSub: u32, pImplStr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVersionInfo_GetSubcomponentCount(self: *const T, ulSub: u32, ulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IVersionInfo.VTable, self.vtable).GetSubcomponentCount(@ptrCast(*const IVersionInfo, self), ulSub, ulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVersionInfo_GetImplementationID(self: *const T, ulSub: u32, implid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IVersionInfo.VTable, self.vtable).GetImplementationID(@ptrCast(*const IVersionInfo, self), ulSub, implid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVersionInfo_GetBuildVersion(self: *const T, ulSub: u32, pdwMajor: ?*u32, pdwMinor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IVersionInfo.VTable, self.vtable).GetBuildVersion(@ptrCast(*const IVersionInfo, self), ulSub, pdwMajor, pdwMinor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVersionInfo_GetComponentDescription(self: *const T, ulSub: u32, pImplStr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IVersionInfo.VTable, self.vtable).GetComponentDescription(@ptrCast(*const IVersionInfo, self), ulSub, pImplStr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IVersionInfo_GetInstanceDescription(self: *const T, ulSub: u32, pImplStr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IVersionInfo.VTable, self.vtable).GetInstanceDescription(@ptrCast(*const IVersionInfo, self), ulSub, pImplStr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_ICoCreateLocally_Value = Guid.initString("03de00aa-f272-41e3-99cb-03c5e8114ea0"); pub const IID_ICoCreateLocally = &IID_ICoCreateLocally_Value; pub const ICoCreateLocally = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CoCreateLocally: fn( self: *const ICoCreateLocally, rclsid: ?*const Guid, dwClsContext: u32, riid: ?*const Guid, punk: ?*?*IUnknown, riidParam: ?*const Guid, punkParam: ?*IUnknown, varParam: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICoCreateLocally_CoCreateLocally(self: *const T, rclsid: ?*const Guid, dwClsContext: u32, riid: ?*const Guid, punk: ?*?*IUnknown, riidParam: ?*const Guid, punkParam: ?*IUnknown, varParam: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICoCreateLocally.VTable, self.vtable).CoCreateLocally(@ptrCast(*const ICoCreateLocally, self), rclsid, dwClsContext, riid, punk, riidParam, punkParam, varParam); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_ICoCreatedLocally_Value = Guid.initString("0a53eb6c-1908-4742-8cff-2cee2e93f94c"); pub const IID_ICoCreatedLocally = &IID_ICoCreatedLocally_Value; pub const ICoCreatedLocally = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, LocalInit: fn( self: *const ICoCreatedLocally, punkLocalObject: ?*IUnknown, riidParam: ?*const Guid, punkParam: ?*IUnknown, varParam: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICoCreatedLocally_LocalInit(self: *const T, punkLocalObject: ?*IUnknown, riidParam: ?*const Guid, punkParam: ?*IUnknown, varParam: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ICoCreatedLocally.VTable, self.vtable).LocalInit(@ptrCast(*const ICoCreatedLocally, self), punkLocalObject, riidParam, punkParam, varParam); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IAccStore_Value = Guid.initString("e2cd4a63-2b72-4d48-b739-95e4765195ba"); pub const IID_IAccStore = &IID_IAccStore_Value; pub const IAccStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Register: fn( self: *const IAccStore, riid: ?*const Guid, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unregister: fn( self: *const IAccStore, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDocuments: fn( self: *const IAccStore, enumUnknown: ?*?*IEnumUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupByHWND: fn( self: *const IAccStore, hWnd: ?HWND, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupByPoint: fn( self: *const IAccStore, pt: POINT, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDocumentFocus: fn( self: *const IAccStore, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFocused: fn( self: *const IAccStore, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_Register(self: *const T, riid: ?*const Guid, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).Register(@ptrCast(*const IAccStore, self), riid, punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_Unregister(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).Unregister(@ptrCast(*const IAccStore, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_GetDocuments(self: *const T, enumUnknown: ?*?*IEnumUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).GetDocuments(@ptrCast(*const IAccStore, self), enumUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_LookupByHWND(self: *const T, hWnd: ?HWND, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).LookupByHWND(@ptrCast(*const IAccStore, self), hWnd, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_LookupByPoint(self: *const T, pt: POINT, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).LookupByPoint(@ptrCast(*const IAccStore, self), pt, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_OnDocumentFocus(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).OnDocumentFocus(@ptrCast(*const IAccStore, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccStore_GetFocused(self: *const T, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccStore.VTable, self.vtable).GetFocused(@ptrCast(*const IAccStore, self), riid, ppunk); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IAccServerDocMgr_Value = Guid.initString("ad7c73cf-6dd5-4855-abc2-b04bad5b9153"); pub const IID_IAccServerDocMgr = &IID_IAccServerDocMgr_Value; pub const IAccServerDocMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NewDocument: fn( self: *const IAccServerDocMgr, riid: ?*const Guid, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RevokeDocument: fn( self: *const IAccServerDocMgr, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDocumentFocus: fn( self: *const IAccServerDocMgr, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccServerDocMgr_NewDocument(self: *const T, riid: ?*const Guid, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccServerDocMgr.VTable, self.vtable).NewDocument(@ptrCast(*const IAccServerDocMgr, self), riid, punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccServerDocMgr_RevokeDocument(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccServerDocMgr.VTable, self.vtable).RevokeDocument(@ptrCast(*const IAccServerDocMgr, self), punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccServerDocMgr_OnDocumentFocus(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccServerDocMgr.VTable, self.vtable).OnDocumentFocus(@ptrCast(*const IAccServerDocMgr, self), punk); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.1.2600' const IID_IAccClientDocMgr_Value = Guid.initString("4c896039-7b6d-49e6-a8c1-45116a98292b"); pub const IID_IAccClientDocMgr = &IID_IAccClientDocMgr_Value; pub const IAccClientDocMgr = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDocuments: fn( self: *const IAccClientDocMgr, enumUnknown: ?*?*IEnumUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupByHWND: fn( self: *const IAccClientDocMgr, hWnd: ?HWND, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LookupByPoint: fn( self: *const IAccClientDocMgr, pt: POINT, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFocused: fn( self: *const IAccClientDocMgr, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccClientDocMgr_GetDocuments(self: *const T, enumUnknown: ?*?*IEnumUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccClientDocMgr.VTable, self.vtable).GetDocuments(@ptrCast(*const IAccClientDocMgr, self), enumUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccClientDocMgr_LookupByHWND(self: *const T, hWnd: ?HWND, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccClientDocMgr.VTable, self.vtable).LookupByHWND(@ptrCast(*const IAccClientDocMgr, self), hWnd, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccClientDocMgr_LookupByPoint(self: *const T, pt: POINT, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccClientDocMgr.VTable, self.vtable).LookupByPoint(@ptrCast(*const IAccClientDocMgr, self), pt, riid, ppunk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAccClientDocMgr_GetFocused(self: *const T, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IAccClientDocMgr.VTable, self.vtable).GetFocused(@ptrCast(*const IAccClientDocMgr, self), riid, ppunk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDocWrap_Value = Guid.initString("dcd285fe-0be0-43bd-99c9-aaaec513c555"); pub const IID_IDocWrap = &IID_IDocWrap_Value; pub const IDocWrap = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetDoc: fn( self: *const IDocWrap, riid: ?*const Guid, punk: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWrappedDoc: fn( self: *const IDocWrap, riid: ?*const Guid, ppunk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDocWrap_SetDoc(self: *const T, riid: ?*const Guid, punk: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDocWrap.VTable, self.vtable).SetDoc(@ptrCast(*const IDocWrap, self), riid, punk); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDocWrap_GetWrappedDoc(self: *const T, riid: ?*const Guid, ppunk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDocWrap.VTable, self.vtable).GetWrappedDoc(@ptrCast(*const IDocWrap, self), riid, ppunk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IClonableWrapper_Value = Guid.initString("b33e75ff-e84c-4dca-a25c-33b8dc003374"); pub const IID_IClonableWrapper = &IID_IClonableWrapper_Value; pub const IClonableWrapper = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CloneNewWrapper: fn( self: *const IClonableWrapper, riid: ?*const Guid, ppv: ?*?*anyopaque, ) 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 IClonableWrapper_CloneNewWrapper(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IClonableWrapper.VTable, self.vtable).CloneNewWrapper(@ptrCast(*const IClonableWrapper, self), riid, ppv); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows5.0' const IID_ITfSpeechUIServer_Value = Guid.initString("90e9a944-9244-489f-a78f-de67afc013a7"); pub const IID_ITfSpeechUIServer = &IID_ITfSpeechUIServer_Value; pub const ITfSpeechUIServer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const ITfSpeechUIServer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ShowUI: fn( self: *const ITfSpeechUIServer, fShow: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateBalloon: fn( self: *const ITfSpeechUIServer, style: TfLBBalloonStyle, pch: [*:0]const u16, cch: 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 ITfSpeechUIServer_Initialize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSpeechUIServer.VTable, self.vtable).Initialize(@ptrCast(*const ITfSpeechUIServer, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSpeechUIServer_ShowUI(self: *const T, fShow: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSpeechUIServer.VTable, self.vtable).ShowUI(@ptrCast(*const ITfSpeechUIServer, self), fShow); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITfSpeechUIServer_UpdateBalloon(self: *const T, style: TfLBBalloonStyle, pch: [*:0]const u16, cch: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITfSpeechUIServer.VTable, self.vtable).UpdateBalloon(@ptrCast(*const ITfSpeechUIServer, self), style, pch, cch); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (3) //-------------------------------------------------------------------------------- pub extern "MsCtfMonitor" fn DoMsCtfMonitor( dwFlags: u32, hEventForServiceStop: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "MsCtfMonitor" fn InitLocalMsCtfMonitor( dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "MsCtfMonitor" fn UninitLocalMsCtfMonitor( ) 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 (23) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const FORMATETC = @import("../system/com.zig").FORMATETC; const HANDLE = @import("../foundation.zig").HANDLE; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDataObject = @import("../system/com.zig").IDataObject; const IEnumGUID = @import("../system/com.zig").IEnumGUID; const IEnumString = @import("../system/com.zig").IEnumString; const IEnumUnknown = @import("../system/com.zig").IEnumUnknown; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const LPARAM = @import("../foundation.zig").LPARAM; const MSG = @import("../ui/windows_and_messaging.zig").MSG; const POINT = @import("../foundation.zig").POINT; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const SIZE = @import("../foundation.zig").SIZE; const VARIANT = @import("../system/com.zig").VARIANT; const WPARAM = @import("../foundation.zig").WPARAM; 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/ui/text_services.zig
//-------------------------------------------------------------------------------- // Section: Types (1) //-------------------------------------------------------------------------------- pub const NV_MEMORY_RANGE = extern struct { BaseAddress: ?*anyopaque, Length: usize, }; //-------------------------------------------------------------------------------- // Section: Functions (7) //-------------------------------------------------------------------------------- pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlGetNonVolatileToken( // TODO: what to do with BytesParamIndex 1? NvBuffer: ?*anyopaque, Size: usize, NvToken: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlFreeNonVolatileToken( NvToken: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlFlushNonVolatileMemory( NvToken: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? NvBuffer: ?*anyopaque, Size: usize, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlDrainNonVolatileFlush( NvToken: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlWriteNonVolatileMemory( NvToken: ?*anyopaque, // TODO: what to do with BytesParamIndex 3? NvDestination: ?*anyopaque, // TODO: what to do with BytesParamIndex 3? Source: ?*const anyopaque, Size: usize, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlFillNonVolatileMemory( NvToken: ?*anyopaque, // TODO: what to do with BytesParamIndex 2? NvDestination: ?*anyopaque, Size: usize, Value: u8, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; pub usingnamespace switch (@import("../../zig.zig").arch) { .X64, .Arm64 => struct { pub extern "ntdll" fn RtlFlushNonVolatileMemoryRanges( NvToken: ?*anyopaque, NvRanges: [*]NV_MEMORY_RANGE, NumRanges: usize, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; }, else => struct { } }; //-------------------------------------------------------------------------------- // 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 (0) //-------------------------------------------------------------------------------- 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/memory/non_volatile.zig
const std = @import("std"); const builtin = @import("builtin"); const os = std.os; const linux = os.linux; const windows = os.windows; const kernel32 = os.windows.kernel32; const GetConsoleScreenBufferInfo = kernel32.GetConsoleScreenBufferInfo; const GetStdHandle = kernel32.GetStdHandle; const GetLastError = kernel32.GetLastError; fn getWindowSizeLinux(rows: *i32, cols: *i32) !void { var ws: linux.winsize = undefined; var result = linux.ioctl(std.os.STDOUT_FILENO, linux.T.IOCGWINSZ, @ptrToInt(&ws)); while (true) { switch (linux.getErrno(result)) { .SUCCESS => { cols.* = ws.ws_col; rows.* = ws.ws_row; return; }, .BADF => unreachable, .FAULT => unreachable, .INVAL => unreachable, .NOTTY => unreachable, .INTR => continue, // Interrupted function call, try again else => |err| return os.unexpectedErrno(err), } } } fn getWindowSizeWindows(rows: *i32, cols: *i32) !void { var csbi: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined; var maybe_handle = GetStdHandle(windows.STD_OUTPUT_HANDLE); if (maybe_handle) |handle| { if (handle == windows.INVALID_HANDLE_VALUE) { switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return os.windows.unexpectedError(err), } } var r = GetConsoleScreenBufferInfo(handle, &csbi); if (r == 0) { switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return os.windows.unexpectedError(err), } } cols.* = csbi.srWindow.Right - csbi.srWindow.Left; rows.* = csbi.srWindow.Bottom - csbi.srWindow.Top; } else { return error.nullHandle; } } const getWindowSize = switch (builtin.os.tag) { .windows => getWindowSizeWindows, else => getWindowSizeLinux, }; pub fn main() anyerror!void { var rows: i32 = undefined; var cols: i32 = undefined; try getWindowSize(&rows, &cols); const stdout = std.io.getStdOut().writer(); var i: i32 = 0; while (i < rows) : (i += 1) { try stdout.writeAll("\n"); } }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const trait = std.meta.trait; const debug = std.debug; const assert = debug.assert; const Allocator = mem.Allocator; const mem = std.mem; const cleveldb = @cImport({ @cInclude("leveldb/c.h"); }); const c = @cImport({ @cInclude("stdio.h"); @cInclude("unistd.h"); }); /////////////////////////////////////////////////////////////////////// // Serialization / Deserialisation // this define the generic API for either Simple Type and composite Type for serialization fn SerDeserAPI(comptime T: type, comptime INType: type, comptime OUTType: type) type { return struct { const MarshallFn = fn (*const INType, *Allocator) []const u8; const UnMarshallFn = fn ([]const u8, *Allocator) *align(1) OUTType; marshall: MarshallFn, unMarshall: UnMarshallFn }; } pub fn ArrSerDeserType(comptime T: type) SerDeserAPI(T, []const T, []T) { const MI = struct { // default functions when the type is still serializable fn noMarshallFn(t: *const []const T, allocator: *Allocator) []const u8 { return t.*; } // unmarshall must make a copy, // because leveldb has its own buffers fn noUnMarshallFn(e: []const u8, allocator: *Allocator) *align(1) []T { const ptrContainer = @ptrToInt(&e); const elements = @intToPtr(*align(1) []T, ptrContainer); const pNew = allocator.create([]T) catch unreachable; pNew.* = elements.*; return pNew; } }; const S = SerDeserAPI(T, []const T, []T); return S{ .marshall = MI.noMarshallFn, .unMarshall = MI.noUnMarshallFn, }; } // need sed deser for storing on disk pub fn SerDeserType(comptime T: type) SerDeserAPI(T, T, T) { comptime { if (comptime @typeInfo(T) == .Pointer) { @panic("this ser deser type is only for simple types"); } } const MI = struct { // default functions when the type is still serializable fn noMarshallFn(t: *const T, allocator: *Allocator) []const u8 { return mem.asBytes(t); } // unmarshall must make a copy, // because leveldb has its own buffers fn noUnMarshallFn(e: []const u8, allocator: *Allocator) *align(1) T { const eptr = @ptrToInt(&e[0]); return @intToPtr(*align(1) T, eptr); } }; const S = SerDeserAPI(T, T, T); return S{ .marshall = MI.noMarshallFn, .unMarshall = MI.noUnMarshallFn, }; } test "use of noMarshallFn" { var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const i: u32 = 12; var r = SerDeserType(u32).marshall(&i, allocator); const ur = SerDeserType(u32).unMarshall(r, allocator); debug.assert(i == ur.*); } // create level db type for single element, pub fn LevelDBHash(comptime K: type, comptime V: type) type { return LevelDBHashWithSerialization(K, K, K, V, V, V, SerDeserType(K), SerDeserType(V)); } // create a leveldb type for arrays of element, for instance // []u8 (strings) pub fn LevelDBHashArray(comptime K: type, comptime V: type) type { return LevelDBHashWithSerialization(K, []const K, []K, V, []const V, []V, ArrSerDeserType(K), ArrSerDeserType(V)); } // This function create a given type for using the leveldb, with serialization // and deserialization pub fn LevelDBHashWithSerialization( // K is the key type, comptime K: type, // KIN is the associated type used in "put" primitive (when the element is passed in) comptime KIN: type, // KOUT is the associated type for out, see get primitive comptime KOUT: type, // V is the value base type comptime V: type, comptime VIN: type, comptime VOUT: type, // marshallkey function serialize the k to be stored in the database comptime marshallKey: SerDeserAPI(K, KIN, KOUT), comptime marshallValue: SerDeserAPI(V, VIN, VOUT), ) type { return struct { leveldbHandle: *cleveldb.leveldb_t = undefined, writeOptions: *cleveldb.leveldb_writeoptions_t = undefined, readOptions: *cleveldb.leveldb_readoptions_t = undefined, allocator: *Allocator, const Self = @This(); const KSerDeser = marshallKey; const VSerDeser = marshallValue; pub fn init(allocator: *Allocator) !*Self { const self = try allocator.create(Self); self.allocator = allocator; self.writeOptions = cleveldb.leveldb_writeoptions_create().?; self.readOptions = cleveldb.leveldb_readoptions_create().?; return self; } pub fn deinit(self: *Self) void { debug.warn("deinit \n", .{}); // close already free the leveldb handle // cleveldb.leveldb_free(self.leveldbHandle); cleveldb.leveldb_free(self.writeOptions); cleveldb.leveldb_free(self.readOptions); } pub fn open(self: *Self, filename: [*c]const u8) !void { const options = cleveldb.leveldb_options_create(); defer cleveldb.leveldb_free(options); // defining a small LRU cache, // on level db, initialy initialized to 32Gb with 4096 bock size // because, the key replace, will keep the values until compaction // to full iteration can get all datas and put them into LRU cache const cache = cleveldb.leveldb_cache_create_lru(4096); const env = cleveldb.leveldb_create_default_env(); cleveldb.leveldb_options_set_cache(options, cache); cleveldb.leveldb_options_set_create_if_missing(options, 1); cleveldb.leveldb_options_set_max_open_files(options, 10); cleveldb.leveldb_options_set_block_restart_interval(options, 4); cleveldb.leveldb_options_set_write_buffer_size(options, 1000); cleveldb.leveldb_options_set_env(options, env); cleveldb.leveldb_options_set_info_log(options, null); cleveldb.leveldb_options_set_block_size(options, 1024); var err: [*c]u8 = null; const result = cleveldb.leveldb_open(options, filename, &err); if (err != null) { _ = debug.warn("{}", .{"open failed"}); defer cleveldb.leveldb_free(err); return error.OPEN_FAILED; } assert(result != null); self.leveldbHandle = result.?; } pub fn close(self: *Self) void { debug.warn("close database \n", .{}); cleveldb.leveldb_close(self.leveldbHandle); self.leveldbHandle = undefined; } pub fn put(self: *Self, key: KIN, value: VIN) !void { var err: [*c]u8 = null; // debug.warn("k size {}\n", .{@sizeOf(K)}); // debug.warn("array size {}\n", .{value.len}); // marshall value const marshalledKey = KSerDeser.marshall(&key, self.allocator); // defer self.allocator.free(marshalledKey); const marshalledValue = VSerDeser.marshall(&value, self.allocator); // defer self.allocator.free(marshalledValue); cleveldb.leveldb_put(self.leveldbHandle, self.writeOptions, marshalledKey.ptr, marshalledKey.len, marshalledValue.ptr, marshalledValue.len, &err); if (err != null) { debug.warn("{}", .{"open failed"}); defer cleveldb.leveldb_free(err); return error.KEY_WRITE_FAILED; } } // retrieve the content of a key pub fn get(self: *Self, key: KIN) !?*align(1) VOUT { var read: ?[*]u8 = undefined; var read_len: usize = 0; var err: [*c]u8 = null; const marshalledKey = KSerDeser.marshall(&key, self.allocator); // defer self.allocator.free(marshalledKey); read = cleveldb.leveldb_get(self.leveldbHandle, self.readOptions, marshalledKey.ptr, marshalledKey.len, &read_len, &err); if (err != null) { _ = c.printf("open failed"); defer cleveldb.leveldb_free(err); return null; } if (read == null) { debug.warn("key not found \n", .{}); return null; } const torelease = @ptrCast(*c_void, read); defer cleveldb.leveldb_free(torelease); // _ = c.printf("returned : %s %d\n", read, read_len); const structAddr = @ptrToInt(read); var cmsg = @intToPtr([*]u8, structAddr); const vTypePtr = VSerDeser.unMarshall(cmsg[0..read_len], self.allocator); //return &cmsg[0..read_len]; return vTypePtr; } // iterator structure const Iterator = struct { const ItSelf = @This(); db: *Self = undefined, innerIt: *cleveldb.leveldb_iterator_t = undefined, allocator: *Allocator = undefined, const ConstIter_t = *const cleveldb.leveldb_iterator_t; fn init(allocator: *Allocator, db: *Self) !*Iterator { const obj = try allocator.create(Iterator); obj.allocator = allocator; const result = cleveldb.leveldb_create_iterator(db.leveldbHandle, db.readOptions); if (result) |innerhandle| { obj.innerIt = innerhandle; return obj; } return error.CannotCreateIterator; } pub fn first(self: *ItSelf) void { cleveldb.leveldb_iter_seek_to_first(self.innerIt); } /// iterKey retrieve the value of the iterator /// the memory on the value has been allocated and needs to be freed if not used pub fn iterKey(self: *ItSelf) ?*align(1) KOUT { var read_len: usize = 0; const read: ?[*c]const u8 = cleveldb.leveldb_iter_key(self.innerIt, &read_len); if (read) |existValue| { const structAddr = @ptrToInt(existValue); var cmsg = @intToPtr([*]const u8, structAddr); const spanRead = mem.bytesAsSlice(u8, cmsg[0..read_len]); const vTypePtr = KSerDeser.unMarshall(spanRead, self.allocator); return vTypePtr; } return null; } /// iterValue retrieve the value of the iterator /// the memory on the value has been allocated and needs to be freed if not used pub fn iterValue(self: *ItSelf) ?*align(1) VOUT { var read_len: usize = 0; const read: ?[*c]const u8 = cleveldb.leveldb_iter_value(self.innerIt, &read_len); if (read) |existValue| { const structAddr = @ptrToInt(existValue); var cmsg = @intToPtr([*]const u8, structAddr); const spanRead = mem.bytesAsSlice(u8, cmsg[0..read_len]); const vTypePtr = VSerDeser.unMarshall(spanRead, self.allocator); return vTypePtr; } return null; } pub fn next(self: *ItSelf) void { cleveldb.leveldb_iter_next(self.innerIt); } pub fn isValid(self: *ItSelf) bool { const result = cleveldb.leveldb_iter_valid(self.innerIt); return result > 0; } pub fn deinit(self: *ItSelf) void { cleveldb.leveldb_iter_destroy(self.innerIt); } }; pub fn iterator(self: *Self) !*Iterator { return Iterator.init(self.allocator, self); } }; } test "test iterators" { // already created database var filename = "countingstorage\x00"; var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const SS = LevelDBHash(u32, u32); var l = try SS.init(allocator); defer l.deinit(); debug.warn("opening databse", .{}); try l.open(filename); defer l.close(); debug.warn("create iterator", .{}); const iterator = try l.iterator(); defer iterator.deinit(); debug.warn("call first", .{}); iterator.first(); var r: ?*align(1) u32 = null; while (iterator.isValid()) { debug.warn("iterKey", .{}); r = iterator.iterKey(); var v = iterator.iterValue(); debug.warn("key :{} value: {}\n", .{ r.?.*, v.?.* }); allocator.destroy(v.?); iterator.next(); } debug.warn("now, close the iterator\n", .{}); } test "test no specialization" { var filename = "othertestnoser\x00"; var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const SS = LevelDBHash(u32, u8); var l = try SS.init(allocator); } test "test storing ints" { var filename = "countingstorage\x00"; var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const SS = LevelDBHash(u32, u32); var l = try SS.init(allocator); defer l.deinit(); _ = try l.open(filename); var i: u32 = 0; while (i < 1000) { try l.put(i, i + 10); i += 1; } l.close(); } test "test storing letters" { var filename = "stringstoragetest\x00"; const allocator = std.heap.c_allocator; const SS = LevelDBHashArray(u8, u8); var l = try SS.init(allocator); defer l.deinit(); _ = try l.open(filename); const MAX_ITERATIONS = 100_000_000; var i: u64 = 0; while (i < MAX_ITERATIONS) { var keyBuffer = [_]u8{ 65, 65, 65, 65, 65, 65 }; var valueBuffer = [_]u8{ 65, 65, 65, 65, 65, 65 }; _ = c.sprintf(&keyBuffer[0], "%d", i % 1000); _ = c.sprintf(&valueBuffer[0], "%d", (i + 1) % 1000); // debug.warn(" {} -> {} , key length {}\n", .{ keyBuffer, valueBuffer, keyBuffer.len }); try l.put(keyBuffer[0..], valueBuffer[0..]); const opt = try l.get(keyBuffer[0..]); allocator.destroy(opt.?); i += 1; // used for reduce pression in test if (i % 100_000 == 0) { _ = c.sleep(2); } } var s = "1\x00AAAA"; const t = mem.span(s); debug.warn("test key length : {}\n", .{t[0..].len}); const lecturealea = try l.get(t[0..]); debug.assert(lecturealea != null); debug.warn("retrieved : {}\n", .{lecturealea}); if (lecturealea) |value| { allocator.destroy(value); } const it = try l.iterator(); defer allocator.destroy(it); defer l.deinit(); it.first(); while (it.isValid()) { const optK = it.iterKey(); const optV = it.iterValue(); if (optK) |k| { defer allocator.destroy(k); debug.warn(" {} value : {}\n", .{ k.*, optV.?.* }); // debug.warn(" key for string \"{}\" \n", .{k.*}); const ovbg = try l.get(k.*); if (ovbg) |rv| { debug.warn(" {} value : {}\n", .{ k.*, rv.* }); } } if (optV) |v| { defer allocator.destroy(v); debug.warn(" value for string \"{}\" \n", .{v.*}); } it.next(); } it.deinit(); l.close(); } test "test marshalling" { debug.warn("start marshall tests\n", .{}); var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const StringMarshall = ArrSerDeserType(u8); const stringToMarshall = "hello\x00"; debug.warn("original string ptr \"{}\"\n", .{@ptrToInt(stringToMarshall)}); const sspan = mem.span(stringToMarshall); debug.warn("span type \"{}\"\n", .{@typeInfo(@TypeOf(sspan))}); const marshalledC = StringMarshall.marshall(&sspan, allocator); debug.warn("marshalled \"{}\", ptr {} \n", .{ marshalledC, marshalledC.ptr }); debug.warn("pointer to first element {} \n", .{@ptrToInt(marshalledC.ptr)}); debug.assert(&marshalledC[0] == &stringToMarshall[0]); } test "test reading" { var filename = "countingstorage\x00"; var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; const SS = LevelDBHash(u32, u32); var l = try SS.init(allocator); defer l.deinit(); _ = try l.open(filename); var i: u32 = 0; while (i < 1000) { const v = try l.get(i); debug.assert(v.?.* == i + 10); i += 1; } l.close(); } test "test serialization types" { // var filename : [100]u8 = [_]u8{0} ** 100; var filename = "hellosimpletypes2\x00"; var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const allocator = &arena.allocator; comptime const u32SerializationType = SerDeserType(u32); comptime const u8ArrSerializationType = ArrSerDeserType(u8); comptime const SS = LevelDBHashWithSerialization(u32, u32, u32, u8, []const u8, []u8, u32SerializationType, u8ArrSerializationType); var l = try SS.init(allocator); _ = try l.open(filename); var h = @intCast(u32, 5); var w = [_]u8{ 'w', 'o', 'r', 'l', 'd', 0x00 }; // debug.warn("slice size : {}\n", .{w[0..].len}); _ = try l.put(h, w[0..]); const t = try l.get(h); debug.warn("returned value {}\n", .{t.?.*}); if (t) |result| { debug.warn("result is :{}\n", .{result.*}); // debug.warn("result type is :{}\n", .{@TypeOf(result.*)}); } defer l.close(); } // RAW C API Tests //test "creating file" { // const options = cleveldb.leveldb_options_create(); // cleveldb.leveldb_options_set_create_if_missing(options, 1); // var err: [*c]u8 = null; // // const db = c.leveldb_open(options, "testdb", @intToPtr([*c][*c]u8,@ptrToInt(&err[0..]))); // const db = cleveldb.leveldb_open(options, "testdb", &err); // if (err != null) { // _ = c.printf("open failed"); // defer cleveldb.leveldb_free(err); // return; // } // var woptions = cleveldb.leveldb_writeoptions_create(); // cleveldb.leveldb_put(db, woptions, "key", 3, "value", 6, &err); // // const roptions = cleveldb.leveldb_readoptions_create(); // var read: [*c]u8 = null; // var read_len: usize = 0; // read = cleveldb.leveldb_get(db, roptions, "key", 3, &read_len, &err); // if (err != null) { // _ = c.printf("open failed"); // defer cleveldb.leveldb_free(err); // return; // } // _ = c.printf("returned : %s %d\n", read, read_len); // cleveldb.leveldb_close(db); //}
leveldb.zig
const std = @import("std"); const format = @import("format.zig"); const decode = @import("decode.zig"); const value = @import("value.zig"); const expect = std.testing.expect; const Format = format.Format; const DecodeError = decode.DecodeError; const ValueWithRest = struct { v: value.Value, rest: []const u8, }; pub fn decodeValue(alloc: *std.mem.Allocator, buf: []const u8) DecodeError!value.Value { var val = try readValueWithRest(alloc, buf); return val.v; } fn readValueWithRest(alloc: *std.mem.Allocator, buf: []const u8) DecodeError!ValueWithRest { if (buf.len == 0) { return error.EmptyInput; } return switch (format.from_u8(buf[0])) { Format.positive_fix_int => |i| ValueWithRest{ .v = value.Value{ .uint = i }, .rest = buf[1..] }, Format.fix_map => |len| readFixMapValue(alloc, buf[1..], len), Format.fix_array => |len| readFixArrayValue(alloc, buf[1..], len), Format.fix_str => |len| ValueWithRest{ .v = value.Value{ .string = try decode.readFixStr(buf[1..], len) }, .rest = buf[1 + len ..] }, Format.nil => ValueWithRest{ .v = .nil, .rest = buf[1..] }, Format.never_used => error.ReservedFormat, Format.bool_false => ValueWithRest{ .v = value.Value{ .bool = false }, .rest = buf[1..] }, Format.bool_true => ValueWithRest{ .v = value.Value{ .bool = true }, .rest = buf[1..] }, Format.bin8 => { var v = value.Value{ .string = try decode.readBin8(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 1 + v.binary.len ..] }; }, Format.bin16 => { var v = value.Value{ .string = try decode.readBin16(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 2 + v.binary.len ..] }; }, Format.bin32 => { var v = value.Value{ .string = try decode.readBin32(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 4 + v.binary.len ..] }; }, Format.float32 => ValueWithRest{ .v = value.Value{ .float = try decode.readFloat32(f32, buf[1..]) }, .rest = buf[5..] }, Format.float64 => ValueWithRest{ .v = value.Value{ .float = try decode.readFloat64(f64, buf[1..]) }, .rest = buf[9..] }, Format.uint8 => ValueWithRest{ .v = value.Value{ .uint = try decode.readUint8(u8, buf[1..]) }, .rest = buf[1..] }, Format.uint16 => ValueWithRest{ .v = value.Value{ .uint = try decode.readUint16(u64, buf[1..]) }, .rest = buf[3..] }, Format.uint32 => ValueWithRest{ .v = value.Value{ .uint = try decode.readUint32(u32, buf[1..]) }, .rest = buf[5..] }, Format.uint64 => ValueWithRest{ .v = value.Value{ .uint = try decode.readUint64(u64, buf[1..]) }, .rest = buf[9..] }, Format.int8 => ValueWithRest{ .v = value.Value{ .int = try decode.readInt8(i8, buf[1..]) }, .rest = buf[1..] }, Format.int16 => ValueWithRest{ .v = value.Value{ .int = try decode.readInt16(i16, buf[1..]) }, .rest = buf[3..] }, Format.int32 => ValueWithRest{ .v = value.Value{ .int = try decode.readInt32(i32, buf[1..]) }, .rest = buf[5..] }, Format.int64 => ValueWithRest{ .v = value.Value{ .int = try decode.readInt64(i64, buf[1..]) }, .rest = buf[9..] }, Format.str8 => { var v = value.Value{ .string = try decode.readStr8(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 1 + v.string.len ..] }; }, Format.str16 => { var v = value.Value{ .string = try decode.readStr16(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 2 + v.string.len ..] }; }, Format.str32 => { var v = value.Value{ .string = try decode.readStr32(buf[1..]) }; return ValueWithRest{ .v = v, .rest = buf[1 + 4 + v.string.len ..] }; }, Format.negative_fix_int => |i| ValueWithRest{ .v = value.Value{ .int = @intCast(i64, i) }, .rest = buf[1..] }, else => unreachable, }; } fn readFixMapValue(allocator: *std.mem.Allocator, buf: []const u8, len: u8) DecodeError!ValueWithRest { return readMapValue(allocator, buf, len); } fn readMapValue(allocator: *std.mem.Allocator, buf: []const u8, len: u8) DecodeError!ValueWithRest { var m = std.StringHashMap(value.Value).init(allocator); if (len == 0) { return ValueWithRest{ .v = value.Value{ .map = m }, .rest = buf }; } var i: usize = 0; var rest = buf; while (i < len) { // first element is a string var key: []const u8 = undefined; switch (format.from_u8(rest[0])) { Format.fix_str => |slen| { key = try decode.readFixStr(rest[1..], slen); rest = rest[1 + slen ..]; }, Format.str8 => { key = try decode.readStr8(rest[1..]); rest = rest[1 + 1 + key.len ..]; }, Format.str16 => { key = try decode.readStr16(rest[1..]); rest = rest[1 + 2 + key.len ..]; }, Format.str32 => { key = try decode.readStr32(rest[1..]); rest = rest[1 + 4 + key.len ..]; }, else => return error.InvalidMapKeyType, } var val = try readValueWithRest(allocator, rest); rest = val.rest; try m.put(key, val.v); i += 1; } return ValueWithRest{ .v = value.Value{ .map = m }, .rest = rest }; } fn readFixArrayValue(allocator: *std.mem.Allocator, buf: []const u8, len: u8) DecodeError!ValueWithRest { return readArrayValue(allocator, buf, len); } fn readArray16Value(allocator: *std.mem.Allocator, buf: []const u8) DecodeError!ValueWithRest { return readArrayValue(allocator, try readUint16(u16, buf), buf[2..]); } fn readArray32Value(allocator: *std.mem.Allocator, buf: []const u8) DecodeError!ValueWithRest { return readArrayValue(allocator, try readUint32(u32, buf), buf[2..]); } fn readArrayValue(allocator: *std.mem.Allocator, buf: []const u8, len: usize) DecodeError!ValueWithRest { if (len == 0) { return ValueWithRest{ .v = value.Value{ .array = try std.ArrayList(value.Value).initCapacity(allocator, 0) }, .rest = buf }; } var array = try std.ArrayList(value.Value).initCapacity(allocator, len); var i: usize = 0; var buff = buf; while (i < len) { var val = try readValueWithRest(allocator, buff); buff = val.rest; // array.items[i] = val.v; try array.append(val.v); i += 1; } return ValueWithRest{ .v = value.Value{ .array = array }, .rest = buff }; } test "empty input" { var data: [0]u8 = undefined; if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.EmptyInput => {}, else => @panic("invalid error received, expected empty input"), } } test "decode nil" { const hex = "c0"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v == .nil); } test "decode false" { const hex = "c2"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.bool == false); } test "decode true" { const hex = "c3"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.bool == true); } test "decode uint8" { const hex = "cc80"; // 128 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.uint == 128); } test "decode uint8 truncated error" { const hex = "cc"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode uint16" { const hex = "cd0640"; // 1600 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.uint == 1600); } test "decode uint16 truncated error" { const hex = "cd06"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode uint32" { const hex = "ce00bbdef8"; // 12312312 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.uint == 12312312); } test "decode uint32 truncated error" { const hex = "ce00bbde"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode uint64" { const hex = "cf0000001caab5c3b3"; // 123123123123 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.uint == 123123123123); } test "decode uint64 truncated error" { const hex = "cf0000001caab5c3"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode int8" { const hex = "d085"; // -123 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.int == -123); } test "decode int8 truncated error" { const hex = "d0"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode int16" { const hex = "d1fb30"; // -1232 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.int == -1232); } test "decode int16 truncated error" { const hex = "d1fb"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode int32" { const hex = "d2fffe1eb4"; // -123212 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.int == -123212); } test "decode int32 truncated error" { const hex = "d2fffe1e"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode int64" { const hex = "d3fffffffd2198eb05"; // -12321232123 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.int == -12321232123); } test "decode int64 truncated error" { const hex = "d3fffffffd2198eb"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode value float 32" { const hex = "ca40918c7d"; // 4.548399448394775 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.float == 4.548399448394775); } test "decode value float 64" { const hex = "cb40918c7df3b645a2"; // 1123.123 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.float == 1123.123); } test "decode positive fix int" { const hex = "0c"; // 12 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.uint == 12); } test "decode negative fix int" { const hex = "e0"; // -32 var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.int == -32); } test "decode fix str" { const hex = "ab68656c6c6f20776f726c64"; // "hello world" var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(std.mem.eql(u8, "hello world", v.string)); } test "decode fix str truncated" { const hex = "ab68656c6c6f20776f"; // "hello world" var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); if (decodeValue(std.testing.allocator, data[0..])) { @panic("unexpected OK with empty input"); } else |err| switch (err) { error.TruncatedInput => {}, else => @panic("invalid error received, expected truncated input"), } } test "decode value str8" { const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world" var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(std.mem.eql(u8, "hello world hello world hello world", v.string)); } test "decode empty array" { const hex = "90"; // "[]" var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.array.items.len == 0); } test "decode array many types" { const hex = "942ac3a6737472696e67cb404535c28f5c28f6"; // "[42, true, "string", 42.42]" var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.array.items.len == 4); expect(v.array.items[0].uint == 42); expect(v.array.items[1].bool == true); expect(std.mem.eql(u8, v.array.items[2].string, "string")); expect(v.array.items[3].float == 42.42); v.free(); } test "decode empty map" { const hex = "80"; // {} var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.map.count() == 0); v.free(); } test "decode map many fields" { // { // "s": "string", // "u": 123456, // "b": true, // "f": -2332.32323, // "i": -12343, // "a": [1, "hello"], // "m": { // "s": "hello world" // }, // "n": null // } const hex = "88a173a6737472696e67a175ce0001e240a162c3a166cbc0a238a57e670e2ca169d1cfc9a1619201a568656c6c6fa16d81a173ab68656c6c6f20776f726c64a16ec0"; var data: [hex.len / 2]u8 = undefined; try std.fmt.hexToBytes(data[0..], hex); var v = try decodeValue(std.testing.allocator, data[0..]); expect(v.map.count() == 8); expect(std.mem.eql(u8, v.map.get("s").?.string, "string")); expect(v.map.get("u").?.uint == 123456); expect(v.map.get("b").?.bool == true); expect(v.map.get("f").?.float == -2332.32323); expect(v.map.get("i").?.int == -12343); expect(v.map.get("a").?.array.items[0].uint == 1); expect(std.mem.eql(u8, v.map.get("a").?.array.items[1].string, "hello")); expect(std.mem.eql(u8, v.map.get("m").?.map.get("s").?.string, "hello world")); expect(v.map.get("n").? == .nil); v.free(); } // test "decode str16" { // const hex = "da2368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world" // var data: [hex.len / 2]u8 = undefined; // try std.fmt.hexToBytes(data[0..], hex); // var v = try read(data[0..]); // expect(std.mem.eql(u8, "hello world hello world hello world", v.string)); // } // test "decode str32" { // const hex = "db2368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world" // var data: [hex.len / 2]u8 = undefined; // try std.fmt.hexToBytes(data[0..], hex); // var v = try read(data[0..]); // expect(std.mem.eql(u8, "hello world hello world hello world", v.string)); // }
src/decode_value.zig
const std = @import("std"); const zjson = @import("zjson"); const lib = @import("main.zig"); const model = lib.model; pub fn parseSearch(input: []const u8, allocator: std.mem.Allocator) !model.SearchResult { const shelves = try zjson.get(input, .{ "contents", "tabbedSearchResultsRenderer", "tabs", 0, "tabRenderer", "content", "sectionListRenderer", "contents" }); var search_result = model.SearchResult.init(allocator); errdefer search_result.deinit(); var shelves_iter = try zjson.ArrayIterator.init(shelves); while (try shelves_iter.next()) |shelf| { // sometimes key is not found, and its because search query can be misspelled // so first shelf is the common: did you mean ...? so its safe to skip const shelf_name = zjson.get(shelf.bytes, .{ "musicShelfRenderer", "title", "runs", 0, "text" }) catch continue; const shelf_type = try model.ShelfType.from_str(shelf_name.bytes); const shelf_items = try zjson.get(shelf.bytes, .{ "musicShelfRenderer", "contents" }); var items = try zjson.ArrayIterator.init(shelf_items); while (try items.next()) |item| { switch (shelf_type) { .top_result => {}, .song => { const song = try parseSong(allocator, item.bytes); try search_result.songs.append(song); }, .video => { const video = try parseVideo(allocator, item.bytes); try search_result.videos.append(video); }, .artist => { const artist = try parseArtist(allocator, item.bytes); try search_result.artists.append(artist); }, else => {}, } } } return search_result; } pub fn parseSong(allocator: std.mem.Allocator, input: []const u8) !model.Song { // Runs 0 contains Song info // text: Song title // endpoint: Song ID const item_flex0 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 0, "musicResponsiveListItemFlexColumnRenderer" }); const runs0 = try zjson.get(item_flex0.bytes, .{ "text", "runs", 0 }); const runs0_text = try zjson.get(runs0.bytes, .{"text"}); const runs0_endpoint = try zjson.get(runs0.bytes, .{ "navigationEndpoint", "watchEndpoint", "videoId" }); // Runs 1 contains artist related info // text: artist name // endpoint: artist ID const item_flex1 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 1, "musicResponsiveListItemFlexColumnRenderer" }); const runs1 = try zjson.get(item_flex1.bytes, .{ "text", "runs", 2 }); const runs1_text = try zjson.get(runs1.bytes, .{"text"}); const runs1_endpoint = try zjson.get(runs1.bytes, .{ "navigationEndpoint", "browseEndpoint", "browseId" }); // Runs 4 contains album related info // text: album name // endpoint: album ID const runs4 = try zjson.get(item_flex1.bytes, .{ "text", "runs", 4 }); const runs4_text = try zjson.get(runs4.bytes, .{"text"}); const runs4_endpoint = try zjson.get(runs4.bytes, .{ "navigationEndpoint", "browseEndpoint", "browseId" }); return model.Song{ .title = try std.fmt.allocPrint(allocator, "{s}", .{runs0_text.bytes}), .id = try std.fmt.allocPrint(allocator, "{s}", .{runs0_endpoint.bytes}), .artist_name = try std.fmt.allocPrint(allocator, "{s}", .{runs1_text.bytes}), .artist_id = try std.fmt.allocPrint(allocator, "{s}", .{runs1_endpoint.bytes}), .album_name = try std.fmt.allocPrint(allocator, "{s}", .{runs4_text.bytes}), .album_id = try std.fmt.allocPrint(allocator, "{s}", .{runs4_endpoint.bytes}), }; } pub fn parseVideo(allocator: std.mem.Allocator, input: []const u8) !model.Video { // Runs 0 contains Song info // text: Song title // endpoint: Song ID const item_flex0 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 0, "musicResponsiveListItemFlexColumnRenderer" }); const runs0 = try zjson.get(item_flex0.bytes, .{ "text", "runs", 0 }); const runs0_text = try zjson.get(runs0.bytes, .{"text"}); const runs0_endpoint = try zjson.get(runs0.bytes, .{ "navigationEndpoint", "watchEndpoint", "videoId" }); // Runs 1 contains artist related info // text: artist name // endpoint: artist ID const item_flex1 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 1, "musicResponsiveListItemFlexColumnRenderer" }); const runs1 = try zjson.get(item_flex1.bytes, .{ "text", "runs", 2 }); const runs1_text = try zjson.get(runs1.bytes, .{"text"}); const runs1_endpoint = try zjson.get(runs1.bytes, .{ "navigationEndpoint", "browseEndpoint", "browseId" }); return model.Video{ .title = try std.fmt.allocPrint(allocator, "{s}", .{runs0_text.bytes}), .id = try std.fmt.allocPrint(allocator, "{s}", .{runs0_endpoint.bytes}), .artist_name = try std.fmt.allocPrint(allocator, "{s}", .{runs1_text.bytes}), .artist_id = try std.fmt.allocPrint(allocator, "{s}", .{runs1_endpoint.bytes}), }; } pub fn parseArtist(allocator: std.mem.Allocator, input: []const u8) !model.Artist { // Artist // text: Artist name // endpoint: null const item_flex0 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 0, "musicResponsiveListItemFlexColumnRenderer" }); const runs0 = try zjson.get(item_flex0.bytes, .{ "text", "runs", 0 }); const runs0_text = try zjson.get(runs0.bytes, .{"text"}); const endpoint = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "navigationEndpoint", "browseEndpoint", "browseId" }); // Subscribers //const item_flex1 = try zjson.get(input, .{ "musicResponsiveListItemRenderer", "flexColumns", 1, "musicResponsiveListItemFlexColumnRenderer" }); //const runs1 = try zjson.get(item_flex1.bytes, .{ "text", "runs", 2 }); //const runs1_text = try zjson.get(runs1.bytes, .{"text"}); return model.Artist{ .name = try std.fmt.allocPrint(allocator, "{s}", .{runs0_text.bytes}), .id = try std.fmt.allocPrint(allocator, "{s}", .{endpoint.bytes}), }; }
src/parser.zig
const graph = @import("weighted_graph.zig").WeightedGraph; const std = @import("std"); const ArrayList = std.ArrayList; const graph_err = @import("graph.zig").GraphError; const testing = std.testing; const AutoArrayHashMap = std.AutoArrayHashMap; const mem = std.mem; const testing_alloc = std.testing.allocator; pub fn WeightedDataGraph(comptime index_type: type, comptime weight_type: type, comptime node_type: type, comptime edge_type: type, directed: bool) type { return struct { const Self = @This(); graph: graph(index_type, weight_type, directed), node_data: AutoArrayHashMap(index_type, node_type), edge_data: AutoArrayHashMap(index_type, edge_type), allocator: *mem.Allocator, pub fn init(alloc: *mem.Allocator) Self { return Self{ .graph = graph(index_type, weight_type, directed).init(alloc), .node_data = AutoArrayHashMap(index_type, node_type).init(alloc), .edge_data = AutoArrayHashMap(index_type, edge_type).init(alloc), .allocator = alloc }; } pub fn deinit(self: *Self) !void { try self.graph.deinit(); self.node_data.deinit(); self.edge_data.deinit(); } //Adding a node into the graph given an index (id), and data pertaining to the node pub fn addNode(self: *Self, node_index: index_type, node_data: node_type) !void { try self.graph.addNode(node_index); try self.node_data.put(node_index, node_data); } //Adding an edge into the graph given id, the node indexes being connected, a weight, and some edge data (Note, order matters for directed graphs) pub fn addEdge(self: *Self, id: index_type, n1: index_type, n2: index_type, w: weight_type, edge_data: edge_type) !void { try self.graph.addEdge(id, n1, n2, w); try self.edge_data.put(id, edge_data); } //Given an ID for an edge removes an edge pub fn removeEdgeByID(self: *Self, id: index_type) !void { try self.graph.removeEdgeByID(id); _ = self.edge_data.orderedRemove(id); } //Given two nodes n1, and n2 removes the edges between them (Order matters for directed graphs) pub fn removeEdgesBetween(self: *Self, n1: index_type, n2: index_type) !ArrayList(index_type) { var removed_edges = try self.graph.removeEdgesBetween(n1, n2); for (removed_edges.items) |edge| { _ = self.edge_data.orderedRemove(edge); } return removed_edges; } //Removes a node along with all edges connected to it pub fn removeNodeWithEdges(self: *Self, id: index_type) !ArrayList(index_type) { var removed_edges = try self.graph.removeNodeWithEdges(id); for (removed_edges.items) |edge| { _ = self.edge_data.orderedRemove(edge); } _ = self.node_data.orderedRemove(id); return removed_edges; } //Gets a list of data given an arraylist of indices of nodes pub fn getNodesData(self: *Self, ids: ArrayList(index_type)) !ArrayList(node_type) { var data = ArrayList(node_type).init(self.allocator); data.deinit(); for (ids.items) |id| { if (!self.node_data.contains(id)) { data.deinit(); return graph_err.NodesDoNotExist; } try data.append(self.node_data.get(id).?); } return data; } //Gets a list of data given an arraylist of indices of edges pub fn getEdgesData(self: *Self, ids: ArrayList(index_type)) !ArrayList(edge_type) { var data = ArrayList(edge_type).init(self.allocator); data.deinit(); for (ids.items) |id| { if (!self.edge_data.contains(id)) { data.deinit(); return graph_err.EdgesDoNotExist; } try data.append(self.edge_data.get(id).?); } return data; } }; } test "nominal-addNode" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try testing.expect(weighted_data_graph.graph.graph.graph.count() == 1); try testing.expect(weighted_data_graph.node_data.count() == 1); try testing.expect(weighted_data_graph.node_data.get(3).? == 4); try weighted_data_graph.deinit(); } test "nominal-addEdge" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 5); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try testing.expect(weighted_data_graph.edge_data.get(1).? == 6); try weighted_data_graph.deinit(); } test "offnominal-addNode" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try testing.expect(if (weighted_data_graph.addNode(3, 4)) |_| unreachable else |err| err == graph_err.NodeAlreadyExists); try weighted_data_graph.deinit(); } test "nominal-removeNodeWithEdges" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 4); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); var edges = try weighted_data_graph.removeNodeWithEdges(3); try testing.expect(weighted_data_graph.graph.graph.graph.count() == 1); try testing.expect(weighted_data_graph.node_data.count() == 1); try testing.expect(weighted_data_graph.edge_data.count() == 0); try testing.expect(edges.items.len == 1); edges.deinit(); try weighted_data_graph.deinit(); } test "offnominal-removeNodeWithEdges" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try testing.expect(if (weighted_data_graph.removeNodeWithEdges(2)) |_| unreachable else |err| err == graph_err.NodesDoNotExist); try weighted_data_graph.deinit(); } test "nominal-removeEdgeByID" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 4); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try weighted_data_graph.removeEdgeByID(1); try testing.expect(weighted_data_graph.edge_data.count() == 0); try weighted_data_graph.deinit(); } test "offnominal-removeEdgeByID" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 4); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try testing.expect(if (weighted_data_graph.removeEdgeByID(2)) |_| unreachable else |err| err == graph_err.EdgesDoNotExist); try weighted_data_graph.deinit(); } test "nominal-removeEdgesBetween" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 4); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try weighted_data_graph.addEdge(2, 3, 4, 7, 6); var edges = try weighted_data_graph.removeEdgesBetween(3, 4); try testing.expect(weighted_data_graph.edge_data.count() == 0); try testing.expect(edges.items.len == 2); edges.deinit(); try weighted_data_graph.deinit(); } test "offnominal-removeEdgesBetween" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 4); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try weighted_data_graph.addEdge(2, 3, 4, 7, 6); try testing.expect(if (weighted_data_graph.removeEdgesBetween(4, 5)) |_| unreachable else |err| err == graph_err.NodesDoNotExist); try weighted_data_graph.deinit(); } test "nominal-getNodesData" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 5); var arr = ArrayList(u32).init(testing_alloc); try arr.append(3); try arr.append(4); var node_data = try weighted_data_graph.getNodesData(arr); try testing.expect(node_data.items[0] == 4); try testing.expect(node_data.items[1] == 5); node_data.deinit(); arr.deinit(); try weighted_data_graph.deinit(); } test "offnominal-getNodesData" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 5); var arr = ArrayList(u32).init(testing_alloc); try arr.append(1); try arr.append(7); try testing.expect(if (weighted_data_graph.getNodesData(arr)) |_| unreachable else |err| err == graph_err.NodesDoNotExist); arr.deinit(); try weighted_data_graph.deinit(); } test "nominal-getEdgesData" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 5); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try weighted_data_graph.addEdge(2, 3, 4, 7, 7); var arr = ArrayList(u32).init(testing_alloc); try arr.append(1); try arr.append(2); var node_data = try weighted_data_graph.getEdgesData(arr); try testing.expect(node_data.items[0] == 6); try testing.expect(node_data.items[1] == 7); node_data.deinit(); arr.deinit(); try weighted_data_graph.deinit(); } test "offnominal-getEdgesData" { var weighted_data_graph = WeightedDataGraph(u32, u64, u64, u64, true).init(testing_alloc); try weighted_data_graph.addNode(3, 4); try weighted_data_graph.addNode(4, 5); try weighted_data_graph.addEdge(1, 3, 4, 5, 6); try weighted_data_graph.addEdge(2, 3, 4, 7, 7); var arr = ArrayList(u32).init(testing_alloc); try arr.append(1); try arr.append(7); try testing.expect(if (weighted_data_graph.getEdgesData(arr)) |_| unreachable else |err| err == graph_err.EdgesDoNotExist); arr.deinit(); try weighted_data_graph.deinit(); }
src/weighted_data_graph.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 exe = b.addExecutable("byway", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addIncludeDir("protocol"); exe.addIncludeDir("."); exe.linkLibC(); exe.linkSystemLibrary("wayland-server"); exe.linkSystemLibrary("wlroots"); exe.linkSystemLibrary("xkbcommon"); exe.linkSystemLibrary("libinput"); exe.linkSystemLibrary("xcb"); exe.linkSystemLibrary("pixman-1"); exe.install(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = gpa.allocator(); const protocols_dir = "$(pkg-config --variable=pkgdatadir wayland-protocols)"; const wayland_scanner = "$(pkg-config --variable=wayland_scanner wayland-scanner)"; const server_header = "server-header"; const fmt_str = "{s} {s} {s}{s} {s}"; const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const xdg_proto = try std.fmt.allocPrint(alloc, fmt_str, .{ wayland_scanner, server_header, protocols_dir, "/stable/xdg-shell/xdg-shell.xml", "xdg-shell-protocol.h", }); defer alloc.free(xdg_proto); const wlr_proto = try std.fmt.allocPrint(alloc, fmt_str, .{ wayland_scanner, server_header, "protocol", "/wlr-layer-shell-unstable-v1.xml", "wlr-layer-shell-unstable-v1-protocol.h", }); defer alloc.free(wlr_proto); exe.step.dependOn(&b.addSystemCommand(&.{ "/bin/sh", "-c", xdg_proto }).step); exe.step.dependOn(&b.addSystemCommand(&.{ "/bin/sh", "-c", wlr_proto }).step); const run_step = b.step("run", "Run Byway"); run_step.dependOn(&run_cmd.step); }
build.zig
const std = @import("std"); const unitbounds = @import("unitbounds.zig"); const Allocator = std.mem.Allocator; pub fn Screen(comptime Cell: type) type { return struct { const Self = @This(); allocator: *Allocator, cells: []Cell, width: usize, height: usize, ub: unitbounds.Pos01ToIndex, pub fn init(allocator: *Allocator, width: usize, height: usize, default: Cell) !Self { const count = width * height; var cells = try allocator.alloc(Cell, count); errdefer allocator.free(cells); for (cells) |*cell| { cell.* = default; } return Self{ .allocator = allocator, .cells = cells, .width = width, .height = height, .ub = unitbounds.Pos01ToIndex.forCenter(width, height, 0), }; } pub fn deinit(self: *const Self) void { self.allocator.free(self.cells); } pub fn indexRef(self: *Self, i: ?usize) ?*Cell { if (i) |j| { return &self.cells[j]; } return null; } pub fn getIndex(self: *const Self, i: ?usize) ?Cell { if (i) |j| { return self.cells[j]; } return null; } pub fn ref(self: *Self, x: f64, y: f64) ?*Cell { return self.indexRef(self.ub.index(x, y)); } pub fn get(self: *const Self, x: f64, y: f64) ?Cell { return self.getIndex(self.ub.index(x, y)); } pub fn refi(self: *Self, xi: isize, yi: isize) ?*Cell { return self.indexRef(self.ub.res.indexi(xi, yi)); } pub fn geti(self: *const Self, xi: isize, yi: isize) ?Cell { return self.getIndex(self.ub.res.indexi(xi, yi)); } pub fn getOff(self: *const Self, x: f64, y: f64, xo: isize, yo: isize) ?Cell { return self.getIndex(self.ub.indexOff(x, y, xo, yo)); } pub fn refOff(self: *Self, x: f64, y: f64, xo: isize, yo: isize) ?*Cell { return self.indexRef(self.ub.indexOff(x, y, xo, yo)); } pub const Offset = unitbounds.Pos01ToIndex.Offset; pub fn getOffsets(self: *const Self, x: f64, y: f64, comptime n: usize, comptime offsets: [n]Offset) [n]?Cell { var result = [_]?Cell{null} ** n; for (self.ub.indexOffsets(x, y, n, offsets)) |index, i| { result[i] = self.getIndex(index); } return result; } pub fn refOffsets(self: *const Self, x: f64, y: f64, comptime n: usize, comptime offsets: [n]Offset) [n]?*Cell { var result = [_]?Cell{null} ** n; for (self.ub.indexOffsets(x, y, n, offsets)) |index, i| { result[i] = self.indexRef(index); } return result; } pub fn neighbors4(self: *const Self, x: f64, y: f64) [4]?Cell { return self.getOffsets(x, y, 4, unitbounds.Pos01ToIndex.neighbors4); } pub fn neighbors5(self: *const Self, x: f64, y: f64) [5]?Cell { return self.getOffsets(x, y, 5, unitbounds.Pos01ToIndex.neighbors5); } pub fn neighbors8(self: *const Self, x: f64, y: f64) [8]?Cell { return self.getOffsets(x, y, 8, unitbounds.Pos01ToIndex.neighbors8); } pub fn neighbors9(self: *const Self, x: f64, y: f64) [9]?Cell { return self.getOffsets(x, y, 9, unitbounds.Pos01ToIndex.neighbors9); } }; }
lib/screen.zig
const std = @import("std"); const fb = @import("../console/fb.zig"); const hw = @import("../hw.zig"); const printf = @import("../console/fb.zig").printf; pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { hw.entry_uart.carefully(.{"\r\n!!!!!!!!!!!!\r\nkernel panic\r\n!!!!!!!!!!!!\r\n"}); const current_el = readRegister(.CurrentEL) >> 2; const sctlr_el1 = readRegister(.SCTLR_EL1); hw.entry_uart.carefully(.{ "CurrentEL: ", current_el, "\r\n" }); hw.entry_uart.carefully(.{ "SCTLR_EL1: ", sctlr_el1, "\r\n" }); if (error_return_trace) |ert| { hw.entry_uart.carefully(.{"trying to print stack ... \r\n"}); var frame_index: usize = 0; var frames_left: usize = std.math.min(ert.index, ert.instruction_addresses.len); while (frames_left != 0) : ({ frames_left -= 1; frame_index = (frame_index + 1) % ert.instruction_addresses.len; }) { const return_address = ert.instruction_addresses[frame_index]; hw.entry_uart.carefully(.{ return_address, "\r\n" }); } } else { hw.entry_uart.carefully(.{"no ert\r\n"}); } hw.entry_uart.carefully(.{ "@returnAddress: ", @returnAddress(), "\r\n" }); hw.entry_uart.carefully(.{ "panic message ptr: ", @ptrToInt(msg.ptr), "\r\n<" }); hw.entry_uart.carefully(.{ hw.entry_uart.Escape.Runtime, msg, ">\r\n" }); if (fb.present()) { fb.panicMessage(msg); } halt(); } pub fn loadAddress(comptime symbol: []const u8) callconv(.Inline) u64 { return asm volatile ("adr %[ret], " ++ symbol : [ret] "=r" (-> u64) ); } pub const Register = enum { MAIR_EL1, TCR_EL1, TTBR0_EL1, TTBR1_EL1, SCTLR_EL1, CurrentEL, CPACR_EL1, CPTR_EL2, CPTR_EL3, }; pub fn writeRegister(comptime register: Register, value: u64) callconv(.Inline) void { asm volatile ("msr " ++ @tagName(register) ++ ", %[value]" : : [value] "r" (value) : "memory" ); } pub fn readRegister(comptime register: Register) callconv(.Inline) u64 { return asm volatile ("mrs %[ret], " ++ @tagName(register) : [ret] "=r" (-> u64) ); } pub fn orRegister(comptime register: Register, value: u64) callconv(.Inline) void { asm volatile ("mrs x0, " ++ @tagName(register) ++ "\n" ++ "orr x0, x0, %[value]\n" ++ "msr " ++ @tagName(register) ++ ", x0\n" : : [value] "r" (value) : "memory", "x0" ); } pub fn sleep(ms: u64) void { // CURSED // CURSED // CURSED asm volatile ( \\ isb \\ mrs x1, cntpct_el0 \\ mrs x2, cntfrq_el0 // x2 has ticks pers second (Hz) \\ mov x3, #1000 \\ udiv x2, x2, x3 // x2 has ticks per millisecond \\ mul x2, x2, x0 // x2 has ticks per `ms` milliseconds \\ add x2, x1, x2 // x2 has start time + ticks \\1: cmp x1, x2 \\ b.hs 2f \\ isb \\ mrs x1, cntpct_el0 \\ b 1b \\2: nop : [ms] "={x0}" (ms) : : "x1", "x2", "x3" ); } pub fn halt() noreturn { asm volatile ("msr daifset, #15"); while (true) { asm volatile ("wfi"); } } pub fn reset() noreturn { psci(0x8400_0009); } pub fn poweroff() noreturn { psci(0x8400_0008); } fn psci(val: u32) noreturn { switch (hw.psci.method) { .Hvc => { printf("goodbye\n", .{}); asm volatile ( \\msr daifset, #15 \\hvc 0 : : [val] "{x0}" (val) : "memory" ); }, .Smc => { printf("goodbye\n", .{}); asm volatile ( \\msr daifset, #15 \\smc 0 : : [val] "{x0}" (val) : "memory" ); }, else => @panic("unknown psci method"), } sleep(5000); @panic("psci returned"); }
dainkrnl/src/arm64/arch.zig
//-------------------------------------------------------------------------------- // Section: Types (5) //-------------------------------------------------------------------------------- // TODO: this type has a FreeFunc 'wglDeleteContext', what can Zig do with this information? pub const HGLRC = *opaque{}; pub const PIXELFORMATDESCRIPTOR = extern struct { nSize: u16, nVersion: u16, dwFlags: u32, iPixelType: u8, cColorBits: u8, cRedBits: u8, cRedShift: u8, cGreenBits: u8, cGreenShift: u8, cBlueBits: u8, cBlueShift: u8, cAlphaBits: u8, cAlphaShift: u8, cAccumBits: u8, cAccumRedBits: u8, cAccumGreenBits: u8, cAccumBlueBits: u8, cAccumAlphaBits: u8, cDepthBits: u8, cStencilBits: u8, cAuxBuffers: u8, iLayerType: u8, bReserved: u8, dwLayerMask: u32, dwVisibleMask: u32, dwDamageMask: u32, }; pub const POINTFLOAT = extern struct { x: f32, y: f32, }; pub const GLYPHMETRICSFLOAT = extern struct { gmfBlackBoxX: f32, gmfBlackBoxY: f32, gmfptGlyphOrigin: POINTFLOAT, gmfCellIncX: f32, gmfCellIncY: f32, }; pub const LAYERPLANEDESCRIPTOR = extern struct { nSize: u16, nVersion: u16, dwFlags: u32, iPixelType: u8, cColorBits: u8, cRedBits: u8, cRedShift: u8, cGreenBits: u8, cGreenShift: u8, cBlueBits: u8, cBlueShift: u8, cAlphaBits: u8, cAlphaShift: u8, cAccumBits: u8, cAccumRedBits: u8, cAccumGreenBits: u8, cAccumBlueBits: u8, cAccumAlphaBits: u8, cDepthBits: u8, cStencilBits: u8, cAuxBuffers: u8, iLayerPlane: u8, bReserved: u8, crTransparent: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (24) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn ChoosePixelFormat( hdc: ?HDC, ppfd: ?*const PIXELFORMATDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn DescribePixelFormat( hdc: ?HDC, iPixelFormat: i32, nBytes: u32, // TODO: what to do with BytesParamIndex 2? ppfd: ?*PIXELFORMATDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetPixelFormat( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetPixelFormat( hdc: ?HDC, format: i32, ppfd: ?*const PIXELFORMATDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetEnhMetaFilePixelFormat( hemf: ?HENHMETAFILE, cbBuffer: u32, // TODO: what to do with BytesParamIndex 1? ppfd: ?*PIXELFORMATDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglCopyContext( param0: ?HGLRC, param1: ?HGLRC, param2: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglCreateContext( param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) ?HGLRC; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglCreateLayerContext( param0: ?HDC, param1: i32, ) callconv(@import("std").os.windows.WINAPI) ?HGLRC; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglDeleteContext( param0: ?HGLRC, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglGetCurrentContext( ) callconv(@import("std").os.windows.WINAPI) ?HGLRC; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglGetCurrentDC( ) callconv(@import("std").os.windows.WINAPI) ?HDC; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglGetProcAddress( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?PROC; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglMakeCurrent( param0: ?HDC, param1: ?HGLRC, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglShareLists( param0: ?HGLRC, param1: ?HGLRC, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglUseFontBitmapsA( param0: ?HDC, param1: u32, param2: u32, param3: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglUseFontBitmapsW( param0: ?HDC, param1: u32, param2: u32, param3: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SwapBuffers( param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglUseFontOutlinesA( param0: ?HDC, param1: u32, param2: u32, param3: u32, param4: f32, param5: f32, param6: i32, param7: ?*GLYPHMETRICSFLOAT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglUseFontOutlinesW( param0: ?HDC, param1: u32, param2: u32, param3: u32, param4: f32, param5: f32, param6: i32, param7: ?*GLYPHMETRICSFLOAT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglDescribeLayerPlane( param0: ?HDC, param1: i32, param2: i32, param3: u32, param4: ?*LAYERPLANEDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglSetLayerPaletteEntries( param0: ?HDC, param1: i32, param2: i32, param3: i32, param4: ?*const u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglGetLayerPaletteEntries( param0: ?HDC, param1: i32, param2: i32, param3: i32, param4: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglRealizeLayerPalette( param0: ?HDC, param1: i32, param2: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "OPENGL32" fn wglSwapLayerBuffers( param0: ?HDC, param1: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (2) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const wglUseFontBitmaps = thismodule.wglUseFontBitmapsA; pub const wglUseFontOutlines = thismodule.wglUseFontOutlinesA; }, .wide => struct { pub const wglUseFontBitmaps = thismodule.wglUseFontBitmapsW; pub const wglUseFontOutlines = thismodule.wglUseFontOutlinesW; }, .unspecified => if (@import("builtin").is_test) struct { pub const wglUseFontBitmaps = *opaque{}; pub const wglUseFontOutlines = *opaque{}; } else struct { pub const wglUseFontBitmaps = @compileError("'wglUseFontBitmaps' requires that UNICODE be set to true or false in the root module"); pub const wglUseFontOutlines = @compileError("'wglUseFontOutlines' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (5) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const HDC = @import("../graphics/gdi.zig").HDC; const HENHMETAFILE = @import("../graphics/gdi.zig").HENHMETAFILE; const PROC = @import("../foundation.zig").PROC; const PSTR = @import("../foundation.zig").PSTR; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/graphics/open_gl.zig
const std = @import("std"); const system = std.os.linux; const ArrayList = std.ArrayList; const Candidate = filter.Candidate; const File = std.fs.File; const filter = @import("filter.zig"); pub const Terminal = struct { tty: File, termios: std.os.termios, raw_termios: std.os.termios, height: usize = undefined, max_height: usize, pub fn init(max_height: usize) !Terminal { var tty = try std.fs.openFileAbsolute("/dev/tty", .{ .read = true, .write = true }); // store original terminal settings to restore later var termios = try std.os.tcgetattr(tty.handle); var raw_termios = termios; raw_termios.iflag &= ~@as(u32, system.ICRNL); raw_termios.lflag &= ~@as(u32, system.ICANON | system.ECHO | system.ISIG); raw_termios.cc[system.V.MIN] = 0; raw_termios.cc[system.V.TIME] = 1; try std.os.tcsetattr(tty.handle, .NOW, raw_termios); return Terminal{ .tty = tty, .termios = termios, .raw_termios = raw_termios, .max_height = max_height, }; } pub fn deinit(self: *Terminal) void { std.os.tcsetattr(self.tty.handle, .NOW, self.termios) catch return; self.tty.close(); } pub fn determineHeight(self: *Terminal) void { const win_size = self.windowSize(); self.height = std.math.clamp(self.max_height, 1, win_size.?.y - 1); } fn write(self: *Terminal, args: anytype) void { std.fmt.format(self.tty.writer(), "\x1b[{d}{c}", args) catch unreachable; } pub fn clearLine(self: *Terminal) void { self.write(.{ 0, 'G' }); self.write(.{ 2, 'K' }); } pub fn lineUp(self: *Terminal) void { self.write(.{ 1, 'A' }); } pub fn lineDown(self: *Terminal) void { self.write(.{ 1, 'B' }); } pub fn cursorVisible(self: *Terminal, show: bool) void { if (show) { self.write(.{ 25, 'h' }); } else { self.write(.{ 25, 'l' }); } } pub fn sgr(self: *Terminal, code: usize) void { self.write(.{ code, 'm' }); } const WinSize = struct { x: usize, y: usize, }; pub fn windowSize(self: *Terminal) ?WinSize { var size: std.os.linux.winsize = undefined; if (std.os.linux.ioctl(self.tty.handle, std.os.system.T.IOCGWINSZ, @ptrToInt(&size)) == -1) { return null; } return WinSize{ .x = size.ws_col, .y = size.ws_row }; } }; const Key = union(enum) { character: u8, control: u8, esc, up, down, left, right, backspace, delete, enter, none, }; fn readKey(file: std.fs.File) Key { // reading may fail (timeout) var byte = file.reader().readByte() catch return .none; // escape if (byte == '\x1b') { var seq: [2]u8 = undefined; seq[0] = file.reader().readByte() catch return .esc; seq[1] = file.reader().readByte() catch return .esc; if (seq[0] == '[') { return switch (seq[1]) { 'A' => .up, 'B' => .down, 'C' => .right, 'D' => .left, '3' => .delete, else => .esc, }; } return .esc; } switch (byte) { '\r' => return .enter, 127 => return .backspace, else => {}, } // control chars if (std.ascii.isCntrl(byte)) return .{ .control = byte }; // ascii chars if (std.ascii.isPrint(byte)) return .{ .character = byte }; return .none; } // the number of rows of output const num_rows: usize = 10; const State = struct { cursor: usize, selected: usize, }; fn draw(terminal: *Terminal, state: *State, query: ArrayList(u8), candidates: []Candidate) !void { const win_size = terminal.windowSize(); terminal.cursorVisible(false); terminal.clearLine(); // draw the candidates var i: usize = 0; while (i < terminal.height) : (i += 1) { terminal.lineDown(); terminal.clearLine(); if (i == state.selected) { terminal.sgr(7); } else { terminal.sgr(0); } if (i < candidates.len) { var str = candidates[i].str[0..std.math.min(win_size.?.x, candidates[i].str.len)]; try std.fmt.format(terminal.tty.writer(), "{s}\r", .{str}); } if (i == state.selected) terminal.sgr(0); } terminal.sgr(0); i = 0; while (i < terminal.height) : (i += 1) { terminal.lineUp(); } // draw the prompt try std.fmt.format(terminal.tty.writer(), "> {s}\r", .{query.items}); // move cursor by drawing chars _ = try terminal.tty.writer().write("> "); for (query.items) |c, index| { if (index == state.cursor) break; _ = try terminal.tty.writer().writeByte(c); } terminal.cursorVisible(true); } fn ctrl(comptime key: u8) u8 { return key & 0x1f; } fn charOrNull(char: u8) ?u8 { // word separator chars for c-w word deletion const word_chars = " -_/."; const idx = std.mem.indexOfScalar(u8, word_chars, char); if (idx) |i| { return word_chars[i]; } return null; } pub fn run(allocator: std.mem.Allocator, terminal: *Terminal, candidates: []Candidate) !?ArrayList(u8) { var query = ArrayList(u8).init(allocator); defer query.deinit(); var state = State{ .cursor = 0, .selected = 0, }; // ensure enough room to draw all `num_rows` lines of output by drawing blank lines // effectively scrolling the view terminal.determineHeight(); { var i: usize = 0; while (i < terminal.height) : (i += 1) { _ = try terminal.tty.writer().write("\n"); } i = 0; while (i < terminal.height) : (i += 1) terminal.lineUp(); } var filtered = candidates; var old_state = state; var old_query = try allocator.alloc(u8, query.items.len); var redraw = true; while (true) { // did the query change? if (!std.mem.eql(u8, query.items, old_query)) { allocator.free(old_query); old_query = try allocator.alloc(u8, query.items.len); std.mem.copy(u8, old_query, query.items); filtered = try filter.rankCandidates(allocator, candidates, query.items); redraw = true; state.selected = 0; } // did the selection move? if (redraw or state.cursor != old_state.cursor or state.selected != old_state.selected) { old_state = state; try draw(terminal, &state, query, filtered); redraw = false; } const visible_rows = std.math.min(terminal.height, filtered.len); var key = readKey(terminal.tty); switch (key) { .character => |byte| { try query.insert(state.cursor, byte); state.cursor += 1; }, .control => |byte| { switch (byte) { // handle ctrl-c here rather than signals to allow for proper cleanup ctrl('c') => break, ctrl('w') => { if (state.cursor > 0) { const first_sep = charOrNull(query.items[state.cursor - 1]); while (first_sep != null and state.cursor > 0 and first_sep.? == query.items[state.cursor - 1]) { _ = query.pop(); state.cursor -= 1; } while (state.cursor > 0) { _ = query.pop(); state.cursor -= 1; if (state.cursor == 0) break; const sep = charOrNull(query.items[state.cursor - 1]); if (first_sep == null and sep != null) break; if (first_sep != null and sep != null and first_sep.? == sep.?) break; } } }, ctrl('u') => { while (state.cursor > 0) { _ = query.orderedRemove(state.cursor - 1); state.cursor -= 1; } }, ctrl('p') => if (state.selected > 0) { state.selected -= 1; }, ctrl('n') => if (state.selected < visible_rows - 1) { state.selected += 1; }, else => {}, } }, .backspace => { if (query.items.len > 0 and state.cursor == query.items.len) { _ = query.pop(); state.cursor -= 1; } else if (query.items.len > 0 and state.cursor > 0) { _ = query.orderedRemove(state.cursor); state.cursor -= 1; } }, .delete => { if (query.items.len > 0 and state.cursor < query.items.len) { _ = query.orderedRemove(state.cursor); } }, .up => if (state.selected > 0) { state.selected -= 1; }, .down => if (state.selected < visible_rows - 1) { state.selected += 1; }, .left => if (state.cursor > 0) { state.cursor -= 1; }, .right => if (state.cursor < query.items.len) { state.cursor += 1; }, .enter => { if (filtered.len == 0) break; var selected = ArrayList(u8).init(allocator); try selected.appendSlice(filtered[state.selected].str); return selected; }, .esc => break, .none => {}, } } return null; } pub fn cleanUp(terminal: *Terminal) !void { // offset to handle prompt line var i: usize = 0; while (i < terminal.height) : (i += 1) { terminal.clearLine(); terminal.lineDown(); } terminal.clearLine(); i = 0; while (i < terminal.height) : (i += 1) { terminal.lineUp(); } }
src/ui.zig
const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const math = std.math; const mem = std.mem; const testing = std.testing; const unicode = std.unicode; pub const ascii = @import("src/ascii.zig"); pub const utf8 = @import("src/utf8.zig"); /// All the ways in which a parser can fail. /// ParserFailed corresponds to the string not matching the expected form and is /// the only one `mecha` intrinsically deals with. pub const Error = error{ ParserFailed, OtherError } || mem.Allocator.Error; pub const Void = Result(void); /// The result of a successful parse pub fn Result(comptime T: type) type { return struct { pub const Value = T; value: T, rest: []const u8 = "", }; } /// The type of all parser that can work with `mecha` pub fn Parser(comptime T: type) type { return ParserWithCC(T, .Unspecified); } pub fn ParserWithCC(comptime T: type, comptime cc: std.builtin.CallingConvention) type { return fn (*mem.Allocator, []const u8) callconv(cc) Error!Result(T); } fn typecheckParser(comptime P: type) void { switch (@typeInfo(P)) { .Fn => |func| { const R = func.return_type orelse @compileError("expected 'mecha.Parser(T)', found '" ++ @typeName(P) ++ "'"); const T = switch (@typeInfo(R)) { .ErrorUnion => |e| e.payload.Value, else => @compileError("expected 'mecha.Parser(T)', found '" ++ @typeName(P) ++ "'"), }; if (P != ParserWithCC(T, func.calling_convention)) @compileError("expected 'mecha.Parser(" ++ @typeName(T) ++ ")', found '" ++ @typeName(P) ++ "'"); }, else => @compileError("expected 'mecha.Parser(T)', found '" ++ @typeName(P) ++ "'"), } } fn ReturnType(comptime P: type) type { return @typeInfo(P).Fn.return_type.?; } /// The reverse of `Parser`. Give it a `Parser` type /// and this function will give you `T`. pub fn ParserResult(comptime P: type) type { typecheckParser(P); return @typeInfo(ReturnType(P)).ErrorUnion.payload.Value; } /// A parser that always succeeds and parses nothing. This parser /// is only really useful for generic code. See `many`. pub fn noop(_: *mem.Allocator, str: []const u8) Error!Void { return Void{ .value = {}, .rest = str }; } /// A parser that only succeeds on the end of the string. pub fn eos(_: *mem.Allocator, str: []const u8) Error!Void { if (str.len != 0) return error.ParserFailed; return Void{ .value = {}, .rest = str }; } test "eos" { const allocator = testing.failing_allocator; expectResult(void, .{ .value = {} }, eos(allocator, "")); expectResult(void, error.ParserFailed, eos(allocator, "a")); } /// A parser that always succeeds with the result being the /// entire string. The same as the '.*$' regex. pub fn rest(_: *mem.Allocator, str: []const u8) Error!Result([]const u8) { return Result([]const u8){ .value = str, .rest = str[str.len..] }; } test "rest" { const allocator = testing.failing_allocator; expectResult([]const u8, .{ .value = "" }, rest(allocator, "")); expectResult([]const u8, .{ .value = "a" }, rest(allocator, "a")); } /// Construct a parser that succeeds if the string passed in starts /// with `str`. pub fn string(comptime str: []const u8) Parser(void) { return struct { fn func(_: *mem.Allocator, s: []const u8) Error!Void { if (!mem.startsWith(u8, s, str)) return error.ParserFailed; return Void{ .value = {}, .rest = s[str.len..] }; } }.func; } test "string" { const allocator = testing.failing_allocator; expectResult(void, .{ .value = {} }, string("aa")(allocator, "aa")); expectResult(void, .{ .value = {}, .rest = "a" }, string("aa")(allocator, "aaa")); expectResult(void, error.ParserFailed, string("aa")(allocator, "ba")); expectResult(void, error.ParserFailed, string("aa")(allocator, "")); } pub const ManyNOptions = struct { /// A parser used to parse the content between each element `manyN` parses. /// The default is `noop`, so each element will be parsed one after another. separator: anytype = noop, }; /// Construct a parser that repeatedly uses `parser` until `n` iterations is reached. /// The parser's result will be an array of the results from the repeated parser. pub fn manyN( comptime parser: anytype, comptime n: usize, comptime options: ManyNOptions, ) Parser([n]ParserResult(@TypeOf(parser))) { const Array = [n]ParserResult(@TypeOf(parser)); const Res = Result(Array); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { var rem = str; var res: Array = undefined; for (res) |*value, i| { if (i != 0) rem = (try options.separator(allocator, rem)).rest; const r = try parser(allocator, rem); rem = r.rest; value.* = r.value; } return Res{ .value = res, .rest = rem }; } }.func; } test "manyN" { const allocator = testing.failing_allocator; const parser1 = comptime manyN(ascii.range('a', 'b'), 3, .{}); expectResult([3]u8, .{ .value = "aba".*, .rest = "bab" }, parser1(allocator, "ababab")); const parser2 = comptime manyN(ascii.range('a', 'b'), 3, .{ .separator = ascii.char(',') }); expectResult([3]u8, .{ .value = "aba".*, .rest = ",b,a,b" }, parser2(allocator, "a,b,a,b,a,b")); } pub const ManyOptions = struct { /// The min number of elements `many` should parse for parsing to be /// considered successful. min: usize = 0, /// The maximum number of elements `many` will parse. `many` will stop /// parsing after reaching this number of elements even if more elements /// could be parsed. max: usize = math.maxInt(usize), /// Have `many` collect the results of all elements in an allocated slice. /// Setting this to false, and `many` will instead just return the parsed /// string as the result without any allocation. collect: bool = true, /// A parser used to parse the content between each element `many` parses. /// The default is `noop`, so each element will be parsed one after another. separator: anytype = noop, }; fn Many(comptime parser: anytype, comptime options: ManyOptions) type { if (options.collect) return []ParserResult(@TypeOf(parser)); return []const u8; } /// Construct a parser that repeatedly uses `parser` as long as it succeeds /// or until `opt.max` is reach. See `ManyOptions` for options this function /// exposes. pub fn many(comptime parser: anytype, comptime options: ManyOptions) Parser(Many(parser, options)) { const ElementParser = @TypeOf(parser); const Element = ParserResult(ElementParser); const Res = Result(Many(parser, options)); typecheckParser(ElementParser); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { var res = if (options.collect) try std.ArrayList(Element).initCapacity(allocator, options.min) else {}; errdefer if (options.collect) res.deinit(); var rem = str; var i: usize = 0; while (i < options.max) : (i += 1) { const after_seperator = if (i != 0) (options.separator(allocator, rem) catch break).rest else rem; const r = parser(allocator, after_seperator) catch |e| switch (e) { error.ParserFailed => break, else => return e, }; rem = r.rest; if (options.collect) try res.append(r.value); } if (i < options.min) return error.ParserFailed; return Res{ .value = if (options.collect) res.toOwnedSlice() else str[0 .. str.len - rem.len], .rest = rem, }; } }.func; } test "many" { const allocator = testing.failing_allocator; const parser1 = comptime many(string("ab"), .{ .collect = false }); expectResult([]const u8, .{ .value = "" }, parser1(allocator, "")); expectResult([]const u8, .{ .value = "", .rest = "a" }, parser1(allocator, "a")); expectResult([]const u8, .{ .value = "ab" }, parser1(allocator, "ab")); expectResult([]const u8, .{ .value = "ab", .rest = "a" }, parser1(allocator, "aba")); expectResult([]const u8, .{ .value = "abab" }, parser1(allocator, "abab")); expectResult([]const u8, .{ .value = "abab", .rest = "a" }, parser1(allocator, "ababa")); expectResult([]const u8, .{ .value = "ababab" }, parser1(allocator, "ababab")); const parser2 = comptime many(string("ab"), .{ .collect = false, .min = 1, .max = 2 }); expectResult([]const u8, error.ParserFailed, parser2(allocator, "")); expectResult([]const u8, error.ParserFailed, parser2(allocator, "a")); expectResult([]const u8, .{ .value = "ab" }, parser2(allocator, "ab")); expectResult([]const u8, .{ .value = "ab", .rest = "a" }, parser2(allocator, "aba")); expectResult([]const u8, .{ .value = "abab" }, parser2(allocator, "abab")); expectResult([]const u8, .{ .value = "abab", .rest = "a" }, parser2(allocator, "ababa")); expectResult([]const u8, .{ .value = "abab", .rest = "ab" }, parser2(allocator, "ababab")); const parser3 = comptime many(string("ab"), .{ .collect = false, .separator = ascii.char(',') }); expectResult([]const u8, .{ .value = "" }, parser3(allocator, "")); expectResult([]const u8, .{ .value = "", .rest = "a" }, parser3(allocator, "a")); expectResult([]const u8, .{ .value = "ab" }, parser3(allocator, "ab")); expectResult([]const u8, .{ .value = "ab", .rest = "a" }, parser3(allocator, "aba")); expectResult([]const u8, .{ .value = "ab", .rest = "ab" }, parser3(allocator, "abab")); expectResult([]const u8, .{ .value = "ab,ab" }, parser3(allocator, "ab,ab")); expectResult([]const u8, .{ .value = "ab,ab", .rest = "," }, parser3(allocator, "ab,ab,")); const parser4 = comptime many(utf8.char(0x100), .{ .collect = false }); expectResult([]const u8, .{ .value = "ĀĀĀ", .rest = "āāā" }, parser4(allocator, "ĀĀĀāāā")); const parser5 = comptime many(utf8.range(0x100, 0x100), .{}); const res = try parser5(testing.allocator, "ĀĀĀāāā"); defer testing.allocator.free(res.value); var expect = [_]u21{ 'Ā', 'Ā', 'Ā' }; expectResult([]u21, .{ .value = &expect, .rest = "āāā" }, res); } /// Construct a parser that will call `parser` on the string /// but never fails to parse. The parser's result will be the /// result of `parser` on success and `null` on failure. pub fn opt(comptime parser: anytype) Parser(?ParserResult(@TypeOf(parser))) { const Res = Result(?ParserResult(@TypeOf(parser))); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { const r = parser(allocator, str) catch |e| switch (e) { error.ParserFailed => return Res{ .value = null, .rest = str }, else => return e, }; return Res{ .value = r.value, .rest = r.rest }; } }.func; } test "opt" { const allocator = testing.failing_allocator; const parser1 = comptime opt(ascii.range('a', 'z')); expectResult(?u8, .{ .value = 'a' }, parser1(allocator, "a")); expectResult(?u8, .{ .value = 'a', .rest = "a" }, parser1(allocator, "aa")); expectResult(?u8, .{ .value = null, .rest = "1" }, parser1(allocator, "1")); } fn parsersTypes(comptime parsers: anytype) []const type { var types: []const type = &[_]type{}; for (parsers) |parser| { const T = ParserResult(@TypeOf(parser)); if (T != void) types = types ++ [_]type{T}; } return types; } fn Combine(comptime parsers: anytype) type { const types = parsersTypes(parsers); if (types.len == 0) return void; if (types.len == 1) return types[0]; return Tuple(types.len, types[0..types.len].*); } /// HACK: Zig cannot cache functions that takes pointers (slices) /// so we have to passed the types as an array by value. fn Tuple(comptime n: usize, comptime types: [n]type) type { return std.meta.Tuple(&types); } /// Takes a tuple of `Parser(any)` and constructs a parser that /// only succeeds if all parsers succeed to parse. The parsers /// will be called in order and parser `N` will use the `rest` /// from parser `N-1`. The parsers result will be a `Tuple` of /// all parser not of type `Parser(void)`. If only one parser /// is not of type `Parser(void)` then this parsers result is /// returned instead of a tuple. pub fn combine(comptime parsers: anytype) Parser(Combine(parsers)) { const types = parsersTypes(parsers); const Res = Result(Combine(parsers)); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { var res: Res = undefined; res.rest = str; comptime var i = 0; comptime var j = 0; inline while (i < parsers.len) : (i += 1) { const r = try parsers[i](allocator, res.rest); res.rest = r.rest; if (@TypeOf(r.value) != void) { if (types.len == 1) { res.value = r.value; } else { res.value[j] = r.value; } j += 1; } } return res; } }.func; } test "combine" { const allocator = testing.failing_allocator; const parser1 = comptime combine(.{ opt(ascii.range('a', 'b')), opt(ascii.range('d', 'e')) }); const Res = ParserResult(@TypeOf(parser1)); expectResult(Res, .{ .value = .{ .@"0" = 'a', .@"1" = 'd' } }, parser1(allocator, "ad")); expectResult(Res, .{ .value = .{ .@"0" = 'a', .@"1" = null }, .rest = "a" }, parser1(allocator, "aa")); expectResult(Res, .{ .value = .{ .@"0" = null, .@"1" = 'd' }, .rest = "a" }, parser1(allocator, "da")); expectResult(Res, .{ .value = .{ .@"0" = null, .@"1" = null }, .rest = "qa" }, parser1(allocator, "qa")); const parser2 = comptime combine(.{ opt(ascii.range('a', 'b')), ascii.char('d') }); expectResult(?u8, .{ .value = 'a' }, parser2(allocator, "ad")); expectResult(?u8, .{ .value = 'a', .rest = "a" }, parser2(allocator, "ada")); expectResult(?u8, .{ .value = null, .rest = "a" }, parser2(allocator, "da")); expectResult(?u8, error.ParserFailed, parser2(allocator, "qa")); } /// Takes a tuple of `Parser(T)` and constructs a parser that /// only succeeds if one of the parsers succeed to parse. The /// parsers will be called in order all with `str` as input. /// The parser will return with the result of the first parser /// that succeeded. The parsers result will be `Result(T)` pub fn oneOf(comptime parsers: anytype) Parser(ParserResult(@TypeOf(parsers[0]))) { inline for (parsers) |parser| typecheckParser(@TypeOf(parser)); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Result(ParserResult(@TypeOf(parsers[0]))) { inline for (parsers) |p| { if (p(allocator, str)) |res| { return res; } else |e| { switch (e) { error.ParserFailed => {}, else => return e, } } } return error.ParserFailed; } }.func; } test "oneOf" { const allocator = testing.failing_allocator; const parser1 = comptime oneOf(.{ ascii.range('a', 'b'), ascii.range('d', 'e') }); expectResult(u8, .{ .value = 'a' }, parser1(allocator, "a")); expectResult(u8, .{ .value = 'b' }, parser1(allocator, "b")); expectResult(u8, .{ .value = 'd' }, parser1(allocator, "d")); expectResult(u8, .{ .value = 'e' }, parser1(allocator, "e")); expectResult(u8, .{ .value = 'a', .rest = "a" }, parser1(allocator, "aa")); expectResult(u8, .{ .value = 'b', .rest = "a" }, parser1(allocator, "ba")); expectResult(u8, .{ .value = 'd', .rest = "a" }, parser1(allocator, "da")); expectResult(u8, .{ .value = 'e', .rest = "a" }, parser1(allocator, "ea")); expectResult(u8, error.ParserFailed, parser1(allocator, "q")); } /// Takes any parser (preferable not of type `Parser([]const u8)`) /// and converts it to a parser where the result is a string that /// contains all characters parsed by `parser`. pub fn asStr(comptime parser: anytype) Parser([]const u8) { const Res = Result([]const u8); typecheckParser(@TypeOf(parser)); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { const r = try parser(allocator, str); return Res{ .value = str[0 .. str.len - r.rest.len], .rest = r.rest }; } }.func; } test "asStr" { const allocator = testing.failing_allocator; const parser1 = comptime asStr(ascii.char('a')); expectResult([]const u8, .{ .value = "a" }, parser1(allocator, "a")); expectResult([]const u8, .{ .value = "a", .rest = "a" }, parser1(allocator, "aa")); expectResult([]const u8, error.ParserFailed, parser1(allocator, "ba")); const parser2 = comptime asStr(combine(.{ opt(ascii.range('a', 'b')), opt(ascii.range('d', 'e')) })); expectResult([]const u8, .{ .value = "ad" }, parser2(allocator, "ad")); expectResult([]const u8, .{ .value = "a", .rest = "a" }, parser2(allocator, "aa")); expectResult([]const u8, .{ .value = "d", .rest = "a" }, parser2(allocator, "da")); expectResult([]const u8, .{ .value = "", .rest = "qa" }, parser2(allocator, "qa")); } /// Constructs a parser that has its result converted with the /// `conv` function. The ´conv` functions signature is /// `fn (*mem.Allocator, ParserResult(parser)) !T`. /// The parser constructed will fail if `conv` fails. pub fn convert( comptime T: type, comptime conv: anytype, comptime parser: anytype, ) Parser(T) { const Res = Result(T); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { const r = try parser(allocator, str); const v = conv(allocator, r.value) catch |e| switch (@as(anyerror, e)) { error.ParserFailed => return error.ParserFailed, error.OutOfMemory => return error.OutOfMemory, else => return error.OtherError, }; return Res{ .value = v, .rest = r.rest }; } }.func; } /// Constructs a convert function for `convert` that takes a /// string and parses it to an int of type `Int`. pub fn toInt(comptime Int: type, comptime base: u8) fn (*mem.Allocator, []const u8) Error!Int { return struct { fn func(_: *mem.Allocator, str: []const u8) Error!Int { return fmt.parseInt(Int, str, base) catch error.ParserFailed; } }.func; } /// Constructs a convert function for `convert` that takes a /// string and parses it to a float of type `Float`. pub fn toFloat(comptime Float: type) fn (*mem.Allocator, []const u8) Error!Float { return struct { fn func(_: *mem.Allocator, str: []const u8) Error!Float { return fmt.parseFloat(Float, str) catch error.ParserFailed; } }.func; } /// A convert function for `convert` that takes a string and /// returns the first codepoint. pub fn toChar(_: *mem.Allocator, str: []const u8) anyerror!u21 { if (str.len > 1) { const cp_len = try unicode.utf8ByteSequenceLength(str[0]); if (cp_len > str.len) return error.ParserFailed; return unicode.utf8Decode(str[0..cp_len]) catch error.ParserFailed; } return @as(u21, str[0]); } /// Constructs a convert function for `convert` that takes a /// string and converts it to an `Enum` with `std.meta.stringToEnum`. pub fn toEnum(comptime Enum: type) fn (*mem.Allocator, []const u8) Error!Enum { return struct { fn func(_: *mem.Allocator, str: []const u8) Error!Enum { return std.meta.stringToEnum(Enum, str) orelse error.ParserFailed; } }.func; } /// A convert function for `convert` that takes a string /// and returns `true` if it is `"true"` and `false` if it /// is `"false"`. pub fn toBool(allocator: *mem.Allocator, str: []const u8) Error!bool { const r = try toEnum(enum { @"false", @"true" })(allocator, str); return r == .@"true"; } test "convert" { const allocator = testing.failing_allocator; const parser1 = comptime convert(u8, toInt(u8, 10), asStr(string("123"))); expectResult(u8, .{ .value = 123 }, parser1(allocator, "123")); expectResult(u8, .{ .value = 123, .rest = "a" }, parser1(allocator, "123a")); expectResult(u8, error.ParserFailed, parser1(allocator, "12")); const parser2 = comptime convert(u21, toChar, asStr(string("a"))); expectResult(u21, .{ .value = 'a' }, parser2(allocator, "a")); expectResult(u21, .{ .value = 'a', .rest = "a" }, parser2(allocator, "aa")); expectResult(u21, error.ParserFailed, parser2(allocator, "b")); const parser3 = comptime convert(bool, toBool, rest); expectResult(bool, .{ .value = true }, parser3(allocator, "true")); expectResult(bool, .{ .value = false }, parser3(allocator, "false")); expectResult(bool, error.ParserFailed, parser3(allocator, "b")); const parser4 = comptime convert(f32, toFloat(f32), asStr(string("1.23"))); expectResult(f32, .{ .value = 1.23 }, parser4(allocator, "1.23")); expectResult(f32, .{ .value = 1.23, .rest = "a" }, parser4(allocator, "1.23a")); expectResult(f32, error.ParserFailed, parser4(allocator, "1.2")); const E = packed enum(u8) { a, b, _ }; const parser5 = comptime convert(E, toEnum(E), rest); expectResult(E, .{ .value = E.a }, parser5(allocator, "a")); expectResult(E, .{ .value = E.b }, parser5(allocator, "b")); expectResult(E, error.ParserFailed, parser5(allocator, "2")); const parser6 = comptime convert(u21, toChar, asStr(string("Āā"))); expectResult(u21, .{ .value = 0x100 }, parser6(allocator, "Āā")); } /// Constructs a parser that has its result converted with the /// `conv` function. The ´conv` functions signature is /// `fn (ParserResult(parser)) T`, so this function should only /// be used for conversions that cannot fail. See `convert`. pub fn map( comptime T: type, comptime conv: anytype, comptime parser: anytype, ) Parser(T) { const Res = Result(T); typecheckParser(@TypeOf(parser)); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { const r = try parser(allocator, str); return Res{ .value = conv(r.value), .rest = r.rest }; } }.func; } fn ToStructResult(comptime T: type) type { return @TypeOf(struct { fn func(tuple: anytype) T { return undefined; } }.func); } /// Constructs a convert function for `map` that takes a tuple or an array and /// converts it into the struct `T`. Fields will be assigned in order, /// so `tuple[i]` will be assigned to the ith field of `T`. This function /// will give a compile error if `T` and the tuple does not have the same /// number of fields, or if the items of the tuple cannot be coerced into /// the fields of the struct. pub fn toStruct(comptime T: type) ToStructResult(T) { return struct { fn func(tuple: anytype) T { const struct_fields = @typeInfo(T).Struct.fields; if (struct_fields.len != tuple.len) @compileError(@typeName(T) ++ " and " ++ @typeName(@TypeOf(tuple)) ++ " does not have " ++ "same number of fields. Conversion is not possible."); var res: T = undefined; inline for (struct_fields) |field, i| @field(res, field.name) = tuple[i]; return res; } }.func; } test "map" { const allocator = testing.failing_allocator; const Point = struct { x: usize, y: usize, }; const parser1 = comptime map(Point, toStruct(Point), combine(.{ int(usize, .{}), ascii.char(' '), int(usize, .{}) })); expectResult(Point, .{ .value = .{ .x = 10, .y = 10 } }, parser1(allocator, "10 10")); expectResult(Point, .{ .value = .{ .x = 20, .y = 20 }, .rest = "aa" }, parser1(allocator, "20 20aa")); expectResult(Point, error.ParserFailed, parser1(allocator, "12")); const parser2 = comptime map(Point, toStruct(Point), manyN(combine(.{ int(usize, .{}), ascii.char(' ') }), 2, .{})); expectResult(Point, .{ .value = .{ .x = 10, .y = 10 } }, parser2(allocator, "10 10 ")); expectResult(Point, .{ .value = .{ .x = 20, .y = 20 }, .rest = "aa" }, parser2(allocator, "20 20 aa")); expectResult(Point, error.ParserFailed, parser2(allocator, "12")); } /// Constructs a parser that discards the result returned from the parser /// it wraps. pub fn discard(comptime parser: anytype) Parser(void) { return map(void, struct { fn d(_: anytype) void {} }.d, parser); } test "discard" { const allocator = testing.failing_allocator; const parser = comptime discard(many(ascii.char(' '), .{ .collect = false })); expectResult(void, .{ .value = {}, .rest = "abc" }, parser(allocator, "abc")); expectResult(void, .{ .value = {}, .rest = "abc" }, parser(allocator, " abc")); expectResult(void, .{ .value = {}, .rest = "abc" }, parser(allocator, " abc")); } fn digitsForBase(val: anytype, base: u8) usize { var res: usize = 0; var tmp = val; while (tmp != 0) : (tmp /= @intCast(@TypeOf(val), base)) res += 1; return math.max(1, res); } pub const IntOptions = struct { /// Parse `+/-` prefix of the int as well parse_sign: bool = true, base: u8 = 10, max_digits: usize = math.maxInt(usize), }; /// Construct a parser that succeeds if it parser an integer of /// `base`. This parser will stop parsing digits after `max_digits` /// after the leading zeros haven been reached. The result of this /// parser will be the string containing the match. pub fn intToken(comptime options: IntOptions) Parser([]const u8) { debug.assert(options.max_digits != 0); const sign_parser = if (options.parse_sign) oneOf(.{ ascii.char('-'), ascii.char('+'), noop }) else noop; return comptime asStr(combine(.{ sign_parser, many(ascii.digit(options.base), .{ .collect = false, .min = 1, .max = options.max_digits, }), })); } /// Same as `intToken` but also converts the parsed string to an /// integer. This parser will at most parse the same number of digits /// as the underlying interger can hold in the specified base. pub fn int(comptime Int: type, comptime options: IntOptions) Parser(Int) { debug.assert(options.max_digits != 0); const Res = Result(Int); return struct { fn intParser(_: *mem.Allocator, str: []const u8) Error!Res { if (options.parse_sign and str.len != 0) { switch (str[0]) { '+' => return parseAfterSign(str[1..], add), '-' => return parseAfterSign(str[1..], sub), else => {}, } } return parseAfterSign(str, add); } fn parseAfterSign(str: []const u8, add_sub: fn (Int, Int) Overflow!Int) Error!Res { if (str.len == 0) return error.ParserFailed; const max_digits = math.min(str.len, options.max_digits); const first = fmt.charToDigit(str[0], options.base) catch return error.ParserFailed; const first_casted = math.cast(Int, first) catch return error.ParserFailed; var res = add_sub(0, first_casted) catch return error.ParserFailed; const end = for (str[1..max_digits]) |c, i| { const d = fmt.charToDigit(c, options.base) catch break i; const casted_b = math.cast(Int, options.base) catch break i; const casted_d = math.cast(Int, d) catch break i; const next = math.mul(Int, res, casted_b) catch break i; res = add_sub(next, casted_d) catch break i; } else max_digits - 1; return Res{ .value = res, .rest = str[end + 1 ..] }; } const Overflow = error{Overflow}; fn add(a: Int, b: Int) Overflow!Int { return math.add(Int, a, b); } fn sub(a: Int, b: Int) Overflow!Int { return math.sub(Int, a, b); } }.intParser; } test "int" { const allocator = testing.failing_allocator; const parser1 = int(u8, .{}); expectResult(u8, .{ .value = 0 }, parser1(allocator, "0")); expectResult(u8, .{ .value = 1 }, parser1(allocator, "1")); expectResult(u8, .{ .value = 1, .rest = "a" }, parser1(allocator, "1a")); expectResult(u8, .{ .value = 255 }, parser1(allocator, "255")); expectResult(u8, .{ .value = 255, .rest = "5" }, parser1(allocator, "2555")); expectResult(u8, .{ .value = 25, .rest = "6" }, parser1(allocator, "256")); expectResult(u8, .{ .value = 255 }, parser1(allocator, "+255")); expectResult(u8, error.ParserFailed, parser1(allocator, "-255")); const parser2 = int(u8, .{ .base = 16 }); expectResult(u8, .{ .value = 0x00 }, parser2(allocator, "0")); expectResult(u8, .{ .value = 0x01 }, parser2(allocator, "1")); expectResult(u8, .{ .value = 0x1a }, parser2(allocator, "1a")); expectResult(u8, .{ .value = 0x01, .rest = "g" }, parser2(allocator, "1g")); expectResult(u8, .{ .value = 0xff }, parser2(allocator, "ff")); expectResult(u8, .{ .value = 0xff }, parser2(allocator, "FF")); expectResult(u8, .{ .value = 0xff }, parser2(allocator, "00FF")); expectResult(u8, .{ .value = 0x10, .rest = "0" }, parser2(allocator, "100")); expectResult(u8, .{ .value = 0xf, .rest = "g" }, parser2(allocator, "fg")); expectResult(u8, .{ .value = 0xff }, parser2(allocator, "+ff")); expectResult(u8, error.ParserFailed, parser2(allocator, "-ff")); const parser3 = int(u8, .{ .base = 16, .max_digits = 2 }); expectResult(u8, .{ .value = 0xff }, parser3(allocator, "FF")); expectResult(u8, .{ .value = 0x00, .rest = "FF" }, parser3(allocator, "00FF")); const parser4 = int(isize, .{}); expectResult(isize, .{ .value = 255 }, parser4(allocator, "+255")); expectResult(isize, .{ .value = -255 }, parser4(allocator, "-255")); const parser5 = int(isize, .{ .parse_sign = false }); expectResult(isize, .{ .value = 255 }, parser5(allocator, "255")); expectResult(isize, error.ParserFailed, parser5(allocator, "+255")); expectResult(isize, error.ParserFailed, parser5(allocator, "-255")); } /// Construct a parser that succeeds if it parses any tag from `Enum` as /// a string. The longest match is always chosen, so for `enum{a,aa}` the /// "aa" string will succeed parsing and have the result of `.aa` and not /// `.a`. pub fn enumeration(comptime Enum: type) Parser(Enum) { const Res = Result(Enum); return struct { fn func(allocator: *mem.Allocator, str: []const u8) Error!Res { var res: Error!Res = error.ParserFailed; inline for (@typeInfo(Enum).Enum.fields) |field| next: { const p = comptime string(field.name); const new = p(allocator, str) catch |err| switch (err) { error.ParserFailed => break :next, else => |e| return e, }; const old = res catch Res{ .value = undefined, .rest = str }; if (new.rest.len < old.rest.len) res = Res{ .value = @field(Enum, field.name), .rest = new.rest }; } return res; } }.func; } test "enumeration" { const allocator = testing.failing_allocator; const E1 = enum { a, b, aa }; const parser1 = enumeration(E1); expectResult(E1, .{ .value = .a }, parser1(allocator, "a")); expectResult(E1, .{ .value = .aa }, parser1(allocator, "aa")); expectResult(E1, .{ .value = .b }, parser1(allocator, "b")); expectResult(E1, .{ .value = .a, .rest = "b" }, parser1(allocator, "ab")); expectResult(E1, .{ .value = .b, .rest = "b" }, parser1(allocator, "bb")); expectResult(E1, error.ParserFailed, parser1(allocator, "256")); } /// Creates a parser that calls a function to obtain its underlying parser. /// This function introduces the indirection required for recursive grammars. /// ``` /// const digit_10 = discard(digit(10)); /// const digits = oneOf(.{ combine(.{ digit_10, ref(digits_ref) }), digit_10 }); /// fn digits_ref() Parser(void) { /// return digits; /// }; /// ``` pub fn ref(comptime func: anytype) Parser(ParserResult(ReturnType(@TypeOf(func)))) { const P = ReturnType(@TypeOf(func)); const T = ParserResult(P); return struct { fn res(allocator: *mem.Allocator, str: []const u8) Error!Result(T) { return func()(allocator, str); } }.res; } test "ref" { const allocator = testing.failing_allocator; const Scope = struct { const digit = discard(ascii.digit(10)); const digits = oneOf(.{ combine(.{ digit, ref(digits_ref) }), digit }); fn digits_ref() Parser(void) { return digits; } }; expectResult(void, .{ .value = {} }, Scope.digits(allocator, "0")); } pub fn expectResult( comptime T: type, m_expect: Error!Result(T), m_actual: Error!Result(T), ) void { const expect = m_expect catch |err| { testing.expectError(err, m_actual); return; }; const actual = m_actual catch |err| std.debug.panic("expected {}, found {} ", .{ expect.value, err }); testing.expectEqualStrings(expect.rest, actual.rest); switch (T) { []const u8 => testing.expectEqualStrings(expect.value, actual.value), else => switch (@typeInfo(T)) { .Pointer => |ptr| testing.expectEqualSlices(ptr.child, expect.value, actual.value), else => testing.expectEqual(expect.value, actual.value), }, } }
mecha.zig
const std = @import("std"); const testing = std.testing; fn flattenT(comptime T: type) type { return struct { const Self = @This(); list: []const []const T, const Iterator = struct { list: []const []const T, outer: usize, inner: usize, fn next(self: *Iterator) ?T { if (self.outer == self.list.len) return null; if (self.inner == self.list[self.outer].len) { self.inner = 1; // set it to the next element self.outer = self.outer + 1; while (self.outer < self.list.len and self.list[self.outer].len == 0) { self.outer = self.outer + 1; } if (self.outer == self.list.len) return null; return self.list[self.outer][0]; } const a = self.list[self.outer][self.inner]; self.inner = self.inner + 1; return a; } }; fn init(list: []const []const T) Self { return Self{ .list = list, }; } fn iterator(self: *Self) Iterator { return Iterator{ .list = self.list, .outer = 0, .inner = 0, }; } }; } fn flatten(list: var) flattenT(@typeOf(list).Child.Child).Iterator { const T = @typeOf(list).Child.Child; return flattenT(T).init(list).iterator(); } test "flatten.non_empty" { const list = ([][]const i32{ ([]i32{1,2,3})[0..], ([]i32{4,5})[0..], })[0..]; var iter = flatten(list); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next().? == 3); testing.expect(iter.next().? == 4); testing.expect(iter.next().? == 5); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "flatten.with_empty" { const list = ([][]const i32{ []i32{}, []i32{1,2}, []i32{}, []i32{}, []i32{3}, })[0..]; var iter = flatten(list); testing.expect(iter.next().? == 1); testing.expect(iter.next().? == 2); testing.expect(iter.next().? == 3); testing.expect(iter.next() == null); testing.expect(iter.next() == null); } test "flatten.empty" { const list = ([][]i32{})[0..]; var iter = flatten(list); testing.expect(iter.next() == null); testing.expect(iter.next() == null); }
src/flatten.zig
const std = @import("std"); const os = std.os; const tcp = std.x.net.tcp; const ip = std.x.net.ip; const net = std.net; const linux = std.os.linux; const IPv4 = std.x.os.IPv4; const Socket = std.x.os.Socket; const fd_t = linux.fd_t; const IO_Uring = linux.IO_Uring; const io_uring_sqe = linux.io_uring_sqe; const IORING_OP = std.os.linux.IORING_OP; const assert = std.debug.assert; const uring = @import("./ring.zig") const Server = struct { const Self = @This(); ring: IO_Uring, fn init(ring: IO_Uring) Server { return Server{ .ring = ring, }; } fn deinit(self: *Self) void { self.ring.deinit(); } fn prep_accept(self: *Self, socket: fd_t, flags: std.enums.EnumFieldStruct(Socket.InitFlags, bool, false)) !*io_uring_sqe { var raw_flags: u32 = 0; const set = std.EnumSet(Socket.InitFlags).init(flags); if (set.contains(.close_on_exec)) raw_flags |= linux.SOCK.CLOEXEC; if (set.contains(.nonblocking)) raw_flags |= linux.SOCK.NONBLOCK; return self.ring.accept(@bitCast(u64, Handle.accept()), socket, null, null, raw_flags); } fn prep_provide_buffers(self: *Self, num_bufs: i32, base_addr: [*]u8, buf_len: usize, group_id: u16, buf_id: u64) !*io_uring_sqe { const sqe = try self.ring.get_sqe(); linux.io_uring_prep_rw(.PROVIDE_BUFFERS, sqe, num_bufs, @ptrToInt(base_addr), buf_len, buf_id); sqe.buf_index = group_id; // this is really the buf_group; sqe.user_data = @bitCast(u64, Handle{ .op = .PROVIDE_BUFFERS, }); return sqe; } const BufOptions = union(enum) { select: struct { buf_group: u16, }, }; fn prep_recv(self: *Self, fd: fd_t, len: usize, buf_opts: BufOptions) !*io_uring_sqe { const sqe = try self.ring.get_sqe(); switch (buf_opts) { // TODO: handle non-provided buffers. .select => |b| { linux.io_uring_prep_rw(.RECV, sqe, fd, 0, len, 0); sqe.user_data = @bitCast(u64, Handle.recv(fd, b.buf_group)); sqe.flags = linux.IOSQE_BUFFER_SELECT; sqe.buf_index = b.buf_group; // this is really the buf_group; }, } return sqe; } }; pub fn BufferGroup(comptime init_num_bufs: usize, comptime each_buf_size: usize) type { return struct { // bufs: std.ArrayListAlignedUnmanaged(T, [each_buf_size]u8) = .{}, bufs: [init_num_bufs][each_buf_size]u8 = undefined, const Self = @This(); }; } /// /// A TCP listener. pub fn main() !void { const address = ip.Address.initIPv4(try IPv4.parse("127.0.0.1"), 3131); var listener = try tcp.Listener.init(.ip, .{ .close_on_exec = true, .nonblocking = false, }); defer listener.deinit(); try listener.bind(address); try listener.listen(1); var server: Server = .{ .ring = try linux.IO_Uring.init(256, 0), }; defer server.deinit(); var need_accept = true; const BUF_COUNT = 16; const BUF_SIZE = 4096; const BUF_GROUP = 36; var bufs: [BUF_COUNT][BUF_SIZE]u8 = undefined; { _ = try server.prep_provide_buffers(bufs.len, &bufs[0], BUF_SIZE, BUF_GROUP, 0); } while (true) { if (need_accept) { std.log.info("queue accept", .{}); _ = try server.prep_accept(listener.socket.fd, .{ .close_on_exec = true, .nonblocking = false, }); need_accept = false; } const nsqe_submitted = try server.ring.submit_and_wait(1); std.log.info("nsqe_submitted: {}", .{nsqe_submitted}); const cqe = try server.ring.copy_cqe(); const handle = @bitCast(Handle, cqe.user_data); switch (handle.op) { .ACCEPT => { need_accept = true; const client_fd = cqe.res; const client_addr = Socket.Address.fromNative(@ptrCast(*os.sockaddr, &server.accept_state.addr)); // new accepted connection. std.log.info("accept: {}", .{client_addr}); _ = try server.prep_recv(client_fd, BUF_SIZE, .{ .select = .{ .buf_group = BUF_GROUP, }, }); }, .READ, .RECV => { // linux.io_uring_prep_recv const bytes_read = cqe.res; const is_fixed_buf = cqe.flags & linux.IORING_CQE_F_BUFFER == 1; const buf_id = cqe.flags >> 16; // IORING_CQE_BUFFER_SHIFT const data = bufs[buf_id][0..@intCast(usize, bytes_read)]; std.log.info("read {} {s}", .{ bytes_read, data }); // Give the buf back. if (is_fixed_buf) { _ = try server.prep_provide_buffers(1, &bufs[buf_id], BUF_SIZE, BUF_GROUP, buf_id); // const sqe = try ring.get_sqe(); // linux.io_uring_prep_rw(.PROVIDE_BUFFERS, sqe, 1, @ptrToInt(&bufs[buf_id][0]), BUF_SIZE, buf_id); // sqe.buf_index = BUF_GROUP; // this is really the buf_group; // sqe.user_data = @bitCast(u64, Handle{ // .op = .PROVIDE_BUFFERS, // }); } }, // .PROVIDE_BUFFERS => else => { std.log.info("state unhandled {}", .{handle}); }, } } }
src/io_uring-tcp-hasher/v3.zig
const std = @import("std"); const testing = std.testing; pub const Password = struct { pub fn init() Password { var self = Password{}; return self; } pub fn deinit(self: *Password) void { _ = self; } pub fn check_count(self: Password, line: []const u8) bool { _ = self; const data = parse_line(line); var cnt: usize = 0; var pos: usize = 0; while (pos < data.pass.len) : (pos += 1) { if (data.pass[pos] == data.chr) { cnt += 1; } } const ok = (cnt >= data.n1 and cnt <= data.n2); return ok; } pub fn check_pos(self: Password, line: []const u8) bool { _ = self; const data = parse_line(line); var cnt: usize = 0; if (data.pass.len >= data.n1 and data.pass[data.n1 - 1] == data.chr) { cnt += 1; } if (data.pass.len >= data.n2 and data.pass[data.n2 - 1] == data.chr) { cnt += 1; } const ok = (cnt == 1); return ok; } const Data = struct { n1: usize, n2: usize, chr: u8, pass: []const u8, pub fn init() Data { var self = Data{ .n1 = 0, .n2 = 0, .chr = 0, .pass = undefined, }; return self; } }; fn parse_line(line: []const u8) Data { var data = Data.init(); var pos: usize = 0; var it = std.mem.tokenize(u8, line, " -:"); while (it.next()) |field| { pos += 1; if (pos == 1) { data.n1 = std.fmt.parseInt(usize, field, 10) catch unreachable; continue; } if (pos == 2) { data.n2 = std.fmt.parseInt(usize, field, 10) catch unreachable; continue; } if (pos == 3) { data.chr = field[0]; continue; } if (pos == 4) { data.pass = field; continue; } std.debug.warn("TOO MANY PARTS\n", .{}); data.chr = 0; break; } return data; } }; test "sample count" { const valid = 2; const data: []const u8 = \\1-3 a: abcde \\1-3 b: cdefg \\2-9 c: ccccccccc ; var password = Password.init(); defer password.deinit(); var count: usize = 0; var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { if (password.check_count(line)) { count += 1; } } try testing.expect(count == valid); } test "sample pos" { const valid = 1; const data: []const u8 = \\1-3 a: abcde \\1-3 b: cdefg \\2-9 c: ccccccccc ; var password = Password.init(); defer password.deinit(); var count: usize = 0; var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { if (password.check_pos(line)) { count += 1; } } try testing.expect(count == valid); }
2020/p02/password.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const input = @embedFile("../inputs/day05.txt"); const i32_max: i32 = std.math.maxInt(i32); const i32_min: i32 = std.math.minInt(i32); pub fn run(alloc: Allocator, stdout_: anytype) !void { var bottom_left: [2]i32 = undefined; var top_right: [2]i32 = undefined; const lines = try parseInput(alloc, &bottom_left, &top_right); defer alloc.free(lines); var board = try Board.init(alloc, bottom_left, top_right); defer board.deinit(); const res1 = part1(lines, &board); const res2 = part2(lines, &board) + res1; if (stdout_) |stdout| { try stdout.print("Part 1: {}\n", .{res1}); try stdout.print("Part 2: {}\n", .{res2}); } } const LineKind = enum { const_x, const_y, diagonal }; const Line = struct { x: [2]i32, y: [2]i32, kind: LineKind, const Self = @This(); pub fn init(p0: [2]i32, p1: [2]i32) Self { const kind: LineKind = if (p0[0] == p1[0]) LineKind.const_x else if (p0[1] == p1[1]) LineKind.const_y else LineKind.diagonal; const x: [2]i32 = .{ p0[0], p1[0] }; const y: [2]i32 = .{ p0[1], p1[1] }; return Self{ .x = x, .y = y, .kind = kind, }; } /// Inserts all of the points on this line into the given board, and returns /// the amount of points that were upgraded to count 2. pub fn insertToBoard(self: *Self, board: *Board) ?i32 { var amount: i32 = 0; var x = self.x[0]; var y = self.y[0]; switch (self.kind) { .const_x => { y = @minimum(y, self.y[1]); while (y <= @maximum(self.y[0], self.y[1])) : (y += 1) { amount += Self.insertPoint(board, x, y) orelse return null; } }, .const_y => { x = @minimum(x, self.x[1]); while (x <= @maximum(self.x[0], self.x[1])) : (x += 1) { amount += Self.insertPoint(board, x, y) orelse return null; } }, .diagonal => { const x_offset = Self.calcDelta(self.x); const y_offset = Self.calcDelta(self.y); var i: i32 = 0; const len = std.math.absInt(self.x[1] - self.x[0]) catch unreachable; while (i <= len) : (i += 1) { amount += Self.insertPoint(board, x, y) orelse return null; x += x_offset; y += y_offset; } }, } return amount; } fn calcDelta(arr: [2]i32) i32 { return if (arr[0] < arr[1]) 1 else -1; } fn insertPoint(board: *Board, x: i32, y: i32) ?i32 { const count = board.insertPoint(.{ x, y }) orelse return null; return if (count == 2) 1 else 0; } }; const Board = struct { map: []i32, // maps Point -> Count (as a matrix) alloc: Allocator, bottom_left: [2]i32, x_length: usize, y_length: usize, const Self = @This(); pub fn init(alloc: Allocator, bottom_left: [2]i32, top_right: [2]i32) !Self { const x_length = @intCast(usize, top_right[0] - bottom_left[0] + 1); const y_length = @intCast(usize, top_right[1] - bottom_left[1] + 1); var map = try alloc.alloc(i32, x_length * y_length); for (map) |*pos| { pos.* = 0; } return Self{ .map = map, .alloc = alloc, .bottom_left = bottom_left, .x_length = x_length, .y_length = y_length, }; } fn get(self: *Self, i: usize, j: usize) ?*i32 { if (i >= self.x_length or j >= self.y_length) return null; return &self.map[i * self.y_length + j]; } pub fn getPoint(self: *Self, pt: [2]i32) ?*i32 { if (pt[0] < self.bottom_left[0] or pt[1] < self.bottom_left[1]) return null; const i = @intCast(usize, pt[0] - self.bottom_left[0]); const j = @intCast(usize, pt[1] - self.bottom_left[1]); return self.get(i, j); } /// Inserts a point into the board, and returns its updated count. pub fn insertPoint(self: *Self, point: [2]i32) ?i32 { var entry = self.getPoint(point) orelse return null; entry.* += 1; return entry.*; } pub fn deinit(self: *Self) void { self.alloc.free(self.map); } }; fn part1(lines: []Line, board: *Board) i32 { var counter: i32 = 0; for (lines) |*line| { if (line.kind == .diagonal) continue; counter += line.insertToBoard(board).?; } return counter; } fn part2(lines: []Line, board: *Board) i32 { var counter: i32 = 0; for (lines) |*line| { if (line.kind != .diagonal) continue; counter += line.insertToBoard(board).?; } return counter; } fn parseInput(alloc: Allocator, lower_left: *[2]i32, top_right: *[2]i32) ![]Line { const line_num = std.mem.count(u8, input, "\n"); var linelist = try alloc.alloc(Line, line_num); var min_x = i32_max; var max_x = i32_min; var min_y = i32_max; var max_y = i32_min; var lines_iter = std.mem.tokenize(u8, input, "\r\n"); for (linelist) |*line| { line.* = try parseLine(lines_iter.next().?); min_x = std.math.min3(min_x, line.x[0], line.x[1]); max_x = std.math.max3(max_x, line.x[0], line.x[1]); min_y = std.math.min3(min_y, line.y[0], line.y[1]); max_y = std.math.max3(max_y, line.y[0], line.y[1]); } lower_left.* = .{ min_x, min_y }; top_right.* = .{ max_x, max_y }; return linelist; } fn parseLine(str: []const u8) !Line { var points = std.mem.split(u8, str, " -> "); const p0 = try parsePoint(points.next().?); const p1 = try parsePoint(points.next().?); return Line.init(p0, p1); } fn parsePoint(str: []const u8) ![2]i32 { var nums = std.mem.split(u8, str, ","); const num0 = try std.fmt.parseInt(i32, nums.next().?, 10); const num1 = try std.fmt.parseInt(i32, nums.next().?, 10); return [2]i32{ num0, num1 }; }
src/day05.zig
const std = @import("std"); pub const CodeGeneratorError = error{OutOfMemory}; pub const CodeGenerator = struct { allocator: std.mem.Allocator, string_pool: std.ArrayList([]const u8), globals: std.ArrayList([]const u8), bytecode: std.ArrayList(u8), const Self = @This(); const word_size = @sizeOf(i32); pub fn init( allocator: std.mem.Allocator, string_pool: std.ArrayList([]const u8), globals: std.ArrayList([]const u8), ) Self { return CodeGenerator{ .allocator = allocator, .string_pool = string_pool, .globals = globals, .bytecode = std.ArrayList(u8).init(allocator), }; } pub fn gen(self: *Self, ast: ?*Tree) CodeGeneratorError!void { try self.genH(ast); try self.emitHalt(); } // Helper function to allow recursion. pub fn genH(self: *Self, ast: ?*Tree) CodeGeneratorError!void { if (ast) |t| { switch (t.typ) { .sequence => { try self.genH(t.left); try self.genH(t.right); }, .kw_while => { const condition_address = self.currentAddress(); try self.genH(t.left); try self.emitByte(.jz); const condition_address_hole = self.currentAddress(); try self.emitHole(); try self.genH(t.right); try self.emitByte(.jmp); try self.emitInt(condition_address); self.insertInt(condition_address_hole, self.currentAddress()); }, .kw_if => { try self.genH(t.left); try self.emitByte(.jz); const condition_address_hole = self.currentAddress(); try self.emitHole(); try self.genH(t.right.?.left); if (t.right.?.right) |else_tree| { try self.emitByte(.jmp); const else_address_hole = self.currentAddress(); try self.emitHole(); const else_address = self.currentAddress(); try self.genH(else_tree); self.insertInt(condition_address_hole, else_address); self.insertInt(else_address_hole, self.currentAddress()); } else { self.insertInt(condition_address_hole, self.currentAddress()); } }, .assign => { try self.genH(t.right); try self.emitByte(.store); try self.emitInt(self.fetchGlobalsOffset(t.left.?.value.?.string)); }, .prts => { try self.genH(t.left); try self.emitByte(.prts); }, .prti => { try self.genH(t.left); try self.emitByte(.prti); }, .prtc => { try self.genH(t.left); try self.emitByte(.prtc); }, .string => { try self.emitByte(.push); try self.emitInt(self.fetchStringsOffset(t.value.?.string)); }, .integer => { try self.emitByte(.push); try self.emitInt(t.value.?.integer); }, .identifier => { try self.emitByte(.fetch); try self.emitInt(self.fetchGlobalsOffset(t.value.?.string)); }, .negate, .not => { try self.genH(t.left); try self.emitByte(Op.fromNodeType(t.typ).?); }, .add, .multiply, .subtract, .divide, .mod, .less, .less_equal, .greater, .greater_equal, .equal, .not_equal, .bool_and, .bool_or, => try self.genBinOp(t), .unknown => { std.debug.print("\nINTERP: UNKNOWN {}\n", .{t.typ}); std.os.exit(1); }, } } } fn genBinOp(self: *Self, tree: *Tree) CodeGeneratorError!void { try self.genH(tree.left); try self.genH(tree.right); try self.emitByte(Op.fromNodeType(tree.typ).?); } fn emitByte(self: *Self, op: Op) CodeGeneratorError!void { try self.bytecode.append(@enumToInt(op)); } fn emitInt(self: *Self, n: i32) CodeGeneratorError!void { var n_var = n; var n_bytes = @ptrCast(*[4]u8, &n_var); for (n_bytes) |byte| { try self.bytecode.append(byte); } } // Holes are later populated via `insertInt` because they can't be known when // we populate the bytecode array sequentially. fn emitHole(self: *Self) CodeGeneratorError!void { try self.emitInt(std.math.maxInt(i32)); } // Populates the "hole" produced by `emitHole`. fn insertInt(self: *Self, address: i32, n: i32) void { var i: i32 = 0; var n_var = n; var n_bytes = @ptrCast(*[4]u8, &n_var); while (i < word_size) : (i += 1) { self.bytecode.items[@intCast(usize, address + i)] = n_bytes[@intCast(usize, i)]; } } fn emitHalt(self: *Self) CodeGeneratorError!void { try self.bytecode.append(@enumToInt(Op.halt)); } fn currentAddress(self: Self) i32 { return @intCast(i32, self.bytecode.items.len); } fn fetchStringsOffset(self: Self, str: []const u8) i32 { for (self.string_pool.items) |string, idx| { if (std.mem.eql(u8, string, str)) { return @intCast(i32, idx); } } unreachable; } fn fetchGlobalsOffset(self: Self, str: []const u8) i32 { for (self.globals.items) |global, idx| { if (std.mem.eql(u8, global, str)) { return @intCast(i32, idx); } } unreachable; } pub fn print(self: Self) ![]u8 { var result = std.ArrayList(u8).init(self.allocator); var writer = result.writer(); try writer.print( "Datasize: {d} Strings: {d}\n", .{ self.globals.items.len, self.string_pool.items.len }, ); for (self.string_pool.items) |string| { try writer.print("{s}\n", .{string}); } var pc: usize = 0; while (pc < self.bytecode.items.len) : (pc += 1) { try writer.print("{d:>5} ", .{pc}); switch (@intToEnum(Op, self.bytecode.items[pc])) { .push => { try writer.print("push {d}\n", .{self.unpackInt(pc + 1)}); pc += word_size; }, .store => { try writer.print("store [{d}]\n", .{self.unpackInt(pc + 1)}); pc += word_size; }, .fetch => { try writer.print("fetch [{d}]\n", .{self.unpackInt(pc + 1)}); pc += word_size; }, .jz => { const address = self.unpackInt(pc + 1); try writer.print("jz ({d}) {d}\n", .{ address - @intCast(i32, pc) - 1, address }); pc += word_size; }, .jmp => { const address = self.unpackInt(pc + 1); try writer.print("jmp ({d}) {d}\n", .{ address - @intCast(i32, pc) - 1, address }); pc += word_size; }, else => try writer.print("{s}\n", .{Op.toString(@intToEnum(Op, self.bytecode.items[pc]))}), } } return result.items; } fn unpackInt(self: Self, pc: usize) i32 { const arg_ptr = @ptrCast(*[4]u8, self.bytecode.items[pc .. pc + word_size]); var arg_array = arg_ptr.*; const arg = @ptrCast(*i32, @alignCast(@alignOf(i32), &arg_array)); return arg.*; } }; pub const Op = enum(u8) { fetch, store, push, add, sub, mul, div, mod, lt, gt, le, ge, eq, ne, @"and", @"or", neg, not, jmp, jz, prtc, prts, prti, halt, const from_node = std.enums.directEnumArray(NodeType, ?Op, 0, .{ .unknown = null, .identifier = null, .string = null, .integer = null, .sequence = null, .kw_if = null, .prtc = null, .prts = null, .prti = null, .kw_while = null, .assign = null, .negate = .neg, .not = .not, .multiply = .mul, .divide = .div, .mod = .mod, .add = .add, .subtract = .sub, .less = .lt, .less_equal = .le, .greater = .gt, .greater_equal = .ge, .equal = .eq, .not_equal = .ne, .bool_and = .@"and", .bool_or = .@"or", }); pub fn fromNodeType(node_type: NodeType) ?Op { return from_node[@enumToInt(node_type)]; } const to_string = std.enums.directEnumArray(Op, []const u8, 0, .{ .fetch = "fetch", .store = "store", .push = "push", .add = "add", .sub = "sub", .mul = "mul", .div = "div", .mod = "mod", .lt = "lt", .gt = "gt", .le = "le", .ge = "ge", .eq = "eq", .ne = "ne", .@"and" = "and", .@"or" = "or", .neg = "neg", .not = "not", .jmp = "jmp", .jz = "jz", .prtc = "prtc", .prts = "prts", .prti = "prti", .halt = "halt", }); pub fn toString(self: Op) []const u8 { return to_string[@enumToInt(self)]; } }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var arg_it = std.process.args(); _ = try arg_it.next(allocator) orelse unreachable; // program name const file_name = arg_it.next(allocator); // We accept both files and standard input. var file_handle = blk: { if (file_name) |file_name_delimited| { const fname: []const u8 = try file_name_delimited; break :blk try std.fs.cwd().openFile(fname, .{}); } else { break :blk std.io.getStdIn(); } }; defer file_handle.close(); const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, input_content, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const result: []const u8 = try code_generator.print(); _ = try std.io.getStdOut().write(result); } pub const NodeType = enum { unknown, identifier, string, integer, sequence, kw_if, prtc, prts, prti, kw_while, assign, negate, not, multiply, divide, mod, add, subtract, less, less_equal, greater, greater_equal, equal, not_equal, bool_and, bool_or, const from_string_map = std.ComptimeStringMap(NodeType, .{ .{ "UNKNOWN", .unknown }, .{ "Identifier", .identifier }, .{ "String", .string }, .{ "Integer", .integer }, .{ "Sequence", .sequence }, .{ "If", .kw_if }, .{ "Prtc", .prtc }, .{ "Prts", .prts }, .{ "Prti", .prti }, .{ "While", .kw_while }, .{ "Assign", .assign }, .{ "Negate", .negate }, .{ "Not", .not }, .{ "Multiply", .multiply }, .{ "Divide", .divide }, .{ "Mod", .mod }, .{ "Add", .add }, .{ "Subtract", .subtract }, .{ "Less", .less }, .{ "LessEqual", .less_equal }, .{ "Greater", .greater }, .{ "GreaterEqual", .greater_equal }, .{ "Equal", .equal }, .{ "NotEqual", .not_equal }, .{ "And", .bool_and }, .{ "Or", .bool_or }, }); pub fn fromString(str: []const u8) NodeType { return from_string_map.get(str).?; } }; pub const NodeValue = union(enum) { integer: i32, string: []const u8, }; pub const Tree = struct { left: ?*Tree, right: ?*Tree, typ: NodeType = .unknown, value: ?NodeValue = null, fn makeNode(allocator: std.mem.Allocator, typ: NodeType, left: ?*Tree, right: ?*Tree) !*Tree { const result = try allocator.create(Tree); result.* = Tree{ .left = left, .right = right, .typ = typ }; return result; } fn makeLeaf(allocator: std.mem.Allocator, typ: NodeType, value: ?NodeValue) !*Tree { const result = try allocator.create(Tree); result.* = Tree{ .left = null, .right = null, .typ = typ, .value = value }; return result; } }; const LoadASTError = error{OutOfMemory} || std.fmt.ParseIntError; fn loadAST( allocator: std.mem.Allocator, str: []const u8, string_pool: *std.ArrayList([]const u8), globals: *std.ArrayList([]const u8), ) LoadASTError!?*Tree { var line_it = std.mem.split(u8, str, "\n"); return try loadASTHelper(allocator, &line_it, string_pool, globals); } fn loadASTHelper( allocator: std.mem.Allocator, line_it: *std.mem.SplitIterator(u8), string_pool: *std.ArrayList([]const u8), globals: *std.ArrayList([]const u8), ) LoadASTError!?*Tree { if (line_it.next()) |line| { var tok_it = std.mem.tokenize(u8, line, " "); const tok_str = tok_it.next().?; if (tok_str[0] == ';') return null; const node_type = NodeType.fromString(tok_str); const pre_iteration_index = tok_it.index; if (tok_it.next()) |leaf_value| { const node_value = blk: { switch (node_type) { .integer => break :blk NodeValue{ .integer = try std.fmt.parseInt(i32, leaf_value, 10) }, .identifier => { var already_exists = false; for (globals.items) |global| { if (std.mem.eql(u8, global, leaf_value)) { already_exists = true; break; } } if (!already_exists) try globals.append(leaf_value); break :blk NodeValue{ .string = leaf_value }; }, .string => { tok_it.index = pre_iteration_index; const str = tok_it.rest(); var already_exists = false; for (string_pool.items) |string| { if (std.mem.eql(u8, string, str)) { already_exists = true; break; } } if (!already_exists) try string_pool.append(str); break :blk NodeValue{ .string = str }; }, else => unreachable, } }; return try Tree.makeLeaf(allocator, node_type, node_value); } const left = try loadASTHelper(allocator, line_it, string_pool, globals); const right = try loadASTHelper(allocator, line_it, string_pool, globals); return try Tree.makeNode(allocator, node_type, left, right); } else { return null; } } fn squishSpaces(allocator: std.mem.Allocator, str: []const u8) ![]u8 { var result = std.ArrayList(u8).init(allocator); var was_space = false; for (str) |ch| { switch (ch) { ' ' => { if (!was_space) { was_space = true; try result.append(ch); } }, else => { was_space = false; try result.append(ch); }, } } return result.items; } const testing = std.testing; test "examples" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); { const example_input_path = "examples/parsed0.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened0.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed1.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened1.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed3.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened3.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed4.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened4.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed5.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened5.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed6.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened6.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed7.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened7.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed8.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened8.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed9.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened9.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed10.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened10.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed11.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened11.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed12.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened12.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed13.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened13.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } { const example_input_path = "examples/parsed14.txt"; var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_input); const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize)); const example_output_path = "examples/codegened14.txt"; var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{}); defer std.fs.File.close(file_output); const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize)); var string_pool = std.ArrayList([]const u8).init(allocator); var globals = std.ArrayList([]const u8).init(allocator); const ast = try loadAST(allocator, content_input, &string_pool, &globals); var code_generator = CodeGenerator.init(allocator, string_pool, globals); try code_generator.gen(ast); const pretty_output: []const u8 = try code_generator.print(); const stripped_expected = try squishSpaces(allocator, content_output); const stripped_result = try squishSpaces(allocator, pretty_output); try testing.expectFmt(stripped_expected, "{s}", .{stripped_result}); } }
codegen.zig
const Self = @This(); const std = @import("std"); const wayland = @import("wayland"); const wl = wayland.server.wl; const zriver = wayland.server.zriver; const util = @import("util.zig"); const Output = @import("Output.zig"); const View = @import("View.zig"); const ViewStack = @import("view_stack.zig").ViewStack; const log = std.log.scoped(.river_status); output: *Output, output_status: *zriver.OutputStatusV1, pub fn init(self: *Self, output: *Output, output_status: *zriver.OutputStatusV1) void { self.* = .{ .output = output, .output_status = output_status }; output_status.setHandler(*Self, handleRequest, handleDestroy, self); // Send view/focused/urgent tags once on bind. self.sendViewTags(); self.sendFocusedTags(output.current.tags); var urgent_tags: u32 = 0; var view_it = self.output.views.first; while (view_it) |node| : (view_it = node.next) { if (node.view.current.urgent) urgent_tags |= node.view.current.tags; } self.sendUrgentTags(urgent_tags); } pub fn destroy(self: *Self) void { const node = @fieldParentPtr(std.SinglyLinkedList(Self).Node, "data", self); self.output.status_trackers.remove(node); self.output_status.setHandler(*Self, handleRequest, null, self); util.gpa.destroy(node); } fn handleRequest(output_status: *zriver.OutputStatusV1, request: zriver.OutputStatusV1.Request, self: *Self) void { switch (request) { .destroy => output_status.destroy(), } } fn handleDestroy(output_status: *zriver.OutputStatusV1, self: *Self) void { self.destroy(); } /// Send the current tags of each view on the output to the client. pub fn sendViewTags(self: Self) void { var view_tags = std.ArrayList(u32).init(util.gpa); defer view_tags.deinit(); var it = self.output.views.first; while (it) |node| : (it = node.next) { if (node.view.surface == null) continue; view_tags.append(node.view.current.tags) catch { self.output_status.postNoMemory(); log.crit("out of memory", .{}); return; }; } var wl_array = wl.Array.fromArrayList(u32, view_tags); self.output_status.sendViewTags(&wl_array); } pub fn sendFocusedTags(self: Self, tags: u32) void { self.output_status.sendFocusedTags(tags); } pub fn sendUrgentTags(self: Self, tags: u32) void { if (self.output_status.getVersion() >= 2) { self.output_status.sendUrgentTags(tags); } }
source/river-0.1.0/river/OutputStatus.zig
const std = @import("std"); const mem = std.mem; const meta = std.meta; const net = std.net; const ArrayList = std.ArrayList; usingnamespace @import("../frame.zig"); usingnamespace @import("../primitive_types.zig"); usingnamespace @import("../query_parameters.zig"); const testing = @import("../testing.zig"); /// QUERY is sent to perform a CQL query. /// /// Described in the protocol spec at §4.1.4 pub const QueryFrame = struct { const Self = @This(); query: []const u8, query_parameters: QueryParameters, pub fn write(self: Self, protocol_version: ProtocolVersion, pw: *PrimitiveWriter) !void { _ = try pw.writeLongString(self.query); _ = try self.query_parameters.write(protocol_version, pw); } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self { return Self{ .query = try pr.readLongString(allocator), .query_parameters = try QueryParameters.read(allocator, protocol_version, pr), }; } }; test "query frame: no values, no paging state" { var arena = testing.arenaAllocator(); defer arena.deinit(); // read const exp = "\x04\x00\x00\x08\x07\x00\x00\x00\x30\x00\x00\x00\x1b\x53\x45\x4c\x45\x43\x54\x20\x2a\x20\x46\x52\x4f\x4d\x20\x66\x6f\x6f\x62\x61\x72\x2e\x75\x73\x65\x72\x20\x3b\x00\x01\x34\x00\x00\x00\x64\x00\x08\x00\x05\xa2\x2c\xf0\x57\x3e\x3f"; const raw_frame = try testing.readRawFrame(&arena.allocator, exp); checkHeader(Opcode.Query, exp.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try QueryFrame.read(&arena.allocator, raw_frame.header.version, &pr); testing.expectEqualStrings("SELECT * FROM foobar.user ;", frame.query); testing.expectEqual(Consistency.One, frame.query_parameters.consistency_level); testing.expect(frame.query_parameters.values == null); testing.expectEqual(@as(u32, 100), frame.query_parameters.page_size.?); testing.expect(frame.query_parameters.paging_state == null); testing.expectEqual(Consistency.Serial, frame.query_parameters.serial_consistency_level.?); testing.expectEqual(@as(u64, 1585688778063423), frame.query_parameters.timestamp.?); testing.expect(frame.query_parameters.keyspace == null); testing.expect(frame.query_parameters.now_in_seconds == null); // write testing.expectSameRawFrame(frame, raw_frame.header, exp); }
src/frames/query.zig
const std = @import("std"); const math = std.math; const INT_MIN = math.minInt(i32); const INT_MAX = math.maxInt(i32); const LEAPOCH = @as(i64, 946684800) + 86400 * (31 + 29); const DAYS_PER_400Y = (365 * 400 + 97); const DAYS_PER_100Y = (365 * 100 + 24); const DAYS_PER_4Y = (365 * 4 + 1); const ConversionError = error{ EOVERFLOW, }; pub const time_t: type = i64; pub const tm_t: type = struct { tm_sec: i16 = 0, // Seconds. [0-60] (1 leap second) // c_int tm_min: i16 = 0, // Minutes. [0-59] // c_int tm_hour: i16 = 0, // Hours. [0-23] // c_int tm_mday: i16 = 1, // Day. [1-31] // c_int tm_mon: i16 = 0, // Month. [0-11] // c_int tm_year: i16 = 70, // Year - 1900. // c_int tm_wday: i16 = 0, // Day of week. [0-6] // c_int tm_yday: i16 = 0, // Days in year. [0-365] // c_int tm_isdst: i16 = 0, // DST. [-1/0/1] // c_int tm_gmtoff: i32 = 0, // Seconds east of UTC. // c_long_int tm_zone: [*:0]const u8 = "UTC", // Timezone abbreviation. // c_char }; fn year_to_secs(year: i64, is_leap: *bool) i64 { if (year - @as(u64, 2) <= 136) { var y: i16 = @intCast(i16, year); var leaps: i16 = (y - 68) >> 2; if (((y - 68) & 3) == 0) { leaps -= 1; is_leap.* = true; } else { is_leap.* = false; } return 31536000 * (@intCast(i64, y) - 70) + 86400 * @intCast(i64, leaps); } var cycles: i16 = 0; var centuries: i16 = 0; var leaps: i16 = 0; var rem: i16 = 0; cycles = @intCast(i16, @divTrunc(year - 100, 400)); rem = @intCast(i16, @rem(year - 100, 400)); if (rem < 0) { cycles -= 1; rem += 400; } if (rem == 0) { is_leap.* = true; centuries = 0; leaps = 0; } else { if (rem >= 200) { if (rem >= 300) { centuries = 3; rem -= 300; } else { centuries = 2; rem -= 200; } } else { if (rem >= 100) { centuries = 1; rem -= 100; } else { centuries = 0; } } if (rem == 0) { is_leap.* = false; leaps = 0; } else { leaps = @divTrunc(rem, @as(u16, 4)); rem = @rem(rem, @as(u16, 4)); is_leap.* = rem == 0; } } var remove_leap: i16 = if (is_leap.*) 1 else 0; leaps += 97 * cycles + 24 * centuries - remove_leap; return (year - 100) * @as(i64, 31536000) + leaps * @as(i64, 86400) + 946684800 + 86400; } fn month_to_secs(month: usize, is_leap: bool) i64 { const secs_through_month = [_]i64{ 0, 31 * 86400, 59 * 86400, 90 * 86400, 120 * 86400, 151 * 86400, 181 * 86400, 212 * 86400, 243 * 86400, 273 * 86400, 304 * 86400, 334 * 86400, }; var t: i64 = secs_through_month[month]; if (is_leap and month >= 2) { t += 86400; } return t; } pub fn mktime(tm: *tm_t) time_t { var t: time_t = 0; //__tm_to_secs { var is_leap: bool = false; var year: i64 = tm.tm_year; var month: i16 = tm.tm_mon; if (month >= 12 or month < 0) { var adj: i16 = @divTrunc(month, 12); month = @rem(month, 12); if (month < 0) { adj -= 1; month += 12; } year += adj; } t = year_to_secs(year, &is_leap); t += month_to_secs(@intCast(usize, month), is_leap); t += @as(i64, 86400) * (tm.tm_mday - 1); t += @as(i64, 3600) * tm.tm_hour; t += @as(i64, 60) * tm.tm_min; t += tm.tm_sec; } return t; } pub fn localtime(tp: *const time_t) !*tm_t { var t: time_t = tp.*; var tm: tm_t = undefined; var days: i64 = 0; var secs: i64 = 0; var years: i64 = 0; var remdays: i64 = 0; var remsecs: i64 = 0; var remyears: i64 = 0; var qc_cycles: i64 = 0; var c_cycles: i64 = 0; var q_cycles: i64 = 0; var months: i64 = 0; var wday: i64 = 0; var yday: i64 = 0; var leap: i64 = 0; const days_in_month = [_]u8{ 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29 }; // Reject time_t values whose year would overflow int if (t < INT_MIN * @as(i64, 31622400) or t > INT_MAX * @as(i64, 31622400)) { return ConversionError.EOVERFLOW; } secs = t - LEAPOCH; days = @divTrunc(secs, 86400); remsecs = @rem(secs, 86400); if (remsecs < 0) { remsecs += 86400; days -= 1; } wday = @rem(3 + days, 7); if (wday < 0) wday += 7; qc_cycles = @divTrunc(days, DAYS_PER_400Y); remdays = @rem(days, DAYS_PER_400Y); if (remdays < 0) { remdays += DAYS_PER_400Y; qc_cycles -= 1; } c_cycles = @divTrunc(remdays, DAYS_PER_100Y); if (c_cycles == 4) c_cycles -= 1; remdays -= c_cycles * DAYS_PER_100Y; q_cycles = @divTrunc(remdays, DAYS_PER_4Y); if (q_cycles == 25) q_cycles -= 1; remdays -= q_cycles * DAYS_PER_4Y; remyears = @divTrunc(remdays, 365); if (remyears == 4) remyears -= 1; remdays -= remyears * 365; leap = if (remyears == 0 and (q_cycles > 1 or c_cycles == 0)) 1 else 0; yday = remdays + 31 + 28 + leap; if (yday >= 365 + leap) yday -= 365 + leap; years = remyears + 4 * q_cycles + 100 * c_cycles + @as(i64, 400) * qc_cycles; months = 0; while (days_in_month[@intCast(usize, months)] <= remdays) : (months += 1) { remdays -= days_in_month[@intCast(usize, months)]; } if (months >= 10) { months -= 12; years += 1; } if (years + 100 > INT_MAX or years + 100 < INT_MIN) { return ConversionError.EOVERFLOW; } tm.tm_year = @intCast(i16, years + 100); tm.tm_mon = @intCast(i16, months + 2); tm.tm_mday = @intCast(i16, remdays + 1); tm.tm_wday = @intCast(i16, wday); tm.tm_yday = @intCast(i16, yday); tm.tm_hour = @intCast(i16, @divTrunc(remsecs, 3600)); tm.tm_min = @intCast(i16, @rem(@divTrunc(remsecs, 60), 60)); tm.tm_sec = @intCast(i16, @rem(remsecs, 60)); return &tm; }
src/time.zig
const cuckoo = @import("./cuckoofilter.zig"); // CONSTS export const CF_OK: c_int = 0; export const CF_TOOFULL: c_int = 1; export const CF_BROKEN: c_int = 2; export const CF_BADLEN: c_int = 3; export const CF_ALIGN8: usize = cuckoo.Filter8.Align; export const CF_ALIGN16: usize = cuckoo.Filter16.Align; export const CF_ALIGN32: usize = cuckoo.Filter32.Align; export const CF_MAXERR8: f32 = cuckoo.Filter8.MaxError; export const CF_MAXERR16: f32 = cuckoo.Filter16.MaxError; export const CF_MAXERR32: f32 = cuckoo.Filter32.MaxError; export const Filter8 = extern struct { cf: [@sizeOf(cuckoo.Filter8)]u8 }; export const Filter16 = extern struct { cf: [@sizeOf(cuckoo.Filter16)]u8 }; export const Filter32 = extern struct { cf: [@sizeOf(cuckoo.Filter32)]u8 }; // seed_default_prng export fn seed_default_prng(seed: u64) void { cuckoo.seed_default_prng(seed); } // get_default_rng_state export fn get_default_prng_state() [2]u64 { return cuckoo.get_default_prng_state(); } // set_default_rng_state export fn set_default_prng_state(s: [2]u64) void { cuckoo.set_default_prng_state(s); } // size_for export fn cf_size_for8(min_capacity: usize) usize { return cuckoo.Filter8.size_for(min_capacity); } export fn cf_size_for16(min_capacity: usize) usize { return cuckoo.Filter16.size_for(min_capacity); } export fn cf_size_for32(min_capacity: usize) usize { return cuckoo.Filter32.size_for(min_capacity); } // size_for_exactly export fn cf_size_for_exactly8(min_capacity: usize) usize { return cuckoo.Filter8.size_for_exactly(min_capacity); } export fn cf_size_for_exactly16(min_capacity: usize) usize { return cuckoo.Filter16.size_for_exactly(min_capacity); } export fn cf_size_for_exactly32(min_capacity: usize) usize { return cuckoo.Filter32.size_for_exactly(min_capacity); } // capacity export fn cf_capacity8(size: usize) usize { return cuckoo.Filter8.capacity(size); } export fn cf_capacity16(size: usize) usize { return cuckoo.Filter16.capacity(size); } export fn cf_capacity32(size: usize) usize { return cuckoo.Filter32.capacity(size); } // init export fn cf_init8(memory: [*]u8, size: usize, cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter8.init(@alignCast(cuckoo.Filter8.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_init16(memory: [*]u8, size: usize, cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter16.init(@alignCast(cuckoo.Filter16.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_init32(memory: [*]u8, size: usize, cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter32.init(@alignCast(cuckoo.Filter32.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } // count export fn cf_count8(cf: *Filter8, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_count16(cf: *Filter16, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_count32(cf: *Filter32, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } // maybe_contains export fn cf_maybe_contains8(cf: *Filter8, hash: u64, fp: u8, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } export fn cf_maybe_contains16(cf: *Filter16, hash: u64, fp: u16, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } export fn cf_maybe_contains32(cf: *Filter32, hash: u64, fp: u32, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } // remove export fn cf_remove8(cf: *Filter8, hash: u64, fp: u8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_remove16(cf: *Filter16, hash: u64, fp: u16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_remove32(cf: *Filter32, hash: u64, fp: u32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } // add export fn cf_add8(cf: *Filter8, hash: u64, fp: u8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } export fn cf_add16(cf: *Filter16, hash: u64, fp: u16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } export fn cf_add32(cf: *Filter32, hash: u64, fp: u32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } // is_broken export fn cf_is_broken8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } export fn cf_is_broken16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } export fn cf_is_broken32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } // is_toofull export fn cf_is_toofull8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } export fn cf_is_toofull16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } export fn cf_is_toofull32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } // fix_toofull export fn cf_fix_toofull8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_fix_toofull16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_fix_toofull32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } // To persist a filter you simply need to save the struct's bytes and the its relative buckets // (referred to as `memory` throughout the documentation). The struct contains a pointer // to its `memory` which would not match when loading the filter back again, so use this // function to properly restore it. export fn cf_restore_memory8(cf: *Filter8, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter8.bytesToBuckets(@alignCast(CF_ALIGN8, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_restore_memory16(cf: *Filter16, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter16.bytesToBuckets(@alignCast(CF_ALIGN16, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_restore_memory32(cf: *Filter32, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter32.bytesToBuckets(@alignCast(CF_ALIGN32, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; }
src/cuckoofilter_c.zig
const std = @import("std"); const math = std.math; const zp = @import("zplay"); const alg = zp.deps.alg; const Vec2 = alg.Vec2; const dig = zp.deps.dig; const nvg = zp.deps.nvg; const nsvg = zp.deps.nsvg; var rng: std.rand.DefaultPrng = undefined; var rg: std.rand.Random = undefined; var tiger: nsvg.SVG = undefined; fn init(ctx: *zp.Context) anyerror!void { std.log.info("game init", .{}); // random generator allocation rng = std.rand.DefaultPrng.init(@intCast(u64, std.time.timestamp())); rg = rng.random(); // init imgui try dig.init(ctx.window); // init nanovg context try nvg.init(nvg.c.NVG_ANTIALIAS | nvg.c.NVG_STENCIL_STROKES); tiger = nsvg.loadFile("assets/23.svg", null, null) orelse unreachable; } fn loop(ctx: *zp.Context) void { while (ctx.pollEvent()) |e| { _ = dig.processEvent(e); switch (e) { .keyboard_event => |key| { if (key.trigger_type == .up) { switch (key.scan_code) { .escape => ctx.kill(), .f1 => ctx.toggleFullscreeen(null), else => {}, } } }, .quit_event => ctx.kill(), else => {}, } } var width: u32 = undefined; var height: u32 = undefined; var fwidth: u32 = undefined; var fheight: u32 = undefined; ctx.getWindowSize(&width, &height); ctx.graphics.getDrawableSize(ctx.window, &fwidth, &fheight); ctx.graphics.setViewport(0, 0, fwidth, fheight); ctx.graphics.clear(true, true, true, [_]f32{ 0.3, 0.3, 0.32, 1.0 }); const S = struct { var positions = std.ArrayList(Vec2).init(std.testing.allocator); }; dig.beginFrame(); { dig.setNextWindowPos( .{ .x = @intToFloat(f32, width) - 30, .y = 50 }, .{ .cond = dig.c.ImGuiCond_Always, .pivot = .{ .x = 1, .y = 0 }, }, ); if (dig.begin( "control", null, dig.c.ImGuiWindowFlags_NoMove | dig.c.ImGuiWindowFlags_NoResize | dig.c.ImGuiWindowFlags_AlwaysAutoResize, )) { var buf: [32]u8 = undefined; dig.text(std.fmt.bufPrintZ(&buf, "FPS: {d:.02}", .{dig.getIO().*.Framerate}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "ms/frame: {d:.02}", .{ctx.delta_tick * 1000}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "drawcall count: {d}", .{nvg.getDrawCallCount()}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "tigers: {d}", .{S.positions.items.len}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "shapes: {d}", .{S.positions.items.len * tiger.nshape}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "strokes: {d}", .{S.positions.items.len * tiger.nstroke}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "fills: {d}", .{S.positions.items.len * tiger.nfill}) catch unreachable); dig.text(std.fmt.bufPrintZ(&buf, "paths: {d}", .{S.positions.items.len * tiger.npath}) catch unreachable); dig.separator(); // add tigers var count: u32 = 0; if (dig.button("add 1 tiger", null)) count = 1; if (dig.button("add 10 tiger", null)) count = 10; if (dig.button("clear", null)) S.positions.shrinkRetainingCapacity(0); while (count > 0) : (count -= 1) { S.positions.append(Vec2.new( rg.float(f32) * @intToFloat(f32, fwidth - 200), rg.float(f32) * @intToFloat(f32, fheight), )) catch unreachable; } } dig.end(); } dig.endFrame(); nvg.beginFrame( @intToFloat(f32, width), @intToFloat(f32, height), @intToFloat(f32, fwidth) / @intToFloat(f32, width), ); { // draw tigers for (S.positions.items) |pos| { nvg.save(); nvg.translate(pos.x, pos.y); nvg.scale(0.3, 0.3); nvg.rotate(nvg.degToRad(ctx.tick * 30)); nvg.translate(-tiger.image.width / 2, -tiger.image.height / 2); nvg.svg(tiger); nvg.restore(); } } nvg.endFrame(); } fn quit(ctx: *zp.Context) void { _ = ctx; std.log.info("game quit", .{}); } pub fn main() anyerror!void { try zp.run(.{ .initFn = init, .loopFn = loop, .quitFn = quit, .width = 1000, .height = 600, .enable_vsync = false, }); }
examples/vg_benchmark.zig
const std = @import("std"); const assert = std.debug.assert; const wren = @import("./wren.zig"); const Vm = @import("./vm.zig").Vm; const ErrorType = @import("./vm.zig").ErrorType; fn cStrToSlice(str: [*c]const u8) []const u8 { return str[0..std.mem.lenZ(str)]; } pub fn writeWrapper(cvm: ?*wren.Vm, ctext: [*c]const u8) callconv(.C) void { const vm = Vm.fromC(cvm); const writeFn = vm.writeFn orelse std.debug.panic("writeWrapper must only be installed when writeFn is set", .{}); writeFn(vm, cStrToSlice(ctext)); } pub fn errorWrapper(cvm: ?*wren.Vm, cerr_type: wren.ErrorType, cmodule: [*c]const u8, cline: c_int, cmessage: [*c]const u8) callconv(.C) void { const vm = Vm.fromC(cvm); const errorFn = vm.errorFn orelse std.debug.panic("errorWrapper must only be installed when errorFn is set", .{}); const err_type: ErrorType = switch (cerr_type) { .WREN_ERROR_COMPILE => .Compile, .WREN_ERROR_RUNTIME => .Runtime, .WREN_ERROR_STACK_TRACE => .StackTrace, else => std.debug.panic("unknown error type: {}", .{cerr_type}), }; errorFn(vm, err_type, if (cmodule != null) cStrToSlice(cmodule) else null, if (cline >= 0) @intCast(u32, cline) else null, cStrToSlice(cmessage)); } pub fn resolveModuleWrapper(cvm: ?*wren.Vm, cimporter: [*c]const u8, cname: [*c]const u8) callconv(.C) [*c]u8 { const vm = Vm.fromC(cvm); const resolveModuleFn = vm.resolveModuleFn orelse std.debug.panic("resolveModuleWrapper must only be installed when resolveModuleFn is set", .{}); const mem = resolveModuleFn(vm, cStrToSlice(cimporter), cStrToSlice(cname)); assert(mem.allocator == if (vm.allocator == null) std.heap.c_allocator else vm.allocator); return mem.data.ptr; } pub fn loadModuleWrapper(cvm: ?*wren.Vm, cname: [*c]const u8) callconv(.C) [*c]u8 { const vm = Vm.fromC(cvm); const loadModuleFn = vm.loadModuleFn orelse std.debug.panic("loadModuleWrapper must only be installed when loadModuleFn is set", .{}); const mem = loadModuleFn(vm, cStrToSlice(cname)); assert(mem.allocator == if (vm.allocator == null) std.heap.c_allocator else vm.allocator); return mem.data.ptr; }
src/zapata/c_wrappers.zig
const c = @cImport({ @cInclude("cfl.h"); @cInclude("cfl_menu.h"); }); const widget = @import("widget.zig"); const enums = @import("enums.zig"); pub const WidgetPtr = ?*c.Fl_Widget; fn shim(w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void { _ = w; c.Fl_awake_msg(data); } pub const MenuFlag = enum(i32) { /// Normal item Normal = 0, /// Inactive item Inactive = 1, /// Item is a checkbox toggle (shows checkbox for on/off state) Toggle = 2, /// The on/off state for checkbox/radio buttons (if set, state is 'on') Value = 4, /// Item is a radio button Radio = 8, /// Invisible item Invisible = 0x10, /// Indicates user_data() is a pointer to another menu array (unused with Rust) SubmenuPointer = 0x20, /// Menu item is a submenu Submenu = 0x40, /// Menu divider MenuDivider = 0x80, /// Horizontal menu (actually reserved for future use) MenuHorizontal = 0x100, }; pub const Menu = struct { inner: ?*c.Fl_Menu_Bar, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Menu { const ptr = c.Fl_Menu_Bar_new(x, y, w, h, title); if (ptr == null) unreachable; return Menu{ .inner = ptr, }; } pub fn raw(self: *Menu) ?*c.Fl_Menu_Bar { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Menu_Bar) Menu { return Menu{ .inner = ptr, }; } pub fn fromWidgetPtr(w: ?*c.Fl_Widget) Menu { return Menu{ .inner = @ptrCast(?*c.Fl_Menu_Bar, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Menu { return Menu{ .inner = @ptrCast(?*c.Fl_Menu_Bar, ptr), }; } pub fn toVoidPtr(self: *Menu) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Menu) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn handle(self: *Menu, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Menu_Bar_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Menu, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Menu_Bar_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } pub fn add(self: *Menu, name: [*c]const u8, shortcut: i32, flag: MenuFlag, cb: fn (w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { _ = c.Fl_Menu_Bar_add(self.inner, name, shortcut, cb, data, @enumToInt(flag)); } pub fn insert(self: *Menu, idx: u32, name: [*c]const u8, shortcut: i32, flag: MenuFlag, cb: fn (w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { _ = c.Fl_Menu_Bar_insert(self.inner, idx, name, shortcut, cb, data, @enumToInt(flag)); } pub fn add_emit(self: *Menu, name: [*c]const u8, shortcut: i32, flag: MenuFlag, comptime T: type, msg: T) void { _ = c.Fl_Menu_Bar_add(self.inner, name, shortcut, shim, @intToPtr(?*c_void, @bitCast(usize, msg)), @enumToInt(flag)); } pub fn insert_emit(self: *Menu, idx: u32, name: [*c]const u8, shortcut: i32, flag: MenuFlag, comptime T: type, msg: T) void { _ = c.Fl_Menu_Bar_insert(self.inner, idx, name, shortcut, shim, @intToPtr(?*c_void, @bitCast(usize, msg)), @enumToInt(flag)); } pub fn remove(self: *Menu, idx: u32) void { _ = c.Fl_Menu_Bar_remove(self.inner, idx); } pub fn findItem(self: *Menu, path: [*c]const u8) MenuItem { return MenuItem{ .inner = c.Fl_Menu_Bar_get_item(self.inner, path) }; } pub fn clear(self: *Menu) void { c.Fl_Menu_Bar_clear(self.inner); } pub fn setTextFont(self: *Menu, font: enums.Font) void { c.Fl_Menu_Bar_set_text_font(self.inner, @enumToInt(font)); } pub fn setTextColor(self: *Menu, col: u32) void { c.Fl_Menu_Bar_set_text_color(self.inner, col); } pub fn setTextSize(self: *Menu, sz: u32) void { c.Fl_Menu_Bar_set_text_size(self.inner, sz); } }; pub const MenuBar = struct { inner: ?*c.Fl_Menu_Bar, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) MenuBar { const ptr = c.Fl_Menu_Bar_new(x, y, w, h, title); if (ptr == null) unreachable; return MenuBar{ .inner = ptr, }; } pub fn raw(self: *MenuBar) ?*c.Fl_Menu_Bar { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Menu_Bar) MenuBar { return MenuBar{ .inner = ptr, }; } pub fn fromWidgetPtr(w: ?*c.Fl_Widget) MenuBar { return MenuBar{ .inner = @ptrCast(?*c.Fl_Menu_Bar, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) MenuBar { return MenuBar{ .inner = @ptrCast(?*c.Fl_Menu_Bar, ptr), }; } pub fn toVoidPtr(self: *MenuBar) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const MenuBar) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asMenu(self: *const MenuBar) Menu { return Menu{ .inner = @ptrCast(?*c.Fl_Menu_Bar, self.inner), }; } pub fn handle(self: *MenuBar, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Menu_Bar_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *MenuBar, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Menu_Bar_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const Choice = struct { inner: ?*c.Fl_Choice, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Choice { const ptr = c.Fl_Choice_new(x, y, w, h, title); if (ptr == null) unreachable; return Choice{ .inner = ptr, }; } pub fn raw(self: *Choice) ?*c.Fl_Choice { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Choice) Choice { return Menu{ .inner = ptr, }; } pub fn fromWidgetPtr(w: ?*c.Fl_Widget) Choice { return Menu{ .inner = @ptrCast(?*c.Fl_Choice, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Choice { return Choice{ .inner = @ptrCast(?*c.Fl_Choice, ptr), }; } pub fn toVoidPtr(self: *Choice) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Choice) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asMenu(self: *const Choice) Menu { return Menu{ .inner = @ptrCast(?*c.Fl_Menu_Bar, self.inner), }; } pub fn handle(self: *Menu, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Choice_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Menu, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Choice_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const SysMenuBar = struct { inner: ?*c.Fl_Sys_Menu_Bar, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) SysMenuBar { const ptr = c.Fl_Sys_Menu_Bar_new(x, y, w, h, title); if (ptr == null) unreachable; return SysMenuBar{ .inner = ptr, }; } pub fn raw(self: *SysMenuBar) ?*c.Fl_Sys_Menu_Bar { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Sys_Menu_Bar) SysMenuBar { return SysMenuBar{ .inner = ptr, }; } pub fn fromWidgetPtr(w: ?*c.Fl_Widget) SysMenuBar { return SysMenuBar{ .inner = @ptrCast(?*c.Fl_Sys_Menu_Bar, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) SysMenuBar { return SysMenuBar{ .inner = @ptrCast(?*c.Fl_Sys_Menu_Bar, ptr), }; } pub fn toVoidPtr(self: *SysMenuBar) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const SysMenuBar) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asMenu(self: *const SysMenuBar) Menu { return Menu{ .inner = @ptrCast(?*c.Fl_Menu_Bar, self.inner), }; } pub fn handle(self: *Menu, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Sys_Menu_Bar_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Menu, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Sys_Menu_Bar_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const MenuItem = struct { inner: ?*c.Fl_Menu_Item, pub fn setCallback(self: *MenuItem, cb: fn (w: ?*c.Fl_Widget, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Menu_Item_set_callback(self.inner, cb, data); } pub fn setLabel(self: *MenuItem, str: [*c]const u8) void { c.Fl_Menu_Item_set_label(self.inner, str); } pub fn color(self: *const MenuItem) enums.Color { return @intToEnum(enums.Color, c.Fl_Menu_Item_color(self.inner)); } pub fn labelColor(self: *const MenuItem) enums.Color { return @intToEnum(enums.Color, c.Fl_Menu_Item_label_color(self.inner)); } pub fn setLabelColor(self: *MenuItem, col: u32) void { c.Fl_Menu_Item_set_label_color(self.inner, col); } pub fn labelFont(self: *const MenuItem) enums.Font { return @intToEnum(enums.Font, c.Fl_Menu_Item_label_font(self.inner)); } pub fn setLabelFont(self: *MenuItem, font: enums.Font) void { c.Fl_Menu_Item_set_label_font(self.inner, @enumToInt(font)); } pub fn labelSize(self: *const MenuItem) i32 { c.Fl_Menu_Item_label_size(self.inner); } pub fn setLabelSize(self: *MenuItem, sz: i32) void { c.Fl_Menu_Item_set_label_size(self.inner, sz); } pub fn show(self: *MenuItem) void { c.Fl_Menu_Item_show(self.inner); } pub fn hide(self: *MenuItem) void { c.Fl_Menu_Item_hide(self.inner); } }; test "" { @import("std").testing.refAllDecls(@This()); }
src/menu.zig
const std = @import("std"); const stdx = @import("stdx"); const ds = stdx.ds; const process = std.process; const build_options = @import("build_options"); const graphics = @import("graphics"); const v8 = @import("v8"); const runtime = @import("../runtime/runtime.zig"); const printFmt = runtime.printFmt; const log = std.log.scoped(.doc_gen); const gen = @import("../runtime/gen.zig"); const api = @import("../runtime/api.zig"); const api_graphics = @import("../runtime/api_graphics.zig"); const cs_graphics = api_graphics.cs_graphics; const doc_versions: []const DocVersion = &.{ DocVersion{ .name = build_options.VersionName, .url = "/docs" }, }; const ModuleId = []const u8; const modules: []const ModuleId = &.{ "cs_audio", "cs_core", "cs_files", "cs_graphics", "cs_http", "cs_input", "cs_net", "cs_test", "cs_window", "cs_worker", }; pub fn generate(alloc: std.mem.Allocator, docs_path: []const u8) !void { try std.fs.cwd().makePath(docs_path); // Copy over assets. try std.fs.cwd().copyFile(fromBuildRoot(alloc, "docs/pico.min.css"), std.fs.cwd(), fromPath(alloc, docs_path, "pico.min.css"), .{}); try std.fs.cwd().copyFile(fromBuildRoot(alloc, "docs/docs.css"), std.fs.cwd(), fromPath(alloc, docs_path, "docs.css"), .{}); try std.fs.cwd().copyFile(fromBuildRoot(alloc, "docs/hljs-tomorrow.css"), std.fs.cwd(), fromPath(alloc, docs_path, "hljs-tomorrow.css"), .{}); try std.fs.cwd().copyFile(fromBuildRoot(alloc, "docs/hljs-tomorrow-night-blue.css"), std.fs.cwd(), fromPath(alloc, docs_path, "hljs-tomorrow-night-blue.css"), .{}); try std.fs.cwd().copyFile(fromBuildRoot(alloc, "docs/highlight.min.js"), std.fs.cwd(), fromPath(alloc, docs_path, "highlight.min.js"), .{}); const api_model = try genApiModel(alloc); var ctx = Context{ .alloc = alloc, .buf = std.ArrayList(u8).init(alloc), }; // Generate a page per module. for (modules) |mod_id| { const mod = api_model.get(mod_id).?; try genHtml(&ctx, mod_id, api_model); const page_file = try std.fmt.allocPrint(alloc, "{s}.html", .{ mod.name }); const page_path = try std.fs.path.join(alloc, &.{ docs_path, page_file }); try std.fs.cwd().writeFile(page_path, ctx.buf.toOwnedSlice()); } // Generate the index page. try genHtml(&ctx, null, api_model); const index_path = try std.fs.path.join(alloc, &.{ docs_path, "index.html" }); try std.fs.cwd().writeFile(index_path, ctx.buf.toOwnedSlice()); } fn fromPath(alloc: std.mem.Allocator, path: []const u8, rel_path: []const u8) []const u8 { return std.fs.path.resolve(alloc, &[_][]const u8{ path, rel_path }) catch unreachable; } fn fromBuildRoot(alloc: std.mem.Allocator, rel_path: []const u8) []const u8 { return std.fs.path.resolve(alloc, &[_][]const u8{ build_options.BuildRoot, rel_path }) catch unreachable; } const Context = struct { const Self = @This(); alloc: std.mem.Allocator, buf: std.ArrayList(u8), fn write(self: *Self, str: []const u8) void { self.buf.appendSlice(str) catch unreachable; } fn writeFmt(self: *Self, comptime format: []const u8, args: anytype) void { const str = std.fmt.allocPrint(self.alloc, format, args) catch unreachable; self.buf.appendSlice(str) catch unreachable; } }; const Source = struct { path: []const u8, package: type, }; // Parses comments and uses comptime to create api model. fn genApiModel(alloc: std.mem.Allocator) !std.StringHashMap(Module) { var res = std.StringHashMap(Module).init(alloc); const srcs: []const Source = &.{ .{ .path = "runtime/api.zig", .package = api }, .{ .path = "runtime/api_graphics.zig", .package = api_graphics }, }; inline for (srcs) |src| { const path = fromBuildRoot(alloc, src.path); const file = std.fs.openFileAbsolute(path, .{ .mode = .read_only}) catch unreachable; defer file.close(); const source = file.readToEndAllocOptions(alloc, 10e6, null, @alignOf(u8), 0) catch unreachable; defer alloc.free(source); var tree = std.zig.parse(alloc, source) catch unreachable; defer tree.deinit(alloc); if (tree.errors.len > 0) { for (tree.errors) |err| { log.debug("Parse error: {s}", .{err}); } unreachable; } const root_members = tree.rootDecls(); for (root_members) |member| { if (tree.nodes.items(.tag)[member] == .simple_var_decl) { const ident_tok = tree.nodes.items(.main_token)[member] + 1; const ident_str = tree.tokenSlice(ident_tok); if (isModuleName(ident_str)) { var module: Module = undefined; log.debug("Parsing {s}", .{ident_str}); // Parse module metadata from doc comments. try parseModuleMetadata(alloc, tree, member, ident_str, &module); var funcs = std.ArrayList(FunctionInfo).init(alloc); var types = std.ArrayList(TypeInfo).init(alloc); const container_node = tree.nodes.items(.data)[member].rhs; // Parse functions and types. const Decls = comptime std.meta.declarations(src.package); log.debug("{s} {}", .{ident_str, Decls.len}); inline for (Decls) |Decl| { if (Decl.is_pub) { const DeclField = @field(src.package, Decl.name); if (@typeInfo(@TypeOf(DeclField)) == .Type) { if (std.mem.eql(u8, Decl.name, ident_str)) { const ModuleDecls = comptime std.meta.declarations(DeclField); inline for (ModuleDecls) |ModuleDecl| { if (ModuleDecl.is_pub) { const ModuleDeclType = @field(DeclField, ModuleDecl.name); if (@typeInfo(@TypeOf(ModuleDeclType)) == .Fn) { const mb_func = try parseFunctionInfo(ModuleDecl, @TypeOf(ModuleDeclType), alloc, tree, container_node); if (mb_func) |func| { try funcs.append(func); } } else if (@typeInfo(@TypeOf(ModuleDeclType)) == .Type) { // Type Declaration. var type_info = TypeInfo{ .name = ModuleDecl.name, .desc = "", .fields = &.{}, .constants = &.{}, .methods = &.{}, .is_enum = @typeInfo(ModuleDeclType) == .Enum, .is_enum_string_sumtype = @hasDecl(ModuleDeclType, "IsStringSumType"), .enum_values = &.{}, }; const child = findContainerChild(tree, container_node, ModuleDecl.name); const data = try parseMetadata(alloc, tree, child); type_info.desc = data.desc; // log.debug("{s} {}", .{ModuleDecl.name, tree.nodes.items(.tag)[child]}); const type_container = tree.simpleVarDecl(child).ast.init_node; parseTypeDecls(alloc, ModuleDeclType, tree, type_container, &type_info); if (@typeInfo(ModuleDeclType) == .Struct) { type_info.fields = parseTypeFields(alloc, ModuleDeclType) catch unreachable; } else if (@typeInfo(ModuleDeclType) == .Enum) { const to_lower = type_info.is_enum_string_sumtype; type_info.enum_values = getEnumValues(alloc, ModuleDeclType, to_lower) catch unreachable; } try types.append(type_info); } } } } } } } module.funcs = funcs.toOwnedSlice(); module.types = types.toOwnedSlice(); try res.put(try alloc.dupe(u8, ident_str), module); } } } } for (modules) |mod_name| { if (!res.contains(mod_name)) { std.debug.panic("No api model for: {s}", .{mod_name}); } } return res; } fn parseModuleMetadata(alloc: std.mem.Allocator, tree: std.zig.Ast, mod_node: std.zig.Ast.Node.Index, mod_name: []const u8, module: *Module) !void { var found_title = false; var found_ns = false; var found_name = false; var desc_buf = std.ArrayList(u8).init(alloc); var cur_tok = tree.firstToken(mod_node); while (cur_tok > 0) { cur_tok -= 1; if (tree.tokens.items(.tag)[cur_tok] == .doc_comment) { const comment = tree.tokenSlice(cur_tok); if (std.mem.indexOf(u8, comment, "@title")) |idx| { const title = std.mem.trim(u8, comment[idx + "@title".len..], " "); module.title = try alloc.dupe(u8, title); found_title = true; continue; } if (std.mem.indexOf(u8, comment, "@ns")) |idx| { const ns = std.mem.trim(u8, comment[idx + "@ns".len..], " "); module.ns = try alloc.dupe(u8, ns); found_ns = true; continue; } if (std.mem.indexOf(u8, comment, "@name")) |idx| { const name = std.mem.trim(u8, comment[idx + "@name".len..], " "); module.name = try alloc.dupe(u8, name); found_name = true; continue; } // Accumulate desc. if (desc_buf.items.len > 0) { // try desc_buf.insertSlice(0, "<br />"); try desc_buf.insertSlice(0, " "); } try desc_buf.insertSlice(0, std.mem.trim(u8, comment[3..], " ")); } else { break; } } module.desc = desc_buf.toOwnedSlice(); if (!found_title) std.debug.panic("{s} is missing @title", .{mod_name}); if (!found_ns) std.debug.panic("{s} is missing @ns", .{mod_name}); if (!found_name) std.debug.panic("{s} is missing @name", .{mod_name}); } pub fn parseTypeDecls(alloc: std.mem.Allocator, comptime T: type, tree: std.zig.Ast, type_container: std.zig.Ast.Node.Index, out: *TypeInfo) void { const Decls = comptime std.meta.declarations(T); var methods = std.ArrayList(FunctionInfo).init(alloc); var constants = std.ArrayList([]const u8).init(alloc); inline for (Decls) |Decl| { if (Decl.is_pub) { const DeclField = @field(T, Decl.name); if (@typeInfo(@TypeOf(DeclField)) == .Fn) { // Assume method. const mb_type_func = parseFunctionInfo(Decl, @TypeOf(DeclField), alloc, tree, type_container) catch unreachable; if (mb_type_func) |type_func| { methods.append(type_func) catch unreachable; } } else if (@typeInfo(@TypeOf(DeclField)) != .Type) { // Constant. const mb_constant = parseConstantInfo(Decl, alloc, tree, type_container) catch unreachable; if (mb_constant) |constant| { constants.append(constant) catch unreachable; } } } } out.methods = methods.toOwnedSlice(); out.constants = constants.toOwnedSlice(); } fn parseTypeFields(alloc: std.mem.Allocator, comptime T: type) ![]const TypeField { var fields = std.ArrayList(TypeField).init(alloc); const Fields = std.meta.fields(T); inline for (Fields) |Field| { var field = TypeField{ .name = Field.name, .type_name = "", .default_value = null, .optional = @typeInfo(Field.field_type) == .Optional, }; if (@typeInfo(Field.field_type) == .Optional) { field.type_name = getJsTypeName(@typeInfo(Field.field_type).Optional.child); } else { field.type_name = getJsTypeName(Field.field_type); } if (Field.default_value != null) { field.default_value = try std.fmt.allocPrint(alloc, "{any}", .{Field.default_value.?}); } try fields.append(field); } return fields.toOwnedSlice(); } fn getEnumValues(alloc: std.mem.Allocator, comptime E: type, to_lower: bool) ![]const []const u8 { var values = std.ArrayList([]const u8).init(alloc); const Fields = std.meta.fields(E); inline for (Fields) |Field| { if (to_lower) { try values.append(runtime.ctLower(Field.name)); } else { try values.append(Field.name); } } return values.toOwnedSlice(); } fn parseConstantInfo(comptime VarDecl: std.builtin.TypeInfo.Declaration, alloc: std.mem.Allocator, tree: std.zig.Ast, container_node: std.zig.Ast.Node.Index) !?[]const u8 { _ = alloc; _ = tree; _ = container_node; if (std.mem.eql(u8, VarDecl.name, "IsStringSumType")) { return null; } else if (std.mem.eql(u8, VarDecl.name, "Default")) { return null; } // For now, just return the name. return VarDecl.name; } // container_node is the parent container that declares the function. fn parseFunctionInfo(comptime FnDecl: std.builtin.TypeInfo.Declaration, comptime FnDeclType: type, alloc: std.mem.Allocator, tree: std.zig.Ast, container_node: std.zig.Ast.Node.Index) !?FunctionInfo { var func = FunctionInfo{ .desc = "", .name = FnDecl.name, .params = &.{}, .ret = undefined, }; // Extract params. const ArgsTuple = std.meta.ArgsTuple(FnDeclType); const ArgFields = std.meta.fields(ArgsTuple); const FuncInfo = comptime gen.getJsFuncInfo(ArgFields); var params = std.ArrayList(FunctionParamInfo).init(alloc); // arg_names are currently empty. // https://github.com/ziglang/zig/issues/8259 inline for (ArgFields) |Field, i| { if (FuncInfo.param_tags[i] == .Param) { const BaseType = if (@typeInfo(Field.field_type) == .Optional) @typeInfo(Field.field_type).Optional.child else Field.field_type; try params.append(.{ .param_name = "", //.param_name = FnDecl.data.Fn.arg_names[Idx], .type_name = getJsTypeName(BaseType), .type_decl_mod = null, .optional = @typeInfo(Field.field_type) == .Optional, }); // log.debug("{s}", .{@typeName(Field.field_type)}); } } func.params = params.toOwnedSlice(); const valid = try extractFunctionMetadata(alloc, tree, container_node, &func); if (!valid) return null; // Extract return. const ReturnType = @typeInfo(FnDeclType).Fn.return_type.?; if (@typeInfo(ReturnType) == .Optional) { const BaseType = @typeInfo(ReturnType).Optional.child; func.ret = .{ .type_name = if (BaseType == void) null else getJsTypeName(BaseType), .type_decl_mod = null, .can_be_null = true, }; } else if (@typeInfo(ReturnType) == .ErrorUnion) { const BaseType = @typeInfo(ReturnType).ErrorUnion.payload; // We are moving away from exceptions so an error union can return null. func.ret = .{ .type_name = if (BaseType == void) null else getJsTypeName(BaseType), .type_decl_mod = null, .can_be_null = true, }; } else { func.ret = .{ .type_name = if (ReturnType == void) null else getJsTypeName(ReturnType), .type_decl_mod = null, .can_be_null = false, }; } return func; } fn getJsTypeName(comptime T: type) []const u8 { return switch (T) { [16]f32, []const f32 => "Array", v8.Uint8Array, runtime.Uint8Array => "Uint8Array", []const api.cs_files.FileEntry => "[]FileEntry", api.cs_files.FileEntry => "FileEntry", v8.String, ds.Box([]const u8), []const u8 => "string", bool => "boolean", v8.Promise => "Promise", u8, f32, f64, u32, i16, i32, u53, u16 => "number", u64 => "BigInt", v8.Value, *const anyopaque => "any", *const v8.C_FunctionCallbackInfo => "...any", std.StringHashMap([]const u8), v8.Persistent(v8.Object), v8.Object => "object", v8.Function => "function", api.cs_http.RequestOptions => "RequestOptions", stdx.http.Response => "Response", api.cs_files.PathInfo => "PathInfo", graphics.Image => "Image", graphics.Color => "Color", cs_graphics.Color => "Color", api.cs_files.FileKind => "FileKind", api.cs_http.RequestMethod => "RequestMethod", api.cs_http.ContentType => "ContentType", api.cs_input.MouseButton => "MouseButton", api.cs_input.Key => "Key", // Shouldn't be available but needed before @internal is parsed. std.mem.Allocator => "Allocator", else => { if (@typeInfo(T) == .Struct) { if (@hasDecl(T, "ManagedStruct")) { return getJsTypeName(std.meta.fieldInfo(T, .val).field_type); } else if (@hasDecl(T, "ManagedSlice")) { return getJsTypeName(std.meta.fieldInfo(T, .slice).field_type); } else { return @typeName(T); } } else if (@typeInfo(T) == .Enum) { return @typeName(T); } std.debug.panic("Can't convert to js type name: {s}", .{ @typeName(T) }); } }; } fn findContainerChild(tree: std.zig.Ast, container_node: std.zig.Ast.Node.Index, name: []const u8) std.zig.Ast.Node.Index { var container: std.zig.Ast.full.ContainerDecl = undefined; if (tree.nodes.items(.tag)[container_node] == .container_decl) { container = tree.containerDecl(container_node); } else if (tree.nodes.items(.tag)[container_node] == .container_decl_trailing) { container = tree.containerDecl(container_node); } else if (tree.nodes.items(.tag)[container_node] == .container_decl_two_trailing) { var buf: [2]std.zig.Ast.Node.Index = undefined; container = tree.containerDeclTwo(&buf, container_node); } else if (tree.nodes.items(.tag)[container_node] == .container_decl_two) { var buf: [2]std.zig.Ast.Node.Index = undefined; container = tree.containerDeclTwo(&buf, container_node); } else { log.debug("Skipping {}", .{tree.nodes.items(.tag)[container_node]}); unreachable; } for (container.ast.members) |member| { if (tree.nodes.items(.tag)[member] == .simple_var_decl) { // const a = struct {}; const ident_tok = tree.nodes.items(.main_token)[member] + 1; if (std.mem.eql(u8, tree.tokenSlice(ident_tok), name)) { return member; } } else if (tree.nodes.items(.tag)[member] == .fn_decl) { // Filter by fn name. const proto_id = tree.nodes.items(.data)[member].lhs; if (tree.nodes.items(.tag)[proto_id] == .fn_proto_multi) { const fn_proto = tree.fnProtoMulti(proto_id); if (std.mem.eql(u8, tree.tokenSlice(fn_proto.name_token.?), name)) { return proto_id; } } else if (tree.nodes.items(.tag)[proto_id] == .fn_proto_simple) { var buf: std.zig.Ast.Node.Index = undefined; const fn_proto = tree.fnProtoSimple(&buf, proto_id); if (std.mem.eql(u8, tree.tokenSlice(fn_proto.name_token.?), name)) { return proto_id; } } else if (tree.nodes.items(.tag)[proto_id] == .fn_proto_one) { var buf: std.zig.Ast.Node.Index = undefined; const fn_proto = tree.fnProtoOne(&buf, proto_id); if (std.mem.eql(u8, tree.tokenSlice(fn_proto.name_token.?), name)) { return proto_id; } } else { log.debug("unsupported: {}", .{tree.nodes.items(.tag)[proto_id]}); continue; } } // log.debug("{}", .{tree.nodes.items(.tag)[member]}); } std.debug.panic("Could not find: {s}", .{name}); } const Metadata = struct { desc: []const u8, param_names: []const []const u8, internal: bool, }; // Parse metadata from doc comments. fn parseMetadata(alloc: std.mem.Allocator, tree: std.zig.Ast, node: std.zig.Ast.Node.Index) !Metadata { var res: Metadata = undefined; var buf = std.ArrayList(u8).init(alloc); var params = std.ArrayList([]const u8).init(alloc); // Start with the first token since we want to break on the first non comment. var cur_tok = tree.firstToken(node); while (cur_tok > 0) { cur_tok -= 1; if (tree.tokens.items(.tag)[cur_tok] == .doc_comment) { const comment = tree.tokenSlice(cur_tok); if (std.mem.indexOf(u8, comment, "@internal")) |_| { // Skip this function. res.internal = true; continue; } if (std.mem.indexOf(u8, comment, "@param")) |idx| { const name = std.mem.trim(u8, comment[idx + "@param".len..], " "); try params.insert(0, try alloc.dupe(u8, name)); continue; } // Accumulate desc. if (buf.items.len > 0) { try buf.insertSlice(0, " "); } try buf.insertSlice(0, std.mem.trim(u8, comment[3..], " ")); } else { break; } } res.desc = buf.toOwnedSlice(); res.param_names = params.toOwnedSlice(); return res; } // Finds the function in the container ast and extracts metadata in comments. fn extractFunctionMetadata(alloc: std.mem.Allocator, tree: std.zig.Ast, container_node: std.zig.Ast.Node.Index, func: *FunctionInfo) !bool { // Skip devmode _DEV functions. if (std.mem.endsWith(u8, func.name, "_DEV")) { return false; } const child = findContainerChild(tree, container_node, func.name); const data = try parseMetadata(alloc, tree, child); if (data.internal) { return false; } func.desc = data.desc; for (data.param_names) |name, i| { if (i < func.params.len) { func.params[i].param_name = name; } } if (func.desc.len == 0) { log.debug("metadata not found for: {s}", .{func.name}); } return true; } fn isModuleName(name: []const u8) bool { for (modules) |mod_name| { if (std.mem.eql(u8, mod_name, name)) { return true; } } return false; } fn genHtml(ctx: *Context, mb_mod_id: ?ModuleId, api_model: std.StringHashMap(Module)) !void { // Head. ctx.writeFmt( \\<!DOCTYPE html> \\<html data-theme="light"> \\<head> \\ <meta http-equiv="content-type" content="text/html; charset=utf-8" /> \\ <meta name="viewport" content="width=device-width, initial-scale=1"> \\ <link rel="stylesheet" href="pico.min.css" /> \\ <link rel="stylesheet" href="docs.css" /> \\ <link rel="stylesheet" href="hljs-tomorrow.css" /> \\ <link rel="stylesheet" href="hljs-tomorrow-night-blue.css" /> \\ <title>Cosmic Docs | {s}</title> \\ <script> \\ // Set correct theme before rest of page loads. \\ let theme = window.localStorage.getItem('theme') \\ if (!theme) {{ \\ theme = 'light' \\ }} \\ document.documentElement.setAttribute('data-theme', theme); \\ </script> \\</head> \\<body> \\ <div class="top-nav grid"> \\ <div><h3><span class="primary">Cosmic</span> Docs</h3></div> \\ <div class="top-menu"><a onclick="clickTheme()" href="#" role="button" class="outline">Theme</a></div> \\ </div> \\ <main class="container-fluid"> , .{ build_options.VersionName } ); defer ctx.write("</body></html>"); // Side nav. ctx.write( \\<aside><div> \\<nav> ); ctx.write("<select>"); for (doc_versions) |version| { ctx.writeFmt("<option value=\"{s}\">{s}</option>", .{version.url, version.name}); } ctx.write("</select>"); { // General. ctx.write("<section class=\"main-links\"><ul>"); ctx.write("<li><a href=\"index.html#about\">About</a></li>"); ctx.write("<li><a href=\"index.html#start\">Getting Started</a></li>"); ctx.write("<li><a href=\"index.html#tools\">Tools</a></li>"); ctx.write("<li><a href=\"index.html#tutorial\">Tutorials</a></li>"); ctx.write("<li><a href=\"index.html#community\">Community</a></li>"); ctx.write("</ul></section>"); // Api. ctx.write("<section><div class=\"category secondary\">API</div><ul>"); for (modules) |mod_id| { const mod = api_model.get(mod_id).?; ctx.writeFmt("<li><a id=\"{s}\" href=\"{s}.html\">{s}</a></li>", .{mod.name, mod.name, mod.ns}); } ctx.write("</ul></section>"); } ctx.write("</nav></div></aside>"); // Main. ctx.write( \\<div class="docs"> ); { if (mb_mod_id) |mod_id| { const mod = api_model.get(mod_id).?; ctx.writeFmt( \\<mark class="ns">{s}</mark> \\<h3>{s}</h3> \\<p>{s}</p> , .{ mod.ns, mod.title, mod.desc } ); // List Functions for (mod.funcs) |func| { ctx.writeFmt( \\<div class="func"> \\ <a id="{s}" href="#"><small class="secondary">{s}.</small>{s}</a> <span class="params">(&nbsp; , .{ func.name, mod.ns, func.name } ); // Params. for (func.params) |param, i| { if (i > 0) { ctx.write(", "); } if (param.optional) { ctx.writeFmt("<span class=\"param\">{s}: <span class=\"secondary\">?{s}</span></span>", .{param.param_name, param.type_name}); } else { ctx.writeFmt("<span class=\"param\">{s}: <span class=\"secondary\">{s}</span></span>", .{param.param_name, param.type_name}); } } ctx.write(" )</span>"); // Return. const ret_type_name: []const u8 = if (func.ret.type_name) |name| name else ""; ctx.writeFmt(" <span class=\"return\">{s}</span>", .{ ret_type_name}); // Description. ctx.writeFmt( \\</div> \\<p class="func-desc">{s}</p> , .{ func.desc } ); } // List Types. for (mod.types) |info| { var type_kind: []const u8 = undefined; if (info.is_enum) { if (info.is_enum_string_sumtype) { type_kind = "string"; } else { type_kind = "enum"; } } else { type_kind = "object"; } ctx.writeFmt( \\<div class="type"> \\ <a id="{s}" href="#"><small class="secondary">{s}</small>.{s}</a> <span class="params">{s}</span> , .{ info.name, mod.ns, info.name, type_kind } ); if (info.is_enum) { if (info.is_enum_string_sumtype) { for (info.enum_values) |value| { ctx.writeFmt( \\<div class="indent field"><span class="primary">"{s}"</span></div> , .{ value } ); } } else { for (info.enum_values) |value| { // List enum integers as constants. ctx.writeFmt( \\<div class="constant"> \\ <a id="{s}" href="#"><small class="secondary">{s}.</small>{s}.{s}</a> , .{ value, mod.ns, info.name, value} ); ctx.write( \\</div> ); } } } else { for (info.fields) |field| { const optional: []const u8 = if (field.optional) "?" else ""; ctx.writeFmt( \\<div class="indent field"><span class="primary">{s}</span>: {s}{s}</div> , .{ field.name, optional, field.type_name } ); } } ctx.writeFmt( \\</div> \\<p class="type-desc">{s}</p> , .{ info.desc } ); // Instance methods. for (info.methods) |func| { ctx.writeFmt( \\<div class="func"> \\ <a id="{s}" href="#"><small class="secondary">{s}.{s}</small><span class="method">{s}</span></a> <span class="params">(&nbsp; , .{ func.name, mod.ns, info.name, func.name } ); // Params. for (func.params) |param, i| { if (i > 0) { ctx.write(", "); } if (param.optional) { ctx.writeFmt("<span class=\"param\">{s}: <span class=\"secondary\">?{s}</span></span>", .{param.param_name, param.type_name}); } else { ctx.writeFmt("<span class=\"param\">{s}: <span class=\"secondary\">{s}</span></span>", .{param.param_name, param.type_name}); } } ctx.write(" )</span>"); // Return. const ret_type_name: []const u8 = if (func.ret.type_name) |name| name else ""; ctx.writeFmt(" <span class=\"return\">{s}</span>", .{ret_type_name}); // Description. ctx.writeFmt( \\</div> \\<p class="func-desc">{s}</p> , .{ func.desc } ); } // Constants. for (info.constants) |constant| { ctx.writeFmt( \\<div class="constant"> \\ <a id="{s}" href="#"><small class="secondary">{s}.</small>{s}.{s}</a> , .{ constant, mod.ns, info.name, constant} ); ctx.writeFmt( \\</div> \\<p class="constant-desc">{s}</p> , .{ "" } ); } } } else { // Render index.html const content_path = fromBuildRoot(ctx.alloc, "docs/docs_main.html"); const content = try std.fs.cwd().readFileAlloc(ctx.alloc, content_path, 10e6); defer ctx.alloc.free(content); ctx.write(content); } } ctx.write( \\</div> ); // Right symbol nav. if (mb_mod_id) |mod_id| { const mod = api_model.get(mod_id).?; ctx.write( \\<aside class="symbols"><div> \\<nav><ul> ); for (mod.funcs) |func| { ctx.writeFmt("<li><a href=\"#{s}\">{s}()</a></li>", .{func.name, func.name}); } for (mod.types) |info| { ctx.writeFmt("<li><a href=\"#{s}\">{s}</a></li>", .{info.name, info.name}); for (info.methods) |func| { ctx.writeFmt("<li class=\"indent\"><a href=\"#{s}\">{s}()</a></li>", .{func.name, func.name}); } for (info.constants) |constant| { ctx.writeFmt("<li><a href=\"#{s}\">{s}.{s}</a></li>", .{constant, info.name, constant}); } } ctx.write("</ul></nav></div></aside>"); } ctx.write("</main>"); // Script if (mb_mod_id) |mod_id| { const mod = api_model.get(mod_id).?; ctx.writeFmt( \\ <script> \\ document.getElementById('{s}').focus(); \\ </script> , .{mod.name} ); } ctx.write( \\<script src="highlight.min.js"></script> \\<script> \\ hljs.highlightAll(); \\ function clickTheme() { \\ if (theme == 'light') { \\ theme = 'dark' \\ } else { \\ theme = 'light' \\ } \\ window.localStorage.setItem('theme', theme) \\ document.documentElement.setAttribute('data-theme', theme) \\ } \\</script> ); } const DocVersion = struct { name: []const u8, url: []const u8, }; const Module = struct { ns: []const u8, title: []const u8, name: []const u8, desc: []const u8, types: []const TypeInfo, funcs: []const FunctionInfo, }; const TypeInfo = struct { name: []const u8, desc: []const u8, fields: []const TypeField, constants: []const []const u8, methods: []const FunctionInfo, is_enum: bool, // Whether the enum is a string sumtype or an actual object with keyed number values. is_enum_string_sumtype: bool, enum_values: []const []const u8, }; const TypeField = struct { name: []const u8, type_name: []const u8, optional: bool, default_value: ?[]const u8, }; const FunctionInfo = struct { desc: []const u8, name: []const u8, params: []FunctionParamInfo, ret: ReturnInfo, }; const ReturnInfo = struct { // Null type name indicates no return type or undefined. type_name: ?[]const u8, type_decl_mod: ?ModuleId, can_be_null: bool, }; const FunctionParamInfo = struct { param_name: []const u8, type_name: []const u8, type_decl_mod: ?ModuleId, optional: bool, }; comptime { // Referencing this lets the build pass. _ = stdx.testing.unitTraceC; }
docs/doc_gen.zig
const std = @import("std"); const TestContext = @import("../../src/test.zig").TestContext; const wasi = std.zig.CrossTarget{ .cpu_arch = .wasm32, .os_tag = .wasi, }; pub fn addCases(ctx: *TestContext) !void { { var case = ctx.exe("wasm function calls", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ foo(); \\ bar(); \\ return 42; \\} \\fn foo() void { \\ bar(); \\ bar(); \\} \\fn bar() void {} , "42\n", ); case.addCompareOutput( \\pub export fn _start() i64 { \\ bar(); \\ foo(); \\ foo(); \\ bar(); \\ foo(); \\ bar(); \\ return 42; \\} \\fn foo() void { \\ bar(); \\} \\fn bar() void {} , "42\n", ); case.addCompareOutput( \\pub export fn _start() f32 { \\ bar(); \\ foo(); \\ return 42.0; \\} \\fn foo() void { \\ bar(); \\ bar(); \\ bar(); \\} \\fn bar() void {} , "42\n", ); case.addCompareOutput( \\pub export fn _start() u32 { \\ foo(10, 20); \\ return 5; \\} \\fn foo(x: u32, y: u32) void { _ = x; _ = y; } , "5\n"); } { var case = ctx.exe("wasm locals", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ var y: f32 = 42.0; \\ var x: u32 = 10; \\ if (false) { \\ y; \\ x; \\ } \\ return i; \\} , "5\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ var y: f32 = 42.0; \\ _ = y; \\ var x: u32 = 10; \\ foo(i, x); \\ i = x; \\ return i; \\} \\fn foo(x: u32, y: u32) void { \\ _ = y; \\ var i: u32 = 10; \\ i = x; \\} , "10\n"); } { var case = ctx.exe("wasm binary operands", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i += 20; \\ return i; \\} , "25\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i += 20; \\ var result: u32 = foo(i, 10); \\ return result; \\} \\fn foo(x: u32, y: u32) u32 { \\ return x + y; \\} , "35\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 20; \\ i -= 5; \\ return i; \\} , "15\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i -= 3; \\ var result: u32 = foo(i, 10); \\ return result; \\} \\fn foo(x: u32, y: u32) u32 { \\ return y - x; \\} , "8\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i *= 7; \\ var result: u32 = foo(i, 10); \\ return result; \\} \\fn foo(x: u32, y: u32) u32 { \\ return x * y; \\} , "350\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 352; \\ i /= 7; // i = 50 \\ var result: u32 = foo(i, 7); \\ return result; \\} \\fn foo(x: u32, y: u32) u32 { \\ return x / y; \\} , "7\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i &= 6; \\ return i; \\} , "4\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i |= 6; \\ return i; \\} , "7\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ i ^= 6; \\ return i; \\} , "3\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = false; \\ b = b or false; \\ return b; \\} , "0\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = true; \\ b = b or false; \\ return b; \\} , "1\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = false; \\ b = b or true; \\ return b; \\} , "1\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = true; \\ b = b or true; \\ return b; \\} , "1\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = false; \\ b = b and false; \\ return b; \\} , "0\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = true; \\ b = b and false; \\ return b; \\} , "0\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = false; \\ b = b and true; \\ return b; \\} , "0\n"); case.addCompareOutput( \\pub export fn _start() bool { \\ var b: bool = true; \\ b = b and true; \\ return b; \\} , "1\n"); } { var case = ctx.exe("wasm conditions", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ if (i > @as(u32, 4)) { \\ i += 10; \\ } \\ return i; \\} , "15\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ if (i < @as(u32, 4)) { \\ i += 10; \\ } else { \\ i = 2; \\ } \\ return i; \\} , "2\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ if (i < @as(u32, 4)) { \\ i += 10; \\ } else if(i == @as(u32, 5)) { \\ i = 20; \\ } \\ return i; \\} , "20\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 11; \\ if (i < @as(u32, 4)) { \\ i += 10; \\ } else { \\ if (i > @as(u32, 10)) { \\ i += 20; \\ } else { \\ i = 20; \\ } \\ } \\ return i; \\} , "31\n"); case.addCompareOutput( \\pub export fn _start() void { \\ assert(foo(true) != @as(i32, 30)); \\} \\ \\fn assert(ok: bool) void { \\ if (!ok) unreachable; \\} \\ \\fn foo(ok: bool) i32 { \\ const x = if(ok) @as(i32, 20) else @as(i32, 10); \\ return x; \\} , ""); case.addCompareOutput( \\pub export fn _start() void { \\ assert(foo(false) == @as(i32, 20)); \\ assert(foo(true) == @as(i32, 30)); \\} \\ \\fn assert(ok: bool) void { \\ if (!ok) unreachable; \\} \\ \\fn foo(ok: bool) i32 { \\ const val: i32 = blk: { \\ var x: i32 = 1; \\ if (!ok) break :blk x + @as(i32, 9); \\ break :blk x + @as(i32, 19); \\ }; \\ return val + 10; \\} , ""); } { var case = ctx.exe("wasm while loops", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 0; \\ while(i < @as(u32, 5)){ \\ i += 1; \\ } \\ \\ return i; \\} , "5\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 0; \\ while(i < @as(u32, 10)){ \\ var x: u32 = 1; \\ i += x; \\ } \\ return i; \\} , "10\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var i: u32 = 0; \\ while(i < @as(u32, 10)){ \\ var x: u32 = 1; \\ i += x; \\ if (i == @as(u32, 5)) break; \\ } \\ return i; \\} , "5\n"); } { var case = ctx.exe("wasm enum values", wasi); case.addCompareOutput( \\const Number = enum { One, Two, Three }; \\ \\pub export fn _start() i32 { \\ var number1 = Number.One; \\ var number2: Number = .Two; \\ if (false) { \\ number1; \\ number2; \\ } \\ const number3 = @intToEnum(Number, 2); \\ \\ return @enumToInt(number3); \\} , "2\n"); case.addCompareOutput( \\const Number = enum { One, Two, Three }; \\ \\pub export fn _start() i32 { \\ var number1 = Number.One; \\ var number2: Number = .Two; \\ const number3 = @intToEnum(Number, 2); \\ if (number1 == number2) return 1; \\ if (number2 == number3) return 1; \\ if (@enumToInt(number1) != 0) return 1; \\ if (@enumToInt(number2) != 1) return 1; \\ if (@enumToInt(number3) != 2) return 1; \\ var x: Number = .Two; \\ if (number2 != x) return 1; \\ \\ return @enumToInt(number3); \\} , "2\n"); } { var case = ctx.exe("wasm structs", wasi); case.addCompareOutput( \\const Example = struct { x: u32 }; \\ \\pub export fn _start() u32 { \\ var example: Example = .{ .x = 5 }; \\ return example.x; \\} , "5\n"); case.addCompareOutput( \\const Example = struct { x: u32 }; \\ \\pub export fn _start() u32 { \\ var example: Example = .{ .x = 5 }; \\ example.x = 10; \\ return example.x; \\} , "10\n"); case.addCompareOutput( \\const Example = struct { x: u32, y: u32 }; \\ \\pub export fn _start() u32 { \\ var example: Example = .{ .x = 5, .y = 10 }; \\ return example.y + example.x; \\} , "15\n"); case.addCompareOutput( \\const Example = struct { x: u32, y: u32 }; \\ \\pub export fn _start() u32 { \\ var example: Example = .{ .x = 5, .y = 10 }; \\ var example2: Example = .{ .x = 10, .y = 20 }; \\ \\ example = example2; \\ return example.y + example.x; \\} , "30\n"); case.addCompareOutput( \\const Example = struct { x: u32, y: u32 }; \\ \\pub export fn _start() u32 { \\ var example: Example = .{ .x = 5, .y = 10 }; \\ \\ example = .{ .x = 10, .y = 20 }; \\ return example.y + example.x; \\} , "30\n"); } // This test case is disabled until the codegen for switch is reworked // to take advantage of br_table rather than a series of br_if opcodes. //{ // var case = ctx.exe("wasm switch", wasi); // case.addCompareOutput( // \\pub export fn _start() u32 { // \\ var val: u32 = 1; // \\ var a: u32 = switch (val) { // \\ 0, 1 => 2, // \\ 2 => 3, // \\ 3 => 4, // \\ else => 5, // \\ }; // \\ // \\ return a; // \\} // , "2\n"); // case.addCompareOutput( // \\pub export fn _start() u32 { // \\ var val: u32 = 2; // \\ var a: u32 = switch (val) { // \\ 0, 1 => 2, // \\ 2 => 3, // \\ 3 => 4, // \\ else => 5, // \\ }; // \\ // \\ return a; // \\} // , "3\n"); // case.addCompareOutput( // \\pub export fn _start() u32 { // \\ var val: u32 = 10; // \\ var a: u32 = switch (val) { // \\ 0, 1 => 2, // \\ 2 => 3, // \\ 3 => 4, // \\ else => 5, // \\ }; // \\ // \\ return a; // \\} // , "5\n"); // case.addCompareOutput( // \\const MyEnum = enum { One, Two, Three }; // \\ // \\pub export fn _start() u32 { // \\ var val: MyEnum = .Two; // \\ var a: u32 = switch (val) { // \\ .One => 1, // \\ .Two => 2, // \\ .Three => 3, // \\ }; // \\ // \\ return a; // \\} // , "2\n"); //} { var case = ctx.exe("wasm error unions", wasi); case.addCompareOutput( \\pub export fn _start() void { \\ var e1 = error.Foo; \\ var e2 = error.Bar; \\ assert(e1 != e2); \\ assert(e1 == error.Foo); \\ assert(e2 == error.Bar); \\} \\ \\fn assert(b: bool) void { \\ if (!b) unreachable; \\} , ""); case.addCompareOutput( \\pub export fn _start() u32 { \\ var e: anyerror!u32 = 5; \\ const i = e catch 10; \\ return i; \\} , "5\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var e: anyerror!u32 = error.Foo; \\ const i = e catch 10; \\ return i; \\} , "10\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var e = foo(); \\ const i = e catch 69; \\ return i; \\} \\ \\fn foo() anyerror!u32 { \\ return 5; \\} , "5\n"); } { var case = ctx.exe("wasm error union part 2", wasi); case.addCompareOutput( \\pub export fn _start() u32 { \\ var e = foo(); \\ const i = e catch 69; \\ return i; \\} \\ \\fn foo() anyerror!u32 { \\ return error.Bruh; \\} , "69\n"); case.addCompareOutput( \\pub export fn _start() u32 { \\ var e = foo(); \\ const i = e catch 42; \\ return i; \\} \\ \\fn foo() anyerror!u32 { \\ return error.Dab; \\} , "42\n"); } }
test/stage2/wasm.zig
const builtin = @import("builtin"); const std = @import("std"); const CrossTarget = std.zig.CrossTarget; const Builder = std.build.Builder; const Step = std.build.Step; const LibExeObjStep = std.build.LibExeObjStep; const warn = std.debug.warn; const allocPrint = std.fmt.allocPrint; const eql = std.mem.eql; const eqlIgnoreCase = std.ascii.eqlIgnoreCase; const toLower = std.ascii.toLower; // ---------------------------------------------------------------------------- pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const want_gdb = b.option(bool, "gdb", "Build for using gdb with qemu") orelse false; const log_level = try logLevelOptions(b); const enable_profile = b.option(bool, "profile", "Enable TZmCFI profiler (e.g., TCDebugDumpProfile)") orelse false; const enable_cfi = b.option(bool, "cfi", "Enable TZmCFI (default = true)") orelse true; var cfi_opts = CfiOpts{ .ctx = b.option(bool, "cfi-ctx", "Enable TZmCFI context management (default = cfi)") orelse enable_cfi, .ses = b.option(bool, "cfi-ses", "Enable TZmCFI shadow exception stacks (default = cfi)") orelse enable_cfi, .ss = b.option(bool, "cfi-ss", "Enable TZmCFI shadow stacks (default = cfi)") orelse enable_cfi, .aborting_ss = b.option(bool, "cfi-aborting-ss", "Use the aborting implementation of SS (default = false)") orelse false, .icall = b.option(bool, "cfi-icall", "Enable indirect call CFI (default = cfi)") orelse enable_cfi, .ses_type = b.option([]const u8, "cfi-ses-type", "TZmCFI shadow exception stack type " ++ "(valid values: [null, naive, unnested, safe], default = safe)") orelse "safe", }; cfi_opts.validate() catch |e| switch (e) { error.IncompatibleCfiOpts => { b.markInvalidUserInput(); }, error.UnrecognizedCfiOpts => { b.markInvalidUserInput(); }, }; const accel_raise_pri = b.option(bool, "accel-raise-pri", "Accelerate vRaisePriority (default = cfi-ctx)") orelse cfi_opts.ctx; if (enable_profile and eql(u8, log_level, "None")) { warn("error: -Dprofile is pointless with -Dlog-level=None\r\n", .{}); b.markInvalidUserInput(); } if (accel_raise_pri and !cfi_opts.ctx) { // `TCRaisePrivilege` is a Secure function, so each thread needs its own // Secure stack warn("error: -Daccel-raise-pri requires -Dcfi-ctx\r\n", .{}); b.markInvalidUserInput(); } const target_board = b.option([]const u8, "target-board", "Specify the target board (default = an505)") orelse "an505"; const supported_boards = [_][]const u8{ "an505", "lpc55s69", }; for (supported_boards) |supported_board| { if (eql(u8, supported_board, target_board)) { break; } } else { warn("error: unknown board name '{}'\r\n", .{target_board}); b.markInvalidUserInput(); } // Flash memory is read in units of blocks, so the placement of functions // affects runtime performance. This options allows experimentation with // this phenomenon. const rom_offset = b.option([]const u8, "rom-offset", "Insert N padding bytes before code. " ++ "Not supported by all targets (default = 0)") orelse "0"; const target = try CrossTarget.parse(.{ .arch_os_abi = "thumb-freestanding-eabi", .cpu_features = "cortex_m33-dsp-fp16-fpregs-vfp2sp-vfp3d16sp-vfp4d16sp", }); // Zig passes a target CPU and features to Clang using `-Xclang -target-cpu ...`. // This is a lower-level mechanism than `-mcpu=cortex-m33` (which the clang // frontend converts to `-target-cpu cortex_m33 ...`.). Unfortunately, there // exists no equivalents of `-Xclang` for assembly files. To work around this, we // pass `-mcpu` to the clang frontend. const as_flags = &[_][]const u8 { "-mcpu=cortex-m33", }; // The utility program for creating a CMSE import library // ------------------------------------------------------- const mkimplib = "../target/debug/tzmcfi_mkimplib"; // TZmCFI Monitor instantiation // ------------------------------------------------------- // This part is shared by all Non-Secure applications. const monitor_name = if (want_gdb) "monitor-dbg" else "monitor"; const monitor = b.addStaticLibrary(monitor_name, "monitor.zig"); monitor.setTarget(target); monitor.setBuildMode(mode); monitor.addPackagePath("tzmcfi-monitor", "../src/monitor.zig"); monitor.addPackagePath("arm_cmse", "../src/drivers/arm_cmse.zig"); monitor.addPackagePath("arm_m", "../src/drivers/arm_m.zig"); monitor.addBuildOption([]const u8, "LOG_LEVEL", try allocPrint(b.allocator, "\"{}\"", .{log_level})); monitor.addBuildOption(bool, "ENABLE_PROFILE", enable_profile); monitor.addBuildOption(bool, "ABORTING_SHADOWSTACK", cfi_opts.aborting_ss); monitor.addBuildOption([]const u8, "SHADOW_EXC_STACK_TYPE", try allocPrint(b.allocator, "\"{}\"", .{cfi_opts.ses_type})); monitor.addBuildOption([]const u8, "BOARD", try allocPrint(b.allocator, "\"{}\"", .{target_board})); monitor.addIncludeDir("../include"); monitor.emit_h = false; // The Secure part // ------------------------------------------------------- // This part is shared by all Non-Secure applications. const exe_s_name = if (want_gdb) "secure-dbg" else "secure"; const exe_s = b.addExecutable(exe_s_name, "secure.zig"); exe_s.setLinkerScriptPath(try allocPrint(b.allocator, "ports/{}/secure.ld", .{target_board})); exe_s.setTarget(target); exe_s.setBuildMode(mode); exe_s.addCSourceFile("common/startup.S", as_flags); exe_s.setOutputDir("zig-cache"); exe_s.addPackagePath("arm_cmse", "../src/drivers/arm_cmse.zig"); exe_s.addPackagePath("arm_m", "../src/drivers/arm_m.zig"); exe_s.addBuildOption([]const u8, "BOARD", try allocPrint(b.allocator, "\"{}\"", .{target_board})); exe_s.linkLibrary(monitor); if (eql(u8, target_board, "lpc55s69")) { // Binary blob from MCUXpresso SDK exe_s.addObjectFile("ports/lpc55s69/sdk/libpower_hardabi_s.a"); } // CMSE import library (generated from the Secure binary) // ------------------------------------------------------- // It includes the absolute addresses of Non-Secure-callable functions // exported by the Secure code. Usually it's generated by passing the // `--cmse-implib` option to a supported version of `arm-none-eabi-gcc`, but // since it might not be available, we use a custom tool to do that. const implib_path = "zig-cache/secure_implib.s"; var implib_args = std.ArrayList([]const u8).init(b.allocator); try implib_args.appendSlice(&[_][]const u8{ mkimplib, exe_s.getOutputPath(), "-o", implib_path, }); const implib = b.addSystemCommand(implib_args.items); implib.step.dependOn(&exe_s.step); const implib_step = b.step("implib", "Create a CMSE import library"); implib_step.dependOn(&implib.step); // FreeRTOS (This runs in Non-Secure mode) // ------------------------------------------------------- const kernel_name = if (want_gdb) "freertos-dbg" else "freertos"; const kernel = b.addStaticLibrary(kernel_name, "freertos.zig"); kernel.setTarget(target); kernel.setBuildMode(mode); const kernel_include_dirs = [_][]const u8{ "freertos/include", "freertos/portable/GCC/ARM_CM33/non_secure", "freertos/portable/GCC/ARM_CM33/secure", "nonsecure-common", // For `FreeRTOSConfig.h` "../include", }; for (kernel_include_dirs) |path| { kernel.addIncludeDir(path); } const kernel_source_files = [_][]const u8{ "freertos/croutine.c", "freertos/event_groups.c", "freertos/list.c", "freertos/queue.c", "freertos/stream_buffer.c", "freertos/tasks.c", "freertos/timers.c", "freertos/portable/Common/mpu_wrappers.c", "freertos/portable/GCC/ARM_CM33/non_secure/port.c", "freertos/portable/GCC/ARM_CM33/non_secure/portasm.c", "freertos/portable/MemMang/heap_4.c", }; var kernel_build_args = std.ArrayList([]const u8).init(b.allocator); try kernel_build_args.append("-flto"); try cfi_opts.addCFlagsTo(&kernel_build_args); if (accel_raise_pri) { try kernel_build_args.append("-DportACCEL_RAISE_PRIVILEGE=1"); } for (kernel_source_files) |file| { kernel.addCSourceFile(file, kernel_build_args.items); } // The Non-Secure part // ------------------------------------------------------- // This build script defines multiple Non-Secure applications. // There are separate build steps defined for each application, allowing // the user to choose whichever application they want to start. const ns_app_deps = NsAppDeps{ .target = target, .mode = mode, .want_gdb = want_gdb, .cfi_opts = &cfi_opts, .target_board = target_board, .as_flags = as_flags, .rom_offset = rom_offset, .implib_path = implib_path, .implib_step = &implib.step, .exe_s = exe_s, .kernel_include_dirs = &kernel_include_dirs, .kernel = kernel, }; try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "rtosbasic", .root = "nonsecure-rtosbasic.zig", .meta = struct { const use_freertos = true; fn modifyExeStep(_builder: *Builder, step: *LibExeObjStep, opts: ModifyExeStepOpts) error{}!void { step.addCSourceFile("nonsecure-rtosbasic.cpp", opts.c_flags); } }, }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "basic", .root = "nonsecure-basic.zig", }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "bench-coremark", .root = "nonsecure-bench-coremark.zig", .meta = @import("nonsecure-bench-coremark/meta.zig"), }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "bench-latency", .root = "nonsecure-bench-latency.zig", }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "bench-rtos", .root = "nonsecure-bench-rtos.zig", .meta = struct { const use_freertos = true; }, }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "profile-ses", .root = "nonsecure-profile-ses.zig", }); try defineNonSecureApp(b, ns_app_deps, NsAppInfo{ .name = "profile-rtos", .root = "nonsecure-profile-rtos.zig", .meta = struct { const use_freertos = true; }, }); // We don't define the default rule. } const CfiOpts = struct { /// Use TZmCFI context management API ctx: bool, /// TZmCFI shadow exception stacks ses: bool, /// TZmCFI shadow stacks ss: bool, /// LLVM indirect call validator icall: bool, /// Abort on shadow stack integrity check failure aborting_ss: bool, /// Shadow exception stack implementation ses_type: []const u8, const Self = @This(); fn validate(self: *Self) !void { if (self.ss and !self.ctx) { // Shadow stacks are managed by context management API. warn("error: cfi-ss requires cfi-ctx\n", .{}); return error.IncompatibleCfiOpts; } if (self.ses and !self.ctx) { // Shadow exception stacks are managed by context management API. warn("error: cfi-ses requires cfi-ctx\n", .{}); return error.IncompatibleCfiOpts; } if (self.ss and !self.ses) { // TZmCFI's shadow stacks do not work without shadow exception stacks. // Probably because the shadow stack routines mess up the lowest bit // of `EXC_RETURN`. warn("error: cfi-ss requires cfi-ses\n", .{}); return error.IncompatibleCfiOpts; } if (self.aborting_ss and !self.ss) { // `aborting_ss` makes no sense without `ss` warn("error: cfi-aborting-ss requires cfi-ss\n", .{}); return error.IncompatibleCfiOpts; } const valid_ses_types = [_][]const u8{ "Safe", "Naive", "Unnested", "Null", }; for (valid_ses_types) |valid_ses_type| { if (eqlIgnoreCase(self.ses_type, valid_ses_type)) { self.ses_type = valid_ses_type; break; } } else { warn("error: invalid cfi-ses-type value: '{}'\n", .{self.ses_type}); return error.UnrecognizedCfiOpts; } } fn addCFlagsTo(self: *const Self, args: var) !void { try args.append(if (self.ses) "-DHAS_TZMCFI_SES=1" else "-DHAS_TZMCFI_SES=0"); if (self.ss) { try args.append("-fsanitize=shadow-call-stack"); } if (self.icall) { try args.append("-fsanitize=cfi-icall"); } } fn configureBuildStep(self: *const Self, b: *Builder, step: *LibExeObjStep) !void { step.enable_shadow_call_stack = self.ss; // TODO: Enable `cfi-icall` on Zig code step.addBuildOption(bool, "HAS_TZMCFI_CTX", self.ctx); step.addBuildOption(bool, "HAS_TZMCFI_SES", self.ses); step.addBuildOption([]const u8, "SHADOW_EXC_STACK_TYPE", try allocPrint(b.allocator, "\"{}\"", .{self.ses_type})); } }; const NsAppDeps = struct { // General target: CrossTarget, mode: builtin.Mode, want_gdb: bool, cfi_opts: *const CfiOpts, target_board: []const u8, as_flags: []const []const u8, rom_offset: []const u8, // Secure dependency implib_path: []const u8, implib_step: *Step, exe_s: *LibExeObjStep, // FreeRTOS kernel_include_dirs: []const []const u8, kernel: *LibExeObjStep, }; const NsAppInfo = struct { name: []const u8, root: []const u8, meta: type = struct {}, c_source: ?[]const u8 = null, use_freertos: bool = false, }; pub const ModifyExeStepOpts = struct { c_flags: [][]const u8, }; /// Define build steps for a single example application. /// /// - `build:name` /// - `qemu:name` /// fn defineNonSecureApp( b: *Builder, ns_app_deps: NsAppDeps, comptime app_info: NsAppInfo, ) !void { const target = ns_app_deps.target; const mode = ns_app_deps.mode; const want_gdb = ns_app_deps.want_gdb; const implib_path = ns_app_deps.implib_path; const implib_step = ns_app_deps.implib_step; const exe_s = ns_app_deps.exe_s; const kernel_include_dirs = ns_app_deps.kernel_include_dirs; const kernel = ns_app_deps.kernel; const target_board = ns_app_deps.target_board; const rom_offset = ns_app_deps.rom_offset; const as_flags = ns_app_deps.as_flags; const name = app_info.name; // Additional options // ------------------------------------------------------- const meta = app_info.meta; const use_freertos = if (@hasDecl(meta, "use_freertos")) meta.use_freertos else false; // The Non-Secure part // ------------------------------------------------------- const exe_ns_name = if (want_gdb) name ++ "-dbg" else name; const exe_ns = b.addExecutable(exe_ns_name, app_info.root); exe_ns.setLinkerScriptPath(try allocPrint(b.allocator, "ports/{}/nonsecure.ld", .{target_board})); exe_ns.setTarget(target); exe_ns.setBuildMode(mode); if (eql(u8, ns_app_deps.cfi_opts.ses_type, "Unnested")) { exe_ns.addCSourceFile("../src/nonsecure_vector_unnest.S", as_flags); } else { exe_ns.addCSourceFile("../src/nonsecure_vector_ses.S", as_flags); } exe_ns.setOutputDir("zig-cache"); exe_ns.addIncludeDir("../include"); exe_ns.addPackagePath("arm_m", "../src/drivers/arm_m.zig"); exe_ns.enable_lto = true; exe_ns.addBuildOption([]const u8, "BOARD", try allocPrint(b.allocator, "\"{}\"", .{target_board})); exe_ns.addBuildOption([]const u8, "ROM_OFFSET", try allocPrint(b.allocator, "{}", .{rom_offset})); try ns_app_deps.cfi_opts.configureBuildStep(b, exe_ns); // The C/C++ compiler options var c_flags = std.ArrayList([]const u8).init(b.allocator); try ns_app_deps.cfi_opts.addCFlagsTo(&c_flags); try c_flags.append("-flto"); try c_flags.append("-msoft-float"); if (@hasDecl(meta, "modifyExeStep")) { try meta.modifyExeStep(b, exe_ns, ModifyExeStepOpts{ .c_flags = c_flags.items }); } var startup_args: []const []const u8 = undefined; if (ns_app_deps.cfi_opts.ses) { startup_args = &comptime [_][]const u8{}; } else { // Disable TZmCFI's exception trampolines by updating VTOR to the // original (unpatched) vector table startup_args = &comptime [_][]const u8{"-DSET_ORIGINAL_VTOR"}; } exe_ns.addCSourceFile("common/startup.S", startup_args); if (use_freertos) { for (kernel_include_dirs) |path| { exe_ns.addIncludeDir(path); } exe_ns.linkLibrary(kernel); exe_ns.addCSourceFile("nonsecure-common/oshooks.c", c_flags.items); } exe_ns.addCSourceFile(implib_path, as_flags); exe_ns.step.dependOn(implib_step); const exe_both = b.step("build:" ++ name, "Build Secure and Non-Secure executables"); exe_both.dependOn(&exe_s.step); exe_both.dependOn(&exe_ns.step); // Launch QEMU // ------------------------------------------------------- const qemu = b.step("qemu:" ++ name, "Run the program in qemu"); var qemu_args = std.ArrayList([]const u8).init(b.allocator); const qemu_device_arg = try std.fmt.allocPrint( b.allocator, "loader,file={}", .{exe_ns.getOutputPath()}, ); try qemu_args.appendSlice(&[_][]const u8{ "qemu-system-arm", "-kernel", exe_s.getOutputPath(), "-device", qemu_device_arg, "-machine", "mps2-an505", "-nographic", "-d", "guest_errors", "-semihosting", "-semihosting-config", "target=native", "-s", }); if (want_gdb) { try qemu_args.appendSlice(&[_][]const u8{"-S"}); } const run_qemu = b.addSystemCommand(qemu_args.items); qemu.dependOn(&run_qemu.step); run_qemu.step.dependOn(exe_both); } fn logLevelOptions(b: *Builder) ![]const u8 { // Must be synchronized with `LogLevel` in `options.zig` const log_levels = [_][]const u8{ "None", "Crticial", "Warning", "Trace" }; var selected: ?[]const u8 = null; for (log_levels) |level| { const opt_name = try allocPrint(b.allocator, "log-{}", .{level}); for (opt_name) |*c| { c.* = toLower(c.*); } const opt_desc = try allocPrint(b.allocator, "Set log level to {}", .{level}); const set = b.option(bool, opt_name, opt_desc) orelse false; if (set) { if (selected != null) { warn("Multiple log levels are specified\n", .{}); b.markInvalidUserInput(); } selected = level; } } return selected orelse "Warning"; }
examples/build.zig
const format = @import("std").fmt.format; const OutStream = @import("std").io.OutStream; const arm_m = @import("arm_m"); const arm_cmse = @import("arm_cmse"); const lpc55s69 = @import("../../drivers/lpc55s69.zig"); pub const VTOR_NS = 0x00010000; extern var __nsc_start: usize; extern var __nsc_end: usize; const Flexcomm = lpc55s69.Flexcomm; const usart = lpc55s69.flexcomm[0]; const Syscon = lpc55s69.Syscon; const syscon = lpc55s69.syscon; const Pmc = lpc55s69.Pmc; const pmc = lpc55s69.pmc; const Iocon = lpc55s69.Iocon; const iocon = lpc55s69.iocon; const AnaCtrl = lpc55s69.AnaCtrl; const ana_ctrl = lpc55s69.ana_ctrl; /// Power Library API to choose normal regulation and set the voltage for the /// desired operating frequency. /// /// Defined in `libpower_*.a`. Source code is not included in the SDK. extern fn POWER_SetVoltageForFreq(system_freq_hz: u32) void; /// Perform the board-specific initialization. pub fn init() void { // Configure Clock Tree // ----------------------------------------------------------------------- POWER_SetVoltageForFreq(150000000); // Power up the crystal oscillator pmc.regPdruncdfclr0().* = Pmc.PDRUNCFG0_PDEN_XTAL32M | Pmc.PDRUNCFG0_PDEN_LDOXO32M; // Enable CLKIN from the crystal oscillator syscon.regClockCtrl().* |= Syscon.CLOCK_CTRL_CLKIN_ENA; // Enable the 16MHz crystal oscilaltor ana_ctrl.regXo32mCtrl().* |= AnaCtrl.XO32M_CTRL_ENABLE_SYSTEM_CLK_OUT; // Wait for it to be stable while ((ana_ctrl.regXo32mStatus().* & AnaCtrl.XO32M_STATUS_XO_READY) == 0) {} // Power up PLL0 pmc.regPdruncdfclr0().* = Pmc.PDRUNCFG0_PDEN_PLL0; // Select CLKIN as PLL0 input syscon.regPll0clksel().* = Syscon.PLL0CLKSEL_CLKIN; // Configure PLL0 syscon.setPll0NDividerRatio(4); // 16MHz / 4 → 4MHz syscon.regPll0sscg1().* = Syscon.pll0sscg1MdivExt(75) | // 4MHz * 75 → 300MHz Syscon.PLL0SSCG1_MREQ | Syscon.PLL0SSCG1_SEL_EXT; syscon.setPll0PDividerRatio(3); // 300MHz / 3 → 100MHz syscon.regPll0ctrl().* = comptime @bitCast( u32, Syscon.Pll0ctrl{ .selr = 0, // selr = 0 .seli = 39, // seli = 2 * floor(M / 4) + 3 = 39 .selp = 19, // selp = floor(M / 4) + 1 = 19 .bypasspostdiv2 = true, // bypass post divide-by-2 .clken = true, }, ); // Wait for PLL0 to lock while ((syscon.regPll0stat().* & Syscon.PLL0STAT_LOCK) == 0) {} // The required flash memory access time for system clock rates up to // 100MHz is 9 system closk syscon.regFmccr().* = syscon.regFmccr().* & (~Syscon.FMCCR_FLASHTIM_MASK) | Syscon.fmccrFlashtim(8); // Select PLL0 output as main clock syscon.regMainclkselb().* = Syscon.MAINCLKSELB_SEL_PLL0; // AHBCLK = main_clk / 1 syscon.regAhbclkdiv().* = Syscon.ahbclkdivDiv(0); // pll0_clk_div = 33.33...MHz syscon.regPll0clkdiv().* = 3 - 1; // Configure Flexcomm 0 clock to 33.33...MHz / (1 + 75 / 256) → 25.78...MHz (25600/993MHz) syscon.regFlexfrgctrl(0).* = Syscon.flexfrgctrlDiv(0xff) | Syscon.flexfrgctrlMult(75); syscon.regFcclksel(0).* = Syscon.FCCLKSEL_PLL0DIV; // Enable Flexcomm 0 clock syscon.regAhbclkctrlset1().* = Syscon.ahbclkctrl1Fc(0); // Configure USART (Flexcomm 0) // ----------------------------------------------------------------------- // Configure the I/O pins syscon.regAhbclkctrlset0().* = Syscon.AHBCLKCTRL0_IOCON; iocon.regP0(29).* = Iocon.pFunc(1) | Iocon.P_DIGIMODE; // RX: P0_29(1) iocon.regP0(30).* = Iocon.pFunc(1); // TX: P0_30(1) syscon.regAhbclkctrlclr0().* = Syscon.AHBCLKCTRL0_IOCON; // Select USART usart.regPselid().* = Flexcomm.PSELID_PERSEL_USART; usart.regUsartBrg().* = 14 - 1; // 25.78 MHz / (16 * 14) ≈ 115091 bps usart.regFifoCfg().* = Flexcomm.FIFO_CFG_ENABLETX | Flexcomm.FIFO_CFG_ENABLERX; usart.regUsartCfg().* = Flexcomm.USART_CFG_ENABLE | Flexcomm.USART_CFG_DATALEN_8BIT; // Configure SAU // ----------------------------------------------------------------------- const Region = arm_cmse.SauRegion; // Flash memory Non-Secure alias arm_cmse.sau.setRegion(0, Region{ .start = 0x00010000, .end = 0x00100000 }); // SRAM 1–3 Non-Secure alias arm_cmse.sau.setRegion(1, Region{ .start = 0x20010000, .end = 0x20040000 }); // The Non-Secure callable region arm_cmse.sau.setRegion(2, Region{ .start = @ptrToInt(&__nsc_start), .end = @ptrToInt(&__nsc_end), .nsc = true, }); // Peripherals arm_cmse.sau.setRegion(3, Region{ .start = 0x40000000, .end = 0x50000000 }); // Configure MPCs and IDAU // ----------------------------------------------------------------------- // TODO: The manual says the rules are initialized to `NsNonpriv`. Is this true? // Enable Non-Secure access to flash memory (`0x[01]0000000`) // for the range `[0x10000, 0xfffff]`. // lpc55s69.mpc_flash.setRuleInRange(0x10000, 0x100000, .NsNonpriv); // Enable Non-Secure access to RAM1–3 (`0x[01]0200000`) // each for the range `[0x0000, 0xffff]`. // lpc55s69.mpc_ram1.setRuleInRange(0x0, 0x10000, .NsNonpriv); // Allow non-Secure unprivileged access to the timers // ----------------------------------------------------------------------- arm_m.nvic.targetIrqToNonSecure(lpc55s69.irqs.CTimer0_IRQn - 16); arm_m.nvic.targetIrqToNonSecure(lpc55s69.irqs.CTimer1_IRQn - 16); lpc55s69.ppc_apb_bridge0.setCTimer0Rule(.NsNonpriv); lpc55s69.ppc_apb_bridge0.setCTimer1Rule(.NsNonpriv); } /// Render the format string `fmt` with `args` and transmit the output. pub fn print(comptime fmt: []const u8, args: var) void { const out_stream = OutStream(void, error{}, printInner){ .context = {} }; format(out_stream, fmt, args) catch unreachable; } fn printInner(ctx: void, data: []const u8) error{}!usize { usart.writeSlice(data); return data.len; } pub fn printByte(b: u8) void { usart.write(b); }
examples/ports/lpc55s69/secure.zig
const std = @import("std"); /// The only output of the tokenizer. pub const ZNodeToken = struct { const Self = @This(); /// 0 is root, 1 is top level children. depth: usize, /// The extent of the slice. start: usize, end: usize, }; /// Parses text outputting ZNodeTokens. Does not convert strings to numbers, and all strings are /// "as is", no escaping is performed. pub const StreamingParser = struct { const Self = @This(); state: State, start_index: usize, current_index: usize, // The maximum node depth. max_depth: usize, // The current line's depth. line_depth: usize, // The current node depth. node_depth: usize, /// Level of multiline string. open_string_level: usize, /// Current level of multiline string close. close_string_level: usize, /// Account for any extra spaces trailing at the end of a word. trailing_spaces: usize, pub const Error = error{ TooMuchIndentation, InvalidWhitespace, OddIndentationValue, InvalidQuotation, InvalidMultilineOpen, InvalidMultilineClose, InvalidNewLineInString, InvalidCharacterAfterString, SemicolonWentPastRoot, UnexpectedEof, }; pub const State = enum { /// Whether we're starting on an openline. OpenLine, ExpectZNode, Indent, OpenCharacter, Quotation, SingleLineCharacter, MultilineOpen0, MultilineOpen1, MultilineLevelOpen, MultilineLevelClose, MultilineClose0, MultilineCharacter, EndString, OpenComment, Comment, }; /// Returns a blank parser. pub fn init() Self { var self: StreamingParser = undefined; self.reset(); return self; } /// Resets the parser back to the beginning state. pub fn reset(self: *Self) void { self.state = .OpenLine; self.start_index = 0; self.current_index = 0; self.max_depth = 0; self.line_depth = 0; self.node_depth = 0; self.open_string_level = 0; self.close_string_level = 0; self.trailing_spaces = 0; } pub fn completeOrError(self: *const Self) !void { switch (self.state) { .ExpectZNode, .OpenLine, .EndString, .Comment, .OpenComment, .Indent => {}, else => return Error.UnexpectedEof, } } /// Feeds a character to the parser. May output a ZNode. Check "hasCompleted" to see if there /// are any unfinished strings. pub fn feed(self: *Self, c: u8) Error!?ZNodeToken { defer self.current_index += 1; //std.debug.print("FEED<{}> {} {} ({c})\n", .{self.state, self.current_index, c, c}); switch (self.state) { .OpenComment, .Comment => switch (c) { '\n' => { self.start_index = self.current_index + 1; // We're ending a line with nodes. if (self.state == .Comment) { self.max_depth = self.line_depth + 1; } self.node_depth = 0; self.line_depth = 0; self.state = .OpenLine; }, else => { // Skip. }, }, // All basically act the same except for a few minor differences. .ExpectZNode, .OpenLine, .EndString, .OpenCharacter => switch (c) { '#' => { if (self.state == .OpenLine) { self.state = .OpenComment; } else { defer self.state = .Comment; if (self.state == .OpenCharacter) { return ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; } } }, // The tricky character (and other whitespace). ' ' => { if (self.state == .OpenLine) { if (self.line_depth >= self.max_depth) { return Error.TooMuchIndentation; } self.state = .Indent; } else if (self.state == .OpenCharacter) { self.trailing_spaces += 1; } else { // Skip spaces when expecting a node on a closed line, // including this one. self.start_index = self.current_index + 1; } }, ':' => { defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; self.node_depth += 1; // Only return when we're not at end of a string. if (self.state != .EndString) { return node; } }, ',' => { defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; // Only return when we're not at end of a string. if (self.state != .EndString) { return node; } }, ';' => { if (self.node_depth == 0) { return Error.SemicolonWentPastRoot; } defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; self.node_depth -= 1; // Only return when we're not at end of a string, or in semicolons // special case, when we don't have an empty string. if (self.state != .EndString and node.start < node.end) { return node; } }, '"' => { if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't start another string. if (self.state == .OpenCharacter) { return null; } // We start here to account for the possibility of a string being "" self.start_index = self.current_index + 1; self.state = .Quotation; }, '[' => { if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't start another string. if (self.state == .OpenCharacter) { return null; } self.open_string_level = 0; self.state = .MultilineOpen0; }, '\n' => { defer self.state = .OpenLine; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; // Only reset on a non open line. if (self.state != .OpenLine) { self.max_depth = self.line_depth + 1; self.line_depth = 0; } self.node_depth = 0; // Only return something if there is something. Quoted strings are good. if (self.state == .OpenCharacter) { return node; } }, '\t', '\r' => { return Error.InvalidWhitespace; }, else => { // We already have a string. if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't reset if we're in a string. if (self.state != .OpenCharacter) { self.start_index = self.current_index; } self.trailing_spaces = 0; self.state = .OpenCharacter; }, }, .Indent => switch (c) { ' ' => { self.start_index = self.current_index + 1; self.line_depth += 1; self.state = .OpenLine; }, else => { return Error.OddIndentationValue; }, }, .Quotation => switch (c) { '"' => { self.state = .EndString; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index, }; // Reset because we're going to expecting nodes. self.start_index = self.current_index + 1; return node; }, else => { self.state = .SingleLineCharacter; }, }, .SingleLineCharacter => switch (c) { '"' => { self.state = .EndString; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index, }; // Reset because we're going to expecting nodes. self.start_index = self.current_index + 1; return node; }, '\n' => { return Error.InvalidNewLineInString; }, else => { // Consume. }, }, .MultilineOpen0, .MultilineLevelOpen => switch (c) { '=' => { self.open_string_level += 1; self.state = .MultilineLevelOpen; }, '[' => { self.start_index = self.current_index + 1; self.state = .MultilineOpen1; }, else => { return Error.InvalidMultilineOpen; }, }, .MultilineOpen1 => switch (c) { ']' => { self.state = .MultilineClose0; }, '\n' => { // Skip first newline. self.start_index = self.current_index + 1; }, else => { self.state = .MultilineCharacter; }, }, .MultilineCharacter => switch (c) { ']' => { self.close_string_level = 0; self.state = .MultilineClose0; }, else => { // Capture EVERYTHING. }, }, .MultilineClose0, .MultilineLevelClose => switch (c) { '=' => { self.close_string_level += 1; self.state = .MultilineLevelClose; }, ']' => { if (self.close_string_level == self.open_string_level) { self.state = .EndString; return ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.open_string_level - 1, }; } self.state = .MultilineCharacter; }, else => { return Error.InvalidMultilineClose; }, }, } return null; } }; fn testNextTextOrError(stream: *StreamingParser, idx: *usize, text: []const u8) ![]const u8 { while (idx.* < text.len) { const node = try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { //std.debug.print("TOKEN {}\n", .{text[n.start..n.end]}); return text[n.start..n.end]; } } return error.ExhaustedLoop; } test "parsing slice output" { const testing = std.testing; const text = \\# woo comment \\mp:10 \\[[sy]] \\ # another \\ : n : "en" , [[m]] \\ "sc" : [[10]] , g #inline \\ [[]]:[==[ \\hi]==] ; var idx: usize = 0; var stream = StreamingParser.init(); try testing.expectEqualSlices(u8, "mp", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "sy", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "n", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "en", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "m", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "sc", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "g", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "hi", try testNextTextOrError(&stream, &idx, text)); } fn testNextLevelOrError(stream: *StreamingParser, idx: *usize, text: []const u8) !usize { while (idx.* < text.len) { const node = try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { return n.depth; } } return error.ExhaustedLoop; } test "parsing depths" { const testing = std.testing; const text = \\# woo comment \\mp:10 \\[[sy]] \\ # another \\ : n : "en" , [[m]] \\ # more \\ \\ # even more \\ \\ "sc" : [[10]] , g #inline \\ [[]]:[==[ \\hi]==] ; var idx: usize = 0; var stream = StreamingParser.init(); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); } /// Parses the stream, outputting ZNodeTokens which reference the text. pub fn parseStream(stream: *StreamingParser, idx: *usize, text: []const u8) !?ZNodeToken { while (idx.* <= text.len) { // Insert an extra newline at the end of the stream. const node = if (idx.* == text.len) try stream.feed('\n') else try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { return n; } } return null; } /// A `ZNode`'s value. pub const ZValue = union(enum) { const Self = @This(); Null, String: []const u8, Int: i32, Float: f32, Bool: bool, /// Checks a ZValues equality. pub fn equals(self: Self, other: Self) bool { if (self == .Null and other == .Null) { return true; } if (self == .String and other == .String) { return std.mem.eql(u8, self.String, other.String); } if (self == .Int and other == .Int) { return self.Int == other.Int; } if (self == .Float and other == .Float) { return std.math.approxEq(f32, self.Float, other.Float, std.math.f32_epsilon); } if (self == .Bool and other == .Bool) { return self.Bool == other.Bool; } return false; } /// Outputs a value to the `out_stream`. This output is parsable. pub fn stringify(self: Self, out_stream: anytype) @TypeOf(out_stream).Error!void { switch (self) { .Null => { // Skip. }, .String => { const find = std.mem.indexOfScalar; const chars = "\"\n\t\r,:;"; const chars_count = @sizeOf(@TypeOf(chars)); var need_escape = false; var found = [_]bool{false} ** chars_count; for ("\"\n\t\r,:;") |ch, i| { const f = find(u8, self.String, ch); if (f != null) { found[i] = true; need_escape = true; } } // TODO: Escaping ]] in string. if (need_escape) { // 0=" 1=\n if (found[0] or found[1]) { // Escape with Lua. try out_stream.writeAll("[["); const ret = try out_stream.writeAll(self.String); try out_stream.writeAll("]]"); return ret; } else { // Escape with basic quotes. try out_stream.writeAll("\""); const ret = try out_stream.writeAll(self.String); try out_stream.writeAll("\""); return ret; } } return try out_stream.writeAll(self.String); }, .Int => { return std.fmt.formatIntValue(self.Int, "", std.fmt.FormatOptions{}, out_stream); }, .Float => { return std.fmt.formatFloatScientific(self.Float, std.fmt.FormatOptions{}, out_stream); }, .Bool => { return out_stream.writeAll(if (self.Bool) "true" else "false"); }, } } /// pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; switch (self) { .Null => try std.fmt.format(writer, ".Null", .{}), .String => try std.fmt.format(writer, ".String({s})", .{self.String}), .Int => try std.fmt.format(writer, ".Int({})", .{self.Int}), .Float => try std.fmt.format(writer, ".Float({})", .{self.Float}), .Bool => try std.fmt.format(writer, ".Bool({})", .{self.Bool}), } } }; /// Result of imprinting pub fn Imprint(comptime T: type) type { return struct { result: T, arena: std.heap.ArenaAllocator, }; } pub const ImprintError = error{ ExpectedBoolNode, ExpectedFloatNode, ExpectedUnsignedIntNode, ExpectedIntNode, ExpectedIntOrStringNode, ExpectedStringNode, FailedToConvertStringToEnum, FailedToConvertIntToEnum, FieldNodeDoesNotExist, ValueNodeDoesNotExist, ArrayElemDoesNotExist, OutOfMemory, InvalidPointerType, InvalidType, }; /// Represents a node in a static tree. Nodes have a parent, child, and sibling pointer /// to a spot in the array. pub const ZNode = struct { const Self = @This(); value: ZValue = .Null, parent: ?*ZNode = null, sibling: ?*ZNode = null, child: ?*ZNode = null, /// Returns the next Node in the tree. Will return Null after reaching root. For nodes further /// down the tree, they will bubble up, resulting in a negative depth. Self is considered to be /// at depth 0. pub fn next(self: *const Self, depth: *isize) ?*ZNode { if (self.child) |c| { depth.* += 1; return c; } else if (self.sibling) |c| { return c; } else { // Go up and forward. var iter: ?*const ZNode = self; while (iter != null) { iter = iter.?.parent; if (iter != null) { depth.* -= 1; if (iter.?.sibling) |c| { return c; } } } return null; } } /// Returns the next node in the tree until reaching root or the stopper node. pub fn nextUntil(self: *const Self, stopper: *const ZNode, depth: *isize) ?*ZNode { if (self.child) |c| { if (c == stopper) { return null; } depth.* += 1; return c; } else if (self.sibling) |c| { if (c == stopper) { return null; } return c; } else { // Go up and forward. var iter: ?*const ZNode = self; while (iter != null) { iter = iter.?.parent; // All these checks. :/ if (iter == stopper) { return null; } if (iter != null) { depth.* -= 1; if (iter.?.sibling) |c| { if (c == stopper) { return null; } return c; } } } return null; } } /// Iterates this node's children. Pass null to start. `iter = node.nextChild(iter);` pub fn nextChild(self: *const Self, iter: ?*const ZNode) ?*ZNode { if (iter) |it| { return it.sibling; } else { return self.child; } } /// Returns the nth child's value. Or null if neither the node or child exist. pub fn getChildValue(self: *const Self, nth: usize) ?Value { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (count == nth) { if (n.child) |c| { return c.value; } else { return null; } } count += 1; iter = n.sibling; } return null; } /// Returns the nth child. O(n) pub fn getChild(self: *const Self, nth: usize) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (count == nth) { return n; } count += 1; iter = n.sibling; } return null; } /// Returns the number of children. O(n) pub fn getChildCount(self: *const Self) usize { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { count += 1; iter = n.sibling; } return count; } /// Finds the next child after the given iterator. This is good for when you can guess the order /// of the nodes, which can cut down on starting from the beginning. Passing null starts over /// from the beginning. Returns the found node or null (it will loop back around). pub fn findNextChild(self: *const Self, start: ?*const ZNode, value: ZValue) ?*ZNode { var iter: ?*ZNode = self.child; if (start) |si| { iter = si.sibling; } while (iter != start) { if (iter) |it| { if (it.value.equals(value)) { return it; } iter = it.sibling; } else { // Loop back. iter = self.child; } } return null; } /// Finds the nth child node with a specific tag. pub fn findNthAny(self: *const Self, nth: usize, tag: std.meta.Tag(ZValue)) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (n.value == tag) { if (count == nth) { return n; } count += 1; } iter = n.sibling; } return null; } /// Finds the nth child node with a specific value. pub fn findNth(self: *const Self, nth: usize, value: ZValue) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child orelse return null; while (iter) |n| { if (n.value.equals(value)) { if (count == nth) { return n; } count += 1; } iter = n.sibling; } return null; } /// Traverses descendants until a node with the tag is found. pub fn findNthAnyDescendant(self: *const Self, nth: usize, value: std.meta.Tag(ZValue)) ?*ZNode { _ = value; var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (n.value == tag) { if (count == nth) { return n; } count += 1; } } return null; } /// Traverses descendants until a node with the specific value is found. pub fn findNthDescendant(self: *const Self, nth: usize, value: ZValue) ?*ZNode { var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (n.value.equals(value)) { if (count == nth) { return n; } count += 1; } } return null; } /// Converts strings to specific types. This just tries converting the string to an int, then /// float, then bool. Booleans are only the string values "true" or "false". pub fn convertStrings(self: *const Self) void { var depth: isize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |c| : (iter = c) { if (c.value != .String) { continue; } // Try to cast to numbers, then true/false checks, then string. const slice = c.value.String; const integer = std.fmt.parseInt(i32, slice, 10) catch { const float = std.fmt.parseFloat(f32, slice) catch { if (std.mem.eql(u8, "true", slice)) { c.value = ZValue{ .Bool = true }; } else if (std.mem.eql(u8, "false", slice)) { c.value = ZValue{ .Bool = false }; } else { // Keep the value. } continue; }; c.value = ZValue{ .Float = float }; continue; }; c.value = ZValue{ .Int = integer }; } } fn imprint_(self: *const Self, comptime T: type, allocator: ?*std.mem.Allocator) ImprintError!T { const TI = @typeInfo(T); switch (TI) { .Void => {}, .Bool => { return switch (self.value) { .Bool => |b| b, else => ImprintError.ExpectedBoolNode, }; }, .Float, .ComptimeFloat => { return switch (self.value) { .Float => |n| @floatCast(T, n), .Int => |n| @intToFloat(T, n), else => ImprintError.ExpectedFloatNode, }; }, .Int, .ComptimeInt => { const is_signed = (TI == .Int and TI.Int.signedness == .signed) or (TI == .ComptimeInt and TI.CompTimeInt.is_signed); switch (self.value) { .Int => |n| { if (is_signed) { return @intCast(T, n); } else { if (n < 0) { return ImprintError.ExpectedUnsignedIntNode; } return @intCast(T, n); } }, else => return ImprintError.ExpectedIntNode, } }, .Enum => { switch (self.value) { .Int => |int| { return std.meta.intToEnum(T, int) catch { return ImprintError.FailedToConvertIntToEnum; }; }, .String => { if (std.meta.stringToEnum(T, self.value.String)) |e| { return e; } else { return ImprintError.FailedToConvertStringToEnum; } }, else => return ImprintError.ExpectedIntOrStringNode, } }, .Optional => |opt_info| { const CI = @typeInfo(opt_info.child); // Aggregate types have a null root, so could still exist. if (self.value != .Null or CI == .Array or CI == .Struct or (CI == .Pointer and CI.Pointer.size == .Slice)) { return try self.imprint_(opt_info.child, allocator); } else { return null; } }, .Struct => |struct_info| { var iter: ?*const ZNode = null; var result: T = .{}; inline for (struct_info.fields) |field| { // Skip underscores. if (field.name[0] == '_') { continue; } const found = self.findNextChild(iter, .{ .String = field.name }); if (found) |child_node| { if (@typeInfo(field.field_type) == .Struct) { @field(result, field.name) = try child_node.imprint_(field.field_type, allocator); } else { if (child_node.child) |value_node| { @field(result, field.name) = try value_node.imprint_(field.field_type, allocator); } } // Found, set the iterator here. iter = found; } } return result; }, // Only handle [N]?T, where T is any other valid type. .Array => |array_info| { // Arrays are weird. They work on siblings. // TODO: For some types this causes a crash like [N]fn() void types. var r: T = std.mem.zeroes(T); var iter: ?*const ZNode = self; comptime var i: usize = 0; inline while (i < array_info.len) : (i += 1) { if (iter) |it| { r[i] = try it.imprint_(array_info.child, allocator); } if (iter) |it| { iter = it.sibling; } } return r; }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { if (ptr_info.child == ZNode) { // This is an odd case because we usually pass the child of a node // for the value, but here since we explicitely asked for the node, // it likely means the top. By taking the parent we force ZNodes // only working when part of a large struct and not stand alone. // // Something like this wouldn't work: ``` // root.imprint(*ZNode); // ``` return self.parent.?; } else if (allocator) |alloc| { var ptr = try alloc.create(ptr_info.child); ptr.* = try self.imprint_(ptr_info.child, allocator); return ptr; } else { return ImprintError.InvalidPointerType; } }, .Slice => { if (ptr_info.child == u8) { switch (self.value) { .String => { if (allocator) |alloc| { return try std.mem.dupe(alloc, u8, self.value.String); } else { return self.value.String; } }, else => return ImprintError.ExpectedStringNode, } } else if (allocator) |alloc| { // Same as pointer above. We take parent. var ret = try alloc.alloc(ptr_info.child, self.parent.?.getChildCount()); var iter: ?*const ZNode = self; var i: usize = 0; while (i < ret.len) : (i += 1) { if (iter) |it| { ret[i] = try it.imprint_(ptr_info.child, allocator); } else { if (@typeInfo(ptr_info.child) == .Optional) { ret[i] = null; } else { return ImprintError.ArrayElemDoesNotExist; } } if (iter) |it| { iter = it.sibling; } } return ret; } else { return ImprintError.InvalidType; } }, else => return ImprintError.InvalidType, } }, else => return ImprintError.InvalidType, } } pub fn imprint(self: *const Self, comptime T: type) ImprintError!T { return try self.imprint_(T, null); } pub fn imprintAlloc(self: *const Self, comptime T: type, allocator: *std.mem.Allocator) ImprintError!Imprint(T) { var arena = std.heap.ArenaAllocator.init(allocator); errdefer { // Free everything. arena.deinit(); } return Imprint(T){ .result = try self.imprint_(T, &arena.allocator), .arena = arena, }; } /// Outputs a `ZNode` and its children on a single line. This can be parsed back. pub fn stringify(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { // Likely not root. if (self.value != .Null) { try self.value.stringify(out_stream); try out_stream.writeAll(":"); } var depth: isize = 0; var last_depth: isize = 1; var iter = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (depth > last_depth) { last_depth = depth; try out_stream.writeAll(":"); } else if (depth < last_depth) { while (depth < last_depth) { try out_stream.writeAll(";"); last_depth -= 1; } } else if (depth > 1) { try out_stream.writeAll(","); } try n.value.stringify(out_stream); } } /// Returns true if node has more than one descendant (child, grandchild, etc). fn _moreThanOneDescendant(self: *const Self) bool { var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { count += 1; if (count > 1) { return true; } } return false; } fn _stringifyPretty(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { try self.value.stringify(out_stream); try out_stream.writeAll(":"); var depth: isize = 0; var last_depth: isize = 1; var iter = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (depth > last_depth) { last_depth = depth; try out_stream.writeAll(":"); // Likely an array. if (n.parent.?.value == .Null) { try out_stream.writeAll(" "); } else if (n.parent.?._moreThanOneDescendant()) { try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } else { try out_stream.writeAll(" "); } } else if (depth < last_depth) { while (depth < last_depth) { last_depth -= 1; } try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } else { try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } try n.value.stringify(out_stream); } } /// Outputs a `ZNode`s children on multiple lines. Excludes this node as root. /// Arrays with children that have: /// - null elements, separate lines /// - non-null, same line pub fn stringifyPretty(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { // Assume root, so don't print this node. var iter: ?*const ZNode = self.child; while (iter) |n| { try n._stringifyPretty(out_stream); try out_stream.writeAll("\n"); iter = n.sibling; } } /// Debug print the node. pub fn show(self: *const Self) void { std.debug.print("{}\n", .{self.value}); var depth: isize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |c| : (iter = c) { var i: isize = 0; while (i < depth) : (i += 1) { std.debug.print(" ", .{}); } std.debug.print("{}\n", .{c.value}); } } }; pub const ZTreeError = error{ TreeFull, TooManyRoots, }; /// ZTree errors. pub const ZError = StreamingParser.Error || ZTreeError; /// Represents a static fixed-size zzz tree. Values are slices over the text passed. pub fn ZTree(comptime R: usize, comptime S: usize) type { return struct { const Self = @This(); roots: [R]*ZNode = undefined, root_count: usize = 0, nodes: [S]ZNode = [_]ZNode{.{}} ** S, node_count: usize = 0, /// Appends correct zzz text to the tree, creating a new root. pub fn appendText(self: *Self, text: []const u8) ZError!*ZNode { const current_node_count = self.node_count; var root = try self.addNode(null, .Null); // Undo everything we did if we encounter an error. errdefer { // Undo adding root above. self.root_count -= 1; // Reset to node count before adding root. self.node_count = current_node_count; } // If we error, undo adding any of this. var current = root; var current_depth: usize = 0; var stream = StreamingParser.init(); var idx: usize = 0; while (try parseStream(&stream, &idx, text)) |token| { const slice = text[token.start..token.end]; const value: ZValue = if (slice.len == 0) .Null else .{ .String = slice }; const new_depth = token.depth; if (new_depth <= current_depth) { // Ascend. while (current_depth > new_depth) { current = current.parent orelse unreachable; current_depth -= 1; } // Sibling. const new = try self.addNode(current.parent, value); current.sibling = new; current = new; } else if (new_depth == current_depth + 1) { // Descend. current_depth += 1; const new = try self.addNode(current, value); current.child = new; current = new; } else { // Levels shouldn't increase by more than one. unreachable; } } try stream.completeOrError(); return root; } /// Clears the entire tree. pub fn clear(self: *Self) void { self.root_count = 0; self.node_count = 0; } /// Returns a slice of active roots. pub fn rootSlice(self: *const Self) []const *ZNode { return self.roots[0..self.root_count]; } /// Adds a node given a parent. Null parent starts a new root. When adding nodes manually /// care must be taken to ensure tree is left in known state after erroring from being full. /// Either reset to root_count/node_count when an error occurs, or leave as is (unfinished). pub fn addNode(self: *Self, parent: ?*ZNode, value: ZValue) ZError!*ZNode { if (self.node_count >= S) { return ZError.TreeFull; } var node = &self.nodes[self.node_count]; if (parent == null) { if (self.root_count >= R) { return ZError.TooManyRoots; } self.roots[self.root_count] = node; self.root_count += 1; } self.node_count += 1; node.value = value; node.parent = parent; node.sibling = null; node.child = null; // Add to end. if (parent) |p| { if (p.child) |child| { var iter = child; while (iter.sibling) |sib| : (iter = sib) {} iter.sibling = node; } else { p.child = node; } } return node; } /// Recursively copies a node from another part of the tree onto a new parent. Strings will /// be by reference. pub fn copyNode(self: *Self, parent: ?*ZNode, node: *const ZNode) ZError!*ZNode { const current_root_count = self.root_count; const current_node_count = self.node_count; // Likely because tree was full. errdefer { self.root_count = current_root_count; self.node_count = current_node_count; } var last_depth: isize = 1; var depth: isize = 0; var iter = node; var piter: ?*ZNode = parent; var plast: ?*ZNode = null; var pfirst: ?*ZNode = null; while (iter.next(&depth)) |child| : (iter = child) { if (depth > last_depth) { piter = plast; last_depth = depth; } else if (depth < last_depth) { plast = piter; while (last_depth != depth) { piter = piter.?.parent; last_depth -= 1; } } plast = try self.addNode(piter, child.value); if (pfirst == null) { pfirst = plast; } } return pfirst.?; } /// Debug print the tree and all of its roots. pub fn show(self: *const Self) void { for (self.rootSlice()) |rt| { rt.show(); } } /// Extract a struct's values onto a tree with a new root. Performs no allocations so any strings /// are by reference. pub fn extract(self: *Self, root: ?*ZNode, from_ptr: anytype) anyerror!void { if (root == null) { return self.extract(try self.addNode(null, .Null), from_ptr); } if (@typeInfo(@TypeOf(from_ptr)) != .Pointer) { @compileError("Passed struct must be a pointer."); } const T = @typeInfo(@TypeOf(from_ptr)).Pointer.child; const TI = @typeInfo(T); switch (TI) { .Void => { // No need. }, .Bool => { _ = try self.addNode(root, .{ .Bool = from_ptr.* }); }, .Float, .ComptimeFloat => { _ = try self.addNode(root, .{ .Float = @floatCast(f32, from_ptr.*) }); }, .Int, .ComptimeInt => { _ = try self.addNode(root, .{ .Int = @intCast(i32, from_ptr.*) }); }, .Enum => { _ = try self.addNode(root, .{ .String = std.meta.tagName(from_ptr.*) }); }, .Optional => { if (from_ptr.* != null) { return self.extract(root, &from_ptr.*.?); } }, .Struct => |struct_info| { inline for (struct_info.fields) |field| { if (field.name[field.name.len - 1] == '_') { continue; } var field_node = try self.addNode(root, .{ .String = field.name }); try self.extract(field_node, &@field(from_ptr.*, field.name)); } }, .Array => |array_info| { comptime var i: usize = 0; inline while (i < array_info.len) : (i += 1) { var null_node = try self.addNode(root, .Null); try self.extract(null_node, &from_ptr.*[i]); } }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { if (ptr_info.child == ZNode) { _ = try self.copyNode(root, from_ptr.*); } else { try self.extract(root, &from_ptr.*.*); } }, .Slice => { if (ptr_info.child != u8) { for (from_ptr.*) |_, i| { var null_node = try self.addNode(root, .Null); try self.extract(null_node, &from_ptr.*[i]); } } else { _ = try self.addNode(root, .{ .String = from_ptr.* }); } return; }, else => return error.InvalidType, } }, else => return error.InvalidType, } } }; } test "stable after error" { const testing = std.testing; var tree = ZTree(2, 6){}; // Using 1 root, 3 nodes (+1 for root). _ = try tree.appendText("foo:bar"); try testing.expectEqual(@as(usize, 1), tree.root_count); try testing.expectEqual(@as(usize, 3), tree.node_count); try testing.expectError(ZError.TreeFull, tree.appendText("bar:foo:baz:ha:ha")); try testing.expectEqual(@as(usize, 1), tree.root_count); try testing.expectEqual(@as(usize, 3), tree.node_count); // Using +1 root, +2 node = 2 roots, 5 nodes. _ = try tree.appendText("bar"); try testing.expectEqual(@as(usize, 2), tree.root_count); try testing.expectEqual(@as(usize, 5), tree.node_count); try testing.expectError(ZError.TooManyRoots, tree.appendText("foo")); try testing.expectEqual(@as(usize, 2), tree.root_count); try testing.expectEqual(@as(usize, 5), tree.node_count); } test "static tree" { const testing = std.testing; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire ; var tree = ZTree(1, 100){}; const node = try tree.appendText(text); node.convertStrings(); var iter = node.findNextChild(null, .{ .String = "max_particles" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "texture" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "max_particles" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "systems" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .Int = 42 }); try testing.expect(iter == null); } test "node appending and searching" { const testing = std.testing; var tree = ZTree(1, 100){}; var root = try tree.addNode(null, .Null); _ = try tree.addNode(root, .Null); _ = try tree.addNode(root, .{ .String = "Hello" }); _ = try tree.addNode(root, .{ .String = "foo" }); _ = try tree.addNode(root, .{ .Int = 42 }); _ = try tree.addNode(root, .{ .Float = 3.14 }); try testing.expectEqual(@as(usize, 6), root.getChildCount()); try testing.expect(root.findNth(0, .Null) != null); try testing.expect(root.findNth(0, .{ .String = "Hello" }) != null); try testing.expect(root.findNth(0, .{ .String = "foo" }) != null); try testing.expect(root.findNth(1, .{ .String = "Hello" }) == null); try testing.expect(root.findNth(1, .{ .String = "foo" }) == null); try testing.expect(root.findNthAny(0, .String) != null); try testing.expect(root.findNthAny(1, .String) != null); try testing.expect(root.findNthAny(2, .String) == null); try testing.expect(root.findNth(0, .{ .Int = 42 }) != null); try testing.expect(root.findNth(0, .{ .Int = 41 }) == null); try testing.expect(root.findNth(1, .{ .Int = 42 }) == null); try testing.expect(root.findNthAny(0, .Int) != null); try testing.expect(root.findNthAny(1, .Int) == null); try testing.expect(root.findNth(0, .{ .Float = 3.14 }) != null); try testing.expect(root.findNth(0, .{ .Float = 3.13 }) == null); try testing.expect(root.findNth(1, .{ .Float = 3.14 }) == null); try testing.expect(root.findNthAny(0, .Float) != null); try testing.expect(root.findNthAny(1, .Float) == null); try testing.expect(root.findNthAny(0, .Bool) != null); try testing.expect(root.findNth(0, .{ .Bool = true }) != null); try testing.expect(root.findNthAny(1, .Bool) == null); try testing.expect(root.findNth(1, .{ .Bool = true }) == null); } test "node conforming imprint" { const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire \\ params \\exists: anything here ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); //const example = try node.imprint(ConformingStruct); //testing.expectEqual(@as(i32, 100), example.max_particles.?); //testing.expectEqualSlices(u8, "circle", example.texture); //testing.expect(null != example.systems[0]); //testing.expect(null != example.systems[1]); //testing.expectEqual(@as(?ConformingSubStruct, null), example.systems[2]); //testing.expectEqual(ConformingEnum.Foo, example.en.?); //testing.expectEqualSlices(u8, "params", example.systems[0].?.params.?.value.String); } test "node nonconforming imprint" { const testing = std.testing; const NonConformingStruct = struct { max_particles: bool = false, }; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); try testing.expectError(ImprintError.ExpectedBoolNode, node.imprint(NonConformingStruct)); } test "imprint allocations" { const testing = std.testing; const Embedded = struct { name: []const u8 = "", count: u32 = 0, }; const SysAlloc = struct { name: []const u8 = "", params: ?*const ZNode = null, }; const FooAlloc = struct { max_particles: ?*i32 = null, texture: []const u8 = "", systems: []SysAlloc = undefined, embedded: Embedded = .{}, }; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire \\ params \\embedded: \\ name: creator \\ count: 12345 \\ ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); var imprint = try node.imprintAlloc(FooAlloc, testing.allocator); try testing.expectEqual(@as(i32, 100), imprint.result.max_particles.?.*); for (imprint.result.systems) |sys, i| { try testing.expectEqualSlices(u8, ([_][]const u8{ "Emitter", "Fire" })[i], sys.name); } imprint.arena.deinit(); } test "extract" { var text_tree = ZTree(1, 100){}; var text_root = try text_tree.appendText("foo:bar:baz;;42"); const FooNested = struct { a_bool: bool = true, a_int: i32 = 42, a_float: f32 = 3.14, }; const foo_struct = struct { foo: ?i32 = null, hi: []const u8 = "lol", arr: [2]FooNested = [_]FooNested{.{}} ** 2, slice: []const FooNested = &[_]FooNested{ .{}, .{}, .{} }, ptr: *const FooNested = &FooNested{}, a_node: *ZNode = undefined, }{ .a_node = text_root, }; var tree = ZTree(1, 100){}; try tree.extract(null, &foo_struct); } /// A minimal factory for creating structs. The type passed should be an interface. Register structs /// with special declarations and instantiate them with ZNodes. Required declarations: /// - ZNAME: []const u8 // name of the struct referenced in zzz /// - zinit: fn(allocator: *std.mem.Allocator, argz: *const ZNode) anyerror!*T // constructor called pub fn ZFactory(comptime T: type) type { return struct { const Self = @This(); const Ctor = struct { func: fn (allocator: *std.mem.Allocator, argz: *const ZNode) anyerror!*T, }; registered: std.StringHashMap(Ctor), /// Create the factory. The allocator is for the internal HashMap. Instantiated objects /// can have their own allocator. pub fn init(allocator: *std.mem.Allocator) Self { return Self{ .registered = std.StringHashMap(Ctor).init(allocator), }; } /// pub fn deinit(self: *Self) void { self.registered.deinit(); } /// Registers an implementor of the interface. Requires ZNAME and a zinit /// method. pub fn register(self: *Self, comptime S: anytype) !void { const SI = @typeInfo(S); if (SI != .Struct) { @compileError("Expected struct got: " ++ @typeName(S)); } if (!@hasDecl(S, "zinit")) { @compileError("Missing `zinit` on registered struct, it could be private: " ++ @typeName(S)); } if (!@hasDecl(S, "ZNAME")) { @compileError("Missing `ZNAME` on registered struct, it could be private: " ++ @typeName(S)); } const ctor = Ctor{ .func = S.zinit, }; try self.registered.put(S.ZNAME, ctor); } /// Instantiates an object with ZNode. The ZNode's first child must have a string value of /// "name" with the child node's value being the name of the registered struct. The node is /// then passed to zinit. /// /// The caller is responsible for the memory. pub fn instantiate(self: *Self, allocator: *std.mem.Allocator, node: *const ZNode) !*T { const name = node.findNth(0, .{ .String = "name" }) orelse return error.ZNodeMissingName; const value_node = name.getChild(0) orelse return error.ZNodeMissingValueUnderName; if (value_node.value != .String) { return error.ZNodeNameValueNotString; } const ctor = self.registered.get(value_node.value.String) orelse return error.StructNotFound; return try ctor.func(allocator, node); } }; } const FooInterface = struct { const Self = @This(); allocator: ?*std.mem.Allocator = null, default: i32 = 100, fooFn: ?fn (*Self) void = null, deinitFn: ?fn (*const Self) void = null, pub fn foo(self: *Self) void { return self.fooFn.?(self); } pub fn deinit(self: *const Self) void { self.deinitFn.?(self); } }; const FooBar = struct { const Self = @This(); const ZNAME = "Foo"; interface: FooInterface = .{}, bar: i32 = 0, pub fn zinit(allocator: *std.mem.Allocator, argz: *const ZNode) !*FooInterface { _ = argz; var self = try allocator.create(Self); self.* = .{ .interface = .{ .allocator = allocator, .fooFn = foo, .deinitFn = deinit, }, }; //const imprint = try argz.imprint(FooBar); //self.bar = imprint.bar; return &self.interface; } pub fn deinit(interface: *const FooInterface) void { const self = @fieldParentPtr(Self, "interface", interface); interface.allocator.?.destroy(self); } pub fn foo(interface: *FooInterface) void { var self = @fieldParentPtr(FooBar, "interface", interface); _ = self; } }; test "factory" { const testing = std.testing; const text = \\name:Foo \\bar:42 ; var tree = ZTree(1, 100){}; var root = try tree.appendText(text); root.convertStrings(); var factory = ZFactory(FooInterface).init(testing.allocator); defer factory.deinit(); try factory.register(FooBar); const foobar = try factory.instantiate(testing.allocator, root); foobar.foo(); defer foobar.deinit(); }
src/main.zig
//-------------------------------------------------------------------------------- // Section: Types (3) //-------------------------------------------------------------------------------- pub const PFN_PDF_CREATE_RENDERER = fn( param0: ?*IDXGIDevice, param1: ?*?*IPdfRendererNative, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PDF_RENDER_PARAMS = extern struct { SourceRect: D2D_RECT_F, DestinationWidth: u32, DestinationHeight: u32, BackgroundColor: D2D_COLOR_F, IgnoreHighContrast: BOOLEAN, }; const IID_IPdfRendererNative_Value = Guid.initString("7d9dcd91-d277-4947-8527-07a0daeda94a"); pub const IID_IPdfRendererNative = &IID_IPdfRendererNative_Value; pub const IPdfRendererNative = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RenderPageToSurface: fn( self: *const IPdfRendererNative, pdfPage: ?*IUnknown, pSurface: ?*IDXGISurface, offset: POINT, pRenderParams: ?*PDF_RENDER_PARAMS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RenderPageToDeviceContext: fn( self: *const IPdfRendererNative, pdfPage: ?*IUnknown, pD2DDeviceContext: ?*ID2D1DeviceContext, pRenderParams: ?*PDF_RENDER_PARAMS, ) 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 IPdfRendererNative_RenderPageToSurface(self: *const T, pdfPage: ?*IUnknown, pSurface: ?*IDXGISurface, offset: POINT, pRenderParams: ?*PDF_RENDER_PARAMS) callconv(.Inline) HRESULT { return @ptrCast(*const IPdfRendererNative.VTable, self.vtable).RenderPageToSurface(@ptrCast(*const IPdfRendererNative, self), pdfPage, pSurface, offset, pRenderParams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPdfRendererNative_RenderPageToDeviceContext(self: *const T, pdfPage: ?*IUnknown, pD2DDeviceContext: ?*ID2D1DeviceContext, pRenderParams: ?*PDF_RENDER_PARAMS) callconv(.Inline) HRESULT { return @ptrCast(*const IPdfRendererNative.VTable, self.vtable).RenderPageToDeviceContext(@ptrCast(*const IPdfRendererNative, self), pdfPage, pD2DDeviceContext, pRenderParams); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (1) //-------------------------------------------------------------------------------- pub extern "Windows.Data.Pdf" fn PdfCreateRenderer( pDevice: ?*IDXGIDevice, ppRenderer: ?*?*IPdfRendererNative, ) 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 (10) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOLEAN = @import("../../foundation.zig").BOOLEAN; const D2D_COLOR_F = @import("../../graphics/direct2d/common.zig").D2D_COLOR_F; const D2D_RECT_F = @import("../../graphics/direct2d/common.zig").D2D_RECT_F; const HRESULT = @import("../../foundation.zig").HRESULT; const ID2D1DeviceContext = @import("../../graphics/direct2d.zig").ID2D1DeviceContext; const IDXGIDevice = @import("../../graphics/dxgi.zig").IDXGIDevice; const IDXGISurface = @import("../../graphics/dxgi.zig").IDXGISurface; const IUnknown = @import("../../system/com.zig").IUnknown; const POINT = @import("../../foundation.zig").POINT; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_PDF_CREATE_RENDERER")) { _ = PFN_PDF_CREATE_RENDERER; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/win_rt/pdf.zig
pub const CF_REQUEST_KEY_DEFAULT = @as(u32, 0); pub const CF_PLACEHOLDER_MAX_FILE_IDENTITY_LENGTH = @as(u32, 4096); pub const CF_MAX_PRIORITY_HINT = @as(u32, 15); pub const CF_MAX_PROVIDER_NAME_LENGTH = @as(u32, 255); pub const CF_MAX_PROVIDER_VERSION_LENGTH = @as(u32, 255); //-------------------------------------------------------------------------------- // Section: Types (75) //-------------------------------------------------------------------------------- pub const CF_CONNECTION_KEY = isize; pub const CF_FS_METADATA = extern struct { BasicInfo: FILE_BASIC_INFO, FileSize: LARGE_INTEGER, }; pub const CF_PLACEHOLDER_CREATE_FLAGS = enum(u32) { NONE = 0, DISABLE_ON_DEMAND_POPULATION = 1, MARK_IN_SYNC = 2, SUPERSEDE = 4, ALWAYS_FULL = 8, _, pub fn initFlags(o: struct { NONE: u1 = 0, DISABLE_ON_DEMAND_POPULATION: u1 = 0, MARK_IN_SYNC: u1 = 0, SUPERSEDE: u1 = 0, ALWAYS_FULL: u1 = 0, }) CF_PLACEHOLDER_CREATE_FLAGS { return @intToEnum(CF_PLACEHOLDER_CREATE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_PLACEHOLDER_CREATE_FLAGS.NONE) else 0) | (if (o.DISABLE_ON_DEMAND_POPULATION == 1) @enumToInt(CF_PLACEHOLDER_CREATE_FLAGS.DISABLE_ON_DEMAND_POPULATION) else 0) | (if (o.MARK_IN_SYNC == 1) @enumToInt(CF_PLACEHOLDER_CREATE_FLAGS.MARK_IN_SYNC) else 0) | (if (o.SUPERSEDE == 1) @enumToInt(CF_PLACEHOLDER_CREATE_FLAGS.SUPERSEDE) else 0) | (if (o.ALWAYS_FULL == 1) @enumToInt(CF_PLACEHOLDER_CREATE_FLAGS.ALWAYS_FULL) else 0) ); } }; pub const CF_PLACEHOLDER_CREATE_FLAG_NONE = CF_PLACEHOLDER_CREATE_FLAGS.NONE; pub const CF_PLACEHOLDER_CREATE_FLAG_DISABLE_ON_DEMAND_POPULATION = CF_PLACEHOLDER_CREATE_FLAGS.DISABLE_ON_DEMAND_POPULATION; pub const CF_PLACEHOLDER_CREATE_FLAG_MARK_IN_SYNC = CF_PLACEHOLDER_CREATE_FLAGS.MARK_IN_SYNC; pub const CF_PLACEHOLDER_CREATE_FLAG_SUPERSEDE = CF_PLACEHOLDER_CREATE_FLAGS.SUPERSEDE; pub const CF_PLACEHOLDER_CREATE_FLAG_ALWAYS_FULL = CF_PLACEHOLDER_CREATE_FLAGS.ALWAYS_FULL; pub const CF_PLACEHOLDER_CREATE_INFO = extern struct { RelativeFileName: ?[*:0]const u16, FsMetadata: CF_FS_METADATA, FileIdentity: ?*const anyopaque, FileIdentityLength: u32, Flags: CF_PLACEHOLDER_CREATE_FLAGS, Result: HRESULT, CreateUsn: i64, }; pub const CF_SYNC_PROVIDER_STATUS = enum(u32) { DISCONNECTED = 0, IDLE = 1, POPULATE_NAMESPACE = 2, POPULATE_METADATA = 4, POPULATE_CONTENT = 8, SYNC_INCREMENTAL = 16, SYNC_FULL = 32, CONNECTIVITY_LOST = 64, CLEAR_FLAGS = 2147483648, TERMINATED = 3221225473, ERROR = 3221225474, _, pub fn initFlags(o: struct { DISCONNECTED: u1 = 0, IDLE: u1 = 0, POPULATE_NAMESPACE: u1 = 0, POPULATE_METADATA: u1 = 0, POPULATE_CONTENT: u1 = 0, SYNC_INCREMENTAL: u1 = 0, SYNC_FULL: u1 = 0, CONNECTIVITY_LOST: u1 = 0, CLEAR_FLAGS: u1 = 0, TERMINATED: u1 = 0, ERROR: u1 = 0, }) CF_SYNC_PROVIDER_STATUS { return @intToEnum(CF_SYNC_PROVIDER_STATUS, (if (o.DISCONNECTED == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.DISCONNECTED) else 0) | (if (o.IDLE == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.IDLE) else 0) | (if (o.POPULATE_NAMESPACE == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.POPULATE_NAMESPACE) else 0) | (if (o.POPULATE_METADATA == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.POPULATE_METADATA) else 0) | (if (o.POPULATE_CONTENT == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.POPULATE_CONTENT) else 0) | (if (o.SYNC_INCREMENTAL == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.SYNC_INCREMENTAL) else 0) | (if (o.SYNC_FULL == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.SYNC_FULL) else 0) | (if (o.CONNECTIVITY_LOST == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.CONNECTIVITY_LOST) else 0) | (if (o.CLEAR_FLAGS == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.CLEAR_FLAGS) else 0) | (if (o.TERMINATED == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.TERMINATED) else 0) | (if (o.ERROR == 1) @enumToInt(CF_SYNC_PROVIDER_STATUS.ERROR) else 0) ); } }; pub const CF_PROVIDER_STATUS_DISCONNECTED = CF_SYNC_PROVIDER_STATUS.DISCONNECTED; pub const CF_PROVIDER_STATUS_IDLE = CF_SYNC_PROVIDER_STATUS.IDLE; pub const CF_PROVIDER_STATUS_POPULATE_NAMESPACE = CF_SYNC_PROVIDER_STATUS.POPULATE_NAMESPACE; pub const CF_PROVIDER_STATUS_POPULATE_METADATA = CF_SYNC_PROVIDER_STATUS.POPULATE_METADATA; pub const CF_PROVIDER_STATUS_POPULATE_CONTENT = CF_SYNC_PROVIDER_STATUS.POPULATE_CONTENT; pub const CF_PROVIDER_STATUS_SYNC_INCREMENTAL = CF_SYNC_PROVIDER_STATUS.SYNC_INCREMENTAL; pub const CF_PROVIDER_STATUS_SYNC_FULL = CF_SYNC_PROVIDER_STATUS.SYNC_FULL; pub const CF_PROVIDER_STATUS_CONNECTIVITY_LOST = CF_SYNC_PROVIDER_STATUS.CONNECTIVITY_LOST; pub const CF_PROVIDER_STATUS_CLEAR_FLAGS = CF_SYNC_PROVIDER_STATUS.CLEAR_FLAGS; pub const CF_PROVIDER_STATUS_TERMINATED = CF_SYNC_PROVIDER_STATUS.TERMINATED; pub const CF_PROVIDER_STATUS_ERROR = CF_SYNC_PROVIDER_STATUS.ERROR; pub const CF_PROCESS_INFO = extern struct { StructSize: u32, ProcessId: u32, ImagePath: ?[*:0]const u16, PackageName: ?[*:0]const u16, ApplicationId: ?[*:0]const u16, CommandLine: ?[*:0]const u16, SessionId: u32, }; pub const CF_PLATFORM_INFO = extern struct { BuildNumber: u32, RevisionNumber: u32, IntegrationNumber: u32, }; pub const CF_REGISTER_FLAGS = enum(u32) { NONE = 0, UPDATE = 1, DISABLE_ON_DEMAND_POPULATION_ON_ROOT = 2, MARK_IN_SYNC_ON_ROOT = 4, _, pub fn initFlags(o: struct { NONE: u1 = 0, UPDATE: u1 = 0, DISABLE_ON_DEMAND_POPULATION_ON_ROOT: u1 = 0, MARK_IN_SYNC_ON_ROOT: u1 = 0, }) CF_REGISTER_FLAGS { return @intToEnum(CF_REGISTER_FLAGS, (if (o.NONE == 1) @enumToInt(CF_REGISTER_FLAGS.NONE) else 0) | (if (o.UPDATE == 1) @enumToInt(CF_REGISTER_FLAGS.UPDATE) else 0) | (if (o.DISABLE_ON_DEMAND_POPULATION_ON_ROOT == 1) @enumToInt(CF_REGISTER_FLAGS.DISABLE_ON_DEMAND_POPULATION_ON_ROOT) else 0) | (if (o.MARK_IN_SYNC_ON_ROOT == 1) @enumToInt(CF_REGISTER_FLAGS.MARK_IN_SYNC_ON_ROOT) else 0) ); } }; pub const CF_REGISTER_FLAG_NONE = CF_REGISTER_FLAGS.NONE; pub const CF_REGISTER_FLAG_UPDATE = CF_REGISTER_FLAGS.UPDATE; pub const CF_REGISTER_FLAG_DISABLE_ON_DEMAND_POPULATION_ON_ROOT = CF_REGISTER_FLAGS.DISABLE_ON_DEMAND_POPULATION_ON_ROOT; pub const CF_REGISTER_FLAG_MARK_IN_SYNC_ON_ROOT = CF_REGISTER_FLAGS.MARK_IN_SYNC_ON_ROOT; pub const CF_HYDRATION_POLICY_PRIMARY = enum(u16) { PARTIAL = 0, PROGRESSIVE = 1, FULL = 2, ALWAYS_FULL = 3, }; pub const CF_HYDRATION_POLICY_PARTIAL = CF_HYDRATION_POLICY_PRIMARY.PARTIAL; pub const CF_HYDRATION_POLICY_PROGRESSIVE = CF_HYDRATION_POLICY_PRIMARY.PROGRESSIVE; pub const CF_HYDRATION_POLICY_FULL = CF_HYDRATION_POLICY_PRIMARY.FULL; pub const CF_HYDRATION_POLICY_ALWAYS_FULL = CF_HYDRATION_POLICY_PRIMARY.ALWAYS_FULL; pub const CF_HYDRATION_POLICY_PRIMARY_USHORT = extern struct { us: u16, }; pub const CF_HYDRATION_POLICY_MODIFIER = enum(u16) { NONE = 0, VALIDATION_REQUIRED = 1, STREAMING_ALLOWED = 2, AUTO_DEHYDRATION_ALLOWED = 4, ALLOW_FULL_RESTART_HYDRATION = 8, _, pub fn initFlags(o: struct { NONE: u1 = 0, VALIDATION_REQUIRED: u1 = 0, STREAMING_ALLOWED: u1 = 0, AUTO_DEHYDRATION_ALLOWED: u1 = 0, ALLOW_FULL_RESTART_HYDRATION: u1 = 0, }) CF_HYDRATION_POLICY_MODIFIER { return @intToEnum(CF_HYDRATION_POLICY_MODIFIER, (if (o.NONE == 1) @enumToInt(CF_HYDRATION_POLICY_MODIFIER.NONE) else 0) | (if (o.VALIDATION_REQUIRED == 1) @enumToInt(CF_HYDRATION_POLICY_MODIFIER.VALIDATION_REQUIRED) else 0) | (if (o.STREAMING_ALLOWED == 1) @enumToInt(CF_HYDRATION_POLICY_MODIFIER.STREAMING_ALLOWED) else 0) | (if (o.AUTO_DEHYDRATION_ALLOWED == 1) @enumToInt(CF_HYDRATION_POLICY_MODIFIER.AUTO_DEHYDRATION_ALLOWED) else 0) | (if (o.ALLOW_FULL_RESTART_HYDRATION == 1) @enumToInt(CF_HYDRATION_POLICY_MODIFIER.ALLOW_FULL_RESTART_HYDRATION) else 0) ); } }; pub const CF_HYDRATION_POLICY_MODIFIER_NONE = CF_HYDRATION_POLICY_MODIFIER.NONE; pub const CF_HYDRATION_POLICY_MODIFIER_VALIDATION_REQUIRED = CF_HYDRATION_POLICY_MODIFIER.VALIDATION_REQUIRED; pub const CF_HYDRATION_POLICY_MODIFIER_STREAMING_ALLOWED = CF_HYDRATION_POLICY_MODIFIER.STREAMING_ALLOWED; pub const CF_HYDRATION_POLICY_MODIFIER_AUTO_DEHYDRATION_ALLOWED = CF_HYDRATION_POLICY_MODIFIER.AUTO_DEHYDRATION_ALLOWED; pub const CF_HYDRATION_POLICY_MODIFIER_ALLOW_FULL_RESTART_HYDRATION = CF_HYDRATION_POLICY_MODIFIER.ALLOW_FULL_RESTART_HYDRATION; pub const CF_HYDRATION_POLICY_MODIFIER_USHORT = extern struct { us: u16, }; pub const CF_HYDRATION_POLICY = extern struct { Primary: CF_HYDRATION_POLICY_PRIMARY_USHORT, Modifier: CF_HYDRATION_POLICY_MODIFIER_USHORT, }; pub const CF_POPULATION_POLICY_PRIMARY = enum(u16) { PARTIAL = 0, FULL = 2, ALWAYS_FULL = 3, }; pub const CF_POPULATION_POLICY_PARTIAL = CF_POPULATION_POLICY_PRIMARY.PARTIAL; pub const CF_POPULATION_POLICY_FULL = CF_POPULATION_POLICY_PRIMARY.FULL; pub const CF_POPULATION_POLICY_ALWAYS_FULL = CF_POPULATION_POLICY_PRIMARY.ALWAYS_FULL; pub const CF_POPULATION_POLICY_PRIMARY_USHORT = extern struct { us: u16, }; pub const CF_POPULATION_POLICY_MODIFIER = enum(u16) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_POPULATION_POLICY_MODIFIER { return @intToEnum(CF_POPULATION_POLICY_MODIFIER, (if (o.E == 1) @enumToInt(CF_POPULATION_POLICY_MODIFIER.E) else 0) ); } }; pub const CF_POPULATION_POLICY_MODIFIER_NONE = CF_POPULATION_POLICY_MODIFIER.E; pub const CF_POPULATION_POLICY_MODIFIER_USHORT = extern struct { us: u16, }; pub const CF_POPULATION_POLICY = extern struct { Primary: CF_POPULATION_POLICY_PRIMARY_USHORT, Modifier: CF_POPULATION_POLICY_MODIFIER_USHORT, }; pub const CF_PLACEHOLDER_MANAGEMENT_POLICY = enum(i32) { DEFAULT = 0, CREATE_UNRESTRICTED = 1, CONVERT_TO_UNRESTRICTED = 2, UPDATE_UNRESTRICTED = 4, }; pub const CF_PLACEHOLDER_MANAGEMENT_POLICY_DEFAULT = CF_PLACEHOLDER_MANAGEMENT_POLICY.DEFAULT; pub const CF_PLACEHOLDER_MANAGEMENT_POLICY_CREATE_UNRESTRICTED = CF_PLACEHOLDER_MANAGEMENT_POLICY.CREATE_UNRESTRICTED; pub const CF_PLACEHOLDER_MANAGEMENT_POLICY_CONVERT_TO_UNRESTRICTED = CF_PLACEHOLDER_MANAGEMENT_POLICY.CONVERT_TO_UNRESTRICTED; pub const CF_PLACEHOLDER_MANAGEMENT_POLICY_UPDATE_UNRESTRICTED = CF_PLACEHOLDER_MANAGEMENT_POLICY.UPDATE_UNRESTRICTED; pub const CF_INSYNC_POLICY = enum(u32) { NONE = 0, TRACK_FILE_CREATION_TIME = 1, TRACK_FILE_READONLY_ATTRIBUTE = 2, TRACK_FILE_HIDDEN_ATTRIBUTE = 4, TRACK_FILE_SYSTEM_ATTRIBUTE = 8, TRACK_DIRECTORY_CREATION_TIME = 16, TRACK_DIRECTORY_READONLY_ATTRIBUTE = 32, TRACK_DIRECTORY_HIDDEN_ATTRIBUTE = 64, TRACK_DIRECTORY_SYSTEM_ATTRIBUTE = 128, TRACK_FILE_LAST_WRITE_TIME = 256, TRACK_DIRECTORY_LAST_WRITE_TIME = 512, TRACK_FILE_ALL = 5592335, TRACK_DIRECTORY_ALL = 11184880, TRACK_ALL = 16777215, PRESERVE_INSYNC_FOR_SYNC_ENGINE = 2147483648, _, pub fn initFlags(o: struct { NONE: u1 = 0, TRACK_FILE_CREATION_TIME: u1 = 0, TRACK_FILE_READONLY_ATTRIBUTE: u1 = 0, TRACK_FILE_HIDDEN_ATTRIBUTE: u1 = 0, TRACK_FILE_SYSTEM_ATTRIBUTE: u1 = 0, TRACK_DIRECTORY_CREATION_TIME: u1 = 0, TRACK_DIRECTORY_READONLY_ATTRIBUTE: u1 = 0, TRACK_DIRECTORY_HIDDEN_ATTRIBUTE: u1 = 0, TRACK_DIRECTORY_SYSTEM_ATTRIBUTE: u1 = 0, TRACK_FILE_LAST_WRITE_TIME: u1 = 0, TRACK_DIRECTORY_LAST_WRITE_TIME: u1 = 0, TRACK_FILE_ALL: u1 = 0, TRACK_DIRECTORY_ALL: u1 = 0, TRACK_ALL: u1 = 0, PRESERVE_INSYNC_FOR_SYNC_ENGINE: u1 = 0, }) CF_INSYNC_POLICY { return @intToEnum(CF_INSYNC_POLICY, (if (o.NONE == 1) @enumToInt(CF_INSYNC_POLICY.NONE) else 0) | (if (o.TRACK_FILE_CREATION_TIME == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_CREATION_TIME) else 0) | (if (o.TRACK_FILE_READONLY_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_READONLY_ATTRIBUTE) else 0) | (if (o.TRACK_FILE_HIDDEN_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_HIDDEN_ATTRIBUTE) else 0) | (if (o.TRACK_FILE_SYSTEM_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_SYSTEM_ATTRIBUTE) else 0) | (if (o.TRACK_DIRECTORY_CREATION_TIME == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_CREATION_TIME) else 0) | (if (o.TRACK_DIRECTORY_READONLY_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_READONLY_ATTRIBUTE) else 0) | (if (o.TRACK_DIRECTORY_HIDDEN_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_HIDDEN_ATTRIBUTE) else 0) | (if (o.TRACK_DIRECTORY_SYSTEM_ATTRIBUTE == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_SYSTEM_ATTRIBUTE) else 0) | (if (o.TRACK_FILE_LAST_WRITE_TIME == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_LAST_WRITE_TIME) else 0) | (if (o.TRACK_DIRECTORY_LAST_WRITE_TIME == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_LAST_WRITE_TIME) else 0) | (if (o.TRACK_FILE_ALL == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_FILE_ALL) else 0) | (if (o.TRACK_DIRECTORY_ALL == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_DIRECTORY_ALL) else 0) | (if (o.TRACK_ALL == 1) @enumToInt(CF_INSYNC_POLICY.TRACK_ALL) else 0) | (if (o.PRESERVE_INSYNC_FOR_SYNC_ENGINE == 1) @enumToInt(CF_INSYNC_POLICY.PRESERVE_INSYNC_FOR_SYNC_ENGINE) else 0) ); } }; pub const CF_INSYNC_POLICY_NONE = CF_INSYNC_POLICY.NONE; pub const CF_INSYNC_POLICY_TRACK_FILE_CREATION_TIME = CF_INSYNC_POLICY.TRACK_FILE_CREATION_TIME; pub const CF_INSYNC_POLICY_TRACK_FILE_READONLY_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_FILE_READONLY_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_FILE_HIDDEN_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_FILE_HIDDEN_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_FILE_SYSTEM_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_FILE_SYSTEM_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_CREATION_TIME = CF_INSYNC_POLICY.TRACK_DIRECTORY_CREATION_TIME; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_READONLY_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_DIRECTORY_READONLY_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_HIDDEN_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_DIRECTORY_HIDDEN_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_SYSTEM_ATTRIBUTE = CF_INSYNC_POLICY.TRACK_DIRECTORY_SYSTEM_ATTRIBUTE; pub const CF_INSYNC_POLICY_TRACK_FILE_LAST_WRITE_TIME = CF_INSYNC_POLICY.TRACK_FILE_LAST_WRITE_TIME; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_LAST_WRITE_TIME = CF_INSYNC_POLICY.TRACK_DIRECTORY_LAST_WRITE_TIME; pub const CF_INSYNC_POLICY_TRACK_FILE_ALL = CF_INSYNC_POLICY.TRACK_FILE_ALL; pub const CF_INSYNC_POLICY_TRACK_DIRECTORY_ALL = CF_INSYNC_POLICY.TRACK_DIRECTORY_ALL; pub const CF_INSYNC_POLICY_TRACK_ALL = CF_INSYNC_POLICY.TRACK_ALL; pub const CF_INSYNC_POLICY_PRESERVE_INSYNC_FOR_SYNC_ENGINE = CF_INSYNC_POLICY.PRESERVE_INSYNC_FOR_SYNC_ENGINE; pub const CF_HARDLINK_POLICY = enum(u32) { NONE = 0, ALLOWED = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, ALLOWED: u1 = 0, }) CF_HARDLINK_POLICY { return @intToEnum(CF_HARDLINK_POLICY, (if (o.NONE == 1) @enumToInt(CF_HARDLINK_POLICY.NONE) else 0) | (if (o.ALLOWED == 1) @enumToInt(CF_HARDLINK_POLICY.ALLOWED) else 0) ); } }; pub const CF_HARDLINK_POLICY_NONE = CF_HARDLINK_POLICY.NONE; pub const CF_HARDLINK_POLICY_ALLOWED = CF_HARDLINK_POLICY.ALLOWED; pub const CF_SYNC_POLICIES = extern struct { StructSize: u32, Hydration: CF_HYDRATION_POLICY, Population: CF_POPULATION_POLICY, InSync: CF_INSYNC_POLICY, HardLink: CF_HARDLINK_POLICY, PlaceholderManagement: CF_PLACEHOLDER_MANAGEMENT_POLICY, }; pub const CF_SYNC_REGISTRATION = extern struct { StructSize: u32, ProviderName: ?[*:0]const u16, ProviderVersion: ?[*:0]const u16, SyncRootIdentity: ?*const anyopaque, SyncRootIdentityLength: u32, FileIdentity: ?*const anyopaque, FileIdentityLength: u32, ProviderId: Guid, }; pub const CF_CALLBACK_INFO = extern struct { StructSize: u32, ConnectionKey: CF_CONNECTION_KEY, CallbackContext: ?*anyopaque, VolumeGuidName: ?[*:0]const u16, VolumeDosName: ?[*:0]const u16, VolumeSerialNumber: u32, SyncRootFileId: LARGE_INTEGER, SyncRootIdentity: ?*const anyopaque, SyncRootIdentityLength: u32, FileId: LARGE_INTEGER, FileSize: LARGE_INTEGER, FileIdentity: ?*const anyopaque, FileIdentityLength: u32, NormalizedPath: ?[*:0]const u16, TransferKey: LARGE_INTEGER, PriorityHint: u8, CorrelationVector: ?*CORRELATION_VECTOR, ProcessInfo: ?*CF_PROCESS_INFO, RequestKey: LARGE_INTEGER, }; pub const CF_CALLBACK_CANCEL_FLAGS = enum(u32) { NONE = 0, IO_TIMEOUT = 1, IO_ABORTED = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, IO_TIMEOUT: u1 = 0, IO_ABORTED: u1 = 0, }) CF_CALLBACK_CANCEL_FLAGS { return @intToEnum(CF_CALLBACK_CANCEL_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_CANCEL_FLAGS.NONE) else 0) | (if (o.IO_TIMEOUT == 1) @enumToInt(CF_CALLBACK_CANCEL_FLAGS.IO_TIMEOUT) else 0) | (if (o.IO_ABORTED == 1) @enumToInt(CF_CALLBACK_CANCEL_FLAGS.IO_ABORTED) else 0) ); } }; pub const CF_CALLBACK_CANCEL_FLAG_NONE = CF_CALLBACK_CANCEL_FLAGS.NONE; pub const CF_CALLBACK_CANCEL_FLAG_IO_TIMEOUT = CF_CALLBACK_CANCEL_FLAGS.IO_TIMEOUT; pub const CF_CALLBACK_CANCEL_FLAG_IO_ABORTED = CF_CALLBACK_CANCEL_FLAGS.IO_ABORTED; pub const CF_CALLBACK_FETCH_DATA_FLAGS = enum(u32) { NONE = 0, RECOVERY = 1, EXPLICIT_HYDRATION = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, RECOVERY: u1 = 0, EXPLICIT_HYDRATION: u1 = 0, }) CF_CALLBACK_FETCH_DATA_FLAGS { return @intToEnum(CF_CALLBACK_FETCH_DATA_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_FETCH_DATA_FLAGS.NONE) else 0) | (if (o.RECOVERY == 1) @enumToInt(CF_CALLBACK_FETCH_DATA_FLAGS.RECOVERY) else 0) | (if (o.EXPLICIT_HYDRATION == 1) @enumToInt(CF_CALLBACK_FETCH_DATA_FLAGS.EXPLICIT_HYDRATION) else 0) ); } }; pub const CF_CALLBACK_FETCH_DATA_FLAG_NONE = CF_CALLBACK_FETCH_DATA_FLAGS.NONE; pub const CF_CALLBACK_FETCH_DATA_FLAG_RECOVERY = CF_CALLBACK_FETCH_DATA_FLAGS.RECOVERY; pub const CF_CALLBACK_FETCH_DATA_FLAG_EXPLICIT_HYDRATION = CF_CALLBACK_FETCH_DATA_FLAGS.EXPLICIT_HYDRATION; pub const CF_CALLBACK_VALIDATE_DATA_FLAGS = enum(u32) { NONE = 0, EXPLICIT_HYDRATION = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, EXPLICIT_HYDRATION: u1 = 0, }) CF_CALLBACK_VALIDATE_DATA_FLAGS { return @intToEnum(CF_CALLBACK_VALIDATE_DATA_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_VALIDATE_DATA_FLAGS.NONE) else 0) | (if (o.EXPLICIT_HYDRATION == 1) @enumToInt(CF_CALLBACK_VALIDATE_DATA_FLAGS.EXPLICIT_HYDRATION) else 0) ); } }; pub const CF_CALLBACK_VALIDATE_DATA_FLAG_NONE = CF_CALLBACK_VALIDATE_DATA_FLAGS.NONE; pub const CF_CALLBACK_VALIDATE_DATA_FLAG_EXPLICIT_HYDRATION = CF_CALLBACK_VALIDATE_DATA_FLAGS.EXPLICIT_HYDRATION; pub const CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS { return @intToEnum(CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS, (if (o.E == 1) @enumToInt(CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS.E) else 0) ); } }; pub const CF_CALLBACK_FETCH_PLACEHOLDERS_FLAG_NONE = CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS.E; pub const CF_CALLBACK_OPEN_COMPLETION_FLAGS = enum(u32) { NONE = 0, PLACEHOLDER_UNKNOWN = 1, PLACEHOLDER_UNSUPPORTED = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, PLACEHOLDER_UNKNOWN: u1 = 0, PLACEHOLDER_UNSUPPORTED: u1 = 0, }) CF_CALLBACK_OPEN_COMPLETION_FLAGS { return @intToEnum(CF_CALLBACK_OPEN_COMPLETION_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_OPEN_COMPLETION_FLAGS.NONE) else 0) | (if (o.PLACEHOLDER_UNKNOWN == 1) @enumToInt(CF_CALLBACK_OPEN_COMPLETION_FLAGS.PLACEHOLDER_UNKNOWN) else 0) | (if (o.PLACEHOLDER_UNSUPPORTED == 1) @enumToInt(CF_CALLBACK_OPEN_COMPLETION_FLAGS.PLACEHOLDER_UNSUPPORTED) else 0) ); } }; pub const CF_CALLBACK_OPEN_COMPLETION_FLAG_NONE = CF_CALLBACK_OPEN_COMPLETION_FLAGS.NONE; pub const CF_CALLBACK_OPEN_COMPLETION_FLAG_PLACEHOLDER_UNKNOWN = CF_CALLBACK_OPEN_COMPLETION_FLAGS.PLACEHOLDER_UNKNOWN; pub const CF_CALLBACK_OPEN_COMPLETION_FLAG_PLACEHOLDER_UNSUPPORTED = CF_CALLBACK_OPEN_COMPLETION_FLAGS.PLACEHOLDER_UNSUPPORTED; pub const CF_CALLBACK_CLOSE_COMPLETION_FLAGS = enum(u32) { NONE = 0, DELETED = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, DELETED: u1 = 0, }) CF_CALLBACK_CLOSE_COMPLETION_FLAGS { return @intToEnum(CF_CALLBACK_CLOSE_COMPLETION_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_CLOSE_COMPLETION_FLAGS.NONE) else 0) | (if (o.DELETED == 1) @enumToInt(CF_CALLBACK_CLOSE_COMPLETION_FLAGS.DELETED) else 0) ); } }; pub const CF_CALLBACK_CLOSE_COMPLETION_FLAG_NONE = CF_CALLBACK_CLOSE_COMPLETION_FLAGS.NONE; pub const CF_CALLBACK_CLOSE_COMPLETION_FLAG_DELETED = CF_CALLBACK_CLOSE_COMPLETION_FLAGS.DELETED; pub const CF_CALLBACK_DEHYDRATE_FLAGS = enum(u32) { NONE = 0, BACKGROUND = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, BACKGROUND: u1 = 0, }) CF_CALLBACK_DEHYDRATE_FLAGS { return @intToEnum(CF_CALLBACK_DEHYDRATE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_DEHYDRATE_FLAGS.NONE) else 0) | (if (o.BACKGROUND == 1) @enumToInt(CF_CALLBACK_DEHYDRATE_FLAGS.BACKGROUND) else 0) ); } }; pub const CF_CALLBACK_DEHYDRATE_FLAG_NONE = CF_CALLBACK_DEHYDRATE_FLAGS.NONE; pub const CF_CALLBACK_DEHYDRATE_FLAG_BACKGROUND = CF_CALLBACK_DEHYDRATE_FLAGS.BACKGROUND; pub const CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS = enum(u32) { NONE = 0, BACKGROUND = 1, DEHYDRATED = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, BACKGROUND: u1 = 0, DEHYDRATED: u1 = 0, }) CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS { return @intToEnum(CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.NONE) else 0) | (if (o.BACKGROUND == 1) @enumToInt(CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.BACKGROUND) else 0) | (if (o.DEHYDRATED == 1) @enumToInt(CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.DEHYDRATED) else 0) ); } }; pub const CF_CALLBACK_DEHYDRATE_COMPLETION_FLAG_NONE = CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.NONE; pub const CF_CALLBACK_DEHYDRATE_COMPLETION_FLAG_BACKGROUND = CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.BACKGROUND; pub const CF_CALLBACK_DEHYDRATE_COMPLETION_FLAG_DEHYDRATED = CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS.DEHYDRATED; pub const CF_CALLBACK_DELETE_FLAGS = enum(u32) { NONE = 0, IS_DIRECTORY = 1, IS_UNDELETE = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, IS_DIRECTORY: u1 = 0, IS_UNDELETE: u1 = 0, }) CF_CALLBACK_DELETE_FLAGS { return @intToEnum(CF_CALLBACK_DELETE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_DELETE_FLAGS.NONE) else 0) | (if (o.IS_DIRECTORY == 1) @enumToInt(CF_CALLBACK_DELETE_FLAGS.IS_DIRECTORY) else 0) | (if (o.IS_UNDELETE == 1) @enumToInt(CF_CALLBACK_DELETE_FLAGS.IS_UNDELETE) else 0) ); } }; pub const CF_CALLBACK_DELETE_FLAG_NONE = CF_CALLBACK_DELETE_FLAGS.NONE; pub const CF_CALLBACK_DELETE_FLAG_IS_DIRECTORY = CF_CALLBACK_DELETE_FLAGS.IS_DIRECTORY; pub const CF_CALLBACK_DELETE_FLAG_IS_UNDELETE = CF_CALLBACK_DELETE_FLAGS.IS_UNDELETE; pub const CF_CALLBACK_DELETE_COMPLETION_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_CALLBACK_DELETE_COMPLETION_FLAGS { return @intToEnum(CF_CALLBACK_DELETE_COMPLETION_FLAGS, (if (o.E == 1) @enumToInt(CF_CALLBACK_DELETE_COMPLETION_FLAGS.E) else 0) ); } }; pub const CF_CALLBACK_DELETE_COMPLETION_FLAG_NONE = CF_CALLBACK_DELETE_COMPLETION_FLAGS.E; pub const CF_CALLBACK_RENAME_FLAGS = enum(u32) { NONE = 0, IS_DIRECTORY = 1, SOURCE_IN_SCOPE = 2, TARGET_IN_SCOPE = 4, _, pub fn initFlags(o: struct { NONE: u1 = 0, IS_DIRECTORY: u1 = 0, SOURCE_IN_SCOPE: u1 = 0, TARGET_IN_SCOPE: u1 = 0, }) CF_CALLBACK_RENAME_FLAGS { return @intToEnum(CF_CALLBACK_RENAME_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CALLBACK_RENAME_FLAGS.NONE) else 0) | (if (o.IS_DIRECTORY == 1) @enumToInt(CF_CALLBACK_RENAME_FLAGS.IS_DIRECTORY) else 0) | (if (o.SOURCE_IN_SCOPE == 1) @enumToInt(CF_CALLBACK_RENAME_FLAGS.SOURCE_IN_SCOPE) else 0) | (if (o.TARGET_IN_SCOPE == 1) @enumToInt(CF_CALLBACK_RENAME_FLAGS.TARGET_IN_SCOPE) else 0) ); } }; pub const CF_CALLBACK_RENAME_FLAG_NONE = CF_CALLBACK_RENAME_FLAGS.NONE; pub const CF_CALLBACK_RENAME_FLAG_IS_DIRECTORY = CF_CALLBACK_RENAME_FLAGS.IS_DIRECTORY; pub const CF_CALLBACK_RENAME_FLAG_SOURCE_IN_SCOPE = CF_CALLBACK_RENAME_FLAGS.SOURCE_IN_SCOPE; pub const CF_CALLBACK_RENAME_FLAG_TARGET_IN_SCOPE = CF_CALLBACK_RENAME_FLAGS.TARGET_IN_SCOPE; pub const CF_CALLBACK_RENAME_COMPLETION_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_CALLBACK_RENAME_COMPLETION_FLAGS { return @intToEnum(CF_CALLBACK_RENAME_COMPLETION_FLAGS, (if (o.E == 1) @enumToInt(CF_CALLBACK_RENAME_COMPLETION_FLAGS.E) else 0) ); } }; pub const CF_CALLBACK_RENAME_COMPLETION_FLAG_NONE = CF_CALLBACK_RENAME_COMPLETION_FLAGS.E; pub const CF_CALLBACK_DEHYDRATION_REASON = enum(i32) { NONE = 0, USER_MANUAL = 1, SYSTEM_LOW_SPACE = 2, SYSTEM_INACTIVITY = 3, SYSTEM_OS_UPGRADE = 4, }; pub const CF_CALLBACK_DEHYDRATION_REASON_NONE = CF_CALLBACK_DEHYDRATION_REASON.NONE; pub const CF_CALLBACK_DEHYDRATION_REASON_USER_MANUAL = CF_CALLBACK_DEHYDRATION_REASON.USER_MANUAL; pub const CF_CALLBACK_DEHYDRATION_REASON_SYSTEM_LOW_SPACE = CF_CALLBACK_DEHYDRATION_REASON.SYSTEM_LOW_SPACE; pub const CF_CALLBACK_DEHYDRATION_REASON_SYSTEM_INACTIVITY = CF_CALLBACK_DEHYDRATION_REASON.SYSTEM_INACTIVITY; pub const CF_CALLBACK_DEHYDRATION_REASON_SYSTEM_OS_UPGRADE = CF_CALLBACK_DEHYDRATION_REASON.SYSTEM_OS_UPGRADE; pub const CF_CALLBACK_PARAMETERS = extern struct { ParamSize: u32, Anonymous: extern union { Cancel: extern struct { Flags: CF_CALLBACK_CANCEL_FLAGS, Anonymous: extern union { FetchData: extern struct { FileOffset: LARGE_INTEGER, Length: LARGE_INTEGER, }, }, }, FetchData: extern struct { Flags: CF_CALLBACK_FETCH_DATA_FLAGS, RequiredFileOffset: LARGE_INTEGER, RequiredLength: LARGE_INTEGER, OptionalFileOffset: LARGE_INTEGER, OptionalLength: LARGE_INTEGER, LastDehydrationTime: LARGE_INTEGER, LastDehydrationReason: CF_CALLBACK_DEHYDRATION_REASON, }, ValidateData: extern struct { Flags: CF_CALLBACK_VALIDATE_DATA_FLAGS, RequiredFileOffset: LARGE_INTEGER, RequiredLength: LARGE_INTEGER, }, FetchPlaceholders: extern struct { Flags: CF_CALLBACK_FETCH_PLACEHOLDERS_FLAGS, Pattern: ?[*:0]const u16, }, OpenCompletion: extern struct { Flags: CF_CALLBACK_OPEN_COMPLETION_FLAGS, }, CloseCompletion: extern struct { Flags: CF_CALLBACK_CLOSE_COMPLETION_FLAGS, }, Dehydrate: extern struct { Flags: CF_CALLBACK_DEHYDRATE_FLAGS, Reason: CF_CALLBACK_DEHYDRATION_REASON, }, DehydrateCompletion: extern struct { Flags: CF_CALLBACK_DEHYDRATE_COMPLETION_FLAGS, Reason: CF_CALLBACK_DEHYDRATION_REASON, }, Delete: extern struct { Flags: CF_CALLBACK_DELETE_FLAGS, }, DeleteCompletion: extern struct { Flags: CF_CALLBACK_DELETE_COMPLETION_FLAGS, }, Rename: extern struct { Flags: CF_CALLBACK_RENAME_FLAGS, TargetPath: ?[*:0]const u16, }, RenameCompletion: extern struct { Flags: CF_CALLBACK_RENAME_COMPLETION_FLAGS, SourcePath: ?[*:0]const u16, }, }, }; pub const CF_CALLBACK = fn( CallbackInfo: ?*const CF_CALLBACK_INFO, CallbackParameters: ?*const CF_CALLBACK_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) void; pub const CF_CALLBACK_TYPE = enum(i32) { FETCH_DATA = 0, VALIDATE_DATA = 1, CANCEL_FETCH_DATA = 2, FETCH_PLACEHOLDERS = 3, CANCEL_FETCH_PLACEHOLDERS = 4, NOTIFY_FILE_OPEN_COMPLETION = 5, NOTIFY_FILE_CLOSE_COMPLETION = 6, NOTIFY_DEHYDRATE = 7, NOTIFY_DEHYDRATE_COMPLETION = 8, NOTIFY_DELETE = 9, NOTIFY_DELETE_COMPLETION = 10, NOTIFY_RENAME = 11, NOTIFY_RENAME_COMPLETION = 12, NONE = -1, }; pub const CF_CALLBACK_TYPE_FETCH_DATA = CF_CALLBACK_TYPE.FETCH_DATA; pub const CF_CALLBACK_TYPE_VALIDATE_DATA = CF_CALLBACK_TYPE.VALIDATE_DATA; pub const CF_CALLBACK_TYPE_CANCEL_FETCH_DATA = CF_CALLBACK_TYPE.CANCEL_FETCH_DATA; pub const CF_CALLBACK_TYPE_FETCH_PLACEHOLDERS = CF_CALLBACK_TYPE.FETCH_PLACEHOLDERS; pub const CF_CALLBACK_TYPE_CANCEL_FETCH_PLACEHOLDERS = CF_CALLBACK_TYPE.CANCEL_FETCH_PLACEHOLDERS; pub const CF_CALLBACK_TYPE_NOTIFY_FILE_OPEN_COMPLETION = CF_CALLBACK_TYPE.NOTIFY_FILE_OPEN_COMPLETION; pub const CF_CALLBACK_TYPE_NOTIFY_FILE_CLOSE_COMPLETION = CF_CALLBACK_TYPE.NOTIFY_FILE_CLOSE_COMPLETION; pub const CF_CALLBACK_TYPE_NOTIFY_DEHYDRATE = CF_CALLBACK_TYPE.NOTIFY_DEHYDRATE; pub const CF_CALLBACK_TYPE_NOTIFY_DEHYDRATE_COMPLETION = CF_CALLBACK_TYPE.NOTIFY_DEHYDRATE_COMPLETION; pub const CF_CALLBACK_TYPE_NOTIFY_DELETE = CF_CALLBACK_TYPE.NOTIFY_DELETE; pub const CF_CALLBACK_TYPE_NOTIFY_DELETE_COMPLETION = CF_CALLBACK_TYPE.NOTIFY_DELETE_COMPLETION; pub const CF_CALLBACK_TYPE_NOTIFY_RENAME = CF_CALLBACK_TYPE.NOTIFY_RENAME; pub const CF_CALLBACK_TYPE_NOTIFY_RENAME_COMPLETION = CF_CALLBACK_TYPE.NOTIFY_RENAME_COMPLETION; pub const CF_CALLBACK_TYPE_NONE = CF_CALLBACK_TYPE.NONE; pub const CF_CALLBACK_REGISTRATION = extern struct { Type: CF_CALLBACK_TYPE, Callback: ?CF_CALLBACK, }; pub const CF_CONNECT_FLAGS = enum(u32) { NONE = 0, REQUIRE_PROCESS_INFO = 2, REQUIRE_FULL_FILE_PATH = 4, BLOCK_SELF_IMPLICIT_HYDRATION = 8, _, pub fn initFlags(o: struct { NONE: u1 = 0, REQUIRE_PROCESS_INFO: u1 = 0, REQUIRE_FULL_FILE_PATH: u1 = 0, BLOCK_SELF_IMPLICIT_HYDRATION: u1 = 0, }) CF_CONNECT_FLAGS { return @intToEnum(CF_CONNECT_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CONNECT_FLAGS.NONE) else 0) | (if (o.REQUIRE_PROCESS_INFO == 1) @enumToInt(CF_CONNECT_FLAGS.REQUIRE_PROCESS_INFO) else 0) | (if (o.REQUIRE_FULL_FILE_PATH == 1) @enumToInt(CF_CONNECT_FLAGS.REQUIRE_FULL_FILE_PATH) else 0) | (if (o.BLOCK_SELF_IMPLICIT_HYDRATION == 1) @enumToInt(CF_CONNECT_FLAGS.BLOCK_SELF_IMPLICIT_HYDRATION) else 0) ); } }; pub const CF_CONNECT_FLAG_NONE = CF_CONNECT_FLAGS.NONE; pub const CF_CONNECT_FLAG_REQUIRE_PROCESS_INFO = CF_CONNECT_FLAGS.REQUIRE_PROCESS_INFO; pub const CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH = CF_CONNECT_FLAGS.REQUIRE_FULL_FILE_PATH; pub const CF_CONNECT_FLAG_BLOCK_SELF_IMPLICIT_HYDRATION = CF_CONNECT_FLAGS.BLOCK_SELF_IMPLICIT_HYDRATION; pub const CF_OPERATION_TYPE = enum(i32) { TRANSFER_DATA = 0, RETRIEVE_DATA = 1, ACK_DATA = 2, RESTART_HYDRATION = 3, TRANSFER_PLACEHOLDERS = 4, ACK_DEHYDRATE = 5, ACK_DELETE = 6, ACK_RENAME = 7, }; pub const CF_OPERATION_TYPE_TRANSFER_DATA = CF_OPERATION_TYPE.TRANSFER_DATA; pub const CF_OPERATION_TYPE_RETRIEVE_DATA = CF_OPERATION_TYPE.RETRIEVE_DATA; pub const CF_OPERATION_TYPE_ACK_DATA = CF_OPERATION_TYPE.ACK_DATA; pub const CF_OPERATION_TYPE_RESTART_HYDRATION = CF_OPERATION_TYPE.RESTART_HYDRATION; pub const CF_OPERATION_TYPE_TRANSFER_PLACEHOLDERS = CF_OPERATION_TYPE.TRANSFER_PLACEHOLDERS; pub const CF_OPERATION_TYPE_ACK_DEHYDRATE = CF_OPERATION_TYPE.ACK_DEHYDRATE; pub const CF_OPERATION_TYPE_ACK_DELETE = CF_OPERATION_TYPE.ACK_DELETE; pub const CF_OPERATION_TYPE_ACK_RENAME = CF_OPERATION_TYPE.ACK_RENAME; pub const CF_SYNC_STATUS = extern struct { StructSize: u32, Code: u32, DescriptionOffset: u32, DescriptionLength: u32, DeviceIdOffset: u32, DeviceIdLength: u32, }; pub const CF_OPERATION_INFO = extern struct { StructSize: u32, Type: CF_OPERATION_TYPE, ConnectionKey: CF_CONNECTION_KEY, TransferKey: LARGE_INTEGER, CorrelationVector: ?*const CORRELATION_VECTOR, SyncStatus: ?*const CF_SYNC_STATUS, RequestKey: LARGE_INTEGER, }; pub const CF_OPERATION_TRANSFER_DATA_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_TRANSFER_DATA_FLAGS { return @intToEnum(CF_OPERATION_TRANSFER_DATA_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_TRANSFER_DATA_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_TRANSFER_DATA_FLAG_NONE = CF_OPERATION_TRANSFER_DATA_FLAGS.E; pub const CF_OPERATION_RETRIEVE_DATA_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_RETRIEVE_DATA_FLAGS { return @intToEnum(CF_OPERATION_RETRIEVE_DATA_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_RETRIEVE_DATA_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_RETRIEVE_DATA_FLAG_NONE = CF_OPERATION_RETRIEVE_DATA_FLAGS.E; pub const CF_OPERATION_ACK_DATA_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_ACK_DATA_FLAGS { return @intToEnum(CF_OPERATION_ACK_DATA_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_ACK_DATA_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_ACK_DATA_FLAG_NONE = CF_OPERATION_ACK_DATA_FLAGS.E; pub const CF_OPERATION_RESTART_HYDRATION_FLAGS = enum(u32) { NONE = 0, MARK_IN_SYNC = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, MARK_IN_SYNC: u1 = 0, }) CF_OPERATION_RESTART_HYDRATION_FLAGS { return @intToEnum(CF_OPERATION_RESTART_HYDRATION_FLAGS, (if (o.NONE == 1) @enumToInt(CF_OPERATION_RESTART_HYDRATION_FLAGS.NONE) else 0) | (if (o.MARK_IN_SYNC == 1) @enumToInt(CF_OPERATION_RESTART_HYDRATION_FLAGS.MARK_IN_SYNC) else 0) ); } }; pub const CF_OPERATION_RESTART_HYDRATION_FLAG_NONE = CF_OPERATION_RESTART_HYDRATION_FLAGS.NONE; pub const CF_OPERATION_RESTART_HYDRATION_FLAG_MARK_IN_SYNC = CF_OPERATION_RESTART_HYDRATION_FLAGS.MARK_IN_SYNC; pub const CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS = enum(u32) { NONE = 0, STOP_ON_ERROR = 1, DISABLE_ON_DEMAND_POPULATION = 2, _, pub fn initFlags(o: struct { NONE: u1 = 0, STOP_ON_ERROR: u1 = 0, DISABLE_ON_DEMAND_POPULATION: u1 = 0, }) CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS { return @intToEnum(CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS, (if (o.NONE == 1) @enumToInt(CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.NONE) else 0) | (if (o.STOP_ON_ERROR == 1) @enumToInt(CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.STOP_ON_ERROR) else 0) | (if (o.DISABLE_ON_DEMAND_POPULATION == 1) @enumToInt(CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.DISABLE_ON_DEMAND_POPULATION) else 0) ); } }; pub const CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAG_NONE = CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.NONE; pub const CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAG_STOP_ON_ERROR = CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.STOP_ON_ERROR; pub const CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAG_DISABLE_ON_DEMAND_POPULATION = CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS.DISABLE_ON_DEMAND_POPULATION; pub const CF_OPERATION_ACK_DEHYDRATE_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_ACK_DEHYDRATE_FLAGS { return @intToEnum(CF_OPERATION_ACK_DEHYDRATE_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_ACK_DEHYDRATE_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_ACK_DEHYDRATE_FLAG_NONE = CF_OPERATION_ACK_DEHYDRATE_FLAGS.E; pub const CF_OPERATION_ACK_RENAME_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_ACK_RENAME_FLAGS { return @intToEnum(CF_OPERATION_ACK_RENAME_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_ACK_RENAME_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_ACK_RENAME_FLAG_NONE = CF_OPERATION_ACK_RENAME_FLAGS.E; pub const CF_OPERATION_ACK_DELETE_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_OPERATION_ACK_DELETE_FLAGS { return @intToEnum(CF_OPERATION_ACK_DELETE_FLAGS, (if (o.E == 1) @enumToInt(CF_OPERATION_ACK_DELETE_FLAGS.E) else 0) ); } }; pub const CF_OPERATION_ACK_DELETE_FLAG_NONE = CF_OPERATION_ACK_DELETE_FLAGS.E; pub const CF_OPERATION_PARAMETERS = extern struct { ParamSize: u32, Anonymous: extern union { TransferData: extern struct { Flags: CF_OPERATION_TRANSFER_DATA_FLAGS, CompletionStatus: NTSTATUS, Buffer: ?*const anyopaque, Offset: LARGE_INTEGER, Length: LARGE_INTEGER, }, RetrieveData: extern struct { Flags: CF_OPERATION_RETRIEVE_DATA_FLAGS, Buffer: ?*anyopaque, Offset: LARGE_INTEGER, Length: LARGE_INTEGER, ReturnedLength: LARGE_INTEGER, }, AckData: extern struct { Flags: CF_OPERATION_ACK_DATA_FLAGS, CompletionStatus: NTSTATUS, Offset: LARGE_INTEGER, Length: LARGE_INTEGER, }, RestartHydration: extern struct { Flags: CF_OPERATION_RESTART_HYDRATION_FLAGS, FsMetadata: ?*const CF_FS_METADATA, FileIdentity: ?*const anyopaque, FileIdentityLength: u32, }, TransferPlaceholders: extern struct { Flags: CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS, CompletionStatus: NTSTATUS, PlaceholderTotalCount: LARGE_INTEGER, PlaceholderArray: ?*CF_PLACEHOLDER_CREATE_INFO, PlaceholderCount: u32, EntriesProcessed: u32, }, AckDehydrate: extern struct { Flags: CF_OPERATION_ACK_DEHYDRATE_FLAGS, CompletionStatus: NTSTATUS, FileIdentity: ?*const anyopaque, FileIdentityLength: u32, }, AckRename: extern struct { Flags: CF_OPERATION_ACK_RENAME_FLAGS, CompletionStatus: NTSTATUS, }, AckDelete: extern struct { Flags: CF_OPERATION_ACK_DELETE_FLAGS, CompletionStatus: NTSTATUS, }, }, }; pub const CF_CREATE_FLAGS = enum(u32) { NONE = 0, STOP_ON_ERROR = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, STOP_ON_ERROR: u1 = 0, }) CF_CREATE_FLAGS { return @intToEnum(CF_CREATE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CREATE_FLAGS.NONE) else 0) | (if (o.STOP_ON_ERROR == 1) @enumToInt(CF_CREATE_FLAGS.STOP_ON_ERROR) else 0) ); } }; pub const CF_CREATE_FLAG_NONE = CF_CREATE_FLAGS.NONE; pub const CF_CREATE_FLAG_STOP_ON_ERROR = CF_CREATE_FLAGS.STOP_ON_ERROR; pub const CF_OPEN_FILE_FLAGS = enum(u32) { NONE = 0, EXCLUSIVE = 1, WRITE_ACCESS = 2, DELETE_ACCESS = 4, FOREGROUND = 8, _, pub fn initFlags(o: struct { NONE: u1 = 0, EXCLUSIVE: u1 = 0, WRITE_ACCESS: u1 = 0, DELETE_ACCESS: u1 = 0, FOREGROUND: u1 = 0, }) CF_OPEN_FILE_FLAGS { return @intToEnum(CF_OPEN_FILE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_OPEN_FILE_FLAGS.NONE) else 0) | (if (o.EXCLUSIVE == 1) @enumToInt(CF_OPEN_FILE_FLAGS.EXCLUSIVE) else 0) | (if (o.WRITE_ACCESS == 1) @enumToInt(CF_OPEN_FILE_FLAGS.WRITE_ACCESS) else 0) | (if (o.DELETE_ACCESS == 1) @enumToInt(CF_OPEN_FILE_FLAGS.DELETE_ACCESS) else 0) | (if (o.FOREGROUND == 1) @enumToInt(CF_OPEN_FILE_FLAGS.FOREGROUND) else 0) ); } }; pub const CF_OPEN_FILE_FLAG_NONE = CF_OPEN_FILE_FLAGS.NONE; pub const CF_OPEN_FILE_FLAG_EXCLUSIVE = CF_OPEN_FILE_FLAGS.EXCLUSIVE; pub const CF_OPEN_FILE_FLAG_WRITE_ACCESS = CF_OPEN_FILE_FLAGS.WRITE_ACCESS; pub const CF_OPEN_FILE_FLAG_DELETE_ACCESS = CF_OPEN_FILE_FLAGS.DELETE_ACCESS; pub const CF_OPEN_FILE_FLAG_FOREGROUND = CF_OPEN_FILE_FLAGS.FOREGROUND; pub const CF_FILE_RANGE = extern struct { StartingOffset: LARGE_INTEGER, Length: LARGE_INTEGER, }; pub const CF_CONVERT_FLAGS = enum(u32) { NONE = 0, MARK_IN_SYNC = 1, DEHYDRATE = 2, ENABLE_ON_DEMAND_POPULATION = 4, ALWAYS_FULL = 8, FORCE_CONVERT_TO_CLOUD_FILE = 16, _, pub fn initFlags(o: struct { NONE: u1 = 0, MARK_IN_SYNC: u1 = 0, DEHYDRATE: u1 = 0, ENABLE_ON_DEMAND_POPULATION: u1 = 0, ALWAYS_FULL: u1 = 0, FORCE_CONVERT_TO_CLOUD_FILE: u1 = 0, }) CF_CONVERT_FLAGS { return @intToEnum(CF_CONVERT_FLAGS, (if (o.NONE == 1) @enumToInt(CF_CONVERT_FLAGS.NONE) else 0) | (if (o.MARK_IN_SYNC == 1) @enumToInt(CF_CONVERT_FLAGS.MARK_IN_SYNC) else 0) | (if (o.DEHYDRATE == 1) @enumToInt(CF_CONVERT_FLAGS.DEHYDRATE) else 0) | (if (o.ENABLE_ON_DEMAND_POPULATION == 1) @enumToInt(CF_CONVERT_FLAGS.ENABLE_ON_DEMAND_POPULATION) else 0) | (if (o.ALWAYS_FULL == 1) @enumToInt(CF_CONVERT_FLAGS.ALWAYS_FULL) else 0) | (if (o.FORCE_CONVERT_TO_CLOUD_FILE == 1) @enumToInt(CF_CONVERT_FLAGS.FORCE_CONVERT_TO_CLOUD_FILE) else 0) ); } }; pub const CF_CONVERT_FLAG_NONE = CF_CONVERT_FLAGS.NONE; pub const CF_CONVERT_FLAG_MARK_IN_SYNC = CF_CONVERT_FLAGS.MARK_IN_SYNC; pub const CF_CONVERT_FLAG_DEHYDRATE = CF_CONVERT_FLAGS.DEHYDRATE; pub const CF_CONVERT_FLAG_ENABLE_ON_DEMAND_POPULATION = CF_CONVERT_FLAGS.ENABLE_ON_DEMAND_POPULATION; pub const CF_CONVERT_FLAG_ALWAYS_FULL = CF_CONVERT_FLAGS.ALWAYS_FULL; pub const CF_CONVERT_FLAG_FORCE_CONVERT_TO_CLOUD_FILE = CF_CONVERT_FLAGS.FORCE_CONVERT_TO_CLOUD_FILE; pub const CF_UPDATE_FLAGS = enum(u32) { NONE = 0, VERIFY_IN_SYNC = 1, MARK_IN_SYNC = 2, DEHYDRATE = 4, ENABLE_ON_DEMAND_POPULATION = 8, DISABLE_ON_DEMAND_POPULATION = 16, REMOVE_FILE_IDENTITY = 32, CLEAR_IN_SYNC = 64, REMOVE_PROPERTY = 128, PASSTHROUGH_FS_METADATA = 256, ALWAYS_FULL = 512, ALLOW_PARTIAL = 1024, _, pub fn initFlags(o: struct { NONE: u1 = 0, VERIFY_IN_SYNC: u1 = 0, MARK_IN_SYNC: u1 = 0, DEHYDRATE: u1 = 0, ENABLE_ON_DEMAND_POPULATION: u1 = 0, DISABLE_ON_DEMAND_POPULATION: u1 = 0, REMOVE_FILE_IDENTITY: u1 = 0, CLEAR_IN_SYNC: u1 = 0, REMOVE_PROPERTY: u1 = 0, PASSTHROUGH_FS_METADATA: u1 = 0, ALWAYS_FULL: u1 = 0, ALLOW_PARTIAL: u1 = 0, }) CF_UPDATE_FLAGS { return @intToEnum(CF_UPDATE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_UPDATE_FLAGS.NONE) else 0) | (if (o.VERIFY_IN_SYNC == 1) @enumToInt(CF_UPDATE_FLAGS.VERIFY_IN_SYNC) else 0) | (if (o.MARK_IN_SYNC == 1) @enumToInt(CF_UPDATE_FLAGS.MARK_IN_SYNC) else 0) | (if (o.DEHYDRATE == 1) @enumToInt(CF_UPDATE_FLAGS.DEHYDRATE) else 0) | (if (o.ENABLE_ON_DEMAND_POPULATION == 1) @enumToInt(CF_UPDATE_FLAGS.ENABLE_ON_DEMAND_POPULATION) else 0) | (if (o.DISABLE_ON_DEMAND_POPULATION == 1) @enumToInt(CF_UPDATE_FLAGS.DISABLE_ON_DEMAND_POPULATION) else 0) | (if (o.REMOVE_FILE_IDENTITY == 1) @enumToInt(CF_UPDATE_FLAGS.REMOVE_FILE_IDENTITY) else 0) | (if (o.CLEAR_IN_SYNC == 1) @enumToInt(CF_UPDATE_FLAGS.CLEAR_IN_SYNC) else 0) | (if (o.REMOVE_PROPERTY == 1) @enumToInt(CF_UPDATE_FLAGS.REMOVE_PROPERTY) else 0) | (if (o.PASSTHROUGH_FS_METADATA == 1) @enumToInt(CF_UPDATE_FLAGS.PASSTHROUGH_FS_METADATA) else 0) | (if (o.ALWAYS_FULL == 1) @enumToInt(CF_UPDATE_FLAGS.ALWAYS_FULL) else 0) | (if (o.ALLOW_PARTIAL == 1) @enumToInt(CF_UPDATE_FLAGS.ALLOW_PARTIAL) else 0) ); } }; pub const CF_UPDATE_FLAG_NONE = CF_UPDATE_FLAGS.NONE; pub const CF_UPDATE_FLAG_VERIFY_IN_SYNC = CF_UPDATE_FLAGS.VERIFY_IN_SYNC; pub const CF_UPDATE_FLAG_MARK_IN_SYNC = CF_UPDATE_FLAGS.MARK_IN_SYNC; pub const CF_UPDATE_FLAG_DEHYDRATE = CF_UPDATE_FLAGS.DEHYDRATE; pub const CF_UPDATE_FLAG_ENABLE_ON_DEMAND_POPULATION = CF_UPDATE_FLAGS.ENABLE_ON_DEMAND_POPULATION; pub const CF_UPDATE_FLAG_DISABLE_ON_DEMAND_POPULATION = CF_UPDATE_FLAGS.DISABLE_ON_DEMAND_POPULATION; pub const CF_UPDATE_FLAG_REMOVE_FILE_IDENTITY = CF_UPDATE_FLAGS.REMOVE_FILE_IDENTITY; pub const CF_UPDATE_FLAG_CLEAR_IN_SYNC = CF_UPDATE_FLAGS.CLEAR_IN_SYNC; pub const CF_UPDATE_FLAG_REMOVE_PROPERTY = CF_UPDATE_FLAGS.REMOVE_PROPERTY; pub const CF_UPDATE_FLAG_PASSTHROUGH_FS_METADATA = CF_UPDATE_FLAGS.PASSTHROUGH_FS_METADATA; pub const CF_UPDATE_FLAG_ALWAYS_FULL = CF_UPDATE_FLAGS.ALWAYS_FULL; pub const CF_UPDATE_FLAG_ALLOW_PARTIAL = CF_UPDATE_FLAGS.ALLOW_PARTIAL; pub const CF_REVERT_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_REVERT_FLAGS { return @intToEnum(CF_REVERT_FLAGS, (if (o.E == 1) @enumToInt(CF_REVERT_FLAGS.E) else 0) ); } }; pub const CF_REVERT_FLAG_NONE = CF_REVERT_FLAGS.E; pub const CF_HYDRATE_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_HYDRATE_FLAGS { return @intToEnum(CF_HYDRATE_FLAGS, (if (o.E == 1) @enumToInt(CF_HYDRATE_FLAGS.E) else 0) ); } }; pub const CF_HYDRATE_FLAG_NONE = CF_HYDRATE_FLAGS.E; pub const CF_DEHYDRATE_FLAGS = enum(u32) { NONE = 0, BACKGROUND = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, BACKGROUND: u1 = 0, }) CF_DEHYDRATE_FLAGS { return @intToEnum(CF_DEHYDRATE_FLAGS, (if (o.NONE == 1) @enumToInt(CF_DEHYDRATE_FLAGS.NONE) else 0) | (if (o.BACKGROUND == 1) @enumToInt(CF_DEHYDRATE_FLAGS.BACKGROUND) else 0) ); } }; pub const CF_DEHYDRATE_FLAG_NONE = CF_DEHYDRATE_FLAGS.NONE; pub const CF_DEHYDRATE_FLAG_BACKGROUND = CF_DEHYDRATE_FLAGS.BACKGROUND; pub const CF_PIN_STATE = enum(i32) { UNSPECIFIED = 0, PINNED = 1, UNPINNED = 2, EXCLUDED = 3, INHERIT = 4, }; pub const CF_PIN_STATE_UNSPECIFIED = CF_PIN_STATE.UNSPECIFIED; pub const CF_PIN_STATE_PINNED = CF_PIN_STATE.PINNED; pub const CF_PIN_STATE_UNPINNED = CF_PIN_STATE.UNPINNED; pub const CF_PIN_STATE_EXCLUDED = CF_PIN_STATE.EXCLUDED; pub const CF_PIN_STATE_INHERIT = CF_PIN_STATE.INHERIT; pub const CF_SET_PIN_FLAGS = enum(u32) { NONE = 0, RECURSE = 1, RECURSE_ONLY = 2, RECURSE_STOP_ON_ERROR = 4, _, pub fn initFlags(o: struct { NONE: u1 = 0, RECURSE: u1 = 0, RECURSE_ONLY: u1 = 0, RECURSE_STOP_ON_ERROR: u1 = 0, }) CF_SET_PIN_FLAGS { return @intToEnum(CF_SET_PIN_FLAGS, (if (o.NONE == 1) @enumToInt(CF_SET_PIN_FLAGS.NONE) else 0) | (if (o.RECURSE == 1) @enumToInt(CF_SET_PIN_FLAGS.RECURSE) else 0) | (if (o.RECURSE_ONLY == 1) @enumToInt(CF_SET_PIN_FLAGS.RECURSE_ONLY) else 0) | (if (o.RECURSE_STOP_ON_ERROR == 1) @enumToInt(CF_SET_PIN_FLAGS.RECURSE_STOP_ON_ERROR) else 0) ); } }; pub const CF_SET_PIN_FLAG_NONE = CF_SET_PIN_FLAGS.NONE; pub const CF_SET_PIN_FLAG_RECURSE = CF_SET_PIN_FLAGS.RECURSE; pub const CF_SET_PIN_FLAG_RECURSE_ONLY = CF_SET_PIN_FLAGS.RECURSE_ONLY; pub const CF_SET_PIN_FLAG_RECURSE_STOP_ON_ERROR = CF_SET_PIN_FLAGS.RECURSE_STOP_ON_ERROR; pub const CF_IN_SYNC_STATE = enum(i32) { NOT_IN_SYNC = 0, IN_SYNC = 1, }; pub const CF_IN_SYNC_STATE_NOT_IN_SYNC = CF_IN_SYNC_STATE.NOT_IN_SYNC; pub const CF_IN_SYNC_STATE_IN_SYNC = CF_IN_SYNC_STATE.IN_SYNC; pub const CF_SET_IN_SYNC_FLAGS = enum(u32) { E = 0, _, pub fn initFlags(o: struct { E: u1 = 0, }) CF_SET_IN_SYNC_FLAGS { return @intToEnum(CF_SET_IN_SYNC_FLAGS, (if (o.E == 1) @enumToInt(CF_SET_IN_SYNC_FLAGS.E) else 0) ); } }; pub const CF_SET_IN_SYNC_FLAG_NONE = CF_SET_IN_SYNC_FLAGS.E; pub const CF_PLACEHOLDER_STATE = enum(u32) { NO_STATES = 0, PLACEHOLDER = 1, SYNC_ROOT = 2, ESSENTIAL_PROP_PRESENT = 4, IN_SYNC = 8, PARTIAL = 16, PARTIALLY_ON_DISK = 32, INVALID = 4294967295, _, pub fn initFlags(o: struct { NO_STATES: u1 = 0, PLACEHOLDER: u1 = 0, SYNC_ROOT: u1 = 0, ESSENTIAL_PROP_PRESENT: u1 = 0, IN_SYNC: u1 = 0, PARTIAL: u1 = 0, PARTIALLY_ON_DISK: u1 = 0, INVALID: u1 = 0, }) CF_PLACEHOLDER_STATE { return @intToEnum(CF_PLACEHOLDER_STATE, (if (o.NO_STATES == 1) @enumToInt(CF_PLACEHOLDER_STATE.NO_STATES) else 0) | (if (o.PLACEHOLDER == 1) @enumToInt(CF_PLACEHOLDER_STATE.PLACEHOLDER) else 0) | (if (o.SYNC_ROOT == 1) @enumToInt(CF_PLACEHOLDER_STATE.SYNC_ROOT) else 0) | (if (o.ESSENTIAL_PROP_PRESENT == 1) @enumToInt(CF_PLACEHOLDER_STATE.ESSENTIAL_PROP_PRESENT) else 0) | (if (o.IN_SYNC == 1) @enumToInt(CF_PLACEHOLDER_STATE.IN_SYNC) else 0) | (if (o.PARTIAL == 1) @enumToInt(CF_PLACEHOLDER_STATE.PARTIAL) else 0) | (if (o.PARTIALLY_ON_DISK == 1) @enumToInt(CF_PLACEHOLDER_STATE.PARTIALLY_ON_DISK) else 0) | (if (o.INVALID == 1) @enumToInt(CF_PLACEHOLDER_STATE.INVALID) else 0) ); } }; pub const CF_PLACEHOLDER_STATE_NO_STATES = CF_PLACEHOLDER_STATE.NO_STATES; pub const CF_PLACEHOLDER_STATE_PLACEHOLDER = CF_PLACEHOLDER_STATE.PLACEHOLDER; pub const CF_PLACEHOLDER_STATE_SYNC_ROOT = CF_PLACEHOLDER_STATE.SYNC_ROOT; pub const CF_PLACEHOLDER_STATE_ESSENTIAL_PROP_PRESENT = CF_PLACEHOLDER_STATE.ESSENTIAL_PROP_PRESENT; pub const CF_PLACEHOLDER_STATE_IN_SYNC = CF_PLACEHOLDER_STATE.IN_SYNC; pub const CF_PLACEHOLDER_STATE_PARTIAL = CF_PLACEHOLDER_STATE.PARTIAL; pub const CF_PLACEHOLDER_STATE_PARTIALLY_ON_DISK = CF_PLACEHOLDER_STATE.PARTIALLY_ON_DISK; pub const CF_PLACEHOLDER_STATE_INVALID = CF_PLACEHOLDER_STATE.INVALID; pub const CF_PLACEHOLDER_INFO_CLASS = enum(i32) { BASIC = 0, STANDARD = 1, }; pub const CF_PLACEHOLDER_INFO_BASIC = CF_PLACEHOLDER_INFO_CLASS.BASIC; pub const CF_PLACEHOLDER_INFO_STANDARD = CF_PLACEHOLDER_INFO_CLASS.STANDARD; pub const CF_PLACEHOLDER_BASIC_INFO = extern struct { PinState: CF_PIN_STATE, InSyncState: CF_IN_SYNC_STATE, FileId: LARGE_INTEGER, SyncRootFileId: LARGE_INTEGER, FileIdentityLength: u32, FileIdentity: [1]u8, }; pub const CF_PLACEHOLDER_STANDARD_INFO = extern struct { OnDiskDataSize: LARGE_INTEGER, ValidatedDataSize: LARGE_INTEGER, ModifiedDataSize: LARGE_INTEGER, PropertiesSize: LARGE_INTEGER, PinState: CF_PIN_STATE, InSyncState: CF_IN_SYNC_STATE, FileId: LARGE_INTEGER, SyncRootFileId: LARGE_INTEGER, FileIdentityLength: u32, FileIdentity: [1]u8, }; pub const CF_SYNC_ROOT_INFO_CLASS = enum(i32) { BASIC = 0, STANDARD = 1, PROVIDER = 2, }; pub const CF_SYNC_ROOT_INFO_BASIC = CF_SYNC_ROOT_INFO_CLASS.BASIC; pub const CF_SYNC_ROOT_INFO_STANDARD = CF_SYNC_ROOT_INFO_CLASS.STANDARD; pub const CF_SYNC_ROOT_INFO_PROVIDER = CF_SYNC_ROOT_INFO_CLASS.PROVIDER; pub const CF_SYNC_ROOT_BASIC_INFO = extern struct { SyncRootFileId: LARGE_INTEGER, }; pub const CF_SYNC_ROOT_PROVIDER_INFO = extern struct { ProviderStatus: CF_SYNC_PROVIDER_STATUS, ProviderName: [256]u16, ProviderVersion: [256]u16, }; pub const CF_SYNC_ROOT_STANDARD_INFO = extern struct { SyncRootFileId: LARGE_INTEGER, HydrationPolicy: CF_HYDRATION_POLICY, PopulationPolicy: CF_POPULATION_POLICY, InSyncPolicy: CF_INSYNC_POLICY, HardLinkPolicy: CF_HARDLINK_POLICY, ProviderStatus: CF_SYNC_PROVIDER_STATUS, ProviderName: [256]u16, ProviderVersion: [256]u16, SyncRootIdentityLength: u32, SyncRootIdentity: [1]u8, }; pub const CF_PLACEHOLDER_RANGE_INFO_CLASS = enum(i32) { ONDISK = 1, VALIDATED = 2, MODIFIED = 3, }; pub const CF_PLACEHOLDER_RANGE_INFO_ONDISK = CF_PLACEHOLDER_RANGE_INFO_CLASS.ONDISK; pub const CF_PLACEHOLDER_RANGE_INFO_VALIDATED = CF_PLACEHOLDER_RANGE_INFO_CLASS.VALIDATED; pub const CF_PLACEHOLDER_RANGE_INFO_MODIFIED = CF_PLACEHOLDER_RANGE_INFO_CLASS.MODIFIED; //-------------------------------------------------------------------------------- // Section: Functions (35) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlatformInfo( PlatformVersion: ?*CF_PLATFORM_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfRegisterSyncRoot( SyncRootPath: ?[*:0]const u16, Registration: ?*const CF_SYNC_REGISTRATION, Policies: ?*const CF_SYNC_POLICIES, RegisterFlags: CF_REGISTER_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfUnregisterSyncRoot( SyncRootPath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfConnectSyncRoot( SyncRootPath: ?[*:0]const u16, CallbackTable: ?*const CF_CALLBACK_REGISTRATION, CallbackContext: ?*const anyopaque, ConnectFlags: CF_CONNECT_FLAGS, ConnectionKey: ?*CF_CONNECTION_KEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfDisconnectSyncRoot( ConnectionKey: CF_CONNECTION_KEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetTransferKey( FileHandle: ?HANDLE, TransferKey: ?*LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfReleaseTransferKey( FileHandle: ?HANDLE, TransferKey: ?*LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfExecute( OpInfo: ?*const CF_OPERATION_INFO, OpParams: ?*CF_OPERATION_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfUpdateSyncProviderStatus( ConnectionKey: CF_CONNECTION_KEY, ProviderStatus: CF_SYNC_PROVIDER_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfQuerySyncProviderStatus( ConnectionKey: CF_CONNECTION_KEY, ProviderStatus: ?*CF_SYNC_PROVIDER_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17134' pub extern "cldapi" fn CfReportSyncStatus( SyncRootPath: ?[*:0]const u16, SyncStatus: ?*CF_SYNC_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfCreatePlaceholders( BaseDirectoryPath: ?[*:0]const u16, PlaceholderArray: [*]CF_PLACEHOLDER_CREATE_INFO, PlaceholderCount: u32, CreateFlags: CF_CREATE_FLAGS, EntriesProcessed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfOpenFileWithOplock( FilePath: ?[*:0]const u16, Flags: CF_OPEN_FILE_FLAGS, ProtectedHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfReferenceProtectedHandle( ProtectedHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetWin32HandleFromProtectedHandle( ProtectedHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfReleaseProtectedHandle( ProtectedHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfCloseHandle( FileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfConvertToPlaceholder( FileHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? FileIdentity: ?*const anyopaque, FileIdentityLength: u32, ConvertFlags: CF_CONVERT_FLAGS, ConvertUsn: ?*i64, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfUpdatePlaceholder( FileHandle: ?HANDLE, FsMetadata: ?*const CF_FS_METADATA, // TODO: what to do with BytesParamIndex 3? FileIdentity: ?*const anyopaque, FileIdentityLength: u32, DehydrateRangeArray: ?[*]const CF_FILE_RANGE, DehydrateRangeCount: u32, UpdateFlags: CF_UPDATE_FLAGS, UpdateUsn: ?*i64, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfRevertPlaceholder( FileHandle: ?HANDLE, RevertFlags: CF_REVERT_FLAGS, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfHydratePlaceholder( FileHandle: ?HANDLE, StartingOffset: LARGE_INTEGER, Length: LARGE_INTEGER, HydrateFlags: CF_HYDRATE_FLAGS, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "cldapi" fn CfDehydratePlaceholder( FileHandle: ?HANDLE, StartingOffset: LARGE_INTEGER, Length: LARGE_INTEGER, DehydrateFlags: CF_DEHYDRATE_FLAGS, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfSetPinState( FileHandle: ?HANDLE, PinState: CF_PIN_STATE, PinFlags: CF_SET_PIN_FLAGS, Overlapped: ?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfSetInSyncState( FileHandle: ?HANDLE, InSyncState: CF_IN_SYNC_STATE, InSyncFlags: CF_SET_IN_SYNC_FLAGS, InSyncUsn: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfSetCorrelationVector( FileHandle: ?HANDLE, CorrelationVector: ?*const CORRELATION_VECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetCorrelationVector( FileHandle: ?HANDLE, CorrelationVector: ?*CORRELATION_VECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlaceholderStateFromAttributeTag( FileAttributes: u32, ReparseTag: u32, ) callconv(@import("std").os.windows.WINAPI) CF_PLACEHOLDER_STATE; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlaceholderStateFromFileInfo( InfoBuffer: ?*const anyopaque, InfoClass: FILE_INFO_BY_HANDLE_CLASS, ) callconv(@import("std").os.windows.WINAPI) CF_PLACEHOLDER_STATE; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlaceholderStateFromFindData( FindData: ?*const WIN32_FIND_DATAA, ) callconv(@import("std").os.windows.WINAPI) CF_PLACEHOLDER_STATE; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlaceholderInfo( FileHandle: ?HANDLE, InfoClass: CF_PLACEHOLDER_INFO_CLASS, // TODO: what to do with BytesParamIndex 3? InfoBuffer: ?*anyopaque, InfoBufferLength: u32, ReturnedLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetSyncRootInfoByPath( FilePath: ?[*:0]const u16, InfoClass: CF_SYNC_ROOT_INFO_CLASS, InfoBuffer: ?*anyopaque, InfoBufferLength: u32, ReturnedLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetSyncRootInfoByHandle( FileHandle: ?HANDLE, InfoClass: CF_SYNC_ROOT_INFO_CLASS, InfoBuffer: ?*anyopaque, InfoBufferLength: u32, ReturnedLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfGetPlaceholderRangeInfo( FileHandle: ?HANDLE, InfoClass: CF_PLACEHOLDER_RANGE_INFO_CLASS, StartingOffset: LARGE_INTEGER, Length: LARGE_INTEGER, // TODO: what to do with BytesParamIndex 5? InfoBuffer: ?*anyopaque, InfoBufferLength: u32, ReturnedLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "cldapi" fn CfReportProviderProgress( ConnectionKey: CF_CONNECTION_KEY, TransferKey: LARGE_INTEGER, ProviderProgressTotal: LARGE_INTEGER, ProviderProgressCompleted: LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "cldapi" fn CfReportProviderProgress2( ConnectionKey: CF_CONNECTION_KEY, TransferKey: LARGE_INTEGER, RequestKey: LARGE_INTEGER, ProviderProgressTotal: LARGE_INTEGER, ProviderProgressCompleted: LARGE_INTEGER, TargetSessionId: u32, ) 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 (12) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const CORRELATION_VECTOR = @import("../system/correlation_vector.zig").CORRELATION_VECTOR; const FILE_BASIC_INFO = @import("../storage/file_system.zig").FILE_BASIC_INFO; const FILE_INFO_BY_HANDLE_CLASS = @import("../storage/file_system.zig").FILE_INFO_BY_HANDLE_CLASS; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const NTSTATUS = @import("../foundation.zig").NTSTATUS; const OVERLAPPED = @import("../system/io.zig").OVERLAPPED; const PWSTR = @import("../foundation.zig").PWSTR; const WIN32_FIND_DATAA = @import("../storage/file_system.zig").WIN32_FIND_DATAA; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "CF_CALLBACK")) { _ = CF_CALLBACK; } @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/storage/cloud_filters.zig
const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const tools = @import("tools"); const Vec2 = tools.Vec2; const stride: usize = 11; const width = 10; const height = 10; const Border = u10; const Map = struct { ident: u32, map: []const u8, borders: ?struct { canon: [4]Border, transformed: [8][4]Border }, }; fn push_bit(v: *u10, tile: u8) void { v.* = (v.* << 1) | (if (tile == '.') @as(u1, 0) else @as(u1, 1)); } fn extractBorders(map: []const u8) [4]Border { var b: [4]Border = undefined; var i: usize = 0; while (i < width) : (i += 1) { push_bit(&b[0], map[i]); push_bit(&b[1], map[i * stride + (width - 1)]); push_bit(&b[2], map[i + (height - 1) * stride]); push_bit(&b[3], map[i * stride + 0]); } return b; } // tranforme la "map" de t par rapport à son centre. fn transform(in: Map, t: Vec2.Transfo, out_buf: []u8) Map { const r = Vec2.referential(t); const c2 = Vec2{ .x = width - 1, .y = height - 1 }; // coordonées doublées pour avoir le centre entre deux cases. var j: i32 = 0; while (j < height) : (j += 1) { var i: i32 = 0; while (i < width) : (i += 1) { const o2 = Vec2{ .x = i * 2 - c2.x, .y = j * 2 - c2.y }; const p2 = Vec2.add(Vec2.scale(o2.x, r.x), Vec2.scale(o2.y, r.y)); const p = Vec2{ .x = @intCast(u16, p2.x + c2.x) / 2, .y = @intCast(u16, p2.y + c2.y) / 2 }; // print("{} <- {} == {}\n", .{ o2, p2, w }); out_buf[@intCast(u32, i) + @intCast(u32, j) * stride] = in.map[@intCast(u32, p.x) + @intCast(u32, p.y) * stride]; } out_buf[width + @intCast(u32, j) * stride] = '\n'; } return Map{ .ident = in.ident, .map = out_buf[0 .. height * stride], .borders = null, }; } fn computeTransormedBorders(in: *Map) void { var borders: [8][4]Border = undefined; for (Vec2.all_tranfos) |t| { var buf: [stride * height]u8 = undefined; const m = transform(in.*, t, &buf); borders[@enumToInt(t)] = extractBorders(m.map); } var canon: [4]Border = undefined; for (canon) |*it, i| { it.* = if (borders[0][i] < @bitReverse(Border, borders[0][i])) borders[0][i] else @bitReverse(Border, borders[0][i]); } const b = borders[0]; assert((b[0] | b[1] | b[2] | b[3]) != 0); // valeur spéciale reservée in.borders = .{ .canon = canon, .transformed = borders }; } fn debugPrint(m: Map) void { print("map n°{}: borders={b},{b},{b},{b}\n", .{ m.ident, m.borders[0], m.borders[1], m.borders[2], m.borders[3] }); print("{}", .{m.map}); } const State = struct { placed: u8, list: [150]struct { map_idx: u8, t: Vec2.Transfo }, }; fn bigPosFromIndex(idx: usize, big_stride: usize) Vec2 { if (true) { // sens de lecture -> permet de placer un coin dès le debut au bon endroit. return Vec2{ .y = @intCast(i32, idx / big_stride), .x = @intCast(i32, idx % big_stride) }; } else { // spirale partant du centre. const c = Vec2{ .y = @intCast(i32, big_stride / 2), .x = @intCast(i32, big_stride / 2) }; const p = Vec2.add(c, tools.posFromSpiralIndex(idx)); const s = @intCast(i32, big_stride); return Vec2{ .x = @intCast(i32, @mod(p.x, s)), .y = @intCast(i32, @mod(p.y, s)) }; // gère le fait que c'est décentré si la taille est paire } } fn checkValid(s: State, maps: []const Map) bool { const big_stride = std.math.sqrt(maps.len); var borders_mem = [_][4]Border{.{ 0, 0, 0, 0 }} ** (16 * 16); var borders = borders_mem[0 .. big_stride * big_stride]; for (s.list[0..s.placed]) |it, i| { const p = bigPosFromIndex(i, big_stride); assert(p.y >= 0 and p.y < big_stride and p.x >= 0 and p.x < big_stride); borders[@intCast(usize, p.x) + @intCast(usize, p.y) * big_stride] = maps[it.map_idx].borders.?.transformed[@enumToInt(it.t)]; } for (borders[0 .. big_stride * big_stride]) |b, i| { if ((b[0] | b[1] | b[2] | b[3]) == 0) continue; const p = Vec2{ .x = @intCast(i32, i % big_stride), .y = @intCast(i32, i / big_stride) }; const border_list = [_]struct { this: u8, other: u8, d: Vec2 }{ .{ .this = 0, .other = 2, .d = Vec2{ .x = 0, .y = -1 } }, .{ .this = 3, .other = 1, .d = Vec2{ .x = -1, .y = 0 } }, .{ .this = 1, .other = 3, .d = Vec2{ .x = 1, .y = 0 } }, .{ .this = 2, .other = 0, .d = Vec2{ .x = 0, .y = 1 } }, }; for (border_list) |it| { const n = Vec2.add(p, it.d); const neib = if (n.y >= 0 and n.y < big_stride and n.x >= 0 and n.x < big_stride) borders[@intCast(usize, n.x) + @intCast(usize, n.y) * big_stride] else [4]Border{ 0, 0, 0, 0 }; const empty = ((neib[0] | neib[1] | neib[2] | neib[3]) == 0); if (!empty and b[it.this] != neib[it.other]) return false; } } return true; } fn replaceIfMatches(pat: []const []const u8, p: Vec2, t: Vec2.Transfo, map: []u8, w: usize, h: usize) void { const r = Vec2.referential(t); // check if pattern matches... for (pat) |line, j| { for (line) |c, i| { if (c == ' ') continue; assert(c == '#'); const p1 = p.add(Vec2.scale(@intCast(i32, i), r.x)).add(Vec2.scale(@intCast(i32, j), r.y)); if (p1.x < 0 or p1.x >= w) return; if (p1.y < 0 or p1.y >= h) return; if (map[@intCast(usize, p1.y) * w + @intCast(usize, p1.x)] != c) return; } } // .. if ok, replace pattern for (pat) |line, j| { for (line) |c, i| { if (c == ' ') continue; const p1 = p.add(Vec2.scale(@intCast(i32, i), r.x)).add(Vec2.scale(@intCast(i32, j), r.y)); map[@intCast(usize, p1.y) * w + @intCast(usize, p1.x)] = '0'; } } } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const param: struct { maps: []const Map, big_stride: usize, } = blk: { var maps = std.ArrayList(Map).init(arena.allocator()); var ident: ?u32 = null; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { if (tools.match_pattern("Tile {}:", line)) |fields| { ident = @intCast(u32, fields[0].imm); } else { const w = std.mem.indexOfScalar(u8, input_text, '\n').?; assert(w == width); assert(ident != null); var map = line; map.len = stride * height; var m = Map{ .ident = ident.?, .map = map, .borders = null }; computeTransormedBorders(&m); try maps.append(m); var h: usize = 1; while (h < height) : (h += 1) { _ = it.next(); } ident = null; } } //print("{}\n", .{maps.items.len}); break :blk .{ .maps = maps.items, .big_stride = std.math.sqrt(maps.items.len), }; }; // corner candidate pieces: const corners: []u8 = blk: { const occurences = try allocator.alloc(u8, 1 << 10); defer allocator.free(occurences); std.mem.set(u8, occurences, 0); for (param.maps) |m| { for (m.borders.?.canon) |b| occurences[b] += 1; } for (occurences) |it| assert(it <= 2); // pff en fait il n'y a pas d'ambiguités... var corners = std.ArrayList(u8).init(arena.allocator()); for (param.maps) |m, i| { var uniq: u32 = 0; for (m.borders.?.canon) |b| uniq += @boolToInt(occurences[b] == 1); assert(uniq <= 2); if (uniq == 2) // deux bords uniques -> coin! try corners.append(@intCast(u8, i)); } //print("found corner pieces: {}\n", .{corners.items}); break :blk corners.items; }; var final_state: State = undefined; const ans1 = ans: { // nb: vu qu'il n'y a pas d'ambiguité, on pourrait juste faire corners[0]*..*corner[3] pour ans1. const BFS = tools.BestFirstSearch(State, void); var bfs = BFS.init(allocator); defer bfs.deinit(); const initial_state = blk: { var s = State{ .placed = 0, .list = undefined }; for (s.list) |*m, i| { m.map_idx = if (i < param.maps.len) @intCast(u8, i) else undefined; m.t = .r0; } // comment avec un coin, ça permet de trouver direct une bonne solution s.list[0].map_idx = corners[0]; s.list[corners[0]].map_idx = 0; break :blk s; }; try bfs.insert(BFS.Node{ .state = initial_state, .trace = {}, .rating = @intCast(i32, param.maps.len), .cost = 0 }); final_state = result: while (bfs.pop()) |n| { //print("agenda: {}, steps:{}\n", .{ bfs.agenda.count(), n.cost }); var next_candidate = n.state.placed; while (next_candidate < param.maps.len) : (next_candidate += 1) { var next = n; next.cost = n.cost + 1; next.rating = n.rating - 1; next.state.list[n.state.placed] = n.state.list[next_candidate]; next.state.list[next_candidate] = n.state.list[n.state.placed]; next.state.placed = n.state.placed + 1; for (Vec2.all_tranfos) |t| { if (n.cost == 0 and t != .r0) continue; // pas la peine d'explorer les 8 sytémetries et trouver 8 resultats.. next.state.list[n.state.placed].t = t; if (!checkValid(next.state, param.maps)) continue; if (next.state.placed == param.maps.len) break :result next.state; // bingo! try bfs.insert(next); } } } else unreachable; if (false) { print("final state: ", .{}); for (final_state.list[0..param.maps.len]) |it, i| { const p = bigPosFromIndex(i, param.big_stride); print("{}:{}{}, ", .{ p, param.maps[it.map_idx].ident, it.t }); } print("\n", .{}); } var checksum: u64 = 1; checksum *= param.maps[final_state.list[0].map_idx].ident; checksum *= param.maps[final_state.list[param.big_stride - 1].map_idx].ident; checksum *= param.maps[final_state.list[param.maps.len - 1].map_idx].ident; checksum *= param.maps[final_state.list[param.maps.len - param.big_stride].map_idx].ident; break :ans checksum; }; const ans2 = ans: { const h = (height - 2) * param.big_stride; const w = (width - 2) * param.big_stride; var big = try allocator.alloc(u8, w * h); defer allocator.free(big); // build merged map for (final_state.list[0..final_state.placed]) |it, i| { const big_p = bigPosFromIndex(i, param.big_stride); var buf: [stride * height]u8 = undefined; const m = transform(param.maps[it.map_idx], it.t, &buf); var j: usize = 0; while (j < height - 2) : (j += 1) { const o = ((@intCast(u32, big_p.y) * (height - 2) + j) * w + @intCast(u32, big_p.x) * (width - 2)); std.mem.copy(u8, big[o .. o + (width - 2)], m.map[(j + 1) * stride + 1 .. (j + 1) * stride + 1 + (width - 2)]); } } { const monster = [_][]const u8{ " # ", "# ## ## ###", " # # # # # # ", }; for (Vec2.all_tranfos) |t| { var j: i32 = 0; while (j < h) : (j += 1) { var i: i32 = 0; while (i < w) : (i += 1) { replaceIfMatches(&monster, Vec2{ .x = i, .y = j }, t, big, w, h); } } } if (false) { print("bigmap: \n", .{}); var j: usize = 0; while (j < h) : (j += 1) { print("{}\n", .{big[j * w .. (j + 1) * w]}); } } } var nb_rocks: usize = 0; for (big) |it| { if (it == '#') nb_rocks += 1; } break :ans nb_rocks; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day20.txt", run);
2020/day20.zig
const io = @import("../../lib/io.zig"); const heap = @import("std").heap; const fmt = @import("std").fmt; const mem = @import("std").mem; const Writer = @import("std").io.Writer; const VGA_WIDTH = 80; const VGA_HEIGHT = 25; const VGA_SIZE = VGA_WIDTH * VGA_HEIGHT; pub const ConsoleColors = enum(u8) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, LightBrown = 14, White = 15, }; var row: usize = 0; var column: usize = 0; var color = vgaEntryColor(ConsoleColors.LightGray, ConsoleColors.Black); var buffer = @intToPtr([*]volatile u16, 0xB8000); fn vgaEntryColor(fg: ?ConsoleColors, bg: ?ConsoleColors) u8 { var fg_: ConsoleColors = ConsoleColors.LightGray; var bg_: ConsoleColors = ConsoleColors.Black; if (fg) |fg__| { fg_ = fg__; } if (bg) |bg__| { bg_ = bg__; } return @enumToInt(fg_) | (@enumToInt(bg_) << 4); } fn vgaEntry(uc: u8, new_color: u8) u16 { return uc | (@intCast(u16, new_color) << 8); } pub fn initialize() void { clear(); } pub fn enableCursor() void { io.outb(0x3D4, 0x0A); io.outb(0x3D5, (io.inb(0x3D5) & 0xC0) | 13); io.outb(0x3D4, 0x0B); io.outb(0x3D5, (io.inb(0x3D5) & 0xE0) | 15); } pub fn disableCursor() void { io.outb(0x3D4, 0x0A); io.outb(0x3D5, 0x20); } pub fn setCursorPosition(x: u16, y: u16) void { const pos = (y * VGA_WIDTH) + x; io.outb(0x3D4, 0x0F); io.outb(0x3D5, pos & 0xFF); io.outb(0x3D4, 0x0E); io.outb(0x3D5, (pos >> 8) & 0xFF); } pub fn getCursorPosition() u16 { var pos: u16 = 0; io.outb(0x3D4, 0x0F); pos |= io.inb(0x3D5); io.outb(0x3D4, 0x0E); pos |= io.inb(0x3D5) << 8; return pos; } pub fn setColor(fg: ?ConsoleColors, bg: ?ConsoleColors) void { color = vgaEntryColor(fg, bg); } pub fn clear() void { mem.set(u16, buffer[0..VGA_SIZE], vgaEntry(' ', color)); } fn scroll() void { var x: usize = 0; var y: usize = 0; while (y < VGA_HEIGHT - 1) : (y += 1) { while (x < VGA_WIDTH) : (x += 1) { buffer[(y * VGA_WIDTH) + x] = buffer[((y + 1) * VGA_WIDTH) + x]; } } while (x < VGA_WIDTH) : (x += 1) { buffer[(y * VGA_WIDTH) + x] = vgaEntry(' ', color); } column = 0; row = VGA_HEIGHT - 1; } pub fn putCharAt(c: u8, new_color: u8, x: usize, y: usize) void { const index: usize = (y * VGA_WIDTH) + x; buffer[index] = vgaEntry(c, new_color); } pub fn putChar(c: u8) void { switch (c) { '\r' => column = 0, '\n' => { column = 0; row += 1; }, '\t' => column += 8, else => putCharAt(c, color, column, row), } if (c != '\n') { defer column += 1; if (column == VGA_WIDTH) { column = 0; defer row += 1; if (row == VGA_HEIGHT) { scroll(); } } } else { if (row == VGA_HEIGHT) { scroll(); } } } pub fn puts(data: []const u8) void { for (data) |c| putChar(c); } pub const writer = Writer(void, error{}, callback){ .context = {} }; fn callback(_: void, string: []const u8) error{}!usize { puts(string); return string.len; } pub fn printf(comptime format: []const u8, args: anytype) void { fmt.format(writer, format, args) catch unreachable; }
stage1/bios/console.zig
//-------------------------------------------------------------------------------- // Section: Types (5) //-------------------------------------------------------------------------------- pub const PFN_D3D11ON12_CREATE_DEVICE = fn( param0: ?*IUnknown, param1: u32, param2: ?[*]const D3D_FEATURE_LEVEL, FeatureLevels: u32, param4: ?[*]?*IUnknown, NumQueues: u32, param6: u32, param7: ?*?*ID3D11Device, param8: ?*?*ID3D11DeviceContext, param9: ?*D3D_FEATURE_LEVEL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const D3D11_RESOURCE_FLAGS = extern struct { BindFlags: u32, MiscFlags: u32, CPUAccessFlags: u32, StructureByteStride: u32, }; const IID_ID3D11On12Device_Value = @import("../zig.zig").Guid.initString("85611e73-70a9-490e-9614-a9e302777904"); pub const IID_ID3D11On12Device = &IID_ID3D11On12Device_Value; pub const ID3D11On12Device = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateWrappedResource: fn( self: *const ID3D11On12Device, pResource12: ?*IUnknown, pFlags11: ?*const D3D11_RESOURCE_FLAGS, InState: D3D12_RESOURCE_STATES, OutState: D3D12_RESOURCE_STATES, riid: ?*const Guid, ppResource11: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseWrappedResources: fn( self: *const ID3D11On12Device, ppResources: [*]?*ID3D11Resource, NumResources: u32, ) callconv(@import("std").os.windows.WINAPI) void, AcquireWrappedResources: fn( self: *const ID3D11On12Device, ppResources: [*]?*ID3D11Resource, NumResources: u32, ) callconv(@import("std").os.windows.WINAPI) void, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device_CreateWrappedResource(self: *const T, pResource12: ?*IUnknown, pFlags11: ?*const D3D11_RESOURCE_FLAGS, InState: D3D12_RESOURCE_STATES, OutState: D3D12_RESOURCE_STATES, riid: ?*const Guid, ppResource11: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const ID3D11On12Device.VTable, self.vtable).CreateWrappedResource(@ptrCast(*const ID3D11On12Device, self), pResource12, pFlags11, InState, OutState, riid, ppResource11); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device_ReleaseWrappedResources(self: *const T, ppResources: [*]?*ID3D11Resource, NumResources: u32) callconv(.Inline) void { return @ptrCast(*const ID3D11On12Device.VTable, self.vtable).ReleaseWrappedResources(@ptrCast(*const ID3D11On12Device, self), ppResources, NumResources); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device_AcquireWrappedResources(self: *const T, ppResources: [*]?*ID3D11Resource, NumResources: u32) callconv(.Inline) void { return @ptrCast(*const ID3D11On12Device.VTable, self.vtable).AcquireWrappedResources(@ptrCast(*const ID3D11On12Device, self), ppResources, NumResources); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows10.0.18362' const IID_ID3D11On12Device1_Value = @import("../zig.zig").Guid.initString("bdb64df4-ea2f-4c70-b861-aaab1258bb5d"); pub const IID_ID3D11On12Device1 = &IID_ID3D11On12Device1_Value; pub const ID3D11On12Device1 = extern struct { pub const VTable = extern struct { base: ID3D11On12Device.VTable, GetD3D12Device: fn( self: *const ID3D11On12Device1, riid: ?*const Guid, ppvDevice: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ID3D11On12Device.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device1_GetD3D12Device(self: *const T, riid: ?*const Guid, ppvDevice: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const ID3D11On12Device1.VTable, self.vtable).GetD3D12Device(@ptrCast(*const ID3D11On12Device1, self), riid, ppvDevice); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows10.0.19041' const IID_ID3D11On12Device2_Value = @import("../zig.zig").Guid.initString("dc90f331-4740-43fa-866e-67f12cb58223"); pub const IID_ID3D11On12Device2 = &IID_ID3D11On12Device2_Value; pub const ID3D11On12Device2 = extern struct { pub const VTable = extern struct { base: ID3D11On12Device1.VTable, UnwrapUnderlyingResource: fn( self: *const ID3D11On12Device2, pResource11: ?*ID3D11Resource, pCommandQueue: ?*ID3D12CommandQueue, riid: ?*const Guid, ppvResource12: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReturnUnderlyingResource: fn( self: *const ID3D11On12Device2, pResource11: ?*ID3D11Resource, NumSync: u32, pSignalValues: [*]u64, ppFences: [*]?*ID3D12Fence, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ID3D11On12Device1.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device2_UnwrapUnderlyingResource(self: *const T, pResource11: ?*ID3D11Resource, pCommandQueue: ?*ID3D12CommandQueue, riid: ?*const Guid, ppvResource12: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const ID3D11On12Device2.VTable, self.vtable).UnwrapUnderlyingResource(@ptrCast(*const ID3D11On12Device2, self), pResource11, pCommandQueue, riid, ppvResource12); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ID3D11On12Device2_ReturnUnderlyingResource(self: *const T, pResource11: ?*ID3D11Resource, NumSync: u32, pSignalValues: [*]u64, ppFences: [*]?*ID3D12Fence) callconv(.Inline) HRESULT { return @ptrCast(*const ID3D11On12Device2.VTable, self.vtable).ReturnUnderlyingResource(@ptrCast(*const ID3D11On12Device2, self), pResource11, NumSync, pSignalValues, ppFences); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (1) //-------------------------------------------------------------------------------- pub extern "d3d11" fn D3D11On12CreateDevice( pDevice: ?*IUnknown, Flags: u32, pFeatureLevels: ?[*]const D3D_FEATURE_LEVEL, FeatureLevels: u32, ppCommandQueues: ?[*]?*IUnknown, NumQueues: u32, NodeMask: u32, ppDevice: ?*?*ID3D11Device, ppImmediateContext: ?*?*ID3D11DeviceContext, pChosenFeatureLevel: ?*D3D_FEATURE_LEVEL, ) 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 (10) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const D3D12_RESOURCE_STATES = @import("../graphics/direct3d12.zig").D3D12_RESOURCE_STATES; const D3D_FEATURE_LEVEL = @import("../graphics/direct3d.zig").D3D_FEATURE_LEVEL; const HRESULT = @import("../foundation.zig").HRESULT; const ID3D11Device = @import("../graphics/direct3d11.zig").ID3D11Device; const ID3D11DeviceContext = @import("../graphics/direct3d11.zig").ID3D11DeviceContext; const ID3D11Resource = @import("../graphics/direct3d11.zig").ID3D11Resource; const ID3D12CommandQueue = @import("../graphics/direct3d12.zig").ID3D12CommandQueue; const ID3D12Fence = @import("../graphics/direct3d12.zig").ID3D12Fence; const IUnknown = @import("../system/com.zig").IUnknown; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_D3D11ON12_CREATE_DEVICE")) { _ = PFN_D3D11ON12_CREATE_DEVICE; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/graphics/direct3d11on12.zig
const xcb = @import("../xcb.zig"); pub const id = xcb.Extension{ .name = "RENDER", .global_id = 0 }; pub const PictType = extern enum(c_uint) { @"Indexed" = 0, @"Direct" = 1, }; pub const Picture = extern enum(c_uint) { @"None" = 0, }; pub const PictOp = extern enum(c_uint) { @"Clear" = 0, @"Src" = 1, @"Dst" = 2, @"Over" = 3, @"OverReverse" = 4, @"In" = 5, @"InReverse" = 6, @"Out" = 7, @"OutReverse" = 8, @"Atop" = 9, @"AtopReverse" = 10, @"Xor" = 11, @"Add" = 12, @"Saturate" = 13, @"DisjointClear" = 16, @"DisjointSrc" = 17, @"DisjointDst" = 18, @"DisjointOver" = 19, @"DisjointOverReverse" = 20, @"DisjointIn" = 21, @"DisjointInReverse" = 22, @"DisjointOut" = 23, @"DisjointOutReverse" = 24, @"DisjointAtop" = 25, @"DisjointAtopReverse" = 26, @"DisjointXor" = 27, @"ConjointClear" = 32, @"ConjointSrc" = 33, @"ConjointDst" = 34, @"ConjointOver" = 35, @"ConjointOverReverse" = 36, @"ConjointIn" = 37, @"ConjointInReverse" = 38, @"ConjointOut" = 39, @"ConjointOutReverse" = 40, @"ConjointAtop" = 41, @"ConjointAtopReverse" = 42, @"ConjointXor" = 43, @"Multiply" = 48, @"Screen" = 49, @"Overlay" = 50, @"Darken" = 51, @"Lighten" = 52, @"ColorDodge" = 53, @"ColorBurn" = 54, @"HardLight" = 55, @"SoftLight" = 56, @"Difference" = 57, @"Exclusion" = 58, @"HSLHue" = 59, @"HSLSaturation" = 60, @"HSLColor" = 61, @"HSLLuminosity" = 62, }; pub const PolyEdge = extern enum(c_uint) { @"Sharp" = 0, @"Smooth" = 1, }; pub const PolyMode = extern enum(c_uint) { @"Precise" = 0, @"Imprecise" = 1, }; pub const CP = extern enum(c_uint) { @"Repeat" = 1, @"AlphaMap" = 2, @"AlphaXOrigin" = 4, @"AlphaYOrigin" = 8, @"ClipXOrigin" = 16, @"ClipYOrigin" = 32, @"ClipMask" = 64, @"GraphicsExposure" = 128, @"SubwindowMode" = 256, @"PolyEdge" = 512, @"PolyMode" = 1024, @"Dither" = 2048, @"ComponentAlpha" = 4096, }; pub const SubPixel = extern enum(c_uint) { @"Unknown" = 0, @"HorizontalRGB" = 1, @"HorizontalBGR" = 2, @"VerticalRGB" = 3, @"VerticalBGR" = 4, @"None" = 5, }; pub const Repeat = extern enum(c_uint) { @"None" = 0, @"Normal" = 1, @"Pad" = 2, @"Reflect" = 3, }; pub const GLYPH = u32; pub const GLYPHSET = u32; pub const PICTURE = u32; pub const PICTFORMAT = u32; pub const FIXED = i32; /// Opcode for PictFormat. pub const PictFormatOpcode = 0; /// @brief PictFormatError pub const PictFormatError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for Picture. pub const PictureOpcode = 1; /// @brief PictureError pub const PictureError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for PictOp. pub const PictOpOpcode = 2; /// @brief PictOpError pub const PictOpError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for GlyphSet. pub const GlyphSetOpcode = 3; /// @brief GlyphSetError pub const GlyphSetError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// Opcode for Glyph. pub const GlyphOpcode = 4; /// @brief GlyphError pub const GlyphError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, }; /// @brief DIRECTFORMAT pub const DIRECTFORMAT = struct { @"red_shift": u16, @"red_mask": u16, @"green_shift": u16, @"green_mask": u16, @"blue_shift": u16, @"blue_mask": u16, @"alpha_shift": u16, @"alpha_mask": u16, }; /// @brief PICTFORMINFO pub const PICTFORMINFO = struct { @"id": xcb.render.PICTFORMAT, @"type": u8, @"depth": u8, @"pad0": [2]u8, @"direct": xcb.render.DIRECTFORMAT, @"colormap": xcb.COLORMAP, }; /// @brief PICTVISUAL pub const PICTVISUAL = struct { @"visual": xcb.VISUALID, @"format": xcb.render.PICTFORMAT, }; /// @brief PICTDEPTH pub const PICTDEPTH = struct { @"depth": u8, @"pad0": u8, @"num_visuals": u16, @"pad1": [4]u8, @"visuals": []xcb.render.PICTVISUAL, }; /// @brief PICTSCREEN pub const PICTSCREEN = struct { @"num_depths": u32, @"fallback": xcb.render.PICTFORMAT, @"depths": []xcb.render.PICTDEPTH, }; /// @brief INDEXVALUE pub const INDEXVALUE = struct { @"pixel": u32, @"red": u16, @"green": u16, @"blue": u16, @"alpha": u16, }; /// @brief COLOR pub const COLOR = struct { @"red": u16, @"green": u16, @"blue": u16, @"alpha": u16, }; /// @brief POINTFIX pub const POINTFIX = struct { @"x": xcb.render.FIXED, @"y": xcb.render.FIXED, }; /// @brief LINEFIX pub const LINEFIX = struct { @"p1": xcb.render.POINTFIX, @"p2": xcb.render.POINTFIX, }; /// @brief TRIANGLE pub const TRIANGLE = struct { @"p1": xcb.render.POINTFIX, @"p2": xcb.render.POINTFIX, @"p3": xcb.render.POINTFIX, }; /// @brief TRAPEZOID pub const TRAPEZOID = struct { @"top": xcb.render.FIXED, @"bottom": xcb.render.FIXED, @"left": xcb.render.LINEFIX, @"right": xcb.render.LINEFIX, }; /// @brief GLYPHINFO pub const GLYPHINFO = struct { @"width": u16, @"height": u16, @"x": i16, @"y": i16, @"x_off": i16, @"y_off": i16, }; /// @brief QueryVersioncookie pub const QueryVersioncookie = struct { sequence: c_uint, }; /// @brief QueryVersionRequest pub const QueryVersionRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 0, @"length": u16, @"client_major_version": u32, @"client_minor_version": u32, }; /// @brief QueryVersionReply pub const QueryVersionReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"major_version": u32, @"minor_version": u32, @"pad1": [16]u8, }; /// @brief QueryPictFormatscookie pub const QueryPictFormatscookie = struct { sequence: c_uint, }; /// @brief QueryPictFormatsRequest pub const QueryPictFormatsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 1, @"length": u16, }; /// @brief QueryPictFormatsReply pub const QueryPictFormatsReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"num_formats": u32, @"num_screens": u32, @"num_depths": u32, @"num_visuals": u32, @"num_subpixel": u32, @"pad1": [4]u8, @"formats": []xcb.render.PICTFORMINFO, @"screens": []xcb.render.PICTSCREEN, @"subpixels": []u32, }; /// @brief QueryPictIndexValuescookie pub const QueryPictIndexValuescookie = struct { sequence: c_uint, }; /// @brief QueryPictIndexValuesRequest pub const QueryPictIndexValuesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 2, @"length": u16, @"format": xcb.render.PICTFORMAT, }; /// @brief QueryPictIndexValuesReply pub const QueryPictIndexValuesReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"num_values": u32, @"pad1": [20]u8, @"values": []xcb.render.INDEXVALUE, }; /// @brief CreatePictureRequest pub const CreatePictureRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 4, @"length": u16, @"pid": xcb.render.PICTURE, @"drawable": xcb.DRAWABLE, @"format": xcb.render.PICTFORMAT, @"value_mask": u32, }; /// @brief ChangePictureRequest pub const ChangePictureRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 5, @"length": u16, @"picture": xcb.render.PICTURE, @"value_mask": u32, }; /// @brief SetPictureClipRectanglesRequest pub const SetPictureClipRectanglesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 6, @"length": u16, @"picture": xcb.render.PICTURE, @"clip_x_origin": i16, @"clip_y_origin": i16, @"rectangles": []const xcb.RECTANGLE, }; /// @brief FreePictureRequest pub const FreePictureRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 7, @"length": u16, @"picture": xcb.render.PICTURE, }; /// @brief CompositeRequest pub const CompositeRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 8, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"mask": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"src_x": i16, @"src_y": i16, @"mask_x": i16, @"mask_y": i16, @"dst_x": i16, @"dst_y": i16, @"width": u16, @"height": u16, }; /// @brief TrapezoidsRequest pub const TrapezoidsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 10, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"src_x": i16, @"src_y": i16, @"traps": []const xcb.render.TRAPEZOID, }; /// @brief TrianglesRequest pub const TrianglesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 11, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"src_x": i16, @"src_y": i16, @"triangles": []const xcb.render.TRIANGLE, }; /// @brief TriStripRequest pub const TriStripRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 12, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"src_x": i16, @"src_y": i16, @"points": []const xcb.render.POINTFIX, }; /// @brief TriFanRequest pub const TriFanRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 13, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"src_x": i16, @"src_y": i16, @"points": []const xcb.render.POINTFIX, }; /// @brief CreateGlyphSetRequest pub const CreateGlyphSetRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 17, @"length": u16, @"gsid": xcb.render.GLYPHSET, @"format": xcb.render.PICTFORMAT, }; /// @brief ReferenceGlyphSetRequest pub const ReferenceGlyphSetRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 18, @"length": u16, @"gsid": xcb.render.GLYPHSET, @"existing": xcb.render.GLYPHSET, }; /// @brief FreeGlyphSetRequest pub const FreeGlyphSetRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 19, @"length": u16, @"glyphset": xcb.render.GLYPHSET, }; /// @brief AddGlyphsRequest pub const AddGlyphsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 20, @"length": u16, @"glyphset": xcb.render.GLYPHSET, @"glyphs_len": u32, @"glyphids": []const u32, @"glyphs": []const xcb.render.GLYPHINFO, @"data": []const u8, }; /// @brief FreeGlyphsRequest pub const FreeGlyphsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 22, @"length": u16, @"glyphset": xcb.render.GLYPHSET, @"glyphs": []const xcb.render.GLYPH, }; /// @brief CompositeGlyphs8Request pub const CompositeGlyphs8Request = struct { @"major_opcode": u8, @"minor_opcode": u8 = 23, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"glyphset": xcb.render.GLYPHSET, @"src_x": i16, @"src_y": i16, @"glyphcmds": []const u8, }; /// @brief CompositeGlyphs16Request pub const CompositeGlyphs16Request = struct { @"major_opcode": u8, @"minor_opcode": u8 = 24, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"glyphset": xcb.render.GLYPHSET, @"src_x": i16, @"src_y": i16, @"glyphcmds": []const u8, }; /// @brief CompositeGlyphs32Request pub const CompositeGlyphs32Request = struct { @"major_opcode": u8, @"minor_opcode": u8 = 25, @"length": u16, @"op": u8, @"pad0": [3]u8, @"src": xcb.render.PICTURE, @"dst": xcb.render.PICTURE, @"mask_format": xcb.render.PICTFORMAT, @"glyphset": xcb.render.GLYPHSET, @"src_x": i16, @"src_y": i16, @"glyphcmds": []const u8, }; /// @brief FillRectanglesRequest pub const FillRectanglesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 26, @"length": u16, @"op": u8, @"pad0": [3]u8, @"dst": xcb.render.PICTURE, @"color": xcb.render.COLOR, @"rects": []const xcb.RECTANGLE, }; /// @brief CreateCursorRequest pub const CreateCursorRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 27, @"length": u16, @"cid": xcb.CURSOR, @"source": xcb.render.PICTURE, @"x": u16, @"y": u16, }; /// @brief TRANSFORM pub const TRANSFORM = struct { @"matrix11": xcb.render.FIXED, @"matrix12": xcb.render.FIXED, @"matrix13": xcb.render.FIXED, @"matrix21": xcb.render.FIXED, @"matrix22": xcb.render.FIXED, @"matrix23": xcb.render.FIXED, @"matrix31": xcb.render.FIXED, @"matrix32": xcb.render.FIXED, @"matrix33": xcb.render.FIXED, }; /// @brief SetPictureTransformRequest pub const SetPictureTransformRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 28, @"length": u16, @"picture": xcb.render.PICTURE, @"transform": xcb.render.TRANSFORM, }; /// @brief QueryFilterscookie pub const QueryFilterscookie = struct { sequence: c_uint, }; /// @brief QueryFiltersRequest pub const QueryFiltersRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 29, @"length": u16, @"drawable": xcb.DRAWABLE, }; /// @brief QueryFiltersReply pub const QueryFiltersReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"num_aliases": u32, @"num_filters": u32, @"pad1": [16]u8, @"aliases": []u16, @"filters": []xcb.STR, }; /// @brief SetPictureFilterRequest pub const SetPictureFilterRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 30, @"length": u16, @"picture": xcb.render.PICTURE, @"filter_len": u16, @"pad0": [2]u8, @"filter": []const u8, @"values": []const xcb.render.FIXED, }; /// @brief ANIMCURSORELT pub const ANIMCURSORELT = struct { @"cursor": xcb.CURSOR, @"delay": u32, }; /// @brief CreateAnimCursorRequest pub const CreateAnimCursorRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 31, @"length": u16, @"cid": xcb.CURSOR, @"cursors": []const xcb.render.ANIMCURSORELT, }; /// @brief SPANFIX pub const SPANFIX = struct { @"l": xcb.render.FIXED, @"r": xcb.render.FIXED, @"y": xcb.render.FIXED, }; /// @brief TRAP pub const TRAP = struct { @"top": xcb.render.SPANFIX, @"bot": xcb.render.SPANFIX, }; /// @brief AddTrapsRequest pub const AddTrapsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 32, @"length": u16, @"picture": xcb.render.PICTURE, @"x_off": i16, @"y_off": i16, @"traps": []const xcb.render.TRAP, }; /// @brief CreateSolidFillRequest pub const CreateSolidFillRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 33, @"length": u16, @"picture": xcb.render.PICTURE, @"color": xcb.render.COLOR, }; /// @brief CreateLinearGradientRequest pub const CreateLinearGradientRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 34, @"length": u16, @"picture": xcb.render.PICTURE, @"p1": xcb.render.POINTFIX, @"p2": xcb.render.POINTFIX, @"num_stops": u32, @"stops": []const xcb.render.FIXED, @"colors": []const xcb.render.COLOR, }; /// @brief CreateRadialGradientRequest pub const CreateRadialGradientRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 35, @"length": u16, @"picture": xcb.render.PICTURE, @"inner": xcb.render.POINTFIX, @"outer": xcb.render.POINTFIX, @"inner_radius": xcb.render.FIXED, @"outer_radius": xcb.render.FIXED, @"num_stops": u32, @"stops": []const xcb.render.FIXED, @"colors": []const xcb.render.COLOR, }; /// @brief CreateConicalGradientRequest pub const CreateConicalGradientRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 36, @"length": u16, @"picture": xcb.render.PICTURE, @"center": xcb.render.POINTFIX, @"angle": xcb.render.FIXED, @"num_stops": u32, @"stops": []const xcb.render.FIXED, @"colors": []const xcb.render.COLOR, }; test "" { @import("std").testing.refAllDecls(@This()); }
src/auto/render.zig
const os = @import("root").os; const paging_common = @import("../paging.zig"); const std = @import("std"); pub const page_sizes = [_]u64 { 0x1000, // 4K << 0 0x4000, // 16K << 0 0x10000, // 32K << 0 0x200000, // 4K << 9 0x2000000, // 16K << 11 0x10000000, // 32K << 12 0x40000000, // 4K << 18 0x1000000000, // 16K << 22 0x8000000000, // 4K << 27 0x10000000000, // 32K << 24 }; const mair_index = u3; fn MAIRContext() type { const mair_encoding = u8; const mair_value = u64; const MAIR = os.platform.msr(mair_value, "MAIR_EL1"); // Current limitation: Outer = Inner and only non-transient // Device nGnRnE const device_uncacheable_encoding = 0b0000_00_00; // Device GRE const device_write_combining_encoding = 0b0000_11_00; // Normal memory, inner and outer non-cacheable const memory_uncacheable_encoding = 0b0100_0100; // Normal memory inner and outer writethrough, non-transient const memory_writethrough_encoding = 0b1011_1011; // Normal memory, inner and outer write-back, non-transient const memory_write_back_encoding = 0b1111_1111; return struct { // The value of the MAIR itself value: mair_value, // Cache the indices for each memory type device_uncacheable: ?mair_index, device_write_combining: ?mair_index, memory_uncacheable: ?mair_index, memory_writethrough: ?mair_index, memory_write_back: ?mair_index, pub fn init_from_mair_value(value: mair_value) @This() { return .{ .value = value, .device_uncacheable = find_mair_index(value, device_uncacheable_encoding), .device_write_combining = find_mair_index(value, device_write_combining_encoding), .memory_uncacheable = find_mair_index(value, memory_uncacheable_encoding), .memory_writethrough = find_mair_index(value, memory_writethrough_encoding), .memory_write_back = find_mair_index(value, memory_write_back_encoding), }; } fn encoding_at_index(value: mair_value, idx: mair_index) mair_encoding { return @truncate(u8, value >> (@as(u6, idx) * 8)); } fn memory_type_at_index(self: *const @This(), idx: mair_index) MemoryType { const val = encoding_at_index(self.value, idx); return switch(val) { device_uncacheable_encoding => .DeviceUncacheable, device_write_combining_encoding => .DeviceWriteCombining, memory_uncacheable_encoding => .MemoryUncacheable, memory_writethrough_encoding => .MemoryWritethrough, memory_write_back_encoding => .MemoryWriteBack, else => { os.log("Index: {}, value = 0x{}\n", .{idx, val}); @panic("Unknown MAIR value!"); }, }; } fn find_mair_index(pat: mair_value, enc: mair_encoding) ?mair_index { var idx: mair_index = 0; while(true): (idx += 1) { if(encoding_at_index(pat, idx) == enc) return idx; if(idx == 7) return null; } } pub fn find_memtype(self: *const @This(), memtype: MemoryType) ?mair_index { var idx: mair_index = 0; while(true): (idx += 1) { if(self.memory_type_at_index(idx) == memtype) return idx; if(idx == 7) return null; } } pub fn get_active() @This() { return init_from_mair_value(MAIR.read()); } pub fn make_default() @This() { const default = comptime init_from_mair_value(0 | memory_write_back_encoding << 0 | device_write_combining_encoding << 8 | memory_writethrough_encoding << 16 | device_uncacheable_encoding << 24 | memory_uncacheable_encoding << 32 ); return default; } }; } const SCTLR = os.platform.msr(u64, "SCTLR_EL1"); const TCR = os.platform.msr(u64, "TCR_EL1"); const ID_AA64MMFR0 = os.platform.msr(u64, "ID_AA64MMFR0_EL1"); const Half = enum { Upper, Lower, }; fn half(vaddr: u64) Half { if(std.math.maxInt(u64)/2 < vaddr) return .Upper; return .Lower; } const PageSizeContext = struct { extrabits: u2, pub fn get_active(h: Half, tcr: u64) @This() { const val = switch(h) { .Upper => @truncate(u5, tcr >> 16), .Lower => @truncate(u5, tcr), }; return switch(val) { 0 => .{.extrabits = 2}, 8 => .{.extrabits = 1}, 16 => .{.extrabits = 0}, else => @panic("Unknown paging mode!"), }; } pub fn offset_bits(self: *const @This()) u64 { return switch(self.extrabits) { 0 => 16, 1 => 8, 2 => 0, 3 => @panic("3 extrabits??"), }; } pub fn granule(self: *const @This(), h: Half) u64 { switch(self.extrabits) { 0 => if(h == .Upper) return 0b10 else return 0b00, 1 => if(h == .Upper) return 0b01 else return 0b10, 2 => if(h == .Upper) return 0b11 else return 0b01, 3 => @panic("3 extrabits??"), } } pub fn make_default() @This() { const id = ID_AA64MMFR0.read(); if(((id >> 28) & 0x0F) == 0b0000) return .{.extrabits = 0}; if(((id >> 20) & 0x0F) == 0b0001) return .{.extrabits = 1}; if(((id >> 24) & 0x0F) == 0b0000) return .{.extrabits = 2}; @panic("Cannot find valid page size"); } pub fn basebits(self: *const @This()) u6 { return 9 + @as(u6, self.extrabits) * 2; } pub fn firstbits(self: *const @This()) u6 { // log2(@sizeOf(PTE)) = log2(8) = 3 return self.basebits() + 3; } pub fn page_size(self: *const @This(), level: u6) usize { return @as(usize, 1) << self.firstbits() + self.basebits() * level; } }; const ttbr_value = u64; const ttbr0 = os.platform.msr(ttbr_value, "TTBR0_EL1"); const ttbr1 = os.platform.msr(ttbr_value, "TTBR1_EL1"); const level_type = u3; pub fn make_page_table(page_size: usize) !u64 { const pt = try os.memory.pmm.alloc_phys(page_size); const pt_bytes = os.platform.phys_slice(u8).init(pt, page_size); @memset(pt_bytes.to_slice_writeback().ptr, 0x00, page_size); return pt; } pub const PagingContext = struct { mair: MAIRContext(), br0: u64, br1: u64, upper: PageSizeContext, lower: PageSizeContext, wb_virt_base: u64 = undefined, wc_virt_base: u64 = undefined, uc_virt_base: u64 = undefined, max_phys: u64 = undefined, pub fn apply(self: *@This()) void { var aa64mmfr0 = ID_AA64MMFR0.read(); aa64mmfr0 &= 0x0F; if(aa64mmfr0 > 5) aa64mmfr0 = 5; // Make sure MMU is enabled const sctlr: u64 = 0x100D; const tcr: u64 = 0 | self.lower.offset_bits() // T0SZ | self.upper.offset_bits() << 16 // T1SZ | (1 << 8) // TTBR0 Inner WB RW-Allocate | (1 << 10) // TTBR0 Outer WB RW-Allocate | (1 << 24) // TTBR1 Inner WB RW-Allocate | (1 << 26) // TTBR1 Outer WB RW-Allocate | (2 << 12) // TTBR0 Inner shareable | (2 << 28) // TTBR1 Inner shareable | (aa64mmfr0 << 32) // intermediate address size | (self.lower.granule(.Lower) << 14) // TTBR0 granule | (self.upper.granule(.Upper) << 30) // TTBR1 granule | (1 << 56) // Fault on TTBR1 access from EL0 | (0 << 55) // Don't fault on TTBR0 access from EL0 ; asm volatile( // First, make sure we're not // doing this on a page boundary \\ .balign 0x20 \\apply_paging: \\ MSR TCR_EL1, %[tcr] \\ MSR SCTLR_EL1, %[sctlr] \\ MSR TTBR0_EL1, %[ttbr0] \\ MSR TTBR1_EL1, %[ttbr1] \\ MSR MAIR_EL1, %[mair] \\ TLBI VMALLE1 \\ DSB ISH \\ ISB : : [tcr] "r" (tcr) , [sctlr] "r" (sctlr) , [ttbr0] "r" (self.br0) , [ttbr1] "r" (self.br1) , [mair] "r" (self.mair.value) ); } pub fn read_current() void { const tcr = TCR.read(); const curr = &os.memory.paging.kernel_context; curr.mair = MAIRContext().get_active(); curr.br0 = ttbr0.read(); curr.br1 = ttbr1.read(); curr.upper = PageSizeContext.get_active(.Upper, tcr); curr.lower = PageSizeContext.get_active(.Lower, tcr); } pub fn make_default() !@This() { const pszc = PageSizeContext.make_default(); const psz = pszc.page_size(0); // 32TB ought to be enough for anyone... const max_phys = 0x200000000000; const curr_base = os.memory.paging.kernel_context.wb_virt_base; return @This(){ .mair = MAIRContext().make_default(), .br0 = try make_page_table(psz), .br1 = try make_page_table(psz), .upper = pszc, .lower = pszc, .wb_virt_base = curr_base, .wc_virt_base = curr_base + max_phys, .uc_virt_base = curr_base + max_phys * 2, .max_phys = max_phys, }; } pub fn can_map_at_level(self: *const @This(), level: level_type) bool { return level < @as(level_type, 2); } pub fn check_phys(self: *const @This(), phys: u64) void { if(comptime(std.debug.runtime_safety)) { if(phys > self.max_phys) @panic("Physical address out of range"); } } pub fn phys_to_write_back_virt(self: *const @This(), phys: u64) u64 { self.check_phys(phys); return self.wb_virt_base + phys; } pub fn phys_to_write_combining_virt(self: *const @This(), phys: u64) u64 { self.check_phys(phys); return self.wc_virt_base + phys; } pub fn phys_to_uncached_virt(self: *const @This(), phys: u64) u64 { self.check_phys(phys); return self.uc_virt_base + phys; } pub fn make_heap_base(self: *const @This()) u64 { // Just after last physical memory mapping return self.uc_virt_base + self.max_phys; } pub fn root_table(self: *@This(), virt: u64) TablePTE { const h = half(virt); return .{ .phys = if(h == .Lower) self.br0 else self.br1, .curr_level = 4, .context = self, .perms = os.memory.paging.rwx(), .underlying = null, .pszc = if(h == .Lower) self.lower else self.upper, }; } fn decode(self: *@This(), enc: *EncodedPTE, level: level_type, pszc: PageSizeContext) PTE { var pte = PTEEncoding{.raw = enc.*}; if(!pte.present.read()) return .Empty; if(pte.walk.read() and level != 0) return .{.Table = self.decode_table(enc, level, pszc)}; return .{.Mapping = self.decode_mapping(enc, level, pszc)}; } fn decode_mapping(self: *@This(), enc: *EncodedPTE, level: level_type, pszc: PageSizeContext) MappingPTE { const map = MappingEncoding{.raw = enc.*}; const memtype: MemoryType = self.mair.memory_type_at_index(map.attr_index.read()); return .{ .context = self, .phys = enc.* & phys_bitmask, .level = level, .memtype = memtype, .underlying = @ptrCast(*MappingEncoding, enc), .perms = .{ .writable = !map.no_write.read(), .executable = !map.no_execute.read(), .userspace = !map.no_user.read(), }, .pszc = pszc, }; } fn decode_table(self: *@This(), enc: *EncodedPTE, level: level_type, pszc: PageSizeContext) TablePTE { const tbl = TableEncoding{.raw = enc.*}; return .{ .context = self, .phys = enc.* & phys_bitmask, .curr_level = level, .underlying = @ptrCast(*TableEncoding, enc), .perms = .{ .writable = !tbl.no_write.read(), .executable = !tbl.no_execute.read(), .userspace = !tbl.no_user.read(), }, .pszc = pszc, }; } pub fn encode_empty(self: *const @This(), level: level_type) EncodedPTE { return 0; } pub fn encode_table(self: *const @This(), pte: TablePTE) !EncodedPTE { var tbl = TableEncoding{.raw = pte.phys}; tbl.present.write(true); tbl.walk.write(true); tbl.nonsecure.write(false); tbl.no_write.write(!pte.perms.writable); tbl.no_execute.write(!pte.perms.executable); tbl.no_user.write(!pte.perms.userspace); return tbl.raw; } pub fn encode_mapping(self: *const @This(), pte: MappingPTE) !EncodedPTE { var map = MappingEncoding{.raw = pte.phys}; map.present.write(true); map.access.write(true); map.nonsecure.write(false); map.walk.write(pte.level == 0); map.no_write.write(!pte.perms.writable); map.no_execute.write(!pte.perms.executable); map.no_user.write(!pte.perms.userspace); map.shareability.write(2); const attr_idx = self.mair.find_memtype(pte.memtype.?) orelse @panic("Could not find MAIR index"); map.attr_index.write(attr_idx); return map.raw; } pub fn domain(self: *const @This(), level: level_type, virtaddr: u64) os.platform.virt_slice { return .{ .ptr = virtaddr & ~(self.page_size(level, virtaddr) - 1), .len = self.page_size(level, virtaddr), }; } pub fn invalidate(self: *const @This(), virt: u64) void { const h = half(virt); const basebits = if(h == .Lower) self.lower.basebits() else self.upper.basebits(); asm volatile( \\TLBI VAE1, %[virt] : : [virt] "r" (virt >> basebits) : "memory" ); } pub fn page_size(self: *const @This(), level: level_type, virtaddr: u64) u64 { return self.half_page_size(level, half(virtaddr)); } pub fn half_page_size(self: *const @This(), level: level_type, h: Half) u64 { if(h == .Lower) return self.lower.page_size(level); return self.upper.page_size(level); } }; pub const MemoryType = enum { DeviceUncacheable, DeviceWriteCombining, MemoryUncacheable, MemoryWritethrough, MemoryWriteBack, }; const phys_bitmask = 0x0000FFFFFFFFF000; const bf = os.lib.bitfields; const PTEEncoding = extern union { raw: u64, present: bf.boolean(u64, 0), walk: bf.boolean(u64, 1), }; const MappingEncoding = extern union { raw: u64, present: bf.boolean(u64, 0), walk: bf.boolean(u64, 1), attr_index: bf.bitfield(u64, 2, 3), nonsecure: bf.boolean(u64, 5), no_user: bf.boolean(u64, 6), no_write: bf.boolean(u64, 7), shareability: bf.bitfield(u64, 8, 2), access: bf.boolean(u64, 10), no_execute: bf.boolean(u64, 54), }; const TableEncoding = extern union { raw: u64, present: bf.boolean(u64, 0), walk: bf.boolean(u64, 1), no_execute: bf.boolean(u64, 60), no_user: bf.boolean(u64, 61), no_write: bf.boolean(u64, 62), nonsecure: bf.boolean(u64, 63), }; fn virt_index_at_level(vaddr: u64, level: u6) u9 { const shamt = 12 + level * 9; return @truncate(u9, (vaddr >> shamt)); } const MappingPTE = struct { phys: u64, level: u3, memtype: ?MemoryType, context: *PagingContext, perms: os.memory.paging.Perms, underlying: *MappingEncoding, pszc: PageSizeContext, pub fn mapped_bytes(self: *const @This()) os.platform.PhysBytes { return .{ .ptr = self.phys, .len = self.context.page_size(self.level, self.context.phys_to_write_back_virt(self.phys)), }; } pub fn get_type(self: *const @This()) ?MemoryType { return self.memtype; } }; const EncodedPTE = u64; const TablePTE = struct { phys: u64, curr_level: level_type, context: *PagingContext, perms: os.memory.paging.Perms, underlying: ?*TableEncoding, pszc: PageSizeContext, pub fn get_child_tables(self: *const @This()) []EncodedPTE { return os.platform.phys_slice(EncodedPTE).init(self.phys, 512).to_slice_writeback(); } pub fn skip_to(self: *const @This(), virt: u64) []EncodedPTE { return self.get_child_tables()[virt_index_at_level(virt, self.curr_level - 1)..]; } pub fn child_domain(self: *const @This(), virt: u64) os.platform.virt_slice { return self.context.domain(self.curr_level - 1, virt); } pub fn decode_child(self: *const @This(), pte: *EncodedPTE) PTE { return self.context.decode(pte, self.curr_level - 1, self.pszc); } pub fn level(self: *const @This()) level_type { return self.curr_level; } pub fn add_perms(self: *const @This(), perms: os.memory.paging.Perms) void { if(perms.executable) self.underlying.?.no_execute.write(false); if(perms.writable) self.underlying.?.no_write.write(false); if(perms.userspace) self.underlying.?.no_user.write(false); } pub fn make_child_table(self: *const @This(), enc: *u64, perms: os.memory.paging.Perms) !TablePTE { const psz = self.pszc.page_size(0); const pmem = try make_page_table(psz); errdefer os.memory.pmm.free_phys(pmem, psz); var result: TablePTE = .{ .phys = pmem, .context = self.context, .curr_level = self.curr_level - 1, .perms = perms, .underlying = @ptrCast(*TableEncoding, enc), .pszc = self.pszc, }; enc.* = try self.context.encode_table(result); return result; } pub fn make_child_mapping( self: *const @This(), enc: *u64, phys: ?u64, perms: os.memory.paging.Perms, memtype: MemoryType, ) !MappingPTE { const page_size = self.pszc.page_size(self.level() - 1); const pmem = phys orelse try os.memory.pmm.alloc_phys(page_size); errdefer if(phys == null) os.memory.pmm.free_phys(pmem, page_size); var result: MappingPTE = .{ .level = self.level() - 1, .memtype = memtype, .context = self.context, .perms = perms, .underlying = @ptrCast(*MappingEncoding, enc), .phys = pmem, .pszc = self.pszc, }; enc.* = try self.context.encode_mapping(result); return result; } }; const EmptyPte = struct { }; pub const PTE = union(paging_common.PTEType) { Mapping: MappingPTE, Table: TablePTE, Empty: EmptyPte, };
src/platform/aarch64/paging.zig
const std = @import("std"); const crypto = std.crypto; const math = std.math; const mem = std.mem; const rand = std.rand; const testing = std.testing; const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const min_inc: u63 = 33; const max_inc: u63 = 333; const base: u6 = 62; const max_seq: u63 = math.pow(u63, base, seq_len); const pre_len: usize = 12; const seq_len: usize = 10; const nuid_len = pre_len + seq_len; var global_nuid: ?Nuid = null; var global_nuid_lock = std.Thread.Mutex{}; pub fn next() [nuid_len]u8 { const lock = global_nuid_lock.acquire(); defer lock.release(); if (global_nuid == null) global_nuid = Nuid.init(); return global_nuid.?.next(); } pub const Nuid = struct { const Self = @This(); rng: rand.Gimli, pre: [pre_len]u8, seq: u63, inc: u63, pub fn init() Self { var seed: [rand.Gimli.secret_seed_length]u8 = undefined; crypto.random.bytes(&seed); var rng = rand.Gimli.init(seed); var n = Self{ .rng = rng, .seq = rng.random.uintLessThan(u63, max_seq), .inc = min_inc + rng.random.uintLessThan(u63, max_inc - min_inc), .pre = [_]u8{0} ** pre_len, }; n.randomizePrefix(); return n; } pub fn next(self: *Self) [nuid_len]u8 { self.seq += self.inc; if (self.seq >= max_seq) { self.randomizePrefix(); self.resetSequential(); } var seq = self.seq; var bs: [nuid_len]u8 = undefined; mem.copy(u8, &bs, &self.pre); var i = bs.len; while (i > pre_len) : (seq /= base) { i -= 1; bs[i] = chars[seq % base]; } return bs; } pub fn randomizePrefix(self: *Self) void { var cb: [pre_len]u8 = undefined; crypto.random.bytes(&cb); var i: usize = 0; while (i < pre_len) : (i += 1) { self.pre[i] = chars[cb[i] % base]; } } fn resetSequential(self: *Self) void { self.seq = self.rng.random.uintLessThan(u63, max_seq); self.inc = min_inc + self.rng.random.uintLessThan(u63, max_inc - min_inc); } }; test { testing.refAllDecls(@This()); testing.refAllDecls(Nuid); } test "chars" { try testing.expect(chars.len == base); } test "global next" { _ = next(); // this shouldn't crash } test "NUID rollover" { if (global_nuid == null) global_nuid = Nuid.init(); global_nuid.?.seq = max_seq; var old_pre = global_nuid.?.pre; _ = next(); try testing.expect(!mem.eql(u8, &global_nuid.?.pre, &old_pre)); } test "proper prefix" { var min: u8 = 255; var max: u8 = 0; for (chars) |c| { if (c < min) { min = c; } else if (c > max) { max = c; } } var total: usize = 100_000; while (total > 0) : (total -= 1) { var nuid = Nuid.init(); for (nuid.pre) |c| { try testing.expect(c >= min and c <= max); } } } test "uniqueness" { const n: usize = 10_000_000; var all: [][nuid_len]u8 = try testing.allocator.alloc([nuid_len]u8, n); defer testing.allocator.free(all); var s = std.StringHashMap(void).init(testing.allocator); defer s.deinit(); var i: usize = 0; while (i < n) : (i += 1) { all[i] = next(); try testing.expect(!s.contains(&all[i])); try s.put(&all[i], undefined); } } test "bench Nuid speed" { const time = std.time; var nuid = Nuid.init(); const n: usize = 100_000_000; var start = time.nanoTimestamp(); var i: usize = 0; while (i < n) : (i += 1) { _ = nuid.next(); } var end = time.nanoTimestamp(); var diff = @intCast(u127, end - start); var seconds = diff / math.pow(u127, 10, 9); var nanos = diff % math.pow(u127, 10, 9); std.debug.print("Generated {d} NUIDs in {d}.{:0.9}s\n", .{ i, seconds, nanos }); std.debug.print("That's {d}ns per NUID\n", .{diff / n}); } test "bench global Nuid speed" { const time = std.time; const n: usize = 100_000_000; var start = time.nanoTimestamp(); var i: usize = 0; while (i < n) : (i += 1) { _ = next(); } var end = time.nanoTimestamp(); var diff = @intCast(u127, end - start); var seconds = diff / math.pow(u127, 10, 9); var nanos = diff % math.pow(u127, 10, 9); std.debug.print("Global Nuid generated {d} NUIDs in {d}.{:0.9}s\n", .{ i, seconds, nanos }); std.debug.print("That's {d}ns per NUID (for the global Nuid)\n", .{diff / n}); }
src/nuid.zig
const std = @import("std"); const array = @import("array.zig"); const Array = array.Array; const DType = array.DType; const reference_counter = @import("reference_counter.zig"); const ReferenceCounter = reference_counter.ReferenceCounter; pub const NO_FLAGS = 0; pub const REQUIRES_GRAD = 1; pub const IS_BRANCH = 2; const ForwardError = error{OutOfMemory}; const BackwardError = error{OutOfMemory}; const ForwardFn = fn (alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array; const BackwardFn = fn (alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void; const DeallocFn = fn (alc: *std.mem.Allocator, extra_args_ptr: u64) void; const GradientRecord = struct { inputs: []Tensor, extra_args_ptr: u64, output: Tensor, grad_output: ?Array, backward_fn: BackwardFn, dealloc_fn: ?DeallocFn, alc: *std.mem.Allocator, const Self = @This(); pub fn alloc(alc: *std.mem.Allocator, inputs: []Tensor, extra_args_ptr: u64, output: Tensor, backward_fn: BackwardFn, dealloc_fn: ?DeallocFn) !Self { var i = try alc.alloc(Tensor, inputs.len); errdefer alc.free(i); std.mem.copy(Tensor, i, inputs); for (i) |*t| { t.retain(); } // we don't keep a reference to the output tensor, since the output tensor will // own this GradientRecord return Self{ .inputs = i, .extra_args_ptr = extra_args_ptr, .output = output, .grad_output = null, .alc = alc, .backward_fn = backward_fn, .dealloc_fn = dealloc_fn }; } pub fn dealloc(self: *Self) void { for (self.inputs) |*t| { t.release(); } if (self.grad_output != null) { @panic("grad_output present on GradientRecord"); } self.alc.free(self.inputs); if (self.dealloc_fn) |dealloc_fn| { dealloc_fn(self.alc, self.extra_args_ptr); } } pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { if (fmt.len != 0) { @compileError("Unknown format character: '" ++ f ++ "'"); } try std.fmt.format(writer, "GradientRecord(num_inputs={}, has_grad_output={})", .{ self.inputs.len, self.grad_output != null }); } }; fn has_flag(flags: u64, flag: u64) bool { return flags & flag == flag; } pub const Tensor = struct { data: Array, grad: ?Array, requires_grad: bool, is_leaf: bool, grad_record: ?*GradientRecord, ref_counter: ?*ReferenceCounter, alc: ?*std.mem.Allocator, const Self = @This(); fn alloc(alc: *std.mem.Allocator, data: Array, grad: ?Array, flags: u64) !Self { var requires_grad = has_flag(flags, REQUIRES_GRAD); var is_leaf = !has_flag(flags, IS_BRANCH); if (requires_grad and !(data.dtype == array.DType.f32 or data.dtype == array.DType.f64)) { @panic("grad requires floating point dtype"); } var grad_array: ?Array = grad; if (is_leaf and requires_grad and grad == null) { grad_array = try array.zerosLikeAlloc(alc, data); } var ref_counter = try alc.create(ReferenceCounter); ref_counter.* = ReferenceCounter.init(); return Self{ .data = data, .grad = grad_array, .requires_grad = requires_grad, .is_leaf = is_leaf, .grad_record = null, .ref_counter = ref_counter, .alc = alc }; } pub fn allocWithValue(comptime T: type, alc: *std.mem.Allocator, shape: []const u64, value: T, flags: u64) !Self { var data = try Array.allocWithValue(T, alc, shape, value); return Self.alloc(alc, data, null, flags); } pub fn allocWithString(comptime T: type, alc: *std.mem.Allocator, str: []const u8, flags: u64) !Self { var data = try Array.allocWithString(T, alc, str); return Self.alloc(alc, data, null, flags); } pub fn allocWithRange(comptime T: type, alc: *std.mem.Allocator, shape: []const u64, start: T, step: T, flags: u64) !Self { var data = try Array.allocWithRange(T, alc, shape, start, step); return Self.alloc(alc, data, null, flags); } pub fn allocWithData(alc: *std.mem.Allocator, data: Array, flags: u64) !Self { data.retain(); return Self.alloc(alc, data, null, flags); } pub fn allocWithDataAndGrad(alc: *std.mem.Allocator, data: Array, grad: Array, flags: u64) !Self { data.retain(); grad.retain(); if (!has_flag(flags, REQUIRES_GRAD)) { @panic("must require grad if grad is specified"); } array.assertShapesAreTheSame(data, grad); array.assertTypesAreTheSame(data, grad); return Self.alloc(alc, data, grad, flags); } pub fn allocWithBuffers(comptime T: type, alc: *std.mem.Allocator, shape: []const u64, data_buf: []T, grad_buf: []T) !Self { var data = Array.fromBuffer(T, shape, data_buf); var grad = Array.fromBuffer(T, shape, grad_buf); return Self.alloc(alc, data, grad, REQUIRES_GRAD); } pub fn fromBuffer(comptime T: type, shape: []const u64, data_buf: []T) Self { var data = Array.fromBuffer(T, shape, data_buf); return Self{ .data = data, .grad = null, .requires_grad = false, .is_leaf = true, .grad_record = null, .ref_counter = null, .alc = null }; } pub fn flatFromBuffer(comptime T: type, data_buf: []T) Self { return Self.fromBuffer(T, &[_]u64{data_buf.len}, data_buf); } pub fn scalarFromBuffer(comptime T: type, data_buf: []T) Self { return Self.fromBuffer(T, &[_]u64{}, data_buf); } pub fn getDType(self: Self) DType { return self.data.dtype; } pub fn narrowView(self: Self, pos: []const u64, shape: []const u64) Self { var grad = self.grad; if (grad != null) { grad = grad.?.narrowView(pos, shape); } return Self{ .data = self.data.narrowView(pos, shape), .grad = grad, .requires_grad = self.requires_grad, .is_leaf = self.is_leaf, .grad_record = self.grad_record, .ref_counter = self.ref_counter, .alc = self.alc }; } pub fn reshapeView(self: Self, shape: []const u64) Self { var grad = self.grad; if (grad != null) { grad = grad.?.reshapeView(shape); } return Self{ .data = self.data.reshapeView(shape), .grad = grad, .requires_grad = self.requires_grad, .is_leaf = self.is_leaf, .grad_record = self.grad_record, .ref_counter = self.ref_counter, .alc = self.alc }; } pub fn retain(self: Self) void { if (self.ref_counter) |ref_counter| { ref_counter.increment(); } } pub fn release(self: Self) void { if (self.ref_counter) |ref_counter| { if (ref_counter.decrement()) { self.data.release(); if (self.grad) |g| { g.release(); } var alc = self.alc.?; alc.destroy(ref_counter); // if the tensor has a grad record, it's owned by the tensor if (self.grad_record) |gr| { gr.dealloc(); alc.destroy(gr); } } } } pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { if (fmt.len != 0) { @compileError("Unknown format character: '" ++ f ++ "'"); } try std.fmt.format(writer, "Tensor(is_leaf={}, requires_grad={}, data={}, grad={}, grad_record={})", .{ self.is_leaf, self.requires_grad, self.data, self.grad, self.grad_record }); } }; test "format_tensor" { var t = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3 }, 1.0, REQUIRES_GRAD); defer t.release(); var t2 = try timesAlloc(std.testing.allocator, t, t); defer t2.release(); std.debug.print("{}\n", .{t2}); } pub fn zerosAlloc(alc: *std.mem.Allocator, dtype: DType, shape: []const u64, flags: u64) !Tensor { var data = try array.zerosAlloc(alc, dtype, shape); var t = try Tensor.allocWithData(alc, data, flags); data.release(); return t; } pub fn zerosLikeAlloc(alc: *std.mem.Allocator, t: Tensor, flags: u64) !Tensor { return zerosAlloc(alc, t.getDType(), t.data.getShape(), flags); } pub fn onesAlloc(alc: *std.mem.Allocator, dtype: DType, shape: []const u64, flags: u64) !Tensor { var data = try array.onesAlloc(alc, dtype, shape); var t = try Tensor.allocWithData(alc, data, flags); data.release(); return t; } pub fn onesLikeAlloc(alc: *std.mem.Allocator, t: Tensor, flags: u64) !Tensor { return onesAlloc(alc, t.getDType(), t.data.getShape(), flags); } pub fn detachAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return try Tensor.allocWithData(alc, x.data, NO_FLAGS); } pub fn scalarAlloc(alc: *std.mem.Allocator, dtype: DType, value: f64) !Tensor { var data = try array.scalarAlloc(alc, dtype, value); var output = try Tensor.allocWithData(alc, data, 0); data.release(); return output; } pub fn plusAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, plusForwardAlloc, plusBackwardAlloc, null); } pub fn plusForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.plusAlloc(alc, inputs[0], inputs[1]); } pub fn plusBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { for (grad_inputs_out) |maybe_grad_input| { if (maybe_grad_input) |grad_input| { array.bcastsum(grad_output, grad_input); } } } pub fn uplusAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { x.retain(); return x; } pub fn minusAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, minusForwardAlloc, minusBackwardAlloc, null); } pub fn minusForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.minusAlloc(alc, inputs[0], inputs[1]); } pub fn minusBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { for (grad_inputs_out) |maybe_grad_input, i| { if (maybe_grad_input) |grad_input| { array.bcastsum(grad_output, grad_input); if (i == 1) { var negative_one = try array.scalarAlloc(alc, grad_input.dtype, -1); defer negative_one.release(); array.times(grad_input, negative_one, grad_input); } } } } pub fn logAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, 0, logForwardAlloc, logBackwardAlloc, null); } pub fn logForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.logAlloc(alc, inputs[0]); } pub fn logBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (grad_inputs_out[0]) |grad| { var x = inputs[0]; var grad_input = try array.expr(alc, "g ./ x", .{ .x = x, .g = grad_output }); defer grad_input.release(); array.copy(grad_input, grad); } } test "log_gradcheck" { var a = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 3, 4 }, 1.0, 1.0, REQUIRES_GRAD); defer a.release(); var inputs = [_]Tensor{a}; std.testing.expect(try gradCheck(f64, std.testing.allocator, logForwardAlloc, logBackwardAlloc, &inputs, 0)); } pub fn log2Alloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, 0, log2ForwardAlloc, log2BackwardAlloc, null); } pub fn log2ForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.log2Alloc(alc, inputs[0]); } pub fn log2BackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (grad_inputs_out[0]) |grad| { var x = inputs[0]; var grad_input = try array.expr(alc, "1.0 ./ (x .* log(2.0)) .* g", .{ .x = x, .g = grad_output }); defer grad_input.release(); array.copy(grad_input, grad); } } test "log2_gradcheck" { var a = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 3, 4 }, 1.0, 1.0, REQUIRES_GRAD); defer a.release(); var inputs = [_]Tensor{a}; std.testing.expect(try gradCheck(f64, std.testing.allocator, log2ForwardAlloc, log2BackwardAlloc, &inputs, 0)); } pub fn expAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, 0, expForwardAlloc, expBackwardAlloc, null); } pub fn expForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.expAlloc(alc, inputs[0]); } pub fn expBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (grad_inputs_out[0]) |grad| { var x = inputs[0]; var grad_input = try array.expr(alc, "exp(x) .* g", .{ .x = x, .g = grad_output }); defer grad_input.release(); array.copy(grad_input, grad); } } test "exp_gradcheck" { var a = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 3, 4 }, 1.0, 1.0, REQUIRES_GRAD); defer a.release(); var inputs = [_]Tensor{a}; std.testing.expect(try gradCheck(f64, std.testing.allocator, expForwardAlloc, expBackwardAlloc, &inputs, 0)); } pub fn uminusAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, 0, uminusForwardAlloc, uminusBackwardAlloc, null); } pub fn uminusForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.uminusAlloc(alc, inputs[0]); } pub fn uminusBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (grad_inputs_out[0]) |grad_input| { array.copy(grad_output, grad_input); var negative_one = try array.scalarAlloc(alc, grad_input.dtype, -1); defer negative_one.release(); array.times(grad_input, negative_one, grad_input); } } pub fn timesAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, timesForwardAlloc, timesBackwardAlloc, null); } pub fn timesForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.timesAlloc(alc, inputs[0], inputs[1]); } pub fn timesBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var x = inputs[0]; var y = inputs[1]; var x_grad_to_sum = try array.timesAlloc(alc, grad_output, y); defer x_grad_to_sum.release(); if (grad_inputs_out[0]) |x_grad| { array.bcastsum(x_grad_to_sum, x_grad); } var y_grad_to_sum = try array.timesAlloc(alc, grad_output, x); defer y_grad_to_sum.release(); if (grad_inputs_out[1]) |y_grad| { array.bcastsum(y_grad_to_sum, y_grad); } } pub fn mtimesAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, mtimesForwardAlloc, mtimesBackwardAlloc, null); } pub fn mtimesForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.mtimesAlloc(alc, inputs[0], inputs[1]); } pub fn mtimesBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var x = inputs[0]; var y = inputs[1]; if (grad_inputs_out[0]) |x_grad| { var x_grad_to_copy = try array.expr(alc, "g * y'", .{ .y = y, .g = grad_output }); defer x_grad_to_copy.release(); array.copy(x_grad_to_copy, x_grad); } if (grad_inputs_out[1]) |y_grad| { var y_grad_to_copy = try array.expr(alc, "x' * g", .{ .x = x, .g = grad_output }); defer y_grad_to_copy.release(); array.copy(y_grad_to_copy, y_grad); } } test "mtimes_gradcheck" { var a = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 3, 4 }, 0.0, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 4, 3 }, 1.0, 2.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, mtimesForwardAlloc, mtimesBackwardAlloc, &inputs, 0)); } pub fn divideAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, divideForwardAlloc, divideBackwardAlloc, null); } pub fn divideForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.divideAlloc(alc, inputs[0], inputs[1]); } pub fn divideBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var x = inputs[0]; var y = inputs[1]; if (grad_inputs_out[0]) |x_grad| { var x_grad_to_sum = try array.divideAlloc(alc, grad_output, y); defer x_grad_to_sum.release(); array.bcastsum(x_grad_to_sum, x_grad); } if (grad_inputs_out[1]) |y_grad| { var y_grad_to_sum = try array.expr(alc, "-x ./ (y .* y) .* g", .{ .x = x, .y = y, .g = grad_output }); defer y_grad_to_sum.release(); array.bcastsum(y_grad_to_sum, y_grad); } } pub fn powerAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, powerForwardAlloc, powerBackwardAlloc, null); } pub fn powerForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.powerAlloc(alc, inputs[0], inputs[1]); } pub fn powerBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var x = inputs[0]; var y = inputs[1]; if (grad_inputs_out[0]) |x_grad| { var x_grad_to_sum = try array.expr(alc, "y .* (x .^ (y-1)) .* g", .{ .x = x, .y = y, .g = grad_output }); defer x_grad_to_sum.release(); array.bcastsum(x_grad_to_sum, x_grad); } if (grad_inputs_out[1]) |y_grad| { var y_grad_to_sum = try array.expr(alc, "log(x) .* (x .^ y) .* g", .{ .x = x, .y = y, .g = grad_output }); defer y_grad_to_sum.release(); array.bcastsum(y_grad_to_sum, y_grad); } } pub fn maxAlloc(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{ x, y }, &[_]Array{ x.data, y.data }, 0, maxForwardAlloc, maxBackwardAlloc, null); } pub fn maxForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return try array.maxAlloc(alc, inputs[0], inputs[1]); } pub fn maxBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var x = inputs[0]; var y = inputs[1]; if (grad_inputs_out[0]) |x_grad| { var x_grad_to_sum = try array.expr(alc, "(x > y) .* g", .{ .x = x, .y = y, .g = grad_output }); defer x_grad_to_sum.release(); array.bcastsum(x_grad_to_sum, x_grad); } if (grad_inputs_out[1]) |y_grad| { var y_grad_to_sum = try array.expr(alc, "(y >= x) .* g", .{ .x = x, .y = y, .g = grad_output }); defer y_grad_to_sum.release(); array.bcastsum(y_grad_to_sum, y_grad); } } test "max_gradcheck" { // gradcheck doesn't work for max because it is discontinuous, so just check that the behavior is similar to pytorch // torch.max(a, b) // a.grad tensor([1., 0., 0.], dtype=torch.float64) // b.grad tensor([0., 1., 1.], dtype=torch.float64) // torch.max(b, a) // a.grad tensor([1., 0., 1.], dtype=torch.float64) // b.grad tensor([0., 1., 0.], dtype=torch.float64) { var a_buf = [_]f32{ 0.0, 0.0, 2.0 }; var a_grad_buf = [_]f32{ 0.0, 0.0, 0.0 }; const a = try Tensor.allocWithBuffers(f32, std.testing.allocator, &[_]u64{3}, &a_buf, &a_grad_buf); defer a.release(); var b_buf = [_]f32{ -1.0, 1.0, 2.0 }; var b_grad_buf = [_]f32{ 0.0, 0.0, 0.0 }; const b = try Tensor.allocWithBuffers(f32, std.testing.allocator, &[_]u64{3}, &b_buf, &b_grad_buf); defer b.release(); const c = try maxAlloc(std.testing.allocator, a, b); defer c.release(); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{3}, 3.0, 0); defer d.release(); try backwardAlloc(std.testing.allocator, c, d); var a_grad_expected_buf = [_]f32{ 3.0, 0.0, 0.0 }; const a_grad_expected = Array.fromBuffer(f32, &[_]u64{3}, &a_grad_expected_buf); var b_grad_expected_buf = [_]f32{ 0.0, 3.0, 3.0 }; const b_grad_expected = Array.fromBuffer(f32, &[_]u64{3}, &b_grad_expected_buf); std.testing.expect(array.equal(a.grad.?, a_grad_expected)); std.testing.expect(array.equal(b.grad.?, b_grad_expected)); } { var a_buf = [_]f32{ 0.0, 0.0, 2.0 }; var a_grad_buf = [_]f32{ 0.0, 0.0, 0.0 }; const a = try Tensor.allocWithBuffers(f32, std.testing.allocator, &[_]u64{3}, &a_buf, &a_grad_buf); defer a.release(); var b_buf = [_]f32{ -1.0, 1.0, 2.0 }; var b_grad_buf = [_]f32{ 0.0, 0.0, 0.0 }; const b = try Tensor.allocWithBuffers(f32, std.testing.allocator, &[_]u64{3}, &b_buf, &b_grad_buf); defer b.release(); const c = try maxAlloc(std.testing.allocator, b, a); defer c.release(); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{3}, 3.0, 0); defer d.release(); try backwardAlloc(std.testing.allocator, c, d); var a_grad_expected_buf = [_]f32{ 3.0, 0.0, 3.0 }; const a_grad_expected = Array.fromBuffer(f32, &[_]u64{3}, &a_grad_expected_buf); var b_grad_expected_buf = [_]f32{ 0.0, 3.0, 0.0 }; const b_grad_expected = Array.fromBuffer(f32, &[_]u64{3}, &b_grad_expected_buf); std.testing.expect(array.equal(a.grad.?, a_grad_expected)); std.testing.expect(array.equal(b.grad.?, b_grad_expected)); } } const CastArgs = struct { dtype: DType, }; pub fn castAlloc(alc: *std.mem.Allocator, x: Tensor, dtype: DType) !Tensor { if (x.data.dtype == dtype) { x.retain(); return x; } // we only need this temporarily for the autograd interface, the backward pass can figure the dtype out var cast_args = CastArgs{ .dtype = dtype, }; var result = autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, @ptrToInt(&cast_args), castForwardAlloc, castBackwardAlloc, null); return result; } pub fn castForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { var cast_args_ptr = @intToPtr(*CastArgs, extra_args_ptr); return try array.castAlloc(alc, inputs[0], cast_args_ptr.dtype); } pub fn castBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 1) { @panic("invalid number of inputs"); } if (grad_inputs_out[0]) |grad| { array.cast(grad_output, grad); } } test "cast_grad" { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try castAlloc(std.testing.allocator, a, DType.f32); defer b.release(); var c = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3 }, 3.0, 0); defer c.release(); var d = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 3.0, 0); defer d.release(); try backwardAlloc(std.testing.allocator, b, c); std.testing.expect(array.equal(a.grad.?, d.data)); } const GatherArgs = struct { dim: u64, }; pub fn gatherAlloc(alc: *std.mem.Allocator, x: Tensor, dim: u64, index: Tensor) !Tensor { var args = try alc.create(GatherArgs); args.* = GatherArgs{ .dim = dim, }; if (index.requires_grad) { @panic("Index cannot have requires_grad set"); } return autogradAlloc(alc, &[_]Tensor{ x, index }, &[_]Array{ x.data, index.data }, @ptrToInt(args), gatherForwardAlloc, gatherBackwardAlloc, gatherDealloc); } pub fn gatherForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { var args_ptr = @intToPtr(*GatherArgs, extra_args_ptr); return try array.gatherAlloc(alc, inputs[0], args_ptr.dim, inputs[1]); } pub fn gatherBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 2) { @panic("invalid number of inputs"); } var index = inputs[1]; var args_ptr = @intToPtr(*GatherArgs, extra_args_ptr); var dim = args_ptr.dim; if (grad_inputs_out[0]) |grad| { array.scatter(grad_output, grad, dim, index); } } fn gatherDealloc(alc: *std.mem.Allocator, extra_args_ptr: u64) void { var args = @intToPtr(*GatherArgs, extra_args_ptr); alc.destroy(args); } test "gather_grad" { const input = try Tensor.allocWithRange(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 0.0, 1.0, REQUIRES_GRAD); defer input.release(); const index = try Tensor.allocWithString(u64, std.testing.allocator, "[[[0], [1], [2]], [[3], [2], [1]]]", NO_FLAGS); defer index.release(); var output = try gatherAlloc(std.testing.allocator, input, 2, index); defer output.release(); const expected_output = try Tensor.allocWithString(f32, std.testing.allocator, "[[[0], [5], [10]], [[15], [18], [21]]]", NO_FLAGS); defer expected_output.release(); std.testing.expect(array.equal(output.data, expected_output.data)); const grad_output = try Tensor.allocWithValue(f32, std.testing.allocator, output.data.getShape(), 3.0, NO_FLAGS); defer grad_output.release(); try backwardAlloc(std.testing.allocator, output, grad_output); const expected_grad = try Tensor.allocWithString(f32, std.testing.allocator, "[[[3,0,0,0], [0,3,0,0], [0,0,3,0]], [[0,0,0,3], [0,0,3,0], [0,3,0,0]]]", NO_FLAGS); defer expected_grad.release(); std.testing.expect(array.equal(input.grad.?, expected_grad.data)); } const ReduceArgs = struct { dims: array.DimArray, keepdims: bool, op: array.ReduceOperation, }; fn reduceAlloc(alc: *std.mem.Allocator, x: Tensor, dims: []const u64, keepdims: bool, op: array.ReduceOperation) !Tensor { var args = try alc.create(ReduceArgs); args.* = ReduceArgs{ .dims = array.DimArray.init(dims), .keepdims = keepdims, .op = op, }; var result = autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, @ptrToInt(args), reduceForwardAlloc, reduceBackwardAlloc, reduceDealloc); return result; } fn reduceDealloc(alc: *std.mem.Allocator, extra_args_ptr: u64) void { var args = @intToPtr(*ReduceArgs, extra_args_ptr); alc.destroy(args); } fn reduceForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { var args = @intToPtr(*ReduceArgs, extra_args_ptr); return try array.reduceAlloc(alc, inputs[0], args.dims.getSlice(), args.keepdims, args.op); } fn reduceBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 1) { @panic("Invalid number of inputs"); } var args = @intToPtr(*ReduceArgs, extra_args_ptr); var reduced_numel: u64 = 1; var expand_shape = array.DimArray.init(inputs[0].getShape()); // if we reduced along a dimension, set its size to 1 in the expanded shape of grad_output for (args.dims.getSlice()) |d| { reduced_numel *= expand_shape.array[d]; expand_shape.array[d] = 1; } var expanded_grad_output = grad_output.reshapeView(expand_shape.getSlice()); if (grad_inputs_out[0]) |grad| { switch (args.op) { .sum => array.copy(expanded_grad_output, grad), .max => { if (args.dims.ndim != 1) { @panic("Too many dimensions for max"); } var dim = args.dims.array[0]; var index = try array.keepArgMaxAlloc(alc, inputs[0], dim); defer index.release(); array.scatter(expanded_grad_output, grad, dim, index); }, .mean => { array.copy(expanded_grad_output, grad); var divisor = try array.scalarAlloc(alc, grad.dtype, @intToFloat(f64, reduced_numel)); defer divisor.release(); array.divide(grad, divisor, grad); }, } } } pub fn reduceSumAlloc(alc: *std.mem.Allocator, x: Tensor, dims: []const u64) !Tensor { return reduceAlloc(alc, x, dims, false, .sum); } pub fn keepSumAlloc(alc: *std.mem.Allocator, x: Tensor, dims: []const u64) !Tensor { return reduceAlloc(alc, x, dims, true, .sum); } pub fn reduceMaxAlloc(alc: *std.mem.Allocator, x: Tensor, dim: u64) !Tensor { return reduceAlloc(alc, x, &[_]u64{dim}, false, .max); } pub fn keepMaxAlloc(alc: *std.mem.Allocator, x: Tensor, dim: u64) !Tensor { return reduceAlloc(alc, x, &[_]u64{dim}, true, .max); } pub fn reduceMeanAlloc(alc: *std.mem.Allocator, x: Tensor, dims: []const u64) !Tensor { return reduceAlloc(alc, x, dims, false, .mean); } pub fn keepMeanAlloc(alc: *std.mem.Allocator, x: Tensor, dims: []const u64) !Tensor { return reduceAlloc(alc, x, dims, true, .mean); } test "reduce_sum_grad" { const a = try Tensor.allocWithRange(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 0.0, 1.0, REQUIRES_GRAD); defer a.release(); const b = try reduceSumAlloc(std.testing.allocator, a, &[_]u64{ 1, 2 }); defer b.release(); var c = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{2}, 3.0, 0); defer c.release(); try backwardAlloc(std.testing.allocator, b, c); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer d.release(); std.testing.expect(array.equal(a.grad.?, d.data)); } test "keep_sum_grad" { const a = try Tensor.allocWithRange(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 0.0, 1.0, REQUIRES_GRAD); defer a.release(); const b = try keepSumAlloc(std.testing.allocator, a, &[_]u64{ 1, 2 }); defer b.release(); var c = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 1, 1 }, 3.0, 0); defer c.release(); try backwardAlloc(std.testing.allocator, b, c); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer d.release(); std.testing.expect(array.equal(a.grad.?, d.data)); } test "reduce_mean_grad" { const input = try Tensor.allocWithString(f32, std.testing.allocator, "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]", REQUIRES_GRAD); defer input.release(); const output = try reduceMeanAlloc(std.testing.allocator, input, &[_]u64{1}); defer output.release(); var grad_output = try Tensor.allocWithValue(f32, std.testing.allocator, output.data.getShape(), 6.0, 0); defer grad_output.release(); try backwardAlloc(std.testing.allocator, output, grad_output); const expected_grad_input = try Tensor.allocWithString(f32, std.testing.allocator, "[[2, 2, 2], [2, 2, 2], [2, 2, 2]]", NO_FLAGS); defer expected_grad_input.release(); std.testing.expect(array.equal(input.grad.?, expected_grad_input.data)); } test "reduce_max_grad" { const TestCase = struct { input: []const u8, dim: u64, expected_grad: []const u8, }; var testcases = [_]TestCase{ TestCase{ .input = "[[[0,1], [1,0], [1,1]]]", .dim = 2, .expected_grad = "[[[0,3], [3,0], [3,0]]]", }, TestCase{ .input = "[[[0,1], [1,0], [1,1]]]", .dim = 1, .expected_grad = "[[[0,3], [3,0], [0,0]]]", }, }; for (testcases) |tc| { const input = try Tensor.allocWithString(f32, std.testing.allocator, tc.input, REQUIRES_GRAD); defer input.release(); const output = try reduceMaxAlloc(std.testing.allocator, input, tc.dim); defer output.release(); const grad_output = try Tensor.allocWithValue(f32, std.testing.allocator, output.data.getShape(), 3.0, 0); defer grad_output.release(); try backwardAlloc(std.testing.allocator, output, grad_output); const expected_grad = try Tensor.allocWithString(f32, std.testing.allocator, tc.expected_grad, 0); defer expected_grad.release(); std.testing.expect(array.equal(input.grad.?, expected_grad.data)); } } pub fn reduceSumExprAlloc(alc: *std.mem.Allocator, x: Tensor, dims: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dims, .u64); defer dims_cast.release(); var dims_buf = dims_cast.data.getBuffer(u64); return try reduceSumAlloc(alc, x, dims_buf); } pub fn keepSumExprAlloc(alc: *std.mem.Allocator, x: Tensor, dims: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dims, .u64); defer dims_cast.release(); var dims_buf = dims_cast.data.getBuffer(u64); return try keepSumAlloc(alc, x, dims_buf); } pub fn reduceMaxExprAlloc(alc: *std.mem.Allocator, x: Tensor, dim: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dim, .u64); defer dims_cast.release(); return reduceMaxAlloc(alc, x, dims_cast.data.getItem(u64)); } pub fn keepMaxExprAlloc(alc: *std.mem.Allocator, x: Tensor, dim: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dim, .u64); defer dims_cast.release(); return keepMaxAlloc(alc, x, dims_cast.data.getItem(u64)); } pub fn reduceMeanExprAlloc(alc: *std.mem.Allocator, x: Tensor, dim: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dim, .u64); defer dims_cast.release(); var dims_buf = dims_cast.data.getBuffer(u64); return reduceMeanAlloc(alc, x, dims_buf); } pub fn keepMeanExprAlloc(alc: *std.mem.Allocator, x: Tensor, dim: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dim, .u64); defer dims_cast.release(); var dims_buf = dims_cast.data.getBuffer(u64); return keepMeanAlloc(alc, x, dims_buf); } pub fn gatherExprAlloc(alc: *std.mem.Allocator, x: Tensor, dim: Tensor, index: Tensor) !Tensor { var dims_cast = try castAlloc(alc, dim, .u64); defer dims_cast.release(); var index_cast = try castAlloc(alc, index, .u64); defer index_cast.release(); return gatherAlloc(alc, x, dims_cast.data.getItem(u64), index_cast); } pub fn transposeAlloc(alc: *std.mem.Allocator, x: Tensor) !Tensor { return autogradAlloc(alc, &[_]Tensor{x}, &[_]Array{x.data}, 0, transposeForwardAlloc, transposeBackwardAlloc, null); } pub fn transposeForwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64) ForwardError!Array { return array.transposeAlloc(alc, inputs[0]); } pub fn transposeBackwardAlloc(alc: *std.mem.Allocator, inputs: []Array, extra_args_ptr: u64, output: Array, grad_inputs_out: []?Array, grad_output: Array) BackwardError!void { if (inputs.len != 1) { @panic("invalid number of inputs"); } if (grad_inputs_out[0]) |grad| { array.transpose(grad_output, grad); } } test "transpose_gradcheck" { var a = try Tensor.allocWithRange(f64, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 0.0, 1.0, REQUIRES_GRAD); defer a.release(); var inputs = [_]Tensor{a}; std.testing.expect(try gradCheck(f64, std.testing.allocator, transposeForwardAlloc, transposeBackwardAlloc, &inputs, 0)); } pub fn autogradAlloc(alc: *std.mem.Allocator, inputs: []Tensor, input_arrays: []Array, extra_args_ptr: u64, forwardFn: ForwardFn, backwardFn: BackwardFn, deallocFn: ?DeallocFn) !Tensor { var output_array = try forwardFn(alc, input_arrays, extra_args_ptr); var requires_grad = false; for (inputs) |input| { if (input.requires_grad) { requires_grad = true; } } var flags: u64 = IS_BRANCH; if (requires_grad) { flags |= REQUIRES_GRAD; } var output = try Tensor.allocWithData(alc, output_array, flags); output_array.release(); if (requires_grad) { var gr = try alc.create(GradientRecord); gr.* = try GradientRecord.alloc(alc, inputs, extra_args_ptr, output, backwardFn, deallocFn); output.grad_record = gr; } else { if (deallocFn) |dealloc| { dealloc(alc, extra_args_ptr); } } return output; } const RecordQueue = struct { const Queue = std.TailQueue(*GradientRecord); queue: Queue, alc: *std.mem.Allocator, const Self = @This(); pub fn init(alc: *std.mem.Allocator) Self { return Self{ .queue = Queue{}, .alc = alc }; } pub fn empty(self: *Self) bool { return self.queue.len == 0; } pub fn pushNode(self: *Self, grad_record: *GradientRecord) !void { var queue_node = try self.alc.create(Queue.Node); queue_node.data = grad_record; self.queue.append(queue_node); } pub fn popNode(self: *Self) *GradientRecord { var maybe_queue_node = self.queue.popFirst(); if (maybe_queue_node) |queue_node| { var gr = queue_node.data; self.alc.destroy(queue_node); return gr; } else { @panic("attempted to dequeue from empty queue"); } } }; fn Counter(comptime T: type) type { return struct { map: std.AutoHashMap(T, u64), const Self = @This(); fn init(alc: *std.mem.Allocator) !Self { return Self{ .map = std.AutoHashMap(T, u64).init(alc) }; } fn incr(self: *Self, key: T) !u64 { var count: u64 = 1; if (self.map.get(key)) |c| { count += c; } try self.map.put(key, count); return count; } fn decr(self: *Self, key: T) !u64 { var count: u64 = 0; if (self.map.get(key)) |c| { count = c - 1; } try self.map.put(key, count); return count; } fn deinit(self: *Self) void { self.map.deinit(); } }; } fn toposort(alc: *std.mem.Allocator, root: *GradientRecord, records: []*GradientRecord) !void { var incoming_edge_counter = try Counter(*GradientRecord).init(std.testing.allocator); defer incoming_edge_counter.deinit(); for (records) |rec| { for (rec.inputs) |input| { if (input.grad_record) |input_rec| { _ = try incoming_edge_counter.incr(input_rec); } } } var sorted_records = std.ArrayList(*GradientRecord).init(std.testing.allocator); defer sorted_records.deinit(); var q = RecordQueue.init(std.testing.allocator); try q.pushNode(root); while (!q.empty()) { var rec = q.popNode(); try sorted_records.append(rec); for (rec.inputs) |input| { if (input.grad_record) |input_rec| { var count = try incoming_edge_counter.decr(input_rec); if (count == 0) { try q.pushNode(input_rec); } } } } if (sorted_records.items.len != records.len) { @panic("Failed to sort graph"); } std.mem.copy(*GradientRecord, records, sorted_records.items); } pub fn backwardScalarAlloc(alc: *std.mem.Allocator, output: Tensor) !void { if (output.data.ndim != 0) { std.debug.panic("Expected scalar, got ndim {}", .{output.data.ndim}); } var grad_output = try onesLikeAlloc(alc, output, NO_FLAGS); defer grad_output.release(); return backwardAlloc(alc, output, grad_output); } pub fn backwardAlloc(alc: *std.mem.Allocator, output: Tensor, grad_output: Tensor) !void { if (output.grad_record == null) { return; } if (!std.mem.eql(u64, output.data.getShape(), grad_output.data.getShape())) { @panic("output shape does not match grad_output shape"); } grad_output.data.retain(); output.grad_record.?.grad_output = grad_output.data; var root = output.grad_record.?; // find all gradient records var seen = std.AutoHashMap(*GradientRecord, bool).init(std.testing.allocator); defer seen.deinit(); var q = RecordQueue.init(std.testing.allocator); var records = std.ArrayList(*GradientRecord).init(std.testing.allocator); defer records.deinit(); try q.pushNode(root); while (!q.empty()) { var rec = q.popNode(); if (seen.get(rec) != null) { continue; } try records.append(rec); try seen.put(rec, true); for (rec.inputs) |input| { if (input.grad_record) |grad_record| { try q.pushNode(grad_record); } } } // sort the records try toposort(std.testing.allocator, root, records.items); // perform backward pass for (records.items) |rec| { var inputs = try alc.alloc(Array, rec.inputs.len); defer alc.free(inputs); var grad_inputs = try alc.alloc(?Array, rec.inputs.len); defer alc.free(grad_inputs); for (grad_inputs) |_, i| { if (rec.inputs[i].requires_grad) { grad_inputs[i] = try array.zerosLikeAlloc(alc, rec.inputs[i].data); } else { grad_inputs[i] = null; } inputs[i] = rec.inputs[i].data; } try rec.backward_fn(alc, inputs, rec.extra_args_ptr, rec.output.data, grad_inputs, rec.grad_output.?); rec.grad_output.?.release(); rec.grad_output = null; for (grad_inputs) |maybe_grad_input, i| { if (maybe_grad_input == null) { continue; } var grad_input = maybe_grad_input.?; var input = rec.inputs[i]; defer grad_input.release(); if (!input.requires_grad) { @panic("Input does not require grad but we created a grad input for it"); } if (input.is_leaf) { if (input.grad == null) { @panic("missing grad buffer on leaf variable"); } if (input.grad_record != null) { @panic("leaf variable has grad record"); } } else { if (input.grad_record == null) { @panic("non-leaf tensor requires grad but has no grad record"); } } if (input.grad) |input_grad| { array.plus(input_grad, grad_input, input_grad); } if (input.grad_record) |input_grad_record| { // enqueue a node to run backward on it // this node now owns the grad_input array if (input_grad_record.grad_output) |gradout| { // there's already a grad output on this node, accumulate into it array.plus(gradout, grad_input, gradout); } else { // there's no grad output, put this value there grad_input.retain(); input_grad_record.grad_output = grad_input; } } } } } fn gradCheck(comptime T: type, alc: *std.mem.Allocator, forwardFn: ForwardFn, backwardFn: BackwardFn, inputs: []Tensor, extra_args_ptr: u64) !bool { const epsilon = 1e-6; const rtol = 1e-3; const atol = 1e-5; for (inputs) |input| { if (!input.data.is_contiguous) { @panic("contiguous inputs required"); } } var input_arrays = try alc.alloc(Array, inputs.len); defer alc.free(input_arrays); for (inputs) |input, i| { input_arrays[i] = input.data; } var output = try forwardFn(alc, input_arrays, extra_args_ptr); defer output.release(); for (inputs) |input, input_index| { if (input.requires_grad) { var fd_jacobian = try Array.allocWithValue(T, alc, &[_]u64{ output.numel, input.data.numel }, 0.0); defer fd_jacobian.release(); // use finite differences to build up the jacobian column by column var input_elem_index: u64 = 0; while (input_elem_index < input.data.numel) : (input_elem_index += 1) { var buf = input.data.getBuffer(T); var val = buf[input_elem_index]; buf[input_elem_index] = val + epsilon; var plus_output = try forwardFn(alc, input_arrays, extra_args_ptr); defer plus_output.release(); buf[input_elem_index] = val - epsilon; var minus_output = try forwardFn(alc, input_arrays, extra_args_ptr); defer minus_output.release(); buf[input_elem_index] = val; var diff = try array.minusAlloc(alc, plus_output, minus_output); defer diff.release(); var divisor = try Array.allocWithValue(T, alc, &[_]u64{}, 2.0 * epsilon); defer divisor.release(); var jacobian_column = try array.divideAlloc(alc, diff, divisor); defer jacobian_column.release(); var fd_column = fd_jacobian.narrowView(&[_]u64{ 0, input_elem_index }, &[_]u64{ output.numel, 1 }); array.copy(jacobian_column.flatView(), fd_column.flatView()); } // use our backward functions to build up the jacobian row by row var backward_jacobian = try Array.allocWithValue(T, alc, &[_]u64{ output.numel, input.data.numel }, 0.0); defer backward_jacobian.release(); var output_elem_index: u64 = 0; while (output_elem_index < output.numel) : (output_elem_index += 1) { var grad_inputs = try alc.alloc(?Array, inputs.len); defer alc.free(grad_inputs); for (grad_inputs) |_, i| { grad_inputs[i] = try array.zerosLikeAlloc(alc, input_arrays[i]); } var grad_output = try array.zerosLikeAlloc(alc, output); var buf = grad_output.getBuffer(T); buf[output_elem_index] = 1.0; defer grad_output.release(); try backwardFn(alc, input_arrays, extra_args_ptr, output, grad_inputs, grad_output); var jacobian_row = grad_inputs[input_index].?; array.copy(jacobian_row.flatView(), backward_jacobian.narrowView(&[_]u64{ output_elem_index, 0 }, &[_]u64{ 1, input.data.numel }).flatView()); for (grad_inputs) |maybe_grad_input| { if (maybe_grad_input) |grad_input| { grad_input.release(); } } } if (!array.allclose(fd_jacobian, backward_jacobian, rtol, atol)) { std.debug.print("jacobian mismatch\n", .{}); std.debug.print("fd_jacobian {}\n", .{fd_jacobian}); std.debug.print("backward_jacobian {}\n", .{backward_jacobian}); return false; } } } return true; } test "plus_gradcheck" { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 2.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, plusForwardAlloc, plusBackwardAlloc, &inputs, 0)); } test "plus_grad" { var a = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 2.0, REQUIRES_GRAD); defer b.release(); var out = try plusAlloc(std.testing.allocator, a, b); defer out.release(); var grad_out = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 4.0, 0); defer grad_out.release(); try backwardAlloc(std.testing.allocator, out, grad_out); std.testing.expect(array.equal(a.grad.?, grad_out.data)); std.testing.expect(array.equal(b.grad.?, grad_out.data)); } test "plus_grad_multiple_levels" { var a = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 2.0, REQUIRES_GRAD); defer b.release(); var c = try plusAlloc(std.testing.allocator, a, b); defer c.release(); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 2.0, REQUIRES_GRAD); defer d.release(); var e = try plusAlloc(std.testing.allocator, c, d); defer e.release(); var f = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer f.release(); try backwardAlloc(std.testing.allocator, e, f); std.testing.expect(array.equal(a.grad.?, f.data)); std.testing.expect(array.equal(b.grad.?, f.data)); } test "plus_grad_bcast" { var a = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{4}, 2.0, REQUIRES_GRAD); defer b.release(); var c = try plusAlloc(std.testing.allocator, a, b); defer c.release(); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer d.release(); try backwardAlloc(std.testing.allocator, c, d); std.testing.expect(array.equal(a.grad.?, d.data)); var e = try Array.allocWithValue(f32, std.testing.allocator, &[_]u64{4}, 18.0); defer e.release(); std.testing.expect(array.equal(b.grad.?, e)); } test "plus_no_grad" { var a = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, 0); defer a.release(); var b = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 2.0, 0); defer b.release(); var c = try plusAlloc(std.testing.allocator, a, b); defer c.release(); var d = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer d.release(); try backwardAlloc(std.testing.allocator, c, d); std.testing.expect(a.grad == null); std.testing.expect(b.grad == null); } test "minus_gradcheck" { { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 1, 3 }, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 2.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, minusForwardAlloc, minusBackwardAlloc, &inputs, 0)); } { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{3}, 1.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 2.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, minusForwardAlloc, minusBackwardAlloc, &inputs, 0)); } } test "times_gradcheck" { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{3}, 2.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 3.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, timesForwardAlloc, timesBackwardAlloc, &inputs, 0)); } test "divide_gradcheck" { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{3}, 2.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 3.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, divideForwardAlloc, divideBackwardAlloc, &inputs, 0)); } test "power_gradcheck" { var a = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{3}, 2.0, REQUIRES_GRAD); defer a.release(); var b = try Tensor.allocWithValue(f64, std.testing.allocator, &[_]u64{ 2, 3 }, 3.0, REQUIRES_GRAD); defer b.release(); var inputs = [_]Tensor{ a, b }; std.testing.expect(try gradCheck(f64, std.testing.allocator, powerForwardAlloc, powerBackwardAlloc, &inputs, 0)); } fn getDType(t: Tensor) DType { return t.data.dtype; } pub fn binaryNotImplemented(alc: *std.mem.Allocator, x: Tensor, y: Tensor) !Tensor { @panic("operation not implemented"); } pub fn unaryNotImplemented(alc: *std.mem.Allocator, x: Tensor) !Tensor { @panic("operation not implemented"); } pub fn scalarNotImplemented(alc: *std.mem.Allocator, dtype: DType, value: f64) !Tensor { @panic("scalar not implemented"); } pub fn expr(alc: *std.mem.Allocator, comptime exp: []const u8, args: anytype) !Tensor { comptime var opsTable = array.OpsTable(Tensor){ .plus = plusAlloc, .minus = minusAlloc, .uplus = uplusAlloc, .uminus = uminusAlloc, .times = timesAlloc, .mtimes = mtimesAlloc, .divide = divideAlloc, .mdivide = binaryNotImplemented, .power = powerAlloc, .mpower = binaryNotImplemented, .eq = binaryNotImplemented, .gt = binaryNotImplemented, .gte = binaryNotImplemented, .lt = binaryNotImplemented, .lte = binaryNotImplemented, .transpose = transposeAlloc, .ctranspose = transposeAlloc, .scalar = scalarAlloc, .cast = castAlloc, .detach = detachAlloc, .log = logAlloc, .log2 = log2Alloc, .exp = expAlloc, .max = maxAlloc, .reduce_sum = reduceSumExprAlloc, .keep_sum = keepSumExprAlloc, .reduce_max = reduceMaxExprAlloc, .keep_max = keepMaxExprAlloc, .reduce_mean = reduceMeanExprAlloc, .keep_mean = keepMeanExprAlloc, .reduce_arg_max = binaryNotImplemented, .keep_arg_max = binaryNotImplemented, .gather = gatherExprAlloc, .get_dtype = getDType, }; return try array.genericExpr(Tensor, opsTable, alc, exp, args); } test "expr" { { const a_data = try Array.allocWithRange(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, 1.0); defer a_data.release(); const b_data = try Array.allocWithRange(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 1.0, 1.0); defer b_data.release(); const a = try Tensor.allocWithData(std.testing.allocator, a_data, REQUIRES_GRAD); defer a.release(); const b = try Tensor.allocWithData(std.testing.allocator, b_data, REQUIRES_GRAD); defer b.release(); var c = try expr(std.testing.allocator, "a + b", .{ .a = a, .b = b }); defer c.release(); var d = try plusAlloc(std.testing.allocator, a, b); defer d.release(); std.testing.expect(array.equal(c.data, d.data)); var e = try Tensor.allocWithValue(f32, std.testing.allocator, &[_]u64{ 2, 3, 4 }, 3.0, 0); defer e.release(); try backwardAlloc(std.testing.allocator, c, e); std.testing.expect(array.equal(a.grad.?, e.data)); std.testing.expect(array.equal(b.grad.?, e.data)); } }
src/tensor.zig
const std = @import("std"); const builtin = std.builtin; const crypto = std.crypto; const mem = std.mem; const meta = std.meta; const EncodingError = crypto.errors.EncodingError; const IdentityElementError = crypto.errors.IdentityElementError; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; /// Group operations over P256. pub const P256 = struct { /// The underlying prime field. pub const Fe = @import("p256/field.zig").Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = @import("p256/scalar.zig"); x: Fe, y: Fe, z: Fe = Fe.one, is_base: bool = false, /// The P256 base point. pub const basePoint = P256{ .x = Fe.fromInt(48439561293906451759052585252797914202762949526041747995844080717082404635286) catch unreachable, .y = Fe.fromInt(36134250956749795798585127919587881956611106672985015071877198253568414405109) catch unreachable, .z = Fe.one, .is_base = true, }; /// The P256 neutral element. pub const identityElement = P256{ .x = Fe.zero, .y = Fe.one, .z = Fe.zero }; pub const B = Fe.fromInt(41058363725152142129326129780047268409114441015993725554835256314039467401291) catch unreachable; /// Reject the neutral element. pub fn rejectIdentity(p: P256) IdentityElementError!void { if (p.x.isZero()) { return error.IdentityElement; } } /// Create a point from affine coordinates after checking that they match the curve equation. pub fn fromAffineCoordinates(p: AffineCoordinates) EncodingError!P256 { const x = p.x; const y = p.y; const x3AxB = x.sq().mul(x).sub(x).sub(x).sub(x).add(B); const yy = y.sq(); const on_curve = @boolToInt(x3AxB.equivalent(yy)); const is_identity = @boolToInt(x.equivalent(AffineCoordinates.identityElement.x)) & @boolToInt(y.equivalent(AffineCoordinates.identityElement.y)); if ((on_curve | is_identity) == 0) { return error.InvalidEncoding; } var ret = P256{ .x = x, .y = y, .z = Fe.one }; ret.z.cMov(P256.identityElement.z, is_identity); return ret; } /// Create a point from serialized affine coordinates. pub fn fromSerializedAffineCoordinates(xs: [32]u8, ys: [32]u8, endian: builtin.Endian) (NonCanonicalError || EncodingError)!P256 { const x = try Fe.fromBytes(xs, endian); const y = try Fe.fromBytes(ys, endian); return fromAffineCoordinates(.{ .x = x, .y = y }); } /// Recover the Y coordinate from the X coordinate. pub fn recoverY(x: Fe, is_odd: bool) NotSquareError!Fe { const x3AxB = x.sq().mul(x).sub(x).sub(x).sub(x).add(B); var y = try x3AxB.sqrt(); const yn = y.neg(); y.cMov(yn, @boolToInt(is_odd) ^ @boolToInt(y.isOdd())); return y; } /// Deserialize a SEC1-encoded point. pub fn fromSec1(s: []const u8) (EncodingError || NotSquareError || NonCanonicalError)!P256 { if (s.len < 1) return error.InvalidEncoding; const encoding_type = s[0]; const encoded = s[1..]; switch (encoding_type) { 0 => { if (encoded.len != 0) return error.InvalidEncoding; return P256.identityElement; }, 2, 3 => { if (encoded.len != 32) return error.InvalidEncoding; const x = try Fe.fromBytes(encoded[0..32].*, .Big); const y_is_odd = (encoding_type == 3); const y = try recoverY(x, y_is_odd); return P256{ .x = x, .y = y }; }, 4 => { if (encoded.len != 64) return error.InvalidEncoding; const x = try Fe.fromBytes(encoded[0..32].*, .Big); const y = try Fe.fromBytes(encoded[32..64].*, .Big); return P256.fromAffineCoordinates(.{ .x = x, .y = y }); }, else => return error.InvalidEncoding, } } /// Serialize a point using the compressed SEC-1 format. pub fn toCompressedSec1(p: P256) [33]u8 { var out: [33]u8 = undefined; const xy = p.affineCoordinates(); out[0] = if (xy.y.isOdd()) 3 else 2; mem.copy(u8, out[1..], &xy.x.toBytes(.Big)); return out; } /// Serialize a point using the uncompressed SEC-1 format. pub fn toUncompressedSec1(p: P256) [65]u8 { var out: [65]u8 = undefined; out[0] = 4; const xy = p.affineCoordinates(); mem.copy(u8, out[1..33], &xy.x.toBytes(.Big)); mem.copy(u8, out[33..65], &xy.y.toBytes(.Big)); return out; } /// Return a random point. pub fn random() P256 { const n = scalar.random(.Little); return basePoint.mul(n, .Little) catch unreachable; } /// Flip the sign of the X coordinate. pub fn neg(p: P256) P256 { return .{ .x = p.x, .y = p.y.neg(), .z = p.z }; } /// Double a P256 point. // Algorithm 6 from https://eprint.iacr.org/2015/1060.pdf pub fn dbl(p: P256) P256 { var t0 = p.x.sq(); var t1 = p.y.sq(); var t2 = p.z.sq(); var t3 = p.x.mul(p.y); t3 = t3.dbl(); var Z3 = p.x.mul(p.z); Z3 = Z3.add(Z3); var Y3 = B.mul(t2); Y3 = Y3.sub(Z3); var X3 = Y3.dbl(); Y3 = X3.add(Y3); X3 = t1.sub(Y3); Y3 = t1.add(Y3); Y3 = X3.mul(Y3); X3 = X3.mul(t3); t3 = t2.dbl(); t2 = t2.add(t3); Z3 = B.mul(Z3); Z3 = Z3.sub(t2); Z3 = Z3.sub(t0); t3 = Z3.dbl(); Z3 = Z3.add(t3); t3 = t0.dbl(); t0 = t3.add(t0); t0 = t0.sub(t2); t0 = t0.mul(Z3); Y3 = Y3.add(t0); t0 = p.y.mul(p.z); t0 = t0.dbl(); Z3 = t0.mul(Z3); X3 = X3.sub(Z3); Z3 = t0.mul(t1); Z3 = Z3.dbl().dbl(); return .{ .x = X3, .y = Y3, .z = Z3, }; } /// Add P256 points, the second being specified using affine coordinates. // Algorithm 5 from https://eprint.iacr.org/2015/1060.pdf pub fn addMixed(p: P256, q: AffineCoordinates) P256 { var t0 = p.x.mul(q.x); var t1 = p.y.mul(q.y); var t3 = q.x.add(q.y); var t4 = p.x.add(p.y); t3 = t3.mul(t4); t4 = t0.add(t1); t3 = t3.sub(t4); t4 = q.y.mul(p.z); t4 = t4.add(p.y); var Y3 = q.x.mul(p.z); Y3 = Y3.add(p.x); var Z3 = B.mul(p.z); var X3 = Y3.sub(Z3); Z3 = X3.dbl(); X3 = X3.add(Z3); Z3 = t1.sub(X3); X3 = t1.add(X3); Y3 = B.mul(Y3); t1 = p.z.dbl(); var t2 = t1.add(p.z); Y3 = Y3.sub(t2); Y3 = Y3.sub(t0); t1 = Y3.dbl(); Y3 = t1.add(Y3); t1 = t0.dbl(); t0 = t1.add(t0); t0 = t0.sub(t2); t1 = t4.mul(Y3); t2 = t0.mul(Y3); Y3 = X3.mul(Z3); Y3 = Y3.add(t2); X3 = t3.mul(X3); X3 = X3.sub(t1); Z3 = t4.mul(Z3); t1 = t3.mul(t0); Z3 = Z3.add(t1); var ret = P256{ .x = X3, .y = Y3, .z = Z3, }; ret.cMov(p, @boolToInt(q.x.isZero())); return ret; } /// Add P256 points. // Algorithm 4 from https://eprint.iacr.org/2015/1060.pdf pub fn add(p: P256, q: P256) P256 { var t0 = p.x.mul(q.x); var t1 = p.y.mul(q.y); var t2 = p.z.mul(q.z); var t3 = p.x.add(p.y); var t4 = q.x.add(q.y); t3 = t3.mul(t4); t4 = t0.add(t1); t3 = t3.sub(t4); t4 = p.y.add(p.z); var X3 = q.y.add(q.z); t4 = t4.mul(X3); X3 = t1.add(t2); t4 = t4.sub(X3); X3 = p.x.add(p.z); var Y3 = q.x.add(q.z); X3 = X3.mul(Y3); Y3 = t0.add(t2); Y3 = X3.sub(Y3); var Z3 = B.mul(t2); X3 = Y3.sub(Z3); Z3 = X3.dbl(); X3 = X3.add(Z3); Z3 = t1.sub(X3); X3 = t1.add(X3); Y3 = B.mul(Y3); t1 = t2.dbl(); t2 = t1.add(t2); Y3 = Y3.sub(t2); Y3 = Y3.sub(t0); t1 = Y3.dbl(); Y3 = t1.add(Y3); t1 = t0.dbl(); t0 = t1.add(t0); t0 = t0.sub(t2); t1 = t4.mul(Y3); t2 = t0.mul(Y3); Y3 = X3.mul(Z3); Y3 = Y3.add(t2); X3 = t3.mul(X3); X3 = X3.sub(t1); Z3 = t4.mul(Z3); t1 = t3.mul(t0); Z3 = Z3.add(t1); return .{ .x = X3, .y = Y3, .z = Z3, }; } /// Subtract P256 points. pub fn sub(p: P256, q: P256) P256 { return p.add(q.neg()); } /// Subtract P256 points, the second being specified using affine coordinates. pub fn subMixed(p: P256, q: AffineCoordinates) P256 { return p.addMixed(q.neg()); } /// Return affine coordinates. pub fn affineCoordinates(p: P256) AffineCoordinates { const zinv = p.z.invert(); var ret = AffineCoordinates{ .x = p.x.mul(zinv), .y = p.y.mul(zinv), }; ret.cMov(AffineCoordinates.identityElement, @boolToInt(p.x.isZero())); return ret; } /// Return true if both coordinate sets represent the same point. pub fn equivalent(a: P256, b: P256) bool { if (a.sub(b).rejectIdentity()) { return false; } else |_| { return true; } } fn cMov(p: *P256, a: P256, c: u1) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); p.z.cMov(a.z, c); } fn pcSelect(comptime n: usize, pc: *const [n]P256, b: u8) P256 { var t = P256.identityElement; comptime var i: u8 = 1; inline while (i < pc.len) : (i += 1) { t.cMov(pc[i], @truncate(u1, (@as(usize, b ^ i) -% 1) >> 8)); } return t; } fn slide(s: [32]u8) [2 * 32 + 1]i8 { var e: [2 * 32 + 1]i8 = undefined; for (s) |x, i| { e[i * 2 + 0] = @as(i8, @truncate(u4, x)); e[i * 2 + 1] = @as(i8, @truncate(u4, x >> 4)); } // Now, e[0..63] is between 0 and 15, e[63] is between 0 and 7 var carry: i8 = 0; for (e[0..64]) |*x| { x.* += carry; carry = (x.* + 8) >> 4; x.* -= carry * 16; std.debug.assert(x.* >= -8 and x.* <= 8); } e[64] = carry; // Now, e[*] is between -8 and 8, including e[64] std.debug.assert(carry >= -8 and carry <= 8); return e; } fn pcMul(pc: *const [9]P256, s: [32]u8, comptime vartime: bool) IdentityElementError!P256 { std.debug.assert(vartime); const e = slide(s); var q = P256.identityElement; var pos = e.len - 1; while (true) : (pos -= 1) { const slot = e[pos]; if (slot > 0) { q = q.add(pc[@intCast(usize, slot)]); } else if (slot < 0) { q = q.sub(pc[@intCast(usize, -slot)]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn pcMul16(pc: *const [16]P256, s: [32]u8, comptime vartime: bool) IdentityElementError!P256 { var q = P256.identityElement; var pos: usize = 252; while (true) : (pos -= 4) { const slot = @truncate(u4, (s[pos >> 3] >> @truncate(u3, pos))); if (vartime) { if (slot != 0) { q = q.add(pc[slot]); } } else { q = q.add(pcSelect(16, pc, slot)); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn precompute(p: P256, comptime count: usize) [1 + count]P256 { var pc: [1 + count]P256 = undefined; pc[0] = P256.identityElement; pc[1] = p; var i: usize = 2; while (i <= count) : (i += 1) { pc[i] = if (i % 2 == 0) pc[i / 2].dbl() else pc[i - 1].add(p); } return pc; } const basePointPc = pc: { @setEvalBranchQuota(50000); break :pc precompute(P256.basePoint, 15); }; /// Multiply an elliptic curve point by a scalar. /// Return error.IdentityElement if the result is the identity element. pub fn mul(p: P256, s_: [32]u8, endian: builtin.Endian) IdentityElementError!P256 { const s = if (endian == .Little) s_ else Fe.orderSwap(s_); if (p.is_base) { return pcMul16(&basePointPc, s, false); } try p.rejectIdentity(); const pc = precompute(p, 15); return pcMul16(&pc, s, false); } /// Multiply an elliptic curve point by a *PUBLIC* scalar *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulPublic(p: P256, s_: [32]u8, endian: builtin.Endian) IdentityElementError!P256 { const s = if (endian == .Little) s_ else Fe.orderSwap(s_); if (p.is_base) { return pcMul16(&basePointPc, s, true); } try p.rejectIdentity(); const pc = precompute(p, 8); return pcMul(&pc, s, true); } /// Double-base multiplication of public parameters - Compute (p1*s1)+(p2*s2) *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulDoubleBasePublic(p1: P256, s1_: [32]u8, p2: P256, s2_: [32]u8, endian: builtin.Endian) IdentityElementError!P256 { const s1 = if (endian == .Little) s1_ else Fe.orderSwap(s1_); const s2 = if (endian == .Little) s2_ else Fe.orderSwap(s2_); try p1.rejectIdentity(); var pc1_array: [9]P256 = undefined; const pc1 = if (p1.is_base) basePointPc[0..9] else pc: { pc1_array = precompute(p1, 8); break :pc &pc1_array; }; try p2.rejectIdentity(); var pc2_array: [9]P256 = undefined; const pc2 = if (p2.is_base) basePointPc[0..9] else pc: { pc2_array = precompute(p2, 8); break :pc &pc2_array; }; const e1 = slide(s1); const e2 = slide(s2); var q = P256.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { const slot1 = e1[pos]; if (slot1 > 0) { q = q.add(pc1[@intCast(usize, slot1)]); } else if (slot1 < 0) { q = q.sub(pc1[@intCast(usize, -slot1)]); } const slot2 = e2[pos]; if (slot2 > 0) { q = q.add(pc2[@intCast(usize, slot2)]); } else if (slot2 < 0) { q = q.sub(pc2[@intCast(usize, -slot2)]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } }; /// A point in affine coordinates. pub const AffineCoordinates = struct { x: P256.Fe, y: P256.Fe, /// Identity element in affine coordinates. pub const identityElement = AffineCoordinates{ .x = P256.identityElement.x, .y = P256.identityElement.y }; fn cMov(p: *AffineCoordinates, a: AffineCoordinates, c: u1) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); } }; test "p256" { _ = @import("tests.zig"); }
lib/std/crypto/pcurves/p256.zig