summaryrefslogtreecommitdiff
path: root/compiler/deSugar/DsArrows.hs
blob: c69d7495d9357844a41609eda7ba5540619eeea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998


Desugaring arrow commands
-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}

module DsArrows ( dsProcExpr ) where

#include "HsVersions.h"

import GhcPrelude

import Match
import DsUtils
import DsMonad

import HsSyn    hiding (collectPatBinders, collectPatsBinders, collectLStmtsBinders, collectLStmtBinders, collectStmtBinders )
import TcHsSyn
import qualified HsUtils

-- NB: The desugarer, which straddles the source and Core worlds, sometimes
--     needs to see source types (newtypes etc), and sometimes not
--     So WATCH OUT; check each use of split*Ty functions.
-- Sigh.  This is a pain.

import {-# SOURCE #-} DsExpr ( dsExpr, dsLExpr, dsLExprNoLP, dsLocalBinds, dsSyntaxExpr )

import TcType
import Type ( splitPiTy )
import TcEvidence
import CoreSyn
import CoreFVs
import CoreUtils
import MkCore
import DsBinds (dsHsWrapper)

import Name
import Id
import ConLike
import TysWiredIn
import BasicTypes
import PrelNames
import Outputable
import Bag
import VarSet
import SrcLoc
import ListSetOps( assocMaybe )
import Data.List
import Util
import UniqDFM
import UniqSet

data DsCmdEnv = DsCmdEnv {
        arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr
    }

mkCmdEnv :: CmdSyntaxTable GhcTc -> DsM ([CoreBind], DsCmdEnv)
-- See Note [CmdSyntaxTable] in HsExpr
mkCmdEnv tc_meths
  = do { (meth_binds, prs) <- mapAndUnzipM mk_bind tc_meths

       -- NB: Some of these lookups might fail, but that's OK if the
       -- symbol is never used. That's why we use Maybe first and then
       -- panic. An eager panic caused trouble in typecheck/should_compile/tc192
       ; let the_arr_id     = assocMaybe prs arrAName
             the_compose_id = assocMaybe prs composeAName
             the_first_id   = assocMaybe prs firstAName
             the_app_id     = assocMaybe prs appAName
             the_choice_id  = assocMaybe prs choiceAName
             the_loop_id    = assocMaybe prs loopAName

           -- used as an argument in, e.g., do_premap
       ; check_lev_poly 3 the_arr_id

           -- used as an argument in, e.g., dsCmdStmt/BodyStmt
       ; check_lev_poly 5 the_compose_id

           -- used as an argument in, e.g., dsCmdStmt/BodyStmt
       ; check_lev_poly 4 the_first_id

           -- the result of the_app_id is used as an argument in, e.g.,
           -- dsCmd/HsCmdArrApp/HsHigherOrderApp
       ; check_lev_poly 2 the_app_id

           -- used as an argument in, e.g., HsCmdIf
       ; check_lev_poly 5 the_choice_id

           -- used as an argument in, e.g., RecStmt
       ; check_lev_poly 4 the_loop_id

       ; return (meth_binds, DsCmdEnv {
               arr_id     = Var (unmaybe the_arr_id arrAName),
               compose_id = Var (unmaybe the_compose_id composeAName),
               first_id   = Var (unmaybe the_first_id firstAName),
               app_id     = Var (unmaybe the_app_id appAName),
               choice_id  = Var (unmaybe the_choice_id choiceAName),
               loop_id    = Var (unmaybe the_loop_id loopAName)
             }) }
  where
    mk_bind (std_name, expr)
      = do { rhs <- dsExpr expr
           ; id <- newSysLocalDs (exprType rhs)  -- no check needed; these are functions
           ; return (NonRec id rhs, (std_name, id)) }

    unmaybe Nothing name = pprPanic "mkCmdEnv" (text "Not found:" <+> ppr name)
    unmaybe (Just id) _  = id

      -- returns the result type of a pi-type (that is, a forall or a function)
      -- Note that this result type may be ill-scoped.
    res_type :: Type -> Type
    res_type ty = res_ty
      where
        (_, res_ty) = splitPiTy ty

    check_lev_poly :: Int -- arity
                   -> Maybe Id -> DsM ()
    check_lev_poly _     Nothing = return ()
    check_lev_poly arity (Just id)
      = dsNoLevPoly (nTimes arity res_type (idType id))
          (text "In the result of the function" <+> quotes (ppr id))


-- arr :: forall b c. (b -> c) -> a b c
do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr
do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f]

-- (>>>) :: forall b c d. a b c -> a c d -> a b d
do_compose :: DsCmdEnv -> Type -> Type -> Type ->
                CoreExpr -> CoreExpr -> CoreExpr
do_compose ids b_ty c_ty d_ty f g
  = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g]

-- first :: forall b c d. a b c -> a (b,d) (c,d)
do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
do_first ids b_ty c_ty d_ty f
  = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f]

-- app :: forall b c. a (a b c, b) c
do_app :: DsCmdEnv -> Type -> Type -> CoreExpr
do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty]

-- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d
-- note the swapping of d and c
do_choice :: DsCmdEnv -> Type -> Type -> Type ->
                CoreExpr -> CoreExpr -> CoreExpr
do_choice ids b_ty c_ty d_ty f g
  = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g]

-- loop :: forall b d c. a (b,d) (c,d) -> a b c
-- note the swapping of d and c
do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr
do_loop ids b_ty c_ty d_ty f
  = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f]

-- premap :: forall b c d. (b -> c) -> a c d -> a b d
-- premap f g = arr f >>> g
do_premap :: DsCmdEnv -> Type -> Type -> Type ->
                CoreExpr -> CoreExpr -> CoreExpr
do_premap ids b_ty c_ty d_ty f g
   = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) g

mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr
mkFailExpr ctxt ty
  = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)

-- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> a
mkFstExpr :: Type -> Type -> DsM CoreExpr
mkFstExpr a_ty b_ty = do
    a_var <- newSysLocalDs a_ty
    b_var <- newSysLocalDs b_ty
    pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty)
    return (Lam pair_var
               (coreCasePair pair_var a_var b_var (Var a_var)))

-- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b
mkSndExpr :: Type -> Type -> DsM CoreExpr
mkSndExpr a_ty b_ty = do
    a_var <- newSysLocalDs a_ty
    b_var <- newSysLocalDs b_ty
    pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty)
    return (Lam pair_var
               (coreCasePair pair_var a_var b_var (Var b_var)))

{-
Build case analysis of a tuple.  This cannot be done in the DsM monad,
because the list of variables is typically not yet defined.
-}

