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