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.

77 lines
2.0 KiB

  1. import { R8 } from "./cpu"
  2. import { Loc, LocType } from "../ir/loc"
  3. import { Operand, AbsInsn2, insnReduce2 } from "../ir/insn"
  4. import { BinaryOp, UnaryOp } from "../ast"
  5. import type { SM83Insn } from "./insn"
  6. export const realizeBlock = (block: Array<AbsInsn2>): Array<SM83Insn> => block.flatMap(realizeInsn)
  7. export const realizeInsn = (insn: AbsInsn2): Array<SM83Insn> => insnReduce2(
  8. realizeCopy,
  9. realizeLabel,
  10. realizeGoto,
  11. realizeUnary,
  12. insn,
  13. )
  14. const getSourceName = (source: Operand): string => typeof source === "number"
  15. ? source.toString()
  16. : source.asmName()
  17. export const realizeCopy = (dest: Loc, source: Operand): Array<SM83Insn> => [
  18. `LD ${dest.asmName()}, ${getSourceName(source)}`
  19. ]
  20. export const realizeLabel = (name: string): Array<SM83Insn> => [
  21. `${name}:`,
  22. ]
  23. export const realizeGoto = (name: string): Array<SM83Insn> => [
  24. `JR ${name}`,
  25. ]
  26. export const realizeUnary = (dest: Loc, op: UnaryOp | BinaryOp, source: Operand): Array<SM83Insn> => {
  27. if (!isA(dest)) {
  28. throw new Error("unexpected form for unary operation")
  29. }
  30. let output: Array<SM83Insn> = []
  31. switch (op) {
  32. case "add":
  33. return [`ADD ${getSourceName(source)}`]
  34. case "subtract":
  35. return [`SUB ${getSourceName(source)}`]
  36. case "bit_and":
  37. return [`AND ${getSourceName(source)}`]
  38. case "bit_or":
  39. return [`OR ${getSourceName(source)}`]
  40. case "bit_xor":
  41. return [`XOR ${getSourceName(source)}`]
  42. case "shift_left":
  43. for (let i = 0; i < source; ++i) {
  44. output.push("SLA A")
  45. }
  46. return output
  47. case "shift_right":
  48. for (let i = 0; i < source; ++i) {
  49. output.push("SRL A")
  50. }
  51. return output
  52. case "arith_negate":
  53. return ["CPL", "INC A"]
  54. case "bit_negate":
  55. return ["CPL"]
  56. }
  57. }
  58. const isA = (loc: Operand): boolean =>
  59. typeof loc === "object" && loc.type === LocType.REGISTER && loc.name === R8.A