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