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