-- | Parsing of format strings.
module Futhark.Format (parseFormatString) where

import Data.Bifunctor
import Data.Text qualified as T
import Data.Void
import Text.Megaparsec

pFormatString :: Parsec Void T.Text [Either T.Text T.Text]
pFormatString :: Parsec Void Text [Either Text Text]
pFormatString =
  forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [forall a b. a -> Either a b
Left forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT Void Text Identity (Tokens Text)
pLiteral, forall a b. b -> Either a b
Right forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT Void Text Identity (Tokens Text)
pInterpolation]) forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* forall e s (m :: * -> *). MonadParsec e s m => m ()
eof
  where
    pInterpolation :: ParsecT Void Text Identity (Tokens Text)
pInterpolation = ParsecT Void Text Identity Text
"{" forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP forall a. Maybe a
Nothing (forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` String
braces) forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity Text
"}"
    pLiteral :: ParsecT Void Text Identity (Tokens Text)
pLiteral = forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P forall a. Maybe a
Nothing (forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` String
braces)
    braces :: String
braces = String
"{}" :: String

-- | The Lefts are pure text; the Rights are the contents of
-- interpolations.
parseFormatString :: T.Text -> Either T.Text [Either T.Text T.Text]
parseFormatString :: Text -> Either Text [Either Text Text]
parseFormatString =
  forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (String -> Text
T.pack forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> String
errorBundlePretty) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser Parsec Void Text [Either Text Text]
pFormatString String
""