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