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