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