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
829 case currentChar# buf2 of
830 'E'# -> float_exponent cont exts buf2
831 'e'# -> float_exponent cont exts buf2
832 _ -> float_done cont exts buf2
834 -- numbers like '9e4' are floats
835 'E'# -> float_exponent cont exts buf'
836 'e'# -> float_exponent cont exts buf'
837 _ -> after_lexnum cont exts acc' buf' -- it's an integer
839 float_exponent cont exts buf2 =
840 let buf3 = incCurrentPos buf2
841 buf4 = case currentChar# buf3 of
842 '-'# | is_digit (lookAhead# buf3 1#)
843 -> expandWhile# is_digit (incCurrentPos buf3)
844 '+'# | is_digit (lookAhead# buf3 1#)
845 -> expandWhile# is_digit (incCurrentPos buf3)
846 x | is_digit x -> expandWhile# is_digit buf3
849 float_done cont exts buf4
851 float_done cont exts buf =
852 case currentChar# buf of -- glasgow exts only
853 '#'# | glaExtsEnabled exts ->
854 let buf' = incCurrentPos buf in
855 case currentChar# buf' of
856 '#'# -> cont (ITprimdouble v) (incCurrentPos buf')
857 _ -> cont (ITprimfloat v) buf'
858 _ -> cont (ITrational v) buf
860 v = readRational__ (lexemeToString buf)
862 after_lexnum cont exts i buf
863 = case currentChar# buf of
864 '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
865 _ -> cont (ITinteger i) buf
867 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
871 return ((n%1)*10^^(k-d), t)
874 (ds,s) <- lexDecDigits r
875 (ds',t) <- lexDotDigits s
876 return (read (ds++ds'), length ds', t)
878 readExp (e:s) | e `elem` "eE" = readExp' s
879 readExp s = return (0,s)
881 readExp' ('+':s) = readDec s
882 readExp' ('-':s) = do
885 readExp' s = readDec s
888 (ds,r) <- nonnull isDigit s
889 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
892 lexDecDigits = nonnull isDigit
894 lexDotDigits ('.':s) = return (span isDigit s)
895 lexDotDigits s = return ("",s)
897 nonnull p s = do (cs@(_:_),t) <- return (span p s)
900 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
903 '-' : xs -> - (read_me xs)
907 = case (do { (x,"") <- readRational s ; return x }) of
909 [] -> error ("readRational__: no parse:" ++ top_s)
910 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
912 -----------------------------------------------------------------------------
913 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
915 -- we lexemeToFastString on the bit between the ``''s, but include the
916 -- quotes in the full lexeme.
918 lex_cstring cont buf =
919 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
920 Just buf' -> cont (ITlitlit (lexemeToFastString
921 (addToCurrentPos buf' (negateInt# 2#))))
922 (mergeLexemes buf buf')
923 Nothing -> lexError "unterminated ``" buf
925 -----------------------------------------------------------------------------
926 -- identifiers, symbols etc.
928 -- used for identifiers with special prefixes like
929 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
930 -- we've already seen the prefix char, so look for an id, and wrap
931 -- the new "ip_constr" around the lexeme returned
933 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
934 where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
935 newcont token buf2 = cont token buf2
937 case expandWhile# is_ident buf of
938 buf' -> cont (ip_constr (tailFS lexeme)) buf'
939 where lexeme = lexemeToFastString buf'
942 lex_id cont exts buf =
943 let buf1 = expandWhile# is_ident buf in
946 case (if glaExtsEnabled exts
947 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
948 else buf1) of { buf' ->
951 let lexeme = lexemeToFastString buf' in
953 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
954 Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
958 let var_token = cont (ITvarid lexeme) buf' in
960 case lookupUFM ghcExtensionKeywordsFM lexeme of {
961 Just (kwd_token, validExts)
962 | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
969 case expandWhile# is_symbol buf of
970 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
971 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
972 cont kwd_token buf' ;
973 Nothing -> --trace ("sym: "++unpackFS lexeme) $
974 cont (mk_var_token lexeme) buf'
976 where lexeme = lexemeToFastString buf'
979 -- lex_con recursively collects components of a qualified identifer.
980 -- The argument buf is the StringBuffer representing the lexeme
981 -- identified so far, where the next character is upper-case.
983 lex_con cont exts buf =
984 -- trace ("con: "{-++unpackFS lexeme-}) $
985 let empty_buf = stepOverLexeme buf in
986 case expandWhile# is_ident empty_buf of { buf1 ->
987 case slurp_trailing_hashes buf1 exts of { con_buf ->
989 let all_buf = mergeLexemes buf con_buf
991 con_lexeme = lexemeToFastString con_buf
992 mod_lexeme = lexemeToFastString (decCurrentPos buf)
993 all_lexeme = lexemeToFastString all_buf
996 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
997 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
1000 case currentChar# all_buf of
1001 '.'# -> maybe_qualified cont exts all_lexeme
1002 (incCurrentPos all_buf) just_a_conid
1007 maybe_qualified cont exts mod buf just_a_conid =
1008 -- trace ("qid: "{-++unpackFS lexeme-}) $
1009 case currentChar# buf of
1010 '['# -> -- Special case for []
1011 case lookAhead# buf 1# of
1012 ']'# -> cont (ITqconid (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
1015 '('# -> -- Special case for (,,,)
1016 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1017 case lookAhead# buf 1# of
1018 '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
1019 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#)
1022 ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1023 ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1026 '-'# -> case lookAhead# buf 1# of
1027 '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1028 _ -> lex_id3 cont exts mod buf just_a_conid
1030 _ -> lex_id3 cont exts mod buf just_a_conid
1033 lex_id3 cont exts mod buf just_a_conid
1034 | is_upper (currentChar# buf) =
1035 lex_con cont exts buf
1037 | is_symbol (currentChar# buf) =
1039 start_new_lexeme = stepOverLexeme buf
1041 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1042 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1044 lexeme = lexemeToFastString buf'
1045 -- real lexeme is M.<sym>
1046 new_buf = mergeLexemes buf buf'
1048 cont (mk_qvar_token mod lexeme) new_buf
1049 -- wrong, but arguably morally right: M... is now a qvarsym
1054 start_new_lexeme = stepOverLexeme buf
1056 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1057 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1062 case slurp_trailing_hashes buf1 exts of { buf' ->
1065 lexeme = lexemeToFastString buf'
1066 new_buf = mergeLexemes buf buf'
1067 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1069 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1070 Nothing -> is_a_qvarid ;
1072 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1073 -> is_a_qvarid -- recognised as keywords here.
1075 -> just_a_conid -- avoid M.where etc.
1078 slurp_trailing_hashes buf exts
1079 | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1084 | is_upper f = ITconid pk_str
1085 | is_ident f = ITvarid pk_str
1086 | f `eqChar#` ':'# = ITconsym pk_str
1087 | otherwise = ITvarsym pk_str
1089 (C# f) = headFS pk_str
1090 -- tl = _TAIL_ pk_str
1092 mk_qvar_token m token =
1093 -- trace ("mk_qvar ") $
1094 case mk_var_token token of
1095 ITconid n -> ITqconid (m,n)
1096 ITvarid n -> ITqvarid (m,n)
1097 ITconsym n -> ITqconsym (m,n)
1098 ITvarsym n -> ITqvarsym (m,n)
1099 _ -> ITunknown (show token)
1102 ----------------------------------------------------------------------------
1103 Horrible stuff for dealing with M.(,,,)
1106 lex_tuple cont mod buf back_off =
1110 case currentChar# buf of
1111 ','# -> go (n+1) (stepOn buf)
1112 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1115 lex_ubx_tuple cont mod buf back_off =
1119 case currentChar# buf of
1120 ','# -> go (n+1) (stepOn buf)
1121 '#'# -> case lookAhead# buf 1# of
1122 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1128 -----------------------------------------------------------------------------
1139 data PState = PState {
1141 extsBitmap :: Int#, -- bitmap that determines permitted extensions
1144 context :: [LayoutContext]
1147 type P a = StringBuffer -- Input string
1152 returnP a buf s = POk s a
1154 thenP :: P a -> (a -> P b) -> P b
1155 m `thenP` k = \ buf s ->
1157 POk s1 a -> k a buf s1
1158 PFailed err -> PFailed err
1160 thenP_ :: P a -> P b -> P b
1161 m `thenP_` k = m `thenP` \_ -> k
1163 mapP :: (a -> P b) -> [a] -> P [b]
1164 mapP f [] = returnP []
1167 mapP f as `thenP` \bs ->
1170 failP :: String -> P a
1171 failP msg buf s = PFailed (text msg)
1173 failMsgP :: Message -> P a
1174 failMsgP msg buf s = PFailed msg
1176 lexError :: String -> P a
1177 lexError str buf s@PState{ loc = loc }
1178 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1180 getSrcLocP :: P SrcLoc
1181 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1183 -- use a temporary SrcLoc for the duration of the argument
1184 setSrcLocP :: SrcLoc -> P a -> P a
1185 setSrcLocP new_loc p buf s =
1186 case p buf s{ loc=new_loc } of
1188 PFailed e -> PFailed e
1190 getSrcFile :: P FastString
1191 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1193 pushContext :: LayoutContext -> P ()
1194 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1198 This special case in layoutOn is to handle layout contexts with are
1199 indented the same or less than the current context. This is illegal
1200 according to the Haskell spec, so we have to arrange to close the
1201 current context. eg.
1206 after the first 'where', the sequence of events is:
1208 - layout system inserts a ';' (column 0)
1209 - parser begins a new context at column 0
1210 - parser shifts ';' (legal empty declaration)
1211 - parser sees 'class': parse error (we're still in the inner context)
1213 trouble is, by the time we know we need a new context, the lexer has
1214 already generated the ';'. Hacky solution is as follows: since we
1215 know the column of the next token (it's the column number of the new
1216 context), we set the ACTUAL column number of the new context to this
1217 numer plus one. Hence the next time the lexer is called, a '}' will
1218 be generated to close the new context straight away. Furthermore, we
1219 have to set the atbol flag so that the ';' that the parser shifted as
1220 part of the new context is re-generated.
1222 when the new context is *less* indented than the current one:
1224 f = f where g = g where
1227 - current context: column 12.
1228 - on seeing 'h' (column 0), the layout system inserts '}'
1229 - parser starts a new context, column 0
1230 - parser sees '}', uses it to close new context
1231 - we still need to insert another '}' followed by a ';',
1232 hence the atbol trick.
1234 There's also a special hack in here to deal with
1241 i.e. the inner context is at the same indentation level as the outer
1242 context. This is strictly illegal according to Haskell 98, but
1243 there's a lot of existing code using this style and it doesn't make
1244 any sense to disallow it, since empty 'do' lists don't make sense.
1247 layoutOn :: Bool -> P ()
1248 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1249 let offset = lexemeIndex buf -# bol in
1252 | if strict then prev_off >=# offset else prev_off ># offset ->
1253 --trace ("layout on, column: " ++ show (I# offset)) $
1254 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1256 --trace ("layout on, column: " ++ show (I# offset)) $
1257 POk s{ context = Layout offset : ctx } ()
1260 layoutOff buf s@(PState{ context = ctx }) =
1261 POk s{ context = NoLayout:ctx } ()
1264 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1266 (_:tl) -> POk s{ context = tl } ()
1267 [] -> PFailed (srcParseErr buf loc)
1269 -- for reasons of efficiency, flags indicating language extensions (eg,
1270 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1273 glaExtsBit, ffiBit, parrBit :: Int
1279 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1280 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1281 ffiEnabled flags = testBit (toInt32 flags) ffiBit
1282 withEnabled flags = testBit (toInt32 flags) withBit
1283 parrEnabled flags = testBit (toInt32 flags) parrBit
1285 toInt32 :: Int# -> Int32
1286 toInt32 x# = fromIntegral (I# x#)
1288 -- convenient record-based bitmap for the interface to the rest of the world
1290 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1292 data ExtFlags = ExtFlags {
1293 glasgowExtsEF :: Bool,
1299 -- create a parse state
1301 mkPState :: SrcLoc -> ExtFlags -> PState
1305 extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1311 bitmap = glaExtsBit `setBitIf` glasgowExtsEF exts
1312 .|. ffiBit `setBitIf` (ffiEF exts
1313 || glasgowExtsEF exts)
1314 .|. withBit `setBitIf` withEF exts
1315 .|. parrBit `setBitIf` parrEF exts
1317 setBitIf :: Int -> Bool -> Int32
1318 b `setBitIf` cond | cond = bit b
1321 -----------------------------------------------------------------------------
1323 srcParseErr :: StringBuffer -> SrcLoc -> Message
1327 then ptext SLIT(": parse error (possibly incorrect indentation)")
1328 else hcat [ptext SLIT(": parse error on input "),
1329 char '`', text token, char '\'']
1332 token = lexemeToString s