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