[project @ 2002-10-11 08:48:13 by simonpj]
[ghc-hetmet.git] / ghc / compiler / parser / Parser.y
1 {-                                                              -*-haskell-*-
2 -----------------------------------------------------------------------------
3 $Id: Parser.y,v 1.109 2002/10/11 08:48:13 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 (reverse $2) }
417         | '{-# RULES' rules '#-}'                       { RdrBindings (reverse $2) }
418         | srcloc '$(' exp ')'                           { RdrHsDecl (SpliceD (SpliceDecl $3 $1)) }
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] }     -- Reversed
491         :  rules ';' rule                       { $3 : $1 }
492         |  rules ';'                            { $1 }
493         |  rule                                 { [$1] }
494         |  {- empty -}                          { [] }
495
496 rule    :: { RdrBinding }
497         : STRING activation rule_forall infixexp '=' srcloc exp
498              { RdrHsDecl (RuleD (HsRule $1 $2 $3 $4 $7 $6)) }
499
500 activation :: { Activation }           -- Omitted means AlwaysActive
501         : {- empty -}                           { AlwaysActive }
502         | explicit_activation                   { $1 }
503
504 inverse_activation :: { Activation }   -- Omitted means NeverActive
505         : {- empty -}                           { NeverActive }
506         | explicit_activation                   { $1 }
507
508 explicit_activation :: { Activation }  -- In brackets
509         : '[' INTEGER ']'                       { ActiveAfter  (fromInteger $2) }
510         | '[' '~' INTEGER ']'                   { ActiveBefore (fromInteger $3) }
511
512 rule_forall :: { [RdrNameRuleBndr] }
513         : 'forall' rule_var_list '.'            { $2 }
514         | {- empty -}                           { [] }
515
516 rule_var_list :: { [RdrNameRuleBndr] }
517         : rule_var                              { [$1] }
518         | rule_var rule_var_list                { $1 : $2 }
519
520 rule_var :: { RdrNameRuleBndr }
521         : varid                                 { RuleBndr $1 }
522         | '(' varid '::' ctype ')'              { RuleBndrSig $2 $4 }
523
524 -----------------------------------------------------------------------------
525 -- Deprecations (c.f. rules)
526
527 deprecations :: { [RdrBinding] }        -- Reversed
528         : deprecations ';' deprecation          { $3 : $1 }
529         | deprecations ';'                      { $1 }
530         | deprecation                           { [$1] }
531         | {- empty -}                           { [] }
532
533 -- SUP: TEMPORARY HACK, not checking for `module Foo'
534 deprecation :: { RdrBinding }
535         : srcloc depreclist STRING
536                 { RdrBindings
537                         [ RdrHsDecl (DeprecD (Deprecation n $3 $1)) | n <- $2 ] }
538
539
540 -----------------------------------------------------------------------------
541 -- Foreign import and export declarations
542
543 -- for the time being, the following accepts foreign declarations conforming
544 -- to the FFI Addendum, Version 1.0 as well as pre-standard declarations
545 --
546 -- * a flag indicates whether pre-standard declarations have been used and
547 --   triggers a deprecation warning further down the road
548 --
549 -- NB: The first two rules could be combined into one by replacing `safety1'
550 --     with `safety'.  However, the combined rule conflicts with the
551 --     DEPRECATED rules.
552 --
553 fdecl :: { RdrNameHsDecl }
554 fdecl : srcloc 'import' callconv safety1 fspec  {% mkImport $3 $4       $5 $1 }
555       | srcloc 'import' callconv         fspec  {% mkImport $3 (PlaySafe False) $4 $1 }
556       | srcloc 'export' callconv         fspec  {% mkExport $3          $4 $1 }
557         -- the following syntax is DEPRECATED
558       | srcloc fdecl1DEPRECATED                 { ForD ($2 True $1) }
559       | srcloc fdecl2DEPRECATED                 { $2 $1 }
560
561 fdecl1DEPRECATED :: { Bool -> SrcLoc -> ForeignDecl RdrName }
562 fdecl1DEPRECATED 
563   ----------- DEPRECATED label decls ------------
564   : 'label' ext_name varid '::' sigtype
565     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
566                                    (CLabel ($2 `orElse` mkExtName $3))) }
567
568   ----------- DEPRECATED ccall/stdcall decls ------------
569   --
570   -- NB: This business with the case expression below may seem overly
571   --     complicated, but it is necessary to avoid some conflicts.
572
573     -- DEPRECATED variant #1: lack of a calling convention specification
574     --                        (import) 
575   | 'import' {-no callconv-} ext_name safety varid_no_unsafe '::' sigtype
576     { let
577         target = StaticTarget ($2 `orElse` mkExtName $4)
578       in
579       ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
580                                    (CFunction target)) }
581
582     -- DEPRECATED variant #2: external name consists of two separate strings
583     --                        (module name and function name) (import)
584   | 'import' callconv STRING STRING safety varid_no_unsafe '::' sigtype
585     {% case $2 of
586          DNCall      -> parseError "Illegal format of .NET foreign import"
587          CCall cconv -> returnP $
588            let
589              imp = CFunction (StaticTarget $4)
590            in
591            ForeignImport $6 $8 (CImport cconv $5 nilFS nilFS imp) }
592
593     -- DEPRECATED variant #3: `unsafe' after entity
594   | 'import' callconv STRING 'unsafe' varid_no_unsafe '::' sigtype
595     {% case $2 of
596          DNCall      -> parseError "Illegal format of .NET foreign import"
597          CCall cconv -> returnP $
598            let
599              imp = CFunction (StaticTarget $3)
600            in
601            ForeignImport $5 $7 (CImport cconv PlayRisky nilFS nilFS imp) }
602
603     -- DEPRECATED variant #4: use of the special identifier `dynamic' without
604     --                        an explicit calling convention (import)
605   | 'import' {-no callconv-} 'dynamic' safety varid_no_unsafe '::' sigtype
606     { ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
607                                    (CFunction DynamicTarget)) }
608
609     -- DEPRECATED variant #5: use of the special identifier `dynamic' (import)
610   | 'import' callconv 'dynamic' safety varid_no_unsafe '::' sigtype
611     {% case $2 of
612          DNCall      -> parseError "Illegal format of .NET foreign import"
613          CCall cconv -> returnP $
614            ForeignImport $5 $7 (CImport cconv $4 nilFS nilFS 
615                                         (CFunction DynamicTarget)) }
616
617     -- DEPRECATED variant #6: lack of a calling convention specification
618     --                        (export) 
619   | 'export' {-no callconv-} ext_name varid '::' sigtype
620     { ForeignExport $3 $5 (CExport (CExportStatic ($2 `orElse` mkExtName $3) 
621                                    defaultCCallConv)) }
622
623     -- DEPRECATED variant #7: external name consists of two separate strings
624     --                        (module name and function name) (export)
625   | 'export' callconv STRING STRING varid '::' sigtype
626     {% case $2 of
627          DNCall      -> parseError "Illegal format of .NET foreign import"
628          CCall cconv -> returnP $
629            ForeignExport $5 $7 
630                          (CExport (CExportStatic $4 cconv)) }
631
632     -- DEPRECATED variant #8: use of the special identifier `dynamic' without
633     --                        an explicit calling convention (export)
634   | 'export' {-no callconv-} 'dynamic' varid '::' sigtype
635     { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
636                                    CWrapper) }
637
638     -- DEPRECATED variant #9: use of the special identifier `dynamic' (export)
639   | 'export' callconv 'dynamic' varid '::' sigtype
640     {% case $2 of
641          DNCall      -> parseError "Illegal format of .NET foreign import"
642          CCall cconv -> returnP $
643            ForeignImport $4 $6 (CImport cconv (PlaySafe False) nilFS nilFS CWrapper) }
644
645   ----------- DEPRECATED .NET decls ------------
646   -- NB: removed the .NET call declaration, as it is entirely subsumed
647   --     by the new standard FFI declarations
648
649 fdecl2DEPRECATED :: { SrcLoc -> RdrNameHsDecl }
650 fdecl2DEPRECATED 
651   : 'import' 'dotnet' 'type' ext_name tycon
652           { \loc -> TyClD (ForeignType $5 $4 DNType loc) }
653     -- left this one unchanged for the moment as type imports are not
654     -- covered currently by the FFI standard -=chak
655
656
657 callconv :: { CallConv }
658           : 'stdcall'                   { CCall  StdCallConv }
659           | 'ccall'                     { CCall  CCallConv   }
660           | 'dotnet'                    { DNCall             }
661
662 safety :: { Safety }
663         : 'unsafe'                      { PlayRisky }
664         | 'safe'                        { PlaySafe False }
665         | 'threadsafe'                  { PlaySafe True  }
666         | {- empty -}                   { PlaySafe False }
667
668 safety1 :: { Safety }
669         : 'unsafe'                      { PlayRisky }
670         | 'safe'                        { PlaySafe  False }
671         | 'threadsafe'                  { PlaySafe  True }
672           -- only needed to avoid conflicts with the DEPRECATED rules
673
674 fspec :: { (FastString, RdrName, RdrNameHsType) }
675        : STRING var '::' sigtype      { ($1      , $2, $4) }
676        |        var '::' sigtype      { (nilFS, $1, $3) }
677          -- if the entity string is missing, it defaults to the empty string;
678          -- the meaning of an empty entity string depends on the calling
679          -- convention
680
681 -- DEPRECATED syntax
682 ext_name :: { Maybe CLabelString }
683         : STRING                { Just $1 }
684         | STRING STRING         { Just $2 }     -- Ignore "module name" for now
685         | {- empty -}           { Nothing }
686
687
688 -----------------------------------------------------------------------------
689 -- Type signatures
690
691 opt_sig :: { Maybe RdrNameHsType }
692         : {- empty -}                   { Nothing }
693         | '::' sigtype                  { Just $2 }
694
695 opt_asig :: { Maybe RdrNameHsType }
696         : {- empty -}                   { Nothing }
697         | '::' atype                    { Just $2 }
698
699 sigtypes :: { [RdrNameHsType] }
700         : sigtype                       { [ $1 ] }
701         | sigtypes ',' sigtype          { $3 : $1 }
702
703 sigtype :: { RdrNameHsType }
704         : ctype                         { mkHsForAllTy Nothing [] $1 }
705
706 sig_vars :: { [RdrName] }
707          : sig_vars ',' var             { $3 : $1 }
708          | var                          { [ $1 ] }
709
710 -----------------------------------------------------------------------------
711 -- Types
712
713 -- A ctype is a for-all type
714 ctype   :: { RdrNameHsType }
715         : 'forall' tv_bndrs '.' ctype   { mkHsForAllTy (Just $2) [] $4 }
716         | context '=>' type             { mkHsForAllTy Nothing   $1 $3 }
717         -- A type of form (context => type) is an *implicit* HsForAllTy
718         | type                          { $1 }
719
720 -- We parse a context as a btype so that we don't get reduce/reduce
721 -- errors in ctype.  The basic problem is that
722 --      (Eq a, Ord a)
723 -- looks so much like a tuple type.  We can't tell until we find the =>
724 context :: { RdrNameContext }
725         : btype                         {% checkContext $1 }
726
727 type :: { RdrNameHsType }
728         : ipvar '::' gentype            { mkHsIParamTy $1 $3 }
729         | gentype                       { $1 }
730
731 gentype :: { RdrNameHsType }
732         : btype                         { $1 }
733         | btype qtyconop gentype        { HsOpTy $1 (HsTyOp $2) $3 }
734         | btype  '`' tyvar '`' gentype  { HsOpTy $1 (HsTyOp $3) $5 }
735         | btype '->' gentype            { HsOpTy $1 HsArrow $3 }
736
737 btype :: { RdrNameHsType }
738         : btype atype                   { HsAppTy $1 $2 }
739         | atype                         { $1 }
740
741 atype :: { RdrNameHsType }
742         : gtycon                        { HsTyVar $1 }
743         | tyvar                         { HsTyVar $1 }
744         | '(' type ',' comma_types1 ')' { HsTupleTy (mkHsTupCon tcName Boxed  ($2:$4)) ($2:$4) }
745         | '(#' comma_types1 '#)'        { HsTupleTy (mkHsTupCon tcName Unboxed     $2) $2      }
746         | '[' type ']'                  { HsListTy  $2 }
747         | '[:' type ':]'                { HsPArrTy  $2 }
748         | '(' ctype ')'                 { HsParTy   $2 }
749         | '(' ctype '::' kind ')'       { HsKindSig $2 $4 }
750 -- Generics
751         | INTEGER                       { HsNumTy $1 }
752
753 -- An inst_type is what occurs in the head of an instance decl
754 --      e.g.  (Foo a, Gaz b) => Wibble a b
755 -- It's kept as a single type, with a MonoDictTy at the right
756 -- hand corner, for convenience.
757 inst_type :: { RdrNameHsType }
758         : ctype                         {% checkInstType $1 }
759
760 comma_types0  :: { [RdrNameHsType] }
761         : comma_types1                  { $1 }
762         | {- empty -}                   { [] }
763
764 comma_types1    :: { [RdrNameHsType] }
765         : type                          { [$1] }
766         | type  ',' comma_types1        { $1 : $3 }
767
768 tv_bndrs :: { [RdrNameHsTyVar] }
769          : tv_bndr tv_bndrs             { $1 : $2 }
770          | {- empty -}                  { [] }
771
772 tv_bndr :: { RdrNameHsTyVar }
773         : tyvar                         { UserTyVar $1 }
774         | '(' tyvar '::' kind ')'       { IfaceTyVar $2 $4 }
775
776 fds :: { [([RdrName], [RdrName])] }
777         : {- empty -}                   { [] }
778         | '|' fds1                      { reverse $2 }
779
780 fds1 :: { [([RdrName], [RdrName])] }
781         : fds1 ',' fd                   { $3 : $1 }
782         | fd                            { [$1] }
783
784 fd :: { ([RdrName], [RdrName]) }
785         : varids0 '->' varids0          { (reverse $1, reverse $3) }
786
787 varids0 :: { [RdrName] }
788         : {- empty -}                   { [] }
789         | varids0 tyvar                 { $2 : $1 }
790
791 -----------------------------------------------------------------------------
792 -- Kinds
793
794 kind    :: { Kind }
795         : akind                 { $1 }
796         | akind '->' kind       { mkArrowKind $1 $3 }
797
798 akind   :: { Kind }
799         : '*'                   { liftedTypeKind }
800         | '(' kind ')'          { $2 }
801
802
803 -----------------------------------------------------------------------------
804 -- Datatype declarations
805
806 newconstr :: { RdrNameConDecl }
807         : srcloc conid atype    { ConDecl $2 [] [] (PrefixCon [unbangedType $3]) $1 }
808         | srcloc conid '{' var '::' ctype '}'
809                                 { ConDecl $2 [] [] (RecCon [($4, unbangedType $6)]) $1 }
810
811 constrs :: { [RdrNameConDecl] }
812         : {- empty; a GHC extension -}  { [] }
813         | '=' constrs1                  { $2 }
814
815 constrs1 :: { [RdrNameConDecl] }
816         : constrs1 '|' constr           { $3 : $1 }
817         | constr                        { [$1] }
818
819 constr :: { RdrNameConDecl }
820         : srcloc forall context '=>' constr_stuff
821                 { ConDecl (fst $5) $2 $3 (snd $5) $1 }
822         | srcloc forall constr_stuff
823                 { ConDecl (fst $3) $2 [] (snd $3) $1 }
824
825 forall :: { [RdrNameHsTyVar] }
826         : 'forall' tv_bndrs '.'         { $2 }
827         | {- empty -}                   { [] }
828
829 constr_stuff :: { (RdrName, RdrNameConDetails) }
830         : btype                         {% mkPrefixCon $1 [] }
831         | btype '!' atype satypes       {% mkPrefixCon $1 (BangType MarkedUserStrict $3 : $4) }
832         | oqtycon '{' '}'               {% mkRecCon $1 [] }
833         | oqtycon '{' fielddecls '}'    {% mkRecCon $1 $3 }
834         | sbtype conop sbtype           { ($2, InfixCon $1 $3) }
835
836 satypes :: { [RdrNameBangType] }
837         : atype satypes                 { unbangedType $1 : $2 }
838         | '!' atype satypes             { BangType MarkedUserStrict $2 : $3 }
839         | {- empty -}                   { [] }
840
841 sbtype :: { RdrNameBangType }
842         : btype                         { unbangedType $1 }
843         | '!' atype                     { BangType MarkedUserStrict $2 }
844
845 fielddecls :: { [([RdrName],RdrNameBangType)] }
846         : fielddecl ',' fielddecls      { $1 : $3 }
847         | fielddecl                     { [$1] }
848
849 fielddecl :: { ([RdrName],RdrNameBangType) }
850         : sig_vars '::' stype           { (reverse $1, $3) }
851
852 stype :: { RdrNameBangType }
853         : ctype                         { unbangedType $1 }
854         | '!' atype                     { BangType MarkedUserStrict $2 }
855
856 deriving :: { Maybe RdrNameContext }
857         : {- empty -}                   { Nothing }
858         | 'deriving' context            { Just $2 }
859              -- Glasgow extension: allow partial 
860              -- applications in derivings
861
862 -----------------------------------------------------------------------------
863 -- Value definitions
864
865 {- There's an awkward overlap with a type signature.  Consider
866         f :: Int -> Int = ...rhs...
867    Then we can't tell whether it's a type signature or a value
868    definition with a result signature until we see the '='.
869    So we have to inline enough to postpone reductions until we know.
870 -}
871
872 {-
873   ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
874   instead of qvar, we get another shift/reduce-conflict. Consider the
875   following programs:
876   
877      { (^^) :: Int->Int ; }          Type signature; only var allowed
878
879      { (^^) :: Int->Int = ... ; }    Value defn with result signature;
880                                      qvar allowed (because of instance decls)
881   
882   We can't tell whether to reduce var to qvar until after we've read the signatures.
883 -}
884
885 decl    :: { RdrBinding }
886         : sigdecl                       { $1 }
887         | infixexp srcloc opt_sig rhs   {% checkValDef $1 $3 $4 $2 }
888
889 rhs     :: { RdrNameGRHSs }
890         : '=' srcloc exp wherebinds     { GRHSs (unguardedRHS $3 $2) $4 placeHolderType }
891         | gdrhs wherebinds              { GRHSs (reverse $1)         $2 placeHolderType }
892
893 gdrhs :: { [RdrNameGRHS] }
894         : gdrhs gdrh                    { $2 : $1 }
895         | gdrh                          { [$1] }
896
897 gdrh :: { RdrNameGRHS }
898         : '|' srcloc quals '=' exp      { GRHS (reverse (ResultStmt $5 $2 : $3)) $2 }
899
900 sigdecl :: { RdrBinding }
901         : infixexp srcloc '::' sigtype          
902                                 {% checkValSig $1 $4 $2 }
903                 -- See the above notes for why we need infixexp here
904         | var ',' sig_vars srcloc '::' sigtype  
905                                 { mkSigDecls [ Sig n $6 $4 | n <- $1:$3 ] }
906         | srcloc infix prec ops { mkSigDecls [ FixSig (FixitySig n (Fixity $3 $2) $1)
907                                              | n <- $4 ] }
908         | '{-# INLINE'   srcloc activation qvar '#-}'         
909                                 { RdrHsDecl (SigD (InlineSig True  $4 $3 $2)) }
910         | '{-# NOINLINE' srcloc inverse_activation qvar '#-}' 
911                                 { RdrHsDecl (SigD (InlineSig False $4 $3 $2)) }
912         | '{-# SPECIALISE' srcloc qvar '::' sigtypes '#-}'
913                                 { mkSigDecls  [ SpecSig $3 t $2 | t <- $5] }
914         | '{-# SPECIALISE' srcloc 'instance' inst_type '#-}'
915                                 { RdrHsDecl (SigD (SpecInstSig $4 $2)) }
916
917 -----------------------------------------------------------------------------
918 -- Expressions
919
920 exp   :: { RdrNameHsExpr }
921         : infixexp '::' sigtype         { ExprWithTySig $1 $3 }
922         | infixexp 'with' dbinding      { HsWith $1 $3 True{-not a let-} }
923         | infixexp                      { $1 }
924
925 infixexp :: { RdrNameHsExpr }
926         : exp10                         { $1 }
927         | infixexp qop exp10            { (OpApp $1 (HsVar $2) 
928                                                 (panic "fixity") $3 )}
929
930 exp10 :: { RdrNameHsExpr }
931         : '\\' srcloc aexp aexps opt_asig '->' srcloc exp       
932                         {% checkPatterns $2 ($3 : reverse $4) `thenP` \ ps -> 
933                            returnP (HsLam (Match ps $5 
934                                             (GRHSs (unguardedRHS $8 $7) 
935                                                    EmptyBinds placeHolderType))) }
936         | 'let' letbinds 'in' exp               { $2 $4 }
937         | 'if' srcloc exp 'then' exp 'else' exp { HsIf $3 $5 $7 $2 }
938         | 'case' srcloc exp 'of' altslist       { HsCase $3 $5 $2 }
939         | '-' fexp                              { mkHsNegApp $2 }
940         | srcloc 'do' stmtlist                  {% checkDo $3  `thenP` \ stmts ->
941                                                    returnP (mkHsDo DoExpr stmts $1) }
942         | srcloc 'mdo' stmtlist                 {% checkMDo $3  `thenP` \ stmts ->
943                                                    returnP (mkHsDo MDoExpr stmts $1) }
944
945         | '_ccall_'    ccallid aexps0           { HsCCall $2 $3 PlayRisky False placeHolderType }
946         | '_ccall_GC_' ccallid aexps0           { HsCCall $2 $3 (PlaySafe False) False placeHolderType }
947         | '_casm_'     CLITLIT aexps0           { HsCCall $2 $3 PlayRisky True  placeHolderType }
948         | '_casm_GC_'  CLITLIT aexps0           { HsCCall $2 $3 (PlaySafe False) True  placeHolderType }
949
950         | scc_annot exp                         { if opt_SccProfilingOn
951                                                         then HsSCC $1 $2
952                                                         else HsPar $2 }
953
954         | fexp                                  { $1 }
955
956 scc_annot :: { FastString }
957         : '_scc_' STRING                        { $2 }
958         | '{-# SCC' STRING '#-}'                { $2 }
959
960 ccallid :: { FastString }
961         :  VARID                                { $1 }
962         |  CONID                                { $1 }
963
964 fexp    :: { RdrNameHsExpr }
965         : fexp aexp                             { (HsApp $1 $2) }
966         | aexp                                  { $1 }
967
968 aexps0  :: { [RdrNameHsExpr] }
969         : aexps                                 { reverse $1 }
970
971 aexps   :: { [RdrNameHsExpr] }
972         : aexps aexp                            { $2 : $1 }
973         | {- empty -}                           { [] }
974
975 aexp    :: { RdrNameHsExpr }
976         : qvar '@' aexp                 { EAsPat $1 $3 }
977         | '~' aexp                      { ELazyPat $2 }
978         | aexp1                         { $1 }
979
980 aexp1   :: { RdrNameHsExpr }
981         : aexp1 '{' fbinds '}'          {% (mkRecConstrOrUpdate $1 (reverse $3)) }
982         | aexp2                         { $1 }
983
984 -- Here was the syntax for type applications that I was planning
985 -- but there are difficulties (e.g. what order for type args)
986 -- so it's not enabled yet.
987         | qcname '{|' gentype '|}'          { (HsApp (HsVar $1) (HsType $3)) }
988
989 aexp2   :: { RdrNameHsExpr }
990         : ipvar                         { HsIPVar $1 }
991         | qcname                        { HsVar $1 }
992         | literal                       { HsLit $1 }
993         | INTEGER                       { HsOverLit (mkHsIntegral   $1) }
994         | RATIONAL                      { HsOverLit (mkHsFractional $1) }
995         | '(' exp ')'                   { HsPar $2 }
996         | '(' exp ',' texps ')'         { ExplicitTuple ($2 : reverse $4) Boxed}
997         | '(#' texps '#)'               { ExplicitTuple (reverse $2)      Unboxed }
998         | '[' list ']'                  { $2 }
999         | '[:' parr ':]'                { $2 }
1000         | '(' infixexp qop ')'          { (SectionL $2 (HsVar $3))  }
1001         | '(' qopm infixexp ')'         { (SectionR $2 $3) }
1002         | '_'                           { EWildPat }
1003         
1004         -- MetaHaskell Extension
1005         | srcloc ID_SPLICE              { mkHsSplice (HsVar (mkUnqual varName $2)) $1 }  -- $x
1006         | srcloc '$(' exp ')'           { mkHsSplice $3 $1 }                             -- $( exp )
1007         | srcloc '[|' exp '|]'          { HsBracket (ExpBr $3) $1 }                       
1008         | srcloc '[t|' ctype '|]'       { HsBracket (TypBr $3) $1 }                       
1009         | srcloc '[p|' infixexp '|]'    {% checkPattern $1 $3 `thenP` \p ->
1010                                            returnP (HsBracket (PatBr p) $1) }
1011         | srcloc '[d|' cvtopdecls '|]'  { HsBracket (DecBr (mkGroup $3)) $1 }
1012
1013
1014 texps :: { [RdrNameHsExpr] }
1015         : texps ',' exp                 { $3 : $1 }
1016         | exp                           { [$1] }
1017
1018
1019 -----------------------------------------------------------------------------
1020 -- List expressions
1021
1022 -- The rules below are little bit contorted to keep lexps left-recursive while
1023 -- avoiding another shift/reduce-conflict.
1024
1025 list :: { RdrNameHsExpr }
1026         : exp                           { ExplicitList placeHolderType [$1] }
1027         | lexps                         { ExplicitList placeHolderType (reverse $1) }
1028         | exp '..'                      { ArithSeqIn (From $1) }
1029         | exp ',' exp '..'              { ArithSeqIn (FromThen $1 $3) }
1030         | exp '..' exp                  { ArithSeqIn (FromTo $1 $3) }
1031         | exp ',' exp '..' exp          { ArithSeqIn (FromThenTo $1 $3 $5) }
1032         | exp srcloc pquals             {% let { body [qs] = qs;
1033                                                  body  qss = [ParStmt (map reverse qss)] }
1034                                            in
1035                                            returnP ( mkHsDo ListComp
1036                                                             (reverse (ResultStmt $1 $2 : body $3))
1037                                                             $2
1038                                                   )
1039                                         }
1040
1041 lexps :: { [RdrNameHsExpr] }
1042         : lexps ',' exp                 { $3 : $1 }
1043         | exp ',' exp                   { [$3,$1] }
1044
1045 -----------------------------------------------------------------------------
1046 -- List Comprehensions
1047
1048 pquals :: { [[RdrNameStmt]] }
1049         : pquals '|' quals              { $3 : $1 }
1050         | '|' quals                     { [$2] }
1051
1052 quals :: { [RdrNameStmt] }
1053         : quals ',' stmt                { $3 : $1 }
1054         | stmt                          { [$1] }
1055
1056 -----------------------------------------------------------------------------
1057 -- Parallel array expressions
1058
1059 -- The rules below are little bit contorted; see the list case for details.
1060 -- Note that, in contrast to lists, we only have finite arithmetic sequences.
1061 -- Moreover, we allow explicit arrays with no element (represented by the nil
1062 -- constructor in the list case).
1063
1064 parr :: { RdrNameHsExpr }
1065         :                               { ExplicitPArr placeHolderType [] }
1066         | exp                           { ExplicitPArr placeHolderType [$1] }
1067         | lexps                         { ExplicitPArr placeHolderType 
1068                                                        (reverse $1) }
1069         | exp '..' exp                  { PArrSeqIn (FromTo $1 $3) }
1070         | exp ',' exp '..' exp          { PArrSeqIn (FromThenTo $1 $3 $5) }
1071         | exp srcloc pquals             {% let {
1072                                              body [qs] = qs;
1073                                              body  qss = [ParStmt 
1074                                                            (map reverse qss)]}
1075                                            in
1076                                            returnP $ 
1077                                              mkHsDo PArrComp 
1078                                                     (reverse (ResultStmt $1 $2 
1079                                                              : body $3))
1080                                                     $2
1081                                         }
1082
1083 -- We are reusing `lexps' and `pquals' from the list case.
1084
1085 -----------------------------------------------------------------------------
1086 -- Case alternatives
1087
1088 altslist :: { [RdrNameMatch] }
1089         : '{'            alts '}'       { reverse $2 }
1090         |     layout_on  alts  close    { reverse $2 }
1091
1092 alts    :: { [RdrNameMatch] }
1093         : alts1                         { $1 }
1094         | ';' alts                      { $2 }
1095
1096 alts1   :: { [RdrNameMatch] }
1097         : alts1 ';' alt                 { $3 : $1 }
1098         | alts1 ';'                     { $1 }
1099         | alt                           { [$1] }
1100
1101 alt     :: { RdrNameMatch }
1102         : srcloc infixexp opt_sig ralt wherebinds
1103                                         {% (checkPattern $1 $2 `thenP` \p ->
1104                                            returnP (Match [p] $3
1105                                                      (GRHSs $4 $5 placeHolderType))  )}
1106
1107 ralt :: { [RdrNameGRHS] }
1108         : '->' srcloc exp               { [GRHS [ResultStmt $3 $2] $2] }
1109         | gdpats                        { reverse $1 }
1110
1111 gdpats :: { [RdrNameGRHS] }
1112         : gdpats gdpat                  { $2 : $1 }
1113         | gdpat                         { [$1] }
1114
1115 gdpat   :: { RdrNameGRHS }
1116         : srcloc '|' quals '->' exp     { GRHS (reverse (ResultStmt $5 $1:$3)) $1}
1117
1118 -----------------------------------------------------------------------------
1119 -- Statement sequences
1120
1121 stmtlist :: { [RdrNameStmt] }
1122         : '{'                   stmts '}'       { $2 }
1123         |     layout_on_for_do  stmts close     { $2 }
1124
1125 --      do { ;; s ; s ; ; s ;; }
1126 -- The last Stmt should be a ResultStmt, but that's hard to enforce
1127 -- here, because we need too much lookahead if we see do { e ; }
1128 -- So we use ExprStmts throughout, and switch the last one over
1129 -- in ParseUtils.checkDo instead
1130 stmts :: { [RdrNameStmt] }
1131         : stmt stmts_help               { $1 : $2 }
1132         | ';' stmts                     { $2 }
1133         | {- empty -}                   { [] }
1134
1135 stmts_help :: { [RdrNameStmt] }
1136         : ';' stmts                     { $2 }
1137         | {- empty -}                   { [] }
1138
1139 -- For typing stmts at the GHCi prompt, where 
1140 -- the input may consist of just comments.
1141 maybe_stmt :: { Maybe RdrNameStmt }
1142         : stmt                          { Just $1 }
1143         | {- nothing -}                 { Nothing }
1144
1145 stmt  :: { RdrNameStmt }
1146         : srcloc infixexp '<-' exp      {% checkPattern $1 $2 `thenP` \p ->
1147                                            returnP (BindStmt p $4 $1) }
1148         | srcloc exp                    { ExprStmt $2 placeHolderType $1 }
1149         | srcloc 'let' decllist         { LetStmt (cvBinds $3) }
1150
1151 -----------------------------------------------------------------------------
1152 -- Record Field Update/Construction
1153
1154 fbinds  :: { RdrNameHsRecordBinds }
1155         : fbinds ',' fbind              { $3 : $1 }
1156         | fbinds ','                    { $1 }
1157         | fbind                         { [$1] }
1158         | {- empty -}                   { [] }
1159
1160 fbind   :: { (RdrName, RdrNameHsExpr) }
1161         : qvar '=' exp                  { ($1,$3) }
1162
1163 -----------------------------------------------------------------------------
1164 -- Implicit Parameter Bindings
1165
1166 dbinding :: { [(IPName RdrName, RdrNameHsExpr)] }
1167         : '{' dbinds '}'                { $2 }
1168         | layout_on dbinds close        { $2 }
1169
1170 dbinds  :: { [(IPName RdrName, RdrNameHsExpr)] }
1171         : dbinds ';' dbind              { $3 : $1 }
1172         | dbinds ';'                    { $1 }
1173         | dbind                         { [$1] }
1174 --      | {- empty -}                   { [] }
1175
1176 dbind   :: { (IPName RdrName, RdrNameHsExpr) }
1177 dbind   : ipvar '=' exp                 { ($1, $3) }
1178
1179 -----------------------------------------------------------------------------
1180 -- Variables, Constructors and Operators.
1181
1182 identifier :: { RdrName }
1183         : qvar                          { $1 }
1184         | gcon                          { $1 }
1185         | qop                           { $1 }
1186
1187 depreclist :: { [RdrName] }
1188 depreclist : deprec_var                 { [$1] }
1189            | deprec_var ',' depreclist  { $1 : $3 }
1190
1191 deprec_var :: { RdrName }
1192 deprec_var : var                        { $1 }
1193            | tycon                      { $1 }
1194
1195 gcon    :: { RdrName }  -- Data constructor namespace
1196         : sysdcon               { $1 }
1197         | qcon                  { $1 }
1198 -- the case of '[:' ':]' is part of the production `parr'
1199
1200 sysdcon :: { RdrName }  -- Data constructor namespace
1201         : '(' ')'               { getRdrName unitDataCon }
1202         | '(' commas ')'        { getRdrName (tupleCon Boxed $2) }
1203         | '[' ']'               { nameRdrName nilDataConName }
1204
1205 var     :: { RdrName }
1206         : varid                 { $1 }
1207         | '(' varsym ')'        { $2 }
1208
1209 qvar    :: { RdrName }
1210         : qvarid                { $1 }
1211         | '(' varsym ')'        { $2 }
1212         | '(' qvarsym1 ')'      { $2 }
1213 -- We've inlined qvarsym here so that the decision about
1214 -- whether it's a qvar or a var can be postponed until
1215 -- *after* we see the close paren.
1216
1217 ipvar   :: { IPName RdrName }
1218         : IPDUPVARID            { Dupable (mkUnqual varName $1) }
1219         | IPSPLITVARID          { Linear  (mkUnqual varName $1) }
1220
1221 qcon    :: { RdrName }
1222         : qconid                { $1 }
1223         | '(' qconsym ')'       { $2 }
1224
1225 varop   :: { RdrName }
1226         : varsym                { $1 }
1227         | '`' varid '`'         { $2 }
1228
1229 qvarop :: { RdrName }
1230         : qvarsym               { $1 }
1231         | '`' qvarid '`'        { $2 }
1232
1233 qvaropm :: { RdrName }
1234         : qvarsym_no_minus      { $1 }
1235         | '`' qvarid '`'        { $2 }
1236
1237 conop :: { RdrName }
1238         : consym                { $1 }  
1239         | '`' conid '`'         { $2 }
1240
1241 qconop :: { RdrName }
1242         : qconsym               { $1 }
1243         | '`' qconid '`'        { $2 }
1244
1245 -----------------------------------------------------------------------------
1246 -- Type constructors
1247
1248 gtycon  :: { RdrName }  -- A "general" qualified tycon
1249         : oqtycon                       { $1 }
1250         | '(' ')'                       { getRdrName unitTyCon }
1251         | '(' commas ')'                { getRdrName (tupleTyCon Boxed $2) }
1252         | '(' '->' ')'                  { nameRdrName funTyConName }
1253         | '[' ']'                       { nameRdrName listTyConName }
1254         | '[:' ':]'                     { nameRdrName parrTyConName }
1255
1256 oqtycon :: { RdrName }  -- An "ordinary" qualified tycon
1257         : qtycon                        { $1 }
1258         | '(' qtyconsym ')'             { $2 }
1259
1260 qtyconop :: { RdrName } -- Qualified or unqualified
1261         : qtyconsym                     { $1 }
1262         | '`' qtycon '`'                { $2 }
1263
1264 tyconop :: { RdrName }  -- Unqualified
1265         : tyconsym                      { $1 }
1266         | '`' tycon '`'                 { $2 }
1267
1268 qtycon :: { RdrName }   -- Qualified or unqualified
1269         : QCONID                        { mkQual tcClsName $1 }
1270         | tycon                         { $1 }
1271
1272 tycon   :: { RdrName }  -- Unqualified
1273         : CONID                         { mkUnqual tcClsName $1 }
1274
1275 qtyconsym :: { RdrName }
1276         : QCONSYM                       { mkQual tcClsName $1 }
1277         | tyconsym                      { $1 }
1278
1279 tyconsym :: { RdrName }
1280         : CONSYM                        { mkUnqual tcClsName $1 }
1281
1282 -----------------------------------------------------------------------------
1283 -- Any operator
1284
1285 op      :: { RdrName }   -- used in infix decls
1286         : varop                 { $1 }
1287         | conop                 { $1 }
1288
1289 qop     :: { RdrName {-HsExpr-} }   -- used in sections
1290         : qvarop                { $1 }
1291         | qconop                { $1 }
1292
1293 qopm    :: { RdrNameHsExpr }   -- used in sections
1294         : qvaropm               { HsVar $1 }
1295         | qconop                { HsVar $1 }
1296
1297 -----------------------------------------------------------------------------
1298 -- VarIds
1299
1300 qvarid :: { RdrName }
1301         : varid                 { $1 }
1302         | QVARID                { mkQual varName $1 }
1303
1304 varid :: { RdrName }
1305         : varid_no_unsafe       { $1 }
1306         | 'unsafe'              { mkUnqual varName FSLIT("unsafe") }
1307         | 'safe'                { mkUnqual varName FSLIT("safe") }
1308         | 'threadsafe'          { mkUnqual varName FSLIT("threadsafe") }
1309
1310 varid_no_unsafe :: { RdrName }
1311         : VARID                 { mkUnqual varName $1 }
1312         | special_id            { mkUnqual varName $1 }
1313         | 'forall'              { mkUnqual varName FSLIT("forall") }
1314
1315 tyvar   :: { RdrName }
1316         : VARID                 { mkUnqual tvName $1 }
1317         | special_id            { mkUnqual tvName $1 }
1318         | 'unsafe'              { mkUnqual tvName FSLIT("unsafe") }
1319         | 'safe'                { mkUnqual tvName FSLIT("safe") }
1320         | 'threadsafe'          { mkUnqual tvName FSLIT("threadsafe") }
1321
1322 -- These special_ids are treated as keywords in various places, 
1323 -- but as ordinary ids elsewhere.   'special_id' collects all these
1324 -- except 'unsafe' and 'forall' whose treatment differs depending on context
1325 special_id :: { UserFS }
1326 special_id
1327         : 'as'                  { FSLIT("as") }
1328         | 'qualified'           { FSLIT("qualified") }
1329         | 'hiding'              { FSLIT("hiding") }
1330         | 'export'              { FSLIT("export") }
1331         | 'label'               { FSLIT("label")  }
1332         | 'dynamic'             { FSLIT("dynamic") }
1333         | 'stdcall'             { FSLIT("stdcall") }
1334         | 'ccall'               { FSLIT("ccall") }
1335
1336 -----------------------------------------------------------------------------
1337 -- Variables 
1338
1339 qvarsym :: { RdrName }
1340         : varsym                { $1 }
1341         | qvarsym1              { $1 }
1342
1343 qvarsym_no_minus :: { RdrName }
1344         : varsym_no_minus       { $1 }
1345         | qvarsym1              { $1 }
1346
1347 qvarsym1 :: { RdrName }
1348 qvarsym1 : QVARSYM              { mkQual varName $1 }
1349
1350 varsym :: { RdrName }
1351         : varsym_no_minus       { $1 }
1352         | '-'                   { mkUnqual varName FSLIT("-") }
1353
1354 varsym_no_minus :: { RdrName } -- varsym not including '-'
1355         : VARSYM                { mkUnqual varName $1 }
1356         | special_sym           { mkUnqual varName $1 }
1357
1358
1359 -- See comments with special_id
1360 special_sym :: { UserFS }
1361 special_sym : '!'       { FSLIT("!") }
1362             | '.'       { FSLIT(".") }
1363             | '*'       { FSLIT("*") }
1364
1365 -----------------------------------------------------------------------------
1366 -- Data constructors
1367
1368 qconid :: { RdrName }   -- Qualified or unqualifiedb
1369         : conid                 { $1 }
1370         | QCONID                { mkQual dataName $1 }
1371
1372 conid   :: { RdrName }
1373         : CONID                 { mkUnqual dataName $1 }
1374
1375 qconsym :: { RdrName }  -- Qualified or unqualified
1376         : consym                { $1 }
1377         | QCONSYM               { mkQual dataName $1 }
1378
1379 consym :: { RdrName }
1380         : CONSYM                { mkUnqual dataName $1 }
1381         | ':'                   { nameRdrName consDataConName }
1382         -- ':' means only list cons
1383
1384
1385 -----------------------------------------------------------------------------
1386 -- Literals
1387
1388 literal :: { HsLit }
1389         : CHAR                  { HsChar       $1 }
1390         | STRING                { HsString     $1 }
1391         | PRIMINTEGER           { HsIntPrim    $1 }
1392         | PRIMCHAR              { HsCharPrim   $1 }
1393         | PRIMSTRING            { HsStringPrim $1 }
1394         | PRIMFLOAT             { HsFloatPrim  $1 }
1395         | PRIMDOUBLE            { HsDoublePrim $1 }
1396         | CLITLIT               { HsLitLit     $1 placeHolderType }
1397
1398 srcloc :: { SrcLoc }    :       {% getSrcLocP }
1399  
1400 -----------------------------------------------------------------------------
1401 -- Layout
1402
1403 close :: { () }
1404         : vccurly               { () } -- context popped in lexer.
1405         | error                 {% popContext }
1406
1407 layout_on         :: { () }     : {% layoutOn True{-strict-} }
1408 layout_on_for_do  :: { () }     : {% layoutOn False }
1409
1410 -----------------------------------------------------------------------------
1411 -- Miscellaneous (mostly renamings)
1412
1413 modid   :: { ModuleName }
1414         : CONID                 { mkModuleNameFS $1 }
1415         | QCONID                { mkModuleNameFS
1416                                    (mkFastString
1417                                      (unpackFS (fst $1) ++ 
1418                                         '.':unpackFS (snd $1)))
1419                                 }
1420
1421 commas :: { Int }
1422         : commas ','                    { $1 + 1 }
1423         | ','                           { 2 }
1424
1425 -----------------------------------------------------------------------------
1426
1427 {
1428 happyError :: P a
1429 happyError buf PState{ loc = loc } = PFailed (srcParseErr buf loc)
1430 }