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.

66 lines
1.6 KiB

  1. import { convertIR } from "./ir/convert"
  2. import { prettyPrintBlock } from "./ir/pretty"
  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(prettyPrintBlock(ir))
  29. // 5. Generate code
  30. return ''
  31. }
  32. export const processDecls = (decls: Array<Decl>): SymbolMap => decls.reduce(processDecl, {})
  33. export const processDecl = (symbols: SymbolMap, decl: Decl): SymbolMap => {
  34. const symbol = processVarDecl(symbols, decl)
  35. return {
  36. ...symbols,
  37. [symbol.name]: symbol,
  38. }
  39. }
  40. export const processVarDecl = (symbols: SymbolMap, decl: VarDecl): SymbolDefn => {
  41. if (typeof symbols[decl.name] !== 'undefined') {
  42. throw new Error(`a variable named \`${decl.name}' is already defined`)
  43. }
  44. return {
  45. attrs: decl.attrs,
  46. name: decl.name,
  47. type: decl.args.type,
  48. }
  49. }