[project @ 2001-08-20 10:19:47 by simonmar]
[ghc-hetmet.git] / ghc / compiler / parser / Parser.y
1 {-
2 -----------------------------------------------------------------------------
3 $Id: Parser.y,v 1.73 2001/08/20 10:19:47 simonmar Exp $
4
5 Haskell grammar.
6
7 Author(s): Simon Marlow, Sven Panne 1997, 1998, 1999
8 -----------------------------------------------------------------------------
9 -}
10
11 {
12 module Parser ( parseModule, parseStmt, parseIdentifier ) where
13
14 import HsSyn
15 import HsTypes          ( mkHsTupCon )
16
17 import RdrHsSyn
18 import Lex
19 import ParseUtil
20 import RdrName
21 import PrelNames        ( mAIN_Name, unitTyCon_RDR, funTyCon_RDR, listTyCon_RDR,
22                           tupleTyCon_RDR, unitCon_RDR, nilCon_RDR, tupleCon_RDR
23                         )
24 import ForeignCall      ( Safety(..), CExportSpec(..), CCallSpec(..), 
25                           CCallConv(..), CCallTarget(..), defaultCCallConv,
26                           DNCallSpec(..) )
27 import OccName          ( UserFS, varName, tcName, dataName, tcClsName, tvName )
28 import SrcLoc           ( SrcLoc )
29 import Module
30 import CmdLineOpts      ( opt_SccProfilingOn )
31 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), 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 %name parseIdentifier  identifier
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 (mkHsIntegral   $1) }
777         | RATIONAL                      { HsOverLit (mkHsFractional $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 identifier :: { RdrName }
928         : qvar                          { $1 }
929         | gcon                          { $1 }
930         | qop                           { $1 }
931
932 depreclist :: { [RdrName] }
933 depreclist : deprec_var                 { [$1] }
934            | deprec_var ',' depreclist  { $1 : $3 }
935
936 deprec_var :: { RdrName }
937 deprec_var : var                        { $1 }
938            | tycon                      { $1 }
939
940 gtycon  :: { RdrName }
941         : qtycon                        { $1 }
942         | '(' qtyconop ')'              { $2 }
943         | '(' ')'                       { unitTyCon_RDR }
944         | '(' '->' ')'                  { funTyCon_RDR }
945         | '[' ']'                       { listTyCon_RDR }
946         | '(' commas ')'                { tupleTyCon_RDR $2 }
947
948 gcon    :: { RdrName }
949         : '(' ')'               { unitCon_RDR }
950         | '[' ']'               { nilCon_RDR }
951         | '(' commas ')'        { tupleCon_RDR $2 }
952         | qcon                  { $1 }
953
954 var     :: { RdrName }
955         : varid                 { $1 }
956         | '(' varsym ')'        { $2 }
957
958 qvar    :: { RdrName }
959         : qvarid                { $1 }
960         | '(' varsym ')'        { $2 }
961         | '(' qvarsym1 ')'      { $2 }
962 -- We've inlined qvarsym here so that the decision about
963 -- whether it's a qvar or a var can be postponed until
964 -- *after* we see the close paren.
965
966 ipvar   :: { RdrName }
967         : IPVARID               { (mkUnqual varName (tailFS $1)) }
968
969 qcon    :: { RdrName }
970         : qconid                { $1 }
971         | '(' qconsym ')'       { $2 }
972
973 varop   :: { RdrName }
974         : varsym                { $1 }
975         | '`' varid '`'         { $2 }
976
977 qvarop :: { RdrName }
978         : qvarsym               { $1 }
979         | '`' qvarid '`'        { $2 }
980
981 qvaropm :: { RdrName }
982         : qvarsym_no_minus      { $1 }
983         | '`' qvarid '`'        { $2 }
984
985 conop :: { RdrName }
986         : consym                { $1 }  
987         | '`' conid '`'         { $2 }
988
989 qconop :: { RdrName }
990         : qconsym               { $1 }
991         | '`' qconid '`'        { $2 }
992
993 -----------------------------------------------------------------------------
994 -- Any operator
995
996 op      :: { RdrName }   -- used in infix decls
997         : varop                 { $1 }
998         | conop                 { $1 }
999
1000 qop     :: { RdrName {-HsExpr-} }   -- used in sections
1001         : qvarop                { $1 }
1002         | qconop                { $1 }
1003
1004 qopm    :: { RdrNameHsExpr }   -- used in sections
1005         : qvaropm               { HsVar $1 }
1006         | qconop                { HsVar $1 }
1007
1008 -----------------------------------------------------------------------------
1009 -- VarIds
1010
1011 qvarid :: { RdrName }
1012         : varid                 { $1 }
1013         | QVARID                { mkQual varName $1 }
1014
1015 varid :: { RdrName }
1016         : varid_no_unsafe       { $1 }
1017         | 'unsafe'              { mkUnqual varName SLIT("unsafe") }
1018
1019 varid_no_unsafe :: { RdrName }
1020         : VARID                 { mkUnqual varName $1 }
1021         | special_id            { mkUnqual varName $1 }
1022         | 'forall'              { mkUnqual varName SLIT("forall") }
1023
1024 tyvar   :: { RdrName }
1025         : VARID                 { mkUnqual tvName $1 }
1026         | special_id            { mkUnqual tvName $1 }
1027         | 'unsafe'              { mkUnqual tvName SLIT("unsafe") }
1028
1029 -- These special_ids are treated as keywords in various places, 
1030 -- but as ordinary ids elsewhere.   A special_id collects all thsee
1031 -- except 'unsafe' and 'forall' whose treatment differs depending on context
1032 special_id :: { UserFS }
1033 special_id
1034         : 'as'                  { SLIT("as") }
1035         | 'qualified'           { SLIT("qualified") }
1036         | 'hiding'              { SLIT("hiding") }
1037         | 'export'              { SLIT("export") }
1038         | 'label'               { SLIT("label")  }
1039         | 'dynamic'             { SLIT("dynamic") }
1040         | 'stdcall'             { SLIT("stdcall") }
1041         | 'ccall'               { SLIT("ccall") }
1042
1043 -----------------------------------------------------------------------------
1044 -- ConIds
1045
1046 qconid :: { RdrName }
1047         : conid                 { $1 }
1048         | QCONID                { mkQual dataName $1 }
1049
1050 conid   :: { RdrName }
1051         : CONID                 { mkUnqual dataName $1 }
1052
1053 -----------------------------------------------------------------------------
1054 -- ConSyms
1055
1056 qconsym :: { RdrName }
1057         : consym                { $1 }
1058         | QCONSYM               { mkQual dataName $1 }
1059
1060 consym :: { RdrName }
1061         : CONSYM                { mkUnqual dataName $1 }
1062
1063 -----------------------------------------------------------------------------
1064 -- VarSyms
1065
1066 qvarsym :: { RdrName }
1067         : varsym                { $1 }
1068         | qvarsym1              { $1 }
1069
1070 qvarsym_no_minus :: { RdrName }
1071         : varsym_no_minus       { $1 }
1072         | qvarsym1              { $1 }
1073
1074 qvarsym1 :: { RdrName }
1075 qvarsym1 : QVARSYM              { mkQual varName $1 }
1076
1077 varsym :: { RdrName }
1078         : varsym_no_minus       { $1 }
1079         | '-'                   { mkUnqual varName SLIT("-") }
1080
1081 varsym_no_minus :: { RdrName } -- varsym not including '-'
1082         : VARSYM                { mkUnqual varName $1 }
1083         | special_sym           { mkUnqual varName $1 }
1084
1085
1086 -- See comments with special_id
1087 special_sym :: { UserFS }
1088 special_sym : '!'       { SLIT("!") }
1089             | '.'       { SLIT(".") }
1090
1091 -----------------------------------------------------------------------------
1092 -- Literals
1093
1094 literal :: { HsLit }
1095         : CHAR                  { HsChar       $1 }
1096         | STRING                { HsString     $1 }
1097         | PRIMINTEGER           { HsIntPrim    $1 }
1098         | PRIMCHAR              { HsCharPrim   $1 }
1099         | PRIMSTRING            { HsStringPrim $1 }
1100         | PRIMFLOAT             { HsFloatPrim  $1 }
1101         | PRIMDOUBLE            { HsDoublePrim $1 }
1102         | CLITLIT               { HsLitLit     $1 placeHolderType }
1103
1104 srcloc :: { SrcLoc }    :       {% getSrcLocP }
1105  
1106 -----------------------------------------------------------------------------
1107 -- Layout
1108
1109 close :: { () }
1110         : vccurly               { () } -- context popped in lexer.
1111         | error                 {% popContext }
1112
1113 layout_on         :: { () }     : {% layoutOn True{-strict-} }
1114 layout_on_for_do  :: { () }     : {% layoutOn False }
1115
1116 -----------------------------------------------------------------------------
1117 -- Miscellaneous (mostly renamings)
1118
1119 modid   :: { ModuleName }
1120         : CONID                 { mkModuleNameFS $1 }
1121         | QCONID                { mkModuleNameFS
1122                                    (mkFastString
1123                                      (unpackFS (fst $1) ++ 
1124                                         '.':unpackFS (snd $1)))
1125                                 }
1126
1127 tycon   :: { RdrName }
1128         : CONID                 { mkUnqual tcClsName $1 }
1129
1130 tyconop :: { RdrName }
1131         : CONSYM                { mkUnqual tcClsName $1 }
1132
1133 qtycon :: { RdrName }
1134         : tycon                 { $1 }
1135         | QCONID                { mkQual tcClsName $1 }
1136
1137 qtyconop :: { RdrName }
1138           : tyconop             { $1 }
1139           | QCONSYM             { mkQual tcClsName $1 }
1140
1141 qtycls  :: { RdrName }
1142         : qtycon                { $1 }
1143
1144 commas :: { Int }
1145         : commas ','                    { $1 + 1 }
1146         | ','                           { 2 }
1147
1148 -----------------------------------------------------------------------------
1149
1150 {
1151 happyError :: P a
1152 happyError buf PState{ loc = loc } = PFailed (srcParseErr buf loc)
1153 }