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 ,("∀", ITforall, bit glaExtsBit)
564 ,("→", ITrarrow, bit glaExtsBit)
565 ,("←", ITlarrow, bit glaExtsBit)
566 ,("⋯", ITdotdot, bit glaExtsBit)
570 -- -----------------------------------------------------------------------------
573 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
575 special :: Token -> Action
576 special tok span _buf len = return (L span tok)
578 token, layout_token :: Token -> Action
579 token t span buf len = return (L span t)
580 layout_token t span buf len = pushLexState layout >> return (L span t)
582 idtoken :: (StringBuffer -> Int -> Token) -> Action
583 idtoken f span buf len = return (L span $! (f buf len))
585 skip_one_varid :: (FastString -> Token) -> Action
586 skip_one_varid f span buf len
587 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
589 strtoken :: (String -> Token) -> Action
590 strtoken f span buf len =
591 return (L span $! (f $! lexemeToString buf len))
593 init_strtoken :: Int -> (String -> Token) -> Action
594 -- like strtoken, but drops the last N character(s)
595 init_strtoken drop f span buf len =
596 return (L span $! (f $! lexemeToString buf (len-drop)))
598 begin :: Int -> Action
599 begin code _span _str _len = do pushLexState code; lexToken
602 pop _span _buf _len = do popLexState; lexToken
604 pop_and :: Action -> Action
605 pop_and act span buf len = do popLexState; act span buf len
607 notFollowedBy char _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf /= char
609 notFollowedBySymbol _ _ _ (AI _ _ buf)
610 = atEnd buf || currentChar buf `notElem` "!#$%&*+./<=>?@\\^|-~"
612 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
614 ifExtension pred bits _ _ _ = pred bits
617 nested comments require traversing by hand, they can't be parsed
618 using regular expressions.
620 nested_comment :: Action
621 nested_comment span _str _len = do
624 where go 0 input = do setInput input; lexToken
626 case alexGetChar input of
631 case alexGetChar input of
633 Just ('\125',input) -> go (n-1) input
634 Just (c,_) -> go n input
636 case alexGetChar input of
638 Just ('-',input') -> go (n+1) input'
639 Just (c,input) -> go n input
642 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
644 open_brace, close_brace :: Action
645 open_brace span _str _len = do
647 setContext (NoLayout:ctx)
648 return (L span ITocurly)
649 close_brace span _str _len = do
651 return (L span ITccurly)
653 -- We have to be careful not to count M.<varid> as a qualified name
654 -- when <varid> is a keyword. We hack around this by catching
655 -- the offending tokens afterward, and re-lexing in a different state.
656 check_qvarid span buf len = do
657 case lookupUFM reservedWordsFM var of
659 | not (isSpecial keyword) ->
663 b <- extension (\i -> exts .&. i /= 0)
666 _other -> return token
668 (mod,var) = splitQualName buf len
669 token = L span (ITqvarid (mod,var))
672 (AI _ offs _) <- getInput
673 setInput (AI (srcSpanStart span) (offs-len) buf)
674 pushLexState bad_qvarid
677 qvarid buf len = ITqvarid $! splitQualName buf len
678 qconid buf len = ITqconid $! splitQualName buf len
680 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
681 -- takes a StringBuffer and a length, and returns the module name
682 -- and identifier parts of a qualified name. Splits at the *last* dot,
683 -- because of hierarchical module names.
684 splitQualName orig_buf len = split orig_buf orig_buf
687 | orig_buf `byteDiff` buf >= len = done dot_buf
688 | c == '.' = found_dot buf'
689 | otherwise = split buf' dot_buf
691 (c,buf') = nextChar buf
693 -- careful, we might get names like M....
694 -- so, if the character after the dot is not upper-case, this is
695 -- the end of the qualifier part.
696 found_dot buf -- buf points after the '.'
697 | isUpper c = split buf' buf
698 | otherwise = done buf
700 (c,buf') = nextChar buf
703 (lexemeToFastString orig_buf (qual_size - 1),
704 lexemeToFastString dot_buf (len - qual_size))
706 qual_size = orig_buf `byteDiff` dot_buf
709 case lookupUFM reservedWordsFM fs of
710 Just (keyword,0) -> do
712 return (L span keyword)
713 Just (keyword,exts) -> do
714 b <- extension (\i -> exts .&. i /= 0)
715 if b then do maybe_layout keyword
716 return (L span keyword)
717 else return (L span (ITvarid fs))
718 _other -> return (L span (ITvarid fs))
720 fs = lexemeToFastString buf len
722 conid buf len = ITconid fs
723 where fs = lexemeToFastString buf len
725 qvarsym buf len = ITqvarsym $! splitQualName buf len
726 qconsym buf len = ITqconsym $! splitQualName buf len
728 varsym = sym ITvarsym
729 consym = sym ITconsym
731 sym con span buf len =
732 case lookupUFM reservedSymsFM fs of
733 Just (keyword,0) -> return (L span keyword)
734 Just (keyword,exts) -> do
735 b <- extension (\i -> exts .&. i /= 0)
736 if b then return (L span keyword)
737 else return (L span $! con fs)
738 _other -> return (L span $! con fs)
740 fs = lexemeToFastString buf len
742 tok_decimal span buf len
743 = return (L span (ITinteger $! parseInteger buf len 10 octDecDigit))
745 tok_octal span buf len
746 = return (L span (ITinteger $! parseInteger (offsetBytes 2 buf) (len-2) 8 octDecDigit))
748 tok_hexadecimal span buf len
749 = return (L span (ITinteger $! parseInteger (offsetBytes 2 buf) (len-2) 16 hexDigit))
751 prim_decimal span buf len
752 = return (L span (ITprimint $! parseInteger buf (len-1) 10 octDecDigit))
754 prim_octal span buf len
755 = return (L span (ITprimint $! parseInteger (offsetBytes 2 buf) (len-3) 8 octDecDigit))
757 prim_hexadecimal span buf len
758 = return (L span (ITprimint $! parseInteger (offsetBytes 2 buf) (len-3) 16 hexDigit))
760 tok_float str = ITrational $! readRational str
761 prim_float str = ITprimfloat $! readRational str
762 prim_double str = ITprimdouble $! readRational str
764 -- -----------------------------------------------------------------------------
767 -- we're at the first token on a line, insert layout tokens if necessary
769 do_bol span _str _len = do
773 --trace "layout: inserting '}'" $ do
775 -- do NOT pop the lex state, we might have a ';' to insert
776 return (L span ITvccurly)
778 --trace "layout: inserting ';'" $ do
780 return (L span ITsemi)
785 -- certain keywords put us in the "layout" state, where we might
786 -- add an opening curly brace.
787 maybe_layout ITdo = pushLexState layout_do
788 maybe_layout ITmdo = pushLexState layout_do
789 maybe_layout ITof = pushLexState layout
790 maybe_layout ITlet = pushLexState layout
791 maybe_layout ITwhere = pushLexState layout
792 maybe_layout ITrec = pushLexState layout
793 maybe_layout _ = return ()
795 -- Pushing a new implicit layout context. If the indentation of the
796 -- next token is not greater than the previous layout context, then
797 -- Haskell 98 says that the new layout context should be empty; that is
798 -- the lexer must generate {}.
800 -- We are slightly more lenient than this: when the new context is started
801 -- by a 'do', then we allow the new context to be at the same indentation as
802 -- the previous context. This is what the 'strict' argument is for.
804 new_layout_context strict span _buf _len = do
806 (AI _ offset _) <- getInput
809 Layout prev_off : _ |
810 (strict && prev_off >= offset ||
811 not strict && prev_off > offset) -> do
812 -- token is indented to the left of the previous context.
813 -- we must generate a {} sequence now.
814 pushLexState layout_left
815 return (L span ITvocurly)
817 setContext (Layout offset : ctx)
818 return (L span ITvocurly)
820 do_layout_left span _buf _len = do
822 pushLexState bol -- we must be at the start of a line
823 return (L span ITvccurly)
825 -- -----------------------------------------------------------------------------
828 setLine :: Int -> Action
829 setLine code span buf len = do
830 let line = parseInteger buf len 10 octDecDigit
831 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
832 -- subtract one: the line number refers to the *following* line
837 setFile :: Int -> Action
838 setFile code span buf len = do
839 let file = lexemeToFastString (stepOn buf) (len-2)
840 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
845 -- -----------------------------------------------------------------------------
848 -- This stuff is horrible. I hates it.
850 lex_string_tok :: Action
851 lex_string_tok span buf len = do
854 return (L (mkSrcSpan (srcSpanStart span) end) tok)
856 lex_string :: String -> P Token
859 case alexGetChar' i of
864 glaexts <- extension glaExtsEnabled
868 case alexGetChar' i of
872 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
873 else let s' = mkZFastString (reverse s) in
874 return (ITprimstring s')
875 -- mkZFastString is a hack to avoid encoding the
876 -- string in UTF-8. We just want the exact bytes.
878 return (ITstring (mkFastString (reverse s)))
880 return (ITstring (mkFastString (reverse s)))
883 | Just ('&',i) <- next -> do
884 setInput i; lex_string s
885 | Just (c,i) <- next, is_space c -> do
886 setInput i; lex_stringgap s
887 where next = alexGetChar' i
897 c | is_space c -> lex_stringgap s
901 lex_char_tok :: Action
902 -- Here we are basically parsing character literals, such as 'x' or '\n'
903 -- but, when Template Haskell is on, we additionally spot
904 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
905 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
906 -- So we have to do two characters of lookahead: when we see 'x we need to
907 -- see if there's a trailing quote
908 lex_char_tok span buf len = do -- We've seen '
909 i1 <- getInput -- Look ahead to first character
910 let loc = srcSpanStart span
911 case alexGetChar' i1 of
914 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
915 th_exts <- extension thEnabled
918 return (L (mkSrcSpan loc end2) ITtyQuote)
921 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
924 mc <- getCharOrFail -- Trailing quote
925 if mc == '\'' then finish_char_tok loc lit_ch
926 else do setInput i2; lit_error
928 Just (c, i2@(AI end2 _ _))
929 | not (isAny c) -> lit_error
932 -- We've seen 'x, where x is a valid character
933 -- (i.e. not newline etc) but not a quote or backslash
934 case alexGetChar' i2 of -- Look ahead one more character
936 Just ('\'', i3) -> do -- We've seen 'x'
938 finish_char_tok loc c
939 _other -> do -- We've seen 'x not followed by quote
940 -- If TH is on, just parse the quote only
941 th_exts <- extension thEnabled
942 let (AI end _ _) = i1
943 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
944 else do setInput i2; lit_error
946 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
947 finish_char_tok loc ch -- We've already seen the closing quote
948 -- Just need to check for trailing #
949 = do glaexts <- extension glaExtsEnabled
950 i@(AI end _ _) <- getInput
952 case alexGetChar' i of
953 Just ('#',i@(AI end _ _)) -> do
955 return (L (mkSrcSpan loc end) (ITprimchar ch))
957 return (L (mkSrcSpan loc end) (ITchar ch))
959 return (L (mkSrcSpan loc end) (ITchar ch))
961 lex_char :: Char -> AlexInput -> P Char
964 '\\' -> do setInput inp; lex_escape
965 c | isAny c -> do setInput inp; return c
968 isAny c | c > '\xff' = isPrint c
969 | otherwise = is_any c
985 '^' -> do c <- getCharOrFail
986 if c >= '@' && c <= '_'
987 then return (chr (ord c - ord '@'))
990 'x' -> readNum is_hexdigit 16 hexDigit
991 'o' -> readNum is_octdigit 8 octDecDigit
992 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
996 case alexGetChar' i of
999 case alexGetChar' i2 of
1000 Nothing -> do setInput i2; lit_error
1002 let str = [c1,c2,c3] in
1003 case [ (c,rest) | (p,c) <- silly_escape_chars,
1004 Just rest <- [maybePrefixMatch p str] ] of
1005 (escape_char,[]):_ -> do
1008 (escape_char,_:_):_ -> do
1013 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1014 readNum is_digit base conv = do
1018 then readNum2 is_digit base conv (conv c)
1019 else do setInput i; lit_error
1021 readNum2 is_digit base conv i = do
1024 where read i input = do
1025 case alexGetChar' input of
1026 Just (c,input') | is_digit c -> do
1027 read (i*base + conv c) input'
1029 if i >= 0 && i <= 0x10FFFF
1030 then do setInput input; return (chr i)
1033 silly_escape_chars = [
1070 -- before calling lit_error, ensure that the current input is pointing to
1071 -- the position of the error in the buffer. This is so that we can report
1072 -- a correct location to the user, but also so we can detect UTF-8 decoding
1073 -- errors if they occur.
1074 lit_error = lexError "lexical error in string/character literal"
1076 getCharOrFail :: P Char
1079 case alexGetChar' i of
1080 Nothing -> lexError "unexpected end-of-file in string/character literal"
1081 Just (c,i) -> do setInput i; return c
1083 -- -----------------------------------------------------------------------------
1093 SrcSpan -- The start and end of the text span related to
1094 -- the error. Might be used in environments which can
1095 -- show this span, e.g. by highlighting it.
1096 Message -- The error message
1098 data PState = PState {
1099 buffer :: StringBuffer,
1100 last_loc :: SrcSpan, -- pos of previous token
1101 last_offs :: !Int, -- offset of the previous token from the
1102 -- beginning of the current line.
1103 -- \t is equal to 8 spaces.
1104 last_len :: !Int, -- len of previous token
1105 loc :: SrcLoc, -- current loc (end of prev token + 1)
1106 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1107 context :: [LayoutContext],
1110 -- last_loc and last_len are used when generating error messages,
1111 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1112 -- current token to happyError, we could at least get rid of last_len.
1113 -- Getting rid of last_loc would require finding another way to
1114 -- implement pushCurrentContext (which is only called from one place).
1116 newtype P a = P { unP :: PState -> ParseResult a }
1118 instance Monad P where
1124 returnP a = P $ \s -> POk s a
1126 thenP :: P a -> (a -> P b) -> P b
1127 (P m) `thenP` k = P $ \ s ->
1129 POk s1 a -> (unP (k a)) s1
1130 PFailed span err -> PFailed span err
1132 failP :: String -> P a
1133 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1135 failMsgP :: String -> P a
1136 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1138 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1139 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1141 failSpanMsgP :: SrcSpan -> String -> P a
1142 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1144 extension :: (Int -> Bool) -> P Bool
1145 extension p = P $ \s -> POk s (p $! extsBitmap s)
1148 getExts = P $ \s -> POk s (extsBitmap s)
1150 setSrcLoc :: SrcLoc -> P ()
1151 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1153 getSrcLoc :: P SrcLoc
1154 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1156 setLastToken :: SrcSpan -> Int -> P ()
1157 setLastToken loc len = P $ \s -> POk s{ last_loc=loc, last_len=len } ()
1159 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1161 alexInputPrevChar :: AlexInput -> Char
1162 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1164 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1165 alexGetChar (AI loc ofs s)
1167 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1168 Just (adj_c, (AI loc' ofs' s'))
1169 where (c,s') = nextChar s
1170 loc' = advanceSrcLoc loc c
1171 ofs' = advanceOffs c ofs
1179 other_graphic = '\x6'
1182 #if __GLASGOW_HASKELL__ < 605
1183 = c -- no Unicode support
1185 | c <= '\x06' = non_graphic
1188 case generalCategory c of
1189 UppercaseLetter -> upper
1190 LowercaseLetter -> lower
1191 TitlecaseLetter -> upper
1192 ModifierLetter -> other_graphic
1193 OtherLetter -> other_graphic
1194 NonSpacingMark -> other_graphic
1195 SpacingCombiningMark -> other_graphic
1196 EnclosingMark -> other_graphic
1197 DecimalNumber -> digit
1198 LetterNumber -> other_graphic
1199 OtherNumber -> other_graphic
1200 ConnectorPunctuation -> other_graphic
1201 DashPunctuation -> other_graphic
1202 OpenPunctuation -> other_graphic
1203 ClosePunctuation -> other_graphic
1204 InitialQuote -> other_graphic
1205 FinalQuote -> other_graphic
1206 OtherPunctuation -> other_graphic
1207 MathSymbol -> symbol
1208 CurrencySymbol -> symbol
1209 ModifierSymbol -> symbol
1210 OtherSymbol -> symbol
1212 _other -> non_graphic
1215 -- This version does not squash unicode characters, it is used when
1217 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1218 alexGetChar' (AI loc ofs s)
1220 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1221 Just (c, (AI loc' ofs' s'))
1222 where (c,s') = nextChar s
1223 loc' = advanceSrcLoc loc c
1224 ofs' = advanceOffs c ofs
1226 advanceOffs :: Char -> Int -> Int
1227 advanceOffs '\n' offs = 0
1228 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1229 advanceOffs _ offs = offs + 1
1231 getInput :: P AlexInput
1232 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1234 setInput :: AlexInput -> P ()
1235 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1237 pushLexState :: Int -> P ()
1238 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1240 popLexState :: P Int
1241 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1243 getLexState :: P Int
1244 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1246 -- for reasons of efficiency, flags indicating language extensions (eg,
1247 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1250 glaExtsBit, ffiBit, parrBit :: Int
1257 tvBit = 7 -- Scoped type variables enables 'forall' keyword
1259 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1260 glaExtsEnabled flags = testBit flags glaExtsBit
1261 ffiEnabled flags = testBit flags ffiBit
1262 parrEnabled flags = testBit flags parrBit
1263 arrowsEnabled flags = testBit flags arrowsBit
1264 thEnabled flags = testBit flags thBit
1265 ipEnabled flags = testBit flags ipBit
1266 tvEnabled flags = testBit flags tvBit
1268 -- create a parse state
1270 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1271 mkPState buf loc flags =
1274 last_loc = mkSrcSpan loc loc,
1278 extsBitmap = fromIntegral bitmap,
1280 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1281 -- we begin in the layout state if toplev_layout is set
1284 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1285 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1286 .|. parrBit `setBitIf` dopt Opt_PArr flags
1287 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1288 .|. thBit `setBitIf` dopt Opt_TH flags
1289 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1290 .|. tvBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1292 setBitIf :: Int -> Bool -> Int
1293 b `setBitIf` cond | cond = bit b
1296 getContext :: P [LayoutContext]
1297 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1299 setContext :: [LayoutContext] -> P ()
1300 setContext ctx = P $ \s -> POk s{context=ctx} ()
1303 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1304 loc = loc, last_len = len, last_loc = last_loc }) ->
1306 (_:tl) -> POk s{ context = tl } ()
1307 [] -> PFailed last_loc (srcParseErr buf len)
1309 -- Push a new layout context at the indentation of the last token read.
1310 -- This is only used at the outer level of a module when the 'module'
1311 -- keyword is missing.
1312 pushCurrentContext :: P ()
1313 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_len=len, context=ctx } ->
1314 POk s{context = Layout (offs-len) : ctx} ()
1316 getOffside :: P Ordering
1317 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1318 let ord = case stk of
1319 (Layout n:_) -> compare offs n
1323 -- ---------------------------------------------------------------------------
1324 -- Construct a parse error
1327 :: StringBuffer -- current buffer (placed just after the last token)
1328 -> Int -- length of the previous token
1331 = hcat [ if null token
1332 then ptext SLIT("parse error (possibly incorrect indentation)")
1333 else hcat [ptext SLIT("parse error on input "),
1334 char '`', text token, char '\'']
1336 where token = lexemeToString (offsetBytes (-len) buf) len
1338 -- Report a parse failure, giving the span of the previous token as
1339 -- the location of the error. This is the entry point for errors
1340 -- detected during parsing.
1342 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1343 last_loc = last_loc } ->
1344 PFailed last_loc (srcParseErr buf len)
1346 -- A lexical error is reported at a particular position in the source file,
1347 -- not over a token range.
1348 lexError :: String -> P a
1351 i@(AI end _ buf) <- getInput
1352 reportLexError loc end buf str
1354 -- -----------------------------------------------------------------------------
1355 -- This is the top-level function: called from the parser each time a
1356 -- new token is to be read from the input.
1358 lexer :: (Located Token -> P a) -> P a
1360 tok@(L _ tok__) <- lexToken
1361 --trace ("token: " ++ show tok__) $ do
1364 lexToken :: P (Located Token)
1366 inp@(AI loc1 _ buf) <- getInput
1369 case alexScanUser exts inp sc of
1370 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1372 return (L span ITeof)
1373 AlexError (AI loc2 _ buf) -> do
1374 reportLexError loc1 loc2 buf "lexical error"
1375 AlexSkip inp2 _ -> do
1378 AlexToken inp2@(AI end _ buf2) len t -> do
1380 let span = mkSrcSpan loc1 end
1381 let bytes = byteDiff buf buf2
1382 span `seq` setLastToken span bytes
1385 -- ToDo: Alex reports the buffer at the start of the erroneous lexeme,
1386 -- but it would be more informative to report the location where the
1387 -- error was actually discovered, especially if this is a decoding
1389 reportLexError loc1 loc2 buf str =
1391 c = fst (nextChar buf)
1393 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1394 then failLocMsgP loc2 loc2 "UTF-8 decoding error"
1395 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)