[project @ 2002-08-28 14:30:12 by simonpj]
[haskell-directory.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 isAlpha
123      s <- munch isIdfChar
124      return (Ident (c:s))
125  where
126   isIdfChar c = isAlphaNum c || c `elem` "_'"
127
128 -- ---------------------------------------------------------------------------
129 -- Lexing character literals
130
131 lexLitChar :: ReadP Lexeme
132 lexLitChar =
133   do char '\''
134      (c,esc) <- lexChar
135      guard (esc || c /= '\'')
136      char '\''
137      return (Char c)
138
139 lexChar :: ReadP (Char, Bool)  -- "escaped or not"?
140 lexChar =
141   do c <- get
142      if c == '\\'
143        then do c <- lexEsc; return (c, True)
144        else do return (c, False)
145  where 
146   lexEsc =
147     lexEscChar
148       +++ lexNumeric
149         +++ lexCntrlChar
150           +++ lexAscii
151   
152   lexEscChar =
153     do c <- get
154        case c of
155          'a'  -> return '\a'
156          'b'  -> return '\b'
157          'f'  -> return '\f'
158          'n'  -> return '\n'
159          'r'  -> return '\r'
160          't'  -> return '\t'
161          'v'  -> return '\v'
162          '\\' -> return '\\'
163          '\"' -> return '\"'
164          '\'' -> return '\''
165          _    -> pfail
166   
167   lexNumeric =
168     do base <- lexBase
169        n    <- lexInteger base
170        guard (n <= toInteger (ord maxBound))
171        return (chr (fromInteger n))
172    where
173     lexBase =
174       do s <- look
175          case s of
176            'o':_ -> do get; return 8
177            'x':_ -> do get; return 16
178            _     -> do return 10
179   
180   lexCntrlChar =
181     do char '^'
182        c <- get
183        case c of
184          '@'  -> return '\^@'
185          'A'  -> return '\^A'
186          'B'  -> return '\^B'
187          'C'  -> return '\^C'
188          'D'  -> return '\^D'
189          'E'  -> return '\^E'
190          'F'  -> return '\^F'
191          'G'  -> return '\^G'
192          'H'  -> return '\^H'
193          'I'  -> return '\^I'
194          'J'  -> return '\^J'
195          'K'  -> return '\^K'
196          'L'  -> return '\^L'
197          'M'  -> return '\^M'
198          'N'  -> return '\^N'
199          'O'  -> return '\^O'
200          'P'  -> return '\^P'
201          'Q'  -> return '\^Q'
202          'R'  -> return '\^R'
203          'S'  -> return '\^S'
204          'T'  -> return '\^T'
205          'U'  -> return '\^U'
206          'V'  -> return '\^V'
207          'W'  -> return '\^W'
208          'X'  -> return '\^X'
209          'Y'  -> return '\^Y'
210          'Z'  -> return '\^Z'
211          '['  -> return '\^['
212          '\\' -> return '\^\'
213          ']'  -> return '\^]'
214          '^'  -> return '\^^'
215          '_'  -> return '\^_'
216          _    -> pfail
217
218   lexAscii =
219     do choice
220          [ do { string "SO" ; s <- look; 
221                 case s of
222                   'H' : _ -> do { get ; return '\SOH' }
223                   other   -> return '\SO' 
224               }
225                 -- \SO and \SOH need maximal-munch treatment
226                 -- See the Haskell report Sect 2.6
227          , string "NUL" >> return '\NUL'
228          , string "STX" >> return '\STX'
229          , string "ETX" >> return '\ETX'
230          , string "EOT" >> return '\EOT'
231          , string "ENQ" >> return '\ENQ'
232          , string "ACK" >> return '\ACK'
233          , string "BEL" >> return '\BEL'
234          , string "BS"  >> return '\BS'
235          , string "HT"  >> return '\HT'
236          , string "LF"  >> return '\LF'
237          , string "VT"  >> return '\VT'
238          , string "FF"  >> return '\FF'
239          , string "CR"  >> return '\CR'
240          , string "SI"  >> return '\SI'
241          , string "DLE" >> return '\DLE'
242          , string "DC1" >> return '\DC1'
243          , string "DC2" >> return '\DC2'
244          , string "DC3" >> return '\DC3'
245          , string "DC4" >> return '\DC4'
246          , string "NAK" >> return '\NAK'
247          , string "SYN" >> return '\SYN'
248          , string "ETB" >> return '\ETB'
249          , string "CAN" >> return '\CAN'
250          , string "EM"  >> return '\EM'
251          , string "SUB" >> return '\SUB'
252          , string "ESC" >> return '\ESC'
253          , string "FS"  >> return '\FS'
254          , string "GS"  >> return '\GS'
255          , string "RS"  >> return '\RS'
256          , string "US"  >> return '\US'
257          , string "SP"  >> return '\SP'
258          , string "DEL" >> return '\DEL'
259          ]
260
261
262 -- ---------------------------------------------------------------------------
263 -- string literal
264
265 lexString :: ReadP Lexeme
266 lexString =
267   do char '"'
268      body id
269  where
270   body f =
271     do (c,esc) <- lexStrItem
272        if c /= '"' || esc
273          then body (f.(c:))
274          else let s = f "" in
275               return (String s)
276
277   lexStrItem =
278     (lexEmpty >> lexStrItem)
279       +++ lexChar
280   
281   lexEmpty =
282     do char '\\'
283        c <- get
284        case c of
285          '&'           -> do return ()
286          _ | isSpace c -> do skipSpaces; char '\\'; return ()
287          _             -> do pfail
288
289 -- ---------------------------------------------------------------------------
290 --  Lexing numbers
291
292 type Base   = Int
293 type Digits = [Int]
294
295 showDigit :: Int -> ShowS
296 showDigit n | n <= 9    = shows n
297             | otherwise = showChar (chr (n + ord 'A' - 10))
298
299 lexNumber :: ReadP Lexeme
300 lexNumber = do { string "NaN";      return (Rat notANumber) } +++
301             do { string "Infinity"; return (Rat infinity) } +++
302             do { base <- lexBase ;  lexNumberBase base }
303  where
304   lexBase =
305     do s <- look
306        case s of
307          '0':'o':_ -> do get; get; return 8
308          '0':'O':_ -> do get; get; return 8
309          '0':'x':_ -> do get; get; return 16
310          '0':'X':_ -> do get; get; return 16
311          _         -> do return 10
312        
313 lexNumberBase :: Base -> ReadP Lexeme
314 lexNumberBase base =
315   do xs    <- lexDigits base
316      mFrac <- lexFrac base
317      mExp  <- lexExp base
318      return (value xs mFrac mExp)
319  where
320   baseInteger :: Integer
321   baseInteger = fromIntegral base
322
323   value xs mFrac mExp = valueFracExp (val baseInteger 0 xs) mFrac mExp
324   
325   valueFracExp :: Integer -> Maybe Digits -> Maybe Integer 
326                -> Lexeme
327   valueFracExp a Nothing Nothing        
328     = Int a                                             -- 43
329   valueFracExp a Nothing (Just exp)
330     | exp >= 0  = Int (a * (baseInteger ^ exp))         -- 43e7
331     | otherwise = Rat (valExp (fromInteger a) exp)      -- 43e-7
332   valueFracExp a (Just fs) mExp 
333      = case mExp of
334          Nothing  -> Rat rat                            -- 4.3
335          Just exp -> Rat (valExp rat exp)               -- 4.3e-4
336      where
337         rat :: Rational
338         rat = fromInteger a + frac (fromIntegral base) 0 1 fs
339
340   valExp :: Rational -> Integer -> Rational
341   valExp rat exp = rat * (fromIntegral base ^^ exp)
342
343 lexFrac :: Base -> ReadP (Maybe Digits)
344 lexFrac base =
345   do s <- look
346      case s of
347        '.' : d : _ | isJust (valDig base d) ->
348         -- The lookahead checks for point and at least one
349         -- valid following digit.  For example 1..n must
350         -- lex the "1" off rather than failing.
351          do get
352             frac <- lexDigits base
353             return (Just frac)
354        
355        _ ->
356          do return Nothing
357
358 lexExp :: Base -> ReadP (Maybe Integer)
359 lexExp base =
360   do s <- look
361      case s of
362        e : _ | e `elem` "eE" && base == 10 ->
363          do get
364             (signedExp +++ exp)
365         where
366          signedExp =
367            do c <- char '-' +++ char '+'
368               n <- lexInteger 10
369               return (Just (if c == '-' then -n else n))
370          
371          exp =
372            do n <- lexInteger 10
373               return (Just n)
374
375        _ ->
376          do return Nothing
377
378 lexDigits :: Int -> ReadP Digits
379 -- Lex a non-empty sequence of digits in specified base
380 lexDigits base =
381   do s  <- look
382      xs <- scan s id
383      guard (not (null xs))
384      return xs
385  where
386   scan (c:cs) f = case valDig base c of
387                     Just n  -> do get; scan cs (f.(n:))
388                     Nothing -> do return (f [])
389   scan []     f = do return (f [])
390
391 lexInteger :: Base -> ReadP Integer
392 lexInteger base =
393   do xs <- lexDigits base
394      return (val (fromIntegral base) 0 xs)
395
396 val :: Num a => a -> a -> Digits -> a
397 -- val base y [d1,..,dn] = y ++ [d1,..,dn], as it were
398 val base y []     = y
399 val base y (x:xs) = y' `seq` val base y' xs
400  where
401   y' = y * base + fromIntegral x
402
403 frac :: Integral a => a -> a -> a -> Digits -> Ratio a
404 frac base a b []     = a % b
405 frac base a b (x:xs) = a' `seq` b' `seq` frac base a' b' xs
406  where
407   a' = a * base + fromIntegral x
408   b' = b * base
409
410 valDig :: Num a => a -> Char -> Maybe Int
411 valDig 8 c
412   | '0' <= c && c <= '7' = Just (ord c - ord '0')
413   | otherwise            = Nothing
414
415 valDig 10 c
416   | '0' <= c && c <= '9' = Just (ord c - ord '0')
417   | otherwise            = Nothing
418
419 valDig 16 c
420   | '0' <= c && c <= '9' = Just (ord c - ord '0')
421   | 'a' <= c && c <= 'f' = Just (ord c - ord 'a' + 10)
422   | 'A' <= c && c <= 'F' = Just (ord c - ord 'A' + 10)
423   | otherwise            = Nothing
424
425 -- ----------------------------------------------------------------------
426 -- other numeric lexing functions
427
428 readIntP :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadP a
429 readIntP base isDigit valDigit =
430   do s <- munch1 isDigit
431      return (val base 0 (map valDigit s))
432
433 readIntP' :: Num a => a -> ReadP a
434 readIntP' base = readIntP base isDigit valDigit
435  where
436   isDigit  c = maybe False (const True) (valDig base c)
437   valDigit c = maybe 0     id           (valDig base c)
438
439 readOctP, readDecP, readHexP :: Num a => ReadP a
440 readOctP = readIntP' 8
441 readDecP = readIntP' 10
442 readHexP = readIntP' 16