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