From ecd9c2277de17e24fa26aefee955caa10b5b990c Mon Sep 17 00:00:00 2001 From: Jose Colon Rodriguez Date: Tue, 27 Feb 2024 18:04:32 -0400 Subject: General Category with GenCatData --- build.zig | 22 ++++++- codegen/gencat.zig | 172 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/GenCatData.zig | 83 ++++++++++++++++++++++++++ src/HangulData.zig | 8 +-- src/main.zig | 33 ++++++---- 5 files changed, 300 insertions(+), 18 deletions(-) create mode 100644 codegen/gencat.zig create mode 100644 src/GenCatData.zig diff --git a/build.zig b/build.zig index 7e41a9a..b10b0d3 100644 --- a/build.zig +++ b/build.zig @@ -79,6 +79,15 @@ pub fn build(b: *std.Build) void { const run_ccc_gen_exe = b.addRunArtifact(ccc_gen_exe); const ccc_gen_out = run_ccc_gen_exe.addOutputFileArg("ccc.bin.z"); + const gencat_gen_exe = b.addExecutable(.{ + .name = "gencat", + .root_source_file = .{ .path = "codegen/gencat.zig" }, + .target = b.host, + .optimize = .Debug, + }); + const run_gencat_gen_exe = b.addRunArtifact(gencat_gen_exe); + const gencat_gen_out = run_gencat_gen_exe.addOutputFileArg("gencat.bin.z"); + // Modules we provide // Code points const code_point = b.addModule("code_point", .{ @@ -185,6 +194,14 @@ pub fn build(b: *std.Build) void { norm.addImport("ziglyph", ziglyph.module("ziglyph")); norm.addImport("NormData", norm_data); + // General Category + const gencat_data = b.createModule(.{ + .root_source_file = .{ .path = "src/GenCatData.zig" }, + .target = target, + .optimize = optimize, + }); + gencat_data.addAnonymousImport("gencat", .{ .root_source_file = gencat_gen_out }); + // Benchmark rig const exe = b.addExecutable(.{ .name = "zg", @@ -194,10 +211,11 @@ pub fn build(b: *std.Build) void { }); // exe.root_module.addImport("ziglyph", ziglyph.module("ziglyph")); // exe.root_module.addImport("ascii", ascii); - // exe.root_module.addImport("code_point", code_point); + exe.root_module.addImport("code_point", code_point); // exe.root_module.addImport("grapheme", grapheme); // exe.root_module.addImport("DisplayWidth", display_width); - exe.root_module.addImport("Normalizer", norm); + // exe.root_module.addImport("Normalizer", norm); + exe.root_module.addImport("GenCatData", gencat_data); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); diff --git a/codegen/gencat.zig b/codegen/gencat.zig new file mode 100644 index 0000000..5407040 --- /dev/null +++ b/codegen/gencat.zig @@ -0,0 +1,172 @@ +const std = @import("std"); +const builtin = @import("builtin"); + +const Gc = enum { + Cc, + Cf, + Cn, + Co, + Cs, + Ll, + Lm, + Lo, + Lt, + Lu, + Mc, + Me, + Mn, + Nd, + Nl, + No, + Pc, + Pd, + Pe, + Pf, + Pi, + Po, + Ps, + Sc, + Sk, + Sm, + So, + Zl, + Zp, + Zs, +}; + +const block_size = 256; +const Block = [block_size]u5; + +const BlockMap = std.HashMap( + Block, + u16, + struct { + pub fn hash(_: @This(), k: Block) u64 { + var hasher = std.hash.Wyhash.init(0); + std.hash.autoHashStrat(&hasher, k, .DeepRecursive); + return hasher.final(); + } + + pub fn eql(_: @This(), a: Block, b: Block) bool { + return std.mem.eql(u5, &a, &b); + } + }, + std.hash_map.default_max_load_percentage, +); + +pub fn main() !void { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + var flat_map = std.AutoHashMap(u21, u5).init(allocator); + defer flat_map.deinit(); + + var line_buf: [4096]u8 = undefined; + + // Process DerivedEastAsianWidth.txt + var in_file = try std.fs.cwd().openFile("data/unicode/extracted/DerivedGeneralCategory.txt", .{}); + defer in_file.close(); + var in_buf = std.io.bufferedReader(in_file.reader()); + const in_reader = in_buf.reader(); + + while (try in_reader.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { + if (line.len == 0 or line[0] == '#') continue; + + const no_comment = if (std.mem.indexOfScalar(u8, line, '#')) |octo| line[0..octo] else line; + + var field_iter = std.mem.tokenizeAny(u8, no_comment, "; "); + var current_code: [2]u21 = undefined; + + var i: usize = 0; + while (field_iter.next()) |field| : (i += 1) { + switch (i) { + 0 => { + // Code point(s) + if (std.mem.indexOf(u8, field, "..")) |dots| { + current_code = .{ + try std.fmt.parseInt(u21, field[0..dots], 16), + try std.fmt.parseInt(u21, field[dots + 2 ..], 16), + }; + } else { + const code = try std.fmt.parseInt(u21, field, 16); + current_code = .{ code, code }; + } + }, + 1 => { + // General category + const gc = std.meta.stringToEnum(Gc, field) orelse return error.UnknownGenCat; + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), @intFromEnum(gc)); + }, + else => {}, + } + } + } + + var blocks_map = BlockMap.init(allocator); + defer blocks_map.deinit(); + + var stage1 = std.ArrayList(u16).init(allocator); + defer stage1.deinit(); + + var stage2 = std.ArrayList(u5).init(allocator); + defer stage2.deinit(); + + var stage3 = std.ArrayList(u5).init(allocator); + defer stage3.deinit(); + + var block: Block = [_]u5{0} ** block_size; + var block_len: u16 = 0; + + for (0..0x110000) |i| { + const cp: u21 = @intCast(i); + const gc = flat_map.get(cp).?; + + const stage3_idx = blk: { + for (stage3.items, 0..) |gci, j| { + if (gc == gci) break :blk j; + } + try stage3.append(gc); + break :blk stage3.items.len - 1; + }; + + // Process block + block[block_len] = @intCast(stage3_idx); + block_len += 1; + + if (block_len < block_size and cp != 0x10ffff) continue; + + const gop = try blocks_map.getOrPut(block); + if (!gop.found_existing) { + gop.value_ptr.* = @intCast(stage2.items.len); + try stage2.appendSlice(&block); + } + + try stage1.append(gop.value_ptr.*); + block_len = 0; + } + + var args_iter = try std.process.argsWithAllocator(allocator); + defer args_iter.deinit(); + _ = args_iter.skip(); + const output_path = args_iter.next() orelse @panic("No output file arg!"); + + const compressor = std.compress.deflate.compressor; + var out_file = try std.fs.cwd().createFile(output_path, .{}); + defer out_file.close(); + var out_comp = try compressor(allocator, out_file.writer(), .{ .level = .best_compression }); + defer out_comp.deinit(); + const writer = out_comp.writer(); + + const endian = builtin.cpu.arch.endian(); + try writer.writeInt(u16, @intCast(stage1.items.len), endian); + for (stage1.items) |i| try writer.writeInt(u16, i, endian); + + try writer.writeInt(u16, @intCast(stage2.items.len), endian); + for (stage2.items) |i| try writer.writeInt(u8, i, endian); + + try writer.writeInt(u8, @intCast(stage3.items.len), endian); + for (stage3.items) |i| try writer.writeInt(u8, i, endian); + + try out_comp.flush(); +} diff --git a/src/GenCatData.zig b/src/GenCatData.zig new file mode 100644 index 0000000..5496e4e --- /dev/null +++ b/src/GenCatData.zig @@ -0,0 +1,83 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const compress = std.compress; +const mem = std.mem; + +/// General Category +pub const Gc = enum { + Cc, + Cf, + Cn, + Co, + Cs, + Ll, + Lm, + Lo, + Lt, + Lu, + Mc, + Me, + Mn, + Nd, + Nl, + No, + Pc, + Pd, + Pe, + Pf, + Pi, + Po, + Ps, + Sc, + Sk, + Sm, + So, + Zl, + Zp, + Zs, +}; + +allocator: mem.Allocator, +s1: []u16 = undefined, +s2: []u5 = undefined, +s3: []u5 = undefined, + +const Self = @This(); + +pub fn init(allocator: mem.Allocator) !Self { + const decompressor = compress.deflate.decompressor; + const in_bytes = @embedFile("gencat"); + var in_fbs = std.io.fixedBufferStream(in_bytes); + var in_decomp = try decompressor(allocator, in_fbs.reader(), null); + defer in_decomp.deinit(); + var reader = in_decomp.reader(); + + const endian = builtin.cpu.arch.endian(); + + var self = Self{ .allocator = allocator }; + + const s1_len: u16 = try reader.readInt(u16, endian); + self.s1 = try allocator.alloc(u16, s1_len); + for (0..s1_len) |i| self.s1[i] = try reader.readInt(u16, endian); + + const s2_len: u16 = try reader.readInt(u16, endian); + self.s2 = try allocator.alloc(u5, s2_len); + for (0..s2_len) |i| self.s2[i] = @intCast(try reader.readInt(u8, endian)); + + const s3_len: u16 = try reader.readInt(u8, endian); + self.s3 = try allocator.alloc(u5, s3_len); + for (0..s3_len) |i| self.s3[i] = @intCast(try reader.readInt(u8, endian)); + + return self; +} + +pub fn deinit(self: *Self) void { + self.allocator.free(self.s1); + self.allocator.free(self.s2); + self.allocator.free(self.s3); +} + +/// Lookup the General Category for `cp`. +pub inline fn gc(self: Self, cp: u21) Gc { + return @enumFromInt(self.s3[self.s2[self.s1[cp >> 8] + (cp & 0xff)]]); +} diff --git a/src/HangulData.zig b/src/HangulData.zig index 4d80c99..b97424c 100644 --- a/src/HangulData.zig +++ b/src/HangulData.zig @@ -15,7 +15,7 @@ pub const Syllable = enum { allocator: mem.Allocator, s1: []u16 = undefined, -s2: []Syllable = undefined, +s2: []u3 = undefined, const Self = @This(); @@ -35,8 +35,8 @@ pub fn init(allocator: mem.Allocator) !Self { for (0..stage_1_len) |i| self.s1[i] = try reader.readInt(u16, endian); const stage_2_len: u16 = try reader.readInt(u16, endian); - self.s2 = try allocator.alloc(Syllable, stage_2_len); - for (0..stage_2_len) |i| self.s2[i] = @enumFromInt(try reader.readInt(u8, endian)); + self.s2 = try allocator.alloc(u3, stage_2_len); + for (0..stage_2_len) |i| self.s2[i] = @intCast(try reader.readInt(u8, endian)); return self; } @@ -48,5 +48,5 @@ pub fn deinit(self: *Self) void { /// Returns the Hangul syllable type for `cp`. pub inline fn syllable(self: Self, cp: u21) Syllable { - return self.s2[self.s1[cp >> 8] + (cp & 0xff)]; + return @enumFromInt(self.s2[self.s1[cp >> 8] + (cp & 0xff)]); } diff --git a/src/main.zig b/src/main.zig index 0f1aab5..c521c4f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -11,14 +11,16 @@ const std = @import("std"); // const strWidth = @import("display_width").strWidth; // const CodePointIterator = @import("ziglyph").CodePointIterator; -// const CodePointIterator = @import("code_point").Iterator; +const CodePointIterator = @import("code_point").Iterator; // const ascii = @import("ascii"); // const ascii = std.ascii; // const Normalizer = @import("ziglyph").Normalizer; -const NormData = @import("Normalizer").NormData; -const Normalizer = @import("Normalizer"); +// const NormData = @import("Normalizer").NormData; +// const Normalizer = @import("Normalizer"); + +const GenCatData = @import("GenCatData"); pub fn main() !void { var args_iter = std.process.args(); @@ -32,16 +34,19 @@ pub fn main() !void { const input = try std.fs.cwd().readFileAlloc(allocator, in_path, std.math.maxInt(u32)); defer allocator.free(input); - var data = try NormData.init(allocator); - defer data.deinit(); - var n = Normalizer{ .norm_data = &data }; + // var data = try NormData.init(allocator); + // defer data.deinit(); + // var n = Normalizer{ .norm_data = &data }; // var n = try Normalizer.init(allocator); // defer n.deinit(); + var gencat_data = try GenCatData.init(allocator); + defer gencat_data.deinit(); + // var iter = GraphemeIterator.init(input, &data); // defer iter.deinit(); - // var iter = CodePointIterator{ .bytes = input }; - var iter = std.mem.splitScalar(u8, input, '\n'); + var iter = CodePointIterator{ .bytes = input }; + // var iter = std.mem.splitScalar(u8, input, '\n'); var result: usize = 0; // var result: isize = 0; @@ -50,10 +55,14 @@ pub fn main() !void { // while (iter.next()) |cp| result += codePointWidth(@intCast(cp.code)); // while (iter.next()) |_| result += 1; // while (iter.next()) |line| result += strWidth(line, &data); - while (iter.next()) |line| { - const nfc = try n.nfc(allocator, line); - result += nfc.slice.len; - // nfc.deinit(); + // while (iter.next()) |line| { + // const nfc = try n.nfc(allocator, line); + // result += nfc.slice.len; + // // nfc.deinit(); + // } + while (iter.next()) |cp| { + if (cp.code == 'É') std.debug.print("`{u}` Gc: {s}\n", .{ cp.code, @tagName(gencat_data.gc(cp.code)) }); + result += 1; } std.debug.print("result: {}, took: {}\n", .{ result, timer.lap() / std.time.ns_per_ms }); -- cgit v1.2.3