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