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