88 lines
2.3 KiB
Zig
88 lines
2.3 KiB
Zig
const std = @import("std");
|
|
|
|
pub const CompilationError = error{TypeError};
|
|
|
|
pub const SymbolTable = std.hash_map.StringHashMap(SymbolData);
|
|
|
|
pub const SymbolUnderlyingTypeEnum = enum {
|
|
Integer32,
|
|
Integer64,
|
|
Bool,
|
|
CustomType,
|
|
};
|
|
|
|
pub const SymbolUnderlyingType = union(SymbolUnderlyingTypeEnum) {
|
|
Integer32: void,
|
|
Integer64: void,
|
|
Bool: void,
|
|
CustomType: []const u8,
|
|
};
|
|
|
|
// functions, for our purposes, other than symbols, have:
|
|
// - a return type
|
|
// - TODO parameters
|
|
pub const FunctionSymbol = struct {
|
|
return_type: SymbolUnderlyingType,
|
|
symbols: SymbolTable,
|
|
};
|
|
|
|
// structs are hashmaps pointing to SymbolUnderlyingType
|
|
pub const UnderlyingTypeMap = std.hash_map.StringHashMap(SymbolUnderlyingType);
|
|
|
|
// enums have lists of identifiers
|
|
pub const IdentifierList = std.ArrayList([]const u8);
|
|
|
|
// TODO const
|
|
pub const SymbolType = enum {
|
|
Function,
|
|
Struct,
|
|
Enum,
|
|
};
|
|
|
|
pub const SymbolData = union(SymbolType) {
|
|
Function: FunctionSymbol,
|
|
Struct: UnderlyingTypeMap,
|
|
Enum: IdentifierList,
|
|
};
|
|
|
|
const builtin_type_identifiers = [_][]const u8{ "i32", "i64", "bool" };
|
|
|
|
const builtin_types = [_]SymbolUnderlyingTypeEnum{ .Integer32, .Integer64, .Bool };
|
|
|
|
pub const CompilationContext = struct {
|
|
allocator: *std.mem.Allocator,
|
|
symbol_table: SymbolTable,
|
|
|
|
pub fn init(allocator: *std.mem.Allocator) CompilationContext {
|
|
return CompilationContext{
|
|
.allocator = allocator,
|
|
.symbol_table = SymbolTable.init(allocator),
|
|
};
|
|
}
|
|
|
|
pub fn solveTypeEnum(
|
|
self: *@This(),
|
|
typ_ident: []const u8,
|
|
) SymbolUnderlyingTypeEnum {
|
|
inline for (builtin_type_identifiers) |typ, idx| {
|
|
if (std.mem.eql(u8, typ, typ_ident)) return builtin_types[idx];
|
|
}
|
|
|
|
return .CustomType;
|
|
}
|
|
|
|
pub fn solveType(
|
|
self: *@This(),
|
|
typ_ident: []const u8,
|
|
) SymbolUnderlyingType {
|
|
const typ_enum_val = self.solveTypeEnum(typ_ident);
|
|
|
|
return switch (typ_enum_val) {
|
|
.Integer32 => SymbolUnderlyingType{ .Integer32 = {} },
|
|
.Integer64 => SymbolUnderlyingType{ .Integer64 = {} },
|
|
.Bool => SymbolUnderlyingType{ .Bool = {} },
|
|
.CustomType => SymbolUnderlyingType{ .CustomType = typ_ident },
|
|
};
|
|
}
|
|
};
|