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