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.

60 lines
1.5 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, source: Operand } & Data
  5. export type SSA = ASSA<{ source: Operand }> // dest = source
  6. | ASSA<{ op: string }> // dest = op(source)
  7. | ASSA<{ op: string, source1: Operand }> // dest = op(source, source1)
  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. }
  36. export const prettyPrintIR = (ssa: SSA): string => {
  37. let output = ""
  38. if ("source1" in ssa) {
  39. output = `${ssa.dest} = ${ssa.source} ${ssa.op} ${ssa.source1}`
  40. } else if ("op" in ssa) {
  41. output = `${ssa.dest} = ${ssa.op} ${ssa.source}`
  42. } else {
  43. output = `${ssa.dest} = ${ssa.source}`
  44. }
  45. return output
  46. }