1 -----------------------------------------------------------------------------
2 -- (c) The University of Glasgow, 2003
6 -- This is a combination of an Alex-generated lexer from a regex
7 -- definition, with some hand-coded bits.
9 -- Completely accurate information about token-spans within the source
10 -- file is maintained. Every token has a start and end SrcLoc attached to it.
12 -----------------------------------------------------------------------------
16 -- - parsing integers is a bit slow
17 -- - readRational is a bit slow
19 -- Known bugs, that were also in the previous version:
20 -- - M... should be 3 tokens, not 1.
21 -- - pragma-end should be only valid in a pragma
25 Token(..), lexer, mkPState,
26 P(..), ParseResult(..), getSrcLoc,
27 failMsgP, failLocMsgP, failSpanMsgP, srcParseFail,
28 popContext, pushCurrentContext,
31 #include "HsVersions.h"
33 import ErrUtils ( Message )
42 import Util ( maybePrefixMatch )
50 $whitechar = [\ \t\n\r\f\v\xa0]
51 $white_no_nl = $whitechar # \n
55 $digit = [$ascdigit $unidigit]
57 $special = [\(\)\,\;\[\]\`\{\}]
58 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~]
60 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
63 $asclarge = [A-Z \xc0-\xd6 \xd8-\xde]
64 $large = [$asclarge $unilarge]
67 $ascsmall = [a-z \xdf-\xf6 \xf8-\xff]
68 $small = [$ascsmall $unismall \_]
70 $graphic = [$small $large $symbol $digit $special \:\"\']
73 $hexit = [$digit A-F a-f]
74 $symchar = [$symbol \:]
76 $idchar = [$small $large $digit \']
78 @varid = $small $idchar*
79 @conid = $large $idchar*
81 @varsym = $symbol $symchar*
82 @consym = \: $symchar*
86 @hexadecimal = $hexit+
87 @exponent = [eE] [\-\+]? @decimal
89 -- we support the hierarchical module name extension:
92 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
96 -- everywhere: skip whitespace and comments
99 -- Everywhere: deal with nested comments. We explicitly rule out
100 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
101 -- (this can happen even though pragmas will normally take precedence due to
102 -- longest-match, because pragmas aren't valid in every state, but comments
104 "{-" / { notFollowedBy '#' } { nested_comment }
106 -- Single-line comments are a bit tricky. Haskell 98 says that two or
107 -- more dashes followed by a symbol should be parsed as a varsym, so we
108 -- have to exclude those.
109 -- The regex says: "munch all the characters after the dashes, as long as
110 -- the first one is not a symbol".
111 "--"\-* ([^$symbol] .*)? ;
113 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
114 -- blank lines) until we find a non-whitespace character, then do layout
117 -- One slight wibble here: what if the line begins with {-#? In
118 -- theory, we have to lex the pragma to see if it's one we recognise,
119 -- and if it is, then we backtrack and do_bol, otherwise we treat it
120 -- as a nested comment. We don't bother with this: if the line begins
121 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
124 ^\# (line)? { begin line_prag1 }
125 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
129 -- after a layout keyword (let, where, do, of), we begin a new layout
130 -- context if the curly brace is missing.
131 -- Careful! This stuff is quite delicate.
132 <layout, layout_do> {
133 \{ / { notFollowedBy '-' } { pop_and open_brace }
134 -- we might encounter {-# here, but {- has been handled already
136 ^\# (line)? { begin line_prag1 }
139 -- do is treated in a subtly different way, see new_layout_context
140 <layout> () { new_layout_context True }
141 <layout_do> () { new_layout_context False }
143 -- after a new layout context which was found to be to the left of the
144 -- previous context, we have generated a '{' token, and we now need to
145 -- generate a matching '}' token.
146 <layout_left> () { do_layout_left }
148 <0,glaexts> \n { begin bol }
150 "{-#" $whitechar* (line|LINE) { begin line_prag2 }
152 -- single-line line pragmas, of the form
153 -- # <line> "<file>" <extra-stuff> \n
154 <line_prag1> $digit+ { set_line line_prag1a }
155 <line_prag1a> \" [$graphic \ ]* \" { set_file line_prag1b }
156 <line_prag1b> .* { pop }
158 -- Haskell-style line pragmas, of the form
159 -- {-# LINE <line> "<file>" #-}
160 <line_prag2> $digit+ { set_line line_prag2a }
161 <line_prag2a> \" [$graphic \ ]* \" { set_file line_prag2b }
162 <line_prag2b> "#-}" { pop }
165 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
166 { token ITspecialise_prag }
167 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
168 "{-#" $whitechar* (INLINE|inline) { token ITinline_prag }
169 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
170 { token ITnoinline_prag }
171 "{-#" $whitechar* (RULES|rules) { token ITrules_prag }
172 "{-#" $whitechar* (DEPRECATED|deprecated)
173 { token ITdeprecated_prag }
174 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
175 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
176 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
178 "{-#" { nested_comment }
180 -- ToDo: should only be valid inside a pragma:
181 "#-}" { token ITclose_prag}
185 -- '0' state: ordinary lexemes
186 -- 'glaexts' state: glasgow extensions (postfix '#', etc.)
191 "[:" / { ifExtension parrEnabled } { token ITopabrack }
192 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
196 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
197 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
198 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
199 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
200 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
201 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
202 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
203 "$(" / { ifExtension thEnabled } { token ITparenEscape }
207 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
208 { special IToparenbar }
209 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
213 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
214 \% @varid / { ifExtension ipEnabled } { skip_one_varid ITsplitipvarid }
218 "(#" / { notFollowedBySymbol } { token IToubxparen }
219 "#)" { token ITcubxparen }
220 "{|" { token ITocurlybar }
221 "|}" { token ITccurlybar }
225 \( { special IToparen }
226 \) { special ITcparen }
227 \[ { special ITobrack }
228 \] { special ITcbrack }
229 \, { special ITcomma }
230 \; { special ITsemi }
231 \` { special ITbackquote }
238 @qual @varid { check_qvarid }
239 @qual @conid { idtoken qconid }
241 @conid { idtoken conid }
244 -- after an illegal qvarid, such as 'M.let',
245 -- we back up and try again in the bad_qvarid state:
247 @conid { pop_and (idtoken conid) }
248 @qual @conid { pop_and (idtoken qconid) }
252 @qual @varid "#"+ { idtoken qvarid }
253 @qual @conid "#"+ { idtoken qconid }
254 @varid "#"+ { varid }
255 @conid "#"+ { idtoken conid }
261 @qual @varsym { idtoken qvarsym }
262 @qual @consym { idtoken qconsym }
268 @decimal { tok_decimal }
269 0[oO] @octal { tok_octal }
270 0[xX] @hexadecimal { tok_hexadecimal }
274 @decimal \# { prim_decimal }
275 0[oO] @octal \# { prim_octal }
276 0[xX] @hexadecimal \# { prim_hexadecimal }
279 <0,glaexts> @floating_point { strtoken tok_float }
280 <glaexts> @floating_point \# { init_strtoken 1 prim_float }
281 <glaexts> @floating_point \# \# { init_strtoken 2 prim_double }
283 -- Strings and chars are lexed by hand-written code. The reason is
284 -- that even if we recognise the string or char here in the regex
285 -- lexer, we would still have to parse the string afterward in order
286 -- to convert it to a String.
289 \" { lex_string_tok }
293 -- work around bug in Alex 2.0
294 #if __GLASGOW_HASKELL__ < 503
295 unsafeAt arr i = arr ! i
298 -- -----------------------------------------------------------------------------
302 = ITas -- Haskell keywords
326 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
328 | ITforall -- GHC extension keywords
341 | ITspecialise_prag -- Pragmas
349 | ITcore_prag -- hdaume: core annotations
353 | ITdotdot -- reserved symbols
369 | ITbiglam -- GHC-extension symbols
371 | ITocurly -- special symbols
373 | ITocurlybar -- {|, for type applications
374 | ITccurlybar -- |}, for type applications
378 | ITopabrack -- [:, for parallel arrays with -fparr
379 | ITcpabrack -- :], for parallel arrays with -fparr
390 | ITvarid FastString -- identifiers
392 | ITvarsym FastString
393 | ITconsym FastString
394 | ITqvarid (FastString,FastString)
395 | ITqconid (FastString,FastString)
396 | ITqvarsym (FastString,FastString)
397 | ITqconsym (FastString,FastString)
399 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
400 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
402 | ITpragma StringBuffer
405 | ITstring FastString
407 | ITrational Rational
410 | ITprimstring FastString
412 | ITprimfloat Rational
413 | ITprimdouble Rational
415 -- MetaHaskell extension tokens
416 | ITopenExpQuote -- [| or [e|
417 | ITopenPatQuote -- [p|
418 | ITopenDecQuote -- [d|
419 | ITopenTypQuote -- [t|
421 | ITidEscape FastString -- $x
422 | ITparenEscape -- $(
426 -- Arrow notation extension
433 | ITLarrowtail -- -<<
434 | ITRarrowtail -- >>-
436 | ITunknown String -- Used when the lexer can't make sense of it
437 | ITeof -- end of file token
439 deriving Show -- debugging
442 isSpecial :: Token -> Bool
443 -- If we see M.x, where x is a keyword, but
444 -- is special, we treat is as just plain M.x,
446 isSpecial ITas = True
447 isSpecial IThiding = True
448 isSpecial ITqualified = True
449 isSpecial ITforall = True
450 isSpecial ITexport = True
451 isSpecial ITlabel = True
452 isSpecial ITdynamic = True
453 isSpecial ITsafe = True
454 isSpecial ITthreadsafe = True
455 isSpecial ITunsafe = True
456 isSpecial ITccallconv = True
457 isSpecial ITstdcallconv = True
458 isSpecial ITmdo = True
461 -- the bitmap provided as the third component indicates whether the
462 -- corresponding extension keyword is valid under the extension options
463 -- provided to the compiler; if the extension corresponding to *any* of the
464 -- bits set in the bitmap is enabled, the keyword is valid (this setup
465 -- facilitates using a keyword in two different extensions that can be
466 -- activated independently)
468 reservedWordsFM = listToUFM $
469 map (\(x, y, z) -> (mkFastString x, (y, z)))
470 [( "_", ITunderscore, 0 ),
472 ( "case", ITcase, 0 ),
473 ( "class", ITclass, 0 ),
474 ( "data", ITdata, 0 ),
475 ( "default", ITdefault, 0 ),
476 ( "deriving", ITderiving, 0 ),
478 ( "else", ITelse, 0 ),
479 ( "hiding", IThiding, 0 ),
481 ( "import", ITimport, 0 ),
483 ( "infix", ITinfix, 0 ),
484 ( "infixl", ITinfixl, 0 ),
485 ( "infixr", ITinfixr, 0 ),
486 ( "instance", ITinstance, 0 ),
488 ( "module", ITmodule, 0 ),
489 ( "newtype", ITnewtype, 0 ),
491 ( "qualified", ITqualified, 0 ),
492 ( "then", ITthen, 0 ),
493 ( "type", ITtype, 0 ),
494 ( "where", ITwhere, 0 ),
495 ( "_scc_", ITscc, 0 ), -- ToDo: remove
497 ( "forall", ITforall, bit glaExtsBit),
498 ( "mdo", ITmdo, bit glaExtsBit),
500 ( "foreign", ITforeign, bit ffiBit),
501 ( "export", ITexport, bit ffiBit),
502 ( "label", ITlabel, bit ffiBit),
503 ( "dynamic", ITdynamic, bit ffiBit),
504 ( "safe", ITsafe, bit ffiBit),
505 ( "threadsafe", ITthreadsafe, bit ffiBit),
506 ( "unsafe", ITunsafe, bit ffiBit),
507 ( "stdcall", ITstdcallconv, bit ffiBit),
508 ( "ccall", ITccallconv, bit ffiBit),
509 ( "dotnet", ITdotnet, bit ffiBit),
511 ( "rec", ITrec, bit arrowsBit),
512 ( "proc", ITproc, bit arrowsBit)
515 reservedSymsFM = listToUFM $
516 map (\ (x,y,z) -> (mkFastString x,(y,z)))
517 [ ("..", ITdotdot, 0)
518 ,(":", ITcolon, 0) -- (:) is a reserved op,
519 -- meaning only list cons
532 ,("*", ITstar, bit glaExtsBit) -- For data T (a::*) = MkT
533 ,(".", ITdot, bit glaExtsBit) -- For 'forall a . t'
535 ,("-<", ITlarrowtail, bit arrowsBit)
536 ,(">-", ITrarrowtail, bit arrowsBit)
537 ,("-<<", ITLarrowtail, bit arrowsBit)
538 ,(">>-", ITRarrowtail, bit arrowsBit)
541 -- -----------------------------------------------------------------------------
544 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
546 special :: Token -> Action
547 special tok span _buf len = return (L span tok)
549 token, layout_token :: Token -> Action
550 token t span buf len = return (L span t)
551 layout_token t span buf len = pushLexState layout >> return (L span t)
553 idtoken :: (StringBuffer -> Int -> Token) -> Action
554 idtoken f span buf len = return (L span $! (f buf len))
556 skip_one_varid :: (FastString -> Token) -> Action
557 skip_one_varid f span buf len
558 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
560 strtoken :: (String -> Token) -> Action
561 strtoken f span buf len =
562 return (L span $! (f $! lexemeToString buf len))
564 init_strtoken :: Int -> (String -> Token) -> Action
565 -- like strtoken, but drops the last N character(s)
566 init_strtoken drop f span buf len =
567 return (L span $! (f $! lexemeToString buf (len-drop)))
569 begin :: Int -> Action
570 begin code _span _str _len = do pushLexState code; lexToken
573 pop _span _buf _len = do popLexState; lexToken
575 pop_and :: Action -> Action
576 pop_and act span buf len = do popLexState; act span buf len
578 notFollowedBy char _ _ _ (_,buf) = atEnd buf || currentChar buf /= char
580 notFollowedBySymbol _ _ _ (_,buf)
581 = atEnd buf || currentChar buf `notElem` "!#$%&*+./<=>?@\\^|-~"
583 ifExtension pred bits _ _ _ = pred bits
586 nested comments require traversing by hand, they can't be parsed
587 using regular expressions.
589 nested_comment :: Action
590 nested_comment span _str _len = do
593 where go 0 input = do setInput input; lexToken
595 case alexGetChar input of
600 case alexGetChar input of
602 Just ('\125',input) -> go (n-1) input
603 Just (c,_) -> go n input
605 case alexGetChar input of
607 Just ('-',input') -> go (n+1) input'
608 Just (c,input) -> go n input
611 err input = do failLocMsgP (srcSpanStart span) (fst input)
614 open_brace, close_brace :: Action
615 open_brace span _str _len = do
617 setContext (NoLayout:ctx)
618 return (L span ITocurly)
619 close_brace span _str _len = do
621 return (L span ITccurly)
623 -- We have to be careful not to count M.<varid> as a qualified name
624 -- when <varid> is a keyword. We hack around this by catching
625 -- the offending tokens afterward, and re-lexing in a different state.
626 check_qvarid span buf len = do
627 case lookupUFM reservedWordsFM var of
629 | not (isSpecial keyword) ->
633 b <- extension (\i -> exts .&. i /= 0)
636 _other -> return token
638 (mod,var) = splitQualName buf len
639 token = L span (ITqvarid (mod,var))
642 setInput (srcSpanStart span,buf)
643 pushLexState bad_qvarid
646 qvarid buf len = ITqvarid $! splitQualName buf len
647 qconid buf len = ITqconid $! splitQualName buf len
649 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
650 -- takes a StringBuffer and a length, and returns the module name
651 -- and identifier parts of a qualified name. Splits at the *last* dot,
652 -- because of hierarchical module names.
653 splitQualName orig_buf len = split orig_buf 0 0
656 | n == len = done dot_off
657 | lookAhead buf n == '.' = split2 buf n (n+1)
658 | otherwise = split buf dot_off (n+1)
660 -- careful, we might get names like M....
661 -- so, if the character after the dot is not upper-case, this is
662 -- the end of the qualifier part.
664 | isUpper (lookAhead buf n) = split buf dot_off (n+1)
665 | otherwise = done dot_off
668 (lexemeToFastString orig_buf dot_off,
669 lexemeToFastString (stepOnBy (dot_off+1) orig_buf) (len - dot_off -1))
672 case lookupUFM reservedWordsFM fs of
673 Just (keyword,0) -> do
675 return (L span keyword)
676 Just (keyword,exts) -> do
677 b <- extension (\i -> exts .&. i /= 0)
678 if b then do maybe_layout keyword
679 return (L span keyword)
680 else return (L span (ITvarid fs))
681 _other -> return (L span (ITvarid fs))
683 fs = lexemeToFastString buf len
685 conid buf len = ITconid fs
686 where fs = lexemeToFastString buf len
688 qvarsym buf len = ITqvarsym $! splitQualName buf len
689 qconsym buf len = ITqconsym $! splitQualName buf len
691 varsym = sym ITvarsym
692 consym = sym ITconsym
694 sym con span buf len =
695 case lookupUFM reservedSymsFM fs of
696 Just (keyword,0) -> return (L span keyword)
697 Just (keyword,exts) -> do
698 b <- extension (\i -> exts .&. i /= 0)
699 if b then return (L span keyword)
700 else return (L span $! con fs)
701 _other -> return (L span $! con fs)
703 fs = lexemeToFastString buf len
705 tok_decimal span buf len
706 = return (L span (ITinteger $! parseInteger buf len 10 oct_or_dec))
708 tok_octal span buf len
709 = return (L span (ITinteger $! parseInteger (stepOnBy 2 buf) (len-2) 8 oct_or_dec))
711 tok_hexadecimal span buf len
712 = return (L span (ITinteger $! parseInteger (stepOnBy 2 buf) (len-2) 16 hex))
714 prim_decimal span buf len
715 = return (L span (ITprimint $! parseInteger buf (len-1) 10 oct_or_dec))
717 prim_octal span buf len
718 = return (L span (ITprimint $! parseInteger (stepOnBy 2 buf) (len-3) 8 oct_or_dec))
720 prim_hexadecimal span buf len
721 = return (L span (ITprimint $! parseInteger (stepOnBy 2 buf) (len-3) 16 hex))
723 tok_float str = ITrational $! readRational__ str
724 prim_float str = ITprimfloat $! readRational__ str
725 prim_double str = ITprimdouble $! readRational__ str
727 parseInteger :: StringBuffer -> Int -> Integer -> (Char->Int) -> Integer
728 parseInteger buf len radix to_int
730 where go i x | i == len = x
731 | otherwise = go (i+1) (x * radix + toInteger (to_int (lookAhead buf i)))
733 -- -----------------------------------------------------------------------------
736 -- we're at the first token on a line, insert layout tokens if necessary
738 do_bol span _str _len = do
739 pos <- getOffside (srcSpanEnd span)
742 --trace "layout: inserting '}'" $ do
744 -- do NOT pop the lex state, we might have a ';' to insert
745 return (L span ITvccurly)
747 --trace "layout: inserting ';'" $ do
749 return (L span ITsemi)
754 -- certain keywords put us in the "layout" state, where we might
755 -- add an opening curly brace.
756 maybe_layout ITdo = pushLexState layout_do
757 maybe_layout ITmdo = pushLexState layout_do
758 maybe_layout ITof = pushLexState layout
759 maybe_layout ITlet = pushLexState layout
760 maybe_layout ITwhere = pushLexState layout
761 maybe_layout ITrec = pushLexState layout
762 maybe_layout _ = return ()
764 -- Pushing a new implicit layout context. If the indentation of the
765 -- next token is not greater than the previous layout context, then
766 -- Haskell 98 says that the new layout context should be empty; that is
767 -- the lexer must generate {}.
769 -- We are slightly more lenient than this: when the new context is started
770 -- by a 'do', then we allow the new context to be at the same indentation as
771 -- the previous context. This is what the 'strict' argument is for.
773 new_layout_context strict span _buf _len = do
775 let offset = srcSpanStartCol span
778 Layout prev_off : _ |
779 (strict && prev_off >= offset ||
780 not strict && prev_off > offset) -> do
781 -- token is indented to the left of the previous context.
782 -- we must generate a {} sequence now.
783 pushLexState layout_left
784 return (L span ITvocurly)
786 setContext (Layout offset : ctx)
787 return (L span ITvocurly)
789 do_layout_left span _buf _len = do
791 pushLexState bol -- we must be at the start of a line
792 return (L span ITvccurly)
794 -- -----------------------------------------------------------------------------
797 set_line :: Int -> Action
798 set_line code span buf len = do
799 let line = parseInteger buf len 10 oct_or_dec
800 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
801 -- subtract one: the line number refers to the *following* line
806 set_file :: Int -> Action
807 set_file code span buf len = do
808 let file = lexemeToFastString (stepOn buf) (len-2)
809 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
814 -- -----------------------------------------------------------------------------
817 -- This stuff is horrible. I hates it.
819 lex_string_tok :: Action
820 lex_string_tok span buf len = do
823 return (L (mkSrcSpan (srcSpanStart span) end) tok)
825 lex_string :: String -> P Token
828 case alexGetChar i of
833 glaexts <- extension glaExtsEnabled
837 case alexGetChar i of
841 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
842 else let s' = mkFastStringNarrow (reverse s) in
843 -- always a narrow string/byte array
844 return (ITprimstring s')
846 return (ITstring (mkFastString (reverse s)))
848 return (ITstring (mkFastString (reverse s)))
851 | Just ('&',i) <- next -> do
852 setInput i; lex_string s
853 | Just (c,i) <- next, is_space c -> do
854 setInput i; lex_stringgap s
855 where next = alexGetChar i
865 c | is_space c -> lex_stringgap s
869 lex_char_tok :: Action
870 -- Here we are basically parsing character literals, such as 'x' or '\n'
871 -- but, when Template Haskell is on, we additionally spot
872 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
873 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
874 -- So we have to do two characters of lookahead: when we see 'x we need to
875 -- see if there's a trailing quote
876 lex_char_tok span buf len = do -- We've seen '
877 i1 <- getInput -- Look ahead to first character
878 let loc = srcSpanStart span
879 case alexGetChar i1 of
882 Just ('\'', i2@(end2,_)) -> do -- We've seen ''
883 th_exts <- extension thEnabled
886 return (L (mkSrcSpan loc end2) ITtyQuote)
889 Just ('\\', i2@(end2,_)) -> do -- We've seen 'backslash
892 mc <- getCharOrFail -- Trailing quote
893 if mc == '\'' then finish_char_tok loc lit_ch
896 Just (c, i2@(end2,_)) | not (is_any c) -> lit_error
899 -- We've seen 'x, where x is a valid character
900 -- (i.e. not newline etc) but not a quote or backslash
901 case alexGetChar i2 of -- Look ahead one more character
903 Just ('\'', i3) -> do -- We've seen 'x'
905 finish_char_tok loc c
906 _other -> do -- We've seen 'x not followed by quote
907 -- If TH is on, just parse the quote only
908 th_exts <- extension thEnabled
909 if th_exts then return (L (mkSrcSpan loc (fst i1)) ITvarQuote)
912 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
913 finish_char_tok loc ch -- We've already seen the closing quote
914 -- Just need to check for trailing #
915 = do glaexts <- extension glaExtsEnabled
916 i@(end,_) <- getInput
918 case alexGetChar i of
919 Just ('#',i@(end,_)) -> do
921 return (L (mkSrcSpan loc end) (ITprimchar ch))
923 return (L (mkSrcSpan loc end) (ITchar ch))
925 return (L (mkSrcSpan loc end) (ITchar ch))
932 c | is_any c -> return c
949 '^' -> do c <- getCharOrFail
950 if c >= '@' && c <= '_'
951 then return (chr (ord c - ord '@'))
954 'x' -> readNum is_hexdigit 16 hex
955 'o' -> readNum is_octdigit 8 oct_or_dec
956 x | is_digit x -> readNum2 is_digit 10 oct_or_dec (oct_or_dec x)
960 case alexGetChar i of
963 case alexGetChar i2 of
966 let str = [c1,c2,c3] in
967 case [ (c,rest) | (p,c) <- silly_escape_chars,
968 Just rest <- [maybePrefixMatch p str] ] of
969 (escape_char,[]):_ -> do
972 (escape_char,_:_):_ -> do
977 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
978 readNum is_digit base conv = do
981 then readNum2 is_digit base conv (conv c)
984 readNum2 is_digit base conv i = do
987 where read i input = do
988 case alexGetChar input of
989 Just (c,input') | is_digit c -> do
990 read (i*base + conv c) input'
993 if i >= 0 && i <= 0x10FFFF
999 || (c >= 'a' && c <= 'f')
1000 || (c >= 'A' && c <= 'F')
1002 hex c | is_digit c = ord c - ord '0'
1003 | otherwise = ord (to_lower c) - ord 'a' + 10
1005 oct_or_dec c = ord c - ord '0'
1007 is_octdigit c = c >= '0' && c <= '7'
1010 | c >= 'A' && c <= 'Z' = chr (ord c - (ord 'A' - ord 'a'))
1013 silly_escape_chars = [
1050 lit_error = lexError "lexical error in string/character literal"
1052 getCharOrFail :: P Char
1055 case alexGetChar i of
1056 Nothing -> lexError "unexpected end-of-file in string/character literal"
1057 Just (c,i) -> do setInput i; return c
1059 -- -----------------------------------------------------------------------------
1062 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
1064 (n,d,s) <- readFix r
1066 return ((n%1)*10^^(k-d), t)
1069 (ds,s) <- lexDecDigits r
1070 (ds',t) <- lexDotDigits s
1071 return (read (ds++ds'), length ds', t)
1073 readExp (e:s) | e `elem` "eE" = readExp' s
1074 readExp s = return (0,s)
1076 readExp' ('+':s) = readDec s
1077 readExp' ('-':s) = do
1080 readExp' s = readDec s
1083 (ds,r) <- nonnull isDigit s
1084 return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
1087 lexDecDigits = nonnull isDigit
1089 lexDotDigits ('.':s) = return (span isDigit s)
1090 lexDotDigits s = return ("",s)
1092 nonnull p s = do (cs@(_:_),t) <- return (span p s)
1095 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
1096 readRational__ top_s
1098 '-' : xs -> - (read_me xs)
1102 = case (do { (x,"") <- readRational s ; return x }) of
1104 [] -> error ("readRational__: no parse:" ++ top_s)
1105 _ -> error ("readRational__: ambiguous parse:" ++ top_s)
1107 -- -----------------------------------------------------------------------------
1117 SrcSpan -- The start and end of the text span related to
1118 -- the error. Might be used in environments which can
1119 -- show this span, e.g. by highlighting it.
1120 Message -- The error message
1122 data PState = PState {
1123 buffer :: StringBuffer,
1124 last_loc :: SrcSpan, -- pos of previous token
1125 last_len :: !Int, -- len of previous token
1126 loc :: SrcLoc, -- current loc (end of prev token + 1)
1127 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1128 context :: [LayoutContext],
1131 -- last_loc and last_len are used when generating error messages,
1132 -- and in pushCurrentContext only.
1134 newtype P a = P { unP :: PState -> ParseResult a }
1136 instance Monad P where
1142 returnP a = P $ \s -> POk s a
1144 thenP :: P a -> (a -> P b) -> P b
1145 (P m) `thenP` k = P $ \ s ->
1147 POk s1 a -> (unP (k a)) s1
1148 PFailed span err -> PFailed span err
1150 failP :: String -> P a
1151 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1153 failMsgP :: String -> P a
1154 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1156 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1157 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1159 failSpanMsgP :: SrcSpan -> String -> P a
1160 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1162 extension :: (Int -> Bool) -> P Bool
1163 extension p = P $ \s -> POk s (p $! extsBitmap s)
1166 getExts = P $ \s -> POk s (extsBitmap s)
1168 setSrcLoc :: SrcLoc -> P ()
1169 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1171 getSrcLoc :: P SrcLoc
1172 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1174 setLastToken :: SrcSpan -> Int -> P ()
1175 setLastToken loc len = P $ \s -> POk s{ last_loc=loc, last_len=len } ()
1177 type AlexInput = (SrcLoc,StringBuffer)
1179 alexInputPrevChar :: AlexInput -> Char
1180 alexInputPrevChar (_,s) = prevChar s '\n'
1182 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1185 | otherwise = c `seq` loc' `seq` s' `seq` Just (c, (loc', s'))
1186 where c = currentChar s
1187 loc' = advanceSrcLoc loc c
1190 getInput :: P AlexInput
1191 getInput = P $ \s@PState{ loc=l, buffer=b } -> POk s (l,b)
1193 setInput :: AlexInput -> P ()
1194 setInput (l,b) = P $ \s -> POk s{ loc=l, buffer=b } ()
1196 pushLexState :: Int -> P ()
1197 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1199 popLexState :: P Int
1200 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1202 getLexState :: P Int
1203 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1205 -- for reasons of efficiency, flags indicating language extensions (eg,
1206 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1209 glaExtsBit, ffiBit, parrBit :: Int
1217 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1218 glaExtsEnabled flags = testBit flags glaExtsBit
1219 ffiEnabled flags = testBit flags ffiBit
1220 parrEnabled flags = testBit flags parrBit
1221 arrowsEnabled flags = testBit flags arrowsBit
1222 thEnabled flags = testBit flags thBit
1223 ipEnabled flags = testBit flags ipBit
1225 -- create a parse state
1227 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1228 mkPState buf loc flags =
1231 last_loc = mkSrcSpan loc loc,
1234 extsBitmap = fromIntegral bitmap,
1236 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1237 -- we begin in the layout state if toplev_layout is set
1240 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1241 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1242 .|. parrBit `setBitIf` dopt Opt_PArr flags
1243 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1244 .|. thBit `setBitIf` dopt Opt_TH flags
1245 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1247 setBitIf :: Int -> Bool -> Int
1248 b `setBitIf` cond | cond = bit b
1251 getContext :: P [LayoutContext]
1252 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1254 setContext :: [LayoutContext] -> P ()
1255 setContext ctx = P $ \s -> POk s{context=ctx} ()
1258 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1259 loc = loc, last_len = len, last_loc = last_loc }) ->
1261 (_:tl) -> POk s{ context = tl } ()
1262 [] -> PFailed last_loc (srcParseErr buf len)
1264 -- Push a new layout context at the indentation of the last token read.
1265 -- This is only used at the outer level of a module when the 'module'
1266 -- keyword is missing.
1267 pushCurrentContext :: P ()
1268 pushCurrentContext = P $ \ s@PState{ last_loc=loc, context=ctx } ->
1269 POk s{ context = Layout (srcSpanStartCol loc) : ctx} ()
1271 getOffside :: SrcLoc -> P Ordering
1272 getOffside loc = P $ \s@PState{context=stk} ->
1273 let ord = case stk of
1274 (Layout n:_) -> compare (srcLocCol loc) n
1278 -- ---------------------------------------------------------------------------
1279 -- Construct a parse error
1282 :: StringBuffer -- current buffer (placed just after the last token)
1283 -> Int -- length of the previous token
1286 = hcat [ if null token
1287 then ptext SLIT("parse error (possibly incorrect indentation)")
1288 else hcat [ptext SLIT("parse error on input "),
1289 char '`', text token, char '\'']
1291 where token = lexemeToString (stepOnBy (-len) buf) len
1293 -- Report a parse failure, giving the span of the previous token as
1294 -- the location of the error. This is the entry point for errors
1295 -- detected during parsing.
1297 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1298 last_loc = last_loc, loc = loc } ->
1299 PFailed last_loc (srcParseErr buf len)
1301 -- A lexical error is reported at a particular position in the source file,
1302 -- not over a token range. TODO: this is slightly wrong, because we record
1303 -- the error at the character position following the one which caused the
1304 -- error. We should somehow back up by one character.
1305 lexError :: String -> P a
1308 i@(end,_) <- getInput
1309 failLocMsgP loc end str
1311 -- -----------------------------------------------------------------------------
1312 -- This is the top-level function: called from the parser each time a
1313 -- new token is to be read from the input.
1315 lexer :: (Located Token -> P a) -> P a
1317 tok@(L _ tok__) <- lexToken
1318 --trace ("token: " ++ show tok__) $ do
1321 lexToken :: P (Located Token)
1323 inp@(loc1,buf) <- getInput
1326 case alexScanUser exts inp sc of
1327 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1329 return (L span ITeof)
1330 AlexError (loc2,_) -> do failLocMsgP loc1 loc2 "lexical error"
1331 AlexSkip inp2 _ -> do
1334 AlexToken inp2@(end,buf2) len t -> do
1336 let span = mkSrcSpan loc1 end
1337 span `seq` setLastToken span len