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.

74 lines
2.1 KiB

  1. // AST factories
  2. {
  3. const attr = (name, args) => ({ name, args })
  4. const stmt = (stmt_type, args) => ({ type: "stmt", stmt_type, args })
  5. const decl = (decl_type, name, attrs, args) => ({ type: "decl", decl_type, name, attrs: attrs || [], args })
  6. const uexpr = (op, arg) => ({ type: "unary", op, arg })
  7. const bexpr = (op, left, right) => ({ type: "binary", op, left, right })
  8. const assocl = (head, tail) => tail.reduce((left, arg) => {
  9. const [op, right] = arg
  10. return bexpr(op, left, right)
  11. }, head)
  12. }
  13. Program = WS @(Decl / Stmt)* WS
  14. // Declarations
  15. Decl = VarDecl
  16. VarDecl = attrs:Attrs? type:Type name:Ident SEMI { return decl("var", name, attrs, { type }) }
  17. // Statements
  18. Stmt = @AssignStmt SEMI
  19. AssignStmt = name:Ident ASSIGN expr:Expr { return stmt("assign", { name, expr }) }
  20. // Expressions
  21. Expr = AddExpr
  22. AddExpr = head:UnaryExpr tail:(op:AddOp e:UnaryExpr)* { return assocl(head, tail || []) }
  23. AddOp = PLUS { return "add" }
  24. UnaryExpr = op:UnaryOp? e:BaseExpr { return op ? uexpr(op, e) : e }
  25. UnaryOp = TILDE { return "bit_negate" }
  26. / MINUS { return "arith_negate" }
  27. BaseExpr = Ident / Number / LPAREN @Expr RPAREN
  28. // Attributes
  29. Attrs = LATTR @AttrList RATTR
  30. AttrList = h:Attr t:(COMMA @Attr)* { return [h].concat(t) }
  31. / '' { return [] }
  32. Attr = name:Ident args:(LPAREN @AttrArgs RPAREN)? { return attr(name, args || []) }
  33. AttrArgs = h:AttrArg t:(COMMA @AttrArg)* { return [h].concat(t) }
  34. / '' { return [] }
  35. AttrArg = Ident / Number
  36. // Types
  37. Type = PrimitiveType
  38. PrimitiveType = S8 / U8 / U16
  39. // Terminals
  40. Ident = h:[a-zA-Z_] t:[0-9a-zA-Z_]* WS { return h + t.join('') }
  41. Number = digits:[0-9]+ WS { return parseInt(digits.join(''), 10) }
  42. / '0x' digits:[a-fA-F0-9]+ WS { return parseInt(digits.join(''), 16) }
  43. / '0b' digits:[01]+ WS { return parseInt(digits.join(''), 2) }
  44. // Terminal keywords
  45. S8 = @'s8' WS
  46. U8 = @'u8' WS
  47. U16 = @'u16' WS
  48. // Terminal symbols
  49. PLUS = '+' WS
  50. TILDE = '~' WS
  51. MINUS = '-' WS
  52. SEMI = ';' WS
  53. ASSIGN = '<-' WS
  54. LPAREN = '(' WS
  55. RPAREN = ')' WS
  56. COMMA = ',' WS
  57. LATTR = '[[' WS
  58. RATTR = ']]' WS
  59. // Misc
  60. WS = [ \t\r\n]*