[project @ 2001-04-14 22:24:24 by qrczak]
[ghc-hetmet.git] / ghc / compiler / parser / Parser.y
1 {-
2 -----------------------------------------------------------------------------
3 $Id: Parser.y,v 1.57 2001/04/14 22:24:24 qrczak 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 ) where
13
14 import HsSyn
15 import HsTypes          ( mkHsTupCon )
16
17 import RdrHsSyn
18 import Lex
19 import ParseUtil
20 import RdrName
21 import PrelNames        ( mAIN_Name, unitTyCon_RDR, funTyCon_RDR, listTyCon_RDR,
22                           tupleTyCon_RDR, unitCon_RDR, nilCon_RDR, tupleCon_RDR
23                         )
24 import OccName          ( UserFS, varName, tcName, dataName, tcClsName, tvName )
25 import SrcLoc           ( SrcLoc )
26 import Module
27 import CallConv
28 import CmdLineOpts      ( opt_SccProfilingOn )
29 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), NewOrData(..) )
30 import Panic
31
32 import GlaExts
33 import FastString       ( tailFS )
34 import Outputable
35
36 #include "HsVersions.h"
37 }
38
39 {-
40 -----------------------------------------------------------------------------
41 Conflicts: 14 shift/reduce
42         (note: it's currently 21 -- JRL, 31/1/2000)
43
44 8 for abiguity in 'if x then y else z + 1'
45         (shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
46 1 for ambiguity in 'if x then y else z :: T'
47         (shift parses as 'if x then y else (z :: T)', as per longest-parse rule)
48 3 for ambiguity in 'case x of y :: a -> b'
49         (don't know whether to reduce 'a' as a btype or shift the '->'.
50          conclusion:  bogus expression anyway, doesn't matter)
51
52 1 for ambiguity in '{-# RULES "name" forall = ... #-}' 
53         since 'forall' is a valid variable name, we don't know whether
54         to treat a forall on the input as the beginning of a quantifier
55         or the beginning of the rule itself.  Resolving to shift means
56         it's always treated as a quantifier, hence the above is disallowed.
57         This saves explicitly defining a grammar for the rule lhs that
58         doesn't include 'forall'.
59
60 1 for ambiguity in 'x @ Rec{..}'.  
61         Only sensible parse is 'x @ (Rec{..})', which is what resolving
62         to shift gives us.
63
64 -----------------------------------------------------------------------------
65 -}
66
67 %token
68  '_'            { ITunderscore }                -- Haskell keywords
69  'as'           { ITas }
70  'case'         { ITcase }      
71  'class'        { ITclass } 
72  'data'         { ITdata } 
73  'default'      { ITdefault }
74  'deriving'     { ITderiving }
75  'do'           { ITdo }
76  'else'         { ITelse }
77  'hiding'       { IThiding }
78  'if'           { ITif }
79  'import'       { ITimport }
80  'in'           { ITin }
81  'infix'        { ITinfix }
82  'infixl'       { ITinfixl }
83  'infixr'       { ITinfixr }
84  'instance'     { ITinstance }
85  'let'          { ITlet }
86  'module'       { ITmodule }
87  'newtype'      { ITnewtype }
88  'of'           { ITof }
89  'qualified'    { ITqualified }
90  'then'         { ITthen }
91  'type'         { ITtype }
92  'where'        { ITwhere }
93  '_scc_'        { ITscc }             -- ToDo: remove
94
95  'forall'       { ITforall }                    -- GHC extension keywords
96  'foreign'      { ITforeign }
97  'export'       { ITexport }
98  'label'        { ITlabel } 
99  'dynamic'      { ITdynamic }
100  'unsafe'       { ITunsafe }
101  'with'         { ITwith }
102  'stdcall'      { ITstdcallconv }
103  'ccall'        { ITccallconv }
104  '_ccall_'      { ITccall (False, False, False) }
105  '_ccall_GC_'   { ITccall (False, False, True)  }
106  '_casm_'       { ITccall (False, True,  False) }
107  '_casm_GC_'    { ITccall (False, True,  True)  }
108
109  '{-# SPECIALISE'  { ITspecialise_prag }
110  '{-# SOURCE'      { ITsource_prag }
111  '{-# INLINE'      { ITinline_prag }
112  '{-# NOINLINE'    { ITnoinline_prag }
113  '{-# RULES'       { ITrules_prag }
114  '{-# SCC'         { ITscc_prag }
115  '{-# DEPRECATED'  { ITdeprecated_prag }
116  '#-}'             { ITclose_prag }
117
118 {-
119  '__interface'  { ITinterface }                 -- interface keywords
120  '__export'     { IT__export }
121  '__instimport' { ITinstimport }
122  '__forall'     { IT__forall }
123  '__letrec'     { ITletrec }
124  '__coerce'     { ITcoerce }
125  '__depends'    { ITdepends }
126  '__inline'     { ITinline }
127  '__DEFAULT'    { ITdefaultbranch }
128  '__bot'        { ITbottom }
129  '__integer'    { ITinteger_lit }
130  '__float'      { ITfloat_lit }
131  '__rational'   { ITrational_lit }
132  '__addr'       { ITaddr_lit }
133  '__label'      { ITlabel_lit }
134  '__litlit'     { ITlit_lit }
135  '__string'     { ITstring_lit }
136  '__ccall'      { ITccall $$ }
137  '__scc'        { IT__scc }
138  '__sccC'       { ITsccAllCafs }
139
140  '__A'          { ITarity }
141  '__P'          { ITspecialise }
142  '__C'          { ITnocaf }
143  '__U'          { ITunfold $$ }
144  '__S'          { ITstrict $$ }
145  '__M'          { ITcprinfo $$ }
146 -}
147
148  '..'           { ITdotdot }                    -- reserved symbols
149  '::'           { ITdcolon }
150  '='            { ITequal }
151  '\\'           { ITlam }
152  '|'            { ITvbar }
153  '<-'           { ITlarrow }
154  '->'           { ITrarrow }
155  '@'            { ITat }
156  '~'            { ITtilde }
157  '=>'           { ITdarrow }
158  '-'            { ITminus }
159  '!'            { ITbang }
160  '.'            { ITdot }
161
162  '{'            { ITocurly }                    -- special symbols
163  '}'            { ITccurly }
164  '{|'           { ITocurlybar }
165  '|}'           { ITccurlybar }
166  vccurly        { ITvccurly } -- virtual close curly (from layout)
167  '['            { ITobrack }
168  ']'            { ITcbrack }
169  '('            { IToparen }
170  ')'            { ITcparen }
171  '(#'           { IToubxparen }
172  '#)'           { ITcubxparen }
173  ';'            { ITsemi }
174  ','            { ITcomma }
175  '`'            { ITbackquote }
176
177  VARID          { ITvarid    $$ }               -- identifiers
178  CONID          { ITconid    $$ }
179  VARSYM         { ITvarsym   $$ }
180  CONSYM         { ITconsym   $$ }
181  QVARID         { ITqvarid   $$ }
182  QCONID         { ITqconid   $$ }
183  QVARSYM        { ITqvarsym  $$ }
184  QCONSYM        { ITqconsym  $$ }
185
186  IPVARID        { ITipvarid  $$ }               -- GHC extension
187
188  CHAR           { ITchar     $$ }
189  STRING         { ITstring   $$ }
190  INTEGER        { ITinteger  $$ }
191  RATIONAL       { ITrational $$ }
192
193  PRIMCHAR       { ITprimchar   $$ }
194  PRIMSTRING     { ITprimstring $$ }
195  PRIMINTEGER    { ITprimint    $$ }
196  PRIMFLOAT      { ITprimfloat  $$ }
197  PRIMDOUBLE     { ITprimdouble $$ }
198  CLITLIT        { ITlitlit     $$ }
199
200 %monad { P } { thenP } { returnP }
201 %lexer { lexer } { ITeof }
202 %name parseModule module
203 %name parseStmt   maybe_stmt
204 %tokentype { Token }
205 %%
206
207 -----------------------------------------------------------------------------
208 -- Module Header
209
210 -- The place for module deprecation is really too restrictive, but if it
211 -- was allowed at its natural place just before 'module', we get an ugly
212 -- s/r conflict with the second alternative. Another solution would be the
213 -- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
214 -- either, and DEPRECATED is only expected to be used by people who really
215 -- know what they are doing. :-)
216
217 module  :: { RdrNameHsModule }
218         : srcloc 'module' modid maybemoddeprec maybeexports 'where' body 
219                 { HsModule $3 Nothing $5 (fst $7) (snd $7) $4 $1 }
220         | srcloc body
221                 { HsModule mAIN_Name Nothing Nothing (fst $2) (snd $2) Nothing $1 }
222
223 maybemoddeprec :: { Maybe DeprecTxt }
224         : '{-# DEPRECATED' STRING '#-}'         { Just $2 }
225         |  {- empty -}                          { Nothing }
226
227 body    :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
228         :  '{'            top '}'               { $2 }
229         |      layout_on  top close             { $2 }
230
231 top     :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
232         : importdecls                           { (reverse $1,[]) }
233         | importdecls ';' cvtopdecls            { (reverse $1,$3) }
234         | cvtopdecls                            { ([],$1) }
235
236 cvtopdecls :: { [RdrNameHsDecl] }
237         : topdecls                              { cvTopDecls (groupBindings $1)}
238
239 -----------------------------------------------------------------------------
240 -- The Export List
241
242 maybeexports :: { Maybe [RdrNameIE] }
243         :  '(' exportlist ')'                   { Just $2 }
244         |  {- empty -}                          { Nothing }
245
246 exportlist :: { [RdrNameIE] }
247         :  exportlist ',' export                { $3 : $1 }
248         |  exportlist ','                       { $1 }
249         |  export                               { [$1]  }
250         |  {- empty -}                          { [] }
251
252    -- GHC extension: we allow things like [] and (,,,) to be exported
253 export  :: { RdrNameIE }
254         :  qvar                                 { IEVar $1 }
255         |  gtycon                               { IEThingAbs $1 }
256         |  gtycon '(' '..' ')'                  { IEThingAll $1 }
257         |  gtycon '(' ')'                       { IEThingWith $1 [] }
258         |  gtycon '(' qcnames ')'               { IEThingWith $1 (reverse $3) }
259         |  'module' modid                       { IEModuleContents $2 }
260
261 qcnames :: { [RdrName] }
262         :  qcnames ',' qcname                   { $3 : $1 }
263         |  qcname                               { [$1]  }
264
265 qcname  :: { RdrName }
266         :  qvar                                 { $1 }
267         |  gcon                                 { $1 }
268
269 -----------------------------------------------------------------------------
270 -- Import Declarations
271
272 -- import decls can be *empty*, or even just a string of semicolons
273 -- whereas topdecls must contain at least one topdecl.
274
275 importdecls :: { [RdrNameImportDecl] }
276         : importdecls ';' importdecl            { $3 : $1 }
277         | importdecls ';'                       { $1 }
278         | importdecl                            { [ $1 ] }
279         | {- empty -}                           { [] }
280
281 importdecl :: { RdrNameImportDecl }
282         : 'import' srcloc maybe_src optqualified CONID maybeas maybeimpspec 
283                 { ImportDecl (mkModuleNameFS $5) $3 $4 $6 $7 $2 }
284
285 maybe_src :: { WhereFrom }
286         : '{-# SOURCE' '#-}'                    { ImportByUserSource }
287         | {- empty -}                           { ImportByUser }
288
289 optqualified :: { Bool }
290         : 'qualified'                           { True  }
291         | {- empty -}                           { False }
292
293 maybeas :: { Maybe ModuleName }
294         : 'as' modid                            { Just $2 }
295         | {- empty -}                           { Nothing }
296
297 maybeimpspec :: { Maybe (Bool, [RdrNameIE]) }
298         : impspec                               { Just $1 }
299         | {- empty -}                           { Nothing }
300
301 impspec :: { (Bool, [RdrNameIE]) }
302         :  '(' exportlist ')'                   { (False, reverse $2) }
303         |  'hiding' '(' exportlist ')'          { (True,  reverse $3) }
304
305 -----------------------------------------------------------------------------
306 -- Fixity Declarations
307
308 prec    :: { Int }
309         : {- empty -}                           { 9 }
310         | INTEGER                               {%  checkPrec $1 `thenP_`
311                                                     returnP (fromInteger $1) }
312
313 infix   :: { FixityDirection }
314         : 'infix'                               { InfixN  }
315         | 'infixl'                              { InfixL  }
316         | 'infixr'                              { InfixR }
317
318 ops     :: { [RdrName] }
319         : ops ',' op                            { $3 : $1 }
320         | op                                    { [$1] }
321
322 -----------------------------------------------------------------------------
323 -- Top-Level Declarations
324
325 topdecls :: { [RdrBinding] }
326         : topdecls ';' topdecl          { ($3 : $1) }
327         | topdecls ';'                  { $1 }
328         | topdecl                       { [$1] }
329
330 topdecl :: { RdrBinding }
331         : srcloc 'type' simpletype '=' ctype    
332                 -- Note ctype, not sigtype.
333                 -- We allow an explicit for-all but we don't insert one
334                 -- in   type Foo a = (b,b)
335                 -- Instead we just say b is out of scope
336                 { RdrHsDecl (TyClD (TySynonym (fst $3) (snd $3) $5 $1)) }
337
338         | srcloc 'data' ctype '=' constrs deriving
339                 {% checkDataHeader $3 `thenP` \(cs,c,ts) ->
340                    returnP (RdrHsDecl (TyClD
341                       (mkTyData DataType cs c ts (reverse $5) (length $5) $6 $1))) }
342
343         | srcloc 'newtype' ctype '=' newconstr deriving
344                 {% checkDataHeader $3 `thenP` \(cs,c,ts) ->
345                    returnP (RdrHsDecl (TyClD
346                       (mkTyData NewType cs c ts [$5] 1 $6 $1))) }
347
348         | srcloc 'class' ctype fds where
349                 {% checkDataHeader $3 `thenP` \(cs,c,ts) ->
350                    let 
351                         (binds,sigs) = cvMonoBindsAndSigs cvClassOpSig (groupBindings $5) 
352                    in
353                    returnP (RdrHsDecl (TyClD
354                       (mkClassDecl cs c ts $4 sigs (Just binds) $1))) }
355
356         | srcloc 'instance' inst_type where
357                 { let (binds,sigs) 
358                         = cvMonoBindsAndSigs cvInstDeclSig 
359                                 (groupBindings $4)
360                   in RdrHsDecl (InstD (InstDecl $3 binds sigs Nothing $1)) }
361
362         | srcloc 'default' '(' types0 ')'
363                 { RdrHsDecl (DefD (DefaultDecl $4 $1)) }
364
365         | srcloc 'foreign' 'import' callconv ext_name 
366           unsafe_flag varid_no_unsafe '::' sigtype
367                 { RdrHsDecl (ForD (ForeignDecl $7 (FoImport $6) $9 (mkExtName $5 $7) $4 $1)) }
368
369         | srcloc 'foreign' 'export' callconv ext_name varid '::' sigtype
370                 { RdrHsDecl (ForD (ForeignDecl $6 FoExport $8 (mkExtName $5 $6) $4 $1)) }
371
372         | srcloc 'foreign' 'label' ext_name varid '::' sigtype
373                 { RdrHsDecl (ForD (ForeignDecl $5 FoLabel $7 (mkExtName $4 $5)
374                                         defaultCallConv $1)) }
375
376         | '{-# DEPRECATED' deprecations '#-}'           { $2 }
377         | '{-# RULES' rules '#-}'                       { $2 }
378         | decl                                          { $1 }
379
380 decls   :: { [RdrBinding] }
381         : decls ';' decl                { $3 : $1 }
382         | decls ';'                     { $1 }
383         | decl                          { [$1] }
384         | {- empty -}                   { [] }
385
386 decl    :: { RdrBinding }
387         : fixdecl                       { $1 }
388         | valdef                        { $1 }
389         | '{-# INLINE'   srcloc opt_phase qvar '#-}'     { RdrSig (InlineSig $4 $3 $2) }
390         | '{-# NOINLINE' srcloc opt_phase qvar '#-}'     { RdrSig (NoInlineSig $4 $3 $2) }
391         | '{-# INLINE' srcloc 'instance' opt_phase '#-}' { RdrSig (InlineInstSig $4 $2) }
392         | '{-# SPECIALISE' srcloc qvar '::' sigtypes '#-}'
393                 { foldr1 RdrAndBindings 
394                     (map (\t -> RdrSig (SpecSig $3 t $2)) $5) }
395         | '{-# SPECIALISE' srcloc 'instance' inst_type '#-}'
396                 { RdrSig (SpecInstSig $4 $2) }
397
398 opt_phase :: { Maybe Int }
399           : INTEGER                     { Just (fromInteger $1) }
400           | {- empty -}                 { Nothing }
401
402 wherebinds :: { RdrNameHsBinds }
403         : where                 { cvBinds cvValSig (groupBindings $1) }
404
405 where   :: { [RdrBinding] }
406         : 'where' decllist              { $2 }
407         | {- empty -}                   { [] }
408
409 declbinds :: { RdrNameHsBinds }
410         : decllist                      { cvBinds cvValSig (groupBindings $1) }
411
412 decllist :: { [RdrBinding] }
413         : '{'            decls '}'      { $2 }
414         |     layout_on  decls close    { $2 }
415
416 fixdecl :: { RdrBinding }
417         : srcloc infix prec ops         { foldr1 RdrAndBindings
418                                             [ RdrSig (FixSig (FixitySig n 
419                                                             (Fixity $3 $2) $1))
420                                             | n <- $4 ] }
421
422 -----------------------------------------------------------------------------
423 -- Transformation Rules
424
425 rules   :: { RdrBinding }
426         :  rules ';' rule                       { $1 `RdrAndBindings` $3 }
427         |  rules ';'                            { $1 }
428         |  rule                                 { $1 }
429         |  {- empty -}                          { RdrNullBind }
430
431 rule    :: { RdrBinding }
432         : STRING rule_forall fexp '=' srcloc exp
433              { RdrHsDecl (RuleD (HsRule $1 [] $2 $3 $6 $5)) }
434
435 rule_forall :: { [RdrNameRuleBndr] }
436         : 'forall' rule_var_list '.'            { $2 }
437         | {- empty -}                           { [] }
438
439 rule_var_list :: { [RdrNameRuleBndr] }
440         : rule_var                              { [$1] }
441         | rule_var rule_var_list                { $1 : $2 }
442
443 rule_var :: { RdrNameRuleBndr }
444         : varid                                 { RuleBndr $1 }
445         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
446
447 -----------------------------------------------------------------------------
448 -- Deprecations
449
450 deprecations :: { RdrBinding }
451         : deprecations ';' deprecation          { $1 `RdrAndBindings` $3 }
452         | deprecations ';'                      { $1 }
453         | deprecation                           { $1 }
454         | {- empty -}                           { RdrNullBind }
455
456 -- SUP: TEMPORARY HACK, not checking for `module Foo'
457 deprecation :: { RdrBinding }
458         : srcloc depreclist STRING
459                 { foldr RdrAndBindings RdrNullBind 
460                         [ RdrHsDecl (DeprecD (Deprecation n $3 $1)) | n <- $2 ] }
461
462 -----------------------------------------------------------------------------
463 -- Foreign import/export
464
465 callconv :: { Int }
466         : 'stdcall'             { stdCallConv }
467         | 'ccall'               { cCallConv }
468         | {- empty -}           { defaultCallConv }
469
470 unsafe_flag :: { Bool }
471         : 'unsafe'              { True }
472         | {- empty -}           { False }
473
474 ext_name :: { Maybe ExtName }
475         : 'dynamic'             { Just Dynamic }
476         | STRING                { Just (ExtName $1 Nothing)   }
477         | STRING STRING         { Just (ExtName $2 (Just $1)) }
478         | {- empty -}           { Nothing }
479
480
481 -----------------------------------------------------------------------------
482 -- Type signatures
483
484 opt_sig :: { Maybe RdrNameHsType }
485         : {- empty -}                   { Nothing }
486         | '::' sigtype                  { Just $2 }
487
488 opt_asig :: { Maybe RdrNameHsType }
489         : {- empty -}                   { Nothing }
490         | '::' atype                    { Just $2 }
491
492 sigtypes :: { [RdrNameHsType] }
493         : sigtype                       { [ $1 ] }
494         | sigtypes ',' sigtype          { $3 : $1 }
495
496 sigtype :: { RdrNameHsType }
497         : ctype                         { (mkHsForAllTy Nothing [] $1) }
498
499 sig_vars :: { [RdrName] }
500          : sig_vars ',' var             { $3 : $1 }
501          | var                          { [ $1 ] }
502
503 -----------------------------------------------------------------------------
504 -- Types
505
506 -- A ctype is a for-all type
507 ctype   :: { RdrNameHsType }
508         : 'forall' tyvars '.' ctype     { mkHsForAllTy (Just $2) [] $4 }
509         | context type                  { mkHsForAllTy Nothing   $1 $2 }
510         -- A type of form (context => type) is an *implicit* HsForAllTy
511         | type                          { $1 }
512
513 type :: { RdrNameHsType }
514         : gentype '->' type             { HsFunTy $1 $3 }
515         | ipvar '::' type               { mkHsIParamTy $1 $3 }
516         | gentype                       { $1 }
517
518 gentype :: { RdrNameHsType }
519         : btype                         { $1 }
520 -- Generics
521         | atype tyconop atype           { HsOpTy $1 $2 $3 }
522
523 btype :: { RdrNameHsType }
524         : btype atype                   { (HsAppTy $1 $2) }
525         | atype                         { $1 }
526
527 atype :: { RdrNameHsType }
528         : gtycon                        { HsTyVar $1 }
529         | tyvar                         { HsTyVar $1 }
530         | '(' type ',' types ')'        { HsTupleTy (mkHsTupCon tcName Boxed  ($2:$4)) ($2 : reverse $4) }
531         | '(#' types '#)'               { HsTupleTy (mkHsTupCon tcName Unboxed     $2) (reverse $2)      }
532         | '[' type ']'                  { HsListTy $2 }
533         | '(' ctype ')'                 { $2 }
534 -- Generics
535         | INTEGER                       { HsNumTy $1 }
536
537 -- An inst_type is what occurs in the head of an instance decl
538 --      e.g.  (Foo a, Gaz b) => Wibble a b
539 -- It's kept as a single type, with a MonoDictTy at the right
540 -- hand corner, for convenience.
541 inst_type :: { RdrNameHsType }
542         : ctype                         {% checkInstType $1 }
543
544 types0  :: { [RdrNameHsType] }
545         : types                         { reverse $1 }
546         | {- empty -}                   { [] }
547
548 types   :: { [RdrNameHsType] }
549         : type                          { [$1] }
550         | types  ',' type               { $3 : $1 }
551
552 simpletype :: { (RdrName, [RdrNameHsTyVar]) }
553         : tycon tyvars                  { ($1, reverse $2) }
554
555 tyvars :: { [RdrNameHsTyVar] }
556         : tyvars tyvar                  { UserTyVar $2 : $1 }
557         | {- empty -}                   { [] }
558
559 fds :: { [([RdrName], [RdrName])] }
560         : {- empty -}                   { [] }
561         | '|' fds1                      { reverse $2 }
562
563 fds1 :: { [([RdrName], [RdrName])] }
564         : fds1 ',' fd                   { $3 : $1 }
565         | fd                            { [$1] }
566
567 fd :: { ([RdrName], [RdrName]) }
568         : varids0 '->' varids0          { (reverse $1, reverse $3) }
569
570 varids0 :: { [RdrName] }
571         : {- empty -}                   { [] }
572         | varids0 tyvar                 { $2 : $1 }
573
574 -----------------------------------------------------------------------------
575 -- Datatype declarations
576
577 newconstr :: { RdrNameConDecl }
578         : srcloc conid atype    { mkConDecl $2 [] [] (VanillaCon [Unbanged $3]) $1 }
579         | srcloc conid '{' var '::' type '}'
580                                 { mkConDecl $2 [] [] (RecCon [([$4], Unbanged $6)]) $1 }
581
582 constrs :: { [RdrNameConDecl] }
583         : constrs '|' constr            { $3 : $1 }
584         | constr                        { [$1] }
585
586 constr :: { RdrNameConDecl }
587         : srcloc forall context constr_stuff
588                 { mkConDecl (fst $4) $2 $3 (snd $4) $1 }
589         | srcloc forall constr_stuff
590                 { mkConDecl (fst $3) $2 [] (snd $3) $1 }
591
592 forall :: { [RdrNameHsTyVar] }
593         : 'forall' tyvars '.'           { $2 }
594         | {- empty -}                   { [] }
595
596 context :: { RdrNameContext }
597         : btype '=>'                    {% checkContext $1 }
598
599 constr_stuff :: { (RdrName, RdrNameConDetails) }
600         : btype                         {% mkVanillaCon $1 []               }
601         | btype '!' atype satypes       {% mkVanillaCon $1 (Banged $3 : $4) }
602         | gtycon '{' fielddecls '}'     {% mkRecCon $1 $3 }
603         | sbtype conop sbtype           { ($2, InfixCon $1 $3) }
604
605 satypes :: { [RdrNameBangType] }
606         : atype satypes                 { Unbanged $1 : $2 }
607         | '!' atype satypes             { Banged   $2 : $3 }
608         | {- empty -}                   { [] }
609
610 sbtype :: { RdrNameBangType }
611         : btype                         { Unbanged $1 }
612         | '!' atype                     { Banged   $2 }
613
614 fielddecls :: { [([RdrName],RdrNameBangType)] }
615         : fielddecl ',' fielddecls      { $1 : $3 }
616         | fielddecl                     { [$1] }
617
618 fielddecl :: { ([RdrName],RdrNameBangType) }
619         : sig_vars '::' stype           { (reverse $1, $3) }
620
621 stype :: { RdrNameBangType }
622         : ctype                         { Unbanged $1 } 
623         | '!' atype                     { Banged   $2 }
624
625 deriving :: { Maybe [RdrName] }
626         : {- empty -}                   { Nothing }
627         | 'deriving' qtycls             { Just [$2] }
628         | 'deriving' '('          ')'   { Just [] }
629         | 'deriving' '(' dclasses ')'   { Just (reverse $3) }
630
631 dclasses :: { [RdrName] }
632         : dclasses ',' qtycls           { $3 : $1 }
633         | qtycls                        { [$1] }
634
635 -----------------------------------------------------------------------------
636 -- Value definitions
637
638 {- There's an awkward overlap with a type signature.  Consider
639         f :: Int -> Int = ...rhs...
640    Then we can't tell whether it's a type signature or a value
641    definition with a result signature until we see the '='.
642    So we have to inline enough to postpone reductions until we know.
643 -}
644
645 {-
646   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
647   instead of qvar, we get another shift/reduce-conflict. Consider the
648   following programs:
649   
650      { (^^) :: Int->Int ; }          Type signature; only var allowed
651
652      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
653                                      qvar allowed (because of instance decls)
654   
655   We can't tell whether to reduce var to qvar until after we've read the signatures.
656 -}
657
658 valdef :: { RdrBinding }
659         : infixexp srcloc opt_sig rhs           {% (checkValDef $1 $3 $4 $2) }
660         | infixexp srcloc '::' sigtype          {% (checkValSig $1 $4 $2) }
661         | var ',' sig_vars srcloc '::' sigtype  { foldr1 RdrAndBindings 
662                                                          [ RdrSig (Sig n $6 $4) | n <- $1:$3 ]
663                                                 }
664
665
666 rhs     :: { RdrNameGRHSs }
667         : '=' srcloc exp wherebinds     { (GRHSs (unguardedRHS $3 $2) 
668                                                                 $4 Nothing)}
669         | gdrhs wherebinds              { GRHSs (reverse $1) $2 Nothing }
670
671 gdrhs :: { [RdrNameGRHS] }
672         : gdrhs gdrh                    { $2 : $1 }
673         | gdrh                          { [$1] }
674
675 gdrh :: { RdrNameGRHS }
676         : '|' srcloc quals '=' exp      { GRHS (reverse (ExprStmt $5 $2 : $3)) $2 }
677
678 -----------------------------------------------------------------------------
679 -- Expressions
680
681 exp   :: { RdrNameHsExpr }
682         : infixexp '::' sigtype         { (ExprWithTySig $1 $3) }
683         | infixexp 'with' dbinding      { HsWith $1 $3 }
684         | infixexp                      { $1 }
685
686 infixexp :: { RdrNameHsExpr }
687         : exp10                         { $1 }
688         | infixexp qop exp10            { (OpApp $1 (HsVar $2) 
689                                                 (panic "fixity") $3 )}
690
691 exp10 :: { RdrNameHsExpr }
692         : '\\' aexp aexps opt_asig '->' srcloc exp      
693                         {% checkPatterns ($2 : reverse $3) `thenP` \ ps -> 
694                            returnP (HsLam (Match [] ps $4 
695                                             (GRHSs (unguardedRHS $7 $6) 
696                                                    EmptyBinds Nothing))) }
697         | 'let' declbinds 'in' exp              { HsLet $2 $4 }
698         | 'if' srcloc exp 'then' exp 'else' exp { HsIf $3 $5 $7 $2 }
699         | 'case' srcloc exp 'of' altslist       { HsCase $3 $5 $2 }
700         | '-' fexp                              { mkHsNegApp $2 }
701         | srcloc 'do' stmtlist                  { HsDo DoExpr $3 $1 }
702
703         | '_ccall_'    ccallid aexps0           { HsCCall $2 $3 False False cbot }
704         | '_ccall_GC_' ccallid aexps0           { HsCCall $2 $3 True  False cbot }
705         | '_casm_'     CLITLIT aexps0           { HsCCall $2 $3 False True  cbot }
706         | '_casm_GC_'  CLITLIT aexps0           { HsCCall $2 $3 True  True  cbot }
707
708         | scc_annot exp                         { if opt_SccProfilingOn
709                                                         then HsSCC $1 $2
710                                                         else HsPar $2 }
711
712         | fexp                                  { $1 }
713
714 scc_annot :: { FAST_STRING }
715         : '_scc_' STRING                        { $2 }
716         | '{-# SCC' STRING '#-}'                { $2 }
717
718 ccallid :: { FAST_STRING }
719         :  VARID                                { $1 }
720         |  CONID                                { $1 }
721
722 fexp    :: { RdrNameHsExpr }
723         : fexp aexp                             { (HsApp $1 $2) }
724         | aexp                                  { $1 }
725
726 aexps0  :: { [RdrNameHsExpr] }
727         : aexps                                 { (reverse $1) }
728
729 aexps   :: { [RdrNameHsExpr] }
730         : aexps aexp                            { $2 : $1 }
731         | {- empty -}                           { [] }
732
733 aexp    :: { RdrNameHsExpr }
734         : var_or_con '{|' gentype '|}'          { (HsApp $1 (HsType $3)) }
735         | aexp '{' fbinds '}'                   {% (mkRecConstrOrUpdate $1 
736                                                         (reverse $3)) }
737         | aexp1                                 { $1 }
738
739 var_or_con :: { RdrNameHsExpr }
740         : qvar                          { HsVar $1 }
741         | gcon                          { HsVar $1 }
742
743 aexp1   :: { RdrNameHsExpr }
744         : ipvar                         { HsIPVar $1 }
745         | var_or_con                    { $1 }
746         | literal                       { HsLit $1 }
747         | INTEGER                       { HsOverLit (HsIntegral   $1) }
748         | RATIONAL                      { HsOverLit (HsFractional $1) }
749         | '(' exp ')'                   { HsPar $2 }
750         | '(' exp ',' texps ')'         { ExplicitTuple ($2 : reverse $4) Boxed}
751         | '(#' texps '#)'               { ExplicitTuple (reverse $2)      Unboxed }
752         | '[' list ']'                  { $2 }
753         | '(' infixexp qop ')'          { (SectionL $2 (HsVar $3))  }
754         | '(' qopm infixexp ')'         { (SectionR $2 $3) }
755         | qvar '@' aexp                 { EAsPat $1 $3 }
756         | '_'                           { EWildPat }
757         | '~' aexp1                     { ELazyPat $2 }
758
759 texps :: { [RdrNameHsExpr] }
760         : texps ',' exp                 { $3 : $1 }
761         | exp                           { [$1] }
762
763
764 -----------------------------------------------------------------------------
765 -- List expressions
766
767 -- The rules below are little bit contorted to keep lexps left-recursive while
768 -- avoiding another shift/reduce-conflict.
769
770 list :: { RdrNameHsExpr }
771         : exp                           { ExplicitList [$1] }
772         | lexps                         { ExplicitList (reverse $1) }
773         | exp '..'                      { ArithSeqIn (From $1) }
774         | exp ',' exp '..'              { ArithSeqIn (FromThen $1 $3) }
775         | exp '..' exp                  { ArithSeqIn (FromTo $1 $3) }
776         | exp ',' exp '..' exp          { ArithSeqIn (FromThenTo $1 $3 $5) }
777         | exp srcloc pquals             {% let { body [qs] = qs;
778                                                  body  qss = [ParStmt (map reverse qss)] }
779                                            in
780                                            returnP ( HsDo ListComp
781                                                            (reverse (ExprStmt $1 $2 : body $3))
782                                                            $2
783                                                   )
784                                         }
785
786 lexps :: { [RdrNameHsExpr] }
787         : lexps ',' exp                 { $3 : $1 }
788         | exp ',' exp                   { [$3,$1] }
789
790 -----------------------------------------------------------------------------
791 -- List Comprehensions
792
793 pquals :: { [[RdrNameStmt]] }
794         : pquals '|' quals              { $3 : $1 }
795         | '|' quals                     { [$2] }
796
797 quals :: { [RdrNameStmt] }
798         : quals ',' stmt                { $3 : $1 }
799         | stmt                          { [$1] }
800
801 -----------------------------------------------------------------------------
802 -- Case alternatives
803
804 altslist :: { [RdrNameMatch] }
805         : '{'            alts '}'       { reverse $2 }
806         |     layout_on  alts  close    { reverse $2 }
807
808 alts    :: { [RdrNameMatch] }
809         : alts1                         { $1 }
810         | ';' alts                      { $2 }
811
812 alts1   :: { [RdrNameMatch] }
813         : alts1 ';' alt                 { $3 : $1 }
814         | alts1 ';'                     { $1 }
815         | alt                           { [$1] }
816
817 alt     :: { RdrNameMatch }
818         : infixexp opt_sig ralt wherebinds
819                                         {% (checkPattern $1 `thenP` \p ->
820                                            returnP (Match [] [p] $2
821                                                      (GRHSs $3 $4 Nothing))  )}
822
823 ralt :: { [RdrNameGRHS] }
824         : '->' srcloc exp               { [GRHS [ExprStmt $3 $2] $2] }
825         | gdpats                        { (reverse $1) }
826
827 gdpats :: { [RdrNameGRHS] }
828         : gdpats gdpat                  { $2 : $1 }
829         | gdpat                         { [$1] }
830
831 gdpat   :: { RdrNameGRHS }
832         : srcloc '|' quals '->' exp     { GRHS (reverse (ExprStmt $5 $1:$3)) $1}
833
834 -----------------------------------------------------------------------------
835 -- Statement sequences
836
837 stmtlist :: { [RdrNameStmt] }
838         : '{'                   stmts '}'       { reverse $2 }
839         |     layout_on_for_do  stmts close     { reverse $2 }
840
841 -- Stmt list should really end in an expression, but it's not
842 -- convenient to enforce this here, so we throw out erroneous
843 -- statement sequences in the renamer instead.
844
845 stmts :: { [RdrNameStmt] }
846         : ';' stmts1                    { $2 }
847         | stmts1                        { $1 }
848
849 stmts1 :: { [RdrNameStmt] }
850         : stmts1 ';' stmt               { $3 : $1 }
851         | stmts1 ';'                    { $1 }
852         | stmt                          { [$1] }
853
854 -- for typing stmts at the GHCi prompt, where the input may consist of
855 -- just comments.
856 maybe_stmt :: { Maybe RdrNameStmt }
857         : stmt                          { Just $1 }
858         | {- nothing -}                 { Nothing }
859
860 stmt  :: { RdrNameStmt }
861         : srcloc infixexp '<-' exp      {% checkPattern $2 `thenP` \p ->
862                                            returnP (BindStmt p $4 $1) }
863         | srcloc exp                    { ExprStmt $2 $1 }
864         | srcloc 'let' declbinds        { LetStmt $3 }
865
866 -----------------------------------------------------------------------------
867 -- Record Field Update/Construction
868
869 fbinds  :: { RdrNameHsRecordBinds }
870         : fbinds ',' fbind              { $3 : $1 }
871         | fbinds ','                    { $1 }
872         | fbind                         { [$1] }
873         | {- empty -}                   { [] }
874
875 fbind   :: { (RdrName, RdrNameHsExpr, Bool) }
876         : qvar '=' exp                  { ($1,$3,False) }
877
878 -----------------------------------------------------------------------------
879 -- Implicit Parameter Bindings
880
881 dbinding :: { [(RdrName, RdrNameHsExpr)] }
882         : '{' dbinds '}'                { $2 }
883         | layout_on dbinds close        { $2 }
884
885 dbinds  :: { [(RdrName, RdrNameHsExpr)] }
886         : dbinds ';' dbind              { $3 : $1 }
887         | dbinds ';'                    { $1 }
888         | dbind                         { [$1] }
889         | {- empty -}                   { [] }
890
891 dbind   :: { (RdrName, RdrNameHsExpr) }
892 dbind   : ipvar '=' exp                 { ($1, $3) }
893
894 -----------------------------------------------------------------------------
895 -- Variables, Constructors and Operators.
896
897 depreclist :: { [RdrName] }
898 depreclist : deprec_var                 { [$1] }
899            | deprec_var ',' depreclist  { $1 : $3 }
900
901 deprec_var :: { RdrName }
902 deprec_var : var                        { $1 }
903            | tycon                      { $1 }
904
905 gtycon  :: { RdrName }
906         : qtycon                        { $1 }
907         | '(' qtyconop ')'              { $2 }
908         | '(' ')'                       { unitTyCon_RDR }
909         | '(' '->' ')'                  { funTyCon_RDR }
910         | '[' ']'                       { listTyCon_RDR }
911         | '(' commas ')'                { tupleTyCon_RDR $2 }
912
913 gcon    :: { RdrName }
914         : '(' ')'               { unitCon_RDR }
915         | '[' ']'               { nilCon_RDR }
916         | '(' commas ')'        { tupleCon_RDR $2 }
917         | qcon                  { $1 }
918
919 var     :: { RdrName }
920         : varid                 { $1 }
921         | '(' varsym ')'        { $2 }
922
923 qvar    :: { RdrName }
924         : qvarid                { $1 }
925         | '(' varsym ')'        { $2 }
926         | '(' qvarsym1 ')'      { $2 }
927 -- We've inlined qvarsym here so that the decision about
928 -- whether it's a qvar or a var can be postponed until
929 -- *after* we see the close paren.
930
931 ipvar   :: { RdrName }
932         : IPVARID               { (mkUnqual varName (tailFS $1)) }
933
934 qcon    :: { RdrName }
935         : qconid                { $1 }
936         | '(' qconsym ')'       { $2 }
937
938 varop   :: { RdrName }
939         : varsym                { $1 }
940         | '`' varid '`'         { $2 }
941
942 qvarop :: { RdrName }
943         : qvarsym               { $1 }
944         | '`' qvarid '`'        { $2 }
945
946 qvaropm :: { RdrName }
947         : qvarsym_no_minus      { $1 }
948         | '`' qvarid '`'        { $2 }
949
950 conop :: { RdrName }
951         : consym                { $1 }  
952         | '`' conid '`'         { $2 }
953
954 qconop :: { RdrName }
955         : qconsym               { $1 }
956         | '`' qconid '`'        { $2 }
957
958 -----------------------------------------------------------------------------
959 -- Any operator
960
961 op      :: { RdrName }   -- used in infix decls
962         : varop                 { $1 }
963         | conop                 { $1 }
964
965 qop     :: { RdrName {-HsExpr-} }   -- used in sections
966         : qvarop                { $1 }
967         | qconop                { $1 }
968
969 qopm    :: { RdrNameHsExpr }   -- used in sections
970         : qvaropm               { HsVar $1 }
971         | qconop                { HsVar $1 }
972
973 -----------------------------------------------------------------------------
974 -- VarIds
975
976 qvarid :: { RdrName }
977         : varid                 { $1 }
978         | QVARID                { mkQual varName $1 }
979
980 varid :: { RdrName }
981         : varid_no_unsafe       { $1 }
982         | 'unsafe'              { mkUnqual varName SLIT("unsafe") }
983
984 varid_no_unsafe :: { RdrName }
985         : VARID                 { mkUnqual varName $1 }
986         | special_id            { mkUnqual varName $1 }
987         | 'forall'              { mkUnqual varName SLIT("forall") }
988
989 tyvar   :: { RdrName }
990         : VARID                 { mkUnqual tvName $1 }
991         | special_id            { mkUnqual tvName $1 }
992         | 'unsafe'              { mkUnqual tvName SLIT("unsafe") }
993
994 -- These special_ids are treated as keywords in various places, 
995 -- but as ordinary ids elsewhere.   A special_id collects all thsee
996 -- except 'unsafe' and 'forall' whose treatment differs depending on context
997 special_id :: { UserFS }
998 special_id
999         : 'as'                  { SLIT("as") }
1000         | 'qualified'           { SLIT("qualified") }
1001         | 'hiding'              { SLIT("hiding") }
1002         | 'export'              { SLIT("export") }
1003         | 'label'               { SLIT("label")  }
1004         | 'dynamic'             { SLIT("dynamic") }
1005         | 'stdcall'             { SLIT("stdcall") }
1006         | 'ccall'               { SLIT("ccall") }
1007
1008 -----------------------------------------------------------------------------
1009 -- ConIds
1010
1011 qconid :: { RdrName }
1012         : conid                 { $1 }
1013         | QCONID                { mkQual dataName $1 }
1014
1015 conid   :: { RdrName }
1016         : CONID                 { mkUnqual dataName $1 }
1017
1018 -----------------------------------------------------------------------------
1019 -- ConSyms
1020
1021 qconsym :: { RdrName }
1022         : consym                { $1 }
1023         | QCONSYM               { mkQual dataName $1 }
1024
1025 consym :: { RdrName }
1026         : CONSYM                { mkUnqual dataName $1 }
1027
1028 -----------------------------------------------------------------------------
1029 -- VarSyms
1030
1031 qvarsym :: { RdrName }
1032         : varsym                { $1 }
1033         | qvarsym1              { $1 }
1034
1035 qvarsym_no_minus :: { RdrName }
1036         : varsym_no_minus       { $1 }
1037         | qvarsym1              { $1 }
1038
1039 qvarsym1 :: { RdrName }
1040 qvarsym1 : QVARSYM              { mkQual varName $1 }
1041
1042 varsym :: { RdrName }
1043         : varsym_no_minus       { $1 }
1044         | '-'                   { mkUnqual varName SLIT("-") }
1045
1046 varsym_no_minus :: { RdrName } -- varsym not including '-'
1047         : VARSYM                { mkUnqual varName $1 }
1048         | special_sym           { mkUnqual varName $1 }
1049
1050
1051 -- See comments with special_id
1052 special_sym :: { UserFS }
1053 special_sym : '!'       { SLIT("!") }
1054             | '.'       { SLIT(".") }
1055
1056 -----------------------------------------------------------------------------
1057 -- Literals
1058
1059 literal :: { HsLit }
1060         : CHAR                  { HsChar       $1 }
1061         | STRING                { HsString     $1 }
1062         | PRIMINTEGER           { HsIntPrim    $1 }
1063         | PRIMCHAR              { HsCharPrim   $1 }
1064         | PRIMSTRING            { HsStringPrim $1 }
1065         | PRIMFLOAT             { HsFloatPrim  $1 }
1066         | PRIMDOUBLE            { HsDoublePrim $1 }
1067         | CLITLIT               { HsLitLit     $1 (error "Parser.y: CLITLIT") }
1068
1069 srcloc :: { SrcLoc }    :       {% getSrcLocP }
1070  
1071 -----------------------------------------------------------------------------
1072 -- Layout
1073
1074 close :: { () }
1075         : vccurly               { () } -- context popped in lexer.
1076         | error                 {% popContext }
1077
1078 layout_on         :: { () }     : {% layoutOn True{-strict-} }
1079 layout_on_for_do  :: { () }     : {% layoutOn False }
1080
1081 -----------------------------------------------------------------------------
1082 -- Miscellaneous (mostly renamings)
1083
1084 modid   :: { ModuleName }
1085         : CONID                 { mkModuleNameFS $1 }
1086
1087 tycon   :: { RdrName }
1088         : CONID                 { mkUnqual tcClsName $1 }
1089
1090 tyconop :: { RdrName }
1091         : CONSYM                { mkUnqual tcClsName $1 }
1092
1093 qtycon :: { RdrName }
1094         : tycon                 { $1 }
1095         | QCONID                { mkQual tcClsName $1 }
1096
1097 qtyconop :: { RdrName }
1098           : tyconop             { $1 }
1099           | QCONSYM             { mkQual tcClsName $1 }
1100
1101 qtycls  :: { RdrName }
1102         : qtycon                { $1 }
1103
1104 commas :: { Int }
1105         : commas ','                    { $1 + 1 }
1106         | ','                           { 2 }
1107
1108 -----------------------------------------------------------------------------
1109
1110 {
1111 happyError :: P a
1112 happyError buf PState{ loc = loc } = PFailed (srcParseErr buf loc)
1113 }