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 -- Arrow notation extension
220 | ITLarrowtail -- -<<
221 | ITRarrowtail -- >>-
223 | ITunknown String -- Used when the lexer can't make sense of it
224 | ITeof -- end of file token
225 deriving Show -- debugging
228 -----------------------------------------------------------------------------
232 pragmaKeywordsFM = listToUFM $
233 map (\ (x,y) -> (mkFastString x,y))
234 [( "SPECIALISE", ITspecialise_prag ),
235 ( "SPECIALIZE", ITspecialise_prag ),
236 ( "SOURCE", ITsource_prag ),
237 ( "INLINE", ITinline_prag ),
238 ( "NOINLINE", ITnoinline_prag ),
239 ( "NOTINLINE", ITnoinline_prag ),
240 ( "LINE", ITline_prag ),
241 ( "RULES", ITrules_prag ),
242 ( "RULEZ", ITrules_prag ), -- american spelling :-)
243 ( "SCC", ITscc_prag ),
244 ( "CORE", ITcore_prag ), -- hdaume: core annotation
245 ( "DEPRECATED", ITdeprecated_prag )
248 haskellKeywordsFM = listToUFM $
249 map (\ (x,y) -> (mkFastString x,y))
250 [( "_", ITunderscore ),
253 ( "class", ITclass ),
255 ( "default", ITdefault ),
256 ( "deriving", ITderiving ),
259 ( "hiding", IThiding ),
261 ( "import", ITimport ),
263 ( "infix", ITinfix ),
264 ( "infixl", ITinfixl ),
265 ( "infixr", ITinfixr ),
266 ( "instance", ITinstance ),
268 ( "module", ITmodule ),
269 ( "newtype", ITnewtype ),
271 ( "qualified", ITqualified ),
274 ( "where", ITwhere ),
275 ( "_scc_", ITscc ) -- ToDo: remove
278 isSpecial :: Token -> Bool
279 -- If we see M.x, where x is a keyword, but
280 -- is special, we treat is as just plain M.x,
282 isSpecial ITas = True
283 isSpecial IThiding = True
284 isSpecial ITqualified = True
285 isSpecial ITforall = True
286 isSpecial ITexport = True
287 isSpecial ITlabel = True
288 isSpecial ITdynamic = True
289 isSpecial ITsafe = True
290 isSpecial ITthreadsafe = True
291 isSpecial ITunsafe = True
292 isSpecial ITwith = True
293 isSpecial ITccallconv = True
294 isSpecial ITstdcallconv = True
295 isSpecial ITmdo = True
298 -- the bitmap provided as the third component indicates whether the
299 -- corresponding extension keyword is valid under the extension options
300 -- provided to the compiler; if the extension corresponding to *any* of the
301 -- bits set in the bitmap is enabled, the keyword is valid (this setup
302 -- facilitates using a keyword in two different extensions that can be
303 -- activated independently)
305 ghcExtensionKeywordsFM = listToUFM $
306 map (\(x, y, z) -> (mkFastString x, (y, z)))
307 [ ( "forall", ITforall, bit glaExtsBit),
308 ( "mdo", ITmdo, bit glaExtsBit),
309 ( "reifyDecl", ITreifyDecl, bit glaExtsBit),
310 ( "reifyType", ITreifyType, bit glaExtsBit),
311 ( "reifyFixity",ITreifyFixity, bit glaExtsBit),
313 ( "rec", ITrec, bit glaExtsBit .|. bit arrowsBit),
315 ( "foreign", ITforeign, bit ffiBit),
316 ( "export", ITexport, bit ffiBit),
317 ( "label", ITlabel, bit ffiBit),
318 ( "dynamic", ITdynamic, bit ffiBit),
319 ( "safe", ITsafe, bit ffiBit),
320 ( "threadsafe", ITthreadsafe, bit ffiBit),
321 ( "unsafe", ITunsafe, bit ffiBit),
322 ( "stdcall", ITstdcallconv, bit ffiBit),
323 ( "ccall", ITccallconv, bit ffiBit),
324 ( "dotnet", ITdotnet, bit ffiBit),
326 ( "with", ITwith, bit withBit),
328 ( "proc", ITproc, bit arrowsBit),
331 ("_ccall_", ITccall (False, False, PlayRisky),
333 ("_ccall_GC_", ITccall (False, False, PlaySafe False),
335 ("_casm_", ITccall (False, True, PlayRisky),
337 ("_casm_GC_", ITccall (False, True, PlaySafe False),
341 haskellKeySymsFM = listToUFM $
342 map (\ (x,y,z) -> (mkFastString x,(y,z)))
343 [ ("..", ITdotdot, Nothing)
344 ,(":", ITcolon, Nothing) -- (:) is a reserved op,
345 -- meaning only list cons
346 ,("::", ITdcolon, Nothing)
347 ,("=", ITequal, Nothing)
348 ,("\\", ITlam, Nothing)
349 ,("|", ITvbar, Nothing)
350 ,("<-", ITlarrow, Nothing)
351 ,("->", ITrarrow, Nothing)
352 ,("@", ITat, Nothing)
353 ,("~", ITtilde, Nothing)
354 ,("=>", ITdarrow, Nothing)
355 ,("-", ITminus, Nothing)
356 ,("!", ITbang, Nothing)
358 ,("*", ITstar, Just (bit glaExtsBit)) -- For data T (a::*) = MkT
359 ,(".", ITdot, Just (bit glaExtsBit)) -- For 'forall a . t'
361 ,("-<", ITlarrowtail, Just (bit arrowsBit))
362 ,(">-", ITrarrowtail, Just (bit arrowsBit))
363 ,("-<<", ITLarrowtail, Just (bit arrowsBit))
364 ,(">>-", ITRarrowtail, Just (bit arrowsBit))
369 -----------------------------------------------------------------------------
374 - (exts) lexing a source with extensions, eg, an interface file or
376 - (bol) pointer to beginning of line (for column calculations)
377 - (buf) pointer to beginning of token
378 - (buf) pointer to current char
379 - (atbol) flag indicating whether we're at the beginning of a line
382 lexer :: (Token -> P a) -> P a
383 lexer cont buf s@(PState{
391 -- first, start a new lexeme and lose all the whitespace
393 tab line bol atbol (stepOverLexeme buf)
395 line = srcLocLine loc
397 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
398 case currentChar# buf of
401 if bufferExhausted (stepOn buf)
402 then cont ITeof buf s'
403 else trace "lexer: misplaced NUL?" $
404 tab y bol atbol (stepOn buf)
406 '\n'# -> let buf' = stepOn buf
407 in tab (y +# 1#) (currentIndex# buf') 1# buf'
409 -- find comments. This got harder in Haskell 98.
410 '-'# -> let trundle n =
411 let next = lookAhead# buf n in
412 if next `eqChar#` '-'# then trundle (n +# 1#)
413 else if is_symbol next || n <# 2#
416 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
419 -- comments and pragmas. We deal with LINE pragmas here,
420 -- and throw out any unrecognised pragmas as comments. Any
421 -- pragmas we know about are dealt with later (after any layout
422 -- processing if necessary).
423 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
424 if lookAhead# buf 2# `eqChar#` '#'# then
425 case expandWhile# is_space (addToCurrentPos buf 3#) of { buf1->
426 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
427 let lexeme = mkFastString -- ToDo: too slow
428 (map toUpper (lexemeToString buf2)) in
429 case lookupUFM pragmaKeywordsFM lexeme of
430 -- ignore RULES pragmas when -fglasgow-exts is off
431 Just ITrules_prag | not (glaExtsEnabled exts) ->
432 skip_to_end (stepOnBy# buf 2#) s'
434 line_prag skip_to_end buf2 s'
435 Just other -> is_a_token
436 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
439 else skip_to_end (stepOnBy# buf 2#) s'
441 skip_to_end = skipNestedComment (lexer cont)
443 -- special GHC extension: we grok cpp-style #line pragmas
444 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
445 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
446 lookAhead# buf 2# `eqChar#` 'i'# &&
447 lookAhead# buf 3# `eqChar#` 'n'# &&
448 lookAhead# buf 4# `eqChar#` 'e'# = stepOnBy# buf 5#
449 | otherwise = stepOn buf
451 case expandWhile# is_space buf1 of { buf2 ->
452 if is_digit (currentChar# buf2)
453 then line_prag next_line buf2 s'
457 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
459 -- tabs have been expanded beforehand
460 c | is_space c -> tab y bol atbol (stepOn buf)
461 | otherwise -> is_a_token
463 where s' = s{loc = replaceSrcLine loc y,
467 is_a_token | atbol /=# 0# = lexBOL cont buf s'
468 | otherwise = lexToken cont exts buf s'
470 -- {-# LINE .. #-} pragmas. yeuch.
471 line_prag cont buf s@PState{loc=loc} =
472 case expandWhile# is_space buf of { buf1 ->
473 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
474 -- subtract one: the line number refers to the *following* line.
475 let real_line = line - 1 in
476 case fromInteger real_line of { i@(I# l) ->
477 -- ToDo, if no filename then we skip the newline.... d'oh
478 case expandWhile# is_space buf2 of { buf3 ->
479 case currentChar# buf3 of
481 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
483 file = lexemeToFastString buf4
484 new_buf = stepOn (stepOverLexeme buf4)
486 if nullFastString file
487 then cont new_buf s{loc = replaceSrcLine loc l}
488 else cont new_buf s{loc = mkSrcLoc file i}
490 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
493 skipNestedComment :: P a -> P a
494 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
496 skipNestedComment' :: SrcLoc -> P a -> P a
497 skipNestedComment' orig_loc cont buf = loop buf
500 case currentChar# buf of
501 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
503 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
505 (skipNestedComment' orig_loc cont)
508 '\n'# -> \ s@PState{loc=loc} ->
509 let buf' = stepOn buf in
510 loop buf' s{loc = incSrcLine loc,
511 bol = currentIndex# buf',
514 -- pass the original SrcLoc to lexError so that the error is
515 -- reported at the line it was originally on, not the line at
516 -- the end of the file.
517 '\NUL'# | bufferExhausted (stepOn buf) ->
518 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
520 _ -> loop (stepOn buf)
522 -- When we are lexing the first token of a line, check whether we need to
523 -- insert virtual semicolons or close braces due to layout.
525 lexBOL :: (Token -> P a) -> P a
526 lexBOL cont buf s@(PState{
533 if need_close_curly then
534 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
535 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
536 else if need_semi_colon then
537 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
538 cont ITsemi buf s{atbol = 0#}
540 lexToken cont exts buf s{atbol = 0#}
542 col = currentIndex# buf -# bol
555 Layout n -> col ==# n
558 lexToken :: (Token -> P a) -> Int# -> P a
559 lexToken cont exts buf =
560 -- trace "lexToken" $
561 case currentChar# buf of
563 -- special symbols ----------------------------------------------------
564 '('# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '#'# &&
565 -- Unboxed tules: '(#' but not '(##'
566 not (lookAhead# buf 2# `eqChar#` '#'#)
567 -> cont IToubxparen (addToCurrentPos buf 2#)
568 -- Arrow notation extension: '(|' but not '(||'
569 | arrowsEnabled exts && lookAhead# buf 1# `eqChar#` '|'# &&
570 not (lookAhead# buf 2# `eqChar#` '|'#)
571 -> cont IToparenbar (addToCurrentPos buf 2#)
573 -> cont IToparen (incCurrentPos buf)
575 ')'# -> cont ITcparen (incCurrentPos buf)
576 '['# | parrEnabled exts && lookAhead# buf 1# `eqChar#` ':'# ->
577 cont ITopabrack (addToCurrentPos buf 2#)
578 ------- MetaHaskell Extensions, looking for [| [e| [t| [p| and [d|
579 | glaExtsEnabled exts &&
580 ((lookAhead# buf 1# ) `eqChar#` '|'# ) ->
581 cont ITopenExpQuote (addToCurrentPos buf 2# )
582 | glaExtsEnabled exts &&
583 (let c = (lookAhead# buf 1# )
584 in eqChar# c 'e'# || eqChar# c 't'# || eqChar# c 'd'# || eqChar# c 'p'#) &&
585 ((lookAhead# buf 2#) `eqChar#` '|'#) ->
586 let quote 'e'# = ITopenExpQuote
587 quote 'p'# = ITopenPatQuote
588 quote 'd'# = ITopenDecQuote
589 quote 't'# = ITopenTypQuote
590 in cont (quote (lookAhead# buf 1#)) (addToCurrentPos buf 3# )
592 cont ITobrack (incCurrentPos buf)
594 ']'# -> cont ITcbrack (incCurrentPos buf)
595 ','# -> cont ITcomma (incCurrentPos buf)
596 ';'# -> cont ITsemi (incCurrentPos buf)
597 '}'# -> \ s@PState{context = ctx} ->
599 (_:ctx') -> cont ITccurly (incCurrentPos buf) s{context=ctx'}
600 _ -> lexError "too many '}'s" buf s
601 '|'# -> case lookAhead# buf 1# of
602 '}'# | glaExtsEnabled exts -> cont ITccurlybar
603 (addToCurrentPos buf 2#)
604 -- MetaHaskell extension
605 ']'# | glaExtsEnabled exts -> cont ITcloseQuote (addToCurrentPos buf 2#)
606 -- arrow notation extension
607 ')'# | arrowsEnabled exts -> cont ITcparenbar
608 (addToCurrentPos buf 2#)
609 other -> lex_sym cont exts (incCurrentPos buf)
610 ':'# -> case lookAhead# buf 1# of
611 ']'# | parrEnabled exts -> cont ITcpabrack
612 (addToCurrentPos buf 2#)
613 _ -> lex_sym cont exts (incCurrentPos buf)
616 '#'# -> case lookAhead# buf 1# of
617 ')'# | glaExtsEnabled exts
618 -> cont ITcubxparen (addToCurrentPos buf 2#)
619 '-'# -> case lookAhead# buf 2# of
620 '}'# -> cont ITclose_prag (addToCurrentPos buf 3#)
621 _ -> lex_sym cont exts (incCurrentPos buf)
622 _ -> lex_sym cont exts (incCurrentPos buf)
624 '`'# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '`'#
625 -> lex_cstring cont (addToCurrentPos buf 2#)
627 -> cont ITbackquote (incCurrentPos buf)
629 '{'# -> -- for Emacs: -}
630 case lookAhead# buf 1# of
631 '|'# | glaExtsEnabled exts
632 -> cont ITocurlybar (addToCurrentPos buf 2#)
633 '-'# -> case lookAhead# buf 2# of
634 '#'# -> lex_prag cont (addToCurrentPos buf 3#)
635 _ -> cont ITocurly (incCurrentPos buf)
636 _ -> (layoutOff `thenP_` cont ITocurly) (incCurrentPos buf)
641 -- strings/characters -------------------------------------------------
642 '\"'#{-"-} -> lex_string cont exts [] (incCurrentPos buf)
643 '\''# -> lex_char (char_end cont) exts (incCurrentPos buf)
645 -- Hexadecimal and octal constants
646 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
647 -> readNum (after_lexnum cont exts) buf' is_hexdigit 16 hex
648 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
649 -> readNum (after_lexnum cont exts) buf' is_octdigit 8 oct_or_dec
650 where ch = lookAhead# buf 1#
651 ch2 = lookAhead# buf 2#
652 buf' = addToCurrentPos buf 2#
655 if bufferExhausted (stepOn buf) then
658 trace "lexIface: misplaced NUL?" $
659 cont (ITunknown "\NUL") (stepOn buf)
661 '?'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- ?x implicit parameter
662 specialPrefixId ITdupipvarid cont exts (incCurrentPos buf)
663 '%'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->
664 specialPrefixId ITsplitipvarid cont exts (incCurrentPos buf)
666 ---------------- MetaHaskell Extensions for quotation escape
667 '$'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- $x variable escape
668 specialPrefixId ITidEscape cont exts (addToCurrentPos buf 1#)
669 '$'# | glaExtsEnabled exts && -- $( f x ) expression escape
670 ((lookAhead# buf 1#) `eqChar#` '('#) -> cont ITparenEscape (addToCurrentPos buf 2#)
672 c | is_digit c -> lex_num cont exts 0 buf
673 | is_symbol c -> lex_sym cont exts buf
674 | is_upper c -> lex_con cont exts buf
675 | is_lower c -> lex_id cont exts buf
676 | otherwise -> lexError "illegal character" buf
678 -- Int# is unlifted, and therefore faster than Bool for flags.
684 -------------------------------------------------------------------------------
688 = case expandWhile# is_space buf of { buf1 ->
689 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
690 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
691 case lookupUFM pragmaKeywordsFM lexeme of
692 Just kw -> cont kw (mergeLexemes buf buf2)
693 Nothing -> panic "lex_prag"
696 -------------------------------------------------------------------------------
699 lex_string cont exts s buf
700 = case currentChar# buf of
702 let buf' = incCurrentPos buf
703 in case currentChar# buf' of
704 '#'# | glaExtsEnabled exts ->
706 then lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
707 else let s' = mkFastStringNarrow (map chr (reverse s)) in
708 -- always a narrow string/byte array
709 cont (ITprimstring s') (incCurrentPos buf')
711 _other -> let s' = mkFastString (map chr (reverse s))
712 in cont (ITstring s') buf'
714 -- ignore \& in a string, deal with string gaps
715 '\\'# | next_ch `eqChar#` '&'#
716 -> lex_string cont exts s buf'
718 -> lex_stringgap cont exts s (incCurrentPos buf)
720 where next_ch = lookAhead# buf 1#
721 buf' = addToCurrentPos buf 2#
723 _ -> lex_char (lex_next_string cont s) exts buf
725 lex_stringgap cont exts s buf
726 = let buf' = incCurrentPos buf in
727 case currentChar# buf of
728 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont exts s buf'
729 st{loc = incSrcLine loc}
730 '\\'# -> lex_string cont exts s buf'
731 c | is_space c -> lex_stringgap cont exts s buf'
732 other -> charError buf'
734 lex_next_string cont s exts c buf = lex_string cont exts (c:s) buf
736 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
737 lex_char cont exts buf
738 = case currentChar# buf of
739 '\\'# -> lex_escape (cont exts) (incCurrentPos buf)
740 c | is_any c -> cont exts (I# (ord# c)) (incCurrentPos buf)
741 other -> charError buf
743 char_end cont exts c buf
744 = case currentChar# buf of
745 '\''# -> let buf' = incCurrentPos buf in
746 case currentChar# buf' of
747 '#'# | glaExtsEnabled exts
748 -> cont (ITprimchar c) (incCurrentPos buf')
749 _ -> cont (ITchar c) buf'
753 = let buf' = incCurrentPos buf in
754 case currentChar# buf of
755 'a'# -> cont (ord '\a') buf'
756 'b'# -> cont (ord '\b') buf'
757 'f'# -> cont (ord '\f') buf'
758 'n'# -> cont (ord '\n') buf'
759 'r'# -> cont (ord '\r') buf'
760 't'# -> cont (ord '\t') buf'
761 'v'# -> cont (ord '\v') buf'
762 '\\'# -> cont (ord '\\') buf'
763 '"'# -> cont (ord '\"') buf'
764 '\''# -> cont (ord '\'') buf'
765 '^'# -> let c = currentChar# buf' in
766 if c `geChar#` '@'# && c `leChar#` '_'#
767 then cont (I# (ord# c -# ord# '@'#)) (incCurrentPos buf')
770 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
771 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
773 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
775 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
776 Just buf2 <- [prefixMatch buf p] ] of
777 (c,buf2):_ -> cont (ord c) buf2
780 after_charnum cont i buf
781 = if i >= 0 && i <= 0x10FFFF
782 then cont (fromInteger i) buf
785 readNum cont buf is_digit base conv = read buf 0
787 = case currentChar# buf of { c ->
789 then read (incCurrentPos buf) (i*base + (toInteger (I# (conv c))))
795 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
796 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
798 hex c | is_digit c = ord# c -# ord# '0'#
799 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
800 oct_or_dec c = ord# c -# ord# '0'#
802 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
805 | c `geChar#` 'A'# && c `leChar#` 'Z'#
806 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
809 charError buf = lexError "error in character literal" buf
811 silly_escape_chars = [
848 -----------------------------------------------------------------------------
851 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
852 lex_num cont exts acc buf =
853 case scanNumLit acc buf of
855 case currentChar# buf' of
856 '.'# | is_digit (lookAhead# buf' 1#) ->
857 -- this case is not optimised at all, as the
858 -- presence of floating point numbers in interface
859 -- files is not that common. (ToDo)
860 case expandWhile# is_digit (incCurrentPos buf') of
861 buf2 -> -- points to first non digit char
862 case currentChar# buf2 of
863 'E'# -> float_exponent cont exts buf2
864 'e'# -> float_exponent cont exts buf2
865 _ -> float_done cont exts buf2
867 -- numbers like '9e4' are floats
868 'E'# -> float_exponent cont exts buf'
869 'e'# -> float_exponent cont exts buf'
870 _ -> after_lexnum cont exts acc' buf' -- it's an integer
872 float_exponent cont exts buf2 =
873 let buf3 = incCurrentPos buf2
874 buf4 = case currentChar# buf3 of
875 '-'# | is_digit (lookAhead# buf3 1#)
876 -> expandWhile# is_digit (incCurrentPos buf3)
877 '+'# | is_digit (lookAhead# buf3 1#)
878 -> expandWhile# is_digit (incCurrentPos buf3)
879 x | is_digit x -> expandWhile# is_digit buf3
882 float_done cont exts buf4
884 float_done cont exts buf =
885 case currentChar# buf of -- glasgow exts only
886 '#'# | glaExtsEnabled exts ->
887 let buf' = incCurrentPos buf in
888 case currentChar# buf' of
889 '#'# -> cont (ITprimdouble v) (incCurrentPos buf')
890 _ -> cont (ITprimfloat v) buf'
891 _ -> cont (ITrational v) buf
893 v = readRational__ (lexemeToString buf)
895 after_lexnum cont exts i buf
896 = case currentChar# buf of
897 '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
898 _ -> cont (ITinteger i) buf
900 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
904 return ((n%1)*10^^(k-d), t)
907 (ds,s) <- lexDecDigits r
908 (ds',t) <- lexDotDigits s
909 return (read (ds++ds'), length ds', t)
911 readExp (e:s) | e `elem` "eE" = readExp' s
912 readExp s = return (0,s)
914 readExp' ('+':s) = readDec s
915 readExp' ('-':s) = do
918 readExp' s = readDec s
921 (ds,r) <- nonnull isDigit s
922 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
925 lexDecDigits = nonnull isDigit
927 lexDotDigits ('.':s) = return (span isDigit s)
928 lexDotDigits s = return ("",s)
930 nonnull p s = do (cs@(_:_),t) <- return (span p s)
933 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
936 '-' : xs -> - (read_me xs)
940 = case (do { (x,"") <- readRational s ; return x }) of
942 [] -> error ("readRational__: no parse:" ++ top_s)
943 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
945 -----------------------------------------------------------------------------
946 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
948 -- we lexemeToFastString on the bit between the ``''s, but include the
949 -- quotes in the full lexeme.
951 lex_cstring cont buf =
952 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
953 Just buf' -> cont (ITlitlit (lexemeToFastString
954 (addToCurrentPos buf' (negateInt# 2#))))
955 (mergeLexemes buf buf')
956 Nothing -> lexError "unterminated ``" buf
958 -----------------------------------------------------------------------------
959 -- identifiers, symbols etc.
961 -- used for identifiers with special prefixes like
962 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
963 -- we've already seen the prefix char, so look for an id, and wrap
964 -- the new "ip_constr" around the lexeme returned
966 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
967 where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
968 newcont token buf2 = cont token buf2
970 case expandWhile# is_ident buf of
971 buf' -> cont (ip_constr (tailFS lexeme)) buf'
972 where lexeme = lexemeToFastString buf'
975 lex_id cont exts buf =
976 let buf1 = expandWhile# is_ident buf in
979 case (if glaExtsEnabled exts
980 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
981 else buf1) of { buf' ->
984 let lexeme = lexemeToFastString buf' in
986 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
987 Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
991 let var_token = cont (ITvarid lexeme) buf' in
993 case lookupUFM ghcExtensionKeywordsFM lexeme of {
994 Just (kwd_token, validExts)
995 | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
1000 lex_sym cont exts buf =
1001 -- trace "lex_sym" $
1002 case expandWhile# is_symbol buf of
1003 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
1004 Just (kwd_token, Nothing)
1005 -> cont kwd_token buf' ;
1006 Just (kwd_token, Just validExts)
1007 | validExts .&. toInt32 exts /= 0
1008 -> cont kwd_token buf' ;
1009 other -> cont (mk_var_token lexeme) buf'
1011 where lexeme = lexemeToFastString buf'
1014 -- lex_con recursively collects components of a qualified identifer.
1015 -- The argument buf is the StringBuffer representing the lexeme
1016 -- identified so far, where the next character is upper-case.
1018 lex_con cont exts buf =
1019 -- trace ("con: "{-++unpackFS lexeme-}) $
1020 let empty_buf = stepOverLexeme buf in
1021 case expandWhile# is_ident empty_buf of { buf1 ->
1022 case slurp_trailing_hashes buf1 exts of { con_buf ->
1024 let all_buf = mergeLexemes buf con_buf
1026 con_lexeme = lexemeToFastString con_buf
1027 mod_lexeme = lexemeToFastString (decCurrentPos buf)
1028 all_lexeme = lexemeToFastString all_buf
1031 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
1032 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
1035 case currentChar# all_buf of
1036 '.'# -> maybe_qualified cont exts all_lexeme
1037 (incCurrentPos all_buf) just_a_conid
1042 maybe_qualified cont exts mod buf just_a_conid =
1043 -- trace ("qid: "{-++unpackFS lexeme-}) $
1044 case currentChar# buf of
1045 '['# -> -- Special case for []
1046 case lookAhead# buf 1# of
1047 ']'# -> cont (ITqconid (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
1050 '('# -> -- Special case for (,,,)
1051 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1052 case lookAhead# buf 1# of
1053 '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
1054 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#)
1057 ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1058 ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1061 '-'# -> case lookAhead# buf 1# of
1062 '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1063 _ -> lex_id3 cont exts mod buf just_a_conid
1065 _ -> lex_id3 cont exts mod buf just_a_conid
1068 lex_id3 cont exts mod buf just_a_conid
1069 | is_upper (currentChar# buf) =
1070 lex_con cont exts buf
1072 | is_symbol (currentChar# buf) =
1074 start_new_lexeme = stepOverLexeme buf
1076 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1077 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1079 lexeme = lexemeToFastString buf'
1080 -- real lexeme is M.<sym>
1081 new_buf = mergeLexemes buf buf'
1083 cont (mk_qvar_token mod lexeme) new_buf
1084 -- wrong, but arguably morally right: M... is now a qvarsym
1089 start_new_lexeme = stepOverLexeme buf
1091 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1092 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1097 case slurp_trailing_hashes buf1 exts of { buf' ->
1100 lexeme = lexemeToFastString buf'
1101 new_buf = mergeLexemes buf buf'
1102 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1104 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1105 Nothing -> is_a_qvarid ;
1107 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1108 -> is_a_qvarid -- recognised as keywords here.
1110 -> just_a_conid -- avoid M.where etc.
1113 slurp_trailing_hashes buf exts
1114 | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1119 | is_upper f = ITconid pk_str
1120 | is_ident f = ITvarid pk_str
1121 | f `eqChar#` ':'# = ITconsym pk_str
1122 | otherwise = ITvarsym pk_str
1124 (C# f) = headFS pk_str
1125 -- tl = _TAIL_ pk_str
1127 mk_qvar_token m token =
1128 -- trace ("mk_qvar ") $
1129 case mk_var_token token of
1130 ITconid n -> ITqconid (m,n)
1131 ITvarid n -> ITqvarid (m,n)
1132 ITconsym n -> ITqconsym (m,n)
1133 ITvarsym n -> ITqvarsym (m,n)
1134 _ -> ITunknown (show token)
1137 ----------------------------------------------------------------------------
1138 Horrible stuff for dealing with M.(,,,)
1141 lex_tuple cont mod buf back_off =
1145 case currentChar# buf of
1146 ','# -> go (n+1) (stepOn buf)
1147 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1150 lex_ubx_tuple cont mod buf back_off =
1154 case currentChar# buf of
1155 ','# -> go (n+1) (stepOn buf)
1156 '#'# -> case lookAhead# buf 1# of
1157 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1163 -----------------------------------------------------------------------------
1174 data PState = PState {
1176 extsBitmap :: Int#, -- bitmap that determines permitted extensions
1179 context :: [LayoutContext]
1182 type P a = StringBuffer -- Input string
1187 returnP a buf s = POk s a
1189 thenP :: P a -> (a -> P b) -> P b
1190 m `thenP` k = \ buf s ->
1192 POk s1 a -> k a buf s1
1193 PFailed err -> PFailed err
1195 thenP_ :: P a -> P b -> P b
1196 m `thenP_` k = m `thenP` \_ -> k
1198 mapP :: (a -> P b) -> [a] -> P [b]
1199 mapP f [] = returnP []
1202 mapP f as `thenP` \bs ->
1205 failP :: String -> P a
1206 failP msg buf s = PFailed (text msg)
1208 failMsgP :: Message -> P a
1209 failMsgP msg buf s = PFailed msg
1211 lexError :: String -> P a
1212 lexError str buf s@PState{ loc = loc }
1213 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1215 getSrcLocP :: P SrcLoc
1216 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1218 -- use a temporary SrcLoc for the duration of the argument
1219 setSrcLocP :: SrcLoc -> P a -> P a
1220 setSrcLocP new_loc p buf s =
1221 case p buf s{ loc=new_loc } of
1223 PFailed e -> PFailed e
1225 getSrcFile :: P FastString
1226 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1228 pushContext :: LayoutContext -> P ()
1229 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1233 This special case in layoutOn is to handle layout contexts with are
1234 indented the same or less than the current context. This is illegal
1235 according to the Haskell spec, so we have to arrange to close the
1236 current context. eg.
1241 after the first 'where', the sequence of events is:
1243 - layout system inserts a ';' (column 0)
1244 - parser begins a new context at column 0
1245 - parser shifts ';' (legal empty declaration)
1246 - parser sees 'class': parse error (we're still in the inner context)
1248 trouble is, by the time we know we need a new context, the lexer has
1249 already generated the ';'. Hacky solution is as follows: since we
1250 know the column of the next token (it's the column number of the new
1251 context), we set the ACTUAL column number of the new context to this
1252 numer plus one. Hence the next time the lexer is called, a '}' will
1253 be generated to close the new context straight away. Furthermore, we
1254 have to set the atbol flag so that the ';' that the parser shifted as
1255 part of the new context is re-generated.
1257 when the new context is *less* indented than the current one:
1259 f = f where g = g where
1262 - current context: column 12.
1263 - on seeing 'h' (column 0), the layout system inserts '}'
1264 - parser starts a new context, column 0
1265 - parser sees '}', uses it to close new context
1266 - we still need to insert another '}' followed by a ';',
1267 hence the atbol trick.
1269 There's also a special hack in here to deal with
1276 i.e. the inner context is at the same indentation level as the outer
1277 context. This is strictly illegal according to Haskell 98, but
1278 there's a lot of existing code using this style and it doesn't make
1279 any sense to disallow it, since empty 'do' lists don't make sense.
1282 layoutOn :: Bool -> P ()
1283 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1284 let offset = lexemeIndex buf -# bol in
1287 | if strict then prev_off >=# offset else prev_off ># offset ->
1288 --trace ("layout on, column: " ++ show (I# offset)) $
1289 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1291 --trace ("layout on, column: " ++ show (I# offset)) $
1292 POk s{ context = Layout offset : ctx } ()
1295 layoutOff buf s@(PState{ context = ctx }) =
1296 POk s{ context = NoLayout:ctx } ()
1299 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1301 (_:tl) -> POk s{ context = tl } ()
1302 [] -> PFailed (srcParseErr buf loc)
1304 -- for reasons of efficiency, flags indicating language extensions (eg,
1305 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1308 glaExtsBit, ffiBit, parrBit :: Int
1315 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1316 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1317 ffiEnabled flags = testBit (toInt32 flags) ffiBit
1318 withEnabled flags = testBit (toInt32 flags) withBit
1319 parrEnabled flags = testBit (toInt32 flags) parrBit
1320 arrowsEnabled flags = testBit (toInt32 flags) arrowsBit
1322 toInt32 :: Int# -> Int32
1323 toInt32 x# = fromIntegral (I# x#)
1325 -- convenient record-based bitmap for the interface to the rest of the world
1327 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1329 data ExtFlags = ExtFlags {
1330 glasgowExtsEF :: Bool,
1337 -- create a parse state
1339 mkPState :: SrcLoc -> ExtFlags -> PState
1343 extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1349 bitmap = glaExtsBit `setBitIf` glasgowExtsEF exts
1350 .|. ffiBit `setBitIf` (ffiEF exts
1351 || glasgowExtsEF exts)
1352 .|. withBit `setBitIf` withEF exts
1353 .|. parrBit `setBitIf` parrEF exts
1354 .|. arrowsBit `setBitIf` arrowsEF exts
1356 setBitIf :: Int -> Bool -> Int32
1357 b `setBitIf` cond | cond = bit b
1360 -----------------------------------------------------------------------------
1362 srcParseErr :: StringBuffer -> SrcLoc -> Message
1366 then ptext SLIT(": parse error (possibly incorrect indentation)")
1367 else hcat [ptext SLIT(": parse error on input "),
1368 char '`', text token, char '\'']
1371 token = lexemeToString s