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