2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Lexical analysis]{Lexical analysis}
6 --------------------------------------------------------
8 There's a known bug in here:
10 If an interface file ends prematurely, Lex tries to
11 do headFS of an empty FastString.
13 An example that provokes the error is
15 f _:_ _forall_ [a] <<<END OF FILE>>>
16 --------------------------------------------------------
24 Token(..), lexer, ParseResult(..), PState(..),
25 ExtFlags(..), mkPState,
28 P, thenP, thenP_, returnP, mapP, failP, failMsgP,
29 getSrcLocP, setSrcLocP, getSrcFile,
30 layoutOn, layoutOff, pushContext, popContext
33 #include "HsVersions.h"
35 import Char ( toUpper, isDigit, chr, ord )
38 import PrelNames ( mkTupNameStr )
39 import ForeignCall ( Safety(..) )
40 import UniqFM ( listToUFM, lookupUFM )
41 import BasicTypes ( Boxity(..) )
42 import SrcLoc ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
43 replaceSrcLine, mkSrcLoc )
45 import ErrUtils ( Message )
53 import DATA_BITS ( Bits(..) )
54 import DATA_INT ( Int32 )
57 %************************************************************************
59 \subsection{Data types}
61 %************************************************************************
63 The token data type, fairly un-interesting except from one
64 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
65 strictness, unfolding etc).
67 The Idea/Observation here is that the renamer needs to scan through
68 all of an interface file before it can continue. But only a fraction
69 of the information contained in the file turns out to be useful, so
70 delaying as much as possible of the scanning and parsing of an
71 interface file Makes Sense (Heap profiles of the compiler
72 show a reduction in heap usage by at least a factor of two,
75 Hence, the interface file lexer spots when value declarations are
76 being scanned and return the @ITidinfo@ and @ITtype@ constructors
77 for the type and any other id info for that binding (unfolding, strictness
78 etc). These constructors are applied to the result of lexing these sub-chunks.
80 The lexing of the type and id info is all done lazily, of course, so
81 the scanning (and subsequent parsing) will be done *only* on the ids the
82 renamer finds out that it is interested in. The rest will just be junked.
83 Laziness, you know it makes sense :-)
87 = ITas -- Haskell keywords
111 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
113 | ITforall -- GHC extension keywords
125 | ITccall (Bool,Bool,Safety) -- (is_dyn, is_casm, may_gc)
127 | ITspecialise_prag -- Pragmas
137 | ITdotdot -- reserved symbols
153 | ITbiglam -- GHC-extension symbols
155 | ITocurly -- special symbols
157 | ITocurlybar -- {|, for type applications
158 | ITccurlybar -- |}, for type applications
161 | ITopabrack -- [:, for parallel arrays with -fparr
162 | ITcpabrack -- :], for parallel arrays with -fparr
173 | ITvarid FastString -- identifiers
175 | ITvarsym FastString
176 | ITconsym FastString
177 | ITqvarid (FastString,FastString)
178 | ITqconid (FastString,FastString)
179 | ITqvarsym (FastString,FastString)
180 | ITqconsym (FastString,FastString)
182 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
183 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
185 | ITpragma StringBuffer
188 | ITstring FastString
190 | ITrational Rational
193 | ITprimstring FastString
195 | ITprimfloat Rational
196 | ITprimdouble Rational
197 | ITlitlit FastString
199 -- MetaHaskell extension tokens
200 | ITopenExpQuote -- [| or [e|
201 | ITopenPatQuote -- [p|
202 | ITopenDecQuote -- [d|
203 | ITopenTypQuote -- [t|
205 | ITidEscape FastString -- $x
206 | ITparenEscape -- $(
208 | ITunknown String -- Used when the lexer can't make sense of it
209 | ITeof -- end of file token
210 deriving Show -- debugging
213 -----------------------------------------------------------------------------
217 pragmaKeywordsFM = listToUFM $
218 map (\ (x,y) -> (mkFastString x,y))
219 [( "SPECIALISE", ITspecialise_prag ),
220 ( "SPECIALIZE", ITspecialise_prag ),
221 ( "SOURCE", ITsource_prag ),
222 ( "INLINE", ITinline_prag ),
223 ( "NOINLINE", ITnoinline_prag ),
224 ( "NOTINLINE", ITnoinline_prag ),
225 ( "LINE", ITline_prag ),
226 ( "RULES", ITrules_prag ),
227 ( "RULEZ", ITrules_prag ), -- american spelling :-)
228 ( "SCC", ITscc_prag ),
229 ( "DEPRECATED", ITdeprecated_prag )
232 haskellKeywordsFM = listToUFM $
233 map (\ (x,y) -> (mkFastString x,y))
234 [( "_", ITunderscore ),
237 ( "class", ITclass ),
239 ( "default", ITdefault ),
240 ( "deriving", ITderiving ),
243 ( "hiding", IThiding ),
245 ( "import", ITimport ),
247 ( "infix", ITinfix ),
248 ( "infixl", ITinfixl ),
249 ( "infixr", ITinfixr ),
250 ( "instance", ITinstance ),
252 ( "module", ITmodule ),
253 ( "newtype", ITnewtype ),
255 ( "qualified", ITqualified ),
258 ( "where", ITwhere ),
259 ( "_scc_", ITscc ) -- ToDo: remove
262 isSpecial :: Token -> Bool
263 -- If we see M.x, where x is a keyword, but
264 -- is special, we treat is as just plain M.x,
266 isSpecial ITas = True
267 isSpecial IThiding = True
268 isSpecial ITqualified = True
269 isSpecial ITforall = True
270 isSpecial ITexport = True
271 isSpecial ITlabel = True
272 isSpecial ITdynamic = True
273 isSpecial ITsafe = True
274 isSpecial ITthreadsafe = True
275 isSpecial ITunsafe = True
276 isSpecial ITwith = True
277 isSpecial ITccallconv = True
278 isSpecial ITstdcallconv = True
281 -- the bitmap provided as the third component indicates whether the
282 -- corresponding extension keyword is valid under the extension options
283 -- provided to the compiler; if the extension corresponding to *any* of the
284 -- bits set in the bitmap is enabled, the keyword is valid (this setup
285 -- facilitates using a keyword in two different extensions that can be
286 -- activated independently)
288 ghcExtensionKeywordsFM = listToUFM $
289 map (\(x, y, z) -> (mkFastString x, (y, z)))
290 [ ( "forall", ITforall, bit glaExtsBit),
291 ( "foreign", ITforeign, bit ffiBit),
292 ( "export", ITexport, bit ffiBit),
293 ( "label", ITlabel, bit ffiBit),
294 ( "dynamic", ITdynamic, bit ffiBit),
295 ( "safe", ITsafe, bit ffiBit),
296 ( "threadsafe", ITthreadsafe, bit ffiBit),
297 ( "unsafe", ITunsafe, bit ffiBit),
298 ( "with", ITwith, bit withBit),
299 ( "stdcall", ITstdcallconv, bit ffiBit),
300 ( "ccall", ITccallconv, bit ffiBit),
301 ( "dotnet", ITdotnet, bit ffiBit),
302 ("_ccall_", ITccall (False, False, PlayRisky),
304 ("_ccall_GC_", ITccall (False, False, PlaySafe False),
306 ("_casm_", ITccall (False, True, PlayRisky),
308 ("_casm_GC_", ITccall (False, True, PlaySafe False),
312 haskellKeySymsFM = listToUFM $
313 map (\ (x,y) -> (mkFastString x,y))
315 ,(":", ITcolon) -- (:) is a reserved op,
316 -- meaning only list cons
329 ,(".", ITdot) -- sadly, for 'forall a . t'
334 -----------------------------------------------------------------------------
339 - (exts) lexing a source with extensions, eg, an interface file or
341 - (bol) pointer to beginning of line (for column calculations)
342 - (buf) pointer to beginning of token
343 - (buf) pointer to current char
344 - (atbol) flag indicating whether we're at the beginning of a line
347 lexer :: (Token -> P a) -> P a
348 lexer cont buf s@(PState{
356 -- first, start a new lexeme and lose all the whitespace
358 tab line bol atbol (stepOverLexeme buf)
360 line = srcLocLine loc
362 tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
363 case currentChar# buf of
366 if bufferExhausted (stepOn buf)
367 then cont ITeof buf s'
368 else trace "lexer: misplaced NUL?" $
369 tab y bol atbol (stepOn buf)
371 '\n'# -> let buf' = stepOn buf
372 in tab (y +# 1#) (currentIndex# buf') 1# buf'
374 -- find comments. This got harder in Haskell 98.
375 '-'# -> let trundle n =
376 let next = lookAhead# buf n in
377 if next `eqChar#` '-'# then trundle (n +# 1#)
378 else if is_symbol next || n <# 2#
381 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
384 -- comments and pragmas. We deal with LINE pragmas here,
385 -- and throw out any unrecognised pragmas as comments. Any
386 -- pragmas we know about are dealt with later (after any layout
387 -- processing if necessary).
388 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
389 if lookAhead# buf 2# `eqChar#` '#'# then
390 case expandWhile# is_space (addToCurrentPos buf 3#) of { buf1->
391 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2->
392 let lexeme = mkFastString -- ToDo: too slow
393 (map toUpper (lexemeToString buf2)) in
394 case lookupUFM pragmaKeywordsFM lexeme of
395 -- ignore RULES pragmas when -fglasgow-exts is off
396 Just ITrules_prag | not (glaExtsEnabled exts) ->
397 skip_to_end (stepOnBy# buf 2#) s'
399 line_prag skip_to_end buf2 s'
400 Just other -> is_a_token
401 Nothing -> skip_to_end (stepOnBy# buf 2#) s'
404 else skip_to_end (stepOnBy# buf 2#) s'
406 skip_to_end = skipNestedComment (lexer cont)
408 -- special GHC extension: we grok cpp-style #line pragmas
409 '#'# | lexemeIndex buf ==# bol -> -- the '#' must be in column 0
410 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
411 lookAhead# buf 2# `eqChar#` 'i'# &&
412 lookAhead# buf 3# `eqChar#` 'n'# &&
413 lookAhead# buf 4# `eqChar#` 'e'# = stepOnBy# buf 5#
414 | otherwise = stepOn buf
416 case expandWhile# is_space buf1 of { buf2 ->
417 if is_digit (currentChar# buf2)
418 then line_prag next_line buf2 s'
422 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
424 -- tabs have been expanded beforehand
425 c | is_space c -> tab y bol atbol (stepOn buf)
426 | otherwise -> is_a_token
428 where s' = s{loc = replaceSrcLine loc y,
432 is_a_token | atbol /=# 0# = lexBOL cont buf s'
433 | otherwise = lexToken cont exts buf s'
435 -- {-# LINE .. #-} pragmas. yeuch.
436 line_prag cont buf s@PState{loc=loc} =
437 case expandWhile# is_space buf of { buf1 ->
438 case scanNumLit 0 (stepOverLexeme buf1) of { (line,buf2) ->
439 -- subtract one: the line number refers to the *following* line.
440 let real_line = line - 1 in
441 case fromInteger real_line of { i@(I# l) ->
442 -- ToDo, if no filename then we skip the newline.... d'oh
443 case expandWhile# is_space buf2 of { buf3 ->
444 case currentChar# buf3 of
446 case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
448 file = lexemeToFastString buf4
449 new_buf = stepOn (stepOverLexeme buf4)
451 if nullFastString file
452 then cont new_buf s{loc = replaceSrcLine loc l}
453 else cont new_buf s{loc = mkSrcLoc file i}
455 _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
458 skipNestedComment :: P a -> P a
459 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
461 skipNestedComment' :: SrcLoc -> P a -> P a
462 skipNestedComment' orig_loc cont buf = loop buf
465 case currentChar# buf of
466 '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
468 '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
470 (skipNestedComment' orig_loc cont)
473 '\n'# -> \ s@PState{loc=loc} ->
474 let buf' = stepOn buf in
475 loop buf' s{loc = incSrcLine loc,
476 bol = currentIndex# buf',
479 -- pass the original SrcLoc to lexError so that the error is
480 -- reported at the line it was originally on, not the line at
481 -- the end of the file.
482 '\NUL'# | bufferExhausted (stepOn buf) ->
483 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
485 _ -> loop (stepOn buf)
487 -- When we are lexing the first token of a line, check whether we need to
488 -- insert virtual semicolons or close braces due to layout.
490 lexBOL :: (Token -> P a) -> P a
491 lexBOL cont buf s@(PState{
498 if need_close_curly then
499 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
500 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
501 else if need_semi_colon then
502 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
503 cont ITsemi buf s{atbol = 0#}
505 lexToken cont exts buf s{atbol = 0#}
507 col = currentIndex# buf -# bol
520 Layout n -> col ==# n
523 lexToken :: (Token -> P a) -> Int# -> P a
524 lexToken cont exts buf =
525 -- trace "lexToken" $
526 case currentChar# buf of
528 -- special symbols ----------------------------------------------------
529 '('# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '#'#
530 -> cont IToubxparen (addToCurrentPos buf 2#)
532 -> cont IToparen (incCurrentPos buf)
534 ')'# -> cont ITcparen (incCurrentPos buf)
535 '['# | parrEnabled exts && lookAhead# buf 1# `eqChar#` ':'# ->
536 cont ITopabrack (addToCurrentPos buf 2#)
537 ------- MetaHaskell Extensions, looking for [| [e| [t| [p| and [d|
538 | glaExtsEnabled exts &&
539 ((lookAhead# buf 1# ) `eqChar#` '|'# ) ->
540 cont ITopenExpQuote (addToCurrentPos buf 2# )
541 | glaExtsEnabled exts &&
542 (let c = (lookAhead# buf 1# )
543 in eqChar# c 'e'# || eqChar# c 't'# || eqChar# c 'd'# || eqChar# c 'p'#) &&
544 ((lookAhead# buf 2#) `eqChar#` '|'#) ->
545 let quote 'e'# = ITopenExpQuote
546 quote 'p'# = ITopenPatQuote
547 quote 'd'# = ITopenDecQuote
548 quote 't'# = ITopenTypQuote
549 in cont (quote (lookAhead# buf 1#)) (addToCurrentPos buf 3# )
551 cont ITobrack (incCurrentPos buf)
553 ']'# -> cont ITcbrack (incCurrentPos buf)
554 ','# -> cont ITcomma (incCurrentPos buf)
555 ';'# -> cont ITsemi (incCurrentPos buf)
556 '}'# -> \ s@PState{context = ctx} ->
558 (_:ctx') -> cont ITccurly (incCurrentPos buf) s{context=ctx'}
559 _ -> lexError "too many '}'s" buf s
560 '|'# -> case lookAhead# buf 1# of
561 '}'# | glaExtsEnabled exts -> cont ITccurlybar
562 (addToCurrentPos buf 2#)
563 -- MetaHaskell extension
564 ']'# | glaExtsEnabled exts -> cont ITcloseQuote (addToCurrentPos buf 2#)
565 other -> lex_sym cont (incCurrentPos buf)
566 ':'# -> case lookAhead# buf 1# of
567 ']'# | parrEnabled exts -> cont ITcpabrack
568 (addToCurrentPos buf 2#)
569 _ -> lex_sym cont (incCurrentPos buf)
572 '#'# -> case lookAhead# buf 1# of
573 ')'# | glaExtsEnabled exts
574 -> cont ITcubxparen (addToCurrentPos buf 2#)
575 '-'# -> case lookAhead# buf 2# of
576 '}'# -> cont ITclose_prag (addToCurrentPos buf 3#)
577 _ -> lex_sym cont (incCurrentPos buf)
578 _ -> lex_sym cont (incCurrentPos buf)
580 '`'# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '`'#
581 -> lex_cstring cont (addToCurrentPos buf 2#)
583 -> cont ITbackquote (incCurrentPos buf)
585 '{'# -> -- for Emacs: -}
586 case lookAhead# buf 1# of
587 '|'# | glaExtsEnabled exts
588 -> cont ITocurlybar (addToCurrentPos buf 2#)
589 '-'# -> case lookAhead# buf 2# of
590 '#'# -> lex_prag cont (addToCurrentPos buf 3#)
591 _ -> cont ITocurly (incCurrentPos buf)
592 _ -> (layoutOff `thenP_` cont ITocurly) (incCurrentPos buf)
597 -- strings/characters -------------------------------------------------
598 '\"'#{-"-} -> lex_string cont exts [] (incCurrentPos buf)
599 '\''# -> lex_char (char_end cont) exts (incCurrentPos buf)
601 -- Hexadecimal and octal constants
602 '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
603 -> readNum (after_lexnum cont exts) buf' is_hexdigit 16 hex
604 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
605 -> readNum (after_lexnum cont exts) buf' is_octdigit 8 oct_or_dec
606 where ch = lookAhead# buf 1#
607 ch2 = lookAhead# buf 2#
608 buf' = addToCurrentPos buf 2#
611 if bufferExhausted (stepOn buf) then
614 trace "lexIface: misplaced NUL?" $
615 cont (ITunknown "\NUL") (stepOn buf)
617 '?'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- ?x implicit parameter
618 specialPrefixId ITdupipvarid cont exts (incCurrentPos buf)
619 '%'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->
620 specialPrefixId ITsplitipvarid cont exts (incCurrentPos buf)
622 ---------------- MetaHaskell Extensions for quotation escape
623 '$'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) -> -- $x variable escape
624 specialPrefixId ITidEscape cont exts (addToCurrentPos buf 1#)
625 '$'# | glaExtsEnabled exts && -- $( f x ) expression escape
626 ((lookAhead# buf 1#) `eqChar#` '('#) -> cont ITparenEscape (addToCurrentPos buf 2#)
628 c | is_digit c -> lex_num cont exts 0 buf
629 | is_symbol c -> lex_sym cont buf
630 | is_upper c -> lex_con cont exts buf
631 | is_lower c -> lex_id cont exts buf
632 | otherwise -> lexError "illegal character" buf
634 -- Int# is unlifted, and therefore faster than Bool for flags.
640 -------------------------------------------------------------------------------
644 = case expandWhile# is_space buf of { buf1 ->
645 case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 ->
646 let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
647 case lookupUFM pragmaKeywordsFM lexeme of
648 Just kw -> cont kw (mergeLexemes buf buf2)
649 Nothing -> panic "lex_prag"
652 -------------------------------------------------------------------------------
655 lex_string cont exts s buf
656 = case currentChar# buf of
658 let buf' = incCurrentPos buf
659 s' = mkFastString (map chr (reverse s))
660 in case currentChar# buf' of
661 '#'# | glaExtsEnabled exts -> if all (<= 0xFF) s
662 then cont (ITprimstring s') (incCurrentPos buf')
663 else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
664 _ -> cont (ITstring s') buf'
666 -- ignore \& in a string, deal with string gaps
667 '\\'# | next_ch `eqChar#` '&'#
668 -> lex_string cont exts s buf'
670 -> lex_stringgap cont exts s (incCurrentPos buf)
672 where next_ch = lookAhead# buf 1#
673 buf' = addToCurrentPos buf 2#
675 _ -> lex_char (lex_next_string cont s) exts buf
677 lex_stringgap cont exts s buf
678 = let buf' = incCurrentPos buf in
679 case currentChar# buf of
680 '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont exts s buf'
681 st{loc = incSrcLine loc}
682 '\\'# -> lex_string cont exts s buf'
683 c | is_space c -> lex_stringgap cont exts s buf'
684 other -> charError buf'
686 lex_next_string cont s exts c buf = lex_string cont exts (c:s) buf
688 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
689 lex_char cont exts buf
690 = case currentChar# buf of
691 '\\'# -> lex_escape (cont exts) (incCurrentPos buf)
692 c | is_any c -> cont exts (I# (ord# c)) (incCurrentPos buf)
693 other -> charError buf
695 char_end cont exts c buf
696 = case currentChar# buf of
697 '\''# -> let buf' = incCurrentPos buf in
698 case currentChar# buf' of
699 '#'# | glaExtsEnabled exts
700 -> cont (ITprimchar c) (incCurrentPos buf')
701 _ -> cont (ITchar c) buf'
705 = let buf' = incCurrentPos buf in
706 case currentChar# buf of
707 'a'# -> cont (ord '\a') buf'
708 'b'# -> cont (ord '\b') buf'
709 'f'# -> cont (ord '\f') buf'
710 'n'# -> cont (ord '\n') buf'
711 'r'# -> cont (ord '\r') buf'
712 't'# -> cont (ord '\t') buf'
713 'v'# -> cont (ord '\v') buf'
714 '\\'# -> cont (ord '\\') buf'
715 '"'# -> cont (ord '\"') buf'
716 '\''# -> cont (ord '\'') buf'
717 '^'# -> let c = currentChar# buf' in
718 if c `geChar#` '@'# && c `leChar#` '_'#
719 then cont (I# (ord# c -# ord# '@'#)) (incCurrentPos buf')
722 'x'# -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
723 'o'# -> readNum (after_charnum cont) buf' is_octdigit 8 oct_or_dec
725 -> readNum (after_charnum cont) buf is_digit 10 oct_or_dec
727 _ -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
728 Just buf2 <- [prefixMatch buf p] ] of
729 (c,buf2):_ -> cont (ord c) buf2
732 after_charnum cont i buf
733 = if i >= 0 && i <= 0x10FFFF
734 then cont (fromInteger i) buf
737 readNum cont buf is_digit base conv = read buf 0
739 = case currentChar# buf of { c ->
741 then read (incCurrentPos buf) (i*base + (toInteger (I# (conv c))))
747 || (c `geChar#` 'a'# && c `leChar#` 'f'#)
748 || (c `geChar#` 'A'# && c `leChar#` 'F'#)
750 hex c | is_digit c = ord# c -# ord# '0'#
751 | otherwise = ord# (to_lower c) -# ord# 'a'# +# 10#
752 oct_or_dec c = ord# c -# ord# '0'#
754 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
757 | c `geChar#` 'A'# && c `leChar#` 'Z'#
758 = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
761 charError buf = lexError "error in character literal" buf
763 silly_escape_chars = [
800 -----------------------------------------------------------------------------
803 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
804 lex_num cont exts acc buf =
805 case scanNumLit acc buf of
807 case currentChar# buf' of
808 '.'# | is_digit (lookAhead# buf' 1#) ->
809 -- this case is not optimised at all, as the
810 -- presence of floating point numbers in interface
811 -- files is not that common. (ToDo)
812 case expandWhile# is_digit (incCurrentPos buf') of
813 buf2 -> -- points to first non digit char
815 let l = case currentChar# buf2 of
821 = let buf3 = incCurrentPos buf2 in
822 case currentChar# buf3 of
823 '-'# | is_digit (lookAhead# buf3 1#)
824 -> expandWhile# is_digit (incCurrentPos buf3)
825 '+'# | is_digit (lookAhead# buf3 1#)
826 -> expandWhile# is_digit (incCurrentPos buf3)
827 x | is_digit x -> expandWhile# is_digit buf3
830 v = readRational__ (lexemeToString l)
832 in case currentChar# l of -- glasgow exts only
833 '#'# | glaExtsEnabled exts -> let l' = incCurrentPos l in
834 case currentChar# l' of
835 '#'# -> cont (ITprimdouble v) (incCurrentPos l')
836 _ -> cont (ITprimfloat v) l'
837 _ -> cont (ITrational v) l
839 _ -> after_lexnum cont exts acc' buf'
841 after_lexnum cont exts i buf
842 = case currentChar# buf of
843 '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
844 _ -> cont (ITinteger i) buf
846 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
850 return ((n%1)*10^^(k-d), t)
853 (ds,s) <- lexDecDigits r
854 (ds',t) <- lexDotDigits s
855 return (read (ds++ds'), length ds', t)
857 readExp (e:s) | e `elem` "eE" = readExp' s
858 readExp s = return (0,s)
860 readExp' ('+':s) = readDec s
861 readExp' ('-':s) = do
864 readExp' s = readDec s
867 (ds,r) <- nonnull isDigit s
868 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
871 lexDecDigits = nonnull isDigit
873 lexDotDigits ('.':s) = return (span isDigit s)
874 lexDotDigits s = return ("",s)
876 nonnull p s = do (cs@(_:_),t) <- return (span p s)
879 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
882 '-' : xs -> - (read_me xs)
886 = case (do { (x,"") <- readRational s ; return x }) of
888 [] -> error ("readRational__: no parse:" ++ top_s)
889 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
891 -----------------------------------------------------------------------------
892 -- C "literal literal"s (i.e. things like ``NULL'', ``stdout'' etc.)
894 -- we lexemeToFastString on the bit between the ``''s, but include the
895 -- quotes in the full lexeme.
897 lex_cstring cont buf =
898 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
899 Just buf' -> cont (ITlitlit (lexemeToFastString
900 (addToCurrentPos buf' (negateInt# 2#))))
901 (mergeLexemes buf buf')
902 Nothing -> lexError "unterminated ``" buf
904 -----------------------------------------------------------------------------
905 -- identifiers, symbols etc.
907 -- used for identifiers with special prefixes like
908 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
909 -- we've already seen the prefix char, so look for an id, and wrap
910 -- the new "ip_constr" around the lexeme returned
912 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
913 where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
914 newcont token buf2 = cont token buf2
916 case expandWhile# is_ident buf of
917 buf' -> cont (ip_constr (tailFS lexeme)) buf'
918 where lexeme = lexemeToFastString buf'
921 lex_id cont exts buf =
922 let buf1 = expandWhile# is_ident buf in
925 case (if glaExtsEnabled exts
926 then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
927 else buf1) of { buf' ->
930 let lexeme = lexemeToFastString buf' in
932 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
933 Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
937 let var_token = cont (ITvarid lexeme) buf' in
939 case lookupUFM ghcExtensionKeywordsFM lexeme of {
940 Just (kwd_token, validExts)
941 | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
948 case expandWhile# is_symbol buf of
949 buf' -> case lookupUFM haskellKeySymsFM lexeme of {
950 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
951 cont kwd_token buf' ;
952 Nothing -> --trace ("sym: "++unpackFS lexeme) $
953 cont (mk_var_token lexeme) buf'
955 where lexeme = lexemeToFastString buf'
958 -- lex_con recursively collects components of a qualified identifer.
959 -- The argument buf is the StringBuffer representing the lexeme
960 -- identified so far, where the next character is upper-case.
962 lex_con cont exts buf =
963 -- trace ("con: "{-++unpackFS lexeme-}) $
964 let empty_buf = stepOverLexeme buf in
965 case expandWhile# is_ident empty_buf of { buf1 ->
966 case slurp_trailing_hashes buf1 exts of { con_buf ->
968 let all_buf = mergeLexemes buf con_buf
970 con_lexeme = lexemeToFastString con_buf
971 mod_lexeme = lexemeToFastString (decCurrentPos buf)
972 all_lexeme = lexemeToFastString all_buf
975 | emptyLexeme buf = cont (ITconid con_lexeme) all_buf
976 | otherwise = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
979 case currentChar# all_buf of
980 '.'# -> maybe_qualified cont exts all_lexeme
981 (incCurrentPos all_buf) just_a_conid
986 maybe_qualified cont exts mod buf just_a_conid =
987 -- trace ("qid: "{-++unpackFS lexeme-}) $
988 case currentChar# buf of
989 '['# -> -- Special case for []
990 case lookAhead# buf 1# of
991 ']'# -> cont (ITqconid (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
994 '('# -> -- Special case for (,,,)
995 -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
996 case lookAhead# buf 1# of
997 '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
998 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#)
1001 ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1002 ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1005 '-'# -> case lookAhead# buf 1# of
1006 '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1007 _ -> lex_id3 cont exts mod buf just_a_conid
1009 _ -> lex_id3 cont exts mod buf just_a_conid
1012 lex_id3 cont exts mod buf just_a_conid
1013 | is_upper (currentChar# buf) =
1014 lex_con cont exts buf
1016 | is_symbol (currentChar# buf) =
1018 start_new_lexeme = stepOverLexeme buf
1020 -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1021 case expandWhile# is_symbol start_new_lexeme of { buf' ->
1023 lexeme = lexemeToFastString buf'
1024 -- real lexeme is M.<sym>
1025 new_buf = mergeLexemes buf buf'
1027 cont (mk_qvar_token mod lexeme) new_buf
1028 -- wrong, but arguably morally right: M... is now a qvarsym
1033 start_new_lexeme = stepOverLexeme buf
1035 -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1036 case expandWhile# is_ident start_new_lexeme of { buf1 ->
1041 case slurp_trailing_hashes buf1 exts of { buf' ->
1044 lexeme = lexemeToFastString buf'
1045 new_buf = mergeLexemes buf buf'
1046 is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1048 case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1049 Nothing -> is_a_qvarid ;
1051 Just kwd_token | isSpecial kwd_token -- special ids (as, qualified, hiding) shouldn't be
1052 -> is_a_qvarid -- recognised as keywords here.
1054 -> just_a_conid -- avoid M.where etc.
1057 slurp_trailing_hashes buf exts
1058 | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1063 | is_upper f = ITconid pk_str
1064 | is_ident f = ITvarid pk_str
1065 | f `eqChar#` ':'# = ITconsym pk_str
1066 | otherwise = ITvarsym pk_str
1068 (C# f) = headFS pk_str
1069 -- tl = _TAIL_ pk_str
1071 mk_qvar_token m token =
1072 -- trace ("mk_qvar ") $
1073 case mk_var_token token of
1074 ITconid n -> ITqconid (m,n)
1075 ITvarid n -> ITqvarid (m,n)
1076 ITconsym n -> ITqconsym (m,n)
1077 ITvarsym n -> ITqvarsym (m,n)
1078 _ -> ITunknown (show token)
1081 ----------------------------------------------------------------------------
1082 Horrible stuff for dealing with M.(,,,)
1085 lex_tuple cont mod buf back_off =
1089 case currentChar# buf of
1090 ','# -> go (n+1) (stepOn buf)
1091 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1094 lex_ubx_tuple cont mod buf back_off =
1098 case currentChar# buf of
1099 ','# -> go (n+1) (stepOn buf)
1100 '#'# -> case lookAhead# buf 1# of
1101 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1107 -----------------------------------------------------------------------------
1118 data PState = PState {
1120 extsBitmap :: Int#, -- bitmap that determines permitted extensions
1123 context :: [LayoutContext]
1126 type P a = StringBuffer -- Input string
1131 returnP a buf s = POk s a
1133 thenP :: P a -> (a -> P b) -> P b
1134 m `thenP` k = \ buf s ->
1136 POk s1 a -> k a buf s1
1137 PFailed err -> PFailed err
1139 thenP_ :: P a -> P b -> P b
1140 m `thenP_` k = m `thenP` \_ -> k
1142 mapP :: (a -> P b) -> [a] -> P [b]
1143 mapP f [] = returnP []
1146 mapP f as `thenP` \bs ->
1149 failP :: String -> P a
1150 failP msg buf s = PFailed (text msg)
1152 failMsgP :: Message -> P a
1153 failMsgP msg buf s = PFailed msg
1155 lexError :: String -> P a
1156 lexError str buf s@PState{ loc = loc }
1157 = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1159 getSrcLocP :: P SrcLoc
1160 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1162 -- use a temporary SrcLoc for the duration of the argument
1163 setSrcLocP :: SrcLoc -> P a -> P a
1164 setSrcLocP new_loc p buf s =
1165 case p buf s{ loc=new_loc } of
1167 PFailed e -> PFailed e
1169 getSrcFile :: P FastString
1170 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1172 pushContext :: LayoutContext -> P ()
1173 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1177 This special case in layoutOn is to handle layout contexts with are
1178 indented the same or less than the current context. This is illegal
1179 according to the Haskell spec, so we have to arrange to close the
1180 current context. eg.
1185 after the first 'where', the sequence of events is:
1187 - layout system inserts a ';' (column 0)
1188 - parser begins a new context at column 0
1189 - parser shifts ';' (legal empty declaration)
1190 - parser sees 'class': parse error (we're still in the inner context)
1192 trouble is, by the time we know we need a new context, the lexer has
1193 already generated the ';'. Hacky solution is as follows: since we
1194 know the column of the next token (it's the column number of the new
1195 context), we set the ACTUAL column number of the new context to this
1196 numer plus one. Hence the next time the lexer is called, a '}' will
1197 be generated to close the new context straight away. Furthermore, we
1198 have to set the atbol flag so that the ';' that the parser shifted as
1199 part of the new context is re-generated.
1201 when the new context is *less* indented than the current one:
1203 f = f where g = g where
1206 - current context: column 12.
1207 - on seeing 'h' (column 0), the layout system inserts '}'
1208 - parser starts a new context, column 0
1209 - parser sees '}', uses it to close new context
1210 - we still need to insert another '}' followed by a ';',
1211 hence the atbol trick.
1213 There's also a special hack in here to deal with
1220 i.e. the inner context is at the same indentation level as the outer
1221 context. This is strictly illegal according to Haskell 98, but
1222 there's a lot of existing code using this style and it doesn't make
1223 any sense to disallow it, since empty 'do' lists don't make sense.
1226 layoutOn :: Bool -> P ()
1227 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1228 let offset = lexemeIndex buf -# bol in
1231 | if strict then prev_off >=# offset else prev_off ># offset ->
1232 --trace ("layout on, column: " ++ show (I# offset)) $
1233 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1235 --trace ("layout on, column: " ++ show (I# offset)) $
1236 POk s{ context = Layout offset : ctx } ()
1239 layoutOff buf s@(PState{ context = ctx }) =
1240 POk s{ context = NoLayout:ctx } ()
1243 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1245 (_:tl) -> POk s{ context = tl } ()
1246 [] -> PFailed (srcParseErr buf loc)
1248 -- for reasons of efficiency, flags indicating language extensions (eg,
1249 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1252 glaExtsBit, ffiBit, parrBit :: Int
1258 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1259 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1260 ffiEnabled flags = testBit (toInt32 flags) ffiBit
1261 withEnabled flags = testBit (toInt32 flags) withBit
1262 parrEnabled flags = testBit (toInt32 flags) parrBit
1264 toInt32 :: Int# -> Int32
1265 toInt32 x# = fromIntegral (I# x#)
1267 -- convenient record-based bitmap for the interface to the rest of the world
1269 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1271 data ExtFlags = ExtFlags {
1272 glasgowExtsEF :: Bool,
1278 -- create a parse state
1280 mkPState :: SrcLoc -> ExtFlags -> PState
1284 extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1290 bitmap = glaExtsBit `setBitIf` glasgowExtsEF exts
1291 .|. ffiBit `setBitIf` (ffiEF exts
1292 || glasgowExtsEF exts)
1293 .|. withBit `setBitIf` withEF exts
1294 .|. parrBit `setBitIf` parrEF exts
1296 setBitIf :: Int -> Bool -> Int32
1297 b `setBitIf` cond | cond = bit b
1300 -----------------------------------------------------------------------------
1302 srcParseErr :: StringBuffer -> SrcLoc -> Message
1306 then ptext SLIT(": parse error (possibly incorrect indentation)")
1307 else hcat [ptext SLIT(": parse error on input "),
1308 char '`', text token, char '\'']
1311 token = lexemeToString s