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