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