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
23 -- qualified operator NOTES.
25 -- - If M.(+) is a single lexeme, then..
26 -- - Probably (+) should be a single lexeme too, for consistency.
27 -- Otherwise ( + ) would be a prefix operator, but M.( + ) would not be.
28 -- - But we have to rule out reserved operators, otherwise (..) becomes
29 -- a different lexeme.
30 -- - Should we therefore also rule out reserved operators in the qualified
31 -- form? This is quite difficult to achieve. We don't do it for
35 {-# OPTIONS -Wwarn -w #-}
36 -- The above warning supression flag is a temporary kludge.
37 -- While working on this module you are encouraged to remove it and fix
38 -- any warnings in the module. See
39 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
42 -- Note that Alex itself generates code with with some unused bindings and
43 -- without type signatures, so removing the flag might not be possible.
45 {-# OPTIONS_GHC -funbox-strict-fields #-}
48 Token(..), lexer, pragState, mkPState, PState(..),
49 P(..), ParseResult(..), getSrcLoc,
50 failLocMsgP, failSpanMsgP, srcParseFail,
52 popContext, pushCurrentContext, setLastToken, setSrcLoc,
53 getLexState, popLexState, pushLexState,
54 extension, standaloneDerivingEnabled, bangPatEnabled,
68 import Util ( maybePrefixMatch, readRational )
76 $unispace = \x05 -- Trick Alex into handling Unicode. See alexGetChar.
77 $whitechar = [\ \n\r\f\v $unispace]
78 $white_no_nl = $whitechar # \n
82 $unidigit = \x03 -- Trick Alex into handling Unicode. See alexGetChar.
83 $decdigit = $ascdigit -- for now, should really be $digit (ToDo)
84 $digit = [$ascdigit $unidigit]
86 $special = [\(\)\,\;\[\]\`\{\}]
87 $ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~]
88 $unisymbol = \x04 -- Trick Alex into handling Unicode. See alexGetChar.
89 $symbol = [$ascsymbol $unisymbol] # [$special \_\:\"\']
91 $unilarge = \x01 -- Trick Alex into handling Unicode. See alexGetChar.
93 $large = [$asclarge $unilarge]
95 $unismall = \x02 -- Trick Alex into handling Unicode. See alexGetChar.
97 $small = [$ascsmall $unismall \_]
99 $unigraphic = \x06 -- Trick Alex into handling Unicode. See alexGetChar.
100 $graphic = [$small $large $symbol $digit $special $unigraphic \:\"\']
103 $hexit = [$decdigit A-F a-f]
104 $symchar = [$symbol \:]
106 $idchar = [$small $large $digit \']
108 $docsym = [\| \^ \* \$]
110 @varid = $small $idchar*
111 @conid = $large $idchar*
113 @varsym = $symbol $symchar*
114 @consym = \: $symchar*
116 @decimal = $decdigit+
118 @hexadecimal = $hexit+
119 @exponent = [eE] [\-\+]? @decimal
121 -- we support the hierarchical module name extension:
124 @floating_point = @decimal \. @decimal @exponent? | @decimal @exponent
126 -- normal signed numerical literals can only be explicitly negative,
127 -- not explicitly positive (contrast @exponent)
129 @signed = @negative ?
133 -- everywhere: skip whitespace and comments
135 $tab+ { warn Opt_WarnTabs (text "Tab character") }
137 -- Everywhere: deal with nested comments. We explicitly rule out
138 -- pragmas, "{-#", so that we don't accidentally treat them as comments.
139 -- (this can happen even though pragmas will normally take precedence due to
140 -- longest-match, because pragmas aren't valid in every state, but comments
141 -- are). We also rule out nested Haddock comments, if the -haddock flag is
144 "{-" / { isNormalComment } { nested_comment lexToken }
146 -- Single-line comments are a bit tricky. Haskell 98 says that two or
147 -- more dashes followed by a symbol should be parsed as a varsym, so we
148 -- have to exclude those.
150 -- Since Haddock comments aren't valid in every state, we need to rule them
153 -- The following two rules match comments that begin with two dashes, but
154 -- continue with a different character. The rules test that this character
155 -- is not a symbol (in which case we'd have a varsym), and that it's not a
156 -- space followed by a Haddock comment symbol (docsym) (in which case we'd
157 -- have a Haddock comment). The rules then munch the rest of the line.
159 "-- " ~[$docsym \#] .* { lineCommentToken }
160 "--" [^$symbol : \ ] .* { lineCommentToken }
162 -- Next, match Haddock comments if no -haddock flag
164 "-- " [$docsym \#] .* / { ifExtension (not . haddockEnabled) } { lineCommentToken }
166 -- Now, when we've matched comments that begin with 2 dashes and continue
167 -- with a different character, we need to match comments that begin with three
168 -- or more dashes (which clearly can't be Haddock comments). We only need to
169 -- make sure that the first non-dash character isn't a symbol, and munch the
172 "---"\-* [^$symbol :] .* { lineCommentToken }
174 -- Since the previous rules all match dashes followed by at least one
175 -- character, we also need to match a whole line filled with just dashes.
177 "--"\-* / { atEOL } { lineCommentToken }
179 -- We need this rule since none of the other single line comment rules
180 -- actually match this case.
182 "-- " / { atEOL } { lineCommentToken }
184 -- 'bol' state: beginning of a line. Slurp up all the whitespace (including
185 -- blank lines) until we find a non-whitespace character, then do layout
188 -- One slight wibble here: what if the line begins with {-#? In
189 -- theory, we have to lex the pragma to see if it's one we recognise,
190 -- and if it is, then we backtrack and do_bol, otherwise we treat it
191 -- as a nested comment. We don't bother with this: if the line begins
192 -- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
195 ^\# (line)? { begin line_prag1 }
196 ^\# pragma .* \n ; -- GCC 3.3 CPP generated, apparently
197 ^\# \! .* \n ; -- #!, for scripts
201 -- after a layout keyword (let, where, do, of), we begin a new layout
202 -- context if the curly brace is missing.
203 -- Careful! This stuff is quite delicate.
204 <layout, layout_do> {
205 \{ / { notFollowedBy '-' } { pop_and open_brace }
206 -- we might encounter {-# here, but {- has been handled already
208 ^\# (line)? { begin line_prag1 }
211 -- do is treated in a subtly different way, see new_layout_context
212 <layout> () { new_layout_context True }
213 <layout_do> () { new_layout_context False }
215 -- after a new layout context which was found to be to the left of the
216 -- previous context, we have generated a '{' token, and we now need to
217 -- generate a matching '}' token.
218 <layout_left> () { do_layout_left }
220 <0,option_prags> \n { begin bol }
222 "{-#" $whitechar* (line|LINE) / { notFollowedByPragmaChar }
225 -- single-line line pragmas, of the form
226 -- # <line> "<file>" <extra-stuff> \n
227 <line_prag1> $decdigit+ { setLine line_prag1a }
228 <line_prag1a> \" [$graphic \ ]* \" { setFile line_prag1b }
229 <line_prag1b> .* { pop }
231 -- Haskell-style line pragmas, of the form
232 -- {-# LINE <line> "<file>" #-}
233 <line_prag2> $decdigit+ { setLine line_prag2a }
234 <line_prag2a> \" [$graphic \ ]* \" { setFile line_prag2b }
235 <line_prag2b> "#-}"|"-}" { pop }
236 -- NOTE: accept -} at the end of a LINE pragma, for compatibility
237 -- with older versions of GHC which generated these.
240 "{-#" $whitechar* (RULES|rules) / { notFollowedByPragmaChar } { rulePrag }
241 "{-#" $whitechar* (INLINE|inline) / { notFollowedByPragmaChar }
242 { token (ITinline_prag True) }
243 "{-#" $whitechar* (NO(T?)INLINE|no(t?)inline) / { notFollowedByPragmaChar }
244 { token (ITinline_prag False) }
245 "{-#" $whitechar* (INLINE|inline)
246 $whitechar+ (CONLIKE|conlike) / { notFollowedByPragmaChar }
247 { token (ITinline_conlike_prag True) }
248 "{-#" $whitechar* (NO(T)?INLINE|no(t?)inline)
249 $whitechar+ (CONLIKE|constructorlike) / { notFollowedByPragmaChar }
250 { token (ITinline_conlike_prag False) }
251 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e) / { notFollowedByPragmaChar }
252 { token ITspec_prag }
253 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
254 $whitechar+ (INLINE|inline) / { notFollowedByPragmaChar }
255 { token (ITspec_inline_prag True) }
256 "{-#" $whitechar* (SPECIALI[SZ]E|speciali[sz]e)
257 $whitechar+ (NO(T?)INLINE|no(t?)inline) / { notFollowedByPragmaChar }
258 { token (ITspec_inline_prag False) }
259 "{-#" $whitechar* (SOURCE|source) / { notFollowedByPragmaChar }
260 { token ITsource_prag }
261 "{-#" $whitechar* (WARNING|warning) / { notFollowedByPragmaChar }
262 { token ITwarning_prag }
263 "{-#" $whitechar* (DEPRECATED|deprecated) / { notFollowedByPragmaChar }
264 { token ITdeprecated_prag }
265 "{-#" $whitechar* (SCC|scc) / { notFollowedByPragmaChar }
267 "{-#" $whitechar* (GENERATED|generated) / { notFollowedByPragmaChar }
268 { token ITgenerated_prag }
269 "{-#" $whitechar* (CORE|core) / { notFollowedByPragmaChar }
270 { token ITcore_prag }
271 "{-#" $whitechar* (UNPACK|unpack) / { notFollowedByPragmaChar }
272 { token ITunpack_prag }
273 "{-#" $whitechar* (ANN|ann) / { notFollowedByPragmaChar }
276 -- We ignore all these pragmas, but don't generate a warning for them
277 -- CFILES is a hugs-only thing.
278 "{-#" $whitechar* (OPTIONS_(HUGS|hugs|NHC98|nhc98|JHC|jhc|YHC|yhc|CATCH|catch|DERIVE|derive)|CFILES|cfiles|CONTRACT|contract) / { notFollowedByPragmaChar }
279 { nested_comment lexToken }
281 -- ToDo: should only be valid inside a pragma:
286 "{-#" $whitechar* (OPTIONS|options) / { notFollowedByPragmaChar }
287 { lex_string_prag IToptions_prag }
288 "{-#" $whitechar* (OPTIONS_GHC|options_ghc) / { notFollowedByPragmaChar }
289 { lex_string_prag IToptions_prag }
290 "{-#" $whitechar* (OPTIONS_HADDOCK|options_haddock)
291 / { notFollowedByPragmaChar }
292 { lex_string_prag ITdocOptions }
293 "-- #" { multiline_doc_comment }
294 "{-#" $whitechar* (LANGUAGE|language) / { notFollowedByPragmaChar }
295 { token ITlanguage_prag }
296 "{-#" $whitechar* (INCLUDE|include) / { notFollowedByPragmaChar }
297 { lex_string_prag ITinclude_prag }
301 -- In the "0" mode we ignore these pragmas
302 "{-#" $whitechar* (OPTIONS|options|OPTIONS_GHC|options_ghc|OPTIONS_HADDOCK|options_haddock|LANGUAGE|language|INCLUDE|include) / { notFollowedByPragmaChar }
303 { nested_comment lexToken }
307 "-- #" .* { lineCommentToken }
311 "{-#" { warnThen Opt_WarnUnrecognisedPragmas (text "Unrecognised pragma")
312 (nested_comment lexToken) }
315 -- '0' state: ordinary lexemes
320 "-- " $docsym / { ifExtension haddockEnabled } { multiline_doc_comment }
321 "{-" \ ? $docsym / { ifExtension haddockEnabled } { nested_doc_comment }
327 "[:" / { ifExtension parrEnabled } { token ITopabrack }
328 ":]" / { ifExtension parrEnabled } { token ITcpabrack }
332 "[|" / { ifExtension thEnabled } { token ITopenExpQuote }
333 "[e|" / { ifExtension thEnabled } { token ITopenExpQuote }
334 "[p|" / { ifExtension thEnabled } { token ITopenPatQuote }
335 "[d|" / { ifExtension thEnabled } { layout_token ITopenDecQuote }
336 "[t|" / { ifExtension thEnabled } { token ITopenTypQuote }
337 "|]" / { ifExtension thEnabled } { token ITcloseQuote }
338 \$ @varid / { ifExtension thEnabled } { skip_one_varid ITidEscape }
339 "$(" / { ifExtension thEnabled } { token ITparenEscape }
341 "[$" @varid "|" / { ifExtension qqEnabled }
342 { lex_quasiquote_tok }
346 "(|" / { ifExtension arrowsEnabled `alexAndPred` notFollowedBySymbol }
347 { special IToparenbar }
348 "|)" / { ifExtension arrowsEnabled } { special ITcparenbar }
352 \? @varid / { ifExtension ipEnabled } { skip_one_varid ITdupipvarid }
356 "(#" / { ifExtension unboxedTuplesEnabled `alexAndPred` notFollowedBySymbol }
357 { token IToubxparen }
358 "#)" / { ifExtension unboxedTuplesEnabled }
359 { token ITcubxparen }
363 "{|" / { ifExtension genericsEnabled } { token ITocurlybar }
364 "|}" / { ifExtension genericsEnabled } { token ITccurlybar }
368 \( { special IToparen }
369 \) { special ITcparen }
370 \[ { special ITobrack }
371 \] { special ITcbrack }
372 \, { special ITcomma }
373 \; { special ITsemi }
374 \` { special ITbackquote }
381 @qual @varid { idtoken qvarid }
382 @qual @conid { idtoken qconid }
384 @conid { idtoken conid }
388 @qual @varid "#"+ / { ifExtension magicHashEnabled } { idtoken qvarid }
389 @qual @conid "#"+ / { ifExtension magicHashEnabled } { idtoken qconid }
390 @varid "#"+ / { ifExtension magicHashEnabled } { varid }
391 @conid "#"+ / { ifExtension magicHashEnabled } { idtoken conid }
394 -- ToDo: - move `var` and (sym) into lexical syntax?
395 -- - remove backquote from $special?
397 @qual @varsym / { ifExtension oldQualOps } { idtoken qvarsym }
398 @qual @consym / { ifExtension oldQualOps } { idtoken qconsym }
399 @qual \( @varsym \) / { ifExtension newQualOps } { idtoken prefixqvarsym }
400 @qual \( @consym \) / { ifExtension newQualOps } { idtoken prefixqconsym }
405 -- For the normal boxed literals we need to be careful
406 -- when trying to be close to Haskell98
408 -- Normal integral literals (:: Num a => a, from Integer)
409 @decimal { tok_num positive 0 0 decimal }
410 0[oO] @octal { tok_num positive 2 2 octal }
411 0[xX] @hexadecimal { tok_num positive 2 2 hexadecimal }
413 -- Normal rational literals (:: Fractional a => a, from Rational)
414 @floating_point { strtoken tok_float }
418 -- Unboxed ints (:: Int#) and words (:: Word#)
419 -- It's simpler (and faster?) to give separate cases to the negatives,
420 -- especially considering octal/hexadecimal prefixes.
421 @decimal \# / { ifExtension magicHashEnabled } { tok_primint positive 0 1 decimal }
422 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 octal }
423 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint positive 2 3 hexadecimal }
424 @negative @decimal \# / { ifExtension magicHashEnabled } { tok_primint negative 1 2 decimal }
425 @negative 0[oO] @octal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 octal }
426 @negative 0[xX] @hexadecimal \# / { ifExtension magicHashEnabled } { tok_primint negative 3 4 hexadecimal }
428 @decimal \# \# / { ifExtension magicHashEnabled } { tok_primword 0 2 decimal }
429 0[oO] @octal \# \# / { ifExtension magicHashEnabled } { tok_primword 2 4 octal }
430 0[xX] @hexadecimal \# \# / { ifExtension magicHashEnabled } { tok_primword 2 4 hexadecimal }
432 -- Unboxed floats and doubles (:: Float#, :: Double#)
433 -- prim_{float,double} work with signed literals
434 @signed @floating_point \# / { ifExtension magicHashEnabled } { init_strtoken 1 tok_primfloat }
435 @signed @floating_point \# \# / { ifExtension magicHashEnabled } { init_strtoken 2 tok_primdouble }
438 -- Strings and chars are lexed by hand-written code. The reason is
439 -- that even if we recognise the string or char here in the regex
440 -- lexer, we would still have to parse the string afterward in order
441 -- to convert it to a String.
444 \" { lex_string_tok }
448 -- -----------------------------------------------------------------------------
452 = ITas -- Haskell keywords
476 | ITscc -- ToDo: remove (we use {-# SCC "..." #-} now)
478 | ITforall -- GHC extension keywords
496 | ITinline_prag Bool -- True <=> INLINE, False <=> NOINLINE
497 | ITinline_conlike_prag Bool -- same
498 | ITspec_prag -- SPECIALISE
499 | ITspec_inline_prag Bool -- SPECIALISE INLINE (or NOINLINE)
507 | ITcore_prag -- hdaume: core annotations
511 | IToptions_prag String
512 | ITinclude_prag String
515 | ITdotdot -- reserved symbols
531 | ITbiglam -- GHC-extension symbols
533 | ITocurly -- special symbols
535 | ITocurlybar -- {|, for type applications
536 | ITccurlybar -- |}, for type applications
540 | ITopabrack -- [:, for parallel arrays with -XParr
541 | ITcpabrack -- :], for parallel arrays with -XParr
552 | ITvarid FastString -- identifiers
554 | ITvarsym FastString
555 | ITconsym FastString
556 | ITqvarid (FastString,FastString)
557 | ITqconid (FastString,FastString)
558 | ITqvarsym (FastString,FastString)
559 | ITqconsym (FastString,FastString)
560 | ITprefixqvarsym (FastString,FastString)
561 | ITprefixqconsym (FastString,FastString)
563 | ITdupipvarid FastString -- GHC extension: implicit param: ?x
565 | ITpragma StringBuffer
568 | ITstring FastString
570 | ITrational Rational
573 | ITprimstring FastString
576 | ITprimfloat Rational
577 | ITprimdouble Rational
579 -- MetaHaskell extension tokens
580 | ITopenExpQuote -- [| or [e|
581 | ITopenPatQuote -- [p|
582 | ITopenDecQuote -- [d|
583 | ITopenTypQuote -- [t|
585 | ITidEscape FastString -- $x
586 | ITparenEscape -- $(
589 | ITquasiQuote (FastString,FastString,SrcSpan) -- [:...|...|]
591 -- Arrow notation extension
598 | ITLarrowtail -- -<<
599 | ITRarrowtail -- >>-
601 | ITunknown String -- Used when the lexer can't make sense of it
602 | ITeof -- end of file token
604 -- Documentation annotations
605 | ITdocCommentNext String -- something beginning '-- |'
606 | ITdocCommentPrev String -- something beginning '-- ^'
607 | ITdocCommentNamed String -- something beginning '-- $'
608 | ITdocSection Int String -- a section heading
609 | ITdocOptions String -- doc options (prune, ignore-exports, etc)
610 | ITdocOptionsOld String -- doc options declared "-- # ..."-style
611 | ITlineComment String -- comment starting by "--"
612 | ITblockComment String -- comment in {- -}
615 deriving Show -- debugging
619 isSpecial :: Token -> Bool
620 -- If we see M.x, where x is a keyword, but
621 -- is special, we treat is as just plain M.x,
623 isSpecial ITas = True
624 isSpecial IThiding = True
625 isSpecial ITqualified = True
626 isSpecial ITforall = True
627 isSpecial ITexport = True
628 isSpecial ITlabel = True
629 isSpecial ITdynamic = True
630 isSpecial ITsafe = True
631 isSpecial ITthreadsafe = True
632 isSpecial ITunsafe = True
633 isSpecial ITccallconv = True
634 isSpecial ITstdcallconv = True
635 isSpecial ITmdo = True
636 isSpecial ITfamily = True
637 isSpecial ITgroup = True
638 isSpecial ITby = True
639 isSpecial ITusing = True
643 -- the bitmap provided as the third component indicates whether the
644 -- corresponding extension keyword is valid under the extension options
645 -- provided to the compiler; if the extension corresponding to *any* of the
646 -- bits set in the bitmap is enabled, the keyword is valid (this setup
647 -- facilitates using a keyword in two different extensions that can be
648 -- activated independently)
650 reservedWordsFM :: UniqFM (Token, Int)
651 reservedWordsFM = listToUFM $
652 map (\(x, y, z) -> (mkFastString x, (y, z)))
653 [( "_", ITunderscore, 0 ),
655 ( "case", ITcase, 0 ),
656 ( "class", ITclass, 0 ),
657 ( "data", ITdata, 0 ),
658 ( "default", ITdefault, 0 ),
659 ( "deriving", ITderiving, 0 ),
661 ( "else", ITelse, 0 ),
662 ( "hiding", IThiding, 0 ),
664 ( "import", ITimport, 0 ),
666 ( "infix", ITinfix, 0 ),
667 ( "infixl", ITinfixl, 0 ),
668 ( "infixr", ITinfixr, 0 ),
669 ( "instance", ITinstance, 0 ),
671 ( "module", ITmodule, 0 ),
672 ( "newtype", ITnewtype, 0 ),
674 ( "qualified", ITqualified, 0 ),
675 ( "then", ITthen, 0 ),
676 ( "type", ITtype, 0 ),
677 ( "where", ITwhere, 0 ),
678 ( "_scc_", ITscc, 0 ), -- ToDo: remove
680 ( "forall", ITforall, bit explicitForallBit .|. bit inRulePragBit),
681 ( "mdo", ITmdo, bit recursiveDoBit),
682 ( "family", ITfamily, bit tyFamBit),
683 ( "group", ITgroup, bit transformComprehensionsBit),
684 ( "by", ITby, bit transformComprehensionsBit),
685 ( "using", ITusing, bit transformComprehensionsBit),
687 ( "foreign", ITforeign, bit ffiBit),
688 ( "export", ITexport, bit ffiBit),
689 ( "label", ITlabel, bit ffiBit),
690 ( "dynamic", ITdynamic, bit ffiBit),
691 ( "safe", ITsafe, bit ffiBit),
692 ( "threadsafe", ITthreadsafe, bit ffiBit),
693 ( "unsafe", ITunsafe, bit ffiBit),
694 ( "stdcall", ITstdcallconv, bit ffiBit),
695 ( "ccall", ITccallconv, bit ffiBit),
696 ( "dotnet", ITdotnet, bit ffiBit),
698 ( "rec", ITrec, bit arrowsBit),
699 ( "proc", ITproc, bit arrowsBit)
702 reservedSymsFM :: UniqFM (Token, Int -> Bool)
703 reservedSymsFM = listToUFM $
704 map (\ (x,y,z) -> (mkFastString x,(y,z)))
705 [ ("..", ITdotdot, always)
706 -- (:) is a reserved op, meaning only list cons
707 ,(":", ITcolon, always)
708 ,("::", ITdcolon, always)
709 ,("=", ITequal, always)
710 ,("\\", ITlam, always)
711 ,("|", ITvbar, always)
712 ,("<-", ITlarrow, always)
713 ,("->", ITrarrow, always)
715 ,("~", ITtilde, always)
716 ,("=>", ITdarrow, always)
717 ,("-", ITminus, always)
718 ,("!", ITbang, always)
720 -- For data T (a::*) = MkT
721 ,("*", ITstar, always) -- \i -> kindSigsEnabled i || tyFamEnabled i)
722 -- For 'forall a . t'
723 ,(".", ITdot, always) -- \i -> explicitForallEnabled i || inRulePrag i)
725 ,("-<", ITlarrowtail, arrowsEnabled)
726 ,(">-", ITrarrowtail, arrowsEnabled)
727 ,("-<<", ITLarrowtail, arrowsEnabled)
728 ,(">>-", ITRarrowtail, arrowsEnabled)
730 ,("∷", ITdcolon, unicodeSyntaxEnabled)
731 ,("⇒", ITdarrow, unicodeSyntaxEnabled)
732 ,("∀", ITforall, \i -> unicodeSyntaxEnabled i &&
733 explicitForallEnabled i)
734 ,("→", ITrarrow, unicodeSyntaxEnabled)
735 ,("←", ITlarrow, unicodeSyntaxEnabled)
736 ,("⋯", ITdotdot, unicodeSyntaxEnabled)
737 -- ToDo: ideally, → and ∷ should be "specials", so that they cannot
738 -- form part of a large operator. This would let us have a better
739 -- syntax for kinds: ɑ∷*→* would be a legal kind signature. (maybe).
742 -- -----------------------------------------------------------------------------
745 type Action = SrcSpan -> StringBuffer -> Int -> P (Located Token)
747 special :: Token -> Action
748 special tok span _buf _len = return (L span tok)
750 token, layout_token :: Token -> Action
751 token t span _buf _len = return (L span t)
752 layout_token t span _buf _len = pushLexState layout >> return (L span t)
754 idtoken :: (StringBuffer -> Int -> Token) -> Action
755 idtoken f span buf len = return (L span $! (f buf len))
757 skip_one_varid :: (FastString -> Token) -> Action
758 skip_one_varid f span buf len
759 = return (L span $! f (lexemeToFastString (stepOn buf) (len-1)))
761 strtoken :: (String -> Token) -> Action
762 strtoken f span buf len =
763 return (L span $! (f $! lexemeToString buf len))
765 init_strtoken :: Int -> (String -> Token) -> Action
766 -- like strtoken, but drops the last N character(s)
767 init_strtoken drop f span buf len =
768 return (L span $! (f $! lexemeToString buf (len-drop)))
770 begin :: Int -> Action
771 begin code _span _str _len = do pushLexState code; lexToken
774 pop _span _buf _len = do popLexState; lexToken
776 pop_and :: Action -> Action
777 pop_and act span buf len = do popLexState; act span buf len
779 {-# INLINE nextCharIs #-}
780 nextCharIs :: StringBuffer -> (Char -> Bool) -> Bool
781 nextCharIs buf p = not (atEnd buf) && p (currentChar buf)
783 notFollowedBy :: Char -> AlexAccPred Int
784 notFollowedBy char _ _ _ (AI _ _ buf)
785 = nextCharIs buf (/=char)
787 notFollowedBySymbol :: AlexAccPred Int
788 notFollowedBySymbol _ _ _ (AI _ _ buf)
789 = nextCharIs buf (`notElem` "!#$%&*+./<=>?@\\^|-~")
791 notFollowedByPragmaChar :: AlexAccPred Int
792 notFollowedByPragmaChar _ _ _ (AI _ _ buf)
793 = nextCharIs buf (\c -> not (isAlphaNum c || c == '_'))
795 -- We must reject doc comments as being ordinary comments everywhere.
796 -- In some cases the doc comment will be selected as the lexeme due to
797 -- maximal munch, but not always, because the nested comment rule is
798 -- valid in all states, but the doc-comment rules are only valid in
799 -- the non-layout states.
800 isNormalComment :: AlexAccPred Int
801 isNormalComment bits _ _ (AI _ _ buf)
802 | haddockEnabled bits = notFollowedByDocOrPragma
803 | otherwise = nextCharIs buf (/='#')
805 notFollowedByDocOrPragma
806 = not $ spaceAndP buf (`nextCharIs` (`elem` "|^*$#"))
808 spaceAndP :: StringBuffer -> (StringBuffer -> Bool) -> Bool
809 spaceAndP buf p = p buf || nextCharIs buf (==' ') && p (snd (nextChar buf))
812 haddockDisabledAnd p bits _ _ (AI _ _ buf)
813 = if haddockEnabled bits then False else (p buf)
816 atEOL :: AlexAccPred Int
817 atEOL _ _ _ (AI _ _ buf) = atEnd buf || currentChar buf == '\n'
819 ifExtension :: (Int -> Bool) -> AlexAccPred Int
820 ifExtension pred bits _ _ _ = pred bits
822 multiline_doc_comment :: Action
823 multiline_doc_comment span buf _len = withLexedDocType (worker "")
825 worker commentAcc input docType oneLine = case alexGetChar input of
827 | oneLine -> docCommentEnd input commentAcc docType buf span
828 | otherwise -> case checkIfCommentLine input' of
829 Just input -> worker ('\n':commentAcc) input docType False
830 Nothing -> docCommentEnd input commentAcc docType buf span
831 Just (c, input) -> worker (c:commentAcc) input docType oneLine
832 Nothing -> docCommentEnd input commentAcc docType buf span
834 checkIfCommentLine input = check (dropNonNewlineSpace input)
836 check input = case alexGetChar input of
837 Just ('-', input) -> case alexGetChar input of
838 Just ('-', input) -> case alexGetChar input of
839 Just (c, _) | c /= '-' -> Just input
844 dropNonNewlineSpace input = case alexGetChar input of
846 | isSpace c && c /= '\n' -> dropNonNewlineSpace input'
850 lineCommentToken :: Action
851 lineCommentToken span buf len = do
852 b <- extension rawTokenStreamEnabled
853 if b then strtoken ITlineComment span buf len else lexToken
856 nested comments require traversing by hand, they can't be parsed
857 using regular expressions.
859 nested_comment :: P (Located Token) -> Action
860 nested_comment cont span _str _len = do
864 go commentAcc 0 input = do setInput input
865 b <- extension rawTokenStreamEnabled
867 then docCommentEnd input commentAcc ITblockComment _str span
869 go commentAcc n input = case alexGetChar input of
870 Nothing -> errBrace input span
871 Just ('-',input) -> case alexGetChar input of
872 Nothing -> errBrace input span
873 Just ('\125',input) -> go commentAcc (n-1) input
874 Just (_,_) -> go ('-':commentAcc) n input
875 Just ('\123',input) -> case alexGetChar input of
876 Nothing -> errBrace input span
877 Just ('-',input) -> go ('-':'\123':commentAcc) (n+1) input
878 Just (_,_) -> go ('\123':commentAcc) n input
879 Just (c,input) -> go (c:commentAcc) n input
881 nested_doc_comment :: Action
882 nested_doc_comment span buf _len = withLexedDocType (go "")
884 go commentAcc input docType _ = case alexGetChar input of
885 Nothing -> errBrace input span
886 Just ('-',input) -> case alexGetChar input of
887 Nothing -> errBrace input span
888 Just ('\125',input) ->
889 docCommentEnd input commentAcc docType buf span
890 Just (_,_) -> go ('-':commentAcc) input docType False
891 Just ('\123', input) -> case alexGetChar input of
892 Nothing -> errBrace input span
893 Just ('-',input) -> do
895 let cont = do input <- getInput; go commentAcc input docType False
896 nested_comment cont span buf _len
897 Just (_,_) -> go ('\123':commentAcc) input docType False
898 Just (c,input) -> go (c:commentAcc) input docType False
900 withLexedDocType :: (AlexInput -> (String -> Token) -> Bool -> P (Located Token))
902 withLexedDocType lexDocComment = do
903 input@(AI _ _ buf) <- getInput
904 case prevChar buf ' ' of
905 '|' -> lexDocComment input ITdocCommentNext False
906 '^' -> lexDocComment input ITdocCommentPrev False
907 '$' -> lexDocComment input ITdocCommentNamed False
908 '*' -> lexDocSection 1 input
909 '#' -> lexDocComment input ITdocOptionsOld False
910 _ -> panic "withLexedDocType: Bad doc type"
912 lexDocSection n input = case alexGetChar input of
913 Just ('*', input) -> lexDocSection (n+1) input
914 Just (_, _) -> lexDocComment input (ITdocSection n) True
915 Nothing -> do setInput input; lexToken -- eof reached, lex it normally
917 -- RULES pragmas turn on the forall and '.' keywords, and we turn them
918 -- off again at the end of the pragma.
920 rulePrag span _ _ = do
921 setExts (.|. bit inRulePragBit)
922 return (L span ITrules_prag)
925 endPrag span _ _ = do
926 setExts (.&. complement (bit inRulePragBit))
927 return (L span ITclose_prag)
930 -------------------------------------------------------------------------------
931 -- This function is quite tricky. We can't just return a new token, we also
932 -- need to update the state of the parser. Why? Because the token is longer
933 -- than what was lexed by Alex, and the lexToken function doesn't know this, so
934 -- it writes the wrong token length to the parser state. This function is
935 -- called afterwards, so it can just update the state.
937 -- This is complicated by the fact that Haddock tokens can span multiple lines,
938 -- which is something that the original lexer didn't account for.
939 -- I have added last_line_len in the parser state which represents the length
940 -- of the part of the token that is on the last line. It is now used for layout
941 -- calculation in pushCurrentContext instead of last_len. last_len is, like it
942 -- was before, the full length of the token, and it is now only used for error
945 docCommentEnd :: AlexInput -> String -> (String -> Token) -> StringBuffer ->
946 SrcSpan -> P (Located Token)
947 docCommentEnd input commentAcc docType buf span = do
949 let (AI loc last_offs nextBuf) = input
950 comment = reverse commentAcc
951 span' = mkSrcSpan (srcSpanStart span) loc
952 last_len = byteDiff buf nextBuf
954 last_line_len = if (last_offs - last_len < 0)
958 span `seq` setLastToken span' last_len last_line_len
959 return (L span' (docType comment))
961 errBrace :: AlexInput -> SrcSpan -> P a
962 errBrace (AI end _ _) span = failLocMsgP (srcSpanStart span) end "unterminated `{-'"
964 open_brace, close_brace :: Action
965 open_brace span _str _len = do
967 setContext (NoLayout:ctx)
968 return (L span ITocurly)
969 close_brace span _str _len = do
971 return (L span ITccurly)
973 qvarid, qconid :: StringBuffer -> Int -> Token
974 qvarid buf len = ITqvarid $! splitQualName buf len False
975 qconid buf len = ITqconid $! splitQualName buf len False
977 splitQualName :: StringBuffer -> Int -> Bool -> (FastString,FastString)
978 -- takes a StringBuffer and a length, and returns the module name
979 -- and identifier parts of a qualified name. Splits at the *last* dot,
980 -- because of hierarchical module names.
981 splitQualName orig_buf len parens = split orig_buf orig_buf
984 | orig_buf `byteDiff` buf >= len = done dot_buf
985 | c == '.' = found_dot buf'
986 | otherwise = split buf' dot_buf
988 (c,buf') = nextChar buf
990 -- careful, we might get names like M....
991 -- so, if the character after the dot is not upper-case, this is
992 -- the end of the qualifier part.
993 found_dot buf -- buf points after the '.'
994 | isUpper c = split buf' buf
995 | otherwise = done buf
997 (c,buf') = nextChar buf
1000 (lexemeToFastString orig_buf (qual_size - 1),
1001 if parens -- Prelude.(+)
1002 then lexemeToFastString (stepOn dot_buf) (len - qual_size - 2)
1003 else lexemeToFastString dot_buf (len - qual_size))
1005 qual_size = orig_buf `byteDiff` dot_buf
1008 varid span buf len =
1010 case lookupUFM reservedWordsFM fs of
1011 Just (keyword,0) -> do
1012 maybe_layout keyword
1013 return (L span keyword)
1014 Just (keyword,exts) -> do
1015 b <- extension (\i -> exts .&. i /= 0)
1016 if b then do maybe_layout keyword
1017 return (L span keyword)
1018 else return (L span (ITvarid fs))
1019 _other -> return (L span (ITvarid fs))
1021 fs = lexemeToFastString buf len
1023 conid :: StringBuffer -> Int -> Token
1024 conid buf len = ITconid fs
1025 where fs = lexemeToFastString buf len
1027 qvarsym, qconsym, prefixqvarsym, prefixqconsym :: StringBuffer -> Int -> Token
1028 qvarsym buf len = ITqvarsym $! splitQualName buf len False
1029 qconsym buf len = ITqconsym $! splitQualName buf len False
1030 prefixqvarsym buf len = ITprefixqvarsym $! splitQualName buf len True
1031 prefixqconsym buf len = ITprefixqconsym $! splitQualName buf len True
1033 varsym, consym :: Action
1034 varsym = sym ITvarsym
1035 consym = sym ITconsym
1037 sym :: (FastString -> Token) -> SrcSpan -> StringBuffer -> Int
1038 -> P (Located Token)
1039 sym con span buf len =
1040 case lookupUFM reservedSymsFM fs of
1041 Just (keyword,exts) -> do
1043 if b then return (L span keyword)
1044 else return (L span $! con fs)
1045 _other -> return (L span $! con fs)
1047 fs = lexemeToFastString buf len
1049 -- Variations on the integral numeric literal.
1050 tok_integral :: (Integer -> Token)
1051 -> (Integer -> Integer)
1052 -- -> (StringBuffer -> StringBuffer) -> (Int -> Int)
1054 -> (Integer, (Char->Int)) -> Action
1055 tok_integral itint transint transbuf translen (radix,char_to_int) span buf len =
1056 return $ L span $ itint $! transint $ parseUnsignedInteger
1057 (offsetBytes transbuf buf) (subtract translen len) radix char_to_int
1059 -- some conveniences for use with tok_integral
1060 tok_num :: (Integer -> Integer)
1062 -> (Integer, (Char->Int)) -> Action
1063 tok_num = tok_integral ITinteger
1064 tok_primint :: (Integer -> Integer)
1066 -> (Integer, (Char->Int)) -> Action
1067 tok_primint = tok_integral ITprimint
1068 tok_primword :: Int -> Int
1069 -> (Integer, (Char->Int)) -> Action
1070 tok_primword = tok_integral ITprimword positive
1071 positive, negative :: (Integer -> Integer)
1074 decimal, octal, hexadecimal :: (Integer, Char -> Int)
1075 decimal = (10,octDecDigit)
1076 octal = (8,octDecDigit)
1077 hexadecimal = (16,hexDigit)
1079 -- readRational can understand negative rationals, exponents, everything.
1080 tok_float, tok_primfloat, tok_primdouble :: String -> Token
1081 tok_float str = ITrational $! readRational str
1082 tok_primfloat str = ITprimfloat $! readRational str
1083 tok_primdouble str = ITprimdouble $! readRational str
1085 -- -----------------------------------------------------------------------------
1086 -- Layout processing
1088 -- we're at the first token on a line, insert layout tokens if necessary
1090 do_bol span _str _len = do
1094 --trace "layout: inserting '}'" $ do
1096 -- do NOT pop the lex state, we might have a ';' to insert
1097 return (L span ITvccurly)
1099 --trace "layout: inserting ';'" $ do
1101 return (L span ITsemi)
1106 -- certain keywords put us in the "layout" state, where we might
1107 -- add an opening curly brace.
1108 maybe_layout :: Token -> P ()
1109 maybe_layout ITdo = pushLexState layout_do
1110 maybe_layout ITmdo = pushLexState layout_do
1111 maybe_layout ITof = pushLexState layout
1112 maybe_layout ITlet = pushLexState layout
1113 maybe_layout ITwhere = pushLexState layout
1114 maybe_layout ITrec = pushLexState layout
1115 maybe_layout _ = return ()
1117 -- Pushing a new implicit layout context. If the indentation of the
1118 -- next token is not greater than the previous layout context, then
1119 -- Haskell 98 says that the new layout context should be empty; that is
1120 -- the lexer must generate {}.
1122 -- We are slightly more lenient than this: when the new context is started
1123 -- by a 'do', then we allow the new context to be at the same indentation as
1124 -- the previous context. This is what the 'strict' argument is for.
1126 new_layout_context :: Bool -> Action
1127 new_layout_context strict span _buf _len = do
1129 (AI _ offset _) <- getInput
1132 Layout prev_off : _ |
1133 (strict && prev_off >= offset ||
1134 not strict && prev_off > offset) -> do
1135 -- token is indented to the left of the previous context.
1136 -- we must generate a {} sequence now.
1137 pushLexState layout_left
1138 return (L span ITvocurly)
1140 setContext (Layout offset : ctx)
1141 return (L span ITvocurly)
1143 do_layout_left :: Action
1144 do_layout_left span _buf _len = do
1146 pushLexState bol -- we must be at the start of a line
1147 return (L span ITvccurly)
1149 -- -----------------------------------------------------------------------------
1152 setLine :: Int -> Action
1153 setLine code span buf len = do
1154 let line = parseUnsignedInteger buf len 10 octDecDigit
1155 setSrcLoc (mkSrcLoc (srcSpanFile span) (fromIntegral line - 1) 0)
1156 -- subtract one: the line number refers to the *following* line
1161 setFile :: Int -> Action
1162 setFile code span buf len = do
1163 let file = lexemeToFastString (stepOn buf) (len-2)
1164 setSrcLoc (mkSrcLoc file (srcSpanEndLine span) (srcSpanEndCol span))
1170 -- -----------------------------------------------------------------------------
1171 -- Options, includes and language pragmas.
1173 lex_string_prag :: (String -> Token) -> Action
1174 lex_string_prag mkTok span _buf _len
1175 = do input <- getInput
1179 return (L (mkSrcSpan start end) tok)
1181 = if isString input "#-}"
1182 then do setInput input
1183 return (mkTok (reverse acc))
1184 else case alexGetChar input of
1185 Just (c,i) -> go (c:acc) i
1186 Nothing -> err input
1187 isString _ [] = True
1189 = case alexGetChar i of
1190 Just (c,i') | c == x -> isString i' xs
1192 err (AI end _ _) = failLocMsgP (srcSpanStart span) end "unterminated options pragma"
1195 -- -----------------------------------------------------------------------------
1198 -- This stuff is horrible. I hates it.
1200 lex_string_tok :: Action
1201 lex_string_tok span _buf _len = do
1202 tok <- lex_string ""
1204 return (L (mkSrcSpan (srcSpanStart span) end) tok)
1206 lex_string :: String -> P Token
1209 case alexGetChar' i of
1210 Nothing -> lit_error
1214 magicHash <- extension magicHashEnabled
1218 case alexGetChar' i of
1222 then failMsgP "primitive string literal must contain only characters <= \'\\xFF\'"
1223 else let s' = mkZFastString (reverse s) in
1224 return (ITprimstring s')
1225 -- mkZFastString is a hack to avoid encoding the
1226 -- string in UTF-8. We just want the exact bytes.
1228 return (ITstring (mkFastString (reverse s)))
1230 return (ITstring (mkFastString (reverse s)))
1233 | Just ('&',i) <- next -> do
1234 setInput i; lex_string s
1235 | Just (c,i) <- next, is_space c -> do
1236 setInput i; lex_stringgap s
1237 where next = alexGetChar' i
1243 lex_stringgap :: String -> P Token
1244 lex_stringgap s = do
1247 '\\' -> lex_string s
1248 c | is_space c -> lex_stringgap s
1252 lex_char_tok :: Action
1253 -- Here we are basically parsing character literals, such as 'x' or '\n'
1254 -- but, when Template Haskell is on, we additionally spot
1255 -- 'x and ''T, returning ITvarQuote and ITtyQuote respectively,
1256 -- but WIHTOUT CONSUMING the x or T part (the parser does that).
1257 -- So we have to do two characters of lookahead: when we see 'x we need to
1258 -- see if there's a trailing quote
1259 lex_char_tok span _buf _len = do -- We've seen '
1260 i1 <- getInput -- Look ahead to first character
1261 let loc = srcSpanStart span
1262 case alexGetChar' i1 of
1263 Nothing -> lit_error
1265 Just ('\'', i2@(AI end2 _ _)) -> do -- We've seen ''
1266 th_exts <- extension thEnabled
1269 return (L (mkSrcSpan loc end2) ITtyQuote)
1272 Just ('\\', i2@(AI _end2 _ _)) -> do -- We've seen 'backslash
1274 lit_ch <- lex_escape
1275 mc <- getCharOrFail -- Trailing quote
1276 if mc == '\'' then finish_char_tok loc lit_ch
1277 else do setInput i2; lit_error
1279 Just (c, i2@(AI _end2 _ _))
1280 | not (isAny c) -> lit_error
1283 -- We've seen 'x, where x is a valid character
1284 -- (i.e. not newline etc) but not a quote or backslash
1285 case alexGetChar' i2 of -- Look ahead one more character
1286 Just ('\'', i3) -> do -- We've seen 'x'
1288 finish_char_tok loc c
1289 _other -> do -- We've seen 'x not followed by quote
1290 -- (including the possibility of EOF)
1291 -- If TH is on, just parse the quote only
1292 th_exts <- extension thEnabled
1293 let (AI end _ _) = i1
1294 if th_exts then return (L (mkSrcSpan loc end) ITvarQuote)
1295 else do setInput i2; lit_error
1297 finish_char_tok :: SrcLoc -> Char -> P (Located Token)
1298 finish_char_tok loc ch -- We've already seen the closing quote
1299 -- Just need to check for trailing #
1300 = do magicHash <- extension magicHashEnabled
1301 i@(AI end _ _) <- getInput
1302 if magicHash then do
1303 case alexGetChar' i of
1304 Just ('#',i@(AI end _ _)) -> do
1306 return (L (mkSrcSpan loc end) (ITprimchar ch))
1308 return (L (mkSrcSpan loc end) (ITchar ch))
1310 return (L (mkSrcSpan loc end) (ITchar ch))
1312 lex_char :: Char -> AlexInput -> P Char
1315 '\\' -> do setInput inp; lex_escape
1316 c | isAny c -> do setInput inp; return c
1319 isAny :: Char -> Bool
1320 isAny c | c > '\x7f' = isPrint c
1321 | otherwise = is_any c
1323 lex_escape :: P Char
1337 '^' -> do c <- getCharOrFail
1338 if c >= '@' && c <= '_'
1339 then return (chr (ord c - ord '@'))
1342 'x' -> readNum is_hexdigit 16 hexDigit
1343 'o' -> readNum is_octdigit 8 octDecDigit
1344 x | is_decdigit x -> readNum2 is_decdigit 10 octDecDigit (octDecDigit x)
1348 case alexGetChar' i of
1349 Nothing -> lit_error
1351 case alexGetChar' i2 of
1352 Nothing -> do setInput i2; lit_error
1354 let str = [c1,c2,c3] in
1355 case [ (c,rest) | (p,c) <- silly_escape_chars,
1356 Just rest <- [maybePrefixMatch p str] ] of
1357 (escape_char,[]):_ -> do
1360 (escape_char,_:_):_ -> do
1365 readNum :: (Char -> Bool) -> Int -> (Char -> Int) -> P Char
1366 readNum is_digit base conv = do
1370 then readNum2 is_digit base conv (conv c)
1371 else do setInput i; lit_error
1373 readNum2 :: (Char -> Bool) -> Int -> (Char -> Int) -> Int -> P Char
1374 readNum2 is_digit base conv i = do
1377 where read i input = do
1378 case alexGetChar' input of
1379 Just (c,input') | is_digit c -> do
1380 read (i*base + conv c) input'
1382 if i >= 0 && i <= 0x10FFFF
1383 then do setInput input; return (chr i)
1386 silly_escape_chars :: [(String, Char)]
1387 silly_escape_chars = [
1424 -- before calling lit_error, ensure that the current input is pointing to
1425 -- the position of the error in the buffer. This is so that we can report
1426 -- a correct location to the user, but also so we can detect UTF-8 decoding
1427 -- errors if they occur.
1429 lit_error = lexError "lexical error in string/character literal"
1431 getCharOrFail :: P Char
1434 case alexGetChar' i of
1435 Nothing -> lexError "unexpected end-of-file in string/character literal"
1436 Just (c,i) -> do setInput i; return c
1438 -- -----------------------------------------------------------------------------
1441 lex_quasiquote_tok :: Action
1442 lex_quasiquote_tok span buf len = do
1443 let quoter = reverse $ takeWhile (/= '$')
1444 $ reverse $ lexemeToString buf (len - 1)
1445 quoteStart <- getSrcLoc
1446 quote <- lex_quasiquote ""
1448 return (L (mkSrcSpan (srcSpanStart span) end)
1449 (ITquasiQuote (mkFastString quoter,
1450 mkFastString (reverse quote),
1451 mkSrcSpan quoteStart end)))
1453 lex_quasiquote :: String -> P String
1454 lex_quasiquote s = do
1456 case alexGetChar' i of
1457 Nothing -> lit_error
1460 | Just ('|',i) <- next -> do
1461 setInput i; lex_quasiquote ('|' : s)
1462 | Just (']',i) <- next -> do
1463 setInput i; lex_quasiquote (']' : s)
1464 where next = alexGetChar' i
1467 | Just (']',i) <- next -> do
1468 setInput i; return s
1469 where next = alexGetChar' i
1472 setInput i; lex_quasiquote (c : s)
1474 -- -----------------------------------------------------------------------------
1477 warn :: DynFlag -> SDoc -> Action
1478 warn option warning srcspan _buf _len = do
1479 addWarning option srcspan warning
1482 warnThen :: DynFlag -> SDoc -> Action -> Action
1483 warnThen option warning action srcspan buf len = do
1484 addWarning option srcspan warning
1485 action srcspan buf len
1487 -- -----------------------------------------------------------------------------
1498 SrcSpan -- The start and end of the text span related to
1499 -- the error. Might be used in environments which can
1500 -- show this span, e.g. by highlighting it.
1501 Message -- The error message
1503 data PState = PState {
1504 buffer :: StringBuffer,
1506 messages :: Messages,
1507 last_loc :: SrcSpan, -- pos of previous token
1508 last_offs :: !Int, -- offset of the previous token from the
1509 -- beginning of the current line.
1510 -- \t is equal to 8 spaces.
1511 last_len :: !Int, -- len of previous token
1512 last_line_len :: !Int,
1513 loc :: SrcLoc, -- current loc (end of prev token + 1)
1514 extsBitmap :: !Int, -- bitmap that determines permitted extensions
1515 context :: [LayoutContext],
1518 -- last_loc and last_len are used when generating error messages,
1519 -- and in pushCurrentContext only. Sigh, if only Happy passed the
1520 -- current token to happyError, we could at least get rid of last_len.
1521 -- Getting rid of last_loc would require finding another way to
1522 -- implement pushCurrentContext (which is only called from one place).
1524 newtype P a = P { unP :: PState -> ParseResult a }
1526 instance Monad P where
1532 returnP a = a `seq` (P $ \s -> POk s a)
1534 thenP :: P a -> (a -> P b) -> P b
1535 (P m) `thenP` k = P $ \ s ->
1537 POk s1 a -> (unP (k a)) s1
1538 PFailed span err -> PFailed span err
1540 failP :: String -> P a
1541 failP msg = P $ \s -> PFailed (last_loc s) (text msg)
1543 failMsgP :: String -> P a
1544 failMsgP msg = P $ \s -> PFailed (last_loc s) (text msg)
1546 failLocMsgP :: SrcLoc -> SrcLoc -> String -> P a
1547 failLocMsgP loc1 loc2 str = P $ \_ -> PFailed (mkSrcSpan loc1 loc2) (text str)
1549 failSpanMsgP :: SrcSpan -> SDoc -> P a
1550 failSpanMsgP span msg = P $ \_ -> PFailed span msg
1552 extension :: (Int -> Bool) -> P Bool
1553 extension p = P $ \s -> POk s (p $! extsBitmap s)
1556 getExts = P $ \s -> POk s (extsBitmap s)
1558 setExts :: (Int -> Int) -> P ()
1559 setExts f = P $ \s -> POk s{ extsBitmap = f (extsBitmap s) } ()
1561 setSrcLoc :: SrcLoc -> P ()
1562 setSrcLoc new_loc = P $ \s -> POk s{loc=new_loc} ()
1564 getSrcLoc :: P SrcLoc
1565 getSrcLoc = P $ \s@(PState{ loc=loc }) -> POk s loc
1567 setLastToken :: SrcSpan -> Int -> Int -> P ()
1568 setLastToken loc len line_len = P $ \s -> POk s {
1571 last_line_len=line_len
1574 data AlexInput = AI SrcLoc {-#UNPACK#-}!Int StringBuffer
1576 alexInputPrevChar :: AlexInput -> Char
1577 alexInputPrevChar (AI _ _ buf) = prevChar buf '\n'
1579 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
1580 alexGetChar (AI loc ofs s)
1582 | otherwise = adj_c `seq` loc' `seq` ofs' `seq` s' `seq`
1583 --trace (show (ord c)) $
1584 Just (adj_c, (AI loc' ofs' s'))
1585 where (c,s') = nextChar s
1586 loc' = advanceSrcLoc loc c
1587 ofs' = advanceOffs c ofs
1595 other_graphic = '\x6'
1598 | c <= '\x06' = non_graphic
1600 -- Alex doesn't handle Unicode, so when Unicode
1601 -- character is encoutered we output these values
1602 -- with the actual character value hidden in the state.
1604 case generalCategory c of
1605 UppercaseLetter -> upper
1606 LowercaseLetter -> lower
1607 TitlecaseLetter -> upper
1608 ModifierLetter -> other_graphic
1609 OtherLetter -> lower -- see #1103
1610 NonSpacingMark -> other_graphic
1611 SpacingCombiningMark -> other_graphic
1612 EnclosingMark -> other_graphic
1613 DecimalNumber -> digit
1614 LetterNumber -> other_graphic
1615 OtherNumber -> other_graphic
1616 ConnectorPunctuation -> symbol
1617 DashPunctuation -> symbol
1618 OpenPunctuation -> other_graphic
1619 ClosePunctuation -> other_graphic
1620 InitialQuote -> other_graphic
1621 FinalQuote -> other_graphic
1622 OtherPunctuation -> symbol
1623 MathSymbol -> symbol
1624 CurrencySymbol -> symbol
1625 ModifierSymbol -> symbol
1626 OtherSymbol -> symbol
1628 _other -> non_graphic
1630 -- This version does not squash unicode characters, it is used when
1632 alexGetChar' :: AlexInput -> Maybe (Char,AlexInput)
1633 alexGetChar' (AI loc ofs s)
1635 | otherwise = c `seq` loc' `seq` ofs' `seq` s' `seq`
1636 --trace (show (ord c)) $
1637 Just (c, (AI loc' ofs' s'))
1638 where (c,s') = nextChar s
1639 loc' = advanceSrcLoc loc c
1640 ofs' = advanceOffs c ofs
1642 advanceOffs :: Char -> Int -> Int
1643 advanceOffs '\n' _ = 0
1644 advanceOffs '\t' offs = (offs `quot` 8 + 1) * 8
1645 advanceOffs _ offs = offs + 1
1647 getInput :: P AlexInput
1648 getInput = P $ \s@PState{ loc=l, last_offs=o, buffer=b } -> POk s (AI l o b)
1650 setInput :: AlexInput -> P ()
1651 setInput (AI l o b) = P $ \s -> POk s{ loc=l, last_offs=o, buffer=b } ()
1653 pushLexState :: Int -> P ()
1654 pushLexState ls = P $ \s@PState{ lex_state=l } -> POk s{lex_state=ls:l} ()
1656 popLexState :: P Int
1657 popLexState = P $ \s@PState{ lex_state=ls:l } -> POk s{ lex_state=l } ls
1659 getLexState :: P Int
1660 getLexState = P $ \s@PState{ lex_state=ls:_ } -> POk s ls
1662 -- for reasons of efficiency, flags indicating language extensions (eg,
1663 -- -fglasgow-exts or -XParr) are represented by a bitmap stored in an unboxed
1667 genericsBit = 0 -- {| and |}
1678 explicitForallBit :: Int
1679 explicitForallBit = 7 -- the 'forall' keyword and '.' symbol
1681 bangPatBit = 8 -- Tells the parser to understand bang-patterns
1682 -- (doesn't affect the lexer)
1684 tyFamBit = 9 -- indexed type families: 'family' keyword and kind sigs
1686 haddockBit = 10 -- Lex and parse Haddock comments
1688 magicHashBit = 11 -- "#" in both functions and operators
1690 kindSigsBit = 12 -- Kind signatures on type variables
1691 recursiveDoBit :: Int
1692 recursiveDoBit = 13 -- mdo
1693 unicodeSyntaxBit :: Int
1694 unicodeSyntaxBit = 14 -- the forall symbol, arrow symbols, etc
1695 unboxedTuplesBit :: Int
1696 unboxedTuplesBit = 15 -- (# and #)
1697 standaloneDerivingBit :: Int
1698 standaloneDerivingBit = 16 -- standalone instance deriving declarations
1699 transformComprehensionsBit :: Int
1700 transformComprehensionsBit = 17
1702 qqBit = 18 -- enable quasiquoting
1703 inRulePragBit :: Int
1705 rawTokenStreamBit :: Int
1706 rawTokenStreamBit = 20 -- producing a token stream with all comments included
1707 newQualOpsBit :: Int
1708 newQualOpsBit = 21 -- Haskell' qualified operator syntax, e.g. Prelude.(+)
1710 always :: Int -> Bool
1712 genericsEnabled :: Int -> Bool
1713 genericsEnabled flags = testBit flags genericsBit
1714 parrEnabled :: Int -> Bool
1715 parrEnabled flags = testBit flags parrBit
1716 arrowsEnabled :: Int -> Bool
1717 arrowsEnabled flags = testBit flags arrowsBit
1718 thEnabled :: Int -> Bool
1719 thEnabled flags = testBit flags thBit
1720 ipEnabled :: Int -> Bool
1721 ipEnabled flags = testBit flags ipBit
1722 explicitForallEnabled :: Int -> Bool
1723 explicitForallEnabled flags = testBit flags explicitForallBit
1724 bangPatEnabled :: Int -> Bool
1725 bangPatEnabled flags = testBit flags bangPatBit
1726 -- tyFamEnabled :: Int -> Bool
1727 -- tyFamEnabled flags = testBit flags tyFamBit
1728 haddockEnabled :: Int -> Bool
1729 haddockEnabled flags = testBit flags haddockBit
1730 magicHashEnabled :: Int -> Bool
1731 magicHashEnabled flags = testBit flags magicHashBit
1732 -- kindSigsEnabled :: Int -> Bool
1733 -- kindSigsEnabled flags = testBit flags kindSigsBit
1734 unicodeSyntaxEnabled :: Int -> Bool
1735 unicodeSyntaxEnabled flags = testBit flags unicodeSyntaxBit
1736 unboxedTuplesEnabled :: Int -> Bool
1737 unboxedTuplesEnabled flags = testBit flags unboxedTuplesBit
1738 standaloneDerivingEnabled :: Int -> Bool
1739 standaloneDerivingEnabled flags = testBit flags standaloneDerivingBit
1740 qqEnabled :: Int -> Bool
1741 qqEnabled flags = testBit flags qqBit
1742 -- inRulePrag :: Int -> Bool
1743 -- inRulePrag flags = testBit flags inRulePragBit
1744 rawTokenStreamEnabled :: Int -> Bool
1745 rawTokenStreamEnabled flags = testBit flags rawTokenStreamBit
1746 newQualOps :: Int -> Bool
1747 newQualOps flags = testBit flags newQualOpsBit
1748 oldQualOps :: Int -> Bool
1749 oldQualOps flags = not (newQualOps flags)
1751 -- PState for parsing options pragmas
1753 pragState :: DynFlags -> StringBuffer -> SrcLoc -> PState
1754 pragState dynflags buf loc =
1757 messages = emptyMessages,
1759 last_loc = mkSrcSpan loc loc,
1766 lex_state = [bol, option_prags, 0]
1770 -- create a parse state
1772 mkPState :: StringBuffer -> SrcLoc -> DynFlags -> PState
1773 mkPState buf loc flags =
1777 messages = emptyMessages,
1778 last_loc = mkSrcSpan loc loc,
1783 extsBitmap = fromIntegral bitmap,
1785 lex_state = [bol, 0]
1786 -- we begin in the layout state if toplev_layout is set
1789 bitmap = genericsBit `setBitIf` dopt Opt_Generics flags
1790 .|. ffiBit `setBitIf` dopt Opt_ForeignFunctionInterface flags
1791 .|. parrBit `setBitIf` dopt Opt_PArr flags
1792 .|. arrowsBit `setBitIf` dopt Opt_Arrows flags
1793 .|. thBit `setBitIf` dopt Opt_TemplateHaskell flags
1794 .|. qqBit `setBitIf` dopt Opt_QuasiQuotes flags
1795 .|. ipBit `setBitIf` dopt Opt_ImplicitParams flags
1796 .|. explicitForallBit `setBitIf` dopt Opt_ScopedTypeVariables flags
1797 .|. explicitForallBit `setBitIf` dopt Opt_LiberalTypeSynonyms flags
1798 .|. explicitForallBit `setBitIf` dopt Opt_PolymorphicComponents flags
1799 .|. explicitForallBit `setBitIf` dopt Opt_ExistentialQuantification flags
1800 .|. explicitForallBit `setBitIf` dopt Opt_Rank2Types flags
1801 .|. explicitForallBit `setBitIf` dopt Opt_RankNTypes flags
1802 .|. bangPatBit `setBitIf` dopt Opt_BangPatterns flags
1803 .|. tyFamBit `setBitIf` dopt Opt_TypeFamilies flags
1804 .|. haddockBit `setBitIf` dopt Opt_Haddock flags
1805 .|. magicHashBit `setBitIf` dopt Opt_MagicHash flags
1806 .|. kindSigsBit `setBitIf` dopt Opt_KindSignatures flags
1807 .|. recursiveDoBit `setBitIf` dopt Opt_RecursiveDo flags
1808 .|. unicodeSyntaxBit `setBitIf` dopt Opt_UnicodeSyntax flags
1809 .|. unboxedTuplesBit `setBitIf` dopt Opt_UnboxedTuples flags
1810 .|. standaloneDerivingBit `setBitIf` dopt Opt_StandaloneDeriving flags
1811 .|. transformComprehensionsBit `setBitIf` dopt Opt_TransformListComp flags
1812 .|. rawTokenStreamBit `setBitIf` dopt Opt_KeepRawTokenStream flags
1813 .|. newQualOpsBit `setBitIf` dopt Opt_NewQualifiedOperators flags
1815 setBitIf :: Int -> Bool -> Int
1816 b `setBitIf` cond | cond = bit b
1819 addWarning :: DynFlag -> SrcSpan -> SDoc -> P ()
1820 addWarning option srcspan warning
1821 = P $ \s@PState{messages=(ws,es), dflags=d} ->
1822 let warning' = mkWarnMsg srcspan alwaysQualify warning
1823 ws' = if dopt option d then ws `snocBag` warning' else ws
1824 in POk s{messages=(ws', es)} ()
1826 getMessages :: PState -> Messages
1827 getMessages PState{messages=ms} = ms
1829 getContext :: P [LayoutContext]
1830 getContext = P $ \s@PState{context=ctx} -> POk s ctx
1832 setContext :: [LayoutContext] -> P ()
1833 setContext ctx = P $ \s -> POk s{context=ctx} ()
1836 popContext = P $ \ s@(PState{ buffer = buf, context = ctx,
1837 last_len = len, last_loc = last_loc }) ->
1839 (_:tl) -> POk s{ context = tl } ()
1840 [] -> PFailed last_loc (srcParseErr buf len)
1842 -- Push a new layout context at the indentation of the last token read.
1843 -- This is only used at the outer level of a module when the 'module'
1844 -- keyword is missing.
1845 pushCurrentContext :: P ()
1846 pushCurrentContext = P $ \ s@PState{ last_offs=offs, last_line_len=len, context=ctx } ->
1847 POk s{context = Layout (offs-len) : ctx} ()
1848 --trace ("off: " ++ show offs ++ ", len: " ++ show len) $ POk s{context = Layout (offs-len) : ctx} ()
1850 getOffside :: P Ordering
1851 getOffside = P $ \s@PState{last_offs=offs, context=stk} ->
1852 let ord = case stk of
1853 (Layout n:_) -> compare offs n
1857 -- ---------------------------------------------------------------------------
1858 -- Construct a parse error
1861 :: StringBuffer -- current buffer (placed just after the last token)
1862 -> Int -- length of the previous token
1865 = hcat [ if null token
1866 then ptext (sLit "parse error (possibly incorrect indentation)")
1867 else hcat [ptext (sLit "parse error on input "),
1868 char '`', text token, char '\'']
1870 where token = lexemeToString (offsetBytes (-len) buf) len
1872 -- Report a parse failure, giving the span of the previous token as
1873 -- the location of the error. This is the entry point for errors
1874 -- detected during parsing.
1876 srcParseFail = P $ \PState{ buffer = buf, last_len = len,
1877 last_loc = last_loc } ->
1878 PFailed last_loc (srcParseErr buf len)
1880 -- A lexical error is reported at a particular position in the source file,
1881 -- not over a token range.
1882 lexError :: String -> P a
1885 (AI end _ buf) <- getInput
1886 reportLexError loc end buf str
1888 -- -----------------------------------------------------------------------------
1889 -- This is the top-level function: called from the parser each time a
1890 -- new token is to be read from the input.
1892 lexer :: (Located Token -> P a) -> P a
1894 tok@(L _span _tok__) <- lexToken
1895 -- trace ("token: " ++ show tok__) $ do
1898 lexToken :: P (Located Token)
1900 inp@(AI loc1 _ buf) <- getInput
1903 case alexScanUser exts inp sc of
1905 let span = mkSrcSpan loc1 loc1
1906 setLastToken span 0 0
1907 return (L span ITeof)
1908 AlexError (AI loc2 _ buf) ->
1909 reportLexError loc1 loc2 buf "lexical error"
1910 AlexSkip inp2 _ -> do
1913 AlexToken inp2@(AI end _ buf2) _ t -> do
1915 let span = mkSrcSpan loc1 end
1916 let bytes = byteDiff buf buf2
1917 span `seq` setLastToken span bytes bytes
1920 reportLexError :: SrcLoc -> SrcLoc -> StringBuffer -> [Char] -> P a
1921 reportLexError loc1 loc2 buf str
1922 | atEnd buf = failLocMsgP loc1 loc2 (str ++ " at end of input")
1925 c = fst (nextChar buf)
1927 if c == '\0' -- decoding errors are mapped to '\0', see utf8DecodeChar#
1928 then failLocMsgP loc2 loc2 (str ++ " (UTF-8 decoding error)")
1929 else failLocMsgP loc1 loc2 (str ++ " at character " ++ show c)
1931 lexTokenStream :: StringBuffer -> SrcLoc -> DynFlags -> ParseResult [Located Token]
1932 lexTokenStream buf loc dflags = unP go initState
1933 where initState = mkPState buf loc (dopt_set (dopt_unset dflags Opt_Haddock) Opt_KeepRawTokenStream)
1935 ltok <- lexer return
1937 L _ ITeof -> return []
1938 _ -> liftM (ltok:) go