2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Desugaring arrow commands
9 module DsArrows ( dsProcExpr ) where
11 #include "HsVersions.h"
20 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
21 -- needs to see source types (newtypes etc), and sometimes not
22 -- So WATCH OUT; check each use of split*Ty functions.
23 -- Sigh. This is a pain.
25 import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLocalBinds )
50 data DsCmdEnv = DsCmdEnv {
51 meth_binds :: [CoreBind],
52 arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
55 mkCmdEnv :: SyntaxTable Id -> DsM DsCmdEnv
57 = dsSyntaxTable ids `thenDs` \ (meth_binds, ds_meths) ->
59 meth_binds = meth_binds,
60 arr_id = Var (lookupEvidence ds_meths arrAName),
61 compose_id = Var (lookupEvidence ds_meths composeAName),
62 first_id = Var (lookupEvidence ds_meths firstAName),
63 app_id = Var (lookupEvidence ds_meths appAName),
64 choice_id = Var (lookupEvidence ds_meths choiceAName),
65 loop_id = Var (lookupEvidence ds_meths loopAName)
68 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
69 bindCmdEnv ids body = foldr Let body (meth_binds ids)
71 -- arr :: forall b c. (b -> c) -> a b c
72 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
73 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
75 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
76 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
77 CoreExpr -> CoreExpr -> CoreExpr
78 do_compose ids b_ty c_ty d_ty f g
79 = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
81 -- first :: forall b c d. a b c -> a (b,d) (c,d)
82 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
83 do_first ids b_ty c_ty d_ty f
84 = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
86 -- app :: forall b c. a (a b c, b) c
87 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
88 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
90 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
91 -- note the swapping of d and c
92 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
93 CoreExpr -> CoreExpr -> CoreExpr
94 do_choice ids b_ty c_ty d_ty f g
95 = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
97 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
98 -- note the swapping of d and c
99 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
100 do_loop ids b_ty c_ty d_ty f
101 = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
103 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
104 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
105 CoreExpr -> CoreExpr -> CoreExpr
106 do_map_arrow ids b_ty c_ty d_ty f c
107 = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
109 mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr
111 = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
113 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
114 mkSndExpr :: Type -> Type -> DsM CoreExpr
116 = newSysLocalDs a_ty `thenDs` \ a_var ->
117 newSysLocalDs b_ty `thenDs` \ b_var ->
118 newSysLocalDs (mkCorePairTy a_ty b_ty) `thenDs` \ pair_var ->
119 returnDs (Lam pair_var
120 (coreCasePair pair_var a_var b_var (Var b_var)))
123 Build case analysis of a tuple. This cannot be done in the DsM monad,
124 because the list of variables is typically not yet defined.
127 -- coreCaseTuple [u1..] v [x1..xn] body
128 -- = case v of v { (x1, .., xn) -> body }
129 -- But the matching may be nested if the tuple is very big
131 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
132 coreCaseTuple uniqs scrut_var vars body
133 = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
135 coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
136 coreCasePair scrut_var var1 var2 body
137 = Case (Var scrut_var) scrut_var (exprType body)
138 [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
142 mkCorePairTy :: Type -> Type -> Type
143 mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]
145 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
146 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
149 The input is divided into a local environment, which is a flat tuple
150 (unless it's too big), and a stack, each element of which is paired
151 with the stack in turn. In general, the input has the form
153 (...((x1,...,xn),s1),...sk)
155 where xi are the environment values, and si the ones on the stack,
156 with s1 being the "top", the first one to be matched with a lambda.
159 envStackType :: [Id] -> [Type] -> Type
160 envStackType ids stack_tys = foldl mkCorePairTy (mkTupleType ids) stack_tys
162 ----------------------------------------------
165 -- (...((x1,...,xn),s1),...sk)
167 buildEnvStack :: [Id] -> [Id] -> CoreExpr
168 buildEnvStack env_ids stack_ids
169 = foldl mkCorePairExpr (mkTupleExpr env_ids) (map Var stack_ids)
171 ----------------------------------------------
174 -- \ (...((x1,...,xn),s1),...sk) -> e
177 -- case zk of (zk-1,sk) ->
179 -- case z1 of (z0,s1) ->
180 -- case z0 of (x1,...,xn) ->
183 matchEnvStack :: [Id] -- x1..xn
187 matchEnvStack env_ids stack_ids body
188 = newUniqueSupply `thenDs` \ uniqs ->
189 newSysLocalDs (mkTupleType env_ids) `thenDs` \ tup_var ->
190 matchVarStack tup_var stack_ids
191 (coreCaseTuple uniqs tup_var env_ids body)
194 ----------------------------------------------
197 -- \ (...(z0,s1),...sk) -> e
200 -- case zk of (zk-1,sk) ->
202 -- case z1 of (z0,s1) ->
205 matchVarStack :: Id -- z0
209 matchVarStack env_id [] body
210 = returnDs (Lam env_id body)
211 matchVarStack env_id (stack_id:stack_ids) body
212 = newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
213 `thenDs` \ pair_id ->
214 matchVarStack pair_id stack_ids
215 (coreCasePair pair_id env_id stack_id body)
219 mkHsTupleExpr :: [HsExpr Id] -> HsExpr Id
220 mkHsTupleExpr [e] = e
221 mkHsTupleExpr es = ExplicitTuple (map noLoc es) Boxed
223 mkHsPairExpr :: HsExpr Id -> HsExpr Id -> HsExpr Id
224 mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]
226 mkHsEnvStackExpr :: [Id] -> [Id] -> HsExpr Id
227 mkHsEnvStackExpr env_ids stack_ids
228 = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
231 Translation of arrow abstraction
235 -- A | xs |- c :: [] t' ---> c'
236 -- --------------------------
237 -- A |- proc p -> c :: a t t' ---> arr (\ p -> (xs)) >>> c'
239 -- where (xs) is the tuple of variables bound by p
245 dsProcExpr pat (L _ (HsCmdTop cmd [] cmd_ty ids))
246 = mkCmdEnv ids `thenDs` \ meth_ids ->
248 locals = mkVarSet (collectPatBinders pat)
250 dsfixCmd meth_ids locals [] cmd_ty cmd
251 `thenDs` \ (core_cmd, free_vars, env_ids) ->
253 env_ty = mkTupleType env_ids
255 mkFailExpr ProcExpr env_ty `thenDs` \ fail_expr ->
256 selectSimpleMatchVarL pat `thenDs` \ var ->
257 matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
258 `thenDs` \ match_code ->
260 pat_ty = hsLPatType pat
261 proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
265 returnDs (bindCmdEnv meth_ids proc_code)
268 Translation of command judgements of the form
270 A | xs |- c :: [ts] t
273 dsLCmd ids local_vars env_ids stack res_ty cmd
274 = dsCmd ids local_vars env_ids stack res_ty (unLoc cmd)
276 dsCmd :: DsCmdEnv -- arrow combinators
277 -> IdSet -- set of local vars available to this command
278 -> [Id] -- list of vars in the input to this command
279 -- This is typically fed back,
280 -- so don't pull on it too early
281 -> [Type] -- type of the stack
282 -> Type -- return type of the command
283 -> HsCmd Id -- command to desugar
284 -> DsM (CoreExpr, -- desugared expression
285 IdSet) -- set of local vars that occur free
287 -- A |- f :: a (t*ts) t'
289 -- -----------------------------
290 -- A | xs |- f -< arg :: [ts] t'
292 -- ---> arr (\ ((xs)*ts) -> (arg*ts)) >>> f
294 dsCmd ids local_vars env_ids stack res_ty
295 (HsArrApp arrow arg arrow_ty HsFirstOrderApp _)
297 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
298 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
299 env_ty = mkTupleType env_ids
301 dsLExpr arrow `thenDs` \ core_arrow ->
302 dsLExpr arg `thenDs` \ core_arg ->
303 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
304 matchEnvStack env_ids stack_ids
305 (foldl mkCorePairExpr core_arg (map Var stack_ids))
306 `thenDs` \ core_make_arg ->
307 returnDs (do_map_arrow ids
308 (envStackType env_ids stack)
313 exprFreeVars core_arg `intersectVarSet` local_vars)
315 -- A, xs |- f :: a (t*ts) t'
317 -- ------------------------------
318 -- A | xs |- f -<< arg :: [ts] t'
320 -- ---> arr (\ ((xs)*ts) -> (f,(arg*ts))) >>> app
322 dsCmd ids local_vars env_ids stack res_ty
323 (HsArrApp arrow arg arrow_ty HsHigherOrderApp _)
325 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
326 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
327 env_ty = mkTupleType env_ids
329 dsLExpr arrow `thenDs` \ core_arrow ->
330 dsLExpr arg `thenDs` \ core_arg ->
331 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
332 matchEnvStack env_ids stack_ids
333 (mkCorePairExpr core_arrow
334 (foldl mkCorePairExpr core_arg (map Var stack_ids)))
335 `thenDs` \ core_make_pair ->
336 returnDs (do_map_arrow ids
337 (envStackType env_ids stack)
338 (mkCorePairTy arrow_ty arg_ty)
341 (do_app ids arg_ty res_ty),
342 (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
343 `intersectVarSet` local_vars)
345 -- A | ys |- c :: [t:ts] t'
347 -- ------------------------
348 -- A | xs |- c e :: [ts] t'
350 -- ---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c
352 dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg)
353 = dsLExpr arg `thenDs` \ core_arg ->
355 arg_ty = exprType core_arg
356 stack' = arg_ty:stack
358 dsfixCmd ids local_vars stack' res_ty cmd
359 `thenDs` \ (core_cmd, free_vars, env_ids') ->
360 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
361 newSysLocalDs arg_ty `thenDs` \ arg_id ->
362 -- push the argument expression onto the stack
364 core_body = bindNonRec arg_id core_arg
365 (buildEnvStack env_ids' (arg_id:stack_ids))
367 -- match the environment and stack against the input
368 matchEnvStack env_ids stack_ids core_body
369 `thenDs` \ core_map ->
370 returnDs (do_map_arrow ids
371 (envStackType env_ids stack)
372 (envStackType env_ids' stack')
376 (exprFreeVars core_arg `intersectVarSet` local_vars)
377 `unionVarSet` free_vars)
379 -- A | ys |- c :: [ts] t'
380 -- -----------------------------------------------
381 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
383 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
385 dsCmd ids local_vars env_ids stack res_ty
386 (HsLam (MatchGroup [L _ (Match pats _ (GRHSs [L _ (GRHS [] body)] _ ))] _))
388 pat_vars = mkVarSet (collectPatsBinders pats)
389 local_vars' = local_vars `unionVarSet` pat_vars
390 stack' = drop (length pats) stack
392 dsfixCmd ids local_vars' stack' res_ty body
393 `thenDs` \ (core_body, free_vars, env_ids') ->
394 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
396 -- the expression is built from the inside out, so the actions
397 -- are presented in reverse order
400 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
401 -- build a new environment, plus what's left of the stack
402 core_expr = buildEnvStack env_ids' stack_ids'
403 in_ty = envStackType env_ids stack
404 in_ty' = envStackType env_ids' stack'
406 mkFailExpr LambdaExpr in_ty' `thenDs` \ fail_expr ->
407 -- match the patterns against the top of the old stack
408 matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
409 `thenDs` \ match_code ->
410 -- match the old environment and stack against the input
411 matchEnvStack env_ids stack_ids match_code
412 `thenDs` \ select_code ->
413 returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
414 free_vars `minusVarSet` pat_vars)
416 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
417 = dsLCmd ids local_vars env_ids stack res_ty cmd
419 -- A, xs |- e :: Bool
420 -- A | xs1 |- c1 :: [ts] t
421 -- A | xs2 |- c2 :: [ts] t
422 -- ----------------------------------------
423 -- A | xs |- if e then c1 else c2 :: [ts] t
425 -- ---> arr (\ ((xs)*ts) ->
426 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
429 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd)
430 = dsLExpr cond `thenDs` \ core_cond ->
431 dsfixCmd ids local_vars stack res_ty then_cmd
432 `thenDs` \ (core_then, fvs_then, then_ids) ->
433 dsfixCmd ids local_vars stack res_ty else_cmd
434 `thenDs` \ (core_else, fvs_else, else_ids) ->
435 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
436 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
437 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
438 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
440 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
441 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
443 in_ty = envStackType env_ids stack
444 then_ty = envStackType then_ids stack
445 else_ty = envStackType else_ids stack
446 sum_ty = mkTyConApp either_con [then_ty, else_ty]
447 fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
449 matchEnvStack env_ids stack_ids
450 (mkIfThenElse core_cond
451 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
452 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
453 `thenDs` \ core_if ->
454 returnDs(do_map_arrow ids in_ty sum_ty res_ty
456 (do_choice ids then_ty else_ty res_ty core_then core_else),
457 fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
460 Case commands are treated in much the same way as if commands
461 (see above) except that there are more alternatives. For example
463 case e of { p1 -> c1; p2 -> c2; p3 -> c3 }
467 arr (\ ((xs)*ts) -> case e of
468 p1 -> (Left (Left (xs1)*ts))
469 p2 -> Left ((Right (xs2)*ts))
470 p3 -> Right ((xs3)*ts)) >>>
473 The idea is to extract the commands from the case, build a balanced tree
474 of choices, and replace the commands with expressions that build tagged
475 tuples, obtaining a case expression that can be desugared normally.
476 To build all this, we use quadruples decribing segments of the list of
477 case bodies, containing the following fields:
478 1. an IdSet containing the environment variables free in the case bodies
479 2. a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
480 into the case replacing the commands
481 3. a sum type that is the common type of these expressions, and also the
482 input type of the arrow
483 4. a CoreExpr for an arrow built by combining the translated command
487 dsCmd ids local_vars env_ids stack res_ty (HsCase exp (MatchGroup matches match_ty))
488 = dsLExpr exp `thenDs` \ core_exp ->
489 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
491 -- Extract and desugar the leaf commands in the case, building tuple
492 -- expressions that will (after tagging) replace these leaves
495 leaves = concatMap leavesMatch matches
496 make_branch (leaf, bound_vars)
497 = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
498 `thenDs` \ (core_leaf, fvs, leaf_ids) ->
499 returnDs (fvs `minusVarSet` bound_vars,
500 [noLoc $ mkHsEnvStackExpr leaf_ids stack_ids],
501 envStackType leaf_ids stack,
504 mappM make_branch leaves `thenDs` \ branches ->
505 dsLookupTyCon eitherTyConName `thenDs` \ either_con ->
506 dsLookupDataCon leftDataConName `thenDs` \ left_con ->
507 dsLookupDataCon rightDataConName `thenDs` \ right_con ->
509 left_id = HsVar (dataConWrapId left_con)
510 right_id = HsVar (dataConWrapId right_con)
511 left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) left_id ) e
512 right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) right_id) e
514 -- Prefix each tuple with a distinct series of Left's and Right's,
515 -- in a balanced way, keeping track of the types.
517 merge_branches (fvs1, builds1, in_ty1, core_exp1)
518 (fvs2, builds2, in_ty2, core_exp2)
519 = (fvs1 `unionVarSet` fvs2,
520 map (left_expr in_ty1 in_ty2) builds1 ++
521 map (right_expr in_ty1 in_ty2) builds2,
522 mkTyConApp either_con [in_ty1, in_ty2],
523 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
524 (fvs_alts, leaves', sum_ty, core_choices)
525 = foldb merge_branches branches
527 -- Replace the commands in the case with these tagged tuples,
528 -- yielding a HsExpr Id we can feed to dsExpr.
530 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
531 in_ty = envStackType env_ids stack
532 fvs_exp = exprFreeVars core_exp `intersectVarSet` local_vars
534 pat_ty = funArgTy match_ty
535 match_ty' = mkFunTy pat_ty sum_ty
536 -- Note that we replace the HsCase result type by sum_ty,
537 -- which is the type of matches'
539 dsExpr (HsCase exp (MatchGroup matches' match_ty')) `thenDs` \ core_body ->
540 matchEnvStack env_ids stack_ids core_body
541 `thenDs` \ core_matches ->
542 returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
543 fvs_exp `unionVarSet` fvs_alts)
545 -- A | ys |- c :: [ts] t
546 -- ----------------------------------
547 -- A | xs |- let binds in c :: [ts] t
549 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
551 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
553 defined_vars = mkVarSet (map unLoc (collectLocalBinders binds))
554 local_vars' = local_vars `unionVarSet` defined_vars
556 dsfixCmd ids local_vars' stack res_ty body
557 `thenDs` \ (core_body, free_vars, env_ids') ->
558 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
559 -- build a new environment, plus the stack, using the let bindings
560 dsLocalBinds binds (buildEnvStack env_ids' stack_ids)
561 `thenDs` \ core_binds ->
562 -- match the old environment and stack against the input
563 matchEnvStack env_ids stack_ids core_binds
564 `thenDs` \ core_map ->
565 returnDs (do_map_arrow ids
566 (envStackType env_ids stack)
567 (envStackType env_ids' stack)
571 exprFreeVars core_binds `intersectVarSet` local_vars)
573 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts body _)
574 = dsCmdDo ids local_vars env_ids res_ty stmts body
576 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
577 -- A | xs |- ci :: [tsi] ti
578 -- -----------------------------------
579 -- A | xs |- (|e c1 ... cn|) :: [ts] t ---> e [t_xs] c1 ... cn
581 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args)
583 env_ty = mkTupleType env_ids
585 dsLExpr op `thenDs` \ core_op ->
586 mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
587 `thenDs` \ (core_args, fv_sets) ->
588 returnDs (mkApps (App core_op (Type env_ty)) core_args,
589 unionVarSets fv_sets)
592 dsCmd ids local_vars env_ids stack res_ty (HsTick ix vars expr)
593 = dsLCmd ids local_vars env_ids stack res_ty expr `thenDs` \ (expr1,id_set) ->
594 mkTickBox ix vars expr1 `thenDs` \ expr2 ->
595 return (expr2,id_set)
597 -- A | ys |- c :: [ts] t (ys <= xs)
598 -- ---------------------
599 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
602 :: IdSet -- set of local vars available to this command
603 -> [Id] -- list of vars in the input to this command
604 -> LHsCmdTop Id -- command argument to desugar
605 -> DsM (CoreExpr, -- desugared expression
606 IdSet) -- set of local vars that occur free
607 dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack cmd_ty ids))
608 = mkCmdEnv ids `thenDs` \ meth_ids ->
609 dsfixCmd meth_ids local_vars stack cmd_ty cmd
610 `thenDs` \ (core_cmd, free_vars, env_ids') ->
611 mappM newSysLocalDs stack `thenDs` \ stack_ids ->
612 matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
613 `thenDs` \ trim_code ->
615 in_ty = envStackType env_ids stack
616 in_ty' = envStackType env_ids' stack
617 arg_code = if env_ids' == env_ids then core_cmd else
618 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
620 returnDs (bindCmdEnv meth_ids arg_code, free_vars)
622 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
623 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
626 :: DsCmdEnv -- arrow combinators
627 -> IdSet -- set of local vars available to this command
628 -> [Type] -- type of the stack
629 -> Type -- return type of the command
630 -> LHsCmd Id -- command to desugar
631 -> DsM (CoreExpr, -- desugared expression
632 IdSet, -- set of local vars that occur free
633 [Id]) -- set as a list, fed back
634 dsfixCmd ids local_vars stack cmd_ty cmd
635 = fixDs (\ ~(_,_,env_ids') ->
636 dsLCmd ids local_vars env_ids' stack cmd_ty cmd
637 `thenDs` \ (core_cmd, free_vars) ->
638 returnDs (core_cmd, free_vars, varSetElems free_vars))
642 Translation of command judgements of the form
644 A | xs |- do { ss } :: [] t
648 dsCmdDo :: DsCmdEnv -- arrow combinators
649 -> IdSet -- set of local vars available to this statement
650 -> [Id] -- list of vars in the input to this statement
651 -- This is typically fed back,
652 -- so don't pull on it too early
653 -> Type -- return type of the statement
654 -> [LStmt Id] -- statements to desugar
655 -> LHsExpr Id -- body
656 -> DsM (CoreExpr, -- desugared expression
657 IdSet) -- set of local vars that occur free
659 -- A | xs |- c :: [] t
660 -- --------------------------
661 -- A | xs |- do { c } :: [] t
663 dsCmdDo ids local_vars env_ids res_ty [] body
664 = dsLCmd ids local_vars env_ids [] res_ty body
666 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts) body
668 bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
669 local_vars' = local_vars `unionVarSet` bound_vars
671 fixDs (\ ~(_,_,env_ids') ->
672 dsCmdDo ids local_vars' env_ids' res_ty stmts body
673 `thenDs` \ (core_stmts, fv_stmts) ->
674 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
675 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
676 dsCmdLStmt ids local_vars env_ids env_ids' stmt
677 `thenDs` \ (core_stmt, fv_stmt) ->
678 returnDs (do_compose ids
679 (mkTupleType env_ids)
680 (mkTupleType env_ids')
687 A statement maps one local environment to another, and is represented
688 as an arrow from one tuple type to another. A statement sequence is
689 translated to a composition of such arrows.
691 dsCmdLStmt ids local_vars env_ids out_ids cmd
692 = dsCmdStmt ids local_vars env_ids out_ids (unLoc cmd)
695 :: DsCmdEnv -- arrow combinators
696 -> IdSet -- set of local vars available to this statement
697 -> [Id] -- list of vars in the input to this statement
698 -- This is typically fed back,
699 -- so don't pull on it too early
700 -> [Id] -- list of vars in the output of this statement
701 -> Stmt Id -- statement to desugar
702 -> DsM (CoreExpr, -- desugared expression
703 IdSet) -- set of local vars that occur free
705 -- A | xs1 |- c :: [] t
706 -- A | xs' |- do { ss } :: [] t'
707 -- ------------------------------
708 -- A | xs |- do { c; ss } :: [] t'
710 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
713 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd _ c_ty)
714 = dsfixCmd ids local_vars [] c_ty cmd
715 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
716 matchEnvStack env_ids []
717 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
718 `thenDs` \ core_mux ->
720 in_ty = mkTupleType env_ids
721 in_ty1 = mkTupleType env_ids1
722 out_ty = mkTupleType out_ids
723 before_c_ty = mkCorePairTy in_ty1 out_ty
724 after_c_ty = mkCorePairTy c_ty out_ty
726 mkSndExpr c_ty out_ty `thenDs` \ snd_fn ->
727 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
728 do_compose ids before_c_ty after_c_ty out_ty
729 (do_first ids in_ty1 c_ty out_ty core_cmd) $
730 do_arr ids after_c_ty out_ty snd_fn,
731 extendVarSetList fv_cmd out_ids)
734 -- A | xs1 |- c :: [] t
735 -- A | xs' |- do { ss } :: [] t' xs2 = xs' - defs(p)
736 -- -----------------------------------
737 -- A | xs |- do { p <- c; ss } :: [] t'
739 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
740 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
742 -- It would be simpler and more consistent to do this using second,
743 -- but that's likely to be defined in terms of first.
745 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _ _)
746 = dsfixCmd ids local_vars [] (hsLPatType pat) cmd
747 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
749 pat_ty = hsLPatType pat
750 pat_vars = mkVarSet (collectPatBinders pat)
751 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
752 env_ty2 = mkTupleType env_ids2
755 -- multiplexing function
756 -- \ (xs) -> ((xs1),(xs2))
758 matchEnvStack env_ids []
759 (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
760 `thenDs` \ core_mux ->
762 -- projection function
763 -- \ (p, (xs2)) -> (zs)
765 newSysLocalDs env_ty2 `thenDs` \ env_id ->
766 newUniqueSupply `thenDs` \ uniqs ->
768 after_c_ty = mkCorePairTy pat_ty env_ty2
769 out_ty = mkTupleType out_ids
770 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
772 mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
773 selectSimpleMatchVarL pat `thenDs` \ pat_id ->
774 matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
775 `thenDs` \ match_code ->
776 newSysLocalDs after_c_ty `thenDs` \ pair_id ->
778 proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
781 -- put it all together
783 in_ty = mkTupleType env_ids
784 in_ty1 = mkTupleType env_ids1
785 in_ty2 = mkTupleType env_ids2
786 before_c_ty = mkCorePairTy in_ty1 in_ty2
788 returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
789 do_compose ids before_c_ty after_c_ty out_ty
790 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
791 do_arr ids after_c_ty out_ty proj_expr,
792 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
794 -- A | xs' |- do { ss } :: [] t
795 -- --------------------------------------
796 -- A | xs |- do { let binds; ss } :: [] t
798 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
800 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
801 -- build a new environment using the let bindings
802 = dsLocalBinds binds (mkTupleExpr out_ids) `thenDs` \ core_binds ->
803 -- match the old environment against the input
804 matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
806 (mkTupleType env_ids)
807 (mkTupleType out_ids)
809 exprFreeVars core_binds `intersectVarSet` local_vars)
811 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
812 -- A | xs' |- do { ss' } :: [] t
813 -- ------------------------------------
814 -- A | xs |- do { rec ss; ss' } :: [] t
816 -- xs1 = xs' /\ defs(ss)
817 -- xs2 = xs' - defs(ss)
818 -- ys1 = ys - defs(ss)
819 -- ys2 = ys /\ defs(ss)
821 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
822 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
823 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
825 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss binds)
826 = let -- ToDo: ****** binds not desugared; ROSS PLEASE FIX ********
827 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
828 env2_ids = varSetElems env2_id_set
829 env2_ty = mkTupleType env2_ids
832 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
834 newUniqueSupply `thenDs` \ uniqs ->
835 newSysLocalDs env2_ty `thenDs` \ env2_id ->
837 later_ty = mkTupleType later_ids
838 post_pair_ty = mkCorePairTy later_ty env2_ty
839 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
841 matchEnvStack later_ids [env2_id] post_loop_body
842 `thenDs` \ post_loop_fn ->
846 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
847 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
849 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
852 env1_ty = mkTupleType env1_ids
853 pre_pair_ty = mkCorePairTy env1_ty env2_ty
854 pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
855 (mkTupleExpr env2_ids)
858 matchEnvStack env_ids [] pre_loop_body
859 `thenDs` \ pre_loop_fn ->
861 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
864 env_ty = mkTupleType env_ids
865 out_ty = mkTupleType out_ids
866 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
868 (do_compose ids pre_pair_ty post_pair_ty out_ty
869 (do_first ids env1_ty later_ty env2_ty
871 (do_arr ids post_pair_ty out_ty
874 returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
876 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
878 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
880 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
882 rec_id_set = mkVarSet rec_ids
883 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
884 out_ty = mkTupleType out_ids
885 local_vars' = local_vars `unionVarSet` rec_id_set
888 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
890 mappM dsExpr rhss `thenDs` \ core_rhss ->
892 later_tuple = mkTupleExpr later_ids
893 later_ty = mkTupleType later_ids
894 rec_tuple = mkBigCoreTup core_rhss
895 rec_ty = mkTupleType rec_ids
896 out_pair = mkCorePairExpr later_tuple rec_tuple
897 out_pair_ty = mkCorePairTy later_ty rec_ty
899 matchEnvStack out_ids [] out_pair
900 `thenDs` \ mk_pair_fn ->
904 dsfixCmdStmts ids local_vars' out_ids stmts
905 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
907 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
909 newSysLocalDs rec_ty `thenDs` \ rec_id ->
911 env1_id_set = fv_stmts `minusVarSet` rec_id_set
912 env1_ids = varSetElems env1_id_set
913 env1_ty = mkTupleType env1_ids
914 in_pair_ty = mkCorePairTy env1_ty rec_ty
915 core_body = mkBigCoreTup (map selectVar env_ids)
918 | v `elemVarSet` rec_id_set
919 = mkTupleSelector rec_ids v rec_id (Var rec_id)
922 matchEnvStack env1_ids [rec_id] core_body
923 `thenDs` \ squash_pair_fn ->
925 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
928 env_ty = mkTupleType env_ids
929 core_loop = do_loop ids env1_ty later_ty rec_ty
930 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
932 (do_compose ids env_ty out_ty out_pair_ty
934 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
936 returnDs (core_loop, env1_id_set, env1_ids)
939 A sequence of statements (as in a rec) is desugared to an arrow between
944 :: DsCmdEnv -- arrow combinators
945 -> IdSet -- set of local vars available to this statement
946 -> [Id] -- output vars of these statements
947 -> [LStmt Id] -- statements to desugar
948 -> DsM (CoreExpr, -- desugared expression
949 IdSet, -- set of local vars that occur free
952 dsfixCmdStmts ids local_vars out_ids stmts
953 = fixDs (\ ~(_,_,env_ids) ->
954 dsCmdStmts ids local_vars env_ids out_ids stmts
955 `thenDs` \ (core_stmts, fv_stmts) ->
956 returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
959 :: DsCmdEnv -- arrow combinators
960 -> IdSet -- set of local vars available to this statement
961 -> [Id] -- list of vars in the input to these statements
962 -> [Id] -- output vars of these statements
963 -> [LStmt Id] -- statements to desugar
964 -> DsM (CoreExpr, -- desugared expression
965 IdSet) -- set of local vars that occur free
967 dsCmdStmts ids local_vars env_ids out_ids [stmt]
968 = dsCmdLStmt ids local_vars env_ids out_ids stmt
970 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
972 bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
973 local_vars' = local_vars `unionVarSet` bound_vars
975 dsfixCmdStmts ids local_vars' out_ids stmts
976 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
977 dsCmdLStmt ids local_vars env_ids env_ids' stmt
978 `thenDs` \ (core_stmt, fv_stmt) ->
979 returnDs (do_compose ids
980 (mkTupleType env_ids)
981 (mkTupleType env_ids')
982 (mkTupleType out_ids)
989 Match a list of expressions against a list of patterns, left-to-right.
992 matchSimplys :: [CoreExpr] -- Scrutinees
993 -> HsMatchContext Name -- Match kind
994 -> [LPat Id] -- Patterns they should match
995 -> CoreExpr -- Return this if they all match
996 -> CoreExpr -- Return this if they don't
998 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
999 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
1000 = matchSimplys exps ctxt pats result_expr fail_expr
1001 `thenDs` \ match_code ->
1002 matchSimply exp ctxt pat match_code fail_expr
1005 List of leaf expressions, with set of variables bound in each
1008 leavesMatch :: LMatch Id -> [(LHsExpr Id, IdSet)]
1009 leavesMatch (L _ (Match pats _ (GRHSs grhss binds)))
1011 defined_vars = mkVarSet (collectPatsBinders pats)
1013 mkVarSet (map unLoc (collectLocalBinders binds))
1016 mkVarSet (map unLoc (collectLStmtsBinders stmts))
1017 `unionVarSet` defined_vars)
1018 | L _ (GRHS stmts expr) <- grhss]
1021 Replace the leaf commands in a match
1025 :: Type -- new result type
1026 -> [LHsExpr Id] -- replacement leaf expressions of that type
1027 -> LMatch Id -- the matches of a case command
1028 -> ([LHsExpr Id],-- remaining leaf expressions
1029 LMatch Id) -- updated match
1030 replaceLeavesMatch res_ty leaves (L loc (Match pat mt (GRHSs grhss binds)))
1032 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
1034 (leaves', L loc (Match pat mt (GRHSs grhss' binds)))
1037 :: [LHsExpr Id] -- replacement leaf expressions of that type
1038 -> LGRHS Id -- rhss of a case command
1039 -> ([LHsExpr Id],-- remaining leaf expressions
1040 LGRHS Id) -- updated GRHS
1041 replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts rhs))
1042 = (leaves, L loc (GRHS stmts leaf))
1045 Balanced fold of a non-empty list.
1048 foldb :: (a -> a -> a) -> [a] -> a
1049 foldb _ [] = error "foldb of empty list"
1051 foldb f xs = foldb f (fold_pairs xs)
1054 fold_pairs [x] = [x]
1055 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs