{-# LANGUAGE ViewPatterns #-}
{-|
Module      : Parser
Description : The CFV Parser
Copyright   : (c) Harley Eades, 2026
Maintainer  : harley.eades@gmail.com

This module consists of the CFV parser API. 
-}
module  Configuration.Cfv.Parser 
    (parseCfvFile
    ,parseCfvFileWith
    ,CfvError (..)
    ,SyntaxError (..)
    ,ErrorKind (..)
    ,Item (..)
    ,Position (..)
    ,parseEvalCfv
    ,parseEvalCfvWith
    ,renderCfvError) where

import qualified GHC.IO.Exception as E
import Data.Text.Encoding.Error (UnicodeException)
import qualified GHC.Exception as E
import Data.Text (Text)
import Text.Megaparsec (SourcePos (..), ParseErrorBundle (..), ParseError (..), ErrorItem (..), ErrorFancy (..), Parsec, unPos, PosState (..), errorOffset, TraversableStream (reachOffset), parseError, getOffset, getSourcePos, empty, try, MonadParsec (takeWhileP, notFollowedBy, observing, eof), satisfy, (<?>), (<|>), many, optional, anySingle, option, parse)
import System.FilePath (takeExtension)
import qualified Control.Exception as E
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as TE
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as Set
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Megaparsec.Char (space1, string, char)
import Control.Monad (void, when)
import Data.Char (isAlphaNum, isAsciiLower, isAsciiUpper)
import qualified Data.Bifunctor as BI

import Configuration.Cfv.AST (VarAttr (..), Binding, Var (..))
import Configuration.Cfv.Shell (CommandError (..), ShellConfig, defaultShellConfig, evalValue, describeProblem)
import qualified Data.Text as DT
import Data.List.NonEmpty (NonEmpty)

-------------------------------------------------------------------------------------------------------------------
-- Public API

-- | Read, parse and evaluate a @.cfv@ file using 'defaultShellConfig'.
-- Returns the variables in source order; a variable declared more than once
-- appears more than once (so 'lookup' finds the first declaration). Commands
-- run one at a time in file order, and the first failure aborts the whole
-- operation.
--
-- Never throws for extension, read, decode, parse or command problems; they are
-- all returned as 'CfvError'. (To throw instead:
-- @either E.throwIO pure =<< parseCfvFile p@.)
parseCfvFile :: FilePath -> IO (Either CfvError [Binding])
parseCfvFile :: String -> IO (Either CfvError [Binding])
parseCfvFile = ShellConfig -> String -> IO (Either CfvError [Binding])
parseCfvFileWith ShellConfig
defaultShellConfig

-- | Like 'parseCfvFile' with an explicit shell configuration.
parseCfvFileWith :: ShellConfig -> FilePath -> IO (Either CfvError [Binding])
parseCfvFileWith :: ShellConfig -> String -> IO (Either CfvError [Binding])
parseCfvFileWith ShellConfig
cfg String
path = do
  Either CfvError [Declaration]
parsed <- String -> IO (Either CfvError [Declaration])
readCfvFile String
path
  case Either CfvError [Declaration]
parsed of
    Left CfvError
err    -> Either CfvError [Binding] -> IO (Either CfvError [Binding])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CfvError -> Either CfvError [Binding]
forall a b. a -> Either a b
Left CfvError
err)
    Right [Declaration]
decls -> ShellConfig -> [Declaration] -> IO (Either CfvError [Binding])
runDeclarations ShellConfig
cfg [Declaration]
decls

-- | Like 'parseCfvFile', but doesn't read from a file. Useful for testing.
parseEvalCfv :: [Char] -> Text -> IO (Either CfvError [Binding])
parseEvalCfv :: String -> Text -> IO (Either CfvError [Binding])
parseEvalCfv = ShellConfig -> String -> Text -> IO (Either CfvError [Binding])
parseEvalCfvWith ShellConfig
defaultShellConfig

-- | Like 'parseEvalCfv' but with an explicit shell configuration.
parseEvalCfvWith :: ShellConfig -> [Char] -> Text -> IO (Either CfvError [Binding])
parseEvalCfvWith :: ShellConfig -> String -> Text -> IO (Either CfvError [Binding])
parseEvalCfvWith ShellConfig
cfg String
path Text
txt = do
  let parsed :: Either CfvError [Declaration]
parsed = (SyntaxError -> CfvError)
-> Either SyntaxError [Declaration]
-> Either CfvError [Declaration]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
BI.first SyntaxError -> CfvError
FileSyntaxError (Either SyntaxError [Declaration] -> Either CfvError [Declaration])
-> Either SyntaxError [Declaration]
-> Either CfvError [Declaration]
forall a b. (a -> b) -> a -> b
$ String -> Text -> Either SyntaxError [Declaration]
parseCfv String
path Text
txt
  case Either CfvError [Declaration]
parsed of
    Left CfvError
err    -> Either CfvError [Binding] -> IO (Either CfvError [Binding])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CfvError -> Either CfvError [Binding]
forall a b. a -> Either a b
Left CfvError
err)
    Right [Declaration]
decls -> ShellConfig -> [Declaration] -> IO (Either CfvError [Binding])
runDeclarations ShellConfig
cfg [Declaration]
decls

-------------------------------------------------------------------------------------------------------------------

-- | One @[secret] name = value@ declaration, as written in the file.
data Declaration = Declaration
  { Declaration -> Text
declName     :: Text
  , Declaration -> VarAttr
declAttr     :: VarAttr
  , Declaration -> Value
declValue    :: Value
  , Declaration -> Position
declPosition :: Position
    -- ^ Where the declaration starts (its @secret@ prefix if it has one,
    -- otherwise its variable name).
  } deriving (Declaration -> Declaration -> Bool
(Declaration -> Declaration -> Bool)
-> (Declaration -> Declaration -> Bool) -> Eq Declaration
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Declaration -> Declaration -> Bool
== :: Declaration -> Declaration -> Bool
$c/= :: Declaration -> Declaration -> Bool
/= :: Declaration -> Declaration -> Bool
Eq)

-- | Like the derived instance, except that the value of a 'Secret'
-- declaration is shown as @\<redacted\>@.
instance Show Declaration where
  showsPrec :: Int -> Declaration -> ShowS
  showsPrec :: Int -> Declaration -> ShowS
showsPrec Int
d (Declaration Text
n VarAttr
a Value
v Position
p) =
    Bool -> ShowS -> ShowS
