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