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