showParen (Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
10) (ShowS -> ShowS) -> ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$
      String -> ShowS
showString String
"Declaration "
        ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Text -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
11 Text
n ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> ShowS
showChar Char
' '
        ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> VarAttr -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
11 VarAttr
a ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> ShowS
showChar Char
' '
        ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (case VarAttr
a of
             VarAttr
Public -> Int -> Value -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
11 Value
v
             VarAttr
Secret -> String -> ShowS
showString String
"<redacted>")
        ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> ShowS
showChar Char
' '
        ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Position -> ShowS
forall a. Show a => Int -> a -> ShowS
showsPrec Int
11 Position
p

-- | The value of a variable declaration.
data Value
  = StringValue Text   -- ^ A quoted string, already unescaped.
  | CommandValue Text  -- ^ The text between backticks, unmodified.
  deriving (Value -> Value -> Bool
(Value -> Value -> Bool) -> (Value -> Value -> Bool) -> Eq Value
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Value -> Value -> Bool
== :: Value -> Value -> Bool
$c/= :: Value -> Value -> Bool
/= :: Value -> Value -> Bool
Eq, Int -> Value -> ShowS
[Value] -> ShowS
Value -> String
(Int -> Value -> ShowS)
-> (Value -> String) -> ([Value] -> ShowS) -> Show Value
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Value -> ShowS
showsPrec :: Int -> Value -> ShowS
$cshow :: Value -> String
show :: Value -> String
$cshowList :: [Value] -> ShowS
showList :: [Value] -> ShowS
Show)

-- | Everything that can go wrong when processing a CFV file.
data CfvError
  = InvalidExtension FilePath
    -- ^ The file name does not end in @.cfv@ (checked before anything is read).
  | FileReadError FilePath E.IOException
    -- ^ The file could not be opened or read.
  | FileDecodeError FilePath UnicodeException
    -- ^ The file's contents are not valid UTF-8.
  | FileSyntaxError SyntaxError
    -- ^ The contents do not parse.
  | FileCommandError CommandError Text VarAttr Position
    -- ^ A backtick command could not be run, or failed. (Only produced by
    -- functions that run commands.)
  deriving (CfvError -> CfvError -> Bool
(CfvError -> CfvError -> Bool)
-> (CfvError -> CfvError -> Bool) -> Eq CfvError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CfvError -> CfvError -> Bool
== :: CfvError -> CfvError -> Bool
$c/= :: CfvError -> CfvError -> Bool
/= :: CfvError -> CfvError -> Bool
Eq, Int -> CfvError -> ShowS
[CfvError] -> ShowS
CfvError -> String
(Int -> CfvError -> ShowS)
-> (CfvError -> String) -> ([CfvError] -> ShowS) -> Show CfvError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CfvError -> ShowS
showsPrec :: Int -> CfvError -> ShowS
$cshow :: CfvError -> String
show :: CfvError -> String
$cshowList :: [CfvError] -> ShowS
showList :: [CfvError] -> ShowS
Show)

-- | A problem with the text itself, with a location.
data SyntaxError = SyntaxError
  { SyntaxError -> Position
syntaxErrorPosition   :: Position
    -- ^ Approximate position where the syntax error occurred.
  , SyntaxError -> ErrorKind
syntaxErrorKind       :: ErrorKind
  -- ^ The kind of syntax error.
  , SyntaxError -> Maybe Text
syntaxErrorSourceLine :: Maybe Text
    -- ^ The source line containing error. Always 'Nothing' when the input
    -- contains the text @secret@ anywhere (even in a comment), because the line
    -- could then contain, or be part of, a secret value. Every secret
    -- declaration contains that text, so this cannot miss one.
  } deriving (SyntaxError -> SyntaxError -> Bool
(SyntaxError -> SyntaxError -> Bool)
-> (SyntaxError -> SyntaxError -> Bool) -> Eq SyntaxError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SyntaxError -> SyntaxError -> Bool
== :: SyntaxError -> SyntaxError -> Bool
$c/= :: SyntaxError -> SyntaxError -> Bool
/= :: SyntaxError -> SyntaxError -> Bool
Eq, Int -> SyntaxError -> ShowS
[SyntaxError] -> ShowS
SyntaxError -> String
(Int -> SyntaxError -> ShowS)
-> (SyntaxError -> String)
-> ([SyntaxError] -> ShowS)
-> Show SyntaxError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SyntaxError -> ShowS
showsPrec :: Int -> SyntaxError -> ShowS
$cshow :: SyntaxError -> String
show :: SyntaxError -> String
$cshowList :: [SyntaxError] -> ShowS
showList :: [SyntaxError] -> ShowS
Show)

-- | The specific kind of syntax error.
data ErrorKind
  = UnexpectedInput (Maybe Item) [Item]
    -- ^ Found this (if known), but expected one of these.
  | ReservedWord Text
    -- ^ A Haskell keyword (or a lone @_@) was used as a variable name.
    -- Position: start of the word.
  | InvalidEscape (Maybe Char)
    -- ^ A backslash followed by a character that is not a known escape.
    -- Position: the backslash. 'Nothing' (character withheld) inside the value
    -- of a 'Secret' declaration.
  | UnterminatedString Char
    -- ^ A string literal with no closing quote (carries the quote character).
    -- Position: the opening quote.
  | UnterminatedCommand
    -- ^ A backtick command with no closing backtick.
    -- Position: the opening backtick.
  | OtherFailure Text
    -- ^ Anything else; should not occur with the current grammar.
  deriving (ErrorKind -> ErrorKind -> Bool
(ErrorKind -> ErrorKind -> Bool)
-> (ErrorKind -> ErrorKind -> Bool) -> Eq ErrorKind
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ErrorKind -> ErrorKind -> Bool
== :: ErrorKind -> ErrorKind -> Bool
$c/= :: ErrorKind -> ErrorKind -> Bool
/= :: ErrorKind -> ErrorKind -> Bool
Eq, Int -> ErrorKind -> ShowS
[ErrorKind] -> ShowS
ErrorKind -> String
(Int -> ErrorKind -> ShowS)
-> (ErrorKind -> String)
-> ([ErrorKind] -> ShowS)
-> Show ErrorKind
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ErrorKind -> ShowS
showsPrec :: Int -> ErrorKind -> ShowS
$cshow :: ErrorKind -> String
show :: ErrorKind -> String
$cshowList :: [ErrorKind] -> ShowS
showList :: [ErrorKind] -> ShowS
Show)

