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.

89 lines
2.3 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. } else if (expr.type === "unary") {
  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. } else {
  45. const [left_source, left_stmts] = convertExpr(state, expr.left)
  46. const [right_source, right_stmts] = convertExpr(state, expr.right)
  47. const expr_stmts = [...left_stmts, ...right_stmts]
  48. const name = `temp${state.nextID++}`
  49. expr_stmts.push({
  50. dest: name,
  51. op: expr.op,
  52. source: left_source,
  53. source1: right_source,
  54. })
  55. return [name, expr_stmts]
  56. }
  57. }
  58. export const prettyPrintIR = (ssa: SSA): string => {
  59. let output = ""
  60. if ("source1" in ssa) {
  61. output = `${ssa.dest} = ${ssa.source} ${ssa.op} ${ssa.source1}`
  62. } else if ("op" in ssa) {
  63. output = `${ssa.dest} = ${ssa.op} ${ssa.source}`
  64. } else {
  65. output = `${ssa.dest} = ${ssa.source}`
  66. }
  67. return output
  68. }