| 1 |
(* calc.g |
| 2 |
* |
| 3 |
* COPYRIGHT (c) 2011 The Fellowship of SML/NJ (http://www.smlnj.org) |
| 4 |
* All rights reserved. |
| 5 |
*) |
| 6 |
|
| 7 |
%name CalcParse; |
| 8 |
|
| 9 |
(* an example of using the header declaration, although it |
| 10 |
* just describes the default behavior. |
| 11 |
*) |
| 12 |
%header (functor CalcParseFn (Lex : ANTLR_LEXER)); |
| 13 |
|
| 14 |
%entry exp; |
| 15 |
|
| 16 |
%tokens |
| 17 |
: KW_let ("let") | KW_in ("in") |
| 18 |
| ID of string | NUM of Int.int |
| 19 |
| EQ ("=") | PLUS ("+") |
| 20 |
| TIMES ("*") | MINUS ("-") |
| 21 |
| LP ("(") | RP (")") |
| 22 |
| SEMI (";") |
| 23 |
| DummyExp of int |
| 24 |
; |
| 25 |
|
| 26 |
%refcell vars : string list = ([]); |
| 27 |
%refcell nums : int list = ([]); |
| 28 |
|
| 29 |
prog |
| 30 |
: (exp@(AtomMap.empty) ";")* |
| 31 |
; |
| 32 |
exp(env) |
| 33 |
: "let" ID "=" exp@(env) |
| 34 |
"in" exp@(AtomMap.insert(env, Atom.atom ID, exp1)) |
| 35 |
=> ( vars := ID::(!vars); exp2 ) |
| 36 |
| addExp@(env) |
| 37 |
; |
| 38 |
addExp(env) |
| 39 |
: multExp@(env) ("+" multExp@(env))* |
| 40 |
=> ( List.foldl op+ multExp SR ) |
| 41 |
; |
| 42 |
multExp(env) |
| 43 |
: prefixExp@(env) ("*" prefixExp@(env))* |
| 44 |
=> ( List.foldl op* prefixExp SR ) |
| 45 |
; |
| 46 |
prefixExp(env) |
| 47 |
: atomicExp@(env) |
| 48 |
| "-" prefixExp@(env) |
| 49 |
=> ( ~prefixExp ) |
| 50 |
; |
| 51 |
atomicExp(env) |
| 52 |
: ID |
| 53 |
%where ( AtomMap.inDomain (env, Atom.atom ID) ) |
| 54 |
=> ( valOf(AtomMap.find (env, Atom.atom ID)) ) |
| 55 |
| NUM |
| 56 |
=> ( nums := NUM::(!nums); NUM ) |
| 57 |
| "(" exp@(env) ")" |
| 58 |
| DummyExp |
| 59 |
; |