[project @ 1999-01-14 18:12:47 by sof]
[ghc-hetmet.git] / ghc / lib / std / PrelRead.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4
5 \section[PrelRead]{Module @PrelRead@}
6
7 Instances of the Read class.
8
9 \begin{code}
10 {-# OPTIONS -fno-implicit-prelude #-}
11
12 module PrelRead where
13
14 import {-# SOURCE #-} PrelErr ( error )
15 import PrelNum
16 import PrelNumExtra
17 import PrelList
18 import PrelTup
19 import PrelMaybe
20 import PrelEither
21 import PrelBase
22 import Monad
23
24 -- needed for readIO.
25 import PrelIOBase ( IO, userError )
26 import PrelException ( ioError )
27 \end{code}
28
29 %*********************************************************
30 %*                                                      *
31 \subsection{The @Read@ class}
32 %*                                                      *
33 %*********************************************************
34
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
38 possible ones.
39
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.]
44
45 \begin{code}
46
47 #ifndef NEW_READS_REP
48 type  ReadS a   = String -> [(a,String)]
49 #else
50 type  ReadS a   = String -> Maybe (a,String)
51 #endif
52
53 class  Read a  where
54     readsPrec :: Int -> ReadS a
55
56     readList  :: ReadS [a]
57     readList   = readList__ reads
58 \end{code}
59
60 %*********************************************************
61 %*                                                      *
62 \subsection{Utility functions}
63 %*                                                      *
64 %*********************************************************
65
66 \begin{code}
67 reads           :: (Read a) => ReadS a
68 reads           =  readsPrec 0
69
70 read            :: (Read a) => String -> a
71 read s          =  
72    case read_s s of
73 #ifndef NEW_READS_REP
74       [x]     -> x
75       []      -> error "Prelude.read: no parse"
76       _       -> error "Prelude.read: ambiguous parse"
77 #else
78       Just x  -> x
79       Nothing -> error "Prelude.read: no parse"
80 #endif
81  where
82   read_s str = do
83     (x,str1) <- reads str
84     ("","")  <- lex str1
85     return x
86
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
90 #ifndef NEW_READS_REP
91                         [x]    -> return x
92                         []     -> ioError (userError "Prelude.readIO: no parse")
93                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
94 #else
95                         Just x -> return x
96                         Nothing  -> ioError (userError "Prelude.readIO: no parse")
97 #endif
98
99 \end{code}
100
101 \begin{code}
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
105                          mandatory r = do
106                                 ("(",s) <- lex r
107                                 (x,t)   <- optional s
108                                 (")",u) <- lex t
109                                 return (x,u)
110
111
112 readList__ :: ReadS a -> ReadS [a]
113
114 readList__ readx
115   = readParen False (\r -> do
116                        ("[",s) <- lex r
117                        readl s)
118   where readl  s = 
119            (do { ("]",t) <- lex s ; return ([],t) }) ++
120            (do { (x,t) <- readx s ; (xs,u) <- readl2 t ; return (x:xs,u) })
121
122         readl2 s = 
123            (do { ("]",t) <- lex s ; return ([],t) }) ++
124            (do { (",",t) <- lex s ; (x,u) <- readx t ; (xs,v) <- readl2 u ; return (x:xs,v) })
125
126 \end{code}
127
128
129 %*********************************************************
130 %*                                                      *
131 \subsection{Lexical analysis}
132 %*                                                      *
133 %*********************************************************
134
135 This lexer is not completely faithful to the Haskell lexical syntax.
136 Current limitations:
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
140
141 \begin{code}
142 lex                   :: ReadS String
143
144 lex ""                = return ("","")
145 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
146 lex ('\'':s)          = do
147             (ch, '\'':t) <- lexLitChar s
148             guard (ch /= "'")
149             return ('\'':ch++"'", t)
150 lex ('"':s)           = do
151             (str,t) <- lexString s
152             return ('"':str, t)
153
154           where
155             lexString ('"':s) = return ("\"",s)
156             lexString s = do
157                     (ch,t)  <- lexStrItem s
158                     (str,u) <- lexString t
159                     return (ch++str, u)
160
161             
162             lexStrItem ('\\':'&':s) = return ("\\&",s)
163             lexStrItem ('\\':c:s) | isSpace c = do
164                         ('\\':t) <- return (dropWhile isSpace s)
165                         return ("\\&",t)
166             lexStrItem s            = lexLitChar s
167      
168 lex (c:s) | isSingle c = return ([c],s)
169           | isSym c    = do
170                 (sym,t) <- return (span isSym s)
171                 return (c:sym,t)
172           | isAlpha c  = do
173                 (nam,t) <- return (span isIdChar s)
174                 return (c:nam, t)
175           | isDigit c  = do
176                  let
177                   (pred, s', isDec) =
178                     case s of
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)
184
185                  (ds,s)  <- return (span pred s')
186                  (fe,t)  <- lexFracExp isDec s
187                  return (c:ds++fe,t)
188           | otherwise  = mzero    -- bad character
189              where
190               isSingle c =  c `elem` ",;()[]{}_`"
191               isSym c    =  c `elem` "!@#$%&*+./<=>?\\^|:-~"
192               isIdChar c =  isAlphaNum c || c `elem` "_'"
193
194               lexFracExp True ('.':cs)   = do
195                         (ds,t) <- lex0Digits cs
196                         (e,u)  <- lexExp t
197                         return ('.':ds++e,u)
198               lexFracExp _ s        = return ("",s)
199
200               lexExp (e:s) | e `elem` "eE" = 
201                   (do
202                     (c:t) <- return s
203                     guard (c `elem` "+-")
204                     (ds,u) <- lexDecDigits t
205                     return (e:c:ds,u))      ++
206                   (do
207                     (ds,t) <- lexDecDigits s
208                     return (e:ds,t))
209
210               lexExp s = return ("",s)
211
212 lexDigits            :: ReadS String
213 lexDigits            = lexDecDigits
214
215 lexDecDigits            :: ReadS String 
216 lexDecDigits            =  nonnull isDigit
217
218 lexOctDigits            :: ReadS String 
219 lexOctDigits            =  nonnull isOctDigit
220
221 lexHexDigits            :: ReadS String 
222 lexHexDigits            =  nonnull isHexDigit
223
224 -- 0 or more digits
225 lex0Digits               :: ReadS String 
226 lex0Digits  s            =  return (span isDigit s)
227
228 nonnull                 :: (Char -> Bool) -> ReadS String
229 nonnull p s             = do
230             (cs@(_:_),t) <- return (span p s)
231             return (cs,t)
232
233 lexLitChar              :: ReadS String
234 lexLitChar ('\\':s)     =  do
235             (esc,t) <- lexEsc s
236             return ('\\':esc, t)
237        where
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
246         lexEsc _                                   = mzero
247
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
253                                    
254
255 lexLitChar (c:s)        =  return ([c],s)
256 lexLitChar ""           =  mzero
257 \end{code}
258
259 %*********************************************************
260 %*                                                      *
261 \subsection{Instances of @Read@}
262 %*                                                      *
263 %*********************************************************
264
265 \begin{code}
266 instance  Read Char  where
267     readsPrec _      = readParen False
268                             (\r -> do
269                                 ('\'':s,t) <- lex r
270                                 (c,"\'")   <- readLitChar s
271                                 return (c,t))
272
273     readList = readParen False (\r -> do
274                                 ('"':s,t) <- lex r
275                                 (l,_)     <- readl s
276                                 return (l,t))
277                where readl ('"':s)      = return ("",s)
278                      readl ('\\':'&':s) = readl s
279                      readl s            = do
280                             (c,t)  <- readLitChar s 
281                             (cs,u) <- readl t
282                             return (c:cs,u)
283
284 instance Read Bool where
285     readsPrec _ = readParen False
286                         (\r ->
287                            lex r >>= \ lr ->
288                            (do { ("True", rest)  <- return lr ; return (True,  rest) }) ++
289                            (do { ("False", rest) <- return lr ; return (False, rest) }))
290                 
291
292 instance Read Ordering where
293     readsPrec _ = readParen False
294                         (\r -> 
295                            lex r >>= \ lr ->
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) }))
299
300 instance Read a => Read (Maybe a) where
301     readsPrec _ = readParen False
302                         (\r -> 
303                             lex r >>= \ lr ->
304                             (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
305                             (do 
306                                 ("Just", rest1) <- return lr
307                                 (x, rest2)      <- reads rest1
308                                 return (Just x, rest2)))
309
310 instance (Read a, Read b) => Read (Either a b) where
311     readsPrec _ = readParen False
312                         (\r ->
313                             lex r >>= \ lr ->
314                             (do 
315                                 ("Left", rest1) <- return lr
316                                 (x, rest2)      <- reads rest1
317                                 return (Left x, rest2)) ++
318                             (do 
319                                 ("Right", rest1) <- return lr
320                                 (x, rest2)      <- reads rest1
321                                 return (Right x, rest2)))
322
323 instance  Read Int  where
324     readsPrec _ x = readSigned readDec x
325
326 instance  Read Integer  where
327     readsPrec _ x = readSigned readDec x
328
329 instance  Read Float  where
330     readsPrec _ x = readSigned readFloat x
331
332 instance  Read Double  where
333     readsPrec _ x = readSigned readFloat x
334
335 instance  (Integral a, Read a)  => Read (Ratio a)  where
336     readsPrec p  =  readParen (p > ratio_prec)
337                               (\r -> do
338                                 (x,s)   <- reads r
339                                 ("%",t) <- lex s
340                                 (y,u)   <- reads t
341                                 return (x%y,u))
342
343 instance  (Read a) => Read [a]  where
344     readsPrec _         = readList
345
346 instance Read () where
347     readsPrec _    = readParen False
348                             (\r -> do
349                                 ("(",s) <- lex r
350                                 (")",t) <- lex s
351                                 return ((),t))
352
353 instance  (Read a, Read b) => Read (a,b)  where
354     readsPrec _ = readParen False
355                             (\r -> do
356                                 ("(",s) <- lex r
357                                 (x,t)   <- readsPrec 0 s
358                                 (",",u) <- lex t
359                                 (y,v)   <- readsPrec 0 u
360                                 (")",w) <- lex v
361                                 return ((x,y), w))
362
363 instance (Read a, Read b, Read c) => Read (a, b, c) where
364     readsPrec _ = readParen False
365                             (\a -> do
366                                 ("(",b) <- lex a
367                                 (x,c)   <- readsPrec 0 b
368                                 (",",d) <- lex c
369                                 (y,e)   <- readsPrec 0 d
370                                 (",",f) <- lex e
371                                 (z,g)   <- readsPrec 0 f
372                                 (")",h) <- lex g
373                                 return ((x,y,z), h))
374
375 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
376     readsPrec _ = readParen False
377                             (\a -> do
378                                 ("(",b) <- lex a
379                                 (w,c)   <- readsPrec 0 b
380                                 (",",d) <- lex c
381                                 (x,e)   <- readsPrec 0 d
382                                 (",",f) <- lex e
383                                 (y,g)   <- readsPrec 0 f
384                                 (",",h) <- lex g
385                                 (z,h)   <- readsPrec 0 h
386                                 (")",i) <- lex h
387                                 return ((w,x,y,z), i))
388
389 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
390     readsPrec _ = readParen False
391                             (\a -> do
392                                 ("(",b) <- lex a
393                                 (v,c)   <- readsPrec 0 b
394                                 (",",d) <- lex c
395                                 (w,e)   <- readsPrec 0 d
396                                 (",",f) <- lex e
397                                 (x,g)   <- readsPrec 0 f
398                                 (",",h) <- lex g
399                                 (y,i)   <- readsPrec 0 h
400                                 (",",j) <- lex i
401                                 (z,k)   <- readsPrec 0 j
402                                 (")",l) <- lex k
403                                 return ((v,w,x,y,z), l))
404 \end{code}
405
406
407 %*********************************************************
408 %*                                                      *
409 \subsection{Reading characters}
410 %*                                                      *
411 %*********************************************************
412
413 \begin{code}
414 readLitChar             :: ReadS Char
415
416 readLitChar []          =  mzero
417 readLitChar ('\\':s)    =  readEsc s
418         where
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
432                          = do
433                           (n,t) <- readDec s
434                           return (chr n,t)
435         readEsc ('o':s)  = do
436                           (n,t) <- readOct s
437                           return (chr n,t)
438         readEsc ('x':s)  = do
439                           (n,t) <- readHex s
440                           return (chr n,t)
441
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
447                                  []     -> mzero
448         readEsc _        = mzero
449
450 readLitChar (c:s)       =  return (c,s)
451
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)
455
456 \end{code}
457
458
459 %*********************************************************
460 %*                                                      *
461 \subsection{Reading numbers}
462 %*                                                      *
463 %*********************************************************
464
465 Note: reading numbers at bases different than 10, does not
466 include lexing common prefixes such as '0x' or '0o' etc.
467
468 \begin{code}
469 {-# SPECIALISE readDec :: 
470                 ReadS Int,
471                 ReadS Integer #-}
472 readDec :: (Integral a) => ReadS a
473 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
474
475 {-# SPECIALISE readOct :: 
476                 ReadS Int,
477                 ReadS Integer #-}
478 readOct :: (Integral a) => ReadS a
479 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
480
481 {-# SPECIALISE readHex :: 
482                 ReadS Int,
483                 ReadS Integer #-}
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)
488
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)
493
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 ++
501                                       (do
502                                         ("-",s) <- lex r
503                                         (x,t)   <- read'' s
504                                         return (-x,t))
505                            read'' r = do
506                                (str,s) <- lex r
507                                (n,"")  <- readPos str
508                                return (n,s)
509 \end{code}
510
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.
515
516 \begin{code}
517 {-# SPECIALISE readFloat ::
518                     ReadS Double,
519                     ReadS Float     #-} 
520 readFloat :: (RealFloat a) => ReadS a
521 readFloat r = do
522     (x,t) <- readRational r
523     return (fromRational x,t)
524
525 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
526
527 readRational r =
528    (do 
529       (n,d,s) <- readFix r
530       (k,t)   <- readExp s
531       return ((n%1)*10^^(k-d), t )) ++
532    (do
533       ("NaN",t) <- lex r
534       return (0/0,t) ) ++
535    (do
536       ("Infinity",t) <- lex r
537       return (1/0,t) )
538  where
539      readFix r = do
540         (ds,s)  <- lexDecDigits r
541         (ds',t) <- lexDotDigits s
542         return (read (ds++ds'), length ds', t)
543
544      readExp (e:s) | e `elem` "eE" = readExp' s
545      readExp s                     = return (0,s)
546
547      readExp' ('+':s) = readDec s
548      readExp' ('-':s) = do
549                         (k,t) <- readDec s
550                         return (-k,t)
551      readExp' s       = readDec s
552
553      lexDotDigits ('.':s) = lex0Digits s
554      lexDotDigits s       = return ("",s)
555
556 readRational__ :: String -> Rational -- we export this one (non-std)
557                                     -- NB: *does* handle a leading "-"
558 readRational__ top_s
559   = case top_s of
560       '-' : xs -> - (read_me xs)
561       xs       -> read_me xs
562   where
563     read_me s
564       = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
565 #ifndef NEW_READS_REP
566           [x] -> x
567           []  -> error ("readRational__: no parse:"        ++ top_s)
568           _   -> error ("readRational__: ambiguous parse:" ++ top_s)
569 #else
570           Just x  -> x
571           Nothing -> error ("readRational__: no parse:"        ++ top_s)
572 #endif
573
574 \end{code}