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