Parser.y 44.7 KB
Newer Older
chak's avatar
chak committed
1
{-								-*-haskell-*-
2
-----------------------------------------------------------------------------
3
$Id: Parser.y,v 1.119 2003/06/23 10:35:22 simonpj Exp $
4 5 6 7 8 9 10 11

Haskell grammar.

Author(s): Simon Marlow, Sven Panne 1997, 1998, 1999
-----------------------------------------------------------------------------
-}

{
12
module Parser ( parseModule, parseStmt, parseIdentifier, parseIface ) where
13

14 15
#include "HsVersions.h"

16
import HsSyn
17
import HsTypes		( mkHsTupCon )
18 19

import RdrHsSyn
20
import HscTypes		( ParsedIface(..), IsBootInterface, noDependencies )
21 22
import Lex
import RdrName
23
import PrelNames	( mAIN_Name, funTyConName, listTyConName, 
24 25
			  parrTyConName, consDataConName )
import TysWiredIn	( unitTyCon, unitDataCon, tupleTyCon, tupleCon, nilDataCon )
26
import ForeignCall	( Safety(..), CExportSpec(..), 
27
			  CCallConv(..), CCallTarget(..), defaultCCallConv,
28
			)
29
import OccName		( UserFS, varName, tcName, dataName, tcClsName, tvName )
30
import TyCon		( DataConDetails(..) )
31
import DataCon		( DataCon, dataConName )
32 33
import SrcLoc		( SrcLoc )
import Module
34
import CmdLineOpts	( opt_SccProfilingOn, opt_InPackage )
35
import Type		( Kind, mkArrowKind, liftedTypeKind )
36
import BasicTypes	( Boxity(..), Fixity(..), FixityDirection(..), IPName(..),
37 38
			  NewOrData(..), StrictnessMark(..), Activation(..),
			  FixitySig(..) )
39 40
import Panic

41
import GLAEXTS
42
import CStrings		( CLabelString )
43
import FastString
44
import Maybes		( orElse )
45
import Outputable
46 47 48 49 50

}

