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