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