-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMisc.hs
84 lines (75 loc) · 2.8 KB
/
Misc.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{-# LANGUAGE
OverloadedStrings
, FlexibleContexts
#-}
module Misc
( (=:)
, int
, loggedExceptT
, parseEither
, readT
, quotedString
)
where
import Control.Arrow ( left )
import Control.Monad.Except ( ExceptT
, runExceptT
, (<=<)
)
import Data.Text ( Text
, pack
, unpack
)
import Logger ( Logger
, Priority(..)
)
import Text.Parsec ( (<|>)
, between
, char
, digit
, many
, many1
, noneOf
, oneOf
, parse
, string
)
import Text.Parsec.Error ( ParseError
, showErrorMessages
, errorMessages
)
import Text.Parsec.Text ( Parser )
import Text.Read ( readMaybe )
-- custom error printer to avoid printing line number,
-- constant strings were copied from parsec source code
showShort :: ParseError -> Text
showShort err = pack $ showErrorMessages
"or"
"unknown parse error"
"expecting"
"unexpected"
"end of input"
(errorMessages err)
parseEither :: Text -> Parser a -> Text -> Either Text a
parseEither what parser =
left ((("Error parsing " <> what <> ": ") <>) . showShort)
. parse parser ""
(=:) :: a -> b -> (a, b)
a =: b = (a, b)
loggedExceptT :: Logger -> ExceptT Text IO () -> IO ()
loggedExceptT log = either (log Error) pure <=< runExceptT
readT :: Read a => Text -> Maybe a
readT = readMaybe . unpack
quotedString :: Parser String
quotedString = between (string "\"" <|> string "\"\n")
(string "\"" <|> string "\n\"")
(many qchar)
where
qchar = noneOf ['\\', '"'] <|> do
_ <- char '\\'
c <- oneOf ['\\', '"', 'n']
return $ case c of
'n' -> '\n'
x -> x
int :: Parser Int
int = read <$> many1 digit