Lexer.x 135 KB
Newer Older
1
-----------------------------------------------------------------------------
2
-- (c) The University of Glasgow, 2006
3
--
4
-- GHC's lexer for Haskell 2010 [1].
5
--
6 7
-- This is a combination of an Alex-generated lexer [2] from a regex
-- definition, with some hand-coded bits. [3]
8 9
--
-- Completely accurate information about token-spans within the source
Ian Lynagh's avatar
Ian Lynagh committed
10 11
-- file is maintained.  Every token has a start and end RealSrcLoc
-- attached to it.
12
--
13 14 15
-- References:
-- [1] https://www.haskell.org/onlinereport/haskell2010/haskellch2.html
-- [2] http://www.haskell.org/alex/
16
-- [3] https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/parser
17
--
18 19 20 21 22 23 24 25 26 27
-----------------------------------------------------------------------------

--   ToDo / known bugs:
--    - parsing integers is a bit slow
--    - readRational is a bit slow
--
--   Known bugs, that were also in the previous version:
--    - M... should be 3 tokens, not 1.
--    - pragma-end should be only valid in a pragma

28
--   qualified operator NOTES.
Ian Lynagh's avatar
Ian Lynagh committed
29
--
30 31 32 33 34 35 36 37 38
--   - If M.(+) is a single lexeme, then..
--     - Probably (+) should be a single lexeme too, for consistency.
--       Otherwise ( + ) would be a prefix operator, but M.( + ) would not be.
--     - But we have to rule out reserved operators, otherwise (..) becomes
--       a different lexeme.
--     - Should we therefore also rule out reserved operators in the qualified
--       form?  This is quite difficult to achieve.  We don't do it for
--       qualified varids.

39 40 41 42

-- -----------------------------------------------------------------------------
-- Alex "Haskell code fragment top"

