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