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