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