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