c25dfdae2e024c4172060170e2b80fd4062cbdda
[ghc-hetmet.git] / ghc / compiler / deSugar / DsArrows.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsArrows]{Desugaring arrow commands}
5
6 \begin{code}
7 module DsArrows ( dsProcExpr ) where
8
9 #include "HsVersions.h"
10
11 import Match            ( matchSimply )
12 import DsUtils          ( mkErrorAppDs,
13                           mkCoreTupTy, mkCoreTup, selectMatchVar,
14                           mkTupleCase, mkBigCoreTup, mkTupleType,
15                           mkTupleExpr, mkTupleSelector,
16                           dsReboundNames, lookupReboundName )
17 import DsMonad
18
19 import HsSyn            ( HsExpr(..), 
20                           Stmt(..), HsMatchContext(..), HsStmtContext(..), 
21                           Match(..), GRHSs(..), GRHS(..),
22                           HsCmdTop(..), HsArrAppType(..),
23                           ReboundNames,
24                           collectHsBinders,
25                           collectStmtBinders, collectStmtsBinders,
26                           matchContextErrString
27                         )
28 import TcHsSyn          ( TypecheckedHsCmd, TypecheckedHsCmdTop,
29                           TypecheckedHsExpr, TypecheckedPat,
30                           TypecheckedMatch, TypecheckedGRHS,
31                           TypecheckedStmt, hsPatType,
32                           TypecheckedMatchContext )
33
34 -- NB: The desugarer, which straddles the source and Core worlds, sometimes
35 --     needs to see source types (newtypes etc), and sometimes not
36 --     So WATCH OUT; check each use of split*Ty functions.
37 -- Sigh.  This is a pain.
38
39 import {-# SOURCE #-} DsExpr ( dsExpr, dsLet )
40
41 import TcType           ( Type, tcSplitAppTy )
42 import Type             ( mkTyConApp )
43 import CoreSyn
44 import CoreFVs          ( exprFreeVars )
45 import CoreUtils        ( mkIfThenElse, bindNonRec )
46
47 import Id               ( Id, idType )
48 import PrelInfo         ( pAT_ERROR_ID )
49 import DataCon          ( dataConWrapId )
50 import TysWiredIn       ( tupleCon )
51 import BasicTypes       ( Boxity(..) )
52 import PrelNames        ( eitherTyConName, leftDataConName, rightDataConName,
53                           arrAName, composeAName, firstAName,
54                           appAName, choiceAName, loopAName )
55 import Util             ( mapAccumL )
56 import Outputable
57
58 import HsPat            ( collectPatBinders, collectPatsBinders )
59 import VarSet           ( IdSet, mkVarSet, varSetElems,
60                           intersectVarSet, minusVarSet, 
61                           unionVarSet, unionVarSets, elemVarSet )
62 import SrcLoc           ( SrcLoc )
63 \end{code}
64
65 \begin{code}
66 data DsCmdEnv = DsCmdEnv {
67         meth_binds :: [CoreBind],
68         arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
69     }
70
71 mkCmdEnv :: ReboundNames Id -> DsM DsCmdEnv
72 mkCmdEnv ids
73   = dsReboundNames ids                  `thenDs` \ (meth_binds, ds_meths) ->
74     return $ DsCmdEnv {
75                 meth_binds = meth_binds,
76                 arr_id     = lookupReboundName ds_meths arrAName,
77                 compose_id = lookupReboundName ds_meths composeAName,
78                 first_id   = lookupReboundName ds_meths firstAName,
79                 app_id     = lookupReboundName ds_meths appAName,
80                 choice_id  = lookupReboundName ds_meths choiceAName,
81                 loop_id    = lookupReboundName ds_meths loopAName
82             }
83
84 bindCmdEnv :: DsCmdEnv -> CoreExpr -> CoreExpr
85 bindCmdEnv ids body = foldr Let body (meth_binds ids)
86
87 -- arr :: forall b c. (b -> c) -> a b c
88 do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
89 do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]
90
91 -- (>>>) :: forall b c d. a b c -> a c d -> a b d
92 do_compose :: DsCmdEnv -> Type -> Type -> Type ->
93                 CoreExpr -> CoreExpr -> CoreExpr
94 do_compose ids b_ty c_ty d_ty f g
95   = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]
96
97 -- first :: forall b c d. a b c -> a (b,d) (c,d)
98 do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
99 do_first ids b_ty c_ty d_ty f
100   = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]
101
102 -- app :: forall b c. a (a b c, b) c
103 do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
104 do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]
105
106 -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
107 -- note the swapping of d and c
108 do_choice :: DsCmdEnv -> Type -> Type -> Type ->
109                 CoreExpr -> CoreExpr -> CoreExpr
110 do_choice ids b_ty c_ty d_ty f g
111   = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]
112
113 -- loop :: forall b d c. a (b,d) (c,d) -> a b c
114 -- note the swapping of d and c
115 do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
116 do_loop ids b_ty c_ty d_ty f
117   = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]
118
119 -- map_arrow (f :: b -> c) (g :: a c d) = arr f >>> g :: a b d
120 do_map_arrow :: DsCmdEnv -> Type -> Type -> Type ->
121                 CoreExpr -> CoreExpr -> CoreExpr
122 do_map_arrow ids b_ty c_ty d_ty f c
123   = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) c
124
125 mkFailExpr :: TypecheckedMatchContext -> Type -> DsM CoreExpr
126 mkFailExpr ctxt ty
127   = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)
128
129 -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
130 mkSndExpr :: Type -> Type -> DsM CoreExpr
131 mkSndExpr a_ty b_ty
132   = newSysLocalDs a_ty                  `thenDs` \ a_var ->
133     newSysLocalDs b_ty                  `thenDs` \ b_var ->
134     newSysLocalDs (mkCorePairTy a_ty b_ty)      `thenDs` \ pair_var ->
135     returnDs (Lam pair_var
136                   (coreCasePair pair_var a_var b_var (Var b_var)))
137 \end{code}
138
139 Build case analysis of a tuple.  This cannot be done in the DsM monad,
140 because the list of variables is typically not yet defined.
141
142 \begin{code}
143 -- coreCaseTuple [u1..] v [x1..xn] body
144 --      = case v of v { (x1, .., xn) -> body }
145 -- But the matching may be nested if the tuple is very big
146
147 coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
148 coreCaseTuple uniqs scrut_var vars body
149   = mkTupleCase uniqs vars body scrut_var (Var scrut_var)
150
151 coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
152 coreCasePair scrut_var var1 var2 body
153   = Case (Var scrut_var) scrut_var
154          [(DataAlt (tupleCon Boxed 2), [var1, var2], body)]
155 \end{code}
156
157 \begin{code}
158 mkCorePairTy :: Type -> Type -> Type
159 mkCorePairTy t1 t2 = mkCoreTupTy [t1, t2]
160
161 mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
162 mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]
163 \end{code}
164
165 The input is divided into a local environment, which is a flat tuple
166 (unless it's too big), and a stack, each element of which is paired
167 with the stack in turn.  In general, the input has the form
168
169         (...((x1,...,xn),s1),...sk)
170
171 where xi are the environment values, and si the ones on the stack,
172 with s1 being the "top", the first one to be matched with a lambda.
173
174 \begin{code}
175 envStackType :: [Id] -> [Type] -> Type
176 envStackType ids stack_tys = foldl mkCorePairTy (mkTupleType ids) stack_tys
177
178 ----------------------------------------------
179 --              buildEnvStack
180 --
181 --      (...((x1,...,xn),s1),...sk)
182
183 buildEnvStack :: [Id] -> [Id] -> CoreExpr
184 buildEnvStack env_ids stack_ids
185   = foldl mkCorePairExpr (mkTupleExpr env_ids) (map Var stack_ids)
186
187 ----------------------------------------------
188 --              matchEnvStack
189 --
190 --      \ (...((x1,...,xn),s1),...sk) -> e
191 --      =>
192 --      \ zk ->
193 --      case zk of (zk-1,sk) ->
194 --      ...
195 --      case z1 of (z0,s1) ->
196 --      case z0 of (x1,...,xn) ->
197 --      e
198
199 matchEnvStack   :: [Id]         -- x1..xn
200                 -> [Id]         -- s1..sk
201                 -> CoreExpr     -- e
202                 -> DsM CoreExpr
203 matchEnvStack env_ids stack_ids body
204   = getUniqSupplyDs                     `thenDs` \ uniqs ->
205     newSysLocalDs (mkTupleType env_ids) `thenDs` \ tup_var ->
206     matchVarStack tup_var stack_ids 
207                   (coreCaseTuple uniqs tup_var env_ids body)
208
209
210 ----------------------------------------------
211 --              matchVarStack
212 --
213 --      \ (...(z0,s1),...sk) -> e
214 --      =>
215 --      \ zk ->
216 --      case zk of (zk-1,sk) ->
217 --      ...
218 --      case z1 of (z0,s1) ->
219 --      e
220
221 matchVarStack :: Id             -- z0
222               -> [Id]           -- s1..sk
223               -> CoreExpr       -- e
224               -> DsM CoreExpr
225 matchVarStack env_id [] body
226   = returnDs (Lam env_id body)
227 matchVarStack env_id (stack_id:stack_ids) body
228   = newSysLocalDs (mkCorePairTy (idType env_id) (idType stack_id))
229                                         `thenDs` \ pair_id ->
230     matchVarStack pair_id stack_ids 
231                   (coreCasePair pair_id env_id stack_id body)
232 \end{code}
233
234 \begin{code}
235 mkHsTupleExpr :: [TypecheckedHsExpr] -> TypecheckedHsExpr
236 mkHsTupleExpr [e] = e
237 mkHsTupleExpr es = ExplicitTuple es Unboxed
238
239 mkHsPairExpr :: TypecheckedHsExpr -> TypecheckedHsExpr -> TypecheckedHsExpr
240 mkHsPairExpr e1 e2 = mkHsTupleExpr [e1, e2]
241
242 mkHsEnvStackExpr :: [Id] -> [Id] -> TypecheckedHsExpr
243 mkHsEnvStackExpr env_ids stack_ids
244   = foldl mkHsPairExpr (mkHsTupleExpr (map HsVar env_ids)) (map HsVar stack_ids)
245 \end{code}
246
247 Translation of arrow abstraction
248
249 \begin{code}
250
251 --      A | xs |- c :: [] t'        ---> c'
252 --      --------------------------
253 --      A |- proc p -> c :: a t t'  ---> arr (\ p -> (xs)) >>> c'
254 --
255 --              where (xs) is the tuple of variables bound by p
256
257 dsProcExpr
258         :: TypecheckedPat
259         -> TypecheckedHsCmdTop
260         -> SrcLoc
261         -> DsM CoreExpr
262 dsProcExpr pat (HsCmdTop cmd [] cmd_ty ids) locn
263   = putSrcLocDs locn $
264     mkCmdEnv ids                        `thenDs` \ meth_ids ->
265     let
266         locals = mkVarSet (collectPatBinders pat)
267     in
268     dsfixCmd meth_ids locals [] cmd_ty cmd
269                                 `thenDs` \ (core_cmd, free_vars, env_ids) ->
270     let
271         env_ty = mkTupleType env_ids
272     in
273     mkFailExpr ProcExpr env_ty          `thenDs` \ fail_expr ->
274     selectMatchVar pat                  `thenDs` \ var ->
275     matchSimply (Var var) ProcExpr pat (mkTupleExpr env_ids) fail_expr
276                                         `thenDs` \ match_code ->
277     let
278         pat_ty = hsPatType pat
279         proc_code = do_map_arrow meth_ids pat_ty env_ty cmd_ty
280                 (Lam var match_code)
281                 core_cmd
282     in
283     returnDs (bindCmdEnv meth_ids proc_code)
284
285 \end{code}
286
287 Translation of command judgements of the form
288
289         A | xs |- c :: [ts] t
290
291 \begin{code}
292
293 dsCmd :: DsCmdEnv               -- arrow combinators
294         -> IdSet                -- set of local vars available to this command
295         -> [Id]                 -- list of vars in the input to this command
296                                 -- This is typically fed back,
297                                 -- so don't pull on it too early
298         -> [Type]               -- type of the stack
299         -> Type                 -- return type of the command
300         -> TypecheckedHsCmd     -- command to desugar
301         -> DsM (CoreExpr,       -- desugared expression
302                 IdSet)          -- set of local vars that occur free
303
304 --      A |- f :: a t t'
305 --      A, xs |- arg :: t
306 --      ---------------------------
307 --      A | xs |- f -< arg :: [] t'     ---> arr (\ (xs) -> arg) >>> f
308
309 dsCmd ids local_vars env_ids [] res_ty
310         (HsArrApp arrow arg arrow_ty HsFirstOrderApp _ _)
311   = let
312         (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
313         (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
314         env_ty = mkTupleType env_ids
315     in
316     dsExpr arrow                        `thenDs` \ core_arrow ->
317     dsExpr arg                          `thenDs` \ core_arg ->
318     matchEnvStack env_ids [] core_arg   `thenDs` \ core_make_arg ->
319     returnDs (do_map_arrow ids env_ty arg_ty res_ty
320                 core_make_arg
321                 core_arrow,
322               exprFreeVars core_arg `intersectVarSet` local_vars)
323
324 --      A, xs |- f :: a t t'
325 --      A, xs |- arg :: t
326 --      ---------------------------
327 --      A | xs |- f -<< arg :: [] t'    ---> arr (\ (xs) -> (f,arg)) >>> app
328
329 dsCmd ids local_vars env_ids [] res_ty
330         (HsArrApp arrow arg arrow_ty HsHigherOrderApp _ _)
331   = let
332         (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
333         (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
334         env_ty = mkTupleType env_ids
335     in
336     dsExpr arrow                        `thenDs` \ core_arrow ->
337     dsExpr arg                          `thenDs` \ core_arg ->
338     matchEnvStack env_ids [] (mkCorePairExpr core_arrow core_arg)
339                                         `thenDs` \ core_make_pair ->
340     returnDs (do_map_arrow ids env_ty (mkCorePairTy arrow_ty arg_ty) res_ty
341                 core_make_pair
342                 (do_app ids arg_ty res_ty),
343               (exprFreeVars core_arrow `unionVarSet` exprFreeVars core_arg)
344                 `intersectVarSet` local_vars)
345
346 --      A | ys |- c :: [ts] t'
347 --      -----------------------------------------------
348 --      A | xs |- \ p1 ... pk -> c :: [t1:...:tk:ts] t'
349 --
350 --              ---> arr (\ ((((xs), p1), ... pk)*ts) -> ((ys)*ts)) >>> c
351
352 dsCmd ids local_vars env_ids stack res_ty
353     (HsLam (Match pats _ (GRHSs [GRHS [ResultStmt body _] _loc] _ _cmd_ty)))
354   = let
355         pat_vars = mkVarSet (collectPatsBinders pats)
356         local_vars' = local_vars `unionVarSet` pat_vars
357         stack' = drop (length pats) stack
358     in
359     dsfixCmd ids local_vars' stack' res_ty body
360                                 `thenDs` \ (core_body, free_vars, env_ids') ->
361     mapDs newSysLocalDs stack   `thenDs` \ stack_ids ->
362
363     -- the expression is built from the inside out, so the actions
364     -- are presented in reverse order
365
366     let
367         (actual_ids, stack_ids') = splitAt (length pats) stack_ids
368         -- build a new environment, plus what's left of the stack
369         core_expr = buildEnvStack env_ids' stack_ids'
370         in_ty = envStackType env_ids stack
371         in_ty' = envStackType env_ids' stack'
372     in
373     mkFailExpr LambdaExpr in_ty'        `thenDs` \ fail_expr ->
374     -- match the patterns against the top of the old stack
375     matchSimplys (map Var actual_ids) LambdaExpr pats core_expr fail_expr
376                                         `thenDs` \ match_code ->
377     -- match the old environment and stack against the input
378     matchEnvStack env_ids stack_ids match_code
379                                         `thenDs` \ select_code ->
380     returnDs (do_map_arrow ids in_ty in_ty' res_ty select_code core_body,
381              free_vars `minusVarSet` pat_vars)
382
383 dsCmd ids local_vars env_ids stack res_ty (HsPar cmd)
384   = dsCmd ids local_vars env_ids stack res_ty cmd
385
386 dsCmd ids local_vars env_ids stack res_ty (HsCase exp matches src_loc)
387   = dsExpr exp                          `thenDs` \ core_exp ->
388     mapDs newSysLocalDs stack           `thenDs` \ stack_ids ->
389
390     -- Extract and desugar the leaf commands in the case, building tuple
391     -- expressions that will (after tagging) replace these leaves
392
393     let
394         leaves = concatMap leavesMatch matches
395         make_branch (leaf, bound_vars)
396           = dsfixCmd ids (local_vars `unionVarSet` bound_vars) stack res_ty leaf
397                                         `thenDs` \ (core_leaf, fvs, leaf_ids) ->
398             returnDs (fvs `minusVarSet` bound_vars,
399                       [mkHsEnvStackExpr leaf_ids stack_ids],
400                       envStackType leaf_ids stack,
401                       core_leaf)
402     in
403     mapDs make_branch leaves            `thenDs` \ branches ->
404     dsLookupTyCon eitherTyConName       `thenDs` \ either_con ->
405     dsLookupDataCon leftDataConName     `thenDs` \ left_con ->
406     dsLookupDataCon rightDataConName    `thenDs` \ right_con ->
407     let
408         left_id = HsVar (dataConWrapId left_con)
409         right_id = HsVar (dataConWrapId right_con)
410         left_expr ty1 ty2 e = HsApp (TyApp left_id [ty1, ty2]) e
411         right_expr ty1 ty2 e = HsApp (TyApp right_id [ty1, ty2]) e
412
413         -- Prefix each tuple with a distinct series of Left's and Right's,
414         -- in a balanced way, keeping track of the types.
415
416         merge_branches (fvs1, builds1, in_ty1, core_exp1)
417                        (fvs2, builds2, in_ty2, core_exp2) 
418           = (fvs1 `unionVarSet` fvs2,
419              map (left_expr in_ty1 in_ty2) builds1 ++
420                 map (right_expr in_ty1 in_ty2) builds2,
421              mkTyConApp either_con [in_ty1, in_ty2],
422              do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
423         (fvs, leaves', sum_ty, core_choices) = foldb merge_branches branches
424
425         -- Replace the commands in the case with these tagged tuples,
426         -- yielding a TypecheckedHsExpr we can feed to dsExpr.
427
428         (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
429         in_ty = envStackType env_ids stack
430     in
431     dsExpr (HsCase exp matches' src_loc) `thenDs` \ core_matches ->
432     returnDs(do_map_arrow ids in_ty sum_ty res_ty core_matches core_choices,
433         exprFreeVars core_exp `unionVarSet` fvs)
434
435 --      A, xs |- e :: Bool
436 --      A | xs1 |- c1 :: [ts] t
437 --      A | xs2 |- c2 :: [ts] t
438 --      ----------------------------------------
439 --      A | xs |- if e then c1 else c2 :: [ts] t
440 --
441 --              ---> arr (\ ((xs)*ts) ->
442 --                      if e then Left ((xs1)*ts) else Right ((xs2)*ts)) >>>
443 --                   c1 ||| c2
444
445 dsCmd ids local_vars env_ids stack res_ty (HsIf cond then_cmd else_cmd _loc)
446   = dsExpr cond                 `thenDs` \ core_cond ->
447     dsfixCmd ids local_vars stack res_ty then_cmd
448                                 `thenDs` \ (core_then, fvs_then, then_ids) ->
449     dsfixCmd ids local_vars stack res_ty else_cmd
450                                 `thenDs` \ (core_else, fvs_else, else_ids) ->
451     mapDs newSysLocalDs stack           `thenDs` \ stack_ids ->
452     dsLookupTyCon eitherTyConName       `thenDs` \ either_con ->
453     dsLookupDataCon leftDataConName     `thenDs` \ left_con ->
454     dsLookupDataCon rightDataConName    `thenDs` \ right_con ->
455     let
456         left_expr ty1 ty2 e = mkConApp left_con [Type ty1, Type ty2, e]
457         right_expr ty1 ty2 e = mkConApp right_con [Type ty1, Type ty2, e]
458
459         in_ty = envStackType env_ids stack
460         then_ty = envStackType then_ids stack
461         else_ty = envStackType else_ids stack
462         sum_ty = mkTyConApp either_con [then_ty, else_ty]
463     in
464     matchEnvStack env_ids stack_ids
465         (mkIfThenElse core_cond
466             (left_expr then_ty else_ty (buildEnvStack then_ids stack_ids))
467             (right_expr then_ty else_ty (buildEnvStack else_ids stack_ids)))
468                                         `thenDs` \ core_if ->
469     returnDs(do_map_arrow ids in_ty sum_ty res_ty
470                 core_if
471                 (do_choice ids then_ty else_ty res_ty core_then core_else),
472         exprFreeVars core_cond `unionVarSet` fvs_then `unionVarSet` fvs_else)
473
474 --      A | ys |- c :: [ts] t
475 --      ----------------------------------
476 --      A | xs |- let binds in c :: [ts] t
477 --
478 --              ---> arr (\ ((xs)*ts) -> let binds in ((ys)*ts)) >>> c
479
480 dsCmd ids local_vars env_ids stack res_ty (HsLet binds body)
481   = let
482         defined_vars = mkVarSet (collectHsBinders binds)
483         local_vars' = local_vars `unionVarSet` defined_vars
484     in
485     dsfixCmd ids local_vars' stack res_ty body
486                                 `thenDs` \ (core_body, free_vars, env_ids') ->
487     mapDs newSysLocalDs stack           `thenDs` \ stack_ids ->
488     -- build a new environment, plus the stack, using the let bindings
489     dsLet binds (buildEnvStack env_ids' stack_ids)
490                                         `thenDs` \ core_binds ->
491     -- match the old environment and stack against the input
492     matchEnvStack env_ids stack_ids core_binds
493                                         `thenDs` \ core_map ->
494     returnDs (do_map_arrow ids
495                         (envStackType env_ids stack)
496                         (envStackType env_ids' stack)
497                         res_ty
498                         core_map
499                         core_body,
500         exprFreeVars core_binds `intersectVarSet` local_vars)
501
502 dsCmd ids local_vars env_ids [] res_ty (HsDo _ctxt stmts _ _ _loc)
503   = dsCmdDo ids local_vars env_ids res_ty stmts
504
505 --      A |- e :: forall e. a1 (e*ts1) t1 -> ... an (e*tsn) tn -> a (e*ts) t
506 --      A | xs |- ci :: [tsi] ti
507 --      -----------------------------------
508 --      A | xs |- (|e|) c1 ... cn :: [ts] t     ---> e [t_xs] c1 ... cn
509
510 dsCmd _ids local_vars env_ids _stack _res_ty (HsArrForm op _ args _)
511   = let
512         env_ty = mkTupleType env_ids
513     in
514     dsExpr op                           `thenDs` \ core_op ->
515     mapAndUnzipDs (dsTrimCmdArg local_vars env_ids) args
516                                         `thenDs` \ (core_args, fv_sets) ->
517     returnDs (mkApps (App core_op (Type env_ty)) core_args,
518               unionVarSets fv_sets)
519
520 --      A | ys |- c :: [ts] t   (ys <= xs)
521 --      ---------------------
522 --      A | xs |- c :: [ts] t   ---> arr_ts (\ (xs) -> (ys)) >>> c
523
524 dsTrimCmdArg
525         :: IdSet                -- set of local vars available to this command
526         -> [Id]                 -- list of vars in the input to this command
527         -> TypecheckedHsCmdTop  -- command argument to desugar
528         -> DsM (CoreExpr,       -- desugared expression
529                 IdSet)          -- set of local vars that occur free
530 dsTrimCmdArg local_vars env_ids (HsCmdTop cmd stack cmd_ty ids)
531   = mkCmdEnv ids                        `thenDs` \ meth_ids ->
532     dsfixCmd meth_ids local_vars stack cmd_ty cmd
533                                 `thenDs` \ (core_cmd, free_vars, env_ids') ->
534     mapDs newSysLocalDs stack           `thenDs` \ stack_ids ->
535     matchEnvStack env_ids stack_ids (buildEnvStack env_ids' stack_ids)
536                                         `thenDs` \ trim_code ->
537     let
538         in_ty = envStackType env_ids stack
539         in_ty' = envStackType env_ids' stack
540         arg_code = if env_ids' == env_ids then core_cmd else
541                 do_map_arrow meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
542     in
543     returnDs (bindCmdEnv meth_ids arg_code, free_vars)
544
545 -- Given A | xs |- c :: [ts] t, builds c with xs fed back.
546 -- Typically needs to be prefixed with arr (\p -> ((xs)*ts))
547
548 dsfixCmd
549         :: DsCmdEnv             -- arrow combinators
550         -> IdSet                -- set of local vars available to this command
551         -> [Type]               -- type of the stack
552         -> Type                 -- return type of the command
553         -> TypecheckedHsCmd     -- command to desugar
554         -> DsM (CoreExpr,       -- desugared expression
555                 IdSet,          -- set of local vars that occur free
556                 [Id])           -- set as a list, fed back
557 dsfixCmd ids local_vars stack cmd_ty cmd
558   = fixDs (\ ~(_,_,env_ids') ->
559         dsCmd ids local_vars env_ids' stack cmd_ty cmd
560                                         `thenDs` \ (core_cmd, free_vars) ->
561         returnDs (core_cmd, free_vars, varSetElems free_vars))
562
563 \end{code}
564
565 Translation of command judgements of the form
566
567         A | xs |- do { ss } :: [] t
568
569 \begin{code}
570
571 dsCmdDo :: DsCmdEnv             -- arrow combinators
572         -> IdSet                -- set of local vars available to this statement
573         -> [Id]                 -- list of vars in the input to this statement
574                                 -- This is typically fed back,
575                                 -- so don't pull on it too early
576         -> Type                 -- return type of the statement
577         -> [TypecheckedStmt]    -- statements to desugar
578         -> DsM (CoreExpr,       -- desugared expression
579                 IdSet)          -- set of local vars that occur free
580
581 --      A | xs |- c :: [] t
582 --      --------------------------
583 --      A | xs |- do { c } :: [] t
584
585 dsCmdDo ids local_vars env_ids res_ty [ResultStmt cmd _locn]
586   = dsCmd ids local_vars env_ids [] res_ty cmd
587
588 dsCmdDo ids local_vars env_ids res_ty (stmt:stmts)
589   = let
590         bound_vars = mkVarSet (collectStmtBinders stmt)
591         local_vars' = local_vars `unionVarSet` bound_vars
592     in
593     fixDs (\ ~(_,_,env_ids') ->
594         dsCmdDo ids local_vars' env_ids' res_ty stmts
595                                         `thenDs` \ (core_stmts, fv_stmts) ->
596         returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
597                                 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
598     dsCmdStmt ids local_vars env_ids env_ids' stmt
599                                 `thenDs` \ (core_stmt, fv_stmt) ->
600     returnDs (do_compose ids
601                 (mkTupleType env_ids)
602                 (mkTupleType env_ids')
603                 res_ty
604                 core_stmt
605                 core_stmts,
606               fv_stmt)
607
608 \end{code}
609 A statement maps one local environment to another, and is represented
610 as an arrow from one tuple type to another.  A statement sequence is
611 translated to a composition of such arrows.
612 \begin{code}
613
614 dsCmdStmt
615         :: DsCmdEnv             -- arrow combinators
616         -> IdSet                -- set of local vars available to this statement
617         -> [Id]                 -- list of vars in the input to this statement
618                                 -- This is typically fed back,
619                                 -- so don't pull on it too early
620         -> [Id]                 -- list of vars in the output of this statement
621         -> TypecheckedStmt      -- statement to desugar
622         -> DsM (CoreExpr,       -- desugared expression
623                 IdSet)          -- set of local vars that occur free
624
625 --      A | xs1 |- c :: [] t
626 --      A | xs' |- do { ss } :: [] t'
627 --      ------------------------------
628 --      A | xs |- do { c; ss } :: [] t'
629 --
630 --              ---> arr (\ (xs) -> ((xs1),(xs'))) >>> first c >>>
631 --                      arr snd >>> ss
632
633 dsCmdStmt ids local_vars env_ids out_ids (ExprStmt cmd c_ty _loc)
634   = dsfixCmd ids local_vars [] c_ty cmd
635                                 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
636     matchEnvStack env_ids []
637         (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr out_ids))
638                                         `thenDs` \ core_mux ->
639     let
640         in_ty = mkTupleType env_ids
641         in_ty1 = mkTupleType env_ids1
642         out_ty = mkTupleType out_ids
643         before_c_ty = mkCorePairTy in_ty1 out_ty
644         after_c_ty = mkCorePairTy c_ty out_ty
645     in
646     mkSndExpr c_ty out_ty               `thenDs` \ snd_fn ->
647     returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
648                 do_compose ids before_c_ty after_c_ty out_ty
649                         (do_first ids in_ty1 c_ty out_ty core_cmd) $
650                 do_arr ids after_c_ty out_ty snd_fn,
651               fv_cmd `unionVarSet` mkVarSet out_ids)
652   where
653
654 --      A | xs1 |- c :: [] t
655 --      A | xs' |- do { ss } :: [] t'           xs2 = xs' - defs(p)
656 --      -----------------------------------
657 --      A | xs |- do { p <- c; ss } :: [] t'
658 --
659 --              ---> arr (\ (xs) -> ((xs1),(xs2))) >>> first c >>>
660 --                      arr (\ (p, (xs2)) -> (xs')) >>> ss
661 --
662 -- It would be simpler and more consistent to do this using second,
663 -- but that's likely to be defined in terms of first.
664
665 dsCmdStmt ids local_vars env_ids out_ids (BindStmt pat cmd _loc)
666   = dsfixCmd ids local_vars [] (hsPatType pat) cmd
667                                 `thenDs` \ (core_cmd, fv_cmd, env_ids1) ->
668     let
669         pat_ty = hsPatType pat
670         pat_vars = mkVarSet (collectPatBinders pat)
671         env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars)
672         env_ty2 = mkTupleType env_ids2
673     in
674
675     -- multiplexing function
676     --          \ (xs) -> ((xs1),(xs2))
677
678     matchEnvStack env_ids []
679         (mkCorePairExpr (mkTupleExpr env_ids1) (mkTupleExpr env_ids2))
680                                         `thenDs` \ core_mux ->
681
682     -- projection function
683     --          \ (p, (xs2)) -> (zs)
684
685     selectMatchVar pat                  `thenDs` \ pat_id ->
686     newSysLocalDs env_ty2               `thenDs` \ env_id ->
687     getUniqSupplyDs                     `thenDs` \ uniqs ->
688     let
689         after_c_ty = mkCorePairTy pat_ty env_ty2
690         out_ty = mkTupleType out_ids
691         body_expr = coreCaseTuple uniqs env_id env_ids2 (mkTupleExpr out_ids)
692     in
693     mkFailExpr (StmtCtxt DoExpr) out_ty `thenDs` \ fail_expr ->
694     matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
695                                         `thenDs` \ match_code ->
696     newSysLocalDs after_c_ty            `thenDs` \ pair_id ->
697     let
698         proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)
699     in
700
701     -- put it all together
702     let
703         in_ty = mkTupleType env_ids
704         in_ty1 = mkTupleType env_ids1
705         in_ty2 = mkTupleType env_ids2
706         before_c_ty = mkCorePairTy in_ty1 in_ty2
707     in
708     returnDs (do_map_arrow ids in_ty before_c_ty out_ty core_mux $
709                 do_compose ids before_c_ty after_c_ty out_ty
710                         (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
711                 do_arr ids after_c_ty out_ty proj_expr,
712               fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars))
713
714 --      A | xs' |- do { ss } :: [] t
715 --      --------------------------------------
716 --      A | xs |- do { let binds; ss } :: [] t
717 --
718 --              ---> arr (\ (xs) -> let binds in (xs')) >>> ss
719
720 dsCmdStmt ids local_vars env_ids out_ids (LetStmt binds)
721     -- build a new environment using the let bindings
722   = dsLet binds (mkTupleExpr out_ids)   `thenDs` \ core_binds ->
723     -- match the old environment against the input
724     matchEnvStack env_ids [] core_binds `thenDs` \ core_map ->
725     returnDs (do_arr ids
726                         (mkTupleType env_ids)
727                         (mkTupleType out_ids)
728                         core_map,
729         exprFreeVars core_binds `intersectVarSet` local_vars)
730
731 --      A | ys |- do { ss; returnA -< ((xs1), (ys2)) } :: [] ...
732 --      A | xs' |- do { ss' } :: [] t
733 --      ------------------------------------
734 --      A | xs |- do { rec ss; ss' } :: [] t
735 --
736 --                      xs1 = xs' /\ defs(ss)
737 --                      xs2 = xs' - defs(ss)
738 --                      ys1 = ys - defs(ss)
739 --                      ys2 = ys /\ defs(ss)
740 --
741 --              ---> arr (\(xs) -> ((ys1),(xs2))) >>>
742 --                      first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
743 --                      arr (\((xs1),(xs2)) -> (xs')) >>> ss'
744
745 dsCmdStmt ids local_vars env_ids out_ids (RecStmt stmts later_ids rec_ids rhss)
746   = let
747         env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids
748         env2_ids = varSetElems env2_id_set
749         env2_ty = mkTupleType env2_ids
750     in
751
752     -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)
753
754     getUniqSupplyDs             `thenDs` \ uniqs ->
755     newSysLocalDs env2_ty       `thenDs` \ env2_id ->
756     let
757         later_ty = mkTupleType later_ids
758         post_pair_ty = mkCorePairTy later_ty env2_ty
759         post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkTupleExpr out_ids)
760     in
761     matchEnvStack later_ids [env2_id] post_loop_body
762                                 `thenDs` \ post_loop_fn ->
763
764     --- loop (...)
765
766     dsRecCmd ids local_vars stmts later_ids rec_ids rhss
767                                 `thenDs` \ (core_loop, env1_id_set, env1_ids) ->
768
769     -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))
770
771     let
772         env1_ty = mkTupleType env1_ids
773         pre_pair_ty = mkCorePairTy env1_ty env2_ty
774         pre_loop_body = mkCorePairExpr (mkTupleExpr env1_ids)
775                                         (mkTupleExpr env2_ids)
776
777     in
778     matchEnvStack env_ids [] pre_loop_body
779                                 `thenDs` \ pre_loop_fn ->
780
781     -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn
782
783     let
784         env_ty = mkTupleType env_ids
785         out_ty = mkTupleType out_ids
786         core_body = do_map_arrow ids env_ty pre_pair_ty out_ty
787                 pre_loop_fn
788                 (do_compose ids pre_pair_ty post_pair_ty out_ty
789                         (do_first ids env1_ty later_ty env2_ty
790                                 core_loop)
791                         (do_arr ids post_pair_ty out_ty
792                                 post_loop_fn))
793     in
794     returnDs (core_body, env1_id_set `unionVarSet` env2_id_set)
795
796 --      loop (arr (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) >>>
797 --            ss >>>
798 --            arr (\ (out_ids) -> ((later_ids),(rhss))) >>>
799
800 dsRecCmd ids local_vars stmts later_ids rec_ids rhss
801   = let
802         rec_id_set = mkVarSet rec_ids
803         out_ids = varSetElems (mkVarSet later_ids `unionVarSet` rec_id_set)
804         out_ty = mkTupleType out_ids
805         local_vars' = local_vars `unionVarSet` rec_id_set
806     in
807
808     -- mk_pair_fn = \ (out_ids) -> ((later_ids),(rhss))
809
810     mapDs dsExpr rhss           `thenDs` \ core_rhss ->
811     let
812         later_tuple = mkTupleExpr later_ids
813         later_ty = mkTupleType later_ids
814         rec_tuple = mkBigCoreTup core_rhss
815         rec_ty = mkTupleType rec_ids
816         out_pair = mkCorePairExpr later_tuple rec_tuple
817         out_pair_ty = mkCorePairTy later_ty rec_ty
818     in
819         matchEnvStack out_ids [] out_pair
820                                 `thenDs` \ mk_pair_fn ->
821
822     -- ss
823
824     dsfixCmdStmts ids local_vars' out_ids stmts
825                                 `thenDs` \ (core_stmts, fv_stmts, env_ids) ->
826
827     -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)
828
829     newSysLocalDs rec_ty        `thenDs` \ rec_id ->
830     let
831         env1_id_set = fv_stmts `minusVarSet` rec_id_set
832         env1_ids = varSetElems env1_id_set
833         env1_ty = mkTupleType env1_ids
834         in_pair_ty = mkCorePairTy env1_ty rec_ty
835         core_body = mkBigCoreTup (map selectVar env_ids)
836           where
837             selectVar v
838                 | v `elemVarSet` rec_id_set
839                   = mkTupleSelector rec_ids v rec_id (Var rec_id)
840                 | otherwise = Var v
841     in
842     matchEnvStack env1_ids [rec_id] core_body
843                                 `thenDs` \ squash_pair_fn ->
844
845     -- loop (arr squash_pair_fn >>> ss >>> arr mk_pair_fn)
846
847     let
848         env_ty = mkTupleType env_ids
849         core_loop = do_loop ids env1_ty later_ty rec_ty
850                 (do_map_arrow ids in_pair_ty env_ty out_pair_ty
851                         squash_pair_fn
852                         (do_compose ids env_ty out_ty out_pair_ty
853                                 core_stmts
854                                 (do_arr ids out_ty out_pair_ty mk_pair_fn)))
855     in
856     returnDs (core_loop, env1_id_set, env1_ids)
857
858 \end{code}
859 A sequence of statements (as in a rec) is desugared to an arrow between
860 two environments
861 \begin{code}
862
863 dsfixCmdStmts
864         :: DsCmdEnv             -- arrow combinators
865         -> IdSet                -- set of local vars available to this statement
866         -> [Id]                 -- output vars of these statements
867         -> [TypecheckedStmt]    -- statements to desugar
868         -> DsM (CoreExpr,       -- desugared expression
869                 IdSet,          -- set of local vars that occur free
870                 [Id])           -- input vars
871
872 dsfixCmdStmts ids local_vars out_ids stmts
873   = fixDs (\ ~(_,_,env_ids) ->
874         dsCmdStmts ids local_vars env_ids out_ids stmts
875                                         `thenDs` \ (core_stmts, fv_stmts) ->
876         returnDs (core_stmts, fv_stmts, varSetElems fv_stmts))
877
878 dsCmdStmts
879         :: DsCmdEnv             -- arrow combinators
880         -> IdSet                -- set of local vars available to this statement
881         -> [Id]                 -- list of vars in the input to these statements
882         -> [Id]                 -- output vars of these statements
883         -> [TypecheckedStmt]    -- statements to desugar
884         -> DsM (CoreExpr,       -- desugared expression
885                 IdSet)          -- set of local vars that occur free
886
887 dsCmdStmts ids local_vars env_ids out_ids [stmt]
888   = dsCmdStmt ids local_vars env_ids out_ids stmt
889
890 dsCmdStmts ids local_vars env_ids out_ids (stmt:stmts)
891   = let
892         bound_vars = mkVarSet (collectStmtBinders stmt)
893         local_vars' = local_vars `unionVarSet` bound_vars
894     in
895     dsfixCmdStmts ids local_vars' out_ids stmts
896                                 `thenDs` \ (core_stmts, fv_stmts, env_ids') ->
897     dsCmdStmt ids local_vars env_ids env_ids' stmt
898                                 `thenDs` \ (core_stmt, fv_stmt) ->
899     returnDs (do_compose ids
900                 (mkTupleType env_ids)
901                 (mkTupleType env_ids')
902                 (mkTupleType out_ids)
903                 core_stmt
904                 core_stmts,
905               fv_stmt)
906
907 \end{code}
908
909 Match a list of expressions against a list of patterns, left-to-right.
910
911 \begin{code}
912 matchSimplys :: [CoreExpr]               -- Scrutinees
913              -> TypecheckedMatchContext  -- Match kind
914              -> [TypecheckedPat]         -- Patterns they should match
915              -> CoreExpr                 -- Return this if they all match
916              -> CoreExpr                 -- Return this if they don't
917              -> DsM CoreExpr
918 matchSimplys [] _ctxt [] result_expr _fail_expr = returnDs result_expr
919 matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr
920   = matchSimplys exps ctxt pats result_expr fail_expr
921                                         `thenDs` \ match_code ->
922     matchSimply exp ctxt pat match_code fail_expr
923 \end{code}
924
925 \begin{code}
926
927 -- list of leaf expressions, with set of variables bound in each
928 leavesMatch :: TypecheckedMatch -> [(TypecheckedHsExpr, IdSet)]
929 leavesMatch (Match pats _ (GRHSs grhss binds _ty))
930   = let
931         defined_vars = mkVarSet (collectPatsBinders pats) `unionVarSet`
932                        mkVarSet (collectHsBinders binds)
933     in
934     [(expr, mkVarSet (collectStmtsBinders stmts) `unionVarSet` defined_vars) |
935         GRHS stmts _locn <- grhss,
936         let ResultStmt expr _ = last stmts]
937
938 -- Replace the leaf commands in a match
939
940 replaceLeavesMatch
941         :: Type                 -- new result type
942         -> [TypecheckedHsExpr]  -- replacement leaf expressions of that type
943         -> TypecheckedMatch     -- the matches of a case command
944         -> ([TypecheckedHsExpr],-- remaining leaf expressions
945             TypecheckedMatch)   -- updated match
946 replaceLeavesMatch res_ty leaves (Match pat mt (GRHSs grhss binds _ty))
947   = let
948         (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
949     in
950     (leaves', Match pat mt (GRHSs grhss' binds res_ty))
951
952 replaceLeavesGRHS
953         :: [TypecheckedHsExpr]  -- replacement leaf expressions of that type
954         -> TypecheckedGRHS      -- rhss of a case command
955         -> ([TypecheckedHsExpr],-- remaining leaf expressions
956             TypecheckedGRHS)    -- updated GRHS
957 replaceLeavesGRHS (leaf:leaves) (GRHS stmts srcloc)
958   = (leaves, GRHS (init stmts ++ [ResultStmt leaf srcloc]) srcloc)
959
960 \end{code}
961
962 Balanced fold of a non-empty list.
963
964 \begin{code}
965 foldb :: (a -> a -> a) -> [a] -> a
966 foldb _ [] = error "foldb of empty list"
967 foldb _ [x] = x
968 foldb f xs = foldb f (fold_pairs xs)
969   where
970     fold_pairs [] = []
971     fold_pairs [x] = [x]
972     fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs
973 \end{code}