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"
17 import HsSyn hiding (collectPatBinders, collectLocatedPatBinders, collectl,
18 collectPatsBinders, collectLocatedPatsBinders)
21 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
22 -- needs to see source types (newtypes etc), and sometimes not
23 -- So WATCH OUT; check each use of split*Ty functions.
24 -- Sigh. This is a pain.
26 import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLocalBinds )
52 data DsCmdEnv = DsCmdEnv {
53 meth_binds :: [CoreBind],
54 arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
57 mkCmdEnv :: SyntaxTable Id -> DsM DsCmdEnv
59 (meth_binds, ds_meths) <- dsSyntaxTable ids
61 meth_binds = meth_binds,
62 arr_id = Var (lookupEvidence ds_meths arrAName),
63 compose_id = Var (lookupEvidence ds_meths composeAName),
64 first_id = Var (lookupEvidence ds_meths firstAName),
65 app_id = Var (lookupEvidence ds_meths appAName),
66 choice_id = Var (lookupEvidence ds_meths choiceAName),
67 loop_id = Var (lookupEvidence ds_meths loopAName)
70 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
71 bindCmdEnv ids body = foldr Let body (meth_binds ids)
73 -- arr :: forall b c. (b -> c) -> a b c
74 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
75 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
77 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
78 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
79 CoreExpr -> CoreExpr -> CoreExpr
80 do_compose ids b_ty c_ty d_ty f g
81 = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
83 -- first :: forall b c d. a b c -> a (b,d) (c,d)
84 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
85 do_first ids b_ty c_ty d_ty f
86 = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
88 -- app :: forall b c. a (a b c, b) c
89 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
90 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
92 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
93 -- note the swapping of d and c
94 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
95 CoreExpr -> CoreExpr -> CoreExpr
96 do_choice ids b_ty c_ty d_ty f g
97 = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
99 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
100 -- note the swapping of d and c
101 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
102 do_loop ids b_ty c_ty d_ty f
103 = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
105 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
106 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
107 CoreExpr -> CoreExpr -> CoreExpr
108 do_map_arrow ids b_ty c_ty d_ty f c
109 = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
111 mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr
113 = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
115 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
116 mkSndExpr :: Type -> Type -> DsM CoreExpr
117 mkSndExpr a_ty b_ty = do
118 a_var <- newSysLocalDs a_ty
119 b_var <- newSysLocalDs b_ty
120 pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty)
122 (coreCasePair pair_var a_var b_var (Var b_var)))
125 Build case analysis of a tuple. This cannot be done in the DsM monad,
126 because the list of variables is typically not yet defined.
129 -- coreCaseTuple [u1..] v [x1..xn] body
130 -- = case v of v { (x1, .., xn) -> body }
131 -- But the matching may be nested if the tuple is very big
133 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
134 coreCaseTuple uniqs scrut_var vars body
135 = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
137 coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
138 coreCasePair scrut_var var1 var2 body
139 = Case (Var scrut_var) scrut_var (exprType body)
140 [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
144 mkCorePairTy :: Type -> Type -> Type
145 mkCorePairTy t1 t2 = mkBoxedTupleTy [t1, t2]
147 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
148 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
151 The input is divided into a local environment, which is a flat tuple
152 (unless it's too big), and a stack, each element of which is paired
153 with the stack in turn. In general, the input has the form
155 (...((x1,...,xn),s1),...sk)
157 where xi are the environment values, and si the ones on the stack,
158 with s1 being the "top", the first one to be matched with a lambda.
161 envStackType :: [Id] -> [Type] -> Type
162 envStackType ids stack_tys = foldl mkCorePairTy (mkBigCoreVarTupTy ids) stack_tys
164 ----------------------------------------------
167 -- (...((x1,...,xn),s1),...sk)
169 buildEnvStack :: [Id] -> [Id] -> CoreExpr
170 buildEnvStack env_ids stack_ids
171 = foldl mkCorePairExpr (mkBigCoreVarTup env_ids) (map Var stack_ids)
173 ----------------------------------------------
176 -- \ (...((x1,...,xn),s1),...sk) -> e
179 -- case zk of (zk-1,sk) ->
181 -- case z1 of (z0,s1) ->
182 -- case z0 of (x1,...,xn) ->
185 matchEnvStack :: [Id] -- x1..xn
189 matchEnvStack env_ids stack_ids body = do
190 uniqs <- newUniqueSupply
191 tup_var <- newSysLocalDs (mkBigCoreVarTupTy env_ids)
192 matchVarStack tup_var stack_ids
193 (coreCaseTuple uniqs tup_var env_ids body)
196 ----------------------------------------------
199 -- \ (...(z0,s1),...sk) -> e
202 -- case zk of (zk-1,sk) ->
204 -- case z1 of (z0,s1) ->
207 matchVarStack :: Id -- z0
211 matchVarStack env_id [] body
212 = return (Lam env_id body)
213 matchVarStack env_id (stack_id:stack_ids) body = do
214 pair_id <- newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
215 matchVarStack pair_id stack_ids
216 (coreCasePair pair_id env_id stack_id body)
220 mkHsEnvStackExpr :: [Id] -> [Id] -> LHsExpr Id
221 mkHsEnvStackExpr env_ids stack_ids
222 = foldl (\a b -> mkLHsTupleExpr [a,b])
223 (mkLHsVarTuple env_ids)
224 (map nlHsVar stack_ids)
227 Translation of arrow abstraction
231 -- A | xs |- c :: [] t' ---> c'
232 -- --------------------------
233 -- A |- proc p -> c :: a t t' ---> arr (\ p -> (xs)) >>> c'
235 -- where (xs) is the tuple of variables bound by p
241 dsProcExpr pat (L _ (HsCmdTop cmd [] cmd_ty ids)) = do
242 meth_ids <- mkCmdEnv ids
243 let locals = mkVarSet (collectPatBinders pat)
244 (core_cmd, _free_vars, env_ids) <- dsfixCmd meth_ids locals [] cmd_ty cmd
245 let env_ty = mkBigCoreVarTupTy env_ids
246 fail_expr <- mkFailExpr ProcExpr env_ty
247 var <- selectSimpleMatchVarL pat
248 match_code <- matchSimply (Var var) ProcExpr pat (mkBigCoreVarTup env_ids) fail_expr
249 let pat_ty = hsLPatType pat
250 proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
253 return (bindCmdEnv meth_ids proc_code)
254 dsProcExpr _ c = pprPanic "dsProcExpr" (ppr c)
257 Translation of command judgements of the form
259 A | xs |- c :: [ts] t
262 dsLCmd :: DsCmdEnv -> IdSet -> [Id] -> [Type] -> Type -> LHsCmd Id
263 -> DsM (CoreExpr, IdSet)
264 dsLCmd ids local_vars env_ids stack res_ty cmd
265 = dsCmd ids local_vars env_ids stack res_ty (unLoc cmd)
267 dsCmd :: DsCmdEnv -- arrow combinators
268 -> IdSet -- set of local vars available to this command
269 -> [Id] -- list of vars in the input to this command
270 -- This is typically fed back,
271 -- so don't pull on it too early
272 -> [Type] -- type of the stack
273 -> Type -- return type of the command
274 -> HsCmd Id -- command to desugar
275 -> DsM (CoreExpr, -- desugared expression
276 IdSet) -- set of local vars that occur free
278 -- A |- f :: a (t*ts) t'
280 -- -----------------------------
281 -- A | xs |- f -< arg :: [ts] t'
283 -- ---> arr (\ ((xs)*ts) -> (arg*ts)) >>> f
285 dsCmd ids local_vars env_ids stack res_ty
286 (HsArrApp arrow arg arrow_ty HsFirstOrderApp _)= do
288 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
289 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
290 core_arrow <- dsLExpr arrow
291 core_arg <- dsLExpr arg
292 stack_ids <- mapM newSysLocalDs stack
293 core_make_arg <- matchEnvStack env_ids stack_ids
294 (foldl mkCorePairExpr core_arg (map Var stack_ids))
295 return (do_map_arrow ids
296 (envStackType env_ids stack)
301 exprFreeVars core_arg `intersectVarSet` local_vars)
303 -- A, xs |- f :: a (t*ts) t'
305 -- ------------------------------
306 -- A | xs |- f -<< arg :: [ts] t'
308 -- ---> arr (\ ((xs)*ts) -> (f,(arg*ts))) >>> app
310 dsCmd ids local_vars env_ids stack res_ty
311 (HsArrApp arrow arg arrow_ty HsHigherOrderApp _) = do
313 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
314 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
316 core_arrow <- dsLExpr arrow
317 core_arg <- dsLExpr arg
318 stack_ids <- mapM newSysLocalDs stack
319 core_make_pair <- matchEnvStack env_ids stack_ids
320 (mkCorePairExpr core_arrow
321 (foldl mkCorePairExpr core_arg (map Var stack_ids)))
323 return (do_map_arrow ids
324 (envStackType env_ids stack)
325 (mkCorePairTy arrow_ty arg_ty)
328 (do_app ids arg_ty res_ty),
329 (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
330 `intersectVarSet` local_vars)
332 -- A | ys |- c :: [t:ts] t'
334 -- ------------------------
335 -- A | xs |- c e :: [ts] t'
337 -- ---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c
339 dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg) = do
340 core_arg <- dsLExpr arg
342 arg_ty = exprType core_arg
343 stack' = arg_ty:stack
344 (core_cmd, free_vars, env_ids')
345 <- dsfixCmd ids local_vars stack' res_ty cmd
346 stack_ids <- mapM newSysLocalDs stack
347 arg_id <- newSysLocalDs arg_ty
348 -- push the argument expression onto the stack
350 core_body = bindNonRec arg_id core_arg
351 (buildEnvStack env_ids' (arg_id:stack_ids))
352 -- match the environment and stack against the input
353 core_map <- matchEnvStack env_ids stack_ids core_body
354 return (do_map_arrow ids
355 (envStackType env_ids stack)
356 (envStackType env_ids' stack')
360 (exprFreeVars core_arg `intersectVarSet` local_vars)
361 `unionVarSet` free_vars)
363 -- A | ys |- c :: [ts] t'
364 -- -----------------------------------------------
365 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
367 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
369 dsCmd ids local_vars env_ids stack res_ty
370 (HsLam (MatchGroup [L _ (Match pats _ (GRHSs [L _ (GRHS [] body)] _ ))] _)) = do
372 pat_vars = mkVarSet (collectPatsBinders pats)
373 local_vars' = local_vars `unionVarSet` pat_vars
374 stack' = drop (length pats) stack
375 (core_body, free_vars, env_ids') <- dsfixCmd ids local_vars' stack' res_ty body
376 stack_ids <- mapM newSysLocalDs stack
378 -- the expression is built from the inside out, so the actions
379 -- are presented in reverse order
382 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
383 -- build a new environment, plus what's left of the stack
384 core_expr = buildEnvStack env_ids' stack_ids'
385 in_ty = envStackType env_ids stack
386 in_ty' = envStackType env_ids' stack'
388 fail_expr <- mkFailExpr LambdaExpr in_ty'
389 -- match the patterns against the top of the old stack
390 match_code <- matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
391 -- match the old environment and stack against the input
392 select_code <- matchEnvStack env_ids stack_ids match_code
393 return (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
394 free_vars `minusVarSet` pat_vars)
396 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
397 = dsLCmd ids local_vars env_ids stack res_ty cmd
399 -- A, xs |- e :: Bool
400 -- A | xs1 |- c1 :: [ts] t
401 -- A | xs2 |- c2 :: [ts] t
402 -- ----------------------------------------
403 -- A | xs |- if e then c1 else c2 :: [ts] t
405 -- ---> arr (\ ((xs)*ts) ->
406 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
409 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd) = do
410 core_cond <- dsLExpr cond
411 (core_then, fvs_then, then_ids) <- dsfixCmd ids local_vars stack res_ty then_cmd
412 (core_else, fvs_else, else_ids) <- dsfixCmd ids local_vars stack res_ty else_cmd
413 stack_ids <- mapM newSysLocalDs stack
414 either_con <- dsLookupTyCon eitherTyConName
415 left_con <- dsLookupDataCon leftDataConName
416 right_con <- dsLookupDataCon rightDataConName
418 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
419 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
421 in_ty = envStackType env_ids stack
422 then_ty = envStackType then_ids stack
423 else_ty = envStackType else_ids stack
424 sum_ty = mkTyConApp either_con [then_ty, else_ty]
425 fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
427 core_if <- matchEnvStack env_ids stack_ids
428 (mkIfThenElse core_cond
429 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
430 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
431 return (do_map_arrow ids in_ty sum_ty res_ty
433 (do_choice ids then_ty else_ty res_ty core_then core_else),
434 fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
437 Case commands are treated in much the same way as if commands
438 (see above) except that there are more alternatives. For example
440 case e of { p1 -> c1; p2 -> c2; p3 -> c3 }
444 arr (\ ((xs)*ts) -> case e of
445 p1 -> (Left (Left (xs1)*ts))
446 p2 -> Left ((Right (xs2)*ts))
447 p3 -> Right ((xs3)*ts)) >>>
450 The idea is to extract the commands from the case, build a balanced tree
451 of choices, and replace the commands with expressions that build tagged
452 tuples, obtaining a case expression that can be desugared normally.
453 To build all this, we use quadruples decribing segments of the list of
454 case bodies, containing the following fields:
455 1. an IdSet containing the environment variables free in the case bodies
456 2. a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
457 into the case replacing the commands
458 3. a sum type that is the common type of these expressions, and also the
459 input type of the arrow
460 4. a CoreExpr for an arrow built by combining the translated command
464 dsCmd ids local_vars env_ids stack res_ty (HsCase exp (MatchGroup matches match_ty)) = do
465 core_exp <- dsLExpr exp
466 stack_ids <- mapM newSysLocalDs stack
468 -- Extract and desugar the leaf commands in the case, building tuple
469 -- expressions that will (after tagging) replace these leaves
472 leaves = concatMap leavesMatch matches
473 make_branch (leaf, bound_vars) = do
474 (core_leaf, fvs, leaf_ids) <-
475 dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
476 return (fvs `minusVarSet` bound_vars,
477 [mkHsEnvStackExpr leaf_ids stack_ids],
478 envStackType leaf_ids stack,
481 branches <- mapM make_branch leaves
482 either_con <- dsLookupTyCon eitherTyConName
483 left_con <- dsLookupDataCon leftDataConName
484 right_con <- dsLookupDataCon rightDataConName
486 left_id = HsVar (dataConWrapId left_con)
487 right_id = HsVar (dataConWrapId right_con)
488 left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) left_id ) e
489 right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) right_id) e
491 -- Prefix each tuple with a distinct series of Left's and Right's,
492 -- in a balanced way, keeping track of the types.
494 merge_branches (fvs1, builds1, in_ty1, core_exp1)
495 (fvs2, builds2, in_ty2, core_exp2)
496 = (fvs1 `unionVarSet` fvs2,
497 map (left_expr in_ty1 in_ty2) builds1 ++
498 map (right_expr in_ty1 in_ty2) builds2,
499 mkTyConApp either_con [in_ty1, in_ty2],
500 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
501 (fvs_alts, leaves', sum_ty, core_choices)
502 = foldb merge_branches branches
504 -- Replace the commands in the case with these tagged tuples,
505 -- yielding a HsExpr Id we can feed to dsExpr.
507 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
508 in_ty = envStackType env_ids stack
509 fvs_exp = exprFreeVars core_exp `intersectVarSet` local_vars
511 pat_ty = funArgTy match_ty
512 match_ty' = mkFunTy pat_ty sum_ty
513 -- Note that we replace the HsCase result type by sum_ty,
514 -- which is the type of matches'
516 core_body <- dsExpr (HsCase exp (MatchGroup matches' match_ty'))
517 core_matches <- matchEnvStack env_ids stack_ids core_body
518 return (do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
519 fvs_exp `unionVarSet` fvs_alts)
521 -- A | ys |- c :: [ts] t
522 -- ----------------------------------
523 -- A | xs |- let binds in c :: [ts] t
525 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
527 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body) = do
529 defined_vars = mkVarSet (map unLoc (collectLocalBinders binds))
530 local_vars' = local_vars `unionVarSet` defined_vars
532 (core_body, _free_vars, env_ids') <- dsfixCmd ids local_vars' stack res_ty body
533 stack_ids <- mapM newSysLocalDs stack
534 -- build a new environment, plus the stack, using the let bindings
535 core_binds <- dsLocalBinds binds (buildEnvStack env_ids' stack_ids)
536 -- match the old environment and stack against the input
537 core_map <- matchEnvStack env_ids stack_ids core_binds
538 return (do_map_arrow ids
539 (envStackType env_ids stack)
540 (envStackType env_ids' stack)
544 exprFreeVars core_binds `intersectVarSet` local_vars)
546 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts body _)
547 = dsCmdDo ids local_vars env_ids res_ty stmts body
549 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
550 -- A | xs |- ci :: [tsi] ti
551 -- -----------------------------------
552 -- A | xs |- (|e c1 ... cn|) :: [ts] t ---> e [t_xs] c1 ... cn
554 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args) = do
555 let env_ty = mkBigCoreVarTupTy env_ids
556 core_op <- dsLExpr op
557 (core_args, fv_sets) <- mapAndUnzipM (dsTrimCmdArg local_vars env_ids) args
558 return (mkApps (App core_op (Type env_ty)) core_args,
559 unionVarSets fv_sets)
562 dsCmd ids local_vars env_ids stack res_ty (HsTick ix vars expr) = do
563 (expr1,id_set) <- dsLCmd ids local_vars env_ids stack res_ty expr
564 expr2 <- mkTickBox ix vars expr1
565 return (expr2,id_set)
567 dsCmd _ _ _ _ _ c = pprPanic "dsCmd" (ppr c)
569 -- A | ys |- c :: [ts] t (ys <= xs)
570 -- ---------------------
571 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
574 :: IdSet -- set of local vars available to this command
575 -> [Id] -- list of vars in the input to this command
576 -> LHsCmdTop Id -- command argument to desugar
577 -> DsM (CoreExpr, -- desugared expression
578 IdSet) -- set of local vars that occur free
579 dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack cmd_ty ids)) = do
580 meth_ids <- mkCmdEnv ids
581 (core_cmd, free_vars, env_ids') <- dsfixCmd meth_ids local_vars stack cmd_ty cmd
582 stack_ids <- mapM newSysLocalDs stack
583 trim_code <- matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
585 in_ty = envStackType env_ids stack
586 in_ty' = envStackType env_ids' stack
587 arg_code = if env_ids' == env_ids then core_cmd else
588 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
589 return (bindCmdEnv meth_ids arg_code, free_vars)
591 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
592 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
595 :: DsCmdEnv -- arrow combinators
596 -> IdSet -- set of local vars available to this command
597 -> [Type] -- type of the stack
598 -> Type -- return type of the command
599 -> LHsCmd Id -- command to desugar
600 -> DsM (CoreExpr, -- desugared expression
601 IdSet, -- set of local vars that occur free
602 [Id]) -- set as a list, fed back
603 dsfixCmd ids local_vars stack cmd_ty cmd
604 = fixDs (\ ~(_,_,env_ids') -> do
605 (core_cmd, free_vars) <- dsLCmd ids local_vars env_ids' stack cmd_ty cmd
606 return (core_cmd, free_vars, varSetElems free_vars))
610 Translation of command judgements of the form
612 A | xs |- do { ss } :: [] t
616 dsCmdDo :: DsCmdEnv -- arrow combinators
617 -> IdSet -- set of local vars available to this statement
618 -> [Id] -- list of vars in the input to this statement
619 -- This is typically fed back,
620 -- so don't pull on it too early
621 -> Type -- return type of the statement
622 -> [LStmt Id] -- statements to desugar
623 -> LHsExpr Id -- body
624 -> DsM (CoreExpr, -- desugared expression
625 IdSet) -- set of local vars that occur free
627 -- A | xs |- c :: [] t
628 -- --------------------------
629 -- A | xs |- do { c } :: [] t
631 dsCmdDo ids local_vars env_ids res_ty [] body
632 = dsLCmd ids local_vars env_ids [] res_ty body
634 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts) body = do
636 bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
637 local_vars' = local_vars `unionVarSet` bound_vars
638 (core_stmts, _, env_ids') <- fixDs (\ ~(_,_,env_ids') -> do
639 (core_stmts, fv_stmts) <- dsCmdDo ids local_vars' env_ids' res_ty stmts body
640 return (core_stmts, fv_stmts, varSetElems fv_stmts))
641 (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids env_ids' stmt
642 return (do_compose ids
643 (mkBigCoreVarTupTy env_ids)
644 (mkBigCoreVarTupTy env_ids')
651 A statement maps one local environment to another, and is represented
652 as an arrow from one tuple type to another. A statement sequence is
653 translated to a composition of such arrows.
655 dsCmdLStmt :: DsCmdEnv -> IdSet -> [Id] -> [Id] -> LStmt Id
656 -> DsM (CoreExpr, IdSet)
657 dsCmdLStmt ids local_vars env_ids out_ids cmd
658 = dsCmdStmt ids local_vars env_ids out_ids (unLoc cmd)
661 :: DsCmdEnv -- arrow combinators
662 -> IdSet -- set of local vars available to this statement
663 -> [Id] -- list of vars in the input to this statement
664 -- This is typically fed back,
665 -- so don't pull on it too early
666 -> [Id] -- list of vars in the output of this statement
667 -> Stmt Id -- statement to desugar
668 -> DsM (CoreExpr, -- desugared expression
669 IdSet) -- set of local vars that occur free
671 -- A | xs1 |- c :: [] t
672 -- A | xs' |- do { ss } :: [] t'
673 -- ------------------------------
674 -- A | xs |- do { c; ss } :: [] t'
676 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
679 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd _ c_ty) = do
680 (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars [] c_ty cmd
681 core_mux <- matchEnvStack env_ids []
682 (mkCorePairExpr (mkBigCoreVarTup env_ids1) (mkBigCoreVarTup out_ids))
684 in_ty = mkBigCoreVarTupTy env_ids
685 in_ty1 = mkBigCoreVarTupTy env_ids1
686 out_ty = mkBigCoreVarTupTy out_ids
687 before_c_ty = mkCorePairTy in_ty1 out_ty
688 after_c_ty = mkCorePairTy c_ty out_ty
689 snd_fn <- mkSndExpr c_ty out_ty
690 return (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
691 do_compose ids before_c_ty after_c_ty out_ty
692 (do_first ids in_ty1 c_ty out_ty core_cmd) $
693 do_arr ids after_c_ty out_ty snd_fn,
694 extendVarSetList fv_cmd out_ids)
697 -- A | xs1 |- c :: [] t
698 -- A | xs' |- do { ss } :: [] t' xs2 = xs' - defs(p)
699 -- -----------------------------------
700 -- A | xs |- do { p <- c; ss } :: [] t'
702 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
703 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
705 -- It would be simpler and more consistent to do this using second,
706 -- but that's likely to be defined in terms of first.
708 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _ _) = do
709 (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars [] (hsLPatType pat) cmd
711 pat_ty = hsLPatType pat
712 pat_vars = mkVarSet (collectPatBinders pat)
713 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
714 env_ty2 = mkBigCoreVarTupTy env_ids2
716 -- multiplexing function
717 -- \ (xs) -> ((xs1),(xs2))
719 core_mux <- matchEnvStack env_ids []
720 (mkCorePairExpr (mkBigCoreVarTup env_ids1) (mkBigCoreVarTup env_ids2))
722 -- projection function
723 -- \ (p, (xs2)) -> (zs)
725 env_id <- newSysLocalDs env_ty2
726 uniqs <- newUniqueSupply
728 after_c_ty = mkCorePairTy pat_ty env_ty2
729 out_ty = mkBigCoreVarTupTy out_ids
730 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkBigCoreVarTup out_ids)
732 fail_expr <- mkFailExpr (StmtCtxt DoExpr) out_ty
733 pat_id <- selectSimpleMatchVarL pat
734 match_code <- matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
735 pair_id <- newSysLocalDs after_c_ty
737 proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
739 -- put it all together
741 in_ty = mkBigCoreVarTupTy env_ids
742 in_ty1 = mkBigCoreVarTupTy env_ids1
743 in_ty2 = mkBigCoreVarTupTy env_ids2
744 before_c_ty = mkCorePairTy in_ty1 in_ty2
745 return (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
746 do_compose ids before_c_ty after_c_ty out_ty
747 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
748 do_arr ids after_c_ty out_ty proj_expr,
749 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
751 -- A | xs' |- do { ss } :: [] t
752 -- --------------------------------------
753 -- A | xs |- do { let binds; ss } :: [] t
755 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
757 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds) = do
758 -- build a new environment using the let bindings
759 core_binds <- dsLocalBinds binds (mkBigCoreVarTup out_ids)
760 -- match the old environment against the input
761 core_map <- matchEnvStack env_ids [] core_binds
763 (mkBigCoreVarTupTy env_ids)
764 (mkBigCoreVarTupTy out_ids)
766 exprFreeVars core_binds `intersectVarSet` local_vars)
768 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
769 -- A | xs' |- do { ss' } :: [] t
770 -- ------------------------------------
771 -- A | xs |- do { rec ss; ss' } :: [] t
773 -- xs1 = xs' /\ defs(ss)
774 -- xs2 = xs' - defs(ss)
775 -- ys1 = ys - defs(ss)
776 -- ys2 = ys /\ defs(ss)
778 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
779 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
780 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
782 dsCmdStmt ids local_vars env_ids out_ids
783 (RecStmt { recS_stmts = stmts, recS_later_ids = later_ids, recS_rec_ids = rec_ids
784 , recS_rec_rets = rhss, recS_dicts = _binds }) = do
785 let -- ToDo: ****** binds not desugared; ROSS PLEASE FIX ********
786 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
787 env2_ids = varSetElems env2_id_set
788 env2_ty = mkBigCoreVarTupTy env2_ids
790 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
792 uniqs <- newUniqueSupply
793 env2_id <- newSysLocalDs env2_ty
795 later_ty = mkBigCoreVarTupTy later_ids
796 post_pair_ty = mkCorePairTy later_ty env2_ty
797 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkBigCoreVarTup out_ids)
799 post_loop_fn <- matchEnvStack later_ids [env2_id] post_loop_body
803 (core_loop, env1_id_set, env1_ids)
804 <- dsRecCmd ids local_vars stmts later_ids rec_ids rhss
806 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
809 env1_ty = mkBigCoreVarTupTy env1_ids
810 pre_pair_ty = mkCorePairTy env1_ty env2_ty
811 pre_loop_body = mkCorePairExpr (mkBigCoreVarTup env1_ids)
812 (mkBigCoreVarTup env2_ids)
814 pre_loop_fn <- matchEnvStack env_ids [] pre_loop_body
816 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
819 env_ty = mkBigCoreVarTupTy env_ids
820 out_ty = mkBigCoreVarTupTy out_ids
821 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
823 (do_compose ids pre_pair_ty post_pair_ty out_ty
824 (do_first ids env1_ty later_ty env2_ty
826 (do_arr ids post_pair_ty out_ty
829 return (core_body, env1_id_set `unionVarSet` env2_id_set)
831 dsCmdStmt _ _ _ _ s = pprPanic "dsCmdStmt" (ppr s)
833 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
835 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
837 dsRecCmd :: DsCmdEnv -> VarSet -> [LStmt Id] -> [Var] -> [Var] -> [HsExpr Id]
838 -> DsM (CoreExpr, VarSet, [Var])
839 dsRecCmd ids local_vars stmts later_ids rec_ids rhss = do
841 rec_id_set = mkVarSet rec_ids
842 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
843 out_ty = mkBigCoreVarTupTy out_ids
844 local_vars' = local_vars `unionVarSet` rec_id_set
846 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
848 core_rhss <- mapM dsExpr rhss
850 later_tuple = mkBigCoreVarTup later_ids
851 later_ty = mkBigCoreVarTupTy later_ids
852 rec_tuple = mkBigCoreTup core_rhss
853 rec_ty = mkBigCoreVarTupTy rec_ids
854 out_pair = mkCorePairExpr later_tuple rec_tuple
855 out_pair_ty = mkCorePairTy later_ty rec_ty
857 mk_pair_fn <- matchEnvStack out_ids [] out_pair
861 (core_stmts, fv_stmts, env_ids) <- dsfixCmdStmts ids local_vars' out_ids stmts
863 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
865 rec_id <- newSysLocalDs rec_ty
867 env1_id_set = fv_stmts `minusVarSet` rec_id_set
868 env1_ids = varSetElems env1_id_set
869 env1_ty = mkBigCoreVarTupTy env1_ids
870 in_pair_ty = mkCorePairTy env1_ty rec_ty
871 core_body = mkBigCoreTup (map selectVar env_ids)
874 | v `elemVarSet` rec_id_set
875 = mkTupleSelector rec_ids v rec_id (Var rec_id)
878 squash_pair_fn <- matchEnvStack env1_ids [rec_id] core_body
880 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
883 env_ty = mkBigCoreVarTupTy env_ids
884 core_loop = do_loop ids env1_ty later_ty rec_ty
885 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
887 (do_compose ids env_ty out_ty out_pair_ty
889 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
891 return (core_loop, env1_id_set, env1_ids)
894 A sequence of statements (as in a rec) is desugared to an arrow between
899 :: DsCmdEnv -- arrow combinators
900 -> IdSet -- set of local vars available to this statement
901 -> [Id] -- output vars of these statements
902 -> [LStmt Id] -- statements to desugar
903 -> DsM (CoreExpr, -- desugared expression
904 IdSet, -- set of local vars that occur free
907 dsfixCmdStmts ids local_vars out_ids stmts
908 = fixDs (\ ~(_,_,env_ids) -> do
909 (core_stmts, fv_stmts) <- dsCmdStmts ids local_vars env_ids out_ids stmts
910 return (core_stmts, fv_stmts, varSetElems fv_stmts))
913 :: DsCmdEnv -- arrow combinators
914 -> IdSet -- set of local vars available to this statement
915 -> [Id] -- list of vars in the input to these statements
916 -> [Id] -- output vars of these statements
917 -> [LStmt Id] -- statements to desugar
918 -> DsM (CoreExpr, -- desugared expression
919 IdSet) -- set of local vars that occur free
921 dsCmdStmts ids local_vars env_ids out_ids [stmt]
922 = dsCmdLStmt ids local_vars env_ids out_ids stmt
924 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts) = do
926 bound_vars = mkVarSet (map unLoc (collectLStmtBinders stmt))
927 local_vars' = local_vars `unionVarSet` bound_vars
928 (core_stmts, _fv_stmts, env_ids') <- dsfixCmdStmts ids local_vars' out_ids stmts
929 (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids env_ids' stmt
930 return (do_compose ids
931 (mkBigCoreVarTupTy env_ids)
932 (mkBigCoreVarTupTy env_ids')
933 (mkBigCoreVarTupTy out_ids)
938 dsCmdStmts _ _ _ _ [] = panic "dsCmdStmts []"
942 Match a list of expressions against a list of patterns, left-to-right.
945 matchSimplys :: [CoreExpr] -- Scrutinees
946 -> HsMatchContext Name -- Match kind
947 -> [LPat Id] -- Patterns they should match
948 -> CoreExpr -- Return this if they all match
949 -> CoreExpr -- Return this if they don't
951 matchSimplys [] _ctxt [] result_expr _fail_expr = return result_expr
952 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr = do
953 match_code <- matchSimplys exps ctxt pats result_expr fail_expr
954 matchSimply exp ctxt pat match_code fail_expr
955 matchSimplys _ _ _ _ _ = panic "matchSimplys"
958 List of leaf expressions, with set of variables bound in each
961 leavesMatch :: LMatch Id -> [(LHsExpr Id, IdSet)]
962 leavesMatch (L _ (Match pats _ (GRHSs grhss binds)))
964 defined_vars = mkVarSet (collectPatsBinders pats)
966 mkVarSet (map unLoc (collectLocalBinders binds))
969 mkVarSet (map unLoc (collectLStmtsBinders stmts))
970 `unionVarSet` defined_vars)
971 | L _ (GRHS stmts expr) <- grhss]
974 Replace the leaf commands in a match
978 :: Type -- new result type
979 -> [LHsExpr Id] -- replacement leaf expressions of that type
980 -> LMatch Id -- the matches of a case command
981 -> ([LHsExpr Id],-- remaining leaf expressions
982 LMatch Id) -- updated match
983 replaceLeavesMatch _res_ty leaves (L loc (Match pat mt (GRHSs grhss binds)))
985 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
987 (leaves', L loc (Match pat mt (GRHSs grhss' binds)))
990 :: [LHsExpr Id] -- replacement leaf expressions of that type
991 -> LGRHS Id -- rhss of a case command
992 -> ([LHsExpr Id],-- remaining leaf expressions
993 LGRHS Id) -- updated GRHS
994 replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts _))
995 = (leaves, L loc (GRHS stmts leaf))
996 replaceLeavesGRHS [] _ = panic "replaceLeavesGRHS []"
999 Balanced fold of a non-empty list.
1002 foldb :: (a -> a -> a) -> [a] -> a
1003 foldb _ [] = error "foldb of empty list"
1005 foldb f xs = foldb f (fold_pairs xs)
1008 fold_pairs [x] = [x]
1009 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs
1012 The following functions to collect value variables from patterns are
1013 copied from HsUtils, with one change: we also collect the dictionary
1014 bindings (pat_binds) from ConPatOut. We need them for cases like
1016 h :: Arrow a => Int -> a (Int,Int) Int
1017 h x = proc (y,z) -> case compare x y of
1018 GT -> returnA -< z+x
1020 The type checker turns the case into
1023 GT { p77 = plusInt } -> returnA -< p77 z x
1025 Here p77 is a local binding for the (+) operation.
1027 See comments in HsUtils for why the other version does not include
1031 collectPatBinders :: OutputableBndr a => LPat a -> [a]
1032 collectPatBinders pat = map unLoc (collectLocatedPatBinders pat)
1034 collectLocatedPatBinders :: OutputableBndr a => LPat a -> [Located a]
1035 collectLocatedPatBinders pat = collectl pat []
1037 collectPatsBinders :: OutputableBndr a => [LPat a] -> [a]
1038 collectPatsBinders pats = map unLoc (collectLocatedPatsBinders pats)
1040 collectLocatedPatsBinders :: OutputableBndr a => [LPat a] -> [Located a]
1041 collectLocatedPatsBinders pats = foldr collectl [] pats
1043 ---------------------
1044 collectl :: OutputableBndr a => LPat a -> [Located a] -> [Located a]
1045 collectl (L l pat) bndrs
1048 go (VarPat var) = L l var : bndrs
1049 go (VarPatOut var bs) = L l var : collectHsBindLocatedBinders bs
1051 go (WildPat _) = bndrs
1052 go (LazyPat pat) = collectl pat bndrs
1053 go (BangPat pat) = collectl pat bndrs
1054 go (AsPat a pat) = a : collectl pat bndrs
1055 go (ParPat pat) = collectl pat bndrs
1057 go (ListPat pats _) = foldr collectl bndrs pats
1058 go (PArrPat pats _) = foldr collectl bndrs pats
1059 go (TuplePat pats _ _) = foldr collectl bndrs pats
1061 go (ConPatIn _ ps) = foldr collectl bndrs (hsConPatArgs ps)
1062 go (ConPatOut {pat_args=ps, pat_binds=ds}) =
1063 collectHsBindLocatedBinders ds
1064 ++ foldr collectl bndrs (hsConPatArgs ps)
1065 go (LitPat _) = bndrs
1066 go (NPat _ _ _) = bndrs
1067 go (NPlusKPat n _ _ _) = n : bndrs
1069 go (SigPatIn pat _) = collectl pat bndrs
1070 go (SigPatOut pat _) = collectl pat bndrs
1071 go (TypePat _) = bndrs
1072 go (CoPat _ pat _) = collectl (noLoc pat) bndrs
1073 go p = pprPanic "collectl/go" (ppr p)