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