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, exprType )
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 = newUniqueSupply `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 Boxed
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 :: [t:ts] t'
348 -- ------------------------
349 -- A | xs |- c e :: [ts] t'
351 -- ---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c
353 dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg)
354 = dsExpr arg `thenDs` \ core_arg ->
356 arg_ty = exprType core_arg
357 stack' = arg_ty:stack
359 dsfixCmd ids local_vars stack' res_ty cmd
360 `thenDs` \ (core_cmd, free_vars, env_ids') ->
361 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
362 newSysLocalDs arg_ty `thenDs` \ arg_id ->
363 -- push the argument expression onto the stack
365 core_body = bindNonRec arg_id core_arg
366 (buildEnvStack env_ids' (arg_id:stack_ids))
368 -- match the environment and stack against the input
369 matchEnvStack env_ids stack_ids core_body
370 `thenDs` \ core_map ->
371 returnDs (do_map_arrow ids
372 (envStackType env_ids stack)
373 (envStackType env_ids' stack')
377 (exprFreeVars core_arg `intersectVarSet` local_vars)
378 `unionVarSet` free_vars)
380 -- A | ys |- c :: [ts] t'
381 -- -----------------------------------------------
382 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
384 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
386 dsCmd ids local_vars env_ids stack res_ty
387 (HsLam (Match pats _ (GRHSs [GRHS [ResultStmt body _] _loc] _ _cmd_ty)))
389 pat_vars = mkVarSet (collectPatsBinders pats)
390 local_vars' = local_vars `unionVarSet` pat_vars
391 stack' = drop (length pats) stack
393 dsfixCmd ids local_vars' stack' res_ty body
394 `thenDs` \ (core_body, free_vars, env_ids') ->
395 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
397 -- the expression is built from the inside out, so the actions
398 -- are presented in reverse order
401 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
402 -- build a new environment, plus what's left of the stack
403 core_expr = buildEnvStack env_ids' stack_ids'
404 in_ty = envStackType env_ids stack
405 in_ty' = envStackType env_ids' stack'
407 mkFailExpr LambdaExpr in_ty' `thenDs` \ fail_expr ->
408 -- match the patterns against the top of the old stack
409 matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
410 `thenDs` \ match_code ->
411 -- match the old environment and stack against the input
412 matchEnvStack env_ids stack_ids match_code
413 `thenDs` \ select_code ->
414 returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
415 free_vars `minusVarSet` pat_vars)
417 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
418 = dsCmd ids local_vars env_ids stack res_ty cmd
420 -- A, xs |- e :: Bool
421 -- A | xs1 |- c1 :: [ts] t
422 -- A | xs2 |- c2 :: [ts] t
423 -- ----------------------------------------
424 -- A | xs |- if e then c1 else c2 :: [ts] t
426 -- ---> arr (\ ((xs)*ts) ->
427 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
430 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd _loc)
431 = dsExpr cond `thenDs` \ core_cond ->
432 dsfixCmd ids local_vars stack res_ty then_cmd
433 `thenDs` \ (core_then, fvs_then, then_ids) ->
434 dsfixCmd ids local_vars stack res_ty else_cmd
435 `thenDs` \ (core_else, fvs_else, else_ids) ->
436 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
437 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
438 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
439 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
441 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
442 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
444 in_ty = envStackType env_ids stack
445 then_ty = envStackType then_ids stack
446 else_ty = envStackType else_ids stack
447 sum_ty = mkTyConApp either_con [then_ty, else_ty]
448 fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
450 matchEnvStack env_ids stack_ids
451 (mkIfThenElse core_cond
452 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
453 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
454 `thenDs` \ core_if ->
455 returnDs(do_map_arrow ids in_ty sum_ty res_ty
457 (do_choice ids then_ty else_ty res_ty core_then core_else),
458 fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
461 Case commands are treated in much the same way as if commands
462 (see above) except that there are more alternatives. For example
464 case e of { p1 -> c1; p2 -> c2; p3 -> c3 }
468 arr (\ ((xs)*ts) -> case e of
469 p1 -> (Left (Left (xs1)*ts))
470 p2 -> Left ((Right (xs2)*ts))
471 p3 -> Right ((xs3)*ts)) >>>
474 The idea is to extract the commands from the case, build a balanced tree
475 of choices, and replace the commands with expressions that build tagged
476 tuples, obtaining a case expression that can be desugared normally.
477 To build all this, we use quadruples decribing segments of the list of
478 case bodies, containing the following fields:
479 1. an IdSet containing the environment variables free in the case bodies
480 2. a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
481 into the case replacing the commands
482 3. a sum type that is the common type of these expressions, and also the
483 input type of the arrow
484 4. a CoreExpr for an arrow built by combining the translated command
488 dsCmd ids local_vars env_ids stack res_ty (HsCase exp matches src_loc)
489 = dsExpr exp `thenDs` \ core_exp ->
490 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
492 -- Extract and desugar the leaf commands in the case, building tuple
493 -- expressions that will (after tagging) replace these leaves
496 leaves = concatMap leavesMatch matches
497 make_branch (leaf, bound_vars)
498 = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
499 `thenDs` \ (core_leaf, fvs, leaf_ids) ->
500 returnDs (fvs `minusVarSet` bound_vars,
501 [mkHsEnvStackExpr leaf_ids stack_ids],
502 envStackType leaf_ids stack,
505 mappM make_branch leaves `thenDs` \ branches ->
506 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
507 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
508 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
510 left_id = HsVar (dataConWrapId left_con)
511 right_id = HsVar (dataConWrapId right_con)
512 left_expr ty1 ty2 e = HsApp (TyApp left_id [ty1, ty2]) e
513 right_expr ty1 ty2 e = HsApp (TyApp right_id [ty1, ty2]) e
515 -- Prefix each tuple with a distinct series of Left's and Right's,
516 -- in a balanced way, keeping track of the types.
518 merge_branches (fvs1, builds1, in_ty1, core_exp1)
519 (fvs2, builds2, in_ty2, core_exp2)
520 = (fvs1 `unionVarSet` fvs2,
521 map (left_expr in_ty1 in_ty2) builds1 ++
522 map (right_expr in_ty1 in_ty2) builds2,
523 mkTyConApp either_con [in_ty1, in_ty2],
524 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
525 (fvs_alts, leaves', sum_ty, core_choices)
526 = foldb merge_branches branches
528 -- Replace the commands in the case with these tagged tuples,
529 -- yielding a TypecheckedHsExpr we can feed to dsExpr.
531 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
532 in_ty = envStackType env_ids stack
533 fvs_exp = exprFreeVars core_exp `intersectVarSet` local_vars
535 dsExpr (HsCase exp matches' src_loc) `thenDs` \ core_body ->
536 matchEnvStack env_ids stack_ids core_body
537 `thenDs` \ core_matches ->
538 returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
539 fvs_exp `unionVarSet` fvs_alts)
541 -- A | ys |- c :: [ts] t
542 -- ----------------------------------
543 -- A | xs |- let binds in c :: [ts] t
545 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
547 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
549 defined_vars = mkVarSet (collectHsBinders binds)
550 local_vars' = local_vars `unionVarSet` defined_vars
552 dsfixCmd ids local_vars' stack res_ty body
553 `thenDs` \ (core_body, free_vars, env_ids') ->
554 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
555 -- build a new environment, plus the stack, using the let bindings
556 dsLet binds (buildEnvStack env_ids' stack_ids)
557 `thenDs` \ core_binds ->
558 -- match the old environment and stack against the input
559 matchEnvStack env_ids stack_ids core_binds
560 `thenDs` \ core_map ->
561 returnDs (do_map_arrow ids
562 (envStackType env_ids stack)
563 (envStackType env_ids' stack)
567 exprFreeVars core_binds `intersectVarSet` local_vars)
569 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts _ _ _loc)
570 = dsCmdDo ids local_vars env_ids res_ty stmts
572 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
573 -- A | xs |- ci :: [tsi] ti
574 -- -----------------------------------
575 -- A | xs |- (|e c1 ... cn|) :: [ts] t ---> e [t_xs] c1 ... cn
577 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args _)
579 env_ty = mkTupleType env_ids
581 dsExpr op `thenDs` \ core_op ->
582 mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
583 `thenDs` \ (core_args, fv_sets) ->
584 returnDs (mkApps (App core_op (Type env_ty)) core_args,
585 unionVarSets fv_sets)
587 -- A | ys |- c :: [ts] t (ys <= xs)
588 -- ---------------------
589 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
592 :: IdSet -- set of local vars available to this command
593 -> [Id] -- list of vars in the input to this command
594 -> TypecheckedHsCmdTop -- command argument to desugar
595 -> DsM (CoreExpr, -- desugared expression
596 IdSet) -- set of local vars that occur free
597 dsTrimCmdArg local_vars env_ids (HsCmdTop cmd stack cmd_ty ids)
598 = mkCmdEnv ids `thenDs` \ meth_ids ->
599 dsfixCmd meth_ids local_vars stack cmd_ty cmd
600 `thenDs` \ (core_cmd, free_vars, env_ids') ->
601 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
602 matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
603 `thenDs` \ trim_code ->
605 in_ty = envStackType env_ids stack
606 in_ty' = envStackType env_ids' stack
607 arg_code = if env_ids' == env_ids then core_cmd else
608 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
610 returnDs (bindCmdEnv meth_ids arg_code, free_vars)
612 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
613 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
616 :: DsCmdEnv -- arrow combinators
617 -> IdSet -- set of local vars available to this command
618 -> [Type] -- type of the stack
619 -> Type -- return type of the command
620 -> TypecheckedHsCmd -- command to desugar
621 -> DsM (CoreExpr, -- desugared expression
622 IdSet, -- set of local vars that occur free
623 [Id]) -- set as a list, fed back
624 dsfixCmd ids local_vars stack cmd_ty cmd
625 = fixDs (\ ~(_,_,env_ids') ->
626 dsCmd ids local_vars env_ids' stack cmd_ty cmd
627 `thenDs` \ (core_cmd, free_vars) ->
628 returnDs (core_cmd, free_vars, varSetElems free_vars))
632 Translation of command judgements of the form
634 A | xs |- do { ss } :: [] t
638 dsCmdDo :: DsCmdEnv -- arrow combinators
639 -> IdSet -- set of local vars available to this statement
640 -> [Id] -- list of vars in the input to this statement
641 -- This is typically fed back,
642 -- so don't pull on it too early
643 -> Type -- return type of the statement
644 -> [TypecheckedStmt] -- statements to desugar
645 -> DsM (CoreExpr, -- desugared expression
646 IdSet) -- set of local vars that occur free
648 -- A | xs |- c :: [] t
649 -- --------------------------
650 -- A | xs |- do { c } :: [] t
652 dsCmdDo ids local_vars env_ids res_ty [ResultStmt cmd _locn]
653 = dsCmd ids local_vars env_ids [] res_ty cmd
655 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts)
657 bound_vars = mkVarSet (collectStmtBinders stmt)
658 local_vars' = local_vars `unionVarSet` bound_vars
660 fixDs (\ ~(_,_,env_ids') ->
661 dsCmdDo ids local_vars' env_ids' res_ty stmts
662 `thenDs` \ (core_stmts, fv_stmts) ->
663 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
664 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
665 dsCmdStmt ids local_vars env_ids env_ids' stmt
666 `thenDs` \ (core_stmt, fv_stmt) ->
667 returnDs (do_compose ids
668 (mkTupleType env_ids)
669 (mkTupleType env_ids')
676 A statement maps one local environment to another, and is represented
677 as an arrow from one tuple type to another. A statement sequence is
678 translated to a composition of such arrows.
682 :: DsCmdEnv -- arrow combinators
683 -> IdSet -- set of local vars available to this statement
684 -> [Id] -- list of vars in the input to this statement
685 -- This is typically fed back,
686 -- so don't pull on it too early
687 -> [Id] -- list of vars in the output of this statement
688 -> TypecheckedStmt -- statement to desugar
689 -> DsM (CoreExpr, -- desugared expression
690 IdSet) -- set of local vars that occur free
692 -- A | xs1 |- c :: [] t
693 -- A | xs' |- do { ss } :: [] t'
694 -- ------------------------------
695 -- A | xs |- do { c; ss } :: [] t'
697 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
700 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd c_ty _loc)
701 = dsfixCmd ids local_vars [] c_ty cmd
702 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
703 matchEnvStack env_ids []
704 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
705 `thenDs` \ core_mux ->
707 in_ty = mkTupleType env_ids
708 in_ty1 = mkTupleType env_ids1
709 out_ty = mkTupleType out_ids
710 before_c_ty = mkCorePairTy in_ty1 out_ty
711 after_c_ty = mkCorePairTy c_ty out_ty
713 mkSndExpr c_ty out_ty `thenDs` \ snd_fn ->
714 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
715 do_compose ids before_c_ty after_c_ty out_ty
716 (do_first ids in_ty1 c_ty out_ty core_cmd) $
717 do_arr ids after_c_ty out_ty snd_fn,
718 fv_cmd `unionVarSet` mkVarSet out_ids)
721 -- A | xs1 |- c :: [] t
722 -- A | xs' |- do { ss } :: [] t' xs2 = xs' - defs(p)
723 -- -----------------------------------
724 -- A | xs |- do { p <- c; ss } :: [] t'
726 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
727 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
729 -- It would be simpler and more consistent to do this using second,
730 -- but that's likely to be defined in terms of first.
732 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _loc)
733 = dsfixCmd ids local_vars [] (hsPatType pat) cmd
734 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
736 pat_ty = hsPatType pat
737 pat_vars = mkVarSet (collectPatBinders pat)
738 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
739 env_ty2 = mkTupleType env_ids2
742 -- multiplexing function
743 -- \ (xs) -> ((xs1),(xs2))
745 matchEnvStack env_ids []
746 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
747 `thenDs` \ core_mux ->
749 -- projection function
750 -- \ (p, (xs2)) -> (zs)
752 selectMatchVar pat `thenDs` \ pat_id ->
753 newSysLocalDs env_ty2 `thenDs` \ env_id ->
754 newUniqueSupply `thenDs` \ uniqs ->
756 after_c_ty = mkCorePairTy pat_ty env_ty2
757 out_ty = mkTupleType out_ids
758 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
760 mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
761 matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
762 `thenDs` \ match_code ->
763 newSysLocalDs after_c_ty `thenDs` \ pair_id ->
765 proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
768 -- put it all together
770 in_ty = mkTupleType env_ids
771 in_ty1 = mkTupleType env_ids1
772 in_ty2 = mkTupleType env_ids2
773 before_c_ty = mkCorePairTy in_ty1 in_ty2
775 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
776 do_compose ids before_c_ty after_c_ty out_ty
777 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
778 do_arr ids after_c_ty out_ty proj_expr,
779 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
781 -- A | xs' |- do { ss } :: [] t
782 -- --------------------------------------
783 -- A | xs |- do { let binds; ss } :: [] t
785 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
787 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
788 -- build a new environment using the let bindings
789 = dsLet binds (mkTupleExpr out_ids) `thenDs` \ core_binds ->
790 -- match the old environment against the input
791 matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
793 (mkTupleType env_ids)
794 (mkTupleType out_ids)
796 exprFreeVars core_binds `intersectVarSet` local_vars)
798 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
799 -- A | xs' |- do { ss' } :: [] t
800 -- ------------------------------------
801 -- A | xs |- do { rec ss; ss' } :: [] t
803 -- xs1 = xs' /\ defs(ss)
804 -- xs2 = xs' - defs(ss)
805 -- ys1 = ys - defs(ss)
806 -- ys2 = ys /\ defs(ss)
808 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
809 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
810 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
812 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss)
814 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
815 env2_ids = varSetElems env2_id_set
816 env2_ty = mkTupleType env2_ids
819 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
821 newUniqueSupply `thenDs` \ uniqs ->
822 newSysLocalDs env2_ty `thenDs` \ env2_id ->
824 later_ty = mkTupleType later_ids
825 post_pair_ty = mkCorePairTy later_ty env2_ty
826 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
828 matchEnvStack later_ids [env2_id] post_loop_body
829 `thenDs` \ post_loop_fn ->
833 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
834 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
836 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
839 env1_ty = mkTupleType env1_ids
840 pre_pair_ty = mkCorePairTy env1_ty env2_ty
841 pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
842 (mkTupleExpr env2_ids)
845 matchEnvStack env_ids [] pre_loop_body
846 `thenDs` \ pre_loop_fn ->
848 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
851 env_ty = mkTupleType env_ids
852 out_ty = mkTupleType out_ids
853 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
855 (do_compose ids pre_pair_ty post_pair_ty out_ty
856 (do_first ids env1_ty later_ty env2_ty
858 (do_arr ids post_pair_ty out_ty
861 returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
863 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
865 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
867 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
869 rec_id_set = mkVarSet rec_ids
870 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
871 out_ty = mkTupleType out_ids
872 local_vars' = local_vars `unionVarSet` rec_id_set
875 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
877 mappM dsExpr rhss `thenDs` \ core_rhss ->
879 later_tuple = mkTupleExpr later_ids
880 later_ty = mkTupleType later_ids
881 rec_tuple = mkBigCoreTup core_rhss
882 rec_ty = mkTupleType rec_ids
883 out_pair = mkCorePairExpr later_tuple rec_tuple
884 out_pair_ty = mkCorePairTy later_ty rec_ty
886 matchEnvStack out_ids [] out_pair
887 `thenDs` \ mk_pair_fn ->
891 dsfixCmdStmts ids local_vars' out_ids stmts
892 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
894 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
896 newSysLocalDs rec_ty `thenDs` \ rec_id ->
898 env1_id_set = fv_stmts `minusVarSet` rec_id_set
899 env1_ids = varSetElems env1_id_set
900 env1_ty = mkTupleType env1_ids
901 in_pair_ty = mkCorePairTy env1_ty rec_ty
902 core_body = mkBigCoreTup (map selectVar env_ids)
905 | v `elemVarSet` rec_id_set
906 = mkTupleSelector rec_ids v rec_id (Var rec_id)
909 matchEnvStack env1_ids [rec_id] core_body
910 `thenDs` \ squash_pair_fn ->
912 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
915 env_ty = mkTupleType env_ids
916 core_loop = do_loop ids env1_ty later_ty rec_ty
917 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
919 (do_compose ids env_ty out_ty out_pair_ty
921 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
923 returnDs (core_loop, env1_id_set, env1_ids)
926 A sequence of statements (as in a rec) is desugared to an arrow between
931 :: DsCmdEnv -- arrow combinators
932 -> IdSet -- set of local vars available to this statement
933 -> [Id] -- output vars of these statements
934 -> [TypecheckedStmt] -- statements to desugar
935 -> DsM (CoreExpr, -- desugared expression
936 IdSet, -- set of local vars that occur free
939 dsfixCmdStmts ids local_vars out_ids stmts
940 = fixDs (\ ~(_,_,env_ids) ->
941 dsCmdStmts ids local_vars env_ids out_ids stmts
942 `thenDs` \ (core_stmts, fv_stmts) ->
943 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
946 :: DsCmdEnv -- arrow combinators
947 -> IdSet -- set of local vars available to this statement
948 -> [Id] -- list of vars in the input to these statements
949 -> [Id] -- output vars of these statements
950 -> [TypecheckedStmt] -- statements to desugar
951 -> DsM (CoreExpr, -- desugared expression
952 IdSet) -- set of local vars that occur free
954 dsCmdStmts ids local_vars env_ids out_ids [stmt]
955 = dsCmdStmt ids local_vars env_ids out_ids stmt
957 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
959 bound_vars = mkVarSet (collectStmtBinders stmt)
960 local_vars' = local_vars `unionVarSet` bound_vars
962 dsfixCmdStmts ids local_vars' out_ids stmts
963 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
964 dsCmdStmt ids local_vars env_ids env_ids' stmt
965 `thenDs` \ (core_stmt, fv_stmt) ->
966 returnDs (do_compose ids
967 (mkTupleType env_ids)
968 (mkTupleType env_ids')
969 (mkTupleType out_ids)
976 Match a list of expressions against a list of patterns, left-to-right.
979 matchSimplys :: [CoreExpr] -- Scrutinees
980 -> TypecheckedMatchContext -- Match kind
981 -> [TypecheckedPat] -- Patterns they should match
982 -> CoreExpr -- Return this if they all match
983 -> CoreExpr -- Return this if they don't
985 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
986 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
987 = matchSimplys exps ctxt pats result_expr fail_expr
988 `thenDs` \ match_code ->
989 matchSimply exp ctxt pat match_code fail_expr
992 List of leaf expressions, with set of variables bound in each
995 leavesMatch :: TypecheckedMatch -> [(TypecheckedHsExpr, IdSet)]
996 leavesMatch (Match pats _ (GRHSs grhss binds _ty))
998 defined_vars = mkVarSet (collectPatsBinders pats) `unionVarSet`
999 mkVarSet (collectHsBinders binds)
1001 [(expr, mkVarSet (collectStmtsBinders stmts) `unionVarSet` defined_vars) |
1002 GRHS stmts _locn <- grhss,
1003 let ResultStmt expr _ = last stmts]
1006 Replace the leaf commands in a match
1010 :: Type -- new result type
1011 -> [TypecheckedHsExpr] -- replacement leaf expressions of that type
1012 -> TypecheckedMatch -- the matches of a case command
1013 -> ([TypecheckedHsExpr],-- remaining leaf expressions
1014 TypecheckedMatch) -- updated match
1015 replaceLeavesMatch res_ty leaves (Match pat mt (GRHSs grhss binds _ty))
1017 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
1019 (leaves', Match pat mt (GRHSs grhss' binds res_ty))
1022 :: [TypecheckedHsExpr] -- replacement leaf expressions of that type
1023 -> TypecheckedGRHS -- rhss of a case command
1024 -> ([TypecheckedHsExpr],-- remaining leaf expressions
1025 TypecheckedGRHS) -- updated GRHS
1026 replaceLeavesGRHS (leaf:leaves) (GRHS stmts srcloc)
1027 = (leaves, GRHS (init stmts ++ [ResultStmt leaf srcloc]) srcloc)
1030 Balanced fold of a non-empty list.
1033 foldb :: (a -> a -> a) -> [a] -> a
1034 foldb _ [] = error "foldb of empty list"
1036 foldb f xs = foldb f (fold_pairs xs)
1039 fold_pairs [x] = [x]
1040 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs