2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow, 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- The 'Read' class and instances for basic data types.
15 -----------------------------------------------------------------------------
22 , ReadS -- :: *; = String -> [(a,String)]
25 , reads -- :: Read a => ReadS a
26 , readp -- :: Read a => ReadP a
27 , readEither -- :: Read a => String -> Either String a
28 , read -- :: Read a => String -> a
31 , lex -- :: ReadS String
32 , lexLitChar -- :: ReadS String
33 , readLitChar -- :: ReadS Char
34 , lexDigits -- :: ReadS String
37 , lexP -- :: ReadPrec Lexeme
38 , paren -- :: ReadPrec a -> ReadPrec a
39 , parens -- :: ReadPrec a -> ReadPrec a
40 , list -- :: ReadPrec a -> ReadPrec [a]
41 , choose -- :: [(String, ReadPrec a)] -> ReadPrec a
42 , readListDefault, readListPrecDefault
49 import qualified Text.ParserCombinators.ReadP as P
51 import Text.ParserCombinators.ReadP
57 import qualified Text.Read.Lex as L
58 -- Lex exports 'lex', which is also defined here,
59 -- hence the qualified import.
60 -- We can't import *anything* unqualified, because that
63 import Text.ParserCombinators.ReadPrec
68 import {-# SOURCE #-} GHC.Err ( error )
70 import {-# SOURCE #-} GHC.Unicode ( isDigit )
83 -- | @'readParen' 'True' p@ parses what @p@ parses, but surrounded with
86 -- @'readParen' 'False' p@ parses what @p@ parses, but optionally
87 -- surrounded with parentheses.
88 readParen :: Bool -> ReadS a -> ReadS a
89 -- A Haskell 98 function
90 readParen b g = if b then mandatory else optional
91 where optional r = g r ++ mandatory r
100 %*********************************************************
102 \subsection{The @Read@ class}
104 %*********************************************************
107 ------------------------------------------------------------------------
110 -- | Parsing of 'String's, producing values.
112 -- Minimal complete definition: 'readsPrec' (or, for GHC only, 'readPrec')
114 -- Derived instances of 'Read' make the following assumptions, which
115 -- derived instances of 'Text.Show.Show' obey:
117 -- * If the constructor is defined to be an infix operator, then the
118 -- derived 'Read' instance will parse only infix applications of
119 -- the constructor (not the prefix form).
121 -- * Associativity is not used to reduce the occurrence of parentheses,
122 -- although precedence may be.
124 -- * If the constructor is defined using record syntax, the derived 'Read'
125 -- will parse only the record-syntax form, and furthermore, the fields
126 -- must be given in the same order as the original declaration.
128 -- * The derived 'Read' instance allows arbitrary Haskell whitespace
129 -- between tokens of the input string. Extra parentheses are also
132 -- For example, given the declarations
135 -- > data Tree a = Leaf a | Tree a :^: Tree a
137 -- the derived instance of 'Read' is equivalent to
139 -- > instance (Read a) => Read (Tree a) where
141 -- > readsPrec d r = readParen (d > up_prec)
142 -- > (\r -> [(u:^:v,w) |
143 -- > (u,s) <- readsPrec (up_prec+1) r,
144 -- > (":^:",t) <- lex s,
145 -- > (v,w) <- readsPrec (up_prec+1) t]) r
147 -- > ++ readParen (d > app_prec)
148 -- > (\r -> [(Leaf m,t) |
149 -- > ("Leaf",s) <- lex r,
150 -- > (m,t) <- readsPrec (app_prec+1) s]) r
152 -- > where up_prec = 5
155 -- Note that right-associativity of @:^:@ is unused.
158 -- | attempts to parse a value from the front of the string, returning
159 -- a list of (parsed value, remaining string) pairs. If there is no
160 -- successful parse, the returned list is empty.
162 -- Derived instances of 'Read' and 'Text.Show.Show' satisfy the following:
164 -- * @(x,\"\")@ is an element of
165 -- @('readsPrec' d ('Text.Show.showsPrec' d x \"\"))@.
167 -- That is, 'readsPrec' parses the string produced by
168 -- 'Text.Show.showsPrec', and delivers the value that
169 -- 'Text.Show.showsPrec' started with.
171 readsPrec :: Int -- ^ the operator precedence of the enclosing
172 -- context (a number from @0@ to @11@).
173 -- Function application has precedence @10@.
176 -- | The method 'readList' is provided to allow the programmer to
177 -- give a specialised way of parsing lists of values.
178 -- For example, this is used by the predefined 'Read' instance of
179 -- the 'Char' type, where values of type 'String' should be are
180 -- expected to use double quotes, rather than square brackets.
181 readList :: ReadS [a]
183 -- | Proposed replacement for 'readsPrec' using new-style parsers (GHC only).
184 readPrec :: ReadPrec a
186 -- | Proposed replacement for 'readList' using new-style parsers (GHC only).
187 readListPrec :: ReadPrec [a]
189 -- default definitions
190 readsPrec = readPrec_to_S readPrec
191 readList = readPrec_to_S (list readPrec) 0
192 readPrec = readS_to_Prec readsPrec
193 readListPrec = readS_to_Prec (\_ -> readList)
195 readListDefault :: Read a => ReadS [a]
196 -- ^ Use this to define the 'readList' method, if you don't want a special
197 -- case (GHC only; for other systems the default suffices).
198 readListDefault = readPrec_to_S readListPrec 0
200 readListPrecDefault :: Read a => ReadPrec [a]
201 -- ^ Use this to define the 'readListPrec' method, if you
202 -- don't want a special case (GHC only).
203 readListPrecDefault = list readPrec
205 ------------------------------------------------------------------------
208 -- | equivalent to 'readsPrec' with a precedence of 0.
209 reads :: Read a => ReadS a
210 reads = readsPrec minPrec
212 readp :: Read a => ReadP a
213 readp = readPrec_to_P readPrec minPrec
215 readEither :: Read a => String -> Either String a
217 case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
219 [] -> Left "Prelude.read: no parse"
220 _ -> Left "Prelude.read: ambiguous parse"
227 -- | The 'read' function reads input from a string, which must be
228 -- completely consumed by the input process.
229 read :: Read a => String -> a
230 read s = either error id (readEither s)
232 ------------------------------------------------------------------------
235 -- | The 'lex' function reads a single lexeme from the input, discarding
236 -- initial white space, and returning the characters that constitute the
237 -- lexeme. If the input string contains only white space, 'lex' returns a
238 -- single successful \`lexeme\' consisting of the empty string. (Thus
239 -- @'lex' \"\" = [(\"\",\"\")]@.) If there is no legal lexeme at the
240 -- beginning of the input string, 'lex' fails (i.e. returns @[]@).
242 -- This lexer is not completely faithful to the Haskell lexical syntax
243 -- in the following respects:
245 -- * Qualified names are not handled properly
247 -- * Octal and hexadecimal numerics are not recognized as a single token
249 -- * Comments are not treated properly
250 lex :: ReadS String -- As defined by H98
251 lex s = readP_to_S L.hsLex s
253 -- | Read a string representation of a character, using Haskell
254 -- source-language escape conventions. For example:
256 -- > lexLitChar "\\nHello" = [("\\n", "Hello")]
258 lexLitChar :: ReadS String -- As defined by H98
259 lexLitChar = readP_to_S (do { (s, _) <- P.gather L.lexChar ;
261 -- There was a skipSpaces before the P.gather L.lexChar,
262 -- but that seems inconsistent with readLitChar
264 -- | Read a string representation of a character, using Haskell
265 -- source-language escape conventions, and convert it to the character
266 -- that it encodes. For example:
268 -- > readLitChar "\\nHello" = [('\n', "Hello")]
270 readLitChar :: ReadS Char -- As defined by H98
271 readLitChar = readP_to_S L.lexChar
273 -- | Reads a non-empty string of decimal digits.
274 lexDigits :: ReadS String
275 lexDigits = readP_to_S (P.munch1 isDigit)
277 ------------------------------------------------------------------------
280 lexP :: ReadPrec L.Lexeme
281 -- ^ Parse a single lexeme
284 paren :: ReadPrec a -> ReadPrec a
285 -- ^ @(paren p)@ parses \"(P0)\"
286 -- where @p@ parses \"P0\" in precedence context zero
287 paren p = do L.Punc "(" <- lexP
292 parens :: ReadPrec a -> ReadPrec a
293 -- ^ @(parens p)@ parses \"P\", \"(P0)\", \"((P0))\", etc,
294 -- where @p@ parses \"P\" in the current precedence context
295 -- parses \"P0\" in precedence context zero
298 optional = p +++ mandatory
299 mandatory = paren optional
301 list :: ReadPrec a -> ReadPrec [a]
302 -- ^ @(list p)@ parses a list of things parsed by @p@,
303 -- using the usual square-bracket syntax.
306 ( do L.Punc "[" <- lexP
307 (listRest False +++ listNext)
314 "," | started -> listNext
322 choose :: [(String, ReadPrec a)] -> ReadPrec a
323 -- ^ Parse the specified lexeme and continue as specified.
324 -- Esp useful for nullary constructors; e.g.
325 -- @choose [(\"A\", return A), (\"B\", return B)]@
326 choose sps = foldr ((+++) . try_one) pfail sps
328 try_one (s,p) = do { L.Ident s' <- lexP ;
329 if s == s' then p else pfail }
333 %*********************************************************
335 \subsection{Simple instances of Read}
337 %*********************************************************
340 instance Read Char where
343 ( do L.Char c <- lexP
349 ( do L.String s <- lexP -- Looks for "foo"
352 readListPrecDefault -- Looks for ['f','o','o']
353 ) -- (more generous than H98 spec)
355 readList = readListDefault
357 instance Read Bool where
360 ( do L.Ident s <- lexP
362 "True" -> return True
363 "False" -> return False
367 readListPrec = readListPrecDefault
368 readList = readListDefault
370 instance Read Ordering where
373 ( do L.Ident s <- lexP
381 readListPrec = readListPrecDefault
382 readList = readListDefault
386 %*********************************************************
388 \subsection{Structure instances of Read: Maybe, List etc}
390 %*********************************************************
392 For structured instances of Read we start using the precedences. The
393 idea is then that 'parens (prec k p)' will fail immediately when trying
394 to parse it in a context with a higher precedence level than k. But if
395 there is one parenthesis parsed, then the required precedence level
396 drops to 0 again, and parsing inside p may succeed.
398 'appPrec' is just the precedence level of function application. So,
399 if we are parsing function application, we'd better require the
400 precedence level to be at least 'appPrec'. Otherwise, we have to put
401 parentheses around it.
403 'step' is used to increase the precedence levels inside a
404 parser, and can be used to express left- or right- associativity. For
405 example, % is defined to be left associative, so we only increase
406 precedence on the right hand side.
408 Note how step is used in for example the Maybe parser to increase the
409 precedence beyond appPrec, so that basically only literals and
410 parenthesis-like objects such as (...) and [...] can be an argument to
414 instance Read a => Read (Maybe a) where
417 (do L.Ident "Nothing" <- lexP
421 do L.Ident "Just" <- lexP
426 readListPrec = readListPrecDefault
427 readList = readListDefault
429 instance (Read a, Read b) => Read (Either a b) where
433 ( do L.Ident "Left" <- lexP
437 do L.Ident "Right" <- lexP
443 readListPrec = readListPrecDefault
444 readList = readListDefault
446 instance Read a => Read [a] where
447 readPrec = readListPrec
448 readListPrec = readListPrecDefault
449 readList = readListDefault
451 instance (Ix a, Read a, Read b) => Read (Array a b) where
452 readPrec = parens $ prec appPrec $
453 do L.Ident "array" <- lexP
454 bounds <- step readPrec
455 vals <- step readPrec
456 return (array bounds vals)
458 readListPrec = readListPrecDefault
459 readList = readListDefault
461 instance Read L.Lexeme where
463 readListPrec = readListPrecDefault
464 readList = readListDefault
468 %*********************************************************
470 \subsection{Numeric instances of Read}
472 %*********************************************************
475 readNumber :: Num a => (L.Lexeme -> Maybe a) -> ReadPrec a
476 -- Read a signed number
481 L.Symbol "-" -> do n <- readNumber convert
484 _ -> case convert x of
489 convertInt :: Num a => L.Lexeme -> Maybe a
490 convertInt (L.Int i) = Just (fromInteger i)
491 convertInt _ = Nothing
493 convertFrac :: Fractional a => L.Lexeme -> Maybe a
494 convertFrac (L.Int i) = Just (fromInteger i)
495 convertFrac (L.Rat r) = Just (fromRational r)
496 convertFrac _ = Nothing
498 instance Read Int where
499 readPrec = readNumber convertInt
500 readListPrec = readListPrecDefault
501 readList = readListDefault
503 instance Read Integer where
504 readPrec = readNumber convertInt
505 readListPrec = readListPrecDefault
506 readList = readListDefault
508 instance Read Float where
509 readPrec = readNumber convertFrac
510 readListPrec = readListPrecDefault
511 readList = readListDefault
513 instance Read Double where
514 readPrec = readNumber convertFrac
515 readListPrec = readListPrecDefault
516 readList = readListDefault
518 instance (Integral a, Read a) => Read (Ratio a) where
522 ( do x <- step readPrec
529 readListPrec = readListPrecDefault
530 readList = readListDefault
534 %*********************************************************
536 \subsection{Tuple instances of Read}
538 %*********************************************************
541 instance Read () where
549 readListPrec = readListPrecDefault
550 readList = readListDefault
552 instance (Read a, Read b) => Read (a,b) where
563 readListPrec = readListPrecDefault
564 readList = readListDefault
567 instance (Read a, Read b, Read c) => Read (a, b, c) where
580 readListPrec = readListPrecDefault
581 readList = readListDefault
583 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
598 readListPrec = readListPrecDefault
599 readList = readListDefault
601 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
618 readListPrec = readListPrecDefault
619 readList = readListDefault