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