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