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