2 % (c) The AQUA Project, Glasgow University, 1994-1998
5 \section[PrelRead]{Module @PrelRead@}
7 Instances of the Read class.
10 {-# OPTIONS -fno-implicit-prelude #-}
14 import {-# SOURCE #-} PrelErr ( error )
24 import PrelIOBase ( IO, fail, userError )
28 %*********************************************************
30 \subsection{The @Read@ class}
32 %*********************************************************
34 Note: if you compile this with -DNEW_READS_REP, you'll get
35 a (simpler) ReadS representation that only allow one valid
36 parse of a string of characters, instead of a list of
39 [changing the ReadS rep has implications for the deriving
40 machinery for Read, a change that hasn't been made, so you
41 probably won't want to compile in this new rep. except
42 when in an experimental mood.]
47 type ReadS a = String -> [(a,String)]
49 type ReadS a = String -> Maybe (a,String)
53 readsPrec :: Int -> ReadS a
56 readList = readList__ reads
59 %*********************************************************
61 \subsection{Utility functions}
63 %*********************************************************
66 reads :: (Read a) => ReadS a
69 read :: (Read a) => String -> a
74 [] -> error "PreludeText.read: no parse"
75 _ -> error "PreludeText.read: ambiguous parse"
78 Nothing -> error "PreludeText.read: no parse"
86 -- raises an exception instead of an error
87 readIO :: Read a => String -> IO a
88 readIO s = case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of
91 [] -> fail (userError "PreludeIO.readIO: no parse")
92 _ -> fail (userError "PreludeIO.readIO: ambiguous parse")
95 Nothing -> fail (userError "PreludeIO.readIO: no parse")
101 readParen :: Bool -> ReadS a -> ReadS a
102 readParen b g = if b then mandatory else optional
103 where optional r = g r ++ mandatory r
111 readList__ :: ReadS a -> ReadS [a]
114 = readParen False (\r -> do
118 (do { ("]",t) <- lex s ; return ([],t) }) ++
119 (do { (x,t) <- readx s ; (xs,u) <- readl2 t ; return (x:xs,u) })
122 (do { ("]",t) <- lex s ; return ([],t) }) ++
123 (do { (",",t) <- lex s ; (x,u) <- readx t ; (xs,v) <- readl2 u ; return (x:xs,v) })
128 %*********************************************************
130 \subsection{Lexical analysis}
132 %*********************************************************
134 This lexer is not completely faithful to the Haskell lexical syntax.
136 Qualified names are not handled properly
137 A `--' does not terminate a symbol
138 Octal and hexidecimal numerics are not recognized as a single token
143 lex "" = return ("","")
144 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
146 (ch, '\'':t) <- lexLitChar s
148 return ('\'':ch++"'", t)
150 (str,t) <- lexString s
154 lexString ('"':s) = return ("\"",s)
156 (ch,t) <- lexStrItem s
157 (str,u) <- lexString t
161 lexStrItem ('\\':'&':s) = return ("\\&",s)
162 lexStrItem ('\\':c:s) | isSpace c = do
163 ('\\':t) <- return (dropWhile isSpace s)
165 lexStrItem s = lexLitChar s
167 lex (c:s) | isSingle c = return ([c],s)
169 (sym,t) <- return (span isSym s)
172 (nam,t) <- return (span isIdChar s)
175 (ds,s) <- return (span isDigit s)
176 (fe,t) <- lexFracExp s
178 | otherwise = zero -- bad character
180 isSingle c = c `elem` ",;()[]{}_`"
181 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
182 isIdChar c = isAlphanum c || c `elem` "_'"
184 lexFracExp ('.':cs) = do
185 (ds,t) <- lex0Digits cs
188 lexFracExp s = return ("",s)
190 lexExp (e:s) | e `elem` "eE" =
193 guard (c `elem` "+-")
194 (ds,u) <- lexDigits t
195 return (e:c:ds,u)) ++
197 (ds,t) <- lexDigits s
200 lexExp s = return ("",s)
202 lexDigits :: ReadS String
203 lexDigits = nonnull isDigit
206 lex0Digits :: ReadS String
207 lex0Digits s = return (span isDigit s)
209 nonnull :: (Char -> Bool) -> ReadS String
211 (cs@(_:_),t) <- return (span p s)
214 lexLitChar :: ReadS String
215 lexLitChar ('\\':s) = do
219 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = return ([c],s)
220 lexEsc s@(d:_) | isDigit d = lexDigits s
223 lexLitChar (c:s) = return ([c],s)
227 %*********************************************************
229 \subsection{Instances of @Read@}
231 %*********************************************************
234 instance Read Char where
235 readsPrec p = readParen False
238 (c,_) <- readLitChar s
241 readList = readParen False (\r -> do
245 where readl ('"':s) = return ("",s)
246 readl ('\\':'&':s) = readl s
248 (c,t) <- readLitChar s
252 instance Read Bool where
253 readsPrec p = readParen False
256 (do { ("True", rest) <- return lr ; return (True, rest) }) ++
257 (do { ("False", rest) <- return lr ; return (False, rest) }))
260 instance Read Ordering where
261 readsPrec p = readParen False
264 (do { ("LT", rest) <- return lr ; return (LT, rest) }) ++
265 (do { ("EQ", rest) <- return lr ; return (EQ, rest) }) ++
266 (do { ("GT", rest) <- return lr ; return (GT, rest) }))
268 instance Read a => Read (Maybe a) where
269 readsPrec p = readParen False
272 (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
274 ("Just", rest1) <- return lr
275 (x, rest2) <- reads rest1
276 return (Just x, rest2)))
278 instance (Read a, Read b) => Read (Either a b) where
279 readsPrec p = readParen False
283 ("Left", rest1) <- return lr
284 (x, rest2) <- reads rest1
285 return (Left x, rest2)) ++
287 ("Right", rest1) <- return lr
288 (x, rest2) <- reads rest1
289 return (Right x, rest2)))
291 instance Read Int where
292 readsPrec p x = readSigned readDec x
294 instance Read Integer where
295 readsPrec p x = readSigned readDec x
297 instance Read Float where
298 readsPrec p x = readSigned readFloat x
300 instance Read Double where
301 readsPrec p x = readSigned readFloat x
303 instance (Integral a, Read a) => Read (Ratio a) where
304 readsPrec p = readParen (p > ratio_prec)
311 instance (Read a) => Read [a] where
312 readsPrec p = readList
314 instance Read () where
315 readsPrec p = readParen False
321 instance (Read a, Read b) => Read (a,b) where
322 readsPrec p = readParen False
325 (x,t) <- readsPrec 0 s
327 (y,v) <- readsPrec 0 u
331 instance (Read a, Read b, Read c) => Read (a, b, c) where
332 readsPrec p = readParen False
335 (x,c) <- readsPrec 0 b
337 (y,e) <- readsPrec 0 d
339 (z,g) <- readsPrec 0 f
343 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
344 readsPrec p = readParen False
347 (w,c) <- readsPrec 0 b
349 (x,e) <- readsPrec 0 d
351 (y,g) <- readsPrec 0 f
353 (z,h) <- readsPrec 0 h
355 return ((w,x,y,z), i))
357 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
358 readsPrec p = readParen False
361 (v,c) <- readsPrec 0 b
363 (w,e) <- readsPrec 0 d
365 (x,g) <- readsPrec 0 f
367 (y,i) <- readsPrec 0 h
369 (z,k) <- readsPrec 0 j
371 return ((v,w,x,y,z), l))
375 %*********************************************************
377 \subsection{Reading characters}
379 %*********************************************************
382 readLitChar :: ReadS Char
384 readLitChar ('\\':s) = readEsc s
386 readEsc ('a':s) = return ('\a',s)
387 readEsc ('b':s) = return ('\b',s)
388 readEsc ('f':s) = return ('\f',s)
389 readEsc ('n':s) = return ('\n',s)
390 readEsc ('r':s) = return ('\r',s)
391 readEsc ('t':s) = return ('\t',s)
392 readEsc ('v':s) = return ('\v',s)
393 readEsc ('\\':s) = return ('\\',s)
394 readEsc ('"':s) = return ('"',s)
395 readEsc ('\'':s) = return ('\'',s)
396 readEsc ('^':c:s) | c >= '@' && c <= '_'
397 = return (chr (ord c - ord '@'), s)
398 readEsc s@(d:_) | isDigit d
409 readEsc s@(c:_) | isUpper c
410 = let table = ('\DEL', "DEL") : zip ['\NUL'..] asciiTab
411 in case [(c,s') | (c, mne) <- table,
412 ([],s') <- [match mne s]]
413 of (pr:_) -> return pr
417 readLitChar (c:s) = return (c,s)
419 match :: (Eq a) => [a] -> [a] -> ([a],[a])
420 match (x:xs) (y:ys) | x == y = match xs ys
421 match xs ys = (xs,ys)
426 %*********************************************************
428 \subsection{Reading numbers}
430 %*********************************************************
432 Note: reading numbers at bases different than 10, does not
433 include lexing common prefixes such as '0x' or '0o' etc.
436 {-# SPECIALISE readDec ::
439 readDec :: (Integral a) => ReadS a
440 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
442 {-# SPECIALISE readOct ::
445 readOct :: (Integral a) => ReadS a
446 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
448 {-# SPECIALISE readHex ::
451 readHex :: (Integral a) => ReadS a
452 readHex = readInt 16 isHexDigit hex
453 where hex d = ord d - (if isDigit d then ord_0
454 else ord (if isUpper d then 'A' else 'a') - 10)
456 readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
457 readInt radix isDig digToInt s = do
458 (ds,r) <- nonnull isDig s
459 return (foldl1 (\n d -> n * radix + d) (map (fromInt . digToInt) ds), r)
461 {-# SPECIALISE readSigned ::
462 ReadS Int -> ReadS Int,
463 ReadS Integer -> ReadS Integer,
464 ReadS Double -> ReadS Double #-}
465 readSigned :: (Real a) => ReadS a -> ReadS a
466 readSigned readPos = readParen False read'
467 where read' r = read'' r ++
474 (n,"") <- readPos str
478 The functions readFloat below uses rational arithmetic
479 to ensure correct conversion between the floating-point radix and
480 decimal. It is often possible to use a higher-precision floating-
481 point type to obtain the same results.
484 {-# SPECIALISE readFloat ::
487 readFloat :: (RealFloat a) => ReadS a
489 (x,t) <- readRational r
490 return (fromRational x,t)
492 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
498 return ((n%1)*10^^(k-d), t )) ++
503 ("Infinity",t) <- lex r
507 (ds,s) <- lexDigits r
508 (ds',t) <- lexDotDigits s
509 return (read (ds++ds'), length ds', t)
511 readExp (e:s) | e `elem` "eE" = readExp' s
512 readExp s = return (0,s)
514 readExp' ('+':s) = readDec s
515 readExp' ('-':s) = do
518 readExp' s = readDec s
520 lexDotDigits ('.':s) = lex0Digits s
521 lexDotDigits s = return ("",s)
523 readRational__ :: String -> Rational -- we export this one (non-std)
524 -- NB: *does* handle a leading "-"
527 '-' : xs -> - (read_me xs)
531 = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
532 #ifndef NEW_READS_REP
534 [] -> error ("readRational__: no parse:" ++ top_s)
535 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
538 Nothing -> error ("readRational__: no parse:" ++ top_s)