-- | Something the parser found or expected.
data Item
  = Literal Text      -- ^ Specific text, such as @";"@.
  | Description Text  -- ^ A named construct, such as @"variable name"@.
  | EndOfFile
  deriving (Item -> Item -> Bool
(Item -> Item -> Bool) -> (Item -> Item -> Bool) -> Eq Item
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Item -> Item -> Bool
== :: Item -> Item -> Bool
$c/= :: Item -> Item -> Bool
/= :: Item -> Item -> Bool
Eq, Eq Item
Eq Item =>
(Item -> Item -> Ordering)
-> (Item -> Item -> Bool)
-> (Item -> Item -> Bool)
-> (Item -> Item -> Bool)
-> (Item -> Item -> Bool)
-> (Item -> Item -> Item)
-> (Item -> Item -> Item)
-> Ord Item
Item -> Item -> Bool
Item -> Item -> Ordering
Item -> Item -> Item
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Item -> Item -> Ordering
compare :: Item -> Item -> Ordering
$c< :: Item -> Item -> Bool
< :: Item -> Item -> Bool
$c<= :: Item -> Item -> Bool
<= :: Item -> Item -> Bool
$c> :: Item -> Item -> Bool
> :: Item -> Item -> Bool
$c>= :: Item -> Item -> Bool
>= :: Item -> Item -> Bool
$cmax :: Item -> Item -> Item
max :: Item -> Item -> Item
$cmin :: Item -> Item -> Item
min :: Item -> Item -> Item
Ord, Int -> Item -> ShowS
[Item] -> ShowS
Item -> String
(Int -> Item -> ShowS)
-> (Item -> String) -> ([Item] -> ShowS) -> Show Item
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Item -> ShowS
showsPrec :: Int -> Item -> ShowS
$cshow :: Item -> String
show :: Item -> String
$cshowList :: [Item] -> ShowS
showList :: [Item] -> ShowS
Show)

-- | A location in the source. Line and column are 1-based; the offset is the
-- 0-based character offset from the start of the input.
data Position = Position
  { Position -> String
posFile   :: FilePath
  , Position -> Int
posLine   :: Int
  , Position -> Int
posColumn :: Int
  , Position -> Int
posOffset :: Int
  } deriving (Position -> Position -> Bool
(Position -> Position -> Bool)
-> (Position -> Position -> Bool) -> Eq Position
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Position -> Position -> Bool
== :: Position -> Position -> Bool
$c/= :: Position -> Position -> Bool
/= :: Position -> Position -> Bool
Eq, Int -> Position -> ShowS
[Position] -> ShowS
Position -> String
(Int -> Position -> ShowS)
-> (Position -> String) -> ([Position] -> ShowS) -> Show Position
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Position -> ShowS
showsPrec :: Int -> Position -> ShowS
$cshow :: Position -> String
show :: Position -> String
$cshowList :: [Position] -> ShowS
showList :: [Position] -> ShowS
Show)

instance E.Exception CfvError where
  displayException :: CfvError -> String
  displayException :: CfvError -> String
displayException = Text -> String
DT.unpack (Text -> String) -> (CfvError -> Text) -> CfvError -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CfvError -> Text
renderCfvError 

instance E.Exception SyntaxError where
  displayException :: SyntaxError -> String
  displayException :: SyntaxError -> String
displayException = Text -> String
DT.unpack (Text -> String) -> (SyntaxError -> Text) -> SyntaxError -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SyntaxError -> Text
renderSyntaxError

-- | Turn declarations into bindings, running each 'CommandValue' in the user's
-- shell. The shell is only looked up if there is at least one command.
runDeclarations :: ShellConfig -> [Declaration] -> IO (Either CfvError [Binding])
runDeclarations :: ShellConfig -> [Declaration] -> IO (Either CfvError [Binding])
runDeclarations ShellConfig
cfg = [Binding] -> [Declaration] -> IO (Either CfvError [Binding])
go []
  where
    go :: [Binding] -> [Declaration] -> IO (Either CfvError [Binding])
go [Binding]
acc [] = Either CfvError [Binding] -> IO (Either CfvError [Binding])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Binding] -> Either CfvError [Binding]
forall a b. b -> Either a b
Right ([Binding] -> [Binding]
forall a. [a] -> [a]
reverse [Binding]
acc))
    go [Binding]
acc (Declaration
d : [Declaration]
ds) = do
      case Declaration -> Value
declValue Declaration
d of
        CommandValue Text
cmd -> do
            Either CommandError String
result <- ShellConfig -> Text -> IO (Either CommandError String)
evalValue ShellConfig
cfg Text
cmd
            case Either CommandError String
result of
              Left CommandError
err -> Either CfvError [Binding] -> IO (Either CfvError [Binding])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CfvError -> Either CfvError [Binding]
forall a b. a -> Either a b
Left (CfvError -> Either CfvError [Binding])
-> CfvError -> Either CfvError [Binding]
forall a b. (a -> b) -> a -> b
$ CommandError -> Text -> VarAttr -> Position -> CfvError
FileCommandError CommandError
err (Declaration -> Text
declName Declaration
d) (Declaration -> VarAttr
declAttr Declaration
d) (Declaration -> Position
declPosition Declaration
d))
              Right String
v  -> [Binding] -> [Declaration] -> IO (Either CfvError [Binding])
go ((Declaration -> Text
declName Declaration
d, VarAttr -> Text -> Var
Var (Declaration -> VarAttr
declAttr Declaration
d) (String -> Text
DT.pack String
v)) Binding -> [Binding] -> [Binding]
forall a. a -> [a] -> [a]
: [Binding]
acc) [Declaration]
ds
        StringValue Text
v -> [Binding] -> [Declaration] -> IO (Either CfvError [Binding])
go ((Declaration -> Text
declName Declaration
d, VarAttr -> Text -> Var
Var (Declaration -> VarAttr
declAttr Declaration
d) Text
v) Binding -> [Binding] -> [Binding]
forall a. a -> [a] -> [a]
: [Binding]
acc) [Declaration]
ds

-- | Check the extension, read and parse a file, without running any command.
-- Never returns 'FileCommandError'.
readCfvFile :: FilePath -> IO (Either CfvError [Declaration])
readCfvFile :: String -> IO (Either CfvError [Declaration])
readCfvFile String
path
  | ShowS
takeExtension String
path String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
".cfv" = Either CfvError [Declaration] -> IO (Either CfvError [Declaration])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (CfvError -> Either CfvError [Declaration]
forall a b. a -> Either a b
Left (String -> CfvError
InvalidExtension String
path))
  | Bool
