A "high-level" language for the Gameboy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

  1. import type { AssignStmt, Expr, Stmt } from "./ast"
  2. // dest <- op(x, y)
  3. type Operand = string | number
  4. type ASSA<Data> = { dest: string } & Data
  5. type SSA = ASSA<{ source: Operand }>
  6. | ASSA<{ source: Operand, op: string }>
  7. | ASSA<{ source1: Operand, op: string, source2: Operand }>
  8. type IRState = {
  9. nextID: number
  10. ssa_stmts: Array<SSA>
  11. }
  12. export const convertIR = (stmts: Array<Stmt>): Array<SSA> => {
  13. const state: IRState = {
  14. nextID: 0,
  15. ssa_stmts: [],
  16. }
  17. stmts.forEach(stmt => {
  18. const ssa_stmts = convertAssignStmt(state, stmt)
  19. state.ssa_stmts.push(...ssa_stmts)
  20. })
  21. return state.ssa_stmts
  22. }
  23. export const convertAssignStmt = (state: IRState, stmt: AssignStmt): Array<SSA> => {
  24. const dest = stmt.args.name
  25. const [source, expr_stmts] = convertExpr(state, stmt.args.expr)
  26. expr_stmts.push({
  27. dest,
  28. source,
  29. })
  30. return expr_stmts
  31. }
  32. export const convertExpr = (state: IRState, expr: Expr): [string, Array<SSA>] => {
  33. const name = `temp${state.nextID++}`
  34. return [name, [{ dest: name, source: expr }]]
  35. }