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