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, getSrcFile,
31 layoutOn, layoutOff, pushContext, popContext
34 #include "HsVersions.h"
36 import Char ( ord, isSpace, toUpper )
37 import List ( isSuffixOf )
39 import IdInfo ( InlinePragInfo(..), CprInfo(..) )
40 import Name ( isLowerISO, isUpperISO )
41 import PrelMods ( mkTupNameStr, mkUbxTupNameStr )
42 import CmdLineOpts ( opt_IgnoreIfacePragmas, opt_HiVersion, opt_NoHiCheck )
43 import Demand ( Demand(..) {- instance Read -} )
44 import UniqFM ( UniqFM, listToUFM, lookupUFM)
45 import BasicTypes ( NewOrData(..) )
46 import SrcLoc ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
47 replaceSrcLine, mkSrcLoc )
49 import Maybes ( MaybeErr(..) )
50 import ErrUtils ( Message )
60 import PrelRead ( readRational__ ) -- Glasgow non-std
63 %************************************************************************
65 \subsection{Data types}
67 %************************************************************************
69 The token data type, fairly un-interesting except from one
70 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
71 strictness, unfolding etc).
73 The Idea/Observation here is that the renamer needs to scan through
74 all of an interface file before it can continue. But only a fraction
75 of the information contained in the file turns out to be useful, so
76 delaying as much as possible of the scanning and parsing of an
77 interface file Makes Sense (Heap profiles of the compiler
78 show a reduction in heap usage by at least a factor of two,
81 Hence, the interface file lexer spots when value declarations are
82 being scanned and return the @ITidinfo@ and @ITtype@ constructors
83 for the type and any other id info for that binding (unfolding, strictness
84 etc). These constructors are applied to the result of lexing these sub-chunks.
86 The lexing of the type and id info is all done lazily, of course, so
87 the scanning (and subsequent parsing) will be done *only* on the ids the
88 renamer finds out that it is interested in. The rest will just be junked.
89 Laziness, you know it makes sense :-)
93 = ITas -- Haskell keywords
119 | ITforall -- GHC extension keywords
129 | ITinterface -- interface keywords
137 | ITccall (Bool,Bool,Bool) -- (is_dyn, is_casm, may_gc)
155 | ITunfold InlinePragInfo
156 | ITstrict ([Demand], Bool)
163 | ITspecialise_prag -- Pragmas
172 | ITdotdot -- reserved symbols
186 | ITbiglam -- GHC-extension symbols
188 | ITocurly -- special symbols
202 | ITvarid FAST_STRING -- identifiers
203 | ITconid FAST_STRING
204 | ITvarsym FAST_STRING
205 | ITconsym FAST_STRING
206 | ITqvarid (FAST_STRING,FAST_STRING)
207 | ITqconid (FAST_STRING,FAST_STRING)
208 | ITqvarsym (FAST_STRING,FAST_STRING)
209 | ITqconsym (FAST_STRING,FAST_STRING)
211 | ITipvarid FAST_STRING -- GHC extension: implicit param: ?x
213 | ITpragma StringBuffer
216 | ITstring FAST_STRING
218 | ITrational Rational
221 | ITprimstring FAST_STRING
223 | ITprimfloat Rational
224 | ITprimdouble Rational
225 | ITlitlit FAST_STRING
227 | ITunknown String -- Used when the lexer can't make sense of it
228 | ITeof -- end of file token
229 deriving Show -- debugging
232 -----------------------------------------------------------------------------
236 pragmaKeywordsFM = listToUFM $
237 map (\ (x,y) -> (_PK_ x,y))
238 [( "SPECIALISE", ITspecialise_prag ),
239 ( "SPECIALIZE", ITspecialise_prag ),
240 ( "SOURCE", ITsource_prag ),
241 ( "INLINE", ITinline_prag ),
242 ( "NOINLINE", ITnoinline_prag ),
243 ( "NOTINLINE", ITnoinline_prag ),
244 ( "LINE", ITline_prag ),
245 ( "RULES", ITrules_prag ),
246 ( "RULEZ", ITrules_prag ), -- american spelling :-)
247 ( "DEPRECATED", ITdeprecated_prag )
250 haskellKeywordsFM = listToUFM $
251 map (\ (x,y) -> (_PK_ x,y))
252 [( "_", ITunderscore ),
255 ( "class", ITclass ),
257 ( "default", ITdefault ),
258 ( "deriving", ITderiving ),
261 ( "hiding", IThiding ),
263 ( "import", ITimport ),
265 ( "infix", ITinfix ),
266 ( "infixl", ITinfixl ),
267 ( "infixr", ITinfixr ),
268 ( "instance", ITinstance ),
270 ( "module", ITmodule ),
271 ( "newtype", ITnewtype ),
273 ( "qualified", ITqualified ),
276 ( "where", ITwhere ),
280 -- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
281 ghcExtensionKeywordsFM = listToUFM $
282 map (\ (x,y) -> (_PK_ x,y))
283 [ ( "forall", ITforall ),
284 ( "foreign", ITforeign ),
285 ( "export", ITexport ),
286 ( "label", ITlabel ),
287 ( "dynamic", ITdynamic ),
288 ( "unsafe", ITunsafe ),
290 ( "stdcall", ITstdcallconv),
291 ( "ccall", ITccallconv),
292 ("_ccall_", ITccall (False, False, False)),
293 ("_ccall_GC_", ITccall (False, False, True)),
294 ("_casm_", ITccall (False, True, False)),
295 ("_casm_GC_", ITccall (False, True, True)),
297 -- interface keywords
298 ("__interface", ITinterface),
299 ("__export", IT__export),
300 ("__depends", ITdepends),
301 ("__forall", IT__forall),
302 ("__letrec", ITletrec),
303 ("__coerce", ITcoerce),
304 ("__inline_me", ITinlineMe),
305 ("__inline_call", ITinlineCall),
306 ("__depends", ITdepends),
307 ("__DEFAULT", ITdefaultbranch),
309 ("__integer", ITinteger_lit),
310 ("__float", ITfloat_lit),
311 ("__int64", ITint64_lit),
312 ("__word", ITword_lit),
313 ("__word64", ITword64_lit),
314 ("__rational", ITrational_lit),
315 ("__addr", ITaddr_lit),
316 ("__litlit", ITlit_lit),
317 ("__string", ITstring_lit),
320 ("__fuall", ITfuall),
322 ("__P", ITspecialise),
325 ("__D", ITdeprecated),
326 ("__U", ITunfold NoInlinePragInfo),
328 ("__ccall", ITccall (False, False, False)),
329 ("__ccall_GC", ITccall (False, False, True)),
330 ("__dyn_ccall", ITccall (True, False, False)),
331 ("__dyn_ccall_GC", ITccall (True, False, True)),
332 ("__casm", ITccall (False, True, False)),
333 ("__dyn_casm", ITccall (True, True, False)),
334 ("__casm_GC", ITccall (False, True, True)),
335 ("__dyn_casm_GC", ITccall (True, True, True)),
341 haskellKeySymsFM = listToUFM $
342 map (\ (x,y) -> (_PK_ x,y))
355 ,(".", ITdot) -- sadly, for 'forall a . t'
359 -----------------------------------------------------------------------------
364 - (glaexts) lexing an interface file or -fglasgow-exts
365 - (bol) pointer to beginning of line (for column calculations)
366 - (buf) pointer to beginning of token
367 - (buf) pointer to current char
368 - (atbol) flag indicating whether we're at the beginning of a line
371 lexer :: (Token -> P a) -> P a
372 lexer cont buf s@(PState{
374 glasgow_exts = glaexts,
380 -- first, start a new lexeme and lose all the whitespace
382 tab line bol atbol (stepOverLexeme buf)
384 line = srcLocLine loc
386 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
387 case currentChar# buf of
390 if bufferExhausted (stepOn buf)
391 then cont ITeof buf s'
392 else trace "lexer: misplaced NUL?" $
393 tab y bol atbol (stepOn buf)
395 '\n'# -> let buf' = stepOn buf
396 in tab (y +# 1#) (currentIndex# buf') 1# buf'
398 -- find comments. This got harder in Haskell 98.
399 '-'# -> let trundle n =
400 let next = lookAhead# buf n in
401 if next `eqChar#` '-'# then trundle (n +# 1#)
402 else if is_symbol next || n <# 2#
404 else case untilChar# (stepOnBy# buf n) '\n'# of
405 { buf' -> tab y bol atbol (stepOverLexeme buf')
409 -- comments and pragmas. We deal with LINE pragmas here,
410 -- and throw out any unrecognised pragmas as comments. Any
411 -- pragmas we know about are dealt with later (after any layout
412 -- processing if necessary).
414 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
415 if lookAhead# buf 2# `eqChar#` '#'# then
416 if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
417 case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
418 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
419 let lexeme = mkFastString -- ToDo: too slow
420 (map toUpper (lexemeToString buf2)) in
421 case lookupUFM pragmaKeywordsFM lexeme of
422 Just ITline_prag -> line_prag (lexer cont) buf2 s'
423 Just other -> is_a_token
424 Nothing -> skip_to_end (stepOnBy# buf 2#)
427 else skip_to_end (stepOnBy# buf 2#)
429 skip_to_end buf = nested_comment (lexer cont) buf s'
431 -- tabs have been expanded beforehand
432 c | is_space c -> tab y bol atbol (stepOn buf)
433 | otherwise -> is_a_token
435 where s' = s{loc = replaceSrcLine loc y,
439 is_a_token | atbol /=# 0# = lexBOL cont buf s'
440 | otherwise = lexToken cont glaexts buf s'
442 -- {-# LINE .. #-} pragmas. yeuch.
444 case expandWhile# is_space buf of { buf1 ->
445 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
446 -- subtract one: the line number refers to the *following* line.
447 let real_line = line - 1 in
448 case fromInteger real_line of { i@(I# l) ->
449 case expandWhile# is_space buf2 of { buf3 ->
450 case currentChar# buf3 of
452 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
453 let file = lexemeToFastString buf4 in
454 \s@PState{loc=loc} -> skipToEnd buf4 s{loc = mkSrcLoc file i}
456 other -> \s@PState{loc=loc} -> skipToEnd buf3 s{loc = replaceSrcLine loc l}
459 skipToEnd buf = nested_comment cont buf
461 nested_comment :: P a -> P a
462 nested_comment cont buf = loop buf
465 case currentChar# buf of
466 '\NUL'# | bufferExhausted (stepOn buf) ->
467 lexError "unterminated `{-'" buf
469 '-'# | lookAhead# buf 1# `eqChar#` '}'# ->
470 cont (stepOnBy# buf 2#)
472 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
473 nested_comment (nested_comment cont) (stepOnBy# buf 2#)
475 '\n'# -> \ s@PState{loc=loc} ->
476 let buf' = stepOn buf in
477 nested_comment cont buf'
478 s{loc = incSrcLine loc, bol = currentIndex# buf',
481 _ -> nested_comment cont (stepOn buf)
483 -- When we are lexing the first token of a line, check whether we need to
484 -- insert virtual semicolons or close braces due to layout.
486 lexBOL :: (Token -> P a) -> P a
487 lexBOL cont buf s@(PState{
489 glasgow_exts = glaexts,
494 if need_close_curly then
495 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
496 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
497 else if need_semi_colon then
498 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
499 cont ITsemi buf s{atbol = 0#}
501 lexToken cont glaexts buf s{atbol = 0#}
503 col = currentIndex# buf -# bol
516 Layout n -> col ==# n
519 lexToken :: (Token -> P a) -> Int# -> P a
520 lexToken cont glaexts buf =
522 case currentChar# buf of
524 -- special symbols ----------------------------------------------------
525 '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'#
526 -> cont IToubxparen (setCurrentPos# buf 2#)
528 -> cont IToparen (incLexeme buf)
530 ')'# -> cont ITcparen (incLexeme buf)
531 '['# -> cont ITobrack (incLexeme buf)
532 ']'# -> cont ITcbrack (incLexeme buf)
533 ','# -> cont ITcomma (incLexeme buf)
534 ';'# -> cont ITsemi (incLexeme buf)
536 '}'# -> \ s@PState{context = ctx} ->
538 (_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
539 _ -> lexError "too many '}'s" buf s
541 '#'# -> case lookAhead# buf 1# of
542 ')'# | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
543 '-'# -> case lookAhead# buf 2# of
544 '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
545 _ -> lex_sym cont (incLexeme buf)
546 _ -> lex_sym cont (incLexeme buf)
548 '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
549 -> lex_cstring cont (setCurrentPos# buf 2#)
551 -> cont ITbackquote (incLexeme buf)
553 '{'# -> -- look for "{-##" special iface pragma
554 case lookAhead# buf 1# of
555 '-'# -> case lookAhead# buf 2# of
556 '#'# -> case lookAhead# buf 3# of
559 = doDiscard False (stepOnBy# (stepOverLexeme buf) 4#) in
560 cont (ITpragma lexeme) buf'
561 _ -> lex_prag cont (setCurrentPos# buf 3#)
562 _ -> cont ITocurly (incLexeme buf)
563 _ -> (layoutOff `thenP_` cont ITocurly) (incLexeme buf)
565 -- strings/characters -------------------------------------------------
566 '\"'#{-"-} -> lex_string cont glaexts "" (incLexeme buf)
567 '\''# -> lex_char (char_end cont) glaexts (incLexeme buf)
569 -- strictness and cpr pragmas and __scc treated specially.
570 '_'# | flag glaexts ->
571 case lookAhead# buf 1# of
572 '_'# -> case lookAhead# buf 2# of
574 lex_demand cont (stepOnUntil (not . isSpace)
575 (stepOnBy# buf 3#)) -- past __S
577 cont ITcprinfo (stepOnBy# buf 3#) -- past __M
580 case prefixMatch (stepOnBy# buf 3#) "cc" of
581 Just buf' -> lex_scc cont (stepOverLexeme buf')
582 Nothing -> lex_id cont glaexts buf
583 _ -> lex_id cont glaexts buf
584 _ -> lex_id cont glaexts buf
586 -- Hexadecimal and octal constants
587 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
588 -> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
589 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
590 -> readNum (after_lexnum cont glaexts) buf' is_octdigit 8 oct_or_dec
591 where ch = lookAhead# buf 1#
592 ch2 = lookAhead# buf 2#
593 buf' = setCurrentPos# buf 2#
596 if bufferExhausted (stepOn buf) then
599 trace "lexIface: misplaced NUL?" $
600 cont (ITunknown "\NUL") (stepOn buf)
602 '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
603 lex_ip cont (incLexeme buf)
604 c | is_digit c -> lex_num cont glaexts 0 buf
605 | is_symbol c -> lex_sym cont buf
606 | is_upper c -> lex_con cont glaexts buf
607 | is_ident c -> lex_id cont glaexts buf
608 | otherwise -> lexError "illegal character" buf
610 -- Int# is unlifted, and therefore faster than Bool for flags.
616 -------------------------------------------------------------------------------
620 = case expandWhile# is_space buf of { buf1 ->
621 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
622 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
623 case lookupUFM pragmaKeywordsFM lexeme of
624 Just kw -> cont kw (mergeLexemes buf buf2)
625 Nothing -> panic "lex_prag"
628 -------------------------------------------------------------------------------
631 lex_string cont glaexts s buf
632 = case currentChar# buf of
634 let buf' = incLexeme buf; s' = mkFastString (reverse s) in
635 case currentChar# buf' of
636 '#'# | flag glaexts -> cont (ITprimstring s') (incLexeme buf')
637 _ -> cont (ITstring s') buf'
639 -- ignore \& in a string, deal with string gaps
640 '\\'# | next_ch `eqChar#` '&'#
641 -> lex_string cont glaexts s buf'
643 -> lex_stringgap cont glaexts s (incLexeme buf)
645 where next_ch = lookAhead# buf 1#
646 buf' = setCurrentPos# buf 2#
648 _ -> lex_char (lex_next_string cont s) glaexts buf
650 lex_stringgap cont glaexts s buf
651 = let buf' = incLexeme buf in
652 case currentChar# buf of
653 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf'
654 st{loc = incSrcLine loc}
655 '\\'# -> lex_string cont glaexts s buf'
656 c | is_space c -> lex_stringgap cont glaexts s buf'
657 other -> charError buf'
659 lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf
661 lex_char :: (Int# -> Char -> P a) -> Int# -> P a
662 lex_char cont glaexts buf
663 = case currentChar# buf of
664 '\\'# -> lex_escape (cont glaexts) (incLexeme buf)
665 c | is_any c -> cont glaexts (C# c) (incLexeme buf)
666 other -> charError buf
668 char_end cont glaexts c buf
669 = case currentChar# buf of
670 '\''# -> let buf' = incLexeme buf in
671 case currentChar# buf' of
673 -> cont (ITprimchar c) (incLexeme buf')
674 _ -> cont (ITchar c) buf'
678 = let buf' = incLexeme buf in
679 case currentChar# buf of
680 'a'# -> cont '\a' buf'
681 'b'# -> cont '\b' buf'
682 'f'# -> cont '\f' buf'
683 'n'# -> cont '\n' buf'
684 'r'# -> cont '\r' buf'
685 't'# -> cont '\t' buf'
686 'v'# -> cont '\v' buf'
687 '\\'# -> cont '\\' buf'
688 '"'# -> cont '\"' buf'
689 '\''# -> cont '\'' buf'
690 '^'# -> let c = currentChar# buf' in
691 if c `geChar#` '@'# && c `leChar#` '_'#
692 then cont (C# (chr# (ord# c -# ord# '@'#))) (incLexeme buf')
695 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
696 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
698 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
700 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
701 Just buf2 <- [prefixMatch buf p] ] of
702 (c,buf2):_ -> cont c buf2
705 after_charnum cont i buf
706 = let int = fromInteger i in
707 if i >= 0 && i <= 255
708 then cont (chr int) buf
711 readNum cont buf is_digit base conv = read buf 0
713 = case currentChar# buf of { c ->
715 then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
721 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
722 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
724 hex c | is_digit c = ord# c -# ord# '0'#
725 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
726 oct_or_dec c = ord# c -# ord# '0'#
728 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
731 | c `geChar#` 'A'# && c `leChar#` 'Z'#
732 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
735 charError buf = lexError "error in character literal" buf
737 silly_escape_chars = [
774 -------------------------------------------------------------------------------
776 lex_demand cont buf =
777 case read_em [] buf of { (ls,buf') ->
778 case currentChar# buf' of
779 'B'# -> cont (ITstrict (ls, True )) (incLexeme buf')
780 _ -> cont (ITstrict (ls, False)) buf'
783 -- code snatched from Demand.lhs
785 case currentChar# buf of
786 'L'# -> read_em (WwLazy False : acc) (stepOn buf)
787 'A'# -> read_em (WwLazy True : acc) (stepOn buf)
788 'S'# -> read_em (WwStrict : acc) (stepOn buf)
789 'P'# -> read_em (WwPrim : acc) (stepOn buf)
790 'E'# -> read_em (WwEnum : acc) (stepOn buf)
791 ')'# -> (reverse acc, stepOn buf)
792 'U'# -> do_unpack DataType True acc (stepOnBy# buf 2#)
793 'u'# -> do_unpack DataType False acc (stepOnBy# buf 2#)
794 'N'# -> do_unpack NewType True acc (stepOnBy# buf 2#)
795 'n'# -> do_unpack NewType False acc (stepOnBy# buf 2#)
796 _ -> (reverse acc, buf)
798 do_unpack new_or_data wrapper_unpacks acc buf
799 = case read_em [] buf of
800 (stuff, rest) -> read_em (WwUnpack new_or_data wrapper_unpacks stuff : acc) rest
805 case currentChar# buf of
806 'C'# -> cont ITsccAllCafs (incLexeme buf)
807 other -> cont ITscc buf
809 -----------------------------------------------------------------------------
812 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
813 lex_num cont glaexts 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 (incLexeme buf') of
822 buf2 -> -- points to first non digit char
824 let l = case currentChar# buf2 of
830 = let buf3 = incLexeme buf2 in
831 case currentChar# buf3 of
832 '-'# -> expandWhile# is_digit (incLexeme buf3)
833 '+'# -> expandWhile# is_digit (incLexeme buf3)
834 x | is_digit x -> expandWhile# is_digit buf3
837 v = readRational__ (lexemeToString l)
839 in case currentChar# l of -- glasgow exts only
840 '#'# | flag glaexts -> let l' = incLexeme l in
841 case currentChar# l' of
842 '#'# -> cont (ITprimdouble v) (incLexeme l')
843 _ -> cont (ITprimfloat v) l'
844 _ -> cont (ITrational v) l
846 _ -> after_lexnum cont glaexts acc' buf'
848 after_lexnum cont glaexts i buf
849 = case currentChar# buf of
850 '#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
851 _ -> cont (ITinteger i) buf
853 -----------------------------------------------------------------------------
854 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
856 -- we lexemeToFastString on the bit between the ``''s, but include the
857 -- quotes in the full lexeme.
859 lex_cstring cont buf =
860 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
861 Just buf' -> cont (ITlitlit (lexemeToFastString
862 (setCurrentPos# buf' (negateInt# 2#))))
863 (mergeLexemes buf buf')
864 Nothing -> lexError "unterminated ``" buf
866 -----------------------------------------------------------------------------
867 -- identifiers, symbols etc.
870 case expandWhile# is_ident buf of
871 buf' -> cont (ITipvarid lexeme) buf'
872 where lexeme = lexemeToFastString buf'
874 lex_id cont glaexts buf =
875 case expandWhile# is_ident buf of { buf1 ->
877 case (if flag glaexts
878 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
879 else buf1) of { buf' ->
881 let lexeme = lexemeToFastString buf' in
883 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
884 Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
888 let var_token = cont (mk_var_token lexeme) buf' in
890 if not (flag glaexts)
894 case lookupUFM ghcExtensionKeywordsFM lexeme of {
895 Just kwd_token -> cont kwd_token buf';
901 case expandWhile# is_symbol buf of
902 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
903 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
904 cont kwd_token buf' ;
905 Nothing -> --trace ("sym: "++unpackFS lexeme) $
906 cont (mk_var_token lexeme) buf'
908 where lexeme = lexemeToFastString buf'
911 lex_con cont glaexts buf =
912 case expandWhile# is_ident buf of { buf1 ->
913 case slurp_trailing_hashes buf1 glaexts of { buf' ->
915 case currentChar# buf' of
920 just_a_conid = --trace ("con: "++unpackFS lexeme) $
921 cont (ITconid lexeme) buf'
922 lexeme = lexemeToFastString buf'
923 munch = lex_qid cont glaexts lexeme (incLexeme buf') just_a_conid
926 lex_qid cont glaexts mod buf just_a_conid =
927 case currentChar# buf of
928 '['# -> -- Special case for []
929 case lookAhead# buf 1# of
930 ']'# -> cont (ITqconid (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
933 '('# -> -- Special case for (,,,)
934 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
935 case lookAhead# buf 1# of
936 '#'# | flag glaexts -> case lookAhead# buf 2# of
937 ','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#)
940 ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
941 ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
944 '-'# -> case lookAhead# buf 1# of
945 '>'# -> cont (ITqconid (mod,SLIT("->"))) (setCurrentPos# buf 2#)
946 _ -> lex_id3 cont glaexts mod buf just_a_conid
947 _ -> lex_id3 cont glaexts mod buf just_a_conid
949 lex_id3 cont glaexts mod buf just_a_conid
950 | is_symbol (currentChar# buf) =
952 start_new_lexeme = stepOverLexeme buf
954 case expandWhile# is_symbol start_new_lexeme of { buf' ->
956 lexeme = lexemeToFastString buf'
957 -- real lexeme is M.<sym>
958 new_buf = mergeLexemes buf buf'
960 cont (mk_qvar_token mod lexeme) new_buf
961 -- wrong, but arguably morally right: M... is now a qvarsym
966 start_new_lexeme = stepOverLexeme buf
968 case expandWhile# is_ident start_new_lexeme of { buf1 ->
973 case slurp_trailing_hashes buf1 glaexts of { buf' ->
976 lexeme = lexemeToFastString buf'
977 new_buf = mergeLexemes buf buf'
978 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
980 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
981 Just kwd_token -> just_a_conid; -- avoid M.where etc.
982 Nothing -> is_a_qvarid
983 -- TODO: special ids (as, qualified, hiding) shouldn't be
984 -- recognised as keywords here. ie. M.as is a qualified varid.
988 slurp_trailing_hashes buf glaexts
989 | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
994 | is_upper f = ITconid pk_str
995 | is_ident f = ITvarid pk_str
996 | f `eqChar#` ':'# = ITconsym pk_str
997 | otherwise = ITvarsym pk_str
999 (C# f) = _HEAD_ pk_str
1002 mk_qvar_token m token =
1003 case mk_var_token token of
1004 ITconid n -> ITqconid (m,n)
1005 ITvarid n -> ITqvarid (m,n)
1006 ITconsym n -> ITqconsym (m,n)
1007 ITvarsym n -> ITqvarsym (m,n)
1008 _ -> ITunknown (show token)
1011 ----------------------------------------------------------------------------
1012 Horrible stuff for dealing with M.(,,,)
1015 lex_tuple cont mod buf back_off =
1019 case currentChar# buf of
1020 ','# -> go (n+1) (stepOn buf)
1021 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr n))) (stepOn buf)
1024 lex_ubx_tuple cont mod buf back_off =
1028 case currentChar# buf of
1029 ','# -> go (n+1) (stepOn buf)
1030 '#'# -> case lookAhead# buf 1# of
1031 ')'# -> cont (ITqconid (mod, snd (mkUbxTupNameStr n)))
1037 -----------------------------------------------------------------------------
1038 doDiscard rips along really fast, looking for a '#-}',
1039 indicating the end of the pragma we're skipping
1042 doDiscard inStr buf =
1043 case currentChar# buf of
1045 case lookAhead# buf 1# of { '#'# ->
1046 case lookAhead# buf 2# of { '-'# ->
1047 case lookAhead# buf 3# of { '}'# ->
1048 (lexemeToBuffer buf, stepOverLexeme (setCurrentPos# buf 4#));
1049 _ -> doDiscard inStr (incLexeme buf) };
1050 _ -> doDiscard inStr (incLexeme buf) };
1051 _ -> doDiscard inStr (incLexeme buf) }
1054 odd_slashes buf flg i# =
1055 case lookAhead# buf i# of
1056 '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
1059 case lookAhead# buf (negateInt# 1#) of --backwards, actually
1060 '\\'# -> -- escaping something..
1061 if odd_slashes buf True (negateInt# 2#) then
1062 -- odd number of slashes, " is escaped.
1063 doDiscard inStr (incLexeme buf)
1065 -- even number of slashes, \ is escaped.
1066 doDiscard (not inStr) (incLexeme buf)
1067 _ -> case inStr of -- forced to avoid build-up
1068 True -> doDiscard False (incLexeme buf)
1069 False -> doDiscard True (incLexeme buf)
1070 _ -> doDiscard inStr (incLexeme buf)
1074 -----------------------------------------------------------------------------
1085 data PState = PState {
1087 glasgow_exts :: Int#,
1090 context :: [LayoutContext]
1093 type P a = StringBuffer -- Input string
1098 returnP a buf s = POk s a
1100 thenP :: P a -> (a -> P b) -> P b
1101 m `thenP` k = \ buf s ->
1103 POk s1 a -> k a buf s1
1104 PFailed err -> PFailed err
1106 thenP_ :: P a -> P b -> P b
1107 m `thenP_` k = m `thenP` \_ -> k
1109 mapP :: (a -> P b) -> [a] -> P [b]
1110 mapP f [] = returnP []
1113 mapP f as `thenP` \bs ->
1116 failP :: String -> P a
1117 failP msg buf s = PFailed (text msg)
1119 failMsgP :: Message -> P a
1120 failMsgP msg buf s = PFailed msg
1122 lexError :: String -> P a
1123 lexError str buf s@PState{ loc = loc }
1124 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1126 getSrcLocP :: P SrcLoc
1127 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1129 getSrcFile :: P FAST_STRING
1130 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1132 getContext :: P [LayoutContext]
1133 getContext buf s@(PState{ context = ctx }) = POk s ctx
1135 pushContext :: LayoutContext -> P ()
1136 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1140 This special case in layoutOn is to handle layout contexts with are
1141 indented the same or less than the current context. This is illegal
1142 according to the Haskell spec, so we have to arrange to close the
1143 current context. eg.
1148 after the first 'where', the sequence of events is:
1150 - layout system inserts a ';' (column 0)
1151 - parser begins a new context at column 0
1152 - parser shifts ';' (legal empty declaration)
1153 - parser sees 'class': parse error (we're still in the inner context)
1155 trouble is, by the time we know we need a new context, the lexer has
1156 already generated the ';'. Hacky solution is as follows: since we
1157 know the column of the next token (it's the column number of the new
1158 context), we set the ACTUAL column number of the new context to this
1159 numer plus one. Hence the next time the lexer is called, a '}' will
1160 be generated to close the new context straight away. Furthermore, we
1161 have to set the atbol flag so that the ';' that the parser shifted as
1162 part of the new context is re-generated.
1164 when the new context is *less* indented than the current one:
1166 f = f where g = g where
1169 - current context: column 12.
1170 - on seeing 'h' (column 0), the layout system inserts '}'
1171 - parser starts a new context, column 0
1172 - parser sees '}', uses it to close new context
1173 - we still need to insert another '}' followed by a ';',
1174 hence the atbol trick.
1176 There's also a special hack in here to deal with
1183 i.e. the inner context is at the same indentation level as the outer
1184 context. This is strictly illegal according to Haskell 98, but
1185 there's a lot of existing code using this style and it doesn't make
1186 any sense to disallow it, since empty 'do' lists don't make sense.
1189 layoutOn :: Bool -> P ()
1190 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1191 let offset = lexemeIndex buf -# bol in
1194 | if strict then prev_off >=# offset else prev_off ># offset ->
1195 --trace ("layout on, column: " ++ show (I# offset)) $
1196 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1198 --trace ("layout on, column: " ++ show (I# offset)) $
1199 POk s{ context = Layout offset : ctx } ()
1202 layoutOff buf s@(PState{ context = ctx }) =
1203 POk s{ context = NoLayout:ctx } ()
1206 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1208 (_:tl) -> POk s{ context = tl } ()
1209 [] -> PFailed (srcParseErr buf loc)
1212 Note that if the name of the file we're processing ends
1213 with `hi-boot', we accept it on faith as having the right
1214 version. This is done so that .hi-boot files that comes
1215 with hsc don't have to be updated before every release,
1216 *and* it allows us to share .hi-boot files with versions
1217 of hsc that don't have .hi version checking (e.g., ghc-2.10's)
1219 If the version number is 0, the checking is also turned off.
1220 (needed to deal with GHC.hi only!)
1222 Once we can assume we're compiling with a version of ghc that
1223 supports interface file checking, we can drop the special
1226 checkVersion :: Maybe Integer -> P ()
1227 checkVersion mb@(Just v) buf s@(PState{loc = loc})
1228 | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
1229 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1230 checkVersion mb@Nothing buf s@(PState{loc = loc})
1231 | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
1232 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1234 -----------------------------------------------------------------
1236 ifaceParseErr :: StringBuffer -> SrcLoc -> Message
1238 = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
1239 text (lexemeToString s), char '\'']
1241 ifaceVersionErr hi_vers l toks
1242 = hsep [ppr l, ptext SLIT("Interface file version error;"),
1243 ptext SLIT("Expected"), int opt_HiVersion,
1244 ptext SLIT("found "), pp_version]
1248 Nothing -> ptext SLIT("pre ghc-3.02 version")
1249 Just v -> ptext SLIT("version") <+> integer v
1251 -----------------------------------------------------------------------------
1253 srcParseErr :: StringBuffer -> SrcLoc -> Message
1257 then ptext SLIT(": parse error (possibly incorrect indentation)")
1258 else hcat [ptext SLIT(": parse error on input "),
1259 char '`', text token, char '\'']
1262 token = lexemeToString s