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