otherwise = do
      Either IOException ByteString
result <- IO ByteString -> IO (Either IOException ByteString)
forall e a. Exception e => IO a -> IO (Either e a)
E.try (String -> IO ByteString
BS.readFile String
path)
      Either CfvError [Declaration] -> IO (Either CfvError [Declaration])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either CfvError [Declaration]
 -> IO (Either CfvError [Declaration]))
-> Either CfvError [Declaration]
-> IO (Either CfvError [Declaration])
forall a b. (a -> b) -> a -> b
$ case Either IOException ByteString
result of
        Left IOException
e -> CfvError -> Either CfvError [Declaration]
forall a b. a -> Either a b
Left (String -> IOException -> CfvError
FileReadError String
path IOException
e)
        Right ByteString
bytes -> 
          case ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
bytes of
            Left UnicodeException
e    -> CfvError -> Either CfvError [Declaration]
forall a b. a -> Either a b
Left (String -> UnicodeException -> CfvError
FileDecodeError String
path UnicodeException
e)
            Right Text
txt -> (SyntaxError -> CfvError)
-> Either SyntaxError [Declaration]
-> Either CfvError [Declaration]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
BI.first SyntaxError -> CfvError
FileSyntaxError (Either SyntaxError [Declaration] -> Either CfvError [Declaration])
-> Either SyntaxError [Declaration]
-> Either CfvError [Declaration]
forall a b. (a -> b) -> a -> b
$ String -> Text -> Either SyntaxError [Declaration]
parseCfv String
path Text
txt

-- | Pure parser; runs nothing. The 'FilePath' is only used to label error
-- positions and is not checked for an extension.
parseCfv :: FilePath -> Text -> Either SyntaxError [Declaration]
parseCfv :: String -> Text -> Either SyntaxError [Declaration]
parseCfv String
name Text
input = (ParseErrorBundle Text Custom -> SyntaxError)
-> Either (ParseErrorBundle Text Custom) [Declaration]
-> Either SyntaxError [Declaration]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
BI.first ParseErrorBundle Text Custom -> SyntaxError
fromBundle (Either (ParseErrorBundle Text Custom) [Declaration]
 -> Either SyntaxError [Declaration])
-> Either (ParseErrorBundle Text Custom) [Declaration]
-> Either SyntaxError [Declaration]
forall a b. (a -> b) -> a -> b
$ Parsec Custom Text [Declaration]
-> String
-> Text
-> Either (ParseErrorBundle Text Custom) [Declaration]
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
parse Parsec Custom Text [Declaration]
program String
name Text
input

-- | Converts a command error into a 'Text' that is appropriate for logging.
renderCommandError :: CommandError -> Text -> VarAttr -> Position -> Text
renderCommandError :: CommandError -> Text -> VarAttr -> Position -> Text
renderCommandError (CommandError Text
cmd CommandProblem
problem) Text
name VarAttr
varAttr (Position String
f Int
l Int
c Int
_)
  = (String -> Text
DT.pack String
f) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall a. Show a => a -> Text
DT.show Int
l Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall a. Show a => a -> Text
DT.show Int
c Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": error: variable " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
forall a. Show a => a -> Text
DT.show Text
name
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> CommandProblem -> Text
describeProblem CommandProblem
problem
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> if VarAttr
varAttr VarAttr -> VarAttr -> Bool
forall a. Eq a => a -> a -> Bool
== VarAttr
Secret then Text
"" else Text
"\n  command: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
cmd 

-- | Converts a error into a 'Text' that is appropriate for logging.
renderCfvError :: CfvError -> Text
renderCfvError :: CfvError -> Text
renderCfvError (InvalidExtension (String -> Text
DT.pack->Text
p))
  = Text
p Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": not a .cfv file (the file name must end in \".cfv\")"
renderCfvError (FileReadError (String -> Text
DT.pack->Text
p) IOException
e)            
  = Text
p Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": cannot read file: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> IOException -> Text
forall a. Show a => a -> Text
DT.show IOException
e
renderCfvError (FileDecodeError (String -> Text
DT.pack->Text
p) UnicodeException
e)          
  = Text
p Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": file is not valid UTF-8: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> UnicodeException -> Text
forall a. Show a => a -> Text
DT.show UnicodeException
e
renderCfvError (FileSyntaxError SyntaxError
e)            
  = SyntaxError -> Text
renderSyntaxError SyntaxError
e
renderCfvError (FileCommandError CommandError
e Text
n VarAttr
vatr Position
p)  
  = CommandError -> Text -> VarAttr -> Position -> Text
renderCommandError CommandError
e Text
n VarAttr
vatr Position
p

-- | Multi-line, compiler-style message with a caret under the error.
renderSyntaxError :: SyntaxError -> Text
renderSyntaxError :: SyntaxError -> Text
renderSyntaxError (SyntaxError (Position (String -> Text
DT.pack->Text
f) Int
l Int
c Int
_) ErrorKind
kind Maybe Text
srcLine) =
  Text -> [Text] -> Text
