1783ce384e55fa3ce7e24c72a22f1622dad2381f
[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                           unboxedSingletonTyCon, unboxedSingletonDataCon,
31                           listTyCon_RDR, parrTyCon_RDR, consDataCon_RDR )
32 import Type             ( funTyCon )
33 import ForeignCall      ( Safety(..), CExportSpec(..), CLabelString,
34                           CCallConv(..), CCallTarget(..), defaultCCallConv
35                         )
36 import OccName          ( varName, dataName, tcClsName, tvName )
37 import DataCon          ( DataCon, dataConName )
38 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc, combineSrcSpans,
39                           SrcSpan, combineLocs, srcLocFile, 
40                           mkSrcLoc, mkSrcSpan )
41 import Module
42 import StaticFlags      ( opt_SccProfilingOn, opt_Hpc )
43 import Type             ( Kind, mkArrowKind, liftedTypeKind, unliftedTypeKind )
44 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), IPName(..),
45                           Activation(..), defaultInlineSpec )
46 import DynFlags
47 import OrdList
48 import HaddockParse
49 import {-# SOURCE #-} HaddockLex hiding ( Token )
50 import HaddockUtils
51
52 import FastString
53 import Maybes           ( orElse )
54 import Outputable
55
56 import Control.Monad    ( unless )
57 import GHC.Exts
58 import Data.Char
59 import Control.Monad    ( mplus )
60 }
61
62 {-
63 -----------------------------------------------------------------------------
64 24 Februar 2006
65
66 Conflicts: 33 shift/reduce
67            1 reduce/reduce
68
69 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
70 would think the two should never occur in the same context.
71
72   -=chak
73
74 -----------------------------------------------------------------------------
75 31 December 2006
76
77 Conflicts: 34 shift/reduce
78            1 reduce/reduce
79
80 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
81 would think the two should never occur in the same context.
82
83   -=chak
84
85 -----------------------------------------------------------------------------
86 6 December 2006
87
88 Conflicts: 32 shift/reduce
89            1 reduce/reduce
90
91 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
92 would think the two should never occur in the same context.
93
94   -=chak
95
96 -----------------------------------------------------------------------------
97 26 July 2006
98
99 Conflicts: 37 shift/reduce
100            1 reduce/reduce
101
102 The reduce/reduce conflict is weird.  It's between tyconsym and consym, and I
103 would think the two should never occur in the same context.
104
105   -=chak
106
107 -----------------------------------------------------------------------------
108 Conflicts: 38 shift/reduce (1.25)
109
110 10 for abiguity in 'if x then y else z + 1'             [State 178]
111         (shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
112         10 because op might be: : - ! * . `x` VARSYM CONSYM QVARSYM QCONSYM
113
114 1 for ambiguity in 'if x then y else z :: T'            [State 178]
115         (shift parses as 'if x then y else (z :: T)', as per longest-parse rule)
116
117 4 for ambiguity in 'if x then y else z -< e'            [State 178]
118         (shift parses as 'if x then y else (z -< T)', as per longest-parse rule)
119         There are four such operators: -<, >-, -<<, >>-
120
121
122 2 for ambiguity in 'case v of { x :: T -> T ... } '     [States 11, 253]
123         Which of these two is intended?
124           case v of
125             (x::T) -> T         -- Rhs is T
126     or
127           case v of
128             (x::T -> T) -> ..   -- Rhs is ...
129
130 10 for ambiguity in 'e :: a `b` c'.  Does this mean     [States 11, 253]
131         (e::a) `b` c, or 
132         (e :: (a `b` c))
133     As well as `b` we can have !, VARSYM, QCONSYM, and CONSYM, hence 5 cases
134     Same duplication between states 11 and 253 as the previous case
135
136 1 for ambiguity in 'let ?x ...'                         [State 329]
137         the parser can't tell whether the ?x is the lhs of a normal binding or
138         an implicit binding.  Fortunately resolving as shift gives it the only
139         sensible meaning, namely the lhs of an implicit binding.
140
141 1 for ambiguity in '{-# RULES "name" [ ... #-}          [State 382]
142         we don't know whether the '[' starts the activation or not: it
143         might be the start of the declaration with the activation being
144         empty.  --SDM 1/4/2002
145
146 1 for ambiguity in '{-# RULES "name" forall = ... #-}'  [State 474]
147         since 'forall' is a valid variable name, we don't know whether
148         to treat a forall on the input as the beginning of a quantifier
149         or the beginning of the rule itself.  Resolving to shift means
150         it's always treated as a quantifier, hence the above is disallowed.
151         This saves explicitly defining a grammar for the rule lhs that
152         doesn't include 'forall'.
153
154 1 for ambiguity when the source file starts with "-- | doc". We need another
155   token of lookahead to determine if a top declaration or the 'module' keyword
156   follows. Shift parses as if the 'module' keyword follows.   
157
158 -- ---------------------------------------------------------------------------
159 -- Adding location info
160
161 This is done in a stylised way using the three macros below, L0, L1
162 and LL.  Each of these macros can be thought of as having type
163
164    L0, L1, LL :: a -> Located a
165
166 They each add a SrcSpan to their argument.
167
168    L0   adds 'noSrcSpan', used for empty productions
169      -- This doesn't seem to work anymore -=chak
170
171    L1   for a production with a single token on the lhs.  Grabs the SrcSpan
172         from that token.
173
174    LL   for a production with >1 token on the lhs.  Makes up a SrcSpan from
175         the first and last tokens.
176
177 These suffice for the majority of cases.  However, we must be
178 especially careful with empty productions: LL won't work if the first
179 or last token on the lhs can represent an empty span.  In these cases,
180 we have to calculate the span using more of the tokens from the lhs, eg.
181
182         | 'newtype' tycl_hdr '=' newconstr deriving
183                 { L (comb3 $1 $4 $5)
184                     (mkTyData NewType (unLoc $2) [$4] (unLoc $5)) }
185
186 We provide comb3 and comb4 functions which are useful in such cases.
187
188 Be careful: there's no checking that you actually got this right, the
189 only symptom will be that the SrcSpans of your syntax will be
190 incorrect.
191
192 /*
193  * We must expand these macros *before* running Happy, which is why this file is
194  * Parser.y.pp rather than just Parser.y - we run the C pre-processor first.
195  */
196 #define L0   L noSrcSpan
197 #define L1   sL (getLoc $1)
198 #define LL   sL (comb2 $1 $>)
199
200 -- -----------------------------------------------------------------------------
201
202 -}
203
204 %token
205  '_'            { L _ ITunderscore }            -- Haskell keywords
206  'as'           { L _ ITas }
207  'case'         { L _ ITcase }          
208  'class'        { L _ ITclass } 
209  'data'         { L _ ITdata } 
210  'default'      { L _ ITdefault }
211  'deriving'     { L _ ITderiving }
212  'do'           { L _ ITdo }
213  'else'         { L _ ITelse }
214  'hiding'       { L _ IThiding }
215  'if'           { L _ ITif }
216  'import'       { L _ ITimport }
217  'in'           { L _ ITin }
218  'infix'        { L _ ITinfix }
219  'infixl'       { L _ ITinfixl }
220  'infixr'       { L _ ITinfixr }
221  'instance'     { L _ ITinstance }
222  'let'          { L _ ITlet }
223  'module'       { L _ ITmodule }
224  'newtype'      { L _ ITnewtype }
225  'of'           { L _ ITof }
226  'qualified'    { L _ ITqualified }
227  'then'         { L _ ITthen }
228  'type'         { L _ ITtype }
229  'where'        { L _ ITwhere }
230  '_scc_'        { L _ ITscc }         -- ToDo: remove
231
232  'forall'       { L _ ITforall }                -- GHC extension keywords
233  'foreign'      { L _ ITforeign }
234  'export'       { L _ ITexport }
235  'label'        { L _ ITlabel } 
236  'dynamic'      { L _ ITdynamic }
237  'safe'         { L _ ITsafe }
238  'threadsafe'   { L _ ITthreadsafe }
239  'unsafe'       { L _ ITunsafe }
240  'mdo'          { L _ ITmdo }
241  'family'       { L _ ITfamily }
242  'stdcall'      { L _ ITstdcallconv }
243  'ccall'        { L _ ITccallconv }
244  'dotnet'       { L _ ITdotnet }
245  'proc'         { L _ ITproc }          -- for arrow notation extension
246  'rec'          { L _ ITrec }           -- for arrow notation extension
247  'group'    { L _ ITgroup }     -- for list transform extension
248  'by'       { L _ ITby }        -- for list transform extension
249  'using'    { L _ ITusing }     -- for list transform extension
250
251  '{-# INLINE'             { L _ (ITinline_prag _) }
252  '{-# SPECIALISE'         { L _ ITspec_prag }
253  '{-# SPECIALISE_INLINE'  { L _ (ITspec_inline_prag _) }
254  '{-# SOURCE'      { L _ ITsource_prag }
255  '{-# RULES'       { L _ ITrules_prag }
256  '{-# CORE'        { L _ ITcore_prag }              -- hdaume: annotated core
257  '{-# SCC'         { L _ ITscc_prag }
258  '{-# GENERATED'   { L _ ITgenerated_prag }
259  '{-# DEPRECATED'  { L _ ITdeprecated_prag }
260  '{-# UNPACK'      { L _ ITunpack_prag }
261  '#-}'             { L _ ITclose_prag }
262
263  '..'           { L _ ITdotdot }                        -- reserved symbols
264  ':'            { L _ ITcolon }
265  '::'           { L _ ITdcolon }
266  '='            { L _ ITequal }
267  '\\'           { L _ ITlam }
268  '|'            { L _ ITvbar }
269  '<-'           { L _ ITlarrow }
270  '->'           { L _ ITrarrow }
271  '@'            { L _ ITat }
272  '~'            { L _ ITtilde }
273  '=>'           { L _ ITdarrow }
274  '-'            { L _ ITminus }
275  '!'            { L _ ITbang }
276  '*'            { L _ ITstar }
277  '-<'           { L _ ITlarrowtail }            -- for arrow notation
278  '>-'           { L _ ITrarrowtail }            -- for arrow notation
279  '-<<'          { L _ ITLarrowtail }            -- for arrow notation
280  '>>-'          { L _ ITRarrowtail }            -- for arrow notation
281  '.'            { L _ ITdot }
282
283  '{'            { L _ ITocurly }                        -- special symbols
284  '}'            { L _ ITccurly }
285  '{|'           { L _ ITocurlybar }
286  '|}'           { L _ ITccurlybar }
287  vocurly        { L _ ITvocurly } -- virtual open curly (from layout)
288  vccurly        { L _ ITvccurly } -- virtual close curly (from layout)
289  '['            { L _ ITobrack }
290  ']'            { L _ ITcbrack }
291  '[:'           { L _ ITopabrack }
292  ':]'           { L _ ITcpabrack }
293  '('            { L _ IToparen }
294  ')'            { L _ ITcparen }
295  '(#'           { L _ IToubxparen }
296  '#)'           { L _ ITcubxparen }
297  '(|'           { L _ IToparenbar }
298  '|)'           { L _ ITcparenbar }
299  ';'            { L _ ITsemi }
300  ','            { L _ ITcomma }
301  '`'            { L _ ITbackquote }
302
303  VARID          { L _ (ITvarid    _) }          -- identifiers
304  CONID          { L _ (ITconid    _) }
305  VARSYM         { L _ (ITvarsym   _) }
306  CONSYM         { L _ (ITconsym   _) }
307  QVARID         { L _ (ITqvarid   _) }
308  QCONID         { L _ (ITqconid   _) }
309  QVARSYM        { L _ (ITqvarsym  _) }
310  QCONSYM        { L _ (ITqconsym  _) }
311
312  IPDUPVARID     { L _ (ITdupipvarid   _) }              -- GHC extension
313
314  CHAR           { L _ (ITchar     _) }
315  STRING         { L _ (ITstring   _) }
316  INTEGER        { L _ (ITinteger  _) }
317  RATIONAL       { L _ (ITrational _) }
318                     
319  PRIMCHAR       { L _ (ITprimchar   _) }
320  PRIMSTRING     { L _ (ITprimstring _) }
321  PRIMINTEGER    { L _ (ITprimint    _) }
322  PRIMFLOAT      { L _ (ITprimfloat  _) }
323  PRIMDOUBLE     { L _ (ITprimdouble _) }
324
325  DOCNEXT        { L _ (ITdocCommentNext _) }
326  DOCPREV        { L _ (ITdocCommentPrev _) }
327  DOCNAMED       { L _ (ITdocCommentNamed _) }
328  DOCSECTION     { L _ (ITdocSection _ _) }
329
330 -- Template Haskell 
331 '[|'            { L _ ITopenExpQuote  }       
332 '[p|'           { L _ ITopenPatQuote  }      
333 '[t|'           { L _ ITopenTypQuote  }      
334 '[d|'           { L _ ITopenDecQuote  }      
335 '|]'            { L _ ITcloseQuote    }
336 TH_ID_SPLICE    { L _ (ITidEscape _)  }     -- $x
337 '$('            { L _ ITparenEscape   }     -- $( exp )
338 TH_VAR_QUOTE    { L _ ITvarQuote      }     -- 'x
339 TH_TY_QUOTE     { L _ ITtyQuote       }      -- ''T
340
341 %monad { P } { >>= } { return }
342 %lexer { lexer } { L _ ITeof }
343 %name parseModule module
344 %name parseStmt   maybe_stmt
345 %name parseIdentifier  identifier
346 %name parseType ctype
347 %partial parseHeader header
348 %tokentype { (Located Token) }
349 %%
350
351 -----------------------------------------------------------------------------
352 -- Identifiers; one of the entry points
353 identifier :: { Located RdrName }
354         : qvar                          { $1 }
355         | qcon                          { $1 }
356         | qvarop                        { $1 }
357         | qconop                        { $1 }
358     | '(' '->' ')'      { LL $ getRdrName funTyCon }
359
360 -----------------------------------------------------------------------------
361 -- Module Header
362
363 -- The place for module deprecation is really too restrictive, but if it
364 -- was allowed at its natural place just before 'module', we get an ugly
365 -- s/r conflict with the second alternative. Another solution would be the
366 -- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
367 -- either, and DEPRECATED is only expected to be used by people who really
368 -- know what they are doing. :-)
369
370 module  :: { Located (HsModule RdrName) }
371         : maybedocheader 'module' modid maybemoddeprec maybeexports 'where' body
372                 {% fileSrcSpan >>= \ loc -> case $1 of { (info, doc) ->
373                    return (L loc (HsModule (Just $3) $5 (fst $7) (snd $7) $4
374                           info doc) )}}
375         | body2
376                 {% fileSrcSpan >>= \ loc ->
377                    return (L loc (HsModule Nothing Nothing
378                           (fst $1) (snd $1) Nothing emptyHaddockModInfo
379                           Nothing)) }
380
381 maybedocheader :: { (HaddockModInfo RdrName, Maybe (HsDoc RdrName)) }
382         : moduleheader            { (fst $1, snd $1) }
383         | {- empty -}             { (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         : maybedocheader 'module' modid maybemoddeprec maybeexports 'where' header_body
413                 {% fileSrcSpan >>= \ loc -> case $1 of { (info, doc) ->
414                    return (L loc (HsModule (Just $3) $5 $7 [] $4
415                    info doc))}}
416         | missing_module_keyword importdecls
417                 {% fileSrcSpan >>= \ loc ->
418                    return (L loc (HsModule Nothing Nothing $2 [] Nothing
419                    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         : '|' guardquals '=' exp        { sL (comb2 $1 $>) $ GRHS (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                        { sL (getLoc $1) (HsOverLit $! mkHsIsString (getSTRING $1) placeHolderType) }
1352         | INTEGER                       { sL (getLoc $1) (HsOverLit $! mkHsIntegral (getINTEGER $1) placeHolderType) }
1353         | RATIONAL                      { sL (getLoc $1) (HsOverLit $! mkHsFractional (getRATIONAL $1) placeHolderType) }
1354         -- N.B.: sections get parsed by these next two productions.
1355         -- This allows you to write, e.g., '(+ 3, 4 -)', which isn't correct Haskell98
1356         -- (you'd have to write '((+ 3), (4 -))')
1357         -- but the less cluttered version fell out of having texps.
1358         | '(' texp ')'                  { LL (HsPar $2) }
1359         | '(' texp ',' texps ')'        { LL $ ExplicitTuple ($2 : reverse $4) Boxed }
1360         | '(#' texps '#)'               { LL $ ExplicitTuple (reverse $2)      Unboxed }
1361         | '[' list ']'                  { LL (unLoc $2) }
1362         | '[:' parr ':]'                { LL (unLoc $2) }
1363         | '_'                           { L1 EWildPat }
1364         
1365         -- Template Haskell Extension
1366         | TH_ID_SPLICE          { L1 $ HsSpliceE (mkHsSplice 
1367                                         (L1 $ HsVar (mkUnqual varName 
1368                                                         (getTH_ID_SPLICE $1)))) } -- $x
1369         | '$(' exp ')'          { LL $ HsSpliceE (mkHsSplice $2) }               -- $( exp )
1370
1371         | TH_VAR_QUOTE qvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1372         | TH_VAR_QUOTE qcon     { LL $ HsBracket (VarBr (unLoc $2)) }
1373         | TH_TY_QUOTE tyvar     { LL $ HsBracket (VarBr (unLoc $2)) }
1374         | TH_TY_QUOTE gtycon    { LL $ HsBracket (VarBr (unLoc $2)) }
1375         | '[|' exp '|]'         { LL $ HsBracket (ExpBr $2) }                       
1376         | '[t|' ctype '|]'      { LL $ HsBracket (TypBr $2) }                       
1377         | '[p|' infixexp '|]'   {% checkPattern $2 >>= \p ->
1378                                         return (LL $ HsBracket (PatBr p)) }
1379         | '[d|' cvtopbody '|]'  {% checkDecBrGroup $2 >>= \g -> 
1380                                         return (LL $ HsBracket (DecBr g)) }
1381
1382         -- arrow notation extension
1383         | '(|' aexp2 cmdargs '|)'       { LL $ HsArrForm $2 Nothing (reverse $3) }
1384
1385 cmdargs :: { [LHsCmdTop RdrName] }
1386         : cmdargs acmd                  { $2 : $1 }
1387         | {- empty -}                   { [] }
1388
1389 acmd    :: { LHsCmdTop RdrName }
1390         : aexp2                 { L1 $ HsCmdTop $1 [] placeHolderType undefined }
1391
1392 cvtopbody :: { [LHsDecl RdrName] }
1393         :  '{'            cvtopdecls0 '}'               { $2 }
1394         |      vocurly    cvtopdecls0 close             { $2 }
1395
1396 cvtopdecls0 :: { [LHsDecl RdrName] }
1397         : {- empty -}           { [] }
1398         | cvtopdecls            { $1 }
1399
1400 -- tuple expressions: things that can appear unparenthesized as long as they're
1401 -- inside parens or delimitted by commas
1402 texp :: { LHsExpr RdrName }
1403         : exp                           { $1 }
1404         -- Technically, this should only be used for bang patterns,
1405        -- but we can be a little more liberal here and avoid parens
1406        -- inside tuples
1407        | infixexp qop   { LL $ SectionL $1 $2 }
1408         | qopm infixexp       { LL $ SectionR $1 $2 }
1409        -- view patterns get parenthesized above
1410         | exp '->' exp   { LL $ EViewPat $1 $3 }
1411
1412 texps :: { [LHsExpr RdrName] }
1413         : texps ',' texp                { $3 : $1 }
1414         | texp                          { [$1] }
1415
1416
1417 -----------------------------------------------------------------------------
1418 -- List expressions
1419
1420 -- The rules below are little bit contorted to keep lexps left-recursive while
1421 -- avoiding another shift/reduce-conflict.
1422
1423 list :: { LHsExpr RdrName }
1424         : texp                  { L1 $ ExplicitList placeHolderType [$1] }
1425         | lexps                 { L1 $ ExplicitList placeHolderType (reverse (unLoc $1)) }
1426         | texp '..'             { LL $ ArithSeq noPostTcExpr (From $1) }
1427         | texp ',' exp '..'     { LL $ ArithSeq noPostTcExpr (FromThen $1 $3) }
1428         | texp '..' exp         { LL $ ArithSeq noPostTcExpr (FromTo $1 $3) }
1429         | texp ',' exp '..' exp { LL $ ArithSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1430         | texp '|' flattenedpquals      { sL (comb2 $1 $>) $ mkHsDo ListComp (unLoc $3) $1 }
1431
1432 lexps :: { Located [LHsExpr RdrName] }
1433         : lexps ',' texp                { LL ($3 : unLoc $1) }
1434         | texp ',' texp                 { LL [$3,$1] }
1435
1436 -----------------------------------------------------------------------------
1437 -- List Comprehensions
1438
1439 flattenedpquals :: { Located [LStmt RdrName] }
1440     : pquals   { case (unLoc $1) of
1441                     ParStmt [(qs, _)] -> L1 qs
1442                     -- We just had one thing in our "parallel" list so 
1443                     -- we simply return that thing directly
1444                     
1445                     _ -> L1 [$1]
1446                     -- We actually found some actual parallel lists so
1447                     -- we leave them into as a ParStmt
1448                 }
1449
1450 pquals :: { LStmt RdrName }
1451     : pquals1   { L1 (ParStmt [(qs, undefined) | qs <- (reverse (unLoc $1))]) }
1452
1453 pquals1 :: { Located [[LStmt RdrName]] }
1454     : pquals1 '|' squals    { LL (unLoc $3 : unLoc $1) }
1455     | squals                { L (getLoc $1) [unLoc $1] }
1456
1457 squals :: { Located [LStmt RdrName] }
1458     : squals1               { L (getLoc $1) (reverse (unLoc $1)) }
1459
1460 squals1 :: { Located [LStmt RdrName] }
1461     : transformquals1       { LL (unLoc $1) }
1462
1463 transformquals1 :: { Located [LStmt RdrName] }
1464     : transformquals1 ',' transformqual         { LL $ [LL ((unLoc $3) (unLoc $1))] }
1465     | transformquals1 ',' qual                  { LL ($3 : unLoc $1) }
1466 --  | transformquals1 ',' '{|' pquals '|}'      { LL ($4 : unLoc $1) }
1467     | transformqual                             { LL $ [LL ((unLoc $1) [])] }
1468     | qual                                      { L1 [$1] }
1469 --  | '{|' pquals '|}'                          { L1 [$2] }
1470
1471
1472 -- It is possible to enable bracketing (associating) qualifier lists by uncommenting the lines with {| |}
1473 -- above. Due to a lack of consensus on the syntax, this feature is not being used until we get user
1474 -- demand. Note that the {| |} symbols are reused from -XGenerics and hence if you want to compile
1475 -- a program that makes use of this temporary syntax you must supply that flag to GHC
1476
1477 transformqual :: { Located ([LStmt RdrName] -> Stmt RdrName) }
1478     : 'then' exp                { LL $ \leftStmts -> (mkTransformStmt (reverse leftStmts) $2) }
1479     | 'then' exp 'by' exp       { LL $ \leftStmts -> (mkTransformByStmt (reverse leftStmts) $2 $4) }
1480     | 'then' 'group' 'by' exp              { LL $ \leftStmts -> (mkGroupByStmt (reverse leftStmts) $4) }
1481     | 'then' 'group' 'using' exp           { LL $ \leftStmts -> (mkGroupUsingStmt (reverse leftStmts) $4) }
1482     | 'then' 'group' 'by' exp 'using' exp  { LL $ \leftStmts -> (mkGroupByUsingStmt (reverse leftStmts) $4 $6) }
1483
1484 -----------------------------------------------------------------------------
1485 -- Parallel array expressions
1486
1487 -- The rules below are little bit contorted; see the list case for details.
1488 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1489 -- Moreover, we allow explicit arrays with no element (represented by the nil
1490 -- constructor in the list case).
1491
1492 parr :: { LHsExpr RdrName }
1493         :                               { noLoc (ExplicitPArr placeHolderType []) }
1494         | texp                          { L1 $ ExplicitPArr placeHolderType [$1] }
1495         | lexps                         { L1 $ ExplicitPArr placeHolderType 
1496                                                        (reverse (unLoc $1)) }
1497         | texp '..' exp                 { LL $ PArrSeq noPostTcExpr (FromTo $1 $3) }
1498         | texp ',' exp '..' exp         { LL $ PArrSeq noPostTcExpr (FromThenTo $1 $3 $5) }
1499         | texp '|' flattenedpquals      { LL $ mkHsDo PArrComp (unLoc $3) $1 }
1500
1501 -- We are reusing `lexps' and `flattenedpquals' from the list case.
1502
1503 -----------------------------------------------------------------------------
1504 -- Guards
1505
1506 guardquals :: { Located [LStmt RdrName] }
1507     : guardquals1           { L (getLoc $1) (reverse (unLoc $1)) }
1508
1509 guardquals1 :: { Located [LStmt RdrName] }
1510     : guardquals1 ',' qual  { LL ($3 : unLoc $1) }
1511     | qual                  { L1 [$1] }
1512
1513 -----------------------------------------------------------------------------
1514 -- Case alternatives
1515
1516 altslist :: { Located [LMatch RdrName] }
1517         : '{'            alts '}'       { LL (reverse (unLoc $2)) }
1518         |     vocurly    alts  close    { L (getLoc $2) (reverse (unLoc $2)) }
1519
1520 alts    :: { Located [LMatch RdrName] }
1521         : alts1                         { L1 (unLoc $1) }
1522         | ';' alts                      { LL (unLoc $2) }
1523
1524 alts1   :: { Located [LMatch RdrName] }
1525         : alts1 ';' alt                 { LL ($3 : unLoc $1) }
1526         | alts1 ';'                     { LL (unLoc $1) }
1527         | alt                           { L1 [$1] }
1528
1529 alt     :: { LMatch RdrName }
1530         : pat opt_sig alt_rhs           { LL (Match [$1] $2 (unLoc $3)) }
1531
1532 alt_rhs :: { Located (GRHSs RdrName) }
1533         : ralt wherebinds               { LL (GRHSs (unLoc $1) (unLoc $2)) }
1534
1535 ralt :: { Located [LGRHS RdrName] }
1536         : '->' exp                      { LL (unguardedRHS $2) }
1537         | gdpats                        { L1 (reverse (unLoc $1)) }
1538
1539 gdpats :: { Located [LGRHS RdrName] }
1540         : gdpats gdpat                  { LL ($2 : unLoc $1) }
1541         | gdpat                         { L1 [$1] }
1542
1543 gdpat   :: { LGRHS RdrName }
1544         : '|' guardquals '->' exp               { sL (comb2 $1 $>) $ GRHS (unLoc $2) $4 }
1545
1546 -- 'pat' recognises a pattern, including one with a bang at the top
1547 --      e.g.  "!x" or "!(x,y)" or "C a b" etc
1548 -- Bangs inside are parsed as infix operator applications, so that
1549 -- we parse them right when bang-patterns are off
1550 pat     :: { LPat RdrName }
1551 pat     :  exp                  {% checkPattern $1 }
1552         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1553
1554 apat   :: { LPat RdrName }      
1555 apat    : aexp                  {% checkPattern $1 }
1556         | '!' aexp              {% checkPattern (LL (SectionR (L1 (HsVar bang_RDR)) $2)) }
1557
1558 apats  :: { [LPat RdrName] }
1559         : apat apats            { $1 : $2 }
1560         | {- empty -}           { [] }
1561
1562 -----------------------------------------------------------------------------
1563 -- Statement sequences
1564
1565 stmtlist :: { Located [LStmt RdrName] }
1566         : '{'           stmts '}'       { LL (unLoc $2) }
1567         |     vocurly   stmts close     { $2 }
1568
1569 --      do { ;; s ; s ; ; s ;; }
1570 -- The last Stmt should be an expression, but that's hard to enforce
1571 -- here, because we need too much lookahead if we see do { e ; }
1572 -- So we use ExprStmts throughout, and switch the last one over
1573 -- in ParseUtils.checkDo instead
1574 stmts :: { Located [LStmt RdrName] }
1575         : stmt stmts_help               { LL ($1 : unLoc $2) }
1576         | ';' stmts                     { LL (unLoc $2) }
1577         | {- empty -}                   { noLoc [] }
1578
1579 stmts_help :: { Located [LStmt RdrName] } -- might be empty
1580         : ';' stmts                     { LL (unLoc $2) }
1581         | {- empty -}                   { noLoc [] }
1582
1583 -- For typing stmts at the GHCi prompt, where 
1584 -- the input may consist of just comments.
1585 maybe_stmt :: { Maybe (LStmt RdrName) }
1586         : stmt                          { Just $1 }
1587         | {- nothing -}                 { Nothing }
1588
1589 stmt  :: { LStmt RdrName }
1590         : qual                              { $1 }
1591         | 'rec' stmtlist                { LL $ mkRecStmt (unLoc $2) }
1592
1593 qual  :: { LStmt RdrName }
1594     : pat '<-' exp                      { LL $ mkBindStmt $1 $3 }
1595     | exp                                   { L1 $ mkExprStmt $1 }
1596     | 'let' binds                       { LL $ LetStmt (unLoc $2) }
1597
1598 -----------------------------------------------------------------------------
1599 -- Record Field Update/Construction
1600
1601 fbinds  :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1602         : fbinds1                       { $1 }
1603         | {- empty -}                   { ([], False) }
1604
1605 fbinds1 :: { ([HsRecField RdrName (LHsExpr RdrName)], Bool) }
1606         : fbind ',' fbinds1             { case $3 of (flds, dd) -> ($1 : flds, dd) } 
1607         | fbind                         { ([$1], False) }
1608         | '..'                          { ([],   True) }
1609   
1610 fbind   :: { HsRecField RdrName (LHsExpr RdrName) }
1611         : qvar '=' exp  { HsRecField $1 $3 False }
1612         | qvar          { HsRecField $1 (L (getLoc $1) (HsVar (unLoc $1))) True }
1613                         -- Here's where we say that plain 'x'
1614                         -- means exactly 'x = x'.  The pun-flag boolean is
1615                         -- there so we can still print it right
1616
1617 -----------------------------------------------------------------------------
1618 -- Implicit Parameter Bindings
1619
1620 dbinds  :: { Located [LIPBind RdrName] }
1621         : dbinds ';' dbind              { LL ($3 : unLoc $1) }
1622         | dbinds ';'                    { LL (unLoc $1) }
1623         | dbind                         { L1 [$1] }
1624 --      | {- empty -}                   { [] }
1625
1626 dbind   :: { LIPBind RdrName }
1627 dbind   : ipvar '=' exp                 { LL (IPBind (unLoc $1) $3) }
1628
1629 ipvar   :: { Located (IPName RdrName) }
1630         : IPDUPVARID            { L1 (IPName (mkUnqual varName (getIPDUPVARID $1))) }
1631
1632 -----------------------------------------------------------------------------
1633 -- Deprecations
1634
1635 depreclist :: { Located [RdrName] }
1636 depreclist : deprec_var                 { L1 [unLoc $1] }
1637            | deprec_var ',' depreclist  { LL (unLoc $1 : unLoc $3) }
1638
1639 deprec_var :: { Located RdrName }
1640 deprec_var : var                        { $1 }
1641            | con                        { $1 }
1642
1643 -----------------------------------------
1644 -- Data constructors
1645 qcon    :: { Located RdrName }
1646         : qconid                { $1 }
1647         | '(' qconsym ')'       { LL (unLoc $2) }
1648         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1649 -- The case of '[:' ':]' is part of the production `parr'
1650
1651 con     :: { Located RdrName }
1652         : conid                 { $1 }
1653         | '(' consym ')'        { LL (unLoc $2) }
1654         | sysdcon               { L1 $ nameRdrName (dataConName (unLoc $1)) }
1655
1656 sysdcon :: { Located DataCon }  -- Wired in data constructors
1657         : '(' ')'               { LL unitDataCon }
1658         | '(' commas ')'        { LL $ tupleCon Boxed $2 }
1659         | '(#' '#)'             { LL $ unboxedSingletonDataCon }
1660         | '(#' commas '#)'      { LL $ tupleCon Unboxed $2 }
1661         | '[' ']'               { LL nilDataCon }
1662
1663 conop :: { Located RdrName }
1664         : consym                { $1 }  
1665         | '`' conid '`'         { LL (unLoc $2) }
1666
1667 qconop :: { Located RdrName }
1668         : qconsym               { $1 }
1669         | '`' qconid '`'        { LL (unLoc $2) }
1670
1671 -----------------------------------------------------------------------------
1672 -- Type constructors
1673
1674 gtycon  :: { Located RdrName }  -- A "general" qualified tycon
1675         : oqtycon                       { $1 }
1676         | '(' ')'                       { LL $ getRdrName unitTyCon }
1677         | '(' commas ')'                { LL $ getRdrName (tupleTyCon Boxed $2) }
1678         | '(#' '#)'                     { LL $ getRdrName unboxedSingletonTyCon }
1679         | '(#' commas '#)'              { LL $ getRdrName (tupleTyCon Unboxed $2) }
1680         | '(' '->' ')'                  { LL $ getRdrName funTyCon }
1681         | '[' ']'                       { LL $ listTyCon_RDR }
1682         | '[:' ':]'                     { LL $ parrTyCon_RDR }
1683
1684 oqtycon :: { Located RdrName }  -- An "ordinary" qualified tycon
1685         : qtycon                        { $1 }
1686         | '(' qtyconsym ')'             { LL (unLoc $2) }
1687
1688 qtyconop :: { Located RdrName } -- Qualified or unqualified
1689         : qtyconsym                     { $1 }
1690         | '`' qtycon '`'                { LL (unLoc $2) }
1691
1692 qtycon :: { Located RdrName }   -- Qualified or unqualified
1693         : QCONID                        { L1 $! mkQual tcClsName (getQCONID $1) }
1694         | tycon                         { $1 }
1695
1696 tycon   :: { Located RdrName }  -- Unqualified
1697         : CONID                         { L1 $! mkUnqual tcClsName (getCONID $1) }
1698
1699 qtyconsym :: { Located RdrName }
1700         : QCONSYM                       { L1 $! mkQual tcClsName (getQCONSYM $1) }
1701         | tyconsym                      { $1 }
1702
1703 tyconsym :: { Located RdrName }
1704         : CONSYM                        { L1 $! mkUnqual tcClsName (getCONSYM $1) }
1705
1706 -----------------------------------------------------------------------------
1707 -- Operators
1708
1709 op      :: { Located RdrName }   -- used in infix decls
1710         : varop                 { $1 }
1711         | conop                 { $1 }
1712
1713 varop   :: { Located RdrName }
1714         : varsym                { $1 }
1715         | '`' varid '`'         { LL (unLoc $2) }
1716
1717 qop     :: { LHsExpr RdrName }   -- used in sections
1718         : qvarop                { L1 $ HsVar (unLoc $1) }
1719         | qconop                { L1 $ HsVar (unLoc $1) }
1720
1721 qopm    :: { LHsExpr RdrName }   -- used in sections
1722         : qvaropm               { L1 $ HsVar (unLoc $1) }
1723         | qconop                { L1 $ HsVar (unLoc $1) }
1724
1725 qvarop :: { Located RdrName }
1726         : qvarsym               { $1 }
1727         | '`' qvarid '`'        { LL (unLoc $2) }
1728
1729 qvaropm :: { Located RdrName }
1730         : qvarsym_no_minus      { $1 }
1731         | '`' qvarid '`'        { LL (unLoc $2) }
1732
1733 -----------------------------------------------------------------------------
1734 -- Type variables
1735
1736 tyvar   :: { Located RdrName }
1737 tyvar   : tyvarid               { $1 }
1738         | '(' tyvarsym ')'      { LL (unLoc $2) }
1739
1740 tyvarop :: { Located RdrName }
1741 tyvarop : '`' tyvarid '`'       { LL (unLoc $2) }
1742         | tyvarsym              { $1 }
1743
1744 tyvarid :: { Located RdrName }
1745         : VARID                 { L1 $! mkUnqual tvName (getVARID $1) }
1746         | special_id            { L1 $! mkUnqual tvName (unLoc $1) }
1747         | 'unsafe'              { L1 $! mkUnqual tvName FSLIT("unsafe") }
1748         | 'safe'                { L1 $! mkUnqual tvName FSLIT("safe") }
1749         | 'threadsafe'          { L1 $! mkUnqual tvName FSLIT("threadsafe") }
1750
1751 tyvarsym :: { Located RdrName }
1752 -- Does not include "!", because that is used for strictness marks
1753 --               or ".", because that separates the quantified type vars from the rest
1754 --               or "*", because that's used for kinds
1755 tyvarsym : VARSYM               { L1 $! mkUnqual tvName (getVARSYM $1) }
1756
1757 -----------------------------------------------------------------------------
1758 -- Variables 
1759
1760 var     :: { Located RdrName }
1761         : varid                 { $1 }
1762         | '(' varsym ')'        { LL (unLoc $2) }
1763
1764 qvar    :: { Located RdrName }
1765         : qvarid                { $1 }
1766         | '(' varsym ')'        { LL (unLoc $2) }
1767         | '(' qvarsym1 ')'      { LL (unLoc $2) }
1768 -- We've inlined qvarsym here so that the decision about
1769 -- whether it's a qvar or a var can be postponed until
1770 -- *after* we see the close paren.
1771
1772 qvarid :: { Located RdrName }
1773         : varid                 { $1 }
1774         | QVARID                { L1 $ mkQual varName (getQVARID $1) }
1775
1776 varid :: { Located RdrName }
1777         : varid_no_unsafe       { $1 }
1778         | 'unsafe'              { L1 $! mkUnqual varName FSLIT("unsafe") }
1779         | 'safe'                { L1 $! mkUnqual varName FSLIT("safe") }
1780         | 'threadsafe'          { L1 $! mkUnqual varName FSLIT("threadsafe") }
1781
1782 varid_no_unsafe :: { Located RdrName }
1783         : VARID                 { L1 $! mkUnqual varName (getVARID $1) }
1784         | special_id            { L1 $! mkUnqual varName (unLoc $1) }
1785         | 'forall'              { L1 $! mkUnqual varName FSLIT("forall") }
1786         | 'family'              { L1 $! mkUnqual varName FSLIT("family") }
1787
1788 qvarsym :: { Located RdrName }
1789         : varsym                { $1 }
1790         | qvarsym1              { $1 }
1791
1792 qvarsym_no_minus :: { Located RdrName }
1793         : varsym_no_minus       { $1 }
1794         | qvarsym1              { $1 }
1795
1796 qvarsym1 :: { Located RdrName }
1797 qvarsym1 : QVARSYM              { L1 $ mkQual varName (getQVARSYM $1) }
1798
1799 varsym :: { Located RdrName }
1800         : varsym_no_minus       { $1 }
1801         | '-'                   { L1 $ mkUnqual varName FSLIT("-") }
1802
1803 varsym_no_minus :: { Located RdrName } -- varsym not including '-'
1804         : VARSYM                { L1 $ mkUnqual varName (getVARSYM $1) }
1805         | special_sym           { L1 $ mkUnqual varName (unLoc $1) }
1806
1807
1808 -- These special_ids are treated as keywords in various places, 
1809 -- but as ordinary ids elsewhere.   'special_id' collects all these
1810 -- except 'unsafe', 'forall', and 'family' whose treatment differs
1811 -- depending on context 
1812 special_id :: { Located FastString }
1813 special_id
1814         : 'as'                  { L1 FSLIT("as") }
1815         | 'qualified'           { L1 FSLIT("qualified") }
1816         | 'hiding'              { L1 FSLIT("hiding") }
1817         | 'export'              { L1 FSLIT("export") }
1818         | 'label'               { L1 FSLIT("label")  }
1819         | 'dynamic'             { L1 FSLIT("dynamic") }
1820         | 'stdcall'             { L1 FSLIT("stdcall") }
1821         | 'ccall'               { L1 FSLIT("ccall") }
1822
1823 special_sym :: { Located FastString }
1824 special_sym : '!'       { L1 FSLIT("!") }
1825             | '.'       { L1 FSLIT(".") }
1826             | '*'       { L1 FSLIT("*") }
1827
1828 -----------------------------------------------------------------------------
1829 -- Data constructors
1830
1831 qconid :: { Located RdrName }   -- Qualified or unqualified
1832         : conid                 { $1 }
1833         | QCONID                { L1 $ mkQual dataName (getQCONID $1) }
1834
1835 conid   :: { Located RdrName }
1836         : CONID                 { L1 $ mkUnqual dataName (getCONID $1) }
1837
1838 qconsym :: { Located RdrName }  -- Qualified or unqualified
1839         : consym                { $1 }
1840         | QCONSYM               { L1 $ mkQual dataName (getQCONSYM $1) }
1841
1842 consym :: { Located RdrName }
1843         : CONSYM                { L1 $ mkUnqual dataName (getCONSYM $1) }
1844
1845         -- ':' means only list cons
1846         | ':'                   { L1 $ consDataCon_RDR }
1847
1848
1849 -----------------------------------------------------------------------------
1850 -- Literals
1851
1852 literal :: { Located HsLit }
1853         : CHAR                  { L1 $ HsChar       $ getCHAR $1 }
1854         | STRING                { L1 $ HsString     $ getSTRING $1 }
1855         | PRIMINTEGER           { L1 $ HsIntPrim    $ getPRIMINTEGER $1 }
1856         | PRIMCHAR              { L1 $ HsCharPrim   $ getPRIMCHAR $1 }
1857         | PRIMSTRING            { L1 $ HsStringPrim $ getPRIMSTRING $1 }
1858         | PRIMFLOAT             { L1 $ HsFloatPrim  $ getPRIMFLOAT $1 }
1859         | PRIMDOUBLE            { L1 $ HsDoublePrim $ getPRIMDOUBLE $1 }
1860
1861 -----------------------------------------------------------------------------
1862 -- Layout
1863
1864 close :: { () }
1865         : vccurly               { () } -- context popped in lexer.
1866         | error                 {% popContext }
1867
1868 -----------------------------------------------------------------------------
1869 -- Miscellaneous (mostly renamings)
1870
1871 modid   :: { Located ModuleName }
1872         : CONID                 { L1 $ mkModuleNameFS (getCONID $1) }
1873         | QCONID                { L1 $ let (mod,c) = getQCONID $1 in
1874                                   mkModuleNameFS
1875                                    (mkFastString
1876                                      (unpackFS mod ++ '.':unpackFS c))
1877                                 }
1878
1879 commas :: { Int }
1880         : commas ','                    { $1 + 1 }
1881         | ','                           { 2 }
1882
1883 -----------------------------------------------------------------------------
1884 -- Documentation comments
1885
1886 docnext :: { LHsDoc RdrName }
1887   : DOCNEXT {% case parseHaddockParagraphs (tokenise (getDOCNEXT $1)) of {
1888       MyLeft  err -> parseError (getLoc $1) err;
1889       MyRight doc -> return (L1 doc) } }
1890
1891 docprev :: { LHsDoc RdrName }
1892   : DOCPREV {% case parseHaddockParagraphs (tokenise (getDOCPREV $1)) of {
1893       MyLeft  err -> parseError (getLoc $1) err;
1894       MyRight doc -> return (L1 doc) } }
1895
1896 docnamed :: { Located (String, (HsDoc RdrName)) }
1897   : DOCNAMED {%
1898       let string = getDOCNAMED $1 
1899           (name, rest) = break isSpace string
1900       in case parseHaddockParagraphs (tokenise rest) of {
1901         MyLeft  err -> parseError (getLoc $1) err;
1902         MyRight doc -> return (L1 (name, doc)) } }
1903
1904 docsection :: { Located (Int, HsDoc RdrName) }
1905   : DOCSECTION {% let (n, doc) = getDOCSECTION $1 in
1906         case parseHaddockString (tokenise doc) of {
1907       MyLeft  err -> parseError (getLoc $1) err;
1908       MyRight doc -> return (L1 (n, doc)) } }
1909
1910 moduleheader :: { (HaddockModInfo RdrName, Maybe (HsDoc RdrName)) }                                    
1911         : DOCNEXT {% let string = getDOCNEXT $1 in
1912                case parseModuleHeader string of {                       
1913                  Right (str, info) ->                                  
1914                    case parseHaddockParagraphs (tokenise str) of {               
1915                      MyLeft err -> parseError (getLoc $1) err;                    
1916                      MyRight doc -> return (info, Just doc);          
1917                    };                                             
1918                  Left err -> parseError (getLoc $1) err
1919             }  }                                                  
1920
1921 maybe_docprev :: { Maybe (LHsDoc RdrName) }
1922         : docprev                       { Just $1 }
1923         | {- empty -}                   { Nothing }
1924
1925 maybe_docnext :: { Maybe (LHsDoc RdrName) }
1926         : docnext                       { Just $1 }
1927         | {- empty -}                   { Nothing }
1928
1929 {
1930 happyError :: P a
1931 happyError = srcParseFail
1932
1933 getVARID        (L _ (ITvarid    x)) = x
1934 getCONID        (L _ (ITconid    x)) = x
1935 getVARSYM       (L _ (ITvarsym   x)) = x
1936 getCONSYM       (L _ (ITconsym   x)) = x
1937 getQVARID       (L _ (ITqvarid   x)) = x
1938 getQCONID       (L _ (ITqconid   x)) = x
1939 getQVARSYM      (L _ (ITqvarsym  x)) = x
1940 getQCONSYM      (L _ (ITqconsym  x)) = x
1941 getIPDUPVARID   (L _ (ITdupipvarid   x)) = x
1942 getCHAR         (L _ (ITchar     x)) = x
1943 getSTRING       (L _ (ITstring   x)) = x
1944 getINTEGER      (L _ (ITinteger  x)) = x
1945 getRATIONAL     (L _ (ITrational x)) = x
1946 getPRIMCHAR     (L _ (ITprimchar   x)) = x
1947 getPRIMSTRING   (L _ (ITprimstring x)) = x
1948 getPRIMINTEGER  (L _ (ITprimint    x)) = x
1949 getPRIMFLOAT    (L _ (ITprimfloat  x)) = x
1950 getPRIMDOUBLE   (L _ (ITprimdouble x)) = x
1951 getTH_ID_SPLICE (L _ (ITidEscape x)) = x
1952 getINLINE       (L _ (ITinline_prag b)) = b
1953 getSPEC_INLINE  (L _ (ITspec_inline_prag b)) = b
1954
1955 getDOCNEXT (L _ (ITdocCommentNext x)) = x
1956 getDOCPREV (L _ (ITdocCommentPrev x)) = x
1957 getDOCNAMED (L _ (ITdocCommentNamed x)) = x
1958 getDOCSECTION (L _ (ITdocSection n x)) = (n, x)
1959
1960 -- Utilities for combining source spans
1961 comb2 :: Located a -> Located b -> SrcSpan
1962 comb2 = combineLocs
1963
1964 comb3 :: Located a -> Located b -> Located c -> SrcSpan
1965 comb3 a b c = combineSrcSpans (getLoc a) (combineSrcSpans (getLoc b) (getLoc c))
1966
1967 comb4 :: Located a -> Located b -> Located c -> Located d -> SrcSpan
1968 comb4 a b c d = combineSrcSpans (getLoc a) $ combineSrcSpans (getLoc b) $
1969                 combineSrcSpans (getLoc c) (getLoc d)
1970
1971 -- strict constructor version:
1972 {-# INLINE sL #-}
1973 sL :: SrcSpan -> a -> Located a
1974 sL span a = span `seq` L span a
1975
1976 -- Make a source location for the file.  We're a bit lazy here and just
1977 -- make a point SrcSpan at line 1, column 0.  Strictly speaking we should
1978 -- try to find the span of the whole file (ToDo).
1979 fileSrcSpan :: P SrcSpan
1980 fileSrcSpan = do 
1981   l <- getSrcLoc; 
1982   let loc = mkSrcLoc (srcLocFile l) 1 0;
1983   return (mkSrcSpan loc loc)
1984 }