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
138 | ITdotdot -- reserved symbols
154 | ITbiglam -- GHC-extension symbols
156 | ITocurly -- special symbols
158 | ITocurlybar -- {|, for type applications
159 | ITccurlybar -- |}, for type applications
162 | ITopabrack -- [:, for parallel arrays with -fparr
163 | ITcpabrack -- :], for parallel arrays with -fparr
174 | ITvarid FastString -- identifiers
176 | ITvarsym FastString
177 | ITconsym FastString
178 | ITqvarid (FastString,FastString)
179 | ITqconid (FastString,FastString)
180 | ITqvarsym (FastString,FastString)
181 | ITqconsym (FastString,FastString)
183 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
184 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
186 | ITpragma StringBuffer
189 | ITstring FastString
191 | ITrational Rational
194 | ITprimstring FastString
196 | ITprimfloat Rational
197 | ITprimdouble Rational
198 | ITlitlit FastString
200 -- MetaHaskell extension tokens
201 | ITopenExpQuote -- [| or [e|
202 | ITopenPatQuote -- [p|
203 | ITopenDecQuote -- [d|
204 | ITopenTypQuote -- [t|
206 | ITidEscape FastString -- $x
207 | ITparenEscape -- $(
212 | ITunknown String -- Used when the lexer can't make sense of it
213 | ITeof -- end of file token
214 deriving Show -- debugging
217 -----------------------------------------------------------------------------
221 pragmaKeywordsFM = listToUFM $
222 map (\ (x,y) -> (mkFastString x,y))
223 [( "SPECIALISE", ITspecialise_prag ),
224 ( "SPECIALIZE", ITspecialise_prag ),
225 ( "SOURCE", ITsource_prag ),
226 ( "INLINE", ITinline_prag ),
227 ( "NOINLINE", ITnoinline_prag ),
228 ( "NOTINLINE", ITnoinline_prag ),
229 ( "LINE", ITline_prag ),
230 ( "RULES", ITrules_prag ),
231 ( "RULEZ", ITrules_prag ), -- american spelling :-)
232 ( "SCC", ITscc_prag ),
233 ( "DEPRECATED", ITdeprecated_prag )
236 haskellKeywordsFM = listToUFM $
237 map (\ (x,y) -> (mkFastString x,y))
238 [( "_", ITunderscore ),
241 ( "class", ITclass ),
243 ( "default", ITdefault ),
244 ( "deriving", ITderiving ),
247 ( "hiding", IThiding ),
249 ( "import", ITimport ),
251 ( "infix", ITinfix ),
252 ( "infixl", ITinfixl ),
253 ( "infixr", ITinfixr ),
254 ( "instance", ITinstance ),
256 ( "module", ITmodule ),
257 ( "newtype", ITnewtype ),
259 ( "qualified", ITqualified ),
262 ( "where", ITwhere ),
263 ( "_scc_", ITscc ) -- ToDo: remove
266 isSpecial :: Token -> Bool
267 -- If we see M.x, where x is a keyword, but
268 -- is special, we treat is as just plain M.x,
270 isSpecial ITas = True
271 isSpecial IThiding = True
272 isSpecial ITqualified = True
273 isSpecial ITforall = True
274 isSpecial ITexport = True
275 isSpecial ITlabel = True
276 isSpecial ITdynamic = True
277 isSpecial ITsafe = True
278 isSpecial ITthreadsafe = True
279 isSpecial ITunsafe = True
280 isSpecial ITwith = True
281 isSpecial ITccallconv = True
282 isSpecial ITstdcallconv = True
283 isSpecial ITmdo = True
286 -- the bitmap provided as the third component indicates whether the
287 -- corresponding extension keyword is valid under the extension options
288 -- provided to the compiler; if the extension corresponding to *any* of the
289 -- bits set in the bitmap is enabled, the keyword is valid (this setup
290 -- facilitates using a keyword in two different extensions that can be
291 -- activated independently)
293 ghcExtensionKeywordsFM = listToUFM $
294 map (\(x, y, z) -> (mkFastString x, (y, z)))
295 [ ( "forall", ITforall, bit glaExtsBit),
296 ( "foreign", ITforeign, bit ffiBit),
297 ( "export", ITexport, bit ffiBit),
298 ( "label", ITlabel, bit ffiBit),
299 ( "dynamic", ITdynamic, bit ffiBit),
300 ( "safe", ITsafe, bit ffiBit),
301 ( "threadsafe", ITthreadsafe, bit ffiBit),
302 ( "unsafe", ITunsafe, bit ffiBit),
303 ( "with", ITwith, bit withBit),
304 ( "mdo", ITmdo, bit glaExtsBit),
305 ( "stdcall", ITstdcallconv, bit ffiBit),
306 ( "ccall", ITccallconv, bit ffiBit),
307 ( "dotnet", ITdotnet, bit ffiBit),
308 ( "reifyDecl", ITreifyDecl, bit glaExtsBit),
309 ( "reifyType", ITreifyType, bit glaExtsBit),
310 ( "reifyFixity",ITreifyFixity, bit glaExtsBit),
311 ("_ccall_", ITccall (False, False, PlayRisky),
313 ("_ccall_GC_", ITccall (False, False, PlaySafe False),
315 ("_casm_", ITccall (False, True, PlayRisky),
317 ("_casm_GC_", ITccall (False, True, PlaySafe False),
321 haskellKeySymsFM = listToUFM $
322 map (\ (x,y) -> (mkFastString x,y))
324 ,(":", ITcolon) -- (:) is a reserved op,
325 -- meaning only list cons
338 ,(".", ITdot) -- sadly, for 'forall a . t'
343 -----------------------------------------------------------------------------
348 - (exts) lexing a source with extensions, eg, an interface file or
350 - (bol) pointer to beginning of line (for column calculations)
351 - (buf) pointer to beginning of token
352 - (buf) pointer to current char
353 - (atbol) flag indicating whether we're at the beginning of a line
356 lexer :: (Token -> P a) -> P a
357 lexer cont buf s@(PState{
365 -- first, start a new lexeme and lose all the whitespace
367 tab line bol atbol (stepOverLexeme buf)
369 line = srcLocLine loc
371 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
372 case currentChar# buf of
375 if bufferExhausted (stepOn buf)
376 then cont ITeof buf s'
377 else trace "lexer: misplaced NUL?" $
378 tab y bol atbol (stepOn buf)
380 '\n'# -> let buf' = stepOn buf
381 in tab (y +# 1#) (currentIndex# buf') 1# buf'
383 -- find comments. This got harder in Haskell 98.
384 '-'# -> let trundle n =
385 let next = lookAhead# buf n in
386 if next `eqChar#` '-'# then trundle (n +# 1#)
387 else if is_symbol next || n <# 2#
390 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
393 -- comments and pragmas. We deal with LINE pragmas here,
394 -- and throw out any unrecognised pragmas as comments. Any
395 -- pragmas we know about are dealt with later (after any layout
396 -- processing if necessary).
397 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
398 if lookAhead# buf 2# `eqChar#` '#'# then
399 case expandWhile# is_space (addToCurrentPos buf 3#) of { buf1->
400 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
401 let lexeme = mkFastString -- ToDo: too slow
402 (map toUpper (lexemeToString buf2)) in
403 case lookupUFM pragmaKeywordsFM lexeme of
404 -- ignore RULES pragmas when -fglasgow-exts is off
405 Just ITrules_prag | not (glaExtsEnabled exts) ->
406 skip_to_end (stepOnBy# buf 2#) s'
408 line_prag skip_to_end buf2 s'
409 Just other -> is_a_token
410 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
413 else skip_to_end (stepOnBy# buf 2#) s'
415 skip_to_end = skipNestedComment (lexer cont)
417 -- special GHC extension: we grok cpp-style #line pragmas
418 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
419 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
420 lookAhead# buf 2# `eqChar#` 'i'# &&
421 lookAhead# buf 3# `eqChar#` 'n'# &&
422 lookAhead# buf 4# `eqChar#` 'e'# = stepOnBy# buf 5#
423 | otherwise = stepOn buf
425 case expandWhile# is_space buf1 of { buf2 ->
426 if is_digit (currentChar# buf2)
427 then line_prag next_line buf2 s'
431 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
433 -- tabs have been expanded beforehand
434 c | is_space c -> tab y bol atbol (stepOn buf)
435 | otherwise -> is_a_token
437 where s' = s{loc = replaceSrcLine loc y,
441 is_a_token | atbol /=# 0# = lexBOL cont buf s'
442 | otherwise = lexToken cont exts buf s'
444 -- {-# LINE .. #-} pragmas. yeuch.
445 line_prag cont buf s@PState{loc=loc} =
446 case expandWhile# is_space buf of { buf1 ->
447 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
448 -- subtract one: the line number refers to the *following* line.
449 let real_line = line - 1 in
450 case fromInteger real_line of { i@(I# l) ->
451 -- ToDo, if no filename then we skip the newline.... d'oh
452 case expandWhile# is_space buf2 of { buf3 ->
453 case currentChar# buf3 of
455 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
457 file = lexemeToFastString buf4
458 new_buf = stepOn (stepOverLexeme buf4)
460 if nullFastString file
461 then cont new_buf s{loc = replaceSrcLine loc l}
462 else cont new_buf s{loc = mkSrcLoc file i}
464 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
467 skipNestedComment :: P a -> P a
468 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
470 skipNestedComment' :: SrcLoc -> P a -> P a
471 skipNestedComment' orig_loc cont buf = loop buf
474 case currentChar# buf of
475 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
477 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
479 (skipNestedComment' orig_loc cont)
482 '\n'# -> \ s@PState{loc=loc} ->
483 let buf' = stepOn buf in
484 loop buf' s{loc = incSrcLine loc,
485 bol = currentIndex# buf',
488 -- pass the original SrcLoc to lexError so that the error is
489 -- reported at the line it was originally on, not the line at
490 -- the end of the file.
491 '\NUL'# | bufferExhausted (stepOn buf) ->
492 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
494 _ -> loop (stepOn buf)
496 -- When we are lexing the first token of a line, check whether we need to
497 -- insert virtual semicolons or close braces due to layout.
499 lexBOL :: (Token -> P a) -> P a
500 lexBOL cont buf s@(PState{
507 if need_close_curly then
508 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
509 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
510 else if need_semi_colon then
511 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
512 cont ITsemi buf s{atbol = 0#}
514 lexToken cont exts buf s{atbol = 0#}
516 col = currentIndex# buf -# bol
529 Layout n -> col ==# n
532 lexToken :: (Token -> P a) -> Int# -> P a
533 lexToken cont exts buf =
534 -- trace "lexToken" $
535 case currentChar# buf of
537 -- special symbols ----------------------------------------------------
538 '('# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '#'#
539 -> cont IToubxparen (addToCurrentPos buf 2#)
541 -> cont IToparen (incCurrentPos buf)
543 ')'# -> cont ITcparen (incCurrentPos buf)
544 '['# | parrEnabled exts && lookAhead# buf 1# `eqChar#` ':'# ->
545 cont ITopabrack (addToCurrentPos buf 2#)
546 ------- MetaHaskell Extensions, looking for [| [e| [t| [p| and [d|
547 | glaExtsEnabled exts &&
548 ((lookAhead# buf 1# ) `eqChar#` '|'# ) ->
549 cont ITopenExpQuote (addToCurrentPos buf 2# )
550 | glaExtsEnabled exts &&
551 (let c = (lookAhead# buf 1# )
552 in eqChar# c 'e'# || eqChar# c 't'# || eqChar# c 'd'# || eqChar# c 'p'#) &&
553 ((lookAhead# buf 2#) `eqChar#` '|'#) ->
554 let quote 'e'# = ITopenExpQuote
555 quote 'p'# = ITopenPatQuote
556 quote 'd'# = ITopenDecQuote
557 quote 't'# = ITopenTypQuote
558 in cont (quote (lookAhead# buf 1#)) (addToCurrentPos buf 3# )
560 cont ITobrack (incCurrentPos buf)
562 ']'# -> cont ITcbrack (incCurrentPos buf)
563 ','# -> cont ITcomma (incCurrentPos buf)
564 ';'# -> cont ITsemi (incCurrentPos buf)
565 '}'# -> \ s@PState{context = ctx} ->
567 (_:ctx') -> cont ITccurly (incCurrentPos buf) s{context=ctx'}
568 _ -> lexError "too many '}'s" buf s
569 '|'# -> case lookAhead# buf 1# of
570 '}'# | glaExtsEnabled exts -> cont ITccurlybar
571 (addToCurrentPos buf 2#)
572 -- MetaHaskell extension
573 ']'# | glaExtsEnabled exts -> cont ITcloseQuote (addToCurrentPos buf 2#)
574 other -> lex_sym cont (incCurrentPos buf)
575 ':'# -> case lookAhead# buf 1# of
576 ']'# | parrEnabled exts -> cont ITcpabrack
577 (addToCurrentPos buf 2#)
578 _ -> lex_sym cont (incCurrentPos buf)
581 '#'# -> case lookAhead# buf 1# of
582 ')'# | glaExtsEnabled exts
583 -> cont ITcubxparen (addToCurrentPos buf 2#)
584 '-'# -> case lookAhead# buf 2# of
585 '}'# -> cont ITclose_prag (addToCurrentPos buf 3#)
586 _ -> lex_sym cont (incCurrentPos buf)
587 _ -> lex_sym cont (incCurrentPos buf)
589 '`'# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '`'#
590 -> lex_cstring cont (addToCurrentPos buf 2#)
592 -> cont ITbackquote (incCurrentPos buf)
594 '{'# -> -- for Emacs: -}
595 case lookAhead# buf 1# of
596 '|'# | glaExtsEnabled exts
597 -> cont ITocurlybar (addToCurrentPos buf 2#)
598 '-'# -> case lookAhead# buf 2# of
599 '#'# -> lex_prag cont (addToCurrentPos buf 3#)
600 _ -> cont ITocurly (incCurrentPos buf)
601 _ -> (layoutOff `thenP_` cont ITocurly) (incCurrentPos buf)
606 -- strings/characters -------------------------------------------------
607 '\"'#{-"-} -> lex_string cont exts [] (incCurrentPos buf)
608 '\''# -> lex_char (char_end cont) exts (incCurrentPos buf)
610 -- Hexadecimal and octal constants
611 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
612 -> readNum (after_lexnum cont exts) buf' is_hexdigit 16 hex
613 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
614 -> readNum (after_lexnum cont exts) buf' is_octdigit 8 oct_or_dec
615 where ch = lookAhead# buf 1#
616 ch2 = lookAhead# buf 2#
617 buf' = addToCurrentPos buf 2#
620 if bufferExhausted (stepOn buf) then
623 trace "lexIface: misplaced NUL?" $
624 cont (ITunknown "\NUL") (stepOn buf)
626 '?'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- ?x implicit parameter
627 specialPrefixId ITdupipvarid cont exts (incCurrentPos buf)
628 '%'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->
629 specialPrefixId ITsplitipvarid cont exts (incCurrentPos buf)
631 ---------------- MetaHaskell Extensions for quotation escape
632 '$'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- $x variable escape
633 specialPrefixId ITidEscape cont exts (addToCurrentPos buf 1#)
634 '$'# | glaExtsEnabled exts && -- $( f x ) expression escape
635 ((lookAhead# buf 1#) `eqChar#` '('#) -> cont ITparenEscape (addToCurrentPos buf 2#)
637 c | is_digit c -> lex_num cont exts 0 buf
638 | is_symbol c -> lex_sym cont buf
639 | is_upper c -> lex_con cont exts buf
640 | is_lower c -> lex_id cont exts buf
641 | otherwise -> lexError "illegal character" buf
643 -- Int# is unlifted, and therefore faster than Bool for flags.
649 -------------------------------------------------------------------------------
653 = case expandWhile# is_space buf of { buf1 ->
654 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
655 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
656 case lookupUFM pragmaKeywordsFM lexeme of
657 Just kw -> cont kw (mergeLexemes buf buf2)
658 Nothing -> panic "lex_prag"
661 -------------------------------------------------------------------------------
664 lex_string cont exts s buf
665 = case currentChar# buf of
667 let buf' = incCurrentPos buf
668 s' = mkFastString (map chr (reverse s))
669 in case currentChar# buf' of
670 '#'# | glaExtsEnabled exts -> if all (<= 0xFF) s
671 then cont (ITprimstring s') (incCurrentPos buf')
672 else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
673 _ -> cont (ITstring s') buf'
675 -- ignore \& in a string, deal with string gaps
676 '\\'# | next_ch `eqChar#` '&'#
677 -> lex_string cont exts s buf'
679 -> lex_stringgap cont exts s (incCurrentPos buf)
681 where next_ch = lookAhead# buf 1#
682 buf' = addToCurrentPos buf 2#
684 _ -> lex_char (lex_next_string cont s) exts buf
686 lex_stringgap cont exts s buf
687 = let buf' = incCurrentPos buf in
688 case currentChar# buf of
689 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont exts s buf'
690 st{loc = incSrcLine loc}
691 '\\'# -> lex_string cont exts s buf'
692 c | is_space c -> lex_stringgap cont exts s buf'
693 other -> charError buf'
695 lex_next_string cont s exts c buf = lex_string cont exts (c:s) buf
697 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
698 lex_char cont exts buf
699 = case currentChar# buf of
700 '\\'# -> lex_escape (cont exts) (incCurrentPos buf)
701 c | is_any c -> cont exts (I# (ord# c)) (incCurrentPos buf)
702 other -> charError buf
704 char_end cont exts c buf
705 = case currentChar# buf of
706 '\''# -> let buf' = incCurrentPos buf in
707 case currentChar# buf' of
708 '#'# | glaExtsEnabled exts
709 -> cont (ITprimchar c) (incCurrentPos buf')
710 _ -> cont (ITchar c) buf'
714 = let buf' = incCurrentPos buf in
715 case currentChar# buf of
716 'a'# -> cont (ord '\a') buf'
717 'b'# -> cont (ord '\b') buf'
718 'f'# -> cont (ord '\f') buf'
719 'n'# -> cont (ord '\n') buf'
720 'r'# -> cont (ord '\r') buf'
721 't'# -> cont (ord '\t') buf'
722 'v'# -> cont (ord '\v') buf'
723 '\\'# -> cont (ord '\\') buf'
724 '"'# -> cont (ord '\"') buf'
725 '\''# -> cont (ord '\'') buf'
726 '^'# -> let c = currentChar# buf' in
727 if c `geChar#` '@'# && c `leChar#` '_'#
728 then cont (I# (ord# c -# ord# '@'#)) (incCurrentPos buf')
731 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
732 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
734 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
736 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
737 Just buf2 <- [prefixMatch buf p] ] of
738 (c,buf2):_ -> cont (ord c) buf2
741 after_charnum cont i buf
742 = if i >= 0 && i <= 0x10FFFF
743 then cont (fromInteger i) buf
746 readNum cont buf is_digit base conv = read buf 0
748 = case currentChar# buf of { c ->
750 then read (incCurrentPos buf) (i*base + (toInteger (I# (conv c))))
756 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
757 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
759 hex c | is_digit c = ord# c -# ord# '0'#
760 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
761 oct_or_dec c = ord# c -# ord# '0'#
763 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
766 | c `geChar#` 'A'# && c `leChar#` 'Z'#
767 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
770 charError buf = lexError "error in character literal" buf
772 silly_escape_chars = [
809 -----------------------------------------------------------------------------
812 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
813 lex_num cont exts acc buf =
814 case scanNumLit acc buf of
816 case currentChar# buf' of
817 '.'# | is_digit (lookAhead# buf' 1#) ->
818 -- this case is not optimised at all, as the
819 -- presence of floating point numbers in interface
820 -- files is not that common. (ToDo)
821 case expandWhile# is_digit (incCurrentPos buf') of
822 buf2 -> -- points to first non digit char
824 let l = case currentChar# buf2 of
830 = let buf3 = incCurrentPos buf2 in
831 case currentChar# buf3 of
832 '-'# | is_digit (lookAhead# buf3 1#)
833 -> expandWhile# is_digit (incCurrentPos buf3)
834 '+'# | is_digit (lookAhead# buf3 1#)
835 -> expandWhile# is_digit (incCurrentPos buf3)
836 x | is_digit x -> expandWhile# is_digit buf3
839 v = readRational__ (lexemeToString l)
841 in case currentChar# l of -- glasgow exts only
842 '#'# | glaExtsEnabled exts -> let l' = incCurrentPos l in
843 case currentChar# l' of
844 '#'# -> cont (ITprimdouble v) (incCurrentPos l')
845 _ -> cont (ITprimfloat v) l'
846 _ -> cont (ITrational v) l
848 _ -> after_lexnum cont exts acc' buf'
850 after_lexnum cont exts i buf
851 = case currentChar# buf of
852 '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
853 _ -> cont (ITinteger i) buf
855 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
859 return ((n%1)*10^^(k-d), t)
862 (ds,s) <- lexDecDigits r
863 (ds',t) <- lexDotDigits s
864 return (read (ds++ds'), length ds', t)
866 readExp (e:s) | e `elem` "eE" = readExp' s
867 readExp s = return (0,s)
869 readExp' ('+':s) = readDec s
870 readExp' ('-':s) = do
873 readExp' s = readDec s
876 (ds,r) <- nonnull isDigit s
877 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
880 lexDecDigits = nonnull isDigit
882 lexDotDigits ('.':s) = return (span isDigit s)
883 lexDotDigits s = return ("",s)
885 nonnull p s = do (cs@(_:_),t) <- return (span p s)
888 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
891 '-' : xs -> - (read_me xs)
895 = case (do { (x,"") <- readRational s ; return x }) of
897 [] -> error ("readRational__: no parse:" ++ top_s)
898 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
900 -----------------------------------------------------------------------------
901 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
903 -- we lexemeToFastString on the bit between the ``''s, but include the
904 -- quotes in the full lexeme.
906 lex_cstring cont buf =
907 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
908 Just buf' -> cont (ITlitlit (lexemeToFastString
909 (addToCurrentPos buf' (negateInt# 2#))))
910 (mergeLexemes buf buf')
911 Nothing -> lexError "unterminated ``" buf
913 -----------------------------------------------------------------------------
914 -- identifiers, symbols etc.
916 -- used for identifiers with special prefixes like
917 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
918 -- we've already seen the prefix char, so look for an id, and wrap
919 -- the new "ip_constr" around the lexeme returned
921 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
922 where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
923 newcont token buf2 = cont token buf2
925 case expandWhile# is_ident buf of
926 buf' -> cont (ip_constr (tailFS lexeme)) buf'
927 where lexeme = lexemeToFastString buf'
930 lex_id cont exts buf =
931 let buf1 = expandWhile# is_ident buf in
934 case (if glaExtsEnabled exts
935 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
936 else buf1) of { buf' ->
939 let lexeme = lexemeToFastString buf' in
941 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
942 Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
946 let var_token = cont (ITvarid lexeme) buf' in
948 case lookupUFM ghcExtensionKeywordsFM lexeme of {
949 Just (kwd_token, validExts)
950 | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
957 case expandWhile# is_symbol buf of
958 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
959 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
960 cont kwd_token buf' ;
961 Nothing -> --trace ("sym: "++unpackFS lexeme) $
962 cont (mk_var_token lexeme) buf'
964 where lexeme = lexemeToFastString buf'
967 -- lex_con recursively collects components of a qualified identifer.
968 -- The argument buf is the StringBuffer representing the lexeme
969 -- identified so far, where the next character is upper-case.
971 lex_con cont exts buf =
972 -- trace ("con: "{-++unpackFS lexeme-}) $
973 let empty_buf = stepOverLexeme buf in
974 case expandWhile# is_ident empty_buf of { buf1 ->
975 case slurp_trailing_hashes buf1 exts of { con_buf ->
977 let all_buf = mergeLexemes buf con_buf
979 con_lexeme = lexemeToFastString con_buf
980 mod_lexeme = lexemeToFastString (decCurrentPos buf)
981 all_lexeme = lexemeToFastString all_buf
984 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
985 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
988 case currentChar# all_buf of
989 '.'# -> maybe_qualified cont exts all_lexeme
990 (incCurrentPos all_buf) just_a_conid
995 maybe_qualified cont exts mod buf just_a_conid =
996 -- trace ("qid: "{-++unpackFS lexeme-}) $
997 case currentChar# buf of
998 '['# -> -- Special case for []
999 case lookAhead# buf 1# of
1000 ']'# -> cont (ITqconid (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
1003 '('# -> -- Special case for (,,,)
1004 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1005 case lookAhead# buf 1# of
1006 '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
1007 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#)
1010 ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1011 ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1014 '-'# -> case lookAhead# buf 1# of
1015 '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1016 _ -> lex_id3 cont exts mod buf just_a_conid
1018 _ -> lex_id3 cont exts mod buf just_a_conid
1021 lex_id3 cont exts mod buf just_a_conid
1022 | is_upper (currentChar# buf) =
1023 lex_con cont exts buf
1025 | is_symbol (currentChar# buf) =
1027 start_new_lexeme = stepOverLexeme buf
1029 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1030 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1032 lexeme = lexemeToFastString buf'
1033 -- real lexeme is M.<sym>
1034 new_buf = mergeLexemes buf buf'
1036 cont (mk_qvar_token mod lexeme) new_buf
1037 -- wrong, but arguably morally right: M... is now a qvarsym
1042 start_new_lexeme = stepOverLexeme buf
1044 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1045 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1050 case slurp_trailing_hashes buf1 exts of { buf' ->
1053 lexeme = lexemeToFastString buf'
1054 new_buf = mergeLexemes buf buf'
1055 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1057 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1058 Nothing -> is_a_qvarid ;
1060 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1061 -> is_a_qvarid -- recognised as keywords here.
1063 -> just_a_conid -- avoid M.where etc.
1066 slurp_trailing_hashes buf exts
1067 | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1072 | is_upper f = ITconid pk_str
1073 | is_ident f = ITvarid pk_str
1074 | f `eqChar#` ':'# = ITconsym pk_str
1075 | otherwise = ITvarsym pk_str
1077 (C# f) = headFS pk_str
1078 -- tl = _TAIL_ pk_str
1080 mk_qvar_token m token =
1081 -- trace ("mk_qvar ") $
1082 case mk_var_token token of
1083 ITconid n -> ITqconid (m,n)
1084 ITvarid n -> ITqvarid (m,n)
1085 ITconsym n -> ITqconsym (m,n)
1086 ITvarsym n -> ITqvarsym (m,n)
1087 _ -> ITunknown (show token)
1090 ----------------------------------------------------------------------------
1091 Horrible stuff for dealing with M.(,,,)
1094 lex_tuple cont mod buf back_off =
1098 case currentChar# buf of
1099 ','# -> go (n+1) (stepOn buf)
1100 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1103 lex_ubx_tuple cont mod buf back_off =
1107 case currentChar# buf of
1108 ','# -> go (n+1) (stepOn buf)
1109 '#'# -> case lookAhead# buf 1# of
1110 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1116 -----------------------------------------------------------------------------
1127 data PState = PState {
1129 extsBitmap :: Int#, -- bitmap that determines permitted extensions
1132 context :: [LayoutContext]
1135 type P a = StringBuffer -- Input string
1140 returnP a buf s = POk s a
1142 thenP :: P a -> (a -> P b) -> P b
1143 m `thenP` k = \ buf s ->
1145 POk s1 a -> k a buf s1
1146 PFailed err -> PFailed err
1148 thenP_ :: P a -> P b -> P b
1149 m `thenP_` k = m `thenP` \_ -> k
1151 mapP :: (a -> P b) -> [a] -> P [b]
1152 mapP f [] = returnP []
1155 mapP f as `thenP` \bs ->
1158 failP :: String -> P a
1159 failP msg buf s = PFailed (text msg)
1161 failMsgP :: Message -> P a
1162 failMsgP msg buf s = PFailed msg
1164 lexError :: String -> P a
1165 lexError str buf s@PState{ loc = loc }
1166 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1168 getSrcLocP :: P SrcLoc
1169 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1171 -- use a temporary SrcLoc for the duration of the argument
1172 setSrcLocP :: SrcLoc -> P a -> P a
1173 setSrcLocP new_loc p buf s =
1174 case p buf s{ loc=new_loc } of
1176 PFailed e -> PFailed e
1178 getSrcFile :: P FastString
1179 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1181 pushContext :: LayoutContext -> P ()
1182 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1186 This special case in layoutOn is to handle layout contexts with are
1187 indented the same or less than the current context. This is illegal
1188 according to the Haskell spec, so we have to arrange to close the
1189 current context. eg.
1194 after the first 'where', the sequence of events is:
1196 - layout system inserts a ';' (column 0)
1197 - parser begins a new context at column 0
1198 - parser shifts ';' (legal empty declaration)
1199 - parser sees 'class': parse error (we're still in the inner context)
1201 trouble is, by the time we know we need a new context, the lexer has
1202 already generated the ';'. Hacky solution is as follows: since we
1203 know the column of the next token (it's the column number of the new
1204 context), we set the ACTUAL column number of the new context to this
1205 numer plus one. Hence the next time the lexer is called, a '}' will
1206 be generated to close the new context straight away. Furthermore, we
1207 have to set the atbol flag so that the ';' that the parser shifted as
1208 part of the new context is re-generated.
1210 when the new context is *less* indented than the current one:
1212 f = f where g = g where
1215 - current context: column 12.
1216 - on seeing 'h' (column 0), the layout system inserts '}'
1217 - parser starts a new context, column 0
1218 - parser sees '}', uses it to close new context
1219 - we still need to insert another '}' followed by a ';',
1220 hence the atbol trick.
1222 There's also a special hack in here to deal with
1229 i.e. the inner context is at the same indentation level as the outer
1230 context. This is strictly illegal according to Haskell 98, but
1231 there's a lot of existing code using this style and it doesn't make
1232 any sense to disallow it, since empty 'do' lists don't make sense.
1235 layoutOn :: Bool -> P ()
1236 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1237 let offset = lexemeIndex buf -# bol in
1240 | if strict then prev_off >=# offset else prev_off ># offset ->
1241 --trace ("layout on, column: " ++ show (I# offset)) $
1242 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1244 --trace ("layout on, column: " ++ show (I# offset)) $
1245 POk s{ context = Layout offset : ctx } ()
1248 layoutOff buf s@(PState{ context = ctx }) =
1249 POk s{ context = NoLayout:ctx } ()
1252 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1254 (_:tl) -> POk s{ context = tl } ()
1255 [] -> PFailed (srcParseErr buf loc)
1257 -- for reasons of efficiency, flags indicating language extensions (eg,
1258 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1261 glaExtsBit, ffiBit, parrBit :: Int
1267 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1268 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1269 ffiEnabled flags = testBit (toInt32 flags) ffiBit
1270 withEnabled flags = testBit (toInt32 flags) withBit
1271 parrEnabled flags = testBit (toInt32 flags) parrBit
1273 toInt32 :: Int# -> Int32
1274 toInt32 x# = fromIntegral (I# x#)
1276 -- convenient record-based bitmap for the interface to the rest of the world
1278 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1280 data ExtFlags = ExtFlags {
1281 glasgowExtsEF :: Bool,
1287 -- create a parse state
1289 mkPState :: SrcLoc -> ExtFlags -> PState
1293 extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1299 bitmap = glaExtsBit `setBitIf` glasgowExtsEF exts
1300 .|. ffiBit `setBitIf` (ffiEF exts
1301 || glasgowExtsEF exts)
1302 .|. withBit `setBitIf` withEF exts
1303 .|. parrBit `setBitIf` parrEF exts
1305 setBitIf :: Int -> Bool -> Int32
1306 b `setBitIf` cond | cond = bit b
1309 -----------------------------------------------------------------------------
1311 srcParseErr :: StringBuffer -> SrcLoc -> Message
1315 then ptext SLIT(": parse error (possibly incorrect indentation)")
1316 else hcat [ptext SLIT(": parse error on input "),
1317 char '`', text token, char '\'']
1320 token = lexemeToString s