[project @ 1999-12-20 10:34:27 by simonpj]
[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 PrelErr          ( error )
15 import PrelEnum         ( Enum(..) )
16 import PrelNum
17 import PrelReal
18 import PrelFloat
19 import PrelList
20 import PrelTup
21 import PrelMaybe
22 import PrelShow         -- isAlpha etc
23 import PrelBase
24 import Monad
25
26 -- needed for readIO and instance Read Buffermode
27 import PrelIOBase ( IO, userError, BufferMode(..) )
28 import PrelException ( ioError )
29 \end{code}
30
31 %*********************************************************
32 %*                                                      *
33 \subsection{The @Read@ class}
34 %*                                                      *
35 %*********************************************************
36
37 Note: if you compile this with -DNEW_READS_REP, you'll get
38 a (simpler) ReadS representation that only allow one valid
39 parse of a string of characters, instead of a list of
40 possible ones.
41
42 [changing the ReadS rep has implications for the deriving
43 machinery for Read, a change that hasn't been made, so you
44 probably won't want to compile in this new rep. except
45 when in an experimental mood.]
46
47 \begin{code}
48
49 #ifndef NEW_READS_REP
50 type  ReadS a   = String -> [(a,String)]
51 #else
52 type  ReadS a   = String -> Maybe (a,String)
53 #endif
54
55 class  Read a  where
56     readsPrec :: Int -> ReadS a
57
58     readList  :: ReadS [a]
59     readList   = readList__ reads
60 \end{code}
61
62 %*********************************************************
63 %*                                                      *
64 \subsection{Utility functions}
65 %*                                                      *
66 %*********************************************************
67
68 \begin{code}
69 reads           :: (Read a) => ReadS a
70 reads           =  readsPrec 0
71
72 read            :: (Read a) => String -> a
73 read s          =  
74    case read_s s of
75 #ifndef NEW_READS_REP
76       [x]     -> x
77       []      -> error "Prelude.read: no parse"
78       _       -> error "Prelude.read: ambiguous parse"
79 #else
80       Just x  -> x
81       Nothing -> error "Prelude.read: no parse"
82 #endif
83  where
84   read_s str = do
85     (x,str1) <- reads str
86     ("","")  <- lex str1
87     return x
88
89   -- raises an exception instead of an error
90 readIO          :: Read a => String -> IO a
91 readIO s        =  case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of
92 #ifndef NEW_READS_REP
93                         [x]    -> return x
94                         []     -> ioError (userError "Prelude.readIO: no parse")
95                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
96 #else
97                         Just x -> return x
98                         Nothing  -> ioError (userError "Prelude.readIO: no parse")
99 #endif
100
101 \end{code}
102
103 \begin{code}
104 readParen       :: Bool -> ReadS a -> ReadS a
105 readParen b g   =  if b then mandatory else optional
106                    where optional r  = g r ++ mandatory r
107                          mandatory r = do
108                                 ("(",s) <- lex r
109                                 (x,t)   <- optional s
110                                 (")",u) <- lex t
111                                 return (x,u)
112
113
114 readList__ :: ReadS a -> ReadS [a]
115
116 readList__ readx
117   = readParen False (\r -> do
118                        ("[",s) <- lex r
119                        readl s)
120   where readl  s = 
121            (do { ("]",t) <- lex s ; return ([],t) }) ++
122            (do { (x,t) <- readx s ; (xs,u) <- readl2 t ; return (x:xs,u) })
123
124         readl2 s = 
125            (do { ("]",t) <- lex s ; return ([],t) }) ++
126            (do { (",",t) <- lex s ; (x,u) <- readx t ; (xs,v) <- readl2 u ; return (x:xs,v) })
127
128 \end{code}
129
130
131 %*********************************************************
132 %*                                                      *
133 \subsection{Lexical analysis}
134 %*                                                      *
135 %*********************************************************
136
137 This lexer is not completely faithful to the Haskell lexical syntax.
138 Current limitations:
139    Qualified names are not handled properly
140    A `--' does not terminate a symbol
141    Octal and hexidecimal numerics are not recognized as a single token
142
143 \begin{code}
144 lex                   :: ReadS String
145
146 lex ""                = return ("","")
147 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
148 lex ('\'':s)          = do
149             (ch, '\'':t) <- lexLitChar s
150             guard (ch /= "'")
151             return ('\'':ch++"'", t)
152 lex ('"':s)           = do
153             (str,t) <- lexString s
154             return ('"':str, t)
155
156           where
157             lexString ('"':s) = return ("\"",s)
158             lexString s = do
159                     (ch,t)  <- lexStrItem s
160                     (str,u) <- lexString t
161                     return (ch++str, u)
162
163             
164             lexStrItem ('\\':'&':s) = return ("\\&",s)
165             lexStrItem ('\\':c:s) | isSpace c = do
166                         ('\\':t) <- return (dropWhile isSpace s)
167                         return ("\\&",t)
168             lexStrItem s            = lexLitChar s
169      
170 lex (c:s) | isSingle c = return ([c],s)
171           | isSym c    = do
172                 (sym,t) <- return (span isSym s)
173                 return (c:sym,t)
174           | isAlpha c  = do
175                 (nam,t) <- return (span isIdChar s)
176                 return (c:nam, t)
177           | isDigit c  = do
178                  let
179                   (pred, s', isDec) =
180                     case s of
181                       ('o':rs) -> (isOctDigit, rs, False)
182                       ('O':rs) -> (isOctDigit, rs, False)
183                       ('x':rs) -> (isHexDigit, rs, False)
184                       ('X':rs) -> (isHexDigit, rs, False)
185                       _        -> (isDigit, s, True)
186
187                  (ds,s)  <- return (span pred s')
188                  (fe,t)  <- lexFracExp isDec s
189                  return (c:ds++fe,t)
190           | otherwise  = mzero    -- bad character
191              where
192               isSingle c =  c `elem` ",;()[]{}_`"
193               isSym c    =  c `elem` "!@#$%&*+./<=>?\\^|:-~"
194               isIdChar c =  isAlphaNum c || c `elem` "_'"
195
196               lexFracExp True ('.':cs)   = do
197                         (ds,t) <- lex0Digits cs
198                         (e,u)  <- lexExp t
199                         return ('.':ds++e,u)
200               lexFracExp _ s        = return ("",s)
201
202               lexExp (e:s) | e `elem` "eE" = 
203                   (do
204                     (c:t) <- return s
205                     guard (c `elem` "+-")
206                     (ds,u) <- lexDecDigits t
207                     return (e:c:ds,u))      ++
208                   (do
209                     (ds,t) <- lexDecDigits s
210                     return (e:ds,t))
211
212               lexExp s = return ("",s)
213
214 lexDigits            :: ReadS String
215 lexDigits            = lexDecDigits
216
217 lexDecDigits            :: ReadS String 
218 lexDecDigits            =  nonnull isDigit
219
220 lexOctDigits            :: ReadS String 
221 lexOctDigits            =  nonnull isOctDigit
222
223 lexHexDigits            :: ReadS String 
224 lexHexDigits            =  nonnull isHexDigit
225
226 -- 0 or more digits
227 lex0Digits               :: ReadS String 
228 lex0Digits  s            =  return (span isDigit s)
229
230 nonnull                 :: (Char -> Bool) -> ReadS String
231 nonnull p s             = do
232             (cs@(_:_),t) <- return (span p s)
233             return (cs,t)
234
235 lexLitChar              :: ReadS String
236 lexLitChar ('\\':s)     =  do
237             (esc,t) <- lexEsc s
238             return ('\\':esc, t)
239        where
240         lexEsc (c:s)     | c `elem` escChars = return ([c],s)
241         lexEsc s@(d:_)   | isDigit d         = checkSize 10 lexDecDigits s
242         lexEsc ('o':d:s) | isOctDigit d      = checkSize  8 lexOctDigits (d:s)
243         lexEsc ('O':d:s) | isOctDigit d      = checkSize  8 lexOctDigits (d:s)
244         lexEsc ('x':d:s) | isHexDigit d      = checkSize 16 lexHexDigits (d:s)
245         lexEsc ('X':d:s) | isHexDigit d      = checkSize 16 lexHexDigits (d:s)
246         lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)] -- cf. cntrl in 2.6 of H. report.
247         lexEsc s@(c:_)   | isUpper c            = fromAsciiLab s
248         lexEsc _                                = mzero
249
250         escChars = "abfnrtv\\\"'"
251
252         fromAsciiLab (x:y:z:ls) | isUpper y && (isUpper z || isDigit z) &&
253                                    [x,y,z] `elem` asciiEscTab = return ([x,y,z], ls)
254         fromAsciiLab (x:y:ls)   | isUpper y &&
255                                    [x,y]   `elem` asciiEscTab = return ([x,y], ls)
256         fromAsciiLab _                                        = mzero
257                                    
258         asciiEscTab = "DEL" : asciiTab
259
260          {-
261            Check that the numerically escaped char literals are
262            within accepted boundaries.
263            
264            Note: this allows char lits with leading zeros, i.e.,
265                  \0000000000000000000000000000001. 
266          -}
267         checkSize base f str = do
268            (num, res) <- f str
269               -- Note: this is assumes that a Char is 8 bits long.
270            if (toAnInt base num) > 255 then 
271               mzero
272             else
273               case base of
274                  8  -> return ('o':num, res)
275                  16 -> return ('x':num, res)
276                  _  -> return (num, res)
277
278         toAnInt base xs = foldl (\ acc n -> acc*base + n) 0 (map digitToInt xs)
279
280
281 lexLitChar (c:s)        =  return ([c],s)
282 lexLitChar ""           =  mzero
283
284 digitToInt :: Char -> Int
285 digitToInt c
286  | isDigit c            =  fromEnum c - fromEnum '0'
287  | c >= 'a' && c <= 'f' =  fromEnum c - fromEnum 'a' + 10
288  | c >= 'A' && c <= 'F' =  fromEnum c - fromEnum 'A' + 10
289  | otherwise            =  error ("Char.digitToInt: not a digit " ++ show c) -- sigh
290 \end{code}
291
292 %*********************************************************
293 %*                                                      *
294 \subsection{Instances of @Read@}
295 %*                                                      *
296 %*********************************************************
297
298 \begin{code}
299 instance  Read Char  where
300     readsPrec _      = readParen False
301                             (\r -> do
302                                 ('\'':s,t) <- lex r
303                                 (c,"\'")   <- readLitChar s
304                                 return (c,t))
305
306     readList = readParen False (\r -> do
307                                 ('"':s,t) <- lex r
308                                 (l,_)     <- readl s
309                                 return (l,t))
310                where readl ('"':s)      = return ("",s)
311                      readl ('\\':'&':s) = readl s
312                      readl s            = do
313                             (c,t)  <- readLitChar s 
314                             (cs,u) <- readl t
315                             return (c:cs,u)
316
317 instance Read Bool where
318     readsPrec _ = readParen False
319                         (\r ->
320                            lex r >>= \ lr ->
321                            (do { ("True", rest)  <- return lr ; return (True,  rest) }) ++
322                            (do { ("False", rest) <- return lr ; return (False, rest) }))
323                 
324
325 instance Read Ordering where
326     readsPrec _ = readParen False
327                         (\r -> 
328                            lex r >>= \ lr ->
329                            (do { ("LT", rest) <- return lr ; return (LT,  rest) }) ++
330                            (do { ("EQ", rest) <- return lr ; return (EQ, rest) })  ++
331                            (do { ("GT", rest) <- return lr ; return (GT, rest) }))
332
333 instance Read a => Read (Maybe a) where
334     readsPrec _ = readParen False
335                         (\r -> 
336                             lex r >>= \ lr ->
337                             (do { ("Nothing", rest) <- return lr ; return (Nothing, rest)}) ++
338                             (do 
339                                 ("Just", rest1) <- return lr
340                                 (x, rest2)      <- reads rest1
341                                 return (Just x, rest2)))
342
343 instance (Read a, Read b) => Read (Either a b) where
344     readsPrec _ = readParen False
345                         (\r ->
346                             lex r >>= \ lr ->
347                             (do 
348                                 ("Left", rest1) <- return lr
349                                 (x, rest2)      <- reads rest1
350                                 return (Left x, rest2)) ++
351                             (do 
352                                 ("Right", rest1) <- return lr
353                                 (x, rest2)      <- reads rest1
354                                 return (Right x, rest2)))
355
356 instance  Read Int  where
357     readsPrec _ x = readSigned readDec x
358
359 instance  Read Integer  where
360     readsPrec _ x = readSigned readDec x
361
362 instance  Read Float  where
363     readsPrec _ x = readSigned readFloat x
364
365 instance  Read Double  where
366     readsPrec _ x = readSigned readFloat x
367
368 instance  (Integral a, Read a)  => Read (Ratio a)  where
369     readsPrec p  =  readParen (p > ratio_prec)
370                               (\r -> do
371                                 (x,s)   <- reads r
372                                 ("%",t) <- lex s
373                                 (y,u)   <- reads t
374                                 return (x%y,u))
375
376 instance  (Read a) => Read [a]  where
377     readsPrec _         = readList
378
379 instance Read () where
380     readsPrec _    = readParen False
381                             (\r -> do
382                                 ("(",s) <- lex r
383                                 (")",t) <- lex s
384                                 return ((),t))
385
386 instance  (Read a, Read b) => Read (a,b)  where
387     readsPrec _ = readParen False
388                             (\r -> do
389                                 ("(",s) <- lex r
390                                 (x,t)   <- readsPrec 0 s
391                                 (",",u) <- lex t
392                                 (y,v)   <- readsPrec 0 u
393                                 (")",w) <- lex v
394                                 return ((x,y), w))
395
396 instance (Read a, Read b, Read c) => Read (a, b, c) where
397     readsPrec _ = readParen False
398                             (\a -> do
399                                 ("(",b) <- lex a
400                                 (x,c)   <- readsPrec 0 b
401                                 (",",d) <- lex c
402                                 (y,e)   <- readsPrec 0 d
403                                 (",",f) <- lex e
404                                 (z,g)   <- readsPrec 0 f
405                                 (")",h) <- lex g
406                                 return ((x,y,z), h))
407
408 instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where
409     readsPrec _ = readParen False
410                             (\a -> do
411                                 ("(",b) <- lex a
412                                 (w,c)   <- readsPrec 0 b
413                                 (",",d) <- lex c
414                                 (x,e)   <- readsPrec 0 d
415                                 (",",f) <- lex e
416                                 (y,g)   <- readsPrec 0 f
417                                 (",",h) <- lex g
418                                 (z,h)   <- readsPrec 0 h
419                                 (")",i) <- lex h
420                                 return ((w,x,y,z), i))
421
422 instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where
423     readsPrec _ = readParen False
424                             (\a -> do
425                                 ("(",b) <- lex a
426                                 (v,c)   <- readsPrec 0 b
427                                 (",",d) <- lex c
428                                 (w,e)   <- readsPrec 0 d
429                                 (",",f) <- lex e
430                                 (x,g)   <- readsPrec 0 f
431                                 (",",h) <- lex g
432                                 (y,i)   <- readsPrec 0 h
433                                 (",",j) <- lex i
434                                 (z,k)   <- readsPrec 0 j
435                                 (")",l) <- lex k
436                                 return ((v,w,x,y,z), l))
437 \end{code}
438
439
440 %*********************************************************
441 %*                                                      *
442 \subsection{Reading characters}
443 %*                                                      *
444 %*********************************************************
445
446 \begin{code}
447 readLitChar             :: ReadS Char
448
449 readLitChar []          =  mzero
450 readLitChar ('\\':s)    =  readEsc s
451         where
452         readEsc ('a':s)  = return ('\a',s)
453         readEsc ('b':s)  = return ('\b',s)
454         readEsc ('f':s)  = return ('\f',s)
455         readEsc ('n':s)  = return ('\n',s)
456         readEsc ('r':s)  = return ('\r',s)
457         readEsc ('t':s)  = return ('\t',s)
458         readEsc ('v':s)  = return ('\v',s)
459         readEsc ('\\':s) = return ('\\',s)
460         readEsc ('"':s)  = return ('"',s)
461         readEsc ('\'':s) = return ('\'',s)
462         readEsc ('^':c:s) | c >= '@' && c <= '_'
463                          = return (chr (ord c - ord '@'), s)
464         readEsc s@(d:_) | isDigit d
465                          = do
466                           (n,t) <- readDec s
467                           return (chr n,t)
468         readEsc ('o':s)  = do
469                           (n,t) <- readOct s
470                           return (chr n,t)
471         readEsc ('x':s)  = do
472                           (n,t) <- readHex s
473                           return (chr n,t)
474
475         readEsc s@(c:_) | isUpper c
476                          = let table = ('\DEL', "DEL") : zip ['\NUL'..] asciiTab
477                            in case [(c,s') | (c, mne) <- table,
478                                              ([],s') <- [match mne s]]
479                               of (pr:_) -> return pr
480                                  []     -> mzero
481         readEsc _        = mzero
482
483 readLitChar (c:s)       =  return (c,s)
484
485 match                   :: (Eq a) => [a] -> [a] -> ([a],[a])
486 match (x:xs) (y:ys) | x == y  =  match xs ys
487 match xs     ys               =  (xs,ys)
488
489 \end{code}
490
491
492 %*********************************************************
493 %*                                                      *
494 \subsection{Reading numbers}
495 %*                                                      *
496 %*********************************************************
497
498 Note: reading numbers at bases different than 10, does not
499 include lexing common prefixes such as '0x' or '0o' etc.
500
501 \begin{code}
502 {-# SPECIALISE readDec :: 
503                 ReadS Int,
504                 ReadS Integer #-}
505 readDec :: (Integral a) => ReadS a
506 readDec = readInt 10 isDigit (\d -> ord d - ord_0)
507
508 {-# SPECIALISE readOct :: 
509                 ReadS Int,
510                 ReadS Integer #-}
511 readOct :: (Integral a) => ReadS a
512 readOct = readInt 8 isOctDigit (\d -> ord d - ord_0)
513
514 {-# SPECIALISE readHex :: 
515                 ReadS Int,
516                 ReadS Integer #-}
517 readHex :: (Integral a) => ReadS a
518 readHex = readInt 16 isHexDigit hex
519             where hex d = ord d - (if isDigit d then ord_0
520                                    else ord (if isUpper d then 'A' else 'a') - 10)
521
522 readInt :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
523 readInt radix isDig digToInt s = do
524     (ds,r) <- nonnull isDig s
525     return (foldl1 (\n d -> n * radix + d) (map (fromInt . digToInt) ds), r)
526
527 {-# SPECIALISE readSigned ::
528                 ReadS Int     -> ReadS Int,
529                 ReadS Integer -> ReadS Integer,
530                 ReadS Double  -> ReadS Double       #-}
531 readSigned :: (Real a) => ReadS a -> ReadS a
532 readSigned readPos = readParen False read'
533                      where read' r  = read'' r ++
534                                       (do
535                                         ("-",s) <- lex r
536                                         (x,t)   <- read'' s
537                                         return (-x,t))
538                            read'' r = do
539                                (str,s) <- lex r
540                                (n,"")  <- readPos str
541                                return (n,s)
542 \end{code}
543
544 The functions readFloat below uses rational arithmetic
545 to ensure correct conversion between the floating-point radix and
546 decimal.  It is often possible to use a higher-precision floating-
547 point type to obtain the same results.
548
549 \begin{code}
550 {-# SPECIALISE readFloat ::
551                     ReadS Double,
552                     ReadS Float     #-} 
553 readFloat :: (RealFloat a) => ReadS a
554 readFloat r = do
555     (x,t) <- readRational r
556     return (fromRational x,t)
557
558 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
559
560 readRational r =
561    (do 
562       (n,d,s) <- readFix r
563       (k,t)   <- readExp s
564       return ((n%1)*10^^(k-d), t )) ++
565    (do
566       ("NaN",t) <- lex r
567       return (0/0,t) ) ++
568    (do
569       ("Infinity",t) <- lex r
570       return (1/0,t) )
571  where
572      readFix r = do
573         (ds,s)  <- lexDecDigits r
574         (ds',t) <- lexDotDigits s
575         return (read (ds++ds'), length ds', t)
576
577      readExp (e:s) | e `elem` "eE" = readExp' s
578      readExp s                     = return (0,s)
579
580      readExp' ('+':s) = readDec s
581      readExp' ('-':s) = do
582                         (k,t) <- readDec s
583                         return (-k,t)
584      readExp' s       = readDec s
585
586      lexDotDigits ('.':s) = lex0Digits s
587      lexDotDigits s       = return ("",s)
588
589 readRational__ :: String -> Rational -- we export this one (non-std)
590                                     -- NB: *does* handle a leading "-"
591 readRational__ top_s
592   = case top_s of
593       '-' : xs -> - (read_me xs)
594       xs       -> read_me xs
595   where
596     read_me s
597       = case (do { (x,t) <- readRational s ; ("","") <- lex t ; return x }) of
598 #ifndef NEW_READS_REP
599           [x] -> x
600           []  -> error ("readRational__: no parse:"        ++ top_s)
601           _   -> error ("readRational__: ambiguous parse:" ++ top_s)
602 #else
603           Just x  -> x
604           Nothing -> error ("readRational__: no parse:"        ++ top_s)
605 #endif
606
607 \end{code}
608
609 %*********************************************************
610 %*                                                      *
611 \subsection{Reading BufferMode}
612 %*                                                      *
613 %*********************************************************
614
615 This instance decl is here rather than somewhere more appropriate in
616 order that we can avoid both orphan-instance modules and recursive
617 dependencies.
618
619 \begin{code}
620 instance Read BufferMode where
621     readsPrec _ = 
622       readParen False
623         (\r ->  let lr = lex r
624                 in
625                 [(NoBuffering, rest)       | ("NoBuffering", rest) <- lr] ++
626                 [(LineBuffering,rest)      | ("LineBuffering",rest) <- lr] ++
627                 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
628                                              (mb, rest2) <- reads rest1])
629
630 \end{code}