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 ( ioError )
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 "Prelude.read: no parse"
76 _ -> error "Prelude.read: ambiguous parse"
79 Nothing -> error "Prelude.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 [] -> ioError (userError "Prelude.readIO: no parse")
93 _ -> ioError (userError "Prelude.readIO: ambiguous parse")
96 Nothing -> ioError (userError "Prelude.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)
179 ('o':rs) -> (isOctDigit, rs, False)
180 ('O':rs) -> (isOctDigit, rs, False)
181 ('x':rs) -> (isHexDigit, rs, False)
182 ('X':rs) -> (isHexDigit, rs, False)
183 _ -> (isDigit, s, True)
185 (ds,s) <- return (span pred s')
186 (fe,t) <- lexFracExp isDec s
188 | otherwise = mzero -- bad character
190 isSingle c = c `elem` ",;()[]{}_`"
191 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
192 isIdChar c = isAlphaNum c || c `elem` "_'"
194 lexFracExp True ('.':cs) = do
195 (ds,t) <- lex0Digits cs
198 lexFracExp _ s = return ("",s)
200 lexExp (e:s) | e `elem` "eE" =
203 guard (c `elem` "+-")
204 (ds,u) <- lexDecDigits t
205 return (e:c:ds,u)) ++
207 (ds,t) <- lexDecDigits s
210 lexExp s = return ("",s)
212 lexDigits :: ReadS String
213 lexDigits = lexDecDigits
215 lexDecDigits :: ReadS String
216 lexDecDigits = nonnull isDigit
218 lexOctDigits :: ReadS String
219 lexOctDigits = nonnull isOctDigit
221 lexHexDigits :: ReadS String
222 lexHexDigits = nonnull isHexDigit
225 lex0Digits :: ReadS String
226 lex0Digits s = return (span isDigit s)
228 nonnull :: (Char -> Bool) -> ReadS String
230 (cs@(_:_),t) <- return (span p s)
233 lexLitChar :: ReadS String
234 lexLitChar ('\\':s) = do
238 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = return ([c],s)
239 lexEsc s@(d:_) | isDigit d = lexDecDigits s
240 lexEsc ('o':d:s) | isDigit d = lexOctDigits (d:s)
241 lexEsc ('O':d:s) | isDigit d = lexOctDigits (d:s)
242 lexEsc ('x':d:s) | isDigit d = lexHexDigits (d:s)
243 lexEsc ('X':d:s) | isDigit d = lexHexDigits (d:s)
244 lexEsc ('^':c:s) | '@' <= c && c <= '_' = [(['^',c],s)] -- cf. cntrl in 2.6 of H. report.
245 lexEsc s@(c:_) | isUpper c = fromAsciiLab s
248 fromAsciiLab (x:y:z:ls) | isUpper y && (isUpper z || isDigit z) &&
249 [x,y,z] `elem` asciiTab = return ([x,y,z], ls)
250 fromAsciiLab (x:y:ls) | isUpper y &&
251 [x,y] `elem` asciiTab = return ([x,y], ls)
252 fromAsciiLab _ = mzero
255 lexLitChar (c:s) = return ([c],s)
256 lexLitChar "" = mzero
259 %*********************************************************
261 \subsection{Instances of @Read@}
263 %*********************************************************
266 instance Read Char where
267 readsPrec _ = readParen False
270 (c,"\'") <- readLitChar s
273 readList = readParen False (\r -> do
277 where readl ('"':s) = return ("",s)
278 readl ('\\':'&':s) = readl s
280 (c,t) <- readLitChar s
284 instance Read Bool where
285 readsPrec _ = readParen False
288 (do { ("True", rest) <- return lr ; return (True, rest) }) ++
289 (do { ("False", rest) <- return lr ; return (False, rest) }))
292 instance Read Ordering where
293 readsPrec _ = readParen False
296 (do { ("LT", rest) <- return lr ; return (LT, rest) }) ++
297 (do { ("EQ", rest) <- return lr ; return (EQ, rest) }) ++
298 (do { ("GT", rest) <- return lr ; return (GT, rest) }))
300 instance Read a => Read (Maybe a) where
301 readsPrec _ = readParen False
304 (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
306 ("Just", rest1) <- return lr
307 (x, rest2) <- reads rest1
308 return (Just x, rest2)))
310 instance (Read a, Read b) => Read (Either a b) where
311 readsPrec _ = readParen False
315 ("Left", rest1) <- return lr
316 (x, rest2) <- reads rest1
317 return (Left x, rest2)) ++
319 ("Right", rest1) <- return lr
320 (x, rest2) <- reads rest1
321 return (Right x, rest2)))
323 instance Read Int where
324 readsPrec _ x = readSigned readDec x
326 instance Read Integer where
327 readsPrec _ x = readSigned readDec x
329 instance Read Float where
330 readsPrec _ x = readSigned readFloat x
332 instance Read Double where
333 readsPrec _ x = readSigned readFloat x
335 instance (Integral a, Read a) => Read (Ratio a) where
336 readsPrec p = readParen (p > ratio_prec)
343 instance (Read a) => Read [a] where
344 readsPrec _ = readList
346 instance Read () where
347 readsPrec _ = readParen False
353 instance (Read a, Read b) => Read (a,b) where
354 readsPrec _ = readParen False
357 (x,t) <- readsPrec 0 s
359 (y,v) <- readsPrec 0 u
363 instance (Read a, Read b, Read c) => Read (a, b, c) where
364 readsPrec _ = readParen False
367 (x,c) <- readsPrec 0 b
369 (y,e) <- readsPrec 0 d
371 (z,g) <- readsPrec 0 f
375 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
376 readsPrec _ = readParen False
379 (w,c) <- readsPrec 0 b
381 (x,e) <- readsPrec 0 d
383 (y,g) <- readsPrec 0 f
385 (z,h) <- readsPrec 0 h
387 return ((w,x,y,z), i))
389 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
390 readsPrec _ = readParen False
393 (v,c) <- readsPrec 0 b
395 (w,e) <- readsPrec 0 d
397 (x,g) <- readsPrec 0 f
399 (y,i) <- readsPrec 0 h
401 (z,k) <- readsPrec 0 j
403 return ((v,w,x,y,z), l))
407 %*********************************************************
409 \subsection{Reading characters}
411 %*********************************************************
414 readLitChar :: ReadS Char
416 readLitChar [] = mzero
417 readLitChar ('\\':s) = readEsc s
419 readEsc ('a':s) = return ('\a',s)
420 readEsc ('b':s) = return ('\b',s)
421 readEsc ('f':s) = return ('\f',s)
422 readEsc ('n':s) = return ('\n',s)
423 readEsc ('r':s) = return ('\r',s)
424 readEsc ('t':s) = return ('\t',s)
425 readEsc ('v':s) = return ('\v',s)
426 readEsc ('\\':s) = return ('\\',s)
427 readEsc ('"':s) = return ('"',s)
428 readEsc ('\'':s) = return ('\'',s)
429 readEsc ('^':c:s) | c >= '@' && c <= '_'
430 = return (chr (ord c - ord '@'), s)
431 readEsc s@(d:_) | isDigit d
442 readEsc s@(c:_) | isUpper c
443 = let table = ('\DEL', "DEL") : zip ['\NUL'..] asciiTab
444 in case [(c,s') | (c, mne) <- table,
445 ([],s') <- [match mne s]]
446 of (pr:_) -> return pr
450 readLitChar (c:s) = return (c,s)
452 match :: (Eq a) => [a] -> [a] -> ([a],[a])
453 match (x:xs) (y:ys) | x == y = match xs ys
454 match xs ys = (xs,ys)
459 %*********************************************************
461 \subsection{Reading numbers}
463 %*********************************************************
465 Note: reading numbers at bases different than 10, does not
466 include lexing common prefixes such as '0x' or '0o' etc.
469 {-# SPECIALISE readDec ::
472 readDec :: (Integral a) => ReadS a
473 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
475 {-# SPECIALISE readOct ::
478 readOct :: (Integral a) => ReadS a
479 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
481 {-# SPECIALISE readHex ::
484 readHex :: (Integral a) => ReadS a
485 readHex = readInt 16 isHexDigit hex
486 where hex d = ord d - (if isDigit d then ord_0
487 else ord (if isUpper d then 'A' else 'a') - 10)
489 readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
490 readInt radix isDig digToInt s = do
491 (ds,r) <- nonnull isDig s
492 return (foldl1 (\n d -> n * radix + d) (map (fromInt . digToInt) ds), r)
494 {-# SPECIALISE readSigned ::
495 ReadS Int -> ReadS Int,
496 ReadS Integer -> ReadS Integer,
497 ReadS Double -> ReadS Double #-}
498 readSigned :: (Real a) => ReadS a -> ReadS a
499 readSigned readPos = readParen False read'
500 where read' r = read'' r ++
507 (n,"") <- readPos str
511 The functions readFloat below uses rational arithmetic
512 to ensure correct conversion between the floating-point radix and
513 decimal. It is often possible to use a higher-precision floating-
514 point type to obtain the same results.
517 {-# SPECIALISE readFloat ::
520 readFloat :: (RealFloat a) => ReadS a
522 (x,t) <- readRational r
523 return (fromRational x,t)
525 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
531 return ((n%1)*10^^(k-d), t )) ++
536 ("Infinity",t) <- lex r
540 (ds,s) <- lexDecDigits r
541 (ds',t) <- lexDotDigits s
542 return (read (ds++ds'), length ds', t)
544 readExp (e:s) | e `elem` "eE" = readExp' s
545 readExp s = return (0,s)
547 readExp' ('+':s) = readDec s
548 readExp' ('-':s) = do
551 readExp' s = readDec s
553 lexDotDigits ('.':s) = lex0Digits s
554 lexDotDigits s = return ("",s)
556 readRational__ :: String -> Rational -- we export this one (non-std)
557 -- NB: *does* handle a leading "-"
560 '-' : xs -> - (read_me xs)
564 = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
565 #ifndef NEW_READS_REP
567 [] -> error ("readRational__: no parse:" ++ top_s)
568 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
571 Nothing -> error ("readRational__: no parse:" ++ top_s)