DsArrows.lhs 34.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[DsArrows]{Desugaring arrow commands}

\begin{code}
module DsArrows ( dsProcExpr ) where

#include "HsVersions.h"

import Match		( matchSimply )
import DsUtils		( mkErrorAppDs,
13
			  mkCoreTupTy, mkCoreTup, selectSimpleMatchVarL,
ross's avatar
ross committed
14
			  mkTupleCase, mkBigCoreTup, mkTupleType,
15
			  mkTupleExpr, mkTupleSelector,
16
			  dsSyntaxTable, lookupEvidence )
17 18
import DsMonad

19 20
import HsSyn
import TcHsSyn		( hsPatType )
21 22 23 24 25 26

-- NB: The desugarer, which straddles the source and Core worlds, sometimes
--     needs to see source types (newtypes etc), and sometimes not
--     So WATCH OUT; check each use of split*Ty functions.
-- Sigh.  This is a pain.

27
import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLocalBinds )
28

29 30
import TcType		( Type, tcSplitAppTy, mkFunTy )
import Type		( mkTyConApp, funArgTy )
31 32
import CoreSyn
import CoreFVs		( exprFreeVars )
ross's avatar
ross committed
33
import CoreUtils	( mkIfThenElse, bindNonRec, exprType )
34 35

import Id		( Id, idType )
36
import Name		( Name )
37
import PrelInfo		( pAT_ERROR_ID )
38 39
import DataCon		( dataConWrapId )
import TysWiredIn	( tupleCon )
40 41 42 43 44 45 46
import BasicTypes	( Boxity(..) )
import PrelNames	( eitherTyConName, leftDataConName, rightDataConName,
			  arrAName, composeAName, firstAName,
			  appAName, choiceAName, loopAName )
import Util		( mapAccumL )
import Outputable

47
import HsUtils		( collectPatBinders, collectPatsBinders )
48
import VarSet		( IdSet, mkVarSet, varSetElems,
49
			  intersectVarSet, minusVarSet, extendVarSetList, 
50
			  unionVarSet, unionVarSets, elemVarSet )
51
import SrcLoc		( Located(..), unLoc, noLoc, getLoc )
52 53 54 55 56 57 58 59
\end{code}

\begin{code}
data DsCmdEnv = DsCmdEnv {
	meth_binds :: [CoreBind],
	arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
    }

60
mkCmdEnv :: SyntaxTable Id -> DsM DsCmdEnv
61
mkCmdEnv ids
62
  = dsSyntaxTable ids			`thenDs` \ (meth_binds, ds_meths) ->
63 64
    return $ DsCmdEnv {
		meth_binds = meth_binds,
65 66 67 68 69 70
		arr_id	   = Var (lookupEvidence ds_meths arrAName),
		compose_id = Var (lookupEvidence ds_meths composeAName),
		first_id   = Var (lookupEvidence ds_meths firstAName),
		app_id	   = Var (lookupEvidence ds_meths appAName),
		choice_id  = Var (lookupEvidence ds_meths choiceAName),
		loop_id	   = Var (lookupEvidence ds_meths loopAName)
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
	    }

bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
bindCmdEnv ids body = foldr Let body (meth_binds ids)

-- arr :: forall b c. (b -> c) -> a b c
do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]

-- (>>>) :: forall b c d. a b c -> a c d -> a b d
do_compose :: DsCmdEnv -> Type -> Type -> Type ->
		CoreExpr -> CoreExpr -> CoreExpr
do_compose ids b_ty c_ty d_ty f g
  = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]

-- first :: forall b c d. a b c -> a (b,d) (c,d)
do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
do_first ids b_ty c_ty d_ty f
  = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]

-- app :: forall b c. a (a b c, b) c
do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]

-- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
-- note the swapping of d and c
do_choice :: DsCmdEnv -> Type -> Type -> Type ->
		CoreExpr -> CoreExpr -> CoreExpr
do_choice ids b_ty c_ty d_ty f g
  = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]

-- loop :: forall b d c. a (b,d) (c,d) -> a b c
-- note the swapping of d and c
do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
do_loop ids b_ty c_ty d_ty f
  = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]

-- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
		CoreExpr -> CoreExpr -> CoreExpr
do_map_arrow ids b_ty c_ty d_ty f c
  = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c

114
mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr
115 116 117 118 119 120
mkFailExpr ctxt ty
  = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)

-- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
mkSndExpr :: Type -> Type -> DsM CoreExpr
mkSndExpr a_ty b_ty
ross's avatar
ross committed
121 122 123 124
  = newSysLocalDs a_ty			`thenDs` \ a_var ->
    newSysLocalDs b_ty			`thenDs` \ b_var ->
    newSysLocalDs (mkCorePairTy a_ty b_ty)	`thenDs` \ pair_var ->
    returnDs (Lam pair_var
ross's avatar
ross committed
125
		  (coreCasePair pair_var a_var b_var (Var b_var)))
126 127 128 129 130 131 132 133 134 135 136
\end{code}

Build case analysis of a tuple.  This cannot be done in the DsM monad,
because the list of variables is typically not yet defined.

\begin{code}
-- coreCaseTuple [u1..] v [x1..xn] body
--	= case v of v { (x1, .., xn) -> body }
-- But the matching may be nested if the tuple is very big

coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
ross's avatar
ross committed
137 138
coreCaseTuple uniqs scrut_var vars body
  = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
139

ross's avatar
ross committed
140 141
coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
coreCasePair scrut_var var1 var2 body
142
  = Case (Var scrut_var) scrut_var (exprType body)
