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