-- coreCaseTuple [u1..] v [x1..xn] body
--      = case v of v { (x1, .., xn) -> body }
-- But the matching may be nested if the tuple is very big

coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr
coreCaseTuple uniqs scrut_var vars body
  = mkTupleCase uniqs vars body scrut_var (Var scrut_var)

coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr
coreCasePair scrut_var var1 var2 body
  = Case (Var scrut_var) scrut_var (exprType body)
         [(DataAlt (tupleDataCon Boxed 2), [var1, var2], body)]

mkCorePairTy :: Type -> Type -> Type
mkCorePairTy t1 t2 = mkBoxedTupleTy [t1, t2]

mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr
mkCorePairExpr e1 e2 = mkCoreTup [e1, e2]

mkCoreUnitExpr :: CoreExpr
mkCoreUnitExpr = mkCoreTup []

{-
The input is divided into a local environment, which is a flat tuple
(unless it's too big), and a stack, which is a right-nested pair.
In general, the input has the form

        ((x1,...,xn), (s1,...(sk,())...))

where xi are the environment values, and si the ones on the stack,
with s1 being the "top", the first one to be matched with a lambda.
-}

envStackType :: [Id] -> Type -> Type
envStackType ids stack_ty = mkCorePairTy (mkBigCoreVarTupTy ids) stack_ty

-- splitTypeAt n (t1,... (tn,t)...) = ([t1, ..., tn], t)
splitTypeAt :: Int -> Type -> ([Type], Type)
splitTypeAt n ty
  | n == 0 = ([], ty)
  | otherwise = case tcTyConAppArgs ty of
      [t, ty'] -> let (ts, ty_r) = splitTypeAt (n-1) ty' in (t:ts, ty_r)
      _ -> pprPanic "splitTypeAt" (ppr ty)

----------------------------------------------
--              buildEnvStack
--
--      ((x1,...,xn),stk)

buildEnvStack :: [Id] -> Id -> CoreExpr
buildEnvStack env_ids stack_id
  = mkCorePairExpr (mkBigCoreVarTup env_ids) (Var stack_id)

----------------------------------------------
--              matchEnvStack
--
--      \ ((x1,...,xn),stk) -> body
--      =>
--      \ pair ->
--      case pair of (tup,stk) ->
--      case tup of (x1,...,xn) ->
--      body

matchEnvStack   :: [Id]         -- x1..xn
                -> Id           -- stk
                -> CoreExpr     -- e
                -> DsM CoreExpr
matchEnvStack env_ids stack_id body = do
    uniqs <- newUniqueSupply
    tup_var <- newSysLocalDs (mkBigCoreVarTupTy env_ids)
    let match_env = coreCaseTuple uniqs tup_var env_ids body
    pair_id <- newSysLocalDs (mkCorePairTy (idType tup_var) (idType stack_id))
    return (Lam pair_id (coreCasePair pair_id tup_var stack_id match_env))

----------------------------------------------
--              matchEnv
--
--      \ (x1,...,xn) -> body
--      =>
--      \ tup ->
--      case tup of (x1,...,xn) ->
--      body

matchEnv :: [Id]        -- x1..xn
         -> CoreExpr    -- e
         -> DsM CoreExpr
matchEnv env_ids body = do
    uniqs <- newUniqueSupply
    tup_id <- newSysLocalDs (mkBigCoreVarTupTy env_ids)
    return (Lam tup_id (coreCaseTuple uniqs tup_id env_ids body))

----------------------------------------------
--              matchVarStack
--
--      case (x1, ...(xn, s)...) -> e
--      =>
--      case z0 of (x1,z1) ->
--      case zn-1 of (xn,s) ->
--      e
matchVarStack :: [Id] -> Id -> CoreExpr -> DsM (Id, CoreExpr)
matchVarStack [] stack_id body = return (stack_id, body)
matchVarStack (param_id:param_ids) stack_id body = do
    (tail_id, tail_code) <- matchVarStack param_ids stack_id body
    pair_id <- newSysLocalDs (mkCorePairTy (idType param_id) (idType tail_id))
    return (pair_id, coreCasePair pair_id param_id tail_id tail_code)

mkHsEnvStackExpr :: [Id] -> Id -> LHsExpr GhcTc
mkHsEnvStackExpr env_ids stack_id
  = mkLHsTupleExpr [mkLHsVarTuple env_ids, nlHsVar stack_id]

-- Translation of arrow abstraction

-- D; xs |-a c : () --> t'      ---> c'
-- --------------------------
-- D |- proc p -> c :: a t t'   ---> premap (\ p -> ((xs),())) c'
--
--              where (xs) is the tuple of variables bound by p

dsProcExpr
        :: LPat GhcTc
        -> LHsCmdTop GhcTc
        -> DsM CoreExpr
dsProcExpr pat (L _ (HsCmdTop (CmdTopTc _unitTy cmd_ty ids) cmd)) = do
    (meth_binds, meth_ids) <- mkCmdEnv ids
    let locals = mkVarSet (collectPatBinders pat)
    (core_cmd, _free_vars, env_ids) <- dsfixCmd meth_ids locals unitTy cmd_ty cmd
    let env_ty = mkBigCoreVarTupTy env_ids
    let env_stk_ty = mkCorePairTy env_ty unitTy
    let env_stk_expr = mkCorePairExpr (mkBigCoreVarTup env_ids) mkCoreUnitExpr
    fail_expr <- mkFailExpr ProcExpr env_stk_ty
    var <- selectSimpleMatchVarL pat
    match_code <- matchSimply (Var var) ProcExpr pat env_stk_expr fail_expr
    let pat_ty = hsLPatType pat
    let proc_code = do_premap meth_ids pat_ty env_stk_ty cmd_ty
                    (Lam var match_code)
                    core_cmd
    return (mkLets meth_binds proc_code)
dsProcExpr _ (L _ XCmdTop{}) = panic "dsProcExpr"

{-
Translation of a command judgement of the form

        D; xs |-a c : stk --> t

to an expression e such that

        D |- e :: a (xs, stk) t
-}

dsLCmd :: DsCmdEnv -> IdSet -> Type -> Type -> LHsCmd GhcTc -> [Id]
       -> DsM (CoreExpr, DIdSet)
dsLCmd ids local_vars stk_ty res_ty cmd env_ids
  = dsCmd ids local_vars stk_ty res_ty (unLoc cmd) env_ids

dsCmd   :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this command
        -> Type                 -- type of the stack (right-nested tuple)
        -> Type                 -- return type of the command
        -> HsCmd GhcTc           -- command to desugar
        -> [Id]           -- list of vars in the input to this command
                                -- This is typically fed back,
                                -- so don't pull on it too early
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet)         -- subset of local vars that occur free

-- D |- fun :: a t1 t2
-- D, xs |- arg :: t1
-- -----------------------------
-- D; xs |-a fun -< arg : stk --> t2
--
--              ---> premap (\ ((xs), _stk) -> arg) fun

dsCmd ids local_vars stack_ty res_ty
        (HsCmdArrApp arrow_ty arrow arg HsFirstOrderApp _)
        env_ids = do
    let
        (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
        (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty
    core_arrow <- dsLExprNoLP arrow
    core_arg   <- dsLExpr arg
    stack_id   <- newSysLocalDs stack_ty
    core_make_arg <- matchEnvStack env_ids stack_id core_arg
    return (do_premap ids
              (envStackType env_ids stack_ty)
              arg_ty
              res_ty
              core_make_arg
              core_arrow,
            exprFreeIdsDSet core_arg `udfmIntersectUFM` (getUniqSet local_vars))

-- D, xs |- fun :: a t1 t2
-- D, xs |- arg :: t1
-- ------------------------------
-- D; xs |-a fun -<< arg : stk --> t2
--
--              ---> premap (\ ((xs), _stk) -> (fun, arg)) app

dsCmd ids local_vars stack_ty res_ty
        (HsCmdArrApp arrow_ty arrow arg HsHigherOrderApp _)
        env_ids = do
    let
        (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty
        (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty

    core_arrow <- dsLExpr arrow
    core_arg   <- dsLExpr arg
    stack_id   <- newSysLocalDs stack_ty
    core_make_pair <- matchEnvStack env_ids stack_id
          (mkCorePairExpr core_arrow core_arg)

    return (do_premap ids
              (envStackType env_ids stack_ty)
              (mkCorePairTy arrow_ty arg_ty)
              res_ty
              core_make_pair
              (do_app ids arg_ty res_ty),
            (exprsFreeIdsDSet [core_arrow, core_arg])
              `udfmIntersectUFM` getUniqSet local_vars)

-- D; ys |-a cmd : (t,stk) --> t'
-- D, xs |-  exp :: t
-- ------------------------
-- D; xs |-a cmd exp : stk --> t'
--
--              ---> premap (\ ((xs),stk) -> ((ys),(e,stk))) cmd

dsCmd ids local_vars stack_ty res_ty (HsCmdApp _ cmd arg) env_ids = do
    core_arg <- dsLExpr arg
    let
        arg_ty = exprType core_arg
        stack_ty' = mkCorePairTy arg_ty stack_ty
    (core_cmd, free_vars, env_ids')
             <- dsfixCmd ids local_vars stack_ty' res_ty cmd
    stack_id <- newSysLocalDs stack_ty
    arg_id <- newSysLocalDsNoLP arg_ty
    -- push the argument expression onto the stack
    let
        stack' = mkCorePairExpr (Var arg_id) (Var stack_id)
        core_body = bindNonRec arg_id core_arg
                        (mkCorePairExpr (mkBigCoreVarTup env_ids') stack')

    -- match the environment and stack against the input
    core_map <- matchEnvStack env_ids stack_id core_body
    return (do_premap ids
                      (envStackType env_ids stack_ty)
                      (envStackType env_ids' stack_ty')
                      res_ty
                      core_map
                      core_cmd,
            free_vars `unionDVarSet`
              (exprFreeIdsDSet core_arg `udfmIntersectUFM` getUniqSet local_vars))

-- D; ys |-a cmd : stk t'
-- -----------------------------------------------
-- D; xs |-a \ p1 ... pk -> cmd : (t1,...(tk,stk)...) t'
--
--              ---> premap (\ ((xs), (p1, ... (pk,stk)...)) -> ((ys),stk)) cmd

dsCmd ids local_vars stack_ty res_ty
        (HsCmdLam _ (MG { mg_alts
          = L _ [L _ (Match { m_pats  = pats
                            , m_grhss = GRHSs _ [L _ (GRHS _ [] body)] _ })] }))
        env_ids = do
    let pat_vars = mkVarSet (collectPatsBinders pats)
    let
        local_vars' = pat_vars `unionVarSet` local_vars
        (pat_tys, stack_ty') = splitTypeAt (length pats) stack_ty
    (core_body, free_vars, env_ids') <- dsfixCmd ids local_vars' stack_ty' res_ty body
    param_ids <- mapM newSysLocalDsNoLP pat_tys
    stack_id' <- newSysLocalDs stack_ty'

    -- the expression is built from the inside out, so the actions
    -- are presented in reverse order

    let
        -- build a new environment, plus what's left of the stack
        core_expr = buildEnvStack env_ids' stack_id'
        in_ty = envStackType env_ids stack_ty
        in_ty' = envStackType env_ids' stack_ty'

    fail_expr <- mkFailExpr LambdaExpr in_ty'
    -- match the patterns against the parameters
    match_code <- matchSimplys (map Var param_ids) LambdaExpr pats core_expr fail_expr
    -- match the parameters against the top of the old stack
    (stack_id, param_code) <- matchVarStack param_ids stack_id' match_code
    -- match the old environment and stack against the input
    select_code <- matchEnvStack env_ids stack_id param_code
    return (do_premap ids in_ty in_ty' res_ty select_code core_body,
            free_vars `udfmMinusUFM` getUniqSet pat_vars)

dsCmd ids local_vars stack_ty res_ty (HsCmdPar _ cmd) env_ids
  = dsLCmd ids local_vars stack_ty res_ty cmd env_ids

-- D, xs |- e :: Bool
-- D; xs1 |-a c1 : stk --> t
-- D; xs2 |-a c2 : stk --> t
-- ----------------------------------------
-- D; xs |-a if e then c1 else c2 : stk --> t
--
--              ---> premap (\ ((xs),stk) ->
--                       if e then Left ((xs1),stk) else Right ((xs2),stk))
--                     (c1 ||| c2)

dsCmd ids local_vars stack_ty res_ty (HsCmdIf _ mb_fun cond then_cmd else_cmd)
        env_ids = do
    core_cond <- dsLExpr cond
    (core_then, fvs_then, then_ids) <- dsfixCmd ids local_vars stack_ty res_ty then_cmd
    (core_else, fvs_else, else_ids) <- dsfixCmd ids local_vars stack_ty res_ty else_cmd
    stack_id   <- newSysLocalDs stack_ty
    either_con <- dsLookupTyCon eitherTyConName
    left_con   <- dsLookupDataCon leftDataConName
    right_con  <- dsLookupDataCon rightDataConName

    let mk_left_expr ty1 ty2 e = mkCoreConApps left_con   [Type ty1, Type ty2, e]
        mk_right_expr ty1 ty2 e = mkCoreConApps right_con [Type ty1, Type ty2, e]

        in_ty = envStackType env_ids stack_ty
        then_ty = envStackType then_ids stack_ty
        else_ty = envStackType else_ids stack_ty
        sum_ty = mkTyConApp either_con [then_ty, else_ty]
        fvs_cond = exprFreeIdsDSet core_cond `udfmIntersectUFM` getUniqSet local_vars

        core_left  = mk_left_expr  then_ty else_ty (buildEnvStack then_ids stack_id)
        core_right = mk_right_expr then_ty else_ty (buildEnvStack else_ids stack_id)

    core_if <- case mb_fun of
       Just fun -> do { fun_apps <- dsSyntaxExpr fun [core_cond, core_left, core_right]
                      ; matchEnvStack env_ids stack_id fun_apps }
       Nothing  -> matchEnvStack env_ids stack_id $
                   mkIfThenElse core_cond core_left core_right

    return (do_premap ids in_ty sum_ty res_ty
                core_if
                (do_choice ids then_ty else_ty res_ty core_then core_else),
        fvs_cond `unionDVarSet` fvs_then `unionDVarSet` fvs_else)

{-
Case commands are treated in much the same way as if commands
(see above) except that there are more alternatives.  For example

        case e of { p1 -> c1; p2 -> c2; p3 -> c3 }

is translated to

        premap (\ ((xs)*ts) -> case e of
                p1 -> (Left (Left (xs1)*ts))
                p2 -> Left ((Right (xs2)*ts))
                p3 -> Right ((xs3)*ts))
        ((c1 ||| c2) ||| c3)

The idea is to extract the commands from the case, build a balanced tree
of choices, and replace the commands with expressions that build tagged
tuples, obtaining a case expression that can be desugared normally.
To build all this, we use triples describing segments of the list of
case bodies, containing the following fields:
 * a list of expressions of the form (Left|Right)* ((xs)*ts), to be put
   into the case replacing the commands
 * a sum type that is the common type of these expressions, and also the
   input type of the arrow
 * a CoreExpr for an arrow built by combining the translated command
   bodies with |||.
-}

dsCmd ids local_vars stack_ty res_ty
      (HsCmdCase _ exp (MG { mg_alts = L l matches
                           , mg_ext = MatchGroupTc arg_tys _
                           , mg_origin = origin }))
      env_ids = do
    stack_id <- newSysLocalDs stack_ty

    -- Extract and desugar the leaf commands in the case, building tuple
    -- expressions that will (after tagging) replace these leaves

    let
        leaves = concatMap leavesMatch matches
        make_branch (leaf, bound_vars) = do
            (core_leaf, _fvs, leaf_ids) <-
                  dsfixCmd ids (bound_vars `unionVarSet` local_vars) stack_ty res_ty leaf
            return ([mkHsEnvStackExpr leaf_ids stack_id],
                    envStackType leaf_ids stack_ty,
                    core_leaf)

    branches <- mapM make_branch leaves
    either_con <- dsLookupTyCon eitherTyConName
    left_con <- dsLookupDataCon leftDataConName
    right_con <- dsLookupDataCon rightDataConName
    let
        left_id  = HsConLikeOut noExt (RealDataCon left_con)
        right_id = HsConLikeOut noExt (RealDataCon right_con)
        left_expr  ty1 ty2 e = noLoc $ HsApp noExt
                           (noLoc $ mkHsWrap (mkWpTyApps [ty1, ty2]) left_id ) e
        right_expr ty1 ty2 e = noLoc $ HsApp noExt
                           (noLoc $ mkHsWrap (mkWpTyApps [ty1, ty2]) right_id) e

        -- Prefix each tuple with a distinct series of Left's and Right's,
        -- in a balanced way, keeping track of the types.

        merge_branches (builds1, in_ty1, core_exp1)
                       (builds2, in_ty2, core_exp2)
          = (map (left_expr in_ty1 in_ty2) builds1 ++
                map (right_expr in_ty1 in_ty2) builds2,
             mkTyConApp either_con [in_ty1, in_ty2],
             do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2)
        (leaves', sum_ty, core_choices) = foldb merge_branches branches

        -- Replace the commands in the case with these tagged tuples,
        -- yielding a HsExpr Id we can feed to dsExpr.

        (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches
        in_ty = envStackType env_ids stack_ty

    core_body <- dsExpr (HsCase noExt exp
                         (MG { mg_alts = L l matches'
                             , mg_ext = MatchGroupTc arg_tys sum_ty
                             , mg_origin = origin }))
        -- Note that we replace the HsCase result type by sum_ty,
        -- which is the type of matches'

    core_matches <- matchEnvStack env_ids stack_id core_body
    return (do_premap ids in_ty sum_ty res_ty core_matches core_choices,
            exprFreeIdsDSet core_body `udfmIntersectUFM` getUniqSet local_vars)

-- D; ys |-a cmd : stk --> t
-- ----------------------------------
-- D; xs |-a let binds in cmd : stk --> t
--
--              ---> premap (\ ((xs),stk) -> let binds in ((ys),stk)) c

dsCmd ids local_vars stack_ty res_ty (HsCmdLet _ lbinds@(L _ binds) body)
                                                                    env_ids = do
    let
        defined_vars = mkVarSet (collectLocalBinders binds)
        local_vars' = defined_vars `unionVarSet` local_vars

    (core_body, _free_vars, env_ids') <- dsfixCmd ids local_vars' stack_ty res_ty body
    stack_id <- newSysLocalDs stack_ty
    -- build a new environment, plus the stack, using the let bindings
    core_binds <- dsLocalBinds lbinds (buildEnvStack env_ids' stack_id)
    -- match the old environment and stack against the input
    core_map <- matchEnvStack env_ids stack_id core_binds
    return (do_premap ids
                        (envStackType env_ids stack_ty)
                        (envStackType env_ids' stack_ty)
                        res_ty
                        core_map
                        core_body,
        exprFreeIdsDSet core_binds `udfmIntersectUFM` getUniqSet local_vars)

-- D; xs |-a ss : t
-- ----------------------------------
-- D; xs |-a do { ss } : () --> t
--
--              ---> premap (\ (env,stk) -> env) c

dsCmd ids local_vars stack_ty res_ty do_block@(HsCmdDo stmts_ty (L loc stmts))
                                                                   env_ids = do
    putSrcSpanDs loc $
      dsNoLevPoly stmts_ty
        (text "In the do-command:" <+> ppr do_block)
    (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids
    let env_ty = mkBigCoreVarTupTy env_ids
    core_fst <- mkFstExpr env_ty stack_ty
    return (do_premap ids
                (mkCorePairTy env_ty stack_ty)
                env_ty
                res_ty
                core_fst
                core_stmts,
        env_ids')

-- D |- e :: forall e. a1 (e,stk1) t1 -> ... an (e,stkn) tn -> a (e,stk) t
-- D; xs |-a ci :: stki --> ti
-- -----------------------------------
-- D; xs |-a (|e c1 ... cn|) :: stk --> t       ---> e [t_xs] c1 ... cn

dsCmd _ local_vars _stack_ty _res_ty (HsCmdArrForm _ op _ _ args) env_ids = do
    let env_ty = mkBigCoreVarTupTy env_ids
    core_op <- dsLExpr op
    (core_args, fv_sets) <- mapAndUnzipM (dsTrimCmdArg local_vars env_ids) args
    return (mkApps (App core_op (Type env_ty)) core_args,
            unionDVarSets fv_sets)

dsCmd ids local_vars stack_ty res_ty (HsCmdWrap _ wrap cmd) env_ids = do
    (core_cmd, env_ids') <- dsCmd ids local_vars stack_ty res_ty cmd env_ids
    core_wrap <- dsHsWrapper wrap
    return (core_wrap core_cmd, env_ids')

dsCmd _ _ _ _ _ c = pprPanic "dsCmd" (ppr c)

-- D; ys |-a c : stk --> t      (ys <= xs)
-- ---------------------
-- D; xs |-a c : stk --> t      ---> premap (\ ((xs),stk) -> ((ys),stk)) c

dsTrimCmdArg
        :: IdSet                -- set of local vars available to this command
        -> [Id]           -- list of vars in the input to this command
        -> LHsCmdTop GhcTc       -- command argument to desugar
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet)         -- subset of local vars that occur free
dsTrimCmdArg local_vars env_ids
                       (L _ (HsCmdTop (CmdTopTc stack_ty cmd_ty ids) cmd )) = do
    (meth_binds, meth_ids) <- mkCmdEnv ids
    (core_cmd, free_vars, env_ids') <- dsfixCmd meth_ids local_vars stack_ty cmd_ty cmd
    stack_id <- newSysLocalDs stack_ty
    trim_code <- matchEnvStack env_ids stack_id (buildEnvStack env_ids' stack_id)
    let
        in_ty = envStackType env_ids stack_ty
        in_ty' = envStackType env_ids' stack_ty
        arg_code = if env_ids' == env_ids then core_cmd else
                do_premap meth_ids in_ty in_ty' cmd_ty trim_code core_cmd
    return (mkLets meth_binds arg_code, free_vars)
dsTrimCmdArg _ _ (L _ XCmdTop{}) = panic "dsTrimCmdArg"

-- Given D; xs |-a c : stk --> t, builds c with xs fed back.
-- Typically needs to be prefixed with arr (\(p, stk) -> ((xs),stk))

dsfixCmd
        :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this command
        -> Type                 -- type of the stack (right-nested tuple)
        -> Type                 -- return type of the command
        -> LHsCmd GhcTc         -- command to desugar
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet,         -- subset of local vars that occur free
                [Id])           -- the same local vars as a list, fed back
dsfixCmd ids local_vars stk_ty cmd_ty cmd
  = do { putSrcSpanDs (getLoc cmd) $ dsNoLevPoly cmd_ty
           (text "When desugaring the command:" <+> ppr cmd)
       ; trimInput (dsLCmd ids local_vars stk_ty cmd_ty cmd) }

-- Feed back the list of local variables actually used a command,
-- for use as the input tuple of the generated arrow.

trimInput
        :: ([Id] -> DsM (CoreExpr, DIdSet))
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet,         -- subset of local vars that occur free
                [Id])           -- same local vars as a list, fed back to
                                -- the inner function to form the tuple of
                                -- inputs to the arrow.
trimInput build_arrow
  = fixDs (\ ~(_,_,env_ids) -> do
        (core_cmd, free_vars) <- build_arrow env_ids
        return (core_cmd, free_vars, dVarSetElems free_vars))

{-
Translation of command judgements of the form

        D |-a do { ss } : t
-}

dsCmdDo :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this statement
        -> Type                 -- return type of the statement
        -> [CmdLStmt GhcTc]     -- statements to desugar
        -> [Id]                 -- list of vars in the input to this statement
                                -- This is typically fed back,
                                -- so don't pull on it too early
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet)         -- subset of local vars that occur free

dsCmdDo _ _ _ [] _ = panic "dsCmdDo"

-- D; xs |-a c : () --> t
-- --------------------------
-- D; xs |-a do { c } : t
--
--              ---> premap (\ (xs) -> ((xs), ())) c

dsCmdDo ids local_vars res_ty [L loc (LastStmt _ body _ _)] env_ids = do
    putSrcSpanDs loc $ dsNoLevPoly res_ty
                         (text "In the command:" <+> ppr body)
    (core_body, env_ids') <- dsLCmd ids local_vars unitTy res_ty body env_ids
    let env_ty = mkBigCoreVarTupTy env_ids
    env_var <- newSysLocalDs env_ty
    let core_map = Lam env_var (mkCorePairExpr (Var env_var) mkCoreUnitExpr)
    return (do_premap ids
                        env_ty
                        (mkCorePairTy env_ty unitTy)
                        res_ty
                        core_map
                        core_body,
        env_ids')

dsCmdDo ids local_vars res_ty (stmt:stmts) env_ids = do
    let bound_vars  = mkVarSet (collectLStmtBinders stmt)
    let local_vars' = bound_vars `unionVarSet` local_vars
    (core_stmts, _, env_ids') <- trimInput (dsCmdDo ids local_vars' res_ty stmts)
    (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids' stmt env_ids
    return (do_compose ids
                (mkBigCoreVarTupTy env_ids)
                (mkBigCoreVarTupTy env_ids')
                res_ty
                core_stmt
                core_stmts,
              fv_stmt)

{-
A statement maps one local environment to another, and is represented
as an arrow from one tuple type to another.  A statement sequence is
translated to a composition of such arrows.
-}

dsCmdLStmt :: DsCmdEnv -> IdSet -> [Id] -> CmdLStmt GhcTc -> [Id]
           -> DsM (CoreExpr, DIdSet)
dsCmdLStmt ids local_vars out_ids cmd env_ids
  = dsCmdStmt ids local_vars out_ids (unLoc cmd) env_ids

dsCmdStmt
        :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this statement
        -> [Id]                 -- list of vars in the output of this statement
        -> CmdStmt GhcTc        -- statement to desugar
        -> [Id]                 -- list of vars in the input to this statement
                                -- This is typically fed back,
                                -- so don't pull on it too early
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet)         -- subset of local vars that occur free

-- D; xs1 |-a c : () --> t
-- D; xs' |-a do { ss } : t'
-- ------------------------------
-- D; xs  |-a do { c; ss } : t'
--
--              ---> premap (\ ((xs)) -> (((xs1),()),(xs')))
--                      (first c >>> arr snd) >>> ss

dsCmdStmt ids local_vars out_ids (BodyStmt c_ty cmd _ _) env_ids = do
    (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars unitTy c_ty cmd
    core_mux <- matchEnv env_ids
        (mkCorePairExpr
            (mkCorePairExpr (mkBigCoreVarTup env_ids1) mkCoreUnitExpr)
            (mkBigCoreVarTup out_ids))
    let
        in_ty = mkBigCoreVarTupTy env_ids
        in_ty1 = mkCorePairTy (mkBigCoreVarTupTy env_ids1) unitTy
        out_ty = mkBigCoreVarTupTy out_ids
        before_c_ty = mkCorePairTy in_ty1 out_ty
        after_c_ty = mkCorePairTy c_ty out_ty
    dsNoLevPoly c_ty empty -- I (Richard E, Dec '16) have no idea what to say here
    snd_fn <- mkSndExpr c_ty out_ty
    return (do_premap ids in_ty before_c_ty out_ty core_mux $
                do_compose ids before_c_ty after_c_ty out_ty
                        (do_first ids in_ty1 c_ty out_ty core_cmd) $
                do_arr ids after_c_ty out_ty snd_fn,
              extendDVarSetList fv_cmd out_ids)

-- D; xs1 |-a c : () --> t
-- D; xs' |-a do { ss } : t'            xs2 = xs' - defs(p)
-- -----------------------------------
-- D; xs  |-a do { p <- c; ss } : t'
--
--              ---> premap (\ (xs) -> (((xs1),()),(xs2)))
--                      (first c >>> arr (\ (p, (xs2)) -> (xs'))) >>> ss
--
-- It would be simpler and more consistent to do this using second,
-- but that's likely to be defined in terms of first.

dsCmdStmt ids local_vars out_ids (BindStmt _ pat cmd _ _) env_ids = do
    let pat_ty = hsLPatType pat
    (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars unitTy pat_ty cmd
    let pat_vars = mkVarSet (collectPatBinders pat)
    let
        env_ids2 = filterOut (`elemVarSet` pat_vars) out_ids
        env_ty2 = mkBigCoreVarTupTy env_ids2

    -- multiplexing function
    --          \ (xs) -> (((xs1),()),(xs2))

    core_mux <- matchEnv env_ids
        (mkCorePairExpr
            (mkCorePairExpr (mkBigCoreVarTup env_ids1) mkCoreUnitExpr)
            (mkBigCoreVarTup env_ids2))

    -- projection function
    --          \ (p, (xs2)) -> (zs)

    env_id <- newSysLocalDs env_ty2
    uniqs <- newUniqueSupply
    let
        after_c_ty = mkCorePairTy pat_ty env_ty2
        out_ty = mkBigCoreVarTupTy out_ids
        body_expr = coreCaseTuple uniqs env_id env_ids2 (mkBigCoreVarTup out_ids)

    fail_expr <- mkFailExpr (StmtCtxt DoExpr) out_ty
    pat_id    <- selectSimpleMatchVarL pat
    match_code <- matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr
    pair_id   <- newSysLocalDs after_c_ty
    let
        proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code)

    -- put it all together
    let
        in_ty = mkBigCoreVarTupTy env_ids
        in_ty1 = mkCorePairTy (mkBigCoreVarTupTy env_ids1) unitTy
        in_ty2 = mkBigCoreVarTupTy env_ids2
        before_c_ty = mkCorePairTy in_ty1 in_ty2
    return (do_premap ids in_ty before_c_ty out_ty core_mux $
                do_compose ids before_c_ty after_c_ty out_ty
                        (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $
                do_arr ids after_c_ty out_ty proj_expr,
              fv_cmd `unionDVarSet` (mkDVarSet out_ids `udfmMinusUFM` getUniqSet pat_vars))

-- D; xs' |-a do { ss } : t
-- --------------------------------------
-- D; xs  |-a do { let binds; ss } : t
--
--              ---> arr (\ (xs) -> let binds in (xs')) >>> ss

dsCmdStmt ids local_vars out_ids (LetStmt _ binds) env_ids = do
    -- build a new environment using the let bindings
    core_binds <- dsLocalBinds binds (mkBigCoreVarTup out_ids)
    -- match the old environment against the input
    core_map <- matchEnv env_ids core_binds
    return (do_arr ids
                        (mkBigCoreVarTupTy env_ids)
                        (mkBigCoreVarTupTy out_ids)
                        core_map,
            exprFreeIdsDSet core_binds `udfmIntersectUFM` getUniqSet local_vars)

-- D; ys  |-a do { ss; returnA -< ((xs1), (ys2)) } : ...
-- D; xs' |-a do { ss' } : t
-- ------------------------------------
-- D; xs  |-a do { rec ss; ss' } : t
--
--                      xs1 = xs' /\ defs(ss)
--                      xs2 = xs' - defs(ss)
--                      ys1 = ys - defs(ss)
--                      ys2 = ys /\ defs(ss)
--
--              ---> arr (\(xs) -> ((ys1),(xs2))) >>>
--                      first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>>
--                      arr (\((xs1),(xs2)) -> (xs')) >>> ss'

dsCmdStmt ids local_vars out_ids
        (RecStmt { recS_stmts = stmts
                 , recS_later_ids = later_ids, recS_rec_ids = rec_ids
                 , recS_ext = RecStmtTc { recS_later_rets = later_rets
                                        , recS_rec_rets = rec_rets } })
        env_ids = do
    let
        later_ids_set = mkVarSet later_ids
        env2_ids = filterOut (`elemVarSet` later_ids_set) out_ids
        env2_id_set = mkDVarSet env2_ids
        env2_ty = mkBigCoreVarTupTy env2_ids

    -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids)

    uniqs <- newUniqueSupply
    env2_id <- newSysLocalDs env2_ty
    let
        later_ty = mkBigCoreVarTupTy later_ids
        post_pair_ty = mkCorePairTy later_ty env2_ty
        post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkBigCoreVarTup out_ids)

    post_loop_fn <- matchEnvStack later_ids env2_id post_loop_body

    --- loop (...)

    (core_loop, env1_id_set, env1_ids)
               <- dsRecCmd ids local_vars stmts later_ids later_rets rec_ids rec_rets

    -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids))

    let
        env1_ty = mkBigCoreVarTupTy env1_ids
        pre_pair_ty = mkCorePairTy env1_ty env2_ty
        pre_loop_body = mkCorePairExpr (mkBigCoreVarTup env1_ids)
                                        (mkBigCoreVarTup env2_ids)

    pre_loop_fn <- matchEnv env_ids pre_loop_body

    -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn

    let
        env_ty = mkBigCoreVarTupTy env_ids
        out_ty = mkBigCoreVarTupTy out_ids
        core_body = do_premap ids env_ty pre_pair_ty out_ty
                pre_loop_fn
                (do_compose ids pre_pair_ty post_pair_ty out_ty
                        (do_first ids env1_ty later_ty env2_ty
                                core_loop)
                        (do_arr ids post_pair_ty out_ty
                                post_loop_fn))

    return (core_body, env1_id_set `unionDVarSet` env2_id_set)

dsCmdStmt _ _ _ _ s = pprPanic "dsCmdStmt" (ppr s)

--      loop (premap (\ ((env1_ids), ~(rec_ids)) -> (env_ids))
--            (ss >>> arr (\ (out_ids) -> ((later_rets),(rec_rets))))) >>>

dsRecCmd
        :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this statement
        -> [CmdLStmt GhcTc]     -- list of statements inside the RecCmd
        -> [Id]                 -- list of vars defined here and used later
        -> [HsExpr GhcTc]       -- expressions corresponding to later_ids
        -> [Id]                 -- list of vars fed back through the loop
        -> [HsExpr GhcTc]       -- expressions corresponding to rec_ids
        -> DsM (CoreExpr,       -- desugared statement
                DIdSet,         -- subset of local vars that occur free
                [Id])           -- same local vars as a list

dsRecCmd ids local_vars stmts later_ids later_rets rec_ids rec_rets = do
    let
        later_id_set = mkVarSet later_ids
        rec_id_set = mkVarSet rec_ids
        local_vars' = rec_id_set `unionVarSet` later_id_set `unionVarSet` local_vars

    -- mk_pair_fn = \ (out_ids) -> ((later_rets),(rec_rets))

    core_later_rets <- mapM dsExpr later_rets
    core_rec_rets <- mapM dsExpr rec_rets
    let
        -- possibly polymorphic version of vars of later_ids and rec_ids
        out_ids = exprsFreeIdsList (core_later_rets ++ core_rec_rets)
        out_ty = mkBigCoreVarTupTy out_ids

        later_tuple = mkBigCoreTup core_later_rets
        later_ty = mkBigCoreVarTupTy later_ids

        rec_tuple = mkBigCoreTup core_rec_rets
        rec_ty = mkBigCoreVarTupTy rec_ids

        out_pair = mkCorePairExpr later_tuple rec_tuple
        out_pair_ty = mkCorePairTy later_ty rec_ty

    mk_pair_fn <- matchEnv out_ids out_pair

    -- ss

    (core_stmts, fv_stmts, env_ids) <- dsfixCmdStmts ids local_vars' out_ids stmts

    -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids)

    rec_id <- newSysLocalDs rec_ty
    let
        env1_id_set = fv_stmts `udfmMinusUFM` getUniqSet rec_id_set
        env1_ids = dVarSetElems env1_id_set
        env1_ty = mkBigCoreVarTupTy env1_ids
        in_pair_ty = mkCorePairTy env1_ty rec_ty
        core_body = mkBigCoreTup (map selectVar env_ids)
          where
            selectVar v
                | v `elemVarSet` rec_id_set
                  = mkTupleSelector rec_ids v rec_id (Var rec_id)
                | otherwise = Var v

    squash_pair_fn <- matchEnvStack env1_ids rec_id core_body

    -- loop (premap squash_pair_fn (ss >>> arr mk_pair_fn))

    let
        env_ty = mkBigCoreVarTupTy env_ids
        core_loop = do_loop ids env1_ty later_ty rec_ty
                (do_premap ids in_pair_ty env_ty out_pair_ty
                        squash_pair_fn
                        (do_compose ids env_ty out_ty out_pair_ty
                                core_stmts
                                (do_arr ids out_ty out_pair_ty mk_pair_fn)))

    return (core_loop, env1_id_set, env1_ids)

{-
A sequence of statements (as in a rec) is desugared to an arrow between
two environments (no stack)
-}

dsfixCmdStmts
        :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this statement
        -> [Id]                 -- output vars of these statements
        -> [CmdLStmt GhcTc]     -- statements to desugar
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet,         -- subset of local vars that occur free
                [Id])           -- same local vars as a list

dsfixCmdStmts ids local_vars out_ids stmts
  = trimInput (dsCmdStmts ids local_vars out_ids stmts)
   -- TODO: Add levity polymorphism check for the resulting expression.
   -- But I (Richard E.) don't know enough about arrows to do so.

dsCmdStmts
        :: DsCmdEnv             -- arrow combinators
        -> IdSet                -- set of local vars available to this statement
        -> [Id]                 -- output vars of these statements
        -> [CmdLStmt GhcTc]     -- statements to desugar
        -> [Id]                 -- list of vars in the input to these statements
        -> DsM (CoreExpr,       -- desugared expression
                DIdSet)         -- subset of local vars that occur free

dsCmdStmts ids local_vars out_ids [stmt] env_ids
  = dsCmdLStmt ids local_vars out_ids stmt env_ids

dsCmdStmts ids local_vars out_ids (stmt:stmts) env_ids = do
    let bound_vars  = mkVarSet (collectLStmtBinders stmt)
    let local_vars' = bound_vars `unionVarSet` local_vars
    (core_stmts, _fv_stmts, env_ids') <- dsfixCmdStmts ids local_vars' out_ids stmts
    (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids' stmt env_ids
    return (do_compose ids
                (mkBigCoreVarTupTy env_ids)
                (mkBigCoreVarTupTy env_ids')
                (mkBigCoreVarTupTy out_ids)
                core_stmt
                core_stmts,
              fv_stmt)

dsCmdStmts _ _ _ [] _ = panic "dsCmdStmts []"

-- Match a list of expressions against a list of patterns, left-to-right.

matchSimplys :: [CoreExpr]              -- Scrutinees
             -> HsMatchContext Name     -- Match kind
             -> [LPat GhcTc]            -- Patterns they should match
             -> CoreExpr                -- Return this if they all match
             -> CoreExpr                -- Return this if they don't
             -> DsM CoreExpr
matchSimplys [] _ctxt [] result_expr _fail_expr = return result_expr
matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr = do
    match_code <- matchSimplys exps ctxt pats result_expr fail_expr
    matchSimply exp ctxt pat match_code fail_expr
matchSimplys _ _ _ _ _ = panic "matchSimplys"

-- List of leaf expressions, with set of variables bound in each

leavesMatch :: LMatch GhcTc (Located (body GhcTc))
            -> [(Located (body GhcTc), IdSet)]
leavesMatch (L _ (Match { m_pats = pats, m_grhss = GRHSs _ grhss (L _ binds) }))
  = let
        defined_vars = mkVarSet (collectPatsBinders pats)
                        `unionVarSet`
                       mkVarSet (collectLocalBinders binds)
    in
    [(body,
      mkVarSet (collectLStmtsBinders stmts)
        `unionVarSet` defined_vars)
    | L _ (GRHS _ stmts body) <- grhss]
leavesMatch (L _ (Match _ _ _ (XGRHSs _))) = panic "leavesMatch"
leavesMatch (L _ (XMatch _)) = panic "leavesMatch"

-- Replace the leaf commands in a match

replaceLeavesMatch
        :: Type                                 -- new result type
        -> [Located (body' GhcTc)] -- replacement leaf expressions of that type
        -> LMatch GhcTc (Located (body GhcTc))  -- the matches of a case command
        -> ([Located (body' GhcTc)],            -- remaining leaf expressions
            LMatch GhcTc (Located (body' GhcTc))) -- updated match
replaceLeavesMatch _res_ty leaves
                        (L loc match@(Match { m_grhss = GRHSs x grhss binds }))
  = let
        (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss
    in
    (leaves', L loc (match { m_ext = noExt, m_grhss = GRHSs x grhss' binds }))
replaceLeavesMatch _ _ (L _ (Match _ _ _ (XGRHSs _)))
  = panic "replaceLeavesMatch"
replaceLeavesMatch _ _ (L _ (XMatch _)) = panic "replaceLeavesMatch"

replaceLeavesGRHS
        :: [Located (body' GhcTc)]  -- replacement leaf expressions of that type
        -> LGRHS GhcTc (Located (body GhcTc))     -- rhss of a case command
        -> ([Located (body' GhcTc)],              -- remaining leaf expressions
            LGRHS GhcTc (Located (body' GhcTc)))  -- updated GRHS
replaceLeavesGRHS (leaf:leaves) (L loc (GRHS x stmts _))
  = (leaves, L loc (GRHS x stmts leaf))
replaceLeavesGRHS _ (L _ (XGRHS _)) = panic "replaceLeavesGRHS"
replaceLeavesGRHS [] _ = panic "replaceLeavesGRHS []"

-- Balanced fold of a non-empty list.

foldb :: (a -> a -> a) -> [a] -> a
foldb _ [] = error "foldb of empty list"
foldb _ [x] = x
foldb f xs = foldb f (fold_pairs xs)
  where
    fold_pairs [] = []
    fold_pairs [x] = [x]
    fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs

{-
Note [Dictionary binders in ConPatOut] See also same Note in HsUtils
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following functions to collect value variables from patterns are
copied from HsUtils, with one change: we also collect the dictionary
bindings (pat_binds) from ConPatOut.  We need them for cases like

h :: Arrow a => Int -> a (Int,Int) Int
h x = proc (y,z) -> case compare x y of
                GT -> returnA -< z+x

The type checker turns the case into

                case compare x y of
                  GT { p77 = plusInt } -> returnA -< p77 z x

Here p77 is a local binding for the (+) operation.

See comments in HsUtils for why the other version does not include
these bindings.
-}

collectPatBinders :: LPat GhcTc -> [Id]
collectPatBinders pat = collectl pat []

collectPatsBinders :: [LPat GhcTc] -> [Id]
collectPatsBinders pats = foldr collectl [] pats

---------------------
collectl :: LPat GhcTc -> [Id] -> [Id]
-- See Note [Dictionary binders in ConPatOut]
collectl (L _ pat) bndrs
  = go pat
  where
    go (VarPat _ (L _ var))       = var : bndrs
    go (WildPat _)                = bndrs
    go (LazyPat _ pat)            = collectl pat bndrs
    go (BangPat _ pat)            = collectl pat bndrs
    go (AsPat _ (L _ a) pat)      = a : collectl pat bndrs
    go (ParPat _ pat)             = collectl pat bndrs

    go (ListPat _ pats)           = foldr collectl bndrs pats
    go (TuplePat _ pats _)        = foldr collectl bndrs pats
    go (SumPat _ pat _ _)         = collectl pat bndrs

    go (ConPatIn _ ps)            = foldr collectl bndrs (hsConPatArgs ps)
    go (ConPatOut {pat_args=ps, pat_binds=ds}) =
                                    collectEvBinders ds
                                    ++ foldr collectl bndrs (hsConPatArgs ps)
    go (LitPat _ _)               = bndrs
    go (NPat {})                  = bndrs
    go (NPlusKPat _ (L _ n) _ _ _ _) = n : bndrs

    go (SigPat _ pat)             = collectl pat bndrs
    go (CoPat _ _ pat _)          = collectl (noLoc pat) bndrs
    go (ViewPat _ _ pat)          = collectl pat bndrs
    go p@(SplicePat {})           = pprPanic "collectl/go" (ppr p)
    go p@(XPat {})                = pprPanic "collectl/go" (ppr p)

collectEvBinders :: TcEvBinds -> [Id]
collectEvBinders (EvBinds bs)   = foldrBag add_ev_bndr [] bs
collectEvBinders (TcEvBinds {}) = panic "ToDo: collectEvBinders"

add_ev_bndr :: EvBind -> [Id] -> [Id]
add_ev_bndr (EvBind { eb_lhs = b }) bs | isId b    = b:bs
                                       | otherwise = bs
  -- A worry: what about coercion variable binders??

collectLStmtsBinders :: [LStmt GhcTc body] -> [Id]
collectLStmtsBinders = concatMap collectLStmtBinders

collectLStmtBinders :: LStmt GhcTc body -> [Id]
collectLStmtBinders = collectStmtBinders . unLoc

collectStmtBinders :: Stmt GhcTc body -> [Id]
collectStmtBinders (RecStmt { recS_later_ids = later_ids }) = later_ids
collectStmtBinders stmt = HsUtils.collectStmtBinders stmt