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