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, pragState, mkPState, PState(..),
26 P(..), ParseResult(..), getSrcLoc,
27 failLocMsgP, failSpanMsgP, srcParseFail,
29 popContext, pushCurrentContext, setLastToken, setSrcLoc,
30 getLexState, popLexState, pushLexState,
31 extension, standaloneDerivingEnabled, bangPatEnabled
34 #include "HsVersions.h"
46 import Util ( maybePrefixMatch, readRational )
50 import Data.Char ( chr, isSpace )
54 #if __GLASGOW_HASKELL__ >= 605
55 import Data.Char ( GeneralCategory(..), generalCategory, isPrint, isUpper )
57 import Compat.Unicode ( GeneralCategory(..), generalCategory, isPrint, isUpper )
61 $unispace = \x05 -- Trick Alex into handling Unicode. See alexGetChar.
62 $whitechar = [\ \n\r\f\v\xa0 $unispace]
63 $white_no_nl = $whitechar # \n
67 $unidigit = \x03 -- Trick Alex into handling Unicode. See alexGetChar.
68 $decdigit = $ascdigit -- for now, should really be $digit (ToDo)
69 $digit = [$ascdigit $unidigit]
71 $special = [\(\)\,\;\[\]\`\{\}]
72 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~ \xa1-\xbf \xd7 \xf7]
73 $unisymbol = \x04 -- Trick Alex into handling Unicode. See alexGetChar.
74 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
76 $unilarge = \x01 -- Trick Alex into handling Unicode. See alexGetChar.
77 $asclarge = [A-Z \xc0-\xd6 \xd8-\xde]
78 $large = [$asclarge $unilarge]
80 $unismall = \x02 -- Trick Alex into handling Unicode. See alexGetChar.
81 $ascsmall = [a-z \xdf-\xf6 \xf8-\xff]
82 $small = [$ascsmall $unismall \_]
84 $unigraphic = \x06 -- Trick Alex into handling Unicode. See alexGetChar.
85 $graphic = [$small $large $symbol $digit $special $unigraphic \:\"\']
88 $hexit = [$decdigit A-F a-f]
89 $symchar = [$symbol \:]
91 $idchar = [$small $large $digit \']
93 $docsym = [\| \^ \* \$]
95 @varid = $small $idchar*
96 @conid = $large $idchar*
98 @varsym = $symbol $symchar*
99 @consym = \: $symchar*
101 @decimal = $decdigit+
103 @hexadecimal = $hexit+
104 @exponent = [eE] [\-\+]? @decimal
106 -- we support the hierarchical module name extension:
109 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
111 -- normal signed numerical literals can only be explicitly negative,
112 -- not explicitly positive (contrast @exponent)
114 @signed = @negative ?
118 -- everywhere: skip whitespace and comments
120 $tab+ { warn Opt_WarnTabs (text "Tab character") }
122 -- Everywhere: deal with nested comments. We explicitly rule out
123 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
124 -- (this can happen even though pragmas will normally take precedence due to
125 -- longest-match, because pragmas aren't valid in every state, but comments
126 -- are). We also rule out nested Haddock comments, if the -haddock flag is
129 "{-" / { isNormalComment } { nested_comment lexToken }
131 -- Single-line comments are a bit tricky. Haskell 98 says that two or
132 -- more dashes followed by a symbol should be parsed as a varsym, so we
133 -- have to exclude those.
135 -- Since Haddock comments aren't valid in every state, we need to rule them
138 -- The following two rules match comments that begin with two dashes, but
139 -- continue with a different character. The rules test that this character
140 -- is not a symbol (in which case we'd have a varsym), and that it's not a
141 -- space followed by a Haddock comment symbol (docsym) (in which case we'd
142 -- have a Haddock comment). The rules then munch the rest of the line.
145 "--" [^$symbol : \ ] .* ;
147 -- Next, match Haddock comments if no -haddock flag
149 "-- " $docsym .* / { ifExtension (not . haddockEnabled) } ;
151 -- Now, when we've matched comments that begin with 2 dashes and continue
152 -- with a different character, we need to match comments that begin with three
153 -- or more dashes (which clearly can't be Haddock comments). We only need to
154 -- make sure that the first non-dash character isn't a symbol, and munch the
157 "---"\-* [^$symbol :] .* ;
159 -- Since the previous rules all match dashes followed by at least one
160 -- character, we also need to match a whole line filled with just dashes.
162 "--"\-* / { atEOL } ;
164 -- We need this rule since none of the other single line comment rules
165 -- actually match this case.
169 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
170 -- blank lines) until we find a non-whitespace character, then do layout
173 -- One slight wibble here: what if the line begins with {-#? In
174 -- theory, we have to lex the pragma to see if it's one we recognise,
175 -- and if it is, then we backtrack and do_bol, otherwise we treat it
176 -- as a nested comment. We don't bother with this: if the line begins
177 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
180 ^\# (line)? { begin line_prag1 }
181 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
182 ^\# \! .* \n ; -- #!, for scripts
186 -- after a layout keyword (let, where, do, of), we begin a new layout
187 -- context if the curly brace is missing.
188 -- Careful! This stuff is quite delicate.
189 <layout, layout_do> {
190 \{ / { notFollowedBy '-' } { pop_and open_brace }
191 -- we might encounter {-# here, but {- has been handled already
193 ^\# (line)? { begin line_prag1 }
196 -- do is treated in a subtly different way, see new_layout_context
197 <layout> () { new_layout_context True }
198 <layout_do> () { new_layout_context False }
200 -- after a new layout context which was found to be to the left of the
201 -- previous context, we have generated a '{' token, and we now need to
202 -- generate a matching '}' token.
203 <layout_left> () { do_layout_left }
205 <0,option_prags> \n { begin bol }
207 "{-#" $whitechar* (line|LINE) { begin line_prag2 }
209 -- single-line line pragmas, of the form
210 -- # <line> "<file>" <extra-stuff> \n
211 <line_prag1> $decdigit+ { setLine line_prag1a }
212 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
213 <line_prag1b> .* { pop }
215 -- Haskell-style line pragmas, of the form
216 -- {-# LINE <line> "<file>" #-}
217 <line_prag2> $decdigit+ { setLine line_prag2a }
218 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
219 <line_prag2b> "#-}"|"-}" { pop }
220 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
221 -- with older versions of GHC which generated these.
223 -- We only want RULES pragmas to be picked up when explicit forall
224 -- syntax is enabled is on, because the contents of the pragma always
225 -- uses it. If it's not on then we're sure to get a parse error.
226 -- (ToDo: we should really emit a warning when ignoring pragmas)
227 -- XXX Now that we can enable this without the -fglasgow-exts hammer,
228 -- is it better just to let the parse error happen?
230 "{-#" $whitechar* (RULES|rules) / { ifExtension explicitForallEnabled } { token ITrules_prag }
233 "{-#" $whitechar* (INLINE|inline) { token (ITinline_prag True) }
234 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
235 { token (ITinline_prag False) }
236 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
237 { token ITspec_prag }
238 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
239 $whitechar* (INLINE|inline) { token (ITspec_inline_prag True) }
240 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
241 $whitechar* (NO(T?)INLINE|no(t?)inline)
242 { token (ITspec_inline_prag False) }
243 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
244 "{-#" $whitechar* (DEPRECATED|deprecated)
245 { token ITdeprecated_prag }
246 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
247 "{-#" $whitechar* (GENERATED|generated)
248 { token ITgenerated_prag }
249 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
250 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
252 "{-#" $whitechar* (DOCOPTIONS|docoptions)
253 / { ifExtension haddockEnabled } { lex_string_prag ITdocOptions }
255 "{-#" { nested_comment lexToken }
257 -- ToDo: should only be valid inside a pragma:
258 "#-}" { token ITclose_prag}
262 "{-#" $whitechar* (OPTIONS|options) { lex_string_prag IToptions_prag }
263 "{-#" $whitechar* (OPTIONS_GHC|options_ghc)
264 { lex_string_prag IToptions_prag }
265 "{-#" $whitechar* (LANGUAGE|language) { token ITlanguage_prag }
266 "{-#" $whitechar* (INCLUDE|include) { lex_string_prag ITinclude_prag }
270 -- This is to catch things like {-# OPTIONS OPTIONS_HUGS ...
271 "{-#" $whitechar* $idchar+ { nested_comment lexToken }
274 -- '0' state: ordinary lexemes
279 "-- " $docsym / { ifExtension haddockEnabled } { multiline_doc_comment }
280 "{-" \ ? $docsym / { ifExtension haddockEnabled } { nested_doc_comment }
286 "[:" / { ifExtension parrEnabled } { token ITopabrack }
287 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
291 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
292 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
293 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
294 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
295 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
296 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
297 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
298 "$(" / { ifExtension thEnabled } { token ITparenEscape }
302 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
303 { special IToparenbar }
304 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
308 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
312 "(#" / { ifExtension unboxedTuplesEnabled `alexAndPred` notFollowedBySymbol }
313 { token IToubxparen }
314 "#)" / { ifExtension unboxedTuplesEnabled }
315 { token ITcubxparen }
319 "{|" / { ifExtension genericsEnabled } { token ITocurlybar }
320 "|}" / { ifExtension genericsEnabled } { token ITccurlybar }
324 \( { special IToparen }
325 \) { special ITcparen }
326 \[ { special ITobrack }
327 \] { special ITcbrack }
328 \, { special ITcomma }
329 \; { special ITsemi }
330 \` { special ITbackquote }
337 @qual @varid { idtoken qvarid }
338 @qual @conid { idtoken qconid }
340 @conid { idtoken conid }
344 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
345 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
346 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
347 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
353 @qual @varsym { idtoken qvarsym }
354 @qual @consym { idtoken qconsym }
359 -- For the normal boxed literals we need to be careful
360 -- when trying to be close to Haskell98
362 -- Normal integral literals (:: Num a => a, from Integer)
363 @decimal { tok_num positive 0 0 decimal }
364 0[oO] @octal { tok_num positive 2 2 octal }
365 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
367 -- Normal rational literals (:: Fractional a => a, from Rational)
368 @floating_point { strtoken tok_float }
372 -- Unboxed ints (:: Int#)
373 -- It's simpler (and faster?) to give separate cases to the negatives,
374 -- especially considering octal/hexadecimal prefixes.
375 @decimal \# / { ifExtension magicHashEnabled } { tok_primint positive 0 1 decimal }
376 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 octal }
377 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 hexadecimal }
378 @negative @decimal \# / { ifExtension magicHashEnabled } { tok_primint negative 1 2 decimal }
379 @negative 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 octal }
380 @negative 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 hexadecimal }
382 -- Unboxed floats and doubles (:: Float#, :: Double#)
383 -- prim_{float,double} work with signed literals
384 @signed @floating_point \# / { ifExtension magicHashEnabled } { init_strtoken 1 tok_primfloat }
385 @signed @floating_point \# \# / { ifExtension magicHashEnabled } { init_strtoken 2 tok_primdouble }
388 -- Strings and chars are lexed by hand-written code. The reason is
389 -- that even if we recognise the string or char here in the regex
390 -- lexer, we would still have to parse the string afterward in order
391 -- to convert it to a String.
394 \" { lex_string_tok }
398 -- -----------------------------------------------------------------------------
402 = ITas -- Haskell keywords
426 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
428 | ITforall -- GHC extension keywords
443 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
444 | ITspec_prag -- SPECIALISE
445 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
452 | ITcore_prag -- hdaume: core annotations
455 | IToptions_prag String
456 | ITinclude_prag String
459 | ITdotdot -- reserved symbols
475 | ITbiglam -- GHC-extension symbols
477 | ITocurly -- special symbols
479 | ITocurlybar -- {|, for type applications
480 | ITccurlybar -- |}, for type applications
484 | ITopabrack -- [:, for parallel arrays with -fparr
485 | ITcpabrack -- :], for parallel arrays with -fparr
496 | ITvarid FastString -- identifiers
498 | ITvarsym FastString
499 | ITconsym FastString
500 | ITqvarid (FastString,FastString)
501 | ITqconid (FastString,FastString)
502 | ITqvarsym (FastString,FastString)
503 | ITqconsym (FastString,FastString)
505 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
507 | ITpragma StringBuffer
510 | ITstring FastString
512 | ITrational Rational
515 | ITprimstring FastString
517 | ITprimfloat Rational
518 | ITprimdouble Rational
520 -- MetaHaskell extension tokens
521 | ITopenExpQuote -- [| or [e|
522 | ITopenPatQuote -- [p|
523 | ITopenDecQuote -- [d|
524 | ITopenTypQuote -- [t|
526 | ITidEscape FastString -- $x
527 | ITparenEscape -- $(
531 -- Arrow notation extension
538 | ITLarrowtail -- -<<
539 | ITRarrowtail -- >>-
541 | ITunknown String -- Used when the lexer can't make sense of it
542 | ITeof -- end of file token
544 -- Documentation annotations
545 | ITdocCommentNext String -- something beginning '-- |'
546 | ITdocCommentPrev String -- something beginning '-- ^'
547 | ITdocCommentNamed String -- something beginning '-- $'
548 | ITdocSection Int String -- a section heading
549 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
552 deriving Show -- debugging
555 isSpecial :: Token -> Bool
556 -- If we see M.x, where x is a keyword, but
557 -- is special, we treat is as just plain M.x,
559 isSpecial ITas = True
560 isSpecial IThiding = True
561 isSpecial ITqualified = True
562 isSpecial ITforall = True
563 isSpecial ITexport = True
564 isSpecial ITlabel = True
565 isSpecial ITdynamic = True
566 isSpecial ITsafe = True
567 isSpecial ITthreadsafe = True
568 isSpecial ITunsafe = True
569 isSpecial ITccallconv = True
570 isSpecial ITstdcallconv = True
571 isSpecial ITmdo = True
572 isSpecial ITfamily = True
575 -- the bitmap provided as the third component indicates whether the
576 -- corresponding extension keyword is valid under the extension options
577 -- provided to the compiler; if the extension corresponding to *any* of the
578 -- bits set in the bitmap is enabled, the keyword is valid (this setup
579 -- facilitates using a keyword in two different extensions that can be
580 -- activated independently)
582 reservedWordsFM = listToUFM $
583 map (\(x, y, z) -> (mkFastString x, (y, z)))
584 [( "_", ITunderscore, 0 ),
586 ( "case", ITcase, 0 ),
587 ( "class", ITclass, 0 ),
588 ( "data", ITdata, 0 ),
589 ( "default", ITdefault, 0 ),
590 ( "deriving", ITderiving, 0 ),
592 ( "else", ITelse, 0 ),
593 ( "hiding", IThiding, 0 ),
595 ( "import", ITimport, 0 ),
597 ( "infix", ITinfix, 0 ),
598 ( "infixl", ITinfixl, 0 ),
599 ( "infixr", ITinfixr, 0 ),
600 ( "instance", ITinstance, 0 ),
602 ( "module", ITmodule, 0 ),
603 ( "newtype", ITnewtype, 0 ),
605 ( "qualified", ITqualified, 0 ),
606 ( "then", ITthen, 0 ),
607 ( "type", ITtype, 0 ),
608 ( "where", ITwhere, 0 ),
609 ( "_scc_", ITscc, 0 ), -- ToDo: remove
611 ( "forall", ITforall, bit explicitForallBit),
612 ( "mdo", ITmdo, bit recursiveDoBit),
613 ( "family", ITfamily, bit tyFamBit),
615 ( "foreign", ITforeign, bit ffiBit),
616 ( "export", ITexport, bit ffiBit),
617 ( "label", ITlabel, bit ffiBit),
618 ( "dynamic", ITdynamic, bit ffiBit),
619 ( "safe", ITsafe, bit ffiBit),
620 ( "threadsafe", ITthreadsafe, bit ffiBit),
621 ( "unsafe", ITunsafe, bit ffiBit),
622 ( "stdcall", ITstdcallconv, bit ffiBit),
623 ( "ccall", ITccallconv, bit ffiBit),
624 ( "dotnet", ITdotnet, bit ffiBit),
626 ( "rec", ITrec, bit arrowsBit),
627 ( "proc", ITproc, bit arrowsBit)
630 reservedSymsFM :: UniqFM (Token, Int -> Bool)
631 reservedSymsFM = listToUFM $
632 map (\ (x,y,z) -> (mkFastString x,(y,z)))
633 [ ("..", ITdotdot, always)
634 -- (:) is a reserved op, meaning only list cons
635 ,(":", ITcolon, always)
636 ,("::", ITdcolon, always)
637 ,("=", ITequal, always)
638 ,("\\", ITlam, always)
639 ,("|", ITvbar, always)
640 ,("<-", ITlarrow, always)
641 ,("->", ITrarrow, always)
643 ,("~", ITtilde, always)
644 ,("=>", ITdarrow, always)
645 ,("-", ITminus, always)
646 ,("!", ITbang, always)
648 -- For data T (a::*) = MkT
649 ,("*", ITstar, \i -> kindSigsEnabled i || tyFamEnabled i)
650 -- For 'forall a . t'
651 ,(".", ITdot, explicitForallEnabled)
653 ,("-<", ITlarrowtail, arrowsEnabled)
654 ,(">-", ITrarrowtail, arrowsEnabled)
655 ,("-<<", ITLarrowtail, arrowsEnabled)
656 ,(">>-", ITRarrowtail, arrowsEnabled)
658 #if __GLASGOW_HASKELL__ >= 605
659 ,("∷", ITdcolon, unicodeSyntaxEnabled)
660 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
661 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
662 explicitForallEnabled i)
663 ,("→", ITrarrow, unicodeSyntaxEnabled)
664 ,("←", ITlarrow, unicodeSyntaxEnabled)
665 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
666 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
667 -- form part of a large operator. This would let us have a better
668 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
672 -- -----------------------------------------------------------------------------
675 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
677 special :: Token -> Action
678 special tok span _buf len = return (L span tok)
680 token, layout_token :: Token -> Action
681 token t span buf len = return (L span t)
682 layout_token t span buf len = pushLexState layout >> return (L span t)
684 idtoken :: (StringBuffer -> Int -> Token) -> Action
685 idtoken f span buf len = return (L span $! (f buf len))
687 skip_one_varid :: (FastString -> Token) -> Action
688 skip_one_varid f span buf len
689 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
691 strtoken :: (String -> Token) -> Action
692 strtoken f span buf len =
693 return (L span $! (f $! lexemeToString buf len))
695 init_strtoken :: Int -> (String -> Token) -> Action
696 -- like strtoken, but drops the last N character(s)
697 init_strtoken drop f span buf len =
698 return (L span $! (f $! lexemeToString buf (len-drop)))
700 begin :: Int -> Action
701 begin code _span _str _len = do pushLexState code; lexToken
704 pop _span _buf _len = do popLexState; lexToken
706 pop_and :: Action -> Action
707 pop_and act span buf len = do popLexState; act span buf len
709 {-# INLINE nextCharIs #-}
710 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
712 notFollowedBy char _ _ _ (AI _ _ buf)
713 = nextCharIs buf (/=char)
715 notFollowedBySymbol _ _ _ (AI _ _ buf)
716 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
718 -- We must reject doc comments as being ordinary comments everywhere.
719 -- In some cases the doc comment will be selected as the lexeme due to
720 -- maximal munch, but not always, because the nested comment rule is
721 -- valid in all states, but the doc-comment rules are only valid in
722 -- the non-layout states.
723 isNormalComment bits _ _ (AI _ _ buf)
724 | haddockEnabled bits = notFollowedByDocOrPragma
725 | otherwise = nextCharIs buf (/='#')
727 notFollowedByDocOrPragma
728 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
730 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
732 haddockDisabledAnd p bits _ _ (AI _ _ buf)
733 = if haddockEnabled bits then False else (p buf)
735 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
737 ifExtension pred bits _ _ _ = pred bits
739 multiline_doc_comment :: Action
740 multiline_doc_comment span buf _len = withLexedDocType (worker "")
742 worker commentAcc input docType oneLine = case alexGetChar input of
744 | oneLine -> docCommentEnd input commentAcc docType buf span
745 | otherwise -> case checkIfCommentLine input' of
746 Just input -> worker ('\n':commentAcc) input docType False
747 Nothing -> docCommentEnd input commentAcc docType buf span
748 Just (c, input) -> worker (c:commentAcc) input docType oneLine
749 Nothing -> docCommentEnd input commentAcc docType buf span
751 checkIfCommentLine input = check (dropNonNewlineSpace input)
753 check input = case alexGetChar input of
754 Just ('-', input) -> case alexGetChar input of
755 Just ('-', input) -> case alexGetChar input of
756 Just (c, _) | c /= '-' -> Just input
761 dropNonNewlineSpace input = case alexGetChar input of
763 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
768 nested comments require traversing by hand, they can't be parsed
769 using regular expressions.
771 nested_comment :: P (Located Token) -> Action
772 nested_comment cont span _str _len = do
776 go 0 input = do setInput input; cont
777 go n input = case alexGetChar input of
778 Nothing -> errBrace input span
779 Just ('-',input) -> case alexGetChar input of
780 Nothing -> errBrace input span
781 Just ('\125',input) -> go (n-1) input
782 Just (c,_) -> go n input
783 Just ('\123',input) -> case alexGetChar input of
784 Nothing -> errBrace input span
785 Just ('-',input) -> go (n+1) input
786 Just (c,_) -> go n input
787 Just (c,input) -> go n input
789 nested_doc_comment :: Action
790 nested_doc_comment span buf _len = withLexedDocType (go "")
792 go commentAcc input docType _ = case alexGetChar input of
793 Nothing -> errBrace input span
794 Just ('-',input) -> case alexGetChar input of
795 Nothing -> errBrace input span
796 Just ('\125',input@(AI end _ buf2)) ->
797 docCommentEnd input commentAcc docType buf span
798 Just (c,_) -> go ('-':commentAcc) input docType False
799 Just ('\123', input) -> case alexGetChar input of
800 Nothing -> errBrace input span
801 Just ('-',input) -> do
803 let cont = do input <- getInput; go commentAcc input docType False
804 nested_comment cont span buf _len
805 Just (c,_) -> go ('\123':commentAcc) input docType False
806 Just (c,input) -> go (c:commentAcc) input docType False
808 withLexedDocType lexDocComment = do
809 input@(AI _ _ buf) <- getInput
810 case prevChar buf ' ' of
811 '|' -> lexDocComment input ITdocCommentNext False
812 '^' -> lexDocComment input ITdocCommentPrev False
813 '$' -> lexDocComment input ITdocCommentNamed False
814 '*' -> lexDocSection 1 input
816 lexDocSection n input = case alexGetChar input of
817 Just ('*', input) -> lexDocSection (n+1) input
818 Just (c, _) -> lexDocComment input (ITdocSection n) True
819 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
822 -------------------------------------------------------------------------------
823 -- This function is quite tricky. We can't just return a new token, we also
824 -- need to update the state of the parser. Why? Because the token is longer
825 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
826 -- it writes the wrong token length to the parser state. This function is
827 -- called afterwards, so it can just update the state.
829 -- This is complicated by the fact that Haddock tokens can span multiple lines,
830 -- which is something that the original lexer didn't account for.
831 -- I have added last_line_len in the parser state which represents the length
832 -- of the part of the token that is on the last line. It is now used for layout
833 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
834 -- was before, the full length of the token, and it is now only used for error
837 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
838 SrcSpan -> P (Located Token)
839 docCommentEnd input commentAcc docType buf span = do
841 let (AI loc last_offs nextBuf) = input
842 comment = reverse commentAcc
843 span' = mkSrcSpan (srcSpanStart span) loc
844 last_len = byteDiff buf nextBuf
846 last_line_len = if (last_offs - last_len < 0)
850 span `seq` setLastToken span' last_len last_line_len
851 return (L span' (docType comment))
853 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
855 open_brace, close_brace :: Action
856 open_brace span _str _len = do
858 setContext (NoLayout:ctx)
859 return (L span ITocurly)
860 close_brace span _str _len = do
862 return (L span ITccurly)
864 qvarid buf len = ITqvarid $! splitQualName buf len
865 qconid buf len = ITqconid $! splitQualName buf len
867 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
868 -- takes a StringBuffer and a length, and returns the module name
869 -- and identifier parts of a qualified name. Splits at the *last* dot,
870 -- because of hierarchical module names.
871 splitQualName orig_buf len = split orig_buf orig_buf
874 | orig_buf `byteDiff` buf >= len = done dot_buf
875 | c == '.' = found_dot buf'
876 | otherwise = split buf' dot_buf
878 (c,buf') = nextChar buf
880 -- careful, we might get names like M....
881 -- so, if the character after the dot is not upper-case, this is
882 -- the end of the qualifier part.
883 found_dot buf -- buf points after the '.'
884 | isUpper c = split buf' buf
885 | otherwise = done buf
887 (c,buf') = nextChar buf
890 (lexemeToFastString orig_buf (qual_size - 1),
891 lexemeToFastString dot_buf (len - qual_size))
893 qual_size = orig_buf `byteDiff` dot_buf
896 case lookupUFM reservedWordsFM fs of
897 Just (keyword,0) -> do
899 return (L span keyword)
900 Just (keyword,exts) -> do
901 b <- extension (\i -> exts .&. i /= 0)
902 if b then do maybe_layout keyword
903 return (L span keyword)
904 else return (L span (ITvarid fs))
905 _other -> return (L span (ITvarid fs))
907 fs = lexemeToFastString buf len
909 conid buf len = ITconid fs
910 where fs = lexemeToFastString buf len
912 qvarsym buf len = ITqvarsym $! splitQualName buf len
913 qconsym buf len = ITqconsym $! splitQualName buf len
915 varsym = sym ITvarsym
916 consym = sym ITconsym
918 sym con span buf len =
919 case lookupUFM reservedSymsFM fs of
920 Just (keyword,exts) -> do
922 if b then return (L span keyword)
923 else return (L span $! con fs)
924 _other -> return (L span $! con fs)
926 fs = lexemeToFastString buf len
928 -- Variations on the integral numeric literal.
929 tok_integral :: (Integer -> Token)
930 -> (Integer -> Integer)
931 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
933 -> (Integer, (Char->Int)) -> Action
934 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
935 return $ L span $ itint $! transint $ parseUnsignedInteger
936 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
938 -- some conveniences for use with tok_integral
939 tok_num = tok_integral ITinteger
940 tok_primint = tok_integral ITprimint
943 decimal = (10,octDecDigit)
944 octal = (8,octDecDigit)
945 hexadecimal = (16,hexDigit)
947 -- readRational can understand negative rationals, exponents, everything.
948 tok_float str = ITrational $! readRational str
949 tok_primfloat str = ITprimfloat $! readRational str
950 tok_primdouble str = ITprimdouble $! readRational str
952 -- -----------------------------------------------------------------------------
955 -- we're at the first token on a line, insert layout tokens if necessary
957 do_bol span _str _len = do
961 --trace "layout: inserting '}'" $ do
963 -- do NOT pop the lex state, we might have a ';' to insert
964 return (L span ITvccurly)
966 --trace "layout: inserting ';'" $ do
968 return (L span ITsemi)
973 -- certain keywords put us in the "layout" state, where we might
974 -- add an opening curly brace.
975 maybe_layout ITdo = pushLexState layout_do
976 maybe_layout ITmdo = pushLexState layout_do
977 maybe_layout ITof = pushLexState layout
978 maybe_layout ITlet = pushLexState layout
979 maybe_layout ITwhere = pushLexState layout
980 maybe_layout ITrec = pushLexState layout
981 maybe_layout _ = return ()
983 -- Pushing a new implicit layout context. If the indentation of the
984 -- next token is not greater than the previous layout context, then
985 -- Haskell 98 says that the new layout context should be empty; that is
986 -- the lexer must generate {}.
988 -- We are slightly more lenient than this: when the new context is started
989 -- by a 'do', then we allow the new context to be at the same indentation as
990 -- the previous context. This is what the 'strict' argument is for.
992 new_layout_context strict span _buf _len = do
994 (AI _ offset _) <- getInput
997 Layout prev_off : _ |
998 (strict && prev_off >= offset ||
999 not strict && prev_off > offset) -> do
1000 -- token is indented to the left of the previous context.
1001 -- we must generate a {} sequence now.
1002 pushLexState layout_left
1003 return (L span ITvocurly)
1005 setContext (Layout offset : ctx)
1006 return (L span ITvocurly)
1008 do_layout_left span _buf _len = do
1010 pushLexState bol -- we must be at the start of a line
1011 return (L span ITvccurly)
1013 -- -----------------------------------------------------------------------------
1016 setLine :: Int -> Action
1017 setLine code span buf len = do
1018 let line = parseUnsignedInteger buf len 10 octDecDigit
1019 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1020 -- subtract one: the line number refers to the *following* line
1025 setFile :: Int -> Action
1026 setFile code span buf len = do
1027 let file = lexemeToFastString (stepOn buf) (len-2)
1028 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1034 -- -----------------------------------------------------------------------------
1035 -- Options, includes and language pragmas.
1037 lex_string_prag :: (String -> Token) -> Action
1038 lex_string_prag mkTok span buf len
1039 = do input <- getInput
1043 return (L (mkSrcSpan start end) tok)
1045 = if isString input "#-}"
1046 then do setInput input
1047 return (mkTok (reverse acc))
1048 else case alexGetChar input of
1049 Just (c,i) -> go (c:acc) i
1050 Nothing -> err input
1051 isString i [] = True
1053 = case alexGetChar i of
1054 Just (c,i') | c == x -> isString i' xs
1056 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1059 -- -----------------------------------------------------------------------------
1062 -- This stuff is horrible. I hates it.
1064 lex_string_tok :: Action
1065 lex_string_tok span buf len = do
1066 tok <- lex_string ""
1068 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1070 lex_string :: String -> P Token
1073 case alexGetChar' i of
1074 Nothing -> lit_error
1078 magicHash <- extension magicHashEnabled
1082 case alexGetChar' i of
1086 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1087 else let s' = mkZFastString (reverse s) in
1088 return (ITprimstring s')
1089 -- mkZFastString is a hack to avoid encoding the
1090 -- string in UTF-8. We just want the exact bytes.
1092 return (ITstring (mkFastString (reverse s)))
1094 return (ITstring (mkFastString (reverse s)))
1097 | Just ('&',i) <- next -> do
1098 setInput i; lex_string s
1099 | Just (c,i) <- next, is_space c -> do
1100 setInput i; lex_stringgap s
1101 where next = alexGetChar' i
1107 lex_stringgap s = do
1110 '\\' -> lex_string s
1111 c | is_space c -> lex_stringgap s
1115 lex_char_tok :: Action
1116 -- Here we are basically parsing character literals, such as 'x' or '\n'
1117 -- but, when Template Haskell is on, we additionally spot
1118 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1119 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1120 -- So we have to do two characters of lookahead: when we see 'x we need to
1121 -- see if there's a trailing quote
1122 lex_char_tok span buf len = do -- We've seen '
1123 i1 <- getInput -- Look ahead to first character
1124 let loc = srcSpanStart span
1125 case alexGetChar' i1 of
1126 Nothing -> lit_error
1128 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1129 th_exts <- extension thEnabled
1132 return (L (mkSrcSpan loc end2) ITtyQuote)
1135 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
1137 lit_ch <- lex_escape
1138 mc <- getCharOrFail -- Trailing quote
1139 if mc == '\'' then finish_char_tok loc lit_ch
1140 else do setInput i2; lit_error
1142 Just (c, i2@(AI end2 _ _))
1143 | not (isAny c) -> lit_error
1146 -- We've seen 'x, where x is a valid character
1147 -- (i.e. not newline etc) but not a quote or backslash
1148 case alexGetChar' i2 of -- Look ahead one more character
1149 Nothing -> lit_error
1150 Just ('\'', i3) -> do -- We've seen 'x'
1152 finish_char_tok loc c
1153 _other -> do -- We've seen 'x not followed by quote
1154 -- If TH is on, just parse the quote only
1155 th_exts <- extension thEnabled
1156 let (AI end _ _) = i1
1157 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1158 else do setInput i2; lit_error
1160 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1161 finish_char_tok loc ch -- We've already seen the closing quote
1162 -- Just need to check for trailing #
1163 = do magicHash <- extension magicHashEnabled
1164 i@(AI end _ _) <- getInput
1165 if magicHash then do
1166 case alexGetChar' i of
1167 Just ('#',i@(AI end _ _)) -> do
1169 return (L (mkSrcSpan loc end) (ITprimchar ch))
1171 return (L (mkSrcSpan loc end) (ITchar ch))
1173 return (L (mkSrcSpan loc end) (ITchar ch))
1175 lex_char :: Char -> AlexInput -> P Char
1178 '\\' -> do setInput inp; lex_escape
1179 c | isAny c -> do setInput inp; return c
1182 isAny c | c > '\xff' = isPrint c
1183 | otherwise = is_any c
1185 lex_escape :: P Char
1199 '^' -> do c <- getCharOrFail
1200 if c >= '@' && c <= '_'
1201 then return (chr (ord c - ord '@'))
1204 'x' -> readNum is_hexdigit 16 hexDigit
1205 'o' -> readNum is_octdigit 8 octDecDigit
1206 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
1210 case alexGetChar' i of
1211 Nothing -> lit_error
1213 case alexGetChar' i2 of
1214 Nothing -> do setInput i2; lit_error
1216 let str = [c1,c2,c3] in
1217 case [ (c,rest) | (p,c) <- silly_escape_chars,
1218 Just rest <- [maybePrefixMatch p str] ] of
1219 (escape_char,[]):_ -> do
1222 (escape_char,_:_):_ -> do
1227 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1228 readNum is_digit base conv = do
1232 then readNum2 is_digit base conv (conv c)
1233 else do setInput i; lit_error
1235 readNum2 is_digit base conv i = do
1238 where read i input = do
1239 case alexGetChar' input of
1240 Just (c,input') | is_digit c -> do
1241 read (i*base + conv c) input'
1243 if i >= 0 && i <= 0x10FFFF
1244 then do setInput input; return (chr i)
1247 silly_escape_chars = [
1284 -- before calling lit_error, ensure that the current input is pointing to
1285 -- the position of the error in the buffer. This is so that we can report
1286 -- a correct location to the user, but also so we can detect UTF-8 decoding
1287 -- errors if they occur.
1288 lit_error = lexError "lexical error in string/character literal"
1290 getCharOrFail :: P Char
1293 case alexGetChar' i of
1294 Nothing -> lexError "unexpected end-of-file in string/character literal"
1295 Just (c,i) -> do setInput i; return c
1297 -- -----------------------------------------------------------------------------
1300 warn :: DynFlag -> SDoc -> Action
1301 warn option warning span _buf _len = do
1302 addWarning option (mkWarnMsg span alwaysQualify warning)
1305 -- -----------------------------------------------------------------------------
1316 SrcSpan -- The start and end of the text span related to
1317 -- the error. Might be used in environments which can
1318 -- show this span, e.g. by highlighting it.
1319 Message -- The error message
1321 data PState = PState {
1322 buffer :: StringBuffer,
1324 messages :: Messages,
1325 last_loc :: SrcSpan, -- pos of previous token
1326 last_offs :: !Int, -- offset of the previous token from the
1327 -- beginning of the current line.
1328 -- \t is equal to 8 spaces.
1329 last_len :: !Int, -- len of previous token
1330 last_line_len :: !Int,
1331 loc :: SrcLoc, -- current loc (end of prev token + 1)
1332 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1333 context :: [LayoutContext],
1336 -- last_loc and last_len are used when generating error messages,
1337 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1338 -- current token to happyError, we could at least get rid of last_len.
1339 -- Getting rid of last_loc would require finding another way to
1340 -- implement pushCurrentContext (which is only called from one place).
1342 newtype P a = P { unP :: PState -> ParseResult a }
1344 instance Monad P where
1350 returnP a = P $ \s -> POk s a
1352 thenP :: P a -> (a -> P b) -> P b
1353 (P m) `thenP` k = P $ \ s ->
1355 POk s1 a -> (unP (k a)) s1
1356 PFailed span err -> PFailed span err
1358 failP :: String -> P a
1359 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1361 failMsgP :: String -> P a
1362 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1364 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1365 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1367 failSpanMsgP :: SrcSpan -> String -> P a
1368 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1370 extension :: (Int -> Bool) -> P Bool
1371 extension p = P $ \s -> POk s (p $! extsBitmap s)
1374 getExts = P $ \s -> POk s (extsBitmap s)
1376 setSrcLoc :: SrcLoc -> P ()
1377 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1379 getSrcLoc :: P SrcLoc
1380 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1382 setLastToken :: SrcSpan -> Int -> Int -> P ()
1383 setLastToken loc len line_len = P $ \s -> POk s {
1386 last_line_len=line_len
1389 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1391 alexInputPrevChar :: AlexInput -> Char
1392 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1394 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1395 alexGetChar (AI loc ofs s)
1397 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1398 --trace (show (ord c)) $
1399 Just (adj_c, (AI loc' ofs' s'))
1400 where (c,s') = nextChar s
1401 loc' = advanceSrcLoc loc c
1402 ofs' = advanceOffs c ofs
1410 other_graphic = '\x6'
1413 | c <= '\x06' = non_graphic
1415 -- Alex doesn't handle Unicode, so when Unicode
1416 -- character is encoutered we output these values
1417 -- with the actual character value hidden in the state.
1419 case generalCategory c of
1420 UppercaseLetter -> upper
1421 LowercaseLetter -> lower
1422 TitlecaseLetter -> upper
1423 ModifierLetter -> other_graphic
1424 OtherLetter -> other_graphic
1425 NonSpacingMark -> other_graphic
1426 SpacingCombiningMark -> other_graphic
1427 EnclosingMark -> other_graphic
1428 DecimalNumber -> digit
1429 LetterNumber -> other_graphic
1430 OtherNumber -> other_graphic
1431 ConnectorPunctuation -> other_graphic
1432 DashPunctuation -> other_graphic
1433 OpenPunctuation -> other_graphic
1434 ClosePunctuation -> other_graphic
1435 InitialQuote -> other_graphic
1436 FinalQuote -> other_graphic
1437 OtherPunctuation -> other_graphic
1438 MathSymbol -> symbol
1439 CurrencySymbol -> symbol
1440 ModifierSymbol -> symbol
1441 OtherSymbol -> symbol
1443 _other -> non_graphic
1445 -- This version does not squash unicode characters, it is used when
1447 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1448 alexGetChar' (AI loc ofs s)
1450 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1451 --trace (show (ord c)) $
1452 Just (c, (AI loc' ofs' s'))
1453 where (c,s') = nextChar s
1454 loc' = advanceSrcLoc loc c
1455 ofs' = advanceOffs c ofs
1457 advanceOffs :: Char -> Int -> Int
1458 advanceOffs '\n' offs = 0
1459 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1460 advanceOffs _ offs = offs + 1
1462 getInput :: P AlexInput
1463 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1465 setInput :: AlexInput -> P ()
1466 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1468 pushLexState :: Int -> P ()
1469 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1471 popLexState :: P Int
1472 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1474 getLexState :: P Int
1475 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1477 -- for reasons of efficiency, flags indicating language extensions (eg,
1478 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1481 genericsBit, ffiBit, parrBit :: Int
1482 genericsBit = 0 -- {| and |}
1488 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1489 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1490 -- (doesn't affect the lexer)
1491 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1492 haddockBit = 10 -- Lex and parse Haddock comments
1493 magicHashBit = 11 -- # in both functions and operators
1494 kindSigsBit = 12 -- Kind signatures on type variables
1495 recursiveDoBit = 13 -- mdo
1496 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1497 unboxedTuplesBit = 15 -- (# and #)
1498 standaloneDerivingBit = 16 -- standalone instance deriving declarations
1500 genericsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1502 genericsEnabled flags = testBit flags genericsBit
1503 ffiEnabled flags = testBit flags ffiBit
1504 parrEnabled flags = testBit flags parrBit
1505 arrowsEnabled flags = testBit flags arrowsBit
1506 thEnabled flags = testBit flags thBit
1507 ipEnabled flags = testBit flags ipBit
1508 explicitForallEnabled flags = testBit flags explicitForallBit
1509 bangPatEnabled flags = testBit flags bangPatBit
1510 tyFamEnabled flags = testBit flags tyFamBit
1511 haddockEnabled flags = testBit flags haddockBit
1512 magicHashEnabled flags = testBit flags magicHashBit
1513 kindSigsEnabled flags = testBit flags kindSigsBit
1514 recursiveDoEnabled flags = testBit flags recursiveDoBit
1515 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1516 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1517 standaloneDerivingEnabled flags = testBit flags standaloneDerivingBit
1519 -- PState for parsing options pragmas
1521 pragState :: StringBuffer -> SrcLoc -> PState
1525 messages = emptyMessages,
1526 -- XXX defaultDynFlags is not right, but we don't have a real
1528 dflags = defaultDynFlags,
1529 last_loc = mkSrcSpan loc loc,
1536 lex_state = [bol, option_prags, 0]
1540 -- create a parse state
1542 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1543 mkPState buf loc flags =
1547 messages = emptyMessages,
1548 last_loc = mkSrcSpan loc loc,
1553 extsBitmap = fromIntegral bitmap,
1555 lex_state = [bol, 0]
1556 -- we begin in the layout state if toplev_layout is set
1559 bitmap = genericsBit `setBitIf` dopt Opt_Generics flags
1560 .|. ffiBit `setBitIf` dopt Opt_ForeignFunctionInterface flags
1561 .|. parrBit `setBitIf` dopt Opt_PArr flags
1562 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1563 .|. thBit `setBitIf` dopt Opt_TemplateHaskell flags
1564 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1565 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1566 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1567 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1568 .|. explicitForallBit `setBitIf` dopt Opt_Rank2Types flags
1569 .|. explicitForallBit `setBitIf` dopt Opt_RankNTypes flags
1570 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1571 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1572 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1573 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1574 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1575 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1576 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1577 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1578 .|. standaloneDerivingBit `setBitIf` dopt Opt_StandaloneDeriving flags
1580 setBitIf :: Int -> Bool -> Int
1581 b `setBitIf` cond | cond = bit b
1584 addWarning :: DynFlag -> WarnMsg -> P ()
1586 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1587 let ws' = if dopt option d then ws `snocBag` w else ws
1588 in POk s{messages=(ws', es)} ()
1590 getMessages :: PState -> Messages
1591 getMessages PState{messages=ms} = ms
1593 getContext :: P [LayoutContext]
1594 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1596 setContext :: [LayoutContext] -> P ()
1597 setContext ctx = P $ \s -> POk s{context=ctx} ()
1600 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1601 loc = loc, last_len = len, last_loc = last_loc }) ->
1603 (_:tl) -> POk s{ context = tl } ()
1604 [] -> PFailed last_loc (srcParseErr buf len)
1606 -- Push a new layout context at the indentation of the last token read.
1607 -- This is only used at the outer level of a module when the 'module'
1608 -- keyword is missing.
1609 pushCurrentContext :: P ()
1610 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1611 POk s{context = Layout (offs-len) : ctx} ()
1612 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1614 getOffside :: P Ordering
1615 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1616 let ord = case stk of
1617 (Layout n:_) -> compare offs n
1621 -- ---------------------------------------------------------------------------
1622 -- Construct a parse error
1625 :: StringBuffer -- current buffer (placed just after the last token)
1626 -> Int -- length of the previous token
1629 = hcat [ if null token
1630 then ptext SLIT("parse error (possibly incorrect indentation)")
1631 else hcat [ptext SLIT("parse error on input "),
1632 char '`', text token, char '\'']
1634 where token = lexemeToString (offsetBytes (-len) buf) len
1636 -- Report a parse failure, giving the span of the previous token as
1637 -- the location of the error. This is the entry point for errors
1638 -- detected during parsing.
1640 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1641 last_loc = last_loc } ->
1642 PFailed last_loc (srcParseErr buf len)
1644 -- A lexical error is reported at a particular position in the source file,
1645 -- not over a token range.
1646 lexError :: String -> P a
1649 i@(AI end _ buf) <- getInput
1650 reportLexError loc end buf str
1652 -- -----------------------------------------------------------------------------
1653 -- This is the top-level function: called from the parser each time a
1654 -- new token is to be read from the input.
1656 lexer :: (Located Token -> P a) -> P a
1658 tok@(L span tok__) <- lexToken
1659 -- trace ("token: " ++ show tok__) $ do
1662 lexToken :: P (Located Token)
1664 inp@(AI loc1 _ buf) <- getInput
1667 case alexScanUser exts inp sc of
1668 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1669 setLastToken span 0 0
1670 return (L span ITeof)
1671 AlexError (AI loc2 _ buf) -> do
1672 reportLexError loc1 loc2 buf "lexical error"
1673 AlexSkip inp2 _ -> do
1676 AlexToken inp2@(AI end _ buf2) len t -> do
1678 let span = mkSrcSpan loc1 end
1679 let bytes = byteDiff buf buf2
1680 span `seq` setLastToken span bytes bytes
1683 reportLexError loc1 loc2 buf str
1684 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1687 c = fst (nextChar buf)
1689 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1690 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1691 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)