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