From 9456f4e2b569b393d6c01784a4545b11b32e16ef Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Thu, 24 Apr 2025 15:10:14 +0200 Subject: Implement grammar parser This implements the grammar struct together with some other helpful structures like char-set and character. The grammar struct parses a grammar file and also generates the FIRST and FOLLOWS tables. --- src/character.zig | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/character.zig (limited to 'src/character.zig') diff --git a/src/character.zig b/src/character.zig new file mode 100644 index 0000000..bd11ccd --- /dev/null +++ b/src/character.zig @@ -0,0 +1,38 @@ +const std = @import("std"); + +pub const Character = union(enum) { + const Self = @This(); + + pub const EPSILON: u8 = '_'; + pub const END: u8 = 0; + + epsilon: void, + terminal: u8, + non_terminal: u8, + + pub fn from_u8(c: u8) Self { + if (c == '_') { + return Self { .epsilon = void{} }; + } else if (std.ascii.isUpper(c)) { + return Self { .non_terminal = c }; + } else { + return Self { .terminal = c }; + } + } + + pub fn format( + self: *const Self, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + + switch (self.*) { + .epsilon => _ = try writer.writeAll("ε"), + .terminal => |c| try writer.writeByte(c), + .non_terminal => |c| try writer.writeByte(c), + } + } +}; -- cgit v1.2.3-70-g09d2