1 -----------------------------------------------------------------------------
2 -- (c) The University of Glasgow, 2006
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 )
52 $whitechar = [\ \t\n\r\f\v\xa0 $unispace]
53 $white_no_nl = $whitechar # \n
57 $decdigit = $ascdigit -- for now, should really be $digit (ToDo)
58 $digit = [$ascdigit $unidigit]
60 $special = [\(\)\,\;\[\]\`\{\}]
61 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~]
63 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
66 $asclarge = [A-Z \xc0-\xd6 \xd8-\xde]
67 $large = [$asclarge $unilarge]
70 $ascsmall = [a-z \xdf-\xf6 \xf8-\xff]
71 $small = [$ascsmall $unismall \_]
74 $graphic = [$small $large $symbol $digit $special $unigraphic \:\"\']
77 $hexit = [$decdigit A-F a-f]
78 $symchar = [$symbol \:]
80 $idchar = [$small $large $digit \']
82 @varid = $small $idchar*
83 @conid = $large $idchar*
85 @varsym = $symbol $symchar*
86 @consym = \: $symchar*
90 @hexadecimal = $hexit+
91 @exponent = [eE] [\-\+]? @decimal
93 -- we support the hierarchical module name extension:
96 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
100 -- everywhere: skip whitespace and comments
103 -- Everywhere: deal with nested comments. We explicitly rule out
104 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
105 -- (this can happen even though pragmas will normally take precedence due to
106 -- longest-match, because pragmas aren't valid in every state, but comments
108 "{-" / { notFollowedBy '#' } { nested_comment }
110 -- Single-line comments are a bit tricky. Haskell 98 says that two or
111 -- more dashes followed by a symbol should be parsed as a varsym, so we
112 -- have to exclude those.
113 -- The regex says: "munch all the characters after the dashes, as long as
114 -- the first one is not a symbol".
115 "--"\-* [^$symbol :] .* ;
116 "--"\-* / { atEOL } ;
118 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
119 -- blank lines) until we find a non-whitespace character, then do layout
122 -- One slight wibble here: what if the line begins with {-#? In
123 -- theory, we have to lex the pragma to see if it's one we recognise,
124 -- and if it is, then we backtrack and do_bol, otherwise we treat it
125 -- as a nested comment. We don't bother with this: if the line begins
126 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
129 ^\# (line)? { begin line_prag1 }
130 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
131 ^\# \! .* \n ; -- #!, for scripts
135 -- after a layout keyword (let, where, do, of), we begin a new layout
136 -- context if the curly brace is missing.
137 -- Careful! This stuff is quite delicate.
138 <layout, layout_do> {
139 \{ / { notFollowedBy '-' } { pop_and open_brace }
140 -- we might encounter {-# here, but {- has been handled already
142 ^\# (line)? { begin line_prag1 }
145 -- do is treated in a subtly different way, see new_layout_context
146 <layout> () { new_layout_context True }
147 <layout_do> () { new_layout_context False }
149 -- after a new layout context which was found to be to the left of the
150 -- previous context, we have generated a '{' token, and we now need to
151 -- generate a matching '}' token.
152 <layout_left> () { do_layout_left }
154 <0,glaexts> \n { begin bol }
156 "{-#" $whitechar* (line|LINE) { begin line_prag2 }
158 -- single-line line pragmas, of the form
159 -- # <line> "<file>" <extra-stuff> \n
160 <line_prag1> $decdigit+ { setLine line_prag1a }
161 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
162 <line_prag1b> .* { pop }
164 -- Haskell-style line pragmas, of the form
165 -- {-# LINE <line> "<file>" #-}
166 <line_prag2> $decdigit+ { setLine line_prag2a }
167 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
168 <line_prag2b> "#-}"|"-}" { pop }
169 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
170 -- with older versions of GHC which generated these.
172 -- We only want RULES pragmas to be picked up when -fglasgow-exts
173 -- is on, because the contents of the pragma is always written using
174 -- glasgow-exts syntax (using forall etc.), so if glasgow exts are not
175 -- enabled, we're sure to get a parse error.
176 -- (ToDo: we should really emit a warning when ignoring pragmas)
178 "{-#" $whitechar* (RULES|rules) { token ITrules_prag }
181 "{-#" $whitechar* (INLINE|inline) { token (ITinline_prag True) }
182 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
183 { token (ITinline_prag False) }
184 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
185 { token ITspec_prag }
186 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
187 $whitechar* (INLINE|inline) { token (ITspec_inline_prag True) }
188 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
189 $whitechar* (NO(T?)INLINE|no(t?)inline)
190 { token (ITspec_inline_prag False) }
191 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
192 "{-#" $whitechar* (DEPRECATED|deprecated)
193 { token ITdeprecated_prag }
194 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
195 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
196 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
198 "{-#" { nested_comment }
200 -- ToDo: should only be valid inside a pragma:
201 "#-}" { token ITclose_prag}
205 -- '0' state: ordinary lexemes
206 -- 'glaexts' state: glasgow extensions (postfix '#', etc.)
211 "[:" / { ifExtension parrEnabled } { token ITopabrack }
212 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
216 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
217 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
218 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
219 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
220 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
221 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
222 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
223 "$(" / { ifExtension thEnabled } { token ITparenEscape }
227 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
228 { special IToparenbar }
229 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
233 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
234 \% @varid / { ifExtension ipEnabled } { skip_one_varid ITsplitipvarid }
238 "(#" / { notFollowedBySymbol } { token IToubxparen }
239 "#)" { token ITcubxparen }
240 "{|" { token ITocurlybar }
241 "|}" { token ITccurlybar }
245 \( { special IToparen }
246 \) { special ITcparen }
247 \[ { special ITobrack }
248 \] { special ITcbrack }
249 \, { special ITcomma }
250 \; { special ITsemi }
251 \` { special ITbackquote }
258 @qual @varid { check_qvarid }
259 @qual @conid { idtoken qconid }
261 @conid { idtoken conid }
264 -- after an illegal qvarid, such as 'M.let',
265 -- we back up and try again in the bad_qvarid state:
267 @conid { pop_and (idtoken conid) }
268 @qual @conid { pop_and (idtoken qconid) }
272 @qual @varid "#"+ { idtoken qvarid }
273 @qual @conid "#"+ { idtoken qconid }
274 @varid "#"+ { varid }
275 @conid "#"+ { idtoken conid }
281 @qual @varsym { idtoken qvarsym }
282 @qual @consym { idtoken qconsym }
288 @decimal { tok_decimal }
289 0[oO] @octal { tok_octal }
290 0[xX] @hexadecimal { tok_hexadecimal }
294 @decimal \# { prim_decimal }
295 0[oO] @octal \# { prim_octal }
296 0[xX] @hexadecimal \# { prim_hexadecimal }
299 <0,glaexts> @floating_point { strtoken tok_float }
300 <glaexts> @floating_point \# { init_strtoken 1 prim_float }
301 <glaexts> @floating_point \# \# { init_strtoken 2 prim_double }
303 -- Strings and chars are lexed by hand-written code. The reason is
304 -- that even if we recognise the string or char here in the regex
305 -- lexer, we would still have to parse the string afterward in order
306 -- to convert it to a String.
309 \" { lex_string_tok }
313 -- work around bug in Alex 2.0
314 #if __GLASGOW_HASKELL__ < 503
315 unsafeAt arr i = arr ! i
318 -- -----------------------------------------------------------------------------
322 = ITas -- Haskell keywords
346 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
348 | ITforall -- GHC extension keywords
362 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
363 | ITspec_prag -- SPECIALISE
364 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
370 | ITcore_prag -- hdaume: core annotations
374 | ITdotdot -- reserved symbols
390 | ITbiglam -- GHC-extension symbols
392 | ITocurly -- special symbols
394 | ITocurlybar -- {|, for type applications
395 | ITccurlybar -- |}, for type applications
399 | ITopabrack -- [:, for parallel arrays with -fparr
400 | ITcpabrack -- :], for parallel arrays with -fparr
411 | ITvarid FastString -- identifiers
413 | ITvarsym FastString
414 | ITconsym FastString
415 | ITqvarid (FastString,FastString)
416 | ITqconid (FastString,FastString)
417 | ITqvarsym (FastString,FastString)
418 | ITqconsym (FastString,FastString)
420 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
421 | ITsplitipvarid FastString -- GHC extension: implicit param: %x
423 | ITpragma StringBuffer
426 | ITstring FastString
428 | ITrational Rational
431 | ITprimstring FastString
433 | ITprimfloat Rational
434 | ITprimdouble Rational
436 -- MetaHaskell extension tokens
437 | ITopenExpQuote -- [| or [e|
438 | ITopenPatQuote -- [p|
439 | ITopenDecQuote -- [d|
440 | ITopenTypQuote -- [t|
442 | ITidEscape FastString -- $x
443 | ITparenEscape -- $(
447 -- Arrow notation extension
454 | ITLarrowtail -- -<<
455 | ITRarrowtail -- >>-
457 | ITunknown String -- Used when the lexer can't make sense of it
458 | ITeof -- end of file token
460 deriving Show -- debugging
463 isSpecial :: Token -> Bool
464 -- If we see M.x, where x is a keyword, but
465 -- is special, we treat is as just plain M.x,
467 isSpecial ITas = True
468 isSpecial IThiding = True
469 isSpecial ITqualified = True
470 isSpecial ITforall = True
471 isSpecial ITexport = True
472 isSpecial ITlabel = True
473 isSpecial ITdynamic = True
474 isSpecial ITsafe = True
475 isSpecial ITthreadsafe = True
476 isSpecial ITunsafe = True
477 isSpecial ITccallconv = True
478 isSpecial ITstdcallconv = True
479 isSpecial ITmdo = True
482 -- the bitmap provided as the third component indicates whether the
483 -- corresponding extension keyword is valid under the extension options
484 -- provided to the compiler; if the extension corresponding to *any* of the
485 -- bits set in the bitmap is enabled, the keyword is valid (this setup
486 -- facilitates using a keyword in two different extensions that can be
487 -- activated independently)
489 reservedWordsFM = listToUFM $
490 map (\(x, y, z) -> (mkFastString x, (y, z)))
491 [( "_", ITunderscore, 0 ),
493 ( "case", ITcase, 0 ),
494 ( "class", ITclass, 0 ),
495 ( "data", ITdata, 0 ),
496 ( "default", ITdefault, 0 ),
497 ( "deriving", ITderiving, 0 ),
499 ( "else", ITelse, 0 ),
500 ( "hiding", IThiding, 0 ),
502 ( "import", ITimport, 0 ),
504 ( "infix", ITinfix, 0 ),
505 ( "infixl", ITinfixl, 0 ),
506 ( "infixr", ITinfixr, 0 ),
507 ( "instance", ITinstance, 0 ),
509 ( "module", ITmodule, 0 ),
510 ( "newtype", ITnewtype, 0 ),
512 ( "qualified", ITqualified, 0 ),
513 ( "then", ITthen, 0 ),
514 ( "type", ITtype, 0 ),
515 ( "where", ITwhere, 0 ),
516 ( "_scc_", ITscc, 0 ), -- ToDo: remove
518 ( "forall", ITforall, bit tvBit),
519 ( "mdo", ITmdo, bit glaExtsBit),
521 ( "foreign", ITforeign, bit ffiBit),
522 ( "export", ITexport, bit ffiBit),
523 ( "label", ITlabel, bit ffiBit),
524 ( "dynamic", ITdynamic, bit ffiBit),
525 ( "safe", ITsafe, bit ffiBit),
526 ( "threadsafe", ITthreadsafe, bit ffiBit),
527 ( "unsafe", ITunsafe, bit ffiBit),
528 ( "stdcall", ITstdcallconv, bit ffiBit),
529 ( "ccall", ITccallconv, bit ffiBit),
530 ( "dotnet", ITdotnet, bit ffiBit),
532 ( "rec", ITrec, bit arrowsBit),
533 ( "proc", ITproc, bit arrowsBit)
536 reservedSymsFM = listToUFM $
537 map (\ (x,y,z) -> (mkFastString x,(y,z)))
538 [ ("..", ITdotdot, 0)
539 ,(":", ITcolon, 0) -- (:) is a reserved op,
540 -- meaning only list cons
553 ,("*", ITstar, bit glaExtsBit) -- For data T (a::*) = MkT
554 ,(".", ITdot, bit tvBit) -- For 'forall a . t'
556 ,("-<", ITlarrowtail, bit arrowsBit)
557 ,(">-", ITrarrowtail, bit arrowsBit)
558 ,("-<<", ITLarrowtail, bit arrowsBit)
559 ,(">>-", ITRarrowtail, bit arrowsBit)
561 #if __GLASGOW_HASKELL__ >= 605
562 ,("λ", ITlam, bit glaExtsBit)
563 ,("∷", ITdcolon, bit glaExtsBit)
564 ,("⇒", ITdarrow, bit glaExtsBit)
565 ,("∀", ITforall, bit glaExtsBit)
566 ,("→", ITrarrow, bit glaExtsBit)
567 ,("←", ITlarrow, bit glaExtsBit)
568 ,("⋯", ITdotdot, bit glaExtsBit)
572 -- -----------------------------------------------------------------------------
575 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
577 special :: Token -> Action
578 special tok span _buf len = return (L span tok)
580 token, layout_token :: Token -> Action
581 token t span buf len = return (L span t)
582 layout_token t span buf len = pushLexState layout >> return (L span t)
584 idtoken :: (StringBuffer -> Int -> Token) -> Action
585 idtoken f span buf len = return (L span $! (f buf len))
587 skip_one_varid :: (FastString -> Token) -> Action
588 skip_one_varid f span buf len
589 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
591 strtoken :: (String -> Token) -> Action
592 strtoken f span buf len =
593 return (L span $! (f $! lexemeToString buf len))
595 init_strtoken :: Int -> (String -> Token) -> Action
596 -- like strtoken, but drops the last N character(s)
597 init_strtoken drop f span buf len =
598 return (L span $! (f $! lexemeToString buf (len-drop)))
600 begin :: Int -> Action
601 begin code _span _str _len = do pushLexState code; lexToken
604 pop _span _buf _len = do popLexState; lexToken
606 pop_and :: Action -> Action
607 pop_and act span buf len = do popLexState; act span buf len
609 notFollowedBy char _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf /= char
611 notFollowedBySymbol _ _ _ (AI _ _ buf)
612 = atEnd buf || currentChar buf `notElem` "!#$%&*+./<=>?@\\^|-~"
614 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
616 ifExtension pred bits _ _ _ = pred bits
619 nested comments require traversing by hand, they can't be parsed
620 using regular expressions.
622 nested_comment :: Action
623 nested_comment span _str _len = do
626 where go 0 input = do setInput input; lexToken
628 case alexGetChar input of
633 case alexGetChar input of
635 Just ('\125',input) -> go (n-1) input
636 Just (c,_) -> go n input
638 case alexGetChar input of
640 Just ('-',input') -> go (n+1) input'
641 Just (c,input) -> go n input
644 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
646 open_brace, close_brace :: Action
647 open_brace span _str _len = do
649 setContext (NoLayout:ctx)
650 return (L span ITocurly)
651 close_brace span _str _len = do
653 return (L span ITccurly)
655 -- We have to be careful not to count M.<varid> as a qualified name
656 -- when <varid> is a keyword. We hack around this by catching
657 -- the offending tokens afterward, and re-lexing in a different state.
658 check_qvarid span buf len = do
659 case lookupUFM reservedWordsFM var of
661 | not (isSpecial keyword) ->
665 b <- extension (\i -> exts .&. i /= 0)
668 _other -> return token
670 (mod,var) = splitQualName buf len
671 token = L span (ITqvarid (mod,var))
674 (AI _ offs _) <- getInput
675 setInput (AI (srcSpanStart span) (offs-len) buf)
676 pushLexState bad_qvarid
679 qvarid buf len = ITqvarid $! splitQualName buf len
680 qconid buf len = ITqconid $! splitQualName buf len
682 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
683 -- takes a StringBuffer and a length, and returns the module name
684 -- and identifier parts of a qualified name. Splits at the *last* dot,
685 -- because of hierarchical module names.
686 splitQualName orig_buf len = split orig_buf orig_buf
689 | orig_buf `byteDiff` buf >= len = done dot_buf
690 | c == '.' = found_dot buf'
691 | otherwise = split buf' dot_buf
693 (c,buf') = nextChar buf
695 -- careful, we might get names like M....
696 -- so, if the character after the dot is not upper-case, this is
697 -- the end of the qualifier part.
698 found_dot buf -- buf points after the '.'
699 | isUpper c = split buf' buf
700 | otherwise = done buf
702 (c,buf') = nextChar buf
705 (lexemeToFastString orig_buf (qual_size - 1),
706 lexemeToFastString dot_buf (len - qual_size))
708 qual_size = orig_buf `byteDiff` dot_buf
711 case lookupUFM reservedWordsFM fs of
712 Just (keyword,0) -> do
714 return (L span keyword)
715 Just (keyword,exts) -> do
716 b <- extension (\i -> exts .&. i /= 0)
717 if b then do maybe_layout keyword
718 return (L span keyword)
719 else return (L span (ITvarid fs))
720 _other -> return (L span (ITvarid fs))
722 fs = lexemeToFastString buf len
724 conid buf len = ITconid fs
725 where fs = lexemeToFastString buf len
727 qvarsym buf len = ITqvarsym $! splitQualName buf len
728 qconsym buf len = ITqconsym $! splitQualName buf len
730 varsym = sym ITvarsym
731 consym = sym ITconsym
733 sym con span buf len =
734 case lookupUFM reservedSymsFM fs of
735 Just (keyword,0) -> return (L span keyword)
736 Just (keyword,exts) -> do
737 b <- extension (\i -> exts .&. i /= 0)
738 if b then return (L span keyword)
739 else return (L span $! con fs)
740 _other -> return (L span $! con fs)
742 fs = lexemeToFastString buf len
744 tok_decimal span buf len
745 = return (L span (ITinteger $! parseInteger buf len 10 octDecDigit))
747 tok_octal span buf len
748 = return (L span (ITinteger $! parseInteger (offsetBytes 2 buf) (len-2) 8 octDecDigit))
750 tok_hexadecimal span buf len
751 = return (L span (ITinteger $! parseInteger (offsetBytes 2 buf) (len-2) 16 hexDigit))
753 prim_decimal span buf len
754 = return (L span (ITprimint $! parseInteger buf (len-1) 10 octDecDigit))
756 prim_octal span buf len
757 = return (L span (ITprimint $! parseInteger (offsetBytes 2 buf) (len-3) 8 octDecDigit))
759 prim_hexadecimal span buf len
760 = return (L span (ITprimint $! parseInteger (offsetBytes 2 buf) (len-3) 16 hexDigit))
762 tok_float str = ITrational $! readRational str
763 prim_float str = ITprimfloat $! readRational str
764 prim_double str = ITprimdouble $! readRational str
766 -- -----------------------------------------------------------------------------
769 -- we're at the first token on a line, insert layout tokens if necessary
771 do_bol span _str _len = do
775 --trace "layout: inserting '}'" $ do
777 -- do NOT pop the lex state, we might have a ';' to insert
778 return (L span ITvccurly)
780 --trace "layout: inserting ';'" $ do
782 return (L span ITsemi)
787 -- certain keywords put us in the "layout" state, where we might
788 -- add an opening curly brace.
789 maybe_layout ITdo = pushLexState layout_do
790 maybe_layout ITmdo = pushLexState layout_do
791 maybe_layout ITof = pushLexState layout
792 maybe_layout ITlet = pushLexState layout
793 maybe_layout ITwhere = pushLexState layout
794 maybe_layout ITrec = pushLexState layout
795 maybe_layout _ = return ()
797 -- Pushing a new implicit layout context. If the indentation of the
798 -- next token is not greater than the previous layout context, then
799 -- Haskell 98 says that the new layout context should be empty; that is
800 -- the lexer must generate {}.
802 -- We are slightly more lenient than this: when the new context is started
803 -- by a 'do', then we allow the new context to be at the same indentation as
804 -- the previous context. This is what the 'strict' argument is for.
806 new_layout_context strict span _buf _len = do
808 (AI _ offset _) <- getInput
811 Layout prev_off : _ |
812 (strict && prev_off >= offset ||
813 not strict && prev_off > offset) -> do
814 -- token is indented to the left of the previous context.
815 -- we must generate a {} sequence now.
816 pushLexState layout_left
817 return (L span ITvocurly)
819 setContext (Layout offset : ctx)
820 return (L span ITvocurly)
822 do_layout_left span _buf _len = do
824 pushLexState bol -- we must be at the start of a line
825 return (L span ITvccurly)
827 -- -----------------------------------------------------------------------------
830 setLine :: Int -> Action
831 setLine code span buf len = do
832 let line = parseInteger buf len 10 octDecDigit
833 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
834 -- subtract one: the line number refers to the *following* line
839 setFile :: Int -> Action
840 setFile code span buf len = do
841 let file = lexemeToFastString (stepOn buf) (len-2)
842 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
847 -- -----------------------------------------------------------------------------
850 -- This stuff is horrible. I hates it.
852 lex_string_tok :: Action
853 lex_string_tok span buf len = do
856 return (L (mkSrcSpan (srcSpanStart span) end) tok)
858 lex_string :: String -> P Token
861 case alexGetChar' i of
866 glaexts <- extension glaExtsEnabled
870 case alexGetChar' i of
874 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
875 else let s' = mkZFastString (reverse s) in
876 return (ITprimstring s')
877 -- mkZFastString is a hack to avoid encoding the
878 -- string in UTF-8. We just want the exact bytes.
880 return (ITstring (mkFastString (reverse s)))
882 return (ITstring (mkFastString (reverse s)))
885 | Just ('&',i) <- next -> do
886 setInput i; lex_string s
887 | Just (c,i) <- next, is_space c -> do
888 setInput i; lex_stringgap s
889 where next = alexGetChar' i
899 c | is_space c -> lex_stringgap s
903 lex_char_tok :: Action
904 -- Here we are basically parsing character literals, such as 'x' or '\n'
905 -- but, when Template Haskell is on, we additionally spot
906 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
907 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
908 -- So we have to do two characters of lookahead: when we see 'x we need to
909 -- see if there's a trailing quote
910 lex_char_tok span buf len = do -- We've seen '
911 i1 <- getInput -- Look ahead to first character
912 let loc = srcSpanStart span
913 case alexGetChar' i1 of
916 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
917 th_exts <- extension thEnabled
920 return (L (mkSrcSpan loc end2) ITtyQuote)
923 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
926 mc <- getCharOrFail -- Trailing quote
927 if mc == '\'' then finish_char_tok loc lit_ch
928 else do setInput i2; lit_error
930 Just (c, i2@(AI end2 _ _))
931 | not (isAny c) -> lit_error
934 -- We've seen 'x, where x is a valid character
935 -- (i.e. not newline etc) but not a quote or backslash
936 case alexGetChar' i2 of -- Look ahead one more character
938 Just ('\'', i3) -> do -- We've seen 'x'
940 finish_char_tok loc c
941 _other -> do -- We've seen 'x not followed by quote
942 -- If TH is on, just parse the quote only
943 th_exts <- extension thEnabled
944 let (AI end _ _) = i1
945 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
946 else do setInput i2; lit_error
948 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
949 finish_char_tok loc ch -- We've already seen the closing quote
950 -- Just need to check for trailing #
951 = do glaexts <- extension glaExtsEnabled
952 i@(AI end _ _) <- getInput
954 case alexGetChar' i of
955 Just ('#',i@(AI end _ _)) -> do
957 return (L (mkSrcSpan loc end) (ITprimchar ch))
959 return (L (mkSrcSpan loc end) (ITchar ch))
961 return (L (mkSrcSpan loc end) (ITchar ch))
963 lex_char :: Char -> AlexInput -> P Char
966 '\\' -> do setInput inp; lex_escape
967 c | isAny c -> do setInput inp; return c
970 isAny c | c > '\xff' = isPrint c
971 | otherwise = is_any c
987 '^' -> do c <- getCharOrFail
988 if c >= '@' && c <= '_'
989 then return (chr (ord c - ord '@'))
992 'x' -> readNum is_hexdigit 16 hexDigit
993 'o' -> readNum is_octdigit 8 octDecDigit
994 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
998 case alexGetChar' i of
1001 case alexGetChar' i2 of
1002 Nothing -> do setInput i2; lit_error
1004 let str = [c1,c2,c3] in
1005 case [ (c,rest) | (p,c) <- silly_escape_chars,
1006 Just rest <- [maybePrefixMatch p str] ] of
1007 (escape_char,[]):_ -> do
1010 (escape_char,_:_):_ -> do
1015 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1016 readNum is_digit base conv = do
1020 then readNum2 is_digit base conv (conv c)
1021 else do setInput i; lit_error
1023 readNum2 is_digit base conv i = do
1026 where read i input = do
1027 case alexGetChar' input of
1028 Just (c,input') | is_digit c -> do
1029 read (i*base + conv c) input'
1031 if i >= 0 && i <= 0x10FFFF
1032 then do setInput input; return (chr i)
1035 silly_escape_chars = [
1072 -- before calling lit_error, ensure that the current input is pointing to
1073 -- the position of the error in the buffer. This is so that we can report
1074 -- a correct location to the user, but also so we can detect UTF-8 decoding
1075 -- errors if they occur.
1076 lit_error = lexError "lexical error in string/character literal"
1078 getCharOrFail :: P Char
1081 case alexGetChar' i of
1082 Nothing -> lexError "unexpected end-of-file in string/character literal"
1083 Just (c,i) -> do setInput i; return c
1085 -- -----------------------------------------------------------------------------
1095 SrcSpan -- The start and end of the text span related to
1096 -- the error. Might be used in environments which can
1097 -- show this span, e.g. by highlighting it.
1098 Message -- The error message
1100 data PState = PState {
1101 buffer :: StringBuffer,
1102 last_loc :: SrcSpan, -- pos of previous token
1103 last_offs :: !Int, -- offset of the previous token from the
1104 -- beginning of the current line.
1105 -- \t is equal to 8 spaces.
1106 last_len :: !Int, -- len of previous token
1107 loc :: SrcLoc, -- current loc (end of prev token + 1)
1108 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1109 context :: [LayoutContext],
1112 -- last_loc and last_len are used when generating error messages,
1113 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1114 -- current token to happyError, we could at least get rid of last_len.
1115 -- Getting rid of last_loc would require finding another way to
1116 -- implement pushCurrentContext (which is only called from one place).
1118 newtype P a = P { unP :: PState -> ParseResult a }
1120 instance Monad P where
1126 returnP a = P $ \s -> POk s a
1128 thenP :: P a -> (a -> P b) -> P b
1129 (P m) `thenP` k = P $ \ s ->
1131 POk s1 a -> (unP (k a)) s1
1132 PFailed span err -> PFailed span err
1134 failP :: String -> P a
1135 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1137 failMsgP :: String -> P a
1138 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1140 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1141 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1143 failSpanMsgP :: SrcSpan -> String -> P a
1144 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1146 extension :: (Int -> Bool) -> P Bool
1147 extension p = P $ \s -> POk s (p $! extsBitmap s)
1150 getExts = P $ \s -> POk s (extsBitmap s)
1152 setSrcLoc :: SrcLoc -> P ()
1153 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1155 getSrcLoc :: P SrcLoc
1156 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1158 setLastToken :: SrcSpan -> Int -> P ()
1159 setLastToken loc len = P $ \s -> POk s{ last_loc=loc, last_len=len } ()
1161 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1163 alexInputPrevChar :: AlexInput -> Char
1164 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1166 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1167 alexGetChar (AI loc ofs s)
1169 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1170 Just (adj_c, (AI loc' ofs' s'))
1171 where (c,s') = nextChar s
1172 loc' = advanceSrcLoc loc c
1173 ofs' = advanceOffs c ofs
1181 other_graphic = '\x6'
1184 #if __GLASGOW_HASKELL__ < 605
1185 = c -- no Unicode support
1187 | c <= '\x06' = non_graphic
1190 case generalCategory c of
1191 UppercaseLetter -> upper
1192 LowercaseLetter -> lower
1193 TitlecaseLetter -> upper
1194 ModifierLetter -> other_graphic
1195 OtherLetter -> other_graphic
1196 NonSpacingMark -> other_graphic
1197 SpacingCombiningMark -> other_graphic
1198 EnclosingMark -> other_graphic
1199 DecimalNumber -> digit
1200 LetterNumber -> other_graphic
1201 OtherNumber -> other_graphic
1202 ConnectorPunctuation -> other_graphic
1203 DashPunctuation -> other_graphic
1204 OpenPunctuation -> other_graphic
1205 ClosePunctuation -> other_graphic
1206 InitialQuote -> other_graphic
1207 FinalQuote -> other_graphic
1208 OtherPunctuation -> other_graphic
1209 MathSymbol -> symbol
1210 CurrencySymbol -> symbol
1211 ModifierSymbol -> symbol
1212 OtherSymbol -> symbol
1214 _other -> non_graphic
1217 -- This version does not squash unicode characters, it is used when
1219 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1220 alexGetChar' (AI loc ofs s)
1222 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1223 Just (c, (AI loc' ofs' s'))
1224 where (c,s') = nextChar s
1225 loc' = advanceSrcLoc loc c
1226 ofs' = advanceOffs c ofs
1228 advanceOffs :: Char -> Int -> Int
1229 advanceOffs '\n' offs = 0
1230 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1231 advanceOffs _ offs = offs + 1
1233 getInput :: P AlexInput
1234 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1236 setInput :: AlexInput -> P ()
1237 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1239 pushLexState :: Int -> P ()
1240 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1242 popLexState :: P Int
1243 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1245 getLexState :: P Int
1246 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
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
1259 tvBit = 7 -- Scoped type variables enables 'forall' keyword
1261 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1262 glaExtsEnabled flags = testBit flags glaExtsBit
1263 ffiEnabled flags = testBit flags ffiBit
1264 parrEnabled flags = testBit flags parrBit
1265 arrowsEnabled flags = testBit flags arrowsBit
1266 thEnabled flags = testBit flags thBit
1267 ipEnabled flags = testBit flags ipBit
1268 tvEnabled flags = testBit flags tvBit
1270 -- create a parse state
1272 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1273 mkPState buf loc flags =
1276 last_loc = mkSrcSpan loc loc,
1280 extsBitmap = fromIntegral bitmap,
1282 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1283 -- we begin in the layout state if toplev_layout is set
1286 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1287 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1288 .|. parrBit `setBitIf` dopt Opt_PArr flags
1289 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1290 .|. thBit `setBitIf` dopt Opt_TH flags
1291 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1292 .|. tvBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1294 setBitIf :: Int -> Bool -> Int
1295 b `setBitIf` cond | cond = bit b
1298 getContext :: P [LayoutContext]
1299 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1301 setContext :: [LayoutContext] -> P ()
1302 setContext ctx = P $ \s -> POk s{context=ctx} ()
1305 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1306 loc = loc, last_len = len, last_loc = last_loc }) ->
1308 (_:tl) -> POk s{ context = tl } ()
1309 [] -> PFailed last_loc (srcParseErr buf len)
1311 -- Push a new layout context at the indentation of the last token read.
1312 -- This is only used at the outer level of a module when the 'module'
1313 -- keyword is missing.
1314 pushCurrentContext :: P ()
1315 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_len=len, context=ctx } ->
1316 POk s{context = Layout (offs-len) : ctx} ()
1318 getOffside :: P Ordering
1319 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1320 let ord = case stk of
1321 (Layout n:_) -> compare offs n
1325 -- ---------------------------------------------------------------------------
1326 -- Construct a parse error
1329 :: StringBuffer -- current buffer (placed just after the last token)
1330 -> Int -- length of the previous token
1333 = hcat [ if null token
1334 then ptext SLIT("parse error (possibly incorrect indentation)")
1335 else hcat [ptext SLIT("parse error on input "),
1336 char '`', text token, char '\'']
1338 where token = lexemeToString (offsetBytes (-len) buf) len
1340 -- Report a parse failure, giving the span of the previous token as
1341 -- the location of the error. This is the entry point for errors
1342 -- detected during parsing.
1344 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1345 last_loc = last_loc } ->
1346 PFailed last_loc (srcParseErr buf len)
1348 -- A lexical error is reported at a particular position in the source file,
1349 -- not over a token range.
1350 lexError :: String -> P a
1353 i@(AI end _ buf) <- getInput
1354 reportLexError loc end buf str
1356 -- -----------------------------------------------------------------------------
1357 -- This is the top-level function: called from the parser each time a
1358 -- new token is to be read from the input.
1360 lexer :: (Located Token -> P a) -> P a
1362 tok@(L _ tok__) <- lexToken
1363 --trace ("token: " ++ show tok__) $ do
1366 lexToken :: P (Located Token)
1368 inp@(AI loc1 _ buf) <- getInput
1371 case alexScanUser exts inp sc of
1372 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1374 return (L span ITeof)
1375 AlexError (AI loc2 _ buf) -> do
1376 reportLexError loc1 loc2 buf "lexical error"
1377 AlexSkip inp2 _ -> do
1380 AlexToken inp2@(AI end _ buf2) len t -> do
1382 let span = mkSrcSpan loc1 end
1383 let bytes = byteDiff buf buf2
1384 span `seq` setLastToken span bytes
1387 -- ToDo: Alex reports the buffer at the start of the erroneous lexeme,
1388 -- but it would be more informative to report the location where the
1389 -- error was actually discovered, especially if this is a decoding
1391 reportLexError loc1 loc2 buf str =
1393 c = fst (nextChar buf)
1395 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1396 then failLocMsgP loc2 loc2 "UTF-8 decoding error"
1397 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)