tadpole/engine/tools/tad/tad.zig

847 lines
28 KiB
Zig

// normalizes a buffer in-place
fn normalizeContents(buffer: []u8) []u8 {
var cursor: usize = 0;
var wcursor: usize = 0;
while (cursor < buffer.len) : (cursor += 1) {
if (cursor + 2 > buffer.len) {
continue;
}
if (mem.eql(u8, buffer[cursor .. cursor + 2], "\r\n")) {
buffer[wcursor] = '\n';
cursor += 1;
wcursor += 1;
continue;
}
buffer[wcursor] = buffer[cursor];
wcursor += 1;
}
return buffer[0..wcursor];
}
const BuiltinType = enum(u8) { usize, int, uint, @"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) = .empty,
returnType: TypeRef,
isInstance: bool, // if true this function definition is a function pointer type
};
pub const PointerType = struct {
alignment: u8,
size: u32,
isConst: bool,
target: TypeId,
};
pub const TypeId = u32;
pub const ResolvedType = struct {
kind: union(enum(u8)) {
@"struct": u32,
@"enum": u32,
@"fn": u32,
fnptr: u32,
builtin: BuiltinType,
pointer: PointerType,
},
};
pub const TypeRef = struct {
lineRef: u32,
tokens: []Token,
resolved: ?TypeId = null,
pub fn format(self: @This(), writer: *std.Io.Writer) !void {
try writer.print("(type line:{d}", .{self.lineRef});
for (self.tokens) |tok| {
try writer.print(" {s}", .{@tagName(tok.tokenKind)});
}
try writer.writeByte(')');
}
};
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 IntegerPresentation = enum { decimal, hex };
const EnumValue = struct {
name: []const u8,
value: i64,
docstring: ?[]const u8 = null,
presentation: IntegerPresentation,
pub fn format(self: @This(), writer: *std.Io.Writer) !void {
try writer.print("(value name:{s} value:{d} presentation:{}", .{ self.name, self.value, @tagName(self.presentation) });
try writer.writeByte(')');
}
};
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 Keyword = enum { @"fn", @"struct", @"enum", module, fnptr, alias, c_ptr, @"const" };
const TokenKind = union(enum(u8)) {
term: TerminalKind,
label: void,
comment: []const u8,
directive: Directive,
keyword: Keyword,
integerValue: struct { i64, IntegerPresentation },
floatValue: f64,
};
pub const Token = struct {
start: u32,
end: u32,
tokenKind: TokenKind,
fn slice(self: @This(), contents: []const u8) []const u8 {
return contents[self.start..self.end];
}
};
pub const TokenMatcher = struct {
search: TokenKind,
query: []const Query,
const Search = struct {
tok: TokenKind,
query: Query,
pub fn match(self: @This(), tok: TokenKind) bool {
if (self.query == .anything) return true; // anything means it'll match any token
if (self.tok != tok) return false; // token kind doesn't match
switch (self.tok) {
.comment => |x| {
return mem.eql(u8, x, tok.comment);
},
.directive => |x| {
return x == tok.directive;
},
.floatValue => |x| {
return std.math.approxEqAbs(f64, x, tok.floatValue, std.math.floatEps(f64));
},
.floatRange => |r| {
switch (r[3]) {
.inclusive_inclusive => {
return (tok.floatValue > r[0] and tok.floatValue < r[1]);
},
.inclusive_exclusive => {
return (tok.floatValue > r[0] and tok.floatValue < r[1]);
},
.exclusive_inclusive => {
return (tok.floatValue > r[0] and tok.floatValue < r[1]);
},
.exclusive_exclusive => {
return (tok.floatValue > r[0] and tok.floatValue < r[1]);
},
}
},
}
}
};
pub const Query = union {
integer: i64,
integerRange: struct { i64, i64 },
floatRange: struct { f64, f64, RangeMode },
floatTolerance: struct { f64, f64 }, // low, then high. in that order
strings: []const []const u8,
anything: void,
pub const RangeMode = enum {
inclusive_inclusive,
inclusive_exclusive,
exclusive_exclusive,
exclusive_inclusive,
pub const default: @This() = .inclusive_exclusive;
};
};
// returns list of tokens
pub fn matchTokenList(self: @This(), tokens: []const Token, gpa: mem.Allocator) ![]u32 {
if (self.search.len != self.query.len) return error.MismatchedQueryLength;
var rv: std.ArrayList(u32) = .empty;
var i: usize = 0;
while (i < tokens.len) : (i += 1) {
const q = self.query[i];
const t = self.search[i];
_ = q;
_ = t;
}
return try rv.toOwnedSlice(gpa);
}
};
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, equals };
const Directive = enum {
import,
backing,
};
const directives = @typeInfo(Directive).@"enum".field_names;
pub const Module = struct {
enums: ArrayList(EnumDefnition) = .empty,
aliases: ArrayList(AliasDefinition) = .empty,
structs: ArrayList(StructDefinition) = .empty,
functions: ArrayList(FunctionDefinition) = .empty,
module: ?ModuleDefinition = null,
typeRefs: ArrayList(TypeRef) = .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,
}
}
fn checkKeyword(segment: []const u8) ?Keyword {
const keywords = @typeInfo(Keyword).@"enum".field_names;
inline for (keywords, 0..) |k, i| {
if (mem.eql(u8, segment, k)) {
const kw: Keyword = @fromBackingInt(@intCast(i));
return kw;
}
}
return null;
}
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]) {
'0'...'9' => {
const start = self.cursor;
var e = self.cursor;
while (e < self.line.len and !(std.ascii.isWhitespace(self.line[e]) or (self.line[e] == '\n'))) {
e += 1;
}
const span = self.line[start..e];
const value = try std.fmt.parseInt(i64, span, 0);
var radix: IntegerPresentation = .decimal;
if (span.len > 2 and std.mem.eql(u8, span[0..2], "0x")) {
radix = .hex;
}
self.cursor = e;
return Token{
.start = start,
.end = e,
.tokenKind = .{ .integerValue = .{ value, radix } },
};
},
'@' => {
// directive?
const start = self.cursor;
const c = self.cursor + 1;
const directive = blk: {
for (directives, 0..) |d, i| {
if (mem.startsWith(u8, self.line[c..], d)) {
const directiveKind: Directive = @fromBackingInt(@intCast(i));
break :blk directiveKind;
}
}
return error.UnrecognizedDirective;
};
self.cursor = c;
self.cursor += @intCast(@tagName(directive).len);
return Token{
.start = start,
.end = self.cursor,
.tokenKind = .{ .directive = directive },
};
},
'a'...'z', 'A'...'Z', '_' => {
var end: u32 = self.cursor;
while (end < self.line.len and isLabelChar(self.line[end])) : (end += 1) {}
var tok = Token{ .start = self.cursor, .end = end, .tokenKind = .{ .label = {} } };
self.cursor = end;
if (checkKeyword(self.line[tok.start..tok.end])) |kw| {
tok.tokenKind = .{ .keyword = kw };
}
return tok;
},
'#' => {
// gobble the comments
const start = self.cursor;
self.cursor = @intCast(self.line.len);
return Token{ .start = start, .end = self.cursor, .tokenKind = .{
.comment = self.line[start..self.cursor],
} };
},
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 (try 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 {
const log = log_tokenizer;
self.* = .{
.file = file,
.contents = contents,
.gpa = gpa,
.module = null,
.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}]: {s})",
.{
@tagName(tok.tokenKind),
tok.slice(nl.contents),
},
);
}
try lines.append(gpa, nl);
}
self.lines = try lines.toOwnedSlice(gpa);
}
const AliasDefinition = struct {
name: []const u8,
target: TypeRef,
};
const ModuleDefinition = struct {
name: []const u8,
imports: std.ArrayList([]const u8) = .empty,
};
const Definition = union(enum(u8)) {
comment: void, // skip these for now
module: ModuleDefinition, //
@"fn": FunctionDefinition,
@"struct": StructDefinition,
@"enum": EnumDefnition,
alias: AliasDefinition,
pub fn format(self: @This(), writer: *std.Io.Writer) !void {
switch (self) {
.alias => |alias| {
try writer.print("(alias {s} {f})", .{ alias.name, alias.target });
},
.module => |mod| {
try writer.print("(module", .{});
for (mod.imports.items) |i| {
try writer.print(" import:{s}", .{i});
}
try writer.writeByte(')');
},
.@"struct" => |s| {
try writer.print("(struct {s}", .{s.name});
for (s.fields.items) |i| {
try writer.print("\n field {s}:{f}", .{ i.name, i.typeReference });
}
try writer.writeByte(')');
},
.@"fn" => |f| {
try writer.print("(fn {s} -> {f}", .{ f.name, f.returnType });
for (f.args.items) |i| {
try writer.print("\n arg {s}:{f}", .{ i.name, i.typeReference });
}
try writer.writeByte(')');
},
.comment => {
try writer.print("(comment)", .{});
},
.@"enum" => |x| {
try writer.print("(enum name:{s} values:{d} backing:{d} any:{})", .{
x.name,
x.values.items.len,
x.backingType,
x.allowAnyInt,
});
},
}
}
};
fn isTerminal(token: Token, kind: TerminalKind) bool {
if (token.tokenKind != .term) return false;
if (token.tokenKind.term != kind) return false;
return true;
}
fn expectTerminal(token: Token, kind: TerminalKind) !void {
if (token.tokenKind != .term) return error.ExpectedTerminal;
if (token.tokenKind.term != kind) return error.ExpectedTerminal;
}
fn expectKeyword(token: Token, kind: Keyword) !void {
if (token.tokenKind != .keyword or token.tokenKind.keyword != kind) return error.ExpectedKeyword;
}
fn parseStruct(self: @This(), cursor: *u32) !StructDefinition {
const lineRef = cursor.*;
const line, const body = try self.setupBodyState(cursor, .@"struct");
if (line.tokens.len < 2) return error.MalformedEnum;
if (line.tokens[1].tokenKind != .label) return error.ExpectedLabel;
var s: StructDefinition = .{
.name = line.tokens[1].slice(line.contents),
.fields = .empty,
};
for (body, 1..) |l, i| {
if (l.tokens.len == 0) continue;
switch (l.tokens[0].tokenKind) {
.directive => return error.UnexpectedDirective, // can easily add directives support here
.label => {
try expectTerminal(l.tokens[1], .colon);
const endsInComment = l.tokens[l.tokens.len - 1].tokenKind == .comment;
try s.fields.append(self.gpa, .{
.docstring = null,
.name = l.tokens[0].slice(l.contents),
.typeReference = .{
.lineRef = lineRef + @as(u32, @intCast(i)),
.tokens = l.tokens[2..if (endsInComment) l.tokens.len - 1 else l.tokens.len],
},
});
log_tokenizer.warn("{d} {f}", .{ i, s.fields.last().?.typeReference });
},
.comment => {},
else => return error.UnexpectedStatement,
}
}
return s;
}
fn parseEnum(self: @This(), cursor: *u32) !EnumDefnition {
const line, const body = try self.setupBodyState(cursor, .@"enum");
if (line.tokens.len < 2) return error.MalformedStructDefinition;
if (line.tokens[1].tokenKind != .label) return error.ExpectedLabel;
var s: EnumDefnition = .{
.name = line.tokens[1].slice(line.contents),
.values = .empty,
.docstring = null,
};
var nextValue: i64 = 0;
for (body) |l| {
if (l.tokens.len == 0) continue;
switch (l.tokens[0].tokenKind) {
.directive => |dir| {
switch (dir) {
.backing => {
try expectLabel(l.tokens[1]);
const backing = std.meta.stringToEnum(BuiltinType, l.tokens[1].slice(l.contents)) orelse return error.InvalidBuiltinValue;
s.backingType = backing;
},
else => {
return error.UnexpectedDirective;
},
}
},
.label => {
var radix: IntegerPresentation = .decimal;
if (l.tokens.len > 1) {
if (isTerminal(l.tokens[1], .equals)) {
if (l.tokens[2].tokenKind != .integerValue) return error.ExpectedInteger;
nextValue = l.tokens[2].tokenKind.integerValue[0];
radix = l.tokens[2].tokenKind.integerValue[1];
} else {
return error.UnexpectedToken;
}
}
try s.values.append(self.gpa, .{ .name = l.tokens[0].slice(l.contents), .value = nextValue, .presentation = radix });
nextValue += 1;
},
.comment => {},
else => return error.UnexpectedStatement,
}
}
return s;
}
fn expectLabel(token: Token) !void {
if (token.tokenKind != .label) return error.ExpectedLabel;
}
fn parseFunction(self: @This(), cursor: *u32) !FunctionDefinition {
const lineRef = cursor.*;
const line, const body, const isInstance = try self.setupFunctionBodyState(cursor);
if (line.tokens.len < 4) return error.MalformedFunctionDefinition;
if (line.tokens[1].tokenKind != .label) return error.ExpectedLabel;
try expectTerminal(line.tokens[2], .arrow);
var func: FunctionDefinition = .{
.name = line.tokens[1].slice(line.contents),
.returnType = .{ .lineRef = lineRef, .tokens = line.tokens[3..] },
.isInstance = isInstance,
};
for (body) |l| {
if (l.tokens.len == 0) continue;
switch (l.tokens[0].tokenKind) {
.directive => return error.UnexpectedDirective, // can easily add directives support here
.label => {
try expectTerminal(l.tokens[1], .colon);
const endsInComment = l.tokens[l.tokens.len - 1].tokenKind == .comment;
try func.args.append(self.gpa, .{
.docstring = null,
.name = l.tokens[0].slice(l.contents),
.typeReference = .{
.lineRef = lineRef,
.tokens = l.tokens[2..if (endsInComment) l.tokens.len - 1 else l.tokens.len],
},
});
},
.comment => {},
else => return error.UnexpectedStatement,
}
}
return func;
}
fn setupFunctionBodyState(self: @This(), cursor: *u32) !struct { Line, []Line, bool } {
const lines = self.lines[cursor.*..];
if (lines[0].tokens[0].tokenKind != .keyword) {
return error.ExpectedKeyword;
}
var isInstance: bool = false;
// zig fmt: off
if(lines[0].tokens[0].tokenKind.keyword == .@"fn")
{
if(lines[0].tokens[0].tokenKind.keyword == .fnptr)
isInstance = true;
}
// zig fmt: on
const indent = lines[0].indent + 1;
const body = readBody(lines[1..], indent);
cursor.* += @as(u32, @intCast(body.len));
return .{ lines[0], body, isInstance };
}
fn setupBodyState(self: @This(), cursor: *u32, keyword: Keyword) !struct { Line, []Line } {
const lines = self.lines[cursor.*..];
try expectKeyword(lines[0].tokens[0], keyword);
const indent = lines[0].indent + 1;
const body = readBody(lines[1..], indent);
cursor.* += @as(u32, @intCast(body.len));
return .{ lines[0], body };
}
fn readBody(lines: []Line, indent: u8) []Line {
for (lines, 0..) |line, i| {
if (line.indent < indent)
return lines[0..i];
}
return lines;
}
fn parseAlias(self: @This(), cursor: *u32) !AliasDefinition {
const lineRef = cursor.*;
const line = self.lines[cursor.*];
try expectKeyword(line.tokens[0], .alias);
if (line.tokens[1].tokenKind != .label) return error.ExpectedLabel;
if (line.tokens[2].tokenKind != .term or line.tokens[2].tokenKind.term != .equals) return error.ExpectedToken;
const endsInComment = line.tokens[line.tokens.len - 1].tokenKind == .comment;
return .{
.name = line.tokens[1].slice(line.contents),
.target = .{
.lineRef = lineRef,
.tokens = line.tokens[2..if (endsInComment) line.tokens.len - 1 else line.tokens.len],
},
};
}
fn parseModule(self: @This(), cursor: *u32) !ModuleDefinition {
const log = log_tokenizer;
const line, const body = try self.setupBodyState(cursor, .module);
var mod: ModuleDefinition = .{ .name = line.tokens[0].slice(line.contents) };
for (body) |l| {
if (l.tokens.len == 0) continue;
switch (l.tokens[0].tokenKind) {
.directive => |d| {
switch (d) {
.import => {
try mod.imports.append(self.gpa, l.tokens[1].slice(l.contents));
},
else => return error.UnexpectedDirective,
}
},
.comment => {},
else => return error.UnexpectedStatement,
}
}
for (mod.imports.items) |i| {
log.info(" (module import:{s})", .{i});
}
return mod;
}
pub fn parseLine(self: *@This(), cursor: *u32) !Definition {
const log = log_main;
const lines = self.lines[cursor.*..];
const line = lines[0];
var newdef: Definition = undefined;
switch (line.tokens[0].tokenKind) {
.comment => {
return .{ .comment = {} };
},
.keyword => |kw| {
switch (kw) {
.alias => {
newdef = .{ .alias = try self.parseAlias(cursor) };
try self.aliases.append(self.gpa, newdef.alias);
},
.@"enum" => {
newdef = .{ .@"enum" = try self.parseEnum(cursor) };
try self.enums.append(self.gpa, newdef.@"enum");
},
.fnptr => {
newdef = .{ .@"fn" = try self.parseFunction(cursor) };
try self.functions.append(self.gpa, newdef.@"fn");
},
.@"fn" => {
newdef = .{ .@"fn" = try self.parseFunction(cursor) };
try self.functions.append(self.gpa, newdef.@"fn");
},
.@"struct" => {
newdef = .{ .@"struct" = try self.parseStruct(cursor) };
try self.structs.append(self.gpa, newdef.@"struct");
},
.module => {
newdef = .{ .module = try self.parseModule(cursor) };
self.module = newdef.module;
},
.@"const", .c_ptr => {
return error.UnexpectedKeyword;
},
}
},
else => return error.UnexpectedToken,
}
log.info("{f}", .{newdef});
return newdef;
}
pub fn parse(self: *@This()) !void {
var cursor: u32 = 0;
while (cursor < @as(u32, @intCast(self.lines.len))) {
const line = try self.parseLine(&cursor);
_ = line;
cursor += 1;
}
}
pub const GenerateZigApiOptions = struct {
io: std.Io,
output: []const u8,
};
fn resolveTypeRef(self: *@This(), typeref: TypeRef) !void {
const line = self.lines[typeref.lineRef];
for (typeref.tokens) |tok| {
const x = tok.slice(line.contents);
log_main.warn(" ({s})", .{x});
}
}
// link all references together
pub fn resolve(self: *@This()) !void {
// walk over structs, then function fields in that order
for (self.structs.items) |st| {
log_main.warn("(struct {s})", .{st.name});
for (st.fields.items) |field| {
try self.resolveTypeRef(field.typeReference);
}
}
}
fn fmt(self: *@This(), comptime f: []const u8, a: anytype) ?[]const u8 {
return self.gpa.print(f, a) catch return null;
}
pub fn generateZigApi(self: *@This(), opts: GenerateZigApiOptions) !void {
const basename = std.fs.path.dirname(opts.output) orelse "./";
const dir = try std.Io.Dir.cwd().createDirPathOpen(opts.io, basename, .{});
defer dir.close(opts.io);
const x = self.fmt("{s}{s}", .{ std.fs.path.stem(opts.output), ".zig" }) orelse return error.BadFormat;
var fwb: WriteBuffer = undefined;
try fwb.create(opts.io, dir, x);
defer fwb.close();
const w = fwb.writer();
try zig_generator.generateApi(self, w);
}
};
pub const TadModuleOptions = struct {
io: std.Io,
allocator: std.mem.Allocator,
path: []const u8,
};
pub fn compileAll(opts: TadModuleOptions) !void {
const rawf = try std.Io.Dir.cwd().readFileAlloc(opts.io, opts.path, opts.allocator, .unlimited);
const normalized = normalizeContents(rawf);
var arena = std.heap.ArenaAllocator.init(opts.allocator);
defer arena.deinit();
var mod: Module = undefined;
try mod.lex(arena.allocator(), opts.path, normalized);
try mod.parse();
try mod.resolve(); // resolve all typeRefs
// parse submodules here...
// generate
try mod.generateZigApi(.{ .io = opts.io, .output = "./zig-out/api/core.zig" });
}
const log_tokenizer = std.log.scoped(.tad_tok);
const log_main = std.log.scoped(.tad);
pub const logScopeLevels: []const std.log.ScopeLevel = &[_]std.log.ScopeLevel{
.{ .scope = .tad, .level = .debug },
.{ .scope = .tad_tok, .level = .debug },
} ++ zig_generator.logScopeLevels;
const std = @import("std");
const ArrayList = std.ArrayList;
const mem = std.mem;
const WriteBuffer = @import("../common/WriteBuffer.zig");
const fmt = std.fmt;
const p2 = @import("p2");
const zig_generator = @import("zig-generator.zig");