Guest User

Untitled

a guest
Sep 23rd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. // PEG grammar for a minimal programming language
  2.  
  3. Program
  4. = (_ Function / Statement _)*
  5.  
  6. Function
  7. = "fun" _ id:Identifier _ "(" Parameters ")" _ (":" _ Identifier _)? _ (Statement)* _ "end"
  8.  
  9. Parameter = Identifier _ ":" _ Identifier
  10.  
  11. Parameters = (Parameter (_ "," _ Parameter)*)?
  12.  
  13. Statement
  14. = Variable
  15. / Assignment
  16. / Repeat
  17. / While
  18. / If
  19. / Expression
  20.  
  21. Variable
  22. = "var" _ id:Identifier _ (":" _ Identifier _)? "=" Expression
  23.  
  24. Assignment
  25. = id:Identifier _ "=" _ Expression
  26.  
  27. Repeat
  28. = "repeat" _ Expression _ "times" _ (Statement)* _ "end"
  29.  
  30. While
  31. = "while" _ Expression _ "do" _ (Statement)* _ "end"
  32.  
  33. If
  34. = "if" _ Expression _ "then" _ (Statement)* _ ("elseif" _ Expression _ "then" _ (Statement)*)* ("else" _ (Statement)*)? _ "end"
  35.  
  36. Expression
  37. = head:Term tail:(_ ("+" / "-") _ Term)*
  38.  
  39. Term
  40. = head:Factor tail:(_ ("*" / "/") _ Factor)*
  41.  
  42. Factor
  43. = "(" _ expr:Expression _ ")"
  44. / Integer
  45. / String
  46. / CallOrIdentifier
  47.  
  48. CallOrIdentifier "function call or variable name"
  49. = Identifier (Arguments)?
  50.  
  51. Arguments "arguments"
  52. = "(" _ (Expression ( _ "," Expression)*) ")"
  53.  
  54. Integer "integer"
  55. = [0-9]+
  56.  
  57. String "string"
  58. = '"' chars:DoubleStringCharacter* '"' {
  59. return { type: "DoubleString", value: JSON.stringify(chars.join("")) };
  60. }
  61. / "'" chars:SingleStringCharacter* "'" {
  62. return { type: "SingleString", value: JSON.stringify(chars.join("")) };
  63. }
  64.  
  65. DoubleStringCharacter
  66. = '\\' '"' { return '"'; }
  67. / !'"' SourceCharacter { return text(); }
  68.  
  69. SingleStringCharacter
  70. = '\\' "'" { return "'"; }
  71. / !"'" SourceCharacter { return text(); }
  72.  
  73. SourceCharacter
  74. = .
  75.  
  76. Identifier "identifier"
  77. = !Reserved [a-zA-Z_]+
  78.  
  79. Reserved
  80. = "var"
  81. / "fun"
  82. / "end"
  83. / "repeat"
  84. / "while"
  85. / "if"
  86. / "then"
  87. / "else"
  88. / "elseif"
  89. / "times"
  90.  
  91. _ "whitespace"
  92. = [ \t\n\r]*
Add Comment
Please, Sign In to add comment