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 )
25 import PrelIOBase ( IO, userError )
26 import PrelException ( fail )
29 %*********************************************************
31 \subsection{The @Read@ class}
33 %*********************************************************
35 Note: if you compile this with -DNEW_READS_REP, you'll get
36 a (simpler) ReadS representation that only allow one valid
37 parse of a string of characters, instead of a list of
40 [changing the ReadS rep has implications for the deriving
41 machinery for Read, a change that hasn't been made, so you
42 probably won't want to compile in this new rep. except
43 when in an experimental mood.]
48 type ReadS a = String -> [(a,String)]
50 type ReadS a = String -> Maybe (a,String)
54 readsPrec :: Int -> ReadS a
57 readList = readList__ reads
60 %*********************************************************
62 \subsection{Utility functions}
64 %*********************************************************
67 reads :: (Read a) => ReadS a
70 read :: (Read a) => String -> a
75 [] -> error "PreludeText.read: no parse"
76 _ -> error "PreludeText.read: ambiguous parse"
79 Nothing -> error "PreludeText.read: no parse"
87 -- raises an exception instead of an error
88 readIO :: Read a => String -> IO a
89 readIO s = case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of
92 [] -> fail (userError "PreludeIO.readIO: no parse")
93 _ -> fail (userError "PreludeIO.readIO: ambiguous parse")
96 Nothing -> fail (userError "PreludeIO.readIO: no parse")
102 readParen :: Bool -> ReadS a -> ReadS a
103 readParen b g = if b then mandatory else optional
104 where optional r = g r ++ mandatory r
112 readList__ :: ReadS a -> ReadS [a]
115 = readParen False (\r -> do
119 (do { ("]",t) <- lex s ; return ([],t) }) ++
120 (do { (x,t) <- readx s ; (xs,u) <- readl2 t ; return (x:xs,u) })
123 (do { ("]",t) <- lex s ; return ([],t) }) ++
124 (do { (",",t) <- lex s ; (x,u) <- readx t ; (xs,v) <- readl2 u ; return (x:xs,v) })
129 %*********************************************************
131 \subsection{Lexical analysis}
133 %*********************************************************
135 This lexer is not completely faithful to the Haskell lexical syntax.
137 Qualified names are not handled properly
138 A `--' does not terminate a symbol
139 Octal and hexidecimal numerics are not recognized as a single token
144 lex "" = return ("","")
145 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
147 (ch, '\'':t) <- lexLitChar s
149 return ('\'':ch++"'", t)
151 (str,t) <- lexString s
155 lexString ('"':s) = return ("\"",s)
157 (ch,t) <- lexStrItem s
158 (str,u) <- lexString t
162 lexStrItem ('\\':'&':s) = return ("\\&",s)
163 lexStrItem ('\\':c:s) | isSpace c = do
164 ('\\':t) <- return (dropWhile isSpace s)
166 lexStrItem s = lexLitChar s
168 lex (c:s) | isSingle c = return ([c],s)
170 (sym,t) <- return (span isSym s)
173 (nam,t) <- return (span isIdChar s)
176 (ds,s) <- return (span isDigit s)
177 (fe,t) <- lexFracExp s
179 | otherwise = zero -- bad character
181 isSingle c = c `elem` ",;()[]{}_`"
182 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
183 isIdChar c = isAlphanum c || c `elem` "_'"
185 lexFracExp ('.':cs) = do
186 (ds,t) <- lex0Digits cs
189 lexFracExp s = return ("",s)
191 lexExp (e:s) | e `elem` "eE" =
194 guard (c `elem` "+-")
195 (ds,u) <- lexDigits t
196 return (e:c:ds,u)) ++
198 (ds,t) <- lexDigits s
201 lexExp s = return ("",s)
203 lexDigits :: ReadS String
204 lexDigits = nonnull isDigit
207 lex0Digits :: ReadS String
208 lex0Digits s = return (span isDigit s)
210 nonnull :: (Char -> Bool) -> ReadS String
212 (cs@(_:_),t) <- return (span p s)
215 lexLitChar :: ReadS String
216 lexLitChar ('\\':s) = do
220 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = return ([c],s)
221 lexEsc s@(d:_) | isDigit d = lexDigits s
224 lexLitChar (c:s) = return ([c],s)
228 %*********************************************************
230 \subsection{Instances of @Read@}
232 %*********************************************************
235 instance Read Char where
236 readsPrec p = readParen False
239 (c,_) <- readLitChar s
242 readList = readParen False (\r -> do
246 where readl ('"':s) = return ("",s)
247 readl ('\\':'&':s) = readl s
249 (c,t) <- readLitChar s
253 instance Read Bool where
254 readsPrec p = readParen False
257 (do { ("True", rest) <- return lr ; return (True, rest) }) ++
258 (do { ("False", rest) <- return lr ; return (False, rest) }))
261 instance Read Ordering where
262 readsPrec p = readParen False
265 (do { ("LT", rest) <- return lr ; return (LT, rest) }) ++
266 (do { ("EQ", rest) <- return lr ; return (EQ, rest) }) ++
267 (do { ("GT", rest) <- return lr ; return (GT, rest) }))
269 instance Read a => Read (Maybe a) where
270 readsPrec p = readParen False
273 (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
275 ("Just", rest1) <- return lr
276 (x, rest2) <- reads rest1
277 return (Just x, rest2)))
279 instance (Read a, Read b) => Read (Either a b) where
280 readsPrec p = readParen False
284 ("Left", rest1) <- return lr
285 (x, rest2) <- reads rest1
286 return (Left x, rest2)) ++
288 ("Right", rest1) <- return lr
289 (x, rest2) <- reads rest1
290 return (Right x, rest2)))
292 instance Read Int where
293 readsPrec p x = readSigned readDec x
295 instance Read Integer where
296 readsPrec p x = readSigned readDec x
298 instance Read Float where
299 readsPrec p x = readSigned readFloat x
301 instance Read Double where
302 readsPrec p x = readSigned readFloat x
304 instance (Integral a, Read a) => Read (Ratio a) where
305 readsPrec p = readParen (p > ratio_prec)
312 instance (Read a) => Read [a] where
313 readsPrec p = readList
315 instance Read () where
316 readsPrec p = readParen False
322 instance (Read a, Read b) => Read (a,b) where
323 readsPrec p = readParen False
326 (x,t) <- readsPrec 0 s
328 (y,v) <- readsPrec 0 u
332 instance (Read a, Read b, Read c) => Read (a, b, c) where
333 readsPrec p = readParen False
336 (x,c) <- readsPrec 0 b
338 (y,e) <- readsPrec 0 d
340 (z,g) <- readsPrec 0 f
344 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
345 readsPrec p = readParen False
348 (w,c) <- readsPrec 0 b
350 (x,e) <- readsPrec 0 d
352 (y,g) <- readsPrec 0 f
354 (z,h) <- readsPrec 0 h
356 return ((w,x,y,z), i))
358 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
359 readsPrec p = readParen False
362 (v,c) <- readsPrec 0 b
364 (w,e) <- readsPrec 0 d
366 (x,g) <- readsPrec 0 f
368 (y,i) <- readsPrec 0 h
370 (z,k) <- readsPrec 0 j
372 return ((v,w,x,y,z), l))
376 %*********************************************************
378 \subsection{Reading characters}
380 %*********************************************************
383 readLitChar :: ReadS Char
385 readLitChar ('\\':s) = readEsc s
387 readEsc ('a':s) = return ('\a',s)
388 readEsc ('b':s) = return ('\b',s)
389 readEsc ('f':s) = return ('\f',s)
390 readEsc ('n':s) = return ('\n',s)
391 readEsc ('r':s) = return ('\r',s)
392 readEsc ('t':s) = return ('\t',s)
393 readEsc ('v':s) = return ('\v',s)
394 readEsc ('\\':s) = return ('\\',s)
395 readEsc ('"':s) = return ('"',s)
396 readEsc ('\'':s) = return ('\'',s)
397 readEsc ('^':c:s) | c >= '@' && c <= '_'
398 = return (chr (ord c - ord '@'), s)
399 readEsc s@(d:_) | isDigit d
410 readEsc s@(c:_) | isUpper c
411 = let table = ('\DEL', "DEL") : zip ['\NUL'..] asciiTab
412 in case [(c,s') | (c, mne) <- table,
413 ([],s') <- [match mne s]]
414 of (pr:_) -> return pr
418 readLitChar (c:s) = return (c,s)
420 match :: (Eq a) => [a] -> [a] -> ([a],[a])
421 match (x:xs) (y:ys) | x == y = match xs ys
422 match xs ys = (xs,ys)
427 %*********************************************************
429 \subsection{Reading numbers}
431 %*********************************************************
433 Note: reading numbers at bases different than 10, does not
434 include lexing common prefixes such as '0x' or '0o' etc.
437 {-# SPECIALISE readDec ::
440 readDec :: (Integral a) => ReadS a
441 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
443 {-# SPECIALISE readOct ::
446 readOct :: (Integral a) => ReadS a
447 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
449 {-# SPECIALISE readHex ::
452 readHex :: (Integral a) => ReadS a
453 readHex = readInt 16 isHexDigit hex
454 where hex d = ord d - (if isDigit d then ord_0
455 else ord (if isUpper d then 'A' else 'a') - 10)
457 readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
458 readInt radix isDig digToInt s = do
459 (ds,r) <- nonnull isDig s
460 return (foldl1 (\n d -> n * radix + d) (map (fromInt . digToInt) ds), r)
462 {-# SPECIALISE readSigned ::
463 ReadS Int -> ReadS Int,
464 ReadS Integer -> ReadS Integer,
465 ReadS Double -> ReadS Double #-}
466 readSigned :: (Real a) => ReadS a -> ReadS a
467 readSigned readPos = readParen False read'
468 where read' r = read'' r ++
475 (n,"") <- readPos str
479 The functions readFloat below uses rational arithmetic
480 to ensure correct conversion between the floating-point radix and
481 decimal. It is often possible to use a higher-precision floating-
482 point type to obtain the same results.
485 {-# SPECIALISE readFloat ::
488 readFloat :: (RealFloat a) => ReadS a
490 (x,t) <- readRational r
491 return (fromRational x,t)
493 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
499 return ((n%1)*10^^(k-d), t )) ++
504 ("Infinity",t) <- lex r
508 (ds,s) <- lexDigits r
509 (ds',t) <- lexDotDigits s
510 return (read (ds++ds'), length ds', t)
512 readExp (e:s) | e `elem` "eE" = readExp' s
513 readExp s = return (0,s)
515 readExp' ('+':s) = readDec s
516 readExp' ('-':s) = do
519 readExp' s = readDec s
521 lexDotDigits ('.':s) = lex0Digits s
522 lexDotDigits s = return ("",s)
524 readRational__ :: String -> Rational -- we export this one (non-std)
525 -- NB: *does* handle a leading "-"
528 '-' : xs -> - (read_me xs)
532 = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
533 #ifndef NEW_READS_REP
535 [] -> error ("readRational__: no parse:" ++ top_s)
536 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
539 Nothing -> error ("readRational__: no parse:" ++ top_s)