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.

65 lines
1.8 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, arg1, arg2) => ({ type: "binary", op, arg1, arg2 })
  8. }
  9. Program = WS @(Decl / Stmt)* WS
  10. // Declarations
  11. Decl = VarDecl
  12. VarDecl = attrs:Attrs? type:Type name:Ident SEMI { return decl("var", name, attrs, { type }) }
  13. // Statements
  14. Stmt = @AssignStmt SEMI
  15. AssignStmt = name:Ident ASSIGN expr:Expr { return stmt("assign", { name, expr }) }
  16. // Expressions
  17. Expr = UnaryExpr
  18. UnaryExpr = op:UnaryOp? e:BaseExpr { return op ? uexpr(op, e) : e }
  19. UnaryOp = TILDE { return "bit_negate" }
  20. / MINUS { return "arith_negate" }
  21. BaseExpr = Ident / Number / LPAREN @Expr RPAREN
  22. // Attributes
  23. Attrs = LATTR @AttrList RATTR
  24. AttrList = h:Attr t:(COMMA @Attr)* { return [h].concat(t) }
  25. / '' { return [] }
  26. Attr = name:Ident args:(LPAREN @AttrArgs RPAREN)? { return attr(name, args || []) }
  27. AttrArgs = h:AttrArg t:(COMMA @AttrArg)* { return [h].concat(t) }
  28. / '' { return [] }
  29. AttrArg = Ident / Number
  30. // Types
  31. Type = PrimitiveType
  32. PrimitiveType = S8 / U8 / U16
  33. // Terminals
  34. Ident = h:[a-zA-Z_] t:[0-9a-zA-Z_]* WS { return h + t.join('') }
  35. Number = digits:[0-9]+ WS { return parseInt(digits.join(''), 10) }
  36. / '0x' digits:[a-fA-F0-9]+ WS { return parseInt(digits.join(''), 16) }
  37. / '0b' digits:[01]+ WS { return parseInt(digits.join(''), 2) }
  38. // Terminal keywords
  39. S8 = @'s8' WS
  40. U8 = @'u8' WS
  41. U16 = @'u16' WS
  42. // Terminal symbols
  43. TILDE = '~' WS
  44. MINUS = '-' WS
  45. SEMI = ';' WS
  46. ASSIGN = '<-' WS
  47. LPAREN = '(' WS
  48. RPAREN = ')' WS
  49. COMMA = ',' WS
  50. LATTR = '[[' WS
  51. RATTR = ']]' WS
  52. // Misc
  53. WS = [ \t\r\n]*