1 -----------------------------------------------------------------------------
2 -- (c) The University of Glasgow, 2006
6 -- This is a combination of an Alex-generated lexer from a regex
7 -- definition, with some hand-coded bits.
9 -- Completely accurate information about token-spans within the source
10 -- file is maintained. Every token has a start and end SrcLoc attached to it.
12 -----------------------------------------------------------------------------
16 -- - parsing integers is a bit slow
17 -- - readRational is a bit slow
19 -- Known bugs, that were also in the previous version:
20 -- - M... should be 3 tokens, not 1.
21 -- - pragma-end should be only valid in a pragma
25 Token(..), lexer, pragState, mkPState, PState(..),
26 P(..), ParseResult(..), getSrcLoc,
27 failLocMsgP, failSpanMsgP, srcParseFail,
29 popContext, pushCurrentContext, setLastToken, setSrcLoc,
30 getLexState, popLexState, pushLexState,
31 extension, standaloneDerivingEnabled, bangPatEnabled,
35 #include "HsVersions.h"
47 import Util ( maybePrefixMatch, readRational )
51 import Data.Char ( chr, isSpace )
55 #if __GLASGOW_HASKELL__ >= 605
56 import Data.Char ( GeneralCategory(..), generalCategory, isPrint, isUpper )
58 import Compat.Unicode ( GeneralCategory(..), generalCategory, isPrint, isUpper )
62 $unispace = \x05 -- Trick Alex into handling Unicode. See alexGetChar.
63 $whitechar = [\ \n\r\f\v\xa0 $unispace]
64 $white_no_nl = $whitechar # \n
68 $unidigit = \x03 -- Trick Alex into handling Unicode. See alexGetChar.
69 $decdigit = $ascdigit -- for now, should really be $digit (ToDo)
70 $digit = [$ascdigit $unidigit]
72 $special = [\(\)\,\;\[\]\`\{\}]
73 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~ \xa1-\xbf \xd7 \xf7]
74 $unisymbol = \x04 -- Trick Alex into handling Unicode. See alexGetChar.
75 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
77 $unilarge = \x01 -- Trick Alex into handling Unicode. See alexGetChar.
78 $asclarge = [A-Z \xc0-\xd6 \xd8-\xde]
79 $large = [$asclarge $unilarge]
81 $unismall = \x02 -- Trick Alex into handling Unicode. See alexGetChar.
82 $ascsmall = [a-z \xdf-\xf6 \xf8-\xff]
83 $small = [$ascsmall $unismall \_]
85 $unigraphic = \x06 -- Trick Alex into handling Unicode. See alexGetChar.
86 $graphic = [$small $large $symbol $digit $special $unigraphic \:\"\']
89 $hexit = [$decdigit A-F a-f]
90 $symchar = [$symbol \:]
92 $idchar = [$small $large $digit \']
94 $docsym = [\| \^ \* \$]
96 @varid = $small $idchar*
97 @conid = $large $idchar*
99 @varsym = $symbol $symchar*
100 @consym = \: $symchar*
102 @decimal = $decdigit+
104 @hexadecimal = $hexit+
105 @exponent = [eE] [\-\+]? @decimal
107 -- we support the hierarchical module name extension:
110 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
112 -- normal signed numerical literals can only be explicitly negative,
113 -- not explicitly positive (contrast @exponent)
115 @signed = @negative ?
119 -- everywhere: skip whitespace and comments
121 $tab+ { warn Opt_WarnTabs (text "Tab character") }
123 -- Everywhere: deal with nested comments. We explicitly rule out
124 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
125 -- (this can happen even though pragmas will normally take precedence due to
126 -- longest-match, because pragmas aren't valid in every state, but comments
127 -- are). We also rule out nested Haddock comments, if the -haddock flag is
130 "{-" / { isNormalComment } { nested_comment lexToken }
132 -- Single-line comments are a bit tricky. Haskell 98 says that two or
133 -- more dashes followed by a symbol should be parsed as a varsym, so we
134 -- have to exclude those.
136 -- Since Haddock comments aren't valid in every state, we need to rule them
139 -- The following two rules match comments that begin with two dashes, but
140 -- continue with a different character. The rules test that this character
141 -- is not a symbol (in which case we'd have a varsym), and that it's not a
142 -- space followed by a Haddock comment symbol (docsym) (in which case we'd
143 -- have a Haddock comment). The rules then munch the rest of the line.
146 "--" [^$symbol : \ ] .* ;
148 -- Next, match Haddock comments if no -haddock flag
150 "-- " $docsym .* / { ifExtension (not . haddockEnabled) } ;
152 -- Now, when we've matched comments that begin with 2 dashes and continue
153 -- with a different character, we need to match comments that begin with three
154 -- or more dashes (which clearly can't be Haddock comments). We only need to
155 -- make sure that the first non-dash character isn't a symbol, and munch the
158 "---"\-* [^$symbol :] .* ;
160 -- Since the previous rules all match dashes followed by at least one
161 -- character, we also need to match a whole line filled with just dashes.
163 "--"\-* / { atEOL } ;
165 -- We need this rule since none of the other single line comment rules
166 -- actually match this case.
170 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
171 -- blank lines) until we find a non-whitespace character, then do layout
174 -- One slight wibble here: what if the line begins with {-#? In
175 -- theory, we have to lex the pragma to see if it's one we recognise,
176 -- and if it is, then we backtrack and do_bol, otherwise we treat it
177 -- as a nested comment. We don't bother with this: if the line begins
178 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
181 ^\# (line)? { begin line_prag1 }
182 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
183 ^\# \! .* \n ; -- #!, for scripts
187 -- after a layout keyword (let, where, do, of), we begin a new layout
188 -- context if the curly brace is missing.
189 -- Careful! This stuff is quite delicate.
190 <layout, layout_do> {
191 \{ / { notFollowedBy '-' } { pop_and open_brace }
192 -- we might encounter {-# here, but {- has been handled already
194 ^\# (line)? { begin line_prag1 }
197 -- do is treated in a subtly different way, see new_layout_context
198 <layout> () { new_layout_context True }
199 <layout_do> () { new_layout_context False }
201 -- after a new layout context which was found to be to the left of the
202 -- previous context, we have generated a '{' token, and we now need to
203 -- generate a matching '}' token.
204 <layout_left> () { do_layout_left }
206 <0,option_prags> \n { begin bol }
208 "{-#" $whitechar* (line|LINE) { begin line_prag2 }
210 -- single-line line pragmas, of the form
211 -- # <line> "<file>" <extra-stuff> \n
212 <line_prag1> $decdigit+ { setLine line_prag1a }
213 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
214 <line_prag1b> .* { pop }
216 -- Haskell-style line pragmas, of the form
217 -- {-# LINE <line> "<file>" #-}
218 <line_prag2> $decdigit+ { setLine line_prag2a }
219 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
220 <line_prag2b> "#-}"|"-}" { pop }
221 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
222 -- with older versions of GHC which generated these.
224 -- We only want RULES pragmas to be picked up when explicit forall
225 -- syntax is enabled is on, because the contents of the pragma always
226 -- uses it. If it's not on then we're sure to get a parse error.
227 -- (ToDo: we should really emit a warning when ignoring pragmas)
228 -- XXX Now that we can enable this without the -fglasgow-exts hammer,
229 -- is it better just to let the parse error happen?
231 "{-#" $whitechar* (RULES|rules) / { ifExtension explicitForallEnabled } { token ITrules_prag }
234 "{-#" $whitechar* (INLINE|inline) { token (ITinline_prag True) }
235 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline)
236 { token (ITinline_prag False) }
237 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
238 { token ITspec_prag }
239 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
240 $whitechar* (INLINE|inline) { token (ITspec_inline_prag True) }
241 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
242 $whitechar* (NO(T?)INLINE|no(t?)inline)
243 { token (ITspec_inline_prag False) }
244 "{-#" $whitechar* (SOURCE|source) { token ITsource_prag }
245 "{-#" $whitechar* (DEPRECATED|deprecated)
246 { token ITdeprecated_prag }
247 "{-#" $whitechar* (SCC|scc) { token ITscc_prag }
248 "{-#" $whitechar* (GENERATED|generated)
249 { token ITgenerated_prag }
250 "{-#" $whitechar* (CORE|core) { token ITcore_prag }
251 "{-#" $whitechar* (UNPACK|unpack) { token ITunpack_prag }
253 "{-#" $whitechar* (DOCOPTIONS|docoptions)
254 / { ifExtension haddockEnabled } { lex_string_prag ITdocOptions }
256 "{-#" { nested_comment lexToken }
258 -- ToDo: should only be valid inside a pragma:
259 "#-}" { token ITclose_prag}
263 "{-#" $whitechar* (OPTIONS|options) { lex_string_prag IToptions_prag }
264 "{-#" $whitechar* (OPTIONS_GHC|options_ghc)
265 { lex_string_prag IToptions_prag }
266 "{-#" $whitechar* (LANGUAGE|language) { token ITlanguage_prag }
267 "{-#" $whitechar* (INCLUDE|include) { lex_string_prag ITinclude_prag }
271 -- This is to catch things like {-# OPTIONS OPTIONS_HUGS ...
272 "{-#" $whitechar* $idchar+ { nested_comment lexToken }
275 -- '0' state: ordinary lexemes
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 }
325 \( { special IToparen }
326 \) { special ITcparen }
327 \[ { special ITobrack }
328 \] { special ITcbrack }
329 \, { special ITcomma }
330 \; { special ITsemi }
331 \` { special ITbackquote }
338 @qual @varid { idtoken qvarid }
339 @qual @conid { idtoken qconid }
341 @conid { idtoken conid }
345 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
346 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
347 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
348 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
354 @qual @varsym { idtoken qvarsym }
355 @qual @consym { idtoken qconsym }
360 -- For the normal boxed literals we need to be careful
361 -- when trying to be close to Haskell98
363 -- Normal integral literals (:: Num a => a, from Integer)
364 @decimal { tok_num positive 0 0 decimal }
365 0[oO] @octal { tok_num positive 2 2 octal }
366 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
368 -- Normal rational literals (:: Fractional a => a, from Rational)
369 @floating_point { strtoken tok_float }
373 -- Unboxed ints (:: Int#)
374 -- It's simpler (and faster?) to give separate cases to the negatives,
375 -- especially considering octal/hexadecimal prefixes.
376 @decimal \# / { ifExtension magicHashEnabled } { tok_primint positive 0 1 decimal }
377 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 octal }
378 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 hexadecimal }
379 @negative @decimal \# / { ifExtension magicHashEnabled } { tok_primint negative 1 2 decimal }
380 @negative 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 octal }
381 @negative 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 hexadecimal }
383 -- Unboxed floats and doubles (:: Float#, :: Double#)
384 -- prim_{float,double} work with signed literals
385 @signed @floating_point \# / { ifExtension magicHashEnabled } { init_strtoken 1 tok_primfloat }
386 @signed @floating_point \# \# / { ifExtension magicHashEnabled } { init_strtoken 2 tok_primdouble }
389 -- Strings and chars are lexed by hand-written code. The reason is
390 -- that even if we recognise the string or char here in the regex
391 -- lexer, we would still have to parse the string afterward in order
392 -- to convert it to a String.
395 \" { lex_string_tok }
399 -- -----------------------------------------------------------------------------
403 = ITas -- Haskell keywords
427 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
429 | ITforall -- GHC extension keywords
444 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
445 | ITspec_prag -- SPECIALISE
446 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
453 | ITcore_prag -- hdaume: core annotations
456 | IToptions_prag String
457 | ITinclude_prag String
460 | ITdotdot -- reserved symbols
476 | ITbiglam -- GHC-extension symbols
478 | ITocurly -- special symbols
480 | ITocurlybar -- {|, for type applications
481 | ITccurlybar -- |}, for type applications
485 | ITopabrack -- [:, for parallel arrays with -fparr
486 | ITcpabrack -- :], for parallel arrays with -fparr
497 | ITvarid FastString -- identifiers
499 | ITvarsym FastString
500 | ITconsym FastString
501 | ITqvarid (FastString,FastString)
502 | ITqconid (FastString,FastString)
503 | ITqvarsym (FastString,FastString)
504 | ITqconsym (FastString,FastString)
506 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
508 | ITpragma StringBuffer
511 | ITstring FastString
513 | ITrational Rational
516 | ITprimstring FastString
518 | ITprimfloat Rational
519 | ITprimdouble Rational
521 -- MetaHaskell extension tokens
522 | ITopenExpQuote -- [| or [e|
523 | ITopenPatQuote -- [p|
524 | ITopenDecQuote -- [d|
525 | ITopenTypQuote -- [t|
527 | ITidEscape FastString -- $x
528 | ITparenEscape -- $(
532 -- Arrow notation extension
539 | ITLarrowtail -- -<<
540 | ITRarrowtail -- >>-
542 | ITunknown String -- Used when the lexer can't make sense of it
543 | ITeof -- end of file token
545 -- Documentation annotations
546 | ITdocCommentNext String -- something beginning '-- |'
547 | ITdocCommentPrev String -- something beginning '-- ^'
548 | ITdocCommentNamed String -- something beginning '-- $'
549 | ITdocSection Int String -- a section heading
550 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
553 deriving Show -- debugging
556 isSpecial :: Token -> Bool
557 -- If we see M.x, where x is a keyword, but
558 -- is special, we treat is as just plain M.x,
560 isSpecial ITas = True
561 isSpecial IThiding = True
562 isSpecial ITqualified = True
563 isSpecial ITforall = True
564 isSpecial ITexport = True
565 isSpecial ITlabel = True
566 isSpecial ITdynamic = True
567 isSpecial ITsafe = True
568 isSpecial ITthreadsafe = True
569 isSpecial ITunsafe = True
570 isSpecial ITccallconv = True
571 isSpecial ITstdcallconv = True
572 isSpecial ITmdo = True
573 isSpecial ITfamily = True
576 -- the bitmap provided as the third component indicates whether the
577 -- corresponding extension keyword is valid under the extension options
578 -- provided to the compiler; if the extension corresponding to *any* of the
579 -- bits set in the bitmap is enabled, the keyword is valid (this setup
580 -- facilitates using a keyword in two different extensions that can be
581 -- activated independently)
583 reservedWordsFM = listToUFM $
584 map (\(x, y, z) -> (mkFastString x, (y, z)))
585 [( "_", ITunderscore, 0 ),
587 ( "case", ITcase, 0 ),
588 ( "class", ITclass, 0 ),
589 ( "data", ITdata, 0 ),
590 ( "default", ITdefault, 0 ),
591 ( "deriving", ITderiving, 0 ),
593 ( "else", ITelse, 0 ),
594 ( "hiding", IThiding, 0 ),
596 ( "import", ITimport, 0 ),
598 ( "infix", ITinfix, 0 ),
599 ( "infixl", ITinfixl, 0 ),
600 ( "infixr", ITinfixr, 0 ),
601 ( "instance", ITinstance, 0 ),
603 ( "module", ITmodule, 0 ),
604 ( "newtype", ITnewtype, 0 ),
606 ( "qualified", ITqualified, 0 ),
607 ( "then", ITthen, 0 ),
608 ( "type", ITtype, 0 ),
609 ( "where", ITwhere, 0 ),
610 ( "_scc_", ITscc, 0 ), -- ToDo: remove
612 ( "forall", ITforall, bit explicitForallBit),
613 ( "mdo", ITmdo, bit recursiveDoBit),
614 ( "family", ITfamily, bit tyFamBit),
616 ( "foreign", ITforeign, bit ffiBit),
617 ( "export", ITexport, bit ffiBit),
618 ( "label", ITlabel, bit ffiBit),
619 ( "dynamic", ITdynamic, bit ffiBit),
620 ( "safe", ITsafe, bit ffiBit),
621 ( "threadsafe", ITthreadsafe, bit ffiBit),
622 ( "unsafe", ITunsafe, bit ffiBit),
623 ( "stdcall", ITstdcallconv, bit ffiBit),
624 ( "ccall", ITccallconv, bit ffiBit),
625 ( "dotnet", ITdotnet, bit ffiBit),
627 ( "rec", ITrec, bit arrowsBit),
628 ( "proc", ITproc, bit arrowsBit)
631 reservedSymsFM :: UniqFM (Token, Int -> Bool)
632 reservedSymsFM = listToUFM $
633 map (\ (x,y,z) -> (mkFastString x,(y,z)))
634 [ ("..", ITdotdot, always)
635 -- (:) is a reserved op, meaning only list cons
636 ,(":", ITcolon, always)
637 ,("::", ITdcolon, always)
638 ,("=", ITequal, always)
639 ,("\\", ITlam, always)
640 ,("|", ITvbar, always)
641 ,("<-", ITlarrow, always)
642 ,("->", ITrarrow, always)
644 ,("~", ITtilde, always)
645 ,("=>", ITdarrow, always)
646 ,("-", ITminus, always)
647 ,("!", ITbang, always)
649 -- For data T (a::*) = MkT
650 ,("*", ITstar, \i -> kindSigsEnabled i || tyFamEnabled i)
651 -- For 'forall a . t'
652 ,(".", ITdot, explicitForallEnabled)
654 ,("-<", ITlarrowtail, arrowsEnabled)
655 ,(">-", ITrarrowtail, arrowsEnabled)
656 ,("-<<", ITLarrowtail, arrowsEnabled)
657 ,(">>-", ITRarrowtail, arrowsEnabled)
659 #if __GLASGOW_HASKELL__ >= 605
660 ,("∷", ITdcolon, unicodeSyntaxEnabled)
661 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
662 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
663 explicitForallEnabled i)
664 ,("→", ITrarrow, unicodeSyntaxEnabled)
665 ,("←", ITlarrow, unicodeSyntaxEnabled)
666 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
667 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
668 -- form part of a large operator. This would let us have a better
669 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
673 -- -----------------------------------------------------------------------------
676 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
678 special :: Token -> Action
679 special tok span _buf len = return (L span tok)
681 token, layout_token :: Token -> Action
682 token t span buf len = return (L span t)
683 layout_token t span buf len = pushLexState layout >> return (L span t)
685 idtoken :: (StringBuffer -> Int -> Token) -> Action
686 idtoken f span buf len = return (L span $! (f buf len))
688 skip_one_varid :: (FastString -> Token) -> Action
689 skip_one_varid f span buf len
690 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
692 strtoken :: (String -> Token) -> Action
693 strtoken f span buf len =
694 return (L span $! (f $! lexemeToString buf len))
696 init_strtoken :: Int -> (String -> Token) -> Action
697 -- like strtoken, but drops the last N character(s)
698 init_strtoken drop f span buf len =
699 return (L span $! (f $! lexemeToString buf (len-drop)))
701 begin :: Int -> Action
702 begin code _span _str _len = do pushLexState code; lexToken
705 pop _span _buf _len = do popLexState; lexToken
707 pop_and :: Action -> Action
708 pop_and act span buf len = do popLexState; act span buf len
710 {-# INLINE nextCharIs #-}
711 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
713 notFollowedBy char _ _ _ (AI _ _ buf)
714 = nextCharIs buf (/=char)
716 notFollowedBySymbol _ _ _ (AI _ _ buf)
717 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
719 -- We must reject doc comments as being ordinary comments everywhere.
720 -- In some cases the doc comment will be selected as the lexeme due to
721 -- maximal munch, but not always, because the nested comment rule is
722 -- valid in all states, but the doc-comment rules are only valid in
723 -- the non-layout states.
724 isNormalComment bits _ _ (AI _ _ buf)
725 | haddockEnabled bits = notFollowedByDocOrPragma
726 | otherwise = nextCharIs buf (/='#')
728 notFollowedByDocOrPragma
729 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
731 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
733 haddockDisabledAnd p bits _ _ (AI _ _ buf)
734 = if haddockEnabled bits then False else (p buf)
736 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
738 ifExtension pred bits _ _ _ = pred bits
740 multiline_doc_comment :: Action
741 multiline_doc_comment span buf _len = withLexedDocType (worker "")
743 worker commentAcc input docType oneLine = case alexGetChar input of
745 | oneLine -> docCommentEnd input commentAcc docType buf span
746 | otherwise -> case checkIfCommentLine input' of
747 Just input -> worker ('\n':commentAcc) input docType False
748 Nothing -> docCommentEnd input commentAcc docType buf span
749 Just (c, input) -> worker (c:commentAcc) input docType oneLine
750 Nothing -> docCommentEnd input commentAcc docType buf span
752 checkIfCommentLine input = check (dropNonNewlineSpace input)
754 check input = case alexGetChar input of
755 Just ('-', input) -> case alexGetChar input of
756 Just ('-', input) -> case alexGetChar input of
757 Just (c, _) | c /= '-' -> Just input
762 dropNonNewlineSpace input = case alexGetChar input of
764 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
769 nested comments require traversing by hand, they can't be parsed
770 using regular expressions.
772 nested_comment :: P (Located Token) -> Action
773 nested_comment cont span _str _len = do
777 go 0 input = do setInput input; cont
778 go n input = case alexGetChar input of
779 Nothing -> errBrace input span
780 Just ('-',input) -> case alexGetChar input of
781 Nothing -> errBrace input span
782 Just ('\125',input) -> go (n-1) input
783 Just (c,_) -> go n input
784 Just ('\123',input) -> case alexGetChar input of
785 Nothing -> errBrace input span
786 Just ('-',input) -> go (n+1) input
787 Just (c,_) -> go n input
788 Just (c,input) -> go n input
790 nested_doc_comment :: Action
791 nested_doc_comment span buf _len = withLexedDocType (go "")
793 go commentAcc input docType _ = case alexGetChar input of
794 Nothing -> errBrace input span
795 Just ('-',input) -> case alexGetChar input of
796 Nothing -> errBrace input span
797 Just ('\125',input@(AI end _ buf2)) ->
798 docCommentEnd input commentAcc docType buf span
799 Just (c,_) -> go ('-':commentAcc) input docType False
800 Just ('\123', input) -> case alexGetChar input of
801 Nothing -> errBrace input span
802 Just ('-',input) -> do
804 let cont = do input <- getInput; go commentAcc input docType False
805 nested_comment cont span buf _len
806 Just (c,_) -> go ('\123':commentAcc) input docType False
807 Just (c,input) -> go (c:commentAcc) input docType False
809 withLexedDocType lexDocComment = do
810 input@(AI _ _ buf) <- getInput
811 case prevChar buf ' ' of
812 '|' -> lexDocComment input ITdocCommentNext False
813 '^' -> lexDocComment input ITdocCommentPrev False
814 '$' -> lexDocComment input ITdocCommentNamed False
815 '*' -> lexDocSection 1 input
817 lexDocSection n input = case alexGetChar input of
818 Just ('*', input) -> lexDocSection (n+1) input
819 Just (c, _) -> lexDocComment input (ITdocSection n) True
820 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
823 -------------------------------------------------------------------------------
824 -- This function is quite tricky. We can't just return a new token, we also
825 -- need to update the state of the parser. Why? Because the token is longer
826 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
827 -- it writes the wrong token length to the parser state. This function is
828 -- called afterwards, so it can just update the state.
830 -- This is complicated by the fact that Haddock tokens can span multiple lines,
831 -- which is something that the original lexer didn't account for.
832 -- I have added last_line_len in the parser state which represents the length
833 -- of the part of the token that is on the last line. It is now used for layout
834 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
835 -- was before, the full length of the token, and it is now only used for error
838 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
839 SrcSpan -> P (Located Token)
840 docCommentEnd input commentAcc docType buf span = do
842 let (AI loc last_offs nextBuf) = input
843 comment = reverse commentAcc
844 span' = mkSrcSpan (srcSpanStart span) loc
845 last_len = byteDiff buf nextBuf
847 last_line_len = if (last_offs - last_len < 0)
851 span `seq` setLastToken span' last_len last_line_len
852 return (L span' (docType comment))
854 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
856 open_brace, close_brace :: Action
857 open_brace span _str _len = do
859 setContext (NoLayout:ctx)
860 return (L span ITocurly)
861 close_brace span _str _len = do
863 return (L span ITccurly)
865 qvarid buf len = ITqvarid $! splitQualName buf len
866 qconid buf len = ITqconid $! splitQualName buf len
868 splitQualName :: StringBuffer -> Int -> (FastString,FastString)
869 -- takes a StringBuffer and a length, and returns the module name
870 -- and identifier parts of a qualified name. Splits at the *last* dot,
871 -- because of hierarchical module names.
872 splitQualName orig_buf len = split orig_buf orig_buf
875 | orig_buf `byteDiff` buf >= len = done dot_buf
876 | c == '.' = found_dot buf'
877 | otherwise = split buf' dot_buf
879 (c,buf') = nextChar buf
881 -- careful, we might get names like M....
882 -- so, if the character after the dot is not upper-case, this is
883 -- the end of the qualifier part.
884 found_dot buf -- buf points after the '.'
885 | isUpper c = split buf' buf
886 | otherwise = done buf
888 (c,buf') = nextChar buf
891 (lexemeToFastString orig_buf (qual_size - 1),
892 lexemeToFastString dot_buf (len - qual_size))
894 qual_size = orig_buf `byteDiff` dot_buf
897 case lookupUFM reservedWordsFM fs of
898 Just (keyword,0) -> do
900 return (L span keyword)
901 Just (keyword,exts) -> do
902 b <- extension (\i -> exts .&. i /= 0)
903 if b then do maybe_layout keyword
904 return (L span keyword)
905 else return (L span (ITvarid fs))
906 _other -> return (L span (ITvarid fs))
908 fs = lexemeToFastString buf len
910 conid buf len = ITconid fs
911 where fs = lexemeToFastString buf len
913 qvarsym buf len = ITqvarsym $! splitQualName buf len
914 qconsym buf len = ITqconsym $! splitQualName buf len
916 varsym = sym ITvarsym
917 consym = sym ITconsym
919 sym con span buf len =
920 case lookupUFM reservedSymsFM fs of
921 Just (keyword,exts) -> do
923 if b then return (L span keyword)
924 else return (L span $! con fs)
925 _other -> return (L span $! con fs)
927 fs = lexemeToFastString buf len
929 -- Variations on the integral numeric literal.
930 tok_integral :: (Integer -> Token)
931 -> (Integer -> Integer)
932 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
934 -> (Integer, (Char->Int)) -> Action
935 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
936 return $ L span $ itint $! transint $ parseUnsignedInteger
937 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
939 -- some conveniences for use with tok_integral
940 tok_num = tok_integral ITinteger
941 tok_primint = tok_integral ITprimint
944 decimal = (10,octDecDigit)
945 octal = (8,octDecDigit)
946 hexadecimal = (16,hexDigit)
948 -- readRational can understand negative rationals, exponents, everything.
949 tok_float str = ITrational $! readRational str
950 tok_primfloat str = ITprimfloat $! readRational str
951 tok_primdouble str = ITprimdouble $! readRational str
953 -- -----------------------------------------------------------------------------
956 -- we're at the first token on a line, insert layout tokens if necessary
958 do_bol span _str _len = do
962 --trace "layout: inserting '}'" $ do
964 -- do NOT pop the lex state, we might have a ';' to insert
965 return (L span ITvccurly)
967 --trace "layout: inserting ';'" $ do
969 return (L span ITsemi)
974 -- certain keywords put us in the "layout" state, where we might
975 -- add an opening curly brace.
976 maybe_layout ITdo = pushLexState layout_do
977 maybe_layout ITmdo = pushLexState layout_do
978 maybe_layout ITof = pushLexState layout
979 maybe_layout ITlet = pushLexState layout
980 maybe_layout ITwhere = pushLexState layout
981 maybe_layout ITrec = pushLexState layout
982 maybe_layout _ = return ()
984 -- Pushing a new implicit layout context. If the indentation of the
985 -- next token is not greater than the previous layout context, then
986 -- Haskell 98 says that the new layout context should be empty; that is
987 -- the lexer must generate {}.
989 -- We are slightly more lenient than this: when the new context is started
990 -- by a 'do', then we allow the new context to be at the same indentation as
991 -- the previous context. This is what the 'strict' argument is for.
993 new_layout_context strict span _buf _len = do
995 (AI _ offset _) <- getInput
998 Layout prev_off : _ |
999 (strict && prev_off >= offset ||
1000 not strict && prev_off > offset) -> do
1001 -- token is indented to the left of the previous context.
1002 -- we must generate a {} sequence now.
1003 pushLexState layout_left
1004 return (L span ITvocurly)
1006 setContext (Layout offset : ctx)
1007 return (L span ITvocurly)
1009 do_layout_left span _buf _len = do
1011 pushLexState bol -- we must be at the start of a line
1012 return (L span ITvccurly)
1014 -- -----------------------------------------------------------------------------
1017 setLine :: Int -> Action
1018 setLine code span buf len = do
1019 let line = parseUnsignedInteger buf len 10 octDecDigit
1020 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1021 -- subtract one: the line number refers to the *following* line
1026 setFile :: Int -> Action
1027 setFile code span buf len = do
1028 let file = lexemeToFastString (stepOn buf) (len-2)
1029 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1035 -- -----------------------------------------------------------------------------
1036 -- Options, includes and language pragmas.
1038 lex_string_prag :: (String -> Token) -> Action
1039 lex_string_prag mkTok span buf len
1040 = do input <- getInput
1044 return (L (mkSrcSpan start end) tok)
1046 = if isString input "#-}"
1047 then do setInput input
1048 return (mkTok (reverse acc))
1049 else case alexGetChar input of
1050 Just (c,i) -> go (c:acc) i
1051 Nothing -> err input
1052 isString i [] = True
1054 = case alexGetChar i of
1055 Just (c,i') | c == x -> isString i' xs
1057 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1060 -- -----------------------------------------------------------------------------
1063 -- This stuff is horrible. I hates it.
1065 lex_string_tok :: Action
1066 lex_string_tok span buf len = do
1067 tok <- lex_string ""
1069 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1071 lex_string :: String -> P Token
1074 case alexGetChar' i of
1075 Nothing -> lit_error
1079 magicHash <- extension magicHashEnabled
1083 case alexGetChar' i of
1087 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1088 else let s' = mkZFastString (reverse s) in
1089 return (ITprimstring s')
1090 -- mkZFastString is a hack to avoid encoding the
1091 -- string in UTF-8. We just want the exact bytes.
1093 return (ITstring (mkFastString (reverse s)))
1095 return (ITstring (mkFastString (reverse s)))
1098 | Just ('&',i) <- next -> do
1099 setInput i; lex_string s
1100 | Just (c,i) <- next, is_space c -> do
1101 setInput i; lex_stringgap s
1102 where next = alexGetChar' i
1108 lex_stringgap s = do
1111 '\\' -> lex_string s
1112 c | is_space c -> lex_stringgap s
1116 lex_char_tok :: Action
1117 -- Here we are basically parsing character literals, such as 'x' or '\n'
1118 -- but, when Template Haskell is on, we additionally spot
1119 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1120 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1121 -- So we have to do two characters of lookahead: when we see 'x we need to
1122 -- see if there's a trailing quote
1123 lex_char_tok span buf len = do -- We've seen '
1124 i1 <- getInput -- Look ahead to first character
1125 let loc = srcSpanStart span
1126 case alexGetChar' i1 of
1127 Nothing -> lit_error
1129 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1130 th_exts <- extension thEnabled
1133 return (L (mkSrcSpan loc end2) ITtyQuote)
1136 Just ('\\', i2@(AI end2 _ _)) -> do -- We've seen 'backslash
1138 lit_ch <- lex_escape
1139 mc <- getCharOrFail -- Trailing quote
1140 if mc == '\'' then finish_char_tok loc lit_ch
1141 else do setInput i2; lit_error
1143 Just (c, i2@(AI end2 _ _))
1144 | not (isAny c) -> lit_error
1147 -- We've seen 'x, where x is a valid character
1148 -- (i.e. not newline etc) but not a quote or backslash
1149 case alexGetChar' i2 of -- Look ahead one more character
1150 Nothing -> lit_error
1151 Just ('\'', i3) -> do -- We've seen 'x'
1153 finish_char_tok loc c
1154 _other -> do -- We've seen 'x not followed by quote
1155 -- If TH is on, just parse the quote only
1156 th_exts <- extension thEnabled
1157 let (AI end _ _) = i1
1158 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1159 else do setInput i2; lit_error
1161 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1162 finish_char_tok loc ch -- We've already seen the closing quote
1163 -- Just need to check for trailing #
1164 = do magicHash <- extension magicHashEnabled
1165 i@(AI end _ _) <- getInput
1166 if magicHash then do
1167 case alexGetChar' i of
1168 Just ('#',i@(AI end _ _)) -> do
1170 return (L (mkSrcSpan loc end) (ITprimchar ch))
1172 return (L (mkSrcSpan loc end) (ITchar ch))
1174 return (L (mkSrcSpan loc end) (ITchar ch))
1176 lex_char :: Char -> AlexInput -> P Char
1179 '\\' -> do setInput inp; lex_escape
1180 c | isAny c -> do setInput inp; return c
1183 isAny c | c > '\xff' = isPrint c
1184 | otherwise = is_any c
1186 lex_escape :: P Char
1200 '^' -> do c <- getCharOrFail
1201 if c >= '@' && c <= '_'
1202 then return (chr (ord c - ord '@'))
1205 'x' -> readNum is_hexdigit 16 hexDigit
1206 'o' -> readNum is_octdigit 8 octDecDigit
1207 x | is_digit x -> readNum2 is_digit 10 octDecDigit (octDecDigit x)
1211 case alexGetChar' i of
1212 Nothing -> lit_error
1214 case alexGetChar' i2 of
1215 Nothing -> do setInput i2; lit_error
1217 let str = [c1,c2,c3] in
1218 case [ (c,rest) | (p,c) <- silly_escape_chars,
1219 Just rest <- [maybePrefixMatch p str] ] of
1220 (escape_char,[]):_ -> do
1223 (escape_char,_:_):_ -> do
1228 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1229 readNum is_digit base conv = do
1233 then readNum2 is_digit base conv (conv c)
1234 else do setInput i; lit_error
1236 readNum2 is_digit base conv i = do
1239 where read i input = do
1240 case alexGetChar' input of
1241 Just (c,input') | is_digit c -> do
1242 read (i*base + conv c) input'
1244 if i >= 0 && i <= 0x10FFFF
1245 then do setInput input; return (chr i)
1248 silly_escape_chars = [
1285 -- before calling lit_error, ensure that the current input is pointing to
1286 -- the position of the error in the buffer. This is so that we can report
1287 -- a correct location to the user, but also so we can detect UTF-8 decoding
1288 -- errors if they occur.
1289 lit_error = lexError "lexical error in string/character literal"
1291 getCharOrFail :: P Char
1294 case alexGetChar' i of
1295 Nothing -> lexError "unexpected end-of-file in string/character literal"
1296 Just (c,i) -> do setInput i; return c
1298 -- -----------------------------------------------------------------------------
1301 warn :: DynFlag -> SDoc -> Action
1302 warn option warning srcspan _buf _len = do
1303 addWarning option srcspan warning
1306 -- -----------------------------------------------------------------------------
1317 SrcSpan -- The start and end of the text span related to
1318 -- the error. Might be used in environments which can
1319 -- show this span, e.g. by highlighting it.
1320 Message -- The error message
1322 data PState = PState {
1323 buffer :: StringBuffer,
1325 messages :: Messages,
1326 last_loc :: SrcSpan, -- pos of previous token
1327 last_offs :: !Int, -- offset of the previous token from the
1328 -- beginning of the current line.
1329 -- \t is equal to 8 spaces.
1330 last_len :: !Int, -- len of previous token
1331 last_line_len :: !Int,
1332 loc :: SrcLoc, -- current loc (end of prev token + 1)
1333 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1334 context :: [LayoutContext],
1337 -- last_loc and last_len are used when generating error messages,
1338 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1339 -- current token to happyError, we could at least get rid of last_len.
1340 -- Getting rid of last_loc would require finding another way to
1341 -- implement pushCurrentContext (which is only called from one place).
1343 newtype P a = P { unP :: PState -> ParseResult a }
1345 instance Monad P where
1351 returnP a = P $ \s -> POk s a
1353 thenP :: P a -> (a -> P b) -> P b
1354 (P m) `thenP` k = P $ \ s ->
1356 POk s1 a -> (unP (k a)) s1
1357 PFailed span err -> PFailed span err
1359 failP :: String -> P a
1360 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1362 failMsgP :: String -> P a
1363 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1365 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1366 failLocMsgP loc1 loc2 str = P $ \s -> PFailed (mkSrcSpan loc1 loc2) (text str)
1368 failSpanMsgP :: SrcSpan -> String -> P a
1369 failSpanMsgP span msg = P $ \s -> PFailed span (text msg)
1371 extension :: (Int -> Bool) -> P Bool
1372 extension p = P $ \s -> POk s (p $! extsBitmap s)
1375 getExts = P $ \s -> POk s (extsBitmap s)
1377 setSrcLoc :: SrcLoc -> P ()
1378 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1380 getSrcLoc :: P SrcLoc
1381 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1383 setLastToken :: SrcSpan -> Int -> Int -> P ()
1384 setLastToken loc len line_len = P $ \s -> POk s {
1387 last_line_len=line_len
1390 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1392 alexInputPrevChar :: AlexInput -> Char
1393 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1395 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1396 alexGetChar (AI loc ofs s)
1398 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1399 --trace (show (ord c)) $
1400 Just (adj_c, (AI loc' ofs' s'))
1401 where (c,s') = nextChar s
1402 loc' = advanceSrcLoc loc c
1403 ofs' = advanceOffs c ofs
1411 other_graphic = '\x6'
1414 | c <= '\x06' = non_graphic
1416 -- Alex doesn't handle Unicode, so when Unicode
1417 -- character is encoutered we output these values
1418 -- with the actual character value hidden in the state.
1420 case generalCategory c of
1421 UppercaseLetter -> upper
1422 LowercaseLetter -> lower
1423 TitlecaseLetter -> upper
1424 ModifierLetter -> other_graphic
1425 OtherLetter -> other_graphic
1426 NonSpacingMark -> other_graphic
1427 SpacingCombiningMark -> other_graphic
1428 EnclosingMark -> other_graphic
1429 DecimalNumber -> digit
1430 LetterNumber -> other_graphic
1431 OtherNumber -> other_graphic
1432 ConnectorPunctuation -> other_graphic
1433 DashPunctuation -> other_graphic
1434 OpenPunctuation -> other_graphic
1435 ClosePunctuation -> other_graphic
1436 InitialQuote -> other_graphic
1437 FinalQuote -> other_graphic
1438 OtherPunctuation -> other_graphic
1439 MathSymbol -> symbol
1440 CurrencySymbol -> symbol
1441 ModifierSymbol -> symbol
1442 OtherSymbol -> symbol
1444 _other -> non_graphic
1446 -- This version does not squash unicode characters, it is used when
1448 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1449 alexGetChar' (AI loc ofs s)
1451 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1452 --trace (show (ord c)) $
1453 Just (c, (AI loc' ofs' s'))
1454 where (c,s') = nextChar s
1455 loc' = advanceSrcLoc loc c
1456 ofs' = advanceOffs c ofs
1458 advanceOffs :: Char -> Int -> Int
1459 advanceOffs '\n' offs = 0
1460 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1461 advanceOffs _ offs = offs + 1
1463 getInput :: P AlexInput
1464 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1466 setInput :: AlexInput -> P ()
1467 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1469 pushLexState :: Int -> P ()
1470 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1472 popLexState :: P Int
1473 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1475 getLexState :: P Int
1476 getLexState = P $ \s@PState{ lex_state=ls:l } -> POk s ls
1478 -- for reasons of efficiency, flags indicating language extensions (eg,
1479 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1482 genericsBit, ffiBit, parrBit :: Int
1483 genericsBit = 0 -- {| and |}
1489 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1490 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1491 -- (doesn't affect the lexer)
1492 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1493 haddockBit = 10 -- Lex and parse Haddock comments
1494 magicHashBit = 11 -- # in both functions and operators
1495 kindSigsBit = 12 -- Kind signatures on type variables
1496 recursiveDoBit = 13 -- mdo
1497 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1498 unboxedTuplesBit = 15 -- (# and #)
1499 standaloneDerivingBit = 16 -- standalone instance deriving declarations
1501 genericsEnabled, ffiEnabled, parrEnabled :: Int -> Bool
1503 genericsEnabled flags = testBit flags genericsBit
1504 ffiEnabled flags = testBit flags ffiBit
1505 parrEnabled flags = testBit flags parrBit
1506 arrowsEnabled flags = testBit flags arrowsBit
1507 thEnabled flags = testBit flags thBit
1508 ipEnabled flags = testBit flags ipBit
1509 explicitForallEnabled flags = testBit flags explicitForallBit
1510 bangPatEnabled flags = testBit flags bangPatBit
1511 tyFamEnabled flags = testBit flags tyFamBit
1512 haddockEnabled flags = testBit flags haddockBit
1513 magicHashEnabled flags = testBit flags magicHashBit
1514 kindSigsEnabled flags = testBit flags kindSigsBit
1515 recursiveDoEnabled flags = testBit flags recursiveDoBit
1516 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1517 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1518 standaloneDerivingEnabled flags = testBit flags standaloneDerivingBit
1520 -- PState for parsing options pragmas
1522 pragState :: StringBuffer -> SrcLoc -> PState
1526 messages = emptyMessages,
1527 -- XXX defaultDynFlags is not right, but we don't have a real
1529 dflags = defaultDynFlags,
1530 last_loc = mkSrcSpan loc loc,
1537 lex_state = [bol, option_prags, 0]
1541 -- create a parse state
1543 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1544 mkPState buf loc flags =
1548 messages = emptyMessages,
1549 last_loc = mkSrcSpan loc loc,
1554 extsBitmap = fromIntegral bitmap,
1556 lex_state = [bol, 0]
1557 -- we begin in the layout state if toplev_layout is set
1560 bitmap = genericsBit `setBitIf` dopt Opt_Generics flags
1561 .|. ffiBit `setBitIf` dopt Opt_ForeignFunctionInterface flags
1562 .|. parrBit `setBitIf` dopt Opt_PArr flags
1563 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1564 .|. thBit `setBitIf` dopt Opt_TemplateHaskell flags
1565 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1566 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1567 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1568 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1569 .|. explicitForallBit `setBitIf` dopt Opt_Rank2Types flags
1570 .|. explicitForallBit `setBitIf` dopt Opt_RankNTypes flags
1571 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1572 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1573 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1574 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1575 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1576 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1577 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1578 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1579 .|. standaloneDerivingBit `setBitIf` dopt Opt_StandaloneDeriving flags
1581 setBitIf :: Int -> Bool -> Int
1582 b `setBitIf` cond | cond = bit b
1585 addWarning :: DynFlag -> SrcSpan -> SDoc -> P ()
1586 addWarning option srcspan warning
1587 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1588 let warning' = mkWarnMsg srcspan alwaysQualify warning
1589 ws' = if dopt option d then ws `snocBag` warning' else ws
1590 in POk s{messages=(ws', es)} ()
1592 getMessages :: PState -> Messages
1593 getMessages PState{messages=ms} = ms
1595 getContext :: P [LayoutContext]
1596 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1598 setContext :: [LayoutContext] -> P ()
1599 setContext ctx = P $ \s -> POk s{context=ctx} ()
1602 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1603 loc = loc, last_len = len, last_loc = last_loc }) ->
1605 (_:tl) -> POk s{ context = tl } ()
1606 [] -> PFailed last_loc (srcParseErr buf len)
1608 -- Push a new layout context at the indentation of the last token read.
1609 -- This is only used at the outer level of a module when the 'module'
1610 -- keyword is missing.
1611 pushCurrentContext :: P ()
1612 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1613 POk s{context = Layout (offs-len) : ctx} ()
1614 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1616 getOffside :: P Ordering
1617 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1618 let ord = case stk of
1619 (Layout n:_) -> compare offs n
1623 -- ---------------------------------------------------------------------------
1624 -- Construct a parse error
1627 :: StringBuffer -- current buffer (placed just after the last token)
1628 -> Int -- length of the previous token
1631 = hcat [ if null token
1632 then ptext SLIT("parse error (possibly incorrect indentation)")
1633 else hcat [ptext SLIT("parse error on input "),
1634 char '`', text token, char '\'']
1636 where token = lexemeToString (offsetBytes (-len) buf) len
1638 -- Report a parse failure, giving the span of the previous token as
1639 -- the location of the error. This is the entry point for errors
1640 -- detected during parsing.
1642 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1643 last_loc = last_loc } ->
1644 PFailed last_loc (srcParseErr buf len)
1646 -- A lexical error is reported at a particular position in the source file,
1647 -- not over a token range.
1648 lexError :: String -> P a
1651 i@(AI end _ buf) <- getInput
1652 reportLexError loc end buf str
1654 -- -----------------------------------------------------------------------------
1655 -- This is the top-level function: called from the parser each time a
1656 -- new token is to be read from the input.
1658 lexer :: (Located Token -> P a) -> P a
1660 tok@(L span tok__) <- lexToken
1661 -- trace ("token: " ++ show tok__) $ do
1664 lexToken :: P (Located Token)
1666 inp@(AI loc1 _ buf) <- getInput
1669 case alexScanUser exts inp sc of
1670 AlexEOF -> do let span = mkSrcSpan loc1 loc1
1671 setLastToken span 0 0
1672 return (L span ITeof)
1673 AlexError (AI loc2 _ buf) -> do
1674 reportLexError loc1 loc2 buf "lexical error"
1675 AlexSkip inp2 _ -> do
1678 AlexToken inp2@(AI end _ buf2) len t -> do
1680 let span = mkSrcSpan loc1 end
1681 let bytes = byteDiff buf buf2
1682 span `seq` setLastToken span bytes bytes
1685 reportLexError loc1 loc2 buf str
1686 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1689 c = fst (nextChar buf)
1691 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1692 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1693 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)