43
{
44
{-# LANGUAGE BangPatterns #-}
45
{-# LANGUAGE LambdaCase #-}
46
{-# LANGUAGE MultiWayIf #-}
47

48
{-# OPTIONS_GHC -funbox-strict-fields #-}
49
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
50

Sylvain Henry's avatar
Sylvain Henry committed
51
module GHC.Parser.Lexer (
52
   Token(..), lexer, lexerDbg, pragState, mkPState, mkPStatePure, PState(..),
Vladislav Zavialov's avatar
Vladislav Zavialov committed
53 54 55 56
   P(..), ParseResult(..), mkParserFlags, mkParserFlags', ParserFlags(..),
   appendWarning,
   appendError,
   allocateComments,
57
   MonadP(..),
Sylvain Henry's avatar
Sylvain Henry committed
58
   getRealSrcLoc, getPState, withHomeUnitId,
59
   failMsgP, failLocMsgP, srcParseFail,
60
   getErrorMessages, getMessages,
61
   popContext, pushModuleContext, setLastToken, setSrcLoc,
vivian's avatar
vivian committed
62
   activeContext, nextIsEOF,
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
63
   getLexState, popLexState, pushLexState,
64
   ExtBits(..),
Vladislav Zavialov's avatar
Vladislav Zavialov committed
65
   xtest,
Alan Zimmerman's avatar
Alan Zimmerman committed
66
   lexTokenStream,
Vladislav Zavialov's avatar
Vladislav Zavialov committed
67 68
   AddAnn(..),mkParensApiAnn,
   addAnnsAt,
69 70
   commentToAnnotation,
   HdkComment(..),
71 72
  ) where

73
import GHC.Prelude
74

rodlogic's avatar
rodlogic committed
75 76 77
-- base
import Control.Monad
import Data.Bits
78
import Data.Char
rodlogic's avatar
rodlogic committed
79 80 81 82
import Data.List
import Data.Maybe
import Data.Word

83
import GHC.Data.EnumSet as EnumSet
84

85 86 87
-- ghc-boot
import qualified GHC.LanguageExtensions as LangExt

rodlogic's avatar
rodlogic committed
88 89 90 91 92 93 94 95
-- bytestring
import Data.ByteString (ByteString)

-- containers
import Data.Map (Map)
import qualified Data.Map as Map

-- compiler/utils
96 97 98 99
import GHC.Data.Bag
import GHC.Utils.Outputable
import GHC.Data.StringBuffer
import GHC.Data.FastString
Sylvain Henry's avatar
Sylvain Henry committed
100
import GHC.Types.Unique.FM
101 102
import GHC.Data.Maybe
import GHC.Data.OrdList
103
import GHC.Utils.Misc ( readRational, readHexRational )
rodlogic's avatar
rodlogic committed
104 105

-- compiler/main
106
import GHC.Utils.Error
Sylvain Henry's avatar
Sylvain Henry committed
107
import GHC.Driver.Session as DynFlags
rodlogic's avatar
rodlogic committed
108 109

-- compiler/basicTypes
Sylvain Henry's avatar
Sylvain Henry committed
110
import GHC.Types.SrcLoc
Sylvain Henry's avatar
Sylvain Henry committed
111
import GHC.Unit
Sylvain Henry's avatar
Sylvain Henry committed
112 113 114
import GHC.Types.Basic ( InlineSpec(..), RuleMatchInfo(..),
                         IntegralLit(..), FractionalLit(..),
                         SourceText(..) )
115
import GHC.Hs.Doc
116

rodlogic's avatar
rodlogic committed
117
-- compiler/parser
Sylvain Henry's avatar
Sylvain Henry committed
118
import GHC.Parser.CharClass
Alan Zimmerman's avatar
Alan Zimmerman committed
119

Sylvain Henry's avatar
Sylvain Henry committed
120
import GHC.Parser.Annotation
121 122
}

123 124 125
-- -----------------------------------------------------------------------------
-- Alex "Character set macros"

126
-- NB: The logic behind these definitions is also reflected in "GHC.Utils.Lexeme"
127
-- Any changes here should likely be reflected there.
128
$unispace    = \x05 -- Trick Alex into handling Unicode. See [Unicode in Alex].
129 130 131
$nl          = [\n\r\f]
$whitechar   = [$nl\v\ $unispace]
$white_no_nl = $whitechar # \n -- TODO #8424
132
$tab         = \t
133 134

$ascdigit  = 0-9
135
$unidigit  = \x03 -- Trick Alex into handling Unicode. See [Unicode in Alex].
136
$decdigit  = $ascdigit -- for now, should really be $digit (ToDo)
137 138 139
$digit     = [$ascdigit $unidigit]

$special   = [\(\)\,\;\[\]\`\{\}]
140
$ascsymbol = [\!\#\$\%\&\*\+\.\/\<\=\>\?\@\\\^\|\-\~\:]
141
$unisymbol = \x04 -- Trick Alex into handling Unicode. See [Unicode in Alex].
142
$symbol    = [$ascsymbol $unisymbol] # [$special \_\"\']
143

144
$unilarge  = \x01 -- Trick Alex into handling Unicode. See [Unicode in Alex].
145
$asclarge  = [A-Z]
146 147
$large     = [$asclarge $unilarge]

148
$unismall  = \x02 -- Trick Alex into handling Unicode. See [Unicode in Alex].
149
$ascsmall  = [a-z]
150 151
$small     = [$ascsmall $unismall \_]

152
$unigraphic = \x06 -- Trick Alex into handling Unicode. See [Unicode in Alex].
153
$graphic   = [$small $large $symbol $digit $special $unigraphic \"\']
154

155
$binit     = 0-1
Ian Lynagh's avatar
Ian Lynagh committed
156
$octit     = 0-7
157
$hexit     = [$decdigit A-F a-f]
158

159
$uniidchar = \x07 -- Trick Alex into handling Unicode. See [Unicode in Alex].
160
$idchar    = [$small $large $digit $uniidchar \']
161

162 163
$pragmachar = [$small $large $digit]

164 165
$docsym    = [\| \^ \* \$]

166

167 168 169 170 171 172 173 174
-- -----------------------------------------------------------------------------
-- Alex "Regular expression macros"

@varid     = $small $idchar*          -- variable identifiers
@conid     = $large $idchar*          -- constructor identifiers

@varsym    = ($symbol # \:) $symbol*  -- variable (operator) symbol
@consym    = \: $symbol*              -- constructor (operator) symbol
175

176 177 178 179 180 181 182 183
-- See Note [Lexing NumericUnderscores extension] and #14473
@numspc       = _*                   -- numeric spacer (#14473)
@decimal      = $decdigit(@numspc $decdigit)*
@binary       = $binit(@numspc $binit)*
@octal        = $octit(@numspc $octit)*
@hexadecimal  = $hexit(@numspc $hexit)*
@exponent     = @numspc [eE] [\-\+]? @decimal
@bin_exponent = @numspc [pP] [\-\+]? @decimal
184 185

@qual = (@conid \.)+
186 187 188 189
@qvarid = @qual @varid
@qconid = @qual @conid
@qvarsym = @qual @varsym
@qconsym = @qual @consym
190

191 192 193 194 195
-- QualifiedDo needs to parse "M.do" not as a variable, so as to keep the
-- layout rules.
@qdo    = @qual "do"
@qmdo   = @qual "mdo"

196 197
@floating_point = @numspc @decimal \. @decimal @exponent? | @numspc @decimal @exponent
@hex_floating_point = @numspc @hexadecimal \. @hexadecimal @bin_exponent? | @numspc @hexadecimal @bin_exponent
198

199 200 201 202
-- normal signed numerical literals can only be explicitly negative,
-- not explicitly positive (contrast @exponent)
@negative = \-

203 204 205 206

-- -----------------------------------------------------------------------------
-- Alex "Identifier"

207 208
haskell :-

209 210 211 212 213

-- -----------------------------------------------------------------------------
-- Alex "Rules"

-- everywhere: skip whitespace
Ian Lynagh's avatar
Ian Lynagh committed
214
$white_no_nl+ ;
215
$tab          { warnTab }
216 217 218 219 220

-- Everywhere: deal with nested comments.  We explicitly rule out
-- pragmas, "{-#", so that we don't accidentally treat them as comments.
-- (this can happen even though pragmas will normally take precedence due to
-- longest-match, because pragmas aren't valid in every state, but comments
221 222 223 224
-- are). We also rule out nested Haddock comments, if the -haddock flag is
-- set.

"{-" / { isNormalComment } { nested_comment lexToken }
225 226 227 228

-- Single-line comments are a bit tricky.  Haskell 98 says that two or
-- more dashes followed by a symbol should be parsed as a varsym, so we
-- have to exclude those.
229 230

-- Since Haddock comments aren't valid in every state, we need to rule them
Ian Lynagh's avatar
Ian Lynagh committed
231
-- out here.
232 233 234 235 236 237 238

-- The following two rules match comments that begin with two dashes, but
-- continue with a different character. The rules test that this character
-- is not a symbol (in which case we'd have a varsym), and that it's not a
-- space followed by a Haddock comment symbol (docsym) (in which case we'd
-- have a Haddock comment). The rules then munch the rest of the line.

239
"-- " ~$docsym .* { lineCommentToken }
240
"--" [^$symbol \ ] .* { lineCommentToken }
241 242 243

-- Next, match Haddock comments if no -haddock flag

244
"-- " $docsym .* / { alexNotPred (ifExtension HaddockBit) } { lineCommentToken }
245 246 247 248 249 250 251

-- Now, when we've matched comments that begin with 2 dashes and continue
-- with a different character, we need to match comments that begin with three
-- or more dashes (which clearly can't be Haddock comments). We only need to
-- make sure that the first non-dash character isn't a symbol, and munch the
-- rest of the line.

252
"---"\-* ~$symbol .* { lineCommentToken }
253 254 255 256

-- Since the previous rules all match dashes followed by at least one
-- character, we also need to match a whole line filled with just dashes.

Jedai's avatar
Jedai committed
257
"--"\-* / { atEOL } { lineCommentToken }
258 259 260 261

-- We need this rule since none of the other single line comment rules
-- actually match this case.

Jedai's avatar
Jedai committed
262
"-- " / { atEOL } { lineCommentToken }
263 264 265 266 267 268 269 270 271 272 273

-- 'bol' state: beginning of a line.  Slurp up all the whitespace (including
-- blank lines) until we find a non-whitespace character, then do layout
-- processing.
--
-- One slight wibble here: what if the line begins with {-#? In
-- theory, we have to lex the pragma to see if it's one we recognise,
-- and if it is, then we backtrack and do_bol, otherwise we treat it
-- as a nested comment.  We don't bother with this: if the line begins
-- with {-#, then we'll assume it's a pragma we know about and go for do_bol.
<bol> {
Ian Lynagh's avatar
Ian Lynagh committed
274
  \n                                    ;
Adam Gundry's avatar
Adam Gundry committed
275 276
  ^\# line                              { begin line_prag1 }
  ^\# / { followedByDigit }             { begin line_prag1 }
Ian Lynagh's avatar
Ian Lynagh committed
277 278 279
  ^\# pragma .* \n                      ; -- GCC 3.3 CPP generated, apparently
  ^\# \! .* \n                          ; -- #!, for scripts
  ()                                    { do_bol }
280 281 282 283 284
}

-- after a layout keyword (let, where, do, of), we begin a new layout
-- context if the curly brace is missing.
-- Careful! This stuff is quite delicate.
285
<layout, layout_do, layout_if> {
Ian Lynagh's avatar
Ian Lynagh committed
286 287 288 289
  \{ / { notFollowedBy '-' }            { hopefully_open_brace }
        -- we might encounter {-# here, but {- has been handled already
  \n                                    ;
  ^\# (line)?                           { begin line_prag1 }
290 291
}

292 293
-- after an 'if', a vertical bar starts a layout context for MultiWayIf
<layout_if> {
294
  \| / { notFollowedBySymbol }          { new_layout_context True dontGenerateSemic ITvbar }
295 296 297
  ()                                    { pop }
}

298
-- do is treated in a subtly different way, see new_layout_context
299 300
<layout>    ()                          { new_layout_context True  generateSemic ITvocurly }
<layout_do> ()                          { new_layout_context False generateSemic ITvocurly }
301 302 303 304

-- after a new layout context which was found to be to the left of the
-- previous context, we have generated a '{' token, and we now need to
-- generate a matching '}' token.
Ian Lynagh's avatar
Ian Lynagh committed
305
<layout_left>  ()                       { do_layout_left }
306

Ian Lynagh's avatar
Ian Lynagh committed
307
<0,option_prags> \n                     { begin bol }
308

309 310
"{-#" $whitechar* $pragmachar+ / { known_pragma linePrags }
                                { dispatch_pragmas linePrags }
311 312 313

-- single-line line pragmas, of the form
--    # <line> "<file>" <extra-stuff> \n
314 315 316 317 318
<line_prag1> {
  @decimal $white_no_nl+ \" [$graphic \ ]* \"  { setLineAndFile line_prag1a }
  ()                                           { failLinePrag1 }
}
<line_prag1a> .*                               { popLinePrag1 }
319 320 321

-- Haskell-style line pragmas, of the form
--    {-# LINE <line> "<file>" #-}
322 323 324 325
<line_prag2> {
  @decimal $white_no_nl+ \" [$graphic \ ]* \"  { setLineAndFile line_prag2a }
}
<line_prag2a> "#-}"|"-}"                       { pop }
326 327
   -- NOTE: accept -} at the end of a LINE pragma, for compatibility
   -- with older versions of GHC which generated these.
328

Rufflewind's avatar
Rufflewind committed
329 330 331 332
-- Haskell-style column pragmas, of the form
--    {-# COLUMN <column> #-}
<column_prag> @decimal $whitechar* "#-}" { setColumn }

333
<0,option_prags> {
Ian Lynagh's avatar
Ian Lynagh committed
334
  "{-#" $whitechar* $pragmachar+
335 336 337 338 339
        $whitechar+ $pragmachar+ / { known_pragma twoWordPrags }
                                 { dispatch_pragmas twoWordPrags }

  "{-#" $whitechar* $pragmachar+ / { known_pragma oneWordPrags }
                                 { dispatch_pragmas oneWordPrags }
340

341
  -- We ignore all these pragmas, but don't generate a warning for them
342 343
  "{-#" $whitechar* $pragmachar+ / { known_pragma ignoredPrags }
                                 { dispatch_pragmas ignoredPrags }
344 345

  -- ToDo: should only be valid inside a pragma:
Ian Lynagh's avatar
Ian Lynagh committed
346
  "#-}"                          { endPrag }
347 348
}

349
<option_prags> {
350 351
  "{-#"  $whitechar* $pragmachar+ / { known_pragma fileHeaderPrags }
                                   { dispatch_pragmas fileHeaderPrags }
David Waern's avatar
David Waern committed
352 353
}

354 355
<0> {
  -- In the "0" mode we ignore these pragmas
356
  "{-#"  $whitechar* $pragmachar+ / { known_pragma fileHeaderPrags }
357 358 359
                     { nested_comment lexToken }
}

360
<0,option_prags> {
361 362
  "{-#"  { warnThen Opt_WarnUnrecognisedPragmas (text "Unrecognised pragma")
                    (nested_comment lexToken) }
363 364
}

365 366
-- '0' state: ordinary lexemes

367 368
-- Haddock comments

369 370
"-- " $docsym      / { ifExtension HaddockBit } { multiline_doc_comment }
"{-" \ ? $docsym   / { ifExtension HaddockBit } { nested_doc_comment }
371

372 373
-- "special" symbols

374
<0> {
375 376 377 378 379 380 381 382 383

  -- Don't check ThQuotesBit here as the renamer can produce a better
  -- error message than the lexer (see the thQuotesEnabled check in rnBracket).
  "[|"  { token (ITopenExpQuote NoE NormalSyntax) }
  "[||" { token (ITopenTExpQuote NoE) }
  "|]"  { token (ITcloseQuote NormalSyntax) }
  "||]" { token ITcloseTExpQuote }

  -- Check ThQuotesBit here as to not steal syntax.
384 385 386 387 388 389 390
  "[e|"       / { ifExtension ThQuotesBit } { token (ITopenExpQuote HasE NormalSyntax) }
  "[e||"      / { ifExtension ThQuotesBit } { token (ITopenTExpQuote HasE) }
  "[p|"       / { ifExtension ThQuotesBit } { token ITopenPatQuote }
  "[d|"       / { ifExtension ThQuotesBit } { layout_token ITopenDecQuote }
  "[t|"       / { ifExtension ThQuotesBit } { token ITopenTypQuote }

  "[" @varid "|"  / { ifExtension QqBit }   { lex_quasiquote_tok }
391 392

  -- qualified quasi-quote (#5555)
393
  "[" @qvarid "|"  / { ifExtension QqBit }  { lex_qquasiquote_tok }
394 395 396

  $unigraphic -- ⟦
    / { ifCurrentChar '⟦' `alexAndPred`
397 398
        ifExtension UnicodeSyntaxBit `alexAndPred`
        ifExtension ThQuotesBit }
399 400 401
    { token (ITopenExpQuote NoE UnicodeSyntax) }
  $unigraphic -- ⟧
    / { ifCurrentChar '⟧' `alexAndPred`
402 403
        ifExtension UnicodeSyntaxBit `alexAndPred`
        ifExtension ThQuotesBit }
404
    { token (ITcloseQuote UnicodeSyntax) }
405 406
}

407
<0> {
408 409 410 411 412 413 414
  "(|"
    / { ifExtension ArrowsBit `alexAndPred`
        notFollowedBySymbol }
    { special (IToparenbar NormalSyntax) }
  "|)"
    / { ifExtension ArrowsBit }
    { special (ITcparenbar NormalSyntax) }
415 416 417

  $unigraphic -- ⦇
    / { ifCurrentChar '⦇' `alexAndPred`
418 419
        ifExtension UnicodeSyntaxBit `alexAndPred`
        ifExtension ArrowsBit }
420 421 422
    { special (IToparenbar UnicodeSyntax) }
  $unigraphic -- ⦈
    / { ifCurrentChar '⦈' `alexAndPred`
423 424
        ifExtension UnicodeSyntaxBit `alexAndPred`
        ifExtension ArrowsBit }
425
    { special (ITcparenbar UnicodeSyntax) }
426 427
}

428
<0> {
429
  \? @varid / { ifExtension IpBit } { skip_one_varid ITdupipvarid }
430 431
}

Adam Gundry's avatar
Adam Gundry committed
432
<0> {
433
  "#" @varid / { ifExtension OverloadedLabelsBit } { skip_one_varid ITlabelvarid }
Adam Gundry's avatar
Adam Gundry committed
434 435
}

436
<0> {
437 438
  "(#" / { ifExtension UnboxedTuplesBit `alexOrPred`
           ifExtension UnboxedSumsBit }
Ian Lynagh's avatar
Ian Lynagh committed
439
         { token IToubxparen }
440 441
  "#)" / { ifExtension UnboxedTuplesBit `alexOrPred`
           ifExtension UnboxedSumsBit }
Ian Lynagh's avatar
Ian Lynagh committed
442 443 444
         { token ITcubxparen }
}

445
<0,option_prags> {
Ian Lynagh's avatar
Ian Lynagh committed
446 447 448 449 450 451 452 453 454 455
  \(                                    { special IToparen }
  \)                                    { special ITcparen }
  \[                                    { special ITobrack }
  \]                                    { special ITcbrack }
  \,                                    { special ITcomma }
  \;                                    { special ITsemi }
  \`                                    { special ITbackquote }

  \{                                    { open_brace }
  \}                                    { close_brace }
456 457
}

458
<0,option_prags> {
459 460
  @qdo                                      { qdo_token ITdo }
  @qmdo    / { ifExtension RecursiveDoBit } { qdo_token ITmdo }
461 462
  @qvarid                       { idtoken qvarid }
  @qconid                       { idtoken qconid }
Ian Lynagh's avatar
Ian Lynagh committed
463
  @varid                        { varid }
464
  @conid                        { idtoken conid }
465 466
}

467
<0> {
468 469 470 471
  @qvarid "#"+      / { ifExtension MagicHashBit } { idtoken qvarid }
  @qconid "#"+      / { ifExtension MagicHashBit } { idtoken qconid }
  @varid "#"+       / { ifExtension MagicHashBit } { varid }
  @conid "#"+       / { ifExtension MagicHashBit } { idtoken conid }
472 473
}

474 475 476 477 478 479 480 481 482
-- Operators classified into prefix, suffix, tight infix, and loose infix.
-- See Note [Whitespace-sensitive operator parsing]
<0> {
  @varsym / { precededByClosingToken `alexAndPred` followedByOpeningToken } { varsym_tight_infix }
  @varsym / { followedByOpeningToken }  { varsym_prefix }
  @varsym / { precededByClosingToken }  { varsym_suffix }
  @varsym                               { varsym_loose_infix }
}

483 484
-- ToDo: - move `var` and (sym) into lexical syntax?
--       - remove backquote from $special?
485
<0> {
486 487
  @qvarsym                                         { idtoken qvarsym }
  @qconsym                                         { idtoken qconsym }
488
  @consym                                          { consym }
489 490
}

491 492
-- For the normal boxed literals we need to be careful
-- when trying to be close to Haskell98
493 494 495 496 497 498 499 500 501 502

-- Note [Lexing NumericUnderscores extension] (#14473)
--
-- NumericUnderscores extension allows underscores in numeric literals.
-- Multiple underscores are represented with @numspc macro.
-- To be simpler, we have only the definitions with underscores.
-- And then we have a separate function (tok_integral and tok_frac)
-- that validates the literals.
-- If extensions are not enabled, check that there are no underscores.
--
503
<0> {
504
  -- Normal integral literals (:: Num a => a, from Integer)
505 506 507 508
  @decimal                                                                   { tok_num positive 0 0 decimal }
  0[bB] @numspc @binary                / { ifExtension BinaryLiteralsBit }   { tok_num positive 2 2 binary }
  0[oO] @numspc @octal                                                       { tok_num positive 2 2 octal }
  0[xX] @numspc @hexadecimal                                                 { tok_num positive 2 2 hexadecimal }
509 510
  @negative @decimal                   / { negLitPred }                      { tok_num negative 1 1 decimal }
  @negative 0[bB] @numspc @binary      / { negLitPred `alexAndPred`
511
                                           ifExtension BinaryLiteralsBit }   { tok_num negative 3 3 binary }
512 513
  @negative 0[oO] @numspc @octal       / { negLitPred }                      { tok_num negative 3 3 octal }
  @negative 0[xX] @numspc @hexadecimal / { negLitPred }                      { tok_num negative 3 3 hexadecimal }
514 515

  -- Normal rational literals (:: Fractional a => a, from Rational)
516
  @floating_point                                                            { tok_frac 0 tok_float }
517
  @negative @floating_point            / { negLitPred }                      { tok_frac 0 tok_float }
518 519 520
  0[xX] @numspc @hex_floating_point    / { ifExtension HexFloatLiteralsBit } { tok_frac 0 tok_hex_float }
  @negative 0[xX] @numspc @hex_floating_point
                                       / { ifExtension HexFloatLiteralsBit `alexAndPred`
521
                                           negLitPred }                      { tok_frac 0 tok_hex_float }
522 523
}

524
<0> {
Ian Lynagh's avatar
Ian Lynagh committed
525
  -- Unboxed ints (:: Int#) and words (:: Word#)
526 527
  -- It's simpler (and faster?) to give separate cases to the negatives,
  -- especially considering octal/hexadecimal prefixes.
528 529 530 531 532
  @decimal                          \# / { ifExtension MagicHashBit }        { tok_primint positive 0 1 decimal }
  0[bB] @numspc @binary             \# / { ifExtension MagicHashBit `alexAndPred`
                                           ifExtension BinaryLiteralsBit }   { tok_primint positive 2 3 binary }
  0[oO] @numspc @octal              \# / { ifExtension MagicHashBit }        { tok_primint positive 2 3 octal }
  0[xX] @numspc @hexadecimal        \# / { ifExtension MagicHashBit }        { tok_primint positive 2 3 hexadecimal }
533 534
  @negative @decimal                \# / { negHashLitPred }                  { tok_primint negative 1 2 decimal }
  @negative 0[bB] @numspc @binary   \# / { negHashLitPred `alexAndPred`
535
                                           ifExtension BinaryLiteralsBit }   { tok_primint negative 3 4 binary }
536
  @negative 0[oO] @numspc @octal    \# / { negHashLitPred }                  { tok_primint negative 3 4 octal }
537
  @negative 0[xX] @numspc @hexadecimal \#
538
                                       / { negHashLitPred }                  { tok_primint negative 3 4 hexadecimal }
539 540 541 542 543 544

  @decimal                       \# \# / { ifExtension MagicHashBit }        { tok_primword 0 2 decimal }
  0[bB] @numspc @binary          \# \# / { ifExtension MagicHashBit `alexAndPred`
                                           ifExtension BinaryLiteralsBit }   { tok_primword 2 4 binary }
  0[oO] @numspc @octal           \# \# / { ifExtension MagicHashBit }        { tok_primword 2 4 octal }
  0[xX] @numspc @hexadecimal     \# \# / { ifExtension MagicHashBit }        { tok_primword 2 4 hexadecimal }
Ian Lynagh's avatar
Ian Lynagh committed
545

546 547
  -- Unboxed floats and doubles (:: Float#, :: Double#)
  -- prim_{float,double} work with signed literals
548 549 550 551 552
  @floating_point                  \# / { ifExtension MagicHashBit }        { tok_frac 1 tok_primfloat }
  @floating_point               \# \# / { ifExtension MagicHashBit }        { tok_frac 2 tok_primdouble }

  @negative @floating_point        \# / { negHashLitPred }                  { tok_frac 1 tok_primfloat }
  @negative @floating_point     \# \# / { negHashLitPred }                  { tok_frac 2 tok_primdouble }
553 554 555 556 557 558
}

-- Strings and chars are lexed by hand-written code.  The reason is
-- that even if we recognise the string or char here in the regex
-- lexer, we would still have to parse the string afterward in order
-- to convert it to a String.
559
<0> {
Ian Lynagh's avatar
Ian Lynagh committed
560 561
  \'                            { lex_char_tok }
  \"                            { lex_string_tok }
562 563
}

564 565 566 567 568 569 570 571 572 573 574
-- Note [Whitespace-sensitive operator parsing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- In accord with GHC Proposal #229 https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0229-whitespace-bang-patterns.rst
-- we classify operator occurrences into four categories:
--
--     a ! b   -- a loose infix occurrence
--     a!b     -- a tight infix occurrence
--     a !b    -- a prefix occurrence
--     a! b    -- a suffix occurrence
--
-- The rules are a bit more elaborate than simply checking for whitespace, in
Brian Wignall's avatar
Brian Wignall committed
575
-- order to accommodate the following use cases:
576 577 578 579 580 581 582
--
--     f (!a) = ...    -- prefix occurrence
--     g (a !)         -- loose infix occurrence
--     g (! a)         -- loose infix occurrence
--
-- The precise rules are as follows:
--
583 584 585
--  * Identifiers, literals, and opening brackets (, (#, (|, [, [|, [||, [p|,
--    [e|, [t|, {, ⟦, ⦇, are considered "opening tokens". The function
--    followedByOpeningToken tests whether the next token is an opening token.
586
--
587
--  * Identifiers, literals, and closing brackets ), #), |), ], |], }, ⟧, ⦈,
588 589
--    are considered "closing tokens". The function precededByClosingToken tests
--    whether the previous token is a closing token.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
590
--
591 592
--  * Whitespace, comments, separators, and other tokens, are considered
--    neither opening nor closing.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
593
--
594 595
--  * Any unqualified operator occurrence is classified as prefix, suffix, or
--    tight/loose infix, based on preceding and following tokens:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
596
--
597 598 599 600 601 602 603
--       precededByClosingToken | followedByOpeningToken | Occurrence
--      ------------------------+------------------------+------------
--       False                  | True                   | prefix
--       True                   | False                  | suffix
--       True                   | True                   | tight infix
--       False                  | False                  | loose infix
--      ------------------------+------------------------+------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
604
--
605 606
-- A loose infix occurrence is always considered an operator. Other types of
-- occurrences may be assigned a special per-operator meaning override:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
607
--
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
--   Operator |  Occurrence   | Token returned
--  ----------+---------------+------------------------------------------
--    !       |  prefix       | ITbang
--            |               |   strictness annotation or bang pattern,
--            |               |   e.g.  f !x = rhs, data T = MkT !a
--            |  not prefix   | ITvarsym "!"
--            |               |   ordinary operator or type operator,
--            |               |   e.g.  xs ! 3, (! x), Int ! Bool
--  ----------+---------------+------------------------------------------
--    ~       |  prefix       | ITtilde
--            |               |   laziness annotation or lazy pattern,
--            |               |   e.g.  f ~x = rhs, data T = MkT ~a
--            |  not prefix   | ITvarsym "~"
--            |               |   ordinary operator or type operator,
--            |               |   e.g.  xs ~ 3, (~ x), Int ~ Bool
--  ----------+---------------+------------------------------------------
--    $  $$   |  prefix       | ITdollar, ITdollardollar
--            |               |   untyped or typed Template Haskell splice,
--            |               |   e.g.  $(f x), $$(f x), $$"str"
--            |  not prefix   | ITvarsym "$", ITvarsym "$$"
--            |               |   ordinary operator or type operator,
--            |               |   e.g.  f $ g x, a $$ b
--  ----------+---------------+------------------------------------------
--    @       |  prefix       | ITtypeApp
--            |               |   type application, e.g.  fmap @Maybe
--            |  tight infix  | ITat
--            |               |   as-pattern, e.g.  f p@(a,b) = rhs
--            |  suffix       | parse error
--            |               |   e.g. f p@ x = rhs
--            |  loose infix  | ITvarsym "@"
--            |               |   ordinary operator or type operator,
--            |               |   e.g.  f @ g, (f @)
--  ----------+---------------+------------------------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
641
--
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
-- Also, some of these overrides are guarded behind language extensions.
-- According to the specification, we must determine the occurrence based on
-- surrounding *tokens* (see the proposal for the exact rules). However, in
-- the implementation we cheat a little and do the classification based on
-- characters, for reasons of both simplicity and efficiency (see
-- 'followedByOpeningToken' and 'precededByClosingToken')
--
-- When an operator is subject to a meaning override, it is mapped to special
-- token: ITbang, ITtilde, ITat, ITdollar, ITdollardollar. Otherwise, it is
-- returned as ITvarsym.
--
-- For example, this is how we process the (!):
--
--    precededByClosingToken | followedByOpeningToken | Token
--   ------------------------+------------------------+-------------
--    False                  | True                   | ITbang
--    True                   | False                  | ITvarsym "!"
--    True                   | True                   | ITvarsym "!"
--    False                  | False                  | ITvarsym "!"
--   ------------------------+------------------------+-------------
--
-- And this is how we process the (@):
--
--    precededByClosingToken | followedByOpeningToken | Token
--   ------------------------+------------------------+-------------
--    False                  | True                   | ITtypeApp
--    True                   | False                  | parse error
--    True                   | True                   | ITat
--    False                  | False                  | ITvarsym "@"
--   ------------------------+------------------------+-------------
672 673 674 675

-- -----------------------------------------------------------------------------
-- Alex "Haskell code fragment bottom"

676
{
677

678 679 680
-- -----------------------------------------------------------------------------
-- The token type

681
data Token
Ian Lynagh's avatar
Ian Lynagh committed
682
  = ITas                        -- Haskell keywords
683 684 685 686 687
  | ITcase
  | ITclass
  | ITdata
  | ITdefault
  | ITderiving
688
  | ITdo (Maybe FastString)
689 690
  | ITelse
  | IThiding
691
  | ITforeign
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
  | ITif
  | ITimport
  | ITin
  | ITinfix
  | ITinfixl
  | ITinfixr
  | ITinstance
  | ITlet
  | ITmodule
  | ITnewtype
  | ITof
  | ITqualified
  | ITthen
  | ITtype
  | ITwhere

708
  | ITforall            IsUnicodeSyntax -- GHC extension keywords
709 710 711 712
  | ITexport
  | ITlabel
  | ITdynamic
  | ITsafe
713
  | ITinterruptible
714 715 716
  | ITunsafe
  | ITstdcallconv
  | ITccallconv
717
  | ITcapiconv
718
  | ITprimcallconv
thoughtpolice's avatar
thoughtpolice committed
719
  | ITjavascriptcallconv
720
  | ITmdo (Maybe FastString)
721
  | ITfamily
722
  | ITrole
723 724 725
  | ITgroup
  | ITby
  | ITusing
Gergő Érdi's avatar
Gergő Érdi committed
726
  | ITpattern
Facundo Domínguez's avatar
Facundo Domínguez committed
727
  | ITstatic
Ryan Scott's avatar
Ryan Scott committed
728 729
  | ITstock
  | ITanyclass
Ryan Scott's avatar
Ryan Scott committed
730
  | ITvia
731

Edward Z. Yang's avatar
Edward Z. Yang committed
732 733 734 735 736 737
  -- Backpack tokens
  | ITunit
  | ITsignature
  | ITdependency
  | ITrequires

738
  -- Pragmas, see  note [Pragma source text] in "GHC.Types.Basic"
Alan Zimmerman's avatar
Alan Zimmerman committed
739 740 741 742 743 744 745
  | ITinline_prag       SourceText InlineSpec RuleMatchInfo
  | ITspec_prag         SourceText                -- SPECIALISE
  | ITspec_inline_prag  SourceText Bool    -- SPECIALISE INLINE (or NOINLINE)
  | ITsource_prag       SourceText
  | ITrules_prag        SourceText
  | ITwarning_prag      SourceText
  | ITdeprecated_prag   SourceText
746 747
  | ITline_prag         SourceText  -- not usually produced, see 'UsePosPragsBit'
  | ITcolumn_prag       SourceText  -- not usually produced, see 'UsePosPragsBit'
Alan Zimmerman's avatar
Alan Zimmerman committed
748 749 750 751 752
  | ITscc_prag          SourceText
  | ITgenerated_prag    SourceText
  | ITunpack_prag       SourceText
  | ITnounpack_prag     SourceText
  | ITann_prag          SourceText
753
  | ITcomplete_prag     SourceText
754
  | ITclose_prag
755 756 757
  | IToptions_prag String
  | ITinclude_prag String
  | ITlanguage_prag
Alan Zimmerman's avatar
Alan Zimmerman committed
758 759 760 761 762 763
  | ITminimal_prag      SourceText
  | IToverlappable_prag SourceText  -- instance overlap mode
  | IToverlapping_prag  SourceText  -- instance overlap mode
  | IToverlaps_prag     SourceText  -- instance overlap mode
  | ITincoherent_prag   SourceText  -- instance overlap mode
  | ITctype             SourceText
764
  | ITcomment_line_prag         -- See Note [Nested comment line pragmas]
765

Ian Lynagh's avatar
Ian Lynagh committed
766
  | ITdotdot                    -- reserved symbols
767
  | ITcolon
768
  | ITdcolon            IsUnicodeSyntax
769 770
  | ITequal
  | ITlam
771
  | ITlcase
772
  | ITvbar
773 774
  | ITlarrow            IsUnicodeSyntax
  | ITrarrow            IsUnicodeSyntax
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
775
  | ITlolly             IsUnicodeSyntax
776
  | ITdarrow            IsUnicodeSyntax
777 778
  | ITminus       -- See Note [Minus tokens]
  | ITprefixminus -- See Note [Minus tokens]
779 780 781 782
  | ITbang     -- Prefix (!) only, e.g. f !x = rhs
  | ITtilde    -- Prefix (~) only, e.g. f ~x = rhs
  | ITat       -- Tight infix (@) only, e.g. f x@pat = rhs
  | ITtypeApp  -- Prefix (@) only, e.g. f @t
783
  | ITstar              IsUnicodeSyntax
784 785
  | ITdot

Ian Lynagh's avatar
Ian Lynagh committed
786
  | ITbiglam                    -- GHC-extension symbols
787

Ian Lynagh's avatar
Ian Lynagh committed
788
  | ITocurly                    -- special symbols
789 790 791 792
  | ITccurly
  | ITvocurly
  | ITvccurly
  | ITobrack
Ian Lynagh's avatar
Ian Lynagh committed
793 794
  | ITopabrack                  -- [:, for parallel arrays with -XParallelArrays
  | ITcpabrack                  -- :], for parallel arrays with -XParallelArrays
795 796 797 798 799 800 801 802 803
  | ITcbrack
  | IToparen
  | ITcparen
  | IToubxparen
  | ITcubxparen
  | ITsemi
  | ITcomma
  | ITunderscore
  | ITbackquote
dreixel's avatar
dreixel committed
804
  | ITsimpleQuote               --  '
805

Ian Lynagh's avatar
Ian Lynagh committed
806
  | ITvarid   FastString        -- identifiers
807 808 809 810 811 812 813 814
  | ITconid   FastString
  | ITvarsym  FastString
  | ITconsym  FastString
  | ITqvarid  (FastString,FastString)
  | ITqconid  (FastString,FastString)
  | ITqvarsym (FastString,FastString)
  | ITqconsym (FastString,FastString)

Ian Lynagh's avatar
Ian Lynagh committed
815
  | ITdupipvarid   FastString   -- GHC extension: implicit param: ?x
Adam Gundry's avatar
Adam Gundry committed
816
  | ITlabelvarid   FastString   -- Overloaded label: #x
817

818 819 820
  | ITchar     SourceText Char       -- Note [Literal source text] in "GHC.Types.Basic"
  | ITstring   SourceText FastString -- Note [Literal source text] in "GHC.Types.Basic"
  | ITinteger  IntegralLit           -- Note [Literal source text] in "GHC.Types.Basic"
Alan Zimmerman's avatar
Alan Zimmerman committed
821
  | ITrational FractionalLit
822

823 824 825 826
  | ITprimchar   SourceText Char     -- Note [Literal source text] in "GHC.Types.Basic"
  | ITprimstring SourceText ByteString -- Note [Literal source text] in "GHC.Types.Basic"
  | ITprimint    SourceText Integer  -- Note [Literal source text] in "GHC.Types.Basic"
  | ITprimword   SourceText Integer  -- Note [Literal source text] in "GHC.Types.Basic"
827 828
  | ITprimfloat  FractionalLit
  | ITprimdouble FractionalLit
829

830
  -- Template Haskell extension tokens
831 832 833 834 835 836 837
  | ITopenExpQuote HasE IsUnicodeSyntax --  [| or [e|
  | ITopenPatQuote                      --  [p|
  | ITopenDecQuote                      --  [d|
  | ITopenTypQuote                      --  [t|
  | ITcloseQuote IsUnicodeSyntax        --  |]
  | ITopenTExpQuote HasE                --  [|| or [e||
  | ITcloseTExpQuote                    --  ||]
838 839
  | ITdollar                            --  prefix $
  | ITdollardollar                      --  prefix $$
840
  | ITtyQuote                           --  ''
841
  | ITquasiQuote (FastString,FastString,PsSpan)
842 843 844
    -- ITquasiQuote(quoter, quote, loc)
    -- represents a quasi-quote of the form
    -- [quoter| quote |]
845
  | ITqQuasiQuote (FastString,FastString,FastString,PsSpan)
846 847 848
    -- ITqQuasiQuote(Qual, quoter, quote, loc)
    -- represents a qualified quasi-quote of the form
    -- [Qual.quoter| quote |]
849 850 851 852

  -- Arrow notation extension
  | ITproc
  | ITrec
853 854 855 856 857 858 859 860 861
  | IToparenbar  IsUnicodeSyntax -- ^ @(|@
  | ITcparenbar  IsUnicodeSyntax -- ^ @|)@
  | ITlarrowtail IsUnicodeSyntax -- ^ @-<@
  | ITrarrowtail IsUnicodeSyntax -- ^ @>-@
  | ITLarrowtail IsUnicodeSyntax -- ^ @-<<@
  | ITRarrowtail IsUnicodeSyntax -- ^ @>>-@

  | ITunknown String             -- ^ Used when the lexer can't make sense of it
  | ITeof                        -- ^ end of file token
862 863

  -- Documentation annotations
864 865 866 867 868 869 870
  | ITdocCommentNext  String     -- ^ something beginning @-- |@
  | ITdocCommentPrev  String     -- ^ something beginning @-- ^@
  | ITdocCommentNamed String     -- ^ something beginning @-- $@
  | ITdocSection      Int String -- ^ a section heading
  | ITdocOptions      String     -- ^ doc options (prune, ignore-exports, etc)
  | ITlineComment     String     -- ^ comment starting by "--"
  | ITblockComment    String     -- ^ comment in {- -}
871

872
  deriving Show
873

Alan Zimmerman's avatar
Alan Zimmerman committed
874 875 876
instance Outputable Token where
  ppr x = text (show x)

Alan Zimmerman's avatar
Alan Zimmerman committed
877

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
{- Note [Minus tokens]
~~~~~~~~~~~~~~~~~~~~~~
A minus sign can be used in prefix form (-x) and infix form (a - b).

When LexicalNegation is on:
  * ITprefixminus  represents the prefix form
  * ITvarsym "-"   represents the infix form
  * ITminus        is not used

When LexicalNegation is off:
  * ITminus        represents all forms
  * ITprefixminus  is not used
  * ITvarsym "-"   is not used
-}

{- Note [Why not LexicalNegationBit]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One might wonder why we define NoLexicalNegationBit instead of
LexicalNegationBit. The problem lies in the following line in reservedSymsFM:

    ,("-", ITminus, NormalSyntax, xbit NoLexicalNegationBit)

We want to generate ITminus only when LexicalNegation is off. How would one
do it if we had LexicalNegationBit? I (int-index) tried to use bitwise
complement:

    ,("-", ITminus, NormalSyntax, complement (xbit LexicalNegationBit))

This did not work, so I opted for NoLexicalNegationBit instead.
-}

909

910 911 912 913 914 915 916
-- the bitmap provided as the third component indicates whether the
-- corresponding extension keyword is valid under the extension options
-- provided to the compiler; if the extension corresponding to *any* of the
-- bits set in the bitmap is enabled, the keyword is valid (this setup
-- facilitates using a keyword in two different extensions that can be
-- activated independently)
--
917
reservedWordsFM :: UniqFM FastString (Token, ExtsBitmap)
918
reservedWordsFM = listToUFM $
Ian Lynagh's avatar
Ian Lynagh committed
919 920 921 922 923 924 925 926
    map (\(x, y, z) -> (mkFastString x, (y, z)))
        [( "_",              ITunderscore,    0 ),
         ( "as",             ITas,            0 ),
         ( "case",           ITcase,          0 ),
         ( "class",          ITclass,         0 ),
         ( "data",           ITdata,          0 ),
         ( "default",        ITdefault,       0 ),
         ( "deriving",       ITderiving,      0 ),
927
         ( "do",             ITdo Nothing,    0 ),
Ian Lynagh's avatar
Ian Lynagh committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
         ( "else",           ITelse,          0 ),
         ( "hiding",         IThiding,        0 ),
         ( "if",             ITif,            0 ),
         ( "import",         ITimport,        0 ),
         ( "in",             ITin,            0 ),
         ( "infix",          ITinfix,         0 ),
         ( "infixl",         ITinfixl,        0 ),
         ( "infixr",         ITinfixr,        0 ),
         ( "instance",       ITinstance,      0 ),
         ( "let",            ITlet,           0 ),
         ( "module",         ITmodule,        0 ),
         ( "newtype",        ITnewtype,       0 ),
         ( "of",             ITof,            0 ),
         ( "qualified",      ITqualified,     0 ),
         ( "then",           ITthen,          0 ),
         ( "type",           ITtype,          0 ),
         ( "where",          ITwhere,         0 ),

946
         ( "forall",         ITforall NormalSyntax, 0),
947
         ( "mdo",            ITmdo Nothing,   xbit RecursiveDoBit),
948 949 950
             -- See Note [Lexing type pseudo-keywords]
         ( "family",         ITfamily,        0 ),
         ( "role",           ITrole,          0 ),
951
         ( "pattern",        ITpattern,       xbit PatternSynonymsBit),
952
         ( "static",         ITstatic,        xbit StaticPointersBit ),
Ryan Scott's avatar
Ryan Scott committed
953 954
         ( "stock",          ITstock,         0 ),
         ( "anyclass",       ITanyclass,      0 ),
Ryan Scott's avatar
Ryan Scott committed
955
         ( "via",            ITvia,           0 ),
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
         ( "group",          ITgroup,         xbit TransformComprehensionsBit),
         ( "by",             ITby,            xbit TransformComprehensionsBit),
         ( "using",          ITusing,         xbit TransformComprehensionsBit),

         ( "foreign",        ITforeign,       xbit FfiBit),
         ( "export",         ITexport,        xbit FfiBit),
         ( "label",          ITlabel,         xbit FfiBit),
         ( "dynamic",        ITdynamic,       xbit FfiBit),
         ( "safe",           ITsafe,          xbit FfiBit .|.
                                              xbit SafeHaskellBit),
         ( "interruptible",  ITinterruptible, xbit InterruptibleFfiBit),
         ( "unsafe",         ITunsafe,        xbit FfiBit),
         ( "stdcall",        ITstdcallconv,   xbit FfiBit),
         ( "ccall",          ITccallconv,     xbit FfiBit),
         ( "capi",           ITcapiconv,      xbit CApiFfiBit),
         ( "prim",           ITprimcallconv,  xbit FfiBit),
         ( "javascript",     ITjavascriptcallconv, xbit FfiBit),

Edward Z. Yang's avatar
Edward Z. Yang committed
974 975 976 977
         ( "unit",           ITunit,          0 ),
         ( "dependency",     ITdependency,       0 ),
         ( "signature",      ITsignature,     0 ),

978 979 980
         ( "rec",            ITrec,           xbit ArrowsBit .|.
                                              xbit RecursiveDoBit),
         ( "proc",           ITproc,          xbit ArrowsBit)
981 982
     ]

983 984 985 986 987 988 989 990
{-----------------------------------
Note [Lexing type pseudo-keywords]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

One might think that we wish to treat 'family' and 'role' as regular old
varids whenever -XTypeFamilies and -XRoleAnnotations are off, respectively.
But, there is no need to do so. These pseudo-keywords are not stolen syntax:
they are only used after the keyword 'type' at the top-level, where varids are
Sylvain Henry's avatar
Sylvain Henry committed
991
not allowed. Furthermore, checks further downstream (GHC.Tc.TyCl) ensure that
992 993 994 995 996 997 998
type families and role annotations are never declared without their extensions
on. In fact, by unconditionally lexing these pseudo-keywords as special, we
can get better error messages.

Also, note that these are included in the `varid` production in the parser --
a key detail to make all this work.
-------------------------------------}
999

1000
reservedSymsFM :: UniqFM FastString (Token, IsUnicodeSyntax, ExtsBitmap)
1001
reservedSymsFM = listToUFM $
1002 1003
    map (\ (x,w,y,z) -> (mkFastString x,(w,y,z)))
      [ ("..",  ITdotdot,                   NormalSyntax,  0 )
Ian Lynagh's avatar
Ian Lynagh committed
1004
        -- (:) is a reserved op, meaning only list cons
1005 1006 1007 1008 1009 1010 1011 1012
       ,(":",   ITcolon,                    NormalSyntax,  0 )
       ,("::",  ITdcolon NormalSyntax,      NormalSyntax,  0 )
       ,("=",   ITequal,                    NormalSyntax,  0 )
       ,("\\",  ITlam,                      NormalSyntax,  0 )
       ,("|",   ITvbar,                     NormalSyntax,  0 )
       ,("<-",  ITlarrow NormalSyntax,      NormalSyntax,  0 )
       ,("->",  ITrarrow NormalSyntax,      NormalSyntax,  0 )
       ,("=>",  ITdarrow NormalSyntax,      NormalSyntax,  0 )
1013
       ,("-",   ITminus,                    NormalSyntax,  xbit NoLexicalNegationBit)
1014 1015

       ,("*",   ITstar NormalSyntax,        NormalSyntax,  xbit StarIsTypeBit)
1016

Ian Lynagh's avatar
Ian Lynagh committed
1017
        -- For 'forall a . t'
1018