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(..), Demands(..),
43 DmdResult(..), mkTopDmdType, evalDmd, lazyDmd )
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
128 | ITinterface -- interface keywords
136 | ITccall (Bool,Bool,Safety) -- (is_dyn, is_casm, may_gc)
163 | ITspecialise_prag -- Pragmas
173 | ITdotdot -- reserved symbols
187 | ITbiglam -- GHC-extension symbols
189 | ITocurly -- special symbols
191 | ITocurlybar -- {|, for type applications
192 | ITccurlybar -- |}, for type applications
205 | ITvarid FAST_STRING -- identifiers
206 | ITconid FAST_STRING
207 | ITvarsym FAST_STRING
208 | ITconsym FAST_STRING
209 | ITqvarid (FAST_STRING,FAST_STRING)
210 | ITqconid (FAST_STRING,FAST_STRING)
211 | ITqvarsym (FAST_STRING,FAST_STRING)
212 | ITqconsym (FAST_STRING,FAST_STRING)
214 | ITdupipvarid FAST_STRING -- GHC extension: implicit param: ?x
215 | ITsplitipvarid FAST_STRING -- GHC extension: implicit param: %x
217 | ITpragma StringBuffer
220 | ITstring FAST_STRING
222 | ITrational Rational
225 | ITprimstring FAST_STRING
227 | ITprimfloat Rational
228 | ITprimdouble Rational
229 | ITlitlit FAST_STRING
231 | ITunknown String -- Used when the lexer can't make sense of it
232 | ITeof -- end of file token
233 deriving Show -- debugging
236 -----------------------------------------------------------------------------
240 pragmaKeywordsFM = listToUFM $
241 map (\ (x,y) -> (_PK_ x,y))
242 [( "SPECIALISE", ITspecialise_prag ),
243 ( "SPECIALIZE", ITspecialise_prag ),
244 ( "SOURCE", ITsource_prag ),
245 ( "INLINE", ITinline_prag ),
246 ( "NOINLINE", ITnoinline_prag ),
247 ( "NOTINLINE", ITnoinline_prag ),
248 ( "LINE", ITline_prag ),
249 ( "RULES", ITrules_prag ),
250 ( "RULEZ", ITrules_prag ), -- american spelling :-)
251 ( "SCC", ITscc_prag ),
252 ( "DEPRECATED", ITdeprecated_prag )
255 haskellKeywordsFM = listToUFM $
256 map (\ (x,y) -> (_PK_ x,y))
257 [( "_", ITunderscore ),
260 ( "class", ITclass ),
262 ( "default", ITdefault ),
263 ( "deriving", ITderiving ),
266 ( "hiding", IThiding ),
268 ( "import", ITimport ),
270 ( "infix", ITinfix ),
271 ( "infixl", ITinfixl ),
272 ( "infixr", ITinfixr ),
273 ( "instance", ITinstance ),
275 ( "module", ITmodule ),
276 ( "newtype", ITnewtype ),
278 ( "qualified", ITqualified ),
281 ( "where", ITwhere ),
282 ( "_scc_", ITscc ) -- ToDo: remove
285 isSpecial :: Token -> Bool
286 -- If we see M.x, where x is a keyword, but
287 -- is special, we treat is as just plain M.x,
289 isSpecial ITas = True
290 isSpecial IThiding = True
291 isSpecial ITqualified = True
292 isSpecial ITforall = True
293 isSpecial ITexport = True
294 isSpecial ITlabel = True
295 isSpecial ITdynamic = True
296 isSpecial ITsafe = True
297 isSpecial ITunsafe = True
298 isSpecial ITwith = True
299 isSpecial ITccallconv = True
300 isSpecial ITstdcallconv = True
303 -- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
304 ghcExtensionKeywordsFM = listToUFM $
305 map (\ (x,y) -> (_PK_ x,y))
306 [ ( "forall", ITforall ),
307 ( "foreign", ITforeign ),
308 ( "export", ITexport ),
309 ( "label", ITlabel ),
310 ( "dynamic", ITdynamic ),
311 ( "safe", ITunsafe ),
312 ( "unsafe", ITunsafe ),
314 ( "stdcall", ITstdcallconv),
315 ( "ccall", ITccallconv),
316 ( "dotnet", ITdotnet),
317 ("_ccall_", ITccall (False, False, PlayRisky)),
318 ("_ccall_GC_", ITccall (False, False, PlaySafe)),
319 ("_casm_", ITccall (False, True, PlayRisky)),
320 ("_casm_GC_", ITccall (False, True, PlaySafe)),
322 -- interface keywords
323 ("__interface", ITinterface),
324 ("__export", IT__export),
325 ("__depends", ITdepends),
326 ("__forall", IT__forall),
327 ("__letrec", ITletrec),
328 ("__coerce", ITcoerce),
329 ("__inline_me", ITinlineMe),
330 ("__inline_call", ITinlineCall),
331 ("__depends", ITdepends),
332 ("__DEFAULT", ITdefaultbranch),
334 ("__integer", ITinteger_lit),
335 ("__float", ITfloat_lit),
336 ("__int64", ITint64_lit),
337 ("__word", ITword_lit),
338 ("__word64", ITword64_lit),
339 ("__rational", ITrational_lit),
340 ("__addr", ITaddr_lit),
341 ("__label", ITlabel_lit),
342 ("__litlit", ITlit_lit),
343 ("__string", ITstring_lit),
346 ("__fuall", ITfuall),
348 ("__P", ITspecialise),
351 ("__D", ITdeprecated),
354 ("__ccall", ITccall (False, False, PlayRisky)),
355 ("__ccall_GC", ITccall (False, False, PlaySafe)),
356 ("__dyn_ccall", ITccall (True, False, PlayRisky)),
357 ("__dyn_ccall_GC", ITccall (True, False, PlaySafe)),
358 ("__casm", ITccall (False, True, PlayRisky)),
359 ("__dyn_casm", ITccall (True, True, PlayRisky)),
360 ("__casm_GC", ITccall (False, True, PlaySafe)),
361 ("__dyn_casm_GC", ITccall (True, True, PlaySafe)),
367 haskellKeySymsFM = listToUFM $
368 map (\ (x,y) -> (_PK_ x,y))
381 ,(".", ITdot) -- sadly, for 'forall a . t'
385 -----------------------------------------------------------------------------
390 - (glaexts) lexing an interface file or -fglasgow-exts
391 - (bol) pointer to beginning of line (for column calculations)
392 - (buf) pointer to beginning of token
393 - (buf) pointer to current char
394 - (atbol) flag indicating whether we're at the beginning of a line
397 lexer :: (Token -> P a) -> P a
398 lexer cont buf s@(PState{
400 glasgow_exts = glaexts,
406 -- first, start a new lexeme and lose all the whitespace
408 tab line bol atbol (stepOverLexeme buf)
410 line = srcLocLine loc
412 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
413 case currentChar# buf of
416 if bufferExhausted (stepOn buf)
417 then cont ITeof buf s'
418 else trace "lexer: misplaced NUL?" $
419 tab y bol atbol (stepOn buf)
421 '\n'# -> let buf' = stepOn buf
422 in tab (y +# 1#) (currentIndex# buf') 1# buf'
424 -- find comments. This got harder in Haskell 98.
425 '-'# -> let trundle n =
426 let next = lookAhead# buf n in
427 if next `eqChar#` '-'# then trundle (n +# 1#)
428 else if is_symbol next || n <# 2#
431 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
434 -- comments and pragmas. We deal with LINE pragmas here,
435 -- and throw out any unrecognised pragmas as comments. Any
436 -- pragmas we know about are dealt with later (after any layout
437 -- processing if necessary).
438 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
439 if lookAhead# buf 2# `eqChar#` '#'# then
440 if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
441 case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
442 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
443 let lexeme = mkFastString -- ToDo: too slow
444 (map toUpper (lexemeToString buf2)) in
445 case lookupUFM pragmaKeywordsFM lexeme of
446 -- ignore RULES pragmas when -fglasgow-exts is off
447 Just ITrules_prag | not (flag glaexts) ->
448 skip_to_end (stepOnBy# buf 2#) s'
450 line_prag skip_to_end buf2 s'
451 Just other -> is_a_token
452 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
455 else skip_to_end (stepOnBy# buf 2#) s'
457 skip_to_end = skipNestedComment (lexer cont)
459 -- special GHC extension: we grok cpp-style #line pragmas
460 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
461 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
462 lookAhead# buf 2# `eqChar#` 'i'# &&
463 lookAhead# buf 3# `eqChar#` 'n'# &&
464 lookAhead# buf 4# `eqChar#` 'e'# = stepOnBy# buf 5#
465 | otherwise = stepOn buf
467 case expandWhile# is_space buf1 of { buf2 ->
468 if is_digit (currentChar# buf2)
469 then line_prag next_line buf2 s'
473 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
475 -- tabs have been expanded beforehand
476 c | is_space c -> tab y bol atbol (stepOn buf)
477 | otherwise -> is_a_token
479 where s' = s{loc = replaceSrcLine loc y,
483 is_a_token | atbol /=# 0# = lexBOL cont buf s'
484 | otherwise = lexToken cont glaexts buf s'
486 -- {-# LINE .. #-} pragmas. yeuch.
487 line_prag cont buf s@PState{loc=loc} =
488 case expandWhile# is_space buf of { buf1 ->
489 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
490 -- subtract one: the line number refers to the *following* line.
491 let real_line = line - 1 in
492 case fromInteger real_line of { i@(I# l) ->
493 -- ToDo, if no filename then we skip the newline.... d'oh
494 case expandWhile# is_space buf2 of { buf3 ->
495 case currentChar# buf3 of
497 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
499 file = lexemeToFastString buf4
500 new_buf = stepOn (stepOverLexeme buf4)
502 if nullFastString file
503 then cont new_buf s{loc = replaceSrcLine loc l}
504 else cont new_buf s{loc = mkSrcLoc file i}
506 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
509 skipNestedComment :: P a -> P a
510 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
512 skipNestedComment' :: SrcLoc -> P a -> P a
513 skipNestedComment' orig_loc cont buf = loop buf
516 case currentChar# buf of
517 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
519 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
521 (skipNestedComment' orig_loc cont)
524 '\n'# -> \ s@PState{loc=loc} ->
525 let buf' = stepOn buf in
526 loop buf' s{loc = incSrcLine loc,
527 bol = currentIndex# buf',
530 -- pass the original SrcLoc to lexError so that the error is
531 -- reported at the line it was originally on, not the line at
532 -- the end of the file.
533 '\NUL'# | bufferExhausted (stepOn buf) ->
534 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
536 _ -> loop (stepOn buf)
538 -- When we are lexing the first token of a line, check whether we need to
539 -- insert virtual semicolons or close braces due to layout.
541 lexBOL :: (Token -> P a) -> P a
542 lexBOL cont buf s@(PState{
544 glasgow_exts = glaexts,
549 if need_close_curly then
550 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
551 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
552 else if need_semi_colon then
553 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
554 cont ITsemi buf s{atbol = 0#}
556 lexToken cont glaexts buf s{atbol = 0#}
558 col = currentIndex# buf -# bol
571 Layout n -> col ==# n
574 lexToken :: (Token -> P a) -> Int# -> P a
575 lexToken cont glaexts buf =
576 -- trace "lexToken" $
577 case currentChar# buf of
579 -- special symbols ----------------------------------------------------
580 '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'#
581 -> cont IToubxparen (setCurrentPos# buf 2#)
583 -> cont IToparen (incLexeme buf)
585 ')'# -> cont ITcparen (incLexeme buf)
586 '['# -> cont ITobrack (incLexeme buf)
587 ']'# -> cont ITcbrack (incLexeme buf)
588 ','# -> cont ITcomma (incLexeme buf)
589 ';'# -> cont ITsemi (incLexeme buf)
590 '}'# -> \ s@PState{context = ctx} ->
592 (_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
593 _ -> lexError "too many '}'s" buf s
594 '|'# -> case lookAhead# buf 1# of
595 '}'# | flag glaexts -> cont ITccurlybar
596 (setCurrentPos# buf 2#)
597 _ -> lex_sym cont (incLexeme buf)
600 '#'# -> case lookAhead# buf 1# of
601 ')'# | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
602 '-'# -> case lookAhead# buf 2# of
603 '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
604 _ -> lex_sym cont (incLexeme buf)
605 _ -> lex_sym cont (incLexeme buf)
607 '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
608 -> lex_cstring cont (setCurrentPos# buf 2#)
610 -> cont ITbackquote (incLexeme buf)
612 '{'# -> -- look for "{-##" special iface pragma
613 case lookAhead# buf 1# of
615 -> cont ITocurlybar (setCurrentPos# buf 2#)
616 '-'# -> case lookAhead# buf 2# of
617 '#'# -> case lookAhead# buf 3# of
621 (\ cont lexeme buf' -> cont (ITpragma lexeme) buf')
623 (stepOnBy# (stepOverLexeme buf) 4#)
624 _ -> lex_prag cont (setCurrentPos# buf 3#)
625 _ -> cont ITocurly (incLexeme buf)
626 _ -> (layoutOff `thenP_` cont ITocurly) (incLexeme buf)
628 -- strings/characters -------------------------------------------------
629 '\"'#{-"-} -> lex_string cont glaexts [] (incLexeme buf)
630 '\''# -> lex_char (char_end cont) glaexts (incLexeme buf)
632 -- strictness and cpr pragmas and __scc treated specially.
633 '_'# | flag glaexts ->
634 case lookAhead# buf 1# of
635 '_'# -> case lookAhead# buf 2# of
637 lex_demand cont (stepOnUntil (not . isSpace)
638 (stepOnBy# buf 3#)) -- past __S
640 cont ITcprinfo (stepOnBy# buf 3#) -- past __M
643 case prefixMatch (stepOnBy# buf 3#) "cc" of
644 Just buf' -> lex_scc cont (stepOverLexeme buf')
645 Nothing -> lex_id cont glaexts buf
646 _ -> lex_id cont glaexts buf
647 _ -> lex_id cont glaexts buf
649 -- Hexadecimal and octal constants
650 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
651 -> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
652 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
653 -> readNum (after_lexnum cont glaexts) buf' is_octdigit 8 oct_or_dec
654 where ch = lookAhead# buf 1#
655 ch2 = lookAhead# buf 2#
656 buf' = setCurrentPos# buf 2#
659 if bufferExhausted (stepOn buf) then
662 trace "lexIface: misplaced NUL?" $
663 cont (ITunknown "\NUL") (stepOn buf)
665 '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
666 lex_ip ITdupipvarid cont (incLexeme buf)
667 '%'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
668 lex_ip ITsplitipvarid cont (incLexeme buf)
669 c | is_digit c -> lex_num cont glaexts 0 buf
670 | is_symbol c -> lex_sym cont buf
671 | is_upper c -> lex_con cont glaexts buf
672 | is_ident c -> lex_id cont glaexts buf
673 | otherwise -> lexError "illegal character" buf
675 -- Int# is unlifted, and therefore faster than Bool for flags.
681 -------------------------------------------------------------------------------
685 = case expandWhile# is_space buf of { buf1 ->
686 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
687 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
688 case lookupUFM pragmaKeywordsFM lexeme of
689 Just kw -> cont kw (mergeLexemes buf buf2)
690 Nothing -> panic "lex_prag"
693 -------------------------------------------------------------------------------
696 lex_string cont glaexts s buf
697 = case currentChar# buf of
699 let buf' = incLexeme buf
700 s' = mkFastStringNarrow (map chr (reverse s))
701 in case currentChar# buf' of
702 '#'# | flag glaexts -> if all (<= 0xFF) s
703 then cont (ITprimstring s') (incLexeme buf')
704 else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
705 _ -> cont (ITstring s') buf'
707 -- ignore \& in a string, deal with string gaps
708 '\\'# | next_ch `eqChar#` '&'#
709 -> lex_string cont glaexts s buf'
711 -> lex_stringgap cont glaexts s (incLexeme buf)
713 where next_ch = lookAhead# buf 1#
714 buf' = setCurrentPos# buf 2#
716 _ -> lex_char (lex_next_string cont s) glaexts buf
718 lex_stringgap cont glaexts s buf
719 = let buf' = incLexeme buf in
720 case currentChar# buf of
721 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf'
722 st{loc = incSrcLine loc}
723 '\\'# -> lex_string cont glaexts s buf'
724 c | is_space c -> lex_stringgap cont glaexts s buf'
725 other -> charError buf'
727 lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf
729 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
730 lex_char cont glaexts buf
731 = case currentChar# buf of
732 '\\'# -> lex_escape (cont glaexts) (incLexeme buf)
733 c | is_any c -> cont glaexts (I# (ord# c)) (incLexeme buf)
734 other -> charError buf
736 char_end cont glaexts c buf
737 = case currentChar# buf of
738 '\''# -> let buf' = incLexeme buf in
739 case currentChar# buf' of
741 -> cont (ITprimchar c) (incLexeme buf')
742 _ -> cont (ITchar c) buf'
746 = let buf' = incLexeme buf in
747 case currentChar# buf of
748 'a'# -> cont (ord '\a') buf'
749 'b'# -> cont (ord '\b') buf'
750 'f'# -> cont (ord '\f') buf'
751 'n'# -> cont (ord '\n') buf'
752 'r'# -> cont (ord '\r') buf'
753 't'# -> cont (ord '\t') buf'
754 'v'# -> cont (ord '\v') buf'
755 '\\'# -> cont (ord '\\') buf'
756 '"'# -> cont (ord '\"') buf'
757 '\''# -> cont (ord '\'') buf'
758 '^'# -> let c = currentChar# buf' in
759 if c `geChar#` '@'# && c `leChar#` '_'#
760 then cont (I# (ord# c -# ord# '@'#)) (incLexeme buf')
763 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
764 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
766 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
768 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
769 Just buf2 <- [prefixMatch buf p] ] of
770 (c,buf2):_ -> cont (ord c) buf2
773 after_charnum cont i buf
774 = if i >= 0 && i <= 0x10FFFF
775 then cont (fromInteger i) buf
778 readNum cont buf is_digit base conv = read buf 0
780 = case currentChar# buf of { c ->
782 then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
788 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
789 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
791 hex c | is_digit c = ord# c -# ord# '0'#
792 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
793 oct_or_dec c = ord# c -# ord# '0'#
795 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
798 | c `geChar#` 'A'# && c `leChar#` 'Z'#
799 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
802 charError buf = lexError "error in character literal" buf
804 silly_escape_chars = [
841 -------------------------------------------------------------------------------
843 lex_demand cont buf =
844 case read_em [] buf of { (ls,buf') ->
845 case currentChar# buf' of
846 'b'# -> cont (ITstrict (StrictSig (mkTopDmdType ls BotRes))) (incLexeme buf')
847 'm'# -> cont (ITstrict (StrictSig (mkTopDmdType ls RetCPR))) (incLexeme buf')
848 _ -> cont (ITstrict (StrictSig (mkTopDmdType ls TopRes))) buf'
852 case currentChar# buf of
853 'T'# -> read_em (Top : acc) (stepOn buf)
854 'L'# -> read_em (lazyDmd : acc) (stepOn buf)
855 'A'# -> read_em (Abs : acc) (stepOn buf)
856 'V'# -> read_em (evalDmd : acc) (stepOn buf) -- Temporary, until
857 -- we've recompiled prelude etc
858 'C'# -> do_unary Call acc (stepOnBy# buf 2#) -- Skip 'C('
860 'U'# -> do_seq1 Eval acc (stepOnBy# buf 1#)
861 'D'# -> do_seq1 Defer acc (stepOnBy# buf 1#)
862 'S'# -> do_seq1 (Box . Eval) acc (stepOnBy# buf 1#)
864 _ -> (reverse acc, buf)
867 = case currentChar# buf of
868 '('# -> do_seq2 fn acc (stepOnBy# buf 1#)
869 _ -> read_em (fn (Poly Abs) : acc) buf
872 = case read_em [] buf of { (dmds, buf) ->
873 case currentChar# buf of
874 ')'# -> read_em (fn (Prod dmds) : acc)
876 '*'# -> ASSERT( length dmds == 1 )
877 read_em (fn (Poly (head dmds)) : acc)
878 (stepOnBy# buf 2#) -- Skip '*)'
882 = case read_em [] buf of
883 ([dmd], rest) -> read_em (fn dmd : acc) (stepOn rest) -- Skip ')'
887 case currentChar# buf of
888 'C'# -> cont ITsccAllCafs (incLexeme buf)
889 other -> cont ITscc buf
891 -----------------------------------------------------------------------------
894 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
895 lex_num cont glaexts acc buf =
896 case scanNumLit acc buf of
898 case currentChar# buf' of
899 '.'# | is_digit (lookAhead# buf' 1#) ->
900 -- this case is not optimised at all, as the
901 -- presence of floating point numbers in interface
902 -- files is not that common. (ToDo)
903 case expandWhile# is_digit (incLexeme buf') of
904 buf2 -> -- points to first non digit char
906 let l = case currentChar# buf2 of
912 = let buf3 = incLexeme buf2 in
913 case currentChar# buf3 of
914 '-'# -> expandWhile# is_digit (incLexeme buf3)
915 '+'# -> expandWhile# is_digit (incLexeme buf3)
916 x | is_digit x -> expandWhile# is_digit buf3
919 v = readRational__ (lexemeToString l)
921 in case currentChar# l of -- glasgow exts only
922 '#'# | flag glaexts -> let l' = incLexeme l in
923 case currentChar# l' of
924 '#'# -> cont (ITprimdouble v) (incLexeme l')
925 _ -> cont (ITprimfloat v) l'
926 _ -> cont (ITrational v) l
928 _ -> after_lexnum cont glaexts acc' buf'
930 after_lexnum cont glaexts i buf
931 = case currentChar# buf of
932 '#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
933 _ -> cont (ITinteger i) buf
935 -----------------------------------------------------------------------------
936 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
938 -- we lexemeToFastString on the bit between the ``''s, but include the
939 -- quotes in the full lexeme.
941 lex_cstring cont buf =
942 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
943 Just buf' -> cont (ITlitlit (lexemeToFastString
944 (setCurrentPos# buf' (negateInt# 2#))))
945 (mergeLexemes buf buf')
946 Nothing -> lexError "unterminated ``" buf
948 -----------------------------------------------------------------------------
949 -- identifiers, symbols etc.
951 lex_ip ip_constr cont buf =
952 case expandWhile# is_ident buf of
953 buf' -> cont (ip_constr (tailFS lexeme)) buf'
954 where lexeme = lexemeToFastString buf'
956 lex_id cont glaexts buf =
957 let buf1 = expandWhile# is_ident buf in
960 case (if flag glaexts
961 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
962 else buf1) of { buf' ->
964 let lexeme = lexemeToFastString buf' in
966 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
967 Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
971 let var_token = cont (ITvarid lexeme) buf' in
973 if not (flag glaexts)
977 case lookupUFM ghcExtensionKeywordsFM lexeme of {
978 Just kwd_token -> cont kwd_token buf';
985 case expandWhile# is_symbol buf of
986 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
987 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
988 cont kwd_token buf' ;
989 Nothing -> --trace ("sym: "++unpackFS lexeme) $
990 cont (mk_var_token lexeme) buf'
992 where lexeme = lexemeToFastString buf'
995 -- lex_con recursively collects components of a qualified identifer.
996 -- The argument buf is the StringBuffer representing the lexeme
997 -- identified so far, where the next character is upper-case.
999 lex_con cont glaexts buf =
1000 -- trace ("con: "{-++unpackFS lexeme-}) $
1001 let empty_buf = stepOverLexeme buf in
1002 case expandWhile# is_ident empty_buf of { buf1 ->
1003 case slurp_trailing_hashes buf1 glaexts of { con_buf ->
1005 let all_buf = mergeLexemes buf con_buf
1007 con_lexeme = lexemeToFastString con_buf
1008 mod_lexeme = lexemeToFastString (decLexeme buf)
1009 all_lexeme = lexemeToFastString all_buf
1012 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
1013 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
1016 case currentChar# all_buf of
1017 '.'# -> maybe_qualified cont glaexts all_lexeme
1018 (incLexeme all_buf) just_a_conid
1023 maybe_qualified cont glaexts mod buf just_a_conid =
1024 -- trace ("qid: "{-++unpackFS lexeme-}) $
1025 case currentChar# buf of
1026 '['# -> -- Special case for []
1027 case lookAhead# buf 1# of
1028 ']'# -> cont (ITqconid (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
1031 '('# -> -- Special case for (,,,)
1032 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1033 case lookAhead# buf 1# of
1034 '#'# | flag glaexts -> case lookAhead# buf 2# of
1035 ','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#)
1038 ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
1039 ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
1042 '-'# -> case lookAhead# buf 1# of
1043 '>'# -> cont (ITqconid (mod,SLIT("(->)"))) (setCurrentPos# buf 2#)
1044 _ -> lex_id3 cont glaexts mod buf just_a_conid
1046 _ -> lex_id3 cont glaexts mod buf just_a_conid
1049 lex_id3 cont glaexts mod buf just_a_conid
1050 | is_upper (currentChar# buf) =
1051 lex_con cont glaexts buf
1053 | is_symbol (currentChar# buf) =
1055 start_new_lexeme = stepOverLexeme buf
1057 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1058 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1060 lexeme = lexemeToFastString buf'
1061 -- real lexeme is M.<sym>
1062 new_buf = mergeLexemes buf buf'
1064 cont (mk_qvar_token mod lexeme) new_buf
1065 -- wrong, but arguably morally right: M... is now a qvarsym
1070 start_new_lexeme = stepOverLexeme buf
1072 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1073 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1078 case slurp_trailing_hashes buf1 glaexts of { buf' ->
1081 lexeme = lexemeToFastString buf'
1082 new_buf = mergeLexemes buf buf'
1083 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1085 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1086 Nothing -> is_a_qvarid ;
1088 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1089 -> is_a_qvarid -- recognised as keywords here.
1091 -> just_a_conid -- avoid M.where etc.
1094 slurp_trailing_hashes buf glaexts
1095 | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
1100 | is_upper f = ITconid pk_str
1101 | is_ident f = ITvarid pk_str
1102 | f `eqChar#` ':'# = ITconsym pk_str
1103 | otherwise = ITvarsym pk_str
1105 (C# f) = _HEAD_ pk_str
1106 -- tl = _TAIL_ pk_str
1108 mk_qvar_token m token =
1109 -- trace ("mk_qvar ") $
1110 case mk_var_token token of
1111 ITconid n -> ITqconid (m,n)
1112 ITvarid n -> ITqvarid (m,n)
1113 ITconsym n -> ITqconsym (m,n)
1114 ITvarsym n -> ITqvarsym (m,n)
1115 _ -> ITunknown (show token)
1118 ----------------------------------------------------------------------------
1119 Horrible stuff for dealing with M.(,,,)
1122 lex_tuple cont mod buf back_off =
1126 case currentChar# buf of
1127 ','# -> go (n+1) (stepOn buf)
1128 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1131 lex_ubx_tuple cont mod buf back_off =
1135 case currentChar# buf of
1136 ','# -> go (n+1) (stepOn buf)
1137 '#'# -> case lookAhead# buf 1# of
1138 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1144 -----------------------------------------------------------------------------
1145 'lexPragma' rips along really fast, looking for a '##-}',
1146 indicating the end of the pragma we're skipping
1149 lexPragma cont contf inStr buf =
1150 case currentChar# buf of
1151 '#'# | inStr ==# 0# ->
1152 case lookAhead# buf 1# of { '#'# ->
1153 case lookAhead# buf 2# of { '-'# ->
1154 case lookAhead# buf 3# of { '}'# ->
1155 contf cont (lexemeToBuffer buf)
1156 (stepOverLexeme (setCurrentPos# buf 4#));
1157 _ -> lexPragma cont contf inStr (incLexeme buf) };
1158 _ -> lexPragma cont contf inStr (incLexeme buf) };
1159 _ -> lexPragma cont contf inStr (incLexeme buf) }
1163 odd_slashes buf flg i# =
1164 case lookAhead# buf i# of
1165 '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
1168 not_inStr = if inStr ==# 0# then 1# else 0#
1170 case lookAhead# buf (negateInt# 1#) of --backwards, actually
1171 '\\'# -> -- escaping something..
1172 if odd_slashes buf True (negateInt# 2#)
1173 then -- odd number of slashes, " is escaped.
1174 lexPragma cont contf inStr (incLexeme buf)
1175 else -- even number of slashes, \ is escaped.
1176 lexPragma cont contf not_inStr (incLexeme buf)
1177 _ -> lexPragma cont contf not_inStr (incLexeme buf)
1179 '\''# | inStr ==# 0# ->
1180 case lookAhead# buf 1# of { '"'# ->
1181 case lookAhead# buf 2# of { '\''# ->
1182 lexPragma cont contf inStr (setCurrentPos# buf 3#);
1183 _ -> lexPragma cont contf inStr (incLexeme buf) };
1184 _ -> lexPragma cont contf inStr (incLexeme buf) }
1186 -- a sign that the input is ill-formed, since pragmas are
1187 -- assumed to always be properly closed (in .hi files).
1188 '\NUL'# -> trace "lexPragma: unexpected end-of-file" $
1189 cont (ITunknown "\NUL") buf
1191 _ -> lexPragma cont contf inStr (incLexeme buf)
1195 -----------------------------------------------------------------------------
1206 data PState = PState {
1208 glasgow_exts :: Int#,
1211 context :: [LayoutContext]
1214 type P a = StringBuffer -- Input string
1219 returnP a buf s = POk s a
1221 thenP :: P a -> (a -> P b) -> P b
1222 m `thenP` k = \ buf s ->
1224 POk s1 a -> k a buf s1
1225 PFailed err -> PFailed err
1227 thenP_ :: P a -> P b -> P b
1228 m `thenP_` k = m `thenP` \_ -> k
1230 mapP :: (a -> P b) -> [a] -> P [b]
1231 mapP f [] = returnP []
1234 mapP f as `thenP` \bs ->
1237 failP :: String -> P a
1238 failP msg buf s = PFailed (text msg)
1240 failMsgP :: Message -> P a
1241 failMsgP msg buf s = PFailed msg
1243 lexError :: String -> P a
1244 lexError str buf s@PState{ loc = loc }
1245 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1247 getSrcLocP :: P SrcLoc
1248 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1250 -- use a temporary SrcLoc for the duration of the argument
1251 setSrcLocP :: SrcLoc -> P a -> P a
1252 setSrcLocP new_loc p buf s =
1253 case p buf s{ loc=new_loc } of
1255 PFailed e -> PFailed e
1257 getSrcFile :: P FAST_STRING
1258 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1260 pushContext :: LayoutContext -> P ()
1261 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1265 This special case in layoutOn is to handle layout contexts with are
1266 indented the same or less than the current context. This is illegal
1267 according to the Haskell spec, so we have to arrange to close the
1268 current context. eg.
1273 after the first 'where', the sequence of events is:
1275 - layout system inserts a ';' (column 0)
1276 - parser begins a new context at column 0
1277 - parser shifts ';' (legal empty declaration)
1278 - parser sees 'class': parse error (we're still in the inner context)
1280 trouble is, by the time we know we need a new context, the lexer has
1281 already generated the ';'. Hacky solution is as follows: since we
1282 know the column of the next token (it's the column number of the new
1283 context), we set the ACTUAL column number of the new context to this
1284 numer plus one. Hence the next time the lexer is called, a '}' will
1285 be generated to close the new context straight away. Furthermore, we
1286 have to set the atbol flag so that the ';' that the parser shifted as
1287 part of the new context is re-generated.
1289 when the new context is *less* indented than the current one:
1291 f = f where g = g where
1294 - current context: column 12.
1295 - on seeing 'h' (column 0), the layout system inserts '}'
1296 - parser starts a new context, column 0
1297 - parser sees '}', uses it to close new context
1298 - we still need to insert another '}' followed by a ';',
1299 hence the atbol trick.
1301 There's also a special hack in here to deal with
1308 i.e. the inner context is at the same indentation level as the outer
1309 context. This is strictly illegal according to Haskell 98, but
1310 there's a lot of existing code using this style and it doesn't make
1311 any sense to disallow it, since empty 'do' lists don't make sense.
1314 layoutOn :: Bool -> P ()
1315 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1316 let offset = lexemeIndex buf -# bol in
1319 | if strict then prev_off >=# offset else prev_off ># offset ->
1320 --trace ("layout on, column: " ++ show (I# offset)) $
1321 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1323 --trace ("layout on, column: " ++ show (I# offset)) $
1324 POk s{ context = Layout offset : ctx } ()
1327 layoutOff buf s@(PState{ context = ctx }) =
1328 POk s{ context = NoLayout:ctx } ()
1331 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1333 (_:tl) -> POk s{ context = tl } ()
1334 [] -> PFailed (srcParseErr buf loc)
1337 Note that if the name of the file we're processing ends
1338 with `hi-boot', we accept it on faith as having the right
1339 version. This is done so that .hi-boot files that comes
1340 with hsc don't have to be updated before every release,
1341 *and* it allows us to share .hi-boot files with versions
1342 of hsc that don't have .hi version checking (e.g., ghc-2.10's)
1344 If the version number is 0, the checking is also turned off.
1345 (needed to deal with GHC.hi only!)
1347 Once we can assume we're compiling with a version of ghc that
1348 supports interface file checking, we can drop the special
1351 checkVersion :: Maybe Integer -> P ()
1352 checkVersion mb@(Just v) buf s@(PState{loc = loc})
1353 | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
1354 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1355 checkVersion mb@Nothing buf s@(PState{loc = loc})
1356 | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
1357 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1359 -----------------------------------------------------------------
1361 ifaceParseErr :: StringBuffer -> SrcLoc -> Message
1363 = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
1364 text (lexemeToString s), char '\'']
1366 ifaceVersionErr hi_vers l toks
1367 = hsep [ppr l, ptext SLIT("Interface file version error;"),
1368 ptext SLIT("Expected"), int opt_HiVersion,
1369 ptext SLIT("found "), pp_version]
1373 Nothing -> ptext SLIT("pre ghc-3.02 version")
1374 Just v -> ptext SLIT("version") <+> integer v
1376 -----------------------------------------------------------------------------
1378 srcParseErr :: StringBuffer -> SrcLoc -> Message
1382 then ptext SLIT(": parse error (possibly incorrect indentation)")
1383 else hcat [ptext SLIT(": parse error on input "),
1384 char '`', text token, char '\'']
1387 token = lexemeToString s