Debian Codegraph @

Data/Csv/Parser/Megaparsec/Internals.hs

raw symbols SCIP
1 -- |
2 -- Module : Data.Csv.Parser.Megaparsec.Internals
3 -- Copyright : © 2016–2021 Stack Builders
4 -- License : MIT
5 --
6
7 {-# LANGUAGE BangPatterns #-}
8 {-# LANGUAGE DeriveDataTypeable #-}
9 {-# LANGUAGE OverloadedStrings #-}
10 {-# LANGUAGE RecordWildCards #-}
11
12 module Data.Csv.Parser.Megaparsec.Internals
13 ( ConversionError (..)
14 , Parser
15 , csv
16 , csvWithHeader
17 , decodeWithC
18 , toNamedRecord
19 , header
20 , name
21 , record
22 , field
23 , escapedField
24 , unescapedField)
25 where
26
27 import Control.Monad
28 import Data.ByteString (ByteString)
29 import Data.Csv hiding
30 ( Parser
31 , record
32 , header
33 , toNamedRecord )
34 import Data.Data
35 import Data.Vector (Vector)
36 import Data.Word (Word8)
37 import Text.Megaparsec
38 import Text.Megaparsec.Byte
39 import qualified Data.ByteString as B
40 import qualified Data.ByteString.Lazy as BL
41 import qualified Data.Csv as C
42 import qualified Data.HashMap.Strict as H
43 import qualified Data.Vector as V
44
45 ----------------------------------------------------------------------------
46 -- Custom error component and other types
47
48 -- | Custom error component for CSV parsing. It allows typed reporting of
49 -- conversion errors.
50
51 newtype ConversionError = ConversionError String
52 deriving (Eq, Data, Typeable, Ord, Read, Show)
53
54 instance ShowErrorComponent ConversionError where
55 showErrorComponent (ConversionError msg) =
56 "conversion error: " ++ msg
57
58 -- | Parser type that uses “custom error component” 'ConversionError'.
59
60 type Parser = Parsec ConversionError BL.ByteString
61
62 ----------------------------------------------------------------------------
63 -- The parser
64
65 -- | Parse a CSV file that does not include a header.
66
67 csv :: FromRecord a
68 => DecodeOptions -- ^ Decoding options
69 -> Parser (Vector a) -- ^ The parser that parses collection of records
70 csv DecodeOptions {..} = do
71 xs <- sepEndBy1 (record decDelimiter parseRecord) eol
72 eof
73 return $! V.fromList xs
74
75 -- | Parse a CSV file that includes a header.
76
77 csvWithHeader :: FromNamedRecord a
78 => DecodeOptions -- ^ Decoding options
79 -> Parser (Header, Vector a)
80 -- ^ The parser that parser collection of named records
81 csvWithHeader DecodeOptions {..} = do
82 !hdr <- header decDelimiter
83 let f = parseNamedRecord . toNamedRecord hdr
84 xs <- sepEndBy1 (record decDelimiter f) eol
85 eof
86 return $ let !v = V.fromList xs in (hdr, v)
87
88 -- | Decode CSV data using the provided parser, skipping a leading header if
89 -- necessary.
90
91 decodeWithC
92 :: (DecodeOptions -> Parser a)
93 -- ^ Parsing function parametrized by 'DecodeOptions'
94 -> DecodeOptions
95 -- ^ Decoding options
96 -> HasHeader
97 -- ^ Whether to expect a header in the input
98 -> FilePath
99 -- ^ File name (only for displaying in parse error messages, use empty
100 -- string if you have none)
101 -> BL.ByteString
102 -- ^ CSV data
103 -> Either (ParseErrorBundle BL.ByteString ConversionError) a
104 decodeWithC p opts@DecodeOptions {..} hasHeader = parse parser
105 where
106 parser = case hasHeader of
107 HasHeader -> header decDelimiter *> p opts
108 NoHeader -> p opts
109 {-# INLINE decodeWithC #-}
110
111 -- | Convert a 'Record' to a 'NamedRecord' by attaching column names. The
112 -- 'Header' and 'Record' must be of the same length.
113
114 toNamedRecord :: Header -> Record -> NamedRecord
115 toNamedRecord hdr v = H.fromList . V.toList $ V.zip hdr v
116 {-# INLINE toNamedRecord #-}
117
118 -- | Parse a header, including the terminating line separator.
119
120 header :: Word8 -> Parser Header
121 header del = V.fromList <$!> p <* eol
122 where
123 p = sepBy1 (name del) (void $ char del) <?> "file header"
124 {-# INLINE header #-}
125
126 -- | Parse a header name. Header names have the same format as regular
127 -- 'field's.
128
129 name :: Word8 -> Parser Name
130 name del = field del <?> "name in header"
131 {-# INLINE name #-}
132
133 -- | Parse a record, not including the terminating line separator. The
134 -- terminating line separate is not included as the last record in a CSV
135 -- file is allowed to not have a terminating line separator.
136
137 record
138 :: Word8 -- ^ Field delimiter
139 -> (Record -> C.Parser a)
140 -- ^ How to “parse” record to get the data of interest
141 -> Parser a
142 record del f = do
143 notFollowedBy eof -- to prevent reading empty line at the end of file
144 r <- V.fromList <$!> (sepBy1 (field del) (void $ char del) <?> "record")
145 case C.runParser (f r) of
146 Left msg -> customFailure (ConversionError msg)
147 Right x -> return x
148 {-# INLINE record #-}
149
150 -- | Parse a field. The field may be in either the escaped or non-escaped
151 -- format. The returned value is unescaped.
152
153 field :: Word8 -> Parser Field
154 field del = label "field" (escapedField <|> unescapedField del)
155 {-# INLINE field #-}
156
157 -- | Parse an escaped field.
158
159 escapedField :: Parser ByteString
160 escapedField =
161 B.pack <$!> between (char 34) (char 34) (many $ normalChar <|> escapedDq)
162 where
163 normalChar = anySingleBut 34 <?> "unescaped character"
164 escapedDq = label "escaped double-quote" (34 <$ string "\"\"")
165 {-# INLINE escapedField #-}
166
167 -- | Parse an unescaped field.
168
169 unescapedField :: Word8 -> Parser ByteString
170 unescapedField del = BL.toStrict <$> takeWhileP (Just "unescaped character") f
171 where
172 f x = x /= del && x /= 34 && x /= 10 && x /= 13
173 {-# INLINE unescapedField #-}