This repository has been archived on 2024-04-05. You can view files and clone it, but cannot push or open issues/pull-requests.
really-bad-compiler-in-haskell/app/Parser/Expression.hs

44 lines
958 B
Haskell
Raw Normal View History

2023-09-08 05:53:11 +00:00
module Parser.Expression (parseExpr, ParseResult) where
2023-09-08 04:13:47 +00:00
import Control.Monad.Combinators.Expr
import Data.Void (Void)
2023-09-08 05:53:11 +00:00
import Objects.Expression
import Text.Megaparsec as MP
2023-09-08 04:13:47 +00:00
import Text.Megaparsec.Char as C
import Text.Megaparsec.Char.Lexer as L
type Parser = Parsec Void String
lexemeParser :: Parser a -> Parser a
lexemeParser = L.lexeme C.space
symbolParser :: String -> Parser String
symbolParser = L.symbol C.space
intParser :: Parser Int
intParser = lexemeParser L.decimal
term :: Parser Expr
2023-09-08 05:53:11 +00:00
term = Lit <$> intParser
2023-09-08 04:13:47 +00:00
table :: [[Operator Parser Expr]]
table =
[ [ binaryOp "*" Mul,
binaryOp "/" Div
],
[ binaryOp "+" Add,
binaryOp "-" Sub
]
]
binaryOp name f = InfixL (f <$ symbolParser name)
expr :: Parser Expr
expr = makeExprParser term table
2023-09-08 05:53:11 +00:00
type ParseResult = Either (ParseErrorBundle String Void) Expr
parseExpr :: String -> ParseResult
parseExpr = MP.parse (C.space *> expr <* eof) ""
2023-09-08 04:13:47 +00:00
2023-09-08 05:53:11 +00:00
-- parseE = parseExpr