1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
{
-- only list imports here
import Data.Char
import Tree
}
%tokentype { Token }
%lexer { lexer } { TokenEOF }
%token
'*' { Sym '*' }
'+' { Sym '+' }
'-' { Sym '-' }
'(' { Sym '(' }
')' { Sym ')' }
i { AnInt $$ }
%%
E :: {Tree ForestId Int}
: E '+' E { Plus $1 $3 }
| E '*' E { Times $1 $3 }
| E '-' E { Minus $1 $3 }
| '(' E ')' { Pars $2 }
| i { Const $1 }
{
data Token
= TokenEOF
| Sym Char
| AnInt {getInt :: Int}
deriving (Show,Eq, Ord)
lexer :: String -> [Token]
lexer [] = []
lexer (' ':cs) = lexer cs
lexer (c:cs) | c `elem` "+*-()"
= Sym c : lexer cs
lexer (c:cs) | isDigit c
= let (yes,no) = span isDigit cs in AnInt (read $ c:yes) : lexer no
}
|