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, glaExtsEnabled, 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,glaexts> \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 -fglasgow-exts
224 -- is on, because the contents of the pragma is always written using
225 -- glasgow-exts syntax (using forall etc.), so if glasgow exts are not
226 -- enabled, we're sure to get a parse error.
227 -- (ToDo: we should really emit a warning when ignoring pragmas)
229 "{-#" $whitechar* (RULES|rules) { token ITrules_prag }
231 <0,option_prags,glaexts> {
232 "{-#" $whitechar* (INLINE|inline) { token (ITinline_prag True) }
233 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
234 { token (ITinline_prag False) }
235 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
236 { token ITspec_prag }
237 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
238 $whitechar* (INLINE|inline) { token (ITspec_inline_prag True) }
239 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
240 $whitechar* (NO(T?)INLINE|no(t?)inline)
241 { token (ITspec_inline_prag False) }
242 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
243 "{-#" $whitechar* (DEPRECATED|deprecated)
244 { token ITdeprecated_prag }
245 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
246 "{-#" $whitechar* (GENERATED|generated)
247 { token ITgenerated_prag }
248 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
249 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
251 "{-#" $whitechar* (DOCOPTIONS|docoptions)
252 / { ifExtension haddockEnabled } { lex_string_prag ITdocOptions }
254 "{-#" { nested_comment lexToken }
256 -- ToDo: should only be valid inside a pragma:
257 "#-}" { token ITclose_prag}
261 "{-#" $whitechar* (OPTIONS|options) { lex_string_prag IToptions_prag }
262 "{-#" $whitechar* (OPTIONS_GHC|options_ghc)
263 { lex_string_prag IToptions_prag }
264 "{-#" $whitechar* (LANGUAGE|language) { token ITlanguage_prag }
265 "{-#" $whitechar* (INCLUDE|include) { lex_string_prag ITinclude_prag }
268 <0,option_prags,glaexts> {
269 -- This is to catch things like {-# OPTIONS OPTIONS_HUGS ...
270 "{-#" $whitechar* $idchar+ { nested_comment lexToken }
273 -- '0' state: ordinary lexemes
274 -- 'glaexts' state: glasgow extensions (postfix '#', etc.)
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 "{|" { token ITocurlybar }
320 "|}" { token ITccurlybar }
323 <0,option_prags,glaexts> {
324 \( { special IToparen }
325 \) { special ITcparen }
326 \[ { special ITobrack }
327 \] { special ITcbrack }
328 \, { special ITcomma }
329 \; { special ITsemi }
330 \` { special ITbackquote }
336 <0,option_prags,glaexts> {
337 @qual @varid { check_qvarid }
338 @qual @conid { idtoken qconid }
340 @conid { idtoken conid }
343 -- after an illegal qvarid, such as 'M.let',
344 -- we back up and try again in the bad_qvarid state:
346 @conid { pop_and (idtoken conid) }
347 @qual @conid { pop_and (idtoken qconid) }
351 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
352 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
353 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
354 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
360 @qual @varsym { idtoken qvarsym }
361 @qual @consym { idtoken qconsym }
366 -- For the normal boxed literals we need to be careful
367 -- when trying to be close to Haskell98
369 -- Normal integral literals (:: Num a => a, from Integer)
370 @decimal { tok_num positive 0 0 decimal }
371 0[oO] @octal { tok_num positive 2 2 octal }
372 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
374 -- Normal rational literals (:: Fractional a => a, from Rational)
375 @floating_point { strtoken tok_float }
379 -- Unboxed ints (:: Int#)
380 -- It's simpler (and faster?) to give separate cases to the negatives,
381 -- especially considering octal/hexadecimal prefixes.
382 @decimal \# { tok_primint positive 0 1 decimal }
383 0[oO] @octal \# { tok_primint positive 2 3 octal }
384 0[xX] @hexadecimal \# { tok_primint positive 2 3 hexadecimal }
385 @negative @decimal \# { tok_primint negative 1 2 decimal }
386 @negative 0[oO] @octal \# { tok_primint negative 3 4 octal }
387 @negative 0[xX] @hexadecimal \# { tok_primint negative 3 4 hexadecimal }
389 -- Unboxed floats and doubles (:: Float#, :: Double#)
390 -- prim_{float,double} work with signed literals
391 @signed @floating_point \# { init_strtoken 1 tok_primfloat }
392 @signed @floating_point \# \# { init_strtoken 2 tok_primdouble }
395 -- Strings and chars are lexed by hand-written code. The reason is
396 -- that even if we recognise the string or char here in the regex
397 -- lexer, we would still have to parse the string afterward in order
398 -- to convert it to a String.
401 \" { lex_string_tok }
405 -- -----------------------------------------------------------------------------
409 = ITas -- Haskell keywords
434 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
436 | ITforall -- GHC extension keywords
451 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
452 | ITspec_prag -- SPECIALISE
453 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
460 | ITcore_prag -- hdaume: core annotations
463 | IToptions_prag String
464 | ITinclude_prag String
467 | ITdotdot -- reserved symbols
483 | ITbiglam -- GHC-extension symbols
485 | ITocurly -- special symbols
487 | ITocurlybar -- {|, for type applications
488 | ITccurlybar -- |}, for type applications
492 | ITopabrack -- [:, for parallel arrays with -fparr
493 | ITcpabrack -- :], for parallel arrays with -fparr
504 | ITvarid FastString -- identifiers
506 | ITvarsym FastString
507 | ITconsym FastString
508 | ITqvarid (FastString,FastString)
509 | ITqconid (FastString,FastString)
510 | ITqvarsym (FastString,FastString)
511 | ITqconsym (FastString,FastString)
513 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
515 | ITpragma StringBuffer
518 | ITstring FastString
520 | ITrational Rational
523 | ITprimstring FastString
525 | ITprimfloat Rational
526 | ITprimdouble Rational
528 -- MetaHaskell extension tokens
529 | ITopenExpQuote -- [| or [e|
530 | ITopenPatQuote -- [p|
531 | ITopenDecQuote -- [d|
532 | ITopenTypQuote -- [t|
534 | ITidEscape FastString -- $x
535 | ITparenEscape -- $(
539 -- Arrow notation extension
546 | ITLarrowtail -- -<<
547 | ITRarrowtail -- >>-
549 | ITunknown String -- Used when the lexer can't make sense of it
550 | ITeof -- end of file token
552 -- Documentation annotations
553 | ITdocCommentNext String -- something beginning '-- |'
554 | ITdocCommentPrev String -- something beginning '-- ^'
555 | ITdocCommentNamed String -- something beginning '-- $'
556 | ITdocSection Int String -- a section heading
557 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
560 deriving Show -- debugging
563 isSpecial :: Token -> Bool
564 -- If we see M.x, where x is a keyword, but
565 -- is special, we treat is as just plain M.x,
567 isSpecial ITas = True
568 isSpecial IThiding = True
569 isSpecial ITderive = True
570 isSpecial ITqualified = True
571 isSpecial ITforall = True
572 isSpecial ITexport = True
573 isSpecial ITlabel = True
574 isSpecial ITdynamic = True
575 isSpecial ITsafe = True
576 isSpecial ITthreadsafe = True
577 isSpecial ITunsafe = True
578 isSpecial ITccallconv = True
579 isSpecial ITstdcallconv = True
580 isSpecial ITmdo = True
581 isSpecial ITfamily = True
584 -- the bitmap provided as the third component indicates whether the
585 -- corresponding extension keyword is valid under the extension options
586 -- provided to the compiler; if the extension corresponding to *any* of the
587 -- bits set in the bitmap is enabled, the keyword is valid (this setup
588 -- facilitates using a keyword in two different extensions that can be
589 -- activated independently)
591 reservedWordsFM = listToUFM $
592 map (\(x, y, z) -> (mkFastString x, (y, z)))
593 [( "_", ITunderscore, 0 ),
595 ( "case", ITcase, 0 ),
596 ( "class", ITclass, 0 ),
597 ( "data", ITdata, 0 ),
598 ( "default", ITdefault, 0 ),
599 ( "deriving", ITderiving, 0 ),
600 ( "derive", ITderive, 0 ),
602 ( "else", ITelse, 0 ),
603 ( "hiding", IThiding, 0 ),
605 ( "import", ITimport, 0 ),
607 ( "infix", ITinfix, 0 ),
608 ( "infixl", ITinfixl, 0 ),
609 ( "infixr", ITinfixr, 0 ),
610 ( "instance", ITinstance, 0 ),
612 ( "module", ITmodule, 0 ),
613 ( "newtype", ITnewtype, 0 ),
615 ( "qualified", ITqualified, 0 ),
616 ( "then", ITthen, 0 ),
617 ( "type", ITtype, 0 ),
618 ( "where", ITwhere, 0 ),
619 ( "_scc_", ITscc, 0 ), -- ToDo: remove
621 ( "forall", ITforall, bit explicitForallBit),
622 ( "mdo", ITmdo, bit recursiveDoBit),
623 ( "family", ITfamily, bit tyFamBit),
625 ( "foreign", ITforeign, bit ffiBit),
626 ( "export", ITexport, bit ffiBit),
627 ( "label", ITlabel, bit ffiBit),
628 ( "dynamic", ITdynamic, bit ffiBit),
629 ( "safe", ITsafe, bit ffiBit),
630 ( "threadsafe", ITthreadsafe, bit ffiBit),
631 ( "unsafe", ITunsafe, bit ffiBit),
632 ( "stdcall", ITstdcallconv, bit ffiBit),
633 ( "ccall", ITccallconv, bit ffiBit),
634 ( "dotnet", ITdotnet, bit ffiBit),
636 ( "rec", ITrec, bit arrowsBit),
637 ( "proc", ITproc, bit arrowsBit)
640 reservedSymsFM :: UniqFM (Token, Int -> Bool)
641 reservedSymsFM = listToUFM $
642 map (\ (x,y,z) -> (mkFastString x,(y,z)))
643 [ ("..", ITdotdot, always)
644 -- (:) is a reserved op, meaning only list cons
645 ,(":", ITcolon, always)
646 ,("::", ITdcolon, always)
647 ,("=", ITequal, always)
648 ,("\\", ITlam, always)
649 ,("|", ITvbar, always)
650 ,("<-", ITlarrow, always)
651 ,("->", ITrarrow, always)
653 ,("~", ITtilde, always)
654 ,("=>", ITdarrow, always)
655 ,("-", ITminus, always)
656 ,("!", ITbang, always)
658 -- For data T (a::*) = MkT
659 ,("*", ITstar, \i -> glaExtsEnabled i ||
662 -- For 'forall a . t'
663 ,(".", ITdot, explicitForallEnabled)
665 ,("-<", ITlarrowtail, arrowsEnabled)
666 ,(">-", ITrarrowtail, arrowsEnabled)
667 ,("-<<", ITLarrowtail, arrowsEnabled)
668 ,(">>-", ITRarrowtail, arrowsEnabled)
670 #if __GLASGOW_HASKELL__ >= 605
671 ,("∷", ITdcolon, unicodeSyntaxEnabled)
672 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
673 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
674 explicitForallEnabled i)
675 ,("→", ITrarrow, unicodeSyntaxEnabled)
676 ,("←", ITlarrow, unicodeSyntaxEnabled)
677 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
678 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
679 -- form part of a large operator. This would let us have a better
680 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
684 -- -----------------------------------------------------------------------------
687 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
689 special :: Token -> Action
690 special tok span _buf len = return (L span tok)
692 token, layout_token :: Token -> Action
693 token t span buf len = return (L span t)
694 layout_token t span buf len = pushLexState layout >> return (L span t)
696 idtoken :: (StringBuffer -> Int -> Token) -> Action
697 idtoken f span buf len = return (L span $! (f buf len))
699 skip_one_varid :: (FastString -> Token) -> Action
700 skip_one_varid f span buf len
701 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
703 strtoken :: (String -> Token) -> Action
704 strtoken f span buf len =
705 return (L span $! (f $! lexemeToString buf len))
707 init_strtoken :: Int -> (String -> Token) -> Action
708 -- like strtoken, but drops the last N character(s)
709 init_strtoken drop f span buf len =
710 return (L span $! (f $! lexemeToString buf (len-drop)))
712 begin :: Int -> Action
713 begin code _span _str _len = do pushLexState code; lexToken
716 pop _span _buf _len = do popLexState; lexToken
718 pop_and :: Action -> Action
719 pop_and act span buf len = do popLexState; act span buf len
721 {-# INLINE nextCharIs #-}
722 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
724 notFollowedBy char _ _ _ (AI _ _ buf)
725 = nextCharIs buf (/=char)
727 notFollowedBySymbol _ _ _ (AI _ _ buf)
728 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
730 -- We must reject doc comments as being ordinary comments everywhere.
731 -- In some cases the doc comment will be selected as the lexeme due to
732 -- maximal munch, but not always, because the nested comment rule is
733 -- valid in all states, but the doc-comment rules are only valid in
734 -- the non-layout states.
735 isNormalComment bits _ _ (AI _ _ buf)
736 | haddockEnabled bits = notFollowedByDocOrPragma
737 | otherwise = nextCharIs buf (/='#')
739 notFollowedByDocOrPragma
740 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
742 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
744 haddockDisabledAnd p bits _ _ (AI _ _ buf)
745 = if haddockEnabled bits then False else (p buf)
747 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
749 ifExtension pred bits _ _ _ = pred bits
751 multiline_doc_comment :: Action
752 multiline_doc_comment span buf _len = withLexedDocType (worker "")
754 worker commentAcc input docType oneLine = case alexGetChar input of
756 | oneLine -> docCommentEnd input commentAcc docType buf span
757 | otherwise -> case checkIfCommentLine input' of
758 Just input -> worker ('\n':commentAcc) input docType False
759 Nothing -> docCommentEnd input commentAcc docType buf span
760 Just (c, input) -> worker (c:commentAcc) input docType oneLine
761 Nothing -> docCommentEnd input commentAcc docType buf span
763 checkIfCommentLine input = check (dropNonNewlineSpace input)
765 check input = case alexGetChar input of
766 Just ('-', input) -> case alexGetChar input of
767 Just ('-', input) -> case alexGetChar input of
768 Just (c, _) | c /= '-' -> Just input
773 dropNonNewlineSpace input = case alexGetChar input of
775 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
780 nested comments require traversing by hand, they can't be parsed
781 using regular expressions.
783 nested_comment :: P (Located Token) -> Action
784 nested_comment cont span _str _len = do
788 go 0 input = do setInput input; cont
789 go n input = case alexGetChar input of
790 Nothing -> errBrace input span
791 Just ('-',input) -> case alexGetChar input of
792 Nothing -> errBrace input span
793 Just ('\125',input) -> go (n-1) input
794 Just (c,_) -> go n input
795 Just ('\123',input) -> case alexGetChar input of
796 Nothing -> errBrace input span
797 Just ('-',input) -> go (n+1) input
798 Just (c,_) -> go n input
799 Just (c,input) -> go n input
801 nested_doc_comment :: Action
802 nested_doc_comment span buf _len = withLexedDocType (go "")
804 go commentAcc input docType _ = case alexGetChar input of
805 Nothing -> errBrace input span
806 Just ('-',input) -> case alexGetChar input of
807 Nothing -> errBrace input span
808 Just ('\125',input@(AI end _ buf2)) ->
809 docCommentEnd input commentAcc docType buf span
810 Just (c,_) -> go ('-':commentAcc) input docType False
811 Just ('\123', input) -> case alexGetChar input of
812 Nothing -> errBrace input span
813 Just ('-',input) -> do
815 let cont = do input <- getInput; go commentAcc input docType False
816 nested_comment cont span buf _len
817 Just (c,_) -> go ('\123':commentAcc) input docType False
818 Just (c,input) -> go (c:commentAcc) input docType False
820 withLexedDocType lexDocComment = do
821 input@(AI _ _ buf) <- getInput
822 case prevChar buf ' ' of
823 '|' -> lexDocComment input ITdocCommentNext False
824 '^' -> lexDocComment input ITdocCommentPrev False
825 '$' -> lexDocComment input ITdocCommentNamed False
826 '*' -> lexDocSection 1 input
828 lexDocSection n input = case alexGetChar input of
829 Just ('*', input) -> lexDocSection (n+1) input
830 Just (c, _) -> lexDocComment input (ITdocSection n) True
831 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
834 -------------------------------------------------------------------------------
835 -- This function is quite tricky. We can't just return a new token, we also
836 -- need to update the state of the parser. Why? Because the token is longer
837 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
838 -- it writes the wrong token length to the parser state. This function is
839 -- called afterwards, so it can just update the state.
841 -- This is complicated by the fact that Haddock tokens can span multiple lines,
842 -- which is something that the original lexer didn't account for.
843 -- I have added last_line_len in the parser state which represents the length
844 -- of the part of the token that is on the last line. It is now used for layout
845 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
846 -- was before, the full length of the token, and it is now only used for error
849 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
850 SrcSpan -> P (Located Token)
851 docCommentEnd input commentAcc docType buf span = do
853 let (AI loc last_offs nextBuf) = input
854 comment = reverse commentAcc
855 span' = mkSrcSpan (srcSpanStart span) loc
856 last_len = byteDiff buf nextBuf
858 last_line_len = if (last_offs - last_len < 0)
862 span `seq` setLastToken span' last_len last_line_len
863 return (L span' (docType comment))
865 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
867 open_brace, close_brace :: Action
868 open_brace span _str _len = do
870 setContext (NoLayout:ctx)
871 return (L span ITocurly)
872 close_brace span _str _len = do
874 return (L span ITccurly)
876 -- We have to be careful not to count M.<varid> as a qualified name
877 -- when <varid> is a keyword. We hack around this by catching
878 -- the offending tokens afterward, and re-lexing in a different state.
879 check_qvarid span buf len = do
880 case lookupUFM reservedWordsFM var of
882 | not (isSpecial keyword) ->
886 b <- extension (\i -> exts .&. i /= 0)
889 _other -> return token
891 (mod,var) = splitQualName buf len
892 token = L span (ITqvarid (mod,var))
895 (AI _ offs _) <- getInput
896 setInput (AI (srcSpanStart span) (offs-len) buf)
897 pushLexState bad_qvarid
900 qvarid buf len = ITqvarid $! splitQualName buf len
901 qconid buf len = ITqconid $! splitQualName buf len
903 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
904 -- takes a StringBuffer and a length, and returns the module name
905 -- and identifier parts of a qualified name. Splits at the *last* dot,
906 -- because of hierarchical module names.
907 splitQualName orig_buf len = split orig_buf orig_buf
910 | orig_buf `byteDiff` buf >= len = done dot_buf
911 | c == '.' = found_dot buf'
912 | otherwise = split buf' dot_buf
914 (c,buf') = nextChar buf
916 -- careful, we might get names like M....
917 -- so, if the character after the dot is not upper-case, this is
918 -- the end of the qualifier part.
919 found_dot buf -- buf points after the '.'
920 | isUpper c = split buf' buf
921 | otherwise = done buf
923 (c,buf') = nextChar buf
926 (lexemeToFastString orig_buf (qual_size - 1),
927 lexemeToFastString dot_buf (len - qual_size))
929 qual_size = orig_buf `byteDiff` dot_buf
932 case lookupUFM reservedWordsFM fs of
933 Just (keyword,0) -> do
935 return (L span keyword)
936 Just (keyword,exts) -> do
937 b <- extension (\i -> exts .&. i /= 0)
938 if b then do maybe_layout keyword
939 return (L span keyword)
940 else return (L span (ITvarid fs))
941 _other -> return (L span (ITvarid fs))
943 fs = lexemeToFastString buf len
945 conid buf len = ITconid fs
946 where fs = lexemeToFastString buf len
948 qvarsym buf len = ITqvarsym $! splitQualName buf len
949 qconsym buf len = ITqconsym $! splitQualName buf len
951 varsym = sym ITvarsym
952 consym = sym ITconsym
954 sym con span buf len =
955 case lookupUFM reservedSymsFM fs of
956 Just (keyword,exts) -> do
958 if b then return (L span keyword)
959 else return (L span $! con fs)
960 _other -> return (L span $! con fs)
962 fs = lexemeToFastString buf len
964 -- Variations on the integral numeric literal.
965 tok_integral :: (Integer -> Token)
966 -> (Integer -> Integer)
967 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
969 -> (Integer, (Char->Int)) -> Action
970 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
971 return $ L span $ itint $! transint $ parseUnsignedInteger
972 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
974 -- some conveniences for use with tok_integral
975 tok_num = tok_integral ITinteger
976 tok_primint = tok_integral ITprimint
979 decimal = (10,octDecDigit)
980 octal = (8,octDecDigit)
981 hexadecimal = (16,hexDigit)
983 -- readRational can understand negative rationals, exponents, everything.
984 tok_float str = ITrational $! readRational str
985 tok_primfloat str = ITprimfloat $! readRational str
986 tok_primdouble str = ITprimdouble $! readRational str
988 -- -----------------------------------------------------------------------------
991 -- we're at the first token on a line, insert layout tokens if necessary
993 do_bol span _str _len = do
997 --trace "layout: inserting '}'" $ do
999 -- do NOT pop the lex state, we might have a ';' to insert
1000 return (L span ITvccurly)
1002 --trace "layout: inserting ';'" $ do
1004 return (L span ITsemi)
1009 -- certain keywords put us in the "layout" state, where we might
1010 -- add an opening curly brace.
1011 maybe_layout ITdo = pushLexState layout_do
1012 maybe_layout ITmdo = pushLexState layout_do
1013 maybe_layout ITof = pushLexState layout
1014 maybe_layout ITlet = pushLexState layout
1015 maybe_layout ITwhere = pushLexState layout
1016 maybe_layout ITrec = pushLexState layout
1017 maybe_layout _ = return ()
1019 -- Pushing a new implicit layout context. If the indentation of the
1020 -- next token is not greater than the previous layout context, then
1021 -- Haskell 98 says that the new layout context should be empty; that is
1022 -- the lexer must generate {}.
1024 -- We are slightly more lenient than this: when the new context is started
1025 -- by a 'do', then we allow the new context to be at the same indentation as
1026 -- the previous context. This is what the 'strict' argument is for.
1028 new_layout_context strict span _buf _len = do
1030 (AI _ offset _) <- getInput
1033 Layout prev_off : _ |
1034 (strict && prev_off >= offset ||
1035 not strict && prev_off > offset) -> do
1036 -- token is indented to the left of the previous context.
1037 -- we must generate a {} sequence now.
1038 pushLexState layout_left
1039 return (L span ITvocurly)
1041 setContext (Layout offset : ctx)
1042 return (L span ITvocurly)
1044 do_layout_left span _buf _len = do
1046 pushLexState bol -- we must be at the start of a line
1047 return (L span ITvccurly)
1049 -- -----------------------------------------------------------------------------
1052 setLine :: Int -> Action
1053 setLine code span buf len = do
1054 let line = parseUnsignedInteger buf len 10 octDecDigit
1055 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1056 -- subtract one: the line number refers to the *following* line
1061 setFile :: Int -> Action
1062 setFile code span buf len = do
1063 let file = lexemeToFastString (stepOn buf) (len-2)
1064 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1070 -- -----------------------------------------------------------------------------
1071 -- Options, includes and language pragmas.
1073 lex_string_prag :: (String -> Token) -> Action
1074 lex_string_prag mkTok span buf len
1075 = do input <- getInput
1079 return (L (mkSrcSpan start end) tok)
1081 = if isString input "#-}"
1082 then do setInput input
1083 return (mkTok (reverse acc))
1084 else case alexGetChar input of
1085 Just (c,i) -> go (c:acc) i
1086 Nothing -> err input
1087 isString i [] = True
1089 = case alexGetChar i of
1090 Just (c,i') | c == x -> isString i' xs
1092 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1095 -- -----------------------------------------------------------------------------
1098 -- This stuff is horrible. I hates it.
1100 lex_string_tok :: Action
1101 lex_string_tok span buf len = do
1102 tok <- lex_string ""
1104 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1106 lex_string :: String -> P Token
1109 case alexGetChar' i of
1110 Nothing -> lit_error
1114 glaexts <- extension glaExtsEnabled
1118 case alexGetChar' i of
1122 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1123 else let s' = mkZFastString (reverse s) in
1124 return (ITprimstring s')
1125 -- mkZFastString is a hack to avoid encoding the
1126 -- string in UTF-8. We just want the exact bytes.
1128 return (ITstring (mkFastString (reverse s)))
1130 return (ITstring (mkFastString (reverse s)))
1133 | Just ('&',i) <- next -> do
1134 setInput i; lex_string s
1135 | Just (c,i) <- next, is_space c -> do
1136 setInput i; lex_stringgap s
1137 where next = alexGetChar' i
1143 lex_stringgap s = do
1146 '\\' -> lex_string s
1147 c | is_space c -> lex_stringgap s
1151 lex_char_tok :: Action
1152 -- Here we are basically parsing character literals, such as 'x' or '\n'
1153 -- but, when Template Haskell is on, we additionally spot
1154 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1155 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1156 -- So we have to do two characters of lookahead: when we see 'x we need to
1157 -- see if there's a trailing quote
1158 lex_char_tok span buf len = do -- We've seen '
1159 i1 <- getInput -- Look ahead to first character
1160 let loc = srcSpanStart span
1161 case alexGetChar' i1 of
1162 Nothing -> lit_error
1164 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1165 th_exts <- extension thEnabled
1168 return (L (mkSrcSpan loc end2) ITtyQuote)
1171 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
1173 lit_ch <- lex_escape
1174 mc <- getCharOrFail -- Trailing quote
1175 if mc == '\'' then finish_char_tok loc lit_ch
1176 else do setInput i2; lit_error
1178 Just (c, i2@(AI end2 _ _))
1179 | not (isAny c) -> lit_error
1182 -- We've seen 'x, where x is a valid character
1183 -- (i.e. not newline etc) but not a quote or backslash
1184 case alexGetChar' i2 of -- Look ahead one more character
1185 Nothing -> lit_error
1186 Just ('\'', i3) -> do -- We've seen 'x'
1188 finish_char_tok loc c
1189 _other -> do -- We've seen 'x not followed by quote
1190 -- If TH is on, just parse the quote only
1191 th_exts <- extension thEnabled
1192 let (AI end _ _) = i1
1193 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1194 else do setInput i2; lit_error
1196 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1197 finish_char_tok loc ch -- We've already seen the closing quote
1198 -- Just need to check for trailing #
1199 = do glaexts <- extension glaExtsEnabled
1200 i@(AI end _ _) <- getInput
1202 case alexGetChar' i of
1203 Just ('#',i@(AI end _ _)) -> do
1205 return (L (mkSrcSpan loc end) (ITprimchar ch))
1207 return (L (mkSrcSpan loc end) (ITchar ch))
1209 return (L (mkSrcSpan loc end) (ITchar ch))
1211 lex_char :: Char -> AlexInput -> P Char
1214 '\\' -> do setInput inp; lex_escape
1215 c | isAny c -> do setInput inp; return c
1218 isAny c | c > '\xff' = isPrint c
1219 | otherwise = is_any c
1221 lex_escape :: P Char
1235 '^' -> do c <- getCharOrFail
1236 if c >= '@' && c <= '_'
1237 then return (chr (ord c - ord '@'))
1240 'x' -> readNum is_hexdigit 16 hexDigit
1241 'o' -> readNum is_octdigit 8 octDecDigit
1242 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
1246 case alexGetChar' i of
1247 Nothing -> lit_error
1249 case alexGetChar' i2 of
1250 Nothing -> do setInput i2; lit_error
1252 let str = [c1,c2,c3] in
1253 case [ (c,rest) | (p,c) <- silly_escape_chars,
1254 Just rest <- [maybePrefixMatch p str] ] of
1255 (escape_char,[]):_ -> do
1258 (escape_char,_:_):_ -> do
1263 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1264 readNum is_digit base conv = do
1268 then readNum2 is_digit base conv (conv c)
1269 else do setInput i; lit_error
1271 readNum2 is_digit base conv i = do
1274 where read i input = do
1275 case alexGetChar' input of
1276 Just (c,input') | is_digit c -> do
1277 read (i*base + conv c) input'
1279 if i >= 0 && i <= 0x10FFFF
1280 then do setInput input; return (chr i)
1283 silly_escape_chars = [
1320 -- before calling lit_error, ensure that the current input is pointing to
1321 -- the position of the error in the buffer. This is so that we can report
1322 -- a correct location to the user, but also so we can detect UTF-8 decoding
1323 -- errors if they occur.
1324 lit_error = lexError "lexical error in string/character literal"
1326 getCharOrFail :: P Char
1329 case alexGetChar' i of
1330 Nothing -> lexError "unexpected end-of-file in string/character literal"
1331 Just (c,i) -> do setInput i; return c
1333 -- -----------------------------------------------------------------------------
1336 warn :: DynFlag -> SDoc -> Action
1337 warn option warning span _buf _len = do
1338 addWarning option (mkWarnMsg span alwaysQualify warning)
1341 -- -----------------------------------------------------------------------------
1352 SrcSpan -- The start and end of the text span related to
1353 -- the error. Might be used in environments which can
1354 -- show this span, e.g. by highlighting it.
1355 Message -- The error message
1357 data PState = PState {
1358 buffer :: StringBuffer,
1360 messages :: Messages,
1361 last_loc :: SrcSpan, -- pos of previous token
1362 last_offs :: !Int, -- offset of the previous token from the
1363 -- beginning of the current line.
1364 -- \t is equal to 8 spaces.
1365 last_len :: !Int, -- len of previous token
1366 last_line_len :: !Int,
1367 loc :: SrcLoc, -- current loc (end of prev token + 1)
1368 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1369 context :: [LayoutContext],
1372 -- last_loc and last_len are used when generating error messages,
1373 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1374 -- current token to happyError, we could at least get rid of last_len.
1375 -- Getting rid of last_loc would require finding another way to
1376 -- implement pushCurrentContext (which is only called from one place).
1378 newtype P a = P { unP :: PState -> ParseResult a }
1380 instance Monad P where
1386 returnP a = P $ \s -> POk s a
1388 thenP :: P a -> (a -> P b) -> P b
1389 (P m) `thenP` k = P $ \ s ->
1391 POk s1 a -> (unP (k a)) s1
1392 PFailed span err -> PFailed span err
1394 failP :: String -> P a
1395 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1397 failMsgP :: String -> P a
1398 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1400 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1401 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1403 failSpanMsgP :: SrcSpan -> String -> P a
1404 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1406 extension :: (Int -> Bool) -> P Bool
1407 extension p = P $ \s -> POk s (p $! extsBitmap s)
1410 getExts = P $ \s -> POk s (extsBitmap s)
1412 setSrcLoc :: SrcLoc -> P ()
1413 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1415 getSrcLoc :: P SrcLoc
1416 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1418 setLastToken :: SrcSpan -> Int -> Int -> P ()
1419 setLastToken loc len line_len = P $ \s -> POk s {
1422 last_line_len=line_len
1425 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1427 alexInputPrevChar :: AlexInput -> Char
1428 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1430 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1431 alexGetChar (AI loc ofs s)
1433 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1434 --trace (show (ord c)) $
1435 Just (adj_c, (AI loc' ofs' s'))
1436 where (c,s') = nextChar s
1437 loc' = advanceSrcLoc loc c
1438 ofs' = advanceOffs c ofs
1446 other_graphic = '\x6'
1449 | c <= '\x06' = non_graphic
1451 -- Alex doesn't handle Unicode, so when Unicode
1452 -- character is encoutered we output these values
1453 -- with the actual character value hidden in the state.
1455 case generalCategory c of
1456 UppercaseLetter -> upper
1457 LowercaseLetter -> lower
1458 TitlecaseLetter -> upper
1459 ModifierLetter -> other_graphic
1460 OtherLetter -> other_graphic
1461 NonSpacingMark -> other_graphic
1462 SpacingCombiningMark -> other_graphic
1463 EnclosingMark -> other_graphic
1464 DecimalNumber -> digit
1465 LetterNumber -> other_graphic
1466 OtherNumber -> other_graphic
1467 ConnectorPunctuation -> other_graphic
1468 DashPunctuation -> other_graphic
1469 OpenPunctuation -> other_graphic
1470 ClosePunctuation -> other_graphic
1471 InitialQuote -> other_graphic
1472 FinalQuote -> other_graphic
1473 OtherPunctuation -> other_graphic
1474 MathSymbol -> symbol
1475 CurrencySymbol -> symbol
1476 ModifierSymbol -> symbol
1477 OtherSymbol -> symbol
1479 _other -> non_graphic
1481 -- This version does not squash unicode characters, it is used when
1483 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1484 alexGetChar' (AI loc ofs s)
1486 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1487 --trace (show (ord c)) $
1488 Just (c, (AI loc' ofs' s'))
1489 where (c,s') = nextChar s
1490 loc' = advanceSrcLoc loc c
1491 ofs' = advanceOffs c ofs
1493 advanceOffs :: Char -> Int -> Int
1494 advanceOffs '\n' offs = 0
1495 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1496 advanceOffs _ offs = offs + 1
1498 getInput :: P AlexInput
1499 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1501 setInput :: AlexInput -> P ()
1502 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1504 pushLexState :: Int -> P ()
1505 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1507 popLexState :: P Int
1508 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1510 getLexState :: P Int
1511 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1513 -- for reasons of efficiency, flags indicating language extensions (eg,
1514 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1517 glaExtsBit, ffiBit, parrBit :: Int
1524 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1525 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1526 -- (doesn't affect the lexer)
1527 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1528 haddockBit = 10 -- Lex and parse Haddock comments
1529 magicHashBit = 11 -- # in both functions and operators
1530 kindSigsBit = 12 -- Kind signatures on type variables
1531 recursiveDoBit = 13 -- mdo
1532 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1533 unboxedTuplesBit = 15 -- (# and #)
1535 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1537 glaExtsEnabled flags = testBit flags glaExtsBit
1538 ffiEnabled flags = testBit flags ffiBit
1539 parrEnabled flags = testBit flags parrBit
1540 arrowsEnabled flags = testBit flags arrowsBit
1541 thEnabled flags = testBit flags thBit
1542 ipEnabled flags = testBit flags ipBit
1543 explicitForallEnabled flags = testBit flags explicitForallBit
1544 bangPatEnabled flags = testBit flags bangPatBit
1545 tyFamEnabled flags = testBit flags tyFamBit
1546 haddockEnabled flags = testBit flags haddockBit
1547 magicHashEnabled flags = testBit flags magicHashBit
1548 kindSigsEnabled flags = testBit flags kindSigsBit
1549 recursiveDoEnabled flags = testBit flags recursiveDoBit
1550 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1551 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1553 -- PState for parsing options pragmas
1555 pragState :: StringBuffer -> SrcLoc -> PState
1559 messages = emptyMessages,
1560 -- XXX defaultDynFlags is not right, but we don't have a real
1562 dflags = defaultDynFlags,
1563 last_loc = mkSrcSpan loc loc,
1570 lex_state = [bol, option_prags, 0]
1574 -- create a parse state
1576 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1577 mkPState buf loc flags =
1581 messages = emptyMessages,
1582 last_loc = mkSrcSpan loc loc,
1587 extsBitmap = fromIntegral bitmap,
1589 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1590 -- we begin in the layout state if toplev_layout is set
1593 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1594 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1595 .|. parrBit `setBitIf` dopt Opt_PArr flags
1596 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1597 .|. thBit `setBitIf` dopt Opt_TH flags
1598 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1599 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1600 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1601 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1602 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1603 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1604 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1605 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1606 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1607 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1608 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1609 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1611 setBitIf :: Int -> Bool -> Int
1612 b `setBitIf` cond | cond = bit b
1615 addWarning :: DynFlag -> WarnMsg -> P ()
1617 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1618 let ws' = if dopt option d then ws `snocBag` w else ws
1619 in POk s{messages=(ws', es)} ()
1621 getMessages :: PState -> Messages
1622 getMessages PState{messages=ms} = ms
1624 getContext :: P [LayoutContext]
1625 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1627 setContext :: [LayoutContext] -> P ()
1628 setContext ctx = P $ \s -> POk s{context=ctx} ()
1631 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1632 loc = loc, last_len = len, last_loc = last_loc }) ->
1634 (_:tl) -> POk s{ context = tl } ()
1635 [] -> PFailed last_loc (srcParseErr buf len)
1637 -- Push a new layout context at the indentation of the last token read.
1638 -- This is only used at the outer level of a module when the 'module'
1639 -- keyword is missing.
1640 pushCurrentContext :: P ()
1641 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1642 POk s{context = Layout (offs-len) : ctx} ()
1643 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1645 getOffside :: P Ordering
1646 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1647 let ord = case stk of
1648 (Layout n:_) -> compare offs n
1652 -- ---------------------------------------------------------------------------
1653 -- Construct a parse error
1656 :: StringBuffer -- current buffer (placed just after the last token)
1657 -> Int -- length of the previous token
1660 = hcat [ if null token
1661 then ptext SLIT("parse error (possibly incorrect indentation)")
1662 else hcat [ptext SLIT("parse error on input "),
1663 char '`', text token, char '\'']
1665 where token = lexemeToString (offsetBytes (-len) buf) len
1667 -- Report a parse failure, giving the span of the previous token as
1668 -- the location of the error. This is the entry point for errors
1669 -- detected during parsing.
1671 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1672 last_loc = last_loc } ->
1673 PFailed last_loc (srcParseErr buf len)
1675 -- A lexical error is reported at a particular position in the source file,
1676 -- not over a token range.
1677 lexError :: String -> P a
1680 i@(AI end _ buf) <- getInput
1681 reportLexError loc end buf str
1683 -- -----------------------------------------------------------------------------
1684 -- This is the top-level function: called from the parser each time a
1685 -- new token is to be read from the input.
1687 lexer :: (Located Token -> P a) -> P a
1689 tok@(L span tok__) <- lexToken
1690 -- trace ("token: " ++ show tok__) $ do
1693 lexToken :: P (Located Token)
1695 inp@(AI loc1 _ buf) <- getInput
1698 case alexScanUser exts inp sc of
1699 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1700 setLastToken span 0 0
1701 return (L span ITeof)
1702 AlexError (AI loc2 _ buf) -> do
1703 reportLexError loc1 loc2 buf "lexical error"
1704 AlexSkip inp2 _ -> do
1707 AlexToken inp2@(AI end _ buf2) len t -> do
1709 let span = mkSrcSpan loc1 end
1710 let bytes = byteDiff buf buf2
1711 span `seq` setLastToken span bytes bytes
1714 reportLexError loc1 loc2 buf str
1715 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1718 c = fst (nextChar buf)
1720 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1721 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1722 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)