new lexer

This commit is contained in:
Peterino2 2026-11-25 22:50:40 -07:00
parent 687eb5930e
commit 36a81bbc87
1 changed files with 198 additions and 348 deletions

View File

@ -1,348 +1,3 @@
const Module = struct {
contents: []const u8,
fileName: []const u8,
backing: std.mem.Allocator,
arena: std.heap.ArenaAllocator,
enums: std.ArrayList(EnumDefnition) = .empty,
writing: ?WritingType = null,
const WritingType = union {
_enum: *EnumDefnition,
// _struct: *StructDefinition,
};
const EnumDefnition = struct {
name: []const u8,
values: std.ArrayList(EnumValue),
docstring: ?[]const u8,
backingType: BuiltinType = ._int,
allowAnyInt: bool = false,
bodyIndent: usize,
_nextvalue: i64 = 0,
};
const EnumValue = struct {
name: []const u8,
value: i64,
docstring: ?[]const u8 = null,
};
const BuiltinType = enum {
_usize,
_int,
_opaque,
_i8,
_u8,
_i32,
_u32,
_i64,
_u64,
};
const State = enum {
root,
comment,
docstring,
module,
_enum,
_struct,
_function,
};
const ParserState = struct {
fileName: []const u8,
contents: []const u8,
state: State = .root,
commentStart: ?usize = null,
commentEnd: usize = 0,
lineCount: usize = 0,
lineLen: usize = 0,
lineStart: usize = 0,
indentCount: usize = 0,
cursor: usize = 0, // used pretty much just for tracking
var psbuf: [4096]u8 = undefined;
pub fn positionErrorString(self: @This()) []const u8 {
var w = std.Io.Writer.fixed(&psbuf);
w.print(
"parser error: pos:{d} in {s}:{d}> \n",
.{ self.cursor, self.fileName, self.lineCount },
) catch return "BAD WRITE";
w.writeAll(std.mem.trim(
u8,
self.contents[self.lineStart .. self.lineStart + self.lineLen],
"\r\n",
)) catch return "BAD WRITE";
w.writeByte('\n') catch return "BAD WRITE";
_ = w.splatByte(' ', self.cursor) catch return "BAD WRITE";
w.writeByte('^') catch return "BAD WRITE";
return w.buffered();
}
};
pub fn parse(self: *@This(), allocator: std.mem.Allocator, filename: []const u8, contents: []const u8) !void {
self.* = .{
.contents = contents,
.fileName = filename,
.arena = std.heap.ArenaAllocator.init(allocator),
.backing = allocator,
};
var tok = mem.tokenizeScalar(u8, contents, '\n');
var state: ParserState = .{ .contents = contents, .fileName = filename };
// comments which are standalone without a space get grouped into one comment block
// comments which are trailing on the same line are used as a docstring only if no previous
// block has a comment
while (tok.next()) |line| {
state.lineCount += 1;
state.lineLen = line.len;
state.lineStart = tok.index - line.len;
// log.debug("\n{d}: {s}", .{ lineCount, line });
const commentIndex = mem.findScalar(u8, line, '#'); // split the comment
//
state.indentCount = countIndent(line);
const statement = mem.trim(u8, if (commentIndex) |ci| line[0..ci][state.indentCount * 4 ..] else line[state.indentCount * 4 ..], " ");
const comment = if (commentIndex) |ci| line[ci..] else "";
state.cursor = state.indentCount * 4;
if (statement.len != 0) {
state.commentEnd = tok.index - line.len;
try self.parseStatement(&state, statement, comment);
state.commentStart = null; // consume the comment
}
if (comment.len != 0) {
if (statement.len == 0) {
if (state.commentStart == null)
state.commentStart = tok.index - line.len; // recover the line start
state.commentEnd = tok.index;
}
}
if (commentIndex == null)
state.commentStart = null;
// log.debug(" (statement: {s}) (comment: ({s})", .{ statement, comment });
// remove when we're solid
if (state.lineCount >= 1200) return error.LinesTooLong;
}
}
fn countIndent(s: []const u8) usize {
var x = s;
var i: usize = 0;
while (mem.startsWith(u8, x, " ")) {
x = x[4..];
i += 1;
}
return i;
}
fn gpa(self: *@This()) mem.Allocator {
return self.arena.allocator();
}
fn beginEnum(self: *@This(), state: *ParserState, statement: []const u8, docstring: ?[]const u8) !void {
state.state = ._enum;
const new = try self.enums.addOne(self.gpa());
new.* = .{ .docstring = docstring, .bodyIndent = state.indentCount + 1, .values = .empty, .name = "@anonymous" };
self.writing = .{ ._enum = new };
new.bodyIndent = state.indentCount + 1;
new.docstring = docstring;
var split = mem.splitAny(u8, statement, " ");
var i: usize = 0;
while (split.next()) |x| {
if (x.len > 0) {
if (i == 1) {
try ensureValidLabel(x);
new.name = x;
}
i += 1;
}
}
}
fn ensureValidLabel(label: []const u8) !void {
if (label.len == 0) return error.InvalidLabel;
for (label) |c| {
switch (c) {
'a'...'z', 'A'...'Z', '0'...'9', '_' => {},
else => {
return error.InvalidLabel;
},
}
}
}
fn splitWhitespaces(statement: []const u8, vector: [][]const u8) ![][]const u8 {
var tok = mem.tokenizeScalar(u8, statement, ' ');
var j: usize = 0;
while (tok.next()) |i| {
if (i.len == 0) continue;
if (j >= vector.len) return error.OutOfMemory;
vector[j] = i;
j += 1;
}
return vector[0..j];
}
const Directive = enum {
backing,
import,
output,
any,
pub fn get(x: []const u8) ?@This() {
const typeinfo = @typeInfo(@This()).@"enum";
inline for (typeinfo.field_names, 0..) |fname, i| {
if (mem.eql(u8, x, "@" ++ fname))
return @fromBackingInt(@intCast(typeinfo.field_values[i]));
}
return null;
}
};
fn eql(a: []const u8, b: []const u8) bool {
return mem.eql(u8, a, b);
}
fn parseInt(x: []const u8) ?i64 {
return std.fmt.parseInt(i64, x, 0) catch null;
}
fn getBuiltinType(x: []const u8) ?BuiltinType {
const ti = @typeInfo(BuiltinType).@"enum";
inline for (ti.field_names, 0..) |fieldname, i| {
if (eql(fieldname[1..], x))
return @fromBackingInt(@intCast(i));
}
return null;
}
fn parseActiveEnum(self: *@This(), state: *ParserState, statement: []const u8, docstring: ?[]const u8) !void {
const activeEnum = self.writing.?._enum;
log.debug("(enum: {s}) (statement: '{s}') (docstring: {?s})", .{ activeEnum.name, statement, docstring });
var b: [32][]const u8 = undefined;
const toks = try splitWhitespaces(statement, &b);
if (statement[0] == '@') {
if (Directive.get(toks[0])) |d| {
switch (d) {
.any => {
activeEnum.allowAnyInt = true;
},
.backing => {
if (toks.len != 2) return error.MalformedDirective;
if (getBuiltinType(toks[1])) |builtintype| {
switch (builtintype) {
._opaque => return error.InvalidBackingType,
else => {
activeEnum.backingType = builtintype;
},
}
}
},
else => return error.UnexpectedDirective,
}
log.debug(" (directive:{s})", .{@tagName(d)});
} else {
self.perror("unexpected directive", state);
return error.CompileError;
}
} else {
switch (toks.len) {
1 => {
log.debug(" (addstatement name:{s} value:{d})", .{ toks[0], activeEnum._nextvalue });
try activeEnum.values.append(self.arena.allocator(), .{
.name = toks[0],
.value = activeEnum._nextvalue,
.docstring = docstring,
});
activeEnum._nextvalue += 1;
},
3 => {
if (!eql(toks[1], "=")) return error.UnexpectedToken;
const results = .{ toks[0], parseInt(toks[2]) orelse return error.UnexpectedToken };
log.debug(" (addstatement name:{s} value:{d} [explicit])", .{ results[0], results[1] });
try activeEnum.values.append(self.arena.allocator(), .{
.name = results[0],
.value = results[1],
.docstring = docstring,
});
activeEnum._nextvalue = results[1] + 1;
},
else => {},
}
}
}
fn endEnum(self: @This(), state: *ParserState) !void {
state.state = .root;
const last = &self.enums.items[self.enums.items.len - 1];
log.debug("(addenum {s}: docstring: {s} values:{d} backingType:{})", .{ last.name, if (last.docstring != null) "yes" else "no", last.values.items.len, last.backingType });
}
fn perror(self: @This(), string: []const u8, state: *ParserState) void {
_ = self;
log.err("{s}", .{string});
log.err("{s}", .{state.positionErrorString()});
}
pub fn parseStatement(self: *@This(), state: *ParserState, statement: []const u8, comment: []const u8) !void {
const doc = blk: {
if (state.commentStart) |cs| {
break :blk state.contents[cs..state.commentEnd];
}
if (comment.len > 0) break :blk comment;
break :blk "";
};
// log.debug(" docstring: len({d})] \n'{s}'", .{ doc.len, doc });
// docstring ready, start parsing the statements
switch (state.state) {
.root => {
if (mem.startsWith(u8, statement, "enum")) {
try self.beginEnum(state, statement, if (doc.len > 0) doc else null);
}
},
._enum => {
const activeEnum = self.writing.?._enum;
if (state.indentCount < self.writing.?._enum.bodyIndent) {
try self.endEnum(state);
} else if (state.indentCount != activeEnum.bodyIndent) {
self.perror("unexpected indent", state);
log.err("unpexected indent {s}", .{state.positionErrorString()});
return error.ParserFailed;
} else {
try self.parseActiveEnum(state, statement, comment);
}
},
else => {
log.debug("not implemented yet {s}", .{@tagName(state.state)});
},
}
}
pub fn deinit(self: *@This()) void {
self.arena.deinit();
}
};
// normalizes a buffer in-place
fn normalizeContents(buffer: []u8) []u8 {
var cursor: usize = 0;
@ -363,16 +18,211 @@ fn normalizeContents(buffer: []u8) []u8 {
return buffer[0..wcursor];
}
const BuiltinType = enum {
_usize,
_int,
_opaque,
_i8,
_u8,
_i32,
_u32,
_i64,
_u64,
};
const StructDefinition = struct {
name: []const u8,
fields: std.ArrayList(Field),
};
const FunctionDefinition = struct {
name: []const u8,
args: std.ArrayList(Field),
returnType: TypeRef,
};
const TypeRef = union {
@"struct": u32,
@"enum": u32,
};
const Field = struct {
name: []const u8,
typeReference: TypeRef,
docstring: ?[]const u8 = null,
};
const EnumDefnition = struct {
name: []const u8,
values: std.ArrayList(EnumValue),
docstring: ?[]const u8,
backingType: BuiltinType = ._int,
allowAnyInt: bool = false,
};
const EnumValue = struct {
name: []const u8,
value: i64,
docstring: ?[]const u8 = null,
};
fn eql(a: []const u8, b: []const u8) bool {
return mem.eql(u8, a, b);
}
fn parseInt(x: []const u8) ?i64 {
return std.fmt.parseInt(i64, x, 0) catch null;
}
const Token = struct {
start: u32,
end: u32,
tokenKind: union { term: TerminalKind, label: void },
fn slice(self: @This(), contents: []const u8) []const u8 {
return contents[self.start..self.end];
}
};
pub const Line = struct {
num: u32,
offset: u32,
contents: []const u8, // sans \n
tokens: []Token,
docstring: ?[]const u8, // leading docstring without a space dominates trailing comment as docstring
indent: u8,
};
const terminals: []const []const u8 = &.{ "->", ";", ":", ")", "(", ">", "<", "[", "]" };
const TerminalKind = enum { arrow, semicolon, colon, rparen, lparen, rangle, langle, lsqbrack, rsqbrack };
// new technique we define all structures and enums and command types then just a single recursive view based descender
pub const Module = struct {
enums: ArrayList(EnumDefnition) = .empty,
structs: ArrayList(StructDefinition) = .empty,
functions: ArrayList(FunctionDefinition) = .empty,
gpa: std.mem.Allocator,
lines: []Line,
file: []const u8,
contents: []const u8,
fn countIndent(x: []const u8) u8 {
var s = x;
var i: u8 = 0;
while (mem.startsWith(u8, s, " ")) {
s = s[4..];
i += 1;
}
return i;
}
const Tokenizer = struct {
line: []const u8,
cursor: u32,
fn init(line: []const u8) @This() {
return .{ .cursor = 0, .line = line };
}
fn isLabelChar(x: u8) bool {
switch (x) {
'a'...'z', 'A'...'Z', '_', '0'...'9' => return true,
else => return false,
}
}
pub fn next(self: *@This()) ?Token {
while (self.cursor < self.line.len and self.line[self.cursor] == ' ') : (self.cursor += 1) {}
if (self.cursor >= self.line.len) return null;
switch (self.line[self.cursor]) {
'a'...'z', 'A'...'Z', '_' => {
var end: u32 = self.cursor;
while (end < self.line.len and isLabelChar(self.line[end])) : (end += 1) {}
const tok = Token{ .start = self.cursor, .end = end, .tokenKind = .{ .label = {} } };
self.cursor = end;
return tok;
},
else => {
for (terminals, 0..) |t, i| {
if (mem.startsWith(u8, self.line[self.cursor..], t)) {
const tok: Token = .{
.start = self.cursor,
.end = self.cursor + @as(u32, @intCast(t.len)),
.tokenKind = .{ .term = @fromBackingInt(@intCast(i)) },
};
self.cursor += @intCast(t.len);
return tok;
}
}
},
}
return null;
}
};
fn tokenize(gpa: std.mem.Allocator, line: []const u8) ![]Token {
var rvl: ArrayList(Token) = .empty;
var tokenizer = Tokenizer.init(line);
while (tokenizer.next()) |n| {
try rvl.append(gpa, n);
}
return try rvl.toOwnedSlice(gpa);
}
pub fn lex(self: *@This(), gpa: std.mem.Allocator, file: []const u8, contents: []const u8) !void {
self.* = .{
.file = file,
.contents = contents,
.gpa = gpa,
.lines = undefined,
};
var lines: std.ArrayList(Line) = .empty;
var toks = mem.tokenizeScalar(u8, contents, '\n');
var linenum: u32 = 0;
while (toks.next()) |line| {
linenum += 1;
log.info("(line: {s})", .{line});
const nl: Line = .{
.offset = @intCast(toks.index - line.len),
.contents = line,
.indent = countIndent(line),
.docstring = null,
.tokens = try tokenize(self.gpa, line),
.num = linenum,
};
for (nl.tokens) |tok| {
log.info(" (token: {s})", .{tok.slice(nl.contents)});
}
}
self.lines = try lines.toOwnedSlice(gpa);
}
pub fn parse(self: *@This()) !void {
_ = self;
}
};
pub fn compile(io: std.Io, allocator: std.mem.Allocator, path: []const u8) !void {
const rawf = try std.Io.Dir.cwd().readFileAlloc(io, path, allocator, .unlimited);
const normalized = normalizeContents(rawf);
var toks: Module = undefined;
try toks.parse(allocator, path, normalized);
defer toks.deinit();
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var mod: Module = undefined;
try mod.lex(arena.allocator(), path, normalized);
try mod.parse();
}
const log = std.log.scoped(.tad);
const std = @import("std");
const ArrayList = std.ArrayList;
const mem = std.mem;