DT.intercalate Text
"\n" ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$
    [ Text
f Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall a. Show a => a -> Text
DT.show Int
l Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
":" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall a. Show a => a -> Text
DT.show Int
c Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
": error: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ErrorKind -> Text
describeKind ErrorKind
kind ]
      [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> case Maybe Text
srcLine of
            Just Text
ln -> [ Text
"  | " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ln, Text
"  | " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text -> Text
DT.replicate (Int
c Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"^" ]
            Maybe Text
Nothing -> []

-- | Describes a syntax error in a logging appropriate fashion.
describeKind :: ErrorKind -> Text
describeKind :: ErrorKind -> Text
describeKind (UnexpectedInput Maybe Item
found [Item]
expected) 
  = Text
"unexpected " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> (Item -> Text) -> Maybe Item -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"input" Item -> Text
describeItem Maybe Item
found
 Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (if [Item] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Item]
expected
     then Text
""
     else Text
"; expected " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
DT.intercalate Text
", " ((Item -> Text) -> [Item] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Item -> Text
describeItem [Item]
expected))
describeKind (ReservedWord Text
w) =
  Text
"reserved word " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
forall a. Show a => a -> Text
DT.show Text
w Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" cannot be used as a variable name"
describeKind (InvalidEscape (Just Char
c)) 
  = Text
"invalid escape sequence \\" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Char -> Text
DT.singleton Char
c
describeKind (InvalidEscape Maybe Char
Nothing) 
  = Text
"invalid escape sequence (character withheld: secret value)"
describeKind (UnterminatedString Char
q) 
  = Text
"unterminated string literal (no closing " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Char -> Text
DT.singleton Char
q Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" for this one)"
describeKind ErrorKind
UnterminatedCommand 
  = Text
"unterminated command (no closing backtick for this one)"
describeKind (OtherFailure Text
msg) 
  = Text
msg

-- | Converts an 'Item' to a 'Text'.
describeItem :: Item -> Text
describeItem :: Item -> Text
describeItem (Literal Text
s)     = Text -> Text
forall a. Show a => a -> Text
DT.show Text
s
describeItem (Description Text
d) = Text
d
describeItem Item
EndOfFile       = Text
"end of input"

-- | Internal custom errors raised by the parser itself.
data Custom
  = CReservedWord Text
  | CInvalidEscape (Maybe Char)
  | CUnterminatedString Char
  | CUnterminatedCommand
  deriving (Custom -> Custom -> Bool
(Custom -> Custom -> Bool)
-> (Custom -> Custom -> Bool) -> Eq Custom
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Custom -> Custom -> Bool
== :: Custom -> Custom -> Bool
$c/= :: Custom -> Custom -> Bool
/= :: Custom -> Custom -> Bool
Eq, Eq Custom
Eq Custom =>
(Custom -> Custom -> Ordering)
-> (Custom -> Custom -> Bool)
-> (Custom -> Custom -> Bool)
-> (Custom -> Custom -> Bool)
-> (Custom -> Custom -> Bool)
-> (Custom -> Custom -> Custom)
-> (Custom -> Custom -> Custom)
-> Ord Custom
Custom -> Custom -> Bool
Custom -> Custom -> Ordering
Custom -> Custom -> Custom
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Custom -> Custom -> Ordering
compare :: Custom -> Custom -> Ordering
$c< :: Custom -> Custom -> Bool
< :: Custom -> Custom -> Bool
$c<= :: Custom -> Custom -> Bool
<= :: Custom -> Custom -> Bool
$c> :: Custom -> Custom -> Bool
> :: Custom -> Custom -> Bool
$c>= :: Custom -> Custom -> Bool
>= :: Custom -> Custom -> Bool
$cmax :: Custom -> Custom -> Custom
max :: Custom -> Custom -> Custom
$cmin :: Custom -> Custom -> Custom
min :: Custom -> Custom -> Custom
Ord, Int -> Custom -> ShowS
[Custom] -> ShowS
Custom -> String
(Int -> Custom -> ShowS)
-> (Custom -> String) -> ([Custom] -> ShowS) -> Show Custom
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Custom -> ShowS
showsPrec :: Int -> Custom -> ShowS
$cshow :: Custom -> String
show :: Custom -> String
$cshowList :: [Custom] -> ShowS
showList :: [Custom] -> ShowS
Show)

-- | Converts a position in the source file into a t'Position'.
toPosition :: SourcePos -> Int -> Position
toPosition :: SourcePos -> Int -> Position
toPosition SourcePos
sp = String -> Int -> Int -> Int -> Position
Position (SourcePos -> String
sourceName SourcePos
sp) (Pos -> Int
unPos (SourcePos -> Pos
sourceLine SourcePos
sp)) (Pos -> Int
unPos (SourcePos -> Pos
sourceColumn SourcePos
sp))

-- | Converts a "Text.Megaparsec" error into a t'SyntaxError'.
fromBundle :: ParseErrorBundle Text Custom -> SyntaxError
fromBundle :: ParseErrorBundle Text Custom -> SyntaxError
fromBundle ParseErrorBundle Text Custom
bundle =
  SyntaxError
    { syntaxErrorPosition :: Position
syntaxErrorPosition   = SourcePos -> Int -> Position
toPosition (PosState Text -> SourcePos
forall s. PosState s -> SourcePos
pstateSourcePos PosState Text
posState) Int
offset
    , syntaxErrorKind :: ErrorKind
syntaxErrorKind       = ErrorKind
kind
    , syntaxErrorSourceLine :: Maybe Text
syntaxErrorSourceLine = if Text
"secret" Text -> Text -> Bool
`DT.isInfixOf` PosState Text -> Text
forall s. PosState s -> s
pstateInput (ParseErrorBundle Text Custom -> PosState Text
forall s e. ParseErrorBundle s e -> PosState s
bundlePosState ParseErrorBundle Text Custom
bundle)
                           then Maybe Text
forall a. Maybe a
Nothing
                           else (String -> Text) -> Maybe String -> Maybe Text
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap String -> Text
DT.pack Maybe String
srcLine
    }
  where
    -- Without error recovery there is exactly one error in the bundle.
    err :: ParseError Text Custom
err = NonEmpty (ParseError Text Custom) -> ParseError Text Custom
forall a. NonEmpty a -> a
NE.head (ParseErrorBundle Text Custom -> NonEmpty (ParseError Text Custom)
forall s e. ParseErrorBundle s e -> NonEmpty (ParseError s e)
bundleErrors ParseErrorBundle Text Custom
bundle)
    offset :: Int
offset = ParseError Text Custom -> Int
forall s e. ParseError s e -> Int
errorOffset ParseError Text Custom
err
    (Maybe String
srcLine, PosState Text
posState) = Int -> PosState Text -> (Maybe String, PosState Text)
forall s.
TraversableStream s =>
Int -> PosState s -> (Maybe String, PosState s)
reachOffset Int
offset (ParseErrorBundle Text Custom -> PosState Text
forall s e. ParseErrorBundle s e -> PosState s
bundlePosState ParseErrorBundle Text Custom
bundle)
    kind :: ErrorKind
kind = case ParseError Text Custom
err of
      TrivialError Int
_ Maybe (ErrorItem (Token Text))
found Set (ErrorItem (Token Text))
expected ->
        Maybe Item -> [Item] -> ErrorKind
UnexpectedInput
          (ErrorItem Char -> Item
fromItem (ErrorItem Char -> Item) -> Maybe (ErrorItem Char) -> Maybe Item
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (ErrorItem Char)
Maybe (ErrorItem (Token Text))
found)
          ((ErrorItem Char -> Item) -> [ErrorItem Char] -> [Item]
forall a b. (a -> b) -> [a] -> [b]
map ErrorItem Char -> Item
fromItem (Set (ErrorItem Char) -> [ErrorItem Char]
forall a. Set a -> [a]
Set.toList Set (ErrorItem Char)
Set (ErrorItem (Token Text))
expected))
      FancyError Int
_ Set (ErrorFancy Custom)
fancy -> case Set (ErrorFancy Custom) -> [ErrorFancy Custom]
forall a. Set a -> [a]
Set.toList Set (ErrorFancy Custom)
fancy of
        (ErrorFancy Custom
f : [ErrorFancy Custom]
_) -> ErrorFancy Custom -> ErrorKind
fromFancy ErrorFancy Custom
f
        []      -> Text -> ErrorKind
OtherFailure Text
"unknown error"

-- | Converts a non-empty list of characters into a 'Text'.
textFromNEList :: NonEmpty Char -> Text
textFromNEList :: NonEmpty Char -> Text
textFromNEList = String -> Text
DT.pack (String -> Text)
-> (NonEmpty Char -> String) -> NonEmpty Char -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. NonEmpty Char -> String
forall a. NonEmpty a -> [a]
NE.toList

-- | Convert an t'Text.Megaparsec.Error.ErrorItem' into an 'Item'.
fromItem :: ErrorItem Char -> Item
fromItem :: ErrorItem Char -> Item
fromItem (Tokens NonEmpty Char
ts) = Text -> Item
Literal (Text -> Item) -> Text -> Item
forall a b. (a -> b) -> a -> b
$ NonEmpty Char -> Text
textFromNEList NonEmpty Char
ts
fromItem (Label NonEmpty Char
cs)  = Text -> Item
Description (Text -> Item) -> Text -> Item
forall a b. (a -> b) -> a -> b
$ NonEmpty Char -> Text
textFromNEList NonEmpty Char
cs
fromItem ErrorItem Char
EndOfInput  = Item
EndOfFile

-- | Convert an t'Text.Megaparsec.Error.ErrorFancy' into an 'ErrorKind'.
fromFancy :: ErrorFancy Custom -> ErrorKind
fromFancy :: ErrorFancy Custom -> ErrorKind
fromFancy (ErrorCustom (CReservedWord Text
w))       = Text -> ErrorKind
ReservedWord Text
w
fromFancy (ErrorCustom (CInvalidEscape Maybe Char
c))      = Maybe Char -> ErrorKind
InvalidEscape Maybe Char
c
fromFancy (ErrorCustom (CUnterminatedString Char
q)) = Char -> ErrorKind
UnterminatedString Char
q
fromFancy (ErrorCustom Custom
CUnterminatedCommand)    = ErrorKind
UnterminatedCommand
fromFancy (ErrorFail String
msg)                       = Text -> ErrorKind
OtherFailure (Text -> ErrorKind) -> (String -> Text) -> String -> ErrorKind
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
DT.pack (String -> ErrorKind) -> String -> ErrorKind
forall a b. (a -> b) -> a -> b
$ String
msg
fromFancy ErrorIndentation {}                   = Text -> ErrorKind
OtherFailure Text
"indentation error"

-- | The parser on 'Text' tokens firing errors based on 'Custom'.
type Parser = Parsec Custom Text

-- | Fail with a custom error reported at the given offset.
failAt :: Int -> Custom -> Parser a
failAt :: forall a. Int -> Custom -> Parser a
failAt Int
o Custom
c = ParseError Text Custom -> ParsecT Custom Text Identity a
forall a. ParseError Text Custom -> ParsecT Custom Text Identity a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
ParseError s e -> m a
parseError (Int -> Set (ErrorFancy Custom) -> ParseError Text Custom
forall s e. Int -> Set (ErrorFancy e) -> ParseError s e
FancyError Int
o (ErrorFancy Custom -> Set (ErrorFancy Custom)
forall a. a -> Set a
Set.singleton (Custom -> ErrorFancy Custom
forall e. e -> ErrorFancy e
ErrorCustom Custom
c)))

-- | Get the current position during parsing.
currentPosition :: Parser Position
currentPosition :: Parser Position
currentPosition = do
  Int
off <- ParsecT Custom Text Identity Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  SourcePos
sp  <- ParsecT Custom Text Identity SourcePos
forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos
  Position -> Parser Position
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SourcePos -> Int -> Position
toPosition SourcePos
sp Int
off)

