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