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` asciiEscTab = return ([x,y,z], ls)
250 fromAsciiLab (x:y:ls) | isUpper y &&
251 [x,y] `elem` asciiEscTab = return ([x,y], ls)
252 fromAsciiLab _ = mzero
254 asciiEscTab = "DEL" : asciiTab
257 lexLitChar (c:s) = return ([c],s)
258 lexLitChar "" = mzero
261 %*********************************************************
263 \subsection{Instances of @Read@}
265 %*********************************************************
268 instance Read Char where
269 readsPrec _ = readParen False
272 (c,"\'") <- readLitChar s
275 readList = readParen False (\r -> do
279 where readl ('"':s) = return ("",s)
280 readl ('\\':'&':s) = readl s
282 (c,t) <- readLitChar s
286 instance Read Bool where
287 readsPrec _ = readParen False
290 (do { ("True", rest) <- return lr ; return (True, rest) }) ++
291 (do { ("False", rest) <- return lr ; return (False, rest) }))
294 instance Read Ordering where
295 readsPrec _ = readParen False
298 (do { ("LT", rest) <- return lr ; return (LT, rest) }) ++
299 (do { ("EQ", rest) <- return lr ; return (EQ, rest) }) ++
300 (do { ("GT", rest) <- return lr ; return (GT, rest) }))
302 instance Read a => Read (Maybe a) where
303 readsPrec _ = readParen False
306 (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
308 ("Just", rest1) <- return lr
309 (x, rest2) <- reads rest1
310 return (Just x, rest2)))
312 instance (Read a, Read b) => Read (Either a b) where
313 readsPrec _ = readParen False
317 ("Left", rest1) <- return lr
318 (x, rest2) <- reads rest1
319 return (Left x, rest2)) ++
321 ("Right", rest1) <- return lr
322 (x, rest2) <- reads rest1
323 return (Right x, rest2)))
325 instance Read Int where
326 readsPrec _ x = readSigned readDec x
328 instance Read Integer where
329 readsPrec _ x = readSigned readDec x
331 instance Read Float where
332 readsPrec _ x = readSigned readFloat x
334 instance Read Double where
335 readsPrec _ x = readSigned readFloat x
337 instance (Integral a, Read a) => Read (Ratio a) where
338 readsPrec p = readParen (p > ratio_prec)
345 instance (Read a) => Read [a] where
346 readsPrec _ = readList
348 instance Read () where
349 readsPrec _ = readParen False
355 instance (Read a, Read b) => Read (a,b) where
356 readsPrec _ = readParen False
359 (x,t) <- readsPrec 0 s
361 (y,v) <- readsPrec 0 u
365 instance (Read a, Read b, Read c) => Read (a, b, c) where
366 readsPrec _ = readParen False
369 (x,c) <- readsPrec 0 b
371 (y,e) <- readsPrec 0 d
373 (z,g) <- readsPrec 0 f
377 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
378 readsPrec _ = readParen False
381 (w,c) <- readsPrec 0 b
383 (x,e) <- readsPrec 0 d
385 (y,g) <- readsPrec 0 f
387 (z,h) <- readsPrec 0 h
389 return ((w,x,y,z), i))
391 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
392 readsPrec _ = readParen False
395 (v,c) <- readsPrec 0 b
397 (w,e) <- readsPrec 0 d
399 (x,g) <- readsPrec 0 f
401 (y,i) <- readsPrec 0 h
403 (z,k) <- readsPrec 0 j
405 return ((v,w,x,y,z), l))
409 %*********************************************************
411 \subsection{Reading characters}
413 %*********************************************************
416 readLitChar :: ReadS Char
418 readLitChar [] = mzero
419 readLitChar ('\\':s) = readEsc s
421 readEsc ('a':s) = return ('\a',s)
422 readEsc ('b':s) = return ('\b',s)
423 readEsc ('f':s) = return ('\f',s)
424 readEsc ('n':s) = return ('\n',s)
425 readEsc ('r':s) = return ('\r',s)
426 readEsc ('t':s) = return ('\t',s)
427 readEsc ('v':s) = return ('\v',s)
428 readEsc ('\\':s) = return ('\\',s)
429 readEsc ('"':s) = return ('"',s)
430 readEsc ('\'':s) = return ('\'',s)
431 readEsc ('^':c:s) | c >= '@' && c <= '_'
432 = return (chr (ord c - ord '@'), s)
433 readEsc s@(d:_) | isDigit d
444 readEsc s@(c:_) | isUpper c
445 = let table = ('\DEL', "DEL") : zip ['\NUL'..] asciiTab
446 in case [(c,s') | (c, mne) <- table,
447 ([],s') <- [match mne s]]
448 of (pr:_) -> return pr
452 readLitChar (c:s) = return (c,s)
454 match :: (Eq a) => [a] -> [a] -> ([a],[a])
455 match (x:xs) (y:ys) | x == y = match xs ys
456 match xs ys = (xs,ys)
461 %*********************************************************
463 \subsection{Reading numbers}
465 %*********************************************************
467 Note: reading numbers at bases different than 10, does not
468 include lexing common prefixes such as '0x' or '0o' etc.
471 {-# SPECIALISE readDec ::
474 readDec :: (Integral a) => ReadS a
475 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
477 {-# SPECIALISE readOct ::
480 readOct :: (Integral a) => ReadS a
481 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
483 {-# SPECIALISE readHex ::
486 readHex :: (Integral a) => ReadS a
487 readHex = readInt 16 isHexDigit hex
488 where hex d = ord d - (if isDigit d then ord_0
489 else ord (if isUpper d then 'A' else 'a') - 10)
491 readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
492 readInt radix isDig digToInt s = do
493 (ds,r) <- nonnull isDig s
494 return (foldl1 (\n d -> n * radix + d) (map (fromInt . digToInt) ds), r)
496 {-# SPECIALISE readSigned ::
497 ReadS Int -> ReadS Int,
498 ReadS Integer -> ReadS Integer,
499 ReadS Double -> ReadS Double #-}
500 readSigned :: (Real a) => ReadS a -> ReadS a
501 readSigned readPos = readParen False read'
502 where read' r = read'' r ++
509 (n,"") <- readPos str
513 The functions readFloat below uses rational arithmetic
514 to ensure correct conversion between the floating-point radix and
515 decimal. It is often possible to use a higher-precision floating-
516 point type to obtain the same results.
519 {-# SPECIALISE readFloat ::
522 readFloat :: (RealFloat a) => ReadS a
524 (x,t) <- readRational r
525 return (fromRational x,t)
527 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
533 return ((n%1)*10^^(k-d), t )) ++
538 ("Infinity",t) <- lex r
542 (ds,s) <- lexDecDigits r
543 (ds',t) <- lexDotDigits s
544 return (read (ds++ds'), length ds', t)
546 readExp (e:s) | e `elem` "eE" = readExp' s
547 readExp s = return (0,s)
549 readExp' ('+':s) = readDec s
550 readExp' ('-':s) = do
553 readExp' s = readDec s
555 lexDotDigits ('.':s) = lex0Digits s
556 lexDotDigits s = return ("",s)
558 readRational__ :: String -> Rational -- we export this one (non-std)
559 -- NB: *does* handle a leading "-"
562 '-' : xs -> - (read_me xs)
566 = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
567 #ifndef NEW_READS_REP
569 [] -> error ("readRational__: no parse:" ++ top_s)
570 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
573 Nothing -> error ("readRational__: no parse:" ++ top_s)