-- | Space consumer: whitespace (incl. newlines) and @--@ line comments.
sc :: Parser ()
sc :: Parser ()
sc = Parser () -> Parser () -> Parser () -> Parser ()
forall e s (m :: * -> *).
MonadParsec e s m =>
m () -> m () -> m () -> m ()
L.space Parser ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space1 Parser ()
lineComment Parser ()
forall a. ParsecT Custom Text Identity a
forall (f :: * -> *) a. Alternative f => f a
empty

-- | A Haskell line comment: two or more dashes NOT followed by a symbol
-- character (so @-->@ or @--|@ is an operator, not a comment, as in Haskell).
lineComment :: Parser ()
lineComment :: Parser ()
lineComment = Parser () -> Parser ()
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Parser () -> Parser ()) -> Parser () -> Parser ()
forall a b. (a -> b) -> a -> b
$ do
  Tokens Text
_ <- Tokens Text -> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"--"
  Tokens Text
_ <- Maybe String
-> (Token Text -> Bool)
-> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token Text -> Token Text -> Bool
forall a. Eq a => a -> a -> Bool
== Char
Token Text
'-')
  ParsecT Custom Text Identity (Token Text) -> Parser ()
forall a. ParsecT Custom Text Identity a -> Parser ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy ((Token Text -> Bool) -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token Text -> Bool
isSymbolChar)
  ParsecT Custom Text Identity (Tokens Text) -> Parser ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Maybe String
-> (Token Text -> Bool)
-> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP (String -> Maybe String
forall a. a -> Maybe a
Just String
"comment text") (Token Text -> Token Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
Token Text
'\n'))
  where
    isSymbolChar :: Char -> Bool
isSymbolChar Char
c = Char
c Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'!',Char
'#',Char
'$',Char
'%',Char
'&',Char
'*',Char
'+',Char
'.',Char
'/',Char
'<',Char
'=',Char
'>',Char
'?',Char
'@',Char
'\\',Char
'^',Char
'|',Char
'~',Char
':']

-- | A lexeme including our space consumer 'sc'.
lexeme :: Parser a -> Parser a
lexeme :: forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
lexeme = Parser ()
-> ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m () -> m a -> m a
L.lexeme Parser ()
sc

-- | A symbol including our space consumer 'sc'.
symbol :: Text -> Parser Text
symbol :: Text -> Parser Text
symbol = Parser ()
-> Tokens Text -> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
m () -> Tokens s -> m (Tokens s)
L.symbol Parser ()
sc

