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