module ParsingHelpers (Parser, makeEofParser, parseFromFile) where

import Text.Megaparsec

import Data.Text (Text)
import qualified Data.Text.IO as T
import Data.Void

type Parser = Parsec Void Text

makeEofParser :: Parser a -> Parser a
makeEofParser :: Parser a -> Parser a
makeEofParser Parser a
p = Parser a
p Parser a -> ParsecT Void Text Identity () -> Parser a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof

parseFromFile :: Parser a -> FilePath -> FilePath -> IO a
parseFromFile :: Parser a -> FilePath -> FilePath -> IO a
parseFromFile Parser a
p FilePath
errorFileName FilePath
grammarFileName = do
    Text
input <-
        if FilePath
grammarFileName FilePath -> FilePath -> Bool
forall a. Eq a => a -> a -> Bool
== FilePath
""
        then IO Text
T.getContents
        else FilePath -> IO Text
T.readFile FilePath
grammarFileName
    case Parser a
-> FilePath -> Text -> Either (ParseErrorBundle Text Void) a
forall e s a.
Parsec e s a -> FilePath -> s -> Either (ParseErrorBundle s e) a
runParser Parser a
p FilePath
errorFileName Text
input of
        Left ParseErrorBundle Text Void
err ->
            FilePath -> IO a
forall (m :: * -> *) a. MonadFail m => FilePath -> m a
fail (FilePath -> IO a) -> FilePath -> IO a
forall a b. (a -> b) -> a -> b
$ FilePath
"Parsing error: " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ ParseErrorBundle Text Void -> FilePath
forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> FilePath
errorBundlePretty ParseErrorBundle Text Void
err
        Right a
res ->
            a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return a
res