Files
one/generator.v
2026-02-06 11:15:44 +01:00

287 lines
6.7 KiB
V

module main
import strings
import os
struct Generator {
mut:
symbols SymbolTable
out strings.Builder
}
fn mangle_var(name string) string {
return 'one_var_${name}'
}
fn mangle_func(name string) string {
if name == 'main' {return 'main'}
return 'one_func_${name}'
}
fn mangle_struct(name string) string {
return 'one_class_${name}_'
}
fn get_type_format(type string) string {
return match type {
'int', 'bool' {'d'}
'real' {'f'}
'string' {'s'}
else {panic("invalid type to print")}
}
}
fn (mut g Generator) get_print_label(expr Expr) string {
return match expr {
Variable { expr.name }
MemberAccess {
"${g.get_print_label(expr.from)}.${expr.member}"
}
else { "" }
}
}
fn (mut g Generator) get_c_type(typ string) string {
return match typ {
'real' {'float'}
'int' {'int32_t'}
'string' {'char*'}
else {typ}
}
}
fn (mut g Generator) mangle_if_class(name string) string {
if g.symbols.lookup_class(name) != none {
return 'struct ${mangle_struct(name)}'
}
return name
}
// thank google gemini for this one, I genuinely did not have the mental strength to
// think this at 9pm
fn (mut g Generator) gen_class_print_func(stmt ClassDecl) {
struct_name := mangle_struct(stmt.name)
g.out.writeln('void print_${struct_name}(struct ${struct_name} s, int indent) {')
g.out.writeln('printf("${stmt.name} {\\n");')
for member in stmt.members {
g.out.writeln('for(int i=0; i<indent + 1; i++) printf(" ");')
g.out.write_string('printf("${member.name}: ");')
if g.symbols.lookup_class(member.type) != none {
inner_struct_name := mangle_struct(member.type)
g.out.writeln('print_${inner_struct_name}(s.${member.name}, indent + 1);')
} else {
format := get_type_format(member.type)
g.out.writeln('printf("%${format}\\n", s.${member.name});')
}
}
g.out.writeln('for(int i=0; i<indent; i++) printf(" ");')
g.out.writeln('printf("}\");')
g.out.writeln('}')
}
fn (mut g Generator) gen_stmt(stmt Stmt) {
match stmt {
VarDecl {
c_type := g.mangle_if_class(g.get_c_type(stmt.type))
if stmt.const {
g.out.write_string('const ')
}
g.out.write_string('${c_type} ${mangle_var(stmt.name)} = ')
g.gen_expr(stmt.value)
g.out.writeln(';')
}
ExprStmt {
g.gen_expr(stmt.expr)
g.out.writeln(';')
}
ReturnStmt {
g.out.write_string('return ')
g.gen_expr(stmt.expr)
g.out.writeln(';')
}
Block {
g.out.writeln('{')
for inner_stmt in stmt.stmts {
g.gen_stmt(inner_stmt)
}
g.out.writeln('}')
}
FuncDecl {
dump(stmt.ret_type)
c_type := g.mangle_if_class(g.get_c_type(stmt.ret_type))
g.out.write_string('${c_type} ${mangle_func(stmt.name)}(')
for param in stmt.params {
g.gen_stmt(param)
if param != stmt.params[stmt.params.len-1]{
g.out.write_string(', ')
}
}
g.out.write_string(')')
g.gen_stmt(stmt.block)
}
Param {
c_type := g.mangle_if_class(g.get_c_type(stmt.type))
g.out.write_string('${c_type} ${mangle_var(stmt.name)}')
}
ClassDecl {
g.out.writeln('struct ${mangle_struct(stmt.name)} {')
for member in stmt.members {
g.gen_expr(member)
g.out.writeln(';')
}
g.out.writeln('};')
g.gen_class_print_func(stmt)
}
}
}
fn (mut g Generator) gen_expr(expr Expr) {
match expr {
RealLiteral {
g.out.write_string(expr.val.str())
}
IntegerLiteral {
g.out.write_string(expr.val.str())
}
BoolLiteral {
g.out.write_string(expr.val.str())
}
StringLiteral {
g.out.write_string('\"${expr.val}\"')
}
Variable {
g.out.write_string(mangle_var(expr.name))
}
UnaryExpr {
g.out.write_string('(${mangle_var(expr.ident)}${expr.op})')
}
BinaryExpr {
g.out.write_string('(')
g.gen_expr(expr.left)
g.out.write_string(' ${expr.op} ')
g.gen_expr(expr.right)
g.out.write_string(')')
}
PrintExpr {
mut i := 0;
for i < expr.exprs.len {
inner_expr := expr.exprs[i];
expr_type := expr.types[i];
label := g.get_print_label(inner_expr);
if g.symbols.lookup_class(expr_type) != none {
class_name := mangle_struct(expr_type)
/*if label != "" {
g.out.write_string('${label}: ");')
}*/
g.out.write_string('print_${class_name}(')
g.gen_expr(inner_expr)
g.out.write_string(', 0);')
} else {
g.out.write_string('printf(\"')
dump(label);
if label != "" {
g.out.write_string('${label}')
g.out.write_string(': ');
}
format := get_type_format(expr_type)
g.out.write_string('%${format}\", ')
g.gen_expr(inner_expr)
g.out.write_string(');')
}
i++;
if i < expr.exprs.len {
g.out.write_string('printf(\", \");')
}
}
g.out.write_string('printf(\"\\n\");\n')
}
TypeCast {
c_type := g.mangle_if_class(g.get_c_type(expr.type))
g.out.write_string('((${c_type})')
g.gen_expr(expr.expr)
g.out.write_string(')')
}
ParenExpr {
g.out.write_string('(')
g.gen_expr(expr.expr)
g.out.write_string(')')
}
FnCall {
g.out.write_string('${mangle_func(expr.name)}(')
for arg in expr.args {
g.gen_expr(arg)
if arg != expr.args[expr.args.len-1]{
g.out.write_string(', ')
}
}
g.out.write_string(')')
}
ClassMember {
c_type := g.mangle_if_class(g.get_c_type(expr.type))
g.out.write_string('${c_type} ${expr.name}')
}
ClassInstantiation {
g.out.write_string('(struct ${mangle_struct(expr.name)}){')
for m_expr in expr.member_values {
g.gen_expr(m_expr)
if m_expr != expr.member_values[expr.member_values.len - 1] {
g.out.write_string(', ')
}
}
g.out.write_string('}')
}
MemberAccess {
g.gen_expr(expr.from)
g.out.write_string('.${expr.member}')
}
else {panic("Unimplemented expression")}
}
}
fn (mut g Generator) gen_c(program []Stmt) string {
g.out.writeln('#include <stdio.h>')
g.out.writeln('#include <stdbool.h>')
g.out.writeln('#include <stdint.h>')
//g.out.writeln('typedef struct __one_string_builtin__ {\nchar* string;\nint len;\n} string;')
for stmt in program {
g.gen_stmt(stmt)
}
return g.out.str()
}
fn compile(c_code string, output_name string, keep_c bool, compiler string) {
c_file := 'middle_c.c'
os.write_file(c_file, c_code) or {
eprintln('Failed to write C file: $err')
return
}
cmd := match compiler {
'clang' {'clang ${c_file} -o ${output_name} -O2'}
'gcc' {'gcc ${c_file} -o ${output_name} -O2'}
else {panic("Invalid compiler")}
}
println('Executing: ${cmd}')
result := os.execute(cmd)
if result.exit_code != 0 {
eprintln('${compiler} Compilation Failed:')
eprintln(result.output)
} else {
println('Compilation successful! Binary created: $output_name')
if !keep_c {
os.rm(c_file) or { }
}
}
}