[project @ 2002-09-06 14:35:42 by simonmar]
[ghc-hetmet.git] / ghc / compiler / parser / Parser.y
1 {-                                                              -*-haskell-*-
2 -----------------------------------------------------------------------------
3 $Id: Parser.y,v 1.101 2002/09/06 14:35:44 simonmar Exp $
4
5 Haskell grammar.
6
7 Author(s): Simon Marlow, Sven Panne 1997, 1998, 1999
8 -----------------------------------------------------------------------------
9 -}
10
11 {
12 module Parser ( parseModule, parseStmt, parseIdentifier, parseIface ) where
13
14 #include "HsVersions.h"
15
16 import HsSyn
17 import HsTypes          ( mkHsTupCon )
18
19 import RdrHsSyn
20 import RnMonad          ( ParsedIface(..) )
21 import Lex
22 import ParseUtil
23 import RdrName
24 import PrelNames        ( mAIN_Name, unitTyCon_RDR, funTyCon_RDR, 
25                           listTyCon_RDR, parrTyCon_RDR, tupleTyCon_RDR, 
26                           unitCon_RDR, nilCon_RDR, tupleCon_RDR )
27 import ForeignCall      ( Safety(..), CExportSpec(..), 
28                           CCallConv(..), CCallTarget(..), defaultCCallConv,
29                         )
30 import OccName          ( UserFS, varName, tcName, dataName, tcClsName, tvName )
31 import TyCon            ( DataConDetails(..) )
32 import SrcLoc           ( SrcLoc )
33 import Module
34 import CmdLineOpts      ( opt_SccProfilingOn, opt_InPackage )
35 import Type             ( Kind, mkArrowKind, liftedTypeKind )
36 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), IPName(..),
37                           NewOrData(..), StrictnessMark(..), Activation(..) )
38 import Panic
39
40 import GLAEXTS
41 import CStrings         ( CLabelString )
42 import FastString
43 import Maybes           ( orElse )
44 import Outputable
45
46 }
47
48 {-
49 -----------------------------------------------------------------------------
50 Conflicts: 21 shift/reduce, -=chak[4Feb2]
51
52 11 for abiguity in 'if x then y else z + 1'             [State 128]
53         (shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
54         8 because op might be: - ! * . `x` VARSYM CONSYM QVARSYM QCONSYM
55
56 1 for ambiguity in '{-# RULES "name" [ ... #-}          [State 210]
57         we don't know whether the '[' starts the activation or not: it
58         might be the start of the declaration with the activation being
59         empty.  --SDM 1/4/2002
60
61 1 for ambiguity in '{-# RULES "name" forall = ... #-}'  [State 412]
62         since 'forall' is a valid variable name, we don't know whether
63         to treat a forall on the input as the beginning of a quantifier
64         or the beginning of the rule itself.  Resolving to shift means
65         it's always treated as a quantifier, hence the above is disallowed.
66         This saves explicitly defining a grammar for the rule lhs that
67         doesn't include 'forall'.
68
69 1 for ambiguity in 'let ?x ...'                         [State 278]
70         the parser can't tell whether the ?x is the lhs of a normal binding or
71         an implicit binding.  Fortunately resolving as shift gives it the only
72         sensible meaning, namely the lhs of an implicit binding.
73
74
75 8 for ambiguity in 'e :: a `b` c'.  Does this mean      [States 238,267]
76         (e::a) `b` c, or 
77         (e :: (a `b` c))
78
79 6 for conflicts between `fdecl' and `fdeclDEPRECATED',  [States 402,403]
80   which are resolved correctly, and moreover, 
81   should go away when `fdeclDEPRECATED' is removed.
82
83 1 for ambiguity in 'if x then y else z :: T'
84         (shift parses as 'if x then y else (z :: T)', as per longest-parse rule)
85 1 for ambiguity in 'if x then y else z with ?x=3'
86         (shift parses as 'if x then y else (z with ?x=3)'
87 3 for ambiguity in 'case x of y :: a -> b'
88         (don't know whether to reduce 'a' as a btype or shift the '->'.
89          conclusion:  bogus expression anyway, doesn't matter)
90
91
92 -----------------------------------------------------------------------------
93 -}
94
95 %token
96  '_'            { ITunderscore }                -- Haskell keywords
97  'as'           { ITas }
98  'case'         { ITcase }      
99  'class'        { ITclass } 
100  'data'         { ITdata } 
101  'default'      { ITdefault }
102  'deriving'     { ITderiving }
103  'do'           { ITdo }
104  'else'         { ITelse }
105  'hiding'       { IThiding }
106  'if'           { ITif }
107  'import'       { ITimport }
108  'in'           { ITin }
109  'infix'        { ITinfix }
110  'infixl'       { ITinfixl }
111  'infixr'       { ITinfixr }
112  'instance'     { ITinstance }
113  'let'          { ITlet }
114  'module'       { ITmodule }
115  'newtype'      { ITnewtype }
116  'of'           { ITof }
117  'qualified'    { ITqualified }
118  'then'         { ITthen }
119  'type'         { ITtype }
120  'where'        { ITwhere }
121  '_scc_'        { ITscc }             -- ToDo: remove
122
123  'forall'       { ITforall }                    -- GHC extension keywords
124  'foreign'      { ITforeign }
125  'export'       { ITexport }
126  'label'        { ITlabel } 
127  'dynamic'      { ITdynamic }
128  'safe'         { ITsafe }
129  'threadsafe'   { ITthreadsafe }
130  'unsafe'       { ITunsafe }
131  'with'         { ITwith }
132  'stdcall'      { ITstdcallconv }
133  'ccall'        { ITccallconv }
134  'dotnet'       { ITdotnet }
135  '_ccall_'      { ITccall (False, False, PlayRisky) }
136  '_ccall_GC_'   { ITccall (False, False, PlaySafe False) }
137  '_casm_'       { ITccall (False, True,  PlayRisky) }
138  '_casm_GC_'    { ITccall (False, True,  PlaySafe False) }
139
140  '{-# SPECIALISE'  { ITspecialise_prag }
141  '{-# SOURCE'      { ITsource_prag }
142  '{-# INLINE'      { ITinline_prag }
143  '{-# NOINLINE'    { ITnoinline_prag }
144  '{-# RULES'       { ITrules_prag }
145  '{-# SCC'         { ITscc_prag }
146  '{-# DEPRECATED'  { ITdeprecated_prag }
147  '#-}'             { ITclose_prag }
148
149 {-
150  '__interface'  { ITinterface }                 -- interface keywords
151  '__export'     { IT__export }
152  '__instimport' { ITinstimport }
153  '__forall'     { IT__forall }
154  '__letrec'     { ITletrec }
155  '__coerce'     { ITcoerce }
156  '__depends'    { ITdepends }
157  '__inline'     { ITinline }
158  '__DEFAULT'    { ITdefaultbranch }
159  '__bot'        { ITbottom }
160  '__integer'    { ITinteger_lit }
161  '__float'      { ITfloat_lit }
162  '__rational'   { ITrational_lit }
163  '__addr'       { ITaddr_lit }
164  '__label'      { ITlabel_lit }
165  '__litlit'     { ITlit_lit }
166  '__string'     { ITstring_lit }
167  '__ccall'      { ITccall $$ }
168  '__scc'        { IT__scc }
169  '__sccC'       { ITsccAllCafs }
170
171  '__A'          { ITarity }
172  '__P'          { ITspecialise }
173  '__C'          { ITnocaf }
174  '__U'          { ITunfold }
175  '__S'          { ITstrict $$ }
176  '__M'          { ITcprinfo $$ }
177 -}
178
179  '..'           { ITdotdot }                    -- reserved symbols
180  '::'           { ITdcolon }
181  '='            { ITequal }
182  '\\'           { ITlam }
183  '|'            { ITvbar }
184  '<-'           { ITlarrow }
185  '->'           { ITrarrow }
186  '@'            { ITat }
187  '~'            { ITtilde }
188  '=>'           { ITdarrow }
189  '-'            { ITminus }
190  '!'            { ITbang }
191  '*'            { ITstar }
192  '.'            { ITdot }
193
194  '{'            { ITocurly }                    -- special symbols
195  '}'            { ITccurly }
196  '{|'           { ITocurlybar }
197  '|}'           { ITccurlybar }
198  vccurly        { ITvccurly } -- virtual close curly (from layout)
199  '['            { ITobrack }
200  ']'            { ITcbrack }
201  '[:'           { ITopabrack }
202  ':]'           { ITcpabrack }
203  '('            { IToparen }
204  ')'            { ITcparen }
205  '(#'           { IToubxparen }
206  '#)'           { ITcubxparen }
207  ';'            { ITsemi }
208  ','            { ITcomma }
209  '`'            { ITbackquote }
210
211  VARID          { ITvarid    $$ }               -- identifiers
212  CONID          { ITconid    $$ }
213  VARSYM         { ITvarsym   $$ }
214  CONSYM         { ITconsym   $$ }
215  QVARID         { ITqvarid   $$ }
216  QCONID         { ITqconid   $$ }
217  QVARSYM        { ITqvarsym  $$ }
218  QCONSYM        { ITqconsym  $$ }
219
220  IPDUPVARID     { ITdupipvarid   $$ }           -- GHC extension
221  IPSPLITVARID   { ITsplitipvarid $$ }           -- GHC extension
222
223  CHAR           { ITchar     $$ }
224  STRING         { ITstring   $$ }
225  INTEGER        { ITinteger  $$ }
226  RATIONAL       { ITrational $$ }
227
228  PRIMCHAR       { ITprimchar   $$ }
229  PRIMSTRING     { ITprimstring $$ }
230  PRIMINTEGER    { ITprimint    $$ }
231  PRIMFLOAT      { ITprimfloat  $$ }
232  PRIMDOUBLE     { ITprimdouble $$ }
233  CLITLIT        { ITlitlit     $$ }
234
235 %monad { P } { thenP } { returnP }
236 %lexer { lexer } { ITeof }
237 %name parseModule module
238 %name parseStmt   maybe_stmt
239 %name parseIdentifier  identifier
240 %name parseIface iface
241 %tokentype { Token }
242 %%
243
244 -----------------------------------------------------------------------------
245 -- Module Header
246
247 -- The place for module deprecation is really too restrictive, but if it
248 -- was allowed at its natural place just before 'module', we get an ugly
249 -- s/r conflict with the second alternative. Another solution would be the
250 -- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
251 -- either, and DEPRECATED is only expected to be used by people who really
252 -- know what they are doing. :-)
253
254 module  :: { RdrNameHsModule }
255         : srcloc 'module' modid maybemoddeprec maybeexports 'where' body 
256                 { HsModule $3 Nothing $5 (fst $7) (snd $7) $4 $1 }
257         | srcloc body
258                 { HsModule mAIN_Name Nothing Nothing (fst $2) (snd $2) Nothing $1 }
259
260 maybemoddeprec :: { Maybe DeprecTxt }
261         : '{-# DEPRECATED' STRING '#-}'         { Just $2 }
262         |  {- empty -}                          { Nothing }
263
264 body    :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
265         :  '{'            top '}'               { $2 }
266         |      layout_on  top close             { $2 }
267
268 top     :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
269         : importdecls                           { (reverse $1,[]) }
270         | importdecls ';' cvtopdecls            { (reverse $1,$3) }
271         | cvtopdecls                            { ([],$1) }
272
273 cvtopdecls :: { [RdrNameHsDecl] }
274         : topdecls                              { cvTopDecls (groupBindings $1)}
275
276 -----------------------------------------------------------------------------
277 -- Interfaces (.hi-boot files)
278
279 iface   :: { ParsedIface }
280         : 'module' modid 'where' ifacebody
281           {         ParsedIface {
282                         pi_mod     = $2,
283                         pi_pkg     = opt_InPackage,
284                         pi_vers    = 1,                 -- Module version
285                         pi_orphan  = False,
286                         pi_exports = (1,[($2,mkIfaceExports $4)]),
287                         pi_usages  = [],
288                         pi_fixity  = [],
289                         pi_insts   = [],
290                         pi_decls   = map (\x -> (1,x)) $4,
291                         pi_rules   = (1,[]),
292                         pi_deprecs = Nothing
293                     }
294            }
295
296 ifacebody :: { [RdrNameTyClDecl] }
297         :  '{'            ifacedecls '}'                { $2 }
298         |      layout_on  ifacedecls close              { $2 }
299
300 ifacedecls :: { [RdrNameTyClDecl] }
301         : ifacedecl ';' ifacedecls                      { $1 : $3 }
302         | ';' ifacedecls                                { $2 }
303         | ifacedecl                                     { [$1] }
304         | {- empty -}                                   { [] }
305
306 ifacedecl :: { RdrNameTyClDecl }
307         : srcloc 'data' tycl_hdr constrs 
308           { mkTyData DataType $3 (DataCons (reverse $4)) Nothing $1 }
309
310         | srcloc 'newtype' tycl_hdr '=' newconstr
311           { mkTyData NewType $3 (DataCons [$5]) Nothing $1 }
312
313         | srcloc 'class' tycl_hdr fds where
314                 { let 
315                         (binds,sigs) = cvMonoBindsAndSigs cvClassOpSig 
316                                         (groupBindings $5) 
317                    in
318                    mkClassDecl $3 $4 sigs (Just binds) $1 }
319
320         | srcloc 'type' tycon tv_bndrs '=' ctype        
321           { TySynonym $3 $4 $6 $1 }
322
323         | srcloc var '::' sigtype
324           { IfaceSig $2 $4 [] $1 }
325
326 -----------------------------------------------------------------------------
327 -- The Export List
328
329 maybeexports :: { Maybe [RdrNameIE] }
330         :  '(' exportlist ')'                   { Just $2 }
331         |  {- empty -}                          { Nothing }
332
333 exportlist :: { [RdrNameIE] }
334         :  exportlist ',' export                { $3 : $1 }
335         |  exportlist ','                       { $1 }
336         |  export                               { [$1]  }
337         |  {- empty -}                          { [] }
338
339    -- GHC extension: we allow things like [] and (,,,) to be exported
340 export  :: { RdrNameIE }
341         :  qvar                                 { IEVar $1 }
342         |  gtycon                               { IEThingAbs $1 }
343         |  gtycon '(' '..' ')'                  { IEThingAll $1 }
344         |  gtycon '(' ')'                       { IEThingWith $1 [] }
345         |  gtycon '(' qcnames ')'               { IEThingWith $1 (reverse $3) }
346         |  'module' modid                       { IEModuleContents $2 }
347
348 qcnames :: { [RdrName] }
349         :  qcnames ',' qcname                   { $3 : $1 }
350         |  qcname                               { [$1]  }
351
352 qcname  :: { RdrName }
353         :  qvar                                 { $1 }
354         |  gcon                                 { $1 }
355
356 -----------------------------------------------------------------------------
357 -- Import Declarations
358
359 -- import decls can be *empty*, or even just a string of semicolons
360 -- whereas topdecls must contain at least one topdecl.
361
362 importdecls :: { [RdrNameImportDecl] }
363         : importdecls ';' importdecl            { $3 : $1 }
364         | importdecls ';'                       { $1 }
365         | importdecl                            { [ $1 ] }
366         | {- empty -}                           { [] }
367
368 importdecl :: { RdrNameImportDecl }
369         : 'import' srcloc maybe_src optqualified modid maybeas maybeimpspec 
370                 { ImportDecl $5 $3 $4 $6 $7 $2 }
371
372 maybe_src :: { WhereFrom }
373         : '{-# SOURCE' '#-}'                    { ImportByUserSource }
374         | {- empty -}                           { ImportByUser }
375
376 optqualified :: { Bool }
377         : 'qualified'                           { True  }
378         | {- empty -}                           { False }
379
380 maybeas :: { Maybe ModuleName }
381         : 'as' modid                            { Just $2 }
382         | {- empty -}                           { Nothing }
383
384 maybeimpspec :: { Maybe (Bool, [RdrNameIE]) }
385         : impspec                               { Just $1 }
386         | {- empty -}                           { Nothing }
387
388 impspec :: { (Bool, [RdrNameIE]) }
389         :  '(' exportlist ')'                   { (False, reverse $2) }
390         |  'hiding' '(' exportlist ')'          { (True,  reverse $3) }
391
392 -----------------------------------------------------------------------------
393 -- Fixity Declarations
394
395 prec    :: { Int }
396         : {- empty -}                           { 9 }
397         | INTEGER                               {%  checkPrec $1 `thenP_`
398                                                     returnP (fromInteger $1) }
399
400 infix   :: { FixityDirection }
401         : 'infix'                               { InfixN  }
402         | 'infixl'                              { InfixL  }
403         | 'infixr'                              { InfixR }
404
405 ops     :: { [RdrName] }
406         : ops ',' op                            { $3 : $1 }
407         | op                                    { [$1] }
408
409 -----------------------------------------------------------------------------
410 -- Top-Level Declarations
411
412 topdecls :: { [RdrBinding] }
413         : topdecls ';' topdecl          { ($3 : $1) }
414         | topdecls ';'                  { $1 }
415         | topdecl                       { [$1] }
416
417 topdecl :: { RdrBinding }
418         : srcloc 'type' syn_hdr '=' ctype       
419                 -- Note ctype, not sigtype.
420                 -- We allow an explicit for-all but we don't insert one
421                 -- in   type Foo a = (b,b)
422                 -- Instead we just say b is out of scope
423                 { let (tc,tvs) = $3
424                   in RdrHsDecl (TyClD (TySynonym tc tvs $5 $1)) }
425
426
427         | srcloc 'data' tycl_hdr constrs deriving
428                 {% returnP (RdrHsDecl (TyClD
429                       (mkTyData DataType $3 (DataCons (reverse $4)) $5 $1))) }
430
431         | srcloc 'newtype' tycl_hdr '=' newconstr deriving
432                 {% returnP (RdrHsDecl (TyClD
433                       (mkTyData NewType $3 (DataCons [$5]) $6 $1))) }
434
435         | srcloc 'class' tycl_hdr fds where
436                 {% let 
437                         (binds,sigs) = cvMonoBindsAndSigs cvClassOpSig (groupBindings $5) 
438                    in
439                    returnP (RdrHsDecl (TyClD
440                       (mkClassDecl $3 $4 sigs (Just binds) $1))) }
441
442         | srcloc 'instance' inst_type where
443                 { let (binds,sigs) 
444                         = cvMonoBindsAndSigs cvInstDeclSig 
445                                 (groupBindings $4)
446                   in RdrHsDecl (InstD (InstDecl $3 binds sigs Nothing $1)) }
447
448         | srcloc 'default' '(' comma_types0 ')'         { RdrHsDecl (DefD (DefaultDecl $4 $1)) }
449         | 'foreign' fdecl                               { RdrHsDecl $2 }
450         | '{-# DEPRECATED' deprecations '#-}'           { $2 }
451         | '{-# RULES' rules '#-}'                       { $2 }
452         | decl                                          { $1 }
453
454 syn_hdr :: { (RdrName, [RdrNameHsTyVar]) }      -- We don't retain the syntax of an infix
455                                                 -- type synonym declaration. Oh well.
456         : tycon tv_bndrs                { ($1, $2) }
457         | tv_bndr tyconop tv_bndr       { ($2, [$1,$3]) }
458
459 -- tycl_hdr parses the header of a type or class decl,
460 -- which takes the form
461 --      T a b
462 --      Eq a => T a
463 --      (Eq a, Ord b) => T a b
464 -- Rather a lot of inlining here, else we get reduce/reduce errors
465 tycl_hdr :: { (RdrNameContext, RdrName, [RdrNameHsTyVar]) }
466         : context '=>' type             {% checkTyClHdr $3      `thenP` \ (tc,tvs) ->
467                                            returnP ($1, tc, tvs) }
468         | type                          {% checkTyClHdr $1      `thenP` \ (tc,tvs) ->
469                                            returnP ([], tc, tvs) }
470
471 {-
472         : '(' comma_types1 ')' '=>' gtycon tv_bndrs
473                 {% mapP checkPred $2    `thenP` \ cxt ->
474                   returnP (cxt, $5, $6) }
475
476         | '(' ')' '=>' gtycon tv_bndrs
477                 { ([], $4, $5) }
478
479           -- qtycon for the class below name would lead to many s/r conflicts
480           --   FIXME: does the renamer pick up all wrong forms and raise an
481           --          error 
482         | gtycon atypes1 '=>' gtycon atypes0    
483                 {% checkTyVars $5       `thenP` \ tvs ->
484                    returnP ([HsClassP $1 $2], $4, tvs) }
485
486         | gtycon  atypes0
487                 {% checkTyVars $2       `thenP` \ tvs ->
488                    returnP ([], $1, tvs) }
489                 -- We have to have qtycon in this production to avoid s/r
490                 -- conflicts with the previous one.  The renamer will complain
491                 -- if we use a qualified tycon.
492                 --
493                 -- Using a `gtycon' throughout.  This enables special syntax,
494                 -- such as "[]" for tycons as well as tycon ops in
495                 -- parentheses.  This is beyond H98, but used repeatedly in
496                 -- the Prelude modules.  (So, it would be a good idea to raise
497                 -- an error in the renamer if some non-H98 form is used and
498                 -- -fglasgow-exts is not given.)  -=chak 
499
500 atypes0 :: { [RdrNameHsType] }
501         : atypes1                       { $1 }
502         | {- empty -}                   { [] }
503
504 atypes1 :: { [RdrNameHsType] }
505         : atype                         { [$1] }
506         | atype atypes1                 { $1 : $2 }
507 -}
508
509 decls   :: { [RdrBinding] }
510         : decls ';' decl                { $3 : $1 }
511         | decls ';'                     { $1 }
512         | decl                          { [$1] }
513         | {- empty -}                   { [] }
514
515 decl    :: { RdrBinding }
516         : fixdecl                       { $1 }
517         | valdef                        { $1 }
518         | '{-# INLINE'   srcloc activation qvar '#-}'         { RdrSig (InlineSig True  $4 $3 $2) }
519         | '{-# NOINLINE' srcloc inverse_activation qvar '#-}' { RdrSig (InlineSig False $4 $3 $2) }
520         | '{-# SPECIALISE' srcloc qvar '::' sigtypes '#-}'
521                 { foldr1 RdrAndBindings 
522                     (map (\t -> RdrSig (SpecSig $3 t $2)) $5) }
523         | '{-# SPECIALISE' srcloc 'instance' inst_type '#-}'
524                 { RdrSig (SpecInstSig $4 $2) }
525
526 wherebinds :: { RdrNameHsBinds }
527         : where                 { cvBinds cvValSig (groupBindings $1) }
528
529 where   :: { [RdrBinding] }
530         : 'where' decllist              { $2 }
531         | {- empty -}                   { [] }
532
533 declbinds :: { RdrNameHsBinds }
534         : decllist                      { cvBinds cvValSig (groupBindings $1) }
535
536 decllist :: { [RdrBinding] }
537         : '{'            decls '}'      { $2 }
538         |     layout_on  decls close    { $2 }
539
540 letbinds :: { RdrNameHsExpr -> RdrNameHsExpr }
541         : decllist              { HsLet (cvBinds cvValSig (groupBindings $1)) }
542         | '{'            dbinds '}'     { \e -> HsWith e $2 False{-not with-} }
543         |     layout_on  dbinds close   { \e -> HsWith e $2 False{-not with-} }
544
545 fixdecl :: { RdrBinding }
546         : srcloc infix prec ops         { foldr1 RdrAndBindings
547                                             [ RdrSig (FixSig (FixitySig n 
548                                                             (Fixity $3 $2) $1))
549                                             | n <- $4 ] }
550
551 -----------------------------------------------------------------------------
552 -- Transformation Rules
553
554 rules   :: { RdrBinding }
555         :  rules ';' rule                       { $1 `RdrAndBindings` $3 }
556         |  rules ';'                            { $1 }
557         |  rule                                 { $1 }
558         |  {- empty -}                          { RdrNullBind }
559
560 rule    :: { RdrBinding }
561         : STRING activation rule_forall infixexp '=' srcloc exp
562              { RdrHsDecl (RuleD (HsRule $1 $2 $3 $4 $7 $6)) }
563
564 activation :: { Activation }           -- Omitted means AlwaysActive
565         : {- empty -}                           { AlwaysActive }
566         | explicit_activation                   { $1 }
567
568 inverse_activation :: { Activation }   -- Omitted means NeverActive
569         : {- empty -}                           { NeverActive }
570         | explicit_activation                   { $1 }
571
572 explicit_activation :: { Activation }  -- In brackets
573         : '[' INTEGER ']'                       { ActiveAfter  (fromInteger $2) }
574         | '[' '~' INTEGER ']'                   { ActiveBefore (fromInteger $3) }
575
576 rule_forall :: { [RdrNameRuleBndr] }
577         : 'forall' rule_var_list '.'            { $2 }
578         | {- empty -}                           { [] }
579
580 rule_var_list :: { [RdrNameRuleBndr] }
581         : rule_var                              { [$1] }
582         | rule_var rule_var_list                { $1 : $2 }
583
584 rule_var :: { RdrNameRuleBndr }
585         : varid                                 { RuleBndr $1 }
586         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
587
588 -----------------------------------------------------------------------------
589 -- Deprecations
590
591 deprecations :: { RdrBinding }
592         : deprecations ';' deprecation          { $1 `RdrAndBindings` $3 }
593         | deprecations ';'                      { $1 }
594         | deprecation                           { $1 }
595         | {- empty -}                           { RdrNullBind }
596
597 -- SUP: TEMPORARY HACK, not checking for `module Foo'
598 deprecation :: { RdrBinding }
599         : srcloc depreclist STRING
600                 { foldr RdrAndBindings RdrNullBind 
601                         [ RdrHsDecl (DeprecD (Deprecation n $3 $1)) | n <- $2 ] }
602
603
604 -----------------------------------------------------------------------------
605 -- Foreign import and export declarations
606
607 -- for the time being, the following accepts foreign declarations conforming
608 -- to the FFI Addendum, Version 1.0 as well as pre-standard declarations
609 --
610 -- * a flag indicates whether pre-standard declarations have been used and
611 --   triggers a deprecation warning further down the road
612 --
613 -- NB: The first two rules could be combined into one by replacing `safety1'
614 --     with `safety'.  However, the combined rule conflicts with the
615 --     DEPRECATED rules.
616 --
617 fdecl :: { RdrNameHsDecl }
618 fdecl : srcloc 'import' callconv safety1 fspec  {% mkImport $3 $4       $5 $1 }
619       | srcloc 'import' callconv         fspec  {% mkImport $3 (PlaySafe False) $4 $1 }
620       | srcloc 'export' callconv         fspec  {% mkExport $3          $4 $1 }
621         -- the following syntax is DEPRECATED
622       | srcloc fdecl1DEPRECATED                 { ForD ($2 True $1) }
623       | srcloc fdecl2DEPRECATED                 { $2 $1 }
624
625 fdecl1DEPRECATED :: { Bool -> SrcLoc -> ForeignDecl RdrName }
626 fdecl1DEPRECATED 
627   ----------- DEPRECATED label decls ------------
628   : 'label' ext_name varid '::' sigtype
629     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
630                                    (CLabel ($2 `orElse` mkExtName $3))) }
631
632   ----------- DEPRECATED ccall/stdcall decls ------------
633   --
634   -- NB: This business with the case expression below may seem overly
635   --     complicated, but it is necessary to avoid some conflicts.
636
637     -- DEPRECATED variant #1: lack of a calling convention specification
638     --                        (import) 
639   | 'import' {-no callconv-} ext_name safety varid_no_unsafe '::' sigtype
640     { let
641         target = StaticTarget ($2 `orElse` mkExtName $4)
642       in
643       ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
644                                    (CFunction target)) }
645
646     -- DEPRECATED variant #2: external name consists of two separate strings
647     --                        (module name and function name) (import)
648   | 'import' callconv STRING STRING safety varid_no_unsafe '::' sigtype
649     {% case $2 of
650          DNCall      -> parseError "Illegal format of .NET foreign import"
651          CCall cconv -> returnP $
652            let
653              imp = CFunction (StaticTarget $4)
654            in
655            ForeignImport $6 $8 (CImport cconv $5 nilFS nilFS imp) }
656
657     -- DEPRECATED variant #3: `unsafe' after entity
658   | 'import' callconv STRING 'unsafe' varid_no_unsafe '::' sigtype
659     {% case $2 of
660          DNCall      -> parseError "Illegal format of .NET foreign import"
661          CCall cconv -> returnP $
662            let
663              imp = CFunction (StaticTarget $3)
664            in
665            ForeignImport $5 $7 (CImport cconv PlayRisky nilFS nilFS imp) }
666
667     -- DEPRECATED variant #4: use of the special identifier `dynamic' without
668     --                        an explicit calling convention (import)
669   | 'import' {-no callconv-} 'dynamic' safety varid_no_unsafe '::' sigtype
670     { ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
671                                    (CFunction DynamicTarget)) }
672
673     -- DEPRECATED variant #5: use of the special identifier `dynamic' (import)
674   | 'import' callconv 'dynamic' safety varid_no_unsafe '::' sigtype
675     {% case $2 of
676          DNCall      -> parseError "Illegal format of .NET foreign import"
677          CCall cconv -> returnP $
678            ForeignImport $5 $7 (CImport cconv $4 nilFS nilFS 
679                                         (CFunction DynamicTarget)) }
680
681     -- DEPRECATED variant #6: lack of a calling convention specification
682     --                        (export) 
683   | 'export' {-no callconv-} ext_name varid '::' sigtype
684     { ForeignExport $3 $5 (CExport (CExportStatic ($2 `orElse` mkExtName $3) 
685                                    defaultCCallConv)) }
686
687     -- DEPRECATED variant #7: external name consists of two separate strings
688     --                        (module name and function name) (export)
689   | 'export' callconv STRING STRING varid '::' sigtype
690     {% case $2 of
691          DNCall      -> parseError "Illegal format of .NET foreign import"
692          CCall cconv -> returnP $
693            ForeignExport $5 $7 
694                          (CExport (CExportStatic $4 cconv)) }
695
696     -- DEPRECATED variant #8: use of the special identifier `dynamic' without
697     --                        an explicit calling convention (export)
698   | 'export' {-no callconv-} 'dynamic' varid '::' sigtype
699     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
700                                    CWrapper) }
701
702     -- DEPRECATED variant #9: use of the special identifier `dynamic' (export)
703   | 'export' callconv 'dynamic' varid '::' sigtype
704     {% case $2 of
705          DNCall      -> parseError "Illegal format of .NET foreign import"
706          CCall cconv -> returnP $
707            ForeignImport $4 $6 (CImport cconv (PlaySafe False) nilFS nilFS CWrapper) }
708
709   ----------- DEPRECATED .NET decls ------------
710   -- NB: removed the .NET call declaration, as it is entirely subsumed
711   --     by the new standard FFI declarations
712
713 fdecl2DEPRECATED :: { SrcLoc -> RdrNameHsDecl }
714 fdecl2DEPRECATED 
715   : 'import' 'dotnet' 'type' ext_name tycon
716           { \loc -> TyClD (ForeignType $5 $4 DNType loc) }
717     -- left this one unchanged for the moment as type imports are not
718     -- covered currently by the FFI standard -=chak
719
720
721 callconv :: { CallConv }
722           : 'stdcall'                   { CCall  StdCallConv }
723           | 'ccall'                     { CCall  CCallConv   }
724           | 'dotnet'                    { DNCall             }
725
726 safety :: { Safety }
727         : 'unsafe'                      { PlayRisky }
728         | 'safe'                        { PlaySafe False }
729         | 'threadsafe'                  { PlaySafe True  }
730         | {- empty -}                   { PlaySafe False }
731
732 safety1 :: { Safety }
733         : 'unsafe'                      { PlayRisky }
734         | 'safe'                        { PlaySafe  False }
735         | 'threadsafe'                  { PlaySafe  True }
736           -- only needed to avoid conflicts with the DEPRECATED rules
737
738 fspec :: { (FastString, RdrName, RdrNameHsType) }
739        : STRING varid '::' sigtype      { ($1      , $2, $4) }
740        |        varid '::' sigtype      { (nilFS, $1, $3) }
741          -- if the entity string is missing, it defaults to the empty string;
742          -- the meaning of an empty entity string depends on the calling
743          -- convention
744
745 -- DEPRECATED syntax
746 ext_name :: { Maybe CLabelString }
747         : STRING                { Just $1 }
748         | STRING STRING         { Just $2 }     -- Ignore "module name" for now
749         | {- empty -}           { Nothing }
750
751
752 -----------------------------------------------------------------------------
753 -- Type signatures
754
755 opt_sig :: { Maybe RdrNameHsType }
756         : {- empty -}                   { Nothing }
757         | '::' sigtype                  { Just $2 }
758
759 opt_asig :: { Maybe RdrNameHsType }
760         : {- empty -}                   { Nothing }
761         | '::' atype                    { Just $2 }
762
763 sigtypes :: { [RdrNameHsType] }
764         : sigtype                       { [ $1 ] }
765         | sigtypes ',' sigtype          { $3 : $1 }
766
767 sigtype :: { RdrNameHsType }
768         : ctype                         { mkHsForAllTy Nothing [] $1 }
769
770 sig_vars :: { [RdrName] }
771          : sig_vars ',' var             { $3 : $1 }
772          | var                          { [ $1 ] }
773
774 -----------------------------------------------------------------------------
775 -- Types
776
777 -- A ctype is a for-all type
778 ctype   :: { RdrNameHsType }
779         : 'forall' tv_bndrs '.' ctype   { mkHsForAllTy (Just $2) [] $4 }
780         | context '=>' type             { mkHsForAllTy Nothing   $1 $3 }
781         -- A type of form (context => type) is an *implicit* HsForAllTy
782         | type                          { $1 }
783
784 -- We parse a context as a btype so that we don't get reduce/reduce
785 -- errors in ctype.  The basic problem is that
786 --      (Eq a, Ord a)
787 -- looks so much like a tuple type.  We can't tell until we find the =>
788 context :: { RdrNameContext }
789         : btype                         {% checkContext $1 }
790
791 type :: { RdrNameHsType }
792         : ipvar '::' gentype            { mkHsIParamTy $1 $3 }
793         | gentype                       { $1 }
794
795 gentype :: { RdrNameHsType }
796         : btype                         { $1 }
797         | btype qtyconop gentype        { HsOpTy $1 (HsTyOp $2) $3 }
798         | btype '->' gentype            { HsOpTy $1 HsArrow $3 }
799
800 btype :: { RdrNameHsType }
801         : btype atype                   { HsAppTy $1 $2 }
802         | atype                         { $1 }
803
804 atype :: { RdrNameHsType }
805         : gtycon                        { HsTyVar $1 }
806         | tyvar                         { HsTyVar $1 }
807         | '(' type ',' comma_types1 ')' { HsTupleTy (mkHsTupCon tcName Boxed  ($2:$4)) ($2:$4) }
808         | '(#' comma_types1 '#)'        { HsTupleTy (mkHsTupCon tcName Unboxed     $2) $2      }
809         | '[' type ']'                  { HsListTy  $2 }
810         | '[:' type ':]'                { HsPArrTy  $2 }
811         | '(' ctype ')'                 { HsParTy   $2 }
812         | '(' ctype '::' kind ')'       { HsKindSig $2 $4 }
813 -- Generics
814         | INTEGER                       { HsNumTy $1 }
815
816 -- An inst_type is what occurs in the head of an instance decl
817 --      e.g.  (Foo a, Gaz b) => Wibble a b
818 -- It's kept as a single type, with a MonoDictTy at the right
819 -- hand corner, for convenience.
820 inst_type :: { RdrNameHsType }
821         : ctype                         {% checkInstType $1 }
822
823 comma_types0  :: { [RdrNameHsType] }
824         : comma_types1                  { $1 }
825         | {- empty -}                   { [] }
826
827 comma_types1    :: { [RdrNameHsType] }
828         : type                          { [$1] }
829         | type  ',' comma_types1        { $1 : $3 }
830
831 tv_bndrs :: { [RdrNameHsTyVar] }
832          : tv_bndr tv_bndrs             { $1 : $2 }
833          | {- empty -}                  { [] }
834
835 tv_bndr :: { RdrNameHsTyVar }
836         : tyvar                         { UserTyVar $1 }
837         | '(' tyvar '::' kind ')'       { IfaceTyVar $2 $4 }
838
839 fds :: { [([RdrName], [RdrName])] }
840         : {- empty -}                   { [] }
841         | '|' fds1                      { reverse $2 }
842
843 fds1 :: { [([RdrName], [RdrName])] }
844         : fds1 ',' fd                   { $3 : $1 }
845         | fd                            { [$1] }
846
847 fd :: { ([RdrName], [RdrName]) }
848         : varids0 '->' varids0          { (reverse $1, reverse $3) }
849
850 varids0 :: { [RdrName] }
851         : {- empty -}                   { [] }
852         | varids0 tyvar                 { $2 : $1 }
853
854 -----------------------------------------------------------------------------
855 -- Kinds
856
857 kind    :: { Kind }
858         : akind                 { $1 }
859         | akind '->' kind       { mkArrowKind $1 $3 }
860
861 akind   :: { Kind }
862         : '*'                   { liftedTypeKind }
863         | '(' kind ')'          { $2 }
864
865
866 -----------------------------------------------------------------------------
867 -- Datatype declarations
868
869 newconstr :: { RdrNameConDecl }
870         : srcloc conid atype    { mkConDecl $2 [] [] (VanillaCon [unbangedType $3]) $1 }
871         | srcloc conid '{' var '::' ctype '}'
872                                 { mkConDecl $2 [] [] (RecCon [([$4], unbangedType $6)]) $1 }
873
874 constrs :: { [RdrNameConDecl] }
875         : {- empty; a GHC extension -}  { [] }
876         | '=' constrs1                  { $2 }
877
878 constrs1 :: { [RdrNameConDecl] }
879         : constrs1 '|' constr           { $3 : $1 }
880         | constr                        { [$1] }
881
882 constr :: { RdrNameConDecl }
883         : srcloc forall context '=>' constr_stuff
884                 { mkConDecl (fst $5) $2 $3 (snd $5) $1 }
885         | srcloc forall constr_stuff
886                 { mkConDecl (fst $3) $2 [] (snd $3) $1 }
887
888 forall :: { [RdrNameHsTyVar] }
889         : 'forall' tv_bndrs '.'         { $2 }
890         | {- empty -}                   { [] }
891
892 constr_stuff :: { (RdrName, RdrNameConDetails) }
893         : btype                         {% mkVanillaCon $1 []               }
894         | btype '!' atype satypes       {% mkVanillaCon $1 (BangType MarkedUserStrict $3 : $4) }
895         | gtycon '{' '}'                {% mkRecCon $1 [] }
896         | gtycon '{' fielddecls '}'     {% mkRecCon $1 $3 }
897         | sbtype conop sbtype           { ($2, InfixCon $1 $3) }
898
899 satypes :: { [RdrNameBangType] }
900         : atype satypes                 { unbangedType $1 : $2 }
901         | '!' atype satypes             { BangType MarkedUserStrict $2 : $3 }
902         | {- empty -}                   { [] }
903
904 sbtype :: { RdrNameBangType }
905         : btype                         { unbangedType $1 }
906         | '!' atype                     { BangType MarkedUserStrict $2 }
907
908 fielddecls :: { [([RdrName],RdrNameBangType)] }
909         : fielddecl ',' fielddecls      { $1 : $3 }
910         | fielddecl                     { [$1] }
911
912 fielddecl :: { ([RdrName],RdrNameBangType) }
913         : sig_vars '::' stype           { (reverse $1, $3) }
914
915 stype :: { RdrNameBangType }
916         : ctype                         { unbangedType $1 }
917         | '!' atype                     { BangType MarkedUserStrict $2 }
918
919 deriving :: { Maybe RdrNameContext }
920         : {- empty -}                   { Nothing }
921         | 'deriving' context            { Just $2 }
922              -- Glasgow extension: allow partial 
923              -- applications in derivings
924
925 -----------------------------------------------------------------------------
926 -- Value definitions
927
928 {- There's an awkward overlap with a type signature.  Consider
929         f :: Int -> Int = ...rhs...
930    Then we can't tell whether it's a type signature or a value
931    definition with a result signature until we see the '='.
932    So we have to inline enough to postpone reductions until we know.
933 -}
934
935 {-
936   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
937   instead of qvar, we get another shift/reduce-conflict. Consider the
938   following programs:
939   
940      { (^^) :: Int->Int ; }          Type signature; only var allowed
941
942      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
943                                      qvar allowed (because of instance decls)
944   
945   We can't tell whether to reduce var to qvar until after we've read the signatures.
946 -}
947
948 valdef :: { RdrBinding }
949         : infixexp srcloc opt_sig rhs           {% (checkValDef $1 $3 $4 $2) }
950         | infixexp srcloc '::' sigtype          {% (checkValSig $1 $4 $2) }
951         | var ',' sig_vars srcloc '::' sigtype  { foldr1 RdrAndBindings 
952                                                          [ RdrSig (Sig n $6 $4) | n <- $1:$3 ]
953                                                 }
954
955
956 rhs     :: { RdrNameGRHSs }
957         : '=' srcloc exp wherebinds     { (GRHSs (unguardedRHS $3 $2) $4 placeHolderType)}
958         | gdrhs wherebinds              { GRHSs (reverse $1) $2 placeHolderType }
959
960 gdrhs :: { [RdrNameGRHS] }
961         : gdrhs gdrh                    { $2 : $1 }
962         | gdrh                          { [$1] }
963
964 gdrh :: { RdrNameGRHS }
965         : '|' srcloc quals '=' exp      { GRHS (reverse (ResultStmt $5 $2 : $3)) $2 }
966
967 -----------------------------------------------------------------------------
968 -- Expressions
969
970 exp   :: { RdrNameHsExpr }
971         : infixexp '::' sigtype         { (ExprWithTySig $1 $3) }
972         | infixexp 'with' dbinding      { HsWith $1 $3 True{-not a let-} }
973         | infixexp                      { $1 }
974
975 infixexp :: { RdrNameHsExpr }
976         : exp10                         { $1 }
977         | infixexp qop exp10            { (OpApp $1 (HsVar $2) 
978                                                 (panic "fixity") $3 )}
979
980 exp10 :: { RdrNameHsExpr }
981         : '\\' srcloc aexp aexps opt_asig '->' srcloc exp       
982                         {% checkPatterns $2 ($3 : reverse $4) `thenP` \ ps -> 
983                            returnP (HsLam (Match ps $5 
984                                             (GRHSs (unguardedRHS $8 $7) 
985                                                    EmptyBinds placeHolderType))) }
986         | 'let' letbinds 'in' exp               { $2 $4 }
987         | 'if' srcloc exp 'then' exp 'else' exp { HsIf $3 $5 $7 $2 }
988         | 'case' srcloc exp 'of' altslist       { HsCase $3 $5 $2 }
989         | '-' fexp                              { mkHsNegApp $2 }
990         | srcloc 'do' stmtlist                  {% checkDo $3  `thenP` \ stmts ->
991                                                    returnP (mkHsDo DoExpr stmts $1) }
992
993         | '_ccall_'    ccallid aexps0           { HsCCall $2 $3 PlayRisky False placeHolderType }
994         | '_ccall_GC_' ccallid aexps0           { HsCCall $2 $3 (PlaySafe False) False placeHolderType }
995         | '_casm_'     CLITLIT aexps0           { HsCCall $2 $3 PlayRisky True  placeHolderType }
996         | '_casm_GC_'  CLITLIT aexps0           { HsCCall $2 $3 (PlaySafe False) True  placeHolderType }
997
998         | scc_annot exp                         { if opt_SccProfilingOn
999                                                         then HsSCC $1 $2
1000                                                         else HsPar $2 }
1001
1002         | fexp                                  { $1 }
1003
1004 scc_annot :: { FastString }
1005         : '_scc_' STRING                        { $2 }
1006         | '{-# SCC' STRING '#-}'                { $2 }
1007
1008 ccallid :: { FastString }
1009         :  VARID                                { $1 }
1010         |  CONID                                { $1 }
1011
1012 fexp    :: { RdrNameHsExpr }
1013         : fexp aexp                             { (HsApp $1 $2) }
1014         | aexp                                  { $1 }
1015
1016 aexps0  :: { [RdrNameHsExpr] }
1017         : aexps                                 { reverse $1 }
1018
1019 aexps   :: { [RdrNameHsExpr] }
1020         : aexps aexp                            { $2 : $1 }
1021         | {- empty -}                           { [] }
1022
1023 aexp    :: { RdrNameHsExpr }
1024         : qvar '@' aexp                 { EAsPat $1 $3 }
1025         | '~' aexp                      { ELazyPat $2 }
1026         | aexp1                         { $1 }
1027
1028 aexp1   :: { RdrNameHsExpr }
1029         : aexp1 '{' fbinds '}'                  {% (mkRecConstrOrUpdate $1 
1030                                                         (reverse $3)) }
1031         | aexp2                                 { $1 }
1032         | var_or_con '{|' gentype '|}'          { HsApp $1 (HsType $3) }
1033
1034
1035 var_or_con :: { RdrNameHsExpr }
1036         : qvar                          { HsVar $1 }
1037         | gcon                          { HsVar $1 }
1038
1039 aexp2   :: { RdrNameHsExpr }
1040         : ipvar                         { HsIPVar $1 }
1041         | var_or_con                    { $1 }
1042         | literal                       { HsLit $1 }
1043         | INTEGER                       { HsOverLit (mkHsIntegral   $1) }
1044         | RATIONAL                      { HsOverLit (mkHsFractional $1) }
1045         | '(' exp ')'                   { HsPar $2 }
1046         | '(' exp ',' texps ')'         { ExplicitTuple ($2 : reverse $4) Boxed}
1047         | '(#' texps '#)'               { ExplicitTuple (reverse $2)      Unboxed }
1048         | '[' list ']'                  { $2 }
1049         | '[:' parr ':]'                { $2 }
1050         | '(' infixexp qop ')'          { (SectionL $2 (HsVar $3))  }
1051         | '(' qopm infixexp ')'         { (SectionR $2 $3) }
1052         | '_'                           { EWildPat }
1053
1054 texps :: { [RdrNameHsExpr] }
1055         : texps ',' exp                 { $3 : $1 }
1056         | exp                           { [$1] }
1057
1058
1059 -----------------------------------------------------------------------------
1060 -- List expressions
1061
1062 -- The rules below are little bit contorted to keep lexps left-recursive while
1063 -- avoiding another shift/reduce-conflict.
1064
1065 list :: { RdrNameHsExpr }
1066         : exp                           { ExplicitList placeHolderType [$1] }
1067         | lexps                         { ExplicitList placeHolderType (reverse $1) }
1068         | exp '..'                      { ArithSeqIn (From $1) }
1069         | exp ',' exp '..'              { ArithSeqIn (FromThen $1 $3) }
1070         | exp '..' exp                  { ArithSeqIn (FromTo $1 $3) }
1071         | exp ',' exp '..' exp          { ArithSeqIn (FromThenTo $1 $3 $5) }
1072         | exp srcloc pquals             {% let { body [qs] = qs;
1073                                                  body  qss = [ParStmt (map reverse qss)] }
1074                                            in
1075                                            returnP ( mkHsDo ListComp
1076                                                             (reverse (ResultStmt $1 $2 : body $3))
1077                                                             $2
1078                                                   )
1079                                         }
1080
1081 lexps :: { [RdrNameHsExpr] }
1082         : lexps ',' exp                 { $3 : $1 }
1083         | exp ',' exp                   { [$3,$1] }
1084
1085 -----------------------------------------------------------------------------
1086 -- List Comprehensions
1087
1088 pquals :: { [[RdrNameStmt]] }
1089         : pquals '|' quals              { $3 : $1 }
1090         | '|' quals                     { [$2] }
1091
1092 quals :: { [RdrNameStmt] }
1093         : quals ',' stmt                { $3 : $1 }
1094         | stmt                          { [$1] }
1095
1096 -----------------------------------------------------------------------------
1097 -- Parallel array expressions
1098
1099 -- The rules below are little bit contorted; see the list case for details.
1100 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1101 -- Moreover, we allow explicit arrays with no element (represented by the nil
1102 -- constructor in the list case).
1103
1104 parr :: { RdrNameHsExpr }
1105         :                               { ExplicitPArr placeHolderType [] }
1106         | exp                           { ExplicitPArr placeHolderType [$1] }
1107         | lexps                         { ExplicitPArr placeHolderType 
1108                                                        (reverse $1) }
1109         | exp '..' exp                  { PArrSeqIn (FromTo $1 $3) }
1110         | exp ',' exp '..' exp          { PArrSeqIn (FromThenTo $1 $3 $5) }
1111         | exp srcloc pquals             {% let {
1112                                              body [qs] = qs;
1113                                              body  qss = [ParStmt 
1114                                                            (map reverse qss)]}
1115                                            in
1116                                            returnP $ 
1117                                              mkHsDo PArrComp 
1118                                                     (reverse (ResultStmt $1 $2 
1119                                                              : body $3))
1120                                                     $2
1121                                         }
1122
1123 -- We are reusing `lexps' and `pquals' from the list case.
1124
1125 -----------------------------------------------------------------------------
1126 -- Case alternatives
1127
1128 altslist :: { [RdrNameMatch] }
1129         : '{'            alts '}'       { reverse $2 }
1130         |     layout_on  alts  close    { reverse $2 }
1131
1132 alts    :: { [RdrNameMatch] }
1133         : alts1                         { $1 }
1134         | ';' alts                      { $2 }
1135
1136 alts1   :: { [RdrNameMatch] }
1137         : alts1 ';' alt                 { $3 : $1 }
1138         | alts1 ';'                     { $1 }
1139         | alt                           { [$1] }
1140
1141 alt     :: { RdrNameMatch }
1142         : srcloc infixexp opt_sig ralt wherebinds
1143                                         {% (checkPattern $1 $2 `thenP` \p ->
1144                                            returnP (Match [p] $3
1145                                                      (GRHSs $4 $5 placeHolderType))  )}
1146
1147 ralt :: { [RdrNameGRHS] }
1148         : '->' srcloc exp               { [GRHS [ResultStmt $3 $2] $2] }
1149         | gdpats                        { reverse $1 }
1150
1151 gdpats :: { [RdrNameGRHS] }
1152         : gdpats gdpat                  { $2 : $1 }
1153         | gdpat                         { [$1] }
1154
1155 gdpat   :: { RdrNameGRHS }
1156         : srcloc '|' quals '->' exp     { GRHS (reverse (ResultStmt $5 $1:$3)) $1}
1157
1158 -----------------------------------------------------------------------------
1159 -- Statement sequences
1160
1161 stmtlist :: { [RdrNameStmt] }
1162         : '{'                   stmts '}'       { $2 }
1163         |     layout_on_for_do  stmts close     { $2 }
1164
1165 --      do { ;; s ; s ; ; s ;; }
1166 -- The last Stmt should be a ResultStmt, but that's hard to enforce
1167 -- here, because we need too much lookahead if we see do { e ; }
1168 -- So we use ExprStmts throughout, and switch the last one over
1169 -- in ParseUtils.checkDo instead
1170 stmts :: { [RdrNameStmt] }
1171         : stmt stmts_help               { $1 : $2 }
1172         | ';' stmts                     { $2 }
1173         | {- empty -}                   { [] }
1174
1175 stmts_help :: { [RdrNameStmt] }
1176         : ';' stmts                     { $2 }
1177         | {- empty -}                   { [] }
1178
1179 -- For typing stmts at the GHCi prompt, where 
1180 -- the input may consist of just comments.
1181 maybe_stmt :: { Maybe RdrNameStmt }
1182         : stmt                          { Just $1 }
1183         | {- nothing -}                 { Nothing }
1184
1185 stmt  :: { RdrNameStmt }
1186         : srcloc infixexp '<-' exp      {% checkPattern $1 $2 `thenP` \p ->
1187                                            returnP (BindStmt p $4 $1) }
1188         | srcloc exp                    { ExprStmt $2 placeHolderType $1 }
1189         | srcloc 'let' declbinds        { LetStmt $3 }
1190
1191 -----------------------------------------------------------------------------
1192 -- Record Field Update/Construction
1193
1194 fbinds  :: { RdrNameHsRecordBinds }
1195         : fbinds ',' fbind              { $3 : $1 }
1196         | fbinds ','                    { $1 }
1197         | fbind                         { [$1] }
1198         | {- empty -}                   { [] }
1199
1200 fbind   :: { (RdrName, RdrNameHsExpr, Bool) }
1201         : qvar '=' exp                  { ($1,$3,False) }
1202
1203 -----------------------------------------------------------------------------
1204 -- Implicit Parameter Bindings
1205
1206 dbinding :: { [(IPName RdrName, RdrNameHsExpr)] }
1207         : '{' dbinds '}'                { $2 }
1208         | layout_on dbinds close        { $2 }
1209
1210 dbinds  :: { [(IPName RdrName, RdrNameHsExpr)] }
1211         : dbinds ';' dbind              { $3 : $1 }
1212         | dbinds ';'                    { $1 }
1213         | dbind                         { [$1] }
1214 --      | {- empty -}                   { [] }
1215
1216 dbind   :: { (IPName RdrName, RdrNameHsExpr) }
1217 dbind   : ipvar '=' exp                 { ($1, $3) }
1218
1219 -----------------------------------------------------------------------------
1220 -- Variables, Constructors and Operators.
1221
1222 identifier :: { RdrName }
1223         : qvar                          { $1 }
1224         | gcon                          { $1 }
1225         | qop                           { $1 }
1226
1227 depreclist :: { [RdrName] }
1228 depreclist : deprec_var                 { [$1] }
1229            | deprec_var ',' depreclist  { $1 : $3 }
1230
1231 deprec_var :: { RdrName }
1232 deprec_var : var                        { $1 }
1233            | tycon                      { $1 }
1234
1235 gtycon  :: { RdrName }
1236         : qtycon                        { $1 }
1237         | '(' qtyconop ')'              { $2 }
1238         | '(' ')'                       { unitTyCon_RDR }
1239         | '(' '->' ')'                  { funTyCon_RDR }
1240         | '[' ']'                       { listTyCon_RDR }
1241         | '[:' ':]'                     { parrTyCon_RDR }
1242         | '(' commas ')'                { tupleTyCon_RDR $2 }
1243
1244 gcon    :: { RdrName }  -- Data constructor namespace
1245         : '(' ')'               { unitCon_RDR }
1246         | '[' ']'               { nilCon_RDR }
1247         | '(' commas ')'        { tupleCon_RDR $2 }
1248         | qcon                  { $1 }
1249 -- the case of '[:' ':]' is part of the production `parr'
1250
1251 var     :: { RdrName }
1252         : varid                 { $1 }
1253         | '(' varsym ')'        { $2 }
1254
1255 qvar    :: { RdrName }
1256         : qvarid                { $1 }
1257         | '(' varsym ')'        { $2 }
1258         | '(' qvarsym1 ')'      { $2 }
1259 -- We've inlined qvarsym here so that the decision about
1260 -- whether it's a qvar or a var can be postponed until
1261 -- *after* we see the close paren.
1262
1263 ipvar   :: { IPName RdrName }
1264         : IPDUPVARID            { Dupable (mkUnqual varName $1) }
1265         | IPSPLITVARID          { Linear  (mkUnqual varName $1) }
1266
1267 qcon    :: { RdrName }
1268         : qconid                { $1 }
1269         | '(' qconsym ')'       { $2 }
1270
1271 varop   :: { RdrName }
1272         : varsym                { $1 }
1273         | '`' varid '`'         { $2 }
1274
1275 qvarop :: { RdrName }
1276         : qvarsym               { $1 }
1277         | '`' qvarid '`'        { $2 }
1278
1279 qvaropm :: { RdrName }
1280         : qvarsym_no_minus      { $1 }
1281         | '`' qvarid '`'        { $2 }
1282
1283 conop :: { RdrName }
1284         : consym                { $1 }  
1285         | '`' conid '`'         { $2 }
1286
1287 qconop :: { RdrName }
1288         : qconsym               { $1 }
1289         | '`' qconid '`'        { $2 }
1290
1291 -----------------------------------------------------------------------------
1292 -- Type constructors
1293
1294 tycon   :: { RdrName }  -- Unqualified
1295         : CONID                 { mkUnqual tcClsName $1 }
1296
1297 tyconop :: { RdrName }  -- Unqualified
1298         : CONSYM                { mkUnqual tcClsName $1 }
1299         | '`' tyvar '`'         { $2 }
1300         | '`' tycon '`'         { $2 }
1301
1302 qtycon :: { RdrName }   -- Qualified or unqualified
1303         : QCONID                { mkQual tcClsName $1 }
1304         | tycon                 { $1 }
1305
1306 qtyconop :: { RdrName } -- Qualified or unqualified
1307           : QCONSYM             { mkQual tcClsName $1 }
1308           | '`' QCONID '`'      { mkQual tcClsName $2 }
1309           | tyconop             { $1 }
1310
1311 -----------------------------------------------------------------------------
1312 -- Any operator
1313
1314 op      :: { RdrName }   -- used in infix decls
1315         : varop                 { $1 }
1316         | conop                 { $1 }
1317
1318 qop     :: { RdrName {-HsExpr-} }   -- used in sections
1319         : qvarop                { $1 }
1320         | qconop                { $1 }
1321
1322 qopm    :: { RdrNameHsExpr }   -- used in sections
1323         : qvaropm               { HsVar $1 }
1324         | qconop                { HsVar $1 }
1325
1326 -----------------------------------------------------------------------------
1327 -- VarIds
1328
1329 qvarid :: { RdrName }
1330         : varid                 { $1 }
1331         | QVARID                { mkQual varName $1 }
1332
1333 varid :: { RdrName }
1334         : varid_no_unsafe       { $1 }
1335         | 'unsafe'              { mkUnqual varName FSLIT("unsafe") }
1336         | 'safe'                { mkUnqual varName FSLIT("safe") }
1337         | 'threadsafe'          { mkUnqual varName FSLIT("threadsafe") }
1338
1339 varid_no_unsafe :: { RdrName }
1340         : VARID                 { mkUnqual varName $1 }
1341         | special_id            { mkUnqual varName $1 }
1342         | 'forall'              { mkUnqual varName FSLIT("forall") }
1343
1344 tyvar   :: { RdrName }
1345         : VARID                 { mkUnqual tvName $1 }
1346         | special_id            { mkUnqual tvName $1 }
1347         | 'unsafe'              { mkUnqual tvName FSLIT("unsafe") }
1348         | 'safe'                { mkUnqual tvName FSLIT("safe") }
1349         | 'threadsafe'          { mkUnqual tvName FSLIT("threadsafe") }
1350
1351 -- These special_ids are treated as keywords in various places, 
1352 -- but as ordinary ids elsewhere.   'special_id' collects all these
1353 -- except 'unsafe' and 'forall' whose treatment differs depending on context
1354 special_id :: { UserFS }
1355 special_id
1356         : 'as'                  { FSLIT("as") }
1357         | 'qualified'           { FSLIT("qualified") }
1358         | 'hiding'              { FSLIT("hiding") }
1359         | 'export'              { FSLIT("export") }
1360         | 'label'               { FSLIT("label")  }
1361         | 'dynamic'             { FSLIT("dynamic") }
1362         | 'stdcall'             { FSLIT("stdcall") }
1363         | 'ccall'               { FSLIT("ccall") }
1364
1365 -----------------------------------------------------------------------------
1366 -- Variables 
1367
1368 qvarsym :: { RdrName }
1369         : varsym                { $1 }
1370         | qvarsym1              { $1 }
1371
1372 qvarsym_no_minus :: { RdrName }
1373         : varsym_no_minus       { $1 }
1374         | qvarsym1              { $1 }
1375
1376 qvarsym1 :: { RdrName }
1377 qvarsym1 : QVARSYM              { mkQual varName $1 }
1378
1379 varsym :: { RdrName }
1380         : varsym_no_minus       { $1 }
1381         | '-'                   { mkUnqual varName FSLIT("-") }
1382
1383 varsym_no_minus :: { RdrName } -- varsym not including '-'
1384         : VARSYM                { mkUnqual varName $1 }
1385         | special_sym           { mkUnqual varName $1 }
1386
1387
1388 -- See comments with special_id
1389 special_sym :: { UserFS }
1390 special_sym : '!'       { FSLIT("!") }
1391             | '.'       { FSLIT(".") }
1392             | '*'       { FSLIT("*") }
1393
1394 -----------------------------------------------------------------------------
1395 -- Data constructors
1396
1397 qconid :: { RdrName }   -- Qualified or unqualifiedb
1398         : conid                 { $1 }
1399         | QCONID                { mkQual dataName $1 }
1400
1401 conid   :: { RdrName }
1402         : CONID                 { mkUnqual dataName $1 }
1403
1404 qconsym :: { RdrName }  -- Qualified or unqualified
1405         : consym                { $1 }
1406         | QCONSYM               { mkQual dataName $1 }
1407
1408 consym :: { RdrName }
1409         : CONSYM                { mkUnqual dataName $1 }
1410
1411
1412 -----------------------------------------------------------------------------
1413 -- Literals
1414
1415 literal :: { HsLit }
1416         : CHAR                  { HsChar       $1 }
1417         | STRING                { HsString     $1 }
1418         | PRIMINTEGER           { HsIntPrim    $1 }
1419         | PRIMCHAR              { HsCharPrim   $1 }
1420         | PRIMSTRING            { HsStringPrim $1 }
1421         | PRIMFLOAT             { HsFloatPrim  $1 }
1422         | PRIMDOUBLE            { HsDoublePrim $1 }
1423         | CLITLIT               { HsLitLit     $1 placeHolderType }
1424
1425 srcloc :: { SrcLoc }    :       {% getSrcLocP }
1426  
1427 -----------------------------------------------------------------------------
1428 -- Layout
1429
1430 close :: { () }
1431         : vccurly               { () } -- context popped in lexer.
1432         | error                 {% popContext }
1433
1434 layout_on         :: { () }     : {% layoutOn True{-strict-} }
1435 layout_on_for_do  :: { () }     : {% layoutOn False }
1436
1437 -----------------------------------------------------------------------------
1438 -- Miscellaneous (mostly renamings)
1439
1440 modid   :: { ModuleName }
1441         : CONID                 { mkModuleNameFS $1 }
1442         | QCONID                { mkModuleNameFS
1443                                    (mkFastString
1444                                      (unpackFS (fst $1) ++ 
1445                                         '.':unpackFS (snd $1)))
1446                                 }
1447
1448 commas :: { Int }
1449         : commas ','                    { $1 + 1 }
1450         | ','                           { 2 }
1451
1452 -----------------------------------------------------------------------------
1453
1454 {
1455 happyError :: P a
1456 happyError buf PState{ loc = loc } = PFailed (srcParseErr buf loc)
1457 }