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