ross's avatar
ross committed
143
         [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
\end{code}

\begin{code}
mkCorePairTy :: Type -> Type -> Type
mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]

mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
\end{code}

The input is divided into a local environment, which is a flat tuple
(unless it's too big), and a stack, each element of which is paired
with the stack in turn.  In general, the input has the form

	(...((x1,...,xn),s1),...sk)

where xi are the environment values, and si the ones on the stack,
with s1 being the "top", the first one to be matched with a lambda.

\begin{code}
envStackType :: [Id] -> [Type] -> Type
ross's avatar
ross committed
165
envStackType ids stack_tys = foldl mkCorePairTy (mkTupleType ids) stack_tys
166 167 168 169

----------------------------------------------
--		buildEnvStack
--
ross's avatar
ross committed
170
--	(...((x1,...,xn),s1),...sk)
171 172 173

buildEnvStack :: [Id] -> [Id] -> CoreExpr
buildEnvStack env_ids stack_ids
ross's avatar
ross committed
174
  = foldl mkCorePairExpr (mkTupleExpr env_ids) (map Var stack_ids)
175 176 177 178

----------------------------------------------
-- 		matchEnvStack
--
ross's avatar
ross committed
179
--	\ (...((x1,...,xn),s1),...sk) -> e
180
--	=>
ross's avatar
ross committed
181 182
--	\ zk ->
--	case zk of (zk-1,sk) ->
183 184
--	...
--	case z1 of (z0,s1) ->
ross's avatar
ross committed
185
--	case z0 of (x1,...,xn) ->
186 187
--	e

ross's avatar
ross committed
188 189
matchEnvStack	:: [Id] 	-- x1..xn
		-> [Id] 	-- s1..sk
190 191 192
		-> CoreExpr 	-- e
		-> DsM CoreExpr
matchEnvStack env_ids stack_ids body
193
  = newUniqueSupply			`thenDs` \ uniqs ->
ross's avatar
ross committed
194
    newSysLocalDs (mkTupleType env_ids)	`thenDs` \ tup_var ->
195 196 197 198 199 200 201
    matchVarStack tup_var stack_ids 
		  (coreCaseTuple uniqs tup_var env_ids body)


----------------------------------------------
-- 		matchVarStack
--
ross's avatar
ross committed
202
--	\ (...(z0,s1),...sk) -> e
203
--	=>
ross's avatar
ross committed
204 205
--	\ zk ->
--	case zk of (zk-1,sk) ->
206 207 208 209 210
--	...
--	case z1 of (z0,s1) ->
--	e

matchVarStack :: Id 		-- z0
ross's avatar
ross committed
211
	      -> [Id] 		-- s1..sk
212 213 214 215 216
	      -> CoreExpr 	-- e
	      -> DsM CoreExpr
matchVarStack env_id [] body
  = returnDs (Lam env_id body)
matchVarStack env_id (stack_id:stack_ids) body
ross's avatar
ross committed
217 218
  = newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
					`thenDs` \ pair_id ->
219
    matchVarStack pair_id stack_ids 
ross's avatar
ross committed
220
		  (coreCasePair pair_id env_id stack_id body)
221 222 223
\end{code}

\begin{code}
224
mkHsTupleExpr :: [HsExpr Id] -> HsExpr Id
225
mkHsTupleExpr [e] = e
226
mkHsTupleExpr es = ExplicitTuple (map noLoc es) Boxed
227

228
mkHsPairExpr :: HsExpr Id -> HsExpr Id -> HsExpr Id
229 230
mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]

231
mkHsEnvStackExpr :: [Id] -> [Id] -> HsExpr Id
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
mkHsEnvStackExpr env_ids stack_ids
  = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
\end{code}

Translation of arrow abstraction

\begin{code}

--	A | xs |- c :: [] t'  	    ---> c'
--	--------------------------
--	A |- proc p -> c :: a t t'  ---> arr (\ p -> (xs)) >>> c'
--
--		where (xs) is the tuple of variables bound by p

dsProcExpr
247 248
	:: LPat Id
	-> LHsCmdTop Id
249
	-> DsM CoreExpr
250 251
dsProcExpr pat (L _ (HsCmdTop cmd [] cmd_ty ids))
  = mkCmdEnv ids			`thenDs` \ meth_ids ->
252 253 254 255 256 257
    let
	locals = mkVarSet (collectPatBinders pat)
    in
    dsfixCmd meth_ids locals [] cmd_ty cmd
				`thenDs` \ (core_cmd, free_vars, env_ids) ->
    let
ross's avatar
ross committed
258
	env_ty = mkTupleType env_ids
259 260
    in
    mkFailExpr ProcExpr env_ty		`thenDs` \ fail_expr ->
261
    selectSimpleMatchVarL pat		`thenDs` \ var ->
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
					`thenDs` \ match_code ->
    let
	pat_ty = hsPatType pat
	proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
		(Lam var match_code)
		core_cmd
    in
    returnDs (bindCmdEnv meth_ids proc_code)
\end{code}

Translation of command judgements of the form

	A | xs |- c :: [ts] t

\begin{code}
278 279
dsLCmd ids local_vars env_ids stack res_ty cmd
  = dsCmd ids local_vars env_ids stack res_ty (unLoc cmd)
280

281
dsCmd   :: DsCmdEnv		-- arrow combinators
282 283 284 285 286 287
	-> IdSet		-- set of local vars available to this command
	-> [Id]			-- list of vars in the input to this command
				-- This is typically fed back,
				-- so don't pull on it too early
	-> [Type]		-- type of the stack
	-> Type			-- return type of the command
