fix haddock submodule pointer
[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 ']>' '@' tyvar     { LL $ HsModalBoxType  (unLoc $5) $2 }
1037         | '[:' ctype ':]'               { LL $ HsPArrTy  $2 }
1038         | '(' ctype ')'                 { LL $ HsParTy   $2 }
1039         | '(' ctype '::' kind ')'       { LL $ HsKindSig $2 (unLoc $4) }
1040         | quasiquote                    { L1 (HsQuasiQuoteTy (unLoc $1)) }
1041         | '$(' exp ')'                  { LL $ mkHsSpliceTy $2 }
1042         | TH_ID_SPLICE                  { LL $ mkHsSpliceTy $ L1 $ HsVar $ 
1043                                           mkUnqual varName (getTH_ID_SPLICE $1) }
1044
1045 -- An inst_type is what occurs in the head of an instance decl
1046 --      e.g.  (Foo a, Gaz b) => Wibble a b
1047 -- It's kept as a single type, with a MonoDictTy at the right
1048 -- hand corner, for convenience.
1049 inst_type :: { LHsType RdrName }
1050         : sigtype                       {% checkInstType $1 }
1051
1052 inst_types1 :: { [LHsType RdrName] }
1053         : inst_type                     { [$1] }
1054         | inst_type ',' inst_types1     { $1 : $3 }
1055
1056 comma_types0  :: { [LHsType RdrName] }
1057         : comma_types1                  { $1 }
1058         | {- empty -}                   { [] }
1059
1060 comma_types1    :: { [LHsType RdrName] }
1061         : ctype                         { [$1] }
1062         | ctype  ',' comma_types1       { $1 : $3 }
1063
1064 tv_bndrs :: { [LHsTyVarBndr RdrName] }
1065          : tv_bndr tv_bndrs             { $1 : $2 }
1066          | {- empty -}                  { [] }
1067
1068 tv_bndr :: { LHsTyVarBndr RdrName }
1069         : tyvar                         { L1 (UserTyVar (unLoc $1) placeHolderKind) }
1070         | '(' tyvar '::' kind ')'       { LL (KindedTyVar (unLoc $2) 
1071                                                           (unLoc $4)) }
1072
1073 fds :: { Located [Located (FunDep RdrName)] }
1074         : {- empty -}                   { noLoc [] }
1075         | '|' fds1                      { LL (reverse (unLoc $2)) }
1076
1077 fds1 :: { Located [Located (FunDep RdrName)] }
1078         : fds1 ',' fd                   { LL ($3 : unLoc $1) }
1079         | fd                            { L1 [$1] }
1080
1081 fd :: { Located (FunDep RdrName) }
1082         : varids0 '->' varids0          { L (comb3 $1 $2 $3)
1083                                            (reverse (unLoc $1), reverse (unLoc $3)) }
1084
1085 varids0 :: { Located [RdrName] }
1086         : {- empty -}                   { noLoc [] }
1087         | varids0 tyvar                 { LL (unLoc $2 : unLoc $1) }
1088
1089 -----------------------------------------------------------------------------
1090 -- Kinds
1091
1092 kind    :: { Located Kind }
1093         : akind                 { $1 }
1094         | akind '->' kind       { LL (mkArrowKind (unLoc $1) (unLoc $3)) }
1095
1096 akind   :: { Located Kind }
1097         : '*'                   { L1 liftedTypeKind }
1098         | '!'                   { L1 unliftedTypeKind }
1099         | '(' kind ')'          { LL (unLoc $2) }
1100
1101
1102 -----------------------------------------------------------------------------
1103 -- Datatype declarations
1104
1105 gadt_constrlist :: { Located [LConDecl RdrName] }       -- Returned in order
1106         : 'where' '{'        gadt_constrs '}'      { L (comb2 $1 $3) (unLoc $3) }
1107         | 'where' vocurly    gadt_constrs close    { L (comb2 $1 $3) (unLoc $3) }
1108         | {- empty -}                              { noLoc [] }
1109
1110 gadt_constrs :: { Located [LConDecl RdrName] }
1111         : gadt_constr ';' gadt_constrs  { L (comb2 (head $1) $3) ($1 ++ unLoc $3) }
1112         | gadt_constr                   { L (getLoc (head $1)) $1 }
1113         | {- empty -}                   { noLoc [] }
1114
1115 -- We allow the following forms:
1116 --      C :: Eq a => a -> T a
1117 --      C :: forall a. Eq a => !a -> T a
1118 --      D { x,y :: a } :: T a
1119 --      forall a. Eq a => D { x,y :: a } :: T a
1120
1121 gadt_constr :: { [LConDecl RdrName] }   -- Returns a list because of:   C,D :: ty
1122         : con_list '::' sigtype
1123                 { map (sL (comb2 $1 $3)) (mkGadtDecl (unLoc $1) $3) } 
1124
1125                 -- Deprecated syntax for GADT record declarations
1126         | oqtycon '{' fielddecls '}' '::' sigtype
1127                 {% do { cd <- mkDeprecatedGadtRecordDecl (comb2 $1 $6) $1 $3 $6
1128                       ; return [cd] } }
1129
1130 constrs :: { Located [LConDecl RdrName] }
1131         : maybe_docnext '=' constrs1    { L (comb2 $2 $3) (addConDocs (unLoc $3) $1) }
1132
1133 constrs1 :: { Located [LConDecl RdrName] }
1134         : constrs1 maybe_docnext '|' maybe_docprev constr { LL (addConDoc $5 $2 : addConDocFirst (unLoc $1) $4) }
1135         | constr                                          { L1 [$1] }
1136
1137 constr :: { LConDecl RdrName }
1138         : maybe_docnext forall context '=>' constr_stuff maybe_docprev  
1139                 { let (con,details) = unLoc $5 in 
1140                   addConDoc (L (comb4 $2 $3 $4 $5) (mkSimpleConDecl con (unLoc $2) $3 details))
1141                             ($1 `mplus` $6) }
1142         | maybe_docnext forall constr_stuff maybe_docprev
1143                 { let (con,details) = unLoc $3 in 
1144                   addConDoc (L (comb2 $2 $3) (mkSimpleConDecl con (unLoc $2) (noLoc []) details))
1145                             ($1 `mplus` $4) }
1146
1147 forall :: { Located [LHsTyVarBndr RdrName] }
1148         : 'forall' tv_bndrs '.'         { LL $2 }
1149         | {- empty -}                   { noLoc [] }
1150
1151 constr_stuff :: { Located (Located RdrName, HsConDeclDetails RdrName) }
1152 -- We parse the constructor declaration 
1153 --      C t1 t2
1154 -- as a btype (treating C as a type constructor) and then convert C to be
1155 -- a data constructor.  Reason: it might continue like this:
1156 --      C t1 t2 %: D Int
1157 -- in which case C really would be a type constructor.  We can't resolve this
1158 -- ambiguity till we come across the constructor oprerator :% (or not, more usually)
1159         : btype                         {% splitCon $1 >>= return.LL }
1160         | btype conop btype             {  LL ($2, InfixCon $1 $3) }
1161
1162 fielddecls :: { [ConDeclField RdrName] }
1163         : {- empty -}     { [] }
1164         | fielddecls1     { $1 }
1165
1166 fielddecls1 :: { [ConDeclField RdrName] }
1167         : fielddecl maybe_docnext ',' maybe_docprev fielddecls1
1168                       { [ addFieldDoc f $4 | f <- $1 ] ++ addFieldDocs $5 $2 }
1169                              -- This adds the doc $4 to each field separately
1170         | fielddecl   { $1 }
1171
1172 fielddecl :: { [ConDeclField RdrName] }    -- A list because of   f,g :: Int
1173         : maybe_docnext sig_vars '::' ctype maybe_docprev      { [ ConDeclField fld $4 ($1 `mplus` $5) 
1174                                                                  | fld <- reverse (unLoc $2) ] }
1175
1176 -- We allow the odd-looking 'inst_type' in a deriving clause, so that
1177 -- we can do deriving( forall a. C [a] ) in a newtype (GHC extension).
1178 -- The 'C [a]' part is converted to an HsPredTy by checkInstType
1179 -- We don't allow a context, but that's sorted out by the type checker.
1180 deriving :: { Located (Maybe [LHsType RdrName]) }
1181         : {- empty -}                           { noLoc Nothing }
1182         | 'deriving' qtycon     {% do { let { L loc tv = $2 }
1183                                       ; p <- checkInstType (L loc (HsTyVar tv))
1184                                       ; return (LL (Just [p])) } }
1185         | 'deriving' '(' ')'                    { LL (Just []) }
1186         | 'deriving' '(' inst_types1 ')'        { LL (Just $3) }
1187              -- Glasgow extension: allow partial 
1188              -- applications in derivings
1189
1190 -----------------------------------------------------------------------------
1191 -- Value definitions
1192
1193 {- Note [Declaration/signature overlap]
1194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1195 There's an awkward overlap with a type signature.  Consider
1196         f :: Int -> Int = ...rhs...
1197    Then we can't tell whether it's a type signature or a value
1198    definition with a result signature until we see the '='.
1199    So we have to inline enough to postpone reductions until we know.
1200 -}
1201
1202 {-
1203   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
1204   instead of qvar, we get another shift/reduce-conflict. Consider the
1205   following programs:
1206   
1207      { (^^) :: Int->Int ; }          Type signature; only var allowed
1208
1209      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
1210                                      qvar allowed (because of instance decls)
1211   
1212   We can't tell whether to reduce var to qvar until after we've read the signatures.
1213 -}
1214
1215 docdecl :: { LHsDecl RdrName }
1216         : docdecld { L1 (DocD (unLoc $1)) }
1217
1218 docdecld :: { LDocDecl }
1219         : docnext                               { L1 (DocCommentNext (unLoc $1)) }
1220         | docprev                               { L1 (DocCommentPrev (unLoc $1)) }
1221         | docnamed                              { L1 (case (unLoc $1) of (n, doc) -> DocCommentNamed n doc) }
1222         | docsection                            { L1 (case (unLoc $1) of (n, doc) -> DocGroup n doc) }
1223
1224 decl    :: { Located (OrdList (LHsDecl RdrName)) }
1225         : sigdecl               { $1 }
1226
1227         | '!' aexp rhs          {% do { let { e = LL (SectionR (LL (HsVar bang_RDR)) $2) };
1228                                         pat <- checkPattern e;
1229                                         return $ LL $ unitOL $ LL $ ValD $
1230                                                PatBind pat (unLoc $3)
1231                                                        placeHolderType placeHolderNames } }
1232                                 -- Turn it all into an expression so that
1233                                 -- checkPattern can check that bangs are enabled
1234
1235         | infixexp opt_sig rhs  {% do { r <- checkValDef $1 $2 $3;
1236                                         let { l = comb2 $1 $> };
1237                                         return $! (sL l (unitOL $! (sL l $ ValD r))) } }
1238
1239         | docdecl               { LL $ unitOL $1 }
1240
1241 rhs     :: { Located (GRHSs RdrName) }
1242         : '=' exp wherebinds    { sL (comb3 $1 $2 $3) $ GRHSs (unguardedRHS $2) (unLoc $3) }
1243         | gdrhs wherebinds      { LL $ GRHSs (reverse (unLoc $1)) (unLoc $2) }
1244
1245 gdrhs :: { Located [LGRHS RdrName] }
1246         : gdrhs gdrh            { LL ($2 : unLoc $1) }
1247         | gdrh                  { L1 [$1] }
1248
1249 gdrh :: { LGRHS RdrName }
1250         : '|' guardquals '=' exp        { sL (comb2 $1 $>) $ GRHS (unLoc $2) $4 }
1251
1252 sigdecl :: { Located (OrdList (LHsDecl RdrName)) }
1253         : 
1254         -- See Note [Declaration/signature overlap] for why we need infixexp here
1255           infixexp '::' sigtypedoc
1256                         {% do s <- checkValSig $1 $3 
1257                         ; return (LL $ unitOL (LL $ SigD s)) }
1258         | var ',' sig_vars '::' sigtypedoc
1259                                 { LL $ toOL [ LL $ SigD (TypeSig n $5) | n <- $1 : unLoc $3 ] }
1260         | infix prec ops        { LL $ toOL [ LL $ SigD (FixSig (FixitySig n (Fixity $2 (unLoc $1))))
1261                                              | n <- unLoc $3 ] }
1262         | '{-# INLINE'   activation qvar '#-}'        
1263                 { LL $ unitOL (LL $ SigD (InlineSig $3 (mkInlinePragma (getINLINE $1) $2))) }
1264         | '{-# SPECIALISE' qvar '::' sigtypes1 '#-}'
1265                 { LL $ toOL [ LL $ SigD (SpecSig $2 t defaultInlinePragma) 
1266                                             | t <- $4] }
1267         | '{-# SPECIALISE_INLINE' activation qvar '::' sigtypes1 '#-}'
1268                 { LL $ toOL [ LL $ SigD (SpecSig $3 t (mkInlinePragma (getSPEC_INLINE $1) $2))
1269                                             | t <- $5] }
1270         | '{-# SPECIALISE' 'instance' inst_type '#-}'
1271                 { LL $ unitOL (LL $ SigD (SpecInstSig $3)) }
1272
1273 -----------------------------------------------------------------------------
1274 -- Expressions
1275
1276 quasiquote :: { Located (HsQuasiQuote RdrName) }
1277         : TH_QUASIQUOTE   { let { loc = getLoc $1
1278                                 ; ITquasiQuote (quoter, quote, quoteSpan) = unLoc $1
1279                                 ; quoterId = mkUnqual varName quoter }
1280                             in L1 (mkHsQuasiQuote quoterId (RealSrcSpan quoteSpan) quote) }
1281
1282 incdepth   :: { Located () } :  {% do { incrBracketDepth  ; return $ noLoc () } }
1283 incdepth1  :: { Located () } :  {% do { incrBracketDepth1 ; return $ noLoc () } }
1284 decdepth   :: { Located () } :  {% do { decrBracketDepth  ; return $ noLoc () } }
1285 pushdepth  :: { Located () } :  {% do { pushBracketDepth  ; return $ noLoc () } }
1286 popdepth   :: { Located () } :  {% do { popBracketDepth   ; return $ noLoc () } }
1287
1288
1289 exp   :: { LHsExpr RdrName }
1290         : infixexp '::' sigtype         { LL $ ExprWithTySig $1 $3 }
1291         | infixexp '-<' exp             { LL $ HsArrApp $1 $3 placeHolderType HsFirstOrderApp True }
1292         | infixexp '>-' exp             { LL $ HsArrApp $3 $1 placeHolderType HsFirstOrderApp False }
1293         | infixexp '-<<' exp            { LL $ HsArrApp $1 $3 placeHolderType HsHigherOrderApp True }
1294         | infixexp '>>-' exp            { LL $ HsArrApp $3 $1 placeHolderType HsHigherOrderApp False}
1295         | infixexp                      { $1 }
1296         | '~~$' pushdepth exp popdepth  {% do { x <- mkHsHetMetEsc placeHolderType placeHolderType $3; return $ sL (comb2 $3 $>) x } }
1297
1298 infixexp :: { LHsExpr RdrName }
1299         : exp10                         { $1 }
1300         | infixexp qop exp10            { LL (OpApp $1 $2 (panic "fixity") $3) }
1301
1302 exp10 :: { LHsExpr RdrName }
1303         : '\\' apat apats opt_asig '->' exp     
1304                         {% do { x <- getParserBrakDepth
1305                               ; return
1306                                   $ case x of
1307                                    KappaFlavor:_ -> LL $ HsKappa (mkMatchGroup[LL $ Match ($2:$3) $4 (unguardedGRHSs $6) ])
1308                                    _             -> LL $ HsLam (mkMatchGroup [LL $ Match ($2:$3) $4 (unguardedGRHSs $6) ])
1309                               } }
1310         | 'let' binds 'in' exp                  { LL $ HsLet (unLoc $2) $4 }
1311         | 'if' exp optSemi 'then' exp optSemi 'else' exp
1312                                         {% checkDoAndIfThenElse $2 $3 $5 $6 $8 >>
1313                                            return (LL $ mkHsIf $2 $5 $8) }
1314         | 'case' exp 'of' altslist              { LL $ HsCase $2 (mkMatchGroup (unLoc $4)) }
1315         | '-' fexp                              { LL $ NegApp $2 noSyntaxExpr }
1316
1317         | 'do' stmtlist                 { L (comb2 $1 $2) (mkHsDo DoExpr  (unLoc $2)) }
1318         | 'mdo' stmtlist                { L (comb2 $1 $2) (mkHsDo MDoExpr (unLoc $2)) }
1319
1320         | scc_annot exp                         { LL $ if opt_SccProfilingOn
1321                                                         then HsSCC (unLoc $1) $2
1322                                                         else HsPar $2 }
1323         | hpc_annot exp                         { LL $ if opt_Hpc
1324                                                         then HsTickPragma (unLoc $1) $2
1325                                                         else HsPar $2 }
1326
1327         | 'proc' aexp '->' exp  
1328                         {% checkPattern $2 >>= \ p -> 
1329                            return (LL $ HsProc p (LL $ HsCmdTop $4 [] 
1330                                                    placeHolderType undefined)) }
1331                                                 -- TODO: is LL right here?
1332
1333         | '{-# CORE' STRING '#-}' exp           { LL $ HsCoreAnn (getSTRING $2) $4 }
1334                                                     -- hdaume: core annotation
1335         | fexp                                  { $1 }
1336
1337 optSemi :: { Bool }
1338         : ';'         { True }
1339         | {- empty -} { False }
1340
1341 scc_annot :: { Located FastString }
1342         : '_scc_' STRING                        {% (addWarning Opt_WarnWarningsDeprecations (getLoc $1) (text "_scc_ is deprecated; use an SCC pragma instead")) >>= \_ ->
1343                                    ( do scc <- getSCC $2; return $ LL scc ) }
1344         | '{-# SCC' STRING '#-}'                {% do scc <- getSCC $2; return $ LL scc }
1345
1346 hpc_annot :: { Located (FastString,(Int,Int),(Int,Int)) }
1347         : '{-# GENERATED' STRING INTEGER ':' INTEGER '-' INTEGER ':' INTEGER '#-}'
1348                                                 { LL $ (getSTRING $2
1349                                                        ,( fromInteger $ getINTEGER $3
1350                                                         , fromInteger $ getINTEGER $5
1351                                                         )
1352                                                        ,( fromInteger $ getINTEGER $7
1353                                                         , fromInteger $ getINTEGER $9
1354                                                         )
1355                                                        )
1356                                                  }
1357
1358 fexp    :: { LHsExpr RdrName }
1359         : fexp aexp                             {% do { x <- getParserBrakDepth
1360                                                       ; return $ case x of 
1361                                                                    []             -> LL $ HsApp $1 $2
1362                                                                    LambdaFlavor:_ -> LL $ HsApp $1 $2
1363                                                                    KappaFlavor:_  -> LL $ HsKappaApp $1 $2
1364                                                       } }
1365         | aexp                                  { $1 }
1366
1367 aexp    :: { LHsExpr RdrName }
1368         : qvar '@' aexp                 { LL $ EAsPat $1 $3 }
1369         | '~' aexp                      { LL $ ELazyPat $2 }
1370         | aexp1                 { $1 }
1371
1372 aexp1   :: { LHsExpr RdrName }
1373         : aexp1 '{' fbinds '}'  {% do { r <- mkRecConstrOrUpdate $1 (comb2 $2 $4) $3
1374                                       ; return (LL r) }}
1375         | aexp2                 { $1 }
1376
1377 -- Here was the syntax for type applications that I was planning
1378 -- but there are difficulties (e.g. what order for type args)
1379 -- so it's not enabled yet.
1380 -- But this case *is* used for the left hand side of a generic definition,
1381 -- which is parsed as an expression before being munged into a pattern
1382         | qcname '{|' type '|}'         { LL $ HsApp (sL (getLoc $1) (HsVar (unLoc $1)))
1383                                                      (sL (getLoc $3) (HsType $3)) }
1384
1385 aexp2   :: { LHsExpr RdrName }
1386         : ipvar                         { L1 (HsIPVar $! unLoc $1) }
1387         | qcname                        { L1 (HsVar   $! unLoc $1) }
1388         | literal                       { L1 (HsLit   $! unLoc $1) }
1389 -- This will enable overloaded strings permanently.  Normally the renamer turns HsString
1390 -- into HsOverLit when -foverloaded-strings is on.
1391 --      | STRING                        { sL (getLoc $1) (HsOverLit $! mkHsIsString (getSTRING $1) placeHolderType) }
1392         | INTEGER                       { sL (getLoc $1) (HsOverLit $! mkHsIntegral (getINTEGER $1) placeHolderType) }
1393         | RATIONAL                      { sL (getLoc $1) (HsOverLit $! mkHsFractional (getRATIONAL $1) placeHolderType) }
1394
1395         -- N.B.: sections get parsed by these next two productions.
1396         -- This allows you to write, e.g., '(+ 3, 4 -)', which isn't
1397         -- correct Haskell (you'd have to write '((+ 3), (4 -))')
1398         -- but the less cluttered version fell out of having texps.
1399         | '(' texp ')'                  { LL (HsPar $2) }
1400         | '(' tup_exprs ')'             { LL (ExplicitTuple $2 Boxed) }
1401
1402         | '(#' texp '#)'                { LL (ExplicitTuple [Present $2] Unboxed) }
1403         | '(#' tup_exprs '#)'           { LL (ExplicitTuple $2 Unboxed) }
1404
1405         | '[' list ']'                  { LL (unLoc $2) }
1406         | '[:' parr ':]'                { LL (unLoc $2) }
1407         | '_'                           { L1 EWildPat }
1408         
1409         -- Template Haskell Extension
1410         | TH_ID_SPLICE          { L1 $ HsSpliceE (mkHsSplice 
1411                                         (L1 $ HsVar (mkUnqual varName 
1412                                                         (getTH_ID_SPLICE $1)))) } 
1413         | '$(' exp ')'          { LL $ HsSpliceE (mkHsSplice $2) }               
1414
1415
1416         | TH_VAR_QUOTE qvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1417         | TH_VAR_QUOTE qcon     { LL $ HsBracket (VarBr (unLoc $2)) }
1418         | TH_TY_QUOTE tyvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1419         | TH_TY_QUOTE gtycon    { LL $ HsBracket (VarBr (unLoc $2)) }
1420         | '[|' exp '|]'         { LL $ HsBracket (ExpBr $2) }                       
1421         | '[t|' ctype '|]'      { LL $ HsBracket (TypBr $2) }                       
1422         | '[p|' infixexp '|]'   {% checkPattern $2 >>= \p ->
1423                                         return (LL $ HsBracket (PatBr p)) }
1424         | '[d|' cvtopbody '|]'  { LL $ HsBracket (DecBrL $2) }
1425         | quasiquote            { L1 (HsQuasiQuoteE (unLoc $1)) }
1426
1427         -- arrow notation extension
1428         | '(|' aexp2 cmdargs '|)'       { LL $ HsArrForm $2 Nothing (reverse $3) }
1429
1430         -- code type notation extension
1431         | '<[' incdepth  exp  decdepth ']>'     { sL (comb2 $3 $>) (HsHetMetBrak  placeHolderType                 $3) }
1432         | '<{' incdepth1 exp  decdepth '}>'     { sL (comb2 $3 $>) (HsHetMetBrak  placeHolderType                 $3) }
1433         | '~~' pushdepth aexp popdepth          {% do { x <- mkHsHetMetEsc placeHolderType placeHolderType $3; return $ sL (comb2 $3 $>) x } }
1434         | '%%' pushdepth aexp popdepth          { sL (comb2 $3 $>) (HsHetMetCSP   placeHolderType                 $3) }
1435
1436 cmdargs :: { [LHsCmdTop RdrName] }
1437         : cmdargs acmd                  { $2 : $1 }
1438         | {- empty -}                   { [] }
1439
1440 acmd    :: { LHsCmdTop RdrName }
1441         : aexp2                 { L1 $ HsCmdTop $1 [] placeHolderType undefined }
1442
1443 cvtopbody :: { [LHsDecl RdrName] }
1444         :  '{'            cvtopdecls0 '}'               { $2 }
1445         |      vocurly    cvtopdecls0 close             { $2 }
1446
1447 cvtopdecls0 :: { [LHsDecl RdrName] }
1448         : {- empty -}           { [] }
1449         | cvtopdecls            { $1 }
1450
1451 -----------------------------------------------------------------------------
1452 -- Tuple expressions
1453
1454 -- "texp" is short for tuple expressions: 
1455 -- things that can appear unparenthesized as long as they're
1456 -- inside parens or delimitted by commas
1457 texp :: { LHsExpr RdrName }
1458         : exp                           { $1 }
1459
1460         -- Note [Parsing sections]
1461         -- ~~~~~~~~~~~~~~~~~~~~~~~
1462         -- We include left and right sections here, which isn't
1463         -- technically right according to the Haskell standard.
1464         -- For example (3 +, True) isn't legal.
1465         -- However, we want to parse bang patterns like
1466         --      (!x, !y)
1467         -- and it's convenient to do so here as a section
1468         -- Then when converting expr to pattern we unravel it again
1469         -- Meanwhile, the renamer checks that real sections appear
1470         -- inside parens.
1471         | infixexp qop  { LL $ SectionL $1 $2 }
1472         | qopm infixexp       { LL $ SectionR $1 $2 }
1473
1474        -- View patterns get parenthesized above
1475         | exp '->' texp   { LL $ EViewPat $1 $3 }
1476
1477 -- Always at least one comma
1478 tup_exprs :: { [HsTupArg RdrName] }
1479            : texp commas_tup_tail  { Present $1 : $2 }
1480            | commas tup_tail       { replicate $1 missingTupArg ++ $2 }
1481
1482 -- Always starts with commas; always follows an expr
1483 commas_tup_tail :: { [HsTupArg RdrName] }
1484 commas_tup_tail : commas tup_tail  { replicate ($1-1) missingTupArg ++ $2 }
1485
1486 -- Always follows a comma
1487 tup_tail :: { [HsTupArg RdrName] }
1488           : texp commas_tup_tail        { Present $1 : $2 }
1489           | texp                        { [Present $1] }
1490           | {- empty -}                 { [missingTupArg] }
1491
1492 -----------------------------------------------------------------------------
1493 -- List expressions
1494
1495 -- The rules below are little bit contorted to keep lexps left-recursive while
1496 -- avoiding another shift/reduce-conflict.
1497
1498 list :: { LHsExpr RdrName }
1499         : texp                  { L1 $ ExplicitList placeHolderType [$1] }
1500         | lexps                 { L1 $ ExplicitList placeHolderType (reverse (unLoc $1)) }
1501         | texp '..'             { LL $ ArithSeq noPostTcExpr (From $1) }
1502         | texp ',' exp '..'     { LL $ ArithSeq noPostTcExpr (FromThen $1 $3) }
1503         | texp '..' exp         { LL $ ArithSeq noPostTcExpr (FromTo $1 $3) }
1504         | texp ',' exp '..' exp { LL $ ArithSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1505         | texp '|' flattenedpquals      
1506              {% checkMonadComp >>= \ ctxt ->
1507                 return (sL (comb2 $1 $>) $ 
1508                         mkHsComp ctxt (unLoc $3) $1) }
1509
1510 lexps :: { Located [LHsExpr RdrName] }
1511         : lexps ',' texp                { LL (((:) $! $3) $! unLoc $1) }
1512         | texp ',' texp                 { LL [$3,$1] }
1513
1514 -----------------------------------------------------------------------------
1515 -- List Comprehensions
1516
1517 flattenedpquals :: { Located [LStmt RdrName] }
1518     : pquals   { case (unLoc $1) of
1519                     [qs] -> L1 qs
1520                     -- We just had one thing in our "parallel" list so 
1521                     -- we simply return that thing directly
1522                     
1523                     qss -> L1 [L1 $ ParStmt [(qs, undefined) | qs <- qss] noSyntaxExpr noSyntaxExpr noSyntaxExpr]
1524                     -- We actually found some actual parallel lists so
1525                     -- we wrap them into as a ParStmt
1526                 }
1527
1528 pquals :: { Located [[LStmt RdrName]] }
1529     : squals '|' pquals     { L (getLoc $2) (reverse (unLoc $1) : unLoc $3) }
1530     | squals                { L (getLoc $1) [reverse (unLoc $1)] }
1531
1532 squals :: { Located [LStmt RdrName] }   -- In reverse order, because the last 
1533                                         -- one can "grab" the earlier ones
1534     : squals ',' transformqual               { LL [L (getLoc $3) ((unLoc $3) (reverse (unLoc $1)))] }
1535     | squals ',' qual                        { LL ($3 : unLoc $1) }
1536     | transformqual                          { LL [L (getLoc $1) ((unLoc $1) [])] }
1537     | qual                                   { L1 [$1] }
1538 --  | transformquals1 ',' '{|' pquals '|}'   { LL ($4 : unLoc $1) }
1539 --  | '{|' pquals '|}'                       { L1 [$2] }
1540
1541
1542 -- It is possible to enable bracketing (associating) qualifier lists by uncommenting the lines with {| |}
1543 -- above. Due to a lack of consensus on the syntax, this feature is not being used until we get user
1544 -- demand.
1545
1546 transformqual :: { Located ([LStmt RdrName] -> Stmt RdrName) }
1547                         -- Function is applied to a list of stmts *in order*
1548     : 'then' exp                { LL $ \leftStmts -> (mkTransformStmt leftStmts $2) }
1549     -- >>>
1550     | 'then' exp 'by' exp       { LL $ \leftStmts -> (mkTransformByStmt leftStmts $2 $4) }
1551     | 'then' 'group' 'by' exp   { LL $ \leftStmts -> (mkGroupByStmt leftStmts $4) }
1552     -- <<<
1553     -- These two productions deliberately have a shift-reduce conflict. I have made 'group' into a special_id,
1554     -- which means you can enable TransformListComp while still using Data.List.group. However, this makes the two
1555     -- productions ambiguous. I've set things up so that Happy chooses to resolve the conflict in that case by
1556     -- choosing the "group by" variant, which is what we want.
1557     --
1558     -- This is rather dubious: the user might be confused as to how to parse this statement. However, it is a good
1559     -- practical choice. NB: Data.List.group :: [a] -> [[a]], so using the first production would not even type check
1560     -- if /that/ is the group function we conflict with.
1561     | 'then' 'group' 'using' exp           { LL $ \leftStmts -> (mkGroupUsingStmt leftStmts $4) }
1562     | 'then' 'group' 'by' exp 'using' exp  { LL $ \leftStmts -> (mkGroupByUsingStmt leftStmts $4 $6) }
1563
1564 -----------------------------------------------------------------------------
1565 -- Parallel array expressions
1566
1567 -- The rules below are little bit contorted; see the list case for details.
1568 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1569 -- Moreover, we allow explicit arrays with no element (represented by the nil
1570 -- constructor in the list case).
1571
1572 parr :: { LHsExpr RdrName }
1573         :                               { noLoc (ExplicitPArr placeHolderType []) }
1574         | texp                          { L1 $ ExplicitPArr placeHolderType [$1] }
1575         | lexps                         { L1 $ ExplicitPArr placeHolderType 
1576                                                        (reverse (unLoc $1)) }
1577         | texp '..' exp                 { LL $ PArrSeq noPostTcExpr (FromTo $1 $3) }
1578         | texp ',' exp '..' exp         { LL $ PArrSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1579         | texp '|' flattenedpquals      { LL $ mkHsComp PArrComp (unLoc $3) $1 }
1580
1581 -- We are reusing `lexps' and `flattenedpquals' from the list case.
1582
1583 -----------------------------------------------------------------------------
1584 -- Guards
1585
1586 guardquals :: { Located [LStmt RdrName] }
1587     : guardquals1           { L (getLoc $1) (reverse (unLoc $1)) }
1588
1589 guardquals1 :: { Located [LStmt RdrName] }
1590     : guardquals1 ',' qual  { LL ($3 : unLoc $1) }
1591     | qual                  { L1 [$1] }
1592
1593 -----------------------------------------------------------------------------
1594 -- Case alternatives
1595
1596 altslist :: { Located [LMatch RdrName] }
1597         : '{'            alts '}'       { LL (reverse (unLoc $2)) }
1598         |     vocurly    alts  close    { L (getLoc $2) (reverse (unLoc $2)) }
1599
1600 alts    :: { Located [LMatch RdrName] }
1601         : alts1                         { L1 (unLoc $1) }
1602         | ';' alts                      { LL (unLoc $2) }
1603
1604 alts1   :: { Located [LMatch RdrName] }
1605         : alts1 ';' alt                 { LL ($3 : unLoc $1) }
1606         | alts1 ';'                     { LL (unLoc $1) }
1607         | alt                           { L1 [$1] }
1608
1609 alt     :: { LMatch RdrName }
1610         : pat opt_sig alt_rhs           { LL (Match [$1] $2 (unLoc $3)) }
1611
1612 alt_rhs :: { Located (GRHSs RdrName) }
1613         : ralt wherebinds               { LL (GRHSs (unLoc $1) (unLoc $2)) }
1614
1615 ralt :: { Located [LGRHS RdrName] }
1616         : '->' exp                      { LL (unguardedRHS $2) }
1617         | gdpats                        { L1 (reverse (unLoc $1)) }
1618
1619 gdpats :: { Located [LGRHS RdrName] }
1620         : gdpats gdpat                  { LL ($2 : unLoc $1) }
1621         | gdpat                         { L1 [$1] }
1622
1623 gdpat   :: { LGRHS RdrName }
1624         : '|' guardquals '->' exp               { sL (comb2 $1 $>) $ GRHS (unLoc $2) $4 }
1625
1626 -- 'pat' recognises a pattern, including one with a bang at the top
1627 --      e.g.  "!x" or "!(x,y)" or "C a b" etc
1628 -- Bangs inside are parsed as infix operator applications, so that
1629 -- we parse them right when bang-patterns are off
1630 pat     :: { LPat RdrName }
1631 pat     :  exp                  {% checkPattern $1 }
1632         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1633
1634 apat   :: { LPat RdrName }      
1635 apat    : aexp                  {% checkPattern $1 }
1636         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1637
1638 apats  :: { [LPat RdrName] }
1639         : apat apats            { $1 : $2 }
1640         | {- empty -}           { [] }
1641
1642 -----------------------------------------------------------------------------
1643 -- Statement sequences
1644
1645 stmtlist :: { Located [LStmt RdrName] }
1646         : '{'           stmts '}'       { LL (unLoc $2) }
1647         |     vocurly   stmts close     { $2 }
1648
1649 --      do { ;; s ; s ; ; s ;; }
1650 -- The last Stmt should be an expression, but that's hard to enforce
1651 -- here, because we need too much lookahead if we see do { e ; }
1652 -- So we use ExprStmts throughout, and switch the last one over
1653 -- in ParseUtils.checkDo instead
1654 stmts :: { Located [LStmt RdrName] }
1655         : stmt stmts_help               { LL ($1 : unLoc $2) }
1656         | ';' stmts                     { LL (unLoc $2) }
1657         | {- empty -}                   { noLoc [] }
1658
1659 stmts_help :: { Located [LStmt RdrName] } -- might be empty
1660         : ';' stmts                     { LL (unLoc $2) }
1661         | {- empty -}                   { noLoc [] }
1662
1663 -- For typing stmts at the GHCi prompt, where 
1664 -- the input may consist of just comments.
1665 maybe_stmt :: { Maybe (LStmt RdrName) }
1666         : stmt                          { Just $1 }
1667         | {- nothing -}                 { Nothing }
1668
1669 stmt  :: { LStmt RdrName }
1670         : qual                              { $1 }
1671         | 'rec' stmtlist                { LL $ mkRecStmt (unLoc $2) }
1672
1673 qual  :: { LStmt RdrName }
1674     : pat '<-' exp                      { LL $ mkBindStmt $1 $3 }
1675     | exp                                   { L1 $ mkExprStmt $1 }
1676     | 'let' binds                       { LL $ LetStmt (unLoc $2) }
1677
1678 -----------------------------------------------------------------------------
1679 -- Record Field Update/Construction
1680
1681 fbinds  :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1682         : fbinds1                       { $1 }
1683         | {- empty -}                   { ([], False) }
1684
1685 fbinds1 :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1686         : fbind ',' fbinds1             { case $3 of (flds, dd) -> ($1 : flds, dd) } 
1687         | fbind                         { ([$1], False) }
1688         | '..'                          { ([],   True) }
1689   
1690 fbind   :: { HsRecField RdrName (LHsExpr RdrName) }
1691         : qvar '=' exp  { HsRecField $1 $3                False }
1692         | qvar          { HsRecField $1 placeHolderPunRhs True }
1693                         -- In the punning case, use a place-holder
1694                         -- The renamer fills in the final value
1695
1696 -----------------------------------------------------------------------------
1697 -- Implicit Parameter Bindings
1698
1699 dbinds  :: { Located [LIPBind RdrName] }
1700         : dbinds ';' dbind              { let { this = $3; rest = unLoc $1 }
1701                               in rest `seq` this `seq` LL (this : rest) }
1702         | dbinds ';'                    { LL (unLoc $1) }
1703         | dbind                         { let this = $1 in this `seq` L1 [this] }
1704 --      | {- empty -}                   { [] }
1705
1706 dbind   :: { LIPBind RdrName }
1707 dbind   : ipvar '=' exp                 { LL (IPBind (unLoc $1) $3) }
1708
1709 ipvar   :: { Located (IPName RdrName) }
1710         : IPDUPVARID            { L1 (IPName (mkUnqual varName (getIPDUPVARID $1))) }
1711
1712 -----------------------------------------------------------------------------
1713 -- Warnings and deprecations
1714
1715 namelist :: { Located [RdrName] }
1716 namelist : name_var              { L1 [unLoc $1] }
1717          | name_var ',' namelist { LL (unLoc $1 : unLoc $3) }
1718
1719 name_var :: { Located RdrName }
1720 name_var : var { $1 }
1721          | con { $1 }
1722
1723 -----------------------------------------
1724 -- Data constructors
1725 qcon    :: { Located RdrName }
1726         : qconid                { $1 }
1727         | '(' qconsym ')'       { LL (unLoc $2) }
1728         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1729 -- The case of '[:' ':]' is part of the production `parr'
1730
1731 con     :: { Located RdrName }
1732         : conid                 { $1 }
1733         | '(' consym ')'        { LL (unLoc $2) }
1734         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1735
1736 con_list :: { Located [Located RdrName] }
1737 con_list : con                  { L1 [$1] }
1738          | con ',' con_list     { LL ($1 : unLoc $3) }
1739
1740 sysdcon :: { Located DataCon }  -- Wired in data constructors
1741         : '(' ')'               { LL unitDataCon }
1742         | '(' commas ')'        { LL $ tupleCon Boxed ($2 + 1) }
1743         | '(#' '#)'             { LL $ unboxedSingletonDataCon }
1744         | '(#' commas '#)'      { LL $ tupleCon Unboxed ($2 + 1) }
1745         | '[' ']'               { LL nilDataCon }
1746
1747 conop :: { Located RdrName }
1748         : consym                { $1 }  
1749         | '`' conid '`'         { LL (unLoc $2) }
1750
1751 qconop :: { Located RdrName }
1752         : qconsym               { $1 }
1753         | '`' qconid '`'        { LL (unLoc $2) }
1754
1755 -----------------------------------------------------------------------------
1756 -- Type constructors
1757
1758 gtycon  :: { Located RdrName }  -- A "general" qualified tycon
1759         : oqtycon                       { $1 }
1760         | '(' ')'                       { LL $ getRdrName unitTyCon }
1761         | '(' commas ')'                { LL $ getRdrName (tupleTyCon Boxed ($2 + 1)) }
1762         | '(#' '#)'                     { LL $ getRdrName unboxedSingletonTyCon }
1763         | '(#' commas '#)'              { LL $ getRdrName (tupleTyCon Unboxed ($2 + 1)) }
1764         | '(' '->' ')'                  { LL $ getRdrName funTyCon }
1765         | '[' ']'                       { LL $ listTyCon_RDR }
1766         | '[:' ':]'                     { LL $ parrTyCon_RDR }
1767
1768 oqtycon :: { Located RdrName }  -- An "ordinary" qualified tycon
1769         : qtycon                        { $1 }
1770         | '(' qtyconsym ')'             { LL (unLoc $2) }
1771
1772 qtyconop :: { Located RdrName } -- Qualified or unqualified
1773         : qtyconsym                     { $1 }
1774         | '`' qtycon '`'                { LL (unLoc $2) }
1775
1776 qtycon :: { Located RdrName }   -- Qualified or unqualified
1777         : QCONID                        { L1 $! mkQual tcClsName (getQCONID $1) }
1778         | PREFIXQCONSYM                 { L1 $! mkQual tcClsName (getPREFIXQCONSYM $1) }
1779         | tycon                         { $1 }
1780
1781 tycon   :: { Located RdrName }  -- Unqualified
1782         : CONID                         { L1 $! mkUnqual tcClsName (getCONID $1) }
1783
1784 qtyconsym :: { Located RdrName }
1785         : QCONSYM                       { L1 $! mkQual tcClsName (getQCONSYM $1) }
1786         | tyconsym                      { $1 }
1787
1788 tyconsym :: { Located RdrName }
1789         : CONSYM                        { L1 $! mkUnqual tcClsName (getCONSYM $1) }
1790
1791 -----------------------------------------------------------------------------
1792 -- Operators
1793
1794 op      :: { Located RdrName }   -- used in infix decls
1795         : varop                 { $1 }
1796         | conop                 { $1 }
1797
1798 varop   :: { Located RdrName }
1799         : varsym                { $1 }
1800         | '`' varid '`'         { LL (unLoc $2) }
1801
1802 qop     :: { LHsExpr RdrName }   -- used in sections
1803         : qvarop                { L1 $ HsVar (unLoc $1) }
1804         | qconop                { L1 $ HsVar (unLoc $1) }
1805
1806 qopm    :: { LHsExpr RdrName }   -- used in sections
1807         : qvaropm               { L1 $ HsVar (unLoc $1) }
1808         | qconop                { L1 $ HsVar (unLoc $1) }
1809
1810 qvarop :: { Located RdrName }
1811         : qvarsym               { $1 }
1812         | '`' qvarid '`'        { LL (unLoc $2) }
1813
1814 qvaropm :: { Located RdrName }
1815         : qvarsym_no_minus      { $1 }
1816         | '`' qvarid '`'        { LL (unLoc $2) }
1817
1818 -----------------------------------------------------------------------------
1819 -- Type variables
1820
1821 tyvar   :: { Located RdrName }
1822 tyvar   : tyvarid               { $1 }
1823         | '(' tyvarsym ')'      { LL (unLoc $2) }
1824
1825 tyvarop :: { Located RdrName }
1826 tyvarop : '`' tyvarid '`'       { LL (unLoc $2) }
1827         | tyvarsym              { $1 }
1828         | '.'                   {% parseErrorSDoc (getLoc $1) 
1829                                       (vcat [ptext (sLit "Illegal symbol '.' in type"), 
1830                                              ptext (sLit "Perhaps you intended -XRankNTypes or similar flag"),
1831                                              ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")])
1832                                 }
1833
1834 tyvarid :: { Located RdrName }
1835         : VARID                 { L1 $! mkUnqual tvName (getVARID $1) }
1836         | special_id            { L1 $! mkUnqual tvName (unLoc $1) }
1837         | 'unsafe'              { L1 $! mkUnqual tvName (fsLit "unsafe") }
1838         | 'safe'                { L1 $! mkUnqual tvName (fsLit "safe") }
1839         | 'interruptible'       { L1 $! mkUnqual tvName (fsLit "interruptible") }
1840         | 'threadsafe'          { L1 $! mkUnqual tvName (fsLit "threadsafe") }
1841
1842 tyvarsym :: { Located RdrName }
1843 -- Does not include "!", because that is used for strictness marks
1844 --               or ".", because that separates the quantified type vars from the rest
1845 --               or "*", because that's used for kinds
1846 tyvarsym : VARSYM               { L1 $! mkUnqual tvName (getVARSYM $1) }
1847
1848 -----------------------------------------------------------------------------
1849 -- Variables 
1850
1851 var     :: { Located RdrName }
1852         : varid                 { $1 }
1853         | '(' varsym ')'        { LL (unLoc $2) }
1854
1855 qvar    :: { Located RdrName }
1856         : qvarid                { $1 }
1857         | '(' varsym ')'        { LL (unLoc $2) }
1858         | '(' qvarsym1 ')'      { LL (unLoc $2) }
1859 -- We've inlined qvarsym here so that the decision about
1860 -- whether it's a qvar or a var can be postponed until
1861 -- *after* we see the close paren.
1862
1863 qvarid :: { Located RdrName }
1864         : varid                 { $1 }
1865         | QVARID                { L1 $! mkQual varName (getQVARID $1) }
1866         | PREFIXQVARSYM         { L1 $! mkQual varName (getPREFIXQVARSYM $1) }
1867
1868 varid :: { Located RdrName }
1869         : VARID                 {% do { depth <- getParserBrakDepth ; return (L1 $! mkUnqual (varNameDepth $ length depth) (getVARID $1)) } }
1870         | special_id            { L1 $! mkUnqual varName (unLoc $1) }
1871         | 'unsafe'              { L1 $! mkUnqual varName (fsLit "unsafe") }
1872         | 'safe'                { L1 $! mkUnqual varName (fsLit "safe") }
1873         | 'interruptible'       { L1 $! mkUnqual varName (fsLit "interruptible") }
1874         | 'threadsafe'          { L1 $! mkUnqual varName (fsLit "threadsafe") }
1875         | 'forall'              { L1 $! mkUnqual varName (fsLit "forall") }
1876         | 'family'              { L1 $! mkUnqual varName (fsLit "family") }
1877
1878 qvarsym :: { Located RdrName }
1879         : varsym                { $1 }
1880         | qvarsym1              { $1 }
1881
1882 qvarsym_no_minus :: { Located RdrName }
1883         : varsym_no_minus       { $1 }
1884         | qvarsym1              { $1 }
1885
1886 qvarsym1 :: { Located RdrName }
1887 qvarsym1 : QVARSYM              { L1 $ mkQual varName (getQVARSYM $1) }
1888
1889 varsym :: { Located RdrName }
1890         : varsym_no_minus       { $1 }
1891         | '-'                   { L1 $ mkUnqual varName (fsLit "-") }
1892
1893 varsym_no_minus :: { Located RdrName } -- varsym not including '-'
1894         : VARSYM                {% do { depth <- getParserBrakDepth
1895                                       ; return (L1 $! mkUnqual (varNameDepth $ length depth) (getVARSYM $1)) } }
1896         | special_sym           {% do { depth <- getParserBrakDepth
1897                                       ; return (L1 $! mkUnqual (varNameDepth $ length depth) (unLoc $1)) } }
1898
1899 -- These special_ids are treated as keywords in various places, 
1900 -- but as ordinary ids elsewhere.   'special_id' collects all these
1901 -- except 'unsafe', 'interruptible', 'forall', and 'family' whose treatment differs
1902 -- depending on context 
1903 special_id :: { Located FastString }
1904 special_id
1905         : 'as'                  { L1 (fsLit "as") }
1906         | 'qualified'           { L1 (fsLit "qualified") }
1907         | 'hiding'              { L1 (fsLit "hiding") }
1908         | 'export'              { L1 (fsLit "export") }
1909         | 'label'               { L1 (fsLit "label")  }
1910         | 'dynamic'             { L1 (fsLit "dynamic") }
1911         | 'stdcall'             { L1 (fsLit "stdcall") }
1912         | 'ccall'               { L1 (fsLit "ccall") }
1913         | 'prim'                { L1 (fsLit "prim") }
1914         | 'group'               { L1 (fsLit "group") }
1915
1916 special_sym :: { Located FastString }
1917 special_sym : '!'       { L1 (fsLit "!") }
1918             | '.'       { L1 (fsLit ".") }
1919             | '*'       { L1 (fsLit "*") }
1920
1921 -----------------------------------------------------------------------------
1922 -- Data constructors
1923
1924 qconid :: { Located RdrName }   -- Qualified or unqualified
1925         : conid                 { $1 }
1926         | QCONID                { L1 $! mkQual dataName (getQCONID $1) }
1927         | PREFIXQCONSYM         { L1 $! mkQual dataName (getPREFIXQCONSYM $1) }
1928
1929 conid   :: { Located RdrName }
1930         : CONID                 { L1 $ mkUnqual dataName (getCONID $1) }
1931
1932 qconsym :: { Located RdrName }  -- Qualified or unqualified
1933         : consym                { $1 }
1934         | QCONSYM               { L1 $ mkQual dataName (getQCONSYM $1) }
1935
1936 consym :: { Located RdrName }
1937         : CONSYM                { L1 $ mkUnqual dataName (getCONSYM $1) }
1938
1939         -- ':' means only list cons
1940         | ':'                   { L1 $ consDataCon_RDR }
1941
1942
1943 -----------------------------------------------------------------------------
1944 -- Literals
1945
1946 literal :: { Located HsLit }
1947         : CHAR                  { L1 $ HsChar       $ getCHAR $1 }
1948         | STRING                { L1 $ HsString     $ getSTRING $1 }
1949         | PRIMINTEGER           { L1 $ HsIntPrim    $ getPRIMINTEGER $1 }
1950         | PRIMWORD              { L1 $ HsWordPrim    $ getPRIMWORD $1 }
1951         | PRIMCHAR              { L1 $ HsCharPrim   $ getPRIMCHAR $1 }
1952         | PRIMSTRING            { L1 $ HsStringPrim $ getPRIMSTRING $1 }
1953         | PRIMFLOAT             { L1 $ HsFloatPrim  $ getPRIMFLOAT $1 }
1954         | PRIMDOUBLE            { L1 $ HsDoublePrim $ getPRIMDOUBLE $1 }
1955
1956 -----------------------------------------------------------------------------
1957 -- Layout
1958
1959 close :: { () }
1960         : vccurly               { () } -- context popped in lexer.
1961         | error                 {% popContext }
1962
1963 -----------------------------------------------------------------------------
1964 -- Miscellaneous (mostly renamings)
1965
1966 modid   :: { Located ModuleName }
1967         : CONID                 { L1 $ mkModuleNameFS (getCONID $1) }
1968         | QCONID                { L1 $ let (mod,c) = getQCONID $1 in
1969                                   mkModuleNameFS
1970                                    (mkFastString
1971                                      (unpackFS mod ++ '.':unpackFS c))
1972                                 }
1973
1974 commas :: { Int }
1975         : commas ','                    { $1 + 1 }
1976         | ','                           { 1 }
1977
1978 -----------------------------------------------------------------------------
1979 -- Documentation comments
1980
1981 docnext :: { LHsDocString }
1982   : DOCNEXT {% return (L1 (HsDocString (mkFastString (getDOCNEXT $1)))) }
1983
1984 docprev :: { LHsDocString }
1985   : DOCPREV {% return (L1 (HsDocString (mkFastString (getDOCPREV $1)))) }
1986
1987 docnamed :: { Located (String, HsDocString) }
1988   : DOCNAMED {%
1989       let string = getDOCNAMED $1 
1990           (name, rest) = break isSpace string
1991       in return (L1 (name, HsDocString (mkFastString rest))) }
1992
1993 docsection :: { Located (Int, HsDocString) }
1994   : DOCSECTION {% let (n, doc) = getDOCSECTION $1 in
1995         return (L1 (n, HsDocString (mkFastString doc))) }
1996
1997 moduleheader :: { Maybe LHsDocString }
1998         : DOCNEXT {% let string = getDOCNEXT $1 in
1999                      return (Just (L1 (HsDocString (mkFastString string)))) }
2000
2001 maybe_docprev :: { Maybe LHsDocString }
2002         : docprev                       { Just $1 }
2003         | {- empty -}                   { Nothing }
2004
2005 maybe_docnext :: { Maybe LHsDocString }
2006         : docnext                       { Just $1 }
2007         | {- empty -}                   { Nothing }
2008
2009 {
2010 happyError :: P a
2011 happyError = srcParseFail
2012
2013 getVARID        (L _ (ITvarid    x)) = x
2014 getCONID        (L _ (ITconid    x)) = x
2015 getVARSYM       (L _ (ITvarsym   x)) = x
2016 getCONSYM       (L _ (ITconsym   x)) = x
2017 getQVARID       (L _ (ITqvarid   x)) = x
2018 getQCONID       (L _ (ITqconid   x)) = x
2019 getQVARSYM      (L _ (ITqvarsym  x)) = x
2020 getQCONSYM      (L _ (ITqconsym  x)) = x
2021 getPREFIXQVARSYM (L _ (ITprefixqvarsym  x)) = x
2022 getPREFIXQCONSYM (L _ (ITprefixqconsym  x)) = x
2023 getIPDUPVARID   (L _ (ITdupipvarid   x)) = x
2024 getCHAR         (L _ (ITchar     x)) = x
2025 getSTRING       (L _ (ITstring   x)) = x
2026 getINTEGER      (L _ (ITinteger  x)) = x
2027 getRATIONAL     (L _ (ITrational x)) = x
2028 getPRIMCHAR     (L _ (ITprimchar   x)) = x
2029 getPRIMSTRING   (L _ (ITprimstring x)) = x
2030 getPRIMINTEGER  (L _ (ITprimint    x)) = x
2031 getPRIMWORD     (L _ (ITprimword x)) = x
2032 getPRIMFLOAT    (L _ (ITprimfloat  x)) = x
2033 getPRIMDOUBLE   (L _ (ITprimdouble x)) = x
2034 getTH_ID_SPLICE (L _ (ITidEscape x)) = x
2035 getINLINE       (L _ (ITinline_prag inl conl)) = (inl,conl)
2036 getSPEC_INLINE  (L _ (ITspec_inline_prag True))  = (Inline,  FunLike)
2037 getSPEC_INLINE  (L _ (ITspec_inline_prag False)) = (NoInline,FunLike)
2038
2039 getDOCNEXT (L _ (ITdocCommentNext x)) = x
2040 getDOCPREV (L _ (ITdocCommentPrev x)) = x
2041 getDOCNAMED (L _ (ITdocCommentNamed x)) = x
2042 getDOCSECTION (L _ (ITdocSection n x)) = (n, x)
2043
2044 getSCC :: Located Token -> P FastString
2045 getSCC lt = do let s = getSTRING lt
2046                    err = "Spaces are not allowed in SCCs"
2047                -- We probably actually want to be more restrictive than this
2048                if ' ' `elem` unpackFS s
2049                    then failSpanMsgP (getLoc lt) (text err)
2050                    else return s
2051
2052 -- Utilities for combining source spans
2053 comb2 :: Located a -> Located b -> SrcSpan
2054 comb2 a b = a `seq` b `seq` combineLocs a b
2055
2056 comb3 :: Located a -> Located b -> Located c -> SrcSpan
2057 comb3 a b c = a `seq` b `seq` c `seq`
2058     combineSrcSpans (getLoc a) (combineSrcSpans (getLoc b) (getLoc c))
2059
2060 comb4 :: Located a -> Located b -> Located c -> Located d -> SrcSpan
2061 comb4 a b c d = a `seq` b `seq` c `seq` d `seq`
2062     (combineSrcSpans (getLoc a) $ combineSrcSpans (getLoc b) $
2063                 combineSrcSpans (getLoc c) (getLoc d))
2064
2065 -- strict constructor version:
2066 {-# INLINE sL #-}
2067 sL :: SrcSpan -> a -> Located a
2068 sL span a = span `seq` a `seq` L span a
2069
2070 -- Make a source location for the file.  We're a bit lazy here and just
2071 -- make a point SrcSpan at line 1, column 0.  Strictly speaking we should
2072 -- try to find the span of the whole file (ToDo).
2073 fileSrcSpan :: P SrcSpan
2074 fileSrcSpan = do 
2075   l <- getSrcLoc; 
2076   let loc = mkSrcLoc (srcLocFile l) 1 1;
2077   return (mkSrcSpan loc loc)
2078
2079 mkHsHetMetEsc a b c = do { depth <- getParserBrakDepth
2080                          ; return $ case head depth of
2081                                     { LambdaFlavor -> HsHetMetEsc  a b c
2082                                     ; KappaFlavor  -> HsHetMetEsc  a b c
2083                                     }
2084                          }
2085
2086 }