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