-- | A Haskell variable identifier: starts with a lowercase letter or @_@,
-- continues with letters, digits, @_@ or @'@, and is not a reserved word.
varName :: Parser Text
varName :: Parser Text
varName = Parser Text -> Parser Text
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
lexeme (Parser Text -> Parser Text) -> Parser Text -> Parser Text
forall a b. (a -> b) -> a -> b
$ do
  Int
start <- ParsecT Custom Text Identity Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  Char
c  <- (Token Text -> Bool) -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy (\Token Text
x -> Char -> Bool
isAsciiLower Char
Token Text
x Bool -> Bool -> Bool
|| Char -> Bool
isAsciiUpper Char
Token Text
x Bool -> Bool -> Bool
|| Char
Token Text
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_') ParsecT Custom Text Identity Char
-> String -> ParsecT Custom Text Identity Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"variable name"
  Text
cs <- Maybe String
-> (Token Text -> Bool)
-> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (\Token Text
x -> Char -> Bool
isAlphaNum Char
Token Text
x Bool -> Bool -> Bool
|| Char
Token Text
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char
Token Text
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\'')
  let name :: Text
name = Char -> Text -> Text
DT.cons Char
c Text
cs
  Bool -> Parser () -> Parser ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Text
name Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text]
reserved) (Parser () -> Parser ()) -> Parser () -> Parser ()
forall a b. (a -> b) -> a -> b
$ Int -> Custom -> Parser ()
forall a. Int -> Custom -> Parser a
failAt Int
start (Text -> Custom
CReservedWord Text
name)
  Text -> Parser Text
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Text
name

-- | Reserved words.
reserved :: [Text]
reserved :: [Text]
reserved = [ Text
"_" ]

-- | A single- or double-quoted string. Supports the escapes
-- @\\\\ \\' \\" \\n \\t \\r \\0@. Raw newlines are allowed inside strings.
stringLit :: Parser Text
stringLit :: Parser Text
stringLit = Parser Text -> Parser Text
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
lexeme (Char -> Parser Text
quoted Char
'\'' Parser Text -> Parser Text -> Parser Text
forall a.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Char -> Parser Text
quoted Char
'"') Parser Text -> String -> Parser Text
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"string literal"

-- | Parser a single or double quoted string.
quoted :: Char -- ^ The quote character.
       -> Parser Text
quoted :: Char -> Parser Text
quoted Char
q = do
  Int
start <- ParsecT Custom Text Identity Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  Char
_ <- Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
q
  String
body <- ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (Int -> ParsecT Custom Text Identity Char
escaped Int
start ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity Char
forall a.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> ParsecT Custom Text Identity Char
ParsecT Custom Text Identity (Token Text)
plain)
  -- 'many' only stops on the closing quote or at end of input.
  Maybe Char
closed <- ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
q)
  case Maybe Char
closed of
    Maybe Char
Nothing -> Int -> Custom -> Parser Text
forall a. Int -> Custom -> Parser a
failAt Int
start (Char -> Custom
CUnterminatedString Char
q)
    Just Char
_  -> Text -> Parser Text
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Parser Text) -> (String -> Text) -> String -> Parser Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
DT.pack (String -> Parser Text) -> String -> Parser Text
forall a b. (a -> b) -> a -> b
$ String
body
  where
    plain :: ParsecT Custom Text Identity (Token Text)
plain = (Token Text -> Bool) -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy (\Token Text
c -> Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
q Bool -> Bool -> Bool
&& Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\\')

    escaped :: Int -> ParsecT Custom Text Identity Char
escaped Int
start = do
      Int
slash <- ParsecT Custom Text Identity Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      Char
_ <- Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'\\'
      Maybe Char
next <- ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional ParsecT Custom Text Identity Char
ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *). MonadParsec e s m => m (Token s)
anySingle
      case Maybe Char
next of
        Maybe Char
Nothing -> Int -> Custom -> ParsecT Custom Text Identity Char
forall a. Int -> Custom -> Parser a
failAt Int
start (Char -> Custom
CUnterminatedString Char
q)
        Just Char
c  -> ParsecT Custom Text Identity Char
-> (Char -> ParsecT Custom Text Identity Char)
-> Maybe Char
-> ParsecT Custom Text Identity Char
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int -> Custom -> ParsecT Custom Text Identity Char
forall a. Int -> Custom -> Parser a
failAt Int
slash (Maybe Char -> Custom
CInvalidEscape (Char -> Maybe Char
forall a. a -> Maybe a
Just Char
c))) Char -> ParsecT Custom Text Identity Char
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Char -> [(Char, Char)] -> Maybe Char
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Char
c [(Char, Char)]
escapes)

    escapes :: [(Char, Char)]
escapes =
      [ (Char
'n', Char
'\n'), (Char
't', Char
'\t'), (Char
'r', Char
'\r'), (Char
'0', Char
'\0')
      , (Char
'\\', Char
'\\'), (Char
'\'', Char
'\''), (Char
'"', Char
'"')
      ]

-- | A backtick-delimited shell command: everything up to the next backtick.
commandLit :: Parser Text
commandLit :: Parser Text
commandLit = Parser Text -> Parser Text
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
lexeme Parser Text
body Parser Text -> String -> Parser Text
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"backtick command"
  where
    body :: ParsecT Custom Text Identity (Tokens Text)
body = do
      Int
start <- ParsecT Custom Text Identity Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      Char
_ <- Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'`'
      Tokens Text
cmd <- Maybe String
-> (Token Text -> Bool)
-> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token Text -> Token Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
Token Text
'`')
      Maybe Char
closed <- ParsecT Custom Text Identity Char
-> ParsecT Custom Text Identity (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'`')
      case Maybe Char
closed of
        Maybe Char
Nothing -> Int -> Custom -> ParsecT Custom Text Identity (Tokens Text)
forall a. Int -> Custom -> Parser a
failAt Int
start Custom
CUnterminatedCommand
        Just Char
_  -> Tokens Text -> ParsecT Custom Text Identity (Tokens Text)
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Tokens Text
cmd

