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