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