simple-arithmetic-compiler/app/Lexer.hs

32 lines
1.1 KiB
Haskell

module Lexer where
data Token = Plus
| Minus
| Multiply
| Divide
| Integer Int
| LBrace
| RBrace
deriving Show
lex :: String -> [Token]
lex source = reverse (lex' source [] (length source))
lex' :: String -> [Token] -> Int -> [Token]
lex' "" tokens _ = tokens
lex' (' ':xs) tokens orgLength = lex' xs tokens orgLength
lex' (x:xs) tokens orgLength = case x of
'+' -> lex' xs (Plus:tokens) orgLength
'-' -> lex' xs (Minus:tokens) orgLength
'*' -> lex' xs (Multiply:tokens) orgLength
'/' -> lex' xs (Divide:tokens) orgLength
'(' -> lex' xs (LBrace:tokens) orgLength
')' -> lex' xs (RBrace:tokens) orgLength
_ -> lexNumbers (x:xs) tokens orgLength
lexNumbers :: String -> [Token] -> Int -> [Token]
lexNumbers (x:xs) tokens orgLength
| isDigit x = lex' (dropWhile isDigit (x:xs)) ((Integer(read (takeWhile isDigit (x:xs))::Int)):tokens) orgLength
| otherwise = error $ "Syntax error: " ++ [x] ++ " (" ++ show (orgLength - (length (x:xs))) ++ ")"
isDigit x = x `elem` "0123456789"