Add quasi-quotation, courtesy of Geoffrey Mainland
[ghc-hetmet.git] / compiler / parser / Parser.y.pp
1 --                                                              -*-haskell-*-
2 -- ---------------------------------------------------------------------------
3 -- (c) The University of Glasgow 1997-2003
4 ---
5 -- The GHC grammar.
6 --
7 -- Author(s): Simon Marlow, Sven Panne 1997, 1998, 1999
8 -- ---------------------------------------------------------------------------
9
10 {
11 {-# OPTIONS -w #-}
12 -- The above warning supression flag is a temporary kludge.
13 -- While working on this module you are encouraged to remove it and fix
14 -- any warnings in the module. See
15 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 -- for details
17
18 module Parser ( parseModule, parseStmt, parseIdentifier, parseType,
19                 parseHeader ) where
20
21 #define INCLUDE #include 
22 INCLUDE "HsVersions.h"
23
24 import HsSyn
25 import RdrHsSyn
26 import HscTypes         ( IsBootInterface, DeprecTxt )
27 import Lexer
28 import RdrName
29 import TysWiredIn       ( unitTyCon, unitDataCon, tupleTyCon, tupleCon, nilDataCon,
30                           unboxedSingletonTyCon, unboxedSingletonDataCon,
31                           listTyCon_RDR, parrTyCon_RDR, consDataCon_RDR )
32 import Type             ( funTyCon )
33 import ForeignCall      ( Safety(..), CExportSpec(..), CLabelString,
34                           CCallConv(..), CCallTarget(..), defaultCCallConv
35                         )
36 import OccName          ( varName, dataName, tcClsName, tvName )
37 import DataCon          ( DataCon, dataConName )
38 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc, combineSrcSpans,
39                           SrcSpan, combineLocs, srcLocFile, 
40                           mkSrcLoc, mkSrcSpan )
41 import Module
42 import StaticFlags      ( opt_SccProfilingOn, opt_Hpc )
43 import Type             ( Kind, mkArrowKind, liftedTypeKind, unliftedTypeKind )
44 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), IPName(..),
45                           Activation(..), defaultInlineSpec )
46 import DynFlags
47 import OrdList
48 import HaddockParse
49 import {-# SOURCE #-} HaddockLex hiding ( Token )
50 import HaddockUtils
51
52 import FastString
53 import Maybes           ( orElse )
54 import Outputable
55
56 import Control.Monad    ( unless )
57 import GHC.Exts
58 import Data.Char
59 import Control.Monad    ( mplus )
60 }
61
62 {-
63 -----------------------------------------------------------------------------
64 24 Februar 2006
65
66 Conflicts: 33 shift/reduce
67            1 reduce/reduce
68
69 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
70 would think the two should never occur in the same context.
71
72   -=chak
73
74 -----------------------------------------------------------------------------
75 31 December 2006
76
77 Conflicts: 34 shift/reduce
78            1 reduce/reduce
79
80 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
81 would think the two should never occur in the same context.
82
83   -=chak
84
85 -----------------------------------------------------------------------------
86 6 December 2006
87
88 Conflicts: 32 shift/reduce
89            1 reduce/reduce
90
91 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
92 would think the two should never occur in the same context.
93
94   -=chak
95
96 -----------------------------------------------------------------------------
97 26 July 2006
98
99 Conflicts: 37 shift/reduce
100            1 reduce/reduce
101
102 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
103 would think the two should never occur in the same context.
104
105   -=chak
106
107 -----------------------------------------------------------------------------
108 Conflicts: 38 shift/reduce (1.25)
109
110 10 for abiguity in 'if x then y else z + 1'             [State 178]
111         (shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
112         10 because op might be: : - ! * . `x` VARSYM CONSYM QVARSYM QCONSYM
113
114 1 for ambiguity in 'if x then y else z :: T'            [State 178]
115         (shift parses as 'if x then y else (z :: T)', as per longest-parse rule)
116
117 4 for ambiguity in 'if x then y else z -< e'            [State 178]
118         (shift parses as 'if x then y else (z -< T)', as per longest-parse rule)
119         There are four such operators: -<, >-, -<<, >>-
120
121
122 2 for ambiguity in 'case v of { x :: T -> T ... } '     [States 11, 253]
123         Which of these two is intended?
124           case v of
125             (x::T) -> T         -- Rhs is T
126     or
127           case v of
128             (x::T -> T) -> ..   -- Rhs is ...
129
130 10 for ambiguity in 'e :: a `b` c'.  Does this mean     [States 11, 253]
131         (e::a) `b` c, or 
132         (e :: (a `b` c))
133     As well as `b` we can have !, VARSYM, QCONSYM, and CONSYM, hence 5 cases
134     Same duplication between states 11 and 253 as the previous case
135
136 1 for ambiguity in 'let ?x ...'                         [State 329]
137         the parser can't tell whether the ?x is the lhs of a normal binding or
138         an implicit binding.  Fortunately resolving as shift gives it the only
139         sensible meaning, namely the lhs of an implicit binding.
140
141 1 for ambiguity in '{-# RULES "name" [ ... #-}          [State 382]
142         we don't know whether the '[' starts the activation or not: it
143         might be the start of the declaration with the activation being
144         empty.  --SDM 1/4/2002
145
146 1 for ambiguity in '{-# RULES "name" forall = ... #-}'  [State 474]
147         since 'forall' is a valid variable name, we don't know whether
148         to treat a forall on the input as the beginning of a quantifier
149         or the beginning of the rule itself.  Resolving to shift means
150         it's always treated as a quantifier, hence the above is disallowed.
151         This saves explicitly defining a grammar for the rule lhs that
152         doesn't include 'forall'.
153
154 1 for ambiguity when the source file starts with "-- | doc". We need another
155   token of lookahead to determine if a top declaration or the 'module' keyword
156   follows. Shift parses as if the 'module' keyword follows.   
157
158 -- ---------------------------------------------------------------------------
159 -- Adding location info
160
161 This is done in a stylised way using the three macros below, L0, L1
162 and LL.  Each of these macros can be thought of as having type
163
164    L0, L1, LL :: a -> Located a
165
166 They each add a SrcSpan to their argument.
167
168    L0   adds 'noSrcSpan', used for empty productions
169      -- This doesn't seem to work anymore -=chak
170
171    L1   for a production with a single token on the lhs.  Grabs the SrcSpan
172         from that token.
173
174    LL   for a production with >1 token on the lhs.  Makes up a SrcSpan from
175         the first and last tokens.
176
177 These suffice for the majority of cases.  However, we must be
178 especially careful with empty productions: LL won't work if the first
179 or last token on the lhs can represent an empty span.  In these cases,
180 we have to calculate the span using more of the tokens from the lhs, eg.
181
182         | 'newtype' tycl_hdr '=' newconstr deriving
183                 { L (comb3 $1 $4 $5)
184                     (mkTyData NewType (unLoc $2) [$4] (unLoc $5)) }
185
186 We provide comb3 and comb4 functions which are useful in such cases.
187
188 Be careful: there's no checking that you actually got this right, the
189 only symptom will be that the SrcSpans of your syntax will be
190 incorrect.
191
192 /*
193  * We must expand these macros *before* running Happy, which is why this file is
194  * Parser.y.pp rather than just Parser.y - we run the C pre-processor first.
195  */
196 #define L0   L noSrcSpan
197 #define L1   sL (getLoc $1)
198 #define LL   sL (comb2 $1 $>)
199
200 -- -----------------------------------------------------------------------------
201
202 -}
203
204 %token
205  '_'            { L _ ITunderscore }            -- Haskell keywords
206  'as'           { L _ ITas }
207  'case'         { L _ ITcase }          
208  'class'        { L _ ITclass } 
209  'data'         { L _ ITdata } 
210  'default'      { L _ ITdefault }
211  'deriving'     { L _ ITderiving }
212  'do'           { L _ ITdo }
213  'else'         { L _ ITelse }
214  'hiding'       { L _ IThiding }
215  'if'           { L _ ITif }
216  'import'       { L _ ITimport }
217  'in'           { L _ ITin }
218  'infix'        { L _ ITinfix }
219  'infixl'       { L _ ITinfixl }
220  'infixr'       { L _ ITinfixr }
221  'instance'     { L _ ITinstance }
222  'let'          { L _ ITlet }
223  'module'       { L _ ITmodule }
224  'newtype'      { L _ ITnewtype }
225  'of'           { L _ ITof }
226  'qualified'    { L _ ITqualified }
227  'then'         { L _ ITthen }
228  'type'         { L _ ITtype }
229  'where'        { L _ ITwhere }
230  '_scc_'        { L _ ITscc }         -- ToDo: remove
231
232  'forall'       { L _ ITforall }                -- GHC extension keywords
233  'foreign'      { L _ ITforeign }
234  'export'       { L _ ITexport }
235  'label'        { L _ ITlabel } 
236  'dynamic'      { L _ ITdynamic }
237  'safe'         { L _ ITsafe }
238  'threadsafe'   { L _ ITthreadsafe }
239  'unsafe'       { L _ ITunsafe }
240  'mdo'          { L _ ITmdo }
241  'family'       { L _ ITfamily }
242  'stdcall'      { L _ ITstdcallconv }
243  'ccall'        { L _ ITccallconv }
244  'dotnet'       { L _ ITdotnet }
245  'proc'         { L _ ITproc }          -- for arrow notation extension
246  'rec'          { L _ ITrec }           -- for arrow notation extension
247  'group'    { L _ ITgroup }     -- for list transform extension
248  'by'       { L _ ITby }        -- for list transform extension
249  'using'    { L _ ITusing }     -- for list transform extension
250
251  '{-# INLINE'             { L _ (ITinline_prag _) }
252  '{-# SPECIALISE'         { L _ ITspec_prag }
253  '{-# SPECIALISE_INLINE'  { L _ (ITspec_inline_prag _) }
254  '{-# SOURCE'      { L _ ITsource_prag }
255  '{-# RULES'       { L _ ITrules_prag }
256  '{-# CORE'        { L _ ITcore_prag }              -- hdaume: annotated core
257  '{-# SCC'         { L _ ITscc_prag }
258  '{-# GENERATED'   { L _ ITgenerated_prag }
259  '{-# DEPRECATED'  { L _ ITdeprecated_prag }
260  '{-# UNPACK'      { L _ ITunpack_prag }
261  '#-}'             { L _ ITclose_prag }
262
263  '..'           { L _ ITdotdot }                        -- reserved symbols
264  ':'            { L _ ITcolon }
265  '::'           { L _ ITdcolon }
266  '='            { L _ ITequal }
267  '\\'           { L _ ITlam }
268  '|'            { L _ ITvbar }
269  '<-'           { L _ ITlarrow }
270  '->'           { L _ ITrarrow }
271  '@'            { L _ ITat }
272  '~'            { L _ ITtilde }
273  '=>'           { L _ ITdarrow }
274  '-'            { L _ ITminus }
275  '!'            { L _ ITbang }
276  '*'            { L _ ITstar }
277  '-<'           { L _ ITlarrowtail }            -- for arrow notation
278  '>-'           { L _ ITrarrowtail }            -- for arrow notation
279  '-<<'          { L _ ITLarrowtail }            -- for arrow notation
280  '>>-'          { L _ ITRarrowtail }            -- for arrow notation
281  '.'            { L _ ITdot }
282
283  '{'            { L _ ITocurly }                        -- special symbols
284  '}'            { L _ ITccurly }
285  '{|'           { L _ ITocurlybar }
286  '|}'           { L _ ITccurlybar }
287  vocurly        { L _ ITvocurly } -- virtual open curly (from layout)
288  vccurly        { L _ ITvccurly } -- virtual close curly (from layout)
289  '['            { L _ ITobrack }
290  ']'            { L _ ITcbrack }
291  '[:'           { L _ ITopabrack }
292  ':]'           { L _ ITcpabrack }
293  '('            { L _ IToparen }
294  ')'            { L _ ITcparen }
295  '(#'           { L _ IToubxparen }
296  '#)'           { L _ ITcubxparen }
297  '(|'           { L _ IToparenbar }
298  '|)'           { L _ ITcparenbar }
299  ';'            { L _ ITsemi }
300  ','            { L _ ITcomma }
301  '`'            { L _ ITbackquote }
302
303  VARID          { L _ (ITvarid    _) }          -- identifiers
304  CONID          { L _ (ITconid    _) }
305  VARSYM         { L _ (ITvarsym   _) }
306  CONSYM         { L _ (ITconsym   _) }
307  QVARID         { L _ (ITqvarid   _) }
308  QCONID         { L _ (ITqconid   _) }
309  QVARSYM        { L _ (ITqvarsym  _) }
310  QCONSYM        { L _ (ITqconsym  _) }
311
312  IPDUPVARID     { L _ (ITdupipvarid   _) }              -- GHC extension
313
314  CHAR           { L _ (ITchar     _) }
315  STRING         { L _ (ITstring   _) }
316  INTEGER        { L _ (ITinteger  _) }
317  RATIONAL       { L _ (ITrational _) }
318                     
319  PRIMCHAR       { L _ (ITprimchar   _) }
320  PRIMSTRING     { L _ (ITprimstring _) }
321  PRIMINTEGER    { L _ (ITprimint    _) }
322  PRIMFLOAT      { L _ (ITprimfloat  _) }
323  PRIMDOUBLE     { L _ (ITprimdouble _) }
324
325  DOCNEXT        { L _ (ITdocCommentNext _) }
326  DOCPREV        { L _ (ITdocCommentPrev _) }
327  DOCNAMED       { L _ (ITdocCommentNamed _) }
328  DOCSECTION     { L _ (ITdocSection _ _) }
329
330 -- Template Haskell 
331 '[|'            { L _ ITopenExpQuote  }       
332 '[p|'           { L _ ITopenPatQuote  }      
333 '[t|'           { L _ ITopenTypQuote  }      
334 '[d|'           { L _ ITopenDecQuote  }      
335 '|]'            { L _ ITcloseQuote    }
336 TH_ID_SPLICE    { L _ (ITidEscape _)  }     -- $x
337 '$('            { L _ ITparenEscape   }     -- $( exp )
338 TH_VAR_QUOTE    { L _ ITvarQuote      }     -- 'x
339 TH_TY_QUOTE     { L _ ITtyQuote       }      -- ''T
340 TH_QUASIQUOTE   { L _ (ITquasiQuote _) }
341
342 %monad { P } { >>= } { return }
343 %lexer { lexer } { L _ ITeof }
344 %name parseModule module
345 %name parseStmt   maybe_stmt
346 %name parseIdentifier  identifier
347 %name parseType ctype
348 %partial parseHeader header
349 %tokentype { (Located Token) }
350 %%
351
352 -----------------------------------------------------------------------------
353 -- Identifiers; one of the entry points
354 identifier :: { Located RdrName }
355         : qvar                          { $1 }
356         | qcon                          { $1 }
357         | qvarop                        { $1 }
358         | qconop                        { $1 }
359     | '(' '->' ')'      { LL $ getRdrName funTyCon }
360
361 -----------------------------------------------------------------------------
362 -- Module Header
363
364 -- The place for module deprecation is really too restrictive, but if it
365 -- was allowed at its natural place just before 'module', we get an ugly
366 -- s/r conflict with the second alternative. Another solution would be the
367 -- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
368 -- either, and DEPRECATED is only expected to be used by people who really
369 -- know what they are doing. :-)
370
371 module  :: { Located (HsModule RdrName) }
372         : maybedocheader 'module' modid maybemoddeprec maybeexports 'where' body
373                 {% fileSrcSpan >>= \ loc -> case $1 of { (info, doc) ->
374                    return (L loc (HsModule (Just $3) $5 (fst $7) (snd $7) $4
375                           info doc) )}}
376         | body2
377                 {% fileSrcSpan >>= \ loc ->
378                    return (L loc (HsModule Nothing Nothing
379                           (fst $1) (snd $1) Nothing emptyHaddockModInfo
380                           Nothing)) }
381
382 maybedocheader :: { (HaddockModInfo RdrName, Maybe (HsDoc RdrName)) }
383         : moduleheader            { (fst $1, snd $1) }
384         | {- empty -}             { (emptyHaddockModInfo, Nothing) }
385
386 missing_module_keyword :: { () }
387         : {- empty -}                           {% pushCurrentContext }
388
389 maybemoddeprec :: { Maybe DeprecTxt }
390         : '{-# DEPRECATED' STRING '#-}'         { Just (getSTRING $2) }
391         |  {- empty -}                          { Nothing }
392
393 body    :: { ([LImportDecl RdrName], [LHsDecl RdrName]) }
394         :  '{'            top '}'               { $2 }
395         |      vocurly    top close             { $2 }
396
397 body2   :: { ([LImportDecl RdrName], [LHsDecl RdrName]) }
398         :  '{' top '}'                          { $2 }
399         |  missing_module_keyword top close     { $2 }
400
401 top     :: { ([LImportDecl RdrName], [LHsDecl RdrName]) }
402         : importdecls                           { (reverse $1,[]) }
403         | importdecls ';' cvtopdecls            { (reverse $1,$3) }
404         | cvtopdecls                            { ([],$1) }
405
406 cvtopdecls :: { [LHsDecl RdrName] }
407         : topdecls                              { cvTopDecls $1 }
408
409 -----------------------------------------------------------------------------
410 -- Module declaration & imports only
411
412 header  :: { Located (HsModule RdrName) }
413         : maybedocheader 'module' modid maybemoddeprec maybeexports 'where' header_body
414                 {% fileSrcSpan >>= \ loc -> case $1 of { (info, doc) ->
415                    return (L loc (HsModule (Just $3) $5 $7 [] $4
416                    info doc))}}
417         | missing_module_keyword importdecls
418                 {% fileSrcSpan >>= \ loc ->
419                    return (L loc (HsModule Nothing Nothing $2 [] Nothing
420                    emptyHaddockModInfo Nothing)) }
421
422 header_body :: { [LImportDecl RdrName] }
423         :  '{'            importdecls           { $2 }
424         |      vocurly    importdecls           { $2 }
425
426 -----------------------------------------------------------------------------
427 -- The Export List
428
429 maybeexports :: { Maybe [LIE RdrName] }
430         :  '(' exportlist ')'                   { Just $2 }
431         |  {- empty -}                          { Nothing }
432
433 exportlist :: { [LIE RdrName] }
434         : expdoclist ',' expdoclist             { $1 ++ $3 }
435         | exportlist1                           { $1 }
436
437 exportlist1 :: { [LIE RdrName] }
438         : expdoclist export expdoclist ',' exportlist  { $1 ++ ($2 : $3) ++ $5 }
439         | expdoclist export expdoclist                 { $1 ++ ($2 : $3) }
440         | expdoclist                                   { $1 }
441
442 expdoclist :: { [LIE RdrName] }
443         : exp_doc expdoclist                           { $1 : $2 }
444         | {- empty -}                                  { [] }
445
446 exp_doc :: { LIE RdrName }                                                   
447         : docsection    { L1 (case (unLoc $1) of (n, doc) -> IEGroup n doc) }
448         | docnamed      { L1 (IEDocNamed ((fst . unLoc) $1)) } 
449         | docnext       { L1 (IEDoc (unLoc $1)) }       
450                        
451    -- No longer allow things like [] and (,,,) to be exported
452    -- They are built in syntax, always available
453 export  :: { LIE RdrName }
454         :  qvar                         { L1 (IEVar (unLoc $1)) }
455         |  oqtycon                      { L1 (IEThingAbs (unLoc $1)) }
456         |  oqtycon '(' '..' ')'         { LL (IEThingAll (unLoc $1)) }
457         |  oqtycon '(' ')'              { LL (IEThingWith (unLoc $1) []) }
458         |  oqtycon '(' qcnames ')'      { LL (IEThingWith (unLoc $1) (reverse $3)) }
459         |  'module' modid               { LL (IEModuleContents (unLoc $2)) }
460
461 qcnames :: { [RdrName] }
462         :  qcnames ',' qcname_ext       { unLoc $3 : $1 }
463         |  qcname_ext                   { [unLoc $1]  }
464
465 qcname_ext :: { Located RdrName }       -- Variable or data constructor
466                                         -- or tagged type constructor
467         :  qcname                       { $1 }
468         |  'type' qcon                  { sL (comb2 $1 $2) 
469                                              (setRdrNameSpace (unLoc $2) 
470                                                               tcClsName)  }
471
472 -- Cannot pull into qcname_ext, as qcname is also used in expression.
473 qcname  :: { Located RdrName }  -- Variable or data constructor
474         :  qvar                         { $1 }
475         |  qcon                         { $1 }
476
477 -----------------------------------------------------------------------------
478 -- Import Declarations
479
480 -- import decls can be *empty*, or even just a string of semicolons
481 -- whereas topdecls must contain at least one topdecl.
482
483 importdecls :: { [LImportDecl RdrName] }
484         : importdecls ';' importdecl            { $3 : $1 }
485         | importdecls ';'                       { $1 }
486         | importdecl                            { [ $1 ] }
487         | {- empty -}                           { [] }
488
489 importdecl :: { LImportDecl RdrName }
490         : 'import' maybe_src optqualified modid maybeas maybeimpspec 
491                 { L (comb4 $1 $4 $5 $6) (ImportDecl $4 $2 $3 (unLoc $5) (unLoc $6)) }
492
493 maybe_src :: { IsBootInterface }
494         : '{-# SOURCE' '#-}'                    { True }
495         | {- empty -}                           { False }
496
497 optqualified :: { Bool }
498         : 'qualified'                           { True  }
499         | {- empty -}                           { False }
500
501 maybeas :: { Located (Maybe ModuleName) }
502         : 'as' modid                            { LL (Just (unLoc $2)) }
503         | {- empty -}                           { noLoc Nothing }
504
505 maybeimpspec :: { Located (Maybe (Bool, [LIE RdrName])) }
506         : impspec                               { L1 (Just (unLoc $1)) }
507         | {- empty -}                           { noLoc Nothing }
508
509 impspec :: { Located (Bool, [LIE RdrName]) }
510         :  '(' exportlist ')'                   { LL (False, $2) }
511         |  'hiding' '(' exportlist ')'          { LL (True,  $3) }
512
513 -----------------------------------------------------------------------------
514 -- Fixity Declarations
515
516 prec    :: { Int }
517         : {- empty -}           { 9 }
518         | INTEGER               {% checkPrecP (L1 (fromInteger (getINTEGER $1))) }
519
520 infix   :: { Located FixityDirection }
521         : 'infix'                               { L1 InfixN  }
522         | 'infixl'                              { L1 InfixL  }
523         | 'infixr'                              { L1 InfixR }
524
525 ops     :: { Located [Located RdrName] }
526         : ops ',' op                            { LL ($3 : unLoc $1) }
527         | op                                    { L1 [$1] }
528
529 -----------------------------------------------------------------------------
530 -- Top-Level Declarations
531
532 topdecls :: { OrdList (LHsDecl RdrName) }
533         : topdecls ';' topdecl                  { $1 `appOL` $3 }
534         | topdecls ';'                          { $1 }
535         | topdecl                               { $1 }
536
537 topdecl :: { OrdList (LHsDecl RdrName) }
538         : cl_decl                       { unitOL (L1 (TyClD (unLoc $1))) }
539         | ty_decl                       { unitOL (L1 (TyClD (unLoc $1))) }
540         | 'instance' inst_type where_inst
541             { let (binds, sigs, ats, _) = cvBindsAndSigs (unLoc $3)
542               in 
543               unitOL (L (comb3 $1 $2 $3) (InstD (InstDecl $2 binds sigs ats)))}
544         | stand_alone_deriving                  { unitOL (LL (DerivD (unLoc $1))) }
545         | 'default' '(' comma_types0 ')'        { unitOL (LL $ DefD (DefaultDecl $3)) }
546         | 'foreign' fdecl                       { unitOL (LL (unLoc $2)) }
547         | '{-# DEPRECATED' deprecations '#-}'   { $2 }
548         | '{-# RULES' rules '#-}'               { $2 }
549         | decl                                  { unLoc $1 }
550
551         -- Template Haskell Extension
552         | '$(' exp ')'                          { unitOL (LL $ SpliceD (SpliceDecl $2)) }
553         | TH_ID_SPLICE                          { unitOL (LL $ SpliceD (SpliceDecl $
554                                                         L1 $ HsVar (mkUnqual varName (getTH_ID_SPLICE $1))
555                                                   )) }
556
557 -- Type classes
558 --
559 cl_decl :: { LTyClDecl RdrName }
560         : 'class' tycl_hdr fds where_cls
561                 {% do { let { (binds, sigs, ats, docs)           = 
562                                 cvBindsAndSigs (unLoc $4)
563                             ; (ctxt, tc, tvs, tparms) = unLoc $2}
564                       ; checkTyVars tparms      -- only type vars allowed
565                       ; checkKindSigs ats
566                       ; return $ L (comb4 $1 $2 $3 $4) 
567                                    (mkClassDecl (ctxt, tc, tvs) 
568                                                 (unLoc $3) sigs binds ats docs) } }
569
570 -- Type declarations (toplevel)
571 --
572 ty_decl :: { LTyClDecl RdrName }
573            -- ordinary type synonyms
574         : 'type' type '=' ctype
575                 -- Note ctype, not sigtype, on the right of '='
576                 -- We allow an explicit for-all but we don't insert one
577                 -- in   type Foo a = (b,b)
578                 -- Instead we just say b is out of scope
579                 --
580                 -- Note the use of type for the head; this allows
581                 -- infix type constructors to be declared 
582                 {% do { (tc, tvs, _) <- checkSynHdr $2 False
583                       ; return (L (comb2 $1 $4) 
584                                   (TySynonym tc tvs Nothing $4))
585                       } }
586
587            -- type family declarations
588         | 'type' 'family' type opt_kind_sig 
589                 -- Note the use of type for the head; this allows
590                 -- infix type constructors to be declared
591                 --
592                 {% do { (tc, tvs, _) <- checkSynHdr $3 False
593                       ; return (L (comb3 $1 $3 $4) 
594                                   (TyFamily TypeFamily tc tvs (unLoc $4)))
595                       } }
596
597            -- type instance declarations
598         | 'type' 'instance' type '=' ctype
599                 -- Note the use of type for the head; this allows
600                 -- infix type constructors and type patterns
601                 --
602                 {% do { (tc, tvs, typats) <- checkSynHdr $3 True
603                       ; return (L (comb2 $1 $5) 
604                                   (TySynonym tc tvs (Just typats) $5)) 
605                       } }
606
607           -- ordinary data type or newtype declaration
608         | data_or_newtype tycl_hdr constrs deriving
609                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $2}
610                       ; checkTyVars tparms    -- no type pattern
611                       ; return $
612                           L (comb4 $1 $2 $3 $4)
613                                    -- We need the location on tycl_hdr in case 
614                                    -- constrs and deriving are both empty
615                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Nothing) 
616                                Nothing (reverse (unLoc $3)) (unLoc $4)) } }
617
618           -- ordinary GADT declaration
619         | data_or_newtype tycl_hdr opt_kind_sig 
620                  'where' gadt_constrlist
621                  deriving
622                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $2}
623                       ; checkTyVars tparms    -- can have type pats
624                       ; return $
625                           L (comb4 $1 $2 $4 $5)
626                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Nothing) 
627                               (unLoc $3) (reverse (unLoc $5)) (unLoc $6)) } }
628
629           -- data/newtype family
630         | 'data' 'family' tycl_hdr opt_kind_sig
631                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $3}
632                       ; checkTyVars tparms            -- no type pattern
633                       ; unless (null (unLoc ctxt)) $  -- and no context
634                           parseError (getLoc ctxt) 
635                             "A family declaration cannot have a context"
636                       ; return $
637                           L (comb3 $1 $2 $4)
638                             (TyFamily DataFamily tc tvs (unLoc $4)) } }
639
640           -- data/newtype instance declaration
641         | data_or_newtype 'instance' tycl_hdr constrs deriving
642                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $3}
643                                              -- can have type pats
644                       ; return $
645                           L (comb4 $1 $3 $4 $5)
646                                    -- We need the location on tycl_hdr in case 
647                                    -- constrs and deriving are both empty
648                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Just tparms) 
649                               Nothing (reverse (unLoc $4)) (unLoc $5)) } }
650
651           -- GADT instance declaration
652         | data_or_newtype 'instance' tycl_hdr opt_kind_sig 
653                  'where' gadt_constrlist
654                  deriving
655                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $3}
656                                              -- can have type pats
657                       ; return $
658                           L (comb4 $1 $3 $6 $7)
659                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Just tparms) 
660                                (unLoc $4) (reverse (unLoc $6)) (unLoc $7)) } }
661
662 -- Associate type family declarations
663 --
664 -- * They have a different syntax than on the toplevel (no family special
665 --   identifier).
666 --
667 -- * They also need to be separate from instances; otherwise, data family
668 --   declarations without a kind signature cause parsing conflicts with empty
669 --   data declarations. 
670 --
671 at_decl_cls :: { LTyClDecl RdrName }
672            -- type family declarations
673         : 'type' type opt_kind_sig
674                 -- Note the use of type for the head; this allows
675                 -- infix type constructors to be declared
676                 --
677                 {% do { (tc, tvs, _) <- checkSynHdr $2 False
678                       ; return (L (comb3 $1 $2 $3) 
679                                   (TyFamily TypeFamily tc tvs (unLoc $3)))
680                       } }
681
682            -- default type instance
683         | 'type' type '=' ctype
684                 -- Note the use of type for the head; this allows
685                 -- infix type constructors and type patterns
686                 --
687                 {% do { (tc, tvs, typats) <- checkSynHdr $2 True
688                       ; return (L (comb2 $1 $4) 
689                                   (TySynonym tc tvs (Just typats) $4)) 
690                       } }
691
692           -- data/newtype family declaration
693         | 'data' tycl_hdr opt_kind_sig
694                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $2}
695                       ; checkTyVars tparms            -- no type pattern
696                       ; unless (null (unLoc ctxt)) $  -- and no context
697                           parseError (getLoc ctxt) 
698                             "A family declaration cannot have a context"
699                       ; return $
700                           L (comb3 $1 $2 $3)
701                             (TyFamily DataFamily tc tvs (unLoc $3)) 
702                       } }
703
704 -- Associate type instances
705 --
706 at_decl_inst :: { LTyClDecl RdrName }
707            -- type instance declarations
708         : 'type' type '=' ctype
709                 -- Note the use of type for the head; this allows
710                 -- infix type constructors and type patterns
711                 --
712                 {% do { (tc, tvs, typats) <- checkSynHdr $2 True
713                       ; return (L (comb2 $1 $4) 
714                                   (TySynonym tc tvs (Just typats) $4)) 
715                       } }
716
717         -- data/newtype instance declaration
718         | data_or_newtype tycl_hdr constrs deriving
719                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $2}
720                                              -- can have type pats
721                       ; return $
722                           L (comb4 $1 $2 $3 $4)
723                                    -- We need the location on tycl_hdr in case 
724                                    -- constrs and deriving are both empty
725                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Just tparms) 
726                               Nothing (reverse (unLoc $3)) (unLoc $4)) } }
727
728         -- GADT instance declaration
729         | data_or_newtype tycl_hdr opt_kind_sig 
730                  'where' gadt_constrlist
731                  deriving
732                 {% do { let {(ctxt, tc, tvs, tparms) = unLoc $2}
733                                              -- can have type pats
734                       ; return $
735                           L (comb4 $1 $2 $5 $6)
736                             (mkTyData (unLoc $1) (ctxt, tc, tvs, Just tparms) 
737                              (unLoc $3) (reverse (unLoc $5)) (unLoc $6)) } }
738
739 data_or_newtype :: { Located NewOrData }
740         : 'data'        { L1 DataType }
741         | 'newtype'     { L1 NewType }
742
743 opt_kind_sig :: { Located (Maybe Kind) }
744         :                               { noLoc Nothing }
745         | '::' kind                     { LL (Just (unLoc $2)) }
746
747 -- tycl_hdr parses the header of a class or data type decl,
748 -- which takes the form
749 --      T a b
750 --      Eq a => T a
751 --      (Eq a, Ord b) => T a b
752 --      T Int [a]                       -- for associated types
753 -- Rather a lot of inlining here, else we get reduce/reduce errors
754 tycl_hdr :: { Located (LHsContext RdrName, 
755                        Located RdrName, 
756                        [LHsTyVarBndr RdrName],
757                        [LHsType RdrName]) }
758         : context '=>' type             {% checkTyClHdr $1         $3 >>= return.LL }
759         | type                          {% checkTyClHdr (noLoc []) $1 >>= return.L1 }
760
761 -----------------------------------------------------------------------------
762 -- Stand-alone deriving
763
764 -- Glasgow extension: stand-alone deriving declarations
765 stand_alone_deriving :: { LDerivDecl RdrName }
766         : 'deriving' 'instance' inst_type {% checkDerivDecl (LL (DerivDecl $3)) }
767
768 -----------------------------------------------------------------------------
769 -- Nested declarations
770
771 -- Declaration in class bodies
772 --
773 decl_cls  :: { Located (OrdList (LHsDecl RdrName)) }
774 decl_cls  : at_decl_cls                 { LL (unitOL (L1 (TyClD (unLoc $1)))) }
775           | decl                        { $1 }
776
777 decls_cls :: { Located (OrdList (LHsDecl RdrName)) }    -- Reversed
778           : decls_cls ';' decl_cls      { LL (unLoc $1 `appOL` unLoc $3) }
779           | decls_cls ';'               { LL (unLoc $1) }
780           | decl_cls                    { $1 }
781           | {- empty -}                 { noLoc nilOL }
782
783
784 decllist_cls
785         :: { Located (OrdList (LHsDecl RdrName)) }      -- Reversed
786         : '{'         decls_cls '}'     { LL (unLoc $2) }
787         |     vocurly decls_cls close   { $2 }
788
789 -- Class body
790 --
791 where_cls :: { Located (OrdList (LHsDecl RdrName)) }    -- Reversed
792                                 -- No implicit parameters
793                                 -- May have type declarations
794         : 'where' decllist_cls          { LL (unLoc $2) }
795         | {- empty -}                   { noLoc nilOL }
796
797 -- Declarations in instance bodies
798 --
799 decl_inst  :: { Located (OrdList (LHsDecl RdrName)) }
800 decl_inst  : at_decl_inst               { LL (unitOL (L1 (TyClD (unLoc $1)))) }
801            | decl                       { $1 }
802
803 decls_inst :: { Located (OrdList (LHsDecl RdrName)) }   -- Reversed
804            : decls_inst ';' decl_inst   { LL (unLoc $1 `appOL` unLoc $3) }
805            | decls_inst ';'             { LL (unLoc $1) }
806            | decl_inst                  { $1 }
807            | {- empty -}                { noLoc nilOL }
808
809 decllist_inst 
810         :: { Located (OrdList (LHsDecl RdrName)) }      -- Reversed
811         : '{'         decls_inst '}'    { LL (unLoc $2) }
812         |     vocurly decls_inst close  { $2 }
813
814 -- Instance body
815 --
816 where_inst :: { Located (OrdList (LHsDecl RdrName)) }   -- Reversed
817                                 -- No implicit parameters
818                                 -- May have type declarations
819         : 'where' decllist_inst         { LL (unLoc $2) }
820         | {- empty -}                   { noLoc nilOL }
821
822 -- Declarations in binding groups other than classes and instances
823 --
824 decls   :: { Located (OrdList (LHsDecl RdrName)) }      
825         : decls ';' decl                { LL (unLoc $1 `appOL` unLoc $3) }
826         | decls ';'                     { LL (unLoc $1) }
827         | decl                          { $1 }
828         | {- empty -}                   { noLoc nilOL }
829
830 decllist :: { Located (OrdList (LHsDecl RdrName)) }
831         : '{'            decls '}'      { LL (unLoc $2) }
832         |     vocurly    decls close    { $2 }
833
834 -- Binding groups other than those of class and instance declarations
835 --
836 binds   ::  { Located (HsLocalBinds RdrName) }          -- May have implicit parameters
837                                                 -- No type declarations
838         : decllist                      { L1 (HsValBinds (cvBindGroup (unLoc $1))) }
839         | '{'            dbinds '}'     { LL (HsIPBinds (IPBinds (unLoc $2) emptyLHsBinds)) }
840         |     vocurly    dbinds close   { L (getLoc $2) (HsIPBinds (IPBinds (unLoc $2) emptyLHsBinds)) }
841
842 wherebinds :: { Located (HsLocalBinds RdrName) }        -- May have implicit parameters
843                                                 -- No type declarations
844         : 'where' binds                 { LL (unLoc $2) }
845         | {- empty -}                   { noLoc emptyLocalBinds }
846
847
848 -----------------------------------------------------------------------------
849 -- Transformation Rules
850
851 rules   :: { OrdList (LHsDecl RdrName) }
852         :  rules ';' rule                       { $1 `snocOL` $3 }
853         |  rules ';'                            { $1 }
854         |  rule                                 { unitOL $1 }
855         |  {- empty -}                          { nilOL }
856
857 rule    :: { LHsDecl RdrName }
858         : STRING activation rule_forall infixexp '=' exp
859              { LL $ RuleD (HsRule (getSTRING $1) 
860                                   ($2 `orElse` AlwaysActive) 
861                                   $3 $4 placeHolderNames $6 placeHolderNames) }
862
863 activation :: { Maybe Activation } 
864         : {- empty -}                           { Nothing }
865         | explicit_activation                   { Just $1 }
866
867 explicit_activation :: { Activation }  -- In brackets
868         : '[' INTEGER ']'               { ActiveAfter  (fromInteger (getINTEGER $2)) }
869         | '[' '~' INTEGER ']'           { ActiveBefore (fromInteger (getINTEGER $3)) }
870
871 rule_forall :: { [RuleBndr RdrName] }
872         : 'forall' rule_var_list '.'            { $2 }
873         | {- empty -}                           { [] }
874
875 rule_var_list :: { [RuleBndr RdrName] }
876         : rule_var                              { [$1] }
877         | rule_var rule_var_list                { $1 : $2 }
878
879 rule_var :: { RuleBndr RdrName }
880         : varid                                 { RuleBndr $1 }
881         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
882
883 -----------------------------------------------------------------------------
884 -- Deprecations (c.f. rules)
885
886 deprecations :: { OrdList (LHsDecl RdrName) }
887         : deprecations ';' deprecation          { $1 `appOL` $3 }
888         | deprecations ';'                      { $1 }
889         | deprecation                           { $1 }
890         | {- empty -}                           { nilOL }
891
892 -- SUP: TEMPORARY HACK, not checking for `module Foo'
893 deprecation :: { OrdList (LHsDecl RdrName) }
894         : depreclist STRING
895                 { toOL [ LL $ DeprecD (Deprecation n (getSTRING $2)) 
896                        | n <- unLoc $1 ] }
897
898
899 -----------------------------------------------------------------------------
900 -- Foreign import and export declarations
901
902 fdecl :: { LHsDecl RdrName }
903 fdecl : 'import' callconv safety fspec
904                 {% mkImport $2 $3 (unLoc $4) >>= return.LL }
905       | 'import' callconv        fspec          
906                 {% do { d <- mkImport $2 (PlaySafe False) (unLoc $3);
907                         return (LL d) } }
908       | 'export' callconv fspec
909                 {% mkExport $2 (unLoc $3) >>= return.LL }
910
911 callconv :: { CallConv }
912           : 'stdcall'                   { CCall  StdCallConv }
913           | 'ccall'                     { CCall  CCallConv   }
914           | 'dotnet'                    { DNCall             }
915
916 safety :: { Safety }
917         : 'unsafe'                      { PlayRisky }
918         | 'safe'                        { PlaySafe  False }
919         | 'threadsafe'                  { PlaySafe  True }
920
921 fspec :: { Located (Located FastString, Located RdrName, LHsType RdrName) }
922        : STRING var '::' sigtypedoc     { LL (L (getLoc $1) (getSTRING $1), $2, $4) }
923        |        var '::' sigtypedoc     { LL (noLoc nilFS, $1, $3) }
924          -- if the entity string is missing, it defaults to the empty string;
925          -- the meaning of an empty entity string depends on the calling
926          -- convention
927
928 -----------------------------------------------------------------------------
929 -- Type signatures
930
931 opt_sig :: { Maybe (LHsType RdrName) }
932         : {- empty -}                   { Nothing }
933         | '::' sigtype                  { Just $2 }
934
935 opt_asig :: { Maybe (LHsType RdrName) }
936         : {- empty -}                   { Nothing }
937         | '::' atype                    { Just $2 }
938
939 sigtypes1 :: { [LHsType RdrName] }
940         : sigtype                       { [ $1 ] }
941         | sigtype ',' sigtypes1         { $1 : $3 }
942
943 sigtype :: { LHsType RdrName }
944         : ctype                         { L1 (mkImplicitHsForAllTy (noLoc []) $1) }
945         -- Wrap an Implicit forall if there isn't one there already
946
947 sigtypedoc :: { LHsType RdrName }
948         : ctypedoc                      { L1 (mkImplicitHsForAllTy (noLoc []) $1) }
949         -- Wrap an Implicit forall if there isn't one there already
950
951 sig_vars :: { Located [Located RdrName] }
952          : sig_vars ',' var             { LL ($3 : unLoc $1) }
953          | var                          { L1 [$1] }
954
955 -----------------------------------------------------------------------------
956 -- Types
957
958 infixtype :: { LHsType RdrName }
959         : btype qtyconop gentype         { LL $ HsOpTy $1 $2 $3 }
960         | btype tyvarop  gentype         { LL $ HsOpTy $1 $2 $3 }
961
962 infixtypedoc :: { LHsType RdrName }
963         : infixtype                      { $1 }
964         | infixtype docprev              { LL $ HsDocTy $1 $2 }
965
966 gentypedoc :: { LHsType RdrName }
967         : btype                          { $1 }
968         | btypedoc                       { $1 }
969         | infixtypedoc                   { $1 }
970         | btype '->' ctypedoc            { LL $ HsFunTy $1 $3 }
971         | btypedoc '->' ctypedoc         { LL $ HsFunTy $1 $3 }
972
973 ctypedoc  :: { LHsType RdrName }
974         : 'forall' tv_bndrs '.' ctypedoc { LL $ mkExplicitHsForAllTy $2 (noLoc []) $4 }
975         | context '=>' ctypedoc          { LL $ mkImplicitHsForAllTy   $1 $3 }
976         -- A type of form (context => type) is an *implicit* HsForAllTy
977         | gentypedoc                     { $1 }
978         
979 strict_mark :: { Located HsBang }
980         : '!'                           { L1 HsStrict }
981         | '{-# UNPACK' '#-}' '!'        { LL HsUnbox }
982
983 -- A ctype is a for-all type
984 ctype   :: { LHsType RdrName }
985         : 'forall' tv_bndrs '.' ctype   { LL $ mkExplicitHsForAllTy $2 (noLoc []) $4 }
986         | context '=>' type             { LL $ mkImplicitHsForAllTy   $1 $3 }
987         -- A type of form (context => type) is an *implicit* HsForAllTy
988         | type                          { $1 }
989
990 -- We parse a context as a btype so that we don't get reduce/reduce
991 -- errors in ctype.  The basic problem is that
992 --      (Eq a, Ord a)
993 -- looks so much like a tuple type.  We can't tell until we find the =>
994 --
995 -- We have the t1 ~ t2 form here and in gentype, to permit an individual
996 -- equational constraint without parenthesis.
997 context :: { LHsContext RdrName }
998         : btype '~'      btype          {% checkContext
999                                              (LL $ HsPredTy (HsEqualP $1 $3)) }
1000         | btype                         {% checkContext $1 }
1001
1002 type :: { LHsType RdrName }
1003         : ipvar '::' gentype            { LL (HsPredTy (HsIParam (unLoc $1) $3)) }
1004         | gentype                       { $1 }
1005
1006 gentype :: { LHsType RdrName }
1007         : btype                         { $1 }
1008         | btype qtyconop gentype        { LL $ HsOpTy $1 $2 $3 }
1009         | btype tyvarop  gentype        { LL $ HsOpTy $1 $2 $3 }
1010         | btype '->'     ctype          { LL $ HsFunTy $1 $3 }
1011         | btype '~'      btype          { LL $ HsPredTy (HsEqualP $1 $3) }
1012
1013 btype :: { LHsType RdrName }
1014         : btype atype                   { LL $ HsAppTy $1 $2 }
1015         | atype                         { $1 }
1016
1017 btypedoc :: { LHsType RdrName }
1018         : btype atype docprev           { LL $ HsDocTy (L (comb2 $1 $2) (HsAppTy $1 $2)) $3 }
1019         | atype docprev                 { LL $ HsDocTy $1 $2 }
1020
1021 atype :: { LHsType RdrName }
1022         : gtycon                        { L1 (HsTyVar (unLoc $1)) }
1023         | tyvar                         { L1 (HsTyVar (unLoc $1)) }
1024         | strict_mark atype             { LL (HsBangTy (unLoc $1) $2) }
1025         | '(' ctype ',' comma_types1 ')'  { LL $ HsTupleTy Boxed  ($2:$4) }
1026         | '(#' comma_types1 '#)'        { LL $ HsTupleTy Unboxed $2     }
1027         | '[' ctype ']'                 { LL $ HsListTy  $2 }
1028         | '[:' ctype ':]'               { LL $ HsPArrTy  $2 }
1029         | '(' ctype ')'                 { LL $ HsParTy   $2 }
1030         | '(' ctype '::' kind ')'       { LL $ HsKindSig $2 (unLoc $4) }
1031 -- Generics
1032         | INTEGER                       { L1 (HsNumTy (getINTEGER $1)) }
1033
1034 -- An inst_type is what occurs in the head of an instance decl
1035 --      e.g.  (Foo a, Gaz b) => Wibble a b
1036 -- It's kept as a single type, with a MonoDictTy at the right
1037 -- hand corner, for convenience.
1038 inst_type :: { LHsType RdrName }
1039         : sigtype                       {% checkInstType $1 }
1040
1041 inst_types1 :: { [LHsType RdrName] }
1042         : inst_type                     { [$1] }
1043         | inst_type ',' inst_types1     { $1 : $3 }
1044
1045 comma_types0  :: { [LHsType RdrName] }
1046         : comma_types1                  { $1 }
1047         | {- empty -}                   { [] }
1048
1049 comma_types1    :: { [LHsType RdrName] }
1050         : ctype                         { [$1] }
1051         | ctype  ',' comma_types1       { $1 : $3 }
1052
1053 tv_bndrs :: { [LHsTyVarBndr RdrName] }
1054          : tv_bndr tv_bndrs             { $1 : $2 }
1055          | {- empty -}                  { [] }
1056
1057 tv_bndr :: { LHsTyVarBndr RdrName }
1058         : tyvar                         { L1 (UserTyVar (unLoc $1)) }
1059         | '(' tyvar '::' kind ')'       { LL (KindedTyVar (unLoc $2) 
1060                                                           (unLoc $4)) }
1061
1062 fds :: { Located [Located ([RdrName], [RdrName])] }
1063         : {- empty -}                   { noLoc [] }
1064         | '|' fds1                      { LL (reverse (unLoc $2)) }
1065
1066 fds1 :: { Located [Located ([RdrName], [RdrName])] }
1067         : fds1 ',' fd                   { LL ($3 : unLoc $1) }
1068         | fd                            { L1 [$1] }
1069
1070 fd :: { Located ([RdrName], [RdrName]) }
1071         : varids0 '->' varids0          { L (comb3 $1 $2 $3)
1072                                            (reverse (unLoc $1), reverse (unLoc $3)) }
1073
1074 varids0 :: { Located [RdrName] }
1075         : {- empty -}                   { noLoc [] }
1076         | varids0 tyvar                 { LL (unLoc $2 : unLoc $1) }
1077
1078 -----------------------------------------------------------------------------
1079 -- Kinds
1080
1081 kind    :: { Located Kind }
1082         : akind                 { $1 }
1083         | akind '->' kind       { LL (mkArrowKind (unLoc $1) (unLoc $3)) }
1084
1085 akind   :: { Located Kind }
1086         : '*'                   { L1 liftedTypeKind }
1087         | '!'                   { L1 unliftedTypeKind }
1088         | '(' kind ')'          { LL (unLoc $2) }
1089
1090
1091 -----------------------------------------------------------------------------
1092 -- Datatype declarations
1093
1094 gadt_constrlist :: { Located [LConDecl RdrName] }
1095         : '{'            gadt_constrs '}'       { LL (unLoc $2) }
1096         |     vocurly    gadt_constrs close     { $2 }
1097
1098 gadt_constrs :: { Located [LConDecl RdrName] }
1099         : gadt_constrs ';' gadt_constr  { LL ($3 : unLoc $1) }
1100         | gadt_constrs ';'              { $1 }
1101         | gadt_constr                   { L1 [$1] } 
1102
1103 -- We allow the following forms:
1104 --      C :: Eq a => a -> T a
1105 --      C :: forall a. Eq a => !a -> T a
1106 --      D { x,y :: a } :: T a
1107 --      forall a. Eq a => D { x,y :: a } :: T a
1108
1109 gadt_constr :: { LConDecl RdrName }
1110         : con '::' sigtype
1111               { LL (mkGadtDecl $1 $3) } 
1112         -- Syntax: Maybe merge the record stuff with the single-case above?
1113         --         (to kill the mostly harmless reduce/reduce error)
1114         -- XXX revisit audreyt
1115         | constr_stuff_record '::' sigtype
1116                 { let (con,details) = unLoc $1 in 
1117                   LL (ConDecl con Implicit [] (noLoc []) details (ResTyGADT $3) Nothing) }
1118 {-
1119         | forall context '=>' constr_stuff_record '::' sigtype
1120                 { let (con,details) = unLoc $4 in 
1121                   LL (ConDecl con Implicit (unLoc $1) $2 details (ResTyGADT $6) Nothing ) }
1122         | forall constr_stuff_record '::' sigtype
1123                 { let (con,details) = unLoc $2 in 
1124                   LL (ConDecl con Implicit (unLoc $1) (noLoc []) details (ResTyGADT $4) Nothing) }
1125 -}
1126
1127
1128 constrs :: { Located [LConDecl RdrName] }
1129         : {- empty; a GHC extension -}  { noLoc [] }
1130         | maybe_docnext '=' constrs1    { L (comb2 $2 $3) (addConDocs (unLoc $3) $1) }
1131
1132 constrs1 :: { Located [LConDecl RdrName] }
1133         : constrs1 maybe_docnext '|' maybe_docprev constr { LL (addConDoc $5 $2 : addConDocFirst (unLoc $1) $4) }
1134         | constr                                          { L1 [$1] }
1135
1136 constr :: { LConDecl RdrName }
1137         : maybe_docnext forall context '=>' constr_stuff maybe_docprev  
1138                 { let (con,details) = unLoc $5 in 
1139                   L (comb4 $2 $3 $4 $5) (ConDecl con Explicit (unLoc $2) $3 details ResTyH98 ($1 `mplus` $6)) }
1140         | maybe_docnext forall constr_stuff maybe_docprev
1141                 { let (con,details) = unLoc $3 in 
1142                   L (comb2 $2 $3) (ConDecl con Explicit (unLoc $2) (noLoc []) details ResTyH98 ($1 `mplus` $4)) }
1143
1144 forall :: { Located [LHsTyVarBndr RdrName] }
1145         : 'forall' tv_bndrs '.'         { LL $2 }
1146         | {- empty -}                   { noLoc [] }
1147
1148 constr_stuff :: { Located (Located RdrName, HsConDeclDetails RdrName) }
1149 -- We parse the constructor declaration 
1150 --      C t1 t2
1151 -- as a btype (treating C as a type constructor) and then convert C to be
1152 -- a data constructor.  Reason: it might continue like this:
1153 --      C t1 t2 %: D Int
1154 -- in which case C really would be a type constructor.  We can't resolve this
1155 -- ambiguity till we come across the constructor oprerator :% (or not, more usually)
1156         : btype                         {% mkPrefixCon $1 [] >>= return.LL }
1157         | oqtycon '{' '}'               {% mkRecCon $1 [] >>= return.LL }
1158         | oqtycon '{' fielddecls '}'    {% mkRecCon $1 $3 >>= return.LL }
1159         | btype conop btype             { LL ($2, InfixCon $1 $3) }
1160
1161 constr_stuff_record :: { Located (Located RdrName, HsConDeclDetails RdrName) }
1162         : oqtycon '{' '}'               {% mkRecCon $1 [] >>= return.sL (comb2 $1 $>) }
1163         | oqtycon '{' fielddecls '}'    {% mkRecCon $1 $3 >>= return.sL (comb2 $1 $>) }
1164
1165 fielddecls :: { [([Located RdrName], LBangType RdrName, Maybe (LHsDoc RdrName))] }
1166         : fielddecl maybe_docnext ',' maybe_docprev fielddecls { addFieldDoc (unLoc $1) $4 : addFieldDocs $5 $2 }
1167         | fielddecl                                            { [unLoc $1] }
1168
1169 fielddecl :: { Located ([Located RdrName], LBangType RdrName, Maybe (LHsDoc RdrName)) }
1170         : maybe_docnext sig_vars '::' ctype maybe_docprev      { L (comb3 $2 $3 $4) (reverse (unLoc $2), $4, $1 `mplus` $5) }
1171
1172 -- We allow the odd-looking 'inst_type' in a deriving clause, so that
1173 -- we can do deriving( forall a. C [a] ) in a newtype (GHC extension).
1174 -- The 'C [a]' part is converted to an HsPredTy by checkInstType
1175 -- We don't allow a context, but that's sorted out by the type checker.
1176 deriving :: { Located (Maybe [LHsType RdrName]) }
1177         : {- empty -}                           { noLoc Nothing }
1178         | 'deriving' qtycon     {% do { let { L loc tv = $2 }
1179                                       ; p <- checkInstType (L loc (HsTyVar tv))
1180                                       ; return (LL (Just [p])) } }
1181         | 'deriving' '(' ')'                    { LL (Just []) }
1182         | 'deriving' '(' inst_types1 ')'        { LL (Just $3) }
1183              -- Glasgow extension: allow partial 
1184              -- applications in derivings
1185
1186 -----------------------------------------------------------------------------
1187 -- Value definitions
1188
1189 {- There's an awkward overlap with a type signature.  Consider
1190         f :: Int -> Int = ...rhs...
1191    Then we can't tell whether it's a type signature or a value
1192    definition with a result signature until we see the '='.
1193    So we have to inline enough to postpone reductions until we know.
1194 -}
1195
1196 {-
1197   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
1198   instead of qvar, we get another shift/reduce-conflict. Consider the
1199   following programs:
1200   
1201      { (^^) :: Int->Int ; }          Type signature; only var allowed
1202
1203      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
1204                                      qvar allowed (because of instance decls)
1205   
1206   We can't tell whether to reduce var to qvar until after we've read the signatures.
1207 -}
1208
1209 docdecl :: { LHsDecl RdrName }
1210         : docdecld { L1 (DocD (unLoc $1)) }
1211
1212 docdecld :: { LDocDecl RdrName }
1213         : docnext                               { L1 (DocCommentNext (unLoc $1)) }
1214         | docprev                               { L1 (DocCommentPrev (unLoc $1)) }
1215         | docnamed                              { L1 (case (unLoc $1) of (n, doc) -> DocCommentNamed n doc) }
1216         | docsection                            { L1 (case (unLoc $1) of (n, doc) -> DocGroup n doc) }
1217
1218 decl    :: { Located (OrdList (LHsDecl RdrName)) }
1219         : sigdecl                       { $1 }
1220         | '!' aexp rhs                  {% do { pat <- checkPattern $2;
1221                                                 return (LL $ unitOL $ LL $ ValD ( 
1222                                                         PatBind (LL $ BangPat pat) (unLoc $3)
1223                                                                 placeHolderType placeHolderNames)) } }
1224         | infixexp opt_sig rhs          {% do { r <- checkValDef $1 $2 $3;
1225                                                 return (LL $ unitOL (LL $ ValD r)) } }
1226         | docdecl                       { LL $ unitOL $1 }
1227
1228 rhs     :: { Located (GRHSs RdrName) }
1229         : '=' exp wherebinds    { L (comb3 $1 $2 $3) $ GRHSs (unguardedRHS $2) (unLoc $3) }
1230         | gdrhs wherebinds      { LL $ GRHSs (reverse (unLoc $1)) (unLoc $2) }
1231
1232 gdrhs :: { Located [LGRHS RdrName] }
1233         : gdrhs gdrh            { LL ($2 : unLoc $1) }
1234         | gdrh                  { L1 [$1] }
1235
1236 gdrh :: { LGRHS RdrName }
1237         : '|' guardquals '=' exp        { sL (comb2 $1 $>) $ GRHS (unLoc $2) $4 }
1238
1239 sigdecl :: { Located (OrdList (LHsDecl RdrName)) }
1240         : infixexp '::' sigtypedoc
1241                                 {% do s <- checkValSig $1 $3; 
1242                                       return (LL $ unitOL (LL $ SigD s)) }
1243                 -- See the above notes for why we need infixexp here
1244         | var ',' sig_vars '::' sigtypedoc
1245                                 { LL $ toOL [ LL $ SigD (TypeSig n $5) | n <- $1 : unLoc $3 ] }
1246         | infix prec ops        { LL $ toOL [ LL $ SigD (FixSig (FixitySig n (Fixity $2 (unLoc $1))))
1247                                              | n <- unLoc $3 ] }
1248         | '{-# INLINE'   activation qvar '#-}'        
1249                                 { LL $ unitOL (LL $ SigD (InlineSig $3 (mkInlineSpec $2 (getINLINE $1)))) }
1250         | '{-# SPECIALISE' qvar '::' sigtypes1 '#-}'
1251                                 { LL $ toOL [ LL $ SigD (SpecSig $2 t defaultInlineSpec) 
1252                                             | t <- $4] }
1253         | '{-# SPECIALISE_INLINE' activation qvar '::' sigtypes1 '#-}'
1254                                 { LL $ toOL [ LL $ SigD (SpecSig $3 t (mkInlineSpec $2 (getSPEC_INLINE $1)))
1255                                             | t <- $5] }
1256         | '{-# SPECIALISE' 'instance' inst_type '#-}'
1257                                 { LL $ unitOL (LL $ SigD (SpecInstSig $3)) }
1258
1259 -----------------------------------------------------------------------------
1260 -- Expressions
1261
1262 exp   :: { LHsExpr RdrName }
1263         : infixexp '::' sigtype         { LL $ ExprWithTySig $1 $3 }
1264         | infixexp '-<' exp             { LL $ HsArrApp $1 $3 placeHolderType HsFirstOrderApp True }
1265         | infixexp '>-' exp             { LL $ HsArrApp $3 $1 placeHolderType HsFirstOrderApp False }
1266         | infixexp '-<<' exp            { LL $ HsArrApp $1 $3 placeHolderType HsHigherOrderApp True }
1267         | infixexp '>>-' exp            { LL $ HsArrApp $3 $1 placeHolderType HsHigherOrderApp False}
1268         | infixexp                      { $1 }
1269
1270 infixexp :: { LHsExpr RdrName }
1271         : exp10                         { $1 }
1272         | infixexp qop exp10            { LL (OpApp $1 $2 (panic "fixity") $3) }
1273
1274 exp10 :: { LHsExpr RdrName }
1275         : '\\' apat apats opt_asig '->' exp     
1276                         { LL $ HsLam (mkMatchGroup [LL $ Match ($2:$3) $4
1277                                                                 (unguardedGRHSs $6)
1278                                                             ]) }
1279         | 'let' binds 'in' exp                  { LL $ HsLet (unLoc $2) $4 }
1280         | 'if' exp 'then' exp 'else' exp        { LL $ HsIf $2 $4 $6 }
1281         | 'case' exp 'of' altslist              { LL $ HsCase $2 (mkMatchGroup (unLoc $4)) }
1282         | '-' fexp                              { LL $ NegApp $2 noSyntaxExpr }
1283
1284         | 'do' stmtlist                 {% let loc = comb2 $1 $2 in
1285                                            checkDo loc (unLoc $2)  >>= \ (stmts,body) ->
1286                                            return (L loc (mkHsDo DoExpr stmts body)) }
1287         | 'mdo' stmtlist                {% let loc = comb2 $1 $2 in
1288                                            checkDo loc (unLoc $2)  >>= \ (stmts,body) ->
1289                                            return (L loc (mkHsDo (MDoExpr noPostTcTable) stmts body)) }
1290         | scc_annot exp                         { LL $ if opt_SccProfilingOn
1291                                                         then HsSCC (unLoc $1) $2
1292                                                         else HsPar $2 }
1293         | hpc_annot exp                         { LL $ if opt_Hpc
1294                                                         then HsTickPragma (unLoc $1) $2
1295                                                         else HsPar $2 }
1296
1297         | 'proc' aexp '->' exp  
1298                         {% checkPattern $2 >>= \ p -> 
1299                            return (LL $ HsProc p (LL $ HsCmdTop $4 [] 
1300                                                    placeHolderType undefined)) }
1301                                                 -- TODO: is LL right here?
1302
1303         | '{-# CORE' STRING '#-}' exp           { LL $ HsCoreAnn (getSTRING $2) $4 }
1304                                                     -- hdaume: core annotation
1305         | fexp                                  { $1 }
1306
1307 scc_annot :: { Located FastString }
1308         : '_scc_' STRING                        {% (addWarning Opt_WarnDeprecations (getLoc $1) (text "_scc_ is deprecated; use an SCC pragma instead")) >>= \_ ->
1309                                    (return $ LL $ getSTRING $2) }
1310         | '{-# SCC' STRING '#-}'                { LL $ getSTRING $2 }
1311
1312 hpc_annot :: { Located (FastString,(Int,Int),(Int,Int)) }
1313         : '{-# GENERATED' STRING INTEGER ':' INTEGER '-' INTEGER ':' INTEGER '#-}'
1314                                                 { LL $ (getSTRING $2
1315                                                        ,( fromInteger $ getINTEGER $3
1316                                                         , fromInteger $ getINTEGER $5
1317                                                         )
1318                                                        ,( fromInteger $ getINTEGER $7
1319                                                         , fromInteger $ getINTEGER $9
1320                                                         )
1321                                                        )
1322                                                  }
1323
1324 fexp    :: { LHsExpr RdrName }
1325         : fexp aexp                             { LL $ HsApp $1 $2 }
1326         | aexp                                  { $1 }
1327
1328 aexp    :: { LHsExpr RdrName }
1329         : qvar '@' aexp                 { LL $ EAsPat $1 $3 }
1330         | '~' aexp                      { LL $ ELazyPat $2 }
1331         | aexp1                 { $1 }
1332
1333 aexp1   :: { LHsExpr RdrName }
1334         : aexp1 '{' fbinds '}'  {% do { r <- mkRecConstrOrUpdate $1 (comb2 $2 $4) $3
1335                                       ; return (LL r) }}
1336         | aexp2                 { $1 }
1337
1338 -- Here was the syntax for type applications that I was planning
1339 -- but there are difficulties (e.g. what order for type args)
1340 -- so it's not enabled yet.
1341 -- But this case *is* used for the left hand side of a generic definition,
1342 -- which is parsed as an expression before being munged into a pattern
1343         | qcname '{|' gentype '|}'      { LL $ HsApp (sL (getLoc $1) (HsVar (unLoc $1)))
1344                                                      (sL (getLoc $3) (HsType $3)) }
1345
1346 aexp2   :: { LHsExpr RdrName }
1347         : ipvar                         { L1 (HsIPVar $! unLoc $1) }
1348         | qcname                        { L1 (HsVar   $! unLoc $1) }
1349         | literal                       { L1 (HsLit   $! unLoc $1) }
1350 -- This will enable overloaded strings permanently.  Normally the renamer turns HsString
1351 -- into HsOverLit when -foverloaded-strings is on.
1352 --      | STRING                        { sL (getLoc $1) (HsOverLit $! mkHsIsString (getSTRING $1) placeHolderType) }
1353         | INTEGER                       { sL (getLoc $1) (HsOverLit $! mkHsIntegral (getINTEGER $1) placeHolderType) }
1354         | RATIONAL                      { sL (getLoc $1) (HsOverLit $! mkHsFractional (getRATIONAL $1) placeHolderType) }
1355         -- N.B.: sections get parsed by these next two productions.
1356         -- This allows you to write, e.g., '(+ 3, 4 -)', which isn't correct Haskell98
1357         -- (you'd have to write '((+ 3), (4 -))')
1358         -- but the less cluttered version fell out of having texps.
1359         | '(' texp ')'                  { LL (HsPar $2) }
1360         | '(' texp ',' texps ')'        { LL $ ExplicitTuple ($2 : reverse $4) Boxed }
1361         | '(#' texps '#)'               { LL $ ExplicitTuple (reverse $2)      Unboxed }
1362         | '[' list ']'                  { LL (unLoc $2) }
1363         | '[:' parr ':]'                { LL (unLoc $2) }
1364         | '_'                           { L1 EWildPat }
1365         
1366         -- Template Haskell Extension
1367         | TH_ID_SPLICE          { L1 $ HsSpliceE (mkHsSplice 
1368                                         (L1 $ HsVar (mkUnqual varName 
1369                                                         (getTH_ID_SPLICE $1)))) } -- $x
1370         | '$(' exp ')'          { LL $ HsSpliceE (mkHsSplice $2) }               -- $( exp )
1371
1372         | TH_QUASIQUOTE         { let { loc = getLoc $1
1373                                       ; ITquasiQuote (quoter, quote, quoteSpan) = unLoc $1
1374                                       ; quoterId = mkUnqual varName quoter
1375                                       }
1376                                   in sL loc $ HsQuasiQuoteE (mkHsQuasiQuote quoterId quoteSpan quote) }
1377         | TH_VAR_QUOTE qvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1378         | TH_VAR_QUOTE qcon     { LL $ HsBracket (VarBr (unLoc $2)) }
1379         | TH_TY_QUOTE tyvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1380         | TH_TY_QUOTE gtycon    { LL $ HsBracket (VarBr (unLoc $2)) }
1381         | '[|' exp '|]'         { LL $ HsBracket (ExpBr $2) }                       
1382         | '[t|' ctype '|]'      { LL $ HsBracket (TypBr $2) }                       
1383         | '[p|' infixexp '|]'   {% checkPattern $2 >>= \p ->
1384                                         return (LL $ HsBracket (PatBr p)) }
1385         | '[d|' cvtopbody '|]'  {% checkDecBrGroup $2 >>= \g -> 
1386                                         return (LL $ HsBracket (DecBr g)) }
1387
1388         -- arrow notation extension
1389         | '(|' aexp2 cmdargs '|)'       { LL $ HsArrForm $2 Nothing (reverse $3) }
1390
1391 cmdargs :: { [LHsCmdTop RdrName] }
1392         : cmdargs acmd                  { $2 : $1 }
1393         | {- empty -}                   { [] }
1394
1395 acmd    :: { LHsCmdTop RdrName }
1396         : aexp2                 { L1 $ HsCmdTop $1 [] placeHolderType undefined }
1397
1398 cvtopbody :: { [LHsDecl RdrName] }
1399         :  '{'            cvtopdecls0 '}'               { $2 }
1400         |      vocurly    cvtopdecls0 close             { $2 }
1401
1402 cvtopdecls0 :: { [LHsDecl RdrName] }
1403         : {- empty -}           { [] }
1404         | cvtopdecls            { $1 }
1405
1406 -- tuple expressions: things that can appear unparenthesized as long as they're
1407 -- inside parens or delimitted by commas
1408 texp :: { LHsExpr RdrName }
1409         : exp                           { $1 }
1410         -- Technically, this should only be used for bang patterns,
1411        -- but we can be a little more liberal here and avoid parens
1412        -- inside tuples
1413        | infixexp qop   { LL $ SectionL $1 $2 }
1414         | qopm infixexp       { LL $ SectionR $1 $2 }
1415        -- view patterns get parenthesized above
1416         | exp '->' exp   { LL $ EViewPat $1 $3 }
1417
1418 texps :: { [LHsExpr RdrName] }
1419         : texps ',' texp                { $3 : $1 }
1420         | texp                          { [$1] }
1421
1422
1423 -----------------------------------------------------------------------------
1424 -- List expressions
1425
1426 -- The rules below are little bit contorted to keep lexps left-recursive while
1427 -- avoiding another shift/reduce-conflict.
1428
1429 list :: { LHsExpr RdrName }
1430         : texp                  { L1 $ ExplicitList placeHolderType [$1] }
1431         | lexps                 { L1 $ ExplicitList placeHolderType (reverse (unLoc $1)) }
1432         | texp '..'             { LL $ ArithSeq noPostTcExpr (From $1) }
1433         | texp ',' exp '..'     { LL $ ArithSeq noPostTcExpr (FromThen $1 $3) }
1434         | texp '..' exp         { LL $ ArithSeq noPostTcExpr (FromTo $1 $3) }
1435         | texp ',' exp '..' exp { LL $ ArithSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1436         | texp '|' flattenedpquals      { sL (comb2 $1 $>) $ mkHsDo ListComp (unLoc $3) $1 }
1437
1438 lexps :: { Located [LHsExpr RdrName] }
1439         : lexps ',' texp                { LL ($3 : unLoc $1) }
1440         | texp ',' texp                 { LL [$3,$1] }
1441
1442 -----------------------------------------------------------------------------
1443 -- List Comprehensions
1444
1445 flattenedpquals :: { Located [LStmt RdrName] }
1446     : pquals   { case (unLoc $1) of
1447                     ParStmt [(qs, _)] -> L1 qs
1448                     -- We just had one thing in our "parallel" list so 
1449                     -- we simply return that thing directly
1450                     
1451                     _ -> L1 [$1]
1452                     -- We actually found some actual parallel lists so
1453                     -- we leave them into as a ParStmt
1454                 }
1455
1456 pquals :: { LStmt RdrName }
1457     : pquals1   { L1 (ParStmt [(qs, undefined) | qs <- (reverse (unLoc $1))]) }
1458
1459 pquals1 :: { Located [[LStmt RdrName]] }
1460     : pquals1 '|' squals    { LL (unLoc $3 : unLoc $1) }
1461     | squals                { L (getLoc $1) [unLoc $1] }
1462
1463 squals :: { Located [LStmt RdrName] }
1464     : squals1               { L (getLoc $1) (reverse (unLoc $1)) }
1465
1466 squals1 :: { Located [LStmt RdrName] }
1467     : transformquals1       { LL (unLoc $1) }
1468
1469 transformquals1 :: { Located [LStmt RdrName] }
1470     : transformquals1 ',' transformqual         { LL $ [LL ((unLoc $3) (unLoc $1))] }
1471     | transformquals1 ',' qual                  { LL ($3 : unLoc $1) }
1472 --  | transformquals1 ',' '{|' pquals '|}'      { LL ($4 : unLoc $1) }
1473     | transformqual                             { LL $ [LL ((unLoc $1) [])] }
1474     | qual                                      { L1 [$1] }
1475 --  | '{|' pquals '|}'                          { L1 [$2] }
1476
1477
1478 -- It is possible to enable bracketing (associating) qualifier lists by uncommenting the lines with {| |}
1479 -- above. Due to a lack of consensus on the syntax, this feature is not being used until we get user
1480 -- demand. Note that the {| |} symbols are reused from -XGenerics and hence if you want to compile
1481 -- a program that makes use of this temporary syntax you must supply that flag to GHC
1482
1483 transformqual :: { Located ([LStmt RdrName] -> Stmt RdrName) }
1484     : 'then' exp                { LL $ \leftStmts -> (mkTransformStmt (reverse leftStmts) $2) }
1485     | 'then' exp 'by' exp       { LL $ \leftStmts -> (mkTransformByStmt (reverse leftStmts) $2 $4) }
1486     | 'then' 'group' 'by' exp              { LL $ \leftStmts -> (mkGroupByStmt (reverse leftStmts) $4) }
1487     | 'then' 'group' 'using' exp           { LL $ \leftStmts -> (mkGroupUsingStmt (reverse leftStmts) $4) }
1488     | 'then' 'group' 'by' exp 'using' exp  { LL $ \leftStmts -> (mkGroupByUsingStmt (reverse leftStmts) $4 $6) }
1489
1490 -----------------------------------------------------------------------------
1491 -- Parallel array expressions
1492
1493 -- The rules below are little bit contorted; see the list case for details.
1494 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1495 -- Moreover, we allow explicit arrays with no element (represented by the nil
1496 -- constructor in the list case).
1497
1498 parr :: { LHsExpr RdrName }
1499         :                               { noLoc (ExplicitPArr placeHolderType []) }
1500         | texp                          { L1 $ ExplicitPArr placeHolderType [$1] }
1501         | lexps                         { L1 $ ExplicitPArr placeHolderType 
1502                                                        (reverse (unLoc $1)) }
1503         | texp '..' exp                 { LL $ PArrSeq noPostTcExpr (FromTo $1 $3) }
1504         | texp ',' exp '..' exp         { LL $ PArrSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1505         | texp '|' flattenedpquals      { LL $ mkHsDo PArrComp (unLoc $3) $1 }
1506
1507 -- We are reusing `lexps' and `flattenedpquals' from the list case.
1508
1509 -----------------------------------------------------------------------------
1510 -- Guards
1511
1512 guardquals :: { Located [LStmt RdrName] }
1513     : guardquals1           { L (getLoc $1) (reverse (unLoc $1)) }
1514
1515 guardquals1 :: { Located [LStmt RdrName] }
1516     : guardquals1 ',' qual  { LL ($3 : unLoc $1) }
1517     | qual                  { L1 [$1] }
1518
1519 -----------------------------------------------------------------------------
1520 -- Case alternatives
1521
1522 altslist :: { Located [LMatch RdrName] }
1523         : '{'            alts '}'       { LL (reverse (unLoc $2)) }
1524         |     vocurly    alts  close    { L (getLoc $2) (reverse (unLoc $2)) }
1525
1526 alts    :: { Located [LMatch RdrName] }
1527         : alts1                         { L1 (unLoc $1) }
1528         | ';' alts                      { LL (unLoc $2) }
1529
1530 alts1   :: { Located [LMatch RdrName] }
1531         : alts1 ';' alt                 { LL ($3 : unLoc $1) }
1532         | alts1 ';'                     { LL (unLoc $1) }
1533         | alt                           { L1 [$1] }
1534
1535 alt     :: { LMatch RdrName }
1536         : pat opt_sig alt_rhs           { LL (Match [$1] $2 (unLoc $3)) }
1537
1538 alt_rhs :: { Located (GRHSs RdrName) }
1539         : ralt wherebinds               { LL (GRHSs (unLoc $1) (unLoc $2)) }
1540
1541 ralt :: { Located [LGRHS RdrName] }
1542         : '->' exp                      { LL (unguardedRHS $2) }
1543         | gdpats                        { L1 (reverse (unLoc $1)) }
1544
1545 gdpats :: { Located [LGRHS RdrName] }
1546         : gdpats gdpat                  { LL ($2 : unLoc $1) }
1547         | gdpat                         { L1 [$1] }
1548
1549 gdpat   :: { LGRHS RdrName }
1550         : '|' guardquals '->' exp               { sL (comb2 $1 $>) $ GRHS (unLoc $2) $4 }
1551
1552 -- 'pat' recognises a pattern, including one with a bang at the top
1553 --      e.g.  "!x" or "!(x,y)" or "C a b" etc
1554 -- Bangs inside are parsed as infix operator applications, so that
1555 -- we parse them right when bang-patterns are off
1556 pat     :: { LPat RdrName }
1557 pat     :  exp                  {% checkPattern $1 }
1558         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1559
1560 apat   :: { LPat RdrName }      
1561 apat    : aexp                  {% checkPattern $1 }
1562         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1563
1564 apats  :: { [LPat RdrName] }
1565         : apat apats            { $1 : $2 }
1566         | {- empty -}           { [] }
1567
1568 -----------------------------------------------------------------------------
1569 -- Statement sequences
1570
1571 stmtlist :: { Located [LStmt RdrName] }
1572         : '{'           stmts '}'       { LL (unLoc $2) }
1573         |     vocurly   stmts close     { $2 }
1574
1575 --      do { ;; s ; s ; ; s ;; }
1576 -- The last Stmt should be an expression, but that's hard to enforce
1577 -- here, because we need too much lookahead if we see do { e ; }
1578 -- So we use ExprStmts throughout, and switch the last one over
1579 -- in ParseUtils.checkDo instead
1580 stmts :: { Located [LStmt RdrName] }
1581         : stmt stmts_help               { LL ($1 : unLoc $2) }
1582         | ';' stmts                     { LL (unLoc $2) }
1583         | {- empty -}                   { noLoc [] }
1584
1585 stmts_help :: { Located [LStmt RdrName] } -- might be empty
1586         : ';' stmts                     { LL (unLoc $2) }
1587         | {- empty -}                   { noLoc [] }
1588
1589 -- For typing stmts at the GHCi prompt, where 
1590 -- the input may consist of just comments.
1591 maybe_stmt :: { Maybe (LStmt RdrName) }
1592         : stmt                          { Just $1 }
1593         | {- nothing -}                 { Nothing }
1594
1595 stmt  :: { LStmt RdrName }
1596         : qual                              { $1 }
1597         | 'rec' stmtlist                { LL $ mkRecStmt (unLoc $2) }
1598
1599 qual  :: { LStmt RdrName }
1600     : pat '<-' exp                      { LL $ mkBindStmt $1 $3 }
1601     | exp                                   { L1 $ mkExprStmt $1 }
1602     | 'let' binds                       { LL $ LetStmt (unLoc $2) }
1603
1604 -----------------------------------------------------------------------------
1605 -- Record Field Update/Construction
1606
1607 fbinds  :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1608         : fbinds1                       { $1 }
1609         | {- empty -}                   { ([], False) }
1610
1611 fbinds1 :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1612         : fbind ',' fbinds1             { case $3 of (flds, dd) -> ($1 : flds, dd) } 
1613         | fbind                         { ([$1], False) }
1614         | '..'                          { ([],   True) }
1615   
1616 fbind   :: { HsRecField RdrName (LHsExpr RdrName) }
1617         : qvar '=' exp  { HsRecField $1 $3 False }
1618         | qvar          { HsRecField $1 (L (getLoc $1) (HsVar (unLoc $1))) True }
1619                         -- Here's where we say that plain 'x'
1620                         -- means exactly 'x = x'.  The pun-flag boolean is
1621                         -- there so we can still print it right
1622
1623 -----------------------------------------------------------------------------
1624 -- Implicit Parameter Bindings
1625
1626 dbinds  :: { Located [LIPBind RdrName] }
1627         : dbinds ';' dbind              { LL ($3 : unLoc $1) }
1628         | dbinds ';'                    { LL (unLoc $1) }
1629         | dbind                         { L1 [$1] }
1630 --      | {- empty -}                   { [] }
1631
1632 dbind   :: { LIPBind RdrName }
1633 dbind   : ipvar '=' exp                 { LL (IPBind (unLoc $1) $3) }
1634
1635 ipvar   :: { Located (IPName RdrName) }
1636         : IPDUPVARID            { L1 (IPName (mkUnqual varName (getIPDUPVARID $1))) }
1637
1638 -----------------------------------------------------------------------------
1639 -- Deprecations
1640
1641 depreclist :: { Located [RdrName] }
1642 depreclist : deprec_var                 { L1 [unLoc $1] }
1643            | deprec_var ',' depreclist  { LL (unLoc $1 : unLoc $3) }
1644
1645 deprec_var :: { Located RdrName }
1646 deprec_var : var                        { $1 }
1647            | con                        { $1 }
1648
1649 -----------------------------------------
1650 -- Data constructors
1651 qcon    :: { Located RdrName }
1652         : qconid                { $1 }
1653         | '(' qconsym ')'       { LL (unLoc $2) }
1654         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1655 -- The case of '[:' ':]' is part of the production `parr'
1656
1657 con     :: { Located RdrName }
1658         : conid                 { $1 }
1659         | '(' consym ')'        { LL (unLoc $2) }
1660         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1661
1662 sysdcon :: { Located DataCon }  -- Wired in data constructors
1663         : '(' ')'               { LL unitDataCon }
1664         | '(' commas ')'        { LL $ tupleCon Boxed $2 }
1665         | '(#' '#)'             { LL $ unboxedSingletonDataCon }
1666         | '(#' commas '#)'      { LL $ tupleCon Unboxed $2 }
1667         | '[' ']'               { LL nilDataCon }
1668
1669 conop :: { Located RdrName }
1670         : consym                { $1 }  
1671         | '`' conid '`'         { LL (unLoc $2) }
1672
1673 qconop :: { Located RdrName }
1674         : qconsym               { $1 }
1675         | '`' qconid '`'        { LL (unLoc $2) }
1676
1677 -----------------------------------------------------------------------------
1678 -- Type constructors
1679
1680 gtycon  :: { Located RdrName }  -- A "general" qualified tycon
1681         : oqtycon                       { $1 }
1682         | '(' ')'                       { LL $ getRdrName unitTyCon }
1683         | '(' commas ')'                { LL $ getRdrName (tupleTyCon Boxed $2) }
1684         | '(#' '#)'                     { LL $ getRdrName unboxedSingletonTyCon }
1685         | '(#' commas '#)'              { LL $ getRdrName (tupleTyCon Unboxed $2) }
1686         | '(' '->' ')'                  { LL $ getRdrName funTyCon }
1687         | '[' ']'                       { LL $ listTyCon_RDR }
1688         | '[:' ':]'                     { LL $ parrTyCon_RDR }
1689
1690 oqtycon :: { Located RdrName }  -- An "ordinary" qualified tycon
1691         : qtycon                        { $1 }
1692         | '(' qtyconsym ')'             { LL (unLoc $2) }
1693
1694 qtyconop :: { Located RdrName } -- Qualified or unqualified
1695         : qtyconsym                     { $1 }
1696         | '`' qtycon '`'                { LL (unLoc $2) }
1697
1698 qtycon :: { Located RdrName }   -- Qualified or unqualified
1699         : QCONID                        { L1 $! mkQual tcClsName (getQCONID $1) }
1700         | tycon                         { $1 }
1701
1702 tycon   :: { Located RdrName }  -- Unqualified
1703         : CONID                         { L1 $! mkUnqual tcClsName (getCONID $1) }
1704
1705 qtyconsym :: { Located RdrName }
1706         : QCONSYM                       { L1 $! mkQual tcClsName (getQCONSYM $1) }
1707         | tyconsym                      { $1 }
1708
1709 tyconsym :: { Located RdrName }
1710         : CONSYM                        { L1 $! mkUnqual tcClsName (getCONSYM $1) }
1711
1712 -----------------------------------------------------------------------------
1713 -- Operators
1714
1715 op      :: { Located RdrName }   -- used in infix decls
1716         : varop                 { $1 }
1717         | conop                 { $1 }
1718
1719 varop   :: { Located RdrName }
1720         : varsym                { $1 }
1721         | '`' varid '`'         { LL (unLoc $2) }
1722
1723 qop     :: { LHsExpr RdrName }   -- used in sections
1724         : qvarop                { L1 $ HsVar (unLoc $1) }
1725         | qconop                { L1 $ HsVar (unLoc $1) }
1726
1727 qopm    :: { LHsExpr RdrName }   -- used in sections
1728         : qvaropm               { L1 $ HsVar (unLoc $1) }
1729         | qconop                { L1 $ HsVar (unLoc $1) }
1730
1731 qvarop :: { Located RdrName }
1732         : qvarsym               { $1 }
1733         | '`' qvarid '`'        { LL (unLoc $2) }
1734
1735 qvaropm :: { Located RdrName }
1736         : qvarsym_no_minus      { $1 }
1737         | '`' qvarid '`'        { LL (unLoc $2) }
1738
1739 -----------------------------------------------------------------------------
1740 -- Type variables
1741
1742 tyvar   :: { Located RdrName }
1743 tyvar   : tyvarid               { $1 }
1744         | '(' tyvarsym ')'      { LL (unLoc $2) }
1745
1746 tyvarop :: { Located RdrName }
1747 tyvarop : '`' tyvarid '`'       { LL (unLoc $2) }
1748         | tyvarsym              { $1 }
1749
1750 tyvarid :: { Located RdrName }
1751         : VARID                 { L1 $! mkUnqual tvName (getVARID $1) }
1752         | special_id            { L1 $! mkUnqual tvName (unLoc $1) }
1753         | 'unsafe'              { L1 $! mkUnqual tvName FSLIT("unsafe") }
1754         | 'safe'                { L1 $! mkUnqual tvName FSLIT("safe") }
1755         | 'threadsafe'          { L1 $! mkUnqual tvName FSLIT("threadsafe") }
1756
1757 tyvarsym :: { Located RdrName }
1758 -- Does not include "!", because that is used for strictness marks
1759 --               or ".", because that separates the quantified type vars from the rest
1760 --               or "*", because that's used for kinds
1761 tyvarsym : VARSYM               { L1 $! mkUnqual tvName (getVARSYM $1) }
1762
1763 -----------------------------------------------------------------------------
1764 -- Variables 
1765
1766 var     :: { Located RdrName }
1767         : varid                 { $1 }
1768         | '(' varsym ')'        { LL (unLoc $2) }
1769
1770 qvar    :: { Located RdrName }
1771         : qvarid                { $1 }
1772         | '(' varsym ')'        { LL (unLoc $2) }
1773         | '(' qvarsym1 ')'      { LL (unLoc $2) }
1774 -- We've inlined qvarsym here so that the decision about
1775 -- whether it's a qvar or a var can be postponed until
1776 -- *after* we see the close paren.
1777
1778 qvarid :: { Located RdrName }
1779         : varid                 { $1 }
1780         | QVARID                { L1 $ mkQual varName (getQVARID $1) }
1781
1782 varid :: { Located RdrName }
1783         : varid_no_unsafe       { $1 }
1784         | 'unsafe'              { L1 $! mkUnqual varName FSLIT("unsafe") }
1785         | 'safe'                { L1 $! mkUnqual varName FSLIT("safe") }
1786         | 'threadsafe'          { L1 $! mkUnqual varName FSLIT("threadsafe") }
1787
1788 varid_no_unsafe :: { Located RdrName }
1789         : VARID                 { L1 $! mkUnqual varName (getVARID $1) }
1790         | special_id            { L1 $! mkUnqual varName (unLoc $1) }
1791         | 'forall'              { L1 $! mkUnqual varName FSLIT("forall") }
1792         | 'family'              { L1 $! mkUnqual varName FSLIT("family") }
1793
1794 qvarsym :: { Located RdrName }
1795         : varsym                { $1 }
1796         | qvarsym1              { $1 }
1797
1798 qvarsym_no_minus :: { Located RdrName }
1799         : varsym_no_minus       { $1 }
1800         | qvarsym1              { $1 }
1801
1802 qvarsym1 :: { Located RdrName }
1803 qvarsym1 : QVARSYM              { L1 $ mkQual varName (getQVARSYM $1) }
1804
1805 varsym :: { Located RdrName }
1806         : varsym_no_minus       { $1 }
1807         | '-'                   { L1 $ mkUnqual varName FSLIT("-") }
1808
1809 varsym_no_minus :: { Located RdrName } -- varsym not including '-'
1810         : VARSYM                { L1 $ mkUnqual varName (getVARSYM $1) }
1811         | special_sym           { L1 $ mkUnqual varName (unLoc $1) }
1812
1813
1814 -- These special_ids are treated as keywords in various places, 
1815 -- but as ordinary ids elsewhere.   'special_id' collects all these
1816 -- except 'unsafe', 'forall', and 'family' whose treatment differs
1817 -- depending on context 
1818 special_id :: { Located FastString }
1819 special_id
1820         : 'as'                  { L1 FSLIT("as") }
1821         | 'qualified'           { L1 FSLIT("qualified") }
1822         | 'hiding'              { L1 FSLIT("hiding") }
1823         | 'export'              { L1 FSLIT("export") }
1824         | 'label'               { L1 FSLIT("label")  }
1825         | 'dynamic'             { L1 FSLIT("dynamic") }
1826         | 'stdcall'             { L1 FSLIT("stdcall") }
1827         | 'ccall'               { L1 FSLIT("ccall") }
1828
1829 special_sym :: { Located FastString }
1830 special_sym : '!'       { L1 FSLIT("!") }
1831             | '.'       { L1 FSLIT(".") }
1832             | '*'       { L1 FSLIT("*") }
1833
1834 -----------------------------------------------------------------------------
1835 -- Data constructors
1836
1837 qconid :: { Located RdrName }   -- Qualified or unqualified
1838         : conid                 { $1 }
1839         | QCONID                { L1 $ mkQual dataName (getQCONID $1) }
1840
1841 conid   :: { Located RdrName }
1842         : CONID                 { L1 $ mkUnqual dataName (getCONID $1) }
1843
1844 qconsym :: { Located RdrName }  -- Qualified or unqualified
1845         : consym                { $1 }
1846         | QCONSYM               { L1 $ mkQual dataName (getQCONSYM $1) }
1847
1848 consym :: { Located RdrName }
1849         : CONSYM                { L1 $ mkUnqual dataName (getCONSYM $1) }
1850
1851         -- ':' means only list cons
1852         | ':'                   { L1 $ consDataCon_RDR }
1853
1854
1855 -----------------------------------------------------------------------------
1856 -- Literals
1857
1858 literal :: { Located HsLit }
1859         : CHAR                  { L1 $ HsChar       $ getCHAR $1 }
1860         | STRING                { L1 $ HsString     $ getSTRING $1 }
1861         | PRIMINTEGER           { L1 $ HsIntPrim    $ getPRIMINTEGER $1 }
1862         | PRIMCHAR              { L1 $ HsCharPrim   $ getPRIMCHAR $1 }
1863         | PRIMSTRING            { L1 $ HsStringPrim $ getPRIMSTRING $1 }
1864         | PRIMFLOAT             { L1 $ HsFloatPrim  $ getPRIMFLOAT $1 }
1865         | PRIMDOUBLE            { L1 $ HsDoublePrim $ getPRIMDOUBLE $1 }
1866
1867 -----------------------------------------------------------------------------
1868 -- Layout
1869
1870 close :: { () }
1871         : vccurly               { () } -- context popped in lexer.
1872         | error                 {% popContext }
1873
1874 -----------------------------------------------------------------------------
1875 -- Miscellaneous (mostly renamings)
1876
1877 modid   :: { Located ModuleName }
1878         : CONID                 { L1 $ mkModuleNameFS (getCONID $1) }
1879         | QCONID                { L1 $ let (mod,c) = getQCONID $1 in
1880                                   mkModuleNameFS
1881                                    (mkFastString
1882                                      (unpackFS mod ++ '.':unpackFS c))
1883                                 }
1884
1885 commas :: { Int }
1886         : commas ','                    { $1 + 1 }
1887         | ','                           { 2 }
1888
1889 -----------------------------------------------------------------------------
1890 -- Documentation comments
1891
1892 docnext :: { LHsDoc RdrName }
1893   : DOCNEXT {% case parseHaddockParagraphs (tokenise (getDOCNEXT $1)) of {
1894       MyLeft  err -> parseError (getLoc $1) err;
1895       MyRight doc -> return (L1 doc) } }
1896
1897 docprev :: { LHsDoc RdrName }
1898   : DOCPREV {% case parseHaddockParagraphs (tokenise (getDOCPREV $1)) of {
1899       MyLeft  err -> parseError (getLoc $1) err;
1900       MyRight doc -> return (L1 doc) } }
1901
1902 docnamed :: { Located (String, (HsDoc RdrName)) }
1903   : DOCNAMED {%
1904       let string = getDOCNAMED $1 
1905           (name, rest) = break isSpace string
1906       in case parseHaddockParagraphs (tokenise rest) of {
1907         MyLeft  err -> parseError (getLoc $1) err;
1908         MyRight doc -> return (L1 (name, doc)) } }
1909
1910 docsection :: { Located (Int, HsDoc RdrName) }
1911   : DOCSECTION {% let (n, doc) = getDOCSECTION $1 in
1912         case parseHaddockString (tokenise doc) of {
1913       MyLeft  err -> parseError (getLoc $1) err;
1914       MyRight doc -> return (L1 (n, doc)) } }
1915
1916 moduleheader :: { (HaddockModInfo RdrName, Maybe (HsDoc RdrName)) }                                    
1917         : DOCNEXT {% let string = getDOCNEXT $1 in
1918                case parseModuleHeader string of {                       
1919                  Right (str, info) ->                                  
1920                    case parseHaddockParagraphs (tokenise str) of {               
1921                      MyLeft err -> parseError (getLoc $1) err;                    
1922                      MyRight doc -> return (info, Just doc);          
1923                    };                                             
1924                  Left err -> parseError (getLoc $1) err
1925             }  }                                                  
1926
1927 maybe_docprev :: { Maybe (LHsDoc RdrName) }
1928         : docprev                       { Just $1 }
1929         | {- empty -}                   { Nothing }
1930
1931 maybe_docnext :: { Maybe (LHsDoc RdrName) }
1932         : docnext                       { Just $1 }
1933         | {- empty -}                   { Nothing }
1934
1935 {
1936 happyError :: P a
1937 happyError = srcParseFail
1938
1939 getVARID        (L _ (ITvarid    x)) = x
1940 getCONID        (L _ (ITconid    x)) = x
1941 getVARSYM       (L _ (ITvarsym   x)) = x
1942 getCONSYM       (L _ (ITconsym   x)) = x
1943 getQVARID       (L _ (ITqvarid   x)) = x
1944 getQCONID       (L _ (ITqconid   x)) = x
1945 getQVARSYM      (L _ (ITqvarsym  x)) = x
1946 getQCONSYM      (L _ (ITqconsym  x)) = x
1947 getIPDUPVARID   (L _ (ITdupipvarid   x)) = x
1948 getCHAR         (L _ (ITchar     x)) = x
1949 getSTRING       (L _ (ITstring   x)) = x
1950 getINTEGER      (L _ (ITinteger  x)) = x
1951 getRATIONAL     (L _ (ITrational x)) = x
1952 getPRIMCHAR     (L _ (ITprimchar   x)) = x
1953 getPRIMSTRING   (L _ (ITprimstring x)) = x
1954 getPRIMINTEGER  (L _ (ITprimint    x)) = x
1955 getPRIMFLOAT    (L _ (ITprimfloat  x)) = x
1956 getPRIMDOUBLE   (L _ (ITprimdouble x)) = x
1957 getTH_ID_SPLICE (L _ (ITidEscape x)) = x
1958 getINLINE       (L _ (ITinline_prag b)) = b
1959 getSPEC_INLINE  (L _ (ITspec_inline_prag b)) = b
1960
1961 getDOCNEXT (L _ (ITdocCommentNext x)) = x
1962 getDOCPREV (L _ (ITdocCommentPrev x)) = x
1963 getDOCNAMED (L _ (ITdocCommentNamed x)) = x
1964 getDOCSECTION (L _ (ITdocSection n x)) = (n, x)
1965
1966 -- Utilities for combining source spans
1967 comb2 :: Located a -> Located b -> SrcSpan
1968 comb2 = combineLocs
1969
1970 comb3 :: Located a -> Located b -> Located c -> SrcSpan
1971 comb3 a b c = combineSrcSpans (getLoc a) (combineSrcSpans (getLoc b) (getLoc c))
1972
1973 comb4 :: Located a -> Located b -> Located c -> Located d -> SrcSpan
1974 comb4 a b c d = combineSrcSpans (getLoc a) $ combineSrcSpans (getLoc b) $
1975                 combineSrcSpans (getLoc c) (getLoc d)
1976
1977 -- strict constructor version:
1978 {-# INLINE sL #-}
1979 sL :: SrcSpan -> a -> Located a
1980 sL span a = span `seq` L span a
1981
1982 -- Make a source location for the file.  We're a bit lazy here and just
1983 -- make a point SrcSpan at line 1, column 0.  Strictly speaking we should
1984 -- try to find the span of the whole file (ToDo).
1985 fileSrcSpan :: P SrcSpan
1986 fileSrcSpan = do 
1987   l <- getSrcLoc; 
1988   let loc = mkSrcLoc (srcLocFile l) 1 0;
1989   return (mkSrcSpan loc loc)
1990 }