Adding a GENERATED pragma
[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  'do'           { L _ ITdo }
182  'else'         { L _ ITelse }
183  'for'          { L _ ITfor }
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         : 'deriving' qtycon            'for' qtycon  {% do { p <- checkInstType (fmap HsTyVar $2)
744                                                            ; checkDerivDecl (LL (DerivDecl p $4)) } }
745
746         | 'deriving' '(' inst_type ')' 'for' qtycon  {% checkDerivDecl (LL (DerivDecl $3 $6)) }
747
748 -----------------------------------------------------------------------------
749 -- Nested declarations
750
751 -- Declaration in class bodies
752 --
753 decl_cls  :: { Located (OrdList (LHsDecl RdrName)) }
754 decl_cls  : at_decl_cls                 { LL (unitOL (L1 (TyClD (unLoc $1)))) }
755           | decl                        { $1 }
756
757 decls_cls :: { Located (OrdList (LHsDecl RdrName)) }    -- Reversed
758           : decls_cls ';' decl_cls      { LL (unLoc $1 `appOL` unLoc $3) }
759           | decls_cls ';'               { LL (unLoc $1) }
760           | decl_cls                    { $1 }
761           | {- empty -}                 { noLoc nilOL }
762
763
764 decllist_cls
765         :: { Located (OrdList (LHsDecl RdrName)) }      -- Reversed
766         : '{'         decls_cls '}'     { LL (unLoc $2) }
767         |     vocurly decls_cls close   { $2 }
768
769 -- Class body
770 --
771 where_cls :: { Located (OrdList (LHsDecl RdrName)) }    -- Reversed
772                                 -- No implicit parameters
773                                 -- May have type declarations
774         : 'where' decllist_cls          { LL (unLoc $2) }
775         | {- empty -}                   { noLoc nilOL }
776
777 -- Declarations in instance bodies
778 --
779 decl_inst  :: { Located (OrdList (LHsDecl RdrName)) }
780 decl_inst  : at_decl_inst               { LL (unitOL (L1 (TyClD (unLoc $1)))) }
781            | decl                       { $1 }
782
783 decls_inst :: { Located (OrdList (LHsDecl RdrName)) }   -- Reversed
784            : decls_inst ';' decl_inst   { LL (unLoc $1 `appOL` unLoc $3) }
785            | decls_inst ';'             { LL (unLoc $1) }
786            | decl_inst                  { $1 }
787            | {- empty -}                { noLoc nilOL }
788
789 decllist_inst 
790         :: { Located (OrdList (LHsDecl RdrName)) }      -- Reversed
791         : '{'         decls_inst '}'    { LL (unLoc $2) }
792         |     vocurly decls_inst close  { $2 }
793
794 -- Instance body
795 --
796 where_inst :: { Located (OrdList (LHsDecl RdrName)) }   -- Reversed
797                                 -- No implicit parameters
798                                 -- May have type declarations
799         : 'where' decllist_inst         { LL (unLoc $2) }
800         | {- empty -}                   { noLoc nilOL }
801
802 -- Declarations in binding groups other than classes and instances
803 --
804 decls   :: { Located (OrdList (LHsDecl RdrName)) }      
805         : decls ';' decl                { LL (unLoc $1 `appOL` unLoc $3) }
806         | decls ';'                     { LL (unLoc $1) }
807         | decl                          { $1 }
808         | {- empty -}                   { noLoc nilOL }
809
810 decllist :: { Located (OrdList (LHsDecl RdrName)) }
811         : '{'            decls '}'      { LL (unLoc $2) }
812         |     vocurly    decls close    { $2 }
813
814 -- Binding groups other than those of class and instance declarations
815 --
816 binds   ::  { Located (HsLocalBinds RdrName) }          -- May have implicit parameters
817                                                 -- No type declarations
818         : decllist                      { L1 (HsValBinds (cvBindGroup (unLoc $1))) }
819         | '{'            dbinds '}'     { LL (HsIPBinds (IPBinds (unLoc $2) emptyLHsBinds)) }
820         |     vocurly    dbinds close   { L (getLoc $2) (HsIPBinds (IPBinds (unLoc $2) emptyLHsBinds)) }
821
822 wherebinds :: { Located (HsLocalBinds RdrName) }        -- May have implicit parameters
823                                                 -- No type declarations
824         : 'where' binds                 { LL (unLoc $2) }
825         | {- empty -}                   { noLoc emptyLocalBinds }
826
827
828 -----------------------------------------------------------------------------
829 -- Transformation Rules
830
831 rules   :: { OrdList (LHsDecl RdrName) }
832         :  rules ';' rule                       { $1 `snocOL` $3 }
833         |  rules ';'                            { $1 }
834         |  rule                                 { unitOL $1 }
835         |  {- empty -}                          { nilOL }
836
837 rule    :: { LHsDecl RdrName }
838         : STRING activation rule_forall infixexp '=' exp
839              { LL $ RuleD (HsRule (getSTRING $1) 
840                                   ($2 `orElse` AlwaysActive) 
841                                   $3 $4 placeHolderNames $6 placeHolderNames) }
842
843 activation :: { Maybe Activation } 
844         : {- empty -}                           { Nothing }
845         | explicit_activation                   { Just $1 }
846
847 explicit_activation :: { Activation }  -- In brackets
848         : '[' INTEGER ']'               { ActiveAfter  (fromInteger (getINTEGER $2)) }
849         | '[' '~' INTEGER ']'           { ActiveBefore (fromInteger (getINTEGER $3)) }
850
851 rule_forall :: { [RuleBndr RdrName] }
852         : 'forall' rule_var_list '.'            { $2 }
853         | {- empty -}                           { [] }
854
855 rule_var_list :: { [RuleBndr RdrName] }
856         : rule_var                              { [$1] }
857         | rule_var rule_var_list                { $1 : $2 }
858
859 rule_var :: { RuleBndr RdrName }
860         : varid                                 { RuleBndr $1 }
861         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
862
863 -----------------------------------------------------------------------------
864 -- Deprecations (c.f. rules)
865
866 deprecations :: { OrdList (LHsDecl RdrName) }
867         : deprecations ';' deprecation          { $1 `appOL` $3 }
868         | deprecations ';'                      { $1 }
869         | deprecation                           { $1 }
870         | {- empty -}                           { nilOL }
871
872 -- SUP: TEMPORARY HACK, not checking for `module Foo'
873 deprecation :: { OrdList (LHsDecl RdrName) }
874         : depreclist STRING
875                 { toOL [ LL $ DeprecD (Deprecation n (getSTRING $2)) 
876                        | n <- unLoc $1 ] }
877
878
879 -----------------------------------------------------------------------------
880 -- Foreign import and export declarations
881
882 fdecl :: { LHsDecl RdrName }
883 fdecl : 'import' callconv safety fspec
884                 {% mkImport $2 $3 (unLoc $4) >>= return.LL }
885       | 'import' callconv        fspec          
886                 {% do { d <- mkImport $2 (PlaySafe False) (unLoc $3);
887                         return (LL d) } }
888       | 'export' callconv fspec
889                 {% mkExport $2 (unLoc $3) >>= return.LL }
890
891 callconv :: { CallConv }
892           : 'stdcall'                   { CCall  StdCallConv }
893           | 'ccall'                     { CCall  CCallConv   }
894           | 'dotnet'                    { DNCall             }
895
896 safety :: { Safety }
897         : 'unsafe'                      { PlayRisky }
898         | 'safe'                        { PlaySafe  False }
899         | 'threadsafe'                  { PlaySafe  True }
900
901 fspec :: { Located (Located FastString, Located RdrName, LHsType RdrName) }
902        : STRING var '::' sigtypedoc     { LL (L (getLoc $1) (getSTRING $1), $2, $4) }
903        |        var '::' sigtypedoc     { LL (noLoc nilFS, $1, $3) }
904          -- if the entity string is missing, it defaults to the empty string;
905          -- the meaning of an empty entity string depends on the calling
906          -- convention
907
908 -----------------------------------------------------------------------------
909 -- Type signatures
910
911 opt_sig :: { Maybe (LHsType RdrName) }
912         : {- empty -}                   { Nothing }
913         | '::' sigtype                  { Just $2 }
914
915 opt_asig :: { Maybe (LHsType RdrName) }
916         : {- empty -}                   { Nothing }
917         | '::' atype                    { Just $2 }
918
919 sigtypes1 :: { [LHsType RdrName] }
920         : sigtype                       { [ $1 ] }
921         | sigtype ',' sigtypes1         { $1 : $3 }
922
923 sigtype :: { LHsType RdrName }
924         : ctype                         { L1 (mkImplicitHsForAllTy (noLoc []) $1) }
925         -- Wrap an Implicit forall if there isn't one there already
926
927 sigtypedoc :: { LHsType RdrName }
928         : ctypedoc                      { L1 (mkImplicitHsForAllTy (noLoc []) $1) }
929         -- Wrap an Implicit forall if there isn't one there already
930
931 sig_vars :: { Located [Located RdrName] }
932          : sig_vars ',' var             { LL ($3 : unLoc $1) }
933          | var                          { L1 [$1] }
934
935 -----------------------------------------------------------------------------
936 -- Types
937
938 infixtype :: { LHsType RdrName }
939         : btype qtyconop gentype         { LL $ HsOpTy $1 $2 $3 }
940         | btype tyvarop  gentype         { LL $ HsOpTy $1 $2 $3 }
941
942 infixtypedoc :: { LHsType RdrName }
943         : infixtype                      { $1 }
944         | infixtype docprev              { LL $ HsDocTy $1 $2 }
945
946 gentypedoc :: { LHsType RdrName }
947         : btype                          { $1 }
948         | btypedoc                       { $1 }
949         | infixtypedoc                   { $1 }
950         | btype '->' ctypedoc            { LL $ HsFunTy $1 $3 }
951         | btypedoc '->' ctypedoc         { LL $ HsFunTy $1 $3 }
952
953 ctypedoc  :: { LHsType RdrName }
954         : 'forall' tv_bndrs '.' ctypedoc { LL $ mkExplicitHsForAllTy $2 (noLoc []) $4 }
955         | context '=>' gentypedoc        { LL $ mkImplicitHsForAllTy   $1 $3 }
956         -- A type of form (context => type) is an *implicit* HsForAllTy
957         | gentypedoc                     { $1 }
958         
959 strict_mark :: { Located HsBang }
960         : '!'                           { L1 HsStrict }
961         | '{-# UNPACK' '#-}' '!'        { LL HsUnbox }
962
963 -- A ctype is a for-all type
964 ctype   :: { LHsType RdrName }
965         : 'forall' tv_bndrs '.' ctype   { LL $ mkExplicitHsForAllTy $2 (noLoc []) $4 }
966         | context '=>' type             { LL $ mkImplicitHsForAllTy   $1 $3 }
967         -- A type of form (context => type) is an *implicit* HsForAllTy
968         | type                          { $1 }
969
970 -- We parse a context as a btype so that we don't get reduce/reduce
971 -- errors in ctype.  The basic problem is that
972 --      (Eq a, Ord a)
973 -- looks so much like a tuple type.  We can't tell until we find the =>
974 context :: { LHsContext RdrName }
975         : btype                         {% checkContext $1 }
976
977 type :: { LHsType RdrName }
978         : ipvar '::' gentype            { LL (HsPredTy (HsIParam (unLoc $1) $3)) }
979         | gentype                       { $1 }
980
981 gentype :: { LHsType RdrName }
982         : btype                         { $1 }
983         | btype qtyconop gentype        { LL $ HsOpTy $1 $2 $3 }
984         | btype tyvarop  gentype        { LL $ HsOpTy $1 $2 $3 }
985         | btype '->'     ctype          { LL $ HsFunTy $1 $3 }
986         | btype '~'      gentype        { LL $ HsPredTy (HsEqualP $1 $3) }
987
988 btype :: { LHsType RdrName }
989         : btype atype                   { LL $ HsAppTy $1 $2 }
990         | atype                         { $1 }
991
992 btypedoc :: { LHsType RdrName }
993         : btype atype docprev           { LL $ HsDocTy (L (comb2 $1 $2) (HsAppTy $1 $2)) $3 }
994         | atype docprev                 { LL $ HsDocTy $1 $2 }
995
996 atype :: { LHsType RdrName }
997         : gtycon                        { L1 (HsTyVar (unLoc $1)) }
998         | tyvar                         { L1 (HsTyVar (unLoc $1)) }
999         | strict_mark atype             { LL (HsBangTy (unLoc $1) $2) }
1000         | '(' ctype ',' comma_types1 ')'  { LL $ HsTupleTy Boxed  ($2:$4) }
1001         | '(#' comma_types1 '#)'        { LL $ HsTupleTy Unboxed $2     }
1002         | '[' ctype ']'                 { LL $ HsListTy  $2 }
1003         | '[:' ctype ':]'               { LL $ HsPArrTy  $2 }
1004         | '(' ctype ')'                 { LL $ HsParTy   $2 }
1005         | '(' ctype '::' kind ')'       { LL $ HsKindSig $2 (unLoc $4) }
1006 -- Generics
1007         | INTEGER                       { L1 (HsNumTy (getINTEGER $1)) }
1008
1009 -- An inst_type is what occurs in the head of an instance decl
1010 --      e.g.  (Foo a, Gaz b) => Wibble a b
1011 -- It's kept as a single type, with a MonoDictTy at the right
1012 -- hand corner, for convenience.
1013 inst_type :: { LHsType RdrName }
1014         : sigtype                       {% checkInstType $1 }
1015
1016 inst_types1 :: { [LHsType RdrName] }
1017         : inst_type                     { [$1] }
1018         | inst_type ',' inst_types1     { $1 : $3 }
1019
1020 comma_types0  :: { [LHsType RdrName] }
1021         : comma_types1                  { $1 }
1022         | {- empty -}                   { [] }
1023
1024 comma_types1    :: { [LHsType RdrName] }
1025         : ctype                         { [$1] }
1026         | ctype  ',' comma_types1       { $1 : $3 }
1027
1028 tv_bndrs :: { [LHsTyVarBndr RdrName] }
1029          : tv_bndr tv_bndrs             { $1 : $2 }
1030          | {- empty -}                  { [] }
1031
1032 tv_bndr :: { LHsTyVarBndr RdrName }
1033         : tyvar                         { L1 (UserTyVar (unLoc $1)) }
1034         | '(' tyvar '::' kind ')'       { LL (KindedTyVar (unLoc $2) 
1035                                                           (unLoc $4)) }
1036
1037 fds :: { Located [Located ([RdrName], [RdrName])] }
1038         : {- empty -}                   { noLoc [] }
1039         | '|' fds1                      { LL (reverse (unLoc $2)) }
1040
1041 fds1 :: { Located [Located ([RdrName], [RdrName])] }
1042         : fds1 ',' fd                   { LL ($3 : unLoc $1) }
1043         | fd                            { L1 [$1] }
1044
1045 fd :: { Located ([RdrName], [RdrName]) }
1046         : varids0 '->' varids0          { L (comb3 $1 $2 $3)
1047                                            (reverse (unLoc $1), reverse (unLoc $3)) }
1048
1049 varids0 :: { Located [RdrName] }
1050         : {- empty -}                   { noLoc [] }
1051         | varids0 tyvar                 { LL (unLoc $2 : unLoc $1) }
1052
1053 -----------------------------------------------------------------------------
1054 -- Kinds
1055
1056 kind    :: { Located Kind }
1057         : akind                 { $1 }
1058         | akind '->' kind       { LL (mkArrowKind (unLoc $1) (unLoc $3)) }
1059
1060 akind   :: { Located Kind }
1061         : '*'                   { L1 liftedTypeKind }
1062         | '!'                   { L1 unliftedTypeKind }
1063         | '(' kind ')'          { LL (unLoc $2) }
1064
1065
1066 -----------------------------------------------------------------------------
1067 -- Datatype declarations
1068
1069 gadt_constrlist :: { Located [LConDecl RdrName] }
1070         : '{'            gadt_constrs '}'       { LL (unLoc $2) }
1071         |     vocurly    gadt_constrs close     { $2 }
1072
1073 gadt_constrs :: { Located [LConDecl RdrName] }
1074         : gadt_constrs ';' gadt_constr  { LL ($3 : unLoc $1) }
1075         | gadt_constrs ';'              { $1 }
1076         | gadt_constr                   { L1 [$1] } 
1077
1078 -- We allow the following forms:
1079 --      C :: Eq a => a -> T a
1080 --      C :: forall a. Eq a => !a -> T a
1081 --      D { x,y :: a } :: T a
1082 --      forall a. Eq a => D { x,y :: a } :: T a
1083
1084 gadt_constr :: { LConDecl RdrName }
1085         : con '::' sigtype
1086               { LL (mkGadtDecl $1 $3) } 
1087         -- Syntax: Maybe merge the record stuff with the single-case above?
1088         --         (to kill the mostly harmless reduce/reduce error)
1089         -- XXX revisit audreyt
1090         | constr_stuff_record '::' sigtype
1091                 { let (con,details) = unLoc $1 in 
1092                   LL (ConDecl con Implicit [] (noLoc []) details (ResTyGADT $3) Nothing) }
1093 {-
1094         | forall context '=>' constr_stuff_record '::' sigtype
1095                 { let (con,details) = unLoc $4 in 
1096                   LL (ConDecl con Implicit (unLoc $1) $2 details (ResTyGADT $6) Nothing ) }
1097         | forall constr_stuff_record '::' sigtype
1098                 { let (con,details) = unLoc $2 in 
1099                   LL (ConDecl con Implicit (unLoc $1) (noLoc []) details (ResTyGADT $4) Nothing) }
1100 -}
1101
1102
1103 constrs :: { Located [LConDecl RdrName] }
1104         : {- empty; a GHC extension -}  { noLoc [] }
1105         | maybe_docnext '=' constrs1    { L (comb2 $2 $3) (addConDocs (unLoc $3) $1) }
1106
1107 constrs1 :: { Located [LConDecl RdrName] }
1108         : constrs1 maybe_docnext '|' maybe_docprev constr { LL (addConDoc $5 $2 : addConDocFirst (unLoc $1) $4) }
1109         | constr                                          { L1 [$1] }
1110
1111 constr :: { LConDecl RdrName }
1112         : maybe_docnext forall context '=>' constr_stuff maybe_docprev  
1113                 { let (con,details) = unLoc $5 in 
1114                   L (comb4 $2 $3 $4 $5) (ConDecl con Explicit (unLoc $2) $3 details ResTyH98 ($1 `mplus` $6)) }
1115         | maybe_docnext forall constr_stuff maybe_docprev
1116                 { let (con,details) = unLoc $3 in 
1117                   L (comb2 $2 $3) (ConDecl con Explicit (unLoc $2) (noLoc []) details ResTyH98 ($1 `mplus` $4)) }
1118
1119 forall :: { Located [LHsTyVarBndr RdrName] }
1120         : 'forall' tv_bndrs '.'         { LL $2 }
1121         | {- empty -}                   { noLoc [] }
1122
1123 constr_stuff :: { Located (Located RdrName, HsConDetails RdrName (LBangType RdrName)) }
1124 -- We parse the constructor declaration 
1125 --      C t1 t2
1126 -- as a btype (treating C as a type constructor) and then convert C to be
1127 -- a data constructor.  Reason: it might continue like this:
1128 --      C t1 t2 %: D Int
1129 -- in which case C really would be a type constructor.  We can't resolve this
1130 -- ambiguity till we come across the constructor oprerator :% (or not, more usually)
1131         : btype                         {% mkPrefixCon $1 [] >>= return.LL }
1132         | oqtycon '{' '}'               {% mkRecCon $1 [] >>= return.LL }
1133         | oqtycon '{' fielddecls '}'    {% mkRecCon $1 $3 >>= return.LL }
1134         | btype conop btype             { LL ($2, InfixCon $1 $3) }
1135
1136 constr_stuff_record :: { Located (Located RdrName, HsConDetails RdrName (LBangType RdrName)) }
1137         : oqtycon '{' '}'               {% mkRecCon $1 [] >>= return.sL (comb2 $1 $>) }
1138         | oqtycon '{' fielddecls '}'    {% mkRecCon $1 $3 >>= return.sL (comb2 $1 $>) }
1139
1140 fielddecls :: { [([Located RdrName], LBangType RdrName, Maybe (LHsDoc RdrName))] }
1141         : fielddecl maybe_docnext ',' maybe_docprev fielddecls { addFieldDoc (unLoc $1) $4 : addFieldDocs $5 $2 }
1142         | fielddecl                                            { [unLoc $1] }
1143
1144 fielddecl :: { Located ([Located RdrName], LBangType RdrName, Maybe (LHsDoc RdrName)) }
1145         : maybe_docnext sig_vars '::' ctype maybe_docprev      { L (comb3 $2 $3 $4) (reverse (unLoc $2), $4, $1 `mplus` $5) }
1146
1147 -- We allow the odd-looking 'inst_type' in a deriving clause, so that
1148 -- we can do deriving( forall a. C [a] ) in a newtype (GHC extension).
1149 -- The 'C [a]' part is converted to an HsPredTy by checkInstType
1150 -- We don't allow a context, but that's sorted out by the type checker.
1151 deriving :: { Located (Maybe [LHsType RdrName]) }
1152         : {- empty -}                           { noLoc Nothing }
1153         | 'deriving' qtycon     {% do { let { L loc tv = $2 }
1154                                       ; p <- checkInstType (L loc (HsTyVar tv))
1155                                       ; return (LL (Just [p])) } }
1156         | 'deriving' '(' ')'                    { LL (Just []) }
1157         | 'deriving' '(' inst_types1 ')'        { LL (Just $3) }
1158              -- Glasgow extension: allow partial 
1159              -- applications in derivings
1160
1161 -----------------------------------------------------------------------------
1162 -- Value definitions
1163
1164 {- There's an awkward overlap with a type signature.  Consider
1165         f :: Int -> Int = ...rhs...
1166    Then we can't tell whether it's a type signature or a value
1167    definition with a result signature until we see the '='.
1168    So we have to inline enough to postpone reductions until we know.
1169 -}
1170
1171 {-
1172   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
1173   instead of qvar, we get another shift/reduce-conflict. Consider the
1174   following programs:
1175   
1176      { (^^) :: Int->Int ; }          Type signature; only var allowed
1177
1178      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
1179                                      qvar allowed (because of instance decls)
1180   
1181   We can't tell whether to reduce var to qvar until after we've read the signatures.
1182 -}
1183
1184 docdecl :: { LHsDecl RdrName }
1185         : docdecld { L1 (DocD (unLoc $1)) }
1186
1187 docdecld :: { LDocDecl RdrName }
1188         : docnext                               { L1 (DocCommentNext (unLoc $1)) }
1189         | docprev                               { L1 (DocCommentPrev (unLoc $1)) }
1190         | docnamed                              { L1 (case (unLoc $1) of (n, doc) -> DocCommentNamed n doc) }
1191         | docsection                            { L1 (case (unLoc $1) of (n, doc) -> DocGroup n doc) }
1192
1193 decl    :: { Located (OrdList (LHsDecl RdrName)) }
1194         : sigdecl                       { $1 }
1195         | '!' aexp rhs                  {% do { pat <- checkPattern $2;
1196                                                 return (LL $ unitOL $ LL $ ValD ( 
1197                                                         PatBind (LL $ BangPat pat) (unLoc $3)
1198                                                                 placeHolderType placeHolderNames)) } }
1199         | infixexp opt_sig rhs          {% do { r <- checkValDef $1 $2 $3;
1200                                                 return (LL $ unitOL (LL $ ValD r)) } }
1201         | docdecl                       { LL $ unitOL $1 }
1202
1203 rhs     :: { Located (GRHSs RdrName) }
1204         : '=' exp wherebinds    { L (comb3 $1 $2 $3) $ GRHSs (unguardedRHS $2) (unLoc $3) }
1205         | gdrhs wherebinds      { LL $ GRHSs (reverse (unLoc $1)) (unLoc $2) }
1206
1207 gdrhs :: { Located [LGRHS RdrName] }
1208         : gdrhs gdrh            { LL ($2 : unLoc $1) }
1209         | gdrh                  { L1 [$1] }
1210
1211 gdrh :: { LGRHS RdrName }
1212         : '|' quals '=' exp     { sL (comb2 $1 $>) $ GRHS (reverse (unLoc $2)) $4 }
1213
1214 sigdecl :: { Located (OrdList (LHsDecl RdrName)) }
1215         : infixexp '::' sigtypedoc
1216                                 {% do s <- checkValSig $1 $3; 
1217                                       return (LL $ unitOL (LL $ SigD s)) }
1218                 -- See the above notes for why we need infixexp here
1219         | var ',' sig_vars '::' sigtypedoc
1220                                 { LL $ toOL [ LL $ SigD (TypeSig n $5) | n <- $1 : unLoc $3 ] }
1221         | infix prec ops        { LL $ toOL [ LL $ SigD (FixSig (FixitySig n (Fixity $2 (unLoc $1))))
1222                                              | n <- unLoc $3 ] }
1223         | '{-# INLINE'   activation qvar '#-}'        
1224                                 { LL $ unitOL (LL $ SigD (InlineSig $3 (mkInlineSpec $2 (getINLINE $1)))) }
1225         | '{-# SPECIALISE' qvar '::' sigtypes1 '#-}'
1226                                 { LL $ toOL [ LL $ SigD (SpecSig $2 t defaultInlineSpec) 
1227                                             | t <- $4] }
1228         | '{-# SPECIALISE_INLINE' activation qvar '::' sigtypes1 '#-}'
1229                                 { LL $ toOL [ LL $ SigD (SpecSig $3 t (mkInlineSpec $2 (getSPEC_INLINE $1)))
1230                                             | t <- $5] }
1231         | '{-# SPECIALISE' 'instance' inst_type '#-}'
1232                                 { LL $ unitOL (LL $ SigD (SpecInstSig $3)) }
1233
1234 -----------------------------------------------------------------------------
1235 -- Expressions
1236
1237 exp   :: { LHsExpr RdrName }
1238         : infixexp '::' sigtype         { LL $ ExprWithTySig $1 $3 }
1239         | infixexp '-<' exp             { LL $ HsArrApp $1 $3 placeHolderType HsFirstOrderApp True }
1240         | infixexp '>-' exp             { LL $ HsArrApp $3 $1 placeHolderType HsFirstOrderApp False }
1241         | infixexp '-<<' exp            { LL $ HsArrApp $1 $3 placeHolderType HsHigherOrderApp True }
1242         | infixexp '>>-' exp            { LL $ HsArrApp $3 $1 placeHolderType HsHigherOrderApp False}
1243         | infixexp                      { $1 }
1244
1245 infixexp :: { LHsExpr RdrName }
1246         : exp10                         { $1 }
1247         | infixexp qop exp10            { LL (OpApp $1 $2 (panic "fixity") $3) }
1248
1249 exp10 :: { LHsExpr RdrName }
1250         : '\\' apat apats opt_asig '->' exp     
1251                         { LL $ HsLam (mkMatchGroup [LL $ Match ($2:$3) $4
1252                                                                 (unguardedGRHSs $6)
1253                                                             ]) }
1254         | 'let' binds 'in' exp                  { LL $ HsLet (unLoc $2) $4 }
1255         | 'if' exp 'then' exp 'else' exp        { LL $ HsIf $2 $4 $6 }
1256         | 'case' exp 'of' altslist              { LL $ HsCase $2 (mkMatchGroup (unLoc $4)) }
1257         | '-' fexp                              { LL $ mkHsNegApp $2 }
1258
1259         | 'do' stmtlist                 {% let loc = comb2 $1 $2 in
1260                                            checkDo loc (unLoc $2)  >>= \ (stmts,body) ->
1261                                            return (L loc (mkHsDo DoExpr stmts body)) }
1262         | 'mdo' stmtlist                {% let loc = comb2 $1 $2 in
1263                                            checkDo loc (unLoc $2)  >>= \ (stmts,body) ->
1264                                            return (L loc (mkHsDo (MDoExpr noPostTcTable) stmts body)) }
1265         | scc_annot exp                         { LL $ if opt_SccProfilingOn
1266                                                         then HsSCC (unLoc $1) $2
1267                                                         else HsPar $2 }
1268         | hpc_annot exp                         { LL $ if opt_Hpc
1269                                                         then HsTickPragma (unLoc $1) $2
1270                                                         else HsPar $2 }
1271
1272         | 'proc' aexp '->' exp  
1273                         {% checkPattern $2 >>= \ p -> 
1274                            return (LL $ HsProc p (LL $ HsCmdTop $4 [] 
1275                                                    placeHolderType undefined)) }
1276                                                 -- TODO: is LL right here?
1277
1278         | '{-# CORE' STRING '#-}' exp           { LL $ HsCoreAnn (getSTRING $2) $4 }
1279                                                     -- hdaume: core annotation
1280         | fexp                                  { $1 }
1281
1282 scc_annot :: { Located FastString }
1283         : '_scc_' STRING                        { LL $ getSTRING $2 }
1284         | '{-# SCC' STRING '#-}'                { LL $ getSTRING $2 }
1285
1286 hpc_annot :: { Located (FastString,(Int,Int),(Int,Int)) }
1287         : '{-# GENERATED' STRING INTEGER ':' INTEGER '-' INTEGER ':' INTEGER '#-}'
1288                                                 { LL $ (getSTRING $2
1289                                                        ,( fromInteger $ getINTEGER $3
1290                                                         , fromInteger $ getINTEGER $5
1291                                                         )
1292                                                        ,( fromInteger $ getINTEGER $7
1293                                                         , fromInteger $ getINTEGER $9
1294                                                         )
1295                                                        )
1296                                                  }
1297
1298 fexp    :: { LHsExpr RdrName }
1299         : fexp aexp                             { LL $ HsApp $1 $2 }
1300         | aexp                                  { $1 }
1301
1302 aexp    :: { LHsExpr RdrName }
1303         : qvar '@' aexp                 { LL $ EAsPat $1 $3 }
1304         | '~' aexp                      { LL $ ELazyPat $2 }
1305         | aexp1                         { $1 }
1306
1307 aexp1   :: { LHsExpr RdrName }
1308         : aexp1 '{' fbinds '}'  {% do { r <- mkRecConstrOrUpdate $1 (comb2 $2 $4) 
1309                                                         (reverse $3);
1310                                         return (LL r) }}
1311         | aexp2                 { $1 }
1312
1313 -- Here was the syntax for type applications that I was planning
1314 -- but there are difficulties (e.g. what order for type args)
1315 -- so it's not enabled yet.
1316 -- But this case *is* used for the left hand side of a generic definition,
1317 -- which is parsed as an expression before being munged into a pattern
1318         | qcname '{|' gentype '|}'      { LL $ HsApp (sL (getLoc $1) (HsVar (unLoc $1)))
1319                                                      (sL (getLoc $3) (HsType $3)) }
1320
1321 aexp2   :: { LHsExpr RdrName }
1322         : ipvar                         { L1 (HsIPVar $! unLoc $1) }
1323         | qcname                        { L1 (HsVar   $! unLoc $1) }
1324         | literal                       { L1 (HsLit   $! unLoc $1) }
1325         | INTEGER                       { L1 (HsOverLit $! mkHsIntegral (getINTEGER $1)) }
1326         | RATIONAL                      { L1 (HsOverLit $! mkHsFractional (getRATIONAL $1)) }
1327         | '(' exp ')'                   { LL (HsPar $2) }
1328         | '(' texp ',' texps ')'        { LL $ ExplicitTuple ($2 : reverse $4) Boxed }
1329         | '(#' texps '#)'               { LL $ ExplicitTuple (reverse $2)      Unboxed }
1330         | '[' list ']'                  { LL (unLoc $2) }
1331         | '[:' parr ':]'                { LL (unLoc $2) }
1332         | '(' infixexp qop ')'          { LL $ SectionL $2 $3 }
1333         | '(' qopm infixexp ')'         { LL $ SectionR $2 $3 }
1334         | '_'                           { L1 EWildPat }
1335         
1336         -- Template Haskell Extension
1337         | TH_ID_SPLICE          { L1 $ HsSpliceE (mkHsSplice 
1338                                         (L1 $ HsVar (mkUnqual varName 
1339                                                         (getTH_ID_SPLICE $1)))) } -- $x
1340         | '$(' exp ')'          { LL $ HsSpliceE (mkHsSplice $2) }               -- $( exp )
1341
1342         | TH_VAR_QUOTE qvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1343         | TH_VAR_QUOTE qcon     { LL $ HsBracket (VarBr (unLoc $2)) }
1344         | TH_TY_QUOTE tyvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1345         | TH_TY_QUOTE gtycon    { LL $ HsBracket (VarBr (unLoc $2)) }
1346         | '[|' exp '|]'         { LL $ HsBracket (ExpBr $2) }                       
1347         | '[t|' ctype '|]'      { LL $ HsBracket (TypBr $2) }                       
1348         | '[p|' infixexp '|]'   {% checkPattern $2 >>= \p ->
1349                                            return (LL $ HsBracket (PatBr p)) }
1350         | '[d|' cvtopbody '|]'  { LL $ HsBracket (DecBr (mkGroup $2)) }
1351
1352         -- arrow notation extension
1353         | '(|' aexp2 cmdargs '|)'       { LL $ HsArrForm $2 Nothing (reverse $3) }
1354
1355 cmdargs :: { [LHsCmdTop RdrName] }
1356         : cmdargs acmd                  { $2 : $1 }
1357         | {- empty -}                   { [] }
1358
1359 acmd    :: { LHsCmdTop RdrName }
1360         : aexp2                 { L1 $ HsCmdTop $1 [] placeHolderType undefined }
1361
1362 cvtopbody :: { [LHsDecl RdrName] }
1363         :  '{'            cvtopdecls0 '}'               { $2 }
1364         |      vocurly    cvtopdecls0 close             { $2 }
1365
1366 cvtopdecls0 :: { [LHsDecl RdrName] }
1367         : {- empty -}           { [] }
1368         | cvtopdecls            { $1 }
1369
1370 texp :: { LHsExpr RdrName }
1371         : exp                           { $1 }
1372         | qopm infixexp                 { LL $ SectionR $1 $2 }
1373         -- The second production is really here only for bang patterns
1374         -- but 
1375
1376 texps :: { [LHsExpr RdrName] }
1377         : texps ',' texp                { $3 : $1 }
1378         | texp                          { [$1] }
1379
1380
1381 -----------------------------------------------------------------------------
1382 -- List expressions
1383
1384 -- The rules below are little bit contorted to keep lexps left-recursive while
1385 -- avoiding another shift/reduce-conflict.
1386
1387 list :: { LHsExpr RdrName }
1388         : texp                  { L1 $ ExplicitList placeHolderType [$1] }
1389         | lexps                 { L1 $ ExplicitList placeHolderType (reverse (unLoc $1)) }
1390         | texp '..'             { LL $ ArithSeq noPostTcExpr (From $1) }
1391         | texp ',' exp '..'     { LL $ ArithSeq noPostTcExpr (FromThen $1 $3) }
1392         | texp '..' exp         { LL $ ArithSeq noPostTcExpr (FromTo $1 $3) }
1393         | texp ',' exp '..' exp { LL $ ArithSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1394         | texp pquals           { sL (comb2 $1 $>) $ mkHsDo ListComp (reverse (unLoc $2)) $1 }
1395
1396 lexps :: { Located [LHsExpr RdrName] }
1397         : lexps ',' texp                { LL ($3 : unLoc $1) }
1398         | texp ',' texp                 { LL [$3,$1] }
1399
1400 -----------------------------------------------------------------------------
1401 -- List Comprehensions
1402
1403 pquals :: { Located [LStmt RdrName] }   -- Either a singleton ParStmt, 
1404                                         -- or a reversed list of Stmts
1405         : pquals1                       { case unLoc $1 of
1406                                             [qs] -> L1 qs
1407                                             qss  -> L1 [L1 (ParStmt stmtss)]
1408                                                  where
1409                                                     stmtss = [ (reverse qs, undefined) 
1410                                                              | qs <- qss ]
1411                                         }
1412                         
1413 pquals1 :: { Located [[LStmt RdrName]] }
1414         : pquals1 '|' quals             { LL (unLoc $3 : unLoc $1) }
1415         | '|' quals                     { L (getLoc $2) [unLoc $2] }
1416
1417 quals :: { Located [LStmt RdrName] }
1418         : quals ',' qual                { LL ($3 : unLoc $1) }
1419         | qual                          { L1 [$1] }
1420
1421 -----------------------------------------------------------------------------
1422 -- Parallel array expressions
1423
1424 -- The rules below are little bit contorted; see the list case for details.
1425 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1426 -- Moreover, we allow explicit arrays with no element (represented by the nil
1427 -- constructor in the list case).
1428
1429 parr :: { LHsExpr RdrName }
1430         :                               { noLoc (ExplicitPArr placeHolderType []) }
1431         | exp                           { L1 $ ExplicitPArr placeHolderType [$1] }
1432         | lexps                         { L1 $ ExplicitPArr placeHolderType 
1433                                                        (reverse (unLoc $1)) }
1434         | exp '..' exp                  { LL $ PArrSeq noPostTcExpr (FromTo $1 $3) }
1435         | exp ',' exp '..' exp          { LL $ PArrSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1436         | exp pquals                    { sL (comb2 $1 $>) $ mkHsDo PArrComp (reverse (unLoc $2)) $1 }
1437
1438 -- We are reusing `lexps' and `pquals' from the list case.
1439
1440 -----------------------------------------------------------------------------
1441 -- Case alternatives
1442
1443 altslist :: { Located [LMatch RdrName] }
1444         : '{'            alts '}'       { LL (reverse (unLoc $2)) }
1445         |     vocurly    alts  close    { L (getLoc $2) (reverse (unLoc $2)) }
1446
1447 alts    :: { Located [LMatch RdrName] }
1448         : alts1                         { L1 (unLoc $1) }
1449         | ';' alts                      { LL (unLoc $2) }
1450
1451 alts1   :: { Located [LMatch RdrName] }
1452         : alts1 ';' alt                 { LL ($3 : unLoc $1) }
1453         | alts1 ';'                     { LL (unLoc $1) }
1454         | alt                           { L1 [$1] }
1455
1456 alt     :: { LMatch RdrName }
1457         : pat opt_sig alt_rhs           { LL (Match [$1] $2 (unLoc $3)) }
1458
1459 alt_rhs :: { Located (GRHSs RdrName) }
1460         : ralt wherebinds               { LL (GRHSs (unLoc $1) (unLoc $2)) }
1461
1462 ralt :: { Located [LGRHS RdrName] }
1463         : '->' exp                      { LL (unguardedRHS $2) }
1464         | gdpats                        { L1 (reverse (unLoc $1)) }
1465
1466 gdpats :: { Located [LGRHS RdrName] }
1467         : gdpats gdpat                  { LL ($2 : unLoc $1) }
1468         | gdpat                         { L1 [$1] }
1469
1470 gdpat   :: { LGRHS RdrName }
1471         : '|' quals '->' exp            { sL (comb2 $1 $>) $ GRHS (reverse (unLoc $2)) $4 }
1472
1473 -- 'pat' recognises a pattern, including one with a bang at the top
1474 --      e.g.  "!x" or "!(x,y)" or "C a b" etc
1475 -- Bangs inside are parsed as infix operator applications, so that
1476 -- we parse them right when bang-patterns are off
1477 pat     :: { LPat RdrName }
1478 pat     : infixexp              {% checkPattern $1 }
1479         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1480
1481 apat   :: { LPat RdrName }      
1482 apat    : aexp                  {% checkPattern $1 }
1483         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1484
1485 apats  :: { [LPat RdrName] }
1486         : apat apats            { $1 : $2 }
1487         | {- empty -}           { [] }
1488
1489 -----------------------------------------------------------------------------
1490 -- Statement sequences
1491
1492 stmtlist :: { Located [LStmt RdrName] }
1493         : '{'           stmts '}'       { LL (unLoc $2) }
1494         |     vocurly   stmts close     { $2 }
1495
1496 --      do { ;; s ; s ; ; s ;; }
1497 -- The last Stmt should be an expression, but that's hard to enforce
1498 -- here, because we need too much lookahead if we see do { e ; }
1499 -- So we use ExprStmts throughout, and switch the last one over
1500 -- in ParseUtils.checkDo instead
1501 stmts :: { Located [LStmt RdrName] }
1502         : stmt stmts_help               { LL ($1 : unLoc $2) }
1503         | ';' stmts                     { LL (unLoc $2) }
1504         | {- empty -}                   { noLoc [] }
1505
1506 stmts_help :: { Located [LStmt RdrName] } -- might be empty
1507         : ';' stmts                     { LL (unLoc $2) }
1508         | {- empty -}                   { noLoc [] }
1509
1510 -- For typing stmts at the GHCi prompt, where 
1511 -- the input may consist of just comments.
1512 maybe_stmt :: { Maybe (LStmt RdrName) }
1513         : stmt                          { Just $1 }
1514         | {- nothing -}                 { Nothing }
1515
1516 stmt  :: { LStmt RdrName }
1517         : qual                          { $1 }
1518 -- What is this next production doing?  I have no clue!  SLPJ Dec06
1519         | infixexp '->' exp             {% checkPattern $3 >>= \p ->
1520                                            return (LL $ mkBindStmt p $1) }
1521         | 'rec' stmtlist                { LL $ mkRecStmt (unLoc $2) }
1522
1523 qual  :: { LStmt RdrName }
1524         : pat '<-' exp                  { LL $ mkBindStmt $1 $3 }
1525         | exp                           { L1 $ mkExprStmt $1 }
1526         | 'let' binds                   { LL $ LetStmt (unLoc $2) }
1527
1528 -----------------------------------------------------------------------------
1529 -- Record Field Update/Construction
1530
1531 fbinds  :: { HsRecordBinds RdrName }
1532         : fbinds1                       { $1 }
1533         | {- empty -}                   { [] }
1534
1535 fbinds1 :: { HsRecordBinds RdrName }
1536         : fbinds1 ',' fbind             { $3 : $1 }
1537         | fbind                         { [$1] }
1538   
1539 fbind   :: { (Located RdrName, LHsExpr RdrName) }
1540         : qvar '=' exp                  { ($1,$3) }
1541
1542 -----------------------------------------------------------------------------
1543 -- Implicit Parameter Bindings
1544
1545 dbinds  :: { Located [LIPBind RdrName] }
1546         : dbinds ';' dbind              { LL ($3 : unLoc $1) }
1547         | dbinds ';'                    { LL (unLoc $1) }
1548         | dbind                         { L1 [$1] }
1549 --      | {- empty -}                   { [] }
1550
1551 dbind   :: { LIPBind RdrName }
1552 dbind   : ipvar '=' exp                 { LL (IPBind (unLoc $1) $3) }
1553
1554 ipvar   :: { Located (IPName RdrName) }
1555         : IPDUPVARID            { L1 (IPName (mkUnqual varName (getIPDUPVARID $1))) }
1556
1557 -----------------------------------------------------------------------------
1558 -- Deprecations
1559
1560 depreclist :: { Located [RdrName] }
1561 depreclist : deprec_var                 { L1 [unLoc $1] }
1562            | deprec_var ',' depreclist  { LL (unLoc $1 : unLoc $3) }
1563
1564 deprec_var :: { Located RdrName }
1565 deprec_var : var                        { $1 }
1566            | con                        { $1 }
1567
1568 -----------------------------------------
1569 -- Data constructors
1570 qcon    :: { Located RdrName }
1571         : qconid                { $1 }
1572         | '(' qconsym ')'       { LL (unLoc $2) }
1573         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1574 -- The case of '[:' ':]' is part of the production `parr'
1575
1576 con     :: { Located RdrName }
1577         : conid                 { $1 }
1578         | '(' consym ')'        { LL (unLoc $2) }
1579         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1580
1581 sysdcon :: { Located DataCon }  -- Wired in data constructors
1582         : '(' ')'               { LL unitDataCon }
1583         | '(' commas ')'        { LL $ tupleCon Boxed $2 }
1584         | '[' ']'               { LL nilDataCon }
1585
1586 conop :: { Located RdrName }
1587         : consym                { $1 }  
1588         | '`' conid '`'         { LL (unLoc $2) }
1589
1590 qconop :: { Located RdrName }
1591         : qconsym               { $1 }
1592         | '`' qconid '`'        { LL (unLoc $2) }
1593
1594 -----------------------------------------------------------------------------
1595 -- Type constructors
1596
1597 gtycon  :: { Located RdrName }  -- A "general" qualified tycon
1598         : oqtycon                       { $1 }
1599         | '(' ')'                       { LL $ getRdrName unitTyCon }
1600         | '(' commas ')'                { LL $ getRdrName (tupleTyCon Boxed $2) }
1601         | '(' '->' ')'                  { LL $ getRdrName funTyCon }
1602         | '[' ']'                       { LL $ listTyCon_RDR }
1603         | '[:' ':]'                     { LL $ parrTyCon_RDR }
1604
1605 oqtycon :: { Located RdrName }  -- An "ordinary" qualified tycon
1606         : qtycon                        { $1 }
1607         | '(' qtyconsym ')'             { LL (unLoc $2) }
1608
1609 qtyconop :: { Located RdrName } -- Qualified or unqualified
1610         : qtyconsym                     { $1 }
1611         | '`' qtycon '`'                { LL (unLoc $2) }
1612
1613 qtycon :: { Located RdrName }   -- Qualified or unqualified
1614         : QCONID                        { L1 $! mkQual tcClsName (getQCONID $1) }
1615         | tycon                         { $1 }
1616
1617 tycon   :: { Located RdrName }  -- Unqualified
1618         : CONID                         { L1 $! mkUnqual tcClsName (getCONID $1) }
1619
1620 qtyconsym :: { Located RdrName }
1621         : QCONSYM                       { L1 $! mkQual tcClsName (getQCONSYM $1) }
1622         | tyconsym                      { $1 }
1623
1624 tyconsym :: { Located RdrName }
1625         : CONSYM                        { L1 $! mkUnqual tcClsName (getCONSYM $1) }
1626
1627 -----------------------------------------------------------------------------
1628 -- Operators
1629
1630 op      :: { Located RdrName }   -- used in infix decls
1631         : varop                 { $1 }
1632         | conop                 { $1 }
1633
1634 varop   :: { Located RdrName }
1635         : varsym                { $1 }
1636         | '`' varid '`'         { LL (unLoc $2) }
1637
1638 qop     :: { LHsExpr RdrName }   -- used in sections
1639         : qvarop                { L1 $ HsVar (unLoc $1) }
1640         | qconop                { L1 $ HsVar (unLoc $1) }
1641
1642 qopm    :: { LHsExpr RdrName }   -- used in sections
1643         : qvaropm               { L1 $ HsVar (unLoc $1) }
1644         | qconop                { L1 $ HsVar (unLoc $1) }
1645
1646 qvarop :: { Located RdrName }
1647         : qvarsym               { $1 }
1648         | '`' qvarid '`'        { LL (unLoc $2) }
1649
1650 qvaropm :: { Located RdrName }
1651         : qvarsym_no_minus      { $1 }
1652         | '`' qvarid '`'        { LL (unLoc $2) }
1653
1654 -----------------------------------------------------------------------------
1655 -- Type variables
1656
1657 tyvar   :: { Located RdrName }
1658 tyvar   : tyvarid               { $1 }
1659         | '(' tyvarsym ')'      { LL (unLoc $2) }
1660
1661 tyvarop :: { Located RdrName }
1662 tyvarop : '`' tyvarid '`'       { LL (unLoc $2) }
1663         | tyvarsym              { $1 }
1664
1665 tyvarid :: { Located RdrName }
1666         : VARID                 { L1 $! mkUnqual tvName (getVARID $1) }
1667         | special_id            { L1 $! mkUnqual tvName (unLoc $1) }
1668         | 'unsafe'              { L1 $! mkUnqual tvName FSLIT("unsafe") }
1669         | 'safe'                { L1 $! mkUnqual tvName FSLIT("safe") }
1670         | 'threadsafe'          { L1 $! mkUnqual tvName FSLIT("threadsafe") }
1671
1672 tyvarsym :: { Located RdrName }
1673 -- Does not include "!", because that is used for strictness marks
1674 --               or ".", because that separates the quantified type vars from the rest
1675 --               or "*", because that's used for kinds
1676 tyvarsym : VARSYM               { L1 $! mkUnqual tvName (getVARSYM $1) }
1677
1678 -----------------------------------------------------------------------------
1679 -- Variables 
1680
1681 var     :: { Located RdrName }
1682         : varid                 { $1 }
1683         | '(' varsym ')'        { LL (unLoc $2) }
1684
1685 qvar    :: { Located RdrName }
1686         : qvarid                { $1 }
1687         | '(' varsym ')'        { LL (unLoc $2) }
1688         | '(' qvarsym1 ')'      { LL (unLoc $2) }
1689 -- We've inlined qvarsym here so that the decision about
1690 -- whether it's a qvar or a var can be postponed until
1691 -- *after* we see the close paren.
1692
1693 qvarid :: { Located RdrName }
1694         : varid                 { $1 }
1695         | QVARID                { L1 $ mkQual varName (getQVARID $1) }
1696
1697 varid :: { Located RdrName }
1698         : varid_no_unsafe       { $1 }
1699         | 'unsafe'              { L1 $! mkUnqual varName FSLIT("unsafe") }
1700         | 'safe'                { L1 $! mkUnqual varName FSLIT("safe") }
1701         | 'threadsafe'          { L1 $! mkUnqual varName FSLIT("threadsafe") }
1702
1703 varid_no_unsafe :: { Located RdrName }
1704         : VARID                 { L1 $! mkUnqual varName (getVARID $1) }
1705         | special_id            { L1 $! mkUnqual varName (unLoc $1) }
1706         | 'forall'              { L1 $! mkUnqual varName FSLIT("forall") }
1707         | 'iso'                 { L1 $! mkUnqual varName FSLIT("iso") }
1708         | 'family'              { L1 $! mkUnqual varName FSLIT("family") }
1709
1710 qvarsym :: { Located RdrName }
1711         : varsym                { $1 }
1712         | qvarsym1              { $1 }
1713
1714 qvarsym_no_minus :: { Located RdrName }
1715         : varsym_no_minus       { $1 }
1716         | qvarsym1              { $1 }
1717
1718 qvarsym1 :: { Located RdrName }
1719 qvarsym1 : QVARSYM              { L1 $ mkQual varName (getQVARSYM $1) }
1720
1721 varsym :: { Located RdrName }
1722         : varsym_no_minus       { $1 }
1723         | '-'                   { L1 $ mkUnqual varName FSLIT("-") }
1724
1725 varsym_no_minus :: { Located RdrName } -- varsym not including '-'
1726         : VARSYM                { L1 $ mkUnqual varName (getVARSYM $1) }
1727         | special_sym           { L1 $ mkUnqual varName (unLoc $1) }
1728
1729
1730 -- These special_ids are treated as keywords in various places, 
1731 -- but as ordinary ids elsewhere.   'special_id' collects all these
1732 -- except 'unsafe', 'forall', 'family', and 'iso' whose treatment differs
1733 -- depending on context 
1734 special_id :: { Located FastString }
1735 special_id
1736         : 'as'                  { L1 FSLIT("as") }
1737         | 'qualified'           { L1 FSLIT("qualified") }
1738         | 'hiding'              { L1 FSLIT("hiding") }
1739         | 'for'                 { L1 FSLIT("for") }
1740         | 'export'              { L1 FSLIT("export") }
1741         | 'label'               { L1 FSLIT("label")  }
1742         | 'dynamic'             { L1 FSLIT("dynamic") }
1743         | 'stdcall'             { L1 FSLIT("stdcall") }
1744         | 'ccall'               { L1 FSLIT("ccall") }
1745
1746 special_sym :: { Located FastString }
1747 special_sym : '!'       { L1 FSLIT("!") }
1748             | '.'       { L1 FSLIT(".") }
1749             | '*'       { L1 FSLIT("*") }
1750
1751 -----------------------------------------------------------------------------
1752 -- Data constructors
1753
1754 qconid :: { Located RdrName }   -- Qualified or unqualified
1755         : conid                 { $1 }
1756         | QCONID                { L1 $ mkQual dataName (getQCONID $1) }
1757
1758 conid   :: { Located RdrName }
1759         : CONID                 { L1 $ mkUnqual dataName (getCONID $1) }
1760
1761 qconsym :: { Located RdrName }  -- Qualified or unqualified
1762         : consym                { $1 }
1763         | QCONSYM               { L1 $ mkQual dataName (getQCONSYM $1) }
1764
1765 consym :: { Located RdrName }
1766         : CONSYM                { L1 $ mkUnqual dataName (getCONSYM $1) }
1767
1768         -- ':' means only list cons
1769         | ':'                   { L1 $ consDataCon_RDR }
1770
1771
1772 -----------------------------------------------------------------------------
1773 -- Literals
1774
1775 literal :: { Located HsLit }
1776         : CHAR                  { L1 $ HsChar       $ getCHAR $1 }
1777         | STRING                { L1 $ HsString     $ getSTRING $1 }
1778         | PRIMINTEGER           { L1 $ HsIntPrim    $ getPRIMINTEGER $1 }
1779         | PRIMCHAR              { L1 $ HsCharPrim   $ getPRIMCHAR $1 }
1780         | PRIMSTRING            { L1 $ HsStringPrim $ getPRIMSTRING $1 }
1781         | PRIMFLOAT             { L1 $ HsFloatPrim  $ getPRIMFLOAT $1 }
1782         | PRIMDOUBLE            { L1 $ HsDoublePrim $ getPRIMDOUBLE $1 }
1783
1784 -----------------------------------------------------------------------------
1785 -- Layout
1786
1787 close :: { () }
1788         : vccurly               { () } -- context popped in lexer.
1789         | error                 {% popContext }
1790
1791 -----------------------------------------------------------------------------
1792 -- Miscellaneous (mostly renamings)
1793
1794 modid   :: { Located ModuleName }
1795         : CONID                 { L1 $ mkModuleNameFS (getCONID $1) }
1796         | QCONID                { L1 $ let (mod,c) = getQCONID $1 in
1797                                   mkModuleNameFS
1798                                    (mkFastString
1799                                      (unpackFS mod ++ '.':unpackFS c))
1800                                 }
1801
1802 commas :: { Int }
1803         : commas ','                    { $1 + 1 }
1804         | ','                           { 2 }
1805
1806 -----------------------------------------------------------------------------
1807 -- Documentation comments
1808
1809 docnext :: { LHsDoc RdrName }
1810   : DOCNEXT {% case parseHaddockParagraphs (tokenise (getDOCNEXT $1)) of {
1811       Left  err -> parseError (getLoc $1) err;
1812       Right doc -> return (L1 doc) } }
1813
1814 docprev :: { LHsDoc RdrName }
1815   : DOCPREV {% case parseHaddockParagraphs (tokenise (getDOCPREV $1)) of {
1816       Left  err -> parseError (getLoc $1) err;
1817       Right doc -> return (L1 doc) } }
1818
1819 docnamed :: { Located (String, (HsDoc RdrName)) }
1820   : DOCNAMED {%
1821       let string = getDOCNAMED $1 
1822           (name, rest) = break isSpace string
1823       in case parseHaddockParagraphs (tokenise rest) of {
1824         Left  err -> parseError (getLoc $1) err;
1825         Right doc -> return (L1 (name, doc)) } }
1826
1827 docsection :: { Located (n, HsDoc RdrName) }
1828   : DOCSECTION {% let (n, doc) = getDOCSECTION $1 in
1829         case parseHaddockString (tokenise doc) of {
1830       Left  err -> parseError (getLoc $1) err;
1831       Right doc -> return (L1 (n, doc)) } }
1832
1833 docoptions :: { String }
1834   : DOCOPTIONS { getDOCOPTIONS $1 }
1835
1836 moduleheader :: { (HaddockModInfo RdrName, Maybe (HsDoc RdrName)) }                                    
1837         : DOCNEXT {% let string = getDOCNEXT $1 in
1838                case parseModuleHeader string of {                       
1839                  Right (str, info) ->                                  
1840                    case parseHaddockParagraphs (tokenise str) of {               
1841                      Left err -> parseError (getLoc $1) err;                    
1842                      Right doc -> return (info, Just doc);          
1843                    };                                             
1844                  Left err -> parseError (getLoc $1) err
1845             }  }                                                  
1846
1847 maybe_docprev :: { Maybe (LHsDoc RdrName) }
1848         : docprev                       { Just $1 }
1849         | {- empty -}                   { Nothing }
1850
1851 maybe_docnext :: { Maybe (LHsDoc RdrName) }
1852         : docnext                       { Just $1 }
1853         | {- empty -}                   { Nothing }
1854
1855 {
1856 happyError :: P a
1857 happyError = srcParseFail
1858
1859 getVARID        (L _ (ITvarid    x)) = x
1860 getCONID        (L _ (ITconid    x)) = x
1861 getVARSYM       (L _ (ITvarsym   x)) = x
1862 getCONSYM       (L _ (ITconsym   x)) = x
1863 getQVARID       (L _ (ITqvarid   x)) = x
1864 getQCONID       (L _ (ITqconid   x)) = x
1865 getQVARSYM      (L _ (ITqvarsym  x)) = x
1866 getQCONSYM      (L _ (ITqconsym  x)) = x
1867 getIPDUPVARID   (L _ (ITdupipvarid   x)) = x
1868 getCHAR         (L _ (ITchar     x)) = x
1869 getSTRING       (L _ (ITstring   x)) = x
1870 getINTEGER      (L _ (ITinteger  x)) = x
1871 getRATIONAL     (L _ (ITrational x)) = x
1872 getPRIMCHAR     (L _ (ITprimchar   x)) = x
1873 getPRIMSTRING   (L _ (ITprimstring x)) = x
1874 getPRIMINTEGER  (L _ (ITprimint    x)) = x
1875 getPRIMFLOAT    (L _ (ITprimfloat  x)) = x
1876 getPRIMDOUBLE   (L _ (ITprimdouble x)) = x
1877 getTH_ID_SPLICE (L _ (ITidEscape x)) = x
1878 getINLINE       (L _ (ITinline_prag b)) = b
1879 getSPEC_INLINE  (L _ (ITspec_inline_prag b)) = b
1880
1881 getDOCNEXT (L _ (ITdocCommentNext x)) = x
1882 getDOCPREV (L _ (ITdocCommentPrev x)) = x
1883 getDOCNAMED (L _ (ITdocCommentNamed x)) = x
1884 getDOCSECTION (L _ (ITdocSection n x)) = (n, x)
1885 getDOCOPTIONS (L _ (ITdocOptions x)) = x
1886
1887 -- Utilities for combining source spans
1888 comb2 :: Located a -> Located b -> SrcSpan
1889 comb2 = combineLocs
1890
1891 comb3 :: Located a -> Located b -> Located c -> SrcSpan
1892 comb3 a b c = combineSrcSpans (getLoc a) (combineSrcSpans (getLoc b) (getLoc c))
1893
1894 comb4 :: Located a -> Located b -> Located c -> Located d -> SrcSpan
1895 comb4 a b c d = combineSrcSpans (getLoc a) $ combineSrcSpans (getLoc b) $
1896                 combineSrcSpans (getLoc c) (getLoc d)
1897
1898 -- strict constructor version:
1899 {-# INLINE sL #-}
1900 sL :: SrcSpan -> a -> Located a
1901 sL span a = span `seq` L span a
1902
1903 -- Make a source location for the file.  We're a bit lazy here and just
1904 -- make a point SrcSpan at line 1, column 0.  Strictly speaking we should
1905 -- try to find the span of the whole file (ToDo).
1906 fileSrcSpan :: P SrcSpan
1907 fileSrcSpan = do 
1908   l <- getSrcLoc; 
1909   let loc = mkSrcLoc (srcLocFile l) 1 0;
1910   return (mkSrcSpan loc loc)
1911 }