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