2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Lexical analysis]{Lexical analysis}
6 --------------------------------------------------------
8 There's a known bug in here:
10 If an interface file ends prematurely, Lex tries to
11 do headFS of an empty FastString.
13 An example that provokes the error is
15 f _:_ _forall_ [a] <<<END OF FILE>>>
16 --------------------------------------------------------
24 Token(..), lexer, ParseResult(..), PState(..),
25 ExtFlags(..), mkPState,
28 P, thenP, thenP_, returnP, mapP, failP, failMsgP,
29 getSrcLocP, setSrcLocP, getSrcFile,
30 layoutOn, layoutOff, pushContext, popContext
33 #include "HsVersions.h"
35 import Char ( toUpper, isDigit, chr, ord )
38 import PrelNames ( mkTupNameStr )
39 import ForeignCall ( Safety(..) )
40 import UniqFM ( listToUFM, lookupUFM )
41 import BasicTypes ( Boxity(..) )
42 import SrcLoc ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
43 replaceSrcLine, mkSrcLoc )
45 import ErrUtils ( Message )
53 import DATA_BITS ( Bits(..) )
54 import DATA_INT ( Int32 )
57 %************************************************************************
59 \subsection{Data types}
61 %************************************************************************
63 The token data type, fairly un-interesting except from one
64 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
65 strictness, unfolding etc).
67 The Idea/Observation here is that the renamer needs to scan through
68 all of an interface file before it can continue. But only a fraction
69 of the information contained in the file turns out to be useful, so
70 delaying as much as possible of the scanning and parsing of an
71 interface file Makes Sense (Heap profiles of the compiler
72 show a reduction in heap usage by at least a factor of two,
75 Hence, the interface file lexer spots when value declarations are
76 being scanned and return the @ITidinfo@ and @ITtype@ constructors
77 for the type and any other id info for that binding (unfolding, strictness
78 etc). These constructors are applied to the result of lexing these sub-chunks.
80 The lexing of the type and id info is all done lazily, of course, so
81 the scanning (and subsequent parsing) will be done *only* on the ids the
82 renamer finds out that it is interested in. The rest will just be junked.
83 Laziness, you know it makes sense :-)
87 = ITas -- Haskell keywords
111 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
113 | ITforall -- GHC extension keywords
125 | ITccall (Bool,Bool,Safety) -- (is_dyn, is_casm, may_gc)
128 | ITspecialise_prag -- Pragmas
136 | ITcore_prag -- hdaume: core annotations
139 | ITdotdot -- reserved symbols
155 | ITbiglam -- GHC-extension symbols
157 | ITocurly -- special symbols
159 | ITocurlybar -- {|, for type applications
160 | ITccurlybar -- |}, for type applications
163 | ITopabrack -- [:, for parallel arrays with -fparr
164 | ITcpabrack -- :], for parallel arrays with -fparr
175 | ITvarid FastString -- identifiers
177 | ITvarsym FastString
178 | ITconsym FastString
179 | ITqvarid (FastString,FastString)
180 | ITqconid (FastString,FastString)
181 | ITqvarsym (FastString,FastString)
182 | ITqconsym (FastString,FastString)
184 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
185 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
187 | ITpragma StringBuffer
190 | ITstring FastString
192 | ITrational Rational
195 | ITprimstring FastString
197 | ITprimfloat Rational
198 | ITprimdouble Rational
199 | ITlitlit FastString
201 -- MetaHaskell extension tokens
202 | ITopenExpQuote -- [| or [e|
203 | ITopenPatQuote -- [p|
204 | ITopenDecQuote -- [d|
205 | ITopenTypQuote -- [t|
207 | ITidEscape FastString -- $x
208 | ITparenEscape -- $(
213 | ITunknown String -- Used when the lexer can't make sense of it
214 | ITeof -- end of file token
215 deriving Show -- debugging
218 -----------------------------------------------------------------------------
222 pragmaKeywordsFM = listToUFM $
223 map (\ (x,y) -> (mkFastString x,y))
224 [( "SPECIALISE", ITspecialise_prag ),
225 ( "SPECIALIZE", ITspecialise_prag ),
226 ( "SOURCE", ITsource_prag ),
227 ( "INLINE", ITinline_prag ),
228 ( "NOINLINE", ITnoinline_prag ),
229 ( "NOTINLINE", ITnoinline_prag ),
230 ( "LINE", ITline_prag ),
231 ( "RULES", ITrules_prag ),
232 ( "RULEZ", ITrules_prag ), -- american spelling :-)
233 ( "SCC", ITscc_prag ),
234 ( "CORE", ITcore_prag ), -- hdaume: core annotation
235 ( "DEPRECATED", ITdeprecated_prag )
238 haskellKeywordsFM = listToUFM $
239 map (\ (x,y) -> (mkFastString x,y))
240 [( "_", ITunderscore ),
243 ( "class", ITclass ),
245 ( "default", ITdefault ),
246 ( "deriving", ITderiving ),
249 ( "hiding", IThiding ),
251 ( "import", ITimport ),
253 ( "infix", ITinfix ),
254 ( "infixl", ITinfixl ),
255 ( "infixr", ITinfixr ),
256 ( "instance", ITinstance ),
258 ( "module", ITmodule ),
259 ( "newtype", ITnewtype ),
261 ( "qualified", ITqualified ),
264 ( "where", ITwhere ),
265 ( "_scc_", ITscc ) -- ToDo: remove
268 isSpecial :: Token -> Bool
269 -- If we see M.x, where x is a keyword, but
270 -- is special, we treat is as just plain M.x,
272 isSpecial ITas = True
273 isSpecial IThiding = True
274 isSpecial ITqualified = True
275 isSpecial ITforall = True
276 isSpecial ITexport = True
277 isSpecial ITlabel = True
278 isSpecial ITdynamic = True
279 isSpecial ITsafe = True
280 isSpecial ITthreadsafe = True
281 isSpecial ITunsafe = True
282 isSpecial ITwith = True
283 isSpecial ITccallconv = True
284 isSpecial ITstdcallconv = True
285 isSpecial ITmdo = True
288 -- the bitmap provided as the third component indicates whether the
289 -- corresponding extension keyword is valid under the extension options
290 -- provided to the compiler; if the extension corresponding to *any* of the
291 -- bits set in the bitmap is enabled, the keyword is valid (this setup
292 -- facilitates using a keyword in two different extensions that can be
293 -- activated independently)
295 ghcExtensionKeywordsFM = listToUFM $
296 map (\(x, y, z) -> (mkFastString x, (y, z)))
297 [ ( "forall", ITforall, bit glaExtsBit),
298 ( "foreign", ITforeign, bit ffiBit),
299 ( "export", ITexport, bit ffiBit),
300 ( "label", ITlabel, bit ffiBit),
301 ( "dynamic", ITdynamic, bit ffiBit),
302 ( "safe", ITsafe, bit ffiBit),
303 ( "threadsafe", ITthreadsafe, bit ffiBit),
304 ( "unsafe", ITunsafe, bit ffiBit),
305 ( "with", ITwith, bit withBit),
306 ( "mdo", ITmdo, bit glaExtsBit),
307 ( "stdcall", ITstdcallconv, bit ffiBit),
308 ( "ccall", ITccallconv, bit ffiBit),
309 ( "dotnet", ITdotnet, bit ffiBit),
310 ( "reifyDecl", ITreifyDecl, bit glaExtsBit),
311 ( "reifyType", ITreifyType, bit glaExtsBit),
312 ( "reifyFixity",ITreifyFixity, bit glaExtsBit),
313 ("_ccall_", ITccall (False, False, PlayRisky),
315 ("_ccall_GC_", ITccall (False, False, PlaySafe False),
317 ("_casm_", ITccall (False, True, PlayRisky),
319 ("_casm_GC_", ITccall (False, True, PlaySafe False),
323 haskellKeySymsFM = listToUFM $
324 map (\ (x,y) -> (mkFastString x,y))
326 ,(":", ITcolon) -- (:) is a reserved op,
327 -- meaning only list cons
340 ,(".", ITdot) -- sadly, for 'forall a . t'
345 -----------------------------------------------------------------------------
350 - (exts) lexing a source with extensions, eg, an interface file or
352 - (bol) pointer to beginning of line (for column calculations)
353 - (buf) pointer to beginning of token
354 - (buf) pointer to current char
355 - (atbol) flag indicating whether we're at the beginning of a line
358 lexer :: (Token -> P a) -> P a
359 lexer cont buf s@(PState{
367 -- first, start a new lexeme and lose all the whitespace
369 tab line bol atbol (stepOverLexeme buf)
371 line = srcLocLine loc
373 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
374 case currentChar# buf of
377 if bufferExhausted (stepOn buf)
378 then cont ITeof buf s'
379 else trace "lexer: misplaced NUL?" $
380 tab y bol atbol (stepOn buf)
382 '\n'# -> let buf' = stepOn buf
383 in tab (y +# 1#) (currentIndex# buf') 1# buf'
385 -- find comments. This got harder in Haskell 98.
386 '-'# -> let trundle n =
387 let next = lookAhead# buf n in
388 if next `eqChar#` '-'# then trundle (n +# 1#)
389 else if is_symbol next || n <# 2#
392 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
395 -- comments and pragmas. We deal with LINE pragmas here,
396 -- and throw out any unrecognised pragmas as comments. Any
397 -- pragmas we know about are dealt with later (after any layout
398 -- processing if necessary).
399 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
400 if lookAhead# buf 2# `eqChar#` '#'# then
401 case expandWhile# is_space (addToCurrentPos buf 3#) of { buf1->
402 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
403 let lexeme = mkFastString -- ToDo: too slow
404 (map toUpper (lexemeToString buf2)) in
405 case lookupUFM pragmaKeywordsFM lexeme of
406 -- ignore RULES pragmas when -fglasgow-exts is off
407 Just ITrules_prag | not (glaExtsEnabled exts) ->
408 skip_to_end (stepOnBy# buf 2#) s'
410 line_prag skip_to_end buf2 s'
411 Just other -> is_a_token
412 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
415 else skip_to_end (stepOnBy# buf 2#) s'
417 skip_to_end = skipNestedComment (lexer cont)
419 -- special GHC extension: we grok cpp-style #line pragmas
420 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
421 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
422 lookAhead# buf 2# `eqChar#` 'i'# &&
423 lookAhead# buf 3# `eqChar#` 'n'# &&
424 lookAhead# buf 4# `eqChar#` 'e'# = stepOnBy# buf 5#
425 | otherwise = stepOn buf
427 case expandWhile# is_space buf1 of { buf2 ->
428 if is_digit (currentChar# buf2)
429 then line_prag next_line buf2 s'
433 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
435 -- tabs have been expanded beforehand
436 c | is_space c -> tab y bol atbol (stepOn buf)
437 | otherwise -> is_a_token
439 where s' = s{loc = replaceSrcLine loc y,
443 is_a_token | atbol /=# 0# = lexBOL cont buf s'
444 | otherwise = lexToken cont exts buf s'
446 -- {-# LINE .. #-} pragmas. yeuch.
447 line_prag cont buf s@PState{loc=loc} =
448 case expandWhile# is_space buf of { buf1 ->
449 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
450 -- subtract one: the line number refers to the *following* line.
451 let real_line = line - 1 in
452 case fromInteger real_line of { i@(I# l) ->
453 -- ToDo, if no filename then we skip the newline.... d'oh
454 case expandWhile# is_space buf2 of { buf3 ->
455 case currentChar# buf3 of
457 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
459 file = lexemeToFastString buf4
460 new_buf = stepOn (stepOverLexeme buf4)
462 if nullFastString file
463 then cont new_buf s{loc = replaceSrcLine loc l}
464 else cont new_buf s{loc = mkSrcLoc file i}
466 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
469 skipNestedComment :: P a -> P a
470 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
472 skipNestedComment' :: SrcLoc -> P a -> P a
473 skipNestedComment' orig_loc cont buf = loop buf
476 case currentChar# buf of
477 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
479 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
481 (skipNestedComment' orig_loc cont)
484 '\n'# -> \ s@PState{loc=loc} ->
485 let buf' = stepOn buf in
486 loop buf' s{loc = incSrcLine loc,
487 bol = currentIndex# buf',
490 -- pass the original SrcLoc to lexError so that the error is
491 -- reported at the line it was originally on, not the line at
492 -- the end of the file.
493 '\NUL'# | bufferExhausted (stepOn buf) ->
494 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
496 _ -> loop (stepOn buf)
498 -- When we are lexing the first token of a line, check whether we need to
499 -- insert virtual semicolons or close braces due to layout.
501 lexBOL :: (Token -> P a) -> P a
502 lexBOL cont buf s@(PState{
509 if need_close_curly then
510 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
511 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
512 else if need_semi_colon then
513 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
514 cont ITsemi buf s{atbol = 0#}
516 lexToken cont exts buf s{atbol = 0#}
518 col = currentIndex# buf -# bol
531 Layout n -> col ==# n
534 lexToken :: (Token -> P a) -> Int# -> P a
535 lexToken cont exts buf =
536 -- trace "lexToken" $
537 case currentChar# buf of
539 -- special symbols ----------------------------------------------------
540 '('# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '#'#
541 -> cont IToubxparen (addToCurrentPos buf 2#)
543 -> cont IToparen (incCurrentPos buf)
545 ')'# -> cont ITcparen (incCurrentPos buf)
546 '['# | parrEnabled exts && lookAhead# buf 1# `eqChar#` ':'# ->
547 cont ITopabrack (addToCurrentPos buf 2#)
548 ------- MetaHaskell Extensions, looking for [| [e| [t| [p| and [d|
549 | glaExtsEnabled exts &&
550 ((lookAhead# buf 1# ) `eqChar#` '|'# ) ->
551 cont ITopenExpQuote (addToCurrentPos buf 2# )
552 | glaExtsEnabled exts &&
553 (let c = (lookAhead# buf 1# )
554 in eqChar# c 'e'# || eqChar# c 't'# || eqChar# c 'd'# || eqChar# c 'p'#) &&
555 ((lookAhead# buf 2#) `eqChar#` '|'#) ->
556 let quote 'e'# = ITopenExpQuote
557 quote 'p'# = ITopenPatQuote
558 quote 'd'# = ITopenDecQuote
559 quote 't'# = ITopenTypQuote
560 in cont (quote (lookAhead# buf 1#)) (addToCurrentPos buf 3# )
562 cont ITobrack (incCurrentPos buf)
564 ']'# -> cont ITcbrack (incCurrentPos buf)
565 ','# -> cont ITcomma (incCurrentPos buf)
566 ';'# -> cont ITsemi (incCurrentPos buf)
567 '}'# -> \ s@PState{context = ctx} ->
569 (_:ctx') -> cont ITccurly (incCurrentPos buf) s{context=ctx'}
570 _ -> lexError "too many '}'s" buf s
571 '|'# -> case lookAhead# buf 1# of
572 '}'# | glaExtsEnabled exts -> cont ITccurlybar
573 (addToCurrentPos buf 2#)
574 -- MetaHaskell extension
575 ']'# | glaExtsEnabled exts -> cont ITcloseQuote (addToCurrentPos buf 2#)
576 other -> lex_sym cont (incCurrentPos buf)
577 ':'# -> case lookAhead# buf 1# of
578 ']'# | parrEnabled exts -> cont ITcpabrack
579 (addToCurrentPos buf 2#)
580 _ -> lex_sym cont (incCurrentPos buf)
583 '#'# -> case lookAhead# buf 1# of
584 ')'# | glaExtsEnabled exts
585 -> cont ITcubxparen (addToCurrentPos buf 2#)
586 '-'# -> case lookAhead# buf 2# of
587 '}'# -> cont ITclose_prag (addToCurrentPos buf 3#)
588 _ -> lex_sym cont (incCurrentPos buf)
589 _ -> lex_sym cont (incCurrentPos buf)
591 '`'# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '`'#
592 -> lex_cstring cont (addToCurrentPos buf 2#)
594 -> cont ITbackquote (incCurrentPos buf)
596 '{'# -> -- for Emacs: -}
597 case lookAhead# buf 1# of
598 '|'# | glaExtsEnabled exts
599 -> cont ITocurlybar (addToCurrentPos buf 2#)
600 '-'# -> case lookAhead# buf 2# of
601 '#'# -> lex_prag cont (addToCurrentPos buf 3#)
602 _ -> cont ITocurly (incCurrentPos buf)
603 _ -> (layoutOff `thenP_` cont ITocurly) (incCurrentPos buf)
608 -- strings/characters -------------------------------------------------
609 '\"'#{-"-} -> lex_string cont exts [] (incCurrentPos buf)
610 '\''# -> lex_char (char_end cont) exts (incCurrentPos buf)
612 -- Hexadecimal and octal constants
613 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
614 -> readNum (after_lexnum cont exts) buf' is_hexdigit 16 hex
615 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
616 -> readNum (after_lexnum cont exts) buf' is_octdigit 8 oct_or_dec
617 where ch = lookAhead# buf 1#
618 ch2 = lookAhead# buf 2#
619 buf' = addToCurrentPos buf 2#
622 if bufferExhausted (stepOn buf) then
625 trace "lexIface: misplaced NUL?" $
626 cont (ITunknown "\NUL") (stepOn buf)
628 '?'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- ?x implicit parameter
629 specialPrefixId ITdupipvarid cont exts (incCurrentPos buf)
630 '%'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->
631 specialPrefixId ITsplitipvarid cont exts (incCurrentPos buf)
633 ---------------- MetaHaskell Extensions for quotation escape
634 '$'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- $x variable escape
635 specialPrefixId ITidEscape cont exts (addToCurrentPos buf 1#)
636 '$'# | glaExtsEnabled exts && -- $( f x ) expression escape
637 ((lookAhead# buf 1#) `eqChar#` '('#) -> cont ITparenEscape (addToCurrentPos buf 2#)
639 c | is_digit c -> lex_num cont exts 0 buf
640 | is_symbol c -> lex_sym cont buf
641 | is_upper c -> lex_con cont exts buf
642 | is_lower c -> lex_id cont exts buf
643 | otherwise -> lexError "illegal character" buf
645 -- Int# is unlifted, and therefore faster than Bool for flags.
651 -------------------------------------------------------------------------------
655 = case expandWhile# is_space buf of { buf1 ->
656 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
657 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
658 case lookupUFM pragmaKeywordsFM lexeme of
659 Just kw -> cont kw (mergeLexemes buf buf2)
660 Nothing -> panic "lex_prag"
663 -------------------------------------------------------------------------------
666 lex_string cont exts s buf
667 = case currentChar# buf of
669 let buf' = incCurrentPos buf
670 in case currentChar# buf' of
671 '#'# | glaExtsEnabled exts ->
673 then lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
674 else let s' = mkFastStringNarrow (map chr (reverse s)) in
675 -- always a narrow string/byte array
676 cont (ITprimstring s') (incCurrentPos buf')
678 _other -> let s' = mkFastString (map chr (reverse s))
679 in cont (ITstring s') buf'
681 -- ignore \& in a string, deal with string gaps
682 '\\'# | next_ch `eqChar#` '&'#
683 -> lex_string cont exts s buf'
685 -> lex_stringgap cont exts s (incCurrentPos buf)
687 where next_ch = lookAhead# buf 1#
688 buf' = addToCurrentPos buf 2#
690 _ -> lex_char (lex_next_string cont s) exts buf
692 lex_stringgap cont exts s buf
693 = let buf' = incCurrentPos buf in
694 case currentChar# buf of
695 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont exts s buf'
696 st{loc = incSrcLine loc}
697 '\\'# -> lex_string cont exts s buf'
698 c | is_space c -> lex_stringgap cont exts s buf'
699 other -> charError buf'
701 lex_next_string cont s exts c buf = lex_string cont exts (c:s) buf
703 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
704 lex_char cont exts buf
705 = case currentChar# buf of
706 '\\'# -> lex_escape (cont exts) (incCurrentPos buf)
707 c | is_any c -> cont exts (I# (ord# c)) (incCurrentPos buf)
708 other -> charError buf
710 char_end cont exts c buf
711 = case currentChar# buf of
712 '\''# -> let buf' = incCurrentPos buf in
713 case currentChar# buf' of
714 '#'# | glaExtsEnabled exts
715 -> cont (ITprimchar c) (incCurrentPos buf')
716 _ -> cont (ITchar c) buf'
720 = let buf' = incCurrentPos buf in
721 case currentChar# buf of
722 'a'# -> cont (ord '\a') buf'
723 'b'# -> cont (ord '\b') buf'
724 'f'# -> cont (ord '\f') buf'
725 'n'# -> cont (ord '\n') buf'
726 'r'# -> cont (ord '\r') buf'
727 't'# -> cont (ord '\t') buf'
728 'v'# -> cont (ord '\v') buf'
729 '\\'# -> cont (ord '\\') buf'
730 '"'# -> cont (ord '\"') buf'
731 '\''# -> cont (ord '\'') buf'
732 '^'# -> let c = currentChar# buf' in
733 if c `geChar#` '@'# && c `leChar#` '_'#
734 then cont (I# (ord# c -# ord# '@'#)) (incCurrentPos buf')
737 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
738 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
740 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
742 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
743 Just buf2 <- [prefixMatch buf p] ] of
744 (c,buf2):_ -> cont (ord c) buf2
747 after_charnum cont i buf
748 = if i >= 0 && i <= 0x10FFFF
749 then cont (fromInteger i) buf
752 readNum cont buf is_digit base conv = read buf 0
754 = case currentChar# buf of { c ->
756 then read (incCurrentPos buf) (i*base + (toInteger (I# (conv c))))
762 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
763 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
765 hex c | is_digit c = ord# c -# ord# '0'#
766 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
767 oct_or_dec c = ord# c -# ord# '0'#
769 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
772 | c `geChar#` 'A'# && c `leChar#` 'Z'#
773 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
776 charError buf = lexError "error in character literal" buf
778 silly_escape_chars = [
815 -----------------------------------------------------------------------------
818 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
819 lex_num cont exts acc buf =
820 case scanNumLit acc buf of
822 case currentChar# buf' of
823 '.'# | is_digit (lookAhead# buf' 1#) ->
824 -- this case is not optimised at all, as the
825 -- presence of floating point numbers in interface
826 -- files is not that common. (ToDo)
827 case expandWhile# is_digit (incCurrentPos buf') of
828 buf2 -> -- points to first non digit char
830 let l = case currentChar# buf2 of
836 = let buf3 = incCurrentPos buf2 in
837 case currentChar# buf3 of
838 '-'# | is_digit (lookAhead# buf3 1#)
839 -> expandWhile# is_digit (incCurrentPos buf3)
840 '+'# | is_digit (lookAhead# buf3 1#)
841 -> expandWhile# is_digit (incCurrentPos buf3)
842 x | is_digit x -> expandWhile# is_digit buf3
845 v = readRational__ (lexemeToString l)
847 in case currentChar# l of -- glasgow exts only
848 '#'# | glaExtsEnabled exts -> let l' = incCurrentPos l in
849 case currentChar# l' of
850 '#'# -> cont (ITprimdouble v) (incCurrentPos l')
851 _ -> cont (ITprimfloat v) l'
852 _ -> cont (ITrational v) l
854 _ -> after_lexnum cont exts acc' buf'
856 after_lexnum cont exts i buf
857 = case currentChar# buf of
858 '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
859 _ -> cont (ITinteger i) buf
861 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
865 return ((n%1)*10^^(k-d), t)
868 (ds,s) <- lexDecDigits r
869 (ds',t) <- lexDotDigits s
870 return (read (ds++ds'), length ds', t)
872 readExp (e:s) | e `elem` "eE" = readExp' s
873 readExp s = return (0,s)
875 readExp' ('+':s) = readDec s
876 readExp' ('-':s) = do
879 readExp' s = readDec s
882 (ds,r) <- nonnull isDigit s
883 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
886 lexDecDigits = nonnull isDigit
888 lexDotDigits ('.':s) = return (span isDigit s)
889 lexDotDigits s = return ("",s)
891 nonnull p s = do (cs@(_:_),t) <- return (span p s)
894 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
897 '-' : xs -> - (read_me xs)
901 = case (do { (x,"") <- readRational s ; return x }) of
903 [] -> error ("readRational__: no parse:" ++ top_s)
904 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
906 -----------------------------------------------------------------------------
907 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
909 -- we lexemeToFastString on the bit between the ``''s, but include the
910 -- quotes in the full lexeme.
912 lex_cstring cont buf =
913 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
914 Just buf' -> cont (ITlitlit (lexemeToFastString
915 (addToCurrentPos buf' (negateInt# 2#))))
916 (mergeLexemes buf buf')
917 Nothing -> lexError "unterminated ``" buf
919 -----------------------------------------------------------------------------
920 -- identifiers, symbols etc.
922 -- used for identifiers with special prefixes like
923 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
924 -- we've already seen the prefix char, so look for an id, and wrap
925 -- the new "ip_constr" around the lexeme returned
927 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
928 where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
929 newcont token buf2 = cont token buf2
931 case expandWhile# is_ident buf of
932 buf' -> cont (ip_constr (tailFS lexeme)) buf'
933 where lexeme = lexemeToFastString buf'
936 lex_id cont exts buf =
937 let buf1 = expandWhile# is_ident buf in
940 case (if glaExtsEnabled exts
941 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
942 else buf1) of { buf' ->
945 let lexeme = lexemeToFastString buf' in
947 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
948 Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
952 let var_token = cont (ITvarid lexeme) buf' in
954 case lookupUFM ghcExtensionKeywordsFM lexeme of {
955 Just (kwd_token, validExts)
956 | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
963 case expandWhile# is_symbol buf of
964 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
965 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
966 cont kwd_token buf' ;
967 Nothing -> --trace ("sym: "++unpackFS lexeme) $
968 cont (mk_var_token lexeme) buf'
970 where lexeme = lexemeToFastString buf'
973 -- lex_con recursively collects components of a qualified identifer.
974 -- The argument buf is the StringBuffer representing the lexeme
975 -- identified so far, where the next character is upper-case.
977 lex_con cont exts buf =
978 -- trace ("con: "{-++unpackFS lexeme-}) $
979 let empty_buf = stepOverLexeme buf in
980 case expandWhile# is_ident empty_buf of { buf1 ->
981 case slurp_trailing_hashes buf1 exts of { con_buf ->
983 let all_buf = mergeLexemes buf con_buf
985 con_lexeme = lexemeToFastString con_buf
986 mod_lexeme = lexemeToFastString (decCurrentPos buf)
987 all_lexeme = lexemeToFastString all_buf
990 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
991 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
994 case currentChar# all_buf of
995 '.'# -> maybe_qualified cont exts all_lexeme
996 (incCurrentPos all_buf) just_a_conid
1001 maybe_qualified cont exts mod buf just_a_conid =
1002 -- trace ("qid: "{-++unpackFS lexeme-}) $
1003 case currentChar# buf of
1004 '['# -> -- Special case for []
1005 case lookAhead# buf 1# of
1006 ']'# -> cont (ITqconid (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
1009 '('# -> -- Special case for (,,,)
1010 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1011 case lookAhead# buf 1# of
1012 '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
1013 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#)
1016 ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1017 ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1020 '-'# -> case lookAhead# buf 1# of
1021 '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1022 _ -> lex_id3 cont exts mod buf just_a_conid
1024 _ -> lex_id3 cont exts mod buf just_a_conid
1027 lex_id3 cont exts mod buf just_a_conid
1028 | is_upper (currentChar# buf) =
1029 lex_con cont exts buf
1031 | is_symbol (currentChar# buf) =
1033 start_new_lexeme = stepOverLexeme buf
1035 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1036 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1038 lexeme = lexemeToFastString buf'
1039 -- real lexeme is M.<sym>
1040 new_buf = mergeLexemes buf buf'
1042 cont (mk_qvar_token mod lexeme) new_buf
1043 -- wrong, but arguably morally right: M... is now a qvarsym
1048 start_new_lexeme = stepOverLexeme buf
1050 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1051 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1056 case slurp_trailing_hashes buf1 exts of { buf' ->
1059 lexeme = lexemeToFastString buf'
1060 new_buf = mergeLexemes buf buf'
1061 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1063 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1064 Nothing -> is_a_qvarid ;
1066 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1067 -> is_a_qvarid -- recognised as keywords here.
1069 -> just_a_conid -- avoid M.where etc.
1072 slurp_trailing_hashes buf exts
1073 | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1078 | is_upper f = ITconid pk_str
1079 | is_ident f = ITvarid pk_str
1080 | f `eqChar#` ':'# = ITconsym pk_str
1081 | otherwise = ITvarsym pk_str
1083 (C# f) = headFS pk_str
1084 -- tl = _TAIL_ pk_str
1086 mk_qvar_token m token =
1087 -- trace ("mk_qvar ") $
1088 case mk_var_token token of
1089 ITconid n -> ITqconid (m,n)
1090 ITvarid n -> ITqvarid (m,n)
1091 ITconsym n -> ITqconsym (m,n)
1092 ITvarsym n -> ITqvarsym (m,n)
1093 _ -> ITunknown (show token)
1096 ----------------------------------------------------------------------------
1097 Horrible stuff for dealing with M.(,,,)
1100 lex_tuple cont mod buf back_off =
1104 case currentChar# buf of
1105 ','# -> go (n+1) (stepOn buf)
1106 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1109 lex_ubx_tuple cont mod buf back_off =
1113 case currentChar# buf of
1114 ','# -> go (n+1) (stepOn buf)
1115 '#'# -> case lookAhead# buf 1# of
1116 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1122 -----------------------------------------------------------------------------
1133 data PState = PState {
1135 extsBitmap :: Int#, -- bitmap that determines permitted extensions
1138 context :: [LayoutContext]
1141 type P a = StringBuffer -- Input string
1146 returnP a buf s = POk s a
1148 thenP :: P a -> (a -> P b) -> P b
1149 m `thenP` k = \ buf s ->
1151 POk s1 a -> k a buf s1
1152 PFailed err -> PFailed err
1154 thenP_ :: P a -> P b -> P b
1155 m `thenP_` k = m `thenP` \_ -> k
1157 mapP :: (a -> P b) -> [a] -> P [b]
1158 mapP f [] = returnP []
1161 mapP f as `thenP` \bs ->
1164 failP :: String -> P a
1165 failP msg buf s = PFailed (text msg)
1167 failMsgP :: Message -> P a
1168 failMsgP msg buf s = PFailed msg
1170 lexError :: String -> P a
1171 lexError str buf s@PState{ loc = loc }
1172 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1174 getSrcLocP :: P SrcLoc
1175 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1177 -- use a temporary SrcLoc for the duration of the argument
1178 setSrcLocP :: SrcLoc -> P a -> P a
1179 setSrcLocP new_loc p buf s =
1180 case p buf s{ loc=new_loc } of
1182 PFailed e -> PFailed e
1184 getSrcFile :: P FastString
1185 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1187 pushContext :: LayoutContext -> P ()
1188 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1192 This special case in layoutOn is to handle layout contexts with are
1193 indented the same or less than the current context. This is illegal
1194 according to the Haskell spec, so we have to arrange to close the
1195 current context. eg.
1200 after the first 'where', the sequence of events is:
1202 - layout system inserts a ';' (column 0)
1203 - parser begins a new context at column 0
1204 - parser shifts ';' (legal empty declaration)
1205 - parser sees 'class': parse error (we're still in the inner context)
1207 trouble is, by the time we know we need a new context, the lexer has
1208 already generated the ';'. Hacky solution is as follows: since we
1209 know the column of the next token (it's the column number of the new
1210 context), we set the ACTUAL column number of the new context to this
1211 numer plus one. Hence the next time the lexer is called, a '}' will
1212 be generated to close the new context straight away. Furthermore, we
1213 have to set the atbol flag so that the ';' that the parser shifted as
1214 part of the new context is re-generated.
1216 when the new context is *less* indented than the current one:
1218 f = f where g = g where
1221 - current context: column 12.
1222 - on seeing 'h' (column 0), the layout system inserts '}'
1223 - parser starts a new context, column 0
1224 - parser sees '}', uses it to close new context
1225 - we still need to insert another '}' followed by a ';',
1226 hence the atbol trick.
1228 There's also a special hack in here to deal with
1235 i.e. the inner context is at the same indentation level as the outer
1236 context. This is strictly illegal according to Haskell 98, but
1237 there's a lot of existing code using this style and it doesn't make
1238 any sense to disallow it, since empty 'do' lists don't make sense.
1241 layoutOn :: Bool -> P ()
1242 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1243 let offset = lexemeIndex buf -# bol in
1246 | if strict then prev_off >=# offset else prev_off ># offset ->
1247 --trace ("layout on, column: " ++ show (I# offset)) $
1248 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1250 --trace ("layout on, column: " ++ show (I# offset)) $
1251 POk s{ context = Layout offset : ctx } ()
1254 layoutOff buf s@(PState{ context = ctx }) =
1255 POk s{ context = NoLayout:ctx } ()
1258 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1260 (_:tl) -> POk s{ context = tl } ()
1261 [] -> PFailed (srcParseErr buf loc)
1263 -- for reasons of efficiency, flags indicating language extensions (eg,
1264 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1267 glaExtsBit, ffiBit, parrBit :: Int
1273 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1274 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1275 ffiEnabled flags = testBit (toInt32 flags) ffiBit
1276 withEnabled flags = testBit (toInt32 flags) withBit
1277 parrEnabled flags = testBit (toInt32 flags) parrBit
1279 toInt32 :: Int# -> Int32
1280 toInt32 x# = fromIntegral (I# x#)
1282 -- convenient record-based bitmap for the interface to the rest of the world
1284 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1286 data ExtFlags = ExtFlags {
1287 glasgowExtsEF :: Bool,
1293 -- create a parse state
1295 mkPState :: SrcLoc -> ExtFlags -> PState
1299 extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1305 bitmap = glaExtsBit `setBitIf` glasgowExtsEF exts
1306 .|. ffiBit `setBitIf` (ffiEF exts
1307 || glasgowExtsEF exts)
1308 .|. withBit `setBitIf` withEF exts
1309 .|. parrBit `setBitIf` parrEF exts
1311 setBitIf :: Int -> Bool -> Int32
1312 b `setBitIf` cond | cond = bit b
1315 -----------------------------------------------------------------------------
1317 srcParseErr :: StringBuffer -> SrcLoc -> Message
1321 then ptext SLIT(": parse error (possibly incorrect indentation)")
1322 else hcat [ptext SLIT(": parse error on input "),
1323 char '`', text token, char '\'']
1326 token = lexemeToString s