2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[DsArrows]{Desugaring arrow commands}
7 module DsArrows ( dsProcExpr ) where
9 #include "HsVersions.h"
11 import Match ( matchSimply )
12 import DsUtils ( mkErrorAppDs,
13 mkCoreTupTy, mkCoreTup, selectMatchVar,
14 mkTupleCase, mkBigCoreTup, mkTupleType,
15 mkTupleExpr, mkTupleSelector,
16 dsReboundNames, lookupReboundName )
19 import HsSyn ( HsExpr(..),
20 Stmt(..), HsMatchContext(..), HsStmtContext(..),
21 Match(..), GRHSs(..), GRHS(..),
22 HsCmdTop(..), HsArrAppType(..),
25 collectStmtBinders, collectStmtsBinders,
28 import TcHsSyn ( TypecheckedHsCmd, TypecheckedHsCmdTop,
29 TypecheckedHsExpr, TypecheckedPat,
30 TypecheckedMatch, TypecheckedGRHS,
31 TypecheckedStmt, hsPatType,
32 TypecheckedMatchContext )
34 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
35 -- needs to see source types (newtypes etc), and sometimes not
36 -- So WATCH OUT; check each use of split*Ty functions.
37 -- Sigh. This is a pain.
39 import {-# SOURCE #-} DsExpr ( dsExpr, dsLet )
41 import TcType ( Type, tcSplitAppTy )
42 import Type ( mkTyConApp )
44 import CoreFVs ( exprFreeVars )
45 import CoreUtils ( mkIfThenElse, bindNonRec )
47 import Id ( Id, idType )
48 import PrelInfo ( pAT_ERROR_ID )
49 import DataCon ( dataConWrapId )
50 import TysWiredIn ( tupleCon )
51 import BasicTypes ( Boxity(..) )
52 import PrelNames ( eitherTyConName, leftDataConName, rightDataConName,
53 arrAName, composeAName, firstAName,
54 appAName, choiceAName, loopAName )
55 import Util ( mapAccumL )
58 import HsPat ( collectPatBinders, collectPatsBinders )
59 import VarSet ( IdSet, mkVarSet, varSetElems,
60 intersectVarSet, minusVarSet,
61 unionVarSet, unionVarSets, elemVarSet )
62 import SrcLoc ( SrcLoc )
66 data DsCmdEnv = DsCmdEnv {
67 meth_binds :: [CoreBind],
68 arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
71 mkCmdEnv :: ReboundNames Id -> DsM DsCmdEnv
73 = dsReboundNames ids `thenDs` \ (meth_binds, ds_meths) ->
75 meth_binds = meth_binds,
76 arr_id = lookupReboundName ds_meths arrAName,
77 compose_id = lookupReboundName ds_meths composeAName,
78 first_id = lookupReboundName ds_meths firstAName,
79 app_id = lookupReboundName ds_meths appAName,
80 choice_id = lookupReboundName ds_meths choiceAName,
81 loop_id = lookupReboundName ds_meths loopAName
84 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
85 bindCmdEnv ids body = foldr Let body (meth_binds ids)
87 -- arr :: forall b c. (b -> c) -> a b c
88 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
89 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
91 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
92 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
93 CoreExpr -> CoreExpr -> CoreExpr
94 do_compose ids b_ty c_ty d_ty f g
95 = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
97 -- first :: forall b c d. a b c -> a (b,d) (c,d)
98 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
99 do_first ids b_ty c_ty d_ty f
100 = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
102 -- app :: forall b c. a (a b c, b) c
103 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
104 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
106 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
107 -- note the swapping of d and c
108 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
109 CoreExpr -> CoreExpr -> CoreExpr
110 do_choice ids b_ty c_ty d_ty f g
111 = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
113 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
114 -- note the swapping of d and c
115 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
116 do_loop ids b_ty c_ty d_ty f
117 = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
119 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
120 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
121 CoreExpr -> CoreExpr -> CoreExpr
122 do_map_arrow ids b_ty c_ty d_ty f c
123 = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
125 mkFailExpr :: TypecheckedMatchContext -> Type -> DsM CoreExpr
127 = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
129 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
130 mkSndExpr :: Type -> Type -> DsM CoreExpr
132 = newSysLocalDs a_ty `thenDs` \ a_var ->
133 newSysLocalDs b_ty `thenDs` \ b_var ->
134 newSysLocalDs (mkCorePairTy a_ty b_ty) `thenDs` \ pair_var ->
135 returnDs (Lam pair_var
136 (coreCasePair pair_var a_var b_var (Var b_var)))
139 Build case analysis of a tuple. This cannot be done in the DsM monad,
140 because the list of variables is typically not yet defined.
143 -- coreCaseTuple [u1..] v [x1..xn] body
144 -- = case v of v { (x1, .., xn) -> body }
145 -- But the matching may be nested if the tuple is very big
147 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
148 coreCaseTuple uniqs scrut_var vars body
149 = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
151 coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
152 coreCasePair scrut_var var1 var2 body
153 = Case (Var scrut_var) scrut_var
154 [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
158 mkCorePairTy :: Type -> Type -> Type
159 mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]
161 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
162 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
165 The input is divided into a local environment, which is a flat tuple
166 (unless it's too big), and a stack, each element of which is paired
167 with the stack in turn. In general, the input has the form
169 (...((x1,...,xn),s1),...sk)
171 where xi are the environment values, and si the ones on the stack,
172 with s1 being the "top", the first one to be matched with a lambda.
175 envStackType :: [Id] -> [Type] -> Type
176 envStackType ids stack_tys = foldl mkCorePairTy (mkTupleType ids) stack_tys
178 ----------------------------------------------
181 -- (...((x1,...,xn),s1),...sk)
183 buildEnvStack :: [Id] -> [Id] -> CoreExpr
184 buildEnvStack env_ids stack_ids
185 = foldl mkCorePairExpr (mkTupleExpr env_ids) (map Var stack_ids)
187 ----------------------------------------------
190 -- \ (...((x1,...,xn),s1),...sk) -> e
193 -- case zk of (zk-1,sk) ->
195 -- case z1 of (z0,s1) ->
196 -- case z0 of (x1,...,xn) ->
199 matchEnvStack :: [Id] -- x1..xn
203 matchEnvStack env_ids stack_ids body
204 = getUniqSupplyDs `thenDs` \ uniqs ->
205 newSysLocalDs (mkTupleType env_ids) `thenDs` \ tup_var ->
206 matchVarStack tup_var stack_ids
207 (coreCaseTuple uniqs tup_var env_ids body)
210 ----------------------------------------------
213 -- \ (...(z0,s1),...sk) -> e
216 -- case zk of (zk-1,sk) ->
218 -- case z1 of (z0,s1) ->
221 matchVarStack :: Id -- z0
225 matchVarStack env_id [] body
226 = returnDs (Lam env_id body)
227 matchVarStack env_id (stack_id:stack_ids) body
228 = newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
229 `thenDs` \ pair_id ->
230 matchVarStack pair_id stack_ids
231 (coreCasePair pair_id env_id stack_id body)
235 mkHsTupleExpr :: [TypecheckedHsExpr] -> TypecheckedHsExpr
236 mkHsTupleExpr [e] = e
237 mkHsTupleExpr es = ExplicitTuple es Unboxed
239 mkHsPairExpr :: TypecheckedHsExpr -> TypecheckedHsExpr -> TypecheckedHsExpr
240 mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]
242 mkHsEnvStackExpr :: [Id] -> [Id] -> TypecheckedHsExpr
243 mkHsEnvStackExpr env_ids stack_ids
244 = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
247 Translation of arrow abstraction
251 -- A | xs |- c :: [] t' ---> c'
252 -- --------------------------
253 -- A |- proc p -> c :: a t t' ---> arr (\ p -> (xs)) >>> c'
255 -- where (xs) is the tuple of variables bound by p
259 -> TypecheckedHsCmdTop
262 dsProcExpr pat (HsCmdTop cmd [] cmd_ty ids) locn
264 mkCmdEnv ids `thenDs` \ meth_ids ->
266 locals = mkVarSet (collectPatBinders pat)
268 dsfixCmd meth_ids locals [] cmd_ty cmd
269 `thenDs` \ (core_cmd, free_vars, env_ids) ->
271 env_ty = mkTupleType env_ids
273 mkFailExpr ProcExpr env_ty `thenDs` \ fail_expr ->
274 selectMatchVar pat `thenDs` \ var ->
275 matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
276 `thenDs` \ match_code ->
278 pat_ty = hsPatType pat
279 proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
283 returnDs (bindCmdEnv meth_ids proc_code)
287 Translation of command judgements of the form
289 A | xs |- c :: [ts] t
293 dsCmd :: DsCmdEnv -- arrow combinators
294 -> IdSet -- set of local vars available to this command
295 -> [Id] -- list of vars in the input to this command
296 -- This is typically fed back,
297 -- so don't pull on it too early
298 -> [Type] -- type of the stack
299 -> Type -- return type of the command
300 -> TypecheckedHsCmd -- command to desugar
301 -> DsM (CoreExpr, -- desugared expression
302 IdSet) -- set of local vars that occur free
306 -- ---------------------------
307 -- A | xs |- f -< arg :: [] t' ---> arr (\ (xs) -> arg) >>> f
309 dsCmd ids local_vars env_ids [] res_ty
310 (HsArrApp arrow arg arrow_ty HsFirstOrderApp _ _)
312 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
313 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
314 env_ty = mkTupleType env_ids
316 dsExpr arrow `thenDs` \ core_arrow ->
317 dsExpr arg `thenDs` \ core_arg ->
318 matchEnvStack env_ids [] core_arg `thenDs` \ core_make_arg ->
319 returnDs (do_map_arrow ids env_ty arg_ty res_ty
322 exprFreeVars core_arg `intersectVarSet` local_vars)
324 -- A, xs |- f :: a t t'
326 -- ---------------------------
327 -- A | xs |- f -<< arg :: [] t' ---> arr (\ (xs) -> (f,arg)) >>> app
329 dsCmd ids local_vars env_ids [] res_ty
330 (HsArrApp arrow arg arrow_ty HsHigherOrderApp _ _)
332 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
333 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
334 env_ty = mkTupleType env_ids
336 dsExpr arrow `thenDs` \ core_arrow ->
337 dsExpr arg `thenDs` \ core_arg ->
338 matchEnvStack env_ids [] (mkCorePairExpr core_arrow core_arg)
339 `thenDs` \ core_make_pair ->
340 returnDs (do_map_arrow ids env_ty (mkCorePairTy arrow_ty arg_ty) res_ty
342 (do_app ids arg_ty res_ty),
343 (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
344 `intersectVarSet` local_vars)
346 -- A | ys |- c :: [ts] t'
347 -- -----------------------------------------------
348 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
350 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
352 dsCmd ids local_vars env_ids stack res_ty
353 (HsLam (Match pats _ (GRHSs [GRHS [ResultStmt body _] _loc] _ _cmd_ty)))
355 pat_vars = mkVarSet (collectPatsBinders pats)
356 local_vars' = local_vars `unionVarSet` pat_vars
357 stack' = drop (length pats) stack
359 dsfixCmd ids local_vars' stack' res_ty body
360 `thenDs` \ (core_body, free_vars, env_ids') ->
361 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
363 -- the expression is built from the inside out, so the actions
364 -- are presented in reverse order
367 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
368 -- build a new environment, plus what's left of the stack
369 core_expr = buildEnvStack env_ids' stack_ids'
370 in_ty = envStackType env_ids stack
371 in_ty' = envStackType env_ids' stack'
373 mkFailExpr LambdaExpr in_ty' `thenDs` \ fail_expr ->
374 -- match the patterns against the top of the old stack
375 matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
376 `thenDs` \ match_code ->
377 -- match the old environment and stack against the input
378 matchEnvStack env_ids stack_ids match_code
379 `thenDs` \ select_code ->
380 returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
381 free_vars `minusVarSet` pat_vars)
383 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
384 = dsCmd ids local_vars env_ids stack res_ty cmd
386 dsCmd ids local_vars env_ids stack res_ty (HsCase exp matches src_loc)
387 = dsExpr exp `thenDs` \ core_exp ->
388 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
390 -- Extract and desugar the leaf commands in the case, building tuple
391 -- expressions that will (after tagging) replace these leaves
394 leaves = concatMap leavesMatch matches
395 make_branch (leaf, bound_vars)
396 = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
397 `thenDs` \ (core_leaf, fvs, leaf_ids) ->
398 returnDs (fvs `minusVarSet` bound_vars,
399 [mkHsEnvStackExpr leaf_ids stack_ids],
400 envStackType leaf_ids stack,
403 mapDs make_branch leaves `thenDs` \ branches ->
404 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
405 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
406 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
408 left_id = HsVar (dataConWrapId left_con)
409 right_id = HsVar (dataConWrapId right_con)
410 left_expr ty1 ty2 e = HsApp (TyApp left_id [ty1, ty2]) e
411 right_expr ty1 ty2 e = HsApp (TyApp right_id [ty1, ty2]) e
413 -- Prefix each tuple with a distinct series of Left's and Right's,
414 -- in a balanced way, keeping track of the types.
416 merge_branches (fvs1, builds1, in_ty1, core_exp1)
417 (fvs2, builds2, in_ty2, core_exp2)
418 = (fvs1 `unionVarSet` fvs2,
419 map (left_expr in_ty1 in_ty2) builds1 ++
420 map (right_expr in_ty1 in_ty2) builds2,
421 mkTyConApp either_con [in_ty1, in_ty2],
422 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
423 (fvs, leaves', sum_ty, core_choices) = foldb merge_branches branches
425 -- Replace the commands in the case with these tagged tuples,
426 -- yielding a TypecheckedHsExpr we can feed to dsExpr.
428 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
429 in_ty = envStackType env_ids stack
431 dsExpr (HsCase exp matches' src_loc) `thenDs` \ core_matches ->
432 returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
433 exprFreeVars core_exp `unionVarSet` fvs)
435 -- A, xs |- e :: Bool
436 -- A | xs1 |- c1 :: [ts] t
437 -- A | xs2 |- c2 :: [ts] t
438 -- ----------------------------------------
439 -- A | xs |- if e then c1 else c2 :: [ts] t
441 -- ---> arr (\ ((xs)*ts) ->
442 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
445 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd _loc)
446 = dsExpr cond `thenDs` \ core_cond ->
447 dsfixCmd ids local_vars stack res_ty then_cmd
448 `thenDs` \ (core_then, fvs_then, then_ids) ->
449 dsfixCmd ids local_vars stack res_ty else_cmd
450 `thenDs` \ (core_else, fvs_else, else_ids) ->
451 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
452 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
453 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
454 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
456 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
457 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
459 in_ty = envStackType env_ids stack
460 then_ty = envStackType then_ids stack
461 else_ty = envStackType else_ids stack
462 sum_ty = mkTyConApp either_con [then_ty, else_ty]
464 matchEnvStack env_ids stack_ids
465 (mkIfThenElse core_cond
466 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
467 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
468 `thenDs` \ core_if ->
469 returnDs(do_map_arrow ids in_ty sum_ty res_ty
471 (do_choice ids then_ty else_ty res_ty core_then core_else),
472 exprFreeVars core_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
474 -- A | ys |- c :: [ts] t
475 -- ----------------------------------
476 -- A | xs |- let binds in c :: [ts] t
478 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
480 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
482 defined_vars = mkVarSet (collectHsBinders binds)
483 local_vars' = local_vars `unionVarSet` defined_vars
485 dsfixCmd ids local_vars' stack res_ty body
486 `thenDs` \ (core_body, free_vars, env_ids') ->
487 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
488 -- build a new environment, plus the stack, using the let bindings
489 dsLet binds (buildEnvStack env_ids' stack_ids)
490 `thenDs` \ core_binds ->
491 -- match the old environment and stack against the input
492 matchEnvStack env_ids stack_ids core_binds
493 `thenDs` \ core_map ->
494 returnDs (do_map_arrow ids
495 (envStackType env_ids stack)
496 (envStackType env_ids' stack)
500 exprFreeVars core_binds `intersectVarSet` local_vars)
502 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts _ _ _loc)
503 = dsCmdDo ids local_vars env_ids res_ty stmts
505 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
506 -- A | xs |- ci :: [tsi] ti
507 -- -----------------------------------
508 -- A | xs |- (|e|) c1 ... cn :: [ts] t ---> e [t_xs] c1 ... cn
510 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args _)
512 env_ty = mkTupleType env_ids
514 dsExpr op `thenDs` \ core_op ->
515 mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
516 `thenDs` \ (core_args, fv_sets) ->
517 returnDs (mkApps (App core_op (Type env_ty)) core_args,
518 unionVarSets fv_sets)
520 -- A | ys |- c :: [ts] t (ys <= xs)
521 -- ---------------------
522 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
525 :: IdSet -- set of local vars available to this command
526 -> [Id] -- list of vars in the input to this command
527 -> TypecheckedHsCmdTop -- command argument to desugar
528 -> DsM (CoreExpr, -- desugared expression
529 IdSet) -- set of local vars that occur free
530 dsTrimCmdArg local_vars env_ids (HsCmdTop cmd stack cmd_ty ids)
531 = mkCmdEnv ids `thenDs` \ meth_ids ->
532 dsfixCmd meth_ids local_vars stack cmd_ty cmd
533 `thenDs` \ (core_cmd, free_vars, env_ids') ->
534 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
535 matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
536 `thenDs` \ trim_code ->
538 in_ty = envStackType env_ids stack
539 in_ty' = envStackType env_ids' stack
540 arg_code = if env_ids' == env_ids then core_cmd else
541 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
543 returnDs (bindCmdEnv meth_ids arg_code, free_vars)
545 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
546 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
549 :: DsCmdEnv -- arrow combinators
550 -> IdSet -- set of local vars available to this command
551 -> [Type] -- type of the stack
552 -> Type -- return type of the command
553 -> TypecheckedHsCmd -- command to desugar
554 -> DsM (CoreExpr, -- desugared expression
555 IdSet, -- set of local vars that occur free
556 [Id]) -- set as a list, fed back
557 dsfixCmd ids local_vars stack cmd_ty cmd
558 = fixDs (\ ~(_,_,env_ids') ->
559 dsCmd ids local_vars env_ids' stack cmd_ty cmd
560 `thenDs` \ (core_cmd, free_vars) ->
561 returnDs (core_cmd, free_vars, varSetElems free_vars))
565 Translation of command judgements of the form
567 A | xs |- do { ss } :: [] t
571 dsCmdDo :: DsCmdEnv -- arrow combinators
572 -> IdSet -- set of local vars available to this statement
573 -> [Id] -- list of vars in the input to this statement
574 -- This is typically fed back,
575 -- so don't pull on it too early
576 -> Type -- return type of the statement
577 -> [TypecheckedStmt] -- statements to desugar
578 -> DsM (CoreExpr, -- desugared expression
579 IdSet) -- set of local vars that occur free
581 -- A | xs |- c :: [] t
582 -- --------------------------
583 -- A | xs |- do { c } :: [] t
585 dsCmdDo ids local_vars env_ids res_ty [ResultStmt cmd _locn]
586 = dsCmd ids local_vars env_ids [] res_ty cmd
588 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts)
590 bound_vars = mkVarSet (collectStmtBinders stmt)
591 local_vars' = local_vars `unionVarSet` bound_vars
593 fixDs (\ ~(_,_,env_ids') ->
594 dsCmdDo ids local_vars' env_ids' res_ty stmts
595 `thenDs` \ (core_stmts, fv_stmts) ->
596 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
597 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
598 dsCmdStmt ids local_vars env_ids env_ids' stmt
599 `thenDs` \ (core_stmt, fv_stmt) ->
600 returnDs (do_compose ids
601 (mkTupleType env_ids)
602 (mkTupleType env_ids')
609 A statement maps one local environment to another, and is represented
610 as an arrow from one tuple type to another. A statement sequence is
611 translated to a composition of such arrows.
615 :: DsCmdEnv -- arrow combinators
616 -> IdSet -- set of local vars available to this statement
617 -> [Id] -- list of vars in the input to this statement
618 -- This is typically fed back,
619 -- so don't pull on it too early
620 -> [Id] -- list of vars in the output of this statement
621 -> TypecheckedStmt -- statement to desugar
622 -> DsM (CoreExpr, -- desugared expression
623 IdSet) -- set of local vars that occur free
625 -- A | xs1 |- c :: [] t
626 -- A | xs' |- do { ss } :: [] t'
627 -- ------------------------------
628 -- A | xs |- do { c; ss } :: [] t'
630 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
633 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd c_ty _loc)
634 = dsfixCmd ids local_vars [] c_ty cmd
635 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
636 matchEnvStack env_ids []
637 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
638 `thenDs` \ core_mux ->
640 in_ty = mkTupleType env_ids
641 in_ty1 = mkTupleType env_ids1
642 out_ty = mkTupleType out_ids
643 before_c_ty = mkCorePairTy in_ty1 out_ty
644 after_c_ty = mkCorePairTy c_ty out_ty
646 mkSndExpr c_ty out_ty `thenDs` \ snd_fn ->
647 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
648 do_compose ids before_c_ty after_c_ty out_ty
649 (do_first ids in_ty1 c_ty out_ty core_cmd) $
650 do_arr ids after_c_ty out_ty snd_fn,
651 fv_cmd `unionVarSet` mkVarSet out_ids)
654 -- A | xs1 |- c :: [] t
655 -- A | xs' |- do { ss } :: [] t' xs2 = xs' - defs(p)
656 -- -----------------------------------
657 -- A | xs |- do { p <- c; ss } :: [] t'
659 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
660 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
662 -- It would be simpler and more consistent to do this using second,
663 -- but that's likely to be defined in terms of first.
665 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _loc)
666 = dsfixCmd ids local_vars [] (hsPatType pat) cmd
667 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
669 pat_ty = hsPatType pat
670 pat_vars = mkVarSet (collectPatBinders pat)
671 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
672 env_ty2 = mkTupleType env_ids2
675 -- multiplexing function
676 -- \ (xs) -> ((xs1),(xs2))
678 matchEnvStack env_ids []
679 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
680 `thenDs` \ core_mux ->
682 -- projection function
683 -- \ (p, (xs2)) -> (zs)
685 selectMatchVar pat `thenDs` \ pat_id ->
686 newSysLocalDs env_ty2 `thenDs` \ env_id ->
687 getUniqSupplyDs `thenDs` \ uniqs ->
689 after_c_ty = mkCorePairTy pat_ty env_ty2
690 out_ty = mkTupleType out_ids
691 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
693 mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
694 matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
695 `thenDs` \ match_code ->
696 newSysLocalDs after_c_ty `thenDs` \ pair_id ->
698 proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
701 -- put it all together
703 in_ty = mkTupleType env_ids
704 in_ty1 = mkTupleType env_ids1
705 in_ty2 = mkTupleType env_ids2
706 before_c_ty = mkCorePairTy in_ty1 in_ty2
708 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
709 do_compose ids before_c_ty after_c_ty out_ty
710 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
711 do_arr ids after_c_ty out_ty proj_expr,
712 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
714 -- A | xs' |- do { ss } :: [] t
715 -- --------------------------------------
716 -- A | xs |- do { let binds; ss } :: [] t
718 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
720 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
721 -- build a new environment using the let bindings
722 = dsLet binds (mkTupleExpr out_ids) `thenDs` \ core_binds ->
723 -- match the old environment against the input
724 matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
726 (mkTupleType env_ids)
727 (mkTupleType out_ids)
729 exprFreeVars core_binds `intersectVarSet` local_vars)
731 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
732 -- A | xs' |- do { ss' } :: [] t
733 -- ------------------------------------
734 -- A | xs |- do { rec ss; ss' } :: [] t
736 -- xs1 = xs' /\ defs(ss)
737 -- xs2 = xs' - defs(ss)
738 -- ys1 = ys - defs(ss)
739 -- ys2 = ys /\ defs(ss)
741 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
742 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
743 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
745 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss)
747 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
748 env2_ids = varSetElems env2_id_set
749 env2_ty = mkTupleType env2_ids
752 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
754 getUniqSupplyDs `thenDs` \ uniqs ->
755 newSysLocalDs env2_ty `thenDs` \ env2_id ->
757 later_ty = mkTupleType later_ids
758 post_pair_ty = mkCorePairTy later_ty env2_ty
759 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
761 matchEnvStack later_ids [env2_id] post_loop_body
762 `thenDs` \ post_loop_fn ->
766 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
767 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
769 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
772 env1_ty = mkTupleType env1_ids
773 pre_pair_ty = mkCorePairTy env1_ty env2_ty
774 pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
775 (mkTupleExpr env2_ids)
778 matchEnvStack env_ids [] pre_loop_body
779 `thenDs` \ pre_loop_fn ->
781 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
784 env_ty = mkTupleType env_ids
785 out_ty = mkTupleType out_ids
786 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
788 (do_compose ids pre_pair_ty post_pair_ty out_ty
789 (do_first ids env1_ty later_ty env2_ty
791 (do_arr ids post_pair_ty out_ty
794 returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
796 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
798 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
800 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
802 rec_id_set = mkVarSet rec_ids
803 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
804 out_ty = mkTupleType out_ids
805 local_vars' = local_vars `unionVarSet` rec_id_set
808 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
810 mapDs dsExpr rhss `thenDs` \ core_rhss ->
812 later_tuple = mkTupleExpr later_ids
813 later_ty = mkTupleType later_ids
814 rec_tuple = mkBigCoreTup core_rhss
815 rec_ty = mkTupleType rec_ids
816 out_pair = mkCorePairExpr later_tuple rec_tuple
817 out_pair_ty = mkCorePairTy later_ty rec_ty
819 matchEnvStack out_ids [] out_pair
820 `thenDs` \ mk_pair_fn ->
824 dsfixCmdStmts ids local_vars' out_ids stmts
825 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
827 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
829 newSysLocalDs rec_ty `thenDs` \ rec_id ->
831 env1_id_set = fv_stmts `minusVarSet` rec_id_set
832 env1_ids = varSetElems env1_id_set
833 env1_ty = mkTupleType env1_ids
834 in_pair_ty = mkCorePairTy env1_ty rec_ty
835 core_body = mkBigCoreTup (map selectVar env_ids)
838 | v `elemVarSet` rec_id_set
839 = mkTupleSelector rec_ids v rec_id (Var rec_id)
842 matchEnvStack env1_ids [rec_id] core_body
843 `thenDs` \ squash_pair_fn ->
845 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
848 env_ty = mkTupleType env_ids
849 core_loop = do_loop ids env1_ty later_ty rec_ty
850 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
852 (do_compose ids env_ty out_ty out_pair_ty
854 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
856 returnDs (core_loop, env1_id_set, env1_ids)
859 A sequence of statements (as in a rec) is desugared to an arrow between
864 :: DsCmdEnv -- arrow combinators
865 -> IdSet -- set of local vars available to this statement
866 -> [Id] -- output vars of these statements
867 -> [TypecheckedStmt] -- statements to desugar
868 -> DsM (CoreExpr, -- desugared expression
869 IdSet, -- set of local vars that occur free
872 dsfixCmdStmts ids local_vars out_ids stmts
873 = fixDs (\ ~(_,_,env_ids) ->
874 dsCmdStmts ids local_vars env_ids out_ids stmts
875 `thenDs` \ (core_stmts, fv_stmts) ->
876 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
879 :: DsCmdEnv -- arrow combinators
880 -> IdSet -- set of local vars available to this statement
881 -> [Id] -- list of vars in the input to these statements
882 -> [Id] -- output vars of these statements
883 -> [TypecheckedStmt] -- statements to desugar
884 -> DsM (CoreExpr, -- desugared expression
885 IdSet) -- set of local vars that occur free
887 dsCmdStmts ids local_vars env_ids out_ids [stmt]
888 = dsCmdStmt ids local_vars env_ids out_ids stmt
890 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
892 bound_vars = mkVarSet (collectStmtBinders stmt)
893 local_vars' = local_vars `unionVarSet` bound_vars
895 dsfixCmdStmts ids local_vars' out_ids stmts
896 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
897 dsCmdStmt ids local_vars env_ids env_ids' stmt
898 `thenDs` \ (core_stmt, fv_stmt) ->
899 returnDs (do_compose ids
900 (mkTupleType env_ids)
901 (mkTupleType env_ids')
902 (mkTupleType out_ids)
909 Match a list of expressions against a list of patterns, left-to-right.
912 matchSimplys :: [CoreExpr] -- Scrutinees
913 -> TypecheckedMatchContext -- Match kind
914 -> [TypecheckedPat] -- Patterns they should match
915 -> CoreExpr -- Return this if they all match
916 -> CoreExpr -- Return this if they don't
918 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
919 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
920 = matchSimplys exps ctxt pats result_expr fail_expr
921 `thenDs` \ match_code ->
922 matchSimply exp ctxt pat match_code fail_expr
927 -- list of leaf expressions, with set of variables bound in each
928 leavesMatch :: TypecheckedMatch -> [(TypecheckedHsExpr, IdSet)]
929 leavesMatch (Match pats _ (GRHSs grhss binds _ty))
931 defined_vars = mkVarSet (collectPatsBinders pats) `unionVarSet`
932 mkVarSet (collectHsBinders binds)
934 [(expr, mkVarSet (collectStmtsBinders stmts) `unionVarSet` defined_vars) |
935 GRHS stmts _locn <- grhss,
936 let ResultStmt expr _ = last stmts]
938 -- Replace the leaf commands in a match
941 :: Type -- new result type
942 -> [TypecheckedHsExpr] -- replacement leaf expressions of that type
943 -> TypecheckedMatch -- the matches of a case command
944 -> ([TypecheckedHsExpr],-- remaining leaf expressions
945 TypecheckedMatch) -- updated match
946 replaceLeavesMatch res_ty leaves (Match pat mt (GRHSs grhss binds _ty))
948 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
950 (leaves', Match pat mt (GRHSs grhss' binds res_ty))
953 :: [TypecheckedHsExpr] -- replacement leaf expressions of that type
954 -> TypecheckedGRHS -- rhss of a case command
955 -> ([TypecheckedHsExpr],-- remaining leaf expressions
956 TypecheckedGRHS) -- updated GRHS
957 replaceLeavesGRHS (leaf:leaves) (GRHS stmts srcloc)
958 = (leaves, GRHS (init stmts ++ [ResultStmt leaf srcloc]) srcloc)
962 Balanced fold of a non-empty list.
965 foldb :: (a -> a -> a) -> [a] -> a
966 foldb _ [] = error "foldb of empty list"
968 foldb f xs = foldb f (fold_pairs xs)
972 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs