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