288
	-> HsCmd Id		-- command to desugar
289 290 291
	-> DsM (CoreExpr,	-- desugared expression
		IdSet)		-- set of local vars that occur free

ross's avatar
ross committed
292
--	A |- f :: a (t*ts) t'
293
--	A, xs |- arg :: t
ross's avatar
ross committed
294 295 296 297
--	-----------------------------
--	A | xs |- f -< arg :: [ts] t'
--
--		---> arr (\ ((xs)*ts) -> (arg*ts)) >>> f
298

ross's avatar
ross committed
299
dsCmd ids local_vars env_ids stack res_ty
300
	(HsArrApp arrow arg arrow_ty HsFirstOrderApp _)
301 302
  = let
	(a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
ross's avatar
ross committed
303
        (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
ross's avatar
ross committed
304
	env_ty = mkTupleType env_ids
305
    in
306 307
    dsLExpr arrow			`thenDs` \ core_arrow ->
    dsLExpr arg				`thenDs` \ core_arg ->
ross's avatar
ross committed
308 309 310 311 312 313 314 315
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
    matchEnvStack env_ids stack_ids
	(foldl mkCorePairExpr core_arg (map Var stack_ids))
					`thenDs` \ core_make_arg ->
    returnDs (do_map_arrow ids
		(envStackType env_ids stack)
		arg_ty
		res_ty
316 317 318 319
		core_make_arg
		core_arrow,
	      exprFreeVars core_arg `intersectVarSet` local_vars)

ross's avatar
ross committed
320
--	A, xs |- f :: a (t*ts) t'
321
--	A, xs |- arg :: t
ross's avatar
ross committed
322 323 324 325
--	------------------------------
--	A | xs |- f -<< arg :: [ts] t'
--
--		---> arr (\ ((xs)*ts) -> (f,(arg*ts))) >>> app
326

ross's avatar
ross committed
327
dsCmd ids local_vars env_ids stack res_ty
328
	(HsArrApp arrow arg arrow_ty HsHigherOrderApp _)
329 330
  = let
	(a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
ross's avatar
ross committed
331
        (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
ross's avatar
ross committed
332
	env_ty = mkTupleType env_ids
333
    in
334 335
    dsLExpr arrow			`thenDs` \ core_arrow ->
    dsLExpr arg				`thenDs` \ core_arg ->
ross's avatar
ross committed
336 337 338 339
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
    matchEnvStack env_ids stack_ids
	(mkCorePairExpr core_arrow
		(foldl mkCorePairExpr core_arg (map Var stack_ids)))
340
					`thenDs` \ core_make_pair ->
ross's avatar
ross committed
341 342 343 344
    returnDs (do_map_arrow ids
		(envStackType env_ids stack)
		(mkCorePairTy arrow_ty arg_ty)
		res_ty
345 346 347 348 349
		core_make_pair
		(do_app ids arg_ty res_ty),
	      (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
		`intersectVarSet` local_vars)

ross's avatar
ross committed
350 351 352 353 354 355 356 357
--	A | ys |- c :: [t:ts] t'
--	A, xs  |- e :: t
--	------------------------
--	A | xs |- c e :: [ts] t'
--
--		---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c

dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg)
358
  = dsLExpr arg			`thenDs` \ core_arg ->
ross's avatar
ross committed
359 360 361 362 363 364
    let
	arg_ty = exprType core_arg
	stack' = arg_ty:stack
    in
    dsfixCmd ids local_vars stack' res_ty cmd
				`thenDs` \ (core_cmd, free_vars, env_ids') ->
365
    mappM newSysLocalDs stack	`thenDs` \ stack_ids ->
ross's avatar
ross committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    newSysLocalDs arg_ty	`thenDs` \ arg_id ->
    -- push the argument expression onto the stack
    let
	core_body = bindNonRec arg_id core_arg
			(buildEnvStack env_ids' (arg_id:stack_ids))
    in
    -- match the environment and stack against the input
    matchEnvStack env_ids stack_ids core_body
				`thenDs` \ core_map ->
    returnDs (do_map_arrow ids
			(envStackType env_ids stack)
			(envStackType env_ids' stack')
			res_ty
			core_map
			core_cmd,
	(exprFreeVars core_arg `intersectVarSet` local_vars)
		`unionVarSet` free_vars)

384 385 386 387 388 389 390
--	A | ys |- c :: [ts] t'
--	-----------------------------------------------
--	A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
--
--		---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c

dsCmd ids local_vars env_ids stack res_ty
391
    (HsLam (MatchGroup [L _ (Match pats _ (GRHSs [L _ (GRHS [] body)] _ ))] _))
392 393 394 395 396 397 398
  = let
	pat_vars = mkVarSet (collectPatsBinders pats)
	local_vars' = local_vars `unionVarSet` pat_vars
	stack' = drop (length pats) stack
    in
    dsfixCmd ids local_vars' stack' res_ty body
				`thenDs` \ (core_body, free_vars, env_ids') ->
399
    mappM newSysLocalDs stack	`thenDs` \ stack_ids ->
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

    -- the expression is built from the inside out, so the actions
    -- are presented in reverse order

    let
        (actual_ids, stack_ids') = splitAt (length pats) stack_ids
	-- build a new environment, plus what's left of the stack
	core_expr = buildEnvStack env_ids' stack_ids'
	in_ty = envStackType env_ids stack
	in_ty' = envStackType env_ids' stack'
    in
    mkFailExpr LambdaExpr in_ty'	`thenDs` \ fail_expr ->
    -- match the patterns against the top of the old stack
    matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
					`thenDs` \ match_code ->
    -- match the old environment and stack against the input
    matchEnvStack env_ids stack_ids match_code
					`thenDs` \ select_code ->
    returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
	     free_vars `minusVarSet` pat_vars)

dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
422
  = dsLCmd ids local_vars env_ids stack res_ty cmd
423

ross's avatar
ross committed
424 425 426 427 428 429 430 431 432 433
--	A, xs |- e :: Bool
--	A | xs1 |- c1 :: [ts] t
--	A | xs2 |- c2 :: [ts] t
--	----------------------------------------
--	A | xs |- if e then c1 else c2 :: [ts] t
--
--		---> arr (\ ((xs)*ts) ->
--			if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
--		     c1 ||| c2

434 435
dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd)
  = dsLExpr cond			`thenDs` \ core_cond ->
ross's avatar
ross committed
436 437 438 439
    dsfixCmd ids local_vars stack res_ty then_cmd
				`thenDs` \ (core_then, fvs_then, then_ids) ->
    dsfixCmd ids local_vars stack res_ty else_cmd
				`thenDs` \ (core_else, fvs_else, else_ids) ->
440
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
ross's avatar
ross committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    dsLookupTyCon eitherTyConName	`thenDs` \ either_con ->
    dsLookupDataCon leftDataConName	`thenDs` \ left_con ->
    dsLookupDataCon rightDataConName	`thenDs` \ right_con ->
    let
	left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
	right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]

	in_ty = envStackType env_ids stack
	then_ty = envStackType then_ids stack
	else_ty = envStackType else_ids stack
	sum_ty = mkTyConApp either_con [then_ty, else_ty]
	fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
    in
    matchEnvStack env_ids stack_ids
	(mkIfThenElse core_cond
	    (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
	    (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
					`thenDs` \ core_if ->
    returnDs(do_map_arrow ids in_ty sum_ty res_ty
		core_if
		(do_choice ids then_ty else_ty res_ty core_then core_else),
	fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
\end{code}

Case commands are treated in much the same way as if commands
(see above) except that there are more alternatives.  For example

	case e of { p1 -> c1; p2 -> c2; p3 -> c3 }

is translated to

	arr (\ ((xs)*ts) -> case e of
		p1 -> (Left (Left (xs1)*ts))
		p2 -> Left ((Right (xs2)*ts))
		p3 -> Right ((xs3)*ts)) >>>
	(c1 ||| c2) ||| c3

The idea is to extract the commands from the case, build a balanced tree
of choices, and replace the commands with expressions that build tagged
tuples, obtaining a case expression that can be desugared normally.
To build all this, we use quadruples decribing segments of the list of
case bodies, containing the following fields:
1. an IdSet containing the environment variables free in the case bodies
2. a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
   into the case replacing the commands
3. a sum type that is the common type of these expressions, and also the
   input type of the arrow
4. a CoreExpr for an arrow built by combining the translated command
   bodies with |||.

\begin{code}
492
dsCmd ids local_vars env_ids stack res_ty (HsCase exp (MatchGroup matches match_ty))
493
  = dsLExpr exp				`thenDs` \ core_exp ->
494
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
495 496 497 498 499 500 501 502

    -- Extract and desugar the leaf commands in the case, building tuple
    -- expressions that will (after tagging) replace these leaves

    let
        leaves = concatMap leavesMatch matches
	make_branch (leaf, bound_vars)
	  = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
503
			   `thenDs` \ (core_leaf, fvs, leaf_ids) ->
504
	    returnDs (fvs `minusVarSet` bound_vars,
505
		      [noLoc $ mkHsEnvStackExpr leaf_ids stack_ids],
506 507 508
		      envStackType leaf_ids stack,
		      core_leaf)
    in
509
    mappM make_branch leaves		`thenDs` \ branches ->
510 511 512 513
    dsLookupTyCon eitherTyConName	`thenDs` \ either_con ->
    dsLookupDataCon leftDataConName	`thenDs` \ left_con ->
    dsLookupDataCon rightDataConName	`thenDs` \ right_con ->
    let
514 515 516 517
	left_id = nlHsVar (dataConWrapId left_con)
	right_id = nlHsVar (dataConWrapId right_con)
	left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ TyApp left_id [ty1, ty2]) e
	right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ TyApp right_id [ty1, ty2]) e
518 519 520 521 522 523 524 525 526 527 528

	-- Prefix each tuple with a distinct series of Left's and Right's,
	-- in a balanced way, keeping track of the types.

        merge_branches (fvs1, builds1, in_ty1, core_exp1)
		       (fvs2, builds2, in_ty2, core_exp2) 
	  = (fvs1 `unionVarSet` fvs2,
	     map (left_expr in_ty1 in_ty2) builds1 ++
		map (right_expr in_ty1 in_ty2) builds2,
	     mkTyConApp either_con [in_ty1, in_ty2],
	     do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
ross's avatar
ross committed
529 530
	(fvs_alts, leaves', sum_ty, core_choices)
	  = foldb merge_branches branches
531 532

	-- Replace the commands in the case with these tagged tuples,
533
	-- yielding a HsExpr Id we can feed to dsExpr.
534 535 536

	(_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
	in_ty = envStackType env_ids stack
ross's avatar
ross committed
537
	fvs_exp = exprFreeVars core_exp `intersectVarSet` local_vars
538 539 540 541 542

	pat_ty    = funArgTy match_ty
	match_ty' = mkFunTy pat_ty sum_ty
	-- Note that we replace the HsCase result type by sum_ty,
	-- which is the type of matches'
543
    in
544
    dsExpr (HsCase exp (MatchGroup matches' match_ty')) `thenDs` \ core_body ->
ross's avatar
ross committed
545 546
    matchEnvStack env_ids stack_ids core_body
					`thenDs` \ core_matches ->
547
    returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
548
	     fvs_exp `unionVarSet` fvs_alts)
549 550 551 552 553 554 555 556 557

--	A | ys |- c :: [ts] t
--	----------------------------------
--	A | xs |- let binds in c :: [ts] t
--
--		---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c

dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
  = let
558
	defined_vars = mkVarSet (map unLoc (collectLocalBinders binds))
559 560 561 562
	local_vars' = local_vars `unionVarSet` defined_vars
    in
    dsfixCmd ids local_vars' stack res_ty body
				`thenDs` \ (core_body, free_vars, env_ids') ->
563
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
564
    -- build a new environment, plus the stack, using the let bindings
565
    dsLocalBinds binds (buildEnvStack env_ids' stack_ids)
566 567 568 569 570 571 572 573 574 575 576 577
					`thenDs` \ core_binds ->
    -- match the old environment and stack against the input
    matchEnvStack env_ids stack_ids core_binds
					`thenDs` \ core_map ->
    returnDs (do_map_arrow ids
			(envStackType env_ids stack)
			(envStackType env_ids' stack)
			res_ty
			core_map
			core_body,
	exprFreeVars core_binds `intersectVarSet` local_vars)

578 579
dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts body _)
  = dsCmdDo ids local_vars env_ids res_ty stmts body
580 581 582 583

--	A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
--	A | xs |- ci :: [tsi] ti
--	-----------------------------------
ross's avatar
ross committed
584
--	A | xs |- (|e c1 ... cn|) :: [ts] t	---> e [t_xs] c1 ... cn
585

586
dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args)
587
  = let
ross's avatar
ross committed
588
	env_ty = mkTupleType env_ids
589
    in
590
    dsLExpr op				`thenDs` \ core_op ->
591 592 593 594 595 596 597 598 599 600 601 602
    mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
					`thenDs` \ (core_args, fv_sets) ->
    returnDs (mkApps (App core_op (Type env_ty)) core_args,
	      unionVarSets fv_sets)

--	A | ys |- c :: [ts] t	(ys <= xs)
--	---------------------
--	A | xs |- c :: [ts] t	---> arr_ts (\ (xs) -> (ys)) >>> c

dsTrimCmdArg
	:: IdSet		-- set of local vars available to this command
	-> [Id]			-- list of vars in the input to this command
603
	-> LHsCmdTop Id	-- command argument to desugar
604 605
	-> DsM (CoreExpr,	-- desugared expression
		IdSet)		-- set of local vars that occur free
606
dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack cmd_ty ids))
607 608 609
  = mkCmdEnv ids			`thenDs` \ meth_ids ->
    dsfixCmd meth_ids local_vars stack cmd_ty cmd
				`thenDs` \ (core_cmd, free_vars, env_ids') ->
610
    mappM newSysLocalDs stack		`thenDs` \ stack_ids ->
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
					`thenDs` \ trim_code ->
    let
	in_ty = envStackType env_ids stack
	in_ty' = envStackType env_ids' stack
	arg_code = if env_ids' == env_ids then core_cmd else
		do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
    in
    returnDs (bindCmdEnv meth_ids arg_code, free_vars)

-- Given A | xs |- c :: [ts] t, builds c with xs fed back.
-- Typically needs to be prefixed with arr (\p -> ((xs)*ts))

dsfixCmd
	:: DsCmdEnv		-- arrow combinators
	-> IdSet		-- set of local vars available to this command
	-> [Type]		-- type of the stack
	-> Type			-- return type of the command
629
	-> LHsCmd Id		-- command to desugar
630 631 632 633 634
	-> DsM (CoreExpr,	-- desugared expression
		IdSet,		-- set of local vars that occur free
		[Id])		-- set as a list, fed back
dsfixCmd ids local_vars stack cmd_ty cmd
  = fixDs (\ ~(_,_,env_ids') ->
635
	dsLCmd ids local_vars env_ids' stack cmd_ty cmd
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
					`thenDs` \ (core_cmd, free_vars) ->
	returnDs (core_cmd, free_vars, varSetElems free_vars))

\end{code}

Translation of command judgements of the form

	A | xs |- do { ss } :: [] t

\begin{code}

dsCmdDo :: DsCmdEnv		-- arrow combinators
	-> IdSet		-- set of local vars available to this statement
	-> [Id]			-- list of vars in the input to this statement
				-- This is typically fed back,
				-- so don't pull on it too early
	-> Type			-- return type of the statement
653 654
	-> [LStmt Id]		-- statements to desugar
	-> LHsExpr Id		-- body
655 656 657 658 659 660 661
	-> DsM (CoreExpr,	-- desugared expression
		IdSet)		-- set of local vars that occur free

--	A | xs |- c :: [] t
--	--------------------------
--	A | xs |- do { c } :: [] t

662 663
dsCmdDo ids local_vars env_ids res_ty [] body
  = dsLCmd ids local_vars env_ids [] res_ty body
664

665
dsCmdDo ids local_vars env_ids res_ty (stmt:stmts) body
666
  = let
667
	bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
668 669 670
	local_vars' = local_vars `unionVarSet` bound_vars
    in
    fixDs (\ ~(_,_,env_ids') ->
671
	dsCmdDo ids local_vars' env_ids' res_ty stmts body
672 673 674
					`thenDs` \ (core_stmts, fv_stmts) ->
	returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
				`thenDs` \ (core_stmts, fv_stmts, env_ids') ->
675
    dsCmdLStmt ids local_vars env_ids env_ids' stmt
676 677
				`thenDs` \ (core_stmt, fv_stmt) ->
    returnDs (do_compose ids
ross's avatar
ross committed
678 679
		(mkTupleType env_ids)
		(mkTupleType env_ids')
680 681 682 683 684
		res_ty
		core_stmt
		core_stmts,
	      fv_stmt)

ross's avatar
ross committed
685 686 687 688 689
\end{code}
A statement maps one local environment to another, and is represented
as an arrow from one tuple type to another.  A statement sequence is
translated to a composition of such arrows.
\begin{code}
690 691
dsCmdLStmt ids local_vars env_ids out_ids cmd
  = dsCmdStmt ids local_vars env_ids out_ids (unLoc cmd)
ross's avatar
ross committed
692

693 694 695 696 697 698 699
dsCmdStmt
	:: DsCmdEnv		-- arrow combinators
	-> IdSet		-- set of local vars available to this statement
	-> [Id]			-- list of vars in the input to this statement
				-- This is typically fed back,
				-- so don't pull on it too early
	-> [Id]			-- list of vars in the output of this statement
700
	-> Stmt Id	-- statement to desugar
701 702 703 704
	-> DsM (CoreExpr,	-- desugared expression
		IdSet)		-- set of local vars that occur free

--	A | xs1 |- c :: [] t
ross's avatar
ross committed
705
--	A | xs' |- do { ss } :: [] t'
706
--	------------------------------
ross's avatar
ross committed
707
--	A | xs |- do { c; ss } :: [] t'
708 709 710 711
--
--		---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
--			arr snd >>> ss

712
dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd _ c_ty)
713 714 715 716 717 718
  = dsfixCmd ids local_vars [] c_ty cmd
				`thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
    matchEnvStack env_ids []
	(mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
					`thenDs` \ core_mux ->
    let
ross's avatar
ross committed
719 720 721
	in_ty = mkTupleType env_ids
	in_ty1 = mkTupleType env_ids1
	out_ty = mkTupleType out_ids
722 723 724 725 726 727 728 729
	before_c_ty = mkCorePairTy in_ty1 out_ty
	after_c_ty = mkCorePairTy c_ty out_ty
    in
    mkSndExpr c_ty out_ty		`thenDs` \ snd_fn ->
    returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
		do_compose ids before_c_ty after_c_ty out_ty
			(do_first ids in_ty1 c_ty out_ty core_cmd) $
		do_arr ids after_c_ty out_ty snd_fn,
730
	      extendVarSetList fv_cmd out_ids)
731 732 733
  where

--	A | xs1 |- c :: [] t
ross's avatar
ross committed
734
--	A | xs' |- do { ss } :: [] t'		xs2 = xs' - defs(p)
735
--	-----------------------------------
ross's avatar
ross committed
736
--	A | xs |- do { p <- c; ss } :: [] t'
737 738 739 740 741 742 743
--
--		---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
--			arr (\ (p, (xs2)) -> (xs')) >>> ss
--
-- It would be simpler and more consistent to do this using second,
-- but that's likely to be defined in terms of first.

744
dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _ _)
745 746 747
  = dsfixCmd ids local_vars [] (hsPatType pat) cmd
				`thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
    let
ross's avatar
ross committed
748
	pat_ty = hsPatType pat
749 750
	pat_vars = mkVarSet (collectPatBinders pat)
	env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
ross's avatar
ross committed
751
	env_ty2 = mkTupleType env_ids2
752 753 754 755 756 757 758 759 760 761 762 763
    in

    -- multiplexing function
    --		\ (xs) -> ((xs1),(xs2))

    matchEnvStack env_ids []
	(mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
					`thenDs` \ core_mux ->

    -- projection function
    --		\ (p, (xs2)) -> (zs)

ross's avatar
ross committed
764
    newSysLocalDs env_ty2		`thenDs` \ env_id ->
765
    newUniqueSupply			`thenDs` \ uniqs ->
766
    let
ross's avatar
ross committed
767 768
	after_c_ty = mkCorePairTy pat_ty env_ty2
	out_ty = mkTupleType out_ids
769 770 771
	body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
    in
    mkFailExpr (StmtCtxt DoExpr) out_ty	`thenDs` \ fail_expr ->
772
    selectSimpleMatchVarL pat		`thenDs` \ pat_id ->
773 774 775 776
    matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
					`thenDs` \ match_code ->
    newSysLocalDs after_c_ty		`thenDs` \ pair_id ->
    let
ross's avatar
ross committed
777
	proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
778 779
    in

ross's avatar
ross committed
780
    -- put it all together
781
    let
ross's avatar
ross committed
782 783 784
	in_ty = mkTupleType env_ids
	in_ty1 = mkTupleType env_ids1
	in_ty2 = mkTupleType env_ids2
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
	before_c_ty = mkCorePairTy in_ty1 in_ty2
    in
    returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
		do_compose ids before_c_ty after_c_ty out_ty
			(do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
		do_arr ids after_c_ty out_ty proj_expr,
	      fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))

--	A | xs' |- do { ss } :: [] t
--	--------------------------------------
--	A | xs |- do { let binds; ss } :: [] t
--
--		---> arr (\ (xs) -> let binds in (xs')) >>> ss

dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
    -- build a new environment using the let bindings
801
  = dsLocalBinds binds (mkTupleExpr out_ids)	`thenDs` \ core_binds ->
802 803 804
    -- match the old environment against the input
    matchEnvStack env_ids [] core_binds	`thenDs` \ core_map ->
    returnDs (do_arr ids
ross's avatar
ross committed
805 806
			(mkTupleType env_ids)
			(mkTupleType out_ids)
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
			core_map,
	exprFreeVars core_binds `intersectVarSet` local_vars)

--	A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
--	A | xs' |- do { ss' } :: [] t
--	------------------------------------
--	A | xs |- do { rec ss; ss' } :: [] t
--
--			xs1 = xs' /\ defs(ss)
--			xs2 = xs' - defs(ss)
--			ys1 = ys - defs(ss)
--			ys2 = ys /\ defs(ss)
--
--		---> arr (\(xs) -> ((ys1),(xs2))) >>>
--			first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
--			arr (\((xs1),(xs2)) -> (xs')) >>> ss'

824
dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss binds)
825
  = let		-- ToDo: ****** binds not desugared; ROSS PLEASE FIX ********
ross's avatar
ross committed
826 827
	env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
	env2_ids = varSetElems env2_id_set
ross's avatar
ross committed
828
	env2_ty = mkTupleType env2_ids
ross's avatar
ross committed
829 830 831 832
    in

    -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)

833
    newUniqueSupply		`thenDs` \ uniqs ->
ross's avatar
ross committed
834 835
    newSysLocalDs env2_ty	`thenDs` \ env2_id ->
    let
ross's avatar
ross committed
836 837
	later_ty = mkTupleType later_ids
	post_pair_ty = mkCorePairTy later_ty env2_ty
ross's avatar
ross committed
838 839 840 841 842 843 844 845 846 847 848 849 850
	post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
    in
    matchEnvStack later_ids [env2_id] post_loop_body
				`thenDs` \ post_loop_fn ->

    --- loop (...)

    dsRecCmd ids local_vars stmts later_ids rec_ids rhss
				`thenDs` \ (core_loop, env1_id_set, env1_ids) ->

    -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))

    let
ross's avatar
ross committed
851 852 853 854
	env1_ty = mkTupleType env1_ids
	pre_pair_ty = mkCorePairTy env1_ty env2_ty
	pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
					(mkTupleExpr env2_ids)
ross's avatar
ross committed
855 856 857 858 859 860 861 862

    in
    matchEnvStack env_ids [] pre_loop_body
				`thenDs` \ pre_loop_fn ->

    -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn

    let
ross's avatar
ross committed
863 864
	env_ty = mkTupleType env_ids
	out_ty = mkTupleType out_ids
ross's avatar
ross committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
	core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
		pre_loop_fn
		(do_compose ids pre_pair_ty post_pair_ty out_ty
			(do_first ids env1_ty later_ty env2_ty
				core_loop)
			(do_arr ids post_pair_ty out_ty
				post_loop_fn))
    in
    returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)

--	loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
--	      ss >>>
--	      arr (\ (out_ids) -> ((later_ids),(rhss))) >>>

dsRecCmd ids local_vars stmts later_ids rec_ids rhss
880 881 882
  = let
	rec_id_set = mkVarSet rec_ids
	out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
ross's avatar
ross committed
883
	out_ty = mkTupleType out_ids
884 885 886 887 888
	local_vars' = local_vars `unionVarSet` rec_id_set
    in

    -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))

889
    mappM dsExpr rhss		`thenDs` \ core_rhss ->
890 891
    let
	later_tuple = mkTupleExpr later_ids
ross's avatar
ross committed
892 893 894 895 896
	later_ty = mkTupleType later_ids
	rec_tuple = mkBigCoreTup core_rhss
	rec_ty = mkTupleType rec_ids
	out_pair = mkCorePairExpr later_tuple rec_tuple
	out_pair_ty = mkCorePairTy later_ty rec_ty
897 898 899 900
    in
	matchEnvStack out_ids [] out_pair
				`thenDs` \ mk_pair_fn ->

ross's avatar
ross committed
901 902
    -- ss

903
    dsfixCmdStmts ids local_vars' out_ids stmts
ross's avatar
ross committed
904
				`thenDs` \ (core_stmts, fv_stmts, env_ids) ->
905

ross's avatar
ross committed
906
    -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
907 908 909 910 911

    newSysLocalDs rec_ty	`thenDs` \ rec_id ->
    let
	env1_id_set = fv_stmts `minusVarSet` rec_id_set
	env1_ids = varSetElems env1_id_set
ross's avatar
ross committed
912 913 914
	env1_ty = mkTupleType env1_ids
	in_pair_ty = mkCorePairTy env1_ty rec_ty
	core_body = mkBigCoreTup (map selectVar env_ids)
915 916 917 918 919 920 921 922 923 924 925 926
	  where
	    selectVar v
		| v `elemVarSet` rec_id_set
		  = mkTupleSelector rec_ids v rec_id (Var rec_id)
		| otherwise = Var v
    in
    matchEnvStack env1_ids [rec_id] core_body
				`thenDs` \ squash_pair_fn ->

    -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)

    let
ross's avatar
ross committed
927
	env_ty = mkTupleType env_ids
928
	core_loop = do_loop ids env1_ty later_ty rec_ty
ross's avatar
ross committed
929
		(do_map_arrow ids in_pair_ty env_ty out_pair_ty
930
			squash_pair_fn
ross's avatar
ross committed
931
			(do_compose ids env_ty out_ty out_pair_ty
932 933 934
				core_stmts
				(do_arr ids out_ty out_pair_ty mk_pair_fn)))
    in
ross's avatar
ross committed
935
    returnDs (core_loop, env1_id_set, env1_ids)
936 937

\end{code}
ross's avatar
ross committed
938
A sequence of statements (as in a rec) is desugared to an arrow between
939 940 941 942 943 944 945
two environments
\begin{code}

dsfixCmdStmts
	:: DsCmdEnv		-- arrow combinators
	-> IdSet		-- set of local vars available to this statement
	-> [Id]			-- output vars of these statements
946
	-> [LStmt Id]	-- statements to desugar
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	-> DsM (CoreExpr,	-- desugared expression
		IdSet,		-- set of local vars that occur free
		[Id])		-- input vars

dsfixCmdStmts ids local_vars out_ids stmts
  = fixDs (\ ~(_,_,env_ids) ->
	dsCmdStmts ids local_vars env_ids out_ids stmts
					`thenDs` \ (core_stmts, fv_stmts) ->
	returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))

dsCmdStmts
	:: DsCmdEnv		-- arrow combinators
	-> IdSet		-- set of local vars available to this statement
	-> [Id]			-- list of vars in the input to these statements
	-> [Id]			-- output vars of these statements
962
	-> [LStmt Id]	-- statements to desugar
963 964 965 966
	-> DsM (CoreExpr,	-- desugared expression
		IdSet)		-- set of local vars that occur free

dsCmdStmts ids local_vars env_ids out_ids [stmt]
967
  = dsCmdLStmt ids local_vars env_ids out_ids stmt
968 969 970

dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
  = let
971
	bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
972 973 974 975
	local_vars' = local_vars `unionVarSet` bound_vars
    in
    dsfixCmdStmts ids local_vars' out_ids stmts
				`thenDs` \ (core_stmts, fv_stmts, env_ids') ->
976
    dsCmdLStmt ids local_vars env_ids env_ids' stmt
977 978
				`thenDs` \ (core_stmt, fv_stmt) ->
    returnDs (do_compose ids
ross's avatar
ross committed
979 980 981
		(mkTupleType env_ids)
		(mkTupleType env_ids')
		(mkTupleType out_ids)
982 983 984 985 986 987 988 989 990
		core_stmt
		core_stmts,
	      fv_stmt)

\end{code}

Match a list of expressions against a list of patterns, left-to-right.

\begin{code}
991 992 993 994 995
matchSimplys :: [CoreExpr]              -- Scrutinees
	     -> HsMatchContext Name	-- Match kind
	     -> [LPat Id]         	-- Patterns they should match
	     -> CoreExpr                -- Return this if they all match
	     -> CoreExpr                -- Return this if they don't
996
	     -> DsM CoreExpr
ross's avatar
ross committed
997
matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
998 999 1000 1001 1002 1003
matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
  = matchSimplys exps ctxt pats result_expr fail_expr
					`thenDs` \ match_code ->
    matchSimply exp ctxt pat match_code fail_expr
\end{code}

ross's avatar
ross committed
1004
List of leaf expressions, with set of variables bound in each
1005

ross's avatar
ross committed
1006
\begin{code}
1007
leavesMatch :: LMatch Id -> [(LHsExpr Id, IdSet)]
1008
leavesMatch (L _ (Match pats _ (GRHSs grhss binds)))
1009
  = let
1010 1011
	defined_vars = mkVarSet (collectPatsBinders pats)
			`unionVarSet`
1012
		       mkVarSet (map unLoc (collectLocalBinders binds))
1013
    in
1014
    [(expr, 
1015
      mkVarSet (map unLoc (collectLStmtsBinders stmts)) 
1016
	`unionVarSet` defined_vars) 
1017
    | L _ (GRHS stmts expr) <- grhss]
ross's avatar
ross committed
1018
\end{code}
1019

ross's avatar
ross committed
1020
Replace the leaf commands in a match
1021

ross's avatar
ross committed
1022
\begin{code}
1023 1024
replaceLeavesMatch
	:: Type			-- new result type
1025 1026 1027 1028
	-> [LHsExpr Id]	-- replacement leaf expressions of that type
	-> LMatch Id	-- the matches of a case command
	-> ([LHsExpr Id],-- remaining leaf expressions
	    LMatch Id)	-- updated match
1029
replaceLeavesMatch res_ty leaves (L loc (Match pat mt (GRHSs grhss binds)))
1030
  = let
ross's avatar
ross committed
1031
	(leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
1032
    in
1033
    (leaves', L loc (Match pat mt (GRHSs grhss' binds)))
1034 1035

replaceLeavesGRHS
1036 1037 1038 1039
	:: [LHsExpr Id]	-- replacement leaf expressions of that type
	-> LGRHS Id	-- rhss of a case command
	-> ([LHsExpr Id],-- remaining leaf expressions
	    LGRHS Id)	-- updated GRHS
1040 1041
replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts rhs))
  = (leaves, L loc (GRHS stmts leaf))
1042 1043 1044 1045 1046 1047
\end{code}

Balanced fold of a non-empty list.

\begin{code}
foldb :: (a -> a -> a) -> [a] -> a
ross's avatar
ross committed
1048 1049
foldb _ [] = error "foldb of empty list"
foldb _ [x] = x
1050 1051 1052 1053 1054 1055
foldb f xs = foldb f (fold_pairs xs)
  where
    fold_pairs [] = []
    fold_pairs [x] = [x]
    fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs
\end{code}