35b8854ebe3addad59c6a696d3485ed58c6bd0db
[ghc-hetmet.git] / ghc / compiler / parser / Parser.y
1 {-                                                              -*-haskell-*-
2 -----------------------------------------------------------------------------
3 $Id: Parser.y,v 1.94 2002/03/28 09:59:03 simonmar Exp $
4
5 Haskell grammar.
6
7 Author(s): Simon Marlow, Sven Panne 1997, 1998, 1999
8 -----------------------------------------------------------------------------
9 -}
10
11 {
12 module Parser ( parseModule, parseStmt, parseIdentifier, parseIface ) where
13
14 import HsSyn
15 import HsTypes          ( mkHsTupCon )
16
17 import RdrHsSyn
18 import RnMonad          ( ParsedIface(..) )
19 import Lex
20 import ParseUtil
21 import RdrName
22 import PrelNames        ( mAIN_Name, unitTyCon_RDR, funTyCon_RDR, 
23                           listTyCon_RDR, parrTyCon_RDR, tupleTyCon_RDR, 
24                           unitCon_RDR, nilCon_RDR, tupleCon_RDR )
25 import ForeignCall      ( Safety(..), CExportSpec(..), 
26                           CCallConv(..), CCallTarget(..), defaultCCallConv,
27                         )
28 import OccName          ( UserFS, varName, tcName, dataName, tcClsName, tvName )
29 import TyCon            ( DataConDetails(..) )
30 import SrcLoc           ( SrcLoc )
31 import Module
32 import CmdLineOpts      ( opt_SccProfilingOn, opt_InPackage )
33 import Type             ( Kind, mkArrowKind, liftedTypeKind )
34 import BasicTypes       ( Boxity(..), Fixity(..), FixityDirection(..), IPName(..),
35                           NewOrData(..), StrictnessMark(..), Activation(..) )
36 import Panic
37
38 import GlaExts
39 import CStrings         ( CLabelString )
40 import FastString
41 import Maybes           ( orElse )
42 import Outputable
43
44 #include "HsVersions.h"
45 }
46
47 {-
48 -----------------------------------------------------------------------------
49 Conflicts: 21 shift/reduce, -=chak[4Feb2]
50
51 9 for abiguity in 'if x then y else z + 1'
52         (shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
53         8 because op might be: - ! * . `x` VARSYM CONSYM QVARSYM QCONSYM
54 1 for ambiguity in 'if x then y else z :: T'
55         (shift parses as 'if x then y else (z :: T)', as per longest-parse rule)
56 1 for ambiguity in 'if x then y else z with ?x=3'
57         (shift parses as 'if x then y else (z with ?x=3)'
58
59 3 for ambiguity in 'case x of y :: a -> b'
60         (don't know whether to reduce 'a' as a btype or shift the '->'.
61          conclusion:  bogus expression anyway, doesn't matter)
62
63 1 for ambiguity in '{-# RULES "name" forall = ... #-}' 
64         since 'forall' is a valid variable name, we don't know whether
65         to treat a forall on the input as the beginning of a quantifier
66         or the beginning of the rule itself.  Resolving to shift means
67         it's always treated as a quantifier, hence the above is disallowed.
68         This saves explicitly defining a grammar for the rule lhs that
69         doesn't include 'forall'.
70
71 1 for ambiguity in 'x @ Rec{..}'.  
72         Only sensible parse is 'x @ (Rec{..})', which is what resolving
73         to shift gives us.
74
75 6 for conflicts between `fdecl' and `fdeclDEPRECATED', which are resolved
76   correctly, and moreover, should go away when `fdeclDEPRECATED' is removed.
77
78 -----------------------------------------------------------------------------
79 -}
80
81 %token
82  '_'            { ITunderscore }                -- Haskell keywords
83  'as'           { ITas }
84  'case'         { ITcase }      
85  'class'        { ITclass } 
86  'data'         { ITdata } 
87  'default'      { ITdefault }
88  'deriving'     { ITderiving }
89  'do'           { ITdo }
90  'else'         { ITelse }
91  'hiding'       { IThiding }
92  'if'           { ITif }
93  'import'       { ITimport }
94  'in'           { ITin }
95  'infix'        { ITinfix }
96  'infixl'       { ITinfixl }
97  'infixr'       { ITinfixr }
98  'instance'     { ITinstance }
99  'let'          { ITlet }
100  'module'       { ITmodule }
101  'newtype'      { ITnewtype }
102  'of'           { ITof }
103  'qualified'    { ITqualified }
104  'then'         { ITthen }
105  'type'         { ITtype }
106  'where'        { ITwhere }
107  '_scc_'        { ITscc }             -- ToDo: remove
108
109  'forall'       { ITforall }                    -- GHC extension keywords
110  'foreign'      { ITforeign }
111  'export'       { ITexport }
112  'label'        { ITlabel } 
113  'dynamic'      { ITdynamic }
114  'safe'         { ITsafe }
115  'threadsafe'   { ITthreadsafe }
116  'unsafe'       { ITunsafe }
117  'with'         { ITwith }
118  'stdcall'      { ITstdcallconv }
119  'ccall'        { ITccallconv }
120  'dotnet'       { ITdotnet }
121  '_ccall_'      { ITccall (False, False, PlayRisky) }
122  '_ccall_GC_'   { ITccall (False, False, PlaySafe False) }
123  '_casm_'       { ITccall (False, True,  PlayRisky) }
124  '_casm_GC_'    { ITccall (False, True,  PlaySafe False) }
125
126  '{-# SPECIALISE'  { ITspecialise_prag }
127  '{-# SOURCE'      { ITsource_prag }
128  '{-# INLINE'      { ITinline_prag }
129  '{-# NOINLINE'    { ITnoinline_prag }
130  '{-# RULES'       { ITrules_prag }
131  '{-# SCC'         { ITscc_prag }
132  '{-# DEPRECATED'  { ITdeprecated_prag }
133  '#-}'             { ITclose_prag }
134
135 {-
136  '__interface'  { ITinterface }                 -- interface keywords
137  '__export'     { IT__export }
138  '__instimport' { ITinstimport }
139  '__forall'     { IT__forall }
140  '__letrec'     { ITletrec }
141  '__coerce'     { ITcoerce }
142  '__depends'    { ITdepends }
143  '__inline'     { ITinline }
144  '__DEFAULT'    { ITdefaultbranch }
145  '__bot'        { ITbottom }
146  '__integer'    { ITinteger_lit }
147  '__float'      { ITfloat_lit }
148  '__rational'   { ITrational_lit }
149  '__addr'       { ITaddr_lit }
150  '__label'      { ITlabel_lit }
151  '__litlit'     { ITlit_lit }
152  '__string'     { ITstring_lit }
153  '__ccall'      { ITccall $$ }
154  '__scc'        { IT__scc }
155  '__sccC'       { ITsccAllCafs }
156
157  '__A'          { ITarity }
158  '__P'          { ITspecialise }
159  '__C'          { ITnocaf }
160  '__U'          { ITunfold }
161  '__S'          { ITstrict $$ }
162  '__M'          { ITcprinfo $$ }
163 -}
164
165  '..'           { ITdotdot }                    -- reserved symbols
166  '::'           { ITdcolon }
167  '='            { ITequal }
168  '\\'           { ITlam }
169  '|'            { ITvbar }
170  '<-'           { ITlarrow }
171  '->'           { ITrarrow }
172  '@'            { ITat }
173  '~'            { ITtilde }
174  '=>'           { ITdarrow }
175  '-'            { ITminus }
176  '!'            { ITbang }
177  '*'            { ITstar }
178  '.'            { ITdot }
179
180  '{'            { ITocurly }                    -- special symbols
181  '}'            { ITccurly }
182  '{|'           { ITocurlybar }
183  '|}'           { ITccurlybar }
184  vccurly        { ITvccurly } -- virtual close curly (from layout)
185  '['            { ITobrack }
186  ']'            { ITcbrack }
187  '[:'           { ITopabrack }
188  ':]'           { ITcpabrack }
189  '('            { IToparen }
190  ')'            { ITcparen }
191  '(#'           { IToubxparen }
192  '#)'           { ITcubxparen }
193  ';'            { ITsemi }
194  ','            { ITcomma }
195  '`'            { ITbackquote }
196
197  VARID          { ITvarid    $$ }               -- identifiers
198  CONID          { ITconid    $$ }
199  VARSYM         { ITvarsym   $$ }
200  CONSYM         { ITconsym   $$ }
201  QVARID         { ITqvarid   $$ }
202  QCONID         { ITqconid   $$ }
203  QVARSYM        { ITqvarsym  $$ }
204  QCONSYM        { ITqconsym  $$ }
205
206  IPDUPVARID     { ITdupipvarid   $$ }           -- GHC extension
207  IPSPLITVARID   { ITsplitipvarid $$ }           -- GHC extension
208
209  CHAR           { ITchar     $$ }
210  STRING         { ITstring   $$ }
211  INTEGER        { ITinteger  $$ }
212  RATIONAL       { ITrational $$ }
213
214  PRIMCHAR       { ITprimchar   $$ }
215  PRIMSTRING     { ITprimstring $$ }
216  PRIMINTEGER    { ITprimint    $$ }
217  PRIMFLOAT      { ITprimfloat  $$ }
218  PRIMDOUBLE     { ITprimdouble $$ }
219  CLITLIT        { ITlitlit     $$ }
220
221 %monad { P } { thenP } { returnP }
222 %lexer { lexer } { ITeof }
223 %name parseModule module
224 %name parseStmt   maybe_stmt
225 %name parseIdentifier  identifier
226 %name parseIface iface
227 %tokentype { Token }
228 %%
229
230 -----------------------------------------------------------------------------
231 -- Module Header
232
233 -- The place for module deprecation is really too restrictive, but if it
234 -- was allowed at its natural place just before 'module', we get an ugly
235 -- s/r conflict with the second alternative. Another solution would be the
236 -- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
237 -- either, and DEPRECATED is only expected to be used by people who really
238 -- know what they are doing. :-)
239
240 module  :: { RdrNameHsModule }
241         : srcloc 'module' modid maybemoddeprec maybeexports 'where' body 
242                 { HsModule $3 Nothing $5 (fst $7) (snd $7) $4 $1 }
243         | srcloc body
244                 { HsModule mAIN_Name Nothing Nothing (fst $2) (snd $2) Nothing $1 }
245
246 maybemoddeprec :: { Maybe DeprecTxt }
247         : '{-# DEPRECATED' STRING '#-}'         { Just $2 }
248         |  {- empty -}                          { Nothing }
249
250 body    :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
251         :  '{'            top '}'               { $2 }
252         |      layout_on  top close             { $2 }
253
254 top     :: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
255         : importdecls                           { (reverse $1,[]) }
256         | importdecls ';' cvtopdecls            { (reverse $1,$3) }
257         | cvtopdecls                            { ([],$1) }
258
259 cvtopdecls :: { [RdrNameHsDecl] }
260         : topdecls                              { cvTopDecls (groupBindings $1)}
261
262 -----------------------------------------------------------------------------
263 -- Interfaces (.hi-boot files)
264
265 iface   :: { ParsedIface }
266         : 'module' modid 'where' ifacebody
267           {         ParsedIface {
268                         pi_mod     = $2,
269                         pi_pkg     = opt_InPackage,
270                         pi_vers    = 1,                 -- Module version
271                         pi_orphan  = False,
272                         pi_exports = (1,[($2,mkIfaceExports $4)]),
273                         pi_usages  = [],
274                         pi_fixity  = [],
275                         pi_insts   = [],
276                         pi_decls   = map (\x -> (1,x)) $4,
277                         pi_rules   = (1,[]),
278                         pi_deprecs = Nothing
279                     }
280            }
281
282 ifacebody :: { [RdrNameTyClDecl] }
283         :  '{'            ifacedecls '}'                { $2 }
284         |      layout_on  ifacedecls close              { $2 }
285
286 ifacedecls :: { [RdrNameTyClDecl] }
287         : ifacedecl ';' ifacedecls                      { $1 : $3 }
288         | ';' ifacedecls                                { $2 }
289         | ifacedecl                                     { [$1] }
290         | {- empty -}                                   { [] }
291
292 ifacedecl :: { RdrNameTyClDecl }
293         : srcloc 'data' tycl_hdr constrs 
294           { mkTyData DataType $3 (DataCons (reverse $4)) Nothing $1 }
295
296         | srcloc 'newtype' tycl_hdr '=' newconstr
297           { mkTyData NewType $3 (DataCons [$5]) Nothing $1 }
298
299         | srcloc 'class' tycl_hdr fds where
300                 { let 
301                         (binds,sigs) = cvMonoBindsAndSigs cvClassOpSig 
302                                         (groupBindings $5) 
303                    in
304                    mkClassDecl $3 $4 sigs (Just binds) $1 }
305
306         | srcloc 'type' tycon tv_bndrs '=' ctype        
307           { TySynonym $3 $4 $6 $1 }
308
309         | srcloc var '::' sigtype
310           { IfaceSig $2 $4 [] $1 }
311
312 -----------------------------------------------------------------------------
313 -- The Export List
314
315 maybeexports :: { Maybe [RdrNameIE] }
316         :  '(' exportlist ')'                   { Just $2 }
317         |  {- empty -}                          { Nothing }
318
319 exportlist :: { [RdrNameIE] }
320         :  exportlist ',' export                { $3 : $1 }
321         |  exportlist ','                       { $1 }
322         |  export                               { [$1]  }
323         |  {- empty -}                          { [] }
324
325    -- GHC extension: we allow things like [] and (,,,) to be exported
326 export  :: { RdrNameIE }
327         :  qvar                                 { IEVar $1 }
328         |  gtycon                               { IEThingAbs $1 }
329         |  gtycon '(' '..' ')'                  { IEThingAll $1 }
330         |  gtycon '(' ')'                       { IEThingWith $1 [] }
331         |  gtycon '(' qcnames ')'               { IEThingWith $1 (reverse $3) }
332         |  'module' modid                       { IEModuleContents $2 }
333
334 qcnames :: { [RdrName] }
335         :  qcnames ',' qcname                   { $3 : $1 }
336         |  qcname                               { [$1]  }
337
338 qcname  :: { RdrName }
339         :  qvar                                 { $1 }
340         |  gcon                                 { $1 }
341
342 -----------------------------------------------------------------------------
343 -- Import Declarations
344
345 -- import decls can be *empty*, or even just a string of semicolons
346 -- whereas topdecls must contain at least one topdecl.
347
348 importdecls :: { [RdrNameImportDecl] }
349         : importdecls ';' importdecl            { $3 : $1 }
350         | importdecls ';'                       { $1 }
351         | importdecl                            { [ $1 ] }
352         | {- empty -}                           { [] }
353
354 importdecl :: { RdrNameImportDecl }
355         : 'import' srcloc maybe_src optqualified modid maybeas maybeimpspec 
356                 { ImportDecl $5 $3 $4 $6 $7 $2 }
357
358 maybe_src :: { WhereFrom }
359         : '{-# SOURCE' '#-}'                    { ImportByUserSource }
360         | {- empty -}                           { ImportByUser }
361
362 optqualified :: { Bool }
363         : 'qualified'                           { True  }
364         | {- empty -}                           { False }
365
366 maybeas :: { Maybe ModuleName }
367         : 'as' modid                            { Just $2 }
368         | {- empty -}                           { Nothing }
369
370 maybeimpspec :: { Maybe (Bool, [RdrNameIE]) }
371         : impspec                               { Just $1 }
372         | {- empty -}                           { Nothing }
373
374 impspec :: { (Bool, [RdrNameIE]) }
375         :  '(' exportlist ')'                   { (False, reverse $2) }
376         |  'hiding' '(' exportlist ')'          { (True,  reverse $3) }
377
378 -----------------------------------------------------------------------------
379 -- Fixity Declarations
380
381 prec    :: { Int }
382         : {- empty -}                           { 9 }
383         | INTEGER                               {%  checkPrec $1 `thenP_`
384                                                     returnP (fromInteger $1) }
385
386 infix   :: { FixityDirection }
387         : 'infix'                               { InfixN  }
388         | 'infixl'                              { InfixL  }
389         | 'infixr'                              { InfixR }
390
391 ops     :: { [RdrName] }
392         : ops ',' op                            { $3 : $1 }
393         | op                                    { [$1] }
394
395 -----------------------------------------------------------------------------
396 -- Top-Level Declarations
397
398 topdecls :: { [RdrBinding] }
399         : topdecls ';' topdecl          { ($3 : $1) }
400         | topdecls ';'                  { $1 }
401         | topdecl                       { [$1] }
402
403 topdecl :: { RdrBinding }
404         : srcloc 'type' tycon tv_bndrs '=' ctype        
405                 -- Note ctype, not sigtype.
406                 -- We allow an explicit for-all but we don't insert one
407                 -- in   type Foo a = (b,b)
408                 -- Instead we just say b is out of scope
409                 { RdrHsDecl (TyClD (TySynonym $3 $4 $6 $1)) }
410
411
412         | srcloc 'data' tycl_hdr constrs deriving
413                 {% returnP (RdrHsDecl (TyClD
414                       (mkTyData DataType $3 (DataCons (reverse $4)) $5 $1))) }
415
416         | srcloc 'newtype' tycl_hdr '=' newconstr deriving
417                 {% returnP (RdrHsDecl (TyClD
418                       (mkTyData NewType $3 (DataCons [$5]) $6 $1))) }
419
420         | srcloc 'class' tycl_hdr fds where
421                 {% let 
422                         (binds,sigs) = cvMonoBindsAndSigs cvClassOpSig (groupBindings $5) 
423                    in
424                    returnP (RdrHsDecl (TyClD
425                       (mkClassDecl $3 $4 sigs (Just binds) $1))) }
426
427         | srcloc 'instance' inst_type where
428                 { let (binds,sigs) 
429                         = cvMonoBindsAndSigs cvInstDeclSig 
430                                 (groupBindings $4)
431                   in RdrHsDecl (InstD (InstDecl $3 binds sigs Nothing $1)) }
432
433         | srcloc 'default' '(' comma_types0 ')'         { RdrHsDecl (DefD (DefaultDecl $4 $1)) }
434         | 'foreign' fdecl                               { RdrHsDecl $2 }
435         | '{-# DEPRECATED' deprecations '#-}'           { $2 }
436         | '{-# RULES' rules '#-}'                       { $2 }
437         | decl                                          { $1 }
438
439 -- tycl_hdr parses the header of a type or class decl,
440 -- which takes the form
441 --      T a b
442 --      Eq a => T a
443 --      (Eq a, Ord b) => T a b
444 -- Rather a lot of inlining here, else we get reduce/reduce errors
445 tycl_hdr :: { (RdrNameContext, RdrName, [RdrNameHsTyVar]) }
446         : '(' comma_types1 ')' '=>' gtycon tv_bndrs
447                 {% mapP checkPred $2    `thenP` \ cxt ->
448                   returnP (cxt, $5, $6) }
449
450         | '(' ')' '=>' gtycon tv_bndrs
451                 { ([], $4, $5) }
452
453           -- qtycon for the class below name would lead to many s/r conflicts
454           --   FIXME: does the renamer pick up all wrong forms and raise an
455           --          error 
456         | gtycon atypes1 '=>' gtycon atypes0    
457                 {% checkTyVars $5       `thenP` \ tvs ->
458                    returnP ([HsClassP $1 $2], $4, tvs) }
459
460         | gtycon  atypes0
461                 {% checkTyVars $2       `thenP` \ tvs ->
462                    returnP ([], $1, tvs) }
463                 -- We have to have qtycon in this production to avoid s/r
464                 -- conflicts with the previous one.  The renamer will complain
465                 -- if we use a qualified tycon.
466                 --
467                 -- Using a `gtycon' throughout.  This enables special syntax,
468                 -- such as "[]" for tycons as well as tycon ops in
469                 -- parentheses.  This is beyond H98, but used repeatedly in
470                 -- the Prelude modules.  (So, it would be a good idea to raise
471                 -- an error in the renamer if some non-H98 form is used and
472                 -- -fglasgow-exts is not given.)  -=chak 
473
474 decls   :: { [RdrBinding] }
475         : decls ';' decl                { $3 : $1 }
476         | decls ';'                     { $1 }
477         | decl                          { [$1] }
478         | {- empty -}                   { [] }
479
480 decl    :: { RdrBinding }
481         : fixdecl                       { $1 }
482         | valdef                        { $1 }
483         | '{-# INLINE'   srcloc activation qvar '#-}'         { RdrSig (InlineSig True  $4 $3 $2) }
484         | '{-# NOINLINE' srcloc inverse_activation qvar '#-}' { RdrSig (InlineSig False $4 $3 $2) }
485         | '{-# SPECIALISE' srcloc qvar '::' sigtypes '#-}'
486                 { foldr1 RdrAndBindings 
487                     (map (\t -> RdrSig (SpecSig $3 t $2)) $5) }
488         | '{-# SPECIALISE' srcloc 'instance' inst_type '#-}'
489                 { RdrSig (SpecInstSig $4 $2) }
490
491 wherebinds :: { RdrNameHsBinds }
492         : where                 { cvBinds cvValSig (groupBindings $1) }
493
494 where   :: { [RdrBinding] }
495         : 'where' decllist              { $2 }
496         | {- empty -}                   { [] }
497
498 declbinds :: { RdrNameHsBinds }
499         : decllist                      { cvBinds cvValSig (groupBindings $1) }
500
501 decllist :: { [RdrBinding] }
502         : '{'            decls '}'      { $2 }
503         |     layout_on  decls close    { $2 }
504
505 fixdecl :: { RdrBinding }
506         : srcloc infix prec ops         { foldr1 RdrAndBindings
507                                             [ RdrSig (FixSig (FixitySig n 
508                                                             (Fixity $3 $2) $1))
509                                             | n <- $4 ] }
510
511 -----------------------------------------------------------------------------
512 -- Transformation Rules
513
514 rules   :: { RdrBinding }
515         :  rules ';' rule                       { $1 `RdrAndBindings` $3 }
516         |  rules ';'                            { $1 }
517         |  rule                                 { $1 }
518         |  {- empty -}                          { RdrNullBind }
519
520 rule    :: { RdrBinding }
521         : STRING activation rule_forall infixexp '=' srcloc exp
522              { RdrHsDecl (RuleD (HsRule $1 $2 $3 $4 $7 $6)) }
523
524 activation :: { Activation }           -- Omitted means AlwaysActive
525         : {- empty -}                           { AlwaysActive }
526         | explicit_activation                   { $1 }
527
528 inverse_activation :: { Activation }   -- Omitted means NeverActive
529         : {- empty -}                           { NeverActive }
530         | explicit_activation                   { $1 }
531
532 explicit_activation :: { Activation }  -- In brackets
533         : '[' INTEGER ']'                       { ActiveAfter  (fromInteger $2) }
534         | '[' '~' INTEGER ']'                   { ActiveBefore (fromInteger $3) }
535
536 rule_forall :: { [RdrNameRuleBndr] }
537         : 'forall' rule_var_list '.'            { $2 }
538         | {- empty -}                           { [] }
539
540 rule_var_list :: { [RdrNameRuleBndr] }
541         : rule_var                              { [$1] }
542         | rule_var rule_var_list                { $1 : $2 }
543
544 rule_var :: { RdrNameRuleBndr }
545         : varid                                 { RuleBndr $1 }
546         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
547
548 -----------------------------------------------------------------------------
549 -- Deprecations
550
551 deprecations :: { RdrBinding }
552         : deprecations ';' deprecation          { $1 `RdrAndBindings` $3 }
553         | deprecations ';'                      { $1 }
554         | deprecation                           { $1 }
555         | {- empty -}                           { RdrNullBind }
556
557 -- SUP: TEMPORARY HACK, not checking for `module Foo'
558 deprecation :: { RdrBinding }
559         : srcloc depreclist STRING
560                 { foldr RdrAndBindings RdrNullBind 
561                         [ RdrHsDecl (DeprecD (Deprecation n $3 $1)) | n <- $2 ] }
562
563
564 -----------------------------------------------------------------------------
565 -- Foreign import and export declarations
566
567 -- for the time being, the following accepts foreign declarations conforming
568 -- to the FFI Addendum, Version 1.0 as well as pre-standard declarations
569 --
570 -- * a flag indicates whether pre-standard declarations have been used and
571 --   triggers a deprecation warning further down the road
572 --
573 -- NB: The first two rules could be combined into one by replacing `safety1'
574 --     with `safety'.  However, the combined rule conflicts with the
575 --     DEPRECATED rules.
576 --
577 fdecl :: { RdrNameHsDecl }
578 fdecl : srcloc 'import' callconv safety1 fspec  {% mkImport $3 $4       $5 $1 }
579       | srcloc 'import' callconv         fspec  {% mkImport $3 (PlaySafe False) $4 $1 }
580       | srcloc 'export' callconv         fspec  {% mkExport $3          $4 $1 }
581         -- the following syntax is DEPRECATED
582       | srcloc fdecl1DEPRECATED                 { ForD ($2 True $1) }
583       | srcloc fdecl2DEPRECATED                 { $2 $1 }
584
585 fdecl1DEPRECATED :: { Bool -> SrcLoc -> ForeignDecl RdrName }
586 fdecl1DEPRECATED 
587   ----------- DEPRECATED label decls ------------
588   : 'label' ext_name varid '::' sigtype
589     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) _NIL_ _NIL_ 
590                                    (CLabel ($2 `orElse` mkExtName $3))) }
591
592   ----------- DEPRECATED ccall/stdcall decls ------------
593   --
594   -- NB: This business with the case expression below may seem overly
595   --     complicated, but it is necessary to avoid some conflicts.
596
597     -- DEPRECATED variant #1: lack of a calling convention specification
598     --                        (import) 
599   | 'import' {-no callconv-} ext_name safety varid_no_unsafe '::' sigtype
600     { let
601         target = StaticTarget ($2 `orElse` mkExtName $4)
602       in
603       ForeignImport $4 $6 (CImport defaultCCallConv $3 _NIL_ _NIL_ 
604                                    (CFunction target)) }
605
606     -- DEPRECATED variant #2: external name consists of two separate strings
607     --                        (module name and function name) (import)
608   | 'import' callconv STRING STRING safety varid_no_unsafe '::' sigtype
609     {% case $2 of
610          DNCall      -> parseError "Illegal format of .NET foreign import"
611          CCall cconv -> returnP $
612            let
613              imp = CFunction (StaticTarget $4)
614            in
615            ForeignImport $6 $8 (CImport cconv $5 _NIL_ _NIL_ imp) }
616
617     -- DEPRECATED variant #3: `unsafe' after entity
618   | 'import' callconv STRING 'unsafe' varid_no_unsafe '::' sigtype
619     {% case $2 of
620          DNCall      -> parseError "Illegal format of .NET foreign import"
621          CCall cconv -> returnP $
622            let
623              imp = CFunction (StaticTarget $3)
624            in
625            ForeignImport $5 $7 (CImport cconv PlayRisky _NIL_ _NIL_ imp) }
626
627     -- DEPRECATED variant #4: use of the special identifier `dynamic' without
628     --                        an explicit calling convention (import)
629   | 'import' {-no callconv-} 'dynamic' safety varid_no_unsafe '::' sigtype
630     { ForeignImport $4 $6 (CImport defaultCCallConv $3 _NIL_ _NIL_ 
631                                    (CFunction DynamicTarget)) }
632
633     -- DEPRECATED variant #5: use of the special identifier `dynamic' (import)
634   | 'import' callconv 'dynamic' safety varid_no_unsafe '::' sigtype
635     {% case $2 of
636          DNCall      -> parseError "Illegal format of .NET foreign import"
637          CCall cconv -> returnP $
638            ForeignImport $5 $7 (CImport cconv $4 _NIL_ _NIL_ 
639                                         (CFunction DynamicTarget)) }
640
641     -- DEPRECATED variant #6: lack of a calling convention specification
642     --                        (export) 
643   | 'export' {-no callconv-} ext_name varid '::' sigtype
644     { ForeignExport $3 $5 (CExport (CExportStatic ($2 `orElse` mkExtName $3) 
645                                    defaultCCallConv)) }
646
647     -- DEPRECATED variant #7: external name consists of two separate strings
648     --                        (module name and function name) (export)
649   | 'export' callconv STRING STRING varid '::' sigtype
650     {% case $2 of
651          DNCall      -> parseError "Illegal format of .NET foreign import"
652          CCall cconv -> returnP $
653            ForeignExport $5 $7 
654                          (CExport (CExportStatic $4 cconv)) }
655
656     -- DEPRECATED variant #8: use of the special identifier `dynamic' without
657     --                        an explicit calling convention (export)
658   | 'export' {-no callconv-} 'dynamic' varid '::' sigtype
659     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) _NIL_ _NIL_ 
660                                    CWrapper) }
661
662     -- DEPRECATED variant #9: use of the special identifier `dynamic' (export)
663   | 'export' callconv 'dynamic' varid '::' sigtype
664     {% case $2 of
665          DNCall      -> parseError "Illegal format of .NET foreign import"
666          CCall cconv -> returnP $
667            ForeignImport $4 $6 (CImport cconv (PlaySafe False) _NIL_ _NIL_ CWrapper) }
668
669   ----------- DEPRECATED .NET decls ------------
670   -- NB: removed the .NET call declaration, as it is entirely subsumed
671   --     by the new standard FFI declarations
672
673 fdecl2DEPRECATED :: { SrcLoc -> RdrNameHsDecl }
674 fdecl2DEPRECATED 
675   : 'import' 'dotnet' 'type' ext_name tycon
676           { \loc -> TyClD (ForeignType $5 $4 DNType loc) }
677     -- left this one unchanged for the moment as type imports are not
678     -- covered currently by the FFI standard -=chak
679
680
681 callconv :: { CallConv }
682           : 'stdcall'                   { CCall  StdCallConv }
683           | 'ccall'                     { CCall  CCallConv   }
684           | 'dotnet'                    { DNCall             }
685
686 safety :: { Safety }
687         : 'unsafe'                      { PlayRisky }
688         | 'safe'                        { PlaySafe False }
689         | 'threadsafe'                  { PlaySafe True  }
690         | {- empty -}                   { PlaySafe False }
691
692 safety1 :: { Safety }
693         : 'unsafe'                      { PlayRisky }
694         | 'safe'                        { PlaySafe  False }
695         | 'threadsafe'                  { PlaySafe  True }
696           -- only needed to avoid conflicts with the DEPRECATED rules
697
698 fspec :: { (FAST_STRING, RdrName, RdrNameHsType) }
699        : STRING varid '::' sigtype      { ($1      , $2, $4) }
700        |        varid '::' sigtype      { (SLIT(""), $1, $3) }
701          -- if the entity string is missing, it defaults to the empty string;
702          -- the meaning of an empty entity string depends on the calling
703          -- convention
704
705 -- DEPRECATED syntax
706 ext_name :: { Maybe CLabelString }
707         : STRING                { Just $1 }
708         | STRING STRING         { Just $2 }     -- Ignore "module name" for now
709         | {- empty -}           { Nothing }
710
711
712 -----------------------------------------------------------------------------
713 -- Type signatures
714
715 opt_sig :: { Maybe RdrNameHsType }
716         : {- empty -}                   { Nothing }
717         | '::' sigtype                  { Just $2 }
718
719 opt_asig :: { Maybe RdrNameHsType }
720         : {- empty -}                   { Nothing }
721         | '::' atype                    { Just $2 }
722
723 sigtypes :: { [RdrNameHsType] }
724         : sigtype                       { [ $1 ] }
725         | sigtypes ',' sigtype          { $3 : $1 }
726
727 sigtype :: { RdrNameHsType }
728         : ctype                         { mkHsForAllTy Nothing [] $1 }
729
730 sig_vars :: { [RdrName] }
731          : sig_vars ',' var             { $3 : $1 }
732          | var                          { [ $1 ] }
733
734 -----------------------------------------------------------------------------
735 -- Types
736
737 -- A ctype is a for-all type
738 ctype   :: { RdrNameHsType }
739         : 'forall' tv_bndrs '.' ctype   { mkHsForAllTy (Just $2) [] $4 }
740         | context '=>' type             { mkHsForAllTy Nothing   $1 $3 }
741         -- A type of form (context => type) is an *implicit* HsForAllTy
742         | type                          { $1 }
743
744 -- We parse a context as a btype so that we don't get reduce/reduce
745 -- errors in ctype.  The basic problem is that
746 --      (Eq a, Ord a)
747 -- looks so much like a tuple type.  We can't tell until we find the =>
748 context :: { RdrNameContext }
749         : btype                         {% checkContext $1 }
750
751 type :: { RdrNameHsType }
752         : gentype '->' type             { HsFunTy $1 $3 }
753         | ipvar '::' type               { mkHsIParamTy $1 $3 }
754         | gentype                       { $1 }
755
756 gentype :: { RdrNameHsType }
757         : btype                         { $1 }
758 -- Generics
759         | atype tyconop atype           { HsOpTy $1 $2 $3 }
760
761 btype :: { RdrNameHsType }
762         : btype atype                   { HsAppTy $1 $2 }
763         | atype                         { $1 }
764
765 atype :: { RdrNameHsType }
766         : gtycon                        { HsTyVar $1 }
767         | tyvar                         { HsTyVar $1 }
768         | '(' type ',' comma_types1 ')' { HsTupleTy (mkHsTupCon tcName Boxed  ($2:$4)) ($2:$4) }
769         | '(#' comma_types1 '#)'        { HsTupleTy (mkHsTupCon tcName Unboxed     $2) $2      }
770         | '[' type ']'                  { HsListTy $2 }
771         | '[:' type ':]'                { HsPArrTy $2 }
772         | '(' ctype ')'                 { $2 }
773         | '(' ctype '::' kind ')'       { HsKindSig $2 $4 }
774 -- Generics
775         | INTEGER                       { HsNumTy $1 }
776
777 -- An inst_type is what occurs in the head of an instance decl
778 --      e.g.  (Foo a, Gaz b) => Wibble a b
779 -- It's kept as a single type, with a MonoDictTy at the right
780 -- hand corner, for convenience.
781 inst_type :: { RdrNameHsType }
782         : ctype                         {% checkInstType $1 }
783
784 comma_types0  :: { [RdrNameHsType] }
785         : comma_types1                  { $1 }
786         | {- empty -}                   { [] }
787
788 comma_types1    :: { [RdrNameHsType] }
789         : type                          { [$1] }
790         | type  ',' comma_types1        { $1 : $3 }
791
792 atypes0 :: { [RdrNameHsType] }
793         : atypes1                       { $1 }
794         | {- empty -}                   { [] }
795
796 atypes1 :: { [RdrNameHsType] }
797         : atype                         { [$1] }
798         | atype atypes1                 { $1 : $2 }
799
800 tv_bndrs :: { [RdrNameHsTyVar] }
801          : tv_bndr tv_bndrs             { $1 : $2 }
802          | {- empty -}                  { [] }
803
804 tv_bndr :: { RdrNameHsTyVar }
805         : tyvar                         { UserTyVar $1 }
806         | '(' tyvar '::' kind ')'       { IfaceTyVar $2 $4 }
807
808 fds :: { [([RdrName], [RdrName])] }
809         : {- empty -}                   { [] }
810         | '|' fds1                      { reverse $2 }
811
812 fds1 :: { [([RdrName], [RdrName])] }
813         : fds1 ',' fd                   { $3 : $1 }
814         | fd                            { [$1] }
815
816 fd :: { ([RdrName], [RdrName]) }
817         : varids0 '->' varids0          { (reverse $1, reverse $3) }
818
819 varids0 :: { [RdrName] }
820         : {- empty -}                   { [] }
821         | varids0 tyvar                 { $2 : $1 }
822
823 -----------------------------------------------------------------------------
824 -- Kinds
825
826 kind    :: { Kind }
827         : akind                 { $1 }
828         | akind '->' kind       { mkArrowKind $1 $3 }
829
830 akind   :: { Kind }
831         : '*'                   { liftedTypeKind }
832         | '(' kind ')'          { $2 }
833
834
835 -----------------------------------------------------------------------------
836 -- Datatype declarations
837
838 newconstr :: { RdrNameConDecl }
839         : srcloc conid atype    { mkConDecl $2 [] [] (VanillaCon [unbangedType $3]) $1 }
840         | srcloc conid '{' var '::' ctype '}'
841                                 { mkConDecl $2 [] [] (RecCon [([$4], unbangedType $6)]) $1 }
842
843 constrs :: { [RdrNameConDecl] }
844         : {- empty; a GHC extension -}  { [] }
845         | '=' constrs1                  { $2 }
846
847 constrs1 :: { [RdrNameConDecl] }
848         : constrs1 '|' constr           { $3 : $1 }
849         | constr                        { [$1] }
850
851 constr :: { RdrNameConDecl }
852         : srcloc forall context '=>' constr_stuff
853                 { mkConDecl (fst $5) $2 $3 (snd $5) $1 }
854         | srcloc forall constr_stuff
855                 { mkConDecl (fst $3) $2 [] (snd $3) $1 }
856
857 forall :: { [RdrNameHsTyVar] }
858         : 'forall' tv_bndrs '.'         { $2 }
859         | {- empty -}                   { [] }
860
861 constr_stuff :: { (RdrName, RdrNameConDetails) }
862         : btype                         {% mkVanillaCon $1 []               }
863         | btype '!' atype satypes       {% mkVanillaCon $1 (BangType MarkedUserStrict $3 : $4) }
864         | gtycon '{' '}'                {% mkRecCon $1 [] }
865         | gtycon '{' fielddecls '}'     {% mkRecCon $1 $3 }
866         | sbtype conop sbtype           { ($2, InfixCon $1 $3) }
867
868 satypes :: { [RdrNameBangType] }
869         : atype satypes                 { unbangedType $1 : $2 }
870         | '!' atype satypes             { BangType MarkedUserStrict $2 : $3 }
871         | {- empty -}                   { [] }
872
873 sbtype :: { RdrNameBangType }
874         : btype                         { unbangedType $1 }
875         | '!' atype                     { BangType MarkedUserStrict $2 }
876
877 fielddecls :: { [([RdrName],RdrNameBangType)] }
878         : fielddecl ',' fielddecls      { $1 : $3 }
879         | fielddecl                     { [$1] }
880
881 fielddecl :: { ([RdrName],RdrNameBangType) }
882         : sig_vars '::' stype           { (reverse $1, $3) }
883
884 stype :: { RdrNameBangType }
885         : ctype                         { unbangedType $1 }
886         | '!' atype                     { BangType MarkedUserStrict $2 }
887
888 deriving :: { Maybe RdrNameContext }
889         : {- empty -}                   { Nothing }
890         | 'deriving' context            { Just $2 }
891              -- Glasgow extension: allow partial 
892              -- applications in derivings
893
894 -----------------------------------------------------------------------------
895 -- Value definitions
896
897 {- There's an awkward overlap with a type signature.  Consider
898         f :: Int -> Int = ...rhs...
899    Then we can't tell whether it's a type signature or a value
900    definition with a result signature until we see the '='.
901    So we have to inline enough to postpone reductions until we know.
902 -}
903
904 {-
905   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
906   instead of qvar, we get another shift/reduce-conflict. Consider the
907   following programs:
908   
909      { (^^) :: Int->Int ; }          Type signature; only var allowed
910
911      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
912                                      qvar allowed (because of instance decls)
913   
914   We can't tell whether to reduce var to qvar until after we've read the signatures.
915 -}
916
917 valdef :: { RdrBinding }
918         : infixexp srcloc opt_sig rhs           {% (checkValDef $1 $3 $4 $2) }
919         | infixexp srcloc '::' sigtype          {% (checkValSig $1 $4 $2) }
920         | var ',' sig_vars srcloc '::' sigtype  { foldr1 RdrAndBindings 
921                                                          [ RdrSig (Sig n $6 $4) | n <- $1:$3 ]
922                                                 }
923
924
925 rhs     :: { RdrNameGRHSs }
926         : '=' srcloc exp wherebinds     { (GRHSs (unguardedRHS $3 $2) $4 placeHolderType)}
927         | gdrhs wherebinds              { GRHSs (reverse $1) $2 placeHolderType }
928
929 gdrhs :: { [RdrNameGRHS] }
930         : gdrhs gdrh                    { $2 : $1 }
931         | gdrh                          { [$1] }
932
933 gdrh :: { RdrNameGRHS }
934         : '|' srcloc quals '=' exp      { GRHS (reverse (ResultStmt $5 $2 : $3)) $2 }
935
936 -----------------------------------------------------------------------------
937 -- Expressions
938
939 exp   :: { RdrNameHsExpr }
940         : infixexp '::' sigtype         { (ExprWithTySig $1 $3) }
941         | infixexp 'with' dbinding      { HsWith $1 $3 }
942         | infixexp                      { $1 }
943
944 infixexp :: { RdrNameHsExpr }
945         : exp10                         { $1 }
946         | infixexp qop exp10            { (OpApp $1 (HsVar $2) 
947                                                 (panic "fixity") $3 )}
948
949 exp10 :: { RdrNameHsExpr }
950         : '\\' srcloc aexp aexps opt_asig '->' srcloc exp       
951                         {% checkPatterns $2 ($3 : reverse $4) `thenP` \ ps -> 
952                            returnP (HsLam (Match ps $5 
953                                             (GRHSs (unguardedRHS $8 $7) 
954                                                    EmptyBinds placeHolderType))) }
955         | 'let' declbinds 'in' exp              { HsLet $2 $4 }
956         | 'if' srcloc exp 'then' exp 'else' exp { HsIf $3 $5 $7 $2 }
957         | 'case' srcloc exp 'of' altslist       { HsCase $3 $5 $2 }
958         | '-' fexp                              { mkHsNegApp $2 }
959         | srcloc 'do' stmtlist                  {% checkDo $3  `thenP` \ stmts ->
960                                                    returnP (HsDo DoExpr stmts $1) }
961
962         | '_ccall_'    ccallid aexps0           { HsCCall $2 $3 PlayRisky False placeHolderType }
963         | '_ccall_GC_' ccallid aexps0           { HsCCall $2 $3 (PlaySafe False) False placeHolderType }
964         | '_casm_'     CLITLIT aexps0           { HsCCall $2 $3 PlayRisky True  placeHolderType }
965         | '_casm_GC_'  CLITLIT aexps0           { HsCCall $2 $3 (PlaySafe False) True  placeHolderType }
966
967         | scc_annot exp                         { if opt_SccProfilingOn
968                                                         then HsSCC $1 $2
969                                                         else HsPar $2 }
970
971         | fexp                                  { $1 }
972
973 scc_annot :: { FAST_STRING }
974         : '_scc_' STRING                        { $2 }
975         | '{-# SCC' STRING '#-}'                { $2 }
976
977 ccallid :: { FAST_STRING }
978         :  VARID                                { $1 }
979         |  CONID                                { $1 }
980
981 fexp    :: { RdrNameHsExpr }
982         : fexp aexp                             { (HsApp $1 $2) }
983         | aexp                                  { $1 }
984
985 aexps0  :: { [RdrNameHsExpr] }
986         : aexps                                 { reverse $1 }
987
988 aexps   :: { [RdrNameHsExpr] }
989         : aexps aexp                            { $2 : $1 }
990         | {- empty -}                           { [] }
991
992 aexp    :: { RdrNameHsExpr }
993         : var_or_con '{|' gentype '|}'          { (HsApp $1 (HsType $3)) }
994         | aexp '{' fbinds '}'                   {% (mkRecConstrOrUpdate $1 
995                                                         (reverse $3)) }
996         | aexp1                                 { $1 }
997
998 var_or_con :: { RdrNameHsExpr }
999         : qvar                          { HsVar $1 }
1000         | gcon                          { HsVar $1 }
1001
1002 aexp1   :: { RdrNameHsExpr }
1003         : ipvar                         { HsIPVar $1 }
1004         | var_or_con                    { $1 }
1005         | literal                       { HsLit $1 }
1006         | INTEGER                       { HsOverLit (mkHsIntegral   $1) }
1007         | RATIONAL                      { HsOverLit (mkHsFractional $1) }
1008         | '(' exp ')'                   { HsPar $2 }
1009         | '(' exp ',' texps ')'         { ExplicitTuple ($2 : reverse $4) Boxed}
1010         | '(#' texps '#)'               { ExplicitTuple (reverse $2)      Unboxed }
1011         | '[' list ']'                  { $2 }
1012         | '[:' parr ':]'                { $2 }
1013         | '(' infixexp qop ')'          { (SectionL $2 (HsVar $3))  }
1014         | '(' qopm infixexp ')'         { (SectionR $2 $3) }
1015         | qvar '@' aexp                 { EAsPat $1 $3 }
1016         | '_'                           { EWildPat }
1017         | '~' aexp1                     { ELazyPat $2 }
1018
1019 texps :: { [RdrNameHsExpr] }
1020         : texps ',' exp                 { $3 : $1 }
1021         | exp                           { [$1] }
1022
1023
1024 -----------------------------------------------------------------------------
1025 -- List expressions
1026
1027 -- The rules below are little bit contorted to keep lexps left-recursive while
1028 -- avoiding another shift/reduce-conflict.
1029
1030 list :: { RdrNameHsExpr }
1031         : exp                           { ExplicitList placeHolderType [$1] }
1032         | lexps                         { ExplicitList placeHolderType (reverse $1) }
1033         | exp '..'                      { ArithSeqIn (From $1) }
1034         | exp ',' exp '..'              { ArithSeqIn (FromThen $1 $3) }
1035         | exp '..' exp                  { ArithSeqIn (FromTo $1 $3) }
1036         | exp ',' exp '..' exp          { ArithSeqIn (FromThenTo $1 $3 $5) }
1037         | exp srcloc pquals             {% let { body [qs] = qs;
1038                                                  body  qss = [ParStmt (map reverse qss)] }
1039                                            in
1040                                            returnP ( HsDo ListComp
1041                                                            (reverse (ResultStmt $1 $2 : body $3))
1042                                                            $2
1043                                                   )
1044                                         }
1045
1046 lexps :: { [RdrNameHsExpr] }
1047         : lexps ',' exp                 { $3 : $1 }
1048         | exp ',' exp                   { [$3,$1] }
1049
1050 -----------------------------------------------------------------------------
1051 -- List Comprehensions
1052
1053 pquals :: { [[RdrNameStmt]] }
1054         : pquals '|' quals              { $3 : $1 }
1055         | '|' quals                     { [$2] }
1056
1057 quals :: { [RdrNameStmt] }
1058         : quals ',' stmt                { $3 : $1 }
1059         | stmt                          { [$1] }
1060
1061 -----------------------------------------------------------------------------
1062 -- Parallel array expressions
1063
1064 -- The rules below are little bit contorted; see the list case for details.
1065 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1066 -- Moreover, we allow explicit arrays with no element (represented by the nil
1067 -- constructor in the list case).
1068
1069 parr :: { RdrNameHsExpr }
1070         :                               { ExplicitPArr placeHolderType [] }
1071         | exp                           { ExplicitPArr placeHolderType [$1] }
1072         | lexps                         { ExplicitPArr placeHolderType 
1073                                                        (reverse $1) }
1074         | exp '..' exp                  { PArrSeqIn (FromTo $1 $3) }
1075         | exp ',' exp '..' exp          { PArrSeqIn (FromThenTo $1 $3 $5) }
1076         | exp srcloc pquals             {% let {
1077                                              body [qs] = qs;
1078                                              body  qss = [ParStmt 
1079                                                            (map reverse qss)]}
1080                                            in
1081                                            returnP $ 
1082                                              HsDo PArrComp 
1083                                                   (reverse (ResultStmt $1 $2 
1084                                                             : body $3))
1085                                                   $2
1086                                         }
1087
1088 -- We are reusing `lexps' and `pquals' from the list case.
1089
1090 -----------------------------------------------------------------------------
1091 -- Case alternatives
1092
1093 altslist :: { [RdrNameMatch] }
1094         : '{'            alts '}'       { reverse $2 }
1095         |     layout_on  alts  close    { reverse $2 }
1096
1097 alts    :: { [RdrNameMatch] }
1098         : alts1                         { $1 }
1099         | ';' alts                      { $2 }
1100
1101 alts1   :: { [RdrNameMatch] }
1102         : alts1 ';' alt                 { $3 : $1 }
1103         | alts1 ';'                     { $1 }
1104         | alt                           { [$1] }
1105
1106 alt     :: { RdrNameMatch }
1107         : srcloc infixexp opt_sig ralt wherebinds
1108                                         {% (checkPattern $1 $2 `thenP` \p ->
1109                                            returnP (Match [p] $3
1110                                                      (GRHSs $4 $5 placeHolderType))  )}
1111
1112 ralt :: { [RdrNameGRHS] }
1113         : '->' srcloc exp               { [GRHS [ResultStmt $3 $2] $2] }
1114         | gdpats                        { reverse $1 }
1115
1116 gdpats :: { [RdrNameGRHS] }
1117         : gdpats gdpat                  { $2 : $1 }
1118         | gdpat                         { [$1] }
1119
1120 gdpat   :: { RdrNameGRHS }
1121         : srcloc '|' quals '->' exp     { GRHS (reverse (ResultStmt $5 $1:$3)) $1}
1122
1123 -----------------------------------------------------------------------------
1124 -- Statement sequences
1125
1126 stmtlist :: { [RdrNameStmt] }
1127         : '{'                   stmts '}'       { $2 }
1128         |     layout_on_for_do  stmts close     { $2 }
1129
1130 --      do { ;; s ; s ; ; s ;; }
1131 -- The last Stmt should be a ResultStmt, but that's hard to enforce
1132 -- here, because we need too much lookahead if we see do { e ; }
1133 -- So we use ExprStmts throughout, and switch the last one over
1134 -- in ParseUtils.checkDo instead
1135 stmts :: { [RdrNameStmt] }
1136         : stmt stmts_help               { $1 : $2 }
1137         | ';' stmts                     { $2 }
1138         | {- empty -}                   { [] }
1139
1140 stmts_help :: { [RdrNameStmt] }
1141         : ';' stmts                     { $2 }
1142         | {- empty -}                   { [] }
1143
1144 -- For typing stmts at the GHCi prompt, where 
1145 -- the input may consist of just comments.
1146 maybe_stmt :: { Maybe RdrNameStmt }
1147         : stmt                          { Just $1 }
1148         | {- nothing -}                 { Nothing }
1149
1150 stmt  :: { RdrNameStmt }
1151         : srcloc infixexp '<-' exp      {% checkPattern $1 $2 `thenP` \p ->
1152                                            returnP (BindStmt p $4 $1) }
1153         | srcloc exp                    { ExprStmt $2 placeHolderType $1 }
1154         | srcloc 'let' declbinds        { LetStmt $3 }
1155
1156 -----------------------------------------------------------------------------
1157 -- Record Field Update/Construction
1158
1159 fbinds  :: { RdrNameHsRecordBinds }
1160         : fbinds ',' fbind              { $3 : $1 }
1161         | fbinds ','                    { $1 }
1162         | fbind                         { [$1] }
1163         | {- empty -}                   { [] }
1164
1165 fbind   :: { (RdrName, RdrNameHsExpr, Bool) }
1166         : qvar '=' exp                  { ($1,$3,False) }
1167
1168 -----------------------------------------------------------------------------
1169 -- Implicit Parameter Bindings
1170
1171 dbinding :: { [(IPName RdrName, RdrNameHsExpr)] }
1172         : '{' dbinds '}'                { $2 }
1173         | layout_on dbinds close        { $2 }
1174
1175 dbinds  :: { [(IPName RdrName, RdrNameHsExpr)] }
1176         : dbinds ';' dbind              { $3 : $1 }
1177         | dbinds ';'                    { $1 }
1178         | dbind                         { [$1] }
1179         | {- empty -}                   { [] }
1180
1181 dbind   :: { (IPName RdrName, RdrNameHsExpr) }
1182 dbind   : ipvar '=' exp                 { ($1, $3) }
1183
1184 -----------------------------------------------------------------------------
1185 -- Variables, Constructors and Operators.
1186
1187 identifier :: { RdrName }
1188         : qvar                          { $1 }
1189         | gcon                          { $1 }
1190         | qop                           { $1 }
1191
1192 depreclist :: { [RdrName] }
1193 depreclist : deprec_var                 { [$1] }
1194            | deprec_var ',' depreclist  { $1 : $3 }
1195
1196 deprec_var :: { RdrName }
1197 deprec_var : var                        { $1 }
1198            | tycon                      { $1 }
1199
1200 gtycon  :: { RdrName }
1201         : qtycon                        { $1 }
1202         | '(' qtyconop ')'              { $2 }
1203         | '(' ')'                       { unitTyCon_RDR }
1204         | '(' '->' ')'                  { funTyCon_RDR }
1205         | '[' ']'                       { listTyCon_RDR }
1206         | '[:' ':]'                     { parrTyCon_RDR }
1207         | '(' commas ')'                { tupleTyCon_RDR $2 }
1208
1209 gcon    :: { RdrName }  -- Data constructor namespace
1210         : '(' ')'               { unitCon_RDR }
1211         | '[' ']'               { nilCon_RDR }
1212         | '(' commas ')'        { tupleCon_RDR $2 }
1213         | qcon                  { $1 }
1214 -- the case of '[:' ':]' is part of the production `parr'
1215
1216 var     :: { RdrName }
1217         : varid                 { $1 }
1218         | '(' varsym ')'        { $2 }
1219
1220 qvar    :: { RdrName }
1221         : qvarid                { $1 }
1222         | '(' varsym ')'        { $2 }
1223         | '(' qvarsym1 ')'      { $2 }
1224 -- We've inlined qvarsym here so that the decision about
1225 -- whether it's a qvar or a var can be postponed until
1226 -- *after* we see the close paren.
1227
1228 ipvar   :: { IPName RdrName }
1229         : IPDUPVARID            { Dupable (mkUnqual varName $1) }
1230         | IPSPLITVARID          { Linear  (mkUnqual varName $1) }
1231
1232 qcon    :: { RdrName }
1233         : qconid                { $1 }
1234         | '(' qconsym ')'       { $2 }
1235
1236 varop   :: { RdrName }
1237         : varsym                { $1 }
1238         | '`' varid '`'         { $2 }
1239
1240 qvarop :: { RdrName }
1241         : qvarsym               { $1 }
1242         | '`' qvarid '`'        { $2 }
1243
1244 qvaropm :: { RdrName }
1245         : qvarsym_no_minus      { $1 }
1246         | '`' qvarid '`'        { $2 }
1247
1248 conop :: { RdrName }
1249         : consym                { $1 }  
1250         | '`' conid '`'         { $2 }
1251
1252 qconop :: { RdrName }
1253         : qconsym               { $1 }
1254         | '`' qconid '`'        { $2 }
1255
1256 -----------------------------------------------------------------------------
1257 -- Any operator
1258
1259 op      :: { RdrName }   -- used in infix decls
1260         : varop                 { $1 }
1261         | conop                 { $1 }
1262
1263 qop     :: { RdrName {-HsExpr-} }   -- used in sections
1264         : qvarop                { $1 }
1265         | qconop                { $1 }
1266
1267 qopm    :: { RdrNameHsExpr }   -- used in sections
1268         : qvaropm               { HsVar $1 }
1269         | qconop                { HsVar $1 }
1270
1271 -----------------------------------------------------------------------------
1272 -- VarIds
1273
1274 qvarid :: { RdrName }
1275         : varid                 { $1 }
1276         | QVARID                { mkQual varName $1 }
1277
1278 varid :: { RdrName }
1279         : varid_no_unsafe       { $1 }
1280         | 'unsafe'              { mkUnqual varName FSLIT("unsafe") }
1281         | 'safe'                { mkUnqual varName FSLIT("safe") }
1282         | 'threadsafe'          { mkUnqual varName FSLIT("threadsafe") }
1283
1284 varid_no_unsafe :: { RdrName }
1285         : VARID                 { mkUnqual varName $1 }
1286         | special_id            { mkUnqual varName $1 }
1287         | 'forall'              { mkUnqual varName FSLIT("forall") }
1288
1289 tyvar   :: { RdrName }
1290         : VARID                 { mkUnqual tvName $1 }
1291         | special_id            { mkUnqual tvName $1 }
1292         | 'unsafe'              { mkUnqual tvName FSLIT("unsafe") }
1293         | 'safe'                { mkUnqual tvName FSLIT("safe") }
1294         | 'threadsafe'          { mkUnqual tvName FSLIT("threadsafe") }
1295
1296 -- These special_ids are treated as keywords in various places, 
1297 -- but as ordinary ids elsewhere.   'special_id' collects all these
1298 -- except 'unsafe' and 'forall' whose treatment differs depending on context
1299 special_id :: { UserFS }
1300 special_id
1301         : 'as'                  { FSLIT("as") }
1302         | 'qualified'           { FSLIT("qualified") }
1303         | 'hiding'              { FSLIT("hiding") }
1304         | 'export'              { FSLIT("export") }
1305         | 'label'               { FSLIT("label")  }
1306         | 'dynamic'             { FSLIT("dynamic") }
1307         | 'stdcall'             { FSLIT("stdcall") }
1308         | 'ccall'               { FSLIT("ccall") }
1309
1310 -----------------------------------------------------------------------------
1311 -- ConIds
1312
1313 qconid :: { RdrName }   -- Qualified or unqualifiedb
1314         : conid                 { $1 }
1315         | QCONID                { mkQual dataName $1 }
1316
1317 conid   :: { RdrName }
1318         : CONID                 { mkUnqual dataName $1 }
1319
1320 -----------------------------------------------------------------------------
1321 -- ConSyms
1322
1323 qconsym :: { RdrName }  -- Qualified or unqualifiedb
1324         : consym                { $1 }
1325         | QCONSYM               { mkQual dataName $1 }
1326
1327 consym :: { RdrName }
1328         : CONSYM                { mkUnqual dataName $1 }
1329
1330 -----------------------------------------------------------------------------
1331 -- VarSyms
1332
1333 qvarsym :: { RdrName }
1334         : varsym                { $1 }
1335         | qvarsym1              { $1 }
1336
1337 qvarsym_no_minus :: { RdrName }
1338         : varsym_no_minus       { $1 }
1339         | qvarsym1              { $1 }
1340
1341 qvarsym1 :: { RdrName }
1342 qvarsym1 : QVARSYM              { mkQual varName $1 }
1343
1344 varsym :: { RdrName }
1345         : varsym_no_minus       { $1 }
1346         | '-'                   { mkUnqual varName FSLIT("-") }
1347
1348 varsym_no_minus :: { RdrName } -- varsym not including '-'
1349         : VARSYM                { mkUnqual varName $1 }
1350         | special_sym           { mkUnqual varName $1 }
1351
1352
1353 -- See comments with special_id
1354 special_sym :: { UserFS }
1355 special_sym : '!'       { FSLIT("!") }
1356             | '.'       { FSLIT(".") }
1357             | '*'       { FSLIT("*") }
1358
1359 -----------------------------------------------------------------------------
1360 -- Literals
1361
1362 literal :: { HsLit }
1363         : CHAR                  { HsChar       $1 }
1364         | STRING                { HsString     $1 }
1365         | PRIMINTEGER           { HsIntPrim    $1 }
1366         | PRIMCHAR              { HsCharPrim   $1 }
1367         | PRIMSTRING            { HsStringPrim $1 }
1368         | PRIMFLOAT             { HsFloatPrim  $1 }
1369         | PRIMDOUBLE            { HsDoublePrim $1 }
1370         | CLITLIT               { HsLitLit     $1 placeHolderType }
1371
1372 srcloc :: { SrcLoc }    :       {% getSrcLocP }
1373  
1374 -----------------------------------------------------------------------------
1375 -- Layout
1376
1377 close :: { () }
1378         : vccurly               { () } -- context popped in lexer.
1379         | error                 {% popContext }
1380
1381 layout_on         :: { () }     : {% layoutOn True{-strict-} }
1382 layout_on_for_do  :: { () }     : {% layoutOn False }
1383
1384 -----------------------------------------------------------------------------
1385 -- Miscellaneous (mostly renamings)
1386
1387 modid   :: { ModuleName }
1388         : CONID                 { mkModuleNameFS $1 }
1389         | QCONID                { mkModuleNameFS
1390                                    (mkFastString
1391                                      (unpackFS (fst $1) ++ 
1392                                         '.':unpackFS (snd $1)))
1393                                 }
1394
1395 tycon   :: { RdrName }
1396         : CONID                 { mkUnqual tcClsName $1 }
1397
1398 tyconop :: { RdrName }
1399         : CONSYM                { mkUnqual tcClsName $1 }
1400
1401 qtycon :: { RdrName }   -- Qualified or unqualified
1402         : QCONID                { mkQual tcClsName $1 }
1403         | tycon                 { $1 }
1404
1405 qtyconop :: { RdrName } -- Qualified or unqualified
1406           : QCONSYM             { mkQual tcClsName $1 }
1407           | tyconop             { $1 }
1408
1409 commas :: { Int }
1410         : commas ','                    { $1 + 1 }
1411         | ','                           { 2 }
1412
1413 -----------------------------------------------------------------------------
1414
1415 {
1416 happyError :: P a
1417 happyError buf PState{ loc = loc } = PFailed (srcParseErr buf loc)
1418 }