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.

80 lines
2.0 KiB

  1. import { convertASM } from "./asm"
  2. import { convertIR, prettyPrintIR } from "./ir"
  3. import { parse } from "./parser"
  4. import type { Attr, Decl, Stmt, Type, VarDecl } from "./ast"
  5. type SymbolDefn = {
  6. attrs: Array<Attr>,
  7. name: string,
  8. type: Type
  9. }
  10. type SymbolMap = {
  11. [name: string]: SymbolDefn
  12. }
  13. // TODO: Support more than one TU
  14. export const compile = (fileName: string, source: string): string => {
  15. // 1. Parse
  16. const ast = parse(source)
  17. // 2. Partition declarations and statements
  18. const decls = ast.filter((x): x is Decl => x.type == "decl")
  19. const stmts = ast.filter((x): x is Stmt => x.type == "stmt")
  20. // 3. Create top-level symbol map
  21. const symbols = processDecls(decls)
  22. // TODO: Support declaring types other than U8/S8
  23. const asmDecls = Object.values(symbols).map(symbol => `${symbol.name}:: DB`)
  24. // TODO: Some form of type-checking
  25. // 4. Generate IR
  26. const ir = convertIR(stmts)
  27. console.log("=== IR === ")
  28. console.log(ir.map(prettyPrintIR).join("\n"))
  29. // 5. Generate code
  30. const insns = convertASM(ir)
  31. let output = ''
  32. if (asmDecls.length > 0) {
  33. output += `SECTION "${fileName} Data", WRAM0\n\n`
  34. output += asmDecls.join("\n")
  35. output += "\n\n"
  36. }
  37. if (insns.length > 0) {
  38. output += `SECTION "${fileName} Code", ROM0\n\n`
  39. output += insns.join("\n")
  40. }
  41. console.log("=== ASM === ")
  42. return output
  43. }
  44. export const processDecls = (decls: Array<Decl>): SymbolMap => decls.reduce(processDecl, {})
  45. export const processDecl = (symbols: SymbolMap, decl: Decl): SymbolMap => {
  46. const symbol = processVarDecl(symbols, decl)
  47. return {
  48. ...symbols,
  49. [symbol.name]: symbol,
  50. }
  51. }
  52. export const processVarDecl = (symbols: SymbolMap, decl: VarDecl): SymbolDefn => {
  53. if (typeof symbols[decl.name] !== 'undefined') {
  54. throw new Error(`a variable named \`${decl.name}' is already defined`)
  55. }
  56. return {
  57. attrs: decl.attrs,
  58. name: decl.name,
  59. type: decl.args.type,
  60. }
  61. }