{-
-----------------------------------------------------------------------------
51
Conflicts: 29 shift/reduce, [SDM 19/9/2002]
52

53
10 for abiguity in 'if x then y else z + 1'		[State 136]
54
	(shift parses as 'if x then y else (z + 1)', as per longest-parse rule)
55
	10 because op might be: : - ! * . `x` VARSYM CONSYM QVARSYM QCONSYM
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
1 for ambiguity in 'if x then y else z with ?x=3' 	[State 136]
	(shift parses as 'if x then y else (z with ?x=3)'

1 for ambiguity in 'if x then y else z :: T'		[State 136]
	(shift parses as 'if x then y else (z :: T)', as per longest-parse rule)

8 for ambiguity in 'e :: a `b` c'.  Does this mean 	[States 160,246]
	(e::a) `b` c, or 
	(e :: (a `b` c))

1 for ambiguity in 'let ?x ...'				[State 268]
	the parser can't tell whether the ?x is the lhs of a normal binding or
	an implicit binding.  Fortunately resolving as shift gives it the only
	sensible meaning, namely the lhs of an implicit binding.

1 for ambiguity in '{-# RULES "name" [ ... #-}		[State 332]
73 74 75 76
	we don't know whether the '[' starts the activation or not: it
  	might be the start of the declaration with the activation being
	empty.  --SDM 1/4/2002

77
1 for ambiguity in '{-# RULES "name" forall = ... #-}' 	[State 394]
78 79 80 81 82 83 84
	since 'forall' is a valid variable name, we don't know whether
	to treat a forall on the input as the beginning of a quantifier
	or the beginning of the rule itself.  Resolving to shift means
	it's always treated as a quantifier, hence the above is disallowed.
	This saves explicitly defining a grammar for the rule lhs that
	doesn't include 'forall'.

85 86 87
6 for conflicts between `fdecl' and `fdeclDEPRECATED', 	[States 384,385]
  	which are resolved correctly, and moreover, 
  	should go away when `fdeclDEPRECATED' is removed.
chak's avatar
chak committed
88

89 90 91 92 93
-----------------------------------------------------------------------------
-}

%token
 '_'            { ITunderscore }		-- Haskell keywords
94
 'as' 		{ ITas }
95 96 97 98 99 100 101
 'case' 	{ ITcase }  	
 'class' 	{ ITclass } 
 'data' 	{ ITdata } 
 'default' 	{ ITdefault }
 'deriving' 	{ ITderiving }
 'do' 		{ ITdo }
 'else' 	{ ITelse }
102
 'hiding' 	{ IThiding }
103 104 105 106 107 108 109 110 111 112 113
 'if' 		{ ITif }
 'import' 	{ ITimport }
 'in' 		{ ITin }
 'infix' 	{ ITinfix }
 'infixl' 	{ ITinfixl }
 'infixr' 	{ ITinfixr }
 'instance' 	{ ITinstance }
 'let' 		{ ITlet }
 'module' 	{ ITmodule }
 'newtype' 	{ ITnewtype }
 'of' 		{ ITof }
114
 'qualified' 	{ ITqualified }
115 116 117
 'then' 	{ ITthen }
 'type' 	{ ITtype }
 'where' 	{ ITwhere }
118
 '_scc_'	{ ITscc }	      -- ToDo: remove
119 120 121 122 123 124

 'forall'	{ ITforall }			-- GHC extension keywords
 'foreign'	{ ITforeign }
 'export'	{ ITexport }
 'label'	{ ITlabel } 
 'dynamic'	{ ITdynamic }
chak's avatar
chak committed
125
 'safe'		{ ITsafe }
sof's avatar
sof committed
126
 'threadsafe'	{ ITthreadsafe }
127
 'unsafe'	{ ITunsafe }
128
 'with' 	{ ITwith }
129
 'mdo'		{ ITmdo }
sof's avatar
sof committed
130 131
 'stdcall'      { ITstdcallconv }
 'ccall'        { ITccallconv }
132
 'dotnet'       { ITdotnet }
133
 '_ccall_'	{ ITccall (False, False, PlayRisky) }
sof's avatar
sof committed
134
 '_ccall_GC_'	{ ITccall (False, False, PlaySafe False) }
135
 '_casm_'	{ ITccall (False, True,  PlayRisky) }
sof's avatar
sof committed
136
 '_casm_GC_'	{ ITccall (False, True,  PlaySafe False) }
137 138 139 140 141 142

 '{-# SPECIALISE'  { ITspecialise_prag }
 '{-# SOURCE'	   { ITsource_prag }
 '{-# INLINE'      { ITinline_prag }
 '{-# NOINLINE'    { ITnoinline_prag }
 '{-# RULES'	   { ITrules_prag }
143
 '{-# CORE'        { ITcore_prag }              -- hdaume: annotated core
144
 '{-# SCC'	   { ITscc_prag }
145
 '{-# DEPRECATED'  { ITdeprecated_prag }
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
 '#-}'		   { ITclose_prag }

{-
 '__interface'	{ ITinterface }			-- interface keywords
 '__export'	{ IT__export }
 '__instimport'	{ ITinstimport }
 '__forall'	{ IT__forall }
 '__letrec'	{ ITletrec }
 '__coerce'	{ ITcoerce }
 '__depends'	{ ITdepends }
 '__inline'	{ ITinline }
 '__DEFAULT'	{ ITdefaultbranch }
 '__bot'	{ ITbottom }
 '__integer'	{ ITinteger_lit }
 '__float'	{ ITfloat_lit }
 '__rational'	{ ITrational_lit }
 '__addr'	{ ITaddr_lit }
163
 '__label'	{ ITlabel_lit }
164 165 166
 '__litlit'	{ ITlit_lit }
 '__string'	{ ITstring_lit }
 '__ccall'	{ ITccall $$ }
167
 '__scc' 	{ IT__scc }
168 169 170 171 172
 '__sccC'       { ITsccAllCafs }

 '__A'		{ ITarity }
 '__P'		{ ITspecialise }
 '__C'		{ ITnocaf }
173
 '__U'		{ ITunfold }
174 175 176 177 178
 '__S'		{ ITstrict $$ }
 '__M'		{ ITcprinfo $$ }
-}

 '..'		{ ITdotdot }  			-- reserved symbols
179
 ':'		{ ITcolon }
180 181 182 183 184 185 186 187 188 189 190
 '::'		{ ITdcolon }
 '='		{ ITequal }
 '\\'		{ ITlam }
 '|'		{ ITvbar }
 '<-'		{ ITlarrow }
 '->'		{ ITrarrow }
 '@'		{ ITat }
 '~'		{ ITtilde }
 '=>'		{ ITdarrow }
 '-'		{ ITminus }
 '!'		{ ITbang }
191
 '*'		{ ITstar }
192 193 194 195
 '.'		{ ITdot }

 '{'		{ ITocurly } 			-- special symbols
 '}'		{ ITccurly }
196 197
 '{|'           { ITocurlybar }
 '|}'           { ITccurlybar }
198 199 200
 vccurly	{ ITvccurly } -- virtual close curly (from layout)
 '['		{ ITobrack }
 ']'		{ ITcbrack }
chak's avatar
chak committed
201 202
 '[:'		{ ITopabrack }
 ':]'		{ ITcpabrack }
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
 '('		{ IToparen }
 ')'		{ ITcparen }
 '(#'		{ IToubxparen }
 '#)'		{ ITcubxparen }
 ';'		{ ITsemi }
 ','		{ ITcomma }
 '`'		{ ITbackquote }

 VARID   	{ ITvarid    $$ }		-- identifiers
 CONID   	{ ITconid    $$ }
 VARSYM  	{ ITvarsym   $$ }
 CONSYM  	{ ITconsym   $$ }
 QVARID  	{ ITqvarid   $$ }
 QCONID  	{ ITqconid   $$ }
 QVARSYM 	{ ITqvarsym  $$ }
 QCONSYM 	{ ITqconsym  $$ }
219

220 221
 IPDUPVARID   	{ ITdupipvarid   $$ }		-- GHC extension
 IPSPLITVARID  	{ ITsplitipvarid $$ }		-- GHC extension
222 223 224 225 226 227 228 229 230 231

 CHAR		{ ITchar     $$ }
 STRING		{ ITstring   $$ }
 INTEGER	{ ITinteger  $$ }
 RATIONAL	{ ITrational $$ }

 PRIMCHAR	{ ITprimchar   $$ }
 PRIMSTRING	{ ITprimstring $$ }
 PRIMINTEGER	{ ITprimint    $$ }
 PRIMFLOAT	{ ITprimfloat  $$ }
232
 PRIMDOUBLE	{ ITprimdouble $$ }
233
 CLITLIT	{ ITlitlit     $$ }
234 235 236 237 238 239 240
 
-- Template Haskell
'[|'            { ITopenExpQuote  }       
'[p|'           { ITopenPatQuote  }      
'[t|'           { ITopenTypQuote  }      
'[d|'           { ITopenDecQuote  }      
'|]'            { ITcloseQuote    }
241 242 243 244 245
ID_SPLICE       { ITidEscape $$   }     -- $x
'$('	        { ITparenEscape   }     -- $( exp )
REIFY_TYPE	{ ITreifyType }	
REIFY_DECL	{ ITreifyDecl }	
REIFY_FIXITY	{ ITreifyFixity }
246 247 248

%monad { P } { thenP } { returnP }
%lexer { lexer } { ITeof }
249
%name parseModule module
250
%name parseStmt   maybe_stmt
251
%name parseIdentifier  identifier
252
%name parseIface iface
253 254 255 256 257 258
%tokentype { Token }
%%

-----------------------------------------------------------------------------
-- Module Header

259 260 261 262 263 264 265
-- The place for module deprecation is really too restrictive, but if it
-- was allowed at its natural place just before 'module', we get an ugly
-- s/r conflict with the second alternative. Another solution would be the
-- introduction of a new pragma DEPRECATED_MODULE, but this is not very nice,
-- either, and DEPRECATED is only expected to be used by people who really
-- know what they are doing. :-)

266
module 	:: { RdrNameHsModule }
267
 	: srcloc 'module' modid maybemoddeprec maybeexports 'where' body 
268
		{ HsModule (Just (mkHomeModule $3)) $5 (fst $7) (snd $7) $4 $1 }
269
	| srcloc body
270
		{ HsModule Nothing Nothing (fst $2) (snd $2) Nothing $1 }
271

272 273
maybemoddeprec :: { Maybe DeprecTxt }
	: '{-# DEPRECATED' STRING '#-}' 	{ Just $2 }
274
	|  {- empty -}				{ Nothing }
275 276 277 278 279 280

body 	:: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
	:  '{'            top '}'		{ $2 }
 	|      layout_on  top close		{ $2 }

top 	:: { ([RdrNameImportDecl], [RdrNameHsDecl]) }
281 282
	: importdecls				{ (reverse $1,[]) }
	| importdecls ';' cvtopdecls		{ (reverse $1,$3) }
283 284 285
	| cvtopdecls				{ ([],$1) }

cvtopdecls :: { [RdrNameHsDecl] }
286
	: topdecls			{ cvTopDecls $1 }
287

288 289 290 291 292 293 294 295 296 297 298
-----------------------------------------------------------------------------
-- Interfaces (.hi-boot files)

iface   :: { ParsedIface }
	: 'module' modid 'where' ifacebody
	  {	    ParsedIface {
			pi_mod     = $2,
			pi_pkg     = opt_InPackage,
			pi_vers    = 1, 		-- Module version
			pi_orphan  = False,
			pi_exports = (1,[($2,mkIfaceExports $4)]),
299
			pi_deps    = noDependencies,
300 301 302 303 304 305 306 307 308 309 310 311 312 313
			pi_usages  = [],
			pi_fixity  = [],
			pi_insts   = [],
			pi_decls   = map (\x -> (1,x)) $4,
		 	pi_rules   = (1,[]),
		 	pi_deprecs = Nothing
	   	    }
	   }

ifacebody :: { [RdrNameTyClDecl] }
	:  '{'            ifacedecls '}'		{ $2 }
 	|      layout_on  ifacedecls close		{ $2 }

ifacedecls :: { [RdrNameTyClDecl] }
314 315 316 317
	: ifacedecl ';' ifacedecls	{ $1 : $3 }
	| ';' ifacedecls		{ $2 }
	| ifacedecl			{ [$1] }
	| {- empty -}			{ [] }
318 319

ifacedecl :: { RdrNameTyClDecl }
320 321
	: tycl_decl			{ $1 }
	| srcloc var '::' sigtype	{ IfaceSig $2 $4 [] $1 }
322

323 324 325 326 327 328 329 330 331 332 333 334 335
-----------------------------------------------------------------------------
-- The Export List

maybeexports :: { Maybe [RdrNameIE] }
	:  '(' exportlist ')'			{ Just $2 }
	|  {- empty -}				{ Nothing }

exportlist :: { [RdrNameIE] }
 	:  exportlist ',' export		{ $3 : $1 }
	|  exportlist ','			{ $1 }
 	|  export				{ [$1]  }
	|  {- empty -}				{ [] }

336 337
   -- No longer allow things like [] and (,,,) to be exported
   -- They are built in syntax, always available
338 339
export 	:: { RdrNameIE }
	:  qvar					{ IEVar $1 }
340 341 342 343
	|  oqtycon				{ IEThingAbs $1 }
	|  oqtycon '(' '..' ')'			{ IEThingAll $1 }
	|  oqtycon '(' ')'		        { IEThingWith $1 [] }
	|  oqtycon '(' qcnames ')'		{ IEThingWith $1 (reverse $3) }
344 345 346 347 348 349
	|  'module' modid			{ IEModuleContents $2 }

qcnames :: { [RdrName] }
	:  qcnames ',' qcname			{ $3 : $1 }
	|  qcname				{ [$1]  }

350
qcname 	:: { RdrName }	-- Variable or data constructor
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
	:  qvar					{ $1 }
	|  gcon					{ $1 }

-----------------------------------------------------------------------------
-- Import Declarations

-- import decls can be *empty*, or even just a string of semicolons
-- whereas topdecls must contain at least one topdecl.

importdecls :: { [RdrNameImportDecl] }
	: importdecls ';' importdecl		{ $3 : $1 }
	| importdecls ';'			{ $1 }
	| importdecl				{ [ $1 ] }
	| {- empty -}				{ [] }

importdecl :: { RdrNameImportDecl }
367 368
	: 'import' srcloc maybe_src optqualified modid maybeas maybeimpspec 
		{ ImportDecl $5 $3 $4 $6 $7 $2 }
369

370 371 372
maybe_src :: { IsBootInterface }
	: '{-# SOURCE' '#-}'			{ True }
	| {- empty -}				{ False }
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

optqualified :: { Bool }
      	: 'qualified'                           { True  }
      	| {- empty -}				{ False }

maybeas :: { Maybe ModuleName }
      	: 'as' modid                            { Just $2 }
      	| {- empty -}				{ Nothing }

maybeimpspec :: { Maybe (Bool, [RdrNameIE]) }
	: impspec				{ Just $1 }
	| {- empty -}				{ Nothing }

impspec :: { (Bool, [RdrNameIE]) }
	:  '(' exportlist ')'  			{ (False, reverse $2) }
	|  'hiding' '(' exportlist ')' 		{ (True,  reverse $3) }

-----------------------------------------------------------------------------
-- Fixity Declarations

prec 	:: { Int }
	: {- empty -}				{ 9 }
395
	| INTEGER				{% checkPrecP (fromInteger $1) }
396 397 398 399 400 401 402 403 404 405 406 407 408

infix 	:: { FixityDirection }
	: 'infix'				{ InfixN  }
	| 'infixl'				{ InfixL  }
	| 'infixr'				{ InfixR }

ops   	:: { [RdrName] }
	: ops ',' op				{ $3 : $1 }
	| op					{ [$1] }

-----------------------------------------------------------------------------
-- Top-Level Declarations

409 410
topdecls :: { [RdrBinding] }	-- Reversed
	: topdecls ';' topdecl		{ $3 : $1 }
411 412 413 414
	| topdecls ';'			{ $1 }
	| topdecl			{ [$1] }

topdecl :: { RdrBinding }
415 416 417 418 419 420
  	: tycl_decl			{ RdrHsDecl (TyClD $1) }
	| srcloc 'instance' inst_type where
		{ let (binds,sigs) = cvMonoBindsAndSigs $4
		  in RdrHsDecl (InstD (InstDecl $3 binds sigs Nothing $1)) }
	| srcloc 'default' '(' comma_types0 ')'		{ RdrHsDecl (DefD (DefaultDecl $4 $1)) }
	| 'foreign' fdecl				{ RdrHsDecl $2 }
421
	| '{-# DEPRECATED' deprecations '#-}'	 	{ RdrBindings (reverse $2) }
sof's avatar
sof committed
422
	| '{-# RULES' rules '#-}'		 	{ RdrBindings (reverse $2) }
423
	| srcloc '$(' exp ')'				{ RdrHsDecl (SpliceD (SpliceDecl $3 $1)) }
424 425 426
      	| decl						{ $1 }

tycl_decl :: { RdrNameTyClDecl }
427
 	: srcloc 'type' syn_hdr '=' ctype	
428 429 430 431
		-- Note ctype, not sigtype.
		-- We allow an explicit for-all but we don't insert one
		-- in 	type Foo a = (b,b)
		-- Instead we just say b is out of scope
432
 		{ let (tc,tvs) = $3 in TySynonym tc tvs $5 $1 }
433

434

435
	| srcloc 'data' tycl_hdr constrs deriving
436
		{ mkTyData DataType $3 (DataCons (reverse $4)) $5 $1 }
437

438
	| srcloc 'newtype' tycl_hdr '=' newconstr deriving
439
		{ mkTyData NewType $3 (DataCons [$5]) $6 $1 }
440

441
	| srcloc 'class' tycl_hdr fds where
442 443 444
		{ let 
			(binds,sigs) = cvMonoBindsAndSigs $5 
		  in
445
	 	  mkClassDecl $3 $4 sigs (Just binds) $1 }
446

447 448 449 450 451
syn_hdr :: { (RdrName, [RdrNameHsTyVar]) }	-- We don't retain the syntax of an infix
						-- type synonym declaration. Oh well.
	: tycon tv_bndrs		{ ($1, $2) }
	| tv_bndr tyconop tv_bndr 	{ ($2, [$1,$3]) }

452 453 454 455 456 457 458
-- tycl_hdr parses the header of a type or class decl,
-- which takes the form
--	T a b
-- 	Eq a => T a
--	(Eq a, Ord b) => T a b
-- Rather a lot of inlining here, else we get reduce/reduce errors
tycl_hdr :: { (RdrNameContext, RdrName, [RdrNameHsTyVar]) }
459 460 461 462 463
	: context '=>' type		{% checkTyClHdr $3	`thenP` \ (tc,tvs) ->
					   returnP ($1, tc, tvs) }
	| type				{% checkTyClHdr $1	`thenP` \ (tc,tvs) ->
					   returnP ([], tc, tvs) }

464 465
-----------------------------------------------------------------------------
-- Nested declarations
466

467
decls 	:: { [RdrBinding] }	-- Reversed
468 469 470 471 472 473
	: decls ';' decl		{ $3 : $1 }
	| decls ';'			{ $1 }
	| decl				{ [$1] }
	| {- empty -}			{ [] }


474 475 476
decllist :: { [RdrBinding] }	-- Reversed
	: '{'            decls '}'	{ $2 }
	|     layout_on  decls close	{ $2 }
477

478
where 	:: { [RdrBinding] }	-- Reversed
479
				-- No implicit parameters
480 481 482
	: 'where' decllist		{ $2 }
	| {- empty -}			{ [] }

483 484 485 486
binds 	::  { RdrNameHsBinds }	-- May have implicit parameters
	: decllist			{ cvBinds $1 }
	| '{'            dbinds '}'	{ IPBinds $2 False{-not with-} }
	|     layout_on  dbinds close	{ IPBinds $2 False{-not with-} }
487

488 489 490
wherebinds :: { RdrNameHsBinds }	-- May have implicit parameters
	: 'where' binds			{ $2 }
	| {- empty -}			{ EmptyBinds }
491

492

493 494 495 496

-----------------------------------------------------------------------------
-- Transformation Rules

497
rules	:: { [RdrBinding] }	-- Reversed
sof's avatar
sof committed
498 499
	:  rules ';' rule			{ $3 : $1 }
        |  rules ';'				{ $1 }
500 501
        |  rule					{ [$1] }
	|  {- empty -}				{ [] }
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

rule  	:: { RdrBinding }
	: STRING activation rule_forall infixexp '=' srcloc exp
	     { RdrHsDecl (RuleD (HsRule $1 $2 $3 $4 $7 $6)) }

activation :: { Activation }           -- Omitted means AlwaysActive
        : {- empty -}                           { AlwaysActive }
        | explicit_activation                   { $1 }

inverse_activation :: { Activation }   -- Omitted means NeverActive
        : {- empty -}                           { NeverActive }
        | explicit_activation                   { $1 }

explicit_activation :: { Activation }  -- In brackets
        : '[' INTEGER ']'                       { ActiveAfter  (fromInteger $2) }
        | '[' '~' INTEGER ']'                   { ActiveBefore (fromInteger $3) }

rule_forall :: { [RdrNameRuleBndr] }
	: 'forall' rule_var_list '.'            { $2 }
        | {- empty -}				{ [] }

rule_var_list :: { [RdrNameRuleBndr] }
        : rule_var				{ [$1] }
        | rule_var rule_var_list		{ $1 : $2 }

rule_var :: { RdrNameRuleBndr }
	: varid                              	{ RuleBndr $1 }
       	| '(' varid '::' ctype ')'             	{ RuleBndrSig $2 $4 }

-----------------------------------------------------------------------------
532
-- Deprecations (c.f. rules)
533

534 535 536
deprecations :: { [RdrBinding] }	-- Reversed
	: deprecations ';' deprecation		{ $3 : $1 }
	| deprecations ';' 			{ $1 }
537 538
	| deprecation				{ [$1] }
	| {- empty -}				{ [] }
539 540 541 542

-- SUP: TEMPORARY HACK, not checking for `module Foo'
deprecation :: { RdrBinding }
	: srcloc depreclist STRING
543
		{ RdrBindings
544 545 546 547 548 549
			[ RdrHsDecl (DeprecD (Deprecation n $3 $1)) | n <- $2 ] }


-----------------------------------------------------------------------------
-- Foreign import and export declarations

chak's avatar
chak committed
550 551 552 553 554 555 556 557 558 559 560 561
-- for the time being, the following accepts foreign declarations conforming
-- to the FFI Addendum, Version 1.0 as well as pre-standard declarations
--
-- * a flag indicates whether pre-standard declarations have been used and
--   triggers a deprecation warning further down the road
--
-- NB: The first two rules could be combined into one by replacing `safety1'
--     with `safety'.  However, the combined rule conflicts with the
--     DEPRECATED rules.
--
fdecl :: { RdrNameHsDecl }
fdecl : srcloc 'import' callconv safety1 fspec	{% mkImport $3 $4       $5 $1 }
sof's avatar
sof committed
562
      | srcloc 'import' callconv         fspec	{% mkImport $3 (PlaySafe False) $4 $1 }
chak's avatar
chak committed
563 564 565 566 567 568 569 570 571
      | srcloc 'export'	callconv         fspec  {% mkExport $3          $4 $1 }
        -- the following syntax is DEPRECATED
      | srcloc fdecl1DEPRECATED			{ ForD ($2 True $1) }
      | srcloc fdecl2DEPRECATED			{ $2 $1 }

fdecl1DEPRECATED :: { Bool -> SrcLoc -> ForeignDecl RdrName }
fdecl1DEPRECATED 
  ----------- DEPRECATED label decls ------------
  : 'label' ext_name varid '::' sigtype
572
    { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
chak's avatar
chak committed
573 574 575 576 577 578 579 580 581 582 583 584 585
				   (CLabel ($2 `orElse` mkExtName $3))) }

  ----------- DEPRECATED ccall/stdcall decls ------------
  --
  -- NB: This business with the case expression below may seem overly
  --	 complicated, but it is necessary to avoid some conflicts.

    -- DEPRECATED variant #1: lack of a calling convention specification
    --			      (import) 
  | 'import' {-no callconv-} ext_name safety varid_no_unsafe '::' sigtype
    { let
	target = StaticTarget ($2 `orElse` mkExtName $4)
      in
586
      ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
chak's avatar
chak committed
587 588 589 590 591 592 593 594 595 596 597
				   (CFunction target)) }

    -- DEPRECATED variant #2: external name consists of two separate strings
    --			      (module name and function name) (import)
  | 'import' callconv STRING STRING safety varid_no_unsafe '::' sigtype
    {% case $2 of
         DNCall      -> parseError "Illegal format of .NET foreign import"
	 CCall cconv -> returnP $
           let
	     imp = CFunction (StaticTarget $4)
	   in
598
	   ForeignImport $6 $8 (CImport cconv $5 nilFS nilFS imp) }
chak's avatar
chak committed
599 600 601 602 603 604 605 606 607

    -- DEPRECATED variant #3: `unsafe' after entity
  | 'import' callconv STRING 'unsafe' varid_no_unsafe '::' sigtype
    {% case $2 of
         DNCall      -> parseError "Illegal format of .NET foreign import"
	 CCall cconv -> returnP $
           let
	     imp = CFunction (StaticTarget $3)
	   in
608
	   ForeignImport $5 $7 (CImport cconv PlayRisky nilFS nilFS imp) }
chak's avatar
chak committed
609 610 611 612

    -- DEPRECATED variant #4: use of the special identifier `dynamic' without
    --			      an explicit calling convention (import)
  | 'import' {-no callconv-} 'dynamic' safety varid_no_unsafe '::' sigtype
613
    { ForeignImport $4 $6 (CImport defaultCCallConv $3 nilFS nilFS 
chak's avatar
chak committed
614 615 616 617 618 619 620
				   (CFunction DynamicTarget)) }

    -- DEPRECATED variant #5: use of the special identifier `dynamic' (import)
  | 'import' callconv 'dynamic' safety varid_no_unsafe '::' sigtype
    {% case $2 of
         DNCall      -> parseError "Illegal format of .NET foreign import"
	 CCall cconv -> returnP $
621
	   ForeignImport $5 $7 (CImport cconv $4 nilFS nilFS 
chak's avatar
chak committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
					(CFunction DynamicTarget)) }

    -- DEPRECATED variant #6: lack of a calling convention specification
    --			      (export) 
  | 'export' {-no callconv-} ext_name varid '::' sigtype
    { ForeignExport $3 $5 (CExport (CExportStatic ($2 `orElse` mkExtName $3) 
				   defaultCCallConv)) }

    -- DEPRECATED variant #7: external name consists of two separate strings
    --			      (module name and function name) (export)
  | 'export' callconv STRING STRING varid '::' sigtype
    {% case $2 of
         DNCall      -> parseError "Illegal format of .NET foreign import"
	 CCall cconv -> returnP $
           ForeignExport $5 $7 
			 (CExport (CExportStatic $4 cconv)) }

    -- DEPRECATED variant #8: use of the special identifier `dynamic' without
    --			      an explicit calling convention (export)
  | 'export' {-no callconv-} 'dynamic' varid '::' sigtype
642
    { ForeignImport $3 $5 (CImport defaultCCallConv (PlaySafe False) nilFS nilFS 
chak's avatar
chak committed
643 644 645 646 647 648 649
				   CWrapper) }

    -- DEPRECATED variant #9: use of the special identifier `dynamic' (export)
  | 'export' callconv 'dynamic' varid '::' sigtype
    {% case $2 of
         DNCall      -> parseError "Illegal format of .NET foreign import"
	 CCall cconv -> returnP $
650
	   ForeignImport $4 $6 (CImport cconv (PlaySafe False) nilFS nilFS CWrapper) }
chak's avatar
chak committed
651 652 653 654 655 656 657 658 659 660 661

  ----------- DEPRECATED .NET decls ------------
  -- NB: removed the .NET call declaration, as it is entirely subsumed
  --     by the new standard FFI declarations

fdecl2DEPRECATED :: { SrcLoc -> RdrNameHsDecl }
fdecl2DEPRECATED 
  : 'import' 'dotnet' 'type' ext_name tycon
	  { \loc -> TyClD (ForeignType $5 $4 DNType loc) }
    -- left this one unchanged for the moment as type imports are not
    -- covered currently by the FFI standard -=chak
662

chak's avatar
chak committed
663 664 665 666 667 668 669 670

callconv :: { CallConv }
	  : 'stdcall'			{ CCall  StdCallConv }
	  | 'ccall'			{ CCall  CCallConv   }
	  | 'dotnet'			{ DNCall	     }

safety :: { Safety }
	: 'unsafe'			{ PlayRisky }
sof's avatar
sof committed
671 672 673
	| 'safe'			{ PlaySafe False }
	| 'threadsafe'			{ PlaySafe True  }
	| {- empty -}			{ PlaySafe False }
chak's avatar
chak committed
674 675 676

safety1 :: { Safety }
	: 'unsafe'			{ PlayRisky }
sof's avatar
sof committed
677 678
	| 'safe'			{ PlaySafe  False }
	| 'threadsafe'			{ PlaySafe  True }
chak's avatar
chak committed
679 680
	  -- only needed to avoid conflicts with the DEPRECATED rules

681
fspec :: { (FastString, RdrName, RdrNameHsType) }
682 683
       : STRING var '::' sigtype      { ($1      , $2, $4) }
       |        var '::' sigtype      { (nilFS, $1, $3) }
chak's avatar
chak committed
684 685 686 687 688
         -- if the entity string is missing, it defaults to the empty string;
         -- the meaning of an empty entity string depends on the calling
         -- convention

-- DEPRECATED syntax
689 690
ext_name :: { Maybe CLabelString }
	: STRING		{ Just $1 }
691
	| STRING STRING		{ Just $2 }	-- Ignore "module name" for now
sof's avatar
sof committed
692
	| {- empty -}           { Nothing }
693

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

-----------------------------------------------------------------------------
-- Type signatures

opt_sig :: { Maybe RdrNameHsType }
	: {- empty -}			{ Nothing }
	| '::' sigtype			{ Just $2 }

opt_asig :: { Maybe RdrNameHsType }
	: {- empty -}			{ Nothing }
	| '::' atype			{ Just $2 }

sigtypes :: { [RdrNameHsType] }
	: sigtype			{ [ $1 ] }
	| sigtypes ',' sigtype		{ $3 : $1 }

sigtype :: { RdrNameHsType }
711
	: ctype				{ mkHsForAllTy Nothing [] $1 }
712 713 714 715 716

sig_vars :: { [RdrName] }
	 : sig_vars ',' var		{ $3 : $1 }
	 | var				{ [ $1 ] }

717 718 719
-----------------------------------------------------------------------------
-- Types

720 721
-- A ctype is a for-all type
ctype	:: { RdrNameHsType }
722
	: 'forall' tv_bndrs '.' ctype	{ mkHsForAllTy (Just $2) [] $4 }
723
	| context '=>' type		{ mkHsForAllTy Nothing   $1 $3 }
724
	-- A type of form (context => type) is an *implicit* HsForAllTy
725
	| type				{ $1 }
726

727 728 729 730 731 732 733
-- We parse a context as a btype so that we don't get reduce/reduce
-- errors in ctype.  The basic problem is that
--	(Eq a, Ord a)
-- looks so much like a tuple type.  We can't tell until we find the =>
context :: { RdrNameContext }
	: btype 			{% checkContext $1 }

734
type :: { RdrNameHsType }
735
	: ipvar '::' gentype		{ mkHsIParamTy $1 $3 }
736 737 738 739
	| gentype			{ $1 }

gentype :: { RdrNameHsType }
        : btype                         { $1 }
740
        | btype qtyconop gentype        { HsOpTy $1 (HsTyOp $2) $3 }
741
        | btype  '`' tyvar '`' gentype  { HsOpTy $1 (HsTyOp $3) $5 }
742
	| btype '->' gentype		{ HsOpTy $1 HsArrow $3 }
743 744

btype :: { RdrNameHsType }
745
	: btype atype			{ HsAppTy $1 $2 }
746 747 748
	| atype				{ $1 }

atype :: { RdrNameHsType }
749 750
	: gtycon			{ HsTyVar $1 }
	| tyvar				{ HsTyVar $1 }
751 752
	| '(' type ',' comma_types1 ')'	{ HsTupleTy (mkHsTupCon tcName Boxed  ($2:$4)) ($2:$4) }
	| '(#' comma_types1 '#)'	{ HsTupleTy (mkHsTupCon tcName Unboxed     $2) $2      }
chak's avatar
chak committed
753 754 755
	| '[' type ']'			{ HsListTy  $2 }
	| '[:' type ':]'		{ HsPArrTy  $2 }
	| '(' ctype ')'		        { HsParTy   $2 }
756
	| '(' ctype '::' kind ')'	{ HsKindSig $2 $4 }
757 758
-- Generics
        | INTEGER                       { HsNumTy $1 }
759 760 761 762 763 764 765 766

-- An inst_type is what occurs in the head of an instance decl
--	e.g.  (Foo a, Gaz b) => Wibble a b
-- It's kept as a single type, with a MonoDictTy at the right
-- hand corner, for convenience.
inst_type :: { RdrNameHsType }
	: ctype				{% checkInstType $1 }

767 768
comma_types0  :: { [RdrNameHsType] }
	: comma_types1			{ $1 }
769 770
	| {- empty -}			{ [] }

771
comma_types1	:: { [RdrNameHsType] }
772
	: type				{ [$1] }
773
	| type  ',' comma_types1	{ $1 : $3 }
774

775 776 777 778 779 780 781 782
tv_bndrs :: { [RdrNameHsTyVar] }
	 : tv_bndr tv_bndrs		{ $1 : $2 }
	 | {- empty -}			{ [] }

tv_bndr :: { RdrNameHsTyVar }
	: tyvar				{ UserTyVar $1 }
	| '(' tyvar '::' kind ')'	{ IfaceTyVar $2 $4 }

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
fds :: { [([RdrName], [RdrName])] }
	: {- empty -}			{ [] }
	| '|' fds1			{ reverse $2 }

fds1 :: { [([RdrName], [RdrName])] }
	: fds1 ',' fd			{ $3 : $1 }
	| fd				{ [$1] }

fd :: { ([RdrName], [RdrName]) }
	: varids0 '->' varids0		{ (reverse $1, reverse $3) }

varids0	:: { [RdrName] }
	: {- empty -}			{ [] }
	| varids0 tyvar			{ $2 : $1 }

798 799 800 801 802 803 804 805 806 807 808 809
-----------------------------------------------------------------------------
-- Kinds

kind	:: { Kind }
	: akind			{ $1 }
	| akind '->' kind	{ mkArrowKind $1 $3 }

akind	:: { Kind }
	: '*'			{ liftedTypeKind }
	| '(' kind ')'		{ $2 }


810 811 812
-----------------------------------------------------------------------------
-- Datatype declarations

813
newconstr :: { RdrNameConDecl }
814
	: srcloc conid atype	{ ConDecl $2 [] [] (PrefixCon [unbangedType $3]) $1 }
815
	| srcloc conid '{' var '::' ctype '}'
816
				{ ConDecl $2 [] [] (RecCon [($4, unbangedType $6)]) $1 }
817

818
constrs :: { [RdrNameConDecl] }
819 820 821 822 823
        : {- empty; a GHC extension -}  { [] }
        | '=' constrs1                  { $2 }

constrs1 :: { [RdrNameConDecl] }
	: constrs1 '|' constr		{ $3 : $1 }
824 825 826
	| constr			{ [$1] }

constr :: { RdrNameConDecl }
827
	: srcloc forall context '=>' constr_stuff
828
		{ ConDecl (fst $5) $2 $3 (snd $5) $1 }
829
	| srcloc forall constr_stuff
830
		{ ConDecl (fst $3) $2 [] (snd $3) $1 }
831 832

forall :: { [RdrNameHsTyVar] }
833
	: 'forall' tv_bndrs '.'		{ $2 }
834 835 836
	| {- empty -}			{ [] }

constr_stuff :: { (RdrName, RdrNameConDetails) }
837 838
	: btype				{% mkPrefixCon $1 [] }
	| btype '!' atype satypes	{% mkPrefixCon $1 (BangType MarkedUserStrict $3 : $4) }
839 840
	| oqtycon '{' '}' 		{% mkRecCon $1 [] }
	| oqtycon '{' fielddecls '}' 	{% mkRecCon $1 $3 }
841
	| sbtype conop sbtype		{ ($2, InfixCon $1 $3) }
842

843
satypes	:: { [RdrNameBangType] }
844 845
	: atype satypes			{ unbangedType $1 : $2 }
	| '!' atype satypes		{ BangType MarkedUserStrict $2 : $3 }
846
	| {- empty -}			{ [] }
847 848

sbtype :: { RdrNameBangType }
849 850
	: btype				{ unbangedType $1 }
	| '!' atype			{ BangType MarkedUserStrict $2 }
851 852

fielddecls :: { [([RdrName],RdrNameBangType)] }
853
	: fielddecl ',' fielddecls	{ $1 : $3 }
854 855 856
	| fielddecl			{ [$1] }

fielddecl :: { ([RdrName],RdrNameBangType) }
857
	: sig_vars '::' stype		{ (reverse $1, $3) }
858 859

stype :: { RdrNameBangType }
860 861
	: ctype				{ unbangedType $1 }
	| '!' atype			{ BangType MarkedUserStrict $2 }
862

863
deriving :: { Maybe RdrNameContext }
864
	: {- empty -}			{ Nothing }
865 866 867
	| 'deriving' context		{ Just $2 }
             -- Glasgow extension: allow partial 
             -- applications in derivings
868 869 870 871

-----------------------------------------------------------------------------
-- Value definitions

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
{- There's an awkward overlap with a type signature.  Consider
	f :: Int -> Int = ...rhs...
   Then we can't tell whether it's a type signature or a value
   definition with a result signature until we see the '='.
   So we have to inline enough to postpone reductions until we know.
-}

{-
  ATTENTION: Dirty Hackery Ahead! If the second alternative of vars is var
  instead of qvar, we get another shift/reduce-conflict. Consider the
  following programs:
  
     { (^^) :: Int->Int ; }          Type signature; only var allowed

     { (^^) :: Int->Int = ... ; }    Value defn with result signature;
				     qvar allowed (because of instance decls)
  
  We can't tell whether to reduce var to qvar until after we've read the signatures.
-}

892 893 894
decl 	:: { RdrBinding }
	: sigdecl			{ $1 }
	| infixexp srcloc opt_sig rhs	{% checkValDef $1 $3 $4 $2 }
895

896
rhs	:: { RdrNameGRHSs }
897 898
	: '=' srcloc exp wherebinds	{ GRHSs (unguardedRHS $3 $2) $4 placeHolderType }
	| gdrhs	wherebinds		{ GRHSs (reverse $1)         $2 placeHolderType }
899 900 901 902 903 904

gdrhs :: { [RdrNameGRHS] }
	: gdrhs gdrh			{ $2 : $1 }
	| gdrh				{ [$1] }

gdrh :: { RdrNameGRHS }
905
	: '|' srcloc quals '=' exp  	{ GRHS (reverse (ResultStmt $5 $2 : $3)) $2 }
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
sigdecl :: { RdrBinding }
	: infixexp srcloc '::' sigtype		
				{% checkValSig $1 $4 $2 }
		-- See the above notes for why we need infixexp here
	| var ',' sig_vars srcloc '::' sigtype	
				{ mkSigDecls [ Sig n $6 $4 | n <- $1:$3 ] }
	| srcloc infix prec ops	{ mkSigDecls [ FixSig (FixitySig n (Fixity $3 $2) $1)
					     | n <- $4 ] }
	| '{-# INLINE'   srcloc activation qvar '#-}'	      
				{ RdrHsDecl (SigD (InlineSig True  $4 $3 $2)) }
	| '{-# NOINLINE' srcloc inverse_activation qvar '#-}' 
				{ RdrHsDecl (SigD (InlineSig False $4 $3 $2)) }
	| '{-# SPECIALISE' srcloc qvar '::' sigtypes '#-}'
			 	{ mkSigDecls  [ SpecSig $3 t $2 | t <- $5] }
	| '{-# SPECIALISE' srcloc 'instance' inst_type '#-}'
				{ RdrHsDecl (SigD (SpecInstSig $4 $2)) }

924 925 926 927
-----------------------------------------------------------------------------
-- Expressions

exp   :: { RdrNameHsExpr }
928
	: infixexp '::' sigtype		{ ExprWithTySig $1 $3 }
929
	| infixexp 'with' dbinding	{ HsLet (IPBinds $3 True{-not a let-}) $1 }
930 931 932 933
	| infixexp			{ $1 }

infixexp :: { RdrNameHsExpr }
	: exp10				{ $1 }
934 935
	| infixexp qop exp10		{ (OpApp $1 (HsVar $2) 
						(panic "fixity") $3 )}
936 937

exp10 :: { RdrNameHsExpr }
938 939
	: '\\' srcloc aexp aexps opt_asig '->' srcloc exp	
			{% checkPatterns $2 ($3 : reverse $4) `thenP` \ ps -> 
940
			   returnP (HsLam (Match ps $5 
941
					    (GRHSs (unguardedRHS $8 $7) 
942
						   EmptyBinds placeHolderType))) }
943
  	| 'let' binds 'in' exp			{ HsLet $2 $4 }
944 945
	| 'if' srcloc exp 'then' exp 'else' exp { HsIf $3 $5 $7 $2 }
   	| 'case' srcloc exp 'of' altslist	{ HsCase $3 $5 $2 }
946
	| '-' fexp				{ mkHsNegApp $2 }
947
  	| srcloc 'do' stmtlist			{% checkDo $3  `thenP` \ stmts ->
948
						   returnP (mkHsDo DoExpr stmts $1) }
949 950
  	| srcloc 'mdo' stmtlist			{% checkMDo $3  `thenP` \ stmts ->
						   returnP (mkHsDo MDoExpr stmts $1) }
951

952
	| '_ccall_'    ccallid aexps0		{ HsCCall $2 $3 PlayRisky False placeHolderType }
sof's avatar
sof committed
953
	| '_ccall_GC_' ccallid aexps0		{ HsCCall $2 $3 (PlaySafe False) False placeHolderType }
954
	| '_casm_'     CLITLIT aexps0		{ HsCCall $2 $3 PlayRisky True  placeHolderType }
sof's avatar
sof committed
955
	| '_casm_GC_'  CLITLIT aexps0		{ HsCCall $2 $3 (PlaySafe False) True  placeHolderType }
956

957 958 959
        | scc_annot exp		    		{ if opt_SccProfilingOn
							then HsSCC $1 $2
							else HsPar $2 }
960

961 962
        | '{-# CORE' STRING '#-}' exp           { HsCoreAnn $2 $4 }    -- hdaume: core annotation

963
	| reifyexp				{ HsReify $1 }
964 965
	| fexp					{ $1 }

966
scc_annot :: { FastString }
967 968 969
	: '_scc_' STRING			{ $2 }
	| '{-# SCC' STRING '#-}'		{ $2 }

970
ccallid :: { FastString }
971 972 973 974
	:  VARID				{ $1 }
	|  CONID				{ $1 }

fexp 	:: { RdrNameHsExpr }
975
	: fexp aexp				{ (HsApp $1 $2) }
976 977
  	| aexp					{ $1 }

978 979 980 981 982 983
reifyexp :: { HsReify RdrName }
	: REIFY_DECL gtycon  			{ Reify ReifyDecl $2 }
	| REIFY_DECL qvar			{ Reify ReifyDecl $2 }
	| REIFY_TYPE qcname			{ Reify ReifyType $2 }
	| REIFY_FIXITY qcname			{ Reify ReifyFixity $2 }

984
aexps0 	:: { [RdrNameHsExpr] }
985
	: aexps					{ reverse $1 }
986 987 988 989 990 991

aexps 	:: { [RdrNameHsExpr] }
	: aexps aexp				{ $2 : $1 }
  	| {- empty -}				{ [] }

aexp	:: { RdrNameHsExpr }
992 993 994 995 996
	: qvar '@' aexp			{ EAsPat $1 $3 }
	| '~' aexp			{ ELazyPat $2 }
	| aexp1				{ $1 }

aexp1	:: { RdrNameHsExpr }
997 998
        : aexp1 '{' fbinds '}' 		{% (mkRecConstrOrUpdate $1 (reverse $3)) }
  	| aexp2				{ $1 }
999

1000 1001 1002 1003
-- Here was the syntax for type applications that I was planning
-- but there are difficulties (e.g. what order for type args)
-- so it's not enabled yet.
 	| qcname '{|' gentype '|}'          { (HsApp (HsVar $1) (HsType $3)) }
1004

1005
aexp2	:: { RdrNameHsExpr }
1006
	: ipvar				{ HsIPVar $1 }
1007
	| qcname			{ HsVar $1 }
1008
	| literal			{ HsLit $1 }
1009 1010
	| INTEGER			{ HsOverLit (mkHsIntegral   $1) }
	| RATIONAL			{ HsOverLit (mkHsFractional $1) }
1011
	| '(' exp ')'			{ HsPar $2 }
1012 1013
	| '(' exp ',' texps ')'		{ ExplicitTuple ($2 : reverse $4) Boxed}
	| '(#' texps '#)'		{ ExplicitTuple (reverse $2)      Unboxed }
1014
	| '[' list ']'                  { $2 }
chak's avatar
chak committed
1015
	| '[:' parr ':]'                { $2 }
1016 1017
	| '(' infixexp qop ')'		{ (SectionL $2 (HsVar $3))  }
	| '(' qopm infixexp ')'		{ (SectionR $2 $3) }
1018
	| '_'				{ EWildPat }
1019 1020
	
	-- MetaHaskell Extension
1021 1022 1023 1024 1025 1026
	| srcloc ID_SPLICE              { mkHsSplice (HsVar (mkUnqual varName $2)) $1 }  -- $x
	| srcloc '$(' exp ')'   	{ mkHsSplice $3 $1 }                             -- $( exp )
	| srcloc '[|' exp '|]'          { HsBracket (ExpBr $3) $1 }                       
	| srcloc '[t|' ctype '|]'       { HsBracket (TypBr $3) $1 }                       
	| srcloc '[p|' infixexp '|]'    {% checkPattern $1 $3 `thenP` \p ->
					   returnP (HsBracket (PatBr p) $1) }
1027
	| srcloc '[d|' cvtopbody '|]'	{ HsBracket (DecBr (mkGroup $3)) $1 }
1028

1029 1030 1031
cvtopbody :: { [RdrNameHsDecl] }
	:  '{'            cvtopdecls '}'		{ $2 }
	|      layout_on  cvtopdecls close		{ $2 }
1032 1033 1034 1035 1036

texps :: { [RdrNameHsExpr] }
	: texps ',' exp			{ $3 : $1 }
	| exp				{ [$1] }

1037

1038 1039 1040 1041 1042 1043 1044
-----------------------------------------------------------------------------
-- List expressions

-- The rules below are little bit contorted to keep lexps left-recursive while
-- avoiding another shift/reduce-conflict.

list :: { RdrNameHsExpr }
1045 1046
	: exp				{ ExplicitList placeHolderType [$1] }
	| lexps 			{ ExplicitList placeHolderType (reverse $1) }
1047 1048 1049 1050
	| exp '..'			{ ArithSeqIn (From $1) }
	| exp ',' exp '..' 		{ ArithSeqIn (FromThen $1 $3) }
	| exp '..' exp	 		{ ArithSeqIn (FromTo $1 $3) }
	| exp ',' exp '..' exp		{ ArithSeqIn (FromThenTo $1 $3 $5) }
1051 1052 1053
	| exp srcloc pquals		{% let { body [qs] = qs;
					         body  qss = [ParStmt (map reverse qss)] }
					   in
1054 1055 1056
					   returnP ( mkHsDo ListComp
							    (reverse (ResultStmt $1 $2 : body $3))
							    $2
1057 1058
						  )
					}
1059 1060 1061 1062 1063 1064 1065 1066

lexps :: { [RdrNameHsExpr] }
	: lexps ',' exp 		{ $3 : $1 }
	| exp ',' exp			{ [$3,$1] }

-----------------------------------------------------------------------------
-- List Comprehensions

1067 1068 1069 1070
pquals :: { [[RdrNameStmt]] }
	: pquals '|' quals		{ $3 : $1 }
	| '|' quals			{ [$2] }

1071
quals :: { [RdrNameStmt] }
1072 1073
	: quals ',' stmt		{ $3 : $1 }
	| stmt				{ [$1] }
1074

chak's avatar
chak committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
-----------------------------------------------------------------------------
-- Parallel array expressions

-- The rules below are little bit contorted; see the list case for details.
-- Note that, in contrast to lists, we only have finite arithmetic sequences.
-- Moreover, we allow explicit arrays with no element (represented by the nil
-- constructor in the list case).

parr :: { RdrNameHsExpr }
	: 				{ ExplicitPArr placeHolderType [] }
	| exp				{ ExplicitPArr placeHolderType [$1] }
	| lexps 			{ ExplicitPArr placeHolderType 
						       (reverse $1) }
	| exp '..' exp	 		{ PArrSeqIn (FromTo $1 $3) }
	| exp ',' exp '..' exp		{ PArrSeqIn (FromThenTo $1 $3 $5) }
	| exp srcloc pquals		{% let {
					     body [qs] = qs;
					     body  qss = [ParStmt 
							   (map reverse qss)]}
					   in
					   returnP $ 
1096 1097 1098 1099
					     mkHsDo PArrComp 
						    (reverse (ResultStmt $1 $2 
							     : body $3))
						    $2
chak's avatar
chak committed
1100 1101 1102 1103
					}

-- We are reusing `lexps' and `pquals' from the list case.

1104 1105 1106 1107 1108 1109 1110
-----------------------------------------------------------------------------
-- Case alternatives

altslist :: { [RdrNameMatch] }
	: '{'            alts '}'	{ reverse $2 }
	|     layout_on  alts  close	{ reverse $2 }

1111 1112 1113
alts    :: { [RdrNameMatch] }
        : alts1				{ $1 }
	| ';' alts			{ $2 }
1114

1115 1116 1117
alts1 	:: { [RdrNameMatch] }
	: alts1 ';' alt			{ $3 : $1 }
	| alts1 ';'			{ $1 }
1118 1119 1120
	| alt				{ [$1] }

alt 	:: { RdrNameMatch }
1121 1122
	: srcloc infixexp opt_sig ralt wherebinds
					{% (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 1131 1132 1133 1134

gdpats :: { [RdrNameGRHS] }
	: gdpats gdpat			{ $2 : $1 }
	| gdpat				{ [$1] }

gdpat	:: { RdrNameGRHS }
1135
	: srcloc '|' quals '->' exp 	{ GRHS (reverse (ResultStmt $5 $1:$3)) $1}
1136 1137 1138 1139 1140

-----------------------------------------------------------------------------
-- Statement sequences

stmtlist :: { [RdrNameStmt] }
1141 1142
	: '{'            	stmts '}'	{ $2 }
	|     layout_on_for_do  stmts close	{ $2 }
1143

1144 1145 1146 1147 1148
--	do { ;; s ; s ; ; s ;; }
-- The last Stmt should be a ResultStmt, but that's hard to enforce
-- here, because we need too much lookahead if we see do { e ; }
-- So we use ExprStmts throughout, and switch the last one over
-- in ParseUtils.checkDo instead
1149
stmts :: { [RdrNameStmt] }
1150 1151 1152 1153 1154
	: stmt stmts_help		{ $1 : $2 }
	| ';' stmts			{ $2 }
	| {- empty -}			{ [] }

stmts_help :: { [RdrNameStmt] }
1155
	: ';' stmts			{ $2 }
1156
	| {- empty -}			{ [] }
1157

1158 1159
-- For typing stmts at the GHCi prompt, where 
-- the input may consist of just comments.
1160 1161 1162 1163
maybe_stmt :: { Maybe RdrNameStmt }
	: stmt				{ Just $1 }
	| {- nothing -}			{ Nothing }

1164
stmt  :: { RdrNameStmt }
1165
	: srcloc infixexp '<-' exp	{% checkPattern $1 $2 `thenP` \p ->