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.

75 lines
1.8 KiB

  1. import type { AssignStmt, Expr, Stmt } from "./ast"
  2. type Operand = string | number
  3. type ASSA<Data> = { dest: string, source: Operand } & Data
  4. export type SSACopy = ASSA<{ source: Operand }> // dest = source
  5. export type SSAUnary = ASSA<{ op: string }> // dest = op(source)
  6. export type SSABinary = ASSA<{ op: string, source1: Operand }> // dest = op(source, source1)
  7. export type SSA = SSACopy | SSAUnary | SSABinary
  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 | number, Array<SSA>] => {
  33. if (typeof expr === "number" || typeof expr === "string") {
  34. return [expr, []]
  35. }
  36. const [source, expr_stmts] = convertExpr(state, expr.arg)
  37. const name = `temp${state.nextID++}`
  38. expr_stmts.push({
  39. dest: name,
  40. source,
  41. op: expr.op,
  42. })
  43. return [name, expr_stmts]
  44. }
  45. export const prettyPrintIR = (ssa: SSA): string => {
  46. let output = ""
  47. if ("source1" in ssa) {
  48. output = `${ssa.dest} = ${ssa.source} ${ssa.op} ${ssa.source1}`
  49. } else if ("op" in ssa) {
  50. output = `${ssa.dest} = ${ssa.op} ${ssa.source}`
  51. } else {
  52. output = `${ssa.dest} = ${ssa.source}`
  53. }
  54. return output
  55. }