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