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