2019-12-24 20:54:43 +03:00
|
|
|
module cgen
|
|
|
|
|
|
|
|
import (
|
|
|
|
strings
|
|
|
|
compiler2.ast
|
|
|
|
)
|
|
|
|
|
|
|
|
struct Gen {
|
|
|
|
out strings.Builder
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn gen(program ast.Program) {
|
|
|
|
mut g := Gen{out:strings.new_builder(100)}
|
|
|
|
for expr in program.exprs {
|
|
|
|
g.expr(expr)
|
|
|
|
g.writeln('')
|
|
|
|
}
|
|
|
|
println(g.out.str())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (g &Gen) save() {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (g mut Gen) write(s string) {
|
|
|
|
g.out.write(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (g mut Gen) writeln(s string) {
|
|
|
|
g.out.writeln(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Type {
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
string_type = Type{'string'}
|
|
|
|
int_type = Type{'int'}
|
|
|
|
void_type = Type{'void'}
|
|
|
|
)
|
|
|
|
|
2019-12-26 13:27:35 +03:00
|
|
|
fn (g mut Gen) expr(node ast.Expr) {
|
2019-12-24 20:54:43 +03:00
|
|
|
//println('cgen expr()')
|
|
|
|
match node {
|
2019-12-26 13:21:41 +03:00
|
|
|
ast.IntegerLiteral {
|
2019-12-24 20:54:43 +03:00
|
|
|
g.write(it.val.str())
|
|
|
|
}
|
2019-12-26 12:02:38 +03:00
|
|
|
ast.UnaryExpr {
|
|
|
|
g.expr(it.left)
|
|
|
|
g.write(' $it.op ')
|
|
|
|
}
|
2019-12-24 20:54:43 +03:00
|
|
|
ast.StringLiteral {
|
|
|
|
g.write('"$it.val"')
|
|
|
|
}
|
|
|
|
ast.BinaryExpr {
|
2019-12-26 13:27:35 +03:00
|
|
|
g.expr(it.left)
|
2019-12-24 20:54:43 +03:00
|
|
|
match it.op {
|
|
|
|
.plus { g.write(' + ') }
|
|
|
|
.minus { g.write(' - ') }
|
|
|
|
.mul { g.write(' * ') }
|
|
|
|
.div { g.write(' / ') }
|
|
|
|
else {}
|
|
|
|
}
|
2019-12-26 13:27:35 +03:00
|
|
|
g.expr(it.right)
|
|
|
|
// if typ.name != typ2.name {
|
|
|
|
//verror('bad types $typ.name $typ2.name')
|
|
|
|
//}
|
2019-12-24 20:54:43 +03:00
|
|
|
}
|
|
|
|
ast.VarDecl {
|
2019-12-26 13:27:35 +03:00
|
|
|
g.write('$it.typ.name $it.name = ')
|
2019-12-24 20:54:43 +03:00
|
|
|
g.expr(it.expr)
|
|
|
|
g.writeln(';')
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
println('bad node')
|
|
|
|
}
|
|
|
|
}
|
2019-12-26 13:27:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn verror(s string) {
|
|
|
|
println(s)
|
|
|
|
exit(1)
|
2019-12-24 20:54:43 +03:00
|
|
|
}
|
|
|
|
|