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