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 --------------------------------------------------------
22 ifaceParseErr, srcParseErr,
25 Token(..), lexer, ParseResult(..), PState(..),
29 P, thenP, thenP_, returnP, mapP, failP, failMsgP,
30 getSrcLocP, setSrcLocP, getSrcFile,
31 layoutOn, layoutOff, pushContext, popContext
34 #include "HsVersions.h"
36 import Char ( isSpace, toUpper )
37 import List ( isSuffixOf )
39 import PrelNames ( mkTupNameStr )
40 import CmdLineOpts ( opt_HiVersion, opt_NoHiCheck )
41 import ForeignCall ( Safety(..) )
42 import NewDemand ( StrictSig(..), Demand(..), Keepity(..),
43 DmdResult(..), mkTopDmdType )
44 import UniqFM ( listToUFM, lookupUFM )
45 import BasicTypes ( Boxity(..) )
46 import SrcLoc ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
47 replaceSrcLine, mkSrcLoc )
49 import ErrUtils ( Message )
56 import Char ( chr, ord )
57 import PrelRead ( readRational__ ) -- Glasgow non-std
60 %************************************************************************
62 \subsection{Data types}
64 %************************************************************************
66 The token data type, fairly un-interesting except from one
67 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
68 strictness, unfolding etc).
70 The Idea/Observation here is that the renamer needs to scan through
71 all of an interface file before it can continue. But only a fraction
72 of the information contained in the file turns out to be useful, so
73 delaying as much as possible of the scanning and parsing of an
74 interface file Makes Sense (Heap profiles of the compiler
75 show a reduction in heap usage by at least a factor of two,
78 Hence, the interface file lexer spots when value declarations are
79 being scanned and return the @ITidinfo@ and @ITtype@ constructors
80 for the type and any other id info for that binding (unfolding, strictness
81 etc). These constructors are applied to the result of lexing these sub-chunks.
83 The lexing of the type and id info is all done lazily, of course, so
84 the scanning (and subsequent parsing) will be done *only* on the ids the
85 renamer finds out that it is interested in. The rest will just be junked.
86 Laziness, you know it makes sense :-)
90 = ITas -- Haskell keywords
114 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
116 | ITforall -- GHC extension keywords
127 | ITinterface -- interface keywords
135 | ITccall (Bool,Bool,Safety) -- (is_dyn, is_casm, may_gc)
162 | ITspecialise_prag -- Pragmas
172 | ITdotdot -- reserved symbols
186 | ITbiglam -- GHC-extension symbols
188 | ITocurly -- special symbols
190 | ITocurlybar -- {|, for type applications
191 | ITccurlybar -- |}, for type applications
204 | ITvarid FAST_STRING -- identifiers
205 | ITconid FAST_STRING
206 | ITvarsym FAST_STRING
207 | ITconsym FAST_STRING
208 | ITqvarid (FAST_STRING,FAST_STRING)
209 | ITqconid (FAST_STRING,FAST_STRING)
210 | ITqvarsym (FAST_STRING,FAST_STRING)
211 | ITqconsym (FAST_STRING,FAST_STRING)
213 | ITipvarid FAST_STRING -- GHC extension: implicit param: ?x
215 | ITpragma StringBuffer
218 | ITstring FAST_STRING
220 | ITrational Rational
223 | ITprimstring FAST_STRING
225 | ITprimfloat Rational
226 | ITprimdouble Rational
227 | ITlitlit FAST_STRING
229 | ITunknown String -- Used when the lexer can't make sense of it
230 | ITeof -- end of file token
231 deriving Show -- debugging
234 -----------------------------------------------------------------------------
238 pragmaKeywordsFM = listToUFM $
239 map (\ (x,y) -> (_PK_ x,y))
240 [( "SPECIALISE", ITspecialise_prag ),
241 ( "SPECIALIZE", ITspecialise_prag ),
242 ( "SOURCE", ITsource_prag ),
243 ( "INLINE", ITinline_prag ),
244 ( "NOINLINE", ITnoinline_prag ),
245 ( "NOTINLINE", ITnoinline_prag ),
246 ( "LINE", ITline_prag ),
247 ( "RULES", ITrules_prag ),
248 ( "RULEZ", ITrules_prag ), -- american spelling :-)
249 ( "SCC", ITscc_prag ),
250 ( "DEPRECATED", ITdeprecated_prag )
253 haskellKeywordsFM = listToUFM $
254 map (\ (x,y) -> (_PK_ x,y))
255 [( "_", ITunderscore ),
258 ( "class", ITclass ),
260 ( "default", ITdefault ),
261 ( "deriving", ITderiving ),
264 ( "hiding", IThiding ),
266 ( "import", ITimport ),
268 ( "infix", ITinfix ),
269 ( "infixl", ITinfixl ),
270 ( "infixr", ITinfixr ),
271 ( "instance", ITinstance ),
273 ( "module", ITmodule ),
274 ( "newtype", ITnewtype ),
276 ( "qualified", ITqualified ),
279 ( "where", ITwhere ),
280 ( "_scc_", ITscc ) -- ToDo: remove
283 isSpecial :: Token -> Bool
284 -- If we see M.x, where x is a keyword, but
285 -- is special, we treat is as just plain M.x,
287 isSpecial ITas = True
288 isSpecial IThiding = True
289 isSpecial ITqualified = True
290 isSpecial ITforall = True
291 isSpecial ITexport = True
292 isSpecial ITlabel = True
293 isSpecial ITdynamic = True
294 isSpecial ITunsafe = True
295 isSpecial ITwith = True
296 isSpecial ITccallconv = True
297 isSpecial ITstdcallconv = True
300 -- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
301 ghcExtensionKeywordsFM = listToUFM $
302 map (\ (x,y) -> (_PK_ x,y))
303 [ ( "forall", ITforall ),
304 ( "foreign", ITforeign ),
305 ( "export", ITexport ),
306 ( "label", ITlabel ),
307 ( "dynamic", ITdynamic ),
308 ( "unsafe", ITunsafe ),
310 ( "stdcall", ITstdcallconv),
311 ( "ccall", ITccallconv),
312 ( "dotnet", ITdotnet),
313 ("_ccall_", ITccall (False, False, PlayRisky)),
314 ("_ccall_GC_", ITccall (False, False, PlaySafe)),
315 ("_casm_", ITccall (False, True, PlayRisky)),
316 ("_casm_GC_", ITccall (False, True, PlaySafe)),
318 -- interface keywords
319 ("__interface", ITinterface),
320 ("__export", IT__export),
321 ("__depends", ITdepends),
322 ("__forall", IT__forall),
323 ("__letrec", ITletrec),
324 ("__coerce", ITcoerce),
325 ("__inline_me", ITinlineMe),
326 ("__inline_call", ITinlineCall),
327 ("__depends", ITdepends),
328 ("__DEFAULT", ITdefaultbranch),
330 ("__integer", ITinteger_lit),
331 ("__float", ITfloat_lit),
332 ("__int64", ITint64_lit),
333 ("__word", ITword_lit),
334 ("__word64", ITword64_lit),
335 ("__rational", ITrational_lit),
336 ("__addr", ITaddr_lit),
337 ("__label", ITlabel_lit),
338 ("__litlit", ITlit_lit),
339 ("__string", ITstring_lit),
342 ("__fuall", ITfuall),
344 ("__P", ITspecialise),
347 ("__D", ITdeprecated),
350 ("__ccall", ITccall (False, False, PlayRisky)),
351 ("__ccall_GC", ITccall (False, False, PlaySafe)),
352 ("__dyn_ccall", ITccall (True, False, PlayRisky)),
353 ("__dyn_ccall_GC", ITccall (True, False, PlaySafe)),
354 ("__casm", ITccall (False, True, PlayRisky)),
355 ("__dyn_casm", ITccall (True, True, PlayRisky)),
356 ("__casm_GC", ITccall (False, True, PlaySafe)),
357 ("__dyn_casm_GC", ITccall (True, True, PlaySafe)),
363 haskellKeySymsFM = listToUFM $
364 map (\ (x,y) -> (_PK_ x,y))
377 ,(".", ITdot) -- sadly, for 'forall a . t'
381 -----------------------------------------------------------------------------
386 - (glaexts) lexing an interface file or -fglasgow-exts
387 - (bol) pointer to beginning of line (for column calculations)
388 - (buf) pointer to beginning of token
389 - (buf) pointer to current char
390 - (atbol) flag indicating whether we're at the beginning of a line
393 lexer :: (Token -> P a) -> P a
394 lexer cont buf s@(PState{
396 glasgow_exts = glaexts,
402 -- first, start a new lexeme and lose all the whitespace
404 tab line bol atbol (stepOverLexeme buf)
406 line = srcLocLine loc
408 tab y bol atbol buf = -- trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
409 case currentChar# buf of
412 if bufferExhausted (stepOn buf)
413 then cont ITeof buf s'
414 else trace "lexer: misplaced NUL?" $
415 tab y bol atbol (stepOn buf)
417 '\n'# -> let buf' = stepOn buf
418 in tab (y +# 1#) (currentIndex# buf') 1# buf'
420 -- find comments. This got harder in Haskell 98.
421 '-'# -> let trundle n =
422 let next = lookAhead# buf n in
423 if next `eqChar#` '-'# then trundle (n +# 1#)
424 else if is_symbol next || n <# 2#
427 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
430 -- comments and pragmas. We deal with LINE pragmas here,
431 -- and throw out any unrecognised pragmas as comments. Any
432 -- pragmas we know about are dealt with later (after any layout
433 -- processing if necessary).
434 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
435 if lookAhead# buf 2# `eqChar#` '#'# then
436 if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
437 case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
438 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
439 let lexeme = mkFastString -- ToDo: too slow
440 (map toUpper (lexemeToString buf2)) in
441 case lookupUFM pragmaKeywordsFM lexeme of
442 -- ignore RULES pragmas when -fglasgow-exts is off
443 Just ITrules_prag | not (flag glaexts) ->
444 skip_to_end (stepOnBy# buf 2#) s'
446 line_prag skip_to_end buf2 s'
447 Just other -> is_a_token
448 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
451 else skip_to_end (stepOnBy# buf 2#) s'
453 skip_to_end = skipNestedComment (lexer cont)
455 -- special GHC extension: we grok cpp-style #line pragmas
456 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
457 case expandWhile# is_space (stepOn buf) of { buf1 ->
458 if is_digit (currentChar# buf1)
459 then line_prag next_line buf1 s'
463 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
465 -- tabs have been expanded beforehand
466 c | is_space c -> tab y bol atbol (stepOn buf)
467 | otherwise -> is_a_token
469 where s' = s{loc = replaceSrcLine loc y,
473 is_a_token | atbol /=# 0# = lexBOL cont buf s'
474 | otherwise = lexToken cont glaexts buf s'
476 -- {-# LINE .. #-} pragmas. yeuch.
477 line_prag cont buf s@PState{loc=loc} =
478 case expandWhile# is_space buf of { buf1 ->
479 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
480 -- subtract one: the line number refers to the *following* line.
481 let real_line = line - 1 in
482 case fromInteger real_line of { i@(I# l) ->
483 -- ToDo, if no filename then we skip the newline.... d'oh
484 case expandWhile# is_space buf2 of { buf3 ->
485 case currentChar# buf3 of
487 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
489 file = lexemeToFastString buf4
490 new_buf = stepOn (stepOverLexeme buf4)
492 if nullFastString file
493 then cont new_buf s{loc = replaceSrcLine loc l}
494 else cont new_buf s{loc = mkSrcLoc file i}
496 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
499 skipNestedComment :: P a -> P a
500 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
502 skipNestedComment' :: SrcLoc -> P a -> P a
503 skipNestedComment' orig_loc cont buf = loop buf
506 case currentChar# buf of
507 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
509 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
511 (skipNestedComment' orig_loc cont)
514 '\n'# -> \ s@PState{loc=loc} ->
515 let buf' = stepOn buf in
516 loop buf' s{loc = incSrcLine loc,
517 bol = currentIndex# buf',
520 -- pass the original SrcLoc to lexError so that the error is
521 -- reported at the line it was originally on, not the line at
522 -- the end of the file.
523 '\NUL'# | bufferExhausted (stepOn buf) ->
524 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
526 _ -> loop (stepOn buf)
528 -- When we are lexing the first token of a line, check whether we need to
529 -- insert virtual semicolons or close braces due to layout.
531 lexBOL :: (Token -> P a) -> P a
532 lexBOL cont buf s@(PState{
534 glasgow_exts = glaexts,
539 if need_close_curly then
540 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
541 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
542 else if need_semi_colon then
543 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
544 cont ITsemi buf s{atbol = 0#}
546 lexToken cont glaexts buf s{atbol = 0#}
548 col = currentIndex# buf -# bol
561 Layout n -> col ==# n
564 lexToken :: (Token -> P a) -> Int# -> P a
565 lexToken cont glaexts buf =
566 -- trace "lexToken" $
567 case currentChar# buf of
569 -- special symbols ----------------------------------------------------
570 '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'#
571 -> cont IToubxparen (setCurrentPos# buf 2#)
573 -> cont IToparen (incLexeme buf)
575 ')'# -> cont ITcparen (incLexeme buf)
576 '['# -> cont ITobrack (incLexeme buf)
577 ']'# -> cont ITcbrack (incLexeme buf)
578 ','# -> cont ITcomma (incLexeme buf)
579 ';'# -> cont ITsemi (incLexeme buf)
580 '}'# -> \ s@PState{context = ctx} ->
582 (_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
583 _ -> lexError "too many '}'s" buf s
584 '|'# -> case lookAhead# buf 1# of
585 '}'# | flag glaexts -> cont ITccurlybar
586 (setCurrentPos# buf 2#)
587 _ -> lex_sym cont (incLexeme buf)
590 '#'# -> case lookAhead# buf 1# of
591 ')'# | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
592 '-'# -> case lookAhead# buf 2# of
593 '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
594 _ -> lex_sym cont (incLexeme buf)
595 _ -> lex_sym cont (incLexeme buf)
597 '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
598 -> lex_cstring cont (setCurrentPos# buf 2#)
600 -> cont ITbackquote (incLexeme buf)
602 '{'# -> -- look for "{-##" special iface pragma
603 case lookAhead# buf 1# of
605 -> cont ITocurlybar (setCurrentPos# buf 2#)
606 '-'# -> case lookAhead# buf 2# of
607 '#'# -> case lookAhead# buf 3# of
610 = doDiscard 0# (stepOnBy# (stepOverLexeme buf) 4#) in
611 cont (ITpragma lexeme) buf'
612 _ -> lex_prag cont (setCurrentPos# buf 3#)
613 _ -> cont ITocurly (incLexeme buf)
614 _ -> (layoutOff `thenP_` cont ITocurly) (incLexeme buf)
616 -- strings/characters -------------------------------------------------
617 '\"'#{-"-} -> lex_string cont glaexts [] (incLexeme buf)
618 '\''# -> lex_char (char_end cont) glaexts (incLexeme buf)
620 -- strictness and cpr pragmas and __scc treated specially.
621 '_'# | flag glaexts ->
622 case lookAhead# buf 1# of
623 '_'# -> case lookAhead# buf 2# of
625 lex_demand cont (stepOnUntil (not . isSpace)
626 (stepOnBy# buf 3#)) -- past __S
628 cont ITcprinfo (stepOnBy# buf 3#) -- past __M
631 case prefixMatch (stepOnBy# buf 3#) "cc" of
632 Just buf' -> lex_scc cont (stepOverLexeme buf')
633 Nothing -> lex_id cont glaexts buf
634 _ -> lex_id cont glaexts buf
635 _ -> lex_id cont glaexts buf
637 -- Hexadecimal and octal constants
638 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
639 -> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
640 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
641 -> readNum (after_lexnum cont glaexts) buf' is_octdigit 8 oct_or_dec
642 where ch = lookAhead# buf 1#
643 ch2 = lookAhead# buf 2#
644 buf' = setCurrentPos# buf 2#
647 if bufferExhausted (stepOn buf) then
650 trace "lexIface: misplaced NUL?" $
651 cont (ITunknown "\NUL") (stepOn buf)
653 '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
654 lex_ip cont (incLexeme buf)
655 c | is_digit c -> lex_num cont glaexts 0 buf
656 | is_symbol c -> lex_sym cont buf
657 | is_upper c -> lex_con cont glaexts buf
658 | is_ident c -> lex_id cont glaexts buf
659 | otherwise -> lexError "illegal character" buf
661 -- Int# is unlifted, and therefore faster than Bool for flags.
667 -------------------------------------------------------------------------------
671 = case expandWhile# is_space buf of { buf1 ->
672 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
673 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
674 case lookupUFM pragmaKeywordsFM lexeme of
675 Just kw -> cont kw (mergeLexemes buf buf2)
676 Nothing -> panic "lex_prag"
679 -------------------------------------------------------------------------------
682 lex_string cont glaexts s buf
683 = case currentChar# buf of
685 let buf' = incLexeme buf
686 s' = mkFastStringNarrow (map chr (reverse s))
687 in case currentChar# buf' of
688 '#'# | flag glaexts -> if all (<= 0xFF) s
689 then cont (ITprimstring s') (incLexeme buf')
690 else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
691 _ -> cont (ITstring s') buf'
693 -- ignore \& in a string, deal with string gaps
694 '\\'# | next_ch `eqChar#` '&'#
695 -> lex_string cont glaexts s buf'
697 -> lex_stringgap cont glaexts s (incLexeme buf)
699 where next_ch = lookAhead# buf 1#
700 buf' = setCurrentPos# buf 2#
702 _ -> lex_char (lex_next_string cont s) glaexts buf
704 lex_stringgap cont glaexts s buf
705 = let buf' = incLexeme buf in
706 case currentChar# buf of
707 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf'
708 st{loc = incSrcLine loc}
709 '\\'# -> lex_string cont glaexts s buf'
710 c | is_space c -> lex_stringgap cont glaexts s buf'
711 other -> charError buf'
713 lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf
715 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
716 lex_char cont glaexts buf
717 = case currentChar# buf of
718 '\\'# -> lex_escape (cont glaexts) (incLexeme buf)
719 c | is_any c -> cont glaexts (I# (ord# c)) (incLexeme buf)
720 other -> charError buf
722 char_end cont glaexts c buf
723 = case currentChar# buf of
724 '\''# -> let buf' = incLexeme buf in
725 case currentChar# buf' of
727 -> cont (ITprimchar c) (incLexeme buf')
728 _ -> cont (ITchar c) buf'
732 = let buf' = incLexeme buf in
733 case currentChar# buf of
734 'a'# -> cont (ord '\a') buf'
735 'b'# -> cont (ord '\b') buf'
736 'f'# -> cont (ord '\f') buf'
737 'n'# -> cont (ord '\n') buf'
738 'r'# -> cont (ord '\r') buf'
739 't'# -> cont (ord '\t') buf'
740 'v'# -> cont (ord '\v') buf'
741 '\\'# -> cont (ord '\\') buf'
742 '"'# -> cont (ord '\"') buf'
743 '\''# -> cont (ord '\'') buf'
744 '^'# -> let c = currentChar# buf' in
745 if c `geChar#` '@'# && c `leChar#` '_'#
746 then cont (I# (ord# c -# ord# '@'#)) (incLexeme buf')
749 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
750 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
752 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
754 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
755 Just buf2 <- [prefixMatch buf p] ] of
756 (c,buf2):_ -> cont (ord c) buf2
759 after_charnum cont i buf
760 = if i >= 0 && i <= 0x10FFFF
761 then cont (fromInteger i) buf
764 readNum cont buf is_digit base conv = read buf 0
766 = case currentChar# buf of { c ->
768 then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
774 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
775 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
777 hex c | is_digit c = ord# c -# ord# '0'#
778 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
779 oct_or_dec c = ord# c -# ord# '0'#
781 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
784 | c `geChar#` 'A'# && c `leChar#` 'Z'#
785 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
788 charError buf = lexError "error in character literal" buf
790 silly_escape_chars = [
827 -------------------------------------------------------------------------------
829 lex_demand cont buf =
830 case read_em [] buf of { (ls,buf') ->
831 case currentChar# buf' of
832 'b'# -> cont (ITstrict (StrictSig (mkTopDmdType ls BotRes))) (incLexeme buf')
833 'm'# -> cont (ITstrict (StrictSig (mkTopDmdType ls RetCPR))) (incLexeme buf')
834 _ -> cont (ITstrict (StrictSig (mkTopDmdType ls TopRes))) buf'
838 case currentChar# buf of
839 'L'# -> read_em (Lazy : acc) (stepOn buf)
840 'A'# -> read_em (Abs : acc) (stepOn buf)
841 'V'# -> read_em (Eval : acc) (stepOn buf)
842 'X'# -> read_em (Err : acc) (stepOn buf)
843 'B'# -> read_em (Bot : acc) (stepOn buf)
844 ')'# -> (reverse acc, stepOn buf)
845 'C'# -> do_call acc (stepOnBy# buf 2#)
846 'D'# -> do_unpack1 Defer acc (stepOnBy# buf 1#)
847 'U'# -> do_unpack1 Drop acc (stepOnBy# buf 1#)
848 'S'# -> do_unpack1 Keep acc (stepOnBy# buf 1#)
849 _ -> (reverse acc, buf)
851 do_unpack1 keepity acc buf
852 = case currentChar# buf of
853 '('# -> do_unpack2 keepity acc (stepOnBy# buf 1#)
854 _ -> read_em (Seq keepity [] : acc) buf
856 do_unpack2 keepity acc buf
857 = case read_em [] buf of
858 (stuff, rest) -> read_em (Seq keepity stuff : acc) rest
861 = case read_em [] buf of
862 ([dmd], rest) -> read_em (Call dmd : acc) rest
866 case currentChar# buf of
867 'C'# -> cont ITsccAllCafs (incLexeme buf)
868 other -> cont ITscc buf
870 -----------------------------------------------------------------------------
873 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
874 lex_num cont glaexts acc buf =
875 case scanNumLit acc buf of
877 case currentChar# buf' of
878 '.'# | is_digit (lookAhead# buf' 1#) ->
879 -- this case is not optimised at all, as the
880 -- presence of floating point numbers in interface
881 -- files is not that common. (ToDo)
882 case expandWhile# is_digit (incLexeme buf') of
883 buf2 -> -- points to first non digit char
885 let l = case currentChar# buf2 of
891 = let buf3 = incLexeme buf2 in
892 case currentChar# buf3 of
893 '-'# -> expandWhile# is_digit (incLexeme buf3)
894 '+'# -> expandWhile# is_digit (incLexeme buf3)
895 x | is_digit x -> expandWhile# is_digit buf3
898 v = readRational__ (lexemeToString l)
900 in case currentChar# l of -- glasgow exts only
901 '#'# | flag glaexts -> let l' = incLexeme l in
902 case currentChar# l' of
903 '#'# -> cont (ITprimdouble v) (incLexeme l')
904 _ -> cont (ITprimfloat v) l'
905 _ -> cont (ITrational v) l
907 _ -> after_lexnum cont glaexts acc' buf'
909 after_lexnum cont glaexts i buf
910 = case currentChar# buf of
911 '#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
912 _ -> cont (ITinteger i) buf
914 -----------------------------------------------------------------------------
915 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
917 -- we lexemeToFastString on the bit between the ``''s, but include the
918 -- quotes in the full lexeme.
920 lex_cstring cont buf =
921 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
922 Just buf' -> cont (ITlitlit (lexemeToFastString
923 (setCurrentPos# buf' (negateInt# 2#))))
924 (mergeLexemes buf buf')
925 Nothing -> lexError "unterminated ``" buf
927 -----------------------------------------------------------------------------
928 -- identifiers, symbols etc.
931 case expandWhile# is_ident buf of
932 buf' -> cont (ITipvarid lexeme) buf'
933 where lexeme = lexemeToFastString buf'
935 lex_id cont glaexts buf =
936 let buf1 = expandWhile# is_ident buf in
939 case (if flag glaexts
940 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
941 else buf1) of { buf' ->
943 let lexeme = lexemeToFastString buf' in
945 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
946 Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
950 let var_token = cont (ITvarid lexeme) buf' in
952 if not (flag glaexts)
956 case lookupUFM ghcExtensionKeywordsFM lexeme of {
957 Just kwd_token -> cont kwd_token buf';
964 case expandWhile# is_symbol buf of
965 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
966 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
967 cont kwd_token buf' ;
968 Nothing -> --trace ("sym: "++unpackFS lexeme) $
969 cont (mk_var_token lexeme) buf'
971 where lexeme = lexemeToFastString buf'
974 -- lex_con recursively collects components of a qualified identifer.
975 -- The argument buf is the StringBuffer representing the lexeme
976 -- identified so far, where the next character is upper-case.
978 lex_con cont glaexts buf =
979 -- trace ("con: "{-++unpackFS lexeme-}) $
980 let empty_buf = stepOverLexeme buf in
981 case expandWhile# is_ident empty_buf of { buf1 ->
982 case slurp_trailing_hashes buf1 glaexts of { con_buf ->
984 let all_buf = mergeLexemes buf con_buf
986 con_lexeme = lexemeToFastString con_buf
987 mod_lexeme = lexemeToFastString (decLexeme buf)
988 all_lexeme = lexemeToFastString all_buf
991 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
992 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
995 case currentChar# all_buf of
996 '.'# -> maybe_qualified cont glaexts all_lexeme
997 (incLexeme all_buf) just_a_conid
1002 maybe_qualified cont glaexts mod buf just_a_conid =
1003 -- trace ("qid: "{-++unpackFS lexeme-}) $
1004 case currentChar# buf of
1005 '['# -> -- Special case for []
1006 case lookAhead# buf 1# of
1007 ']'# -> cont (ITqconid (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
1010 '('# -> -- Special case for (,,,)
1011 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1012 case lookAhead# buf 1# of
1013 '#'# | flag glaexts -> case lookAhead# buf 2# of
1014 ','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#)
1017 ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
1018 ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
1021 '-'# -> case lookAhead# buf 1# of
1022 '>'# -> cont (ITqconid (mod,SLIT("(->)"))) (setCurrentPos# buf 2#)
1023 _ -> lex_id3 cont glaexts mod buf just_a_conid
1025 _ -> lex_id3 cont glaexts mod buf just_a_conid
1028 lex_id3 cont glaexts mod buf just_a_conid
1029 | is_upper (currentChar# buf) =
1030 lex_con cont glaexts buf
1032 | is_symbol (currentChar# buf) =
1034 start_new_lexeme = stepOverLexeme buf
1036 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1037 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1039 lexeme = lexemeToFastString buf'
1040 -- real lexeme is M.<sym>
1041 new_buf = mergeLexemes buf buf'
1043 cont (mk_qvar_token mod lexeme) new_buf
1044 -- wrong, but arguably morally right: M... is now a qvarsym
1049 start_new_lexeme = stepOverLexeme buf
1051 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1052 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1057 case slurp_trailing_hashes buf1 glaexts of { buf' ->
1060 lexeme = lexemeToFastString buf'
1061 new_buf = mergeLexemes buf buf'
1062 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1064 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1065 Nothing -> is_a_qvarid ;
1067 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1068 -> is_a_qvarid -- recognised as keywords here.
1070 -> just_a_conid -- avoid M.where etc.
1073 slurp_trailing_hashes buf glaexts
1074 | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
1079 | is_upper f = ITconid pk_str
1080 | is_ident f = ITvarid pk_str
1081 | f `eqChar#` ':'# = ITconsym pk_str
1082 | otherwise = ITvarsym pk_str
1084 (C# f) = _HEAD_ pk_str
1085 -- tl = _TAIL_ pk_str
1087 mk_qvar_token m token =
1088 -- trace ("mk_qvar ") $
1089 case mk_var_token token of
1090 ITconid n -> ITqconid (m,n)
1091 ITvarid n -> ITqvarid (m,n)
1092 ITconsym n -> ITqconsym (m,n)
1093 ITvarsym n -> ITqvarsym (m,n)
1094 _ -> ITunknown (show token)
1097 ----------------------------------------------------------------------------
1098 Horrible stuff for dealing with M.(,,,)
1101 lex_tuple cont mod buf back_off =
1105 case currentChar# buf of
1106 ','# -> go (n+1) (stepOn buf)
1107 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1110 lex_ubx_tuple cont mod buf back_off =
1114 case currentChar# buf of
1115 ','# -> go (n+1) (stepOn buf)
1116 '#'# -> case lookAhead# buf 1# of
1117 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1123 -----------------------------------------------------------------------------
1124 doDiscard rips along really fast, looking for a '##-}',
1125 indicating the end of the pragma we're skipping
1128 doDiscard inStr buf =
1129 case currentChar# buf of
1130 '#'# | inStr ==# 0# ->
1131 case lookAhead# buf 1# of { '#'# ->
1132 case lookAhead# buf 2# of { '-'# ->
1133 case lookAhead# buf 3# of { '}'# ->
1134 (lexemeToBuffer buf, stepOverLexeme (setCurrentPos# buf 4#));
1135 _ -> doDiscard inStr (incLexeme buf) };
1136 _ -> doDiscard inStr (incLexeme buf) };
1137 _ -> doDiscard inStr (incLexeme buf) }
1141 odd_slashes buf flg i# =
1142 case lookAhead# buf i# of
1143 '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
1146 not_inStr = if inStr ==# 0# then 1# else 0#
1148 case lookAhead# buf (negateInt# 1#) of --backwards, actually
1149 '\\'# -> -- escaping something..
1150 if odd_slashes buf True (negateInt# 2#)
1151 then -- odd number of slashes, " is escaped.
1152 doDiscard inStr (incLexeme buf)
1153 else -- even number of slashes, \ is escaped.
1154 doDiscard not_inStr (incLexeme buf)
1155 _ -> doDiscard not_inStr (incLexeme buf)
1157 '\''# | inStr ==# 0# ->
1158 case lookAhead# buf 1# of { '"'# ->
1159 case lookAhead# buf 2# of { '\''# ->
1160 doDiscard inStr (setCurrentPos# buf 3#);
1161 _ -> doDiscard inStr (incLexeme buf) };
1162 _ -> doDiscard inStr (incLexeme buf) }
1164 _ -> doDiscard inStr (incLexeme buf)
1168 -----------------------------------------------------------------------------
1179 data PState = PState {
1181 glasgow_exts :: Int#,
1184 context :: [LayoutContext]
1187 type P a = StringBuffer -- Input string
1192 returnP a buf s = POk s a
1194 thenP :: P a -> (a -> P b) -> P b
1195 m `thenP` k = \ buf s ->
1197 POk s1 a -> k a buf s1
1198 PFailed err -> PFailed err
1200 thenP_ :: P a -> P b -> P b
1201 m `thenP_` k = m `thenP` \_ -> k
1203 mapP :: (a -> P b) -> [a] -> P [b]
1204 mapP f [] = returnP []
1207 mapP f as `thenP` \bs ->
1210 failP :: String -> P a
1211 failP msg buf s = PFailed (text msg)
1213 failMsgP :: Message -> P a
1214 failMsgP msg buf s = PFailed msg
1216 lexError :: String -> P a
1217 lexError str buf s@PState{ loc = loc }
1218 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1220 getSrcLocP :: P SrcLoc
1221 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1223 -- use a temporary SrcLoc for the duration of the argument
1224 setSrcLocP :: SrcLoc -> P a -> P a
1225 setSrcLocP new_loc p buf s =
1226 case p buf s{ loc=new_loc } of
1228 PFailed e -> PFailed e
1230 getSrcFile :: P FAST_STRING
1231 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1233 pushContext :: LayoutContext -> P ()
1234 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1238 This special case in layoutOn is to handle layout contexts with are
1239 indented the same or less than the current context. This is illegal
1240 according to the Haskell spec, so we have to arrange to close the
1241 current context. eg.
1246 after the first 'where', the sequence of events is:
1248 - layout system inserts a ';' (column 0)
1249 - parser begins a new context at column 0
1250 - parser shifts ';' (legal empty declaration)
1251 - parser sees 'class': parse error (we're still in the inner context)
1253 trouble is, by the time we know we need a new context, the lexer has
1254 already generated the ';'. Hacky solution is as follows: since we
1255 know the column of the next token (it's the column number of the new
1256 context), we set the ACTUAL column number of the new context to this
1257 numer plus one. Hence the next time the lexer is called, a '}' will
1258 be generated to close the new context straight away. Furthermore, we
1259 have to set the atbol flag so that the ';' that the parser shifted as
1260 part of the new context is re-generated.
1262 when the new context is *less* indented than the current one:
1264 f = f where g = g where
1267 - current context: column 12.
1268 - on seeing 'h' (column 0), the layout system inserts '}'
1269 - parser starts a new context, column 0
1270 - parser sees '}', uses it to close new context
1271 - we still need to insert another '}' followed by a ';',
1272 hence the atbol trick.
1274 There's also a special hack in here to deal with
1281 i.e. the inner context is at the same indentation level as the outer
1282 context. This is strictly illegal according to Haskell 98, but
1283 there's a lot of existing code using this style and it doesn't make
1284 any sense to disallow it, since empty 'do' lists don't make sense.
1287 layoutOn :: Bool -> P ()
1288 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1289 let offset = lexemeIndex buf -# bol in
1292 | if strict then prev_off >=# offset else prev_off ># offset ->
1293 --trace ("layout on, column: " ++ show (I# offset)) $
1294 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1296 --trace ("layout on, column: " ++ show (I# offset)) $
1297 POk s{ context = Layout offset : ctx } ()
1300 layoutOff buf s@(PState{ context = ctx }) =
1301 POk s{ context = NoLayout:ctx } ()
1304 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1306 (_:tl) -> POk s{ context = tl } ()
1307 [] -> PFailed (srcParseErr buf loc)
1310 Note that if the name of the file we're processing ends
1311 with `hi-boot', we accept it on faith as having the right
1312 version. This is done so that .hi-boot files that comes
1313 with hsc don't have to be updated before every release,
1314 *and* it allows us to share .hi-boot files with versions
1315 of hsc that don't have .hi version checking (e.g., ghc-2.10's)
1317 If the version number is 0, the checking is also turned off.
1318 (needed to deal with GHC.hi only!)
1320 Once we can assume we're compiling with a version of ghc that
1321 supports interface file checking, we can drop the special
1324 checkVersion :: Maybe Integer -> P ()
1325 checkVersion mb@(Just v) buf s@(PState{loc = loc})
1326 | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
1327 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1328 checkVersion mb@Nothing buf s@(PState{loc = loc})
1329 | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
1330 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1332 -----------------------------------------------------------------
1334 ifaceParseErr :: StringBuffer -> SrcLoc -> Message
1336 = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
1337 text (lexemeToString s), char '\'']
1339 ifaceVersionErr hi_vers l toks
1340 = hsep [ppr l, ptext SLIT("Interface file version error;"),
1341 ptext SLIT("Expected"), int opt_HiVersion,
1342 ptext SLIT("found "), pp_version]
1346 Nothing -> ptext SLIT("pre ghc-3.02 version")
1347 Just v -> ptext SLIT("version") <+> integer v
1349 -----------------------------------------------------------------------------
1351 srcParseErr :: StringBuffer -> SrcLoc -> Message
1355 then ptext SLIT(": parse error (possibly incorrect indentation)")
1356 else hcat [ptext SLIT(": parse error on input "),
1357 char '`', text token, char '\'']
1360 token = lexemeToString s