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, collectPatsBinders )
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 (meth_binds, ds_meths) <- dsSyntaxTable ids
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
115 mkSndExpr a_ty b_ty = do
116 a_var <- newSysLocalDs a_ty
117 b_var <- newSysLocalDs b_ty
118 pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty)
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 = mkBoxedTupleTy [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 environment 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 (mkBigCoreVarTupTy ids) stack_tys
162 ----------------------------------------------
165 -- (...((x1,...,xn),s1),...sk)
167 buildEnvStack :: [Id] -> [Id] -> CoreExpr
168 buildEnvStack env_ids stack_ids
169 = foldl mkCorePairExpr (mkBigCoreVarTup 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 = do
188 uniqs <- newUniqueSupply
189 tup_var <- newSysLocalDs (mkBigCoreVarTupTy env_ids)
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 = return (Lam env_id body)
211 matchVarStack env_id (stack_id:stack_ids) body = do
212 pair_id <- newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
213 matchVarStack pair_id stack_ids
214 (coreCasePair pair_id env_id stack_id body)
218 mkHsEnvStackExpr :: [Id] -> [Id] -> LHsExpr Id
219 mkHsEnvStackExpr env_ids stack_ids
220 = foldl (\a b -> mkLHsTupleExpr [a,b])
221 (mkLHsVarTuple env_ids)
222 (map nlHsVar stack_ids)
225 Translation of arrow abstraction
229 -- A | xs |- c :: [] t' ---> c'
230 -- --------------------------
231 -- A |- proc p -> c :: a t t' ---> arr (\ p -> (xs)) >>> c'
233 -- where (xs) is the tuple of variables bound by p
239 dsProcExpr pat (L _ (HsCmdTop cmd [] cmd_ty ids)) = do
240 meth_ids <- mkCmdEnv ids
241 let locals = mkVarSet (collectPatBinders pat)
242 (core_cmd, _free_vars, env_ids) <- dsfixCmd meth_ids locals [] cmd_ty cmd
243 let env_ty = mkBigCoreVarTupTy env_ids
244 fail_expr <- mkFailExpr ProcExpr env_ty
245 var <- selectSimpleMatchVarL pat
246 match_code <- matchSimply (Var var) ProcExpr pat (mkBigCoreVarTup env_ids) fail_expr
247 let pat_ty = hsLPatType pat
248 proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
251 return (bindCmdEnv meth_ids proc_code)
252 dsProcExpr _ c = pprPanic "dsProcExpr" (ppr c)
255 Translation of command judgements of the form
257 A | xs |- c :: [ts] t
260 dsLCmd :: DsCmdEnv -> IdSet -> [Id] -> [Type] -> Type -> LHsCmd Id
261 -> DsM (CoreExpr, IdSet)
262 dsLCmd ids local_vars env_ids stack res_ty cmd
263 = dsCmd ids local_vars env_ids stack res_ty (unLoc cmd)
265 dsCmd :: DsCmdEnv -- arrow combinators
266 -> IdSet -- set of local vars available to this command
267 -> [Id] -- list of vars in the input to this command
268 -- This is typically fed back,
269 -- so don't pull on it too early
270 -> [Type] -- type of the stack
271 -> Type -- return type of the command
272 -> HsCmd Id -- command to desugar
273 -> DsM (CoreExpr, -- desugared expression
274 IdSet) -- set of local vars that occur free
276 -- A |- f :: a (t*ts) t'
278 -- -----------------------------
279 -- A | xs |- f -< arg :: [ts] t'
281 -- ---> arr (\ ((xs)*ts) -> (arg*ts)) >>> f
283 dsCmd ids local_vars env_ids stack res_ty
284 (HsArrApp arrow arg arrow_ty HsFirstOrderApp _)= do
286 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
287 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
288 core_arrow <- dsLExpr arrow
289 core_arg <- dsLExpr arg
290 stack_ids <- mapM newSysLocalDs stack
291 core_make_arg <- matchEnvStack env_ids stack_ids
292 (foldl mkCorePairExpr core_arg (map Var stack_ids))
293 return (do_map_arrow ids
294 (envStackType env_ids stack)
299 exprFreeVars core_arg `intersectVarSet` local_vars)
301 -- A, xs |- f :: a (t*ts) t'
303 -- ------------------------------
304 -- A | xs |- f -<< arg :: [ts] t'
306 -- ---> arr (\ ((xs)*ts) -> (f,(arg*ts))) >>> app
308 dsCmd ids local_vars env_ids stack res_ty
309 (HsArrApp arrow arg arrow_ty HsHigherOrderApp _) = do
311 (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
312 (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
314 core_arrow <- dsLExpr arrow
315 core_arg <- dsLExpr arg
316 stack_ids <- mapM newSysLocalDs stack
317 core_make_pair <- matchEnvStack env_ids stack_ids
318 (mkCorePairExpr core_arrow
319 (foldl mkCorePairExpr core_arg (map Var stack_ids)))
321 return (do_map_arrow ids
322 (envStackType env_ids stack)
323 (mkCorePairTy arrow_ty arg_ty)
326 (do_app ids arg_ty res_ty),
327 (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
328 `intersectVarSet` local_vars)
330 -- A | ys |- c :: [t:ts] t'
332 -- ------------------------
333 -- A | xs |- c e :: [ts] t'
335 -- ---> arr (\ ((xs)*ts) -> let z = e in (((ys),z)*ts)) >>> c
337 dsCmd ids local_vars env_ids stack res_ty (HsApp cmd arg) = do
338 core_arg <- dsLExpr arg
340 arg_ty = exprType core_arg
341 stack' = arg_ty:stack
342 (core_cmd, free_vars, env_ids')
343 <- dsfixCmd ids local_vars stack' res_ty cmd
344 stack_ids <- mapM newSysLocalDs stack
345 arg_id <- newSysLocalDs arg_ty
346 -- push the argument expression onto the stack
348 core_body = bindNonRec arg_id core_arg
349 (buildEnvStack env_ids' (arg_id:stack_ids))
350 -- match the environment and stack against the input
351 core_map <- matchEnvStack env_ids stack_ids core_body
352 return (do_map_arrow ids
353 (envStackType env_ids stack)
354 (envStackType env_ids' stack')
358 (exprFreeVars core_arg `intersectVarSet` local_vars)
359 `unionVarSet` free_vars)
361 -- A | ys |- c :: [ts] t'
362 -- -----------------------------------------------
363 -- A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
365 -- ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
367 dsCmd ids local_vars env_ids stack res_ty
368 (HsLam (MatchGroup [L _ (Match pats _ (GRHSs [L _ (GRHS [] body)] _ ))] _)) = do
370 pat_vars = mkVarSet (collectPatsBinders pats)
371 local_vars' = local_vars `unionVarSet` pat_vars
372 stack' = drop (length pats) stack
373 (core_body, free_vars, env_ids') <- dsfixCmd ids local_vars' stack' res_ty body
374 stack_ids <- mapM newSysLocalDs stack
376 -- the expression is built from the inside out, so the actions
377 -- are presented in reverse order
380 (actual_ids, stack_ids') = splitAt (length pats) stack_ids
381 -- build a new environment, plus what's left of the stack
382 core_expr = buildEnvStack env_ids' stack_ids'
383 in_ty = envStackType env_ids stack
384 in_ty' = envStackType env_ids' stack'
386 fail_expr <- mkFailExpr LambdaExpr in_ty'
387 -- match the patterns against the top of the old stack
388 match_code <- matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
389 -- match the old environment and stack against the input
390 select_code <- matchEnvStack env_ids stack_ids match_code
391 return (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
392 free_vars `minusVarSet` pat_vars)
394 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
395 = dsLCmd ids local_vars env_ids stack res_ty cmd
397 -- A, xs |- e :: Bool
398 -- A | xs1 |- c1 :: [ts] t
399 -- A | xs2 |- c2 :: [ts] t
400 -- ----------------------------------------
401 -- A | xs |- if e then c1 else c2 :: [ts] t
403 -- ---> arr (\ ((xs)*ts) ->
404 -- if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
407 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd) = do
408 core_cond <- dsLExpr cond
409 (core_then, fvs_then, then_ids) <- dsfixCmd ids local_vars stack res_ty then_cmd
410 (core_else, fvs_else, else_ids) <- dsfixCmd ids local_vars stack res_ty else_cmd
411 stack_ids <- mapM newSysLocalDs stack
412 either_con <- dsLookupTyCon eitherTyConName
413 left_con <- dsLookupDataCon leftDataConName
414 right_con <- dsLookupDataCon rightDataConName
416 left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
417 right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
419 in_ty = envStackType env_ids stack
420 then_ty = envStackType then_ids stack
421 else_ty = envStackType else_ids stack
422 sum_ty = mkTyConApp either_con [then_ty, else_ty]
423 fvs_cond = exprFreeVars core_cond `intersectVarSet` local_vars
425 core_if <- matchEnvStack env_ids stack_ids
426 (mkIfThenElse core_cond
427 (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
428 (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
429 return (do_map_arrow ids in_ty sum_ty res_ty
431 (do_choice ids then_ty else_ty res_ty core_then core_else),
432 fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
435 Case commands are treated in much the same way as if commands
436 (see above) except that there are more alternatives. For example
438 case e of { p1 -> c1; p2 -> c2; p3 -> c3 }
442 arr (\ ((xs)*ts) -> case e of
443 p1 -> (Left (Left (xs1)*ts))
444 p2 -> Left ((Right (xs2)*ts))
445 p3 -> Right ((xs3)*ts)) >>>
448 The idea is to extract the commands from the case, build a balanced tree
449 of choices, and replace the commands with expressions that build tagged
450 tuples, obtaining a case expression that can be desugared normally.
451 To build all this, we use triples describing segments of the list of
452 case bodies, containing the following fields:
453 * a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
454 into the case replacing the commands
455 * a sum type that is the common type of these expressions, and also the
456 input type of the arrow
457 * a CoreExpr for an arrow built by combining the translated command
461 dsCmd ids local_vars env_ids stack res_ty (HsCase exp (MatchGroup matches match_ty)) = do
462 stack_ids <- mapM newSysLocalDs stack
464 -- Extract and desugar the leaf commands in the case, building tuple
465 -- expressions that will (after tagging) replace these leaves
468 leaves = concatMap leavesMatch matches
469 make_branch (leaf, bound_vars) = do
470 (core_leaf, _fvs, leaf_ids) <-
471 dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
472 return ([mkHsEnvStackExpr leaf_ids stack_ids],
473 envStackType leaf_ids stack,
476 branches <- mapM make_branch leaves
477 either_con <- dsLookupTyCon eitherTyConName
478 left_con <- dsLookupDataCon leftDataConName
479 right_con <- dsLookupDataCon rightDataConName
481 left_id = HsVar (dataConWrapId left_con)
482 right_id = HsVar (dataConWrapId right_con)
483 left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) left_id ) e
484 right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) right_id) e
486 -- Prefix each tuple with a distinct series of Left's and Right's,
487 -- in a balanced way, keeping track of the types.
489 merge_branches (builds1, in_ty1, core_exp1)
490 (builds2, in_ty2, core_exp2)
491 = (map (left_expr in_ty1 in_ty2) builds1 ++
492 map (right_expr in_ty1 in_ty2) builds2,
493 mkTyConApp either_con [in_ty1, in_ty2],
494 do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
495 (leaves', sum_ty, core_choices) = foldb merge_branches branches
497 -- Replace the commands in the case with these tagged tuples,
498 -- yielding a HsExpr Id we can feed to dsExpr.
500 (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
501 in_ty = envStackType env_ids stack
503 pat_ty = funArgTy match_ty
504 match_ty' = mkFunTy pat_ty sum_ty
505 -- Note that we replace the HsCase result type by sum_ty,
506 -- which is the type of matches'
508 core_body <- dsExpr (HsCase exp (MatchGroup matches' match_ty'))
509 core_matches <- matchEnvStack env_ids stack_ids core_body
510 return (do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
511 exprFreeVars core_body `intersectVarSet` local_vars)
513 -- A | ys |- c :: [ts] t
514 -- ----------------------------------
515 -- A | xs |- let binds in c :: [ts] t
517 -- ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
519 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body) = do
521 defined_vars = mkVarSet (collectLocalBinders binds)
522 local_vars' = local_vars `unionVarSet` defined_vars
524 (core_body, _free_vars, env_ids') <- dsfixCmd ids local_vars' stack res_ty body
525 stack_ids <- mapM newSysLocalDs stack
526 -- build a new environment, plus the stack, using the let bindings
527 core_binds <- dsLocalBinds binds (buildEnvStack env_ids' stack_ids)
528 -- match the old environment and stack against the input
529 core_map <- matchEnvStack env_ids stack_ids core_binds
530 return (do_map_arrow ids
531 (envStackType env_ids stack)
532 (envStackType env_ids' stack)
536 exprFreeVars core_binds `intersectVarSet` local_vars)
538 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts body _)
539 = dsCmdDo ids local_vars env_ids res_ty stmts body
541 -- A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
542 -- A | xs |- ci :: [tsi] ti
543 -- -----------------------------------
544 -- A | xs |- (|e c1 ... cn|) :: [ts] t ---> e [t_xs] c1 ... cn
546 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args) = do
547 let env_ty = mkBigCoreVarTupTy env_ids
548 core_op <- dsLExpr op
549 (core_args, fv_sets) <- mapAndUnzipM (dsTrimCmdArg local_vars env_ids) args
550 return (mkApps (App core_op (Type env_ty)) core_args,
551 unionVarSets fv_sets)
554 dsCmd ids local_vars env_ids stack res_ty (HsTick ix vars expr) = do
555 (expr1,id_set) <- dsLCmd ids local_vars env_ids stack res_ty expr
556 expr2 <- mkTickBox ix vars expr1
557 return (expr2,id_set)
559 dsCmd _ _ _ _ _ c = pprPanic "dsCmd" (ppr c)
561 -- A | ys |- c :: [ts] t (ys <= xs)
562 -- ---------------------
563 -- A | xs |- c :: [ts] t ---> arr_ts (\ (xs) -> (ys)) >>> c
566 :: IdSet -- set of local vars available to this command
567 -> [Id] -- list of vars in the input to this command
568 -> LHsCmdTop Id -- command argument to desugar
569 -> DsM (CoreExpr, -- desugared expression
570 IdSet) -- set of local vars that occur free
571 dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack cmd_ty ids)) = do
572 meth_ids <- mkCmdEnv ids
573 (core_cmd, free_vars, env_ids') <- dsfixCmd meth_ids local_vars stack cmd_ty cmd
574 stack_ids <- mapM newSysLocalDs stack
575 trim_code <- matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
577 in_ty = envStackType env_ids stack
578 in_ty' = envStackType env_ids' stack
579 arg_code = if env_ids' == env_ids then core_cmd else
580 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
581 return (bindCmdEnv meth_ids arg_code, free_vars)
583 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
584 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
587 :: DsCmdEnv -- arrow combinators
588 -> IdSet -- set of local vars available to this command
589 -> [Type] -- type of the stack
590 -> Type -- return type of the command
591 -> LHsCmd Id -- command to desugar
592 -> DsM (CoreExpr, -- desugared expression
593 IdSet, -- set of local vars that occur free
594 [Id]) -- set as a list, fed back
595 dsfixCmd ids local_vars stack cmd_ty cmd
596 = fixDs (\ ~(_,_,env_ids') -> do
597 (core_cmd, free_vars) <- dsLCmd ids local_vars env_ids' stack cmd_ty cmd
598 return (core_cmd, free_vars, varSetElems free_vars))
602 Translation of command judgements of the form
604 A | xs |- do { ss } :: [] t
608 dsCmdDo :: DsCmdEnv -- arrow combinators
609 -> IdSet -- set of local vars available to this statement
610 -> [Id] -- list of vars in the input to this statement
611 -- This is typically fed back,
612 -- so don't pull on it too early
613 -> Type -- return type of the statement
614 -> [LStmt Id] -- statements to desugar
615 -> LHsExpr Id -- body
616 -> DsM (CoreExpr, -- desugared expression
617 IdSet) -- set of local vars that occur free
619 -- A | xs |- c :: [] t
620 -- --------------------------
621 -- A | xs |- do { c } :: [] t
623 dsCmdDo ids local_vars env_ids res_ty [] body
624 = dsLCmd ids local_vars env_ids [] res_ty body
626 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts) body = do
628 bound_vars = mkVarSet (collectLStmtBinders stmt)
629 local_vars' = local_vars `unionVarSet` bound_vars
630 (core_stmts, _, env_ids') <- fixDs (\ ~(_,_,env_ids') -> do
631 (core_stmts, fv_stmts) <- dsCmdDo ids local_vars' env_ids' res_ty stmts body
632 return (core_stmts, fv_stmts, varSetElems fv_stmts))
633 (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids env_ids' stmt
634 return (do_compose ids
635 (mkBigCoreVarTupTy env_ids)
636 (mkBigCoreVarTupTy env_ids')
643 A statement maps one local environment to another, and is represented
644 as an arrow from one tuple type to another. A statement sequence is
645 translated to a composition of such arrows.
647 dsCmdLStmt :: DsCmdEnv -> IdSet -> [Id] -> [Id] -> LStmt Id
648 -> DsM (CoreExpr, IdSet)
649 dsCmdLStmt ids local_vars env_ids out_ids cmd
650 = dsCmdStmt ids local_vars env_ids out_ids (unLoc cmd)
653 :: DsCmdEnv -- arrow combinators
654 -> IdSet -- set of local vars available to this statement
655 -> [Id] -- list of vars in the input to this statement
656 -- This is typically fed back,
657 -- so don't pull on it too early
658 -> [Id] -- list of vars in the output of this statement
659 -> Stmt Id -- statement to desugar
660 -> DsM (CoreExpr, -- desugared expression
661 IdSet) -- set of local vars that occur free
663 -- A | xs1 |- c :: [] t
664 -- A | xs' |- do { ss } :: [] t'
665 -- ------------------------------
666 -- A | xs |- do { c; ss } :: [] t'
668 -- ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
671 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd _ c_ty) = do
672 (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars [] c_ty cmd
673 core_mux <- matchEnvStack env_ids []
674 (mkCorePairExpr (mkBigCoreVarTup env_ids1) (mkBigCoreVarTup out_ids))
676 in_ty = mkBigCoreVarTupTy env_ids
677 in_ty1 = mkBigCoreVarTupTy env_ids1
678 out_ty = mkBigCoreVarTupTy out_ids
679 before_c_ty = mkCorePairTy in_ty1 out_ty
680 after_c_ty = mkCorePairTy c_ty out_ty
681 snd_fn <- mkSndExpr c_ty out_ty
682 return (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
683 do_compose ids before_c_ty after_c_ty out_ty
684 (do_first ids in_ty1 c_ty out_ty core_cmd) $
685 do_arr ids after_c_ty out_ty snd_fn,
686 extendVarSetList fv_cmd out_ids)
689 -- A | xs1 |- c :: [] t
690 -- A | xs' |- do { ss } :: [] t' xs2 = xs' - defs(p)
691 -- -----------------------------------
692 -- A | xs |- do { p <- c; ss } :: [] t'
694 -- ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
695 -- arr (\ (p, (xs2)) -> (xs')) >>> ss
697 -- It would be simpler and more consistent to do this using second,
698 -- but that's likely to be defined in terms of first.
700 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _ _) = do
701 (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars [] (hsLPatType pat) cmd
703 pat_ty = hsLPatType pat
704 pat_vars = mkVarSet (collectPatBinders pat)
705 env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
706 env_ty2 = mkBigCoreVarTupTy env_ids2
708 -- multiplexing function
709 -- \ (xs) -> ((xs1),(xs2))
711 core_mux <- matchEnvStack env_ids []
712 (mkCorePairExpr (mkBigCoreVarTup env_ids1) (mkBigCoreVarTup env_ids2))
714 -- projection function
715 -- \ (p, (xs2)) -> (zs)
717 env_id <- newSysLocalDs env_ty2
718 uniqs <- newUniqueSupply
720 after_c_ty = mkCorePairTy pat_ty env_ty2
721 out_ty = mkBigCoreVarTupTy out_ids
722 body_expr = coreCaseTuple uniqs env_id env_ids2 (mkBigCoreVarTup out_ids)
724 fail_expr <- mkFailExpr (StmtCtxt DoExpr) out_ty
725 pat_id <- selectSimpleMatchVarL pat
726 match_code <- matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
727 pair_id <- newSysLocalDs after_c_ty
729 proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
731 -- put it all together
733 in_ty = mkBigCoreVarTupTy env_ids
734 in_ty1 = mkBigCoreVarTupTy env_ids1
735 in_ty2 = mkBigCoreVarTupTy env_ids2
736 before_c_ty = mkCorePairTy in_ty1 in_ty2
737 return (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
738 do_compose ids before_c_ty after_c_ty out_ty
739 (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
740 do_arr ids after_c_ty out_ty proj_expr,
741 fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
743 -- A | xs' |- do { ss } :: [] t
744 -- --------------------------------------
745 -- A | xs |- do { let binds; ss } :: [] t
747 -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss
749 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds) = do
750 -- build a new environment using the let bindings
751 core_binds <- dsLocalBinds binds (mkBigCoreVarTup out_ids)
752 -- match the old environment against the input
753 core_map <- matchEnvStack env_ids [] core_binds
755 (mkBigCoreVarTupTy env_ids)
756 (mkBigCoreVarTupTy out_ids)
758 exprFreeVars core_binds `intersectVarSet` local_vars)
760 -- A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
761 -- A | xs' |- do { ss' } :: [] t
762 -- ------------------------------------
763 -- A | xs |- do { rec ss; ss' } :: [] t
765 -- xs1 = xs' /\ defs(ss)
766 -- xs2 = xs' - defs(ss)
767 -- ys1 = ys - defs(ss)
768 -- ys2 = ys /\ defs(ss)
770 -- ---> arr (\(xs) -> ((ys1),(xs2))) >>>
771 -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
772 -- arr (\((xs1),(xs2)) -> (xs')) >>> ss'
774 dsCmdStmt ids local_vars env_ids out_ids
775 (RecStmt { recS_stmts = stmts, recS_later_ids = later_ids, recS_rec_ids = rec_ids
776 , recS_rec_rets = rhss, recS_dicts = _binds }) = do
777 let -- ToDo: ****** binds not desugared; ROSS PLEASE FIX ********
778 env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
779 env2_ids = varSetElems env2_id_set
780 env2_ty = mkBigCoreVarTupTy env2_ids
782 -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
784 uniqs <- newUniqueSupply
785 env2_id <- newSysLocalDs env2_ty
787 later_ty = mkBigCoreVarTupTy later_ids
788 post_pair_ty = mkCorePairTy later_ty env2_ty
789 post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkBigCoreVarTup out_ids)
791 post_loop_fn <- matchEnvStack later_ids [env2_id] post_loop_body
795 (core_loop, env1_id_set, env1_ids)
796 <- dsRecCmd ids local_vars stmts later_ids rec_ids rhss
798 -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
801 env1_ty = mkBigCoreVarTupTy env1_ids
802 pre_pair_ty = mkCorePairTy env1_ty env2_ty
803 pre_loop_body = mkCorePairExpr (mkBigCoreVarTup env1_ids)
804 (mkBigCoreVarTup env2_ids)
806 pre_loop_fn <- matchEnvStack env_ids [] pre_loop_body
808 -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
811 env_ty = mkBigCoreVarTupTy env_ids
812 out_ty = mkBigCoreVarTupTy out_ids
813 core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
815 (do_compose ids pre_pair_ty post_pair_ty out_ty
816 (do_first ids env1_ty later_ty env2_ty
818 (do_arr ids post_pair_ty out_ty
821 return (core_body, env1_id_set `unionVarSet` env2_id_set)
823 dsCmdStmt _ _ _ _ s = pprPanic "dsCmdStmt" (ppr s)
825 -- loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
827 -- arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
829 dsRecCmd :: DsCmdEnv -> VarSet -> [LStmt Id] -> [Var] -> [Var] -> [HsExpr Id]
830 -> DsM (CoreExpr, VarSet, [Var])
831 dsRecCmd ids local_vars stmts later_ids rec_ids rhss = do
833 rec_id_set = mkVarSet rec_ids
834 out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
835 out_ty = mkBigCoreVarTupTy out_ids
836 local_vars' = local_vars `unionVarSet` rec_id_set
838 -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
840 core_rhss <- mapM dsExpr rhss
842 later_tuple = mkBigCoreVarTup later_ids
843 later_ty = mkBigCoreVarTupTy later_ids
844 rec_tuple = mkBigCoreTup core_rhss
845 rec_ty = mkBigCoreVarTupTy rec_ids
846 out_pair = mkCorePairExpr later_tuple rec_tuple
847 out_pair_ty = mkCorePairTy later_ty rec_ty
849 mk_pair_fn <- matchEnvStack out_ids [] out_pair
853 (core_stmts, fv_stmts, env_ids) <- dsfixCmdStmts ids local_vars' out_ids stmts
855 -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
857 rec_id <- newSysLocalDs rec_ty
859 env1_id_set = fv_stmts `minusVarSet` rec_id_set
860 env1_ids = varSetElems env1_id_set
861 env1_ty = mkBigCoreVarTupTy env1_ids
862 in_pair_ty = mkCorePairTy env1_ty rec_ty
863 core_body = mkBigCoreTup (map selectVar env_ids)
866 | v `elemVarSet` rec_id_set
867 = mkTupleSelector rec_ids v rec_id (Var rec_id)
870 squash_pair_fn <- matchEnvStack env1_ids [rec_id] core_body
872 -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
875 env_ty = mkBigCoreVarTupTy env_ids
876 core_loop = do_loop ids env1_ty later_ty rec_ty
877 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
879 (do_compose ids env_ty out_ty out_pair_ty
881 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
883 return (core_loop, env1_id_set, env1_ids)
886 A sequence of statements (as in a rec) is desugared to an arrow between
891 :: DsCmdEnv -- arrow combinators
892 -> IdSet -- set of local vars available to this statement
893 -> [Id] -- output vars of these statements
894 -> [LStmt Id] -- statements to desugar
895 -> DsM (CoreExpr, -- desugared expression
896 IdSet, -- set of local vars that occur free
899 dsfixCmdStmts ids local_vars out_ids stmts
900 = fixDs (\ ~(_,_,env_ids) -> do
901 (core_stmts, fv_stmts) <- dsCmdStmts ids local_vars env_ids out_ids stmts
902 return (core_stmts, fv_stmts, varSetElems fv_stmts))
905 :: DsCmdEnv -- arrow combinators
906 -> IdSet -- set of local vars available to this statement
907 -> [Id] -- list of vars in the input to these statements
908 -> [Id] -- output vars of these statements
909 -> [LStmt Id] -- statements to desugar
910 -> DsM (CoreExpr, -- desugared expression
911 IdSet) -- set of local vars that occur free
913 dsCmdStmts ids local_vars env_ids out_ids [stmt]
914 = dsCmdLStmt ids local_vars env_ids out_ids stmt
916 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts) = do
918 bound_vars = mkVarSet (collectLStmtBinders stmt)
919 local_vars' = local_vars `unionVarSet` bound_vars
920 (core_stmts, _fv_stmts, env_ids') <- dsfixCmdStmts ids local_vars' out_ids stmts
921 (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids env_ids' stmt
922 return (do_compose ids
923 (mkBigCoreVarTupTy env_ids)
924 (mkBigCoreVarTupTy env_ids')
925 (mkBigCoreVarTupTy out_ids)
930 dsCmdStmts _ _ _ _ [] = panic "dsCmdStmts []"
934 Match a list of expressions against a list of patterns, left-to-right.
937 matchSimplys :: [CoreExpr] -- Scrutinees
938 -> HsMatchContext Name -- Match kind
939 -> [LPat Id] -- Patterns they should match
940 -> CoreExpr -- Return this if they all match
941 -> CoreExpr -- Return this if they don't
943 matchSimplys [] _ctxt [] result_expr _fail_expr = return result_expr
944 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr = do
945 match_code <- matchSimplys exps ctxt pats result_expr fail_expr
946 matchSimply exp ctxt pat match_code fail_expr
947 matchSimplys _ _ _ _ _ = panic "matchSimplys"
950 List of leaf expressions, with set of variables bound in each
953 leavesMatch :: LMatch Id -> [(LHsExpr Id, IdSet)]
954 leavesMatch (L _ (Match pats _ (GRHSs grhss binds)))
956 defined_vars = mkVarSet (collectPatsBinders pats)
958 mkVarSet (collectLocalBinders binds)
961 mkVarSet (collectLStmtsBinders stmts)
962 `unionVarSet` defined_vars)
963 | L _ (GRHS stmts expr) <- grhss]
966 Replace the leaf commands in a match
970 :: Type -- new result type
971 -> [LHsExpr Id] -- replacement leaf expressions of that type
972 -> LMatch Id -- the matches of a case command
973 -> ([LHsExpr Id],-- remaining leaf expressions
974 LMatch Id) -- updated match
975 replaceLeavesMatch _res_ty leaves (L loc (Match pat mt (GRHSs grhss binds)))
977 (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
979 (leaves', L loc (Match pat mt (GRHSs grhss' binds)))
982 :: [LHsExpr Id] -- replacement leaf expressions of that type
983 -> LGRHS Id -- rhss of a case command
984 -> ([LHsExpr Id],-- remaining leaf expressions
985 LGRHS Id) -- updated GRHS
986 replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts _))
987 = (leaves, L loc (GRHS stmts leaf))
988 replaceLeavesGRHS [] _ = panic "replaceLeavesGRHS []"
991 Balanced fold of a non-empty list.
994 foldb :: (a -> a -> a) -> [a] -> a
995 foldb _ [] = error "foldb of empty list"
997 foldb f xs = foldb f (fold_pairs xs)
1000 fold_pairs [x] = [x]
1001 fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs
1004 Note [Dictionary binders in ConPatOut] See also same Note in HsUtils
1005 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1006 The following functions to collect value variables from patterns are
1007 copied from HsUtils, with one change: we also collect the dictionary
1008 bindings (pat_binds) from ConPatOut. We need them for cases like
1010 h :: Arrow a => Int -> a (Int,Int) Int
1011 h x = proc (y,z) -> case compare x y of
1012 GT -> returnA -< z+x
1014 The type checker turns the case into
1017 GT { p77 = plusInt } -> returnA -< p77 z x
1019 Here p77 is a local binding for the (+) operation.
1021 See comments in HsUtils for why the other version does not include
1025 collectPatBinders :: LPat Id -> [Id]
1026 collectPatBinders pat = collectl pat []
1028 collectPatsBinders :: [LPat Id] -> [Id]
1029 collectPatsBinders pats = foldr collectl [] pats
1031 ---------------------
1032 collectl :: LPat Id -> [Id] -> [Id]
1033 -- See Note [Dictionary binders in ConPatOut]
1034 collectl (L _ pat) bndrs
1037 go (VarPat var) = var : bndrs
1038 go (VarPatOut var bs) = var : collectEvBinders bs
1040 go (WildPat _) = bndrs
1041 go (LazyPat pat) = collectl pat bndrs
1042 go (BangPat pat) = collectl pat bndrs
1043 go (AsPat (L _ a) pat) = a : collectl pat bndrs
1044 go (ParPat pat) = collectl pat bndrs
1046 go (ListPat pats _) = foldr collectl bndrs pats
1047 go (PArrPat pats _) = foldr collectl bndrs pats
1048 go (TuplePat pats _ _) = foldr collectl bndrs pats
1050 go (ConPatIn _ ps) = foldr collectl bndrs (hsConPatArgs ps)
1051 go (ConPatOut {pat_args=ps, pat_binds=ds}) =
1053 ++ foldr collectl bndrs (hsConPatArgs ps)
1054 go (LitPat _) = bndrs
1055 go (NPat _ _ _) = bndrs
1056 go (NPlusKPat (L _ n) _ _ _) = n : bndrs
1058 go (SigPatIn pat _) = collectl pat bndrs
1059 go (SigPatOut pat _) = collectl pat bndrs
1060 go (TypePat _) = bndrs
1061 go (CoPat _ pat _) = collectl (noLoc pat) bndrs
1062 go (ViewPat _ pat _) = collectl pat bndrs
1063 go p@(QuasiQuotePat {}) = pprPanic "collectl/go" (ppr p)
1065 collectEvBinders :: TcEvBinds -> [Id]
1066 collectEvBinders (EvBinds bs) = foldrBag add_ev_bndr [] bs
1067 collectEvBinders (TcEvBinds {}) = panic "ToDo: collectEvBinders"
1069 add_ev_bndr :: EvBind -> [Id] -> [Id]
1070 add_ev_bndr (EvBind b _) bs | isId b = b:bs
1072 -- A worry: what about coercion variable binders??