[project @ 2003-02-14 13:01:32 by simonpj]
[ghc-base.git] / Text / Read / Lex.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Text.Read.Lex
5 -- Copyright   :  (c) The University of Glasgow 2002
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- The cut-down Haskell lexer, used by Text.Read
13 --
14 -----------------------------------------------------------------------------
15
16 module Text.Read.Lex
17   -- lexing types
18   ( Lexeme(..)       -- :: *; Show, Eq
19   
20   -- lexer
21   , lex              -- :: ReadP Lexeme -- Skips leading spaces
22   , hsLex            -- :: ReadP String
23   
24   , readIntP         -- :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadP a
25   , readOctP         -- :: Num a => ReadP a 
26   , readDecP         -- :: Num a => ReadP a
27   , readHexP         -- :: Num a => ReadP a
28   )
29  where
30
31 import Text.ParserCombinators.ReadP
32
33 import GHC.Base
34 import GHC.Num( Num(..), Integer )
35 import GHC.Show( Show(.. ), showChar, showString,
36                  isSpace, isAlpha, isAlphaNum,
37                  isOctDigit, isHexDigit, toUpper )
38 import GHC.Real( Ratio(..), Integral, Rational, (%), fromIntegral, fromRational, 
39                  toInteger, (^), (^^), infinity, notANumber )
40 import GHC.Float( Float, Double )
41 import GHC.List
42 import GHC.Show( ShowS, shows )
43 import GHC.Enum( minBound, maxBound )
44 import Data.Maybe
45 import Data.Either
46 import Control.Monad
47
48 -- -----------------------------------------------------------------------------
49 -- Lexing types
50
51 type LexP = ReadP Lexeme
52
53 data Lexeme
54   = Char   Char         -- Quotes removed, 
55   | String String       --      escapes interpreted
56   | Punc   String       -- Punctuation, eg "(", "::"
57   | Ident  String       -- Haskell identifiers, e.g. foo, baz
58   | Symbol String       -- Haskell symbols, e.g. >>, %
59   | Int Integer
60   | Rat Rational
61   | EOF
62  deriving (Eq, Show)
63
64 -- -----------------------------------------------------------------------------
65 -- Lexing
66
67 lex :: ReadP Lexeme
68 lex = skipSpaces >> lexToken
69
70 hsLex :: ReadP String
71 -- ^ Haskell lexer: returns the lexed string, rather than the lexeme
72 hsLex = do skipSpaces 
73            (s,_) <- gather lexToken
74            return s
75
76 lexToken :: ReadP Lexeme
77 lexToken = lexEOF     +++
78            lexLitChar +++ 
79            lexString  +++ 
80            lexPunc    +++ 
81            lexSymbol  +++ 
82            lexId      +++ 
83            lexNumber
84
85
86 -- ----------------------------------------------------------------------
87 -- End of file
88 lexEOF :: ReadP Lexeme
89 lexEOF = do s <- look
90             guard (null s)
91             return EOF
92
93 -- ---------------------------------------------------------------------------
94 -- Single character lexemes
95
96 lexPunc :: ReadP Lexeme
97 lexPunc =
98   do c <- satisfy isPuncChar
99      return (Punc [c])
100  where
101   isPuncChar c = c `elem` ",;()[]{}`"
102
103 -- ----------------------------------------------------------------------
104 -- Symbols
105
106 lexSymbol :: ReadP Lexeme
107 lexSymbol =
108   do s <- munch1 isSymbolChar
109      if s `elem` reserved_ops then 
110         return (Punc s)         -- Reserved-ops count as punctuation
111       else
112         return (Symbol s)
113  where
114   isSymbolChar c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
115   reserved_ops   = ["..", "::", "=", "\\", "|", "<-", "->", "@", "~", "=>"]
116
117 -- ----------------------------------------------------------------------
118 -- identifiers
119
120 lexId :: ReadP Lexeme
121 lexId =
122   do c <- satisfy isIdsChar
123      s <- munch isIdfChar
124      return (Ident (c:s))
125  where
126         -- Identifiers can start with a '_'
127   isIdsChar c = isAlpha c || c == '_'
128   isIdfChar c = isAlphaNum c || c `elem` "_'"
129
130 -- ---------------------------------------------------------------------------
131 -- Lexing character literals
132
133 lexLitChar :: ReadP Lexeme
134 lexLitChar =
135   do char '\''
136      (c,esc) <- lexChar
137      guard (esc || c /= '\'')
138      char '\''
139      return (Char c)
140
141 lexChar :: ReadP (Char, Bool)  -- "escaped or not"?
142 lexChar =
143   do c <- get
144      if c == '\\'
145        then do c <- lexEsc; return (c, True)
146        else do return (c, False)
147  where 
148   lexEsc =
149     lexEscChar
150       +++ lexNumeric
151         +++ lexCntrlChar
152           +++ lexAscii
153   
154   lexEscChar =
155     do c <- get
156        case c of
157          'a'  -> return '\a'
158          'b'  -> return '\b'
159          'f'  -> return '\f'
160          'n'  -> return '\n'
161          'r'  -> return '\r'
162          't'  -> return '\t'
163          'v'  -> return '\v'
164          '\\' -> return '\\'
165          '\"' -> return '\"'
166          '\'' -> return '\''
167          _    -> pfail
168   
169   lexNumeric =
170     do base <- lexBase
171        n    <- lexInteger base
172        guard (n <= toInteger (ord maxBound))
173        return (chr (fromInteger n))
174    where
175     lexBase =
176       do s <- look
177          case s of
178            'o':_ -> do get; return 8
179            'x':_ -> do get; return 16
180            _     -> do return 10
181   
182   lexCntrlChar =
183     do char '^'
184        c <- get
185        case c of
186          '@'  -> return '\^@'
187          'A'  -> return '\^A'
188          'B'  -> return '\^B'
189          'C'  -> return '\^C'
190          'D'  -> return '\^D'
191          'E'  -> return '\^E'
192          'F'  -> return '\^F'
193          'G'  -> return '\^G'
194          'H'  -> return '\^H'
195          'I'  -> return '\^I'
196          'J'  -> return '\^J'
197          'K'  -> return '\^K'
198          'L'  -> return '\^L'
199          'M'  -> return '\^M'
200          'N'  -> return '\^N'
201          'O'  -> return '\^O'
202          'P'  -> return '\^P'
203          'Q'  -> return '\^Q'
204          'R'  -> return '\^R'
205          'S'  -> return '\^S'
206          'T'  -> return '\^T'
207          'U'  -> return '\^U'
208          'V'  -> return '\^V'
209          'W'  -> return '\^W'
210          'X'  -> return '\^X'
211          'Y'  -> return '\^Y'
212          'Z'  -> return '\^Z'
213          '['  -> return '\^['
214          '\\' -> return '\^\'
215          ']'  -> return '\^]'
216          '^'  -> return '\^^'
217          '_'  -> return '\^_'
218          _    -> pfail
219
220   lexAscii =
221     do choice
222          [ do { string "SO" ; s <- look; 
223                 case s of
224                   'H' : _ -> do { get ; return '\SOH' }
225                   other   -> return '\SO' 
226               }
227                 -- \SO and \SOH need maximal-munch treatment
228                 -- See the Haskell report Sect 2.6
229          , string "NUL" >> return '\NUL'
230          , string "STX" >> return '\STX'
231          , string "ETX" >> return '\ETX'
232          , string "EOT" >> return '\EOT'
233          , string "ENQ" >> return '\ENQ'
234          , string "ACK" >> return '\ACK'
235          , string "BEL" >> return '\BEL'
236          , string "BS"  >> return '\BS'
237          , string "HT"  >> return '\HT'
238          , string "LF"  >> return '\LF'
239          , string "VT"  >> return '\VT'
240          , string "FF"  >> return '\FF'
241          , string "CR"  >> return '\CR'
242          , string "SI"  >> return '\SI'
243          , string "DLE" >> return '\DLE'
244          , string "DC1" >> return '\DC1'
245          , string "DC2" >> return '\DC2'
246          , string "DC3" >> return '\DC3'
247          , string "DC4" >> return '\DC4'
248          , string "NAK" >> return '\NAK'
249          , string "SYN" >> return '\SYN'
250          , string "ETB" >> return '\ETB'
251          , string "CAN" >> return '\CAN'
252          , string "EM"  >> return '\EM'
253          , string "SUB" >> return '\SUB'
254          , string "ESC" >> return '\ESC'
255          , string "FS"  >> return '\FS'
256          , string "GS"  >> return '\GS'
257          , string "RS"  >> return '\RS'
258          , string "US"  >> return '\US'
259          , string "SP"  >> return '\SP'
260          , string "DEL" >> return '\DEL'
261          ]
262
263
264 -- ---------------------------------------------------------------------------
265 -- string literal
266
267 lexString :: ReadP Lexeme
268 lexString =
269   do char '"'
270      body id
271  where
272   body f =
273     do (c,esc) <- lexStrItem
274        if c /= '"' || esc
275          then body (f.(c:))
276          else let s = f "" in
277               return (String s)
278
279   lexStrItem =
280     (lexEmpty >> lexStrItem)
281       +++ lexChar
282   
283   lexEmpty =
284     do char '\\'
285        c <- get
286        case c of
287          '&'           -> do return ()
288          _ | isSpace c -> do skipSpaces; char '\\'; return ()
289          _             -> do pfail
290
291 -- ---------------------------------------------------------------------------
292 --  Lexing numbers
293
294 type Base   = Int
295 type Digits = [Int]
296
297 showDigit :: Int -> ShowS
298 showDigit n | n <= 9    = shows n
299             | otherwise = showChar (chr (n + ord 'A' - 10))
300
301 lexNumber :: ReadP Lexeme
302 lexNumber = do { string "NaN";      return (Rat notANumber) } +++
303             do { string "Infinity"; return (Rat infinity) } +++
304             do { base <- lexBase ;  lexNumberBase base }
305  where
306   lexBase =
307     do s <- look
308        case s of
309          '0':'o':_ -> do get; get; return 8
310          '0':'O':_ -> do get; get; return 8
311          '0':'x':_ -> do get; get; return 16
312          '0':'X':_ -> do get; get; return 16
313          _         -> do return 10
314        
315 lexNumberBase :: Base -> ReadP Lexeme
316 lexNumberBase base =
317   do xs    <- lexDigits base
318      mFrac <- lexFrac base
319      mExp  <- lexExp base
320      return (value xs mFrac mExp)
321  where
322   baseInteger :: Integer
323   baseInteger = fromIntegral base
324
325   value xs mFrac mExp = valueFracExp (val baseInteger 0 xs) mFrac mExp
326   
327   valueFracExp :: Integer -> Maybe Digits -> Maybe Integer 
328                -> Lexeme
329   valueFracExp a Nothing Nothing        
330     = Int a                                             -- 43
331   valueFracExp a Nothing (Just exp)
332     | exp >= 0  = Int (a * (baseInteger ^ exp))         -- 43e7
333     | otherwise = Rat (valExp (fromInteger a) exp)      -- 43e-7
334   valueFracExp a (Just fs) mExp 
335      = case mExp of
336          Nothing  -> Rat rat                            -- 4.3
337          Just exp -> Rat (valExp rat exp)               -- 4.3e-4
338      where
339         rat :: Rational
340         rat = fromInteger a + frac (fromIntegral base) 0 1 fs
341
342   valExp :: Rational -> Integer -> Rational
343   valExp rat exp = rat * (fromIntegral base ^^ exp)
344
345 lexFrac :: Base -> ReadP (Maybe Digits)
346 lexFrac base =
347   do s <- look
348      case s of
349        '.' : d : _ | isJust (valDig base d) ->
350         -- The lookahead checks for point and at least one
351         -- valid following digit.  For example 1..n must
352         -- lex the "1" off rather than failing.
353          do get
354             frac <- lexDigits base
355             return (Just frac)
356        
357        _ ->
358          do return Nothing
359
360 lexExp :: Base -> ReadP (Maybe Integer)
361 lexExp base =
362   do s <- look
363      case s of
364        e : _ | e `elem` "eE" && base == 10 ->
365          do get
366             (signedExp +++ exp)
367         where
368          signedExp =
369            do c <- char '-' +++ char '+'
370               n <- lexInteger 10
371               return (Just (if c == '-' then -n else n))
372          
373          exp =
374            do n <- lexInteger 10
375               return (Just n)
376
377        _ ->
378          do return Nothing
379
380 lexDigits :: Int -> ReadP Digits
381 -- Lex a non-empty sequence of digits in specified base
382 lexDigits base =
383   do s  <- look
384      xs <- scan s id
385      guard (not (null xs))
386      return xs
387  where
388   scan (c:cs) f = case valDig base c of
389                     Just n  -> do get; scan cs (f.(n:))
390                     Nothing -> do return (f [])
391   scan []     f = do return (f [])
392
393 lexInteger :: Base -> ReadP Integer
394 lexInteger base =
395   do xs <- lexDigits base
396      return (val (fromIntegral base) 0 xs)
397
398 val :: Num a => a -> a -> Digits -> a
399 -- val base y [d1,..,dn] = y ++ [d1,..,dn], as it were
400 val base y []     = y
401 val base y (x:xs) = y' `seq` val base y' xs
402  where
403   y' = y * base + fromIntegral x
404
405 frac :: Integral a => a -> a -> a -> Digits -> Ratio a
406 frac base a b []     = a % b
407 frac base a b (x:xs) = a' `seq` b' `seq` frac base a' b' xs
408  where
409   a' = a * base + fromIntegral x
410   b' = b * base
411
412 valDig :: Num a => a -> Char -> Maybe Int
413 valDig 8 c
414   | '0' <= c && c <= '7' = Just (ord c - ord '0')
415   | otherwise            = Nothing
416
417 valDig 10 c
418   | '0' <= c && c <= '9' = Just (ord c - ord '0')
419   | otherwise            = Nothing
420
421 valDig 16 c
422   | '0' <= c && c <= '9' = Just (ord c - ord '0')
423   | 'a' <= c && c <= 'f' = Just (ord c - ord 'a' + 10)
424   | 'A' <= c && c <= 'F' = Just (ord c - ord 'A' + 10)
425   | otherwise            = Nothing
426
427 -- ----------------------------------------------------------------------
428 -- other numeric lexing functions
429
430 readIntP :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadP a
431 readIntP base isDigit valDigit =
432   do s <- munch1 isDigit
433      return (val base 0 (map valDigit s))
434
435 readIntP' :: Num a => a -> ReadP a
436 readIntP' base = readIntP base isDigit valDigit
437  where
438   isDigit  c = maybe False (const True) (valDig base c)
439   valDigit c = maybe 0     id           (valDig base c)
440
441 readOctP, readDecP, readHexP :: Num a => ReadP a
442 readOctP = readIntP' 8
443 readDecP = readIntP' 10
444 readHexP = readIntP' 16