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