Move parser to separate file

main
Ethan Reece 2023-09-07 23:13:47 -05:00
parent a58bb2bab0
commit 7f28dc939f
Signed by: me
GPG Key ID: D3993665FF92E1C3
2 changed files with 51 additions and 45 deletions

View File

@ -1,53 +1,10 @@
module Main (main) where
import Control.Monad.Combinators.Expr
import Data.Void (Void)
import Parser.Equation
import System.Environment
import Text.Megaparsec
import Text.Megaparsec.Char as C
import Text.Megaparsec.Char.Lexer as L
type Parser = Parsec Void String
data Expr
= Int Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show)
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
term = Int <$> intParser
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
parseExpr :: String -> Either (ParseErrorBundle String Void) Expr
parseExpr = parse (C.space *> expr <* eof) ""
-- main :: IO ()
main = do
input <- fmap head getArgs
parseTest expr input
parseTest equationParser input

View File

@ -0,0 +1,49 @@
module Parser.Equation (equationParser) where
import Control.Monad.Combinators.Expr
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char as C
import Text.Megaparsec.Char.Lexer as L
type Parser = Parsec Void String
data Expr
= Int Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show)
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
term = Int <$> intParser
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
parseExpr :: String -> Either (ParseErrorBundle String Void) Expr
parseExpr = parse (C.space *> expr <* eof) ""
equationParser = expr