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