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 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 }
232 <0,option_prags,glaexts> {
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 }
269 <0,option_prags,glaexts> {
270 -- This is to catch things like {-# OPTIONS OPTIONS_HUGS ...
271 "{-#" $whitechar* $idchar+ { nested_comment lexToken }
274 -- '0' state: ordinary lexemes
275 -- 'glaexts' state: glasgow extensions (postfix '#', etc.)
280 "-- " $docsym / { ifExtension haddockEnabled } { multiline_doc_comment }
281 "{-" \ ? $docsym / { ifExtension haddockEnabled } { nested_doc_comment }
287 "[:" / { ifExtension parrEnabled } { token ITopabrack }
288 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
292 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
293 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
294 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
295 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
296 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
297 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
298 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
299 "$(" / { ifExtension thEnabled } { token ITparenEscape }
303 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
304 { special IToparenbar }
305 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
309 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
313 "(#" / { ifExtension unboxedTuplesEnabled `alexAndPred` notFollowedBySymbol }
314 { token IToubxparen }
315 "#)" / { ifExtension unboxedTuplesEnabled }
316 { token ITcubxparen }
320 "{|" / { ifExtension genericsEnabled } { token ITocurlybar }
321 "|}" / { ifExtension genericsEnabled } { token ITccurlybar }
324 <0,option_prags,glaexts> {
325 \( { special IToparen }
326 \) { special ITcparen }
327 \[ { special ITobrack }
328 \] { special ITcbrack }
329 \, { special ITcomma }
330 \; { special ITsemi }
331 \` { special ITbackquote }
337 <0,option_prags,glaexts> {
338 @qual @varid { check_qvarid }
339 @qual @conid { idtoken qconid }
341 @conid { idtoken conid }
344 -- after an illegal qvarid, such as 'M.let',
345 -- we back up and try again in the bad_qvarid state:
347 @conid { pop_and (idtoken conid) }
348 @qual @conid { pop_and (idtoken qconid) }
352 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
353 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
354 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
355 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
361 @qual @varsym { idtoken qvarsym }
362 @qual @consym { idtoken qconsym }
367 -- For the normal boxed literals we need to be careful
368 -- when trying to be close to Haskell98
370 -- Normal integral literals (:: Num a => a, from Integer)
371 @decimal { tok_num positive 0 0 decimal }
372 0[oO] @octal { tok_num positive 2 2 octal }
373 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
375 -- Normal rational literals (:: Fractional a => a, from Rational)
376 @floating_point { strtoken tok_float }
380 -- Unboxed ints (:: Int#)
381 -- It's simpler (and faster?) to give separate cases to the negatives,
382 -- especially considering octal/hexadecimal prefixes.
383 @decimal \# { tok_primint positive 0 1 decimal }
384 0[oO] @octal \# { tok_primint positive 2 3 octal }
385 0[xX] @hexadecimal \# { tok_primint positive 2 3 hexadecimal }
386 @negative @decimal \# { tok_primint negative 1 2 decimal }
387 @negative 0[oO] @octal \# { tok_primint negative 3 4 octal }
388 @negative 0[xX] @hexadecimal \# { tok_primint negative 3 4 hexadecimal }
390 -- Unboxed floats and doubles (:: Float#, :: Double#)
391 -- prim_{float,double} work with signed literals
392 @signed @floating_point \# { init_strtoken 1 tok_primfloat }
393 @signed @floating_point \# \# { init_strtoken 2 tok_primdouble }
396 -- Strings and chars are lexed by hand-written code. The reason is
397 -- that even if we recognise the string or char here in the regex
398 -- lexer, we would still have to parse the string afterward in order
399 -- to convert it to a String.
402 \" { lex_string_tok }
406 -- -----------------------------------------------------------------------------
410 = ITas -- Haskell keywords
435 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
437 | ITforall -- GHC extension keywords
452 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
453 | ITspec_prag -- SPECIALISE
454 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
461 | ITcore_prag -- hdaume: core annotations
464 | IToptions_prag String
465 | ITinclude_prag String
468 | ITdotdot -- reserved symbols
484 | ITbiglam -- GHC-extension symbols
486 | ITocurly -- special symbols
488 | ITocurlybar -- {|, for type applications
489 | ITccurlybar -- |}, for type applications
493 | ITopabrack -- [:, for parallel arrays with -fparr
494 | ITcpabrack -- :], for parallel arrays with -fparr
505 | ITvarid FastString -- identifiers
507 | ITvarsym FastString
508 | ITconsym FastString
509 | ITqvarid (FastString,FastString)
510 | ITqconid (FastString,FastString)
511 | ITqvarsym (FastString,FastString)
512 | ITqconsym (FastString,FastString)
514 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
516 | ITpragma StringBuffer
519 | ITstring FastString
521 | ITrational Rational
524 | ITprimstring FastString
526 | ITprimfloat Rational
527 | ITprimdouble Rational
529 -- MetaHaskell extension tokens
530 | ITopenExpQuote -- [| or [e|
531 | ITopenPatQuote -- [p|
532 | ITopenDecQuote -- [d|
533 | ITopenTypQuote -- [t|
535 | ITidEscape FastString -- $x
536 | ITparenEscape -- $(
540 -- Arrow notation extension
547 | ITLarrowtail -- -<<
548 | ITRarrowtail -- >>-
550 | ITunknown String -- Used when the lexer can't make sense of it
551 | ITeof -- end of file token
553 -- Documentation annotations
554 | ITdocCommentNext String -- something beginning '-- |'
555 | ITdocCommentPrev String -- something beginning '-- ^'
556 | ITdocCommentNamed String -- something beginning '-- $'
557 | ITdocSection Int String -- a section heading
558 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
561 deriving Show -- debugging
564 isSpecial :: Token -> Bool
565 -- If we see M.x, where x is a keyword, but
566 -- is special, we treat is as just plain M.x,
568 isSpecial ITas = True
569 isSpecial IThiding = True
570 isSpecial ITderive = True
571 isSpecial ITqualified = True
572 isSpecial ITforall = True
573 isSpecial ITexport = True
574 isSpecial ITlabel = True
575 isSpecial ITdynamic = True
576 isSpecial ITsafe = True
577 isSpecial ITthreadsafe = True
578 isSpecial ITunsafe = True
579 isSpecial ITccallconv = True
580 isSpecial ITstdcallconv = True
581 isSpecial ITmdo = True
582 isSpecial ITfamily = True
585 -- the bitmap provided as the third component indicates whether the
586 -- corresponding extension keyword is valid under the extension options
587 -- provided to the compiler; if the extension corresponding to *any* of the
588 -- bits set in the bitmap is enabled, the keyword is valid (this setup
589 -- facilitates using a keyword in two different extensions that can be
590 -- activated independently)
592 reservedWordsFM = listToUFM $
593 map (\(x, y, z) -> (mkFastString x, (y, z)))
594 [( "_", ITunderscore, 0 ),
596 ( "case", ITcase, 0 ),
597 ( "class", ITclass, 0 ),
598 ( "data", ITdata, 0 ),
599 ( "default", ITdefault, 0 ),
600 ( "deriving", ITderiving, 0 ),
601 ( "derive", ITderive, 0 ),
603 ( "else", ITelse, 0 ),
604 ( "hiding", IThiding, 0 ),
606 ( "import", ITimport, 0 ),
608 ( "infix", ITinfix, 0 ),
609 ( "infixl", ITinfixl, 0 ),
610 ( "infixr", ITinfixr, 0 ),
611 ( "instance", ITinstance, 0 ),
613 ( "module", ITmodule, 0 ),
614 ( "newtype", ITnewtype, 0 ),
616 ( "qualified", ITqualified, 0 ),
617 ( "then", ITthen, 0 ),
618 ( "type", ITtype, 0 ),
619 ( "where", ITwhere, 0 ),
620 ( "_scc_", ITscc, 0 ), -- ToDo: remove
622 ( "forall", ITforall, bit explicitForallBit),
623 ( "mdo", ITmdo, bit recursiveDoBit),
624 ( "family", ITfamily, bit tyFamBit),
626 ( "foreign", ITforeign, bit ffiBit),
627 ( "export", ITexport, bit ffiBit),
628 ( "label", ITlabel, bit ffiBit),
629 ( "dynamic", ITdynamic, bit ffiBit),
630 ( "safe", ITsafe, bit ffiBit),
631 ( "threadsafe", ITthreadsafe, bit ffiBit),
632 ( "unsafe", ITunsafe, bit ffiBit),
633 ( "stdcall", ITstdcallconv, bit ffiBit),
634 ( "ccall", ITccallconv, bit ffiBit),
635 ( "dotnet", ITdotnet, bit ffiBit),
637 ( "rec", ITrec, bit arrowsBit),
638 ( "proc", ITproc, bit arrowsBit)
641 reservedSymsFM :: UniqFM (Token, Int -> Bool)
642 reservedSymsFM = listToUFM $
643 map (\ (x,y,z) -> (mkFastString x,(y,z)))
644 [ ("..", ITdotdot, always)
645 -- (:) is a reserved op, meaning only list cons
646 ,(":", ITcolon, always)
647 ,("::", ITdcolon, always)
648 ,("=", ITequal, always)
649 ,("\\", ITlam, always)
650 ,("|", ITvbar, always)
651 ,("<-", ITlarrow, always)
652 ,("->", ITrarrow, always)
654 ,("~", ITtilde, always)
655 ,("=>", ITdarrow, always)
656 ,("-", ITminus, always)
657 ,("!", ITbang, always)
659 -- For data T (a::*) = MkT
660 ,("*", ITstar, \i -> glaExtsEnabled i ||
663 -- For 'forall a . t'
664 ,(".", ITdot, explicitForallEnabled)
666 ,("-<", ITlarrowtail, arrowsEnabled)
667 ,(">-", ITrarrowtail, arrowsEnabled)
668 ,("-<<", ITLarrowtail, arrowsEnabled)
669 ,(">>-", ITRarrowtail, arrowsEnabled)
671 #if __GLASGOW_HASKELL__ >= 605
672 ,("∷", ITdcolon, unicodeSyntaxEnabled)
673 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
674 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
675 explicitForallEnabled i)
676 ,("→", ITrarrow, unicodeSyntaxEnabled)
677 ,("←", ITlarrow, unicodeSyntaxEnabled)
678 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
679 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
680 -- form part of a large operator. This would let us have a better
681 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
685 -- -----------------------------------------------------------------------------
688 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
690 special :: Token -> Action
691 special tok span _buf len = return (L span tok)
693 token, layout_token :: Token -> Action
694 token t span buf len = return (L span t)
695 layout_token t span buf len = pushLexState layout >> return (L span t)
697 idtoken :: (StringBuffer -> Int -> Token) -> Action
698 idtoken f span buf len = return (L span $! (f buf len))
700 skip_one_varid :: (FastString -> Token) -> Action
701 skip_one_varid f span buf len
702 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
704 strtoken :: (String -> Token) -> Action
705 strtoken f span buf len =
706 return (L span $! (f $! lexemeToString buf len))
708 init_strtoken :: Int -> (String -> Token) -> Action
709 -- like strtoken, but drops the last N character(s)
710 init_strtoken drop f span buf len =
711 return (L span $! (f $! lexemeToString buf (len-drop)))
713 begin :: Int -> Action
714 begin code _span _str _len = do pushLexState code; lexToken
717 pop _span _buf _len = do popLexState; lexToken
719 pop_and :: Action -> Action
720 pop_and act span buf len = do popLexState; act span buf len
722 {-# INLINE nextCharIs #-}
723 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
725 notFollowedBy char _ _ _ (AI _ _ buf)
726 = nextCharIs buf (/=char)
728 notFollowedBySymbol _ _ _ (AI _ _ buf)
729 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
731 -- We must reject doc comments as being ordinary comments everywhere.
732 -- In some cases the doc comment will be selected as the lexeme due to
733 -- maximal munch, but not always, because the nested comment rule is
734 -- valid in all states, but the doc-comment rules are only valid in
735 -- the non-layout states.
736 isNormalComment bits _ _ (AI _ _ buf)
737 | haddockEnabled bits = notFollowedByDocOrPragma
738 | otherwise = nextCharIs buf (/='#')
740 notFollowedByDocOrPragma
741 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
743 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
745 haddockDisabledAnd p bits _ _ (AI _ _ buf)
746 = if haddockEnabled bits then False else (p buf)
748 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
750 ifExtension pred bits _ _ _ = pred bits
752 multiline_doc_comment :: Action
753 multiline_doc_comment span buf _len = withLexedDocType (worker "")
755 worker commentAcc input docType oneLine = case alexGetChar input of
757 | oneLine -> docCommentEnd input commentAcc docType buf span
758 | otherwise -> case checkIfCommentLine input' of
759 Just input -> worker ('\n':commentAcc) input docType False
760 Nothing -> docCommentEnd input commentAcc docType buf span
761 Just (c, input) -> worker (c:commentAcc) input docType oneLine
762 Nothing -> docCommentEnd input commentAcc docType buf span
764 checkIfCommentLine input = check (dropNonNewlineSpace input)
766 check input = case alexGetChar input of
767 Just ('-', input) -> case alexGetChar input of
768 Just ('-', input) -> case alexGetChar input of
769 Just (c, _) | c /= '-' -> Just input
774 dropNonNewlineSpace input = case alexGetChar input of
776 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
781 nested comments require traversing by hand, they can't be parsed
782 using regular expressions.
784 nested_comment :: P (Located Token) -> Action
785 nested_comment cont span _str _len = do
789 go 0 input = do setInput input; cont
790 go n input = case alexGetChar input of
791 Nothing -> errBrace input span
792 Just ('-',input) -> case alexGetChar input of
793 Nothing -> errBrace input span
794 Just ('\125',input) -> go (n-1) input
795 Just (c,_) -> go n input
796 Just ('\123',input) -> case alexGetChar input of
797 Nothing -> errBrace input span
798 Just ('-',input) -> go (n+1) input
799 Just (c,_) -> go n input
800 Just (c,input) -> go n input
802 nested_doc_comment :: Action
803 nested_doc_comment span buf _len = withLexedDocType (go "")
805 go commentAcc input docType _ = case alexGetChar input of
806 Nothing -> errBrace input span
807 Just ('-',input) -> case alexGetChar input of
808 Nothing -> errBrace input span
809 Just ('\125',input@(AI end _ buf2)) ->
810 docCommentEnd input commentAcc docType buf span
811 Just (c,_) -> go ('-':commentAcc) input docType False
812 Just ('\123', input) -> case alexGetChar input of
813 Nothing -> errBrace input span
814 Just ('-',input) -> do
816 let cont = do input <- getInput; go commentAcc input docType False
817 nested_comment cont span buf _len
818 Just (c,_) -> go ('\123':commentAcc) input docType False
819 Just (c,input) -> go (c:commentAcc) input docType False
821 withLexedDocType lexDocComment = do
822 input@(AI _ _ buf) <- getInput
823 case prevChar buf ' ' of
824 '|' -> lexDocComment input ITdocCommentNext False
825 '^' -> lexDocComment input ITdocCommentPrev False
826 '$' -> lexDocComment input ITdocCommentNamed False
827 '*' -> lexDocSection 1 input
829 lexDocSection n input = case alexGetChar input of
830 Just ('*', input) -> lexDocSection (n+1) input
831 Just (c, _) -> lexDocComment input (ITdocSection n) True
832 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
835 -------------------------------------------------------------------------------
836 -- This function is quite tricky. We can't just return a new token, we also
837 -- need to update the state of the parser. Why? Because the token is longer
838 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
839 -- it writes the wrong token length to the parser state. This function is
840 -- called afterwards, so it can just update the state.
842 -- This is complicated by the fact that Haddock tokens can span multiple lines,
843 -- which is something that the original lexer didn't account for.
844 -- I have added last_line_len in the parser state which represents the length
845 -- of the part of the token that is on the last line. It is now used for layout
846 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
847 -- was before, the full length of the token, and it is now only used for error
850 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
851 SrcSpan -> P (Located Token)
852 docCommentEnd input commentAcc docType buf span = do
854 let (AI loc last_offs nextBuf) = input
855 comment = reverse commentAcc
856 span' = mkSrcSpan (srcSpanStart span) loc
857 last_len = byteDiff buf nextBuf
859 last_line_len = if (last_offs - last_len < 0)
863 span `seq` setLastToken span' last_len last_line_len
864 return (L span' (docType comment))
866 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
868 open_brace, close_brace :: Action
869 open_brace span _str _len = do
871 setContext (NoLayout:ctx)
872 return (L span ITocurly)
873 close_brace span _str _len = do
875 return (L span ITccurly)
877 -- We have to be careful not to count M.<varid> as a qualified name
878 -- when <varid> is a keyword. We hack around this by catching
879 -- the offending tokens afterward, and re-lexing in a different state.
880 check_qvarid span buf len = do
881 case lookupUFM reservedWordsFM var of
883 | not (isSpecial keyword) ->
887 b <- extension (\i -> exts .&. i /= 0)
890 _other -> return token
892 (mod,var) = splitQualName buf len
893 token = L span (ITqvarid (mod,var))
896 (AI _ offs _) <- getInput
897 setInput (AI (srcSpanStart span) (offs-len) buf)
898 pushLexState bad_qvarid
901 qvarid buf len = ITqvarid $! splitQualName buf len
902 qconid buf len = ITqconid $! splitQualName buf len
904 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
905 -- takes a StringBuffer and a length, and returns the module name
906 -- and identifier parts of a qualified name. Splits at the *last* dot,
907 -- because of hierarchical module names.
908 splitQualName orig_buf len = split orig_buf orig_buf
911 | orig_buf `byteDiff` buf >= len = done dot_buf
912 | c == '.' = found_dot buf'
913 | otherwise = split buf' dot_buf
915 (c,buf') = nextChar buf
917 -- careful, we might get names like M....
918 -- so, if the character after the dot is not upper-case, this is
919 -- the end of the qualifier part.
920 found_dot buf -- buf points after the '.'
921 | isUpper c = split buf' buf
922 | otherwise = done buf
924 (c,buf') = nextChar buf
927 (lexemeToFastString orig_buf (qual_size - 1),
928 lexemeToFastString dot_buf (len - qual_size))
930 qual_size = orig_buf `byteDiff` dot_buf
933 case lookupUFM reservedWordsFM fs of
934 Just (keyword,0) -> do
936 return (L span keyword)
937 Just (keyword,exts) -> do
938 b <- extension (\i -> exts .&. i /= 0)
939 if b then do maybe_layout keyword
940 return (L span keyword)
941 else return (L span (ITvarid fs))
942 _other -> return (L span (ITvarid fs))
944 fs = lexemeToFastString buf len
946 conid buf len = ITconid fs
947 where fs = lexemeToFastString buf len
949 qvarsym buf len = ITqvarsym $! splitQualName buf len
950 qconsym buf len = ITqconsym $! splitQualName buf len
952 varsym = sym ITvarsym
953 consym = sym ITconsym
955 sym con span buf len =
956 case lookupUFM reservedSymsFM fs of
957 Just (keyword,exts) -> do
959 if b then return (L span keyword)
960 else return (L span $! con fs)
961 _other -> return (L span $! con fs)
963 fs = lexemeToFastString buf len
965 -- Variations on the integral numeric literal.
966 tok_integral :: (Integer -> Token)
967 -> (Integer -> Integer)
968 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
970 -> (Integer, (Char->Int)) -> Action
971 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
972 return $ L span $ itint $! transint $ parseUnsignedInteger
973 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
975 -- some conveniences for use with tok_integral
976 tok_num = tok_integral ITinteger
977 tok_primint = tok_integral ITprimint
980 decimal = (10,octDecDigit)
981 octal = (8,octDecDigit)
982 hexadecimal = (16,hexDigit)
984 -- readRational can understand negative rationals, exponents, everything.
985 tok_float str = ITrational $! readRational str
986 tok_primfloat str = ITprimfloat $! readRational str
987 tok_primdouble str = ITprimdouble $! readRational str
989 -- -----------------------------------------------------------------------------
992 -- we're at the first token on a line, insert layout tokens if necessary
994 do_bol span _str _len = do
998 --trace "layout: inserting '}'" $ do
1000 -- do NOT pop the lex state, we might have a ';' to insert
1001 return (L span ITvccurly)
1003 --trace "layout: inserting ';'" $ do
1005 return (L span ITsemi)
1010 -- certain keywords put us in the "layout" state, where we might
1011 -- add an opening curly brace.
1012 maybe_layout ITdo = pushLexState layout_do
1013 maybe_layout ITmdo = pushLexState layout_do
1014 maybe_layout ITof = pushLexState layout
1015 maybe_layout ITlet = pushLexState layout
1016 maybe_layout ITwhere = pushLexState layout
1017 maybe_layout ITrec = pushLexState layout
1018 maybe_layout _ = return ()
1020 -- Pushing a new implicit layout context. If the indentation of the
1021 -- next token is not greater than the previous layout context, then
1022 -- Haskell 98 says that the new layout context should be empty; that is
1023 -- the lexer must generate {}.
1025 -- We are slightly more lenient than this: when the new context is started
1026 -- by a 'do', then we allow the new context to be at the same indentation as
1027 -- the previous context. This is what the 'strict' argument is for.
1029 new_layout_context strict span _buf _len = do
1031 (AI _ offset _) <- getInput
1034 Layout prev_off : _ |
1035 (strict && prev_off >= offset ||
1036 not strict && prev_off > offset) -> do
1037 -- token is indented to the left of the previous context.
1038 -- we must generate a {} sequence now.
1039 pushLexState layout_left
1040 return (L span ITvocurly)
1042 setContext (Layout offset : ctx)
1043 return (L span ITvocurly)
1045 do_layout_left span _buf _len = do
1047 pushLexState bol -- we must be at the start of a line
1048 return (L span ITvccurly)
1050 -- -----------------------------------------------------------------------------
1053 setLine :: Int -> Action
1054 setLine code span buf len = do
1055 let line = parseUnsignedInteger buf len 10 octDecDigit
1056 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1057 -- subtract one: the line number refers to the *following* line
1062 setFile :: Int -> Action
1063 setFile code span buf len = do
1064 let file = lexemeToFastString (stepOn buf) (len-2)
1065 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1071 -- -----------------------------------------------------------------------------
1072 -- Options, includes and language pragmas.
1074 lex_string_prag :: (String -> Token) -> Action
1075 lex_string_prag mkTok span buf len
1076 = do input <- getInput
1080 return (L (mkSrcSpan start end) tok)
1082 = if isString input "#-}"
1083 then do setInput input
1084 return (mkTok (reverse acc))
1085 else case alexGetChar input of
1086 Just (c,i) -> go (c:acc) i
1087 Nothing -> err input
1088 isString i [] = True
1090 = case alexGetChar i of
1091 Just (c,i') | c == x -> isString i' xs
1093 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1096 -- -----------------------------------------------------------------------------
1099 -- This stuff is horrible. I hates it.
1101 lex_string_tok :: Action
1102 lex_string_tok span buf len = do
1103 tok <- lex_string ""
1105 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1107 lex_string :: String -> P Token
1110 case alexGetChar' i of
1111 Nothing -> lit_error
1115 glaexts <- extension glaExtsEnabled
1119 case alexGetChar' i of
1123 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1124 else let s' = mkZFastString (reverse s) in
1125 return (ITprimstring s')
1126 -- mkZFastString is a hack to avoid encoding the
1127 -- string in UTF-8. We just want the exact bytes.
1129 return (ITstring (mkFastString (reverse s)))
1131 return (ITstring (mkFastString (reverse s)))
1134 | Just ('&',i) <- next -> do
1135 setInput i; lex_string s
1136 | Just (c,i) <- next, is_space c -> do
1137 setInput i; lex_stringgap s
1138 where next = alexGetChar' i
1144 lex_stringgap s = do
1147 '\\' -> lex_string s
1148 c | is_space c -> lex_stringgap s
1152 lex_char_tok :: Action
1153 -- Here we are basically parsing character literals, such as 'x' or '\n'
1154 -- but, when Template Haskell is on, we additionally spot
1155 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1156 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1157 -- So we have to do two characters of lookahead: when we see 'x we need to
1158 -- see if there's a trailing quote
1159 lex_char_tok span buf len = do -- We've seen '
1160 i1 <- getInput -- Look ahead to first character
1161 let loc = srcSpanStart span
1162 case alexGetChar' i1 of
1163 Nothing -> lit_error
1165 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1166 th_exts <- extension thEnabled
1169 return (L (mkSrcSpan loc end2) ITtyQuote)
1172 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
1174 lit_ch <- lex_escape
1175 mc <- getCharOrFail -- Trailing quote
1176 if mc == '\'' then finish_char_tok loc lit_ch
1177 else do setInput i2; lit_error
1179 Just (c, i2@(AI end2 _ _))
1180 | not (isAny c) -> lit_error
1183 -- We've seen 'x, where x is a valid character
1184 -- (i.e. not newline etc) but not a quote or backslash
1185 case alexGetChar' i2 of -- Look ahead one more character
1186 Nothing -> lit_error
1187 Just ('\'', i3) -> do -- We've seen 'x'
1189 finish_char_tok loc c
1190 _other -> do -- We've seen 'x not followed by quote
1191 -- If TH is on, just parse the quote only
1192 th_exts <- extension thEnabled
1193 let (AI end _ _) = i1
1194 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1195 else do setInput i2; lit_error
1197 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1198 finish_char_tok loc ch -- We've already seen the closing quote
1199 -- Just need to check for trailing #
1200 = do glaexts <- extension glaExtsEnabled
1201 i@(AI end _ _) <- getInput
1203 case alexGetChar' i of
1204 Just ('#',i@(AI end _ _)) -> do
1206 return (L (mkSrcSpan loc end) (ITprimchar ch))
1208 return (L (mkSrcSpan loc end) (ITchar ch))
1210 return (L (mkSrcSpan loc end) (ITchar ch))
1212 lex_char :: Char -> AlexInput -> P Char
1215 '\\' -> do setInput inp; lex_escape
1216 c | isAny c -> do setInput inp; return c
1219 isAny c | c > '\xff' = isPrint c
1220 | otherwise = is_any c
1222 lex_escape :: P Char
1236 '^' -> do c <- getCharOrFail
1237 if c >= '@' && c <= '_'
1238 then return (chr (ord c - ord '@'))
1241 'x' -> readNum is_hexdigit 16 hexDigit
1242 'o' -> readNum is_octdigit 8 octDecDigit
1243 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
1247 case alexGetChar' i of
1248 Nothing -> lit_error
1250 case alexGetChar' i2 of
1251 Nothing -> do setInput i2; lit_error
1253 let str = [c1,c2,c3] in
1254 case [ (c,rest) | (p,c) <- silly_escape_chars,
1255 Just rest <- [maybePrefixMatch p str] ] of
1256 (escape_char,[]):_ -> do
1259 (escape_char,_:_):_ -> do
1264 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1265 readNum is_digit base conv = do
1269 then readNum2 is_digit base conv (conv c)
1270 else do setInput i; lit_error
1272 readNum2 is_digit base conv i = do
1275 where read i input = do
1276 case alexGetChar' input of
1277 Just (c,input') | is_digit c -> do
1278 read (i*base + conv c) input'
1280 if i >= 0 && i <= 0x10FFFF
1281 then do setInput input; return (chr i)
1284 silly_escape_chars = [
1321 -- before calling lit_error, ensure that the current input is pointing to
1322 -- the position of the error in the buffer. This is so that we can report
1323 -- a correct location to the user, but also so we can detect UTF-8 decoding
1324 -- errors if they occur.
1325 lit_error = lexError "lexical error in string/character literal"
1327 getCharOrFail :: P Char
1330 case alexGetChar' i of
1331 Nothing -> lexError "unexpected end-of-file in string/character literal"
1332 Just (c,i) -> do setInput i; return c
1334 -- -----------------------------------------------------------------------------
1337 warn :: DynFlag -> SDoc -> Action
1338 warn option warning span _buf _len = do
1339 addWarning option (mkWarnMsg span alwaysQualify warning)
1342 -- -----------------------------------------------------------------------------
1353 SrcSpan -- The start and end of the text span related to
1354 -- the error. Might be used in environments which can
1355 -- show this span, e.g. by highlighting it.
1356 Message -- The error message
1358 data PState = PState {
1359 buffer :: StringBuffer,
1361 messages :: Messages,
1362 last_loc :: SrcSpan, -- pos of previous token
1363 last_offs :: !Int, -- offset of the previous token from the
1364 -- beginning of the current line.
1365 -- \t is equal to 8 spaces.
1366 last_len :: !Int, -- len of previous token
1367 last_line_len :: !Int,
1368 loc :: SrcLoc, -- current loc (end of prev token + 1)
1369 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1370 context :: [LayoutContext],
1373 -- last_loc and last_len are used when generating error messages,
1374 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1375 -- current token to happyError, we could at least get rid of last_len.
1376 -- Getting rid of last_loc would require finding another way to
1377 -- implement pushCurrentContext (which is only called from one place).
1379 newtype P a = P { unP :: PState -> ParseResult a }
1381 instance Monad P where
1387 returnP a = P $ \s -> POk s a
1389 thenP :: P a -> (a -> P b) -> P b
1390 (P m) `thenP` k = P $ \ s ->
1392 POk s1 a -> (unP (k a)) s1
1393 PFailed span err -> PFailed span err
1395 failP :: String -> P a
1396 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1398 failMsgP :: String -> P a
1399 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1401 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1402 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1404 failSpanMsgP :: SrcSpan -> String -> P a
1405 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1407 extension :: (Int -> Bool) -> P Bool
1408 extension p = P $ \s -> POk s (p $! extsBitmap s)
1411 getExts = P $ \s -> POk s (extsBitmap s)
1413 setSrcLoc :: SrcLoc -> P ()
1414 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1416 getSrcLoc :: P SrcLoc
1417 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1419 setLastToken :: SrcSpan -> Int -> Int -> P ()
1420 setLastToken loc len line_len = P $ \s -> POk s {
1423 last_line_len=line_len
1426 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1428 alexInputPrevChar :: AlexInput -> Char
1429 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1431 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1432 alexGetChar (AI loc ofs s)
1434 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1435 --trace (show (ord c)) $
1436 Just (adj_c, (AI loc' ofs' s'))
1437 where (c,s') = nextChar s
1438 loc' = advanceSrcLoc loc c
1439 ofs' = advanceOffs c ofs
1447 other_graphic = '\x6'
1450 | c <= '\x06' = non_graphic
1452 -- Alex doesn't handle Unicode, so when Unicode
1453 -- character is encoutered we output these values
1454 -- with the actual character value hidden in the state.
1456 case generalCategory c of
1457 UppercaseLetter -> upper
1458 LowercaseLetter -> lower
1459 TitlecaseLetter -> upper
1460 ModifierLetter -> other_graphic
1461 OtherLetter -> other_graphic
1462 NonSpacingMark -> other_graphic
1463 SpacingCombiningMark -> other_graphic
1464 EnclosingMark -> other_graphic
1465 DecimalNumber -> digit
1466 LetterNumber -> other_graphic
1467 OtherNumber -> other_graphic
1468 ConnectorPunctuation -> other_graphic
1469 DashPunctuation -> other_graphic
1470 OpenPunctuation -> other_graphic
1471 ClosePunctuation -> other_graphic
1472 InitialQuote -> other_graphic
1473 FinalQuote -> other_graphic
1474 OtherPunctuation -> other_graphic
1475 MathSymbol -> symbol
1476 CurrencySymbol -> symbol
1477 ModifierSymbol -> symbol
1478 OtherSymbol -> symbol
1480 _other -> non_graphic
1482 -- This version does not squash unicode characters, it is used when
1484 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1485 alexGetChar' (AI loc ofs s)
1487 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1488 --trace (show (ord c)) $
1489 Just (c, (AI loc' ofs' s'))
1490 where (c,s') = nextChar s
1491 loc' = advanceSrcLoc loc c
1492 ofs' = advanceOffs c ofs
1494 advanceOffs :: Char -> Int -> Int
1495 advanceOffs '\n' offs = 0
1496 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1497 advanceOffs _ offs = offs + 1
1499 getInput :: P AlexInput
1500 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1502 setInput :: AlexInput -> P ()
1503 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1505 pushLexState :: Int -> P ()
1506 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1508 popLexState :: P Int
1509 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1511 getLexState :: P Int
1512 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1514 -- for reasons of efficiency, flags indicating language extensions (eg,
1515 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1518 glaExtsBit, ffiBit, parrBit :: Int
1525 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1526 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1527 -- (doesn't affect the lexer)
1528 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1529 haddockBit = 10 -- Lex and parse Haddock comments
1530 magicHashBit = 11 -- # in both functions and operators
1531 kindSigsBit = 12 -- Kind signatures on type variables
1532 recursiveDoBit = 13 -- mdo
1533 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1534 unboxedTuplesBit = 15 -- (# and #)
1535 genericsBit = 16 -- {| and |}
1537 glaExtsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1539 glaExtsEnabled flags = testBit flags glaExtsBit
1540 ffiEnabled flags = testBit flags ffiBit
1541 parrEnabled flags = testBit flags parrBit
1542 arrowsEnabled flags = testBit flags arrowsBit
1543 thEnabled flags = testBit flags thBit
1544 ipEnabled flags = testBit flags ipBit
1545 explicitForallEnabled flags = testBit flags explicitForallBit
1546 bangPatEnabled flags = testBit flags bangPatBit
1547 tyFamEnabled flags = testBit flags tyFamBit
1548 haddockEnabled flags = testBit flags haddockBit
1549 magicHashEnabled flags = testBit flags magicHashBit
1550 kindSigsEnabled flags = testBit flags kindSigsBit
1551 recursiveDoEnabled flags = testBit flags recursiveDoBit
1552 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1553 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1554 genericsEnabled flags = testBit flags genericsBit
1556 -- PState for parsing options pragmas
1558 pragState :: StringBuffer -> SrcLoc -> PState
1562 messages = emptyMessages,
1563 -- XXX defaultDynFlags is not right, but we don't have a real
1565 dflags = defaultDynFlags,
1566 last_loc = mkSrcSpan loc loc,
1573 lex_state = [bol, option_prags, 0]
1577 -- create a parse state
1579 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1580 mkPState buf loc flags =
1584 messages = emptyMessages,
1585 last_loc = mkSrcSpan loc loc,
1590 extsBitmap = fromIntegral bitmap,
1592 lex_state = [bol, if glaExtsEnabled bitmap then glaexts else 0]
1593 -- we begin in the layout state if toplev_layout is set
1596 bitmap = glaExtsBit `setBitIf` dopt Opt_GlasgowExts flags
1597 .|. ffiBit `setBitIf` dopt Opt_FFI flags
1598 .|. parrBit `setBitIf` dopt Opt_PArr flags
1599 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1600 .|. thBit `setBitIf` dopt Opt_TH flags
1601 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1602 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1603 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1604 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1605 .|. explicitForallBit `setBitIf` dopt Opt_Rank2Types flags
1606 .|. explicitForallBit `setBitIf` dopt Opt_RankNTypes flags
1607 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1608 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1609 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1610 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1611 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1612 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1613 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1614 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1615 .|. genericsBit `setBitIf` dopt Opt_Generics flags
1617 setBitIf :: Int -> Bool -> Int
1618 b `setBitIf` cond | cond = bit b
1621 addWarning :: DynFlag -> WarnMsg -> P ()
1623 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1624 let ws' = if dopt option d then ws `snocBag` w else ws
1625 in POk s{messages=(ws', es)} ()
1627 getMessages :: PState -> Messages
1628 getMessages PState{messages=ms} = ms
1630 getContext :: P [LayoutContext]
1631 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1633 setContext :: [LayoutContext] -> P ()
1634 setContext ctx = P $ \s -> POk s{context=ctx} ()
1637 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1638 loc = loc, last_len = len, last_loc = last_loc }) ->
1640 (_:tl) -> POk s{ context = tl } ()
1641 [] -> PFailed last_loc (srcParseErr buf len)
1643 -- Push a new layout context at the indentation of the last token read.
1644 -- This is only used at the outer level of a module when the 'module'
1645 -- keyword is missing.
1646 pushCurrentContext :: P ()
1647 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1648 POk s{context = Layout (offs-len) : ctx} ()
1649 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1651 getOffside :: P Ordering
1652 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1653 let ord = case stk of
1654 (Layout n:_) -> compare offs n
1658 -- ---------------------------------------------------------------------------
1659 -- Construct a parse error
1662 :: StringBuffer -- current buffer (placed just after the last token)
1663 -> Int -- length of the previous token
1666 = hcat [ if null token
1667 then ptext SLIT("parse error (possibly incorrect indentation)")
1668 else hcat [ptext SLIT("parse error on input "),
1669 char '`', text token, char '\'']
1671 where token = lexemeToString (offsetBytes (-len) buf) len
1673 -- Report a parse failure, giving the span of the previous token as
1674 -- the location of the error. This is the entry point for errors
1675 -- detected during parsing.
1677 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1678 last_loc = last_loc } ->
1679 PFailed last_loc (srcParseErr buf len)
1681 -- A lexical error is reported at a particular position in the source file,
1682 -- not over a token range.
1683 lexError :: String -> P a
1686 i@(AI end _ buf) <- getInput
1687 reportLexError loc end buf str
1689 -- -----------------------------------------------------------------------------
1690 -- This is the top-level function: called from the parser each time a
1691 -- new token is to be read from the input.
1693 lexer :: (Located Token -> P a) -> P a
1695 tok@(L span tok__) <- lexToken
1696 -- trace ("token: " ++ show tok__) $ do
1699 lexToken :: P (Located Token)
1701 inp@(AI loc1 _ buf) <- getInput
1704 case alexScanUser exts inp sc of
1705 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1706 setLastToken span 0 0
1707 return (L span ITeof)
1708 AlexError (AI loc2 _ buf) -> do
1709 reportLexError loc1 loc2 buf "lexical error"
1710 AlexSkip inp2 _ -> do
1713 AlexToken inp2@(AI end _ buf2) len t -> do
1715 let span = mkSrcSpan loc1 end
1716 let bytes = byteDiff buf buf2
1717 span `seq` setLastToken span bytes bytes
1720 reportLexError loc1 loc2 buf str
1721 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1724 c = fst (nextChar buf)
1726 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1727 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1728 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)