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 -----------------------------------------------------------------------------
15 -- - parsing integers is a bit slow
16 -- - readRational is a bit slow
18 -- Known bugs, that were also in the previous version:
19 -- - M... should be 3 tokens, not 1.
20 -- - pragma-end should be only valid in a pragma
22 -- qualified operator NOTES.
24 -- - If M.(+) is a single lexeme, then..
25 -- - Probably (+) should be a single lexeme too, for consistency.
26 -- Otherwise ( + ) would be a prefix operator, but M.( + ) would not be.
27 -- - But we have to rule out reserved operators, otherwise (..) becomes
28 -- a different lexeme.
29 -- - Should we therefore also rule out reserved operators in the qualified
30 -- form? This is quite difficult to achieve. We don't do it for
34 {-# OPTIONS -Wwarn -w #-}
35 -- The above warning supression flag is a temporary kludge.
36 -- While working on this module you are encouraged to remove it and fix
37 -- any warnings in the module. See
38 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
41 -- Note that Alex itself generates code with with some unused bindings and
42 -- without type signatures, so removing the flag might not be possible.
44 {-# OPTIONS_GHC -funbox-strict-fields #-}
47 Token(..), lexer, pragState, mkPState, PState(..),
48 P(..), ParseResult(..), getSrcLoc,
49 failLocMsgP, failSpanMsgP, srcParseFail,
51 popContext, pushCurrentContext, setLastToken, setSrcLoc,
52 getLexState, popLexState, pushLexState,
53 extension, standaloneDerivingEnabled, bangPatEnabled,
67 import Util ( maybePrefixMatch, readRational )
75 $unispace = \x05 -- Trick Alex into handling Unicode. See alexGetChar.
76 $whitechar = [\ \n\r\f\v $unispace]
77 $white_no_nl = $whitechar # \n
81 $unidigit = \x03 -- Trick Alex into handling Unicode. See alexGetChar.
82 $decdigit = $ascdigit -- for now, should really be $digit (ToDo)
83 $digit = [$ascdigit $unidigit]
85 $special = [\(\)\,\;\[\]\`\{\}]
86 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~]
87 $unisymbol = \x04 -- Trick Alex into handling Unicode. See alexGetChar.
88 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
90 $unilarge = \x01 -- Trick Alex into handling Unicode. See alexGetChar.
92 $large = [$asclarge $unilarge]
94 $unismall = \x02 -- Trick Alex into handling Unicode. See alexGetChar.
96 $small = [$ascsmall $unismall \_]
98 $unigraphic = \x06 -- Trick Alex into handling Unicode. See alexGetChar.
99 $graphic = [$small $large $symbol $digit $special $unigraphic \:\"\']
102 $hexit = [$decdigit A-F a-f]
103 $symchar = [$symbol \:]
105 $idchar = [$small $large $digit \']
107 $docsym = [\| \^ \* \$]
109 @varid = $small $idchar*
110 @conid = $large $idchar*
112 @varsym = $symbol $symchar*
113 @consym = \: $symchar*
115 @decimal = $decdigit+
117 @hexadecimal = $hexit+
118 @exponent = [eE] [\-\+]? @decimal
120 -- we support the hierarchical module name extension:
123 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
125 -- normal signed numerical literals can only be explicitly negative,
126 -- not explicitly positive (contrast @exponent)
128 @signed = @negative ?
132 -- everywhere: skip whitespace and comments
134 $tab+ { warn Opt_WarnTabs (text "Tab character") }
136 -- Everywhere: deal with nested comments. We explicitly rule out
137 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
138 -- (this can happen even though pragmas will normally take precedence due to
139 -- longest-match, because pragmas aren't valid in every state, but comments
140 -- are). We also rule out nested Haddock comments, if the -haddock flag is
143 "{-" / { isNormalComment } { nested_comment lexToken }
145 -- Single-line comments are a bit tricky. Haskell 98 says that two or
146 -- more dashes followed by a symbol should be parsed as a varsym, so we
147 -- have to exclude those.
149 -- Since Haddock comments aren't valid in every state, we need to rule them
152 -- The following two rules match comments that begin with two dashes, but
153 -- continue with a different character. The rules test that this character
154 -- is not a symbol (in which case we'd have a varsym), and that it's not a
155 -- space followed by a Haddock comment symbol (docsym) (in which case we'd
156 -- have a Haddock comment). The rules then munch the rest of the line.
158 "-- " ~[$docsym \#] .* { lineCommentToken }
159 "--" [^$symbol : \ ] .* { lineCommentToken }
161 -- Next, match Haddock comments if no -haddock flag
163 "-- " [$docsym \#] .* / { ifExtension (not . haddockEnabled) } { lineCommentToken }
165 -- Now, when we've matched comments that begin with 2 dashes and continue
166 -- with a different character, we need to match comments that begin with three
167 -- or more dashes (which clearly can't be Haddock comments). We only need to
168 -- make sure that the first non-dash character isn't a symbol, and munch the
171 "---"\-* [^$symbol :] .* { lineCommentToken }
173 -- Since the previous rules all match dashes followed by at least one
174 -- character, we also need to match a whole line filled with just dashes.
176 "--"\-* / { atEOL } { lineCommentToken }
178 -- We need this rule since none of the other single line comment rules
179 -- actually match this case.
181 "-- " / { atEOL } { lineCommentToken }
183 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
184 -- blank lines) until we find a non-whitespace character, then do layout
187 -- One slight wibble here: what if the line begins with {-#? In
188 -- theory, we have to lex the pragma to see if it's one we recognise,
189 -- and if it is, then we backtrack and do_bol, otherwise we treat it
190 -- as a nested comment. We don't bother with this: if the line begins
191 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
194 ^\# (line)? { begin line_prag1 }
195 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
196 ^\# \! .* \n ; -- #!, for scripts
200 -- after a layout keyword (let, where, do, of), we begin a new layout
201 -- context if the curly brace is missing.
202 -- Careful! This stuff is quite delicate.
203 <layout, layout_do> {
204 \{ / { notFollowedBy '-' } { pop_and open_brace }
205 -- we might encounter {-# here, but {- has been handled already
207 ^\# (line)? { begin line_prag1 }
210 -- do is treated in a subtly different way, see new_layout_context
211 <layout> () { new_layout_context True }
212 <layout_do> () { new_layout_context False }
214 -- after a new layout context which was found to be to the left of the
215 -- previous context, we have generated a '{' token, and we now need to
216 -- generate a matching '}' token.
217 <layout_left> () { do_layout_left }
219 <0,option_prags> \n { begin bol }
221 "{-#" $whitechar* (line|LINE) / { notFollowedByPragmaChar }
224 -- single-line line pragmas, of the form
225 -- # <line> "<file>" <extra-stuff> \n
226 <line_prag1> $decdigit+ { setLine line_prag1a }
227 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
228 <line_prag1b> .* { pop }
230 -- Haskell-style line pragmas, of the form
231 -- {-# LINE <line> "<file>" #-}
232 <line_prag2> $decdigit+ { setLine line_prag2a }
233 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
234 <line_prag2b> "#-}"|"-}" { pop }
235 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
236 -- with older versions of GHC which generated these.
239 "{-#" $whitechar* (RULES|rules) / { notFollowedByPragmaChar } { rulePrag }
240 "{-#" $whitechar* (INLINE|inline) / { notFollowedByPragmaChar }
241 { token (ITinline_prag True) }
242 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline) / { notFollowedByPragmaChar }
243 { token (ITinline_prag False) }
244 "{-#" $whitechar* (INLINE|inline)
245 $whitechar+ (CONLIKE|conlike) / { notFollowedByPragmaChar }
246 { token (ITinline_conlike_prag True) }
247 "{-#" $whitechar* (NO(T)?INLINE|no(t?)inline)
248 $whitechar+ (CONLIKE|constructorlike) / { notFollowedByPragmaChar }
249 { token (ITinline_conlike_prag False) }
250 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e) / { notFollowedByPragmaChar }
251 { token ITspec_prag }
252 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
253 $whitechar+ (INLINE|inline) / { notFollowedByPragmaChar }
254 { token (ITspec_inline_prag True) }
255 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
256 $whitechar+ (NO(T?)INLINE|no(t?)inline) / { notFollowedByPragmaChar }
257 { token (ITspec_inline_prag False) }
258 "{-#" $whitechar* (SOURCE|source) / { notFollowedByPragmaChar }
259 { token ITsource_prag }
260 "{-#" $whitechar* (WARNING|warning) / { notFollowedByPragmaChar }
261 { token ITwarning_prag }
262 "{-#" $whitechar* (DEPRECATED|deprecated) / { notFollowedByPragmaChar }
263 { token ITdeprecated_prag }
264 "{-#" $whitechar* (SCC|scc) / { notFollowedByPragmaChar }
266 "{-#" $whitechar* (GENERATED|generated) / { notFollowedByPragmaChar }
267 { token ITgenerated_prag }
268 "{-#" $whitechar* (CORE|core) / { notFollowedByPragmaChar }
269 { token ITcore_prag }
270 "{-#" $whitechar* (UNPACK|unpack) / { notFollowedByPragmaChar }
271 { token ITunpack_prag }
272 "{-#" $whitechar* (ANN|ann) / { notFollowedByPragmaChar }
275 -- We ignore all these pragmas, but don't generate a warning for them
276 -- CFILES is a hugs-only thing.
277 "{-#" $whitechar* (OPTIONS_(HUGS|hugs|NHC98|nhc98|JHC|jhc|YHC|yhc|CATCH|catch|DERIVE|derive)|CFILES|cfiles|CONTRACT|contract) / { notFollowedByPragmaChar }
278 { nested_comment lexToken }
280 -- ToDo: should only be valid inside a pragma:
285 "{-#" $whitechar* (OPTIONS|options) / { notFollowedByPragmaChar }
286 { lex_string_prag IToptions_prag }
287 "{-#" $whitechar* (OPTIONS_GHC|options_ghc) / { notFollowedByPragmaChar }
288 { lex_string_prag IToptions_prag }
289 "{-#" $whitechar* (OPTIONS_HADDOCK|options_haddock)
290 / { notFollowedByPragmaChar }
291 { lex_string_prag ITdocOptions }
292 "-- #" { multiline_doc_comment }
293 "{-#" $whitechar* (LANGUAGE|language) / { notFollowedByPragmaChar }
294 { token ITlanguage_prag }
295 "{-#" $whitechar* (INCLUDE|include) / { notFollowedByPragmaChar }
296 { lex_string_prag ITinclude_prag }
300 -- In the "0" mode we ignore these pragmas
301 "{-#" $whitechar* (OPTIONS|options|OPTIONS_GHC|options_ghc|OPTIONS_HADDOCK|options_haddock|LANGUAGE|language|INCLUDE|include) / { notFollowedByPragmaChar }
302 { nested_comment lexToken }
306 "-- #" .* { lineCommentToken }
310 "{-#" { warnThen Opt_WarnUnrecognisedPragmas (text "Unrecognised pragma")
311 (nested_comment lexToken) }
314 -- '0' state: ordinary lexemes
319 "-- " $docsym / { ifExtension haddockEnabled } { multiline_doc_comment }
320 "{-" \ ? $docsym / { ifExtension haddockEnabled } { nested_doc_comment }
326 "[:" / { ifExtension parrEnabled } { token ITopabrack }
327 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
331 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
332 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
333 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
334 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
335 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
336 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
337 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
338 "$(" / { ifExtension thEnabled } { token ITparenEscape }
340 "[$" @varid "|" / { ifExtension qqEnabled }
341 { lex_quasiquote_tok }
345 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
346 { special IToparenbar }
347 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
351 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
355 "(#" / { ifExtension unboxedTuplesEnabled `alexAndPred` notFollowedBySymbol }
356 { token IToubxparen }
357 "#)" / { ifExtension unboxedTuplesEnabled }
358 { token ITcubxparen }
362 "{|" / { ifExtension genericsEnabled } { token ITocurlybar }
363 "|}" / { ifExtension genericsEnabled } { token ITccurlybar }
367 \( { special IToparen }
368 \) { special ITcparen }
369 \[ { special ITobrack }
370 \] { special ITcbrack }
371 \, { special ITcomma }
372 \; { special ITsemi }
373 \` { special ITbackquote }
380 @qual @varid { idtoken qvarid }
381 @qual @conid { idtoken qconid }
383 @conid { idtoken conid }
387 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
388 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
389 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
390 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
393 -- ToDo: - move `var` and (sym) into lexical syntax?
394 -- - remove backquote from $special?
396 @qual @varsym / { ifExtension oldQualOps } { idtoken qvarsym }
397 @qual @consym / { ifExtension oldQualOps } { idtoken qconsym }
398 @qual \( @varsym \) / { ifExtension newQualOps } { idtoken prefixqvarsym }
399 @qual \( @consym \) / { ifExtension newQualOps } { idtoken prefixqconsym }
404 -- For the normal boxed literals we need to be careful
405 -- when trying to be close to Haskell98
407 -- Normal integral literals (:: Num a => a, from Integer)
408 @decimal { tok_num positive 0 0 decimal }
409 0[oO] @octal { tok_num positive 2 2 octal }
410 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
412 -- Normal rational literals (:: Fractional a => a, from Rational)
413 @floating_point { strtoken tok_float }
417 -- Unboxed ints (:: Int#) and words (:: Word#)
418 -- It's simpler (and faster?) to give separate cases to the negatives,
419 -- especially considering octal/hexadecimal prefixes.
420 @decimal \# / { ifExtension magicHashEnabled } { tok_primint positive 0 1 decimal }
421 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 octal }
422 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 hexadecimal }
423 @negative @decimal \# / { ifExtension magicHashEnabled } { tok_primint negative 1 2 decimal }
424 @negative 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 octal }
425 @negative 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 hexadecimal }
427 @decimal \# \# / { ifExtension magicHashEnabled } { tok_primword 0 2 decimal }
428 0[oO] @octal \# \# / { ifExtension magicHashEnabled } { tok_primword 2 4 octal }
429 0[xX] @hexadecimal \# \# / { ifExtension magicHashEnabled } { tok_primword 2 4 hexadecimal }
431 -- Unboxed floats and doubles (:: Float#, :: Double#)
432 -- prim_{float,double} work with signed literals
433 @signed @floating_point \# / { ifExtension magicHashEnabled } { init_strtoken 1 tok_primfloat }
434 @signed @floating_point \# \# / { ifExtension magicHashEnabled } { init_strtoken 2 tok_primdouble }
437 -- Strings and chars are lexed by hand-written code. The reason is
438 -- that even if we recognise the string or char here in the regex
439 -- lexer, we would still have to parse the string afterward in order
440 -- to convert it to a String.
443 \" { lex_string_tok }
447 -- -----------------------------------------------------------------------------
451 = ITas -- Haskell keywords
475 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
477 | ITforall -- GHC extension keywords
495 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
496 | ITinline_conlike_prag Bool -- same
497 | ITspec_prag -- SPECIALISE
498 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
506 | ITcore_prag -- hdaume: core annotations
510 | IToptions_prag String
511 | ITinclude_prag String
514 | ITdotdot -- reserved symbols
530 | ITbiglam -- GHC-extension symbols
532 | ITocurly -- special symbols
534 | ITocurlybar -- {|, for type applications
535 | ITccurlybar -- |}, for type applications
539 | ITopabrack -- [:, for parallel arrays with -XParr
540 | ITcpabrack -- :], for parallel arrays with -XParr
551 | ITvarid FastString -- identifiers
553 | ITvarsym FastString
554 | ITconsym FastString
555 | ITqvarid (FastString,FastString)
556 | ITqconid (FastString,FastString)
557 | ITqvarsym (FastString,FastString)
558 | ITqconsym (FastString,FastString)
559 | ITprefixqvarsym (FastString,FastString)
560 | ITprefixqconsym (FastString,FastString)
562 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
564 | ITpragma StringBuffer
567 | ITstring FastString
569 | ITrational Rational
572 | ITprimstring FastString
575 | ITprimfloat Rational
576 | ITprimdouble Rational
578 -- MetaHaskell extension tokens
579 | ITopenExpQuote -- [| or [e|
580 | ITopenPatQuote -- [p|
581 | ITopenDecQuote -- [d|
582 | ITopenTypQuote -- [t|
584 | ITidEscape FastString -- $x
585 | ITparenEscape -- $(
588 | ITquasiQuote (FastString,FastString,SrcSpan) -- [:...|...|]
590 -- Arrow notation extension
597 | ITLarrowtail -- -<<
598 | ITRarrowtail -- >>-
600 | ITunknown String -- Used when the lexer can't make sense of it
601 | ITeof -- end of file token
603 -- Documentation annotations
604 | ITdocCommentNext String -- something beginning '-- |'
605 | ITdocCommentPrev String -- something beginning '-- ^'
606 | ITdocCommentNamed String -- something beginning '-- $'
607 | ITdocSection Int String -- a section heading
608 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
609 | ITdocOptionsOld String -- doc options declared "-- # ..."-style
610 | ITlineComment String -- comment starting by "--"
611 | ITblockComment String -- comment in {- -}
614 deriving Show -- debugging
618 isSpecial :: Token -> Bool
619 -- If we see M.x, where x is a keyword, but
620 -- is special, we treat is as just plain M.x,
622 isSpecial ITas = True
623 isSpecial IThiding = True
624 isSpecial ITqualified = True
625 isSpecial ITforall = True
626 isSpecial ITexport = True
627 isSpecial ITlabel = True
628 isSpecial ITdynamic = True
629 isSpecial ITsafe = True
630 isSpecial ITthreadsafe = True
631 isSpecial ITunsafe = True
632 isSpecial ITccallconv = True
633 isSpecial ITstdcallconv = True
634 isSpecial ITmdo = True
635 isSpecial ITfamily = True
636 isSpecial ITgroup = True
637 isSpecial ITby = True
638 isSpecial ITusing = True
642 -- the bitmap provided as the third component indicates whether the
643 -- corresponding extension keyword is valid under the extension options
644 -- provided to the compiler; if the extension corresponding to *any* of the
645 -- bits set in the bitmap is enabled, the keyword is valid (this setup
646 -- facilitates using a keyword in two different extensions that can be
647 -- activated independently)
649 reservedWordsFM :: UniqFM (Token, Int)
650 reservedWordsFM = listToUFM $
651 map (\(x, y, z) -> (mkFastString x, (y, z)))
652 [( "_", ITunderscore, 0 ),
654 ( "case", ITcase, 0 ),
655 ( "class", ITclass, 0 ),
656 ( "data", ITdata, 0 ),
657 ( "default", ITdefault, 0 ),
658 ( "deriving", ITderiving, 0 ),
660 ( "else", ITelse, 0 ),
661 ( "hiding", IThiding, 0 ),
663 ( "import", ITimport, 0 ),
665 ( "infix", ITinfix, 0 ),
666 ( "infixl", ITinfixl, 0 ),
667 ( "infixr", ITinfixr, 0 ),
668 ( "instance", ITinstance, 0 ),
670 ( "module", ITmodule, 0 ),
671 ( "newtype", ITnewtype, 0 ),
673 ( "qualified", ITqualified, 0 ),
674 ( "then", ITthen, 0 ),
675 ( "type", ITtype, 0 ),
676 ( "where", ITwhere, 0 ),
677 ( "_scc_", ITscc, 0 ), -- ToDo: remove
679 ( "forall", ITforall, bit explicitForallBit .|. bit inRulePragBit),
680 ( "mdo", ITmdo, bit recursiveDoBit),
681 ( "family", ITfamily, bit tyFamBit),
682 ( "group", ITgroup, bit transformComprehensionsBit),
683 ( "by", ITby, bit transformComprehensionsBit),
684 ( "using", ITusing, bit transformComprehensionsBit),
686 ( "foreign", ITforeign, bit ffiBit),
687 ( "export", ITexport, bit ffiBit),
688 ( "label", ITlabel, bit ffiBit),
689 ( "dynamic", ITdynamic, bit ffiBit),
690 ( "safe", ITsafe, bit ffiBit),
691 ( "threadsafe", ITthreadsafe, bit ffiBit),
692 ( "unsafe", ITunsafe, bit ffiBit),
693 ( "stdcall", ITstdcallconv, bit ffiBit),
694 ( "ccall", ITccallconv, bit ffiBit),
695 ( "dotnet", ITdotnet, bit ffiBit),
697 ( "rec", ITrec, bit arrowsBit),
698 ( "proc", ITproc, bit arrowsBit)
701 reservedSymsFM :: UniqFM (Token, Int -> Bool)
702 reservedSymsFM = listToUFM $
703 map (\ (x,y,z) -> (mkFastString x,(y,z)))
704 [ ("..", ITdotdot, always)
705 -- (:) is a reserved op, meaning only list cons
706 ,(":", ITcolon, always)
707 ,("::", ITdcolon, always)
708 ,("=", ITequal, always)
709 ,("\\", ITlam, always)
710 ,("|", ITvbar, always)
711 ,("<-", ITlarrow, always)
712 ,("->", ITrarrow, always)
714 ,("~", ITtilde, always)
715 ,("=>", ITdarrow, always)
716 ,("-", ITminus, always)
717 ,("!", ITbang, always)
719 -- For data T (a::*) = MkT
720 ,("*", ITstar, always) -- \i -> kindSigsEnabled i || tyFamEnabled i)
721 -- For 'forall a . t'
722 ,(".", ITdot, always) -- \i -> explicitForallEnabled i || inRulePrag i)
724 ,("-<", ITlarrowtail, arrowsEnabled)
725 ,(">-", ITrarrowtail, arrowsEnabled)
726 ,("-<<", ITLarrowtail, arrowsEnabled)
727 ,(">>-", ITRarrowtail, arrowsEnabled)
729 ,("∷", ITdcolon, unicodeSyntaxEnabled)
730 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
731 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
732 explicitForallEnabled i)
733 ,("→", ITrarrow, unicodeSyntaxEnabled)
734 ,("←", ITlarrow, unicodeSyntaxEnabled)
735 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
736 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
737 -- form part of a large operator. This would let us have a better
738 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
741 -- -----------------------------------------------------------------------------
744 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
746 special :: Token -> Action
747 special tok span _buf _len = return (L span tok)
749 token, layout_token :: Token -> Action
750 token t span _buf _len = return (L span t)
751 layout_token t span _buf _len = pushLexState layout >> return (L span t)
753 idtoken :: (StringBuffer -> Int -> Token) -> Action
754 idtoken f span buf len = return (L span $! (f buf len))
756 skip_one_varid :: (FastString -> Token) -> Action
757 skip_one_varid f span buf len
758 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
760 strtoken :: (String -> Token) -> Action
761 strtoken f span buf len =
762 return (L span $! (f $! lexemeToString buf len))
764 init_strtoken :: Int -> (String -> Token) -> Action
765 -- like strtoken, but drops the last N character(s)
766 init_strtoken drop f span buf len =
767 return (L span $! (f $! lexemeToString buf (len-drop)))
769 begin :: Int -> Action
770 begin code _span _str _len = do pushLexState code; lexToken
773 pop _span _buf _len = do popLexState; lexToken
775 pop_and :: Action -> Action
776 pop_and act span buf len = do popLexState; act span buf len
778 {-# INLINE nextCharIs #-}
779 nextCharIs :: StringBuffer -> (Char -> Bool) -> Bool
780 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
782 notFollowedBy :: Char -> AlexAccPred Int
783 notFollowedBy char _ _ _ (AI _ _ buf)
784 = nextCharIs buf (/=char)
786 notFollowedBySymbol :: AlexAccPred Int
787 notFollowedBySymbol _ _ _ (AI _ _ buf)
788 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
790 notFollowedByPragmaChar :: AlexAccPred Int
791 notFollowedByPragmaChar _ _ _ (AI _ _ buf)
792 = nextCharIs buf (\c -> not (isAlphaNum c || c == '_'))
794 -- We must reject doc comments as being ordinary comments everywhere.
795 -- In some cases the doc comment will be selected as the lexeme due to
796 -- maximal munch, but not always, because the nested comment rule is
797 -- valid in all states, but the doc-comment rules are only valid in
798 -- the non-layout states.
799 isNormalComment :: AlexAccPred Int
800 isNormalComment bits _ _ (AI _ _ buf)
801 | haddockEnabled bits = notFollowedByDocOrPragma
802 | otherwise = nextCharIs buf (/='#')
804 notFollowedByDocOrPragma
805 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
807 spaceAndP :: StringBuffer -> (StringBuffer -> Bool) -> Bool
808 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
811 haddockDisabledAnd p bits _ _ (AI _ _ buf)
812 = if haddockEnabled bits then False else (p buf)
815 atEOL :: AlexAccPred Int
816 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
818 ifExtension :: (Int -> Bool) -> AlexAccPred Int
819 ifExtension pred bits _ _ _ = pred bits
821 multiline_doc_comment :: Action
822 multiline_doc_comment span buf _len = withLexedDocType (worker "")
824 worker commentAcc input docType oneLine = case alexGetChar input of
826 | oneLine -> docCommentEnd input commentAcc docType buf span
827 | otherwise -> case checkIfCommentLine input' of
828 Just input -> worker ('\n':commentAcc) input docType False
829 Nothing -> docCommentEnd input commentAcc docType buf span
830 Just (c, input) -> worker (c:commentAcc) input docType oneLine
831 Nothing -> docCommentEnd input commentAcc docType buf span
833 checkIfCommentLine input = check (dropNonNewlineSpace input)
835 check input = case alexGetChar input of
836 Just ('-', input) -> case alexGetChar input of
837 Just ('-', input) -> case alexGetChar input of
838 Just (c, _) | c /= '-' -> Just input
843 dropNonNewlineSpace input = case alexGetChar input of
845 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
849 lineCommentToken :: Action
850 lineCommentToken span buf len = do
851 b <- extension rawTokenStreamEnabled
852 if b then strtoken ITlineComment span buf len else lexToken
855 nested comments require traversing by hand, they can't be parsed
856 using regular expressions.
858 nested_comment :: P (Located Token) -> Action
859 nested_comment cont span _str _len = do
863 go commentAcc 0 input = do setInput input
864 b <- extension rawTokenStreamEnabled
866 then docCommentEnd input commentAcc ITblockComment _str span
868 go commentAcc n input = case alexGetChar input of
869 Nothing -> errBrace input span
870 Just ('-',input) -> case alexGetChar input of
871 Nothing -> errBrace input span
872 Just ('\125',input) -> go commentAcc (n-1) input
873 Just (_,_) -> go ('-':commentAcc) n input
874 Just ('\123',input) -> case alexGetChar input of
875 Nothing -> errBrace input span
876 Just ('-',input) -> go ('-':'\123':commentAcc) (n+1) input
877 Just (_,_) -> go ('\123':commentAcc) n input
878 Just (c,input) -> go (c:commentAcc) n input
880 nested_doc_comment :: Action
881 nested_doc_comment span buf _len = withLexedDocType (go "")
883 go commentAcc input docType _ = case alexGetChar input of
884 Nothing -> errBrace input span
885 Just ('-',input) -> case alexGetChar input of
886 Nothing -> errBrace input span
887 Just ('\125',input) ->
888 docCommentEnd input commentAcc docType buf span
889 Just (_,_) -> go ('-':commentAcc) input docType False
890 Just ('\123', input) -> case alexGetChar input of
891 Nothing -> errBrace input span
892 Just ('-',input) -> do
894 let cont = do input <- getInput; go commentAcc input docType False
895 nested_comment cont span buf _len
896 Just (_,_) -> go ('\123':commentAcc) input docType False
897 Just (c,input) -> go (c:commentAcc) input docType False
899 withLexedDocType :: (AlexInput -> (String -> Token) -> Bool -> P (Located Token))
901 withLexedDocType lexDocComment = do
902 input@(AI _ _ buf) <- getInput
903 case prevChar buf ' ' of
904 '|' -> lexDocComment input ITdocCommentNext False
905 '^' -> lexDocComment input ITdocCommentPrev False
906 '$' -> lexDocComment input ITdocCommentNamed False
907 '*' -> lexDocSection 1 input
908 '#' -> lexDocComment input ITdocOptionsOld False
909 _ -> panic "withLexedDocType: Bad doc type"
911 lexDocSection n input = case alexGetChar input of
912 Just ('*', input) -> lexDocSection (n+1) input
913 Just (_, _) -> lexDocComment input (ITdocSection n) True
914 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
916 -- RULES pragmas turn on the forall and '.' keywords, and we turn them
917 -- off again at the end of the pragma.
919 rulePrag span _ _ = do
920 setExts (.|. bit inRulePragBit)
921 return (L span ITrules_prag)
924 endPrag span _ _ = do
925 setExts (.&. complement (bit inRulePragBit))
926 return (L span ITclose_prag)
929 -------------------------------------------------------------------------------
930 -- This function is quite tricky. We can't just return a new token, we also
931 -- need to update the state of the parser. Why? Because the token is longer
932 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
933 -- it writes the wrong token length to the parser state. This function is
934 -- called afterwards, so it can just update the state.
936 -- This is complicated by the fact that Haddock tokens can span multiple lines,
937 -- which is something that the original lexer didn't account for.
938 -- I have added last_line_len in the parser state which represents the length
939 -- of the part of the token that is on the last line. It is now used for layout
940 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
941 -- was before, the full length of the token, and it is now only used for error
944 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
945 SrcSpan -> P (Located Token)
946 docCommentEnd input commentAcc docType buf span = do
948 let (AI loc last_offs nextBuf) = input
949 comment = reverse commentAcc
950 span' = mkSrcSpan (srcSpanStart span) loc
951 last_len = byteDiff buf nextBuf
953 last_line_len = if (last_offs - last_len < 0)
957 span `seq` setLastToken span' last_len last_line_len
958 return (L span' (docType comment))
960 errBrace :: AlexInput -> SrcSpan -> P a
961 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
963 open_brace, close_brace :: Action
964 open_brace span _str _len = do
966 setContext (NoLayout:ctx)
967 return (L span ITocurly)
968 close_brace span _str _len = do
970 return (L span ITccurly)
972 qvarid, qconid :: StringBuffer -> Int -> Token
973 qvarid buf len = ITqvarid $! splitQualName buf len False
974 qconid buf len = ITqconid $! splitQualName buf len False
976 splitQualName :: StringBuffer -> Int -> Bool -> (FastString,FastString)
977 -- takes a StringBuffer and a length, and returns the module name
978 -- and identifier parts of a qualified name. Splits at the *last* dot,
979 -- because of hierarchical module names.
980 splitQualName orig_buf len parens = split orig_buf orig_buf
983 | orig_buf `byteDiff` buf >= len = done dot_buf
984 | c == '.' = found_dot buf'
985 | otherwise = split buf' dot_buf
987 (c,buf') = nextChar buf
989 -- careful, we might get names like M....
990 -- so, if the character after the dot is not upper-case, this is
991 -- the end of the qualifier part.
992 found_dot buf -- buf points after the '.'
993 | isUpper c = split buf' buf
994 | otherwise = done buf
996 (c,buf') = nextChar buf
999 (lexemeToFastString orig_buf (qual_size - 1),
1000 if parens -- Prelude.(+)
1001 then lexemeToFastString (stepOn dot_buf) (len - qual_size - 2)
1002 else lexemeToFastString dot_buf (len - qual_size))
1004 qual_size = orig_buf `byteDiff` dot_buf
1007 varid span buf len =
1009 case lookupUFM reservedWordsFM fs of
1010 Just (keyword,0) -> do
1011 maybe_layout keyword
1012 return (L span keyword)
1013 Just (keyword,exts) -> do
1014 b <- extension (\i -> exts .&. i /= 0)
1015 if b then do maybe_layout keyword
1016 return (L span keyword)
1017 else return (L span (ITvarid fs))
1018 _other -> return (L span (ITvarid fs))
1020 fs = lexemeToFastString buf len
1022 conid :: StringBuffer -> Int -> Token
1023 conid buf len = ITconid fs
1024 where fs = lexemeToFastString buf len
1026 qvarsym, qconsym, prefixqvarsym, prefixqconsym :: StringBuffer -> Int -> Token
1027 qvarsym buf len = ITqvarsym $! splitQualName buf len False
1028 qconsym buf len = ITqconsym $! splitQualName buf len False
1029 prefixqvarsym buf len = ITprefixqvarsym $! splitQualName buf len True
1030 prefixqconsym buf len = ITprefixqconsym $! splitQualName buf len True
1032 varsym, consym :: Action
1033 varsym = sym ITvarsym
1034 consym = sym ITconsym
1036 sym :: (FastString -> Token) -> SrcSpan -> StringBuffer -> Int
1037 -> P (Located Token)
1038 sym con span buf len =
1039 case lookupUFM reservedSymsFM fs of
1040 Just (keyword,exts) -> do
1042 if b then return (L span keyword)
1043 else return (L span $! con fs)
1044 _other -> return (L span $! con fs)
1046 fs = lexemeToFastString buf len
1048 -- Variations on the integral numeric literal.
1049 tok_integral :: (Integer -> Token)
1050 -> (Integer -> Integer)
1051 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
1053 -> (Integer, (Char->Int)) -> Action
1054 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
1055 return $ L span $ itint $! transint $ parseUnsignedInteger
1056 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
1058 -- some conveniences for use with tok_integral
1059 tok_num :: (Integer -> Integer)
1061 -> (Integer, (Char->Int)) -> Action
1062 tok_num = tok_integral ITinteger
1063 tok_primint :: (Integer -> Integer)
1065 -> (Integer, (Char->Int)) -> Action
1066 tok_primint = tok_integral ITprimint
1067 tok_primword :: Int -> Int
1068 -> (Integer, (Char->Int)) -> Action
1069 tok_primword = tok_integral ITprimword positive
1070 positive, negative :: (Integer -> Integer)
1073 decimal, octal, hexadecimal :: (Integer, Char -> Int)
1074 decimal = (10,octDecDigit)
1075 octal = (8,octDecDigit)
1076 hexadecimal = (16,hexDigit)
1078 -- readRational can understand negative rationals, exponents, everything.
1079 tok_float, tok_primfloat, tok_primdouble :: String -> Token
1080 tok_float str = ITrational $! readRational str
1081 tok_primfloat str = ITprimfloat $! readRational str
1082 tok_primdouble str = ITprimdouble $! readRational str
1084 -- -----------------------------------------------------------------------------
1085 -- Layout processing
1087 -- we're at the first token on a line, insert layout tokens if necessary
1089 do_bol span _str _len = do
1093 --trace "layout: inserting '}'" $ do
1095 -- do NOT pop the lex state, we might have a ';' to insert
1096 return (L span ITvccurly)
1098 --trace "layout: inserting ';'" $ do
1100 return (L span ITsemi)
1105 -- certain keywords put us in the "layout" state, where we might
1106 -- add an opening curly brace.
1107 maybe_layout :: Token -> P ()
1108 maybe_layout ITdo = pushLexState layout_do
1109 maybe_layout ITmdo = pushLexState layout_do
1110 maybe_layout ITof = pushLexState layout
1111 maybe_layout ITlet = pushLexState layout
1112 maybe_layout ITwhere = pushLexState layout
1113 maybe_layout ITrec = pushLexState layout
1114 maybe_layout _ = return ()
1116 -- Pushing a new implicit layout context. If the indentation of the
1117 -- next token is not greater than the previous layout context, then
1118 -- Haskell 98 says that the new layout context should be empty; that is
1119 -- the lexer must generate {}.
1121 -- We are slightly more lenient than this: when the new context is started
1122 -- by a 'do', then we allow the new context to be at the same indentation as
1123 -- the previous context. This is what the 'strict' argument is for.
1125 new_layout_context :: Bool -> Action
1126 new_layout_context strict span _buf _len = do
1128 (AI _ offset _) <- getInput
1131 Layout prev_off : _ |
1132 (strict && prev_off >= offset ||
1133 not strict && prev_off > offset) -> do
1134 -- token is indented to the left of the previous context.
1135 -- we must generate a {} sequence now.
1136 pushLexState layout_left
1137 return (L span ITvocurly)
1139 setContext (Layout offset : ctx)
1140 return (L span ITvocurly)
1142 do_layout_left :: Action
1143 do_layout_left span _buf _len = do
1145 pushLexState bol -- we must be at the start of a line
1146 return (L span ITvccurly)
1148 -- -----------------------------------------------------------------------------
1151 setLine :: Int -> Action
1152 setLine code span buf len = do
1153 let line = parseUnsignedInteger buf len 10 octDecDigit
1154 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1155 -- subtract one: the line number refers to the *following* line
1160 setFile :: Int -> Action
1161 setFile code span buf len = do
1162 let file = lexemeToFastString (stepOn buf) (len-2)
1163 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1169 -- -----------------------------------------------------------------------------
1170 -- Options, includes and language pragmas.
1172 lex_string_prag :: (String -> Token) -> Action
1173 lex_string_prag mkTok span _buf _len
1174 = do input <- getInput
1178 return (L (mkSrcSpan start end) tok)
1180 = if isString input "#-}"
1181 then do setInput input
1182 return (mkTok (reverse acc))
1183 else case alexGetChar input of
1184 Just (c,i) -> go (c:acc) i
1185 Nothing -> err input
1186 isString _ [] = True
1188 = case alexGetChar i of
1189 Just (c,i') | c == x -> isString i' xs
1191 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1194 -- -----------------------------------------------------------------------------
1197 -- This stuff is horrible. I hates it.
1199 lex_string_tok :: Action
1200 lex_string_tok span _buf _len = do
1201 tok <- lex_string ""
1203 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1205 lex_string :: String -> P Token
1208 case alexGetChar' i of
1209 Nothing -> lit_error
1213 magicHash <- extension magicHashEnabled
1217 case alexGetChar' i of
1221 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1222 else let s' = mkZFastString (reverse s) in
1223 return (ITprimstring s')
1224 -- mkZFastString is a hack to avoid encoding the
1225 -- string in UTF-8. We just want the exact bytes.
1227 return (ITstring (mkFastString (reverse s)))
1229 return (ITstring (mkFastString (reverse s)))
1232 | Just ('&',i) <- next -> do
1233 setInput i; lex_string s
1234 | Just (c,i) <- next, is_space c -> do
1235 setInput i; lex_stringgap s
1236 where next = alexGetChar' i
1242 lex_stringgap :: String -> P Token
1243 lex_stringgap s = do
1246 '\\' -> lex_string s
1247 c | is_space c -> lex_stringgap s
1251 lex_char_tok :: Action
1252 -- Here we are basically parsing character literals, such as 'x' or '\n'
1253 -- but, when Template Haskell is on, we additionally spot
1254 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1255 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1256 -- So we have to do two characters of lookahead: when we see 'x we need to
1257 -- see if there's a trailing quote
1258 lex_char_tok span _buf _len = do -- We've seen '
1259 i1 <- getInput -- Look ahead to first character
1260 let loc = srcSpanStart span
1261 case alexGetChar' i1 of
1262 Nothing -> lit_error
1264 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1265 th_exts <- extension thEnabled
1268 return (L (mkSrcSpan loc end2) ITtyQuote)
1271 Just ('\\', i2@(AI _end2 _ _)) -> do -- We've seen 'backslash
1273 lit_ch <- lex_escape
1274 mc <- getCharOrFail -- Trailing quote
1275 if mc == '\'' then finish_char_tok loc lit_ch
1276 else do setInput i2; lit_error
1278 Just (c, i2@(AI _end2 _ _))
1279 | not (isAny c) -> lit_error
1282 -- We've seen 'x, where x is a valid character
1283 -- (i.e. not newline etc) but not a quote or backslash
1284 case alexGetChar' i2 of -- Look ahead one more character
1285 Just ('\'', i3) -> do -- We've seen 'x'
1287 finish_char_tok loc c
1288 _other -> do -- We've seen 'x not followed by quote
1289 -- (including the possibility of EOF)
1290 -- If TH is on, just parse the quote only
1291 th_exts <- extension thEnabled
1292 let (AI end _ _) = i1
1293 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1294 else do setInput i2; lit_error
1296 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1297 finish_char_tok loc ch -- We've already seen the closing quote
1298 -- Just need to check for trailing #
1299 = do magicHash <- extension magicHashEnabled
1300 i@(AI end _ _) <- getInput
1301 if magicHash then do
1302 case alexGetChar' i of
1303 Just ('#',i@(AI end _ _)) -> do
1305 return (L (mkSrcSpan loc end) (ITprimchar ch))
1307 return (L (mkSrcSpan loc end) (ITchar ch))
1309 return (L (mkSrcSpan loc end) (ITchar ch))
1311 lex_char :: Char -> AlexInput -> P Char
1314 '\\' -> do setInput inp; lex_escape
1315 c | isAny c -> do setInput inp; return c
1318 isAny :: Char -> Bool
1319 isAny c | c > '\x7f' = isPrint c
1320 | otherwise = is_any c
1322 lex_escape :: P Char
1336 '^' -> do c <- getCharOrFail
1337 if c >= '@' && c <= '_'
1338 then return (chr (ord c - ord '@'))
1341 'x' -> readNum is_hexdigit 16 hexDigit
1342 'o' -> readNum is_octdigit 8 octDecDigit
1343 x | is_decdigit x -> readNum2 is_decdigit 10 octDecDigit (octDecDigit x)
1347 case alexGetChar' i of
1348 Nothing -> lit_error
1350 case alexGetChar' i2 of
1351 Nothing -> do setInput i2; lit_error
1353 let str = [c1,c2,c3] in
1354 case [ (c,rest) | (p,c) <- silly_escape_chars,
1355 Just rest <- [maybePrefixMatch p str] ] of
1356 (escape_char,[]):_ -> do
1359 (escape_char,_:_):_ -> do
1364 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1365 readNum is_digit base conv = do
1369 then readNum2 is_digit base conv (conv c)
1370 else do setInput i; lit_error
1372 readNum2 :: (Char -> Bool) -> Int -> (Char -> Int) -> Int -> P Char
1373 readNum2 is_digit base conv i = do
1376 where read i input = do
1377 case alexGetChar' input of
1378 Just (c,input') | is_digit c -> do
1379 read (i*base + conv c) input'
1381 if i >= 0 && i <= 0x10FFFF
1382 then do setInput input; return (chr i)
1385 silly_escape_chars :: [(String, Char)]
1386 silly_escape_chars = [
1423 -- before calling lit_error, ensure that the current input is pointing to
1424 -- the position of the error in the buffer. This is so that we can report
1425 -- a correct location to the user, but also so we can detect UTF-8 decoding
1426 -- errors if they occur.
1428 lit_error = lexError "lexical error in string/character literal"
1430 getCharOrFail :: P Char
1433 case alexGetChar' i of
1434 Nothing -> lexError "unexpected end-of-file in string/character literal"
1435 Just (c,i) -> do setInput i; return c
1437 -- -----------------------------------------------------------------------------
1440 lex_quasiquote_tok :: Action
1441 lex_quasiquote_tok span buf len = do
1442 let quoter = reverse $ takeWhile (/= '$')
1443 $ reverse $ lexemeToString buf (len - 1)
1444 quoteStart <- getSrcLoc
1445 quote <- lex_quasiquote ""
1447 return (L (mkSrcSpan (srcSpanStart span) end)
1448 (ITquasiQuote (mkFastString quoter,
1449 mkFastString (reverse quote),
1450 mkSrcSpan quoteStart end)))
1452 lex_quasiquote :: String -> P String
1453 lex_quasiquote s = do
1455 case alexGetChar' i of
1456 Nothing -> lit_error
1459 | Just ('|',i) <- next -> do
1460 setInput i; lex_quasiquote ('|' : s)
1461 | Just (']',i) <- next -> do
1462 setInput i; lex_quasiquote (']' : s)
1463 where next = alexGetChar' i
1466 | Just (']',i) <- next -> do
1467 setInput i; return s
1468 where next = alexGetChar' i
1471 setInput i; lex_quasiquote (c : s)
1473 -- -----------------------------------------------------------------------------
1476 warn :: DynFlag -> SDoc -> Action
1477 warn option warning srcspan _buf _len = do
1478 addWarning option srcspan warning
1481 warnThen :: DynFlag -> SDoc -> Action -> Action
1482 warnThen option warning action srcspan buf len = do
1483 addWarning option srcspan warning
1484 action srcspan buf len
1486 -- -----------------------------------------------------------------------------
1497 SrcSpan -- The start and end of the text span related to
1498 -- the error. Might be used in environments which can
1499 -- show this span, e.g. by highlighting it.
1500 Message -- The error message
1502 data PState = PState {
1503 buffer :: StringBuffer,
1505 messages :: Messages,
1506 last_loc :: SrcSpan, -- pos of previous token
1507 last_offs :: !Int, -- offset of the previous token from the
1508 -- beginning of the current line.
1509 -- \t is equal to 8 spaces.
1510 last_len :: !Int, -- len of previous token
1511 last_line_len :: !Int,
1512 loc :: SrcLoc, -- current loc (end of prev token + 1)
1513 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1514 context :: [LayoutContext],
1517 -- last_loc and last_len are used when generating error messages,
1518 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1519 -- current token to happyError, we could at least get rid of last_len.
1520 -- Getting rid of last_loc would require finding another way to
1521 -- implement pushCurrentContext (which is only called from one place).
1523 newtype P a = P { unP :: PState -> ParseResult a }
1525 instance Monad P where
1531 returnP a = a `seq` (P $ \s -> POk s a)
1533 thenP :: P a -> (a -> P b) -> P b
1534 (P m) `thenP` k = P $ \ s ->
1536 POk s1 a -> (unP (k a)) s1
1537 PFailed span err -> PFailed span err
1539 failP :: String -> P a
1540 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1542 failMsgP :: String -> P a
1543 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1545 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1546 failLocMsgP loc1 loc2 str = P $ \_ -> PFailed (mkSrcSpan loc1 loc2) (text str)
1548 failSpanMsgP :: SrcSpan -> SDoc -> P a
1549 failSpanMsgP span msg = P $ \_ -> PFailed span msg
1551 extension :: (Int -> Bool) -> P Bool
1552 extension p = P $ \s -> POk s (p $! extsBitmap s)
1555 getExts = P $ \s -> POk s (extsBitmap s)
1557 setExts :: (Int -> Int) -> P ()
1558 setExts f = P $ \s -> POk s{ extsBitmap = f (extsBitmap s) } ()
1560 setSrcLoc :: SrcLoc -> P ()
1561 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1563 getSrcLoc :: P SrcLoc
1564 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1566 setLastToken :: SrcSpan -> Int -> Int -> P ()
1567 setLastToken loc len line_len = P $ \s -> POk s {
1570 last_line_len=line_len
1573 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1575 alexInputPrevChar :: AlexInput -> Char
1576 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1578 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1579 alexGetChar (AI loc ofs s)
1581 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1582 --trace (show (ord c)) $
1583 Just (adj_c, (AI loc' ofs' s'))
1584 where (c,s') = nextChar s
1585 loc' = advanceSrcLoc loc c
1586 ofs' = advanceOffs c ofs
1594 other_graphic = '\x6'
1597 | c <= '\x06' = non_graphic
1599 -- Alex doesn't handle Unicode, so when Unicode
1600 -- character is encoutered we output these values
1601 -- with the actual character value hidden in the state.
1603 case generalCategory c of
1604 UppercaseLetter -> upper
1605 LowercaseLetter -> lower
1606 TitlecaseLetter -> upper
1607 ModifierLetter -> other_graphic
1608 OtherLetter -> lower -- see #1103
1609 NonSpacingMark -> other_graphic
1610 SpacingCombiningMark -> other_graphic
1611 EnclosingMark -> other_graphic
1612 DecimalNumber -> digit
1613 LetterNumber -> other_graphic
1614 OtherNumber -> other_graphic
1615 ConnectorPunctuation -> symbol
1616 DashPunctuation -> symbol
1617 OpenPunctuation -> other_graphic
1618 ClosePunctuation -> other_graphic
1619 InitialQuote -> other_graphic
1620 FinalQuote -> other_graphic
1621 OtherPunctuation -> symbol
1622 MathSymbol -> symbol
1623 CurrencySymbol -> symbol
1624 ModifierSymbol -> symbol
1625 OtherSymbol -> symbol
1627 _other -> non_graphic
1629 -- This version does not squash unicode characters, it is used when
1631 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1632 alexGetChar' (AI loc ofs s)
1634 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1635 --trace (show (ord c)) $
1636 Just (c, (AI loc' ofs' s'))
1637 where (c,s') = nextChar s
1638 loc' = advanceSrcLoc loc c
1639 ofs' = advanceOffs c ofs
1641 advanceOffs :: Char -> Int -> Int
1642 advanceOffs '\n' _ = 0
1643 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1644 advanceOffs _ offs = offs + 1
1646 getInput :: P AlexInput
1647 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1649 setInput :: AlexInput -> P ()
1650 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1652 pushLexState :: Int -> P ()
1653 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1655 popLexState :: P Int
1656 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1658 getLexState :: P Int
1659 getLexState = P $ \s@PState{ lex_state=ls:_ } -> POk s ls
1661 -- for reasons of efficiency, flags indicating language extensions (eg,
1662 -- -fglasgow-exts or -XParr) are represented by a bitmap stored in an unboxed
1666 genericsBit = 0 -- {| and |}
1677 explicitForallBit :: Int
1678 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1680 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1681 -- (doesn't affect the lexer)
1683 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1685 haddockBit = 10 -- Lex and parse Haddock comments
1687 magicHashBit = 11 -- "#" in both functions and operators
1689 kindSigsBit = 12 -- Kind signatures on type variables
1690 recursiveDoBit :: Int
1691 recursiveDoBit = 13 -- mdo
1692 unicodeSyntaxBit :: Int
1693 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1694 unboxedTuplesBit :: Int
1695 unboxedTuplesBit = 15 -- (# and #)
1696 standaloneDerivingBit :: Int
1697 standaloneDerivingBit = 16 -- standalone instance deriving declarations
1698 transformComprehensionsBit :: Int
1699 transformComprehensionsBit = 17
1701 qqBit = 18 -- enable quasiquoting
1702 inRulePragBit :: Int
1704 rawTokenStreamBit :: Int
1705 rawTokenStreamBit = 20 -- producing a token stream with all comments included
1706 newQualOpsBit :: Int
1707 newQualOpsBit = 21 -- Haskell' qualified operator syntax, e.g. Prelude.(+)
1709 always :: Int -> Bool
1711 genericsEnabled :: Int -> Bool
1712 genericsEnabled flags = testBit flags genericsBit
1713 parrEnabled :: Int -> Bool
1714 parrEnabled flags = testBit flags parrBit
1715 arrowsEnabled :: Int -> Bool
1716 arrowsEnabled flags = testBit flags arrowsBit
1717 thEnabled :: Int -> Bool
1718 thEnabled flags = testBit flags thBit
1719 ipEnabled :: Int -> Bool
1720 ipEnabled flags = testBit flags ipBit
1721 explicitForallEnabled :: Int -> Bool
1722 explicitForallEnabled flags = testBit flags explicitForallBit
1723 bangPatEnabled :: Int -> Bool
1724 bangPatEnabled flags = testBit flags bangPatBit
1725 -- tyFamEnabled :: Int -> Bool
1726 -- tyFamEnabled flags = testBit flags tyFamBit
1727 haddockEnabled :: Int -> Bool
1728 haddockEnabled flags = testBit flags haddockBit
1729 magicHashEnabled :: Int -> Bool
1730 magicHashEnabled flags = testBit flags magicHashBit
1731 -- kindSigsEnabled :: Int -> Bool
1732 -- kindSigsEnabled flags = testBit flags kindSigsBit
1733 unicodeSyntaxEnabled :: Int -> Bool
1734 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1735 unboxedTuplesEnabled :: Int -> Bool
1736 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1737 standaloneDerivingEnabled :: Int -> Bool
1738 standaloneDerivingEnabled flags = testBit flags standaloneDerivingBit
1739 qqEnabled :: Int -> Bool
1740 qqEnabled flags = testBit flags qqBit
1741 -- inRulePrag :: Int -> Bool
1742 -- inRulePrag flags = testBit flags inRulePragBit
1743 rawTokenStreamEnabled :: Int -> Bool
1744 rawTokenStreamEnabled flags = testBit flags rawTokenStreamBit
1745 newQualOps :: Int -> Bool
1746 newQualOps flags = testBit flags newQualOpsBit
1747 oldQualOps :: Int -> Bool
1748 oldQualOps flags = not (newQualOps flags)
1750 -- PState for parsing options pragmas
1752 pragState :: DynFlags -> StringBuffer -> SrcLoc -> PState
1753 pragState dynflags buf loc =
1756 messages = emptyMessages,
1758 last_loc = mkSrcSpan loc loc,
1765 lex_state = [bol, option_prags, 0]
1769 -- create a parse state
1771 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1772 mkPState buf loc flags =
1776 messages = emptyMessages,
1777 last_loc = mkSrcSpan loc loc,
1782 extsBitmap = fromIntegral bitmap,
1784 lex_state = [bol, 0]
1785 -- we begin in the layout state if toplev_layout is set
1788 bitmap = genericsBit `setBitIf` dopt Opt_Generics flags
1789 .|. ffiBit `setBitIf` dopt Opt_ForeignFunctionInterface flags
1790 .|. parrBit `setBitIf` dopt Opt_PArr flags
1791 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1792 .|. thBit `setBitIf` dopt Opt_TemplateHaskell flags
1793 .|. qqBit `setBitIf` dopt Opt_QuasiQuotes flags
1794 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1795 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1796 .|. explicitForallBit `setBitIf` dopt Opt_LiberalTypeSynonyms flags
1797 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1798 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1799 .|. explicitForallBit `setBitIf` dopt Opt_Rank2Types flags
1800 .|. explicitForallBit `setBitIf` dopt Opt_RankNTypes flags
1801 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1802 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1803 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1804 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1805 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1806 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1807 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1808 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1809 .|. standaloneDerivingBit `setBitIf` dopt Opt_StandaloneDeriving flags
1810 .|. transformComprehensionsBit `setBitIf` dopt Opt_TransformListComp flags
1811 .|. rawTokenStreamBit `setBitIf` dopt Opt_KeepRawTokenStream flags
1812 .|. newQualOpsBit `setBitIf` dopt Opt_NewQualifiedOperators flags
1814 setBitIf :: Int -> Bool -> Int
1815 b `setBitIf` cond | cond = bit b
1818 addWarning :: DynFlag -> SrcSpan -> SDoc -> P ()
1819 addWarning option srcspan warning
1820 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1821 let warning' = mkWarnMsg srcspan alwaysQualify warning
1822 ws' = if dopt option d then ws `snocBag` warning' else ws
1823 in POk s{messages=(ws', es)} ()
1825 getMessages :: PState -> Messages
1826 getMessages PState{messages=ms} = ms
1828 getContext :: P [LayoutContext]
1829 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1831 setContext :: [LayoutContext] -> P ()
1832 setContext ctx = P $ \s -> POk s{context=ctx} ()
1835 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1836 last_len = len, last_loc = last_loc }) ->
1838 (_:tl) -> POk s{ context = tl } ()
1839 [] -> PFailed last_loc (srcParseErr buf len)
1841 -- Push a new layout context at the indentation of the last token read.
1842 -- This is only used at the outer level of a module when the 'module'
1843 -- keyword is missing.
1844 pushCurrentContext :: P ()
1845 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1846 POk s{context = Layout (offs-len) : ctx} ()
1847 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1849 getOffside :: P Ordering
1850 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1851 let ord = case stk of
1852 (Layout n:_) -> compare offs n
1856 -- ---------------------------------------------------------------------------
1857 -- Construct a parse error
1860 :: StringBuffer -- current buffer (placed just after the last token)
1861 -> Int -- length of the previous token
1864 = hcat [ if null token
1865 then ptext (sLit "parse error (possibly incorrect indentation)")
1866 else hcat [ptext (sLit "parse error on input "),
1867 char '`', text token, char '\'']
1869 where token = lexemeToString (offsetBytes (-len) buf) len
1871 -- Report a parse failure, giving the span of the previous token as
1872 -- the location of the error. This is the entry point for errors
1873 -- detected during parsing.
1875 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1876 last_loc = last_loc } ->
1877 PFailed last_loc (srcParseErr buf len)
1879 -- A lexical error is reported at a particular position in the source file,
1880 -- not over a token range.
1881 lexError :: String -> P a
1884 (AI end _ buf) <- getInput
1885 reportLexError loc end buf str
1887 -- -----------------------------------------------------------------------------
1888 -- This is the top-level function: called from the parser each time a
1889 -- new token is to be read from the input.
1891 lexer :: (Located Token -> P a) -> P a
1893 tok@(L _span _tok__) <- lexToken
1894 -- trace ("token: " ++ show tok__) $ do
1897 lexToken :: P (Located Token)
1899 inp@(AI loc1 _ buf) <- getInput
1902 case alexScanUser exts inp sc of
1904 let span = mkSrcSpan loc1 loc1
1905 setLastToken span 0 0
1906 return (L span ITeof)
1907 AlexError (AI loc2 _ buf) ->
1908 reportLexError loc1 loc2 buf "lexical error"
1909 AlexSkip inp2 _ -> do
1912 AlexToken inp2@(AI end _ buf2) _ t -> do
1914 let span = mkSrcSpan loc1 end
1915 let bytes = byteDiff buf buf2
1916 span `seq` setLastToken span bytes bytes
1919 reportLexError :: SrcLoc -> SrcLoc -> StringBuffer -> [Char] -> P a
1920 reportLexError loc1 loc2 buf str
1921 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1924 c = fst (nextChar buf)
1926 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1927 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1928 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)
1930 lexTokenStream :: StringBuffer -> SrcLoc -> DynFlags -> ParseResult [Located Token]
1931 lexTokenStream buf loc dflags = unP go initState
1932 where initState = mkPState buf loc (dopt_set (dopt_unset dflags Opt_Haddock) Opt_KeepRawTokenStream)
1934 ltok <- lexer return
1936 L _ ITeof -> return []
1937 _ -> liftM (ltok:) go