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 mkTupleExpr, mkTupleSelector,
15 dsReboundNames, lookupReboundName )
18 import HsSyn ( HsExpr(..), Pat(..),
19 Stmt(..), HsMatchContext(..), HsStmtContext(..),
20 Match(..), GRHSs(..), GRHS(..),
21 HsCmdTop(..), HsArrAppType(..),
24 collectStmtBinders, collectStmtsBinders,
27 import TcHsSyn ( TypecheckedHsCmd, TypecheckedHsCmdTop,
28 TypecheckedHsExpr, TypecheckedPat,
29 TypecheckedMatch, TypecheckedGRHS,
30 TypecheckedStmt, hsPatType,
31 TypecheckedMatchContext )
33 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
34 -- needs to see source types (newtypes etc), and sometimes not
35 -- So WATCH OUT; check each use of split*Ty functions.
36 -- Sigh. This is a pain.
38 import {-# SOURCE #-} DsExpr ( dsExpr, dsLet )
40 import TcType ( Type, tcSplitAppTy )
41 import Type ( mkTyConApp )
43 import CoreFVs ( exprFreeVars )
44 import CoreUtils ( exprType, mkIfThenElse, bindNonRec )
46 import Id ( Id, idType )
47 import PrelInfo ( pAT_ERROR_ID )
48 import DataCon ( DataCon, dataConWrapId )
49 import TysWiredIn ( tupleCon, mkTupleTy )
50 import BasicTypes ( Boxity(..) )
51 import PrelNames ( eitherTyConName, leftDataConName, rightDataConName,
52 arrAName, composeAName, firstAName,
53 appAName, choiceAName, loopAName )
54 import Util ( mapAccumL )
57 import HsPat ( collectPatBinders, collectPatsBinders )
58 import VarSet ( IdSet, emptyVarSet, mkVarSet, varSetElems,
59 intersectVarSet, minusVarSet,
60 unionVarSet, unionVarSets, elemVarSet )
61 import SrcLoc ( SrcLoc )
65 data DsCmdEnv = DsCmdEnv {
66 meth_binds :: [CoreBind],
67 arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
70 mkCmdEnv :: ReboundNames Id -> DsM DsCmdEnv
72 = dsReboundNames ids `thenDs` \ (meth_binds, ds_meths) ->
74 meth_binds = meth_binds,
75 arr_id = lookupReboundName ds_meths arrAName,
76 compose_id = lookupReboundName ds_meths composeAName,
77 first_id = lookupReboundName ds_meths firstAName,
78 app_id = lookupReboundName ds_meths appAName,
79 choice_id = lookupReboundName ds_meths choiceAName,
80 loop_id = lookupReboundName ds_meths loopAName
83 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
84 bindCmdEnv ids body = foldr Let body (meth_binds ids)
86 -- arr :: forall b c. (b -> c) -> a b c
87 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
88 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
90 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
91 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
92 CoreExpr -> CoreExpr -> CoreExpr
93 do_compose ids b_ty c_ty d_ty f g
94 = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
96 -- first :: forall b c d. a b c -> a (b,d) (c,d)
97 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
98 do_first ids b_ty c_ty d_ty f
99 = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
101 -- app :: forall b c. a (a b c, b) c
102 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
103 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
105 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
106 -- note the swapping of d and c
107 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
108 CoreExpr -> CoreExpr -> CoreExpr
109 do_choice ids b_ty c_ty d_ty f g
110 = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
112 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
113 -- note the swapping of d and c
114 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
115 do_loop ids b_ty c_ty d_ty f
116 = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
118 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
119 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
120 CoreExpr -> CoreExpr -> CoreExpr
121 do_map_arrow ids b_ty c_ty d_ty f c
122 = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
124 mkFailExpr :: TypecheckedMatchContext -> Type -> DsM CoreExpr
126 = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
128 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
129 mkSndExpr :: Type -> Type -> DsM CoreExpr
131 = newSysLocalDs a_ty `thenDs` \ a_var ->
132 newSysLocalDs b_ty `thenDs` \ b_var ->
133 newSysLocalDs (mkCorePairTy a_ty b_ty) `thenDs` \ pair_var ->
134 returnDs (Lam pair_var
135 (coreCaseSmallTuple pair_var [a_var, b_var] (Var b_var)))
138 Build case analysis of a tuple. This cannot be done in the DsM monad,
139 because the list of variables is typically not yet defined.
142 -- coreCaseTuple [u1..] v [x1..xn] body
143 -- = case v of v { (x1, .., xn) -> body }
144 -- But the matching may be nested if the tuple is very big
146 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
147 coreCaseTuple uniqs = coreCaseSmallTuple -- TODO: do this right
149 -- same, but with a tuple small enough not to need nesting
151 coreCaseSmallTuple :: Id -> [Id] -> CoreExpr -> CoreExpr
152 coreCaseSmallTuple scrut_var [var] body
153 = bindNonRec var (Var scrut_var) body
154 coreCaseSmallTuple scrut_var vars body
155 = Case (Var scrut_var) scrut_var
156 [(DataAlt (tupleCon Boxed (length vars)), vars, body)]
160 -- Not right: doesn't handle nested tuples
161 tupleType :: [Id] -> Type
162 tupleType vars = mkCoreTupTy (map idType vars)
164 mkCorePairTy :: Type -> Type -> Type
165 mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]
167 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
168 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
171 The input is divided into a local environment, which is a flat tuple
172 (unless it's too big), and a stack, each element of which is paired
173 with the stack in turn. In general, the input has the form
175 (...((x1,...,xn),s1),...sk)
177 where xi are the environment values, and si the ones on the stack,
178 with s1 being the "top", the first one to be matched with a lambda.
181 envStackType :: [Id] -> [Type] -> Type
182 envStackType ids stack_tys = foldl mkCorePairTy (tupleType ids) stack_tys
184 ----------------------------------------------
187 -- (...((x1,...,xn),s1),...sn)
189 buildEnvStack :: [Id] -> [Id] -> CoreExpr
190 buildEnvStack env_ids stack_ids
191 = envStackExpr (mkTupleExpr env_ids) (map Var stack_ids)
193 envStackExpr :: CoreExpr -> [CoreExpr] -> CoreExpr
194 envStackExpr core_ids core_exprs = foldl mkCorePairExpr core_ids core_exprs
196 ----------------------------------------------
199 -- \ (...((x1,...,xm),s1),...sn) -> e
202 -- case zn of (zn-1,sn) ->
204 -- case z1 of (z0,s1) ->
205 -- case z0 of (x1,...,xm) ->
208 matchEnvStack :: [Id] -- x1..xm
212 matchEnvStack env_ids stack_ids body
213 = getUniqSupplyDs `thenDs` \ uniqs ->
214 newSysLocalDs (tupleType env_ids) `thenDs` \ tup_var ->
215 matchVarStack tup_var stack_ids
216 (coreCaseTuple uniqs tup_var env_ids body)
219 ----------------------------------------------
222 -- \ (...(z0,s1),...sn) -> e
225 -- case zn of (zn-1,sn) ->
227 -- case z1 of (z0,s1) ->
230 matchVarStack :: Id -- z0
234 matchVarStack env_id [] body
235 = returnDs (Lam env_id body)
236 matchVarStack env_id (stack_id:stack_ids) body
238 pair_ids = [env_id, stack_id]
240 newSysLocalDs (tupleType pair_ids) `thenDs` \ pair_id ->
241 matchVarStack pair_id stack_ids
242 (coreCaseSmallTuple pair_id pair_ids body)
246 mkHsTupleExpr :: [TypecheckedHsExpr] -> TypecheckedHsExpr
247 mkHsTupleExpr [e] = e
248 mkHsTupleExpr es = ExplicitTuple es Unboxed
250 mkHsPairExpr :: TypecheckedHsExpr -> TypecheckedHsExpr -> TypecheckedHsExpr
251 mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]
253 mkHsEnvStackExpr :: [Id] -> [Id] -> TypecheckedHsExpr
254 mkHsEnvStackExpr env_ids stack_ids
255 = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
258 Translation of arrow abstraction
262 -- A | xs |- c :: [] t' ---> c'
263 -- --------------------------
264 -- A |- proc p -> c :: a t t' ---> arr (\ p -> (xs)) >>> c'
266 -- where (xs) is the tuple of variables bound by p
270 -> TypecheckedHsCmdTop
273 dsProcExpr pat (HsCmdTop cmd [] cmd_ty ids) locn
275 mkCmdEnv ids `thenDs` \ meth_ids ->
277 locals = mkVarSet (collectPatBinders pat)
279 dsfixCmd meth_ids locals [] cmd_ty cmd
280 `thenDs` \ (core_cmd, free_vars, env_ids) ->
282 env_ty = tupleType env_ids
284 mkFailExpr ProcExpr env_ty `thenDs` \ fail_expr ->
285 selectMatchVar pat `thenDs` \ var ->
286 matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
287 `thenDs` \ match_code ->
289 pat_ty = hsPatType pat
290 proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
294 returnDs (bindCmdEnv meth_ids proc_code)
298 Translation of command judgements of the form
300 A | xs |- c :: [ts] t
304 dsCmd :: DsCmdEnv -- arrow combinators
305 -> IdSet -- set of local vars available to this command
306 -> [Id] -- list of vars in the input to this command
307 -- This is typically fed back,
308 -- so don't pull on it too early
309 -> [Type] -- type of the stack
310 -> Type -- return type of the command
311 -> TypecheckedHsCmd -- command to desugar
312 -> DsM (CoreExpr, -- desugared expression
313 IdSet) -- set of local vars that occur free
317 -- ---------------------------
318 -- A | xs |- f -< arg :: [] t' ---> arr (\ (xs) -> arg) >>> f
320 dsCmd ids local_vars env_ids [] res_ty
321 (HsArrApp arrow arg arrow_ty HsFirstOrderApp _ _)
323 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
324 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
325 env_ty = tupleType env_ids
327 dsExpr arrow `thenDs` \ core_arrow ->
328 dsExpr arg `thenDs` \ core_arg ->
329 matchEnvStack env_ids [] core_arg `thenDs` \ core_make_arg ->
330 returnDs (do_map_arrow ids env_ty arg_ty res_ty
333 exprFreeVars core_arg `intersectVarSet` local_vars)
335 -- A, xs |- f :: a t t'
337 -- ---------------------------
338 -- A | xs |- f -<< arg :: [] t' ---> arr (\ (xs) -> (f,arg)) >>> app
340 dsCmd ids local_vars env_ids [] res_ty
341 (HsArrApp arrow arg arrow_ty HsHigherOrderApp _ _)
343 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
344 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
345 env_ty = tupleType env_ids
347 dsExpr arrow `thenDs` \ core_arrow ->
348 dsExpr arg `thenDs` \ core_arg ->
349 matchEnvStack env_ids [] (mkCoreTup [core_arrow, core_arg])
350 `thenDs` \ core_make_pair ->
351 returnDs (do_map_arrow ids env_ty (mkCorePairTy arrow_ty arg_ty) res_ty
353 (do_app ids arg_ty res_ty),
354 (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
355 `intersectVarSet` local_vars)
357 -- A | ys |- c :: [ts] t'
358 -- -----------------------------------------------
359 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
361 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
363 dsCmd ids local_vars env_ids stack res_ty
364 (HsLam (Match pats _ (GRHSs [GRHS [ResultStmt body _] _loc] _ _cmd_ty)))
366 pat_vars = mkVarSet (collectPatsBinders pats)
367 local_vars' = local_vars `unionVarSet` pat_vars
368 stack' = drop (length pats) stack
370 dsfixCmd ids local_vars' stack' res_ty body
371 `thenDs` \ (core_body, free_vars, env_ids') ->
372 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
374 -- the expression is built from the inside out, so the actions
375 -- are presented in reverse order
378 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
379 -- build a new environment, plus what's left of the stack
380 core_expr = buildEnvStack env_ids' stack_ids'
381 in_ty = envStackType env_ids stack
382 in_ty' = envStackType env_ids' stack'
384 mkFailExpr LambdaExpr in_ty' `thenDs` \ fail_expr ->
385 -- match the patterns against the top of the old stack
386 matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
387 `thenDs` \ match_code ->
388 -- match the old environment and stack against the input
389 matchEnvStack env_ids stack_ids match_code
390 `thenDs` \ select_code ->
391 returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
392 free_vars `minusVarSet` pat_vars)
394 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
395 = dsCmd ids local_vars env_ids stack res_ty cmd
397 dsCmd ids local_vars env_ids stack res_ty (HsCase exp matches src_loc)
398 = dsExpr exp `thenDs` \ core_exp ->
399 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
401 -- Extract and desugar the leaf commands in the case, building tuple
402 -- expressions that will (after tagging) replace these leaves
405 leaves = concatMap leavesMatch matches
406 make_branch (leaf, bound_vars)
407 = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
408 `thenDs` \ (core_leaf, fvs, leaf_ids) ->
409 returnDs (fvs `minusVarSet` bound_vars,
410 [mkHsEnvStackExpr leaf_ids stack_ids],
411 envStackType leaf_ids stack,
414 mapDs make_branch leaves `thenDs` \ branches ->
415 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
416 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
417 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
419 left_id = HsVar (dataConWrapId left_con)
420 right_id = HsVar (dataConWrapId right_con)
421 left_expr ty1 ty2 e = HsApp (TyApp left_id [ty1, ty2]) e
422 right_expr ty1 ty2 e = HsApp (TyApp right_id [ty1, ty2]) e
424 -- Prefix each tuple with a distinct series of Left's and Right's,
425 -- in a balanced way, keeping track of the types.
427 merge_branches (fvs1, builds1, in_ty1, core_exp1)
428 (fvs2, builds2, in_ty2, core_exp2)
429 = (fvs1 `unionVarSet` fvs2,
430 map (left_expr in_ty1 in_ty2) builds1 ++
431 map (right_expr in_ty1 in_ty2) builds2,
432 mkTyConApp either_con [in_ty1, in_ty2],
433 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
434 (fvs, leaves', sum_ty, core_choices) = foldb merge_branches branches
436 -- Replace the commands in the case with these tagged tuples,
437 -- yielding a TypecheckedHsExpr we can feed to dsExpr.
439 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
440 in_ty = envStackType env_ids stack
442 dsExpr (HsCase exp matches' src_loc) `thenDs` \ core_matches ->
443 returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
444 exprFreeVars core_exp `unionVarSet` fvs)
446 -- A, xs |- e :: Bool
447 -- A | xs1 |- c1 :: [ts] t
448 -- A | xs2 |- c2 :: [ts] t
449 -- ----------------------------------------
450 -- A | xs |- if e then c1 else c2 :: [ts] t
452 -- ---> arr (\ ((xs)*ts) ->
453 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
456 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd _loc)
457 = dsExpr cond `thenDs` \ core_cond ->
458 dsfixCmd ids local_vars stack res_ty then_cmd
459 `thenDs` \ (core_then, fvs_then, then_ids) ->
460 dsfixCmd ids local_vars stack res_ty else_cmd
461 `thenDs` \ (core_else, fvs_else, else_ids) ->
462 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
463 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
464 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
465 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
467 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
468 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
470 in_ty = envStackType env_ids stack
471 then_ty = envStackType then_ids stack
472 else_ty = envStackType else_ids stack
473 sum_ty = mkTyConApp either_con [then_ty, else_ty]
475 matchEnvStack env_ids stack_ids
476 (mkIfThenElse core_cond
477 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
478 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
479 `thenDs` \ core_if ->
480 returnDs(do_map_arrow ids in_ty sum_ty res_ty
482 (do_choice ids then_ty else_ty res_ty core_then core_else),
483 exprFreeVars core_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
485 -- A | ys |- c :: [ts] t
486 -- ----------------------------------
487 -- A | xs |- let binds in c :: [ts] t
489 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
491 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
493 defined_vars = mkVarSet (collectHsBinders binds)
494 local_vars' = local_vars `unionVarSet` defined_vars
496 dsfixCmd ids local_vars' stack res_ty body
497 `thenDs` \ (core_body, free_vars, env_ids') ->
498 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
499 -- build a new environment, plus the stack, using the let bindings
500 dsLet binds (buildEnvStack env_ids' stack_ids)
501 `thenDs` \ core_binds ->
502 -- match the old environment and stack against the input
503 matchEnvStack env_ids stack_ids core_binds
504 `thenDs` \ core_map ->
505 returnDs (do_map_arrow ids
506 (envStackType env_ids stack)
507 (envStackType env_ids' stack)
511 exprFreeVars core_binds `intersectVarSet` local_vars)
513 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts _ _ _loc)
514 = dsCmdDo ids local_vars env_ids res_ty stmts
516 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
517 -- A | xs |- ci :: [tsi] ti
518 -- -----------------------------------
519 -- A | xs |- (|e|) c1 ... cn :: [ts] t ---> e [t_xs] c1 ... cn
521 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args _)
523 env_ty = tupleType env_ids
525 dsExpr op `thenDs` \ core_op ->
526 mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
527 `thenDs` \ (core_args, fv_sets) ->
528 returnDs (mkApps (App core_op (Type env_ty)) core_args,
529 unionVarSets fv_sets)
531 -- A | ys |- c :: [ts] t (ys <= xs)
532 -- ---------------------
533 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
536 :: IdSet -- set of local vars available to this command
537 -> [Id] -- list of vars in the input to this command
538 -> TypecheckedHsCmdTop -- command argument to desugar
539 -> DsM (CoreExpr, -- desugared expression
540 IdSet) -- set of local vars that occur free
541 dsTrimCmdArg local_vars env_ids (HsCmdTop cmd stack cmd_ty ids)
542 = mkCmdEnv ids `thenDs` \ meth_ids ->
543 dsfixCmd meth_ids local_vars stack cmd_ty cmd
544 `thenDs` \ (core_cmd, free_vars, env_ids') ->
545 mapDs newSysLocalDs stack `thenDs` \ stack_ids ->
546 matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
547 `thenDs` \ trim_code ->
549 in_ty = envStackType env_ids stack
550 in_ty' = envStackType env_ids' stack
551 arg_code = if env_ids' == env_ids then core_cmd else
552 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
554 returnDs (bindCmdEnv meth_ids arg_code, free_vars)
556 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
557 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
560 :: DsCmdEnv -- arrow combinators
561 -> IdSet -- set of local vars available to this command
562 -> [Type] -- type of the stack
563 -> Type -- return type of the command
564 -> TypecheckedHsCmd -- command to desugar
565 -> DsM (CoreExpr, -- desugared expression
566 IdSet, -- set of local vars that occur free
567 [Id]) -- set as a list, fed back
568 dsfixCmd ids local_vars stack cmd_ty cmd
569 = fixDs (\ ~(_,_,env_ids') ->
570 dsCmd ids local_vars env_ids' stack cmd_ty cmd
571 `thenDs` \ (core_cmd, free_vars) ->
572 returnDs (core_cmd, free_vars, varSetElems free_vars))
576 Translation of command judgements of the form
578 A | xs |- do { ss } :: [] t
582 dsCmdDo :: DsCmdEnv -- arrow combinators
583 -> IdSet -- set of local vars available to this statement
584 -> [Id] -- list of vars in the input to this statement
585 -- This is typically fed back,
586 -- so don't pull on it too early
587 -> Type -- return type of the statement
588 -> [TypecheckedStmt] -- statements to desugar
589 -> DsM (CoreExpr, -- desugared expression
590 IdSet) -- set of local vars that occur free
592 -- A | xs |- c :: [] t
593 -- --------------------------
594 -- A | xs |- do { c } :: [] t
596 dsCmdDo ids local_vars env_ids res_ty [ResultStmt cmd _locn]
597 = dsCmd ids local_vars env_ids [] res_ty cmd
599 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts)
601 bound_vars = mkVarSet (collectStmtBinders stmt)
602 local_vars' = local_vars `unionVarSet` bound_vars
604 fixDs (\ ~(_,_,env_ids') ->
605 dsCmdDo ids local_vars' env_ids' res_ty stmts
606 `thenDs` \ (core_stmts, fv_stmts) ->
607 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
608 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
609 dsCmdStmt ids local_vars env_ids env_ids' stmt
610 `thenDs` \ (core_stmt, fv_stmt) ->
611 returnDs (do_compose ids
620 A statement maps one local environment to another, and is represented
621 as an arrow from one tuple type to another. A statement sequence is
622 translated to a composition of such arrows.
626 :: DsCmdEnv -- arrow combinators
627 -> IdSet -- set of local vars available to this statement
628 -> [Id] -- list of vars in the input to this statement
629 -- This is typically fed back,
630 -- so don't pull on it too early
631 -> [Id] -- list of vars in the output of this statement
632 -> TypecheckedStmt -- statement to desugar
633 -> DsM (CoreExpr, -- desugared expression
634 IdSet) -- set of local vars that occur free
636 -- A | xs1 |- c :: [] t
637 -- A | xs' |- do { ss } :: [] t
638 -- ------------------------------
639 -- A | xs |- do { c; ss } :: [] t
641 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
644 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd c_ty _loc)
645 = dsfixCmd ids local_vars [] c_ty cmd
646 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
647 matchEnvStack env_ids []
648 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
649 `thenDs` \ core_mux ->
651 in_ty = tupleType env_ids
652 in_ty1 = tupleType env_ids1
653 out_ty = tupleType out_ids
654 before_c_ty = mkCorePairTy in_ty1 out_ty
655 after_c_ty = mkCorePairTy c_ty out_ty
657 mkSndExpr c_ty out_ty `thenDs` \ snd_fn ->
658 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
659 do_compose ids before_c_ty after_c_ty out_ty
660 (do_first ids in_ty1 c_ty out_ty core_cmd) $
661 do_arr ids after_c_ty out_ty snd_fn,
662 fv_cmd `unionVarSet` mkVarSet out_ids)
665 -- A | xs1 |- c :: [] t
666 -- A | xs' |- do { ss } :: [] t xs2 = xs' - defs(p)
667 -- -----------------------------------
668 -- A | xs |- do { p <- c; ss } :: [] t
670 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
671 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
673 -- It would be simpler and more consistent to do this using second,
674 -- but that's likely to be defined in terms of first.
676 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _loc)
677 = dsfixCmd ids local_vars [] (hsPatType pat) cmd
678 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
680 pat_vars = mkVarSet (collectPatBinders pat)
681 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
684 -- multiplexing function
685 -- \ (xs) -> ((xs1),(xs2))
687 matchEnvStack env_ids []
688 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
689 `thenDs` \ core_mux ->
691 -- projection function
692 -- \ (p, (xs2)) -> (zs)
694 selectMatchVar pat `thenDs` \ pat_id ->
695 newSysLocalDs (tupleType env_ids2) `thenDs` \ env_id ->
696 getUniqSupplyDs `thenDs` \ uniqs ->
698 pair_ids = [pat_id, env_id]
699 after_c_ty = tupleType pair_ids
700 out_ty = tupleType out_ids
701 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
703 mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
704 matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
705 `thenDs` \ match_code ->
706 newSysLocalDs after_c_ty `thenDs` \ pair_id ->
708 proj_expr = Lam pair_id (coreCaseSmallTuple pair_id pair_ids match_code)
711 -- put it all togther
713 pat_ty = hsPatType pat
714 in_ty = tupleType env_ids
715 in_ty1 = tupleType env_ids1
716 in_ty2 = tupleType env_ids2
717 before_c_ty = mkCorePairTy in_ty1 in_ty2
719 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
720 do_compose ids before_c_ty after_c_ty out_ty
721 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
722 do_arr ids after_c_ty out_ty proj_expr,
723 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
725 -- A | xs' |- do { ss } :: [] t
726 -- --------------------------------------
727 -- A | xs |- do { let binds; ss } :: [] t
729 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
731 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
732 -- build a new environment using the let bindings
733 = dsLet binds (mkTupleExpr out_ids) `thenDs` \ core_binds ->
734 -- match the old environment against the input
735 matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
740 exprFreeVars core_binds `intersectVarSet` local_vars)
742 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
743 -- A | xs' |- do { ss' } :: [] t
744 -- ------------------------------------
745 -- A | xs |- do { rec ss; ss' } :: [] t
747 -- xs1 = xs' /\ defs(ss)
748 -- xs2 = xs' - defs(ss)
749 -- ys1 = ys - defs(ss)
750 -- ys2 = ys /\ defs(ss)
752 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
753 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
754 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
756 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss)
758 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
759 env2_ids = varSetElems env2_id_set
760 env2_ty = tupleType env2_ids
763 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
765 getUniqSupplyDs `thenDs` \ uniqs ->
766 newSysLocalDs env2_ty `thenDs` \ env2_id ->
768 later_ty = tupleType later_ids
769 post_pair_ty = mkCoreTupTy [later_ty, env2_ty]
770 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
772 matchEnvStack later_ids [env2_id] post_loop_body
773 `thenDs` \ post_loop_fn ->
777 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
778 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
780 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
783 env1_ty = tupleType env1_ids
784 pre_pair_ty = mkCoreTupTy [env1_ty, env2_ty]
785 pre_loop_body = mkCoreTup [mkTupleExpr env1_ids, mkTupleExpr env2_ids]
788 matchEnvStack env_ids [] pre_loop_body
789 `thenDs` \ pre_loop_fn ->
791 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
794 env_ty = tupleType env_ids
795 out_ty = tupleType out_ids
796 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
798 (do_compose ids pre_pair_ty post_pair_ty out_ty
799 (do_first ids env1_ty later_ty env2_ty
801 (do_arr ids post_pair_ty out_ty
804 returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
806 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
808 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
810 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
812 rec_id_set = mkVarSet rec_ids
813 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
814 out_ty = tupleType out_ids
815 local_vars' = local_vars `unionVarSet` rec_id_set
818 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
820 mapDs dsExpr rhss `thenDs` \ core_rhss ->
822 later_tuple = mkTupleExpr later_ids
823 later_ty = tupleType later_ids
824 rec_tuple = mkCoreTup core_rhss
825 rec_ty = tupleType rec_ids
826 out_pair = mkCoreTup [later_tuple, rec_tuple]
827 out_pair_ty = mkCoreTupTy [later_ty, rec_ty]
829 matchEnvStack out_ids [] out_pair
830 `thenDs` \ mk_pair_fn ->
834 dsfixCmdStmts ids local_vars' out_ids stmts
835 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
837 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
839 newSysLocalDs rec_ty `thenDs` \ rec_id ->
841 env1_id_set = fv_stmts `minusVarSet` rec_id_set
842 env1_ids = varSetElems env1_id_set
843 env1_ty = tupleType env1_ids
844 in_pair_ty = mkCoreTupTy [env1_ty, rec_ty]
845 core_body = mkCoreTup (map selectVar env_ids)
848 | v `elemVarSet` rec_id_set
849 = mkTupleSelector rec_ids v rec_id (Var rec_id)
852 matchEnvStack env1_ids [rec_id] core_body
853 `thenDs` \ squash_pair_fn ->
855 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
858 env_ty = tupleType env_ids
859 core_loop = do_loop ids env1_ty later_ty rec_ty
860 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
862 (do_compose ids env_ty out_ty out_pair_ty
864 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
866 returnDs (core_loop, env1_id_set, env1_ids)
869 A sequence of statements (as in a rec) is desugared to an arrow between
874 :: DsCmdEnv -- arrow combinators
875 -> IdSet -- set of local vars available to this statement
876 -> [Id] -- output vars of these statements
877 -> [TypecheckedStmt] -- statements to desugar
878 -> DsM (CoreExpr, -- desugared expression
879 IdSet, -- set of local vars that occur free
882 dsfixCmdStmts ids local_vars out_ids stmts
883 = fixDs (\ ~(_,_,env_ids) ->
884 dsCmdStmts ids local_vars env_ids out_ids stmts
885 `thenDs` \ (core_stmts, fv_stmts) ->
886 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
889 :: DsCmdEnv -- arrow combinators
890 -> IdSet -- set of local vars available to this statement
891 -> [Id] -- list of vars in the input to these statements
892 -> [Id] -- output vars of these statements
893 -> [TypecheckedStmt] -- statements to desugar
894 -> DsM (CoreExpr, -- desugared expression
895 IdSet) -- set of local vars that occur free
897 dsCmdStmts ids local_vars env_ids out_ids [stmt]
898 = dsCmdStmt ids local_vars env_ids out_ids stmt
900 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
902 bound_vars = mkVarSet (collectStmtBinders stmt)
903 local_vars' = local_vars `unionVarSet` bound_vars
905 dsfixCmdStmts ids local_vars' out_ids stmts
906 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
907 dsCmdStmt ids local_vars env_ids env_ids' stmt
908 `thenDs` \ (core_stmt, fv_stmt) ->
909 returnDs (do_compose ids
919 Match a list of expressions against a list of patterns, left-to-right.
922 matchSimplys :: [CoreExpr] -- Scrutinees
923 -> TypecheckedMatchContext -- Match kind
924 -> [TypecheckedPat] -- Patterns they should match
925 -> CoreExpr -- Return this if they all match
926 -> CoreExpr -- Return this if they don't
928 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
929 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
930 = matchSimplys exps ctxt pats result_expr fail_expr
931 `thenDs` \ match_code ->
932 matchSimply exp ctxt pat match_code fail_expr
937 -- list of leaf expressions, with set of variables bound in each
938 leavesMatch :: TypecheckedMatch -> [(TypecheckedHsExpr, IdSet)]
939 leavesMatch (Match pats _ (GRHSs grhss binds _ty))
941 defined_vars = mkVarSet (collectPatsBinders pats) `unionVarSet`
942 mkVarSet (collectHsBinders binds)
944 [(expr, mkVarSet (collectStmtsBinders stmts) `unionVarSet` defined_vars) |
945 GRHS stmts _locn <- grhss,
946 let ResultStmt expr _ = last stmts]
948 -- Replace the leaf commands in a match
951 :: Type -- new result type
952 -> [TypecheckedHsExpr] -- replacement leaf expressions of that type
953 -> TypecheckedMatch -- the matches of a case command
954 -> ([TypecheckedHsExpr],-- remaining leaf expressions
955 TypecheckedMatch) -- updated match
956 replaceLeavesMatch res_ty leaves (Match pat mt (GRHSs grhss binds _ty))
958 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
960 (leaves', Match pat mt (GRHSs grhss' binds res_ty))
963 :: [TypecheckedHsExpr] -- replacement leaf expressions of that type
964 -> TypecheckedGRHS -- rhss of a case command
965 -> ([TypecheckedHsExpr],-- remaining leaf expressions
966 TypecheckedGRHS) -- updated GRHS
967 replaceLeavesGRHS (leaf:leaves) (GRHS stmts srcloc)
968 = (leaves, GRHS (init stmts ++ [ResultStmt leaf srcloc]) srcloc)
972 Balanced fold of a non-empty list.
975 foldb :: (a -> a -> a) -> [a] -> a
976 foldb _ [] = error "foldb of empty list"
978 foldb f xs = foldb f (fold_pairs xs)
982 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs