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