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, PState(..),
26 P(..), ParseResult(..), getSrcLoc,
27 failLocMsgP, failSpanMsgP, srcParseFail,
28 popContext, pushCurrentContext, setLastToken, setSrcLoc,
29 getLexState, popLexState, pushLexState
32 #include "HsVersions.h"
34 import ErrUtils ( Message )
43 import Util ( maybePrefixMatch, readRational )
51 $whitechar = [\ \t\n\r\f\v\xa0]
52 $white_no_nl = $whitechar # \n
56 $digit = [$ascdigit $unidigit]
58 $special = [\(\)\,\;\[\]\`\{\}]
59 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~]
61 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
64 $asclarge = [A-Z \xc0-\xd6 \xd8-\xde]
65 $large = [$asclarge $unilarge]
68 $ascsmall = [a-z \xdf-\xf6 \xf8-\xff]
69 $small = [$ascsmall $unismall \_]
71 $graphic = [$small $large $symbol $digit $special \:\"\']
74 $hexit = [$digit A-F a-f]
75 $symchar = [$symbol \:]
77 $idchar = [$small $large $digit \']
79 @varid = $small $idchar*
80 @conid = $large $idchar*
82 @varsym = $symbol $symchar*
83 @consym = \: $symchar*
87 @hexadecimal = $hexit+
88 @exponent = [eE] [\-\+]? @decimal
90 -- we support the hierarchical module name extension:
93 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
97 -- everywhere: skip whitespace and comments
100 -- Everywhere: deal with nested comments. We explicitly rule out
101 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
102 -- (this can happen even though pragmas will normally take precedence due to
103 -- longest-match, because pragmas aren't valid in every state, but comments
105 "{-" / { notFollowedBy '#' } { nested_comment }
107 -- Single-line comments are a bit tricky. Haskell 98 says that two or
108 -- more dashes followed by a symbol should be parsed as a varsym, so we
109 -- have to exclude those.
110 -- The regex says: "munch all the characters after the dashes, as long as
111 -- the first one is not a symbol".
112 "--"\-* [^$symbol] .* ;
113 "--"\-* / { atEOL } ;
115 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
116 -- blank lines) until we find a non-whitespace character, then do layout
119 -- One slight wibble here: what if the line begins with {-#? In
120 -- theory, we have to lex the pragma to see if it's one we recognise,
121 -- and if it is, then we backtrack and do_bol, otherwise we treat it
122 -- as a nested comment. We don't bother with this: if the line begins
123 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
126 ^\# (line)? { begin line_prag1 }
127 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
128 ^\# \! .* \n ; -- #!, for scripts
132 -- after a layout keyword (let, where, do, of), we begin a new layout
133 -- context if the curly brace is missing.
134 -- Careful! This stuff is quite delicate.
135 <layout, layout_do> {
136 \{ / { notFollowedBy '-' } { pop_and open_brace }
137 -- we might encounter {-# here, but {- has been handled already
139 ^\# (line)? { begin line_prag1 }
142 -- do is treated in a subtly different way, see new_layout_context
143 <layout> () { new_layout_context True }
144 <layout_do> () { new_layout_context False }
146 -- after a new layout context which was found to be to the left of the
147 -- previous context, we have generated a '{' token, and we now need to
148 -- generate a matching '}' token.
149 <layout_left> () { do_layout_left }
151 <0,glaexts> \n { begin bol }
153 "{-#" $whitechar* (line|LINE) { begin line_prag2 }
155 -- single-line line pragmas, of the form
156 -- # <line> "<file>" <extra-stuff> \n
157 <line_prag1> $digit+ { setLine line_prag1a }
158 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
159 <line_prag1b> .* { pop }
161 -- Haskell-style line pragmas, of the form
162 -- {-# LINE <line> "<file>" #-}
163 <line_prag2> $digit+ { setLine line_prag2a }
164 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
165 <line_prag2b> "#-}"|"-}" { pop }
166 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
167 -- with older versions of GHC which generated these.
170 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
171 { token ITspecialise_prag }
172 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
173 "{-#" $whitechar* (INLINE|inline) { token ITinline_prag }
174 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
175 { token ITnoinline_prag }
176 "{-#" $whitechar* (RULES|rules) { token ITrules_prag }
177 "{-#" $whitechar* (DEPRECATED|deprecated)
178 { token ITdeprecated_prag }
179 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
180 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
181 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
183 "{-#" { nested_comment }
185 -- ToDo: should only be valid inside a pragma:
186 "#-}" { token ITclose_prag}
190 -- '0' state: ordinary lexemes
191 -- 'glaexts' state: glasgow extensions (postfix '#', etc.)
196 "[:" / { ifExtension parrEnabled } { token ITopabrack }
197 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
201 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
202 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
203 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
204 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
205 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
206 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
207 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
208 "$(" / { ifExtension thEnabled } { token ITparenEscape }
212 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
213 { special IToparenbar }
214 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
218 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
219 \% @varid / { ifExtension ipEnabled } { skip_one_varid ITsplitipvarid }
223 "(#" / { notFollowedBySymbol } { token IToubxparen }
224 "#)" { token ITcubxparen }
225 "{|" { token ITocurlybar }
226 "|}" { token ITccurlybar }
230 \( { special IToparen }
231 \) { special ITcparen }
232 \[ { special ITobrack }
233 \] { special ITcbrack }
234 \, { special ITcomma }
235 \; { special ITsemi }
236 \` { special ITbackquote }
243 @qual @varid { check_qvarid }
244 @qual @conid { idtoken qconid }
246 @conid { idtoken conid }
249 -- after an illegal qvarid, such as 'M.let',
250 -- we back up and try again in the bad_qvarid state:
252 @conid { pop_and (idtoken conid) }
253 @qual @conid { pop_and (idtoken qconid) }
257 @qual @varid "#"+ { idtoken qvarid }
258 @qual @conid "#"+ { idtoken qconid }
259 @varid "#"+ { varid }
260 @conid "#"+ { idtoken conid }
266 @qual @varsym { idtoken qvarsym }
267 @qual @consym { idtoken qconsym }
273 @decimal { tok_decimal }
274 0[oO] @octal { tok_octal }
275 0[xX] @hexadecimal { tok_hexadecimal }
279 @decimal \# { prim_decimal }
280 0[oO] @octal \# { prim_octal }
281 0[xX] @hexadecimal \# { prim_hexadecimal }
284 <0,glaexts> @floating_point { strtoken tok_float }
285 <glaexts> @floating_point \# { init_strtoken 1 prim_float }
286 <glaexts> @floating_point \# \# { init_strtoken 2 prim_double }
288 -- Strings and chars are lexed by hand-written code. The reason is
289 -- that even if we recognise the string or char here in the regex
290 -- lexer, we would still have to parse the string afterward in order
291 -- to convert it to a String.
294 \" { lex_string_tok }
298 -- work around bug in Alex 2.0
299 #if __GLASGOW_HASKELL__ < 503
300 unsafeAt arr i = arr ! i
303 -- -----------------------------------------------------------------------------
307 = ITas -- Haskell keywords
331 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
333 | ITforall -- GHC extension keywords
346 | ITspecialise_prag -- Pragmas
354 | ITcore_prag -- hdaume: core annotations
358 | ITdotdot -- reserved symbols
374 | ITbiglam -- GHC-extension symbols
376 | ITocurly -- special symbols
378 | ITocurlybar -- {|, for type applications
379 | ITccurlybar -- |}, for type applications
383 | ITopabrack -- [:, for parallel arrays with -fparr
384 | ITcpabrack -- :], for parallel arrays with -fparr
395 | ITvarid FastString -- identifiers
397 | ITvarsym FastString
398 | ITconsym FastString
399 | ITqvarid (FastString,FastString)
400 | ITqconid (FastString,FastString)
401 | ITqvarsym (FastString,FastString)
402 | ITqconsym (FastString,FastString)
404 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
405 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
407 | ITpragma StringBuffer
410 | ITstring FastString
412 | ITrational Rational
415 | ITprimstring FastString
417 | ITprimfloat Rational
418 | ITprimdouble Rational
420 -- MetaHaskell extension tokens
421 | ITopenExpQuote -- [| or [e|
422 | ITopenPatQuote -- [p|
423 | ITopenDecQuote -- [d|
424 | ITopenTypQuote -- [t|
426 | ITidEscape FastString -- $x
427 | ITparenEscape -- $(
431 -- Arrow notation extension
438 | ITLarrowtail -- -<<
439 | ITRarrowtail -- >>-
441 | ITunknown String -- Used when the lexer can't make sense of it
442 | ITeof -- end of file token
444 deriving Show -- debugging
447 isSpecial :: Token -> Bool
448 -- If we see M.x, where x is a keyword, but
449 -- is special, we treat is as just plain M.x,
451 isSpecial ITas = True
452 isSpecial IThiding = True
453 isSpecial ITqualified = True
454 isSpecial ITforall = True
455 isSpecial ITexport = True
456 isSpecial ITlabel = True
457 isSpecial ITdynamic = True
458 isSpecial ITsafe = True
459 isSpecial ITthreadsafe = True
460 isSpecial ITunsafe = True
461 isSpecial ITccallconv = True
462 isSpecial ITstdcallconv = True
463 isSpecial ITmdo = True
466 -- the bitmap provided as the third component indicates whether the
467 -- corresponding extension keyword is valid under the extension options
468 -- provided to the compiler; if the extension corresponding to *any* of the
469 -- bits set in the bitmap is enabled, the keyword is valid (this setup
470 -- facilitates using a keyword in two different extensions that can be
471 -- activated independently)
473 reservedWordsFM = listToUFM $
474 map (\(x, y, z) -> (mkFastString x, (y, z)))
475 [( "_", ITunderscore, 0 ),
477 ( "case", ITcase, 0 ),
478 ( "class", ITclass, 0 ),
479 ( "data", ITdata, 0 ),
480 ( "default", ITdefault, 0 ),
481 ( "deriving", ITderiving, 0 ),
483 ( "else", ITelse, 0 ),
484 ( "hiding", IThiding, 0 ),
486 ( "import", ITimport, 0 ),
488 ( "infix", ITinfix, 0 ),
489 ( "infixl", ITinfixl, 0 ),
490 ( "infixr", ITinfixr, 0 ),
491 ( "instance", ITinstance, 0 ),
493 ( "module", ITmodule, 0 ),
494 ( "newtype", ITnewtype, 0 ),
496 ( "qualified", ITqualified, 0 ),
497 ( "then", ITthen, 0 ),
498 ( "type", ITtype, 0 ),
499 ( "where", ITwhere, 0 ),
500 ( "_scc_", ITscc, 0 ), -- ToDo: remove
502 ( "forall", ITforall, bit glaExtsBit),
503 ( "mdo", ITmdo, bit glaExtsBit),
505 ( "foreign", ITforeign, bit ffiBit),
506 ( "export", ITexport, bit ffiBit),
507 ( "label", ITlabel, bit ffiBit),
508 ( "dynamic", ITdynamic, bit ffiBit),
509 ( "safe", ITsafe, bit ffiBit),
510 ( "threadsafe", ITthreadsafe, bit ffiBit),
511 ( "unsafe", ITunsafe, bit ffiBit),
512 ( "stdcall", ITstdcallconv, bit ffiBit),
513 ( "ccall", ITccallconv, bit ffiBit),
514 ( "dotnet", ITdotnet, bit ffiBit),
516 ( "rec", ITrec, bit arrowsBit),
517 ( "proc", ITproc, bit arrowsBit)
520 reservedSymsFM = listToUFM $
521 map (\ (x,y,z) -> (mkFastString x,(y,z)))
522 [ ("..", ITdotdot, 0)
523 ,(":", ITcolon, 0) -- (:) is a reserved op,
524 -- meaning only list cons
537 ,("*", ITstar, bit glaExtsBit) -- For data T (a::*) = MkT
538 ,(".", ITdot, bit glaExtsBit) -- For 'forall a . t'
540 ,("-<", ITlarrowtail, bit arrowsBit)
541 ,(">-", ITrarrowtail, bit arrowsBit)
542 ,("-<<", ITLarrowtail, bit arrowsBit)
543 ,(">>-", ITRarrowtail, bit arrowsBit)
546 -- -----------------------------------------------------------------------------
549 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
551 special :: Token -> Action
552 special tok span _buf len = return (L span tok)
554 token, layout_token :: Token -> Action
555 token t span buf len = return (L span t)
556 layout_token t span buf len = pushLexState layout >> return (L span t)
558 idtoken :: (StringBuffer -> Int -> Token) -> Action
559 idtoken f span buf len = return (L span $! (f buf len))
561 skip_one_varid :: (FastString -> Token) -> Action
562 skip_one_varid f span buf len
563 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
565 strtoken :: (String -> Token) -> Action
566 strtoken f span buf len =
567 return (L span $! (f $! lexemeToString buf len))
569 init_strtoken :: Int -> (String -> Token) -> Action
570 -- like strtoken, but drops the last N character(s)
571 init_strtoken drop f span buf len =
572 return (L span $! (f $! lexemeToString buf (len-drop)))
574 begin :: Int -> Action
575 begin code _span _str _len = do pushLexState code; lexToken
578 pop _span _buf _len = do popLexState; lexToken
580 pop_and :: Action -> Action
581 pop_and act span buf len = do popLexState; act span buf len
583 notFollowedBy char _ _ _ (_,buf) = atEnd buf || currentChar buf /= char
585 notFollowedBySymbol _ _ _ (_,buf)
586 = atEnd buf || currentChar buf `notElem` "!#$%&*+./<=>?@\\^|-~"
588 atEOL _ _ _ (_,buf) = atEnd buf || currentChar buf == '\n'
590 ifExtension pred bits _ _ _ = pred bits
593 nested comments require traversing by hand, they can't be parsed
594 using regular expressions.
596 nested_comment :: Action
597 nested_comment span _str _len = do
600 where go 0 input = do setInput input; lexToken
602 case alexGetChar input of
607 case alexGetChar input of
609 Just ('\125',input) -> go (n-1) input
610 Just (c,_) -> go n input
612 case alexGetChar input of
614 Just ('-',input') -> go (n+1) input'
615 Just (c,input) -> go n input
618 err input = do failLocMsgP (srcSpanStart span) (fst input)
621 open_brace, close_brace :: Action
622 open_brace span _str _len = do
624 setContext (NoLayout:ctx)
625 return (L span ITocurly)
626 close_brace span _str _len = do
628 return (L span ITccurly)
630 -- We have to be careful not to count M.<varid> as a qualified name
631 -- when <varid> is a keyword. We hack around this by catching
632 -- the offending tokens afterward, and re-lexing in a different state.
633 check_qvarid span buf len = do
634 case lookupUFM reservedWordsFM var of
636 | not (isSpecial keyword) ->
640 b <- extension (\i -> exts .&. i /= 0)
643 _other -> return token
645 (mod,var) = splitQualName buf len
646 token = L span (ITqvarid (mod,var))
649 setInput (srcSpanStart span,buf)
650 pushLexState bad_qvarid
653 qvarid buf len = ITqvarid $! splitQualName buf len
654 qconid buf len = ITqconid $! splitQualName buf len
656 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
657 -- takes a StringBuffer and a length, and returns the module name
658 -- and identifier parts of a qualified name. Splits at the *last* dot,
659 -- because of hierarchical module names.
660 splitQualName orig_buf len = split orig_buf 0 0
663 | n == len = done dot_off
664 | lookAhead buf n == '.' = split2 buf n (n+1)
665 | otherwise = split buf dot_off (n+1)
667 -- careful, we might get names like M....
668 -- so, if the character after the dot is not upper-case, this is
669 -- the end of the qualifier part.
671 | isUpper (lookAhead buf n) = split buf dot_off (n+1)
672 | otherwise = done dot_off
675 (lexemeToFastString orig_buf dot_off,
676 lexemeToFastString (stepOnBy (dot_off+1) orig_buf) (len - dot_off -1))
679 case lookupUFM reservedWordsFM fs of
680 Just (keyword,0) -> do
682 return (L span keyword)
683 Just (keyword,exts) -> do
684 b <- extension (\i -> exts .&. i /= 0)
685 if b then do maybe_layout keyword
686 return (L span keyword)
687 else return (L span (ITvarid fs))
688 _other -> return (L span (ITvarid fs))
690 fs = lexemeToFastString buf len
692 conid buf len = ITconid fs
693 where fs = lexemeToFastString buf len
695 qvarsym buf len = ITqvarsym $! splitQualName buf len
696 qconsym buf len = ITqconsym $! splitQualName buf len
698 varsym = sym ITvarsym
699 consym = sym ITconsym
701 sym con span buf len =
702 case lookupUFM reservedSymsFM fs of
703 Just (keyword,0) -> return (L span keyword)
704 Just (keyword,exts) -> do
705 b <- extension (\i -> exts .&. i /= 0)
706 if b then return (L span keyword)
707 else return (L span $! con fs)
708 _other -> return (L span $! con fs)
710 fs = lexemeToFastString buf len
712 tok_decimal span buf len
713 = return (L span (ITinteger $! parseInteger buf len 10 octDecDigit))
715 tok_octal span buf len
716 = return (L span (ITinteger $! parseInteger (stepOnBy 2 buf) (len-2) 8 octDecDigit))
718 tok_hexadecimal span buf len
719 = return (L span (ITinteger $! parseInteger (stepOnBy 2 buf) (len-2) 16 hexDigit))
721 prim_decimal span buf len
722 = return (L span (ITprimint $! parseInteger buf (len-1) 10 octDecDigit))
724 prim_octal span buf len
725 = return (L span (ITprimint $! parseInteger (stepOnBy 2 buf) (len-3) 8 octDecDigit))
727 prim_hexadecimal span buf len
728 = return (L span (ITprimint $! parseInteger (stepOnBy 2 buf) (len-3) 16 hexDigit))
730 tok_float str = ITrational $! readRational str
731 prim_float str = ITprimfloat $! readRational str
732 prim_double str = ITprimdouble $! readRational str
734 -- -----------------------------------------------------------------------------
737 -- we're at the first token on a line, insert layout tokens if necessary
739 do_bol span _str _len = do
740 pos <- getOffside (srcSpanEnd span)
743 --trace "layout: inserting '}'" $ do
745 -- do NOT pop the lex state, we might have a ';' to insert
746 return (L span ITvccurly)
748 --trace "layout: inserting ';'" $ do
750 return (L span ITsemi)
755 -- certain keywords put us in the "layout" state, where we might
756 -- add an opening curly brace.
757 maybe_layout ITdo = pushLexState layout_do
758 maybe_layout ITmdo = pushLexState layout_do
759 maybe_layout ITof = pushLexState layout
760 maybe_layout ITlet = pushLexState layout
761 maybe_layout ITwhere = pushLexState layout
762 maybe_layout ITrec = pushLexState layout
763 maybe_layout _ = return ()
765 -- Pushing a new implicit layout context. If the indentation of the
766 -- next token is not greater than the previous layout context, then
767 -- Haskell 98 says that the new layout context should be empty; that is
768 -- the lexer must generate {}.
770 -- We are slightly more lenient than this: when the new context is started
771 -- by a 'do', then we allow the new context to be at the same indentation as
772 -- the previous context. This is what the 'strict' argument is for.
774 new_layout_context strict span _buf _len = do
776 let offset = srcSpanStartCol span
779 Layout prev_off : _ |
780 (strict && prev_off >= offset ||
781 not strict && prev_off > offset) -> do
782 -- token is indented to the left of the previous context.
783 -- we must generate a {} sequence now.
784 pushLexState layout_left
785 return (L span ITvocurly)
787 setContext (Layout offset : ctx)
788 return (L span ITvocurly)
790 do_layout_left span _buf _len = do
792 pushLexState bol -- we must be at the start of a line
793 return (L span ITvccurly)
795 -- -----------------------------------------------------------------------------
798 setLine :: Int -> Action
799 setLine code span buf len = do
800 let line = parseInteger buf len 10 octDecDigit
801 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
802 -- subtract one: the line number refers to the *following* line
807 setFile :: Int -> Action
808 setFile code span buf len = do
809 let file = lexemeToFastString (stepOn buf) (len-2)
810 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
815 -- -----------------------------------------------------------------------------
818 -- This stuff is horrible. I hates it.
820 lex_string_tok :: Action
821 lex_string_tok span buf len = do
824 return (L (mkSrcSpan (srcSpanStart span) end) tok)
826 lex_string :: String -> P Token
829 case alexGetChar i of
834 glaexts <- extension glaExtsEnabled
838 case alexGetChar i of
842 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
843 else let s' = mkFastStringNarrow (reverse s) in
844 -- always a narrow string/byte array
845 return (ITprimstring s')
847 return (ITstring (mkFastString (reverse s)))
849 return (ITstring (mkFastString (reverse s)))
852 | Just ('&',i) <- next -> do
853 setInput i; lex_string s
854 | Just (c,i) <- next, is_space c -> do
855 setInput i; lex_stringgap s
856 where next = alexGetChar i
866 c | is_space c -> lex_stringgap s
870 lex_char_tok :: Action
871 -- Here we are basically parsing character literals, such as 'x' or '\n'
872 -- but, when Template Haskell is on, we additionally spot
873 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
874 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
875 -- So we have to do two characters of lookahead: when we see 'x we need to
876 -- see if there's a trailing quote
877 lex_char_tok span buf len = do -- We've seen '
878 i1 <- getInput -- Look ahead to first character
879 let loc = srcSpanStart span
880 case alexGetChar i1 of
883 Just ('\'', i2@(end2,_)) -> do -- We've seen ''
884 th_exts <- extension thEnabled
887 return (L (mkSrcSpan loc end2) ITtyQuote)
890 Just ('\\', i2@(end2,_)) -> do -- We've seen 'backslash
893 mc <- getCharOrFail -- Trailing quote
894 if mc == '\'' then finish_char_tok loc lit_ch
897 Just (c, i2@(end2,_)) | not (is_any c) -> lit_error
900 -- We've seen 'x, where x is a valid character
901 -- (i.e. not newline etc) but not a quote or backslash
902 case alexGetChar i2 of -- Look ahead one more character
904 Just ('\'', i3) -> do -- We've seen 'x'
906 finish_char_tok loc c
907 _other -> do -- We've seen 'x not followed by quote
908 -- If TH is on, just parse the quote only
909 th_exts <- extension thEnabled
910 if th_exts then return (L (mkSrcSpan loc (fst i1)) ITvarQuote)
913 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
914 finish_char_tok loc ch -- We've already seen the closing quote
915 -- Just need to check for trailing #
916 = do glaexts <- extension glaExtsEnabled
917 i@(end,_) <- getInput
919 case alexGetChar i of
920 Just ('#',i@(end,_)) -> do
922 return (L (mkSrcSpan loc end) (ITprimchar ch))
924 return (L (mkSrcSpan loc end) (ITchar ch))
926 return (L (mkSrcSpan loc end) (ITchar ch))
933 c | is_any c -> return c
950 '^' -> do c <- getCharOrFail
951 if c >= '@' && c <= '_'
952 then return (chr (ord c - ord '@'))
955 'x' -> readNum is_hexdigit 16 hexDigit
956 'o' -> readNum is_octdigit 8 octDecDigit
957 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
961 case alexGetChar i of
964 case alexGetChar i2 of
967 let str = [c1,c2,c3] in
968 case [ (c,rest) | (p,c) <- silly_escape_chars,
969 Just rest <- [maybePrefixMatch p str] ] of
970 (escape_char,[]):_ -> do
973 (escape_char,_:_):_ -> do
978 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
979 readNum is_digit base conv = do
982 then readNum2 is_digit base conv (conv c)
985 readNum2 is_digit base conv i = do
988 where read i input = do
989 case alexGetChar input of
990 Just (c,input') | is_digit c -> do
991 read (i*base + conv c) input'
994 if i >= 0 && i <= 0x10FFFF
998 silly_escape_chars = [
1035 lit_error = lexError "lexical error in string/character literal"
1037 getCharOrFail :: P Char
1040 case alexGetChar i of
1041 Nothing -> lexError "unexpected end-of-file in string/character literal"
1042 Just (c,i) -> do setInput i; return c
1044 -- -----------------------------------------------------------------------------
1054 SrcSpan -- The start and end of the text span related to
1055 -- the error. Might be used in environments which can
1056 -- show this span, e.g. by highlighting it.
1057 Message -- The error message
1059 data PState = PState {
1060 buffer :: StringBuffer,
1061 last_loc :: SrcSpan, -- pos of previous token
1062 last_len :: !Int, -- len of previous token
1063 loc :: SrcLoc, -- current loc (end of prev token + 1)
1064 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1065 context :: [LayoutContext],
1068 -- last_loc and last_len are used when generating error messages,
1069 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1070 -- current token to happyError, we could at least get rid of last_len.
1071 -- Getting rid of last_loc would require finding another way to
1072 -- implement pushCurrentContext (which is only called from one place).
1074 newtype P a = P { unP :: PState -> ParseResult a }
1076 instance Monad P where
1082 returnP a = P $ \s -> POk s a
1084 thenP :: P a -> (a -> P b) -> P b
1085 (P m) `thenP` k = P $ \ s ->
1087 POk s1 a -> (unP (k a)) s1
1088 PFailed span err -> PFailed span err
1090 failP :: String -> P a
1091 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1093 failMsgP :: String -> P a
1094 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1096 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1097 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1099 failSpanMsgP :: SrcSpan -> String -> P a
1100 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1102 extension :: (Int -> Bool) -> P Bool
1103 extension p = P $ \s -> POk s (p $! extsBitmap s)
1106 getExts = P $ \s -> POk s (extsBitmap s)
1108 setSrcLoc :: SrcLoc -> P ()
1109 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1111 getSrcLoc :: P SrcLoc
1112 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1114 setLastToken :: SrcSpan -> Int -> P ()
1115 setLastToken loc len = P $ \s -> POk s{ last_loc=loc, last_len=len } ()
1117 type AlexInput = (SrcLoc,StringBuffer)
1119 alexInputPrevChar :: AlexInput -> Char
1120 alexInputPrevChar (_,s) = prevChar s '\n'
1122 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1125 | otherwise = c `seq` loc' `seq` s' `seq` Just (c, (loc', s'))
1126 where c = currentChar s
1127 loc' = advanceSrcLoc loc c
1130 getInput :: P AlexInput
1131 getInput = P $ \s@PState{ loc=l, buffer=b } -> POk s (l,b)
1133 setInput :: AlexInput -> P ()
1134 setInput (l,b) = P $ \s -> POk s{ loc=l, buffer=b } ()
1136 pushLexState :: Int -> P ()
1137 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1139 popLexState :: P Int
1140 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1142 getLexState :: P Int
1143 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1145 -- for reasons of efficiency, flags indicating language extensions (eg,
1146 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1149 glaExtsBit, ffiBit, parrBit :: Int
1157 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1158 glaExtsEnabled flags = testBit flags glaExtsBit
1159 ffiEnabled flags = testBit flags ffiBit
1160 parrEnabled flags = testBit flags parrBit
1161 arrowsEnabled flags = testBit flags arrowsBit
1162 thEnabled flags = testBit flags thBit
1163 ipEnabled flags = testBit flags ipBit
1165 -- create a parse state
1167 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1168 mkPState buf loc flags =
1171 last_loc = mkSrcSpan loc loc,
1174 extsBitmap = fromIntegral bitmap,
1176 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1177 -- we begin in the layout state if toplev_layout is set
1180 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1181 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1182 .|. parrBit `setBitIf` dopt Opt_PArr flags
1183 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1184 .|. thBit `setBitIf` dopt Opt_TH flags
1185 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1187 setBitIf :: Int -> Bool -> Int
1188 b `setBitIf` cond | cond = bit b
1191 getContext :: P [LayoutContext]
1192 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1194 setContext :: [LayoutContext] -> P ()
1195 setContext ctx = P $ \s -> POk s{context=ctx} ()
1198 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1199 loc = loc, last_len = len, last_loc = last_loc }) ->
1201 (_:tl) -> POk s{ context = tl } ()
1202 [] -> PFailed last_loc (srcParseErr buf len)
1204 -- Push a new layout context at the indentation of the last token read.
1205 -- This is only used at the outer level of a module when the 'module'
1206 -- keyword is missing.
1207 pushCurrentContext :: P ()
1208 pushCurrentContext = P $ \ s@PState{ last_loc=loc, context=ctx } ->
1209 POk s{ context = Layout (srcSpanStartCol loc) : ctx} ()
1211 getOffside :: SrcLoc -> P Ordering
1212 getOffside loc = P $ \s@PState{context=stk} ->
1213 let ord = case stk of
1214 (Layout n:_) -> compare (srcLocCol loc) n
1218 -- ---------------------------------------------------------------------------
1219 -- Construct a parse error
1222 :: StringBuffer -- current buffer (placed just after the last token)
1223 -> Int -- length of the previous token
1226 = hcat [ if null token
1227 then ptext SLIT("parse error (possibly incorrect indentation)")
1228 else hcat [ptext SLIT("parse error on input "),
1229 char '`', text token, char '\'']
1231 where token = lexemeToString (stepOnBy (-len) buf) len
1233 -- Report a parse failure, giving the span of the previous token as
1234 -- the location of the error. This is the entry point for errors
1235 -- detected during parsing.
1237 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1238 last_loc = last_loc } ->
1239 PFailed last_loc (srcParseErr buf len)
1241 -- A lexical error is reported at a particular position in the source file,
1242 -- not over a token range. TODO: this is slightly wrong, because we record
1243 -- the error at the character position following the one which caused the
1244 -- error. We should somehow back up by one character.
1245 lexError :: String -> P a
1248 i@(end,_) <- getInput
1249 failLocMsgP loc end str
1251 -- -----------------------------------------------------------------------------
1252 -- This is the top-level function: called from the parser each time a
1253 -- new token is to be read from the input.
1255 lexer :: (Located Token -> P a) -> P a
1257 tok@(L _ tok__) <- lexToken
1258 --trace ("token: " ++ show tok__) $ do
1261 lexToken :: P (Located Token)
1263 inp@(loc1,buf) <- getInput
1266 case alexScanUser exts inp sc of
1267 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1269 return (L span ITeof)
1270 AlexError (loc2,_) -> do failLocMsgP loc1 loc2 "lexical error"
1271 AlexSkip inp2 _ -> do
1274 AlexToken inp2@(end,buf2) len t -> do
1276 let span = mkSrcSpan loc1 end
1277 span `seq` setLastToken span len