-- | Parse a variable attribute.
attribute :: Parser VarAttr
attribute :: Parser VarAttr
attribute = VarAttr -> Parser VarAttr -> Parser VarAttr
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option VarAttr
Public (VarAttr
Secret VarAttr -> Parser Text -> Parser VarAttr
forall a b.
a
-> ParsecT Custom Text Identity b -> ParsecT Custom Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Parser Text -> Parser Text
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Parser Text
keyword Parser Text -> Parser () -> Parser Text
forall a b.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity b -> ParsecT Custom Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Custom Text Identity Char -> Parser ()
forall a. ParsecT Custom Text Identity a -> Parser ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy (Token Text -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'=')))
  where
    keyword :: ParsecT Custom Text Identity (Tokens Text)
keyword = ParsecT Custom Text Identity (Tokens Text)
-> ParsecT Custom Text Identity (Tokens Text)
forall a.
ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
lexeme (Tokens Text -> ParsecT Custom Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"secret" ParsecT Custom Text Identity (Tokens Text)
-> Parser () -> ParsecT Custom Text Identity (Tokens Text)
forall a b.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity b -> ParsecT Custom Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Custom Text Identity (Token Text) -> Parser ()
forall a. ParsecT Custom Text Identity a -> Parser ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy ((Token Text -> Bool) -> ParsecT Custom Text Identity (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token Text -> Bool
isNameChar))
    isNameChar :: Char -> Bool
isNameChar Char
x = Char -> Bool
isAlphaNum Char
x Bool -> Bool -> Bool
|| Char
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\''

-- | Parser a variable declaration.
declaration :: Parser Declaration
declaration :: Parser Declaration
declaration = do
  Position
pos   <- Parser Position
currentPosition
  VarAttr
attr  <- Parser VarAttr
attribute
  Text
name  <- Parser Text
varName
  Text
_     <- Text -> Parser Text
symbol Text
"="
  Value
value <- VarAttr -> Parser Value -> Parser Value
forall a. VarAttr -> Parser a -> Parser a
withholdIfSecret VarAttr
attr (Text -> Value
StringValue (Text -> Value) -> Parser Text -> Parser Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parser Text
stringLit Parser Value -> Parser Value -> Parser Value
forall a.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Text -> Value
CommandValue (Text -> Value) -> Parser Text -> Parser Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parser Text
commandLit)
  case Value
value of
    StringValue Text
_  -> Parser Text -> Parser ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Text -> Parser Text
symbol Text
";")
    CommandValue Text
_ -> ParsecT Custom Text Identity (Maybe Text) -> Parser ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Parser Text -> ParsecT Custom Text Identity (Maybe Text)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (Text -> Parser Text
symbol Text
";"))
  Declaration -> Parser Declaration
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> VarAttr -> Value -> Position -> Declaration
Declaration Text
name VarAttr
attr Value
value Position
pos)

-- | Run a parser for the value of a declaration. If it fails inside a
-- 'Secret' value, strip from the error any input that was quoted in it: the
-- unexpected character (which could be the start of the secret) and the
-- character after a bad backslash.
withholdIfSecret :: VarAttr -> Parser a -> Parser a
withholdIfSecret :: forall a. VarAttr -> Parser a -> Parser a
withholdIfSecret VarAttr
Public Parser a
p = Parser a
p
withholdIfSecret VarAttr
Secret Parser a
p = Parser a
-> ParsecT Custom Text Identity (Either (ParseError Text Custom) a)
forall a.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity (Either (ParseError Text Custom) a)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> m (Either (ParseError s e) a)
observing Parser a
p ParsecT Custom Text Identity (Either (ParseError Text Custom) a)
-> (Either (ParseError Text Custom) a -> Parser a) -> Parser a
forall a b.
ParsecT Custom Text Identity a
-> (a -> ParsecT Custom Text Identity b)
-> ParsecT Custom Text Identity b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ParseError Text Custom -> Parser a)
-> (a -> Parser a) -> Either (ParseError Text Custom) a -> Parser a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (ParseError Text Custom -> Parser a
forall a. ParseError Text Custom -> ParsecT Custom Text Identity a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
ParseError s e -> m a
parseError (ParseError Text Custom -> Parser a)
-> (ParseError Text Custom -> ParseError Text Custom)
-> ParseError Text Custom
-> Parser a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ParseError Text Custom -> ParseError Text Custom
forall {s} {s}.
(Token s ~ Token s) =>
ParseError s Custom -> ParseError s Custom
withhold) a -> Parser a
forall a. a -> ParsecT Custom Text Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
  where
    withhold :: ParseError s Custom -> ParseError s Custom
withhold (TrivialError Int
o Maybe (ErrorItem (Token s))
_ Set (ErrorItem (Token s))
expected) = Int
-> Maybe (ErrorItem (Token s))
-> Set (ErrorItem (Token s))
-> ParseError s Custom
forall s e.
Int
-> Maybe (ErrorItem (Token s))
-> Set (ErrorItem (Token s))
-> ParseError s e
TrivialError Int
o Maybe (ErrorItem (Token s))
forall a. Maybe a
Nothing Set (ErrorItem (Token s))
Set (ErrorItem (Token s))
expected
    withhold (FancyError Int
o Set (ErrorFancy Custom)
fancy)        = Int -> Set (ErrorFancy Custom) -> ParseError s Custom
forall s e. Int -> Set (ErrorFancy e) -> ParseError s e
FancyError Int
o ((ErrorFancy Custom -> ErrorFancy Custom)
-> Set (ErrorFancy Custom) -> Set (ErrorFancy Custom)
forall b a. Ord b => (a -> b) -> Set a -> Set b
Set.map ErrorFancy Custom -> ErrorFancy Custom
hide Set (ErrorFancy Custom)
fancy)
    hide :: ErrorFancy Custom -> ErrorFancy Custom
hide (ErrorCustom (CInvalidEscape Maybe Char
_)) = Custom -> ErrorFancy Custom
forall e. e -> ErrorFancy e
ErrorCustom (Maybe Char -> Custom
CInvalidEscape Maybe Char
forall a. Maybe a
Nothing)
    hide ErrorFancy Custom
f                                = ErrorFancy Custom
f

-- | A whole file: any number of declarations, with comments/whitespace anywhere.
program :: Parser [Declaration]
program :: Parsec Custom Text [Declaration]
program = Parser ()
sc Parser ()
-> Parsec Custom Text [Declaration]
-> Parsec Custom Text [Declaration]
forall a b.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity b -> ParsecT Custom Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Parser Declaration -> Parsec Custom Text [Declaration]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many Parser Declaration
declaration Parsec Custom Text [Declaration]
-> Parser () -> Parsec Custom Text [Declaration]
forall a b.
ParsecT Custom Text Identity a
-> ParsecT Custom Text Identity b -